可信发布允许你使用 OpenID Connect (OIDC) 身份验证直接从 CI/CD 工作流发布 npm 包,从而无需使用长期有效的 npm 令牌。此功能实现了开源安全基金会 (OpenSSF) 指定的 可信发布者行业标准,加入了包括 PyPIRubyGems 和其他主要软件包注册中心在内的不断发展的生态系统,从而提供了此安全增强功能。

¥Trusted publishing allows you to publish npm packages directly from your CI/CD workflows using OpenID Connect (OIDC) authentication, eliminating the need for long-lived npm tokens. This feature implements the trusted publishers industry standard specified by the Open Source Security Foundation (OpenSSF), joining a growing ecosystem including PyPI, RubyGems, and other major package registries in offering this security enhancement.

注意:可信发布需要 npm 命令行 11.5.1 或更高版本。

¥Note: Trusted publishing requires npm CLI version 11.5.1 or later.

可信发布的工作原理

¥How trusted publishing works

可信发布使用 OIDC 在 npm 和你的 CI/CD 提供商之间建立信任关系。当你为你的软件包配置可信发布者时,除了传统的身份验证方法(例如 npm 令牌和手动发布)之外,npm 还会接受来自你授权的特定工作流的发布。npm CLI 会自动检测 OIDC 环境,并在回退到传统令牌之前使用它们进行身份验证。

¥Trusted publishing creates a trust relationship between npm and your CI/CD provider using OIDC. When you configure a trusted publisher for your package, npm will accept publishes from the specific workflow you've authorized, in addition to traditional authentication methods like npm tokens and manual publishes. The npm CLI automatically detects OIDC environments and uses them for authentication before falling back to traditional tokens.

这种方法消除了与长期写入令牌相关的安全风险,这些令牌可能会被盗用、在日志中意外暴露或需要手动轮换。相反,每次发布都会使用特定于你的工作流程的短期加密签名令牌,这些令牌无法提取或重复使用。

¥This approach eliminates the security risks associated with long-lived write tokens, which can be compromised, accidentally exposed in logs, or require manual rotation. Instead, each publish uses short-lived, cryptographically-signed tokens that are specific to your workflow and cannot be extracted or reused.

支持的 CI/CD 提供商

¥Supported CI/CD providers

受信任的发布目前支持:

¥Trusted publishing currently supports:

目前不支持自托管运行器,但计划在未来版本中支持。

¥Self-hosted runners are not currently supported but are planned for future releases.

配置可信发布

¥Configuring trusted publishing

步骤 1:在 npmjs.com 上添加可信发布者

¥Step 1: Add a trusted publisher on npmjs.com

导航到 npmjs.com 上的软件包设置并找到 "受信任的发布者" 部分。在 "选择你的发布者" 下,点击 GitHub Actions 或 GitLab CI/CD 按钮选择你的 CI/CD 提供商。

¥Navigate to your package settings on npmjs.com and find the "Trusted Publisher" section. Under "Select your publisher", choose your CI/CD provider by clicking either the GitHub Actions or GitLab CI/CD button.

Screenshot showing the Trusted Publisher section with Select your publisher label and provider buttons

对于 GitHub Actions

¥For GitHub Actions

配置以下字段:

¥Configure the following fields:

  • 组织或用户(必填):你的 GitHub 用户名或组织名称

    ¥Organization or user (required): Your GitHub username or organization name

  • 仓库(必填):你的仓库名称

    ¥Repository (required): Your repository name

  • 工作流文件名(必填):工作流程的文件名(例如,publish.yml

    ¥Workflow filename (required): The filename of your workflow (e.g., publish.yml)

    • 仅输入文件名,无需完整路径

      ¥Enter only the filename, not the full path

    • 必须包含 .yml.yaml 扩展名

      ¥Must include the .yml or .yaml extension

    • 工作流程文件必须存在于存储库的 .github/workflows/

      ¥The workflow file must exist in .github/workflows/ in your repository

  • 环境名称(可选):如果使用 GitHub 环境 进行部署保护

    ¥Environment name (optional): If using GitHub environments for deployment protection

Screenshot of GitHub Actions trusted publisher configuration form

对于 GitLab CI/CD

¥For GitLab CI/CD

配置以下字段:

¥Configure the following fields:

  • 命名空间(必填):你的 GitLab 用户名或群组名称

    ¥Namespace (required): Your GitLab username or group name

  • 项目名称(必填):你的项目名称

    ¥Project name (required): Your project name

  • 顶层 CI 文件路径(必需):CI 文件的路径(例如,.gitlab-ci.yml

    ¥Top-level CI file path (required): The path to your CI file (e.g., .gitlab-ci.yml)

    • 必须包含 .yml 扩展名

      ¥Must include the .yml extension

  • 环境名称(可选):如果使用 GitLab 环境

    ¥Environment name (optional): If using GitLab environments

Screenshot of GitLab CI/CD trusted publisher configuration form

注意:每个包一次只能配置一个可信发布者。

¥Note: Each package can only have one trusted publisher configured at a time.

步骤 2:配置你的 CI/CD 工作流程

¥Step 2: Configure your CI/CD workflow

GitHub Actions 配置

¥GitHub Actions configuration

将所需的 OIDC 权限添加到你的工作流。完整示例:

¥Add the required OIDC permissions to your workflow. Here's a complete example:

name: Publish Package
on:
push:
tags:
- 'v*'
permissions:
id-token: write # Required for OIDC
contents: read
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org'
# Ensure npm 11.5.1 or later is installed
- name: Update npm
run: npm install -g npm@latest
- run: npm ci
- run: npm run build --if-present
- run: npm test
- run: npm publish

关键要求是 id-token: write 权限,它允许 GitHub Actions 生成 OIDC 令牌。在 GitHub 的 OIDC 文档 中了解更多信息。

¥The critical requirement is the id-token: write permission, which allows GitHub Actions to generate OIDC tokens. Learn more in GitHub's OIDC documentation.

GitLab CI/CD 配置

¥GitLab CI/CD configuration

在你的管道中配置 OIDC ID 令牌:

¥Configure the OIDC ID token in your pipeline:

stages:
- test
- build
- publish
variables:
NODE_VERSION: '20'
id_tokens:
NPM_ID_TOKEN:
aud: "npm:registry.npmjs.org"
test:
stage: test
image: node:${NODE_VERSION}
script:
- npm ci
- npm test
publish:
stage: publish
image: node:${NODE_VERSION}
script:
# Ensure npm 11.5.1 or later is installed
- npm install -g npm@latest
- npm ci
- npm run build --if-present
- npm publish
only:
- tags

id_tokens 配置指示 GitLab 为 npm 生成 OIDC 令牌。在 GitLab 的 OIDC 文档 中了解更多信息。

¥The id_tokens configuration tells GitLab to generate an OIDC token for npm. Learn more in GitLab's OIDC documentation.

管理可信发布者配置

¥Managing trusted publisher configurations

你可以随时通过 npmjs.com 上的软件包设置修改或删除可信发布者配置。每个包一次只能连接一个可信发布者,但可以根据需要编辑或删除此连接。要更改提供商(例如,从 GitHub Actions 切换到 GitLab CI/CD),只需编辑现有配置并选择新的提供商即可。此更改将立即生效,并用于未来的发布。要完全删除受信任的发布并返回基于令牌的身份验证,请从软件包设置中删除受信任的发布者配置。

¥You can modify or remove your trusted publisher configuration at any time through your package settings on npmjs.com. Each package can only have one trusted publisher connection at a time, but this connection can be edited or deleted as needed. To change providers (for example, switching from GitHub Actions to GitLab CI/CD), simply edit your existing configuration and select the new provider. The change takes effect immediately for future publishes. To remove trusted publishing entirely and return to token-based authentication, delete the trusted publisher configuration from your package settings.

自动溯源生成

¥Automatic provenance generation

当你使用可信发布功能进行发布时,npm 会自动为你的软件包生成并发布 出处证明。此操作默认发生 - 你无需在发布命令中添加 --provenance 标志。

¥When you publish using trusted publishing, npm automatically generates and publishes provenance attestations for your package. This happens by default—you don't need to add the --provenance flag to your publish command.

Screenshot showing provenance badge/information on a package page

Provenance 提供软件包构建位置和方式的加密证明,允许用户验证其真实性。此自动生成仅在满足以下所有条件时才适用:

¥Provenance provides cryptographic proof of where and how your package was built, allowing users to verify its authenticity. This automatic generation only applies when all of these conditions are met:

  • 通过可信发布 (OIDC) 发布

    ¥Publishing via trusted publishing (OIDC)

  • 从公共仓库发布

    ¥Publishing from a public repository

  • 发布公共软件包

    ¥Publishing a public package

注意:即使发布公共软件包,Provenance 生成也是 不支持私有仓库

¥Note: Provenance generation is not supported for private repositories, even when publishing public packages.

禁用溯源生成

¥Disabling provenance generation

虽然我们强烈建议保持 provenance 启用状态,但你也可以根据需要禁用它。通过以下任一方式将 provenance 选项设置为 false

¥While we strongly recommend keeping provenance enabled, you can disable it if needed. Set the provenance option to false in any of these ways:

使用环境变量:

¥Using environment variable:

NPM_CONFIG_PROVENANCE=false npm publish

在你的 .npmrc 文件中:

¥In your .npmrc file:

provenance=false

在你的 package.json 中:

¥In your package.json:

{
"publishConfig": {
"provenance": false
}
}

安全最佳实践

¥Security best practices

优先使用可信发布而不是令牌

¥Prefer trusted publishing over tokens

当你的工作流程支持可信发布时,请始终优先选择它,而不是长期令牌。传统的 npm 令牌存在多种安全风险:

¥When trusted publishing is available for your workflow, always prefer it over long-lived tokens. Traditional npm tokens pose several security risks:

  • 它们可能会在 CI 日志或配置文件中意外暴露

    ¥They can be accidentally exposed in CI logs or configuration files

  • 它们需要手动轮换和管理

    ¥They require manual rotation and management

  • 如果遭到入侵,它们将提供持久访问权限,直至被撤销

    ¥If compromised, they provide persistent access until revoked

  • 它们通常具有比必要更广泛的权限

    ¥They often have broader permissions than necessary

可信发布通过使用短期有效、特定于工作流的凭据来消除这些风险,这些凭据会自动管理且无法提取。

¥Trusted publishing eliminates these risks by using short-lived, workflow-specific credentials that are automatically managed and cannot be extracted.

处理私有依赖

¥Handling private dependencies

虽然可信发布功能会处理发布操作,但你可能仍然需要身份验证才能安装私有 npm 依赖。对于这种情况,我们建议:

¥While trusted publishing handles the publish operation, you may still need authentication for installing private npm dependencies. For this scenario, we recommend:

# GitHub Actions example
- uses: actions/setup-node@v4
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org'
# Ensure npm 11.5.1 or later for trusted publishing
- run: npm install -g npm@latest
# Use a read-only token for installing dependencies
- run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_READ_TOKEN }}
# Publish uses OIDC - no token needed
- run: npm publish

始终使用 只读细粒度访问令牌 安装依赖。这可以限制令牌被盗用时的潜在损害。

¥Always use read-only granular access tokens for installing dependencies. This limits potential damage if the token is ever compromised.

其他安全措施

¥Additional security measures

请考虑实现以下额外的安全措施:

¥Consider implementing these additional security practices:

  • 使用 部署环境 添加审批要求

    ¥Use deployment environments to add approval requirements

  • 启用 标签保护规则 以控制谁可以创建发布标签

    ¥Enable tag protection rules to control who can create release tags

  • 定期审核你的可信发布者配置

    ¥Regularly audit your trusted publisher configurations

  • 从你的 npm 账户中移除所有未使用的发布令牌

    ¥Remove any unused publish tokens from your npm account

故障排除

¥Troubleshooting

如果你在发布时遇到 "无法验证" 错误,请首先验证工作流文件名是否与你在 npmjs.com 上配置的完全匹配,包括 .yml 扩展名。文件名区分大小写,并且必须完全一致。另请确保你使用的是 GitHub 托管的运行器或 GitLab.com 共享运行器,因为目前不支持自托管运行器。特别是对于 GitHub Actions,请检查你的工作流中是否设置了 id-token: write 权限。

¥If you encounter an "Unable to authenticate" error when publishing, first verify that the workflow filename matches exactly what you configured on npmjs.com, including the .yml extension. The filename is case-sensitive and must be exact. Also ensure you're using GitHub-hosted runners or GitLab.com shared runners, as self-hosted runners are not currently supported. For GitHub Actions specifically, check that the id-token: write permission is set in your workflow.

注意:保存时,npm 不会验证你的受信任发布者配置。请仔细检查你的存储库、工作流文件名和其他详细信息是否正确,因为只有在你尝试发布时才会出现错误。

¥Note: npm does not verify your trusted publisher configuration when you save it. Double-check that your repository, workflow filename, and other details are correct, as errors will only appear when you attempt to publish.

如果你的软件包包含私有依赖,并且 npm installnpm ci 因身份验证错误而失败,请记住,可信发布仅适用于 npm publish 命令。如上例所示,你仍然需要提供只读令牌来安装私有软件包。

¥If your package has private dependencies and npm install or npm ci is failing with authentication errors, remember that trusted publishing only applies to the npm publish command. You'll still need to provide a read-only token for installing private packages as shown in the examples above.

对于私有仓库中的软件包,即使你使用受信任的发布方式,也不会生成来源信息。无论你的软件包本身是公开的还是私有的,此 已知限制 都会生效。

¥For packages in private repositories, provenance will not be generated even though you're using trusted publishing. This is a known limitation that applies regardless of whether your package itself is public or private.

限制和未来改进

¥Limitations and future improvements

可信发布目前仅支持云托管运行器。自托管运行器的支持计划在未来版本中实现。每个包一次只能配置一个可信发布者,但你可以根据需要更新此配置。

¥Trusted publishing currently supports only cloud-hosted runners. Support for self-hosted runners is intended for a future release. Each package can only have one trusted publisher configured at a time, though you can update this configuration as needed.

OIDC 身份验证目前仅限于发布操作。其他 npm 命令(例如 installviewaccess)仍然需要传统的身份验证方法。npm whoami 命令不会反映 OIDC 身份验证状态,因为身份验证仅在发布操作期间发生。

¥OIDC authentication is currently limited to the publish operation. Other npm commands such as install, view, or access still require traditional authentication methods. The npm whoami command will not reflect OIDC authentication status since the authentication occurs only during the publish operation.

我们计划将可信发布支持扩展到更多 CI/CD 提供商,并根据社区反馈增强该功能。

¥We intend to expand trusted publishing support to additional CI/CD providers and enhance the feature based on community feedback.

了解更多

¥Learn more

npm v11.5 中文网 - 粤ICP备13048890号