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..c40e574 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,53 +18,143 @@ 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 }} + REVIEWED_NPM_TARBALL: https://registry.npmjs.org/npm/-/npm-11.18.0.tgz + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== 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}" =~ ^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 + 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}" + 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 + 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 + 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 + - name: Check release metadata + run: pnpm run release:check + - name: Check formatting run: pnpm run format:check @@ -74,22 +164,88 @@ jobs: - name: Run tests run: pnpm test + - name: Remove generated package outputs + shell: bash + run: | + set -euo pipefail + rm -rf -- packages/sessions/dist + find . -path './node_modules' -prune -o \ + -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 + - name: Check the prepared file inventory + id: inventory + shell: bash + run: | + set -euo pipefail + node --input-type=module <<'NODE' + import { + copyFileSync, + lstatSync, + mkdirSync, + 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"); + } + } + 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-upload/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-upload/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 +255,370 @@ 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 }} + REVIEWED_NPM_TARBALL: https://registry.npmjs.org/npm/-/npm-11.18.0.tgz + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== 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}" =~ ^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 + 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}" - - name: Set up Node.js and the npm registry + tag_ref="refs/tags/${RELEASE_TAG}" + 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 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false + - name: Use the reviewed npm release + 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 with: name: sessions-release-${{ github.run_id }} - path: .release + 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 + 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", + "dist/index.d.ts", + "dist/index.js", + ]) { + 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", + "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)) { + 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; + }; + 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, + ); + }; - - 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 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 { + npm([ + "publish", + tarballPath, + "--access", + "public", + "--registry", + REGISTRY, + "--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 }); + } + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 27cf755..64136a6 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`; @@ -60,7 +61,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 +119,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 ``` @@ -134,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 @@ -149,16 +150,29 @@ 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 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 +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. 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/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 e9e46a4..00d5d41 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; @@ -16,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 { @@ -54,6 +60,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 +84,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, diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 245bedf..3a2efb2 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,19 @@ 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) && + STABLE_SEMVER.test(releaseTag.slice(1)) && + releaseTag !== "v0.1.0" + ); +} + function exportTargets(value) { if (typeof value === "string") return [value]; if (value !== null && typeof value === "object" && !Array.isArray(value)) { @@ -270,12 +377,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 +458,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 +599,60 @@ 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 }); + 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) { const directory = await mkdtemp(join(tmpdir(), "sessions-release-smoke-")); try { @@ -506,9 +667,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 +702,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 ( @@ -564,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, @@ -575,6 +744,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 @@ -583,16 +753,28 @@ export async function prepareRelease(options = {}) { }, }; const manifestPath = join(output, "package-manifest.json"); - await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); + 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 }; } 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 +793,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 +869,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 +941,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 +963,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 +980,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..e892afa 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 (!/^[|>][+-]?$/u.test(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,78 @@ 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(source).toContain('runNpm(["--prefix", root, "run", "build"]);'); + expect(runNpm(["--version"], { capture: true }).stdout.trim()).toMatch( + /^\d+\.\d+\.\d+(?:-.+)?$/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 +357,92 @@ 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.01.0")).toBe(false); + expect(isSupportedReleaseTag("v0.1.01")).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 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, + smokeTest: async () => undefined, + }); + 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, + ); + await expect( + validateReleaseInventory(output, prepared.package.tarball), + ).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); }); describe("release source authentication", () => { @@ -291,20 +480,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 +505,7 @@ describe("release source authentication", () => { "commit.gpgsign=false", "tag", "--annotate", - "v0.0.2", + "v0.1.3", "--message", "unsigned", ], @@ -325,16 +514,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 +551,128 @@ 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.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( + "-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( + "tarball=release-upload/pegma-sessions-${version}.tgz", + ); + 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).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(prepare).toContain("npm install --global npm@11.18.0"); + 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('"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( + "RELEASE_DIRECTORY: ${{ runner.temp }}/sessions-release/.release", + ); + expect(publish).toContain('"--provenance"'); + expect(publish).toContain('"--ignore-scripts"'); + expect(publish).toContain('"--registry"'); + expect(publish).toContain("spawnSync(process.execPath"); + 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); + const verificationScripts = workflowRunScripts(workflow).filter((script) => + script.includes("release-verify.XXXXXX"), + ); + 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, + ), + ).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); + expect(workflowRunScripts('run: >-\n echo "${{ value }}"')).toEqual([ + ' echo "${{ value }}"', + ]); + 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 +688,7 @@ describe("release source authentication", () => { expect(workflow).toContain( "pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86", ); + expect(workflow).toContain("pnpm run release:check"); }); });