Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
The arg npm package is a simple argument parsing library. It allows developers to parse command-line arguments in Node.js applications into a structured format that is easy to work with. It supports various types of flags and options, including boolean flags, string options, and number options.
Parsing command-line flags and options
This feature allows the parsing of command-line arguments with various types of expected values. The example code demonstrates how to define the expected types for each flag and option, including boolean, count, number, and string types, as well as how to set up aliases for shorthand notation.
{"const arg = require('arg');\n\nconst args = arg({\n // Types\n '--help': Boolean,\n '--version': Boolean,\n '--verbose': arg.COUNT, // A count of how many times the flag was set\n '--port': Number, // A port number\n '--name': String, // A string name\n // Aliases\n '-h': '--help',\n '-v': '--version',\n '-n': '--name'\n});\n\nconsole.log(args); // Output the parsed arguments"}
Handling default values
This feature allows developers to specify default values for command-line options that are not provided by the user. The example code shows how to set default values for a port and host.
{"const arg = require('arg');\n\nconst args = arg({\n '--port': Number,\n '--host': String\n}, {\n // Default values\n '--port': 8080,\n '--host': 'localhost'\n});\n\nconsole.log(args); // Output the parsed arguments with defaults"}
Permissive parsing
This feature enables permissive parsing, which means that the parser will ignore any flags that are not explicitly defined in the schema. The example code shows how to enable permissive parsing.
{"const arg = require('arg');\n\nconst args = arg({\n '--port': Number,\n '--host': String\n}, {\n permissive: true\n});\n\nconsole.log(args); // Output the parsed arguments, ignoring any non-specified flags"}
Yargs is a more feature-rich command-line argument parsing library. It provides a fluent API, built-in help, command handling, and more. It is often preferred for complex CLI applications that require detailed configurations and command structures.
Commander is another popular npm package for command-line interfaces. It includes support for subcommands, custom help, auto-versioning, and is used by many large projects. It is more object-oriented compared to arg and is suitable for applications with a variety of commands and options.
Minimist is a minimalistic argument parsing library. It is lightweight and straightforward, with fewer features than arg. It is a good choice for simple command-line applications or for those who prefer a minimalistic approach.
Meow is a CLI app helper built on top of minimist. It provides a higher-level API with features like help text generation and input normalization. It is designed to create simple CLI tools quickly and with less boilerplate.
arg
is an unopinionated, no-frills CLI argument parser.
npm install arg
arg()
takes either 1 or 2 arguments:
{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}
)It returns an object with any values present on the command-line (missing options are thus missing from the resulting object). Arg performs no validation/requirement checking - we leave that up to the application.
All parameters that aren't consumed by options (commonly referred to as "extra" parameters)
are added to result._
, which is always an array (even if no extra parameters are passed,
in which case an empty array is returned).
const arg = require('arg');
// `options` is an optional parameter
const args = arg(
spec,
(options = { permissive: false, argv: process.argv.slice(2) })
);
For example:
$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
// hello.js
const arg = require('arg');
const args = arg({
// Types
'--help': Boolean,
'--version': Boolean,
'--verbose': arg.COUNT, // Counts the number of times --verbose is passed
'--port': Number, // --port <number> or --port=<number>
'--name': String, // --name <string> or --name=<string>
'--tag': [String], // --tag <string> or --tag=<string>
// Aliases
'-v': '--verbose',
'-n': '--name', // -n <string>; result is stored in --name
'--label': '--name' // --label <string> or --label=<string>;
// result is stored in --name
});
console.log(args);
/*
{
_: ["foo", "bar", "--foobar"],
'--port': 1234,
'--verbose': 4,
'--name': "My name",
'--tag': ["qux", "qix"]
}
*/
The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias).
In the case of a function, the string value of the argument's value is passed to it, and the return value is used as the ultimate value.
In the case of an array, the only element must be a type function. Array types indicate that the argument may be passed multiple times, and as such the resulting value in the returned object is an array with all of the values that were passed using the specified flag.
In the case of a string, an alias is established. If a flag is passed that matches the key, then the value is substituted in its place.
Type functions are passed three arguments:
--label
)-v
multiple times, etc.)This means the built-in String
, Number
, and Boolean
type constructors "just work" as type functions.
Note that Boolean
and [Boolean]
have special treatment - an option argument is not consumed or passed, but instead true
is
returned. These options are called "flags".
For custom handlers that wish to behave as flags, you may pass the function through arg.flag()
:
const arg = require('arg');
const argv = [
'--foo',
'bar',
'-ff',
'baz',
'--foo',
'--foo',
'qux',
'-fff',
'qix'
];
function myHandler(value, argName, previousValue) {
/* `value` is always `true` */
return 'na ' + (previousValue || 'batman!');
}
const args = arg(
{
'--foo': arg.flag(myHandler),
'-f': '--foo'
},
{
argv
}
);
console.log(args);
/*
{
_: ['bar', 'baz', 'qux', 'qix'],
'--foo': 'na na na na na na na na batman!'
}
*/
As well, arg
supplies a helper argument handler called arg.COUNT
, which equivalent to a [Boolean]
argument's .length
property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line..
For example, this is how you could implement ssh
's multiple levels of verbosity (-vvvv
being the most verbose).
const arg = require('arg');
const argv = ['-AAAA', '-BBBB'];
const args = arg(
{
'-A': arg.COUNT,
'-B': [Boolean]
},
{
argv
}
);
console.log(args);
/*
{
_: [],
'-A': 4,
'-B': [true, true, true, true]
}
*/
If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of arg()
.
argv
If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting arg
slice them from process.argv
) you may specify them in the argv
option.
For example:
const args = arg(
{
'--foo': String
},
{
argv: ['hello', '--foo', 'world']
}
);
results in:
const args = {
_: ['hello'],
'--foo': 'world'
};
permissive
When permissive
set to true
, arg
will push any unknown arguments
onto the "extra" argument array (result._
) instead of throwing an error about
an unknown flag.
For example:
const arg = require('arg');
const argv = [
'--foo',
'hello',
'--qux',
'qix',
'--bar',
'12345',
'hello again'
];
const args = arg(
{
'--foo': String,
'--bar': Number
},
{
argv,
permissive: true
}
);
results in:
const args = {
_: ['--qux', 'qix', 'hello again'],
'--foo': 'hello',
'--bar': 12345
};
stopAtPositional
When stopAtPositional
is set to true
, arg
will halt parsing at the first
positional argument.
For example:
const arg = require('arg');
const argv = ['--foo', 'hello', '--bar'];
const args = arg(
{
'--foo': Boolean,
'--bar': Boolean
},
{
argv,
stopAtPositional: true
}
);
results in:
const args = {
_: ['hello', '--bar'],
'--foo': true
};
Some errors that arg
throws provide a .code
property in order to aid in recovering from user error, or to
differentiate between user error and developer error (bug).
If an unknown option (not defined in the spec object) is passed, an error with code ARG_UNKNOWN_OPTION
will be thrown:
// cli.js
try {
require('arg')({ '--hi': String });
} catch (err) {
if (err.code === 'ARG_UNKNOWN_OPTION') {
console.log(err.message);
} else {
throw err;
}
}
node cli.js --extraneous true
Unknown or unexpected option: --extraneous
A few questions and answers that have been asked before:
arg
?Do the assertion yourself, such as:
const args = arg({ '--name': String });
if (!args['--name']) throw new Error('missing required argument: --name');
Released under the MIT License.
FAQs
Unopinionated, no-frills CLI argument parser
We found that arg demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 164 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.