From a84395d9e348331730fb4942893f73fe2194a6f8 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 12:56:13 -0500 Subject: [PATCH 1/7] Tighten release workflow validation --- .github/workflows/ci.yml | 5 + .github/workflows/publish.yml | 383 ++++++++++++++++++++++++++++++--- docs/RELEASING.md | 31 ++- scripts/release-packages.d.mts | 36 ++++ scripts/release-packages.mjs | 281 ++++++++++++++++++++---- test/release-packages.test.ts | 282 ++++++++++++++++++++++-- 6 files changed, 926 insertions(+), 92 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de0483a..387d46a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,8 @@ jobs: validate: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest + env: + CI: "1" strategy: fail-fast: false matrix: @@ -42,6 +44,9 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Check release metadata + run: pnpm run release:check + - name: Check formatting run: pnpm run format:check diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e5f4527..31ac769 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,53 +18,95 @@ jobs: prepare: runs-on: ubuntu-latest env: + CI: "1" 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 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 + - name: Verify the release source shell: bash run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases are supported" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then + echo "::error::Release tag must be a supported stable version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Release commit must be an exact commit ID" + exit 1 + fi 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 + : > "${allowed_signers}" + chmod 0600 "${allowed_signers}" printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + + scratch="$(mktemp -d "${RUNNER_TEMP}/release-verify.XXXXXX")" + trap 'rm -rf -- "${scratch}"' EXIT + repository="${scratch}/repository.git" + git init --quiet --bare "${repository}" + git -C "${repository}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${repository}" config gpg.format ssh + git -C "${repository}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${repository}" fetch --quiet --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + + tag_ref="refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" == "tag" ]] + git -C "${repository}" verify-tag "${tag_ref}" + tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")" + [[ "${tag_commit}" == "${RELEASE_COMMIT}" ]] + git -C "${repository}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the verified release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + + - name: Fetch verified release refs + shell: bash + run: | + set -euo pipefail + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" git config --local gpg.format ssh git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" - - - name: Enable Corepack - run: corepack enable + git fetch --quiet --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - - name: Activate pnpm + - name: Enable Corepack run: corepack enable - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Check release metadata + run: pnpm run release:check + - name: Check formatting run: pnpm run format:check @@ -74,22 +116,66 @@ jobs: - name: Run tests run: pnpm test + - name: Remove generated package outputs + shell: bash + run: | + set -euo pipefail + rm -rf -- packages/sessions/dist + find packages/sessions -type f -name '*.tsbuildinfo' -delete + - name: Prepare and verify the release tarball run: pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + - name: Check the prepared file inventory + id: inventory + shell: bash + run: | + set -euo pipefail + node --input-type=module <<'NODE' + import { lstatSync, readdirSync } from "node:fs"; + import { join } from "node:path"; + + const version = process.env.RELEASE_TAG.slice(1); + const tarball = `pegma-sessions-${version}.tgz`; + const expected = ["package-manifest.json", tarball].sort(); + const directory = ".release"; + const entries = readdirSync(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + if ( + names.length !== expected.length || + names.some((name, index) => name !== expected[index]) + ) { + throw new Error("prepared file inventory is not exact"); + } + for (const name of expected) { + const entry = entries.find((candidate) => candidate.name === name); + if (entry?.isFile() !== true || !lstatSync(join(directory, name)).isFile()) { + throw new Error("prepared entries must be regular files"); + } + } + NODE + node --input-type=module >> "${GITHUB_OUTPUT}" <<'NODE' + const version = process.env.RELEASE_TAG.slice(1); + process.stdout.write(`tarball=.release/pegma-sessions-${version}.tgz\n`); + NODE + - name: Upload the prepared release id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: sessions-release-${{ github.run_id }} - path: .release/ + path: | + .release/package-manifest.json + ${{ steps.inventory.outputs.tarball }} if-no-files-found: error - include-hidden-files: true + include-hidden-files: false 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}" + env: + ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} + run: echo "Prepared artifact SHA-256 ${ARTIFACT_DIGEST}" >> "${GITHUB_STEP_SUMMARY}" publish: needs: prepare @@ -99,28 +185,267 @@ jobs: contents: read id-token: write env: + CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release 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: Verify the release source + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases are supported" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then + echo "::error::Release tag must be a supported stable version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Release commit must be an exact commit ID" + exit 1 + fi + 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 + : > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + + scratch="$(mktemp -d "${RUNNER_TEMP}/release-verify.XXXXXX")" + trap 'rm -rf -- "${scratch}"' EXIT + repository="${scratch}/repository.git" + git init --quiet --bare "${repository}" + git -C "${repository}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${repository}" config gpg.format ssh + git -C "${repository}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${repository}" fetch --quiet --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + + tag_ref="refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" == "tag" ]] + git -C "${repository}" verify-tag "${tag_ref}" + tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")" + [[ "${tag_commit}" == "${RELEASE_COMMIT}" ]] + git -C "${repository}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main - - name: Set up Node.js and the npm registry + - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 --ignore-scripts + - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: sessions-release-${{ github.run_id }} - path: .release + path: ${{ env.RELEASE_DIRECTORY }} + + - name: Publish the prepared tarball + shell: bash + run: | + set -euo pipefail + node --input-type=module <<'NODE' + import { spawnSync } from "node:child_process"; + import { createHash, timingSafeEqual } from "node:crypto"; + import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + writeFileSync, + } from "node:fs"; + import { tmpdir } from "node:os"; + import { basename, dirname, join, resolve } from "node:path"; + + const PACKAGE_NAME = "@pegma/sessions"; + const REGISTRY = "https://registry.npmjs.org/"; + const directory = resolve(process.env.RELEASE_DIRECTORY); + const version = process.env.RELEASE_TAG.slice(1); + const expectedTarball = `pegma-sessions-${version}.tgz`; + const expectedNames = ["package-manifest.json", expectedTarball].sort(); + const entries = readdirSync(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + if ( + names.length !== expectedNames.length || + names.some((name, index) => name !== expectedNames[index]) + ) { + throw new Error("prepared file inventory is not exact"); + } + for (const name of expectedNames) { + const entry = entries.find((candidate) => candidate.name === name); + if (entry?.isFile() !== true || !lstatSync(join(directory, name)).isFile()) { + throw new Error("prepared entries must be regular files"); + } + } + + const hasExactKeys = (value, expected) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const actual = Object.keys(value).sort(); + const keys = [...expected].sort(); + return actual.length === keys.length && actual.every((key, index) => key === keys[index]); + }; + const manifestPath = join(directory, "package-manifest.json"); + const prepared = JSON.parse(readFileSync(manifestPath, "utf8")); + const record = prepared.package; + if ( + !hasExactKeys(prepared, ["gitCommit", "package", "releaseTag", "schemaVersion", "version"]) || + !hasExactKeys(record, ["files", "integrity", "name", "sha256", "shasum", "tarball", "version"]) || + prepared.schemaVersion !== 1 || + prepared.version !== version || + prepared.releaseTag !== process.env.RELEASE_TAG || + prepared.gitCommit !== process.env.RELEASE_COMMIT || + record.name !== PACKAGE_NAME || + record.version !== version || + record.tarball !== expectedTarball || + !/^[0-9a-f]{64}$/u.test(record.sha256) || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) || + !/^[0-9a-f]{40}$/u.test(record.shasum) || + !Array.isArray(record.files) || + record.files.some((file) => + !hasExactKeys(file, ["path", "size"]) || + typeof file.path !== "string" || + file.path.length === 0 || + !Number.isSafeInteger(file.size) || + file.size < 0, + ) + ) { + throw new Error("prepared package manifest is invalid"); + } + const packedPaths = record.files.map(({ path }) => path); + for (const required of ["package.json", "README.md", "LICENSE"]) { + if (!packedPaths.includes(required)) { + throw new Error(`package is missing ${required}`); + } + } + if (packedPaths.some((path) => + !["package.json", "README.md", "LICENSE"].includes(path) && !path.startsWith("dist/"), + )) { + throw new Error("package file inventory is not expected"); + } + + const tarballPath = join(directory, expectedTarball); + if (basename(tarballPath) !== expectedTarball || dirname(tarballPath) !== directory) { + throw new Error("prepared tarball path is invalid"); + } + const bytes = readFileSync(tarballPath); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + const shasum = createHash("sha1").update(bytes).digest("hex"); + const equal = (left, right) => { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes); + }; + if (!equal(sha256, record.sha256) || !equal(integrity, record.integrity) || !equal(shasum, record.shasum)) { + throw new Error("prepared tarball digests do not match"); + } + + const executableDirectory = dirname(process.execPath); + const npmCandidates = [ + join(executableDirectory, "node_modules", "npm", "bin", "npm-cli.js"), + resolve(executableDirectory, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"), + ]; + const npmCliCandidate = npmCandidates.find(existsSync); + if (npmCliCandidate === undefined) { + throw new Error("npm CLI was not found beside Node.js"); + } + const npmCli = realpathSync(npmCliCandidate); + const runtimeRoot = mkdtempSync(join(tmpdir(), "sessions-publish-")); + const cwd = join(runtimeRoot, "cwd"); + const userConfig = join(runtimeRoot, "user.npmrc"); + const globalConfig = join(runtimeRoot, "global.npmrc"); + mkdirSync(cwd, { mode: 0o700 }); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + + const allowedNames = new Set([ + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "CI", + "HOME", + "PATH", + "SystemRoot", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + ]); + const env = {}; + for (const [name, value] of Object.entries(process.env)) { + if (value !== undefined && (allowedNames.has(name) || name.startsWith("GITHUB_"))) { + env[name] = value; + } + } + env.NPM_CONFIG_USERCONFIG = userConfig; + env.NPM_CONFIG_GLOBALCONFIG = globalConfig; + + const npm = (arguments_, allowFailure = false) => { + const result = spawnSync(process.execPath, [npmCli, ...arguments_], { + cwd, + env, + encoding: "utf8", + stdio: "pipe", + }); + if (result.error) throw result.error; + if (result.status !== 0 && !allowFailure) { + throw new Error(`npm failed with exit code ${String(result.status)}:\n${result.stdout}\n${result.stderr}`); + } + return result; + }; - - name: Publish the verified prepared tarball - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + try { + const npmVersion = npm(["--version"]).stdout.trim(); + if (npmVersion !== "11.18.0") { + throw new Error(`unexpected npm version ${npmVersion}`); + } + const spec = `${PACKAGE_NAME}@${version}`; + const lookup = npm(["view", spec, "dist.integrity", "--json", "--registry", REGISTRY], true); + if (lookup.status === 0) { + const publishedIntegrity = JSON.parse(lookup.stdout); + if (!equal(record.integrity, publishedIntegrity)) { + throw new Error("registry version has different package integrity"); + } + process.stdout.write(`Verified existing ${spec}; skipping.\n`); + } else { + const lookupOutput = `${lookup.stdout}\n${lookup.stderr}`; + if (!/\bE404\b/u.test(lookupOutput)) { + throw new Error(`npm registry lookup failed:\n${lookupOutput.trim()}`); + } + npm([ + "publish", + tarballPath, + "--access", + "public", + "--registry", + REGISTRY, + "--provenance", + "--ignore-scripts", + ]); + } + } finally { + rmSync(runtimeRoot, { recursive: true, force: true }); + } + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 27cf755..fdc0925 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -60,7 +60,7 @@ The release tool verifies that: - every exported file exists and a clean consumer can import the package; and - the prepared manifest records the exact commit, tag, file inventory, - SHA-1, and SHA-512 integrity. + SHA-1, SHA-256, and SHA-512 integrity. For a GitHub release, preparation additionally requires a stable annotated `vX.Y.Z` tag signed by an approved signer. The tag must match the manifest @@ -118,10 +118,10 @@ npm install -g corepack corepack enable npm install --global npm@11.18.0 pnpm install +pnpm run release:check pnpm run format:check pnpm run check pnpm test -pnpm run release:check pnpm run release:pack -- -- --output .release ``` @@ -149,16 +149,27 @@ tag; if any byte must change, prepare a new version. The globally serialized preparation job: -1. checks out the fully qualified release tag and fetches `origin/main`; -2. configures the reviewed allowed-signers file; -3. uses Node 24.18.0, pnpm 10.34.5, and npm 11.18.0 for pack and publish; -4. runs the full gate without OIDC publication authority; -5. prepares, smoke-tests, and hashes the exact tarball; and -6. uploads `.release` for 30 days with an Actions transport digest. +1. validates the stable version floor and release event fields from the + environment; +2. fetches only `origin/main` and the named tag into a scratch bare Git + repository, then verifies the annotated tag, approved signature, exact + event commit, and `origin/main` ancestry; +3. checks out the already verified commit by exact SHA without persisted Git + credentials; +4. uses Node 24.18.0, pnpm 10.34.5, and npm 11.18.0 for validation and pack; +5. runs the full gate without OIDC publication authority; +6. removes generated build outputs, performs a clean build, smoke-tests the + package, and records the exact tarball digests; and +7. uploads only the regular manifest and tarball files for 30 days with an + Actions transport digest. Only the `npm-publish` job receives `id-token: write`. It downloads the -prepared artifact, installs no dependencies, rechecks the commit, tag, -manifest, and tarball hashes, and publishes with provenance. +prepared artifact without a repository checkout, repeats the bare Git tag +verification, and validates the two-file inventory, manifest schema, commit, +version, and tarball digests using workflow-owned inline code. It runs the +reviewed npm CLI from an empty temporary directory with empty private npm +configuration files and an allowlisted environment, then publishes the +absolute tarball path with provenance and lifecycle scripts disabled. If a hardened release fails, rerun its failed jobs against the unchanged tag: diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index e9e46a4..47b9664 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -54,6 +54,16 @@ export interface ParsedPnpmLock { export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; +export interface IsolatedNpmRuntime { + readonly command: string; + readonly argumentsPrefix: readonly string[]; + readonly cwd: string; + readonly env: Readonly>; + readonly userConfig: string; + readonly globalConfig: string; + cleanup(): void; +} + export function parseArguments( arguments_: readonly string[], ): ReleaseCommandOptions; @@ -68,6 +78,31 @@ export function validateReleaseTag(options?: { readonly expectedReleaseCommit?: string; }): { headCommit: string; releaseTag: string }; +export function isSupportedReleaseTag(releaseTag: string): boolean; + +export function isolatedNpmEnvironment( + source: Readonly>, + userConfig: string, + globalConfig: string, +): Record; + +export function createIsolatedNpmRuntime( + source?: Readonly>, +): IsolatedNpmRuntime; + +export function runNpm( + arguments_: readonly string[], + options?: { + readonly capture?: boolean; + readonly allowFailure?: boolean; + }, +): SpawnSyncReturns; + +export function validateReleaseInventory( + directory: string, + expectedTarball?: string, +): Promise<{ tarball: string }>; + export function decidePublication( localIntegrity: string, registryIntegrity: string | null, @@ -97,3 +132,4 @@ export function inspectPreparedRegistry( export function publishPreparedRelease( options?: ReleaseCommandOptions, ): Promise; +import type { SpawnSyncReturns } from "node:child_process"; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 245bedf..d3aef5b 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,8 +1,18 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; import { mkdtemp, mkdir, + lstat, readFile, readdir, rm, @@ -20,6 +30,8 @@ const PACKAGE = { const REPOSITORY_URL = "git+https://github.com/pegma-dev/sessions.git"; const REVIEWED_PNPM_VERSION = "10.34.5"; const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +const RELEASE_TAG = /^v(0\.[1-9]\d*|[1-9]\d*\.\d+)\.\d+$/u; +const NPM_REGISTRY = "https://registry.npmjs.org/"; const DEPENDENCY_SECTIONS = [ "dependencies", "devDependencies", @@ -64,13 +76,99 @@ function run(command, arguments_, options = {}) { return result; } -function runNpm(arguments_, options = {}) { - // Always invoke the npm CLI, not npm_execpath. Scripts run under pnpm set - // npm_execpath to pnpm, and pack/publish/view must stay on reviewed npm. - return run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { - ...options, - shell: process.platform === "win32", - }); +function resolveNpmCli() { + const executableDirectory = dirname(process.execPath); + const candidates = [ + join(executableDirectory, "node_modules", "npm", "bin", "npm-cli.js"), + join( + executableDirectory, + "..", + "lib", + "node_modules", + "npm", + "bin", + "npm-cli.js", + ), + ]; + for (const candidate of candidates) { + if (existsSync(candidate)) return realpathSync(candidate); + } + fail("could not locate the npm CLI beside the active Node.js runtime"); +} + +const NPM_ENVIRONMENT_NAMES = new Set([ + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "CI", + "COMSPEC", + "HOME", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", + "PATH", + "Path", + "PATHEXT", + "SystemRoot", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + "USERPROFILE", + "WINDIR", +]); + +export function isolatedNpmEnvironment(source, userConfig, globalConfig) { + const env = {}; + for (const [name, value] of Object.entries(source)) { + if ( + value !== undefined && + (NPM_ENVIRONMENT_NAMES.has(name) || name.startsWith("GITHUB_")) + ) { + env[name] = value; + } + } + env.NPM_CONFIG_USERCONFIG = userConfig; + env.NPM_CONFIG_GLOBALCONFIG = globalConfig; + return env; +} + +export function createIsolatedNpmRuntime(source = process.env) { + const directory = mkdtempSync(join(tmpdir(), "sessions-release-npm-")); + const cwd = join(directory, "cwd"); + const userConfig = join(directory, "user.npmrc"); + const globalConfig = join(directory, "global.npmrc"); + mkdirSync(cwd, { mode: 0o700 }); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + return { + command: process.execPath, + argumentsPrefix: [resolveNpmCli()], + cwd, + env: isolatedNpmEnvironment(source, userConfig, globalConfig), + userConfig, + globalConfig, + cleanup() { + rmSync(directory, { recursive: true, force: true }); + }, + }; +} + +export function runNpm(arguments_, options = {}) { + // Invoke npm's JavaScript entry point with Node so Windows does not require + // a command shell and package-manager wrapper variables are never followed. + const runtime = createIsolatedNpmRuntime(); + try { + return run(runtime.command, [...runtime.argumentsPrefix, ...arguments_], { + ...options, + cwd: runtime.cwd, + env: runtime.env, + shell: false, + }); + } finally { + runtime.cleanup(); + } } function parseYamlScalar(raw) { @@ -253,10 +351,15 @@ function defaultRoot() { function hashTarball(bytes) { return { shasum: createHash("sha1").update(bytes).digest("hex"), + sha256: createHash("sha256").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, }; } +export function isSupportedReleaseTag(releaseTag) { + return RELEASE_TAG.test(releaseTag) && releaseTag !== "v0.1.0"; +} + function exportTargets(value) { if (typeof value === "string") return [value]; if (value !== null && typeof value === "object" && !Array.isArray(value)) { @@ -270,12 +373,12 @@ export function validateReleaseTag(options = {}) { 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)) { + if (releaseTag === undefined || !isSupportedReleaseTag(releaseTag)) { fail("a stable release tag is required"); } if ( expectedReleaseCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) + !/^[0-9a-f]{40}$/u.test(expectedReleaseCommit) ) { fail("an exact release event commit is required"); } @@ -351,7 +454,7 @@ export async function validateRepository(options = {}) { ); if ( manifest.name !== PACKAGE.name || - !STABLE_SEMVER.test(manifest.version) || + !isSupportedReleaseTag(`v${manifest.version}`) || manifest.private === true || manifest.license !== "MIT" || manifest.type !== "module" || @@ -492,6 +595,48 @@ function verifyPackedFiles(manifest, files) { } } +export async function validateReleaseInventory(directory, expectedTarball) { + const entries = await readdir(directory, { withFileTypes: true }); + const tarballs = entries + .map(({ name }) => name) + .filter((name) => name.endsWith(".tgz")); + const tarball = expectedTarball ?? tarballs[0]; + const version = /^pegma-sessions-(.+)\.tgz$/u.exec(tarball ?? "")?.[1]; + if ( + tarballs.length !== 1 || + version === undefined || + !isSupportedReleaseTag(`v${version}`) + ) { + fail("release directory must contain one supported package tarball"); + } + const expected = ["package-manifest.json", tarball].sort(); + const names = entries.map(({ name }) => name).sort(); + if ( + names.length !== expected.length || + names.some((name, index) => name !== expected[index]) + ) { + fail( + "release directory must contain only the manifest and package tarball", + ); + } + for (const name of expected) { + const entry = entries.find((candidate) => candidate.name === name); + const details = await lstat(join(directory, name)); + if (entry?.isFile() !== true || !details.isFile()) { + fail("release directory entries must be regular files"); + } + } + return { tarball }; +} + +async function buildFromCleanOutputs(root, packageDirectory) { + const typescript = join(root, "node_modules", "typescript", "bin", "tsc"); + run(process.execPath, [typescript, "-b", "--clean"], { cwd: root }); + await rm(join(packageDirectory, "dist"), { recursive: true, force: true }); + await rm(join(packageDirectory, "tsconfig.tsbuildinfo"), { force: true }); + run(process.execPath, [typescript, "-b"], { cwd: root }); +} + async function smokeTestTarball(tarball, manifest) { const directory = await mkdtemp(join(tmpdir(), "sessions-release-smoke-")); try { @@ -506,9 +651,13 @@ async function smokeTestTarball(tarball, manifest) { "--no-audit", "--no-fund", "--package-lock=false", + "--registry", + NPM_REGISTRY, + "--prefix", + directory, tarball, ], - { cwd: directory, capture: true }, + { capture: true }, ); for (const key of Object.keys(manifest.exports)) { const specifier = @@ -537,14 +686,18 @@ export async function prepareRelease(options = {}) { }).stdout.trim(); const output = resolve(root, options.output ?? ".release"); await mkdir(output, { recursive: true }); + const outputDetails = await lstat(output); + if (!outputDetails.isDirectory() || outputDetails.isSymbolicLink()) { + fail(`release output must be a directory: ${output}`); + } if ((await readdir(output)).length !== 0) { fail(`release output directory must be empty: ${output}`); } - runNpm(["run", "build"], { cwd: root }); + await buildFromCleanOutputs(root, packageDirectory); const result = runNpm( ["pack", packageDirectory, "--json", "--pack-destination", output], - { cwd: root, capture: true }, + { capture: true }, ); const [packed] = JSON.parse(result.stdout); if ( @@ -575,6 +728,7 @@ export async function prepareRelease(options = {}) { name: manifest.name, version, tarball: basename(tarballPath), + sha256: hashes.sha256, integrity: hashes.integrity, shasum: hashes.shasum, files: packed.files @@ -584,15 +738,19 @@ export async function prepareRelease(options = {}) { }; const manifestPath = join(output, "package-manifest.json"); await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); + await validateReleaseInventory(output, basename(tarballPath)); return { manifestPath, manifest: prepared }; } function queryRegistryIntegrity(name, version) { const spec = `${name}@${version}`; - const result = runNpm(["view", spec, "dist.integrity", "--json"], { - capture: true, - allowFailure: true, - }); + const result = runNpm( + ["view", spec, "dist.integrity", "--json", "--registry", NPM_REGISTRY], + { + capture: true, + allowFailure: true, + }, + ); if (result.status === 0) { const integrity = JSON.parse(result.stdout); if (typeof integrity !== "string" || integrity.length === 0) { @@ -611,23 +769,65 @@ export function decidePublication(localIntegrity, registryIntegrity) { fail("the registry version exists with different tarball integrity"); } +function hasExactKeys(value, expected) { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const actual = Object.keys(value).sort(); + const keys = [...expected].sort(); + return ( + actual.length === keys.length && + actual.every((key, index) => key === keys[index]) + ); +} + async function verifyPreparedManifest(manifestPath) { + if (basename(manifestPath) !== "package-manifest.json") { + fail("prepared manifest must use the expected filename"); + } + const directory = dirname(manifestPath); + const inventory = await validateReleaseInventory(directory); const prepared = await readJson(manifestPath); const record = prepared.package; const { manifest } = await validateRepository(); if ( + !hasExactKeys(prepared, [ + "gitCommit", + "package", + "releaseTag", + "schemaVersion", + "version", + ]) || + !hasExactKeys(record, [ + "files", + "integrity", + "name", + "sha256", + "shasum", + "tarball", + "version", + ]) || prepared.schemaVersion !== 1 || - !STABLE_SEMVER.test(prepared.version) || - !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || + !isSupportedReleaseTag(`v${prepared.version}`) || + !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || !( prepared.releaseTag === null || prepared.releaseTag === `v${prepared.version}` ) || record?.name !== PACKAGE.name || record?.version !== prepared.version || - typeof record.integrity !== "string" || - typeof record.shasum !== "string" || - !Array.isArray(record.files) + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) || + !/^[0-9a-f]{64}$/u.test(record.sha256) || + !/^[0-9a-f]{40}$/u.test(record.shasum) || + !Array.isArray(record.files) || + record.files.some( + (file) => + !hasExactKeys(file, ["path", "size"]) || + typeof file.path !== "string" || + file.path.length === 0 || + !Number.isSafeInteger(file.size) || + file.size < 0, + ) ) { fail("prepared package manifest is invalid"); } @@ -645,16 +845,20 @@ async function verifyPreparedManifest(manifestPath) { const expectedTarball = `${PACKAGE.name .slice(1) .replace("/", "-")}-${record.version}.tgz`; - if (record.tarball !== expectedTarball) { + if ( + record.tarball !== expectedTarball || + inventory.tarball !== expectedTarball + ) { fail("prepared tarball name is invalid"); } - const tarball = resolve(dirname(manifestPath), record.tarball); - if (dirname(tarball) !== resolve(dirname(manifestPath))) { + const tarball = resolve(directory, record.tarball); + if (dirname(tarball) !== resolve(directory)) { fail("prepared tarball must be beside the package manifest"); } const hashes = hashTarball(await readFile(tarball)); if ( !safeEqual(hashes.integrity, record.integrity) || + !safeEqual(hashes.sha256, record.sha256) || !safeEqual(hashes.shasum, record.shasum) ) { fail("prepared tarball has changed"); @@ -713,7 +917,10 @@ export async function publishPreparedRelease(options = {}) { ) { fail("release:publish is restricted to a GitHub release workflow"); } - if (process.env.NODE_AUTH_TOKEN !== undefined) { + if ( + process.env.NODE_AUTH_TOKEN !== undefined || + process.env.NPM_TOKEN !== undefined + ) { fail("release:publish refuses npm token authentication"); } requireTrustedPublishingNpm(); @@ -732,7 +939,7 @@ export async function publishPreparedRelease(options = {}) { } if ( expectedCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedCommit) || + !/^[0-9a-f]{40}$/u.test(expectedCommit) || !safeEqual(expectedCommit, prepared.gitCommit) ) { fail("prepared package manifest must match the release event commit"); @@ -749,16 +956,16 @@ export async function publishPreparedRelease(options = {}) { ); return; } - runNpm( - [ - "publish", - resolve(dirname(manifestPath), record.tarball), - "--access", - "public", - "--provenance", - ], - { cwd: dirname(manifestPath) }, - ); + runNpm([ + "publish", + resolve(dirname(manifestPath), record.tarball), + "--access", + "public", + "--provenance", + "--ignore-scripts", + "--registry", + NPM_REGISTRY, + ]); confirmRegistryIntegrity(record); } diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 0e64e25..6332dbb 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -1,15 +1,30 @@ import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { RELEASE_PACKAGES, + createIsolatedNpmRuntime, decidePublication, + isSupportedReleaseTag, + isolatedNpmEnvironment, parseArguments, parsePnpmLockImporters, + prepareRelease, resolvedVersionSatisfies, + runNpm, validateLockImporter, + validateReleaseInventory, validateReleaseTag, validateRepository, } from "../scripts/release-packages.mjs"; @@ -32,6 +47,33 @@ function run(command: string, arguments_: string[], cwd?: string): string { }).trim(); } +function workflowRunScripts(workflow: string): string[] { + const lines = workflow.split(/\r?\n/u); + const scripts: string[] = []; + for (let index = 0; index < lines.length; index += 1) { + const match = /^(\s*)run:\s*(.*)$/u.exec(lines[index] ?? ""); + if (match === null) continue; + const runValue = match[2] ?? ""; + if (runValue !== "|") { + scripts.push(runValue); + continue; + } + const indentation = (match[1] ?? "").length; + const block: string[] = []; + for (index += 1; index < lines.length; index += 1) { + const line = lines[index] ?? ""; + const lineIndentation = /^\s*/u.exec(line)?.[0].length ?? 0; + if (line !== "" && lineIndentation <= indentation) { + index -= 1; + break; + } + block.push(line); + } + scripts.push(block.join("\n")); + } + return scripts; +} + describe("release package metadata", () => { it("accepts npm's cross-platform argument separator", () => { expect(parseArguments(["--", "--output", ".release"])).toEqual({ @@ -51,17 +93,77 @@ describe("release package metadata", () => { }); }); - it("never routes pack, view, or publish through npm_execpath", () => { + it("resolves npm beside Node and does not use a package-manager wrapper", () => { const source = readFileSync( join(process.cwd(), "scripts", "release-packages.mjs"), "utf8", ); expect(source).not.toContain("process.env.npm_execpath"); - expect(source).toContain( - 'process.platform === "win32" ? "npm.cmd" : "npm"', + expect(source).toContain('"npm", "bin", "npm-cli.js"'); + expect(source).toContain("command: process.execPath"); + expect(source).toContain("shell: false"); + expect(runNpm(["--version"], { capture: true }).stdout.trim()).toMatch( + /^11\.18\.0$/u, ); }); + it("uses private npm configuration and an allowlisted environment", () => { + const source = { + PATH: process.env.PATH, + HOME: process.env.HOME, + SystemRoot: process.env.SystemRoot, + TEMP: process.env.TEMP, + CI: "1", + GITHUB_ACTIONS: "true", + GITHUB_REPOSITORY: "pegma-dev/sessions", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.test/id-token", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "request-token", + npm_config_registry: "https://example.test/registry", + NPM_CONFIG_CACHE: "cache", + NPM_TOKEN: "package-token", + NODE_AUTH_TOKEN: "node-token", + NODE_OPTIONS: "--inspect", + NODE_EXTRA_CA_CERTS: "ca.pem", + HTTPS_PROXY: "https://example.test/proxy", + }; + const env = isolatedNpmEnvironment(source, "user-config", "global-config"); + expect(env).toMatchObject({ + CI: "1", + GITHUB_ACTIONS: "true", + GITHUB_REPOSITORY: "pegma-dev/sessions", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.test/id-token", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "request-token", + NPM_CONFIG_USERCONFIG: "user-config", + NPM_CONFIG_GLOBALCONFIG: "global-config", + }); + for (const name of [ + "npm_config_registry", + "NPM_CONFIG_CACHE", + "NPM_TOKEN", + "NODE_AUTH_TOKEN", + "NODE_OPTIONS", + "NODE_EXTRA_CA_CERTS", + "HTTPS_PROXY", + ]) { + expect(env).not.toHaveProperty(name); + } + + const runtime = createIsolatedNpmRuntime(source); + try { + expect(readdirSync(runtime.cwd)).toEqual([]); + if (process.platform !== "win32") { + expect(statSync(runtime.userConfig).mode & 0o777).toBe(0o600); + expect(statSync(runtime.globalConfig).mode & 0o777).toBe(0o600); + } + expect(readFileSync(runtime.userConfig, "utf8")).toBe(""); + expect(readFileSync(runtime.globalConfig, "utf8")).toBe(""); + expect(runtime.command).toBe(process.execPath); + expect(runtime.argumentsPrefix[0]).toMatch(/npm-cli\.js$/u); + } finally { + runtime.cleanup(); + } + }); + it("matches each lockfile dependency to its own specifier and resolved version", () => { const lock = parsePnpmLockImporters( readFileSync(join(process.cwd(), "pnpm-lock.yaml"), "utf8"), @@ -254,6 +356,81 @@ importers: }), ).rejects.toThrow("prereleases cannot publish packages"); }); + + it("accepts only stable release tags at or above the supported floor", () => { + expect(isSupportedReleaseTag("v0.1.1")).toBe(true); + expect(isSupportedReleaseTag("v0.12.0")).toBe(true); + expect(isSupportedReleaseTag("v1.0.0")).toBe(true); + expect(isSupportedReleaseTag("v0.1.0")).toBe(false); + expect(isSupportedReleaseTag("v0.0.9")).toBe(false); + expect(isSupportedReleaseTag("v01.2.3")).toBe(false); + expect(isSupportedReleaseTag("v1.2.3-beta.1")).toBe(false); + }); + + it("requires an exact regular-file release inventory", async () => { + const root = mkdtempSync(join(tmpdir(), "sessions-release-inventory-")); + const directory = join(root, "release"); + const tarball = "pegma-sessions-0.1.1.tgz"; + try { + mkdirSync(directory); + writeFileSync(join(directory, "package-manifest.json"), "{}\n"); + writeFileSync(join(directory, tarball), "package bytes"); + await expect( + validateReleaseInventory(directory, tarball), + ).resolves.toEqual({ tarball }); + + writeFileSync(join(directory, ".extra"), "extra"); + await expect( + validateReleaseInventory(directory, tarball), + ).rejects.toThrow("only the manifest and package tarball"); + rmSync(join(directory, ".extra")); + + rmSync(join(directory, tarball)); + mkdirSync(join(directory, tarball)); + await expect( + validateReleaseInventory(directory, tarball), + ).rejects.toThrow("regular files"); + rmSync(join(directory, tarball), { recursive: true }); + + if (process.platform !== "win32") { + const target = join(root, "target.tgz"); + writeFileSync(target, "package bytes"); + symlinkSync(target, join(directory, tarball), "file"); + await expect( + validateReleaseInventory(directory, tarball), + ).rejects.toThrow("regular files"); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("removes generated outputs before building and records both digests", async () => { + const packageDirectory = join(process.cwd(), "packages", "sessions"); + const dist = join(packageDirectory, "dist"); + const buildInfo = join(packageDirectory, "tsconfig.tsbuildinfo"); + const root = mkdtempSync(join(tmpdir(), "sessions-release-pack-")); + const output = join(root, "release"); + try { + mkdirSync(dist, { recursive: true }); + writeFileSync(join(dist, "stale.js"), "stale output\n"); + writeFileSync(buildInfo, "stale build information\n"); + const result = await prepareRelease({ output }); + const prepared = result.manifest as { + package: { integrity: string; sha256: string; tarball: string }; + }; + expect(() => statSync(join(dist, "stale.js"))).toThrow(); + expect(prepared.package.sha256).toMatch(/^[0-9a-f]{64}$/u); + expect(prepared.package.integrity).toMatch( + /^sha512-[A-Za-z0-9+/]{86}==$/u, + ); + await expect( + validateReleaseInventory(output, prepared.package.tarball), + ).resolves.toEqual({ tarball: prepared.package.tarball }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, 120_000); }); describe("release source authentication", () => { @@ -291,20 +468,20 @@ describe("release source authentication", () => { 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); + run(git, ["tag", "--sign", "v0.1.1", "--message", "signed"], root); expect( validateReleaseTag({ root, - releaseTag: "v0.0.0", + releaseTag: "v0.1.1", expectedReleaseCommit: releaseCommit, }), - ).toEqual({ headCommit: releaseCommit, releaseTag: "v0.0.0" }); + ).toEqual({ headCommit: releaseCommit, releaseTag: "v0.1.1" }); - run(git, ["tag", "v0.0.1"], root); + run(git, ["tag", "v0.1.2"], root); expect(() => validateReleaseTag({ root, - releaseTag: "v0.0.1", + releaseTag: "v0.1.2", expectedReleaseCommit: releaseCommit, }), ).toThrow("annotated tag object"); @@ -316,7 +493,7 @@ describe("release source authentication", () => { "commit.gpgsign=false", "tag", "--annotate", - "v0.0.2", + "v0.1.3", "--message", "unsigned", ], @@ -325,16 +502,24 @@ describe("release source authentication", () => { expect(() => validateReleaseTag({ root, - releaseTag: "v0.0.2", + releaseTag: "v0.1.3", expectedReleaseCommit: releaseCommit, }), ).toThrow("not valid for an approved signer"); + + expect(() => + validateReleaseTag({ + root, + releaseTag: "v0.1.0", + expectedReleaseCommit: releaseCommit, + }), + ).toThrow("stable release tag"); } finally { rmSync(root, { recursive: true, force: true }); } }); - it("keeps broad preparation outside the OIDC-enabled publisher job", () => { + it("verifies the release source before preparation and isolates publication", () => { const workflow = readFileSync( join(process.cwd(), ".github", "workflows", "publish.yml"), "utf8", @@ -354,16 +539,80 @@ describe("release source authentication", () => { expect(prepare).not.toContain("id-token: write"); expect(publish).toContain("environment: npm-publish"); expect(publish).toContain("id-token: write"); - expect(publish).not.toContain("npm ci"); - expect(publish).not.toContain("npm install"); + + const prepareVerify = prepare.indexOf("- name: Verify the release source"); + const prepareCheckout = prepare.indexOf("uses: actions/checkout@"); + expect(prepareVerify).toBeGreaterThanOrEqual(0); + expect(prepareCheckout).toBeGreaterThan(prepareVerify); + expect(prepare.slice(0, prepareCheckout)).toContain( + "git init --quiet --bare", + ); + expect(prepare.slice(0, prepareCheckout)).toContain( + 'git -C "${repository}" verify-tag "${tag_ref}"', + ); + expect(prepare.slice(0, prepareCheckout)).toContain( + "merge-base --is-ancestor", + ); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(prepare).toContain("pnpm run release:check"); + expect(prepare).toContain("rm -rf -- packages/sessions/dist"); + expect(prepare).toContain( + "find packages/sessions -type f -name '*.tsbuildinfo'", + ); + expect(prepare).toContain("include-hidden-files: false"); + expect(prepare).toContain(".release/package-manifest.json"); + expect(prepare).toContain("steps.inventory.outputs.tarball"); + + expect(publish).not.toContain("actions/checkout@"); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("release:pack"); - expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("scripts/release-packages.mjs"); expect(publish).not.toContain("corepack"); expect(publish).not.toContain("pnpm run"); + expect(publish).toContain("git init --quiet --bare"); + expect(publish).toContain('git -C "${repository}" verify-tag'); + expect(publish).toContain("merge-base --is-ancestor"); + expect(publish).toContain( + 'const expectedNames = ["package-manifest.json", expectedTarball]', + ); + expect(publish).toContain("entry?.isFile() !== true"); + expect(publish).toContain("record.sha256"); + expect(publish).toContain("record.integrity"); + expect(publish).toContain("NPM_CONFIG_USERCONFIG"); + expect(publish).toContain("NPM_CONFIG_GLOBALCONFIG"); + expect(publish).toContain('"--provenance"'); + expect(publish).toContain('"--ignore-scripts"'); + expect(publish).toContain('"--registry"'); + expect(publish).toContain("spawnSync(process.execPath"); expect(prepare).toContain("npm install --global npm@11.18.0"); + expect(publish).toContain("npm install --global npm@11.18.0"); + expect(workflow.match(/git init --quiet --bare/gu)).toHaveLength(2); + expect( + workflow.match( + /RELEASE_TAG: \$\{\{ github\.event\.release\.tag_name \}\}/gu, + ), + ).toHaveLength(2); + expect( + workflow.match( + /RELEASE_PRERELEASE: \$\{\{ github\.event\.release\.prerelease \}\}/gu, + ), + ).toHaveLength(2); + expect( + workflow.match(/RELEASE_COMMIT: \$\{\{ github\.sha \}\}/gu), + ).toHaveLength(2); + expect( + workflow.match( + /RELEASE_ALLOWED_SIGNERS: \$\{\{ vars\.RELEASE_ALLOWED_SIGNERS \}\}/gu, + ), + ).toHaveLength(2); + expect( + workflow.match(/\[\[ "\$\{RELEASE_TAG\}" == "v0\.1\.0" \]\]/gu), + ).toHaveLength(2); + for (const script of workflowRunScripts(workflow)) { + expect(script).not.toContain("${{"); + } expect(workflow).not.toContain("workflow_dispatch"); - expect(workflow).not.toContain("NODE_AUTH_TOKEN"); expect(workflow).toContain("retention-days: 30"); }); @@ -379,6 +628,7 @@ describe("release source authentication", () => { expect(workflow).toContain( "pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86", ); + expect(workflow).toContain("pnpm run release:check"); }); }); From 10ba59283a49a8dcb12f1149ecbce3c3cfc9d7b7 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 12:58:50 -0500 Subject: [PATCH 2/7] Allow bundled npm versions in CI test --- test/release-packages.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 6332dbb..1e6930a 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -103,7 +103,7 @@ describe("release package metadata", () => { expect(source).toContain("command: process.execPath"); expect(source).toContain("shell: false"); expect(runNpm(["--version"], { capture: true }).stdout.trim()).toMatch( - /^11\.18\.0$/u, + /^\d+\.\d+\.\d+(?:-.+)?$/u, ); }); From 5880eb621017b697db280d951d5cbdfe6decea3b Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:22:58 -0500 Subject: [PATCH 3/7] Address automated release review --- .github/workflows/publish.yml | 193 +++++++++++++++++++++++++++++---- docs/RELEASING.md | 9 +- scripts/release-packages.d.mts | 3 +- scripts/release-packages.mjs | 32 +++++- test/release-packages.test.ts | 46 +++++++- 5 files changed, 245 insertions(+), 38 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 31ac769..99305a9 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -23,6 +23,8 @@ jobs: RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + REVIEWED_NPM_TARBALL: https://registry.npmjs.org/npm/-/npm-11.18.0.tgz + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== steps: - name: Verify the release source @@ -33,7 +35,9 @@ jobs: echo "::error::Only stable releases are supported" exit 1 fi - if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || + [[ ! "${RELEASE_TAG}" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || + [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then echo "::error::Release tag must be a supported stable version" exit 1 fi @@ -64,12 +68,27 @@ jobs: "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" tag_ref="refs/tags/${RELEASE_TAG}" - [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" == "tag" ]] - git -C "${repository}" verify-tag "${tag_ref}" - tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")" - [[ "${tag_commit}" == "${RELEASE_COMMIT}" ]] - git -C "${repository}" merge-base --is-ancestor \ - "${RELEASE_COMMIT}" refs/remotes/origin/main + if [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" != "tag" ]]; then + echo "::error::Release ref must be an annotated tag" + exit 1 + fi + if ! git -C "${repository}" verify-tag "${tag_ref}"; then + echo "::error::Release tag signature is not approved" + exit 1 + fi + if ! tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")"; then + echo "::error::Release tag commit could not be resolved" + exit 1 + fi + if [[ "${tag_commit}" != "${RELEASE_COMMIT}" ]]; then + echo "::error::Release tag does not match the event commit" + exit 1 + fi + if ! git -C "${repository}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main; then + echo "::error::Release commit is not contained in origin/main" + exit 1 + fi - name: Check out the verified release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -99,7 +118,36 @@ jobs: run: corepack enable - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 --ignore-scripts + shell: bash + run: | + set -euo pipefail + npm_directory="$(mktemp -d "${RUNNER_TEMP}/reviewed-npm.XXXXXX")" + trap 'rm -rf -- "${npm_directory}"' EXIT + npm_tarball="${npm_directory}/npm-11.18.0.tgz" + curl --fail --location --proto '=https' --tlsv1.2 \ + --output "${npm_tarball}" "${REVIEWED_NPM_TARBALL}" + node --input-type=module - "${npm_tarball}" <<'NODE' + import { createHash, timingSafeEqual } from "node:crypto"; + import { readFileSync } from "node:fs"; + + const actual = `sha512-${createHash("sha512") + .update(readFileSync(process.argv[2])) + .digest("base64")}`; + const expected = process.env.REVIEWED_NPM_INTEGRITY; + const actualBytes = Buffer.from(actual); + const expectedBytes = Buffer.from(expected); + if ( + actualBytes.length !== expectedBytes.length || + !timingSafeEqual(actualBytes, expectedBytes) + ) { + throw new Error("reviewed npm integrity does not match"); + } + NODE + npm install --global "${npm_tarball}" --ignore-scripts + if [[ "$(npm --version)" != "11.18.0" ]]; then + echo "::error::Reviewed npm version is not active" + exit 1 + fi - name: Install dependencies run: pnpm install --frozen-lockfile @@ -121,7 +169,8 @@ jobs: run: | set -euo pipefail rm -rf -- packages/sessions/dist - find packages/sessions -type f -name '*.tsbuildinfo' -delete + find . -path './node_modules' -prune -o \ + -type f -name '*.tsbuildinfo' -delete - name: Prepare and verify the release tarball run: pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release @@ -191,6 +240,8 @@ jobs: RELEASE_COMMIT: ${{ github.sha }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release + REVIEWED_NPM_TARBALL: https://registry.npmjs.org/npm/-/npm-11.18.0.tgz + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== steps: - name: Verify the release source @@ -201,7 +252,9 @@ jobs: echo "::error::Only stable releases are supported" exit 1 fi - if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]] || + [[ ! "${RELEASE_TAG}" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || + [[ "${RELEASE_TAG}" == "v0.1.0" ]]; then echo "::error::Release tag must be a supported stable version" exit 1 fi @@ -232,12 +285,27 @@ jobs: "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" tag_ref="refs/tags/${RELEASE_TAG}" - [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" == "tag" ]] - git -C "${repository}" verify-tag "${tag_ref}" - tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")" - [[ "${tag_commit}" == "${RELEASE_COMMIT}" ]] - git -C "${repository}" merge-base --is-ancestor \ - "${RELEASE_COMMIT}" refs/remotes/origin/main + if [[ "$(git -C "${repository}" cat-file -t "${tag_ref}")" != "tag" ]]; then + echo "::error::Release ref must be an annotated tag" + exit 1 + fi + if ! git -C "${repository}" verify-tag "${tag_ref}"; then + echo "::error::Release tag signature is not approved" + exit 1 + fi + if ! tag_commit="$(git -C "${repository}" rev-parse --verify "${tag_ref}^{commit}")"; then + echo "::error::Release tag commit could not be resolved" + exit 1 + fi + if [[ "${tag_commit}" != "${RELEASE_COMMIT}" ]]; then + echo "::error::Release tag does not match the event commit" + exit 1 + fi + if ! git -C "${repository}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main; then + echo "::error::Release commit is not contained in origin/main" + exit 1 + fi - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 @@ -246,7 +314,36 @@ jobs: package-manager-cache: false - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 --ignore-scripts + shell: bash + run: | + set -euo pipefail + npm_directory="$(mktemp -d "${RUNNER_TEMP}/reviewed-npm.XXXXXX")" + trap 'rm -rf -- "${npm_directory}"' EXIT + npm_tarball="${npm_directory}/npm-11.18.0.tgz" + curl --fail --location --proto '=https' --tlsv1.2 \ + --output "${npm_tarball}" "${REVIEWED_NPM_TARBALL}" + node --input-type=module - "${npm_tarball}" <<'NODE' + import { createHash, timingSafeEqual } from "node:crypto"; + import { readFileSync } from "node:fs"; + + const actual = `sha512-${createHash("sha512") + .update(readFileSync(process.argv[2])) + .digest("base64")}`; + const expected = process.env.REVIEWED_NPM_INTEGRITY; + const actualBytes = Buffer.from(actual); + const expectedBytes = Buffer.from(expected); + if ( + actualBytes.length !== expectedBytes.length || + !timingSafeEqual(actualBytes, expectedBytes) + ) { + throw new Error("reviewed npm integrity does not match"); + } + NODE + npm install --global "${npm_tarball}" --ignore-scripts + if [[ "$(npm --version)" != "11.18.0" ]]; then + echo "::error::Reviewed npm version is not active" + exit 1 + fi - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -385,13 +482,21 @@ jobs: "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_URL", "CI", + "COMSPEC", "HOME", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", "PATH", + "Path", + "PATHEXT", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", + "USERPROFILE", + "WINDIR", ]); const env = {}; for (const [name, value] of Object.entries(process.env)) { @@ -415,6 +520,34 @@ jobs: } return result; }; + const queryRegistryIntegrity = (spec) => { + const lookup = npm([ + "view", + spec, + "dist.integrity", + "--json", + "--registry", + REGISTRY, + ], true); + if (lookup.status === 0) { + const value = JSON.parse(lookup.stdout); + if (typeof value !== "string" || value.length === 0) { + throw new Error("registry version has no package integrity"); + } + return value; + } + const output = `${lookup.stdout}\n${lookup.stderr}`; + if (/\bE404\b/u.test(output)) return null; + throw new Error(`npm registry lookup failed:\n${output.trim()}`); + }; + const wait = (milliseconds) => { + Atomics.wait( + new Int32Array(new SharedArrayBuffer(4)), + 0, + 0, + milliseconds, + ); + }; try { const npmVersion = npm(["--version"]).stdout.trim(); @@ -422,18 +555,13 @@ jobs: throw new Error(`unexpected npm version ${npmVersion}`); } const spec = `${PACKAGE_NAME}@${version}`; - const lookup = npm(["view", spec, "dist.integrity", "--json", "--registry", REGISTRY], true); - if (lookup.status === 0) { - const publishedIntegrity = JSON.parse(lookup.stdout); + const publishedIntegrity = queryRegistryIntegrity(spec); + if (publishedIntegrity !== null) { if (!equal(record.integrity, publishedIntegrity)) { throw new Error("registry version has different package integrity"); } process.stdout.write(`Verified existing ${spec}; skipping.\n`); } else { - const lookupOutput = `${lookup.stdout}\n${lookup.stderr}`; - if (!/\bE404\b/u.test(lookupOutput)) { - throw new Error(`npm registry lookup failed:\n${lookupOutput.trim()}`); - } npm([ "publish", tarballPath, @@ -444,6 +572,23 @@ jobs: "--provenance", "--ignore-scripts", ]); + let confirmed = false; + for (let attempt = 0; attempt < 6; attempt += 1) { + const currentIntegrity = queryRegistryIntegrity(spec); + if ( + currentIntegrity !== null && + equal(record.integrity, currentIntegrity) + ) { + confirmed = true; + break; + } + if (attempt < 5) wait(2 ** attempt * 1000); + } + if (!confirmed) { + throw new Error( + `${spec} did not expose the prepared package integrity`, + ); + } } } finally { rmSync(runtimeRoot, { recursive: true, force: true }); diff --git a/docs/RELEASING.md b/docs/RELEASING.md index fdc0925..3c501fc 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -50,7 +50,8 @@ The release tool verifies that: - the root pins `pnpm@10.34.5` and `pnpm-lock.yaml` matches each dependency, including `peerDependencies`, to its own specifier and a resolved version that satisfies that specifier; -- pack and trusted publish still use reviewed `npm@11.18.0`; +- pack and trusted publish use reviewed `npm@11.18.0`, downloaded from its + fixed registry URL and matched to the repository-recorded SHA-512 value; - `@pegma/sessions` is public MIT-licensed ESM for Node 22 or newer; - runtime dependencies are pinned exactly; - repository metadata points to `pegma-dev/sessions`; @@ -156,7 +157,8 @@ The globally serialized preparation job: event commit, and `origin/main` ancestry; 3. checks out the already verified commit by exact SHA without persisted Git credentials; -4. uses Node 24.18.0, pnpm 10.34.5, and npm 11.18.0 for validation and pack; +4. uses Node 24.18.0, pnpm 10.34.5, and the SHA-512-matched npm 11.18.0 + tarball for validation and pack; 5. runs the full gate without OIDC publication authority; 6. removes generated build outputs, performs a clean build, smoke-tests the package, and records the exact tarball digests; and @@ -169,7 +171,8 @@ verification, and validates the two-file inventory, manifest schema, commit, version, and tarball digests using workflow-owned inline code. It runs the reviewed npm CLI from an empty temporary directory with empty private npm configuration files and an allowlisted environment, then publishes the -absolute tarball path with provenance and lifecycle scripts disabled. +absolute tarball path with provenance and lifecycle scripts disabled. After a +new publication, it waits for the registry to report the prepared integrity. If a hardened release fails, rerun its failed jobs against the unchanged tag: diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 47b9664..5af16c1 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -1,3 +1,5 @@ +import type { SpawnSyncReturns } from "node:child_process"; + export interface ReleasePackageDefinition { readonly directory: string; readonly name: string; @@ -132,4 +134,3 @@ export function inspectPreparedRegistry( export function publishPreparedRelease( options?: ReleaseCommandOptions, ): Promise; -import type { SpawnSyncReturns } from "node:child_process"; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index d3aef5b..ad78445 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -357,7 +357,11 @@ function hashTarball(bytes) { } export function isSupportedReleaseTag(releaseTag) { - return RELEASE_TAG.test(releaseTag) && releaseTag !== "v0.1.0"; + return ( + RELEASE_TAG.test(releaseTag) && + STABLE_SEMVER.test(releaseTag.slice(1)) && + releaseTag !== "v0.1.0" + ); } function exportTargets(value) { @@ -634,7 +638,19 @@ async function buildFromCleanOutputs(root, packageDirectory) { run(process.execPath, [typescript, "-b", "--clean"], { cwd: root }); await rm(join(packageDirectory, "dist"), { recursive: true, force: true }); await rm(join(packageDirectory, "tsconfig.tsbuildinfo"), { force: true }); - run(process.execPath, [typescript, "-b"], { cwd: root }); + await rm(join(root, "tsconfig.tsbuildinfo"), { force: true }); + runNpm(["--prefix", root, "run", "build"]); +} + +async function removeOwnedReleaseFile(path) { + try { + const details = await lstat(path); + if (details.isFile() || details.isSymbolicLink()) { + await rm(path, { force: true }); + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } } async function smokeTestTarball(tarball, manifest) { @@ -737,8 +753,16 @@ export async function prepareRelease(options = {}) { }, }; const manifestPath = join(output, "package-manifest.json"); - await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); - await validateReleaseInventory(output, basename(tarballPath)); + try { + await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); + await validateReleaseInventory(output, basename(tarballPath)); + } catch (error) { + await Promise.allSettled([ + removeOwnedReleaseFile(manifestPath), + removeOwnedReleaseFile(tarballPath), + ]); + throw error; + } return { manifestPath, manifest: prepared }; } diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 1e6930a..17a699b 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -54,7 +54,7 @@ function workflowRunScripts(workflow: string): string[] { const match = /^(\s*)run:\s*(.*)$/u.exec(lines[index] ?? ""); if (match === null) continue; const runValue = match[2] ?? ""; - if (runValue !== "|") { + if (!/^[|>][+-]?$/u.test(runValue)) { scripts.push(runValue); continue; } @@ -102,6 +102,7 @@ describe("release package metadata", () => { expect(source).toContain('"npm", "bin", "npm-cli.js"'); expect(source).toContain("command: process.execPath"); expect(source).toContain("shell: false"); + expect(source).toContain('runNpm(["--prefix", root, "run", "build"]);'); expect(runNpm(["--version"], { capture: true }).stdout.trim()).toMatch( /^\d+\.\d+\.\d+(?:-.+)?$/u, ); @@ -364,6 +365,8 @@ importers: expect(isSupportedReleaseTag("v0.1.0")).toBe(false); expect(isSupportedReleaseTag("v0.0.9")).toBe(false); expect(isSupportedReleaseTag("v01.2.3")).toBe(false); + expect(isSupportedReleaseTag("v1.01.0")).toBe(false); + expect(isSupportedReleaseTag("v0.1.01")).toBe(false); expect(isSupportedReleaseTag("v1.2.3-beta.1")).toBe(false); }); @@ -409,17 +412,20 @@ importers: const packageDirectory = join(process.cwd(), "packages", "sessions"); const dist = join(packageDirectory, "dist"); const buildInfo = join(packageDirectory, "tsconfig.tsbuildinfo"); + const rootBuildInfo = join(process.cwd(), "tsconfig.tsbuildinfo"); const root = mkdtempSync(join(tmpdir(), "sessions-release-pack-")); const output = join(root, "release"); try { mkdirSync(dist, { recursive: true }); writeFileSync(join(dist, "stale.js"), "stale output\n"); writeFileSync(buildInfo, "stale build information\n"); + writeFileSync(rootBuildInfo, "stale root build information\n"); const result = await prepareRelease({ output }); const prepared = result.manifest as { package: { integrity: string; sha256: string; tarball: string }; }; expect(() => statSync(join(dist, "stale.js"))).toThrow(); + expect(() => statSync(rootBuildInfo)).toThrow(); expect(prepared.package.sha256).toMatch(/^[0-9a-f]{64}$/u); expect(prepared.package.integrity).toMatch( /^sha512-[A-Za-z0-9+/]{86}==$/u, @@ -429,6 +435,9 @@ importers: ).resolves.toEqual({ tarball: prepared.package.tarball }); } finally { rmSync(root, { recursive: true, force: true }); + rmSync(dist, { recursive: true, force: true }); + rmSync(buildInfo, { force: true }); + rmSync(rootBuildInfo, { force: true }); } }, 120_000); }); @@ -553,13 +562,14 @@ describe("release source authentication", () => { expect(prepare.slice(0, prepareCheckout)).toContain( "merge-base --is-ancestor", ); + expect(prepare.slice(0, prepareCheckout)).toContain( + "::error::Release ref must be an annotated tag", + ); expect(prepare).toContain("ref: ${{ github.sha }}"); expect(prepare).toContain("persist-credentials: false"); expect(prepare).toContain("pnpm run release:check"); expect(prepare).toContain("rm -rf -- packages/sessions/dist"); - expect(prepare).toContain( - "find packages/sessions -type f -name '*.tsbuildinfo'", - ); + expect(prepare).toContain("-type f -name '*.tsbuildinfo' -delete"); expect(prepare).toContain("include-hidden-files: false"); expect(prepare).toContain(".release/package-manifest.json"); expect(prepare).toContain("steps.inventory.outputs.tarball"); @@ -585,8 +595,29 @@ describe("release source authentication", () => { expect(publish).toContain('"--ignore-scripts"'); expect(publish).toContain('"--registry"'); expect(publish).toContain("spawnSync(process.execPath"); - expect(prepare).toContain("npm install --global npm@11.18.0"); - expect(publish).toContain("npm install --global npm@11.18.0"); + expect(publish).toContain("for (let attempt = 0; attempt < 6"); + expect(publish).toContain("did not expose the prepared package integrity"); + expect(prepare).toContain('npm install --global "${npm_tarball}"'); + expect(publish).toContain('npm install --global "${npm_tarball}"'); + expect( + workflow.match(/npm-11\.18\.0\.tgz/gu)?.length, + ).toBeGreaterThanOrEqual(4); + expect( + workflow.match( + /sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW\/WJ\+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0\+vzXysCvAsepbMaBTwnrAD\+w==/gu, + ), + ).toHaveLength(2); + for (const name of [ + "COMSPEC", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", + "PATHEXT", + "USERPROFILE", + "WINDIR", + ]) { + expect(publish).toContain(`"${name}"`); + } expect(workflow.match(/git init --quiet --bare/gu)).toHaveLength(2); expect( workflow.match( @@ -609,6 +640,9 @@ describe("release source authentication", () => { expect( workflow.match(/\[\[ "\$\{RELEASE_TAG\}" == "v0\.1\.0" \]\]/gu), ).toHaveLength(2); + expect(workflowRunScripts('run: >-\n echo "${{ value }}"')).toEqual([ + ' echo "${{ value }}"', + ]); for (const script of workflowRunScripts(workflow)) { expect(script).not.toContain("${{"); } From 072b018fda74d348608b2ed70801790c0b17d1ad Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:26:11 -0500 Subject: [PATCH 4/7] Address follow-up release review --- .github/workflows/publish.yml | 35 ++++++++++++++++++++++++++++++---- docs/RELEASING.md | 12 ++++++------ docs/securityscan.md | 4 ++++ scripts/release-packages.d.mts | 4 ++++ scripts/release-packages.mjs | 2 +- test/release-packages.test.ts | 17 +++++++++++++++-- 6 files changed, 61 insertions(+), 13 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 99305a9..5c92731 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -181,7 +181,12 @@ jobs: run: | set -euo pipefail node --input-type=module <<'NODE' - import { lstatSync, readdirSync } from "node:fs"; + import { + copyFileSync, + lstatSync, + mkdirSync, + readdirSync, + } from "node:fs"; import { join } from "node:path"; const version = process.env.RELEASE_TAG.slice(1); @@ -202,10 +207,26 @@ jobs: throw new Error("prepared entries must be regular files"); } } + const uploadDirectory = "release-upload"; + mkdirSync(uploadDirectory); + for (const name of expected) { + copyFileSync(join(directory, name), join(uploadDirectory, name)); + } + const uploadEntries = readdirSync(uploadDirectory, { + withFileTypes: true, + }); + const uploadNames = uploadEntries.map(({ name }) => name).sort(); + if ( + uploadNames.length !== expected.length || + uploadNames.some((name, index) => name !== expected[index]) || + uploadEntries.some((entry) => !entry.isFile()) + ) { + throw new Error("upload file inventory is not exact"); + } NODE node --input-type=module >> "${GITHUB_OUTPUT}" <<'NODE' const version = process.env.RELEASE_TAG.slice(1); - process.stdout.write(`tarball=.release/pegma-sessions-${version}.tgz\n`); + process.stdout.write(`tarball=release-upload/pegma-sessions-${version}.tgz\n`); NODE - name: Upload the prepared release @@ -214,7 +235,7 @@ jobs: with: name: sessions-release-${{ github.run_id }} path: | - .release/package-manifest.json + release-upload/package-manifest.json ${{ steps.inventory.outputs.tarball }} if-no-files-found: error include-hidden-files: false @@ -430,7 +451,13 @@ jobs: throw new Error("prepared package manifest is invalid"); } const packedPaths = record.files.map(({ path }) => path); - for (const required of ["package.json", "README.md", "LICENSE"]) { + for (const required of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.d.ts", + "dist/index.js", + ]) { if (!packedPaths.includes(required)) { throw new Error(`package is missing ${required}`); } diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 3c501fc..64136a6 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -135,12 +135,12 @@ git switch --detach origin/main git config gpg.format ssh git config user.signingkey ~/.ssh/pegma-release-signing-key git config gpg.ssh.allowedSignersFile ~/.config/pegma/release-allowed-signers -git tag --sign v0.1.1 --message "Sessions v0.1.1" HEAD -git verify-tag v0.1.1 -git push origin refs/tags/v0.1.1 -git fetch origin tag v0.1.1 --force -git verify-tag v0.1.1 -gh release create v0.1.1 --verify-tag --title "@pegma/sessions v0.1.1" --notes-file RELEASE_NOTES.md +git tag --sign v0.2.0 --message "Sessions v0.2.0" HEAD +git verify-tag v0.2.0 +git push origin refs/tags/v0.2.0 +git fetch origin tag v0.2.0 --force +git verify-tag v0.2.0 +gh release create v0.2.0 --verify-tag --title "@pegma/sessions v0.2.0" --notes-file RELEASE_NOTES.md ``` Do not let `gh release create` create a tag. Never move or recreate a release diff --git a/docs/securityscan.md b/docs/securityscan.md index 99be15e..b4f0332 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -119,6 +119,10 @@ Review criteria include the hard rules in `AGENTS.md`: ### 3. Release pipeline — verified sound, two informational observations (Informational) +> Snapshot note: the source-line references and observations below describe +> the 2026-07-29 revision. See `docs/RELEASING.md` and the current workflow +> invariant tests for the maintained release path. + - **Severity:** Informational - **Files:** `.github/workflows/publish.yml`, `scripts/release-packages.mjs` - **Verified good:** diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 5af16c1..00d5d41 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -18,6 +18,10 @@ export interface ValidationOptions { export interface ReleaseCommandOptions extends ValidationOptions { readonly manifest?: string; readonly output?: string; + readonly smokeTest?: ( + tarball: string, + manifest: PublicPackageManifest, + ) => Promise; } export interface PublicPackageManifest { diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index ad78445..3a2efb2 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -733,7 +733,7 @@ export async function prepareRelease(options = {}) { ) { fail("tarball hashes do not match npm pack metadata"); } - await smokeTestTarball(tarballPath, manifest); + await (options.smokeTest ?? smokeTestTarball)(tarballPath, manifest); const prepared = { schemaVersion: 1, diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 17a699b..ad57349 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -420,7 +420,10 @@ importers: writeFileSync(join(dist, "stale.js"), "stale output\n"); writeFileSync(buildInfo, "stale build information\n"); writeFileSync(rootBuildInfo, "stale root build information\n"); - const result = await prepareRelease({ output }); + const result = await prepareRelease({ + output, + smokeTest: async () => undefined, + }); const prepared = result.manifest as { package: { integrity: string; sha256: string; tarball: string }; }; @@ -571,7 +574,10 @@ describe("release source authentication", () => { expect(prepare).toContain("rm -rf -- packages/sessions/dist"); expect(prepare).toContain("-type f -name '*.tsbuildinfo' -delete"); expect(prepare).toContain("include-hidden-files: false"); - expect(prepare).toContain(".release/package-manifest.json"); + expect(prepare).toContain("release-upload/package-manifest.json"); + expect(prepare).toContain( + "tarball=release-upload/pegma-sessions-${version}.tgz", + ); expect(prepare).toContain("steps.inventory.outputs.tarball"); expect(publish).not.toContain("actions/checkout@"); @@ -589,6 +595,8 @@ describe("release source authentication", () => { expect(publish).toContain("entry?.isFile() !== true"); expect(publish).toContain("record.sha256"); expect(publish).toContain("record.integrity"); + expect(publish).toContain('"dist/index.d.ts"'); + expect(publish).toContain('"dist/index.js"'); expect(publish).toContain("NPM_CONFIG_USERCONFIG"); expect(publish).toContain("NPM_CONFIG_GLOBALCONFIG"); expect(publish).toContain('"--provenance"'); @@ -619,6 +627,11 @@ describe("release source authentication", () => { expect(publish).toContain(`"${name}"`); } expect(workflow.match(/git init --quiet --bare/gu)).toHaveLength(2); + const verificationScripts = workflowRunScripts(workflow).filter((script) => + script.includes("release-verify.XXXXXX"), + ); + expect(verificationScripts).toHaveLength(2); + expect(verificationScripts[1]).toBe(verificationScripts[0]); expect( workflow.match( /RELEASE_TAG: \$\{\{ github\.event\.release\.tag_name \}\}/gu, From e23c891ce7c37ffa520a67e5e4ede31e65a59306 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:32:53 -0500 Subject: [PATCH 5/7] Fix release workflow context --- .github/workflows/publish.yml | 5 +++-- test/release-packages.test.ts | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5c92731..1b072ef 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -260,7 +260,6 @@ jobs: RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} - RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release REVIEWED_NPM_TARBALL: https://registry.npmjs.org/npm/-/npm-11.18.0.tgz REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== @@ -370,9 +369,11 @@ jobs: uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: sessions-release-${{ github.run_id }} - path: ${{ env.RELEASE_DIRECTORY }} + path: ${{ runner.temp }}/sessions-release/.release - name: Publish the prepared tarball + env: + RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release shell: bash run: | set -euo pipefail diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index ad57349..8b21954 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -581,6 +581,9 @@ describe("release source authentication", () => { expect(prepare).toContain("steps.inventory.outputs.tarball"); expect(publish).not.toContain("actions/checkout@"); + const publishSteps = publish.indexOf("\n steps:"); + expect(publishSteps).toBeGreaterThanOrEqual(0); + expect(publish.slice(0, publishSteps)).not.toContain("${{ runner."); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("release:pack"); expect(publish).not.toContain("scripts/release-packages.mjs"); @@ -599,6 +602,9 @@ describe("release source authentication", () => { expect(publish).toContain('"dist/index.js"'); expect(publish).toContain("NPM_CONFIG_USERCONFIG"); expect(publish).toContain("NPM_CONFIG_GLOBALCONFIG"); + expect(publish).toContain( + "RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release", + ); expect(publish).toContain('"--provenance"'); expect(publish).toContain('"--ignore-scripts"'); expect(publish).toContain('"--registry"'); From 3751790667bb81cf5b91002f8142137627277bf9 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:34:01 -0500 Subject: [PATCH 6/7] Preserve node modules during release cleanup --- .github/workflows/publish.yml | 2 +- test/release-packages.test.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1b072ef..c40e574 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -170,7 +170,7 @@ jobs: set -euo pipefail rm -rf -- packages/sessions/dist find . -path './node_modules' -prune -o \ - -type f -name '*.tsbuildinfo' -delete + -type f -name '*.tsbuildinfo' -exec rm -f -- {} + - name: Prepare and verify the release tarball run: pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 8b21954..1fce5f3 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -572,7 +572,9 @@ describe("release source authentication", () => { expect(prepare).toContain("persist-credentials: false"); expect(prepare).toContain("pnpm run release:check"); expect(prepare).toContain("rm -rf -- packages/sessions/dist"); - expect(prepare).toContain("-type f -name '*.tsbuildinfo' -delete"); + expect(prepare).toContain( + "-type f -name '*.tsbuildinfo' -exec rm -f -- {} +", + ); expect(prepare).toContain("include-hidden-files: false"); expect(prepare).toContain("release-upload/package-manifest.json"); expect(prepare).toContain( From 153c7c2c7744afc5af906a6d24c0599f6838a1f7 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:41:11 -0500 Subject: [PATCH 7/7] Keep reviewed npm steps aligned --- test/release-packages.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 1fce5f3..e892afa 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -640,6 +640,11 @@ describe("release source authentication", () => { ); expect(verificationScripts).toHaveLength(2); expect(verificationScripts[1]).toBe(verificationScripts[0]); + const reviewedNpmScripts = workflowRunScripts(workflow).filter((script) => + script.includes("reviewed-npm.XXXXXX"), + ); + expect(reviewedNpmScripts).toHaveLength(2); + expect(reviewedNpmScripts[1]).toBe(reviewedNpmScripts[0]); expect( workflow.match( /RELEASE_TAG: \$\{\{ github\.event\.release\.tag_name \}\}/gu,