npm-audit

Run a security audit运行安全审核

Synopsis提要


npm audit [fix|signatures]

Description描述

The audit command submits a description of the dependencies configured in your project to your default registry and asks for a report of known vulnerabilities. audit命令将项目中配置的依赖项的描述提交到默认注册表,并要求提供已知漏洞的报告。If any vulnerabilities are found, then the impact and appropriate remediation will be calculated. 如果发现任何漏洞,将计算影响和适当的补救措施。If the fix argument is provided, then remediations will be applied to the package tree.如果提供了fix参数,则修正将应用于包树。

The command will exit with a 0 exit code if no vulnerabilities were found.如果未发现漏洞,该命令将以0退出代码退出。

Note that some vulnerabilities cannot be fixed automatically and will require manual intervention or review. 请注意,有些漏洞无法自动修复,需要手动干预或审查。 Also note that since npm audit fix runs a full-fledged npm install under the hood, all configs that apply to the installer will also apply to npm install -- so things like npm audit fix --package-lock-only will work as expected.还要注意的是,由于npm audit fix在后台运行完整的npm install,因此应用于安装程序的所有配置也将应用于npm install——因此像npm audit fix --package-lock-only这样的东西只能按预期工作。

By default, the audit command will exit with a non-zero code if any vulnerability is found. 默认情况下,如果发现任何漏洞,audit命令将以非零代码退出。It may be useful in CI environments to include the --audit-level parameter to specify the minimum vulnerability level that will cause the command to fail. 在CI环境中,包含--audit-level参数以指定将导致命令失败的最低漏洞级别可能很有用。This option does not filter the report output, it simply changes the command's failure threshold.此选项不筛选报告输出,它只是更改命令的失败阈值。

Audit Signatures审核签名

To ensure the integrity of packages you download from the public npm registry, or any registry that supports signatures, you can verify the registry signatures of downloaded packages using the npm CLI.为了确保从公共npm注册表或任何支持签名的注册表下载的包的完整性,可以使用npm CLI验证下载包的注册表签名。

Registry signatures can be verified using the following audit command:可以使用以下audit命令验证注册表签名:


$ npm audit signatures

The npm CLI supports registry signatures and signing keys provided by any registry if the following conventions are followed:如果遵循以下约定,npm CLI支持任何注册表提供的注册表签名和签名密钥:

  1. Signatures are provided in the package's packument in each published version within the dist object:dist对象中每个已发布版本的packument中都提供了签名:

"dist":{
"..omitted..": "..omitted..",
"signatures": [{
"keyid": "SHA256:{{SHA256_PUBLIC_KEY}}",
"sig": "a312b9c3cb4a1b693e8ebac5ee1ca9cc01f2661c14391917dcb111517f72370809..."
}]
}

See this example of a signed package from the public npm registry.请参阅以下来自公共npm注册表的签名包的示例

The sig is generated using the following template: ${package.name}@${package.version}:${package.dist.integrity} and the keyid has to match one of the public signing keys below.

  1. Public signing keys are provided at registry-host.tld/-/npm/v1/keys in the following format:注册表registry-host.tld/-/npm/v1/keys中提供了以下格式的公共签名密钥:

{
"keys": [{
"expires": null,
"keyid": "SHA256:{{SHA256_PUBLIC_KEY}}",
"keytype": "ecdsa-sha2-nistp256",
"scheme": "ecdsa-sha2-nistp256",
"key": "{{B64_PUBLIC_KEY}}"
}]
}

Keys response:按键响应:

  • expires: null or a simplified extended ISO 8601 format: YYYY-MM-DDTHH:mm:ss.sssZ
  • keydid: sha256 fingerprint of the public key:sha256公钥指纹
  • keytype: only ecdsa-sha2-nistp256 is currently supported by the npm CLI当前由npm CLI支持
  • scheme: only ecdsa-sha2-nistp256 is currently supported by the npm CLI当前由npm CLI支持
  • key: base64 encoded public key:base64编码的公钥

See this example key's response from the public npm registry.请参阅此示例密钥从公共npm注册表中的响应。

Audit Endpoints

There are two audit endpoints that npm may use to fetch vulnerability information: the Bulk Advisory endpoint and the Quick Audit endpoint.npm可以使用两个审计端点来获取漏洞信息:Bulk Advisory端点和Quick Audit端点。

Bulk Advisory Endpoint批量咨询终结点

As of version 7, npm uses the much faster Bulk Advisory endpoint to optimize the speed of calculating audit results.从版本7开始,npm使用更快的Bulk Advisory端点来优化计算审计结果的速度。

npm will generate a JSON payload with the name and list of versions of each package in the tree, and POST it to the default configured registry at the path /-/npm/v1/security/advisories/bulk.npm将生成一个JSON负载,其中包含树中每个包的名称和版本列表,并将其POST到路径为/-/npm/v1/security/advisories/bulk的默认配置注册表中。

Any packages in the tree that do not have a version field in their package.json file will be ignored. If any --omit options are specified (either via the --omit config, or one of the shorthands such as --production, --only=dev, and so on), then packages will be omitted from the submitted payload as appropriate.

If the registry responds with an error, or with an invalid response, then npm will attempt to load advisory data from the Quick Audit endpoint.

The expected result will contain a set of advisory objects for each dependency that matches the advisory range. Each advisory object contains a name, url, id, severity, vulnerable_versions, and title.

npm then uses these advisory objects to calculate vulnerabilities and meta-vulnerabilities of the dependencies within the tree.

Quick Audit Endpoint快速审核终结点

If the Bulk Advisory endpoint returns an error, or invalid data, npm will attempt to load advisory data from the Quick Audit endpoint, which is considerably slower in most cases.

The full package tree as found in package-lock.json is submitted, along with the following pieces of additional metadata:package-lock.json中找到的完整包树以及以下附加元数据将被提交:

  • npm_version
  • node_version
  • platform
  • arch
  • node_env

All packages in the tree are submitted to the Quick Audit endpoint. 树中的所有包都将提交到快速审核端点。Omitted dependency types are skipped when generating the report.生成报告时会跳过省略的依赖关系类型。

Scrubbing擦洗

Out of an abundance of caution, npm versions 5 and 6 would "scrub" any packages from the submitted report if their name contained a / character, so as to avoid leaking the names of potentially private packages or git URLs.出于谨慎,npm版本5和6会从提交的报告中“清除”任何名称包含/字符的包,以避免泄露潜在的私有包或git URL的名称。

However, in practice, this resulted in audits often failing to properly detect meta-vulnerabilities, because the tree would appear to be invalid due to missing dependencies, and prevented the detection of vulnerabilities in package trees that used git dependencies or private modules.然而,在实践中,这导致审计往往无法正确检测元漏洞,因为树由于缺少依赖项而显得无效,并阻止了对使用git依赖项或私有模块的包树中的漏洞的检测。

This scrubbing has been removed from npm as of version 7.自版本7起,此清理已从npm中删除。

Calculating Meta-Vulnerabilities and Remediations计算元漏洞和补救措施

npm uses the @npmcli/metavuln-calculator module to turn a set of security advisories into a set of "vulnerability" objects. A "meta-vulnerability" is a dependency that is vulnerable by virtue of dependence on vulnerable versions of a vulnerable package.

For example, if the package foo is vulnerable in the range >=1.0.2 <2.0.0, and the package bar depends on foo@^1.1.0, then that version of bar can only be installed by installing a vulnerable version of foo. In this case, bar is a "metavulnerability".

Once metavulnerabilities for a given package are calculated, they are cached in the ~/.npm folder and only re-evaluated if the advisory range changes, or a new version of the package is published (in which case, the new version is checked for metavulnerable status as well).

If the chain of metavulnerabilities extends all the way to the root project, and it cannot be updated without changing its dependency ranges, then npm audit fix will require the --force option to apply the remediation. If remediations do not require changes to the dependency ranges, then all vulnerable packages will be updated to a version that does not have an advisory or metavulnerability posted against it.如果修正不需要更改依赖关系范围,则所有易受攻击的程序包都将更新到没有针对其发布的咨询或元漏洞的版本。

Exit Code

The npm audit command will exit with a 0 exit code if no vulnerabilities were found. 如果未发现漏洞,npm audit命令将以0退出代码退出。The npm audit fix command will exit with 0 exit code if no vulnerabilities are found or if the remediation is able to successfully fix all vulnerabilities.

If vulnerabilities were found the exit code will depend on the audit-level config.

Examples

Scan your project for vulnerabilities and automatically install any compatible updates to vulnerable dependencies:扫描您的项目以查找漏洞,并自动安装针对易受攻击依赖项的任何兼容更新:


$ npm audit fix

Run audit fix without modifying node_modules, but still updating the pkglock:运行audit fix,不修改node_modules,但仍更新pkglock:


$ npm audit fix --package-lock-only

Skip updating devDependencies:跳过更新devDependencies


$ npm audit fix --only=prod

Have audit fix install SemVer-major updates to toplevel dependencies, not just SemVer-compatible ones:audit fix安装SemVer对顶级依赖项的主要更新,而不仅仅是与SemVer兼容的依赖项:


$ npm audit fix --force

Do a dry run to get an idea of what audit fix will do, and also output install information in JSON format:进行一次试运行,了解audit fix的作用,并以JSON格式输出安装信息:


$ npm audit fix --dry-run --json

Scan your project for vulnerabilities and just show the details, without fixing anything:扫描您的项目中的漏洞,只显示详细信息,而不修复任何内容:


$ npm audit

Get the detailed audit report in JSON format:获取JSON格式的详细审计报告:


$ npm audit --json

Fail an audit only if the results include a vulnerability with a level of moderate or higher:仅当结果包括中等或更高级别的漏洞时,审核失败:


$ npm audit --audit-level=moderate

Configuration

audit-level

  • Default: null
  • Type: null, "info", "low", "moderate", "high", "critical", or "none"

The minimum level of vulnerability for npm audit to exit with a non-zero exit code.

dry-run

  • Default: false
  • Type: Boolean

Indicates that you don't want npm to make any changes and that it should only report what it would have done. This can be passed into any of the commands that modify your local installation, eg, install, update, dedupe, uninstall, as well as pack and publish.

Note: This is NOT honored by other network related commands, eg dist-tags, owner, etc.

force

  • Default: false
  • Type: Boolean

Removes various protections against unfortunate side effects, common mistakes, unnecessary performance degradation, and malicious input.

  • Allow clobbering non-npm files in global installs.
  • Allow the npm version command to work on an unclean git repository.
  • Allow deleting the cache folder with npm cache clean.
  • Allow installing packages that have an engines declaration requiring a different version of npm.
  • Allow installing packages that have an engines declaration requiring a different version of node, even if --engine-strict is enabled.
  • Allow npm audit fix to install modules outside your stated dependency range (including SemVer-major changes).
  • Allow unpublishing all versions of a published package.
  • Allow conflicting peerDependencies to be installed in the root project.
  • Implicitly set --yes during npm init.
  • Allow clobbering existing values in npm pkg
  • Allow unpublishing of entire packages (not just a single version).

If you don't have a clear idea of what you want to do, it is strongly recommended that you do not use this option!

json

  • Default: false
  • Type: Boolean

Whether or not to output JSON data, rather than the normal output.

  • In npm pkg set it enables parsing set values with JSON.parse() before saving them to your package.json.

Not supported by all npm commands.

package-lock-only

  • Default: false
  • Type: Boolean

If set to true, the current operation will only use the package-lock.json, ignoring node_modules.

For update this means only the package-lock.json will be updated, instead of checking node_modules and downloading dependencies.

For list this means the output will be based on the tree described by the package-lock.json, rather than the contents of node_modules.

omit

  • Default: 'dev' if the NODE_ENV environment variable is set to 'production', otherwise empty.
  • Type: "dev", "optional", or "peer" (can be set multiple times)

Dependency types to omit from the installation tree on disk.

Note that these dependencies are still resolved and added to the package-lock.json or npm-shrinkwrap.json file. They are just not physically installed on disk.

If a package type appears in both the --include and --omit lists, then it will be included.

If the resulting omit list includes 'dev', then the NODE_ENV environment variable will be set to 'production' for all lifecycle scripts.

foreground-scripts

  • Default: false
  • Type: Boolean

Run all build scripts (ie, preinstall, install, and postinstall) scripts for installed packages in the foreground process, sharing standard input, output, and error with the main npm process.

Note that this will generally make installs run slower, and be much noisier, but can be useful for debugging.

ignore-scripts

  • Default: false
  • Type: Boolean

If true, npm does not run scripts specified in package.json files.

Note that commands explicitly intended to run a particular script, such as npm start, npm stop, npm restart, npm test, and npm run-script will still run their intended script if ignore-scripts is set, but they will not run any pre- or post-scripts.

workspace

  • Default:
  • Type: String (can be set multiple times)

Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option.

Valid values for the workspace config are either:

  • Workspace names
  • Path to a workspace directory
  • Path to a parent workspace directory (will result in selecting all workspaces within that folder)

When set for the npm init command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project.

This value is not exported to the environment for child processes.

workspaces

  • Default: null
  • Type: null or Boolean

Set to true to run the command in the context of all configured workspaces.

Explicitly setting this to false will cause commands like install to ignore workspaces altogether. When not set explicitly:

  • Commands that operate on the node_modules tree (install, update, etc.) will link workspaces into the node_modules folder. - Commands that do other things (test, exec, publish, etc.) will operate on the root project, unless one or more workspaces are specified in the workspace config.

This value is not exported to the environment for child processes.

include-workspace-root

  • Default: false
  • Type: Boolean

Include the workspace root when workspaces are enabled for a command.

When false, specifying individual workspaces via the workspace config, or all workspaces via the workspaces flag, will cause npm to operate only on the specified workspaces, and not on the root project.

This value is not exported to the environment for child processes.

  • Default: false
  • Type: Boolean

When set file: protocol dependencies will be packed and installed as regular dependencies instead of creating a symlink. This option has no effect on workspaces.

See Also