diff --git a/.github/projections/self-topology/releases.mjs b/.github/projections/self-topology/releases.mjs index d11e44aea..f5b321ae1 100644 --- a/.github/projections/self-topology/releases.mjs +++ b/.github/projections/self-topology/releases.mjs @@ -13,8 +13,15 @@ // revision, which can't see that configuration, so it publishes nothing here: an npm job that waits for approval is // no npm release. Turning publishing on in the workflow (an unconditional step, a dist `publish-jobs` entry) shows it. +// npm options that take a value, which may follow them after a space (`npm -w sdk publish`). Any other option before +// `publish` is a flag or carries its value after `=`, so `npm --silent run publish` isn't read as a publish. +const npmValueOptions = '--workspace|-w|--registry|--tag|--access|--otp|--userconfig|--prefix|-C|--cache|--loglevel' const registries = [ - {pattern: /\bnpm\s+publish\b(.*)$/u, registry: 'npm', option: /(?:--workspace|-w)[ =](\S+)/u}, + { + pattern: new RegExp(`\\bnpm\\s+((?:(?:(?:${npmValueOptions})\\s+[^-\\s]\\S*|-[\\w-]+(?:=\\S*)?)\\s+)*publish\\b.*)$`, 'u'), + registry: 'npm', + option: /(?:--workspace|-w)[ =](\S+)/u, + }, {pattern: /\b(?:@vscode\/)?vsce\s+publish\b(.*)$/u, registry: 'Marketplace', option: /(?:--packagePath|-i)[ =](\S+)/u, vscode: true}, {pattern: /\bovsx\s+publish\b(.*)$/u, registry: 'Open VSX', option: /(?:--packagePath|-i)[ =](\S+)/u, vscode: true}, {pattern: /\bcargo\s+publish\b(.*)$/u, registry: 'crates.io', option: /(?:--package|-p)[ =](\S+)/u, crate: true}, diff --git a/.github/projections/self-topology/releases.test.mjs b/.github/projections/self-topology/releases.test.mjs index 89de1c35f..039312893 100644 --- a/.github/projections/self-topology/releases.test.mjs +++ b/.github/projections/self-topology/releases.test.mjs @@ -52,6 +52,27 @@ ${condition} steps: assert.deepEqual(channels({'.github/workflows/publish.yml': publish()}), {'npm:sdk': ['npm'], 'npm:ext': ['Marketplace']}) }) +test('npm options before publish, the workspace among them, still publish the workspace', () => { + const publish = `jobs: + publish: + steps: + - run: npm --ignore-scripts --registry=https://registry.npmjs.org/ publish --workspace sdk +` + assert.deepEqual(channels({'.github/workflows/publish.yml': publish}), {'npm:sdk': ['npm']}) + const before = 'jobs:\n publish:\n steps:\n - run: npm --ignore-scripts --workspace=sdk publish\n' + assert.deepEqual(channels({'.github/workflows/publish.yml': before}), {'npm:sdk': ['npm']}) + for (const command of [ + 'npm --workspace sdk publish', + 'npm -w sdk publish', + 'npm --registry https://registry.npmjs.org/ publish --workspace sdk', + ]) { + const spaced = `jobs:\n publish:\n steps:\n - run: ${command}\n` + assert.deepEqual(channels({'.github/workflows/publish.yml': spaced}), {'npm:sdk': ['npm']}, command) + } + const script = 'jobs:\n publish:\n steps:\n - run: npm --silent -w sdk run publish\n' + assert.deepEqual(channels({'.github/workflows/publish.yml': script}), {}) +}) + test('a TOML list is found by its literal key', () => { const text = 'a.b = ["dot"]\naxb = ["any"]\npublish-jobs = ["./npm", \'homebrew\']\n' assert.deepEqual(tomlList(text, 'a.b'), ['dot']) diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index c40b39827..e56c34c9a 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -4,6 +4,10 @@ name: Publish npm package # CLI's: a release whose tag, Cargo.toml and packages/sdk/package.json disagree publishes nothing. Run it by hand to publish # a release again; a version already on npm is left as it is. # +# Every publish runs as this workflow, started by workflow_dispatch. npm's trusted publishing checks the workflow that +# started the run, so when release.yml calls this one it would check release.yml instead. The release therefore +# dispatches this workflow at its tag rather than publishing itself, and npm trusts a single workflow: publish-npm.yml. +# # Inert until configured: until the NPM_PUBLISHING repository variable says how it authenticates (trusted publishing, # or an NPM_TOKEN secret in the npm environment), it only says so. npm publishing awaits security approval, so it stays # unconfigured; meanwhile every release attaches the packed package, which renderers depend on by URL (release-proof.yml). @@ -48,9 +52,29 @@ jobs: exit 1 ;; esac + # Called by the release: start this workflow at the release's tag, so the publish runs as publish-npm.yml. Workflow + # runs that GITHUB_TOKEN starts by workflow_dispatch are allowed, unlike its other events. + dispatch: + needs: configured + if: needs.configured.outputs.ready == 'true' && inputs.plan != '' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: write + steps: + - shell: bash + env: + GH_TOKEN: ${{ github.token }} + PLAN: ${{ inputs.plan }} + REPOSITORY: ${{ github.repository }} + run: | + set -euo pipefail + TAG=$(jq -r '.announcement_tag' <<< "$PLAN") + gh workflow run publish-npm.yml --repo "$REPOSITORY" --ref "$TAG" -f tag="$TAG" + echo "::notice title=npm publish started::Publish npm package is publishing $TAG in its own run." publish: needs: configured - if: needs.configured.outputs.ready == 'true' + if: needs.configured.outputs.ready == 'true' && inputs.tag != '' runs-on: ubuntu-24.04 timeout-minutes: 20 # npm trusts this repository, workflow and environment (trusted publishing), or the environment holds NPM_TOKEN. @@ -66,10 +90,8 @@ jobs: - id: release shell: bash env: - PLAN: ${{ inputs.plan }} TAG: ${{ inputs.tag }} run: | - if [ -z "$TAG" ]; then TAG=$(jq -r '.announcement_tag' <<< "$PLAN"); fi if ! [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then echo "::error title=Not a release tag::$TAG is not a release tag such as v0.2.0." exit 1 @@ -83,7 +105,8 @@ jobs: - uses: actions/setup-node@v6.5.0 with: node-version-file: .node-version - registry-url: https://registry.npmjs.org + # No registry-url: setup-node would then write an .npmrc that authenticates with NODE_AUTH_TOKEN. Trusted + # publishing needs no token, and token publishing configures its own below. - name: Check the version shell: bash env: @@ -93,8 +116,12 @@ jobs: npm ci --ignore-scripts --no-audit --no-fund # Every shipped manifest carries the release's version (docs/maintainers/releasing.md). npm run --silent tools -- version --tag "$TAG" - # Trusted publishing needs npm 11.5.1 or later. - npm --version + # Trusted publishing needs npm 11.5.1 or later, which the Node in .node-version ships. + npm_version=$(npm --version) + if [ "$(printf '%s\n' 11.5.1 "$npm_version" | sort -V | head -n 1)" != 11.5.1 ]; then + echo "::error title=npm too old::Trusted publishing needs npm 11.5.1 or later, but this Node ships npm $npm_version." + exit 1 + fi - name: Build and check the package shell: bash run: | @@ -102,28 +129,53 @@ jobs: npm run build --workspace "$workspace" done node packages/sdk/scripts/check-pack.mjs --contents - - name: Publish + - id: prepare + name: Prepare the publish shell: bash env: VERSION: ${{ steps.release.outputs.version }} METHOD: ${{ vars.NPM_PUBLISHING }} - # Unused with trusted publishing, which needs no token. - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + # Whether the secret is set, not the secret: only the token publish step sees NPM_TOKEN. + HAS_TOKEN: ${{ secrets.NPM_TOKEN != '' }} run: | set -euo pipefail - if [ "$METHOD" = token ] && [ -z "$NODE_AUTH_TOKEN" ]; then + if [ "$METHOD" = token ] && [ "$HAS_TOKEN" != true ]; then echo "::error title=No npm token::NPM_PUBLISHING is token, but the npm environment has no NPM_TOKEN secret." exit 1 fi - registry=https://registry.npmjs.org/ - if npm view "@githubnext/projections-sdk@$VERSION" version --registry "$registry" > /dev/null 2>&1; then + if npm view "@githubnext/projections-sdk@$VERSION" version --registry https://registry.npmjs.org/ > /dev/null 2>&1; then echo "::notice title=Already published::@githubnext/projections-sdk@$VERSION is already on npm; versions are immutable." exit 0 fi # A prerelease such as 0.3.0-beta.1 is published under the next tag, so latest stays the latest stable. - tag=latest - if [[ "$VERSION" == *-* ]]; then tag=next; fi + dist_tag=latest + if [[ "$VERSION" == *-* ]]; then dist_tag=next; fi + echo "dist-tag=$dist_tag" >> "$GITHUB_OUTPUT" # npm uploads package.json as the version's registry metadata too, so it is the published manifest on disk # (without the internal workspaces it is built from) before publishing starts. node packages/sdk/scripts/manifest.mjs strip - npm publish --workspace packages/sdk --registry "$registry" --access public --provenance --tag "$tag" + echo publish=true >> "$GITHUB_OUTPUT" + # The package was built above; --ignore-scripts keeps npm from running lifecycle scripts while it holds the + # credential. + - name: Publish with trusted publishing + if: steps.prepare.outputs.publish == 'true' && vars.NPM_PUBLISHING == 'trusted' + shell: bash + # No NODE_AUTH_TOKEN: npm exchanges the job's OIDC token for a short-lived one that can publish only this package. + env: + DIST_TAG: ${{ steps.prepare.outputs.dist-tag }} + run: >- + npm --ignore-scripts publish --workspace packages/sdk --registry https://registry.npmjs.org/ --access public + --provenance --tag "$DIST_TAG" + - name: Publish with a token + if: steps.prepare.outputs.publish == 'true' && vars.NPM_PUBLISHING == 'token' + shell: bash + env: + DIST_TAG: ${{ steps.prepare.outputs.dist-tag }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + set -euo pipefail + # npm expands ${NODE_AUTH_TOKEN} itself, so the token is never written to disk. + # shellcheck disable=SC2016 + printf '%s\n' '//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}' > "$RUNNER_TEMP/.npmrc" + NPM_CONFIG_USERCONFIG="$RUNNER_TEMP/.npmrc" npm --ignore-scripts publish --workspace packages/sdk \ + --registry https://registry.npmjs.org/ --access public --provenance --tag "$DIST_TAG" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 42524b91d..d3f1d2107 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -391,6 +391,7 @@ jobs: plan: ${{ needs.plan.outputs.val }} secrets: inherit permissions: + "actions": "write" "contents": "read" "id-token": "write" diff --git a/dist-workspace.toml b/dist-workspace.toml index afe1b10b5..a2f232515 100644 --- a/dist-workspace.toml +++ b/dist-workspace.toml @@ -45,10 +45,11 @@ global-artifacts-jobs = ["./release-proof"] publish-jobs = ["./release-approval"] # Once the release is announced, its JSON Schemas are published to the schemas host # (publish-schemas.yml, docs/maintainers/schema-publishing.md) and @githubnext/projections-sdk to npm -# (publish-npm.yml, docs/maintainers/npm-publishing.md; inert until npm publishing is approved), and a stable +# (publish-npm.yml, docs/maintainers/npm-publishing.md; inert until npm publishing is approved, then it dispatches +# itself, hence actions: write, so npm's trusted publishing sees publish-npm.yml), and a stable # release moves its major version tag, v0, which `uses: githubnext/projections@v0` follows (move-major-tag.yml). post-announce-jobs = ["./publish-schemas", "./publish-npm", "./move-major-tag"] -github-custom-job-permissions = { "release-proof" = { contents = "read" }, "release-approval" = { actions = "read", attestations = "write", id-token = "write" }, "publish-schemas" = { contents = "read", id-token = "write" }, "publish-npm" = { contents = "read", id-token = "write" }, "move-major-tag" = { contents = "read" } } +github-custom-job-permissions = { "release-proof" = { contents = "read" }, "release-approval" = { actions = "read", attestations = "write", id-token = "write" }, "publish-schemas" = { contents = "read", id-token = "write" }, "publish-npm" = { actions = "write", contents = "read", id-token = "write" }, "move-major-tag" = { contents = "read" } } [dist.github-custom-runners] global = "ubuntu-24.04" diff --git a/docs/maintainers/npm-publishing.md b/docs/maintainers/npm-publishing.md index e7bb9ba7e..7ed02fdfd 100644 --- a/docs/maintainers/npm-publishing.md +++ b/docs/maintainers/npm-publishing.md @@ -24,9 +24,12 @@ the only one we publish. `.github/workflows/publish-npm.yml` runs as a dist post-announce job (listed under `post-announce-jobs` in `dist-workspace.toml`), meaning it only fires after the release workflow announces a release — the npm package never goes live -before the CLI release exists. You can also trigger it manually from the Actions -tab by picking the release tag under **Use workflow from** and passing that same -tag as `tag`. +before the CLI release exists. The release workflow doesn't publish to npm +itself; it starts a separate **Publish npm package** run at the release tag so +npm only has to trust one workflow (see +[Why one workflow publishes](#why-one-workflow-publishes)). You can also run it +manually from the Actions tab by picking the release tag under **Use workflow +from** and passing that same tag as `tag`. The workflow runs three steps: @@ -50,44 +53,114 @@ The workflow runs three steps: safe. Right before publishing, `node packages/sdk/scripts/manifest.mjs strip` strips devDependencies (the internal workspaces used to build the package) from `packages/sdk/package.json`, since npm stores that manifest as registry - metadata as well as inside the tarball. + metadata as well as inside the tarball. The job calls + `npm --ignore-scripts publish` so lifecycle scripts won't run while npm holds + a credential. The package has no `prepack` or `prepublishOnly` script, and + the previous step already built it. With trusted publishing, the job leaves + `NODE_AUTH_TOKEN` unset and doesn't write a token line to `.npmrc`, so npm + authenticates using only the job's OIDC token. The Node version from + `.node-version` ships npm 11.5.1 or later (required for trusted publishing), + and the job fails if it doesn't. Until publishing is configured, the job simply logs a notice and exits cleanly. +## Why one workflow publishes + +When one workflow calls another with `workflow_call`, npm's trusted publishing +checks the name of the workflow that started the run, not the one that runs +`npm publish` +([npm's trusted publishing guide](https://docs.npmjs.com/trusted-publishers#troubleshooting)). +If the release workflow published directly, npm would see `release.yml` on +releases and `publish-npm.yml` on manual runs, which would mean registering two +trusted publishers. Unvalidated trusted publisher configurations expire after 48 +hours unless they publish something +([changelog](https://github.blog/changelog/2026-10-02-unvalidated-npm-trusted-publishing-configurations-now-expire/)), +so a `release.yml` registration could only be validated by cutting a release +within those two days. + +To avoid that, the release workflow dispatches `publish-npm.yml` at the release +tag with `workflow_dispatch` (unlike most events, a dispatch sent with +`GITHUB_TOKEN` starts a new run) rather than publishing in its own run. Every +publish, automatic or manual, then runs as `publish-npm.yml`. npm only has to +trust that one workflow, and a manual run validates it. To send that dispatch, +the release workflow's call needs `actions: write` +(`github-custom-job-permissions` in `dist-workspace.toml`). + ## Set up -1. **Reserve the package name.** Publishing requires access to the `@githubnext` - scope on npm with an account or team permitted to publish - `@githubnext/projections-sdk`. The first publish creates the package. If you - plan to use trusted publishing, someone with publish rights (or a scope - owner) must publish the initial version manually from a release checkout - first: run `npm run build`, then - `node packages/sdk/scripts/manifest.mjs strip`, then - `npm publish --workspace packages/sdk --access public`, and restore the file - with `git checkout packages/sdk/package.json`. After that, configure the - steps below. -2. **Create a GitHub environment named `npm`** under Settings → Environments. +Wait until npm publishing is approved before doing these steps. You need publish +rights in the `@githubnext` npm scope. + +1. **Publish a placeholder version.** npm only lets you configure trusted + publishing for packages that already exist, so start by publishing a minimal + stub from an empty directory. npm will prompt for your two-factor code, and + because the scope is org-owned, the first publish needs `--access public`: + + ```sh + mkdir projections-npm-stub && cd projections-npm-stub + cat > package.json <<'EOF' + { + "name": "@githubnext/projections-sdk", + "version": "0.0.0", + "description": "Placeholder that reserves the name. Install a release version instead.", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/githubnext/projections.git", + "directory": "packages/sdk" + } + } + EOF + npm publish --access public + npm deprecate @githubnext/projections-sdk@0.0.0 "Placeholder. Install a release version instead." + ``` + + The first real publish will become `latest`. + +2. **Set the package's publishing access.** On npmjs.com, go to the package's + **Settings → Publishing access**, select **Require two-factor authentication + or a granular access token with bypass 2FA enabled** (npm's default; older + pages call it "or automation tokens"), and save. Once the first trusted + publish succeeds, you can switch to **Require two-factor authentication and + disallow tokens** if you only plan to use trusted publishing. That setting + doesn't affect trusted publishing, but it rules out the token method below. +3. **Create a GitHub environment named `npm`** under Settings → Environments. Limit deployments to release tags (deployment branches and tags: `v*`), and optionally add required reviewers if you want manual sign-off before each publish. -3. **Configure credentials** using one of two methods: - - **Trusted publishing (recommended).** On npmjs.com, go to the package's - **Settings → Trusted publishing** and add two GitHub Actions publishers (up - to 10 are allowed), both pointing to this repository's owner, name, and the - `npm` environment: one for `release.yml` (automated post-release runs) and - one for `publish-npm.yml` (manual runs). Because npm matches whichever - workflow started the run and doesn't validate filenames on save, double - check the spelling. Make sure `repository` in `packages/sdk/package.json` - names this repository, then set the repository variable `NPM_PUBLISHING` to - `trusted` (Settings → Secrets and variables → Actions → Variables). No - token is stored. Once a publish succeeds, lock down the package's - publishing access to require two-factor authentication and disallow tokens. - - **Granular access token.** Create a token on npmjs.com scoped to read and - write `@githubnext/projections-sdk` only, store it as the `NPM_TOKEN` - secret in the `npm` environment, and set the repository variable - `NPM_PUBLISHING` to `token` (the variable is needed because the gating job - can't read environment secrets). Remember to rotate the token before it - expires. +4. **Register the trusted publisher.** On npmjs.com, go to the package's + **Settings → Trusted publishing** and add a GitHub Actions publisher with + these exact, case-sensitive values: + - Organization or user: `githubnext` + - Repository: `projections` + - Workflow filename: `publish-npm.yml` (not `release.yml`; see + [Why one workflow publishes](#why-one-workflow-publishes)) + - Environment name: `npm` + - Allowed actions: include `npm publish`. npm allows staged publishing + (`npm stage publish`) by default, but direct publishing is opt-in, and the + workflow publishes directly. + + npm doesn't check these values when you save them, so double-check the + spelling. Also check that `repository` in `packages/sdk/package.json` still + points to this repository, since npm compares them. + +5. **Turn the workflow on.** Set the repository variable `NPM_PUBLISHING` to + `trusted` (Settings → Secrets and variables → Actions → Variables). No token + is stored. +6. **Publish the current release within 48 hours.** From the Actions tab, run + **Publish npm package**, choose the current release tag under **Use workflow + from**, and enter that tag as `tag`. That first successful publish validates + the trusted publisher. If you don't publish in time, the registration expires + and you'll have to recreate it. Future releases publish on their own. + +### Token publishing instead + +If trusted publishing isn't an option, create a granular access token on +npmjs.com with read and write access to `@githubnext/projections-sdk` only. +Store it as the `NPM_TOKEN` secret in the `npm` environment, and set +`NPM_PUBLISHING` to `token` because the gating job can't read environment +secrets. Only the token publish step sees the token. Remember to rotate it +before it expires. Provenance ties every published version back to this repository, the exact release workflow run, and the commit it was built from, and displays a badge on diff --git a/packages/cli/test/release.test.mjs b/packages/cli/test/release.test.mjs index c980c033c..397f97cbb 100644 --- a/packages/cli/test/release.test.mjs +++ b/packages/cli/test/release.test.mjs @@ -100,10 +100,14 @@ test('the generated workflow pins every action and announces only after every pr assert.deepEqual(release.jobs['custom-release-proof'].permissions, {contents: 'read'}) // dist attests the CLI archives as it builds them, so its build jobs' token is read-only. assert.deepEqual(release.jobs['build-local-artifacts'].permissions, {attestations: 'write', contents: 'read', 'id-token': 'write'}) - // The JSON Schemas and the npm package are published only once the release is announced. - for (const job of ['custom-publish-schemas', 'custom-publish-npm']) { + // The JSON Schemas and the npm package are published only once the release is announced. The npm job dispatches + // publish-npm.yml at the release's tag, so npm's trusted publishing sees that workflow rather than release.yml. + for (const [job, permissions] of [ + ['custom-publish-schemas', {contents: 'read', 'id-token': 'write'}], + ['custom-publish-npm', {actions: 'write', contents: 'read', 'id-token': 'write'}], + ]) { assert.deepEqual(release.jobs[job].needs, ['plan', 'announce'], job) - assert.deepEqual(release.jobs[job].permissions, {contents: 'read', 'id-token': 'write'}, job) + assert.deepEqual(release.jobs[job].permissions, permissions, job) } // The major version tag moves after the release is announced, with a deploy key rather than the workflow's token. assert.deepEqual(release.jobs['custom-move-major-tag'].needs, ['plan', 'announce'])