diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..08c614b --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,46 @@ +name: CodeQL + +on: + push: + branches: + - main + pull_request: + branches: + - main + schedule: + - cron: "31 7 * * 1" + +permissions: + contents: read + security-events: write + +concurrency: + group: codeql-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + analyze: + name: Analyze JavaScript and TypeScript + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 + with: + languages: javascript-typescript + + - name: Build + uses: github/codeql-action/autobuild@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 + + - name: Analyze + uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 79f8ffc..fd87d3c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,65 +1,64 @@ -# Publishes every public workspace package to npm. -# -# Runs when a GitHub release is published, so the tag, the release notes, and -# the published version are one action rather than three. -# -# AUTHENTICATION -# -# This package is configured on npmjs.com to accept publishes only from a -# trusted publisher: this repository, this workflow file. Authentication is a -# short-lived OIDC token minted per run, so there is no long-lived credential -# to leak, rotate, or forget to delete. `--provenance` additionally attaches a -# signed attestation tying the tarball to the commit that built it. -# -# There is deliberately no token fallback. If OIDC fails, the publish should -# fail loudly rather than quietly reaching for a secret. -# -# Bootstrapping a NEW package is the one case this cannot cover: npm will not -# let you configure a trusted publisher for a package that does not exist yet -# (https://github.com/npm/cli/issues/8544). Publish version 0.1.0 once from a -# workstation with `npm publish -w `, add the trusted publisher on -# npmjs.com, and every release after that runs here. +# Publishes the exact tarball prepared from a stable GitHub release tag. +# Authentication is npm trusted-publisher OIDC only; no token fallback exists. name: Publish on: release: types: [published] - workflow_dispatch: permissions: contents: read - id-token: write # OIDC: trusted publishing and provenance attestation concurrency: - group: publish-${{ github.ref }} + group: npm-publish cancel-in-progress: false jobs: - publish: + prepare: runs-on: ubuntu-latest + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out repository + - name: Check out the release tag uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: refs/tags/${{ github.event.release.tag_name }} + fetch-depth: 0 + + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main + + - name: Configure approved release signers + shell: bash + run: | + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + git config --local gpg.format ssh + git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: - node-version: 24 - cache: npm + node-version: 24.18.0 registry-url: https://registry.npmjs.org + package-manager-cache: false - # Trusted publishing needs npm 11.5.1 or newer, which is ahead of what - # some Node images bundle. - - name: Use a current npm - run: npm install -g npm@latest + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 - name: Install dependencies run: npm ci - # Publishing runs the same gate as CI. A release should never ship - # something that would have failed a pull request. - name: Check formatting run: npm run format:check @@ -69,5 +68,53 @@ jobs: - name: Run tests run: npm test - - name: Publish - run: npm publish --workspaces --provenance + - name: Prepare and verify the release tarball + run: npm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + + - name: Upload the prepared release + id: upload + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: spine-release-${{ github.run_id }} + path: .release/ + if-no-files-found: error + include-hidden-files: true + overwrite: true + retention-days: 30 + + - name: Record the prepared artifact digest + run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + + publish: + needs: prepare + runs-on: ubuntu-latest + environment: npm-publish + permissions: + contents: read + id-token: write + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_COMMIT: ${{ github.sha }} + + steps: + - name: Check out the exact release tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: refs/tags/${{ github.event.release.tag_name }} + fetch-depth: 1 + + - name: Set up Node.js and the npm registry + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + registry-url: https://registry.npmjs.org + package-manager-cache: false + + - name: Download the prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: spine-release-${{ github.run_id }} + path: .release + + - name: Publish the verified prepared tarball + run: npm run release:publish -- -- --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json diff --git a/.gitignore b/.gitignore index 95b2c34..91d1257 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ dist/ coverage/ +.release/ *.tsbuildinfo .env diff --git a/AGENTS.md b/AGENTS.md index edb3a12..782eca3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,9 +55,11 @@ exclude `src/**/*.test.ts`, or compiled tests are published to consumers. Work on a `claude/*` branch and open a pull request. The gate is `npm run format:check`, `npm run check`, `npm test` — all three, on Node 22 and 24. -Publishing is trusted-publisher only; no tokens exist. A release is -`gh release create vX.Y.Z`, which runs the gate and publishes with a provenance -attestation. +Publishing is trusted-publisher only; no tokens exist. A release starts from a +protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by +`gh release create vX.Y.Z --verify-tag`. The unprivileged preparation job runs +the gate and packs the exact artifact; only the minimal publish job receives +OIDC authority. See `docs/RELEASING.md`. ## Where things stand diff --git a/README.md b/README.md index 2a425f0..9a7d3f2 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,9 @@ npm test npm run format:check ``` +Maintainers should follow [the release runbook](docs/RELEASING.md). Releases +publish only from protected signed tags through npm trusted publishing. + ## License [MIT](LICENSE) © 2026 RetireGolden, LLC diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..68c2f28 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,64 @@ +# Release operations + +`@pegma/spine` publishes only from a stable GitHub release. Merging a pull +request never publishes, and the workflow has no manual-dispatch or npm-token +fallback. + +## Required external configuration + +Before the first release through this workflow: + +- configure `@pegma/spine` on npm with the GitHub Actions trusted publisher + `pegma-dev/spine`, workflow `publish.yml`, environment `npm-publish`, and + allowed action `npm publish`; +- create the GitHub `npm-publish` environment. A second reviewer is not + required under Pegma's single-maintainer policy; +- create the repository Actions variable `RELEASE_ALLOWED_SIGNERS` containing + the reviewed Git SSH allowed-signers entry for the maintainer's release key; + this is public-key material, not a secret; and +- create an active tag ruleset targeting `v*` that prevents tag updates and + deletions and limits tag creation to the release maintainer. + +Do not add `NODE_AUTH_TOKEN`, an npm automation token, or another credential +fallback. After one trusted-publisher release is verified, disable any +remaining traditional npm publish tokens. + +## Release procedure + +The version in `packages/spine/package.json` is the release version. Change it +through an ordinary reviewed pull request and run the complete gate on Node 22 +and 24. + +After that pull request is merged, create a signed annotated tag at the exact +`origin/main` commit, push the tag, verify the fetched tag, and only then +create the GitHub release with `--verify-tag`. Do not let GitHub create the tag +and never move or recreate a release tag. + +The release workflow verifies that the tag: + +- is a stable annotated `vX.Y.Z` tag signed by an allowed signer; +- matches the package version; +- points to the checkout and the GitHub release-event commit; and +- is contained in `origin/main`. + +Its preparation job has no OIDC permission. It installs the reviewed npm +version without dependency caching, runs the full gate, builds and packs once, +smoke-tests the tarball from a clean consumer, records its SHA-1 and SHA-512 +integrity, and uploads the exact prepared artifact. + +Only the `npm-publish` job receives `id-token: write`. It installs no +dependencies, verifies the prepared manifest and tarball hashes against the +release commit, and publishes that tarball with npm provenance. + +## Safe retry + +The workflow is globally serialized. Re-run the failed release jobs against +the unchanged tag: + +- an absent version is published; +- an existing version with identical `dist.integrity` is verified and skipped; +- a different integrity, or any registry error other than `E404`, stops the + release. + +Never unpublish and reuse a version. If any released byte must change, prepare +a new version and a new signed tag. diff --git a/package-lock.json b/package-lock.json index ded977b..59837ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1714,7 +1714,7 @@ }, "packages/spine": { "name": "@pegma/spine", - "version": "0.0.0", + "version": "0.1.1", "license": "MIT", "engines": { "node": ">=22" diff --git a/package.json b/package.json index f40c7e4..c552c52 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "description": "Shared identity, time, logging, and event contracts for the Pegma component ecosystem.", "license": "MIT", "type": "module", + "packageManager": "npm@11.18.0", "engines": { "node": ">=22" }, @@ -17,6 +18,9 @@ "clean": "tsc -b --clean", "format": "prettier --write .", "format:check": "prettier --check .", + "release:check": "node scripts/release-packages.mjs check", + "release:pack": "node scripts/release-packages.mjs pack", + "release:publish": "node scripts/release-packages.mjs publish", "test": "npm run build && vitest run" }, "devDependencies": { diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts new file mode 100644 index 0000000..309a4ac --- /dev/null +++ b/scripts/release-packages.d.mts @@ -0,0 +1,61 @@ +export interface ReleasePackageDefinition { + readonly directory: string; + readonly name: string; +} + +export interface ValidationOptions { + readonly root?: string; + readonly releaseTag?: string; + readonly releasePrerelease?: boolean | string; + readonly expectedReleaseCommit?: string; + readonly requireClean?: boolean; + readonly requireMainAncestor?: boolean; + readonly requireReleaseTag?: boolean; +} + +export interface ReleaseCommandOptions extends ValidationOptions { + readonly manifest?: string; + readonly output?: string; +} + +export interface PublicPackageManifest { + readonly name: string; + readonly version: string; + readonly [key: string]: unknown; +} + +export interface ValidationResult { + readonly root: string; + readonly manifest: PublicPackageManifest; + readonly packageDirectory: string; + readonly releaseTag: string | undefined; +} + +export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; + +export function parseArguments( + arguments_: readonly string[], +): ReleaseCommandOptions; + +export function validateRepository( + options?: ValidationOptions, +): Promise; + +export function validateReleaseTag(options?: { + readonly root?: string; + readonly releaseTag?: string; + readonly expectedReleaseCommit?: string; +}): { headCommit: string; releaseTag: string }; + +export function decidePublication( + localIntegrity: string, + registryIntegrity: string | null, +): "publish" | "skip"; + +export function prepareRelease( + options?: ReleaseCommandOptions, +): Promise<{ manifestPath: string; manifest: unknown }>; + +export function publishPreparedRelease( + options?: ReleaseCommandOptions, +): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs new file mode 100644 index 0000000..304dc69 --- /dev/null +++ b/scripts/release-packages.mjs @@ -0,0 +1,584 @@ +import { spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual } from "node:crypto"; +import { + mkdtemp, + mkdir, + readFile, + readdir, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const PACKAGE = { + directory: "spine", + name: "@pegma/spine", +}; +const REPOSITORY_URL = "git+https://github.com/pegma-dev/spine.git"; +const REVIEWED_NPM_VERSION = "11.18.0"; +const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; + +export const RELEASE_PACKAGES = [PACKAGE]; + +function fail(message) { + throw new Error(message); +} + +async function readJson(path) { + return JSON.parse(await readFile(path, "utf8")); +} + +function safeEqual(left, right) { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return ( + leftBytes.length === rightBytes.length && + timingSafeEqual(leftBytes, rightBytes) + ); +} + +function run(command, arguments_, options = {}) { + const result = spawnSync(command, arguments_, { + cwd: options.cwd, + encoding: "utf8", + env: options.env ?? process.env, + shell: options.shell ?? false, + stdio: options.capture ? "pipe" : "inherit", + }); + if (result.error) throw result.error; + if (result.status !== 0 && !options.allowFailure) { + const detail = [result.stdout, result.stderr].filter(Boolean).join("\n"); + fail( + `${command} ${arguments_.join(" ")} failed with exit code ${String(result.status)}${detail ? `:\n${detail}` : ""}`, + ); + } + return result; +} + +function runNpm(arguments_, options = {}) { + const npmExecPath = process.env.npm_execpath; + return npmExecPath === undefined + ? run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { + ...options, + shell: process.platform === "win32", + }) + : run(process.execPath, [npmExecPath, ...arguments_], options); +} + +function gitCommand() { + return process.platform === "win32" ? "git.exe" : "git"; +} + +function hashTarball(bytes) { + return { + shasum: createHash("sha1").update(bytes).digest("hex"), + integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + }; +} + +function exportTargets(value) { + if (typeof value === "string") return [value]; + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + return Object.values(value).flatMap(exportTargets); + } + return []; +} + +export function validateReleaseTag(options = {}) { + const root = resolve(options.root ?? defaultRoot()); + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + const expectedReleaseCommit = + options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; + if (releaseTag === undefined || !/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { + fail("a stable release tag is required"); + } + if ( + expectedReleaseCommit === undefined || + !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) + ) { + fail("an exact release event commit is required"); + } + + const tagRef = `refs/tags/${releaseTag}`; + const type = run(gitCommand(), ["cat-file", "-t", tagRef], { + cwd: root, + capture: true, + allowFailure: true, + }); + if (type.status !== 0 || type.stdout.trim() !== "tag") { + fail("the release ref must be an annotated tag object"); + } + const headCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + const tagCommit = run(gitCommand(), ["rev-parse", `${tagRef}^{commit}`], { + cwd: root, + capture: true, + }).stdout.trim(); + if ( + !safeEqual(headCommit, tagCommit) || + !safeEqual(headCommit, expectedReleaseCommit) + ) { + fail( + "the release checkout, signed tag target, and release event commit must match", + ); + } + const signature = run(gitCommand(), ["verify-tag", "--raw", tagRef], { + cwd: root, + capture: true, + allowFailure: true, + }); + if (signature.status !== 0) { + fail("the release tag signature is not valid for an approved signer"); + } + const onMain = run( + gitCommand(), + ["merge-base", "--is-ancestor", tagCommit, "refs/remotes/origin/main"], + { cwd: root, capture: true, allowFailure: true }, + ); + if (onMain.status !== 0) { + fail("the release tag commit must be contained in origin/main"); + } + return { headCommit, releaseTag }; +} + +export async function validateRepository(options = {}) { + const root = resolve(options.root ?? defaultRoot()); + const rootManifest = await readJson(join(root, "package.json")); + const packageDirectory = join(root, "packages", PACKAGE.directory); + const manifest = await readJson(join(packageDirectory, "package.json")); + const lockfile = await readJson(join(root, "package-lock.json")); + const lockEntry = lockfile.packages?.[`packages/${PACKAGE.directory}`]; + + if ( + rootManifest.private !== true || + rootManifest.packageManager !== `npm@${REVIEWED_NPM_VERSION}` + ) { + fail(`the private root must pin npm@${REVIEWED_NPM_VERSION}`); + } + if ( + manifest.name !== PACKAGE.name || + !STABLE_SEMVER.test(manifest.version) || + manifest.private === true || + manifest.license !== "MIT" || + manifest.type !== "module" || + manifest.publishConfig?.access !== "public" || + manifest.engines?.node !== ">=22" || + manifest.repository?.type !== "git" || + manifest.repository?.url !== REPOSITORY_URL || + manifest.repository?.directory !== `packages/${PACKAGE.directory}` + ) { + fail(`${PACKAGE.name} has invalid public package metadata`); + } + if ( + !Array.isArray(manifest.files) || + manifest.files.length === 0 || + manifest.files.some((entry) => !entry.startsWith("dist/")) || + typeof manifest.scripts?.prepack !== "string" || + !manifest.scripts.prepack.includes("build") + ) { + fail(`${PACKAGE.name} has an unsafe package allowlist or prepack`); + } + const targets = exportTargets(manifest.exports); + if ( + targets.length === 0 || + targets.some( + (target) => + typeof target !== "string" || + !target.startsWith("./dist/") || + target.includes(".."), + ) + ) { + fail(`${PACKAGE.name} exports must point into dist`); + } + await stat(join(packageDirectory, "README.md")); + await stat(join(packageDirectory, "LICENSE")); + if (lockEntry?.version !== manifest.version) { + fail(`${PACKAGE.name} version is not synchronized with package-lock.json`); + } + + const publicWorkspaces = []; + for (const entry of await readdir(join(root, "packages"), { + withFileTypes: true, + })) { + if (!entry.isDirectory()) continue; + try { + const workspace = await readJson( + join(root, "packages", entry.name, "package.json"), + ); + if (workspace.private !== true) publicWorkspaces.push(workspace.name); + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + } + if (publicWorkspaces.length !== 1 || publicWorkspaces[0] !== PACKAGE.name) { + fail("public workspace inventory does not match the reviewed release list"); + } + + if (options.requireClean) { + const status = run(gitCommand(), ["status", "--porcelain"], { + cwd: root, + capture: true, + }).stdout; + if (status.trim() !== "") + fail("release preparation requires a clean checkout"); + } + if (options.requireMainAncestor) { + const head = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + const onMain = run( + gitCommand(), + ["merge-base", "--is-ancestor", head, "refs/remotes/origin/main"], + { cwd: root, capture: true, allowFailure: true }, + ); + if (onMain.status !== 0) { + fail("release commit must be contained in origin/main"); + } + } + + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + if (releaseTag !== undefined && releaseTag !== `v${manifest.version}`) { + fail(`release tag must be v${manifest.version}`); + } + const prerelease = + options.releasePrerelease ?? process.env.RELEASE_PRERELEASE ?? false; + if (prerelease === true || prerelease === "true") { + fail("prereleases cannot publish packages"); + } + if (options.requireReleaseTag) { + validateReleaseTag({ + root, + releaseTag, + expectedReleaseCommit: options.expectedReleaseCommit, + }); + } + return { root, manifest, packageDirectory, releaseTag }; +} + +function verifyPackedFiles(manifest, files) { + const paths = files.map(({ path }) => path); + for (const required of ["package.json", "README.md", "LICENSE"]) { + if (!paths.includes(required)) + fail(`${manifest.name} is missing ${required}`); + } + if ( + paths.some( + (path) => + !["package.json", "README.md", "LICENSE"].includes(path) && + !path.startsWith("dist/"), + ) + ) { + fail(`${manifest.name} tarball contains an unreviewed file`); + } + for (const target of exportTargets(manifest.exports)) { + const path = target.replace(/^\.\//u, ""); + if (!paths.includes(path)) fail(`${manifest.name} is missing ${path}`); + } +} + +async function smokeTestTarball(tarball, manifest) { + const directory = await mkdtemp(join(tmpdir(), "spine-release-smoke-")); + try { + await writeFile( + join(directory, "package.json"), + '{"name":"spine-release-smoke","private":true,"type":"module"}\n', + ); + runNpm( + [ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--package-lock=false", + tarball, + ], + { cwd: directory, capture: true }, + ); + for (const key of Object.keys(manifest.exports)) { + const specifier = + key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`; + run( + process.execPath, + [ + "--input-type=module", + "--eval", + `await import(${JSON.stringify(specifier)})`, + ], + { cwd: directory, capture: true }, + ); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +export async function prepareRelease(options = {}) { + const { root, manifest, packageDirectory, releaseTag } = + await validateRepository(options); + const gitCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + const output = resolve(root, options.output ?? ".release"); + await mkdir(output, { recursive: true }); + if ((await readdir(output)).length !== 0) { + fail(`release output directory must be empty: ${output}`); + } + + runNpm(["run", "build"], { cwd: root }); + const result = runNpm( + ["pack", packageDirectory, "--json", "--pack-destination", output], + { cwd: root, capture: true }, + ); + const [packed] = JSON.parse(result.stdout); + if ( + packed?.name !== manifest.name || + packed?.version !== manifest.version || + typeof packed.filename !== "string" || + !Array.isArray(packed.files) + ) { + fail("npm pack returned invalid metadata"); + } + verifyPackedFiles(manifest, packed.files); + const tarballPath = join(output, basename(packed.filename)); + const hashes = hashTarball(await readFile(tarballPath)); + if ( + !safeEqual(hashes.integrity, packed.integrity) || + !safeEqual(hashes.shasum, packed.shasum) + ) { + fail("tarball hashes do not match npm pack metadata"); + } + await smokeTestTarball(tarballPath, manifest); + + const prepared = { + schemaVersion: 1, + gitCommit, + releaseTag: releaseTag ?? null, + package: { + name: manifest.name, + version: manifest.version, + tarball: basename(tarballPath), + integrity: hashes.integrity, + shasum: hashes.shasum, + files: packed.files + .map(({ path, size }) => ({ path, size })) + .sort((left, right) => left.path.localeCompare(right.path)), + }, + }; + const manifestPath = join(output, "package-manifest.json"); + await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); + return { manifestPath, manifest: prepared }; +} + +function queryRegistryIntegrity(name, version) { + const spec = `${name}@${version}`; + const result = runNpm(["view", spec, "dist.integrity", "--json"], { + capture: true, + allowFailure: true, + }); + if (result.status === 0) { + const integrity = JSON.parse(result.stdout); + if (typeof integrity !== "string" || integrity.length === 0) { + fail(`${spec} exists without dist.integrity`); + } + return integrity; + } + const output = `${result.stdout}\n${result.stderr}`; + if (/\bE404\b/u.test(output)) return null; + fail(`npm registry lookup failed for ${spec}:\n${output.trim()}`); +} + +export function decidePublication(localIntegrity, registryIntegrity) { + if (registryIntegrity === null) return "publish"; + if (safeEqual(localIntegrity, registryIntegrity)) return "skip"; + fail("the registry version exists with different tarball integrity"); +} + +function requireTrustedPublishingNpm() { + const version = runNpm(["--version"], { capture: true }).stdout.trim(); + const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); + if (match === null) fail(`could not parse npm version ${version}`); + const [major, minor, patch] = match.slice(1).map(Number); + if ( + major < 11 || + (major === 11 && minor < 5) || + (major === 11 && minor === 5 && patch < 1) + ) { + fail("trusted publishing requires npm 11.5.1 or newer"); + } +} + +function wait(milliseconds) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); +} + +function confirmRegistryIntegrity(record) { + for (let attempt = 0; attempt < 6; attempt += 1) { + const integrity = queryRegistryIntegrity(record.name, record.version); + if (integrity !== null && safeEqual(record.integrity, integrity)) return; + if (attempt < 5) wait(2 ** attempt * 1000); + } + fail( + `${record.name}@${record.version} did not expose the prepared integrity`, + ); +} + +async function verifyPreparedManifest(path) { + const prepared = await readJson(path); + const record = prepared.package; + if ( + prepared.schemaVersion !== 1 || + !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || + prepared.releaseTag !== `v${record?.version}` || + record?.name !== PACKAGE.name || + !STABLE_SEMVER.test(record.version) || + typeof record.integrity !== "string" || + typeof record.shasum !== "string" || + !Array.isArray(record.files) + ) { + fail("prepared package manifest is invalid"); + } + const currentCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: defaultRoot(), + capture: true, + }).stdout.trim(); + if (!safeEqual(currentCommit, prepared.gitCommit)) { + fail("prepared package manifest commit does not match the checkout"); + } + const expectedTarball = `${PACKAGE.name + .slice(1) + .replace("/", "-")}-${record.version}.tgz`; + if (record.tarball !== expectedTarball) + fail("prepared tarball name is invalid"); + const tarball = resolve(dirname(path), record.tarball); + if (dirname(tarball) !== resolve(dirname(path))) { + fail("prepared tarball must be beside the package manifest"); + } + const hashes = hashTarball(await readFile(tarball)); + if ( + !safeEqual(hashes.integrity, record.integrity) || + !safeEqual(hashes.shasum, record.shasum) + ) { + fail("prepared tarball has changed"); + } + return prepared; +} + +export async function publishPreparedRelease(options = {}) { + if ( + process.env.GITHUB_ACTIONS !== "true" || + process.env.GITHUB_EVENT_NAME !== "release" + ) { + fail("release:publish is restricted to a GitHub release workflow"); + } + requireTrustedPublishingNpm(); + const path = resolve(options.manifest ?? ".release/package-manifest.json"); + const prepared = await verifyPreparedManifest(path); + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + const expectedCommit = + options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; + if (releaseTag !== prepared.releaseTag) { + fail("prepared manifest must match the release tag"); + } + if ( + expectedCommit === undefined || + !/^[0-9a-f]{40,64}$/u.test(expectedCommit) || + !safeEqual(expectedCommit, prepared.gitCommit) + ) { + fail("prepared package manifest must match the release event commit"); + } + + const record = prepared.package; + const decision = decidePublication( + record.integrity, + queryRegistryIntegrity(record.name, record.version), + ); + if (decision === "skip") { + process.stdout.write( + `Verified existing ${record.name}@${record.version}; skipping.\n`, + ); + return; + } + runNpm( + [ + "publish", + resolve(dirname(path), record.tarball), + "--access", + "public", + "--provenance", + ], + { cwd: dirname(path) }, + ); + confirmRegistryIntegrity(record); +} + +export function parseArguments(arguments_) { + const options = {}; + for (let index = 0; index < arguments_.length; index += 1) { + const argument = arguments_[index]; + if (argument === "--") continue; + if (argument === "--require-main-ancestor") { + options.requireMainAncestor = true; + continue; + } + if (argument === "--require-clean") { + options.requireClean = true; + continue; + } + if (argument === "--require-release-tag") { + options.requireReleaseTag = true; + continue; + } + const key = + argument === "--root" + ? "root" + : argument === "--output" + ? "output" + : argument === "--manifest" + ? "manifest" + : argument === "--expected-release-commit" + ? "expectedReleaseCommit" + : null; + if (key === null || arguments_[index + 1] === undefined) { + fail(`unknown or incomplete argument: ${argument}`); + } + options[key] = arguments_[index + 1]; + index += 1; + } + return options; +} + +function defaultRoot() { + return resolve(dirname(fileURLToPath(import.meta.url)), ".."); +} + +async function main() { + const [command, ...arguments_] = process.argv.slice(2); + const options = parseArguments(arguments_); + if (command === "check") { + await validateRepository(options); + process.stdout.write("Release metadata is valid.\n"); + return; + } + if (command === "pack") { + const { manifestPath } = await prepareRelease(options); + process.stdout.write(`Prepared release package at ${manifestPath}.\n`); + return; + } + if (command === "publish") { + await publishPreparedRelease(options); + return; + } + fail("usage: release-packages.mjs [options]"); +} + +const isMain = + process.argv[1] !== undefined && + resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isMain) await main(); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts new file mode 100644 index 0000000..3058b52 --- /dev/null +++ b/tests/release-packages.test.ts @@ -0,0 +1,181 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { + RELEASE_PACKAGES, + decidePublication, + parseArguments, + validateReleaseTag, + validateRepository, +} from "../scripts/release-packages.mjs"; + +const git = process.platform === "win32" ? "git.exe" : "git"; +const packageVersion = ( + JSON.parse( + readFileSync( + join(process.cwd(), "packages", "spine", "package.json"), + "utf8", + ), + ) as { version: string } +).version; + +function run(command: string, arguments_: string[], cwd?: string): string { + return execFileSync(command, arguments_, { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); +} + +describe("release package metadata", () => { + it("accepts npm's cross-platform argument separator", () => { + expect(parseArguments(["--", "--output", ".release"])).toEqual({ + output: ".release", + }); + }); + + it("keeps the exact public package inventory", () => { + expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual(["@pegma/spine"]); + }); + + it("validates package manifests and the lockfile together", async () => { + await expect(validateRepository()).resolves.toBeDefined(); + }); + + it("requires the release tag to match a public package version", async () => { + await expect(validateRepository({ releaseTag: "v9.9.9" })).rejects.toThrow( + `release tag must be v${packageVersion}`, + ); + await expect( + validateRepository({ + releaseTag: `v${packageVersion}`, + releasePrerelease: true, + }), + ).rejects.toThrow("prereleases cannot publish packages"); + }); +}); + +describe("release source authentication", () => { + it("accepts only an approved signed annotated tag at the event commit", () => { + const root = mkdtempSync(join(tmpdir(), "spine-release-tag-")); + try { + run(git, ["init", "--quiet"], root); + run(git, ["config", "user.name", "Release Test"], root); + run(git, ["config", "user.email", "release@example.com"], root); + writeFileSync(join(root, "README.md"), "release test\n"); + run(git, ["add", "README.md"], root); + run(git, ["commit", "--quiet", "-m", "release"], root); + run(git, ["branch", "-M", "main"], root); + run(git, ["update-ref", "refs/remotes/origin/main", "HEAD"], root); + const releaseCommit = run(git, ["rev-parse", "HEAD"], root); + + const signingKey = join(root, "release-signing-key"); + run("ssh-keygen", [ + "-q", + "-t", + "ed25519", + "-N", + "", + "-C", + "release@example.com", + "-f", + signingKey, + ]); + const allowedSigners = join(root, "allowed-signers"); + writeFileSync( + allowedSigners, + `release@example.com ${readFileSync(`${signingKey}.pub`, "utf8").trim()}\n`, + ); + run(git, ["config", "gpg.format", "ssh"], root); + run(git, ["config", "user.signingkey", signingKey], root); + run(git, ["config", "gpg.ssh.allowedSignersFile", allowedSigners], root); + + run(git, ["tag", "--sign", "v0.0.0", "--message", "signed"], root); + expect( + validateReleaseTag({ + root, + releaseTag: "v0.0.0", + expectedReleaseCommit: releaseCommit, + }), + ).toEqual({ headCommit: releaseCommit, releaseTag: "v0.0.0" }); + + run(git, ["tag", "v0.0.1"], root); + expect(() => + validateReleaseTag({ + root, + releaseTag: "v0.0.1", + expectedReleaseCommit: releaseCommit, + }), + ).toThrow("annotated tag object"); + + run( + git, + [ + "-c", + "commit.gpgsign=false", + "tag", + "--annotate", + "v0.0.2", + "--message", + "unsigned", + ], + root, + ); + expect(() => + validateReleaseTag({ + root, + releaseTag: "v0.0.2", + expectedReleaseCommit: releaseCommit, + }), + ).toThrow("not valid for an approved signer"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("keeps preparation outside the OIDC-enabled publisher job", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const jobsMarker = "\njobs:\n"; + const jobsIndex = workflow.indexOf(jobsMarker); + expect(jobsIndex).toBeGreaterThanOrEqual(0); + const header = workflow.slice(0, jobsIndex); + const jobs = workflow.slice(jobsIndex + jobsMarker.length); + const prepareStart = jobs.indexOf(" prepare:"); + const publishStart = jobs.indexOf("\n publish:"); + expect(header).not.toContain("id-token: write"); + expect(prepareStart).toBeGreaterThanOrEqual(0); + expect(publishStart).toBeGreaterThan(prepareStart); + const prepare = jobs.slice(prepareStart, publishStart); + const publish = jobs.slice(publishStart); + expect(prepare).not.toContain("id-token: write"); + expect(publish).toContain("id-token: write"); + expect(publish).not.toContain("npm ci"); + expect(publish).not.toContain("npm install"); + expect(publish).toContain("npm run release:publish"); + expect(workflow).not.toContain("workflow_dispatch"); + expect(workflow).toContain("retention-days: 30"); + }); +}); + +describe("retry-safe publication", () => { + const integrity = "sha512-cHJlcGFyZWQtdGFyYmFsbA=="; + + it("publishes an absent version", () => { + expect(decidePublication(integrity, null)).toBe("publish"); + }); + + it("skips a byte-identical existing version", () => { + expect(decidePublication(integrity, integrity)).toBe("skip"); + }); + + it("rejects an existing version with different bytes", () => { + expect(() => decidePublication(integrity, "sha512-ZGlmZmVyZW50")).toThrow( + "different tarball integrity", + ); + }); +}); diff --git a/tsconfig.test.json b/tsconfig.test.json index f4dabda..857994d 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -7,5 +7,9 @@ "sourceMap": false, "noEmit": true }, - "include": ["packages/*/src/**/*.test.ts", "vitest.config.ts"] + "include": [ + "packages/*/src/**/*.test.ts", + "tests/**/*.test.ts", + "vitest.config.ts" + ] } diff --git a/vitest.config.ts b/vitest.config.ts index e783135..a191fca 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { - include: ["packages/**/*.test.ts"], + include: ["packages/**/*.test.ts", "tests/**/*.test.ts"], exclude: ["**/dist/**", "**/node_modules/**"], }, });