From fb17026b09f36153a8126b624e79f3909d8a6c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:17:14 +0000 Subject: [PATCH] Release: publish only the npm versions that are missing The publish step now publishes each package version npm does not have yet and skips a version npm already serves with the same contents, so a release run that stopped half way can simply run again. A version npm serves with other contents fails the run with its name. Publishing keeps provenance through npm trusted publishing (OIDC), with no npm token in the repository. A manual run of the workflow now proves npm's trusted-publisher login without publishing anything (npm-trust-proof job); the release jobs run only on a tag. --- .github/scripts/npm-publish-new.mjs | 73 +++++++++++++++ .github/scripts/npm-trust-proof.mjs | 140 ++++++++++++++++++++++++++++ .github/workflows/release.yml | 32 ++++++- 3 files changed, 243 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/npm-publish-new.mjs create mode 100644 .github/scripts/npm-trust-proof.mjs diff --git a/.github/scripts/npm-publish-new.mjs b/.github/scripts/npm-publish-new.mjs new file mode 100644 index 0000000..b69c5a5 --- /dev/null +++ b/.github/scripts/npm-publish-new.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +// The publish step of the release workflow. +// +// npm refuses any version it already serves, so a plain `npm publish` (or `--workspaces`) fails the whole job on a +// retry after a partial publish and on a workspace that was not bumped. This publishes each public package version +// npm lacks, with provenance, and skips a version npm already serves with exactly the contents `npm pack` makes here +// (same integrity); the same version with other contents fails. Every package is tried, so a retry finishes the rest, +// and every failure is named. The skipped versions go to --out (already-published.json) and the step summary. +// +// Usage in the publish job (permissions: id-token: write; npm 11 for trusted publishing): +// node .github/scripts/npm-publish-new.mjs [--dir .] [--out already-published.json] +// It reads only public registry metadata; npm publish authenticates through the workflow's OIDC token. +import fs from 'node:fs'; +import path from 'node:path'; +import {spawnSync} from 'node:child_process'; +import {pathToFileURL} from 'node:url'; +import {publicPackages} from './npm-trust-proof.mjs'; + +const REGISTRY = 'https://registry.npmjs.org'; + +const run = (cmd, args, opts) => spawnSync(cmd, args, {...opts, encoding: 'utf8'}); + +export async function publishNew({dir = '.', fetchFn = fetch, exec = run, registry = REGISTRY, out = ''} = {}) { + const r = {published: [], skipped: [], failed: [], ok: true}; + for (const pkg of publicPackages(dir)) { + const id = `${pkg.name}@${pkg.version}`; + const cwd = path.join(dir, pkg.dir); + let res; + try { + res = await fetchFn(`${registry}/${pkg.name.replace('/', '%2f')}/${pkg.version}`); + } catch (e) { + r.failed.push(`${id}: npm could not be read (${e.message})`); + continue; + } + if (res.status === 200) { + const served = (await res.json())?.dist?.integrity || ''; + const packed = exec('npm', ['pack', '--dry-run', '--json'], {cwd}); + let mine = ''; + try { mine = JSON.parse(packed.stdout || '[]')[0]?.integrity || ''; } catch { mine = ''; } + if (packed.status === 0 && mine && mine === served) r.skipped.push(id); + else r.failed.push(`${id}: npm already has this version with other contents; raise the version`); + continue; + } + if (res.status !== 404) { + r.failed.push(`${id}: npm answered ${res.status}`); + continue; + } + const pub = exec('npm', ['publish', '--provenance', '--access', 'public'], {cwd}); + if (pub.status === 0) r.published.push(id); + else r.failed.push(`${id}: npm publish failed: ${String(pub.stderr || pub.stdout || '').trim().split('\n').slice(-3).join(' ')}`); + } + r.ok = r.failed.length === 0; + if (out) fs.writeFileSync(out, JSON.stringify(r.skipped) + '\n'); + return r; +} + +export function summary(r) { + const rows = [...r.published.map((p) => `| ${p} | published |`), ...r.skipped.map((p) => `| ${p} | already published, same contents |`), + ...r.failed.map((f) => `| ${f.split(': ')[0]} | ${f.split(': ').slice(1).join(': ')} |`)]; + return ['| package | result |', '|---|---|', ...rows].join('\n') + '\n'; +} + +const isMain = () => { + try { return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href; } catch { return false; } +}; + +if (isMain()) { + const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; + const r = await publishNew({dir: arg('--dir', '.'), out: arg('--out', 'already-published.json')}); + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary(r)); + console.log(JSON.stringify(r, null, 1)); + process.exit(r.ok ? 0 : 1); +} diff --git a/.github/scripts/npm-trust-proof.mjs b/.github/scripts/npm-trust-proof.mjs new file mode 100644 index 0000000..6bbc85d --- /dev/null +++ b/.github/scripts/npm-trust-proof.mjs @@ -0,0 +1,140 @@ +#!/usr/bin/env node +// Proves, without publishing, that npm trusts this workflow for every public package of the repo. +// +// npm binds a GitHub trusted publisher to owner, repository, workflow filename and an optional environment; the +// trigger event is not part of it (docs.npmjs.com/trusted-publishers). So a workflow_dispatch job inside the same +// release.yml asks GitHub for an OIDC id token with audience npm:registry.npmjs.org and posts it to npm's exchange +// endpoint, POST /-/npm/v1/oidc/token/exchange/package/, the same call npm publish makes first +// (npm 11.21.3 lib/utils/oidc.js). A 201 with a token means a publish from this workflow would authenticate; the +// token is a short-lived credential for that one package and is dropped at once, never printed or stored. +// Not proven by the exchange: the publisher's "allowed actions" (publish vs stage publish), checked at publish time; +// `npm trust list ` shows them. +// +// Usage on a runner (job permissions: id-token: write, contents: read): +// node npm-trust-proof.mjs [--dir .] [--out npm-trust-proof.json] +// Exit 0 only when every public package exchanged; the JSON and the step summary carry one row per package. +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const REGISTRY = 'https://registry.npmjs.org'; +const AUDIENCE = 'npm:registry.npmjs.org'; + +// the repo's public packages: the root, or every workspace whose package.json is not private +export function publicPackages(dir, read = (p) => JSON.parse(fs.readFileSync(p, 'utf8')), list = fs.readdirSync) { + const root = read(path.join(dir, 'package.json')); + const patterns = Array.isArray(root.workspaces) ? root.workspaces : root.workspaces?.packages || []; + const dirs = []; + for (const pat of patterns) { + if (pat.endsWith('/*')) { + const base = path.join(dir, pat.slice(0, -2)); + let names = []; + try { names = list(base); } catch { names = []; } + for (const n of names.sort()) dirs.push(path.join(base, n)); + } else dirs.push(path.join(dir, pat)); + } + const out = []; + for (const d of patterns.length ? dirs : [dir]) { + let pkg; + try { pkg = read(path.join(d, 'package.json')); } catch { continue; } + if (pkg.private === true || !pkg.name || !pkg.version) continue; + const repo = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url || ''; + out.push({ name: pkg.name, version: pkg.version, dir: path.relative(dir, d) || '.', repository: repo }); + } + return out; +} + +// GitHub's OIDC id token for npm's audience; the request token and the id token are never printed +export async function idToken(env = process.env, fetchFn = fetch) { + if (!env.ACTIONS_ID_TOKEN_REQUEST_URL || !env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) + throw new Error('no OIDC request token: the job needs permissions id-token: write'); + const url = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL); + url.searchParams.append('audience', AUDIENCE); + const r = await fetchFn(url.href, { headers: { Accept: 'application/json', Authorization: `Bearer ${env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` } }); + if (!r.ok) throw new Error(`GitHub refused the OIDC id token request (${r.status})`); + const body = await r.json(); + if (typeof body?.value !== 'string' || !body.value) throw new Error('GitHub returned no OIDC id token'); + return body.value; +} + +const WHY = { + 400: 'npm refused the id token as malformed', + 401: 'npm did not accept the id token (audience or signature)', + 403: 'npm has no trusted publisher for this owner, repository, workflow file or environment', + 404: 'no trusted publisher on npm for this package, or its configuration expired unvalidated (2 days), or the package does not exist yet', +}; + +// one package: the exchange (201 + token = trusted) and whether this version is still free on npm +// npm's provenance refuses a publish whose package.json repository.url is not the GitHub repository it runs in +export function repoMatches(url, ghRepo) { + if (!ghRepo) return true; + const m = String(url || '').match(/github\.com[/:]([^/]+\/[^/#]+?)(?:\.git)?(?:[#/].*)?$/i) || String(url || '').match(/^github:([^/]+\/[^/#]+)$/i); + return Boolean(m) && m[1].toLowerCase() === ghRepo.toLowerCase(); +} + +export async function provePackage(pkg, token, fetchFn = fetch, registry = REGISTRY) { + const name = encodeURIComponent(pkg.name).replace(/^%40/, '@'); + let status = 0, trusted = false, why = ''; + try { + const r = await fetchFn(`${registry}/-/npm/v1/oidc/token/exchange/package/${name}`, { + method: 'POST', headers: { Accept: 'application/json', Authorization: `Bearer ${token}` } }); + status = r.status; + let body = {}; + try { body = await r.json(); } catch { body = {}; } + trusted = r.ok && typeof body?.token === 'string' && body.token.length > 0; + // the exchanged token is a live credential: nothing keeps or prints it + body = null; + if (!trusted) why = WHY[status] || (r.ok ? 'npm answered without a token' : `npm answered ${status}`); + } catch (e) { + why = `exchange request failed: ${e?.cause?.code || e?.name || 'network error'}`; + } + let versionFree = null; + try { + const v = await fetchFn(`${registry}/${name}/${encodeURIComponent(pkg.version)}`, { headers: { Accept: 'application/json' } }); + versionFree = v.status === 404 ? true : v.ok ? false : null; + } catch { versionFree = null; } + return { name: pkg.name, version: pkg.version, dir: pkg.dir, trusted, status, why, version_free: versionFree }; +} + +export async function prove({ dir = '.', env = process.env, fetchFn = fetch } = {}) { + const pkgs = publicPackages(dir); + const result = { + at: new Date().toISOString(), + repository: env.GITHUB_REPOSITORY || '', workflow_ref: env.GITHUB_WORKFLOW_REF || '', sha: env.GITHUB_SHA || '', + event: env.GITHUB_EVENT_NAME || '', packages: [], ok: false, + }; + if (!pkgs.length) { result.why = 'no public package found'; return result; } + let token; + try { token = await idToken(env, fetchFn); } catch (e) { result.why = e.message; return result; } + for (const p of pkgs) { + const row = await provePackage(p, token, fetchFn); + row.repository_matches = repoMatches(p.repository, env.GITHUB_REPOSITORY); + if (!row.repository_matches) { + row.why = [row.why, `repository.url ${p.repository ? `"${p.repository}"` : 'missing'} is not github.com/${env.GITHUB_REPOSITORY}: provenance refuses the publish`].filter(Boolean).join('; '); + } + result.packages.push(row); + } + token = null; + result.ok = result.packages.every((p) => p.trusted && p.repository_matches); + return result; +} + +export function summary(r) { + const rows = r.packages.map((p) => `| ${p.name} | ${p.version} | ${p.trusted ? 'trusted' : 'NOT trusted'} | ${p.version_free === true ? 'free' : p.version_free === false ? 'already published' : 'unknown'} | ${p.why || ''} |`); + return [`### npm trust proof: ${r.ok ? 'every package trusted' : 'not proven'}`, r.why ? `\n${r.why}\n` : '', + '| package | version | exchange | version on npm | why |', '|---|---|---|---|---|', ...rows, ''].join('\n'); +} + +// run as a script (also from a path with spaces or through a symlink), not when imported by a test +export const isMain = (argv1 = process.argv[1]) => { + try { return Boolean(argv1) && import.meta.url === pathToFileURL(fs.realpathSync(argv1)).href; } catch { return false; } +}; + +if (isMain()) { + const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; + const r = await prove({ dir: arg('--dir', '.') }); + fs.writeFileSync(arg('--out', 'npm-trust-proof.json'), JSON.stringify(r, null, 2) + '\n'); + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary(r)); + console.log(summary(r)); + process.exit(r.ok ? 0 : 1); +} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 37ec2fa..ee7e979 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,12 +8,36 @@ on: push: tags: - 'v*' + # Proof only, no publish: npm trusts this workflow file whatever its trigger, so a manual run exchanges the + # job's OIDC token and says whether npm would take the publish (.github/scripts/npm-trust-proof.mjs). + workflow_dispatch: permissions: contents: read jobs: + npm-trust-proof: + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + id-token: write # the OIDC token npm exchanges; nothing is published + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + - name: Exchange the OIDC token with npm for the package + run: node .github/scripts/npm-trust-proof.mjs --out npm-trust-proof.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: npm-trust-proof + path: npm-trust-proof.json + portable-native: + if: github.event_name == 'push' strategy: fail-fast: false matrix: @@ -57,6 +81,7 @@ jobs: if-no-files-found: error release: + if: github.event_name == 'push' needs: portable-native runs-on: ubuntu-latest permissions: @@ -116,8 +141,11 @@ jobs: exit 1 fi - - name: Publish to npm with provenance - run: npm publish --provenance --access public + - name: npm publish of each version npm lacks; one npm already serves with the same contents is skipped + id: already-published + env: + NPM_CONFIG_PROVENANCE: true + run: node .github/scripts/npm-publish-new.mjs --dir . --out already-published.json - name: Create GitHub Release uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4