diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4b6105b..6d1b20e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,9 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + outputs: + artifact_id: ${{ steps.upload.outputs['artifact-id'] }} + manifest_digest: ${{ steps.manifest.outputs.digest }} env: RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} @@ -24,52 +27,84 @@ jobs: 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: Authenticate the release tag shell: bash run: | - if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::The release tag must be a stable vX.Y.Z tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9A-Fa-f]{40}$ ]]; then + echo "::error::The release event must identify one commit" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS//[[:space:]]/}" ]]; then echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" exit 1 fi - allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + + auth_root="$(mktemp -d "${RUNNER_TEMP}/audit-release-auth.XXXXXX")" + trap 'rm -rf "${auth_root}"' EXIT + repository="${auth_root}/repository.git" + allowed_signers="${auth_root}/allowed-signers" umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" - git config --local gpg.format ssh - git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare --quiet "${repository}" + git -C "${repository}" config gpg.format ssh + git -C "${repository}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${repository}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${repository}" fetch --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${repository}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${repository}" verify-tag "${RELEASE_TAG}" + tag_commit="$(git -C "${repository}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + [[ "${tag_commit}" == "${RELEASE_COMMIT,,}" ]] + git -C "${repository}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 - 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: Enable Corepack run: corepack enable - # The CLI that packs and publishes the release is fetched from the - # registry, so its bytes are verified against the reviewed integrity in - # scripts/release-packages.mjs before it is installed and trusted. - name: Use the reviewed npm release shell: bash env: REVIEWED_NPM_VERSION: 11.18.0 + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== run: | + set -euo pipefail tarball="${RUNNER_TEMP}/npm-${REVIEWED_NPM_VERSION}.tgz" curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ --output "${tarball}" \ "https://registry.npmjs.org/npm/-/npm-${REVIEWED_NPM_VERSION}.tgz" - node scripts/release-packages.mjs verify-npm --tarball "${tarball}" - npm install --global "${tarball}" + actual_integrity="$(node - "${tarball}" <<'NODE' + const { createHash } = require("node:crypto"); + const { readFileSync } = require("node:fs"); + const bytes = readFileSync(process.argv[2]); + process.stdout.write(`sha512-${createHash("sha512").update(bytes).digest("base64")}`); + NODE + )" + [[ "${actual_integrity}" == "${REVIEWED_NPM_INTEGRITY}" ]] + npm install --global "${tarball}" --ignore-scripts - name: Install dependencies run: pnpm install --frozen-lockfile @@ -83,8 +118,15 @@ jobs: - name: Run tests run: pnpm test - - 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: Prepare the release tarball + run: pnpm run release:pack -- --require-clean --require-main-ancestor --expected-release-commit "${RELEASE_COMMIT}" --output .release + + - name: Record the package manifest digest + id: manifest + shell: bash + run: | + digest="$(node -e 'const { createHash } = require("node:crypto"); const { readFileSync } = require("node:fs"); process.stdout.write(createHash("sha256").update(readFileSync(".release/package-manifest.json")).digest("hex"));')" + echo "digest=${digest}" >> "${GITHUB_OUTPUT}" - name: Upload the prepared release id: upload @@ -93,15 +135,114 @@ jobs: name: audit-release-${{ github.run_id }} path: .release/ 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}" + smoke: + needs: prepare + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + shell: bash + env: + REVIEWED_NPM_VERSION: 11.18.0 + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== + run: | + set -euo pipefail + tarball="${RUNNER_TEMP}/npm-${REVIEWED_NPM_VERSION}.tgz" + curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ + --output "${tarball}" \ + "https://registry.npmjs.org/npm/-/npm-${REVIEWED_NPM_VERSION}.tgz" + actual_integrity="$(node - "${tarball}" <<'NODE' + const { createHash } = require("node:crypto"); + const { readFileSync } = require("node:fs"); + const bytes = readFileSync(process.argv[2]); + process.stdout.write(`sha512-${createHash("sha512").update(bytes).digest("base64")}`); + NODE + )" + [[ "${actual_integrity}" == "${REVIEWED_NPM_INTEGRITY}" ]] + npm install --global "${tarball}" --ignore-scripts + + - name: Download the prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact_id }} + path: .release + + - name: Verify the prepared release + id: prepared + shell: bash + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + RELEASE_DIRECTORY: ${{ github.workspace }}/.release + run: | + node <<'NODE' + const { createHash } = require("node:crypto"); + const { appendFileSync, lstatSync, readFileSync, readdirSync } = require("node:fs"); + const { join } = require("node:path"); + const directory = process.env.RELEASE_DIRECTORY; + const manifestPath = join(directory, "package-manifest.json"); + const manifestBytes = readFileSync(manifestPath); + const manifestDigest = createHash("sha256").update(manifestBytes).digest("hex"); + if (manifestDigest !== process.env.EXPECTED_MANIFEST_DIGEST) { + throw new Error("prepared package manifest digest does not match preparation"); + } + const manifest = JSON.parse(manifestBytes); + const record = manifest.package; + if ( + manifest.schemaVersion !== 1 || + record?.name !== "@pegma/audit" || + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(record.version) || + !/^[0-9a-f]{64}$/.test(record.sha256) || + typeof record.integrity !== "string" + ) throw new Error("prepared package manifest is invalid"); + const expectedTarball = `pegma-audit-${record.version}.tgz`; + if (record.tarball !== expectedTarball) throw new Error("prepared tarball name is invalid"); + const entries = readdirSync(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + if (JSON.stringify(names) !== JSON.stringify([expectedTarball, "package-manifest.json"].sort())) { + throw new Error("prepared release inventory is invalid"); + } + for (const entry of entries) { + if (!entry.isFile() || entry.isSymbolicLink() || !lstatSync(join(directory, entry.name)).isFile()) { + throw new Error(`prepared release entry is not a regular file: ${entry.name}`); + } + } + const tarballPath = join(directory, expectedTarball); + const bytes = readFileSync(tarballPath); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (sha256 !== record.sha256 || integrity !== record.integrity) { + throw new Error("prepared tarball digest does not match its manifest"); + } + appendFileSync(process.env.GITHUB_OUTPUT, `tarball=${tarballPath}\nname=${record.name}\n`); + NODE + + - name: Import from a clean consumer + shell: bash + env: + PACKAGE_NAME: ${{ steps.prepared.outputs.name }} + PACKAGE_TARBALL: ${{ steps.prepared.outputs.tarball }} + run: | + set -euo pipefail + consumer="$(mktemp -d "${RUNNER_TEMP}/audit-release-smoke.XXXXXX")" + printf '%s\n' '{"name":"audit-release-smoke","private":true,"type":"module"}' > "${consumer}/package.json" + cd "${consumer}" + npm install --ignore-scripts --no-audit --no-fund --package-lock=false "${PACKAGE_TARBALL}" + node --input-type=module --eval "await import(${PACKAGE_NAME@Q})" publish: - needs: prepare + needs: [prepare, smoke] runs-on: ubuntu-latest environment: npm-publish permissions: @@ -109,27 +250,206 @@ jobs: id-token: write env: RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the exact release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 1 + - name: Authenticate the release tag + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::The release tag must be a stable vX.Y.Z tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9A-Fa-f]{40}$ ]]; then + echo "::error::The release event must identify one commit" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS//[[:space:]]/}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + exit 1 + fi + + auth_root="$(mktemp -d "${RUNNER_TEMP}/audit-release-auth.XXXXXX")" + trap 'rm -rf "${auth_root}"' EXIT + repository="${auth_root}/repository.git" + allowed_signers="${auth_root}/allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare --quiet "${repository}" + git -C "${repository}" config gpg.format ssh + git -C "${repository}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${repository}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${repository}" fetch --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${repository}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${repository}" verify-tag "${RELEASE_TAG}" + tag_commit="$(git -C "${repository}" rev-parse "refs/tags/${RELEASE_TAG}^{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 + shell: bash + env: + REVIEWED_NPM_VERSION: 11.18.0 + REVIEWED_NPM_INTEGRITY: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w== + run: | + set -euo pipefail + tarball="${RUNNER_TEMP}/npm-${REVIEWED_NPM_VERSION}.tgz" + curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ + --output "${tarball}" \ + "https://registry.npmjs.org/npm/-/npm-${REVIEWED_NPM_VERSION}.tgz" + actual_integrity="$(node - "${tarball}" <<'NODE' + const { createHash } = require("node:crypto"); + const { readFileSync } = require("node:fs"); + const bytes = readFileSync(process.argv[2]); + process.stdout.write(`sha512-${createHash("sha512").update(bytes).digest("base64")}`); + NODE + )" + [[ "${actual_integrity}" == "${REVIEWED_NPM_INTEGRITY}" ]] + npm install --global "${tarball}" --ignore-scripts + - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: audit-release-${{ github.run_id }} + artifact-ids: ${{ needs.prepare.outputs.artifact_id }} path: .release - - name: Publish the verified prepared tarball - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + - name: Verify the prepared release + id: prepared + shell: bash + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + RELEASE_DIRECTORY: ${{ github.workspace }}/.release + run: | + node <<'NODE' + const { createHash } = require("node:crypto"); + const { appendFileSync, lstatSync, readFileSync, readdirSync } = require("node:fs"); + const { join } = require("node:path"); + const directory = process.env.RELEASE_DIRECTORY; + const manifestPath = join(directory, "package-manifest.json"); + const manifestBytes = readFileSync(manifestPath); + const manifestDigest = createHash("sha256").update(manifestBytes).digest("hex"); + if (manifestDigest !== process.env.EXPECTED_MANIFEST_DIGEST) { + throw new Error("prepared package manifest digest does not match preparation"); + } + const manifest = JSON.parse(manifestBytes); + const record = manifest.package; + if ( + manifest.schemaVersion !== 1 || + manifest.gitCommit !== process.env.RELEASE_COMMIT.toLowerCase() || + manifest.releaseTag !== process.env.RELEASE_TAG || + record?.name !== "@pegma/audit" || + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(record.version) || + manifest.releaseTag !== `v${record.version}` || + !/^[0-9a-f]{64}$/.test(record.sha256) || + typeof record.integrity !== "string" + ) throw new Error("prepared package manifest is invalid"); + const expectedTarball = `pegma-audit-${record.version}.tgz`; + if (record.tarball !== expectedTarball) throw new Error("prepared tarball name is invalid"); + const entries = readdirSync(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + if (JSON.stringify(names) !== JSON.stringify([expectedTarball, "package-manifest.json"].sort())) { + throw new Error("prepared release inventory is invalid"); + } + for (const entry of entries) { + if (!entry.isFile() || entry.isSymbolicLink() || !lstatSync(join(directory, entry.name)).isFile()) { + throw new Error(`prepared release entry is not a regular file: ${entry.name}`); + } + } + const tarballPath = join(directory, expectedTarball); + const bytes = readFileSync(tarballPath); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (sha256 !== record.sha256 || integrity !== record.integrity) { + throw new Error("prepared tarball digest does not match its manifest"); + } + appendFileSync( + process.env.GITHUB_OUTPUT, + `tarball=${tarballPath}\nname=${record.name}\nversion=${record.version}\nintegrity=${record.integrity}\n`, + ); + NODE + + - name: Publish the prepared tarball + shell: bash + env: + PACKAGE_INTEGRITY: ${{ steps.prepared.outputs.integrity }} + PACKAGE_NAME: ${{ steps.prepared.outputs.name }} + PACKAGE_TARBALL: ${{ steps.prepared.outputs.tarball }} + PACKAGE_VERSION: ${{ steps.prepared.outputs.version }} + run: | + set -euo pipefail + publish_root="$(mktemp -d "${RUNNER_TEMP}/audit-publish.XXXXXX")" + publish_directory="${publish_root}/work" + config_directory="${publish_root}/config" + mkdir -p "${publish_directory}" "${config_directory}" + user_config="${config_directory}/user.npmrc" + global_config="${config_directory}/global.npmrc" + : > "${user_config}" + : > "${global_config}" + chmod 0600 "${user_config}" "${global_config}" + + allowed_env=( + "CI=${CI}" + "PATH=${PATH}" + "HOME=${HOME}" + "RUNNER_TEMP=${RUNNER_TEMP}" + "NPM_CONFIG_USERCONFIG=${user_config}" + "NPM_CONFIG_GLOBALCONFIG=${global_config}" + ) + while IFS='=' read -r name value; do + case "${name}" in + TMP*|SYSTEMROOT|GITHUB_*|ACTIONS_ID_TOKEN_*) allowed_env+=("${name}=${value}") ;; + esac + done < <(env) + npm_clean() { + env -i "${allowed_env[@]}" npm "$@" + } + + cd "${publish_directory}" + package_spec="${PACKAGE_NAME}@${PACKAGE_VERSION}" + view_error="${publish_root}/npm-view-error" + if view_output="$(npm_clean view "${package_spec}" dist.integrity --json --registry https://registry.npmjs.org/ 2>"${view_error}")"; then + registry_integrity="$(printf '%s' "${view_output}" | node -e 'const { readFileSync } = require("node:fs"); const value = JSON.parse(readFileSync(0, "utf8")); if (typeof value !== "string") process.exit(1); process.stdout.write(value);')" + if [[ "${registry_integrity}" != "${PACKAGE_INTEGRITY}" ]]; then + echo "::error::The registry version has different package integrity" + exit 1 + fi + echo "Verified existing ${package_spec}; skipping publish." + exit 0 + elif ! grep -Eq '(^|[^A-Za-z0-9_])E404([^A-Za-z0-9_]|$)' "${view_error}"; then + sed 's/^/::error::/' "${view_error}" + exit 1 + fi + + npm_clean publish "${PACKAGE_TARBALL}" \ + --tag latest \ + --registry https://registry.npmjs.org/ \ + --access public \ + --provenance \ + --ignore-scripts + + for attempt in 1 2 3 4 5 6; do + if view_output="$(npm_clean view "${package_spec}" dist.integrity --json --registry https://registry.npmjs.org/ 2>"${view_error}")"; then + registry_integrity="$(printf '%s' "${view_output}" | node -e 'const { readFileSync } = require("node:fs"); const value = JSON.parse(readFileSync(0, "utf8")); if (typeof value !== "string") process.exit(1); process.stdout.write(value);')" + if [[ "${registry_integrity}" == "${PACKAGE_INTEGRITY}" ]]; then exit 0; fi + fi + if [[ "${attempt}" -lt 6 ]]; then sleep "$((2 ** (attempt - 1)))"; fi + done + echo "::error::The published package integrity was not available from the registry" + exit 1 diff --git a/docs/RELEASING.md b/docs/RELEASING.md index a071e26..fab4945 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -38,19 +38,25 @@ The release workflow verifies that the tag: - is a stable annotated `vX.Y.Z` tag signed by an allowed signer; - matches the package version; -- points to the checkout and the GitHub release-event commit; and +- points to the GitHub release-event commit; and - is contained in `origin/main`. -Its preparation job has no OIDC permission. It installs dependencies with -the pinned pnpm, installs the reviewed npm version without dependency -caching, runs the full gate, builds and packs once, -smoke-tests the tarball from a clean consumer, records its SHA-1 and SHA-512 -integrity, and uploads the exact prepared artifact. - -Only the `npm-publish` job receives `id-token: write`. It installs no -dependencies and does not download pnpm. It invokes the publish helper with -`node`, verifies the prepared manifest and tarball hashes against the -release commit, and publishes that tarball with npm provenance. +The preparation job authenticates the tag in a temporary bare repository +before checkout or dependency installation. It then checks out the immutable +release-event commit without retained credentials, installs dependencies with +the pinned pnpm, installs the reviewed npm bytes, runs the full gate, and +builds and packs once. The packed manifest is checked against the reviewed +source manifest, and the output is sealed as exactly one manifest and one +tarball before upload. A separate job downloads that sealed artifact and +imports it from a clean consumer without OIDC permission. + +Only the `npm-publish` job receives `id-token: write`. It performs no checkout, +installs no project dependencies, and does not download pnpm. It authenticates +the tag again in a fresh bare repository, installs the reviewed npm bytes, +downloads the prepared artifact by its upload id, and verifies the preparation +manifest digest, exact two-file inventory, release commit, and tarball SHA-256 +and SHA-512. Registry lookup and publication run from a fresh empty directory +with empty npm configuration files and a minimal environment. ## Safe retry diff --git a/packages/audit/src/index.test.ts b/packages/audit/src/index.test.ts index 7f4c6b7..edfb716 100644 --- a/packages/audit/src/index.test.ts +++ b/packages/audit/src/index.test.ts @@ -1,4 +1,5 @@ import { createMemoryStore, defineCollection } from "@pegma/storage-core"; +import { runInNewContext } from "node:vm"; import { describe, expect, it } from "vitest"; import { @@ -98,6 +99,21 @@ const event = (overrides: Partial = {}): AuditEvent => ...overrides, }); +const rawEvent = (overrides: Partial = {}): AuditEvent => ({ + id: "evt_1", + occurredAt: "2026-07-26T12:00:00.000Z", + actor: { kind: "principal", principalId: "prn_admin" }, + action: "account.member.added", + subject: "mem_1", + ...overrides, +}); + +const nullPrototypeDetails = (): AuditDetails => { + const details = Object.create(null) as AuditDetails; + (details as Record)["role"] = "support"; + return details; +}; + describe("the event shape", () => { it("survives a round trip through a flat record", () => { const original = event({ @@ -129,6 +145,89 @@ describe("the event shape", () => { ).toThrow(/details.nested/); }); + it.each([ + ["null", null], + ["array", []], + ["string", "support"], + ["number", 2], + ["boolean", true], + ["function", () => undefined], + ["symbol", Symbol("detail")], + ["date", new Date("2026-07-26T12:00:00.000Z")], + ["regular expression", /detail/u], + ["map", new Map()], + ["set", new Set()], + ])( + "rejects a %s details container at every write entry point", + async (_, value) => { + const collection = records(); + const candidate = rawEvent({ + id: `evt_invalid_${String(_)}`, + details: value as unknown as AuditDetails, + }); + + expect(() => auditEvent(candidate)).toThrow( + /details must be a plain object/, + ); + expect(() => encodeAuditEvent(candidate)).toThrow( + /details must be a plain object/, + ); + expect(() => audit.action(candidate)).toThrow( + /details must be a plain object/, + ); + await expect(audit.append(collection, candidate)).rejects.toThrow( + /details must be a plain object/, + ); + expect(await audit.history(collection, PARTITION)).toEqual([]); + }, + ); + + it("accepts a null-prototype details bag at every write entry point", async () => { + const collection = records(); + const direct = rawEvent({ + id: "evt_null_prototype_direct", + details: nullPrototypeDetails(), + }); + const encoded = encodeAuditEvent( + rawEvent({ + id: "evt_null_prototype_encoded", + details: nullPrototypeDetails(), + }), + ); + + expect(auditEvent(rawEvent({ details: {} })).details).toEqual({}); + expect(auditEvent(direct).details).toEqual({ role: "support" }); + expect(encoded["auditDetails"]).toBe('{"role":"support"}'); + await expect( + collection.transact(PARTITION, [ + audit.action( + rawEvent({ + id: "evt_null_prototype_action", + details: nullPrototypeDetails(), + }), + ), + ]), + ).resolves.toMatchObject({ committed: true }); + await expect( + audit.append( + collection, + rawEvent({ + id: "evt_null_prototype_append", + details: nullPrototypeDetails(), + }), + ), + ).resolves.toMatchObject({ appended: true }); + expect(await audit.history(collection, PARTITION)).toHaveLength(2); + }); + + it("accepts an ordinary details bag from another realm", () => { + const details = runInNewContext('({ role: "support" })') as AuditDetails; + + expect(auditEvent(rawEvent({ details })).details).toEqual({ + role: "support", + }); + }); + it("rejects a timestamp only Date.parse would accept", () => { // `Date.parse` accepts implementation-defined formats, so it cannot be the // whole check: the value is kept forever exactly as it was submitted, and @@ -250,7 +349,9 @@ describe("an audit action inside the caller's transaction", () => { // action is perfectly valid on its own, and must still not land. const outcome = await collection.transact(PARTITION, [ { action: "insert", value: member }, - audit.action(event({ id: "evt_orphan" })), + audit.action( + rawEvent({ id: "evt_orphan", details: nullPrototypeDetails() }), + ), ]); expect(outcome).toMatchObject({ committed: false, reason: "exists" }); diff --git a/packages/audit/src/index.ts b/packages/audit/src/index.ts index 100664a..da60793 100644 --- a/packages/audit/src/index.ts +++ b/packages/audit/src/index.ts @@ -224,7 +224,31 @@ function requireSequence(value: number): number { return value; } +const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object); + +function isPlainDetailsContainer(value: unknown): value is AuditDetails { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const prototype = Object.getPrototypeOf(value); + if (prototype === null) return true; + if ( + Object.getPrototypeOf(prototype) !== null || + !Object.prototype.hasOwnProperty.call(prototype, "constructor") + ) { + return false; + } + const constructor = (prototype as { constructor: unknown }).constructor; + return ( + typeof constructor === "function" && + Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE + ); +} + function requireDetails(details: AuditDetails): AuditDetails { + if (!isPlainDetailsContainer(details)) { + throw new AuditError("details must be a plain object"); + } const copied: Record = {}; for (const key of Object.keys(details).sort()) { const value = details[key]; diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index dc038bd..498888b 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -22,9 +22,26 @@ export interface ReleaseCommandOptions extends ValidationOptions { export interface PublicPackageManifest { readonly name: string; readonly version: string; + readonly dependencies?: Readonly>; + readonly publishConfig?: Readonly>; readonly [key: string]: unknown; } +export interface PreparedReleaseManifest { + readonly schemaVersion: 1; + readonly gitCommit: string; + readonly releaseTag: string | null; + readonly package: { + readonly name: string; + readonly version: string; + readonly tarball: string; + readonly integrity: string; + readonly sha256: string; + readonly shasum: string; + readonly files: readonly { readonly path: string; readonly size: number }[]; + }; +} + export interface ValidationResult { readonly root: string; readonly manifest: PublicPackageManifest; @@ -76,6 +93,25 @@ export function findInstallTimeScript( export function verifyReviewedNpmTarball(bytes: Uint8Array | string): string; +export function validatePackageManifest( + manifest: PublicPackageManifest, + options?: { + readonly label?: string; + readonly expectedName?: string; + readonly expectedVersion?: string; + }, +): PublicPackageManifest; + +export function comparePackedManifest( + source: PublicPackageManifest, + packed: PublicPackageManifest, +): void; + +export function validateReleaseInventory( + directory: string, + expectedTarball: string, +): Promise; + export function parseArguments( arguments_: readonly string[], ): ReleaseCommandOptions; @@ -97,7 +133,7 @@ export function decidePublication( export function prepareRelease( options?: ReleaseCommandOptions, -): Promise<{ manifestPath: string; manifest: unknown }>; +): Promise<{ manifestPath: string; manifest: PreparedReleaseManifest }>; export function publishPreparedRelease( options?: ReleaseCommandOptions, diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index c3a3659..d669c02 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -2,17 +2,16 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; import { existsSync } from "node:fs"; import { - mkdtemp, + lstat, mkdir, readFile, readdir, - rm, stat, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { isDeepStrictEqual } from "node:util"; const PACKAGE = { directory: "audit", @@ -42,6 +41,40 @@ const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; * here instead, where they belong. */ const INSTALL_TIME_SCRIPTS = ["preinstall", "install", "postinstall"]; +const DEPENDENCY_FIELDS = [ + "dependencies", + "optionalDependencies", + "peerDependencies", +]; +const RELEASE_MANIFEST_FIELDS = [ + "name", + "version", + "private", + "description", + "license", + "type", + "sideEffects", + "publishConfig", + "files", + "exports", + "imports", + "main", + "module", + "types", + "typings", + "bin", + "engines", + "os", + "cpu", + "repository", + "dependencies", + "optionalDependencies", + "peerDependencies", + "peerDependenciesMeta", + "bundledDependencies", + "bundleDependencies", + "scripts", +]; export const RELEASE_PACKAGES = [PACKAGE]; @@ -156,10 +189,15 @@ function gitCommand() { 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")}`, }; } +function packageTarballName(name, version) { + return `${name.slice(1).replace("/", "-")}-${version}.tgz`; +} + /** * Confirms a downloaded npm CLI tarball is the reviewed one, before it is * installed and used to build the release. @@ -390,47 +428,71 @@ export function assertPnpmLockfileSynchronized( } } -export async function validateRepository(options = {}) { - const root = resolve(options.root ?? defaultRoot()); - const rootManifest = await readJson(join(root, "package.json")); - const packageDirectory = join(root, "packages", PACKAGE.directory); - const manifest = await readJson(join(packageDirectory, "package.json")); - const lockfile = await readFile(join(root, "pnpm-lock.yaml"), "utf8"); - - if ( - rootManifest.private !== true || - rootManifest.packageManager !== `pnpm@${REVIEWED_PNPM_VERSION}` - ) { - fail(`the private root must pin pnpm@${REVIEWED_PNPM_VERSION}`); +function isPlainRecord(value) { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return false; } + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +export function validatePackageManifest(manifest, options = {}) { + const label = options.label ?? PACKAGE.name; + const expectedName = options.expectedName ?? PACKAGE.name; + const expectedVersion = options.expectedVersion; if ( - manifest.name !== PACKAGE.name || + !isPlainRecord(manifest) || + manifest.name !== expectedName || !STABLE_SEMVER.test(manifest.version) || + (expectedVersion !== undefined && manifest.version !== expectedVersion) || manifest.private === true || manifest.license !== "MIT" || manifest.type !== "module" || - manifest.publishConfig?.access !== "public" || manifest.engines?.node !== ">=22" || manifest.repository?.type !== "git" || manifest.repository?.url !== REPOSITORY_URL || manifest.repository?.directory !== `packages/${PACKAGE.directory}` ) { - fail(`${PACKAGE.name} has invalid public package metadata`); + fail(`${label} has invalid public package metadata`); + } + if ( + !isPlainRecord(manifest.publishConfig) || + !isDeepStrictEqual(Object.keys(manifest.publishConfig).sort(), [ + "access", + ]) || + manifest.publishConfig.access !== "public" + ) { + fail(`${label} has invalid publish configuration`); } if ( !Array.isArray(manifest.files) || manifest.files.length === 0 || - manifest.files.some((entry) => !entry.startsWith("dist/")) || + manifest.files.some( + (entry) => typeof entry !== "string" || !entry.startsWith("dist/"), + ) || typeof manifest.scripts?.prepack !== "string" || !manifest.scripts.prepack.includes("build") ) { - fail(`${PACKAGE.name} has an unsafe package allowlist or prepack`); + fail(`${label} has an invalid package allowlist or prepack`); } const installScript = findInstallTimeScript(manifest.scripts); if (installScript !== null) { - fail( - `${PACKAGE.name} must not define the install-time script ${installScript}`, - ); + fail(`${label} must not define the install-time script ${installScript}`); + } + for (const field of DEPENDENCY_FIELDS) { + const dependencies = manifest[field]; + if (field === "dependencies" && !isPlainRecord(dependencies)) { + fail(`${label} dependencies must be an object`); + } + if (dependencies === undefined) continue; + if (!isPlainRecord(dependencies)) { + fail(`${label} ${field} must be an object`); + } + for (const [name, version] of Object.entries(dependencies)) { + if (name.startsWith("@pegma/") && !STABLE_SEMVER.test(version)) { + fail(`${label} must pin ${name} to an exact stable version`); + } + } } const targets = exportTargets(manifest.exports); if ( @@ -442,8 +504,33 @@ export async function validateRepository(options = {}) { target.includes(".."), ) ) { - fail(`${PACKAGE.name} exports must point into dist`); + fail(`${label} exports must point into dist`); + } + return manifest; +} + +export function comparePackedManifest(source, packed) { + for (const field of RELEASE_MANIFEST_FIELDS) { + if (!isDeepStrictEqual(packed[field], source[field])) { + fail(`packed package manifest changed ${field}`); + } + } +} + +export async function validateRepository(options = {}) { + const root = resolve(options.root ?? defaultRoot()); + const rootManifest = await readJson(join(root, "package.json")); + const packageDirectory = join(root, "packages", PACKAGE.directory); + const manifest = await readJson(join(packageDirectory, "package.json")); + const lockfile = await readFile(join(root, "pnpm-lock.yaml"), "utf8"); + + if ( + rootManifest.private !== true || + rootManifest.packageManager !== `pnpm@${REVIEWED_PNPM_VERSION}` + ) { + fail(`the private root must pin pnpm@${REVIEWED_PNPM_VERSION}`); } + validatePackageManifest(manifest); await stat(join(packageDirectory, "README.md")); await stat(join(packageDirectory, "LICENSE")); assertPnpmLockfileSynchronized( @@ -533,39 +620,31 @@ function verifyPackedFiles(manifest, files) { } } -async function smokeTestTarball(tarball, manifest) { - const directory = await mkdtemp(join(tmpdir(), "audit-release-smoke-")); +function readPackedPackageManifest(tarball) { + const result = run("tar", ["-xOf", tarball, "package/package.json"], { + capture: true, + }); try { - await writeFile( - join(directory, "package.json"), - '{"name":"audit-release-smoke","private":true,"type":"module"}\n', - ); - runNpm( - [ - "install", - "--ignore-scripts", - "--no-audit", - "--no-fund", - "--package-lock=false", - tarball, - ], - { cwd: directory, capture: true }, - ); - for (const key of Object.keys(manifest.exports)) { - const specifier = - key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`; - run( - process.execPath, - [ - "--input-type=module", - "--eval", - `await import(${JSON.stringify(specifier)})`, - ], - { cwd: directory, capture: true }, - ); + return JSON.parse(result.stdout); + } catch (error) { + throw new Error("packed package manifest is not valid JSON", { + cause: error, + }); + } +} + +export async function validateReleaseInventory(directory, expectedTarball) { + const expected = ["package-manifest.json", expectedTarball].sort(); + const entries = await readdir(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + if (!isDeepStrictEqual(names, expected)) { + fail("release output must contain only its manifest and tarball"); + } + for (const entry of entries) { + const details = await lstat(join(directory, entry.name)); + if (!entry.isFile() || entry.isSymbolicLink() || !details.isFile()) { + fail(`release output entry must be a regular file: ${entry.name}`); } - } finally { - await rm(directory, { recursive: true, force: true }); } } @@ -588,16 +667,26 @@ export async function prepareRelease(options = {}) { { cwd: root, capture: true }, ); const [packed] = JSON.parse(result.stdout); + const expectedTarball = packageTarballName(manifest.name, manifest.version); if ( packed?.name !== manifest.name || packed?.version !== manifest.version || - typeof packed.filename !== "string" || + packed.filename !== expectedTarball || + typeof packed.integrity !== "string" || + typeof packed.shasum !== "string" || !Array.isArray(packed.files) ) { fail("npm pack returned invalid metadata"); } verifyPackedFiles(manifest, packed.files); const tarballPath = join(output, basename(packed.filename)); + const packedManifest = readPackedPackageManifest(tarballPath); + validatePackageManifest(packedManifest, { + label: "packed package manifest", + expectedName: manifest.name, + expectedVersion: manifest.version, + }); + comparePackedManifest(manifest, packedManifest); const hashes = hashTarball(await readFile(tarballPath)); if ( !safeEqual(hashes.integrity, packed.integrity) || @@ -605,8 +694,6 @@ export async function prepareRelease(options = {}) { ) { fail("tarball hashes do not match npm pack metadata"); } - await smokeTestTarball(tarballPath, manifest); - const prepared = { schemaVersion: 1, gitCommit, @@ -616,6 +703,7 @@ export async function prepareRelease(options = {}) { version: manifest.version, tarball: basename(tarballPath), integrity: hashes.integrity, + sha256: hashes.sha256, shasum: hashes.shasum, files: packed.files .map(({ path, size }) => ({ path, size })) @@ -624,6 +712,7 @@ 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 }; } @@ -690,6 +779,7 @@ async function verifyPreparedManifest(path) { record?.name !== PACKAGE.name || !STABLE_SEMVER.test(record.version) || typeof record.integrity !== "string" || + !/^[0-9a-f]{64}$/u.test(record.sha256) || typeof record.shasum !== "string" || !Array.isArray(record.files) ) { @@ -702,18 +792,18 @@ async function verifyPreparedManifest(path) { if (!safeEqual(currentCommit, prepared.gitCommit)) { fail("prepared package manifest commit does not match the checkout"); } - const expectedTarball = `${PACKAGE.name - .slice(1) - .replace("/", "-")}-${record.version}.tgz`; + const expectedTarball = packageTarballName(PACKAGE.name, record.version); if (record.tarball !== expectedTarball) fail("prepared tarball name is invalid"); const tarball = resolve(dirname(path), record.tarball); if (dirname(tarball) !== resolve(dirname(path))) { fail("prepared tarball must be beside the package manifest"); } + await validateReleaseInventory(dirname(path), record.tarball); 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"); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 6bb07e8..fd603cf 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,18 +1,29 @@ import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { + existsSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { RELEASE_PACKAGES, REVIEWED_NPM, REVIEWED_PNPM, assertPnpmLockfileSynchronized, + comparePackedManifest, decidePublication, findInstallTimeScript, parseArguments, resolveNpmCli, resolvedVersionSatisfies, + validatePackageManifest, + validateReleaseInventory, validateReleaseTag, validateRepository, verifyReviewedNpmTarball, @@ -36,6 +47,18 @@ function run(command: string, arguments_: string[], cwd?: string): string { }).trim(); } +function corepackPnpmCli(): string { + const nodeDirectory = dirname(process.execPath); + const candidates = [ + join(nodeDirectory, "node_modules/corepack/dist/pnpm.js"), + resolve(nodeDirectory, "../lib/node_modules/corepack/dist/pnpm.js"), + ]; + const found = candidates.find(existsSync); + if (found === undefined) + throw new Error("could not resolve Corepack's pnpm CLI"); + return found; +} + describe("release package metadata", () => { it("accepts npm's cross-platform argument separator", () => { expect(parseArguments(["--", "--output", ".release"])).toEqual({ @@ -82,7 +105,11 @@ describe("release package metadata", () => { "utf8", ); expect(workflow).toContain(`REVIEWED_NPM_VERSION: ${REVIEWED_NPM.version}`); - expect(workflow).toContain("verify-npm --tarball"); + expect(workflow).toContain( + `REVIEWED_NPM_INTEGRITY: ${REVIEWED_NPM.integrity}`, + ); + expect(workflow).toContain('createHash("sha512")'); + expect(workflow).not.toContain("verify-npm --tarball"); // Installing the registry spec directly would trust whatever bytes the // registry serves for the tool that packs and publishes the release. expect(workflow).not.toContain(`npm@${REVIEWED_NPM.version}`); @@ -104,6 +131,59 @@ describe("release package metadata", () => { } }); + it("revalidates the manifest produced by npm pack", async () => { + const { manifest } = await validateRepository(); + expect(() => + validatePackageManifest({ + ...manifest, + publishConfig: { access: "public", registry: "https://example.test" }, + }), + ).toThrow("publish configuration"); + expect(() => + comparePackedManifest(manifest, { + ...manifest, + dependencies: { ...manifest.dependencies, "@pegma/spine": "0.1.2" }, + }), + ).toThrow("changed dependencies"); + }); + + it("seals a packed release as one manifest and one tarball", async () => { + const output = mkdtempSync(join(tmpdir(), "audit-release-output-")); + try { + run( + process.execPath, + [corepackPnpmCli(), "run", "release:pack", "--", "--output", output], + process.cwd(), + ); + const manifestPath = join(output, "package-manifest.json"); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { + package: { tarball: string; sha256: string; integrity: string }; + }; + const names = readdirSync(output).sort(); + expect(names).toEqual( + [manifest.package.tarball, "package-manifest.json"].sort(), + ); + await expect( + validateReleaseInventory(output, manifest.package.tarball), + ).resolves.toBeUndefined(); + const bytes = readFileSync(join(output, manifest.package.tarball)); + expect(manifest.package.sha256).toBe( + createHash("sha256").update(bytes).digest("hex"), + ); + expect(manifest.package.integrity).toBe( + `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + ); + expect(manifestPath).toBe(join(output, "package-manifest.json")); + + writeFileSync(join(output, ".npmrc"), "registry=https://example.test\n"); + await expect( + validateReleaseInventory(output, manifest.package.tarball), + ).rejects.toThrow("only its manifest and tarball"); + } finally { + rmSync(output, { recursive: true, force: true }); + } + }); + it("matches each lockfile dependency to its own specifier and version", () => { const lockfile = `lockfileVersion: '9.0' @@ -271,7 +351,7 @@ describe("release source authentication", () => { } }); - it("keeps preparation outside the OIDC-enabled publisher job", () => { + it("keeps preparation and smoke testing outside the OIDC-enabled job", () => { const workflow = readFileSync( join(process.cwd(), ".github", "workflows", "publish.yml"), "utf8", @@ -282,22 +362,58 @@ describe("release source authentication", () => { const header = workflow.slice(0, jobsIndex); const jobs = workflow.slice(jobsIndex + jobsMarker.length); const prepareStart = jobs.indexOf(" prepare:"); + const smokeStart = jobs.indexOf("\n smoke:"); const publishStart = jobs.indexOf("\n publish:"); expect(header).not.toContain("id-token: write"); expect(prepareStart).toBeGreaterThanOrEqual(0); - expect(publishStart).toBeGreaterThan(prepareStart); - const prepare = jobs.slice(prepareStart, publishStart); + expect(smokeStart).toBeGreaterThan(prepareStart); + expect(publishStart).toBeGreaterThan(smokeStart); + const prepare = jobs.slice(prepareStart, smokeStart); + const smoke = jobs.slice(smokeStart, publishStart); const publish = jobs.slice(publishStart); expect(prepare).not.toContain("id-token: write"); + expect(smoke).not.toContain("id-token: write"); expect(publish).toContain("id-token: write"); - expect(publish).not.toContain("npm ci"); - expect(publish).not.toContain("npm install"); expect(publish).not.toContain("pnpm"); expect(publish).not.toContain("corepack"); - expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).not.toContain("scripts/release-packages.mjs"); + expect(publish).toContain("needs: [prepare, smoke]"); + expect(smoke).toContain("Import from a clean consumer"); + expect(workflow).toContain("include-hidden-files: false"); + expect(workflow).toContain("manifest_digest:"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).toContain("retention-days: 30"); }); + + it("authenticates release input before checkout and keeps job env expressions portable", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const firstAuthentication = workflow.indexOf( + "- name: Authenticate the release tag", + ); + const firstCheckout = workflow.indexOf("uses: actions/checkout@"); + expect(firstAuthentication).toBeGreaterThanOrEqual(0); + expect(firstCheckout).toBeGreaterThan(firstAuthentication); + expect(workflow).toContain("git init --bare"); + expect(workflow).toContain('git -C "${repository}" verify-tag'); + expect(workflow).toContain("merge-base --is-ancestor"); + expect(workflow).toContain("ref: ${{ github.sha }}"); + expect(workflow).toContain("persist-credentials: false"); + expect(workflow).toContain('[[ "${RELEASE_PRERELEASE}" != "false" ]]'); + expect(workflow).toContain("^[0-9A-Fa-f]{40}$"); + + const jobEnvBlocks = [ + ...workflow.matchAll(/^ env:\n((?:^ [^\n]*\n)+)/gmu), + ].map((match) => match[1]); + expect(jobEnvBlocks.length).toBeGreaterThan(0); + for (const block of jobEnvBlocks) { + expect(block).not.toContain("${{ runner."); + expect(block).not.toContain("${{ steps."); + } + }); }); describe("retry-safe publication", () => {