npm-audit

运行安全审计

选择命令行版本:

概要

¥Synopsis

npm audit [fix|signatures]

描述

¥Description

audit 命令将项目中配置的依赖的描述提交到默认注册表,并要求报告已知漏洞。如果发现任何漏洞,则将计算影响和适当的补救措施。如果提供了 fix 参数,则补救措施将应用于包树。

¥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. 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.

如果没有发现漏洞,该命令将以 0 退出代码退出。

¥The command will exit with a 0 exit code if no vulnerabilities were found.

请注意,某些漏洞无法自动修复,需要人工干预或审查。另请注意,由于 npm audit fix 在引擎盖下运行一个成熟的 npm install,适用于安装程序的所有配置也将适用于 npm install - 所以像 npm audit fix --package-lock-only 这样的东西将按预期工作。

¥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.

默认情况下,如果发现任何漏洞,审计命令将以非零代码退出。在 CI 环境中包含 --audit-level 参数以指定将导致命令失败的最低漏洞级别可能很有用。此选项不过滤报告输出,它只是更改命令的失败阈值。

¥By default, the audit command will exit with a non-zero code if any vulnerability is found. 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. This option does not filter the report output, it simply changes the command's failure threshold.

包锁

¥Package lock

默认情况下,npm 需要包锁或收缩封装才能运行审核。你可以使用 --no-package-lock 绕过包锁,但请注意每次运行的结果可能会有所不同,因为 npm 每次都会重新构建依赖树。

¥By default npm requires a package-lock or shrinkwrap in order to run the audit. You can bypass the package lock with --no-package-lock but be aware the results may be different with every run, since npm will re-build the dependency tree each time.

审计签名

¥Audit Signatures

为了确保你从公共 npm 注册表或任何支持签名的注册表下载的包的完整性,你可以使用 npm CLI 验证下载包的注册表签名。

¥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.

可以使用以下 audit 命令验证注册表签名:

¥Registry signatures can be verified using the following audit command:

$ npm audit signatures

audit signatures 命令还将验证下载包的来源证明。由于出处证明是一项新功能,因此随着时间的推移,安全功能可能会添加到证明格式中(或更改)。为了确保你始终能够验证证明签名,请检查你是否正在运行最新版本的 npm CLI。请注意,这通常意味着更新 npm 超出 Node.js 附带的版本。

¥The audit signatures command will also verify the provenance attestations of downloaded packages. Because provenance attestations are such a new feature, security features may be added to (or changed in) the attestation format over time. To ensure that you're always able to verify attestation signatures check that you're running the latest version of the npm CLI. Please note this often means updating npm beyond the version that ships with Node.js.

如果遵循以下约定,npm CLI 支持任何注册表提供的注册表签名和签名密钥:

¥The npm CLI supports registry signatures and signing keys provided by any registry if the following conventions are followed:

  1. 签名在 dist 对象中每个已发布版本的包的 packument 中提供:

    ¥Signatures are provided in the package's packument in each published version within the dist object:

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

查看来自公共 npm 注册表的签名包的 示例

¥See this example of a signed package from the public npm registry.

sig 是使用以下模板生成的:${package.name}@${package.version}:${package.dist.integrity}keyid 必须匹配以下公共签名密钥之一。

¥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. 公共签名密钥在 registry-host.tld/-/npm/v1/keys 以以下格式提供:

    ¥Public signing keys are provided at registry-host.tld/-/npm/v1/keys in the following format:

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

键响应:

¥Keys response:

  • expires:null 或简化的扩展 ISO 8601 格式YYYY-MM-DDTHH:mm:ss.sssZ

    ¥expires: null or a simplified extended ISO 8601 format: YYYY-MM-DDTHH:mm:ss.sssZ

  • keydid:公钥的 sha256 指纹

    ¥keydid: sha256 fingerprint of the public key

  • keytype:npm CLI 当前仅支持 ecdsa-sha2-nistp256

    ¥keytype: only ecdsa-sha2-nistp256 is currently supported by the npm CLI

  • scheme:npm CLI 当前仅支持 ecdsa-sha2-nistp256

    ¥scheme: only ecdsa-sha2-nistp256 is currently supported by the npm CLI

  • key:base64 编码的公钥

    ¥key: base64 encoded public key

请参阅此 来自公共 npm 注册表的示例密钥响应

¥See this example key's response from the public npm registry.

审计端点

¥Audit Endpoints

npm 可以使用两个审计端点来获取漏洞信息:Bulk Advisory 端点和 Quick Audit 端点。

¥There are two audit endpoints that npm may use to fetch vulnerability information: the Bulk Advisory endpoint and the Quick Audit endpoint.

批量咨询端点

¥Bulk Advisory Endpoint

从版本 7 开始,npm 使用更快的 Bulk Advisory 端点来优化计算审计结果的速度。

¥As of version 7, npm uses the much faster Bulk Advisory endpoint to optimize the speed of calculating audit results.

npm 将生成一个 JSON 有效负载,其中包含树中每个包的名称和版本列表,并将其 POST 到路径 /-/npm/v1/security/advisories/bulk 处的默认配置注册表。

¥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.

树中任何 package.json 文件中没有 version 字段的包都将被忽略。如果指定了任何 --omit 选项(通过 --omit 配置--production--only=dev 等简写之一),则将根据需要从提交的有效负载中省略包。

¥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.

如果注册表响应错误或无效响应,则 npm 将尝试从 Quick Audit 端点加载咨询数据。

¥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.

预期结果将包含一组与咨询范围匹配的每个依赖的咨询对象。每个咨询对象都包含一个 nameurlidseverityvulnerable_versionstitle

¥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 使用这些咨询对象来计算树中依赖的漏洞和元漏洞。

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

快速审计端点

¥Quick Audit Endpoint

如果 Bulk Advisory 端点返回错误或无效数据,npm 将尝试从 Quick Audit 端点加载咨询数据,这在大多数情况下要慢得多。

¥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.

提交 package-lock.json 中的完整包树以及以下附加元数据:

¥The full package tree as found in package-lock.json is submitted, along with the following pieces of additional metadata:

  • 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

出于谨慎考虑,npm 版本 5 和 6 如果名称包含 / 字符,则会对提交的报告中的任何包进行 "scrub",以避免泄露潜在私有包或 git URL 的名称。

¥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.

然而,在实践中,这导致审计经常无法正确检测元漏洞,因为由于缺少依赖,树看起来是无效的,并且阻止了检测使用 git 依赖或私有模块的包树中的漏洞。

¥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.

从版本 7 开始,此清理已从 npm 中删除。

¥This scrubbing has been removed from npm as of version 7.

计算元漏洞和补救措施

¥Calculating Meta-Vulnerabilities and Remediations

npm 使用 @npmcli/metavuln-calculator 模块将一组安全建议转换为一组 "vulnerability" 对象。"meta-vulnerability" 是一种依赖,由于依赖于易受攻击的包的易受攻击版本,因此易受攻击。

¥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.

例如,如果包 foo>=1.0.2 <2.0.0 范围内易受攻击,而包 bar 依赖于 foo@^1.1.0,则只能通过安装易受攻击的 foo 版本来安装该版本的 bar。在这种情况下,bar 是 "metavulnerability"。

¥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".

一旦计算了给定包的元漏洞,它们就会被缓存在 ~/.npm 文件夹中,并且只有在建议范围发生变化或发布了包的新版本时才会重新评估(在这种情况下,将检查新版本的元漏洞状态为出色地)。

¥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).

如果元漏洞链一直延伸到根项目,并且在不更改其依赖范围的情况下无法更新,则 npm audit fix 将需要 --force 选项来应用修复。如果补救措施不需要更改依赖范围,那么所有易受攻击的包都将更新到没有针对它发布建议或元漏洞的版本。

¥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

如果没有发现漏洞,npm audit 命令将以 0 退出代码退出。如果没有发现漏洞或者修复能够成功修复所有漏洞,npm audit fix 命令将以 0 退出代码退出。

¥The npm audit command will exit with a 0 exit code if no vulnerabilities were found. 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.

如果发现漏洞,退出代码将取决于 audit-level 配置

¥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

在不修改 node_modules 的情况下运行 audit fix,但仍然更新 pkglock:

¥Run audit fix without modifying node_modules, but still updating the pkglock:

$ npm audit fix --package-lock-only

跳过更新 devDependencies

¥Skip updating devDependencies:

$ npm audit fix --only=prod

audit fix 对顶层依赖安装 SemVer 主要更新,而不仅仅是与 SemVer 兼容的更新:

¥Have audit fix install SemVer-major updates to toplevel dependencies, not just SemVer-compatible ones:

$ npm audit fix --force

进行试运行以了解 audit fix 将做什么,并以 JSON 格式输出安装信息:

¥Do a dry run to get an idea of what audit fix will do, and also output install information in JSON format:

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

扫描你的项目中的漏洞并仅显示详细信息,而不修复任何内容:

¥Scan your project for vulnerabilities and just show the details, without fixing anything:

$ npm audit

获取 JSON 格式的详细审计报告:

¥Get the detailed audit report in JSON format:

$ 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

  • 默认值:null

    ¥Default: null

  • 类型:空、"info"、"low"、"moderate"、"high"、"critical" 或 "none"

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

npm audit 以非零退出代码退出的最低漏洞级别。

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

dry-run

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

表示你不希望 npm 进行任何更改,并且它应该只报告它会做的事情。这可以传递到任何修改本地安装的命令中,例如 installupdatededupeuninstall 以及 packpublish

¥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.

注意:其他网络相关命令不支持此功能,例如 dist-tagsowner 等。

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

force

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

删除了针对不幸的副作用、常见错误、不必要的性能下降和恶意输入的各种保护。

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

  • 允许在全局安装中破坏非 npm 文件。

    ¥Allow clobbering non-npm files in global installs.

  • 允许 npm version 命令在不干净的 git 存储库上工作。

    ¥Allow the npm version command to work on an unclean git repository.

  • 允许使用 npm cache clean 删除缓存文件夹。

    ¥Allow deleting the cache folder with npm cache clean.

  • 允许安装具有 engines 声明需要不同版本的 npm 的包。

    ¥Allow installing packages that have an engines declaration requiring a different version of npm.

  • 允许安装具有 engines 声明需要不同版本 node 的包,即使启用了 --engine-strict

    ¥Allow installing packages that have an engines declaration requiring a different version of node, even if --engine-strict is enabled.

  • 允许 npm audit fix 安装超出你声明的依赖范围的模块(包括 SemVer 的主要更改)。

    ¥Allow npm audit fix to install modules outside your stated dependency range (including SemVer-major changes).

  • 允许取消发布已发布包的所有版本。

    ¥Allow unpublishing all versions of a published package.

  • 允许在根项目中安装冲突的 peerDependencies。

    ¥Allow conflicting peerDependencies to be installed in the root project.

  • npm init 时隐式设置 --yes

    ¥Implicitly set --yes during npm init.

  • 允许破坏 npm pkg 中的现有值

    ¥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

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

是否输出 JSON 数据,而不是正常输出。

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

  • npm pkg set 中,它可以使用 JSON.parse() 解析集合值,然后再将它们保存到你的 package.json

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

并非所有 npm 命令都支持。

¥Not supported by all npm commands.

package-lock-only

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

如果设置为 true,当前操作将只使用 package-lock.json,忽略 node_modules

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

对于 update,这意味着只会更新 package-lock.json,而不是检查 node_modules 并下载依赖。

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

对于 list,这意味着输出将基于 package-lock.json 描述的树,而不是 node_modules 的内容。

¥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.

package-lock

  • 默认值:true

    ¥Default: true

  • 类型:布尔值

    ¥Type: Boolean

如果设置为 false,则安装时忽略 package-lock.json 文件。如果 save 为真,这也将阻止写入 package-lock.json

¥If set to false, then ignore package-lock.json files when installing. This will also prevent writing package-lock.json if save is true.

omit

  • 默认值:'dev' 如果 NODE_ENV 环境变量设置为 'production',否则为空。

    ¥Default: 'dev' if the NODE_ENV environment variable is set to 'production', otherwise empty.

  • 类型:"dev"、"optional"、"peer"(可多次设置)

    ¥Type: "dev", "optional", or "peer" (can be set multiple times)

要从磁盘上的安装树中省略的依赖类型。

¥Dependency types to omit from the installation tree on disk.

请注意,这些依赖仍会被解析并添加到 package-lock.jsonnpm-shrinkwrap.json 文件中。它们只是没有物理安装在磁盘上。

¥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.

如果一个包类型同时出现在 --include--omit 列表中,那么它将被包括在内。

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

如果生成的省略列表包含 'dev',则 NODE_ENV 环境变量将针对所有生命周期脚本设置为 'production'

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

include

  • 默认值:

    ¥Default:

  • 类型:"prod"、"dev"、"optional"、"peer"(可多次设置)

    ¥Type: "prod", "dev", "optional", or "peer" (can be set multiple times)

允许定义要安装的依赖类型的选项。

¥Option that allows for defining which types of dependencies to install.

这是 --omit=<type> 的倒数。

¥This is the inverse of --omit=<type>.

--include 中指定的依赖类型将不会被忽略,无论命令行中指定省略/包含的顺序如何。

¥Dependency types specified in --include will not be omitted, regardless of the order in which omit/include are specified on the command-line.

foreground-scripts

  • 默认值:false 除非使用 npm packnpm publish 时默认为 true

    ¥Default: false unless when using npm pack or npm publish where it defaults to true

  • 类型:布尔值

    ¥Type: Boolean

在前台进程中运行已安装包的所有构建脚本(即 preinstallinstallpostinstall)脚本,与主 npm 进程共享标准输入、输出和错误。

¥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

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

如果为 true,npm 不会运行 package.json 文件中指定的脚本。

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

请注意,如果设置了 ignore-scripts,则明确旨在运行特定脚本的命令(例如 npm startnpm stopnpm restartnpm testnpm run-script)仍将运行其预期的脚本,但它们不会运行任何前置或后置脚本。

¥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.

workspace 配置的有效值为:

¥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)

npm init 命令设置时,可以将其设置为尚不存在的工作区的文件夹,以创建文件夹并将其设置为项目中的全新工作区。

¥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

  • 默认值:null

    ¥Default: null

  • 类型:空值或布尔值

    ¥Type: null or Boolean

设置为 true 可在所有已配置工作区的上下文中运行该命令。

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

显式将此设置为 false 将导致像 install 这样的命令完全忽略工作区。未明确设置时:

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

  • node_modules 树上运行的命令(安装、更新等)会将工作区链接到 node_modules 文件夹。* 执行其他操作(测试、执行、发布等)的命令将在根项目上运行,除非在 workspace 配置中指定了一个或多个工作区。

    ¥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

  • 默认值:false

    ¥Default: false

  • 类型:布尔值

    ¥Type: Boolean

为命令启用工作区时包括工作区根。

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

当为 false 时,通过 workspace 配置指定单个工作区,或通过 workspaces 标志指定所有工作区,将导致 npm 仅在指定的工作区上运行,而不是在根项目上运行。

¥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.

  • 默认值:false

    ¥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

npm 中文网 - 粤ICP备13048890号