diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f14c224..e16013e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,11 +37,14 @@ jobs: run: corepack enable - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ - 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 1366196..d53f9e4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,67 +18,126 @@ jobs: prepare: runs-on: ubuntu-latest env: + CI: "1" RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_REPOSITORY: https://github.com/${{ github.repository }}.git + RELEASE_TAG: ${{ github.event.release.tag_name }} steps: - - name: Check out the release tag + - name: Verify the release ref + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases can be prepared" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.(0|[1-9][0-9]*))\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::The release tag is not a stable package tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The release commit is not an exact object ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers-${GITHUB_RUN_ID}" + scratch="$(mktemp -d "${RUNNER_TEMP}/mail-release-git.XXXXXX")" + trap 'rm -rf -- "${scratch}"' EXIT + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare "${scratch}" + git -C "${scratch}" remote add origin "${RELEASE_REPOSITORY}" + git -C "${scratch}" config gpg.format ssh + git -C "${scratch}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${scratch}" fetch --no-tags --force origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${scratch}" cat-file -t "refs/tags/${RELEASE_TAG}")" = tag + git -C "${scratch}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${scratch}" rev-parse --verify "refs/tags/${RELEASE_TAG}^{commit}")" + test "${tag_commit}" = "${RELEASE_COMMIT}" + git -C "${scratch}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the verified commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: ${{ github.sha }} + persist-credentials: false 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: Fetch verified release refs shell: bash run: | + set -euo pipefail + allowed_signers="${RUNNER_TEMP}/release-allowed-signers-${GITHUB_RUN_ID}" if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" exit 1 fi - allowed_signers="${RUNNER_TEMP}/release-allowed-signers" umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + test -f "${allowed_signers}" git config --local gpg.format ssh git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + git fetch --no-tags --force 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: Enable Corepack run: corepack enable - - name: Require an advertised release version - run: pnpm run release:check - - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Run the complete gate - run: pnpm run format:check && pnpm run check && pnpm test + - name: Check release metadata + run: pnpm run release:check + + - name: Check formatting + run: pnpm run format:check + + - name: Check types + run: pnpm run check - - name: Prepare and verify the release tarball - env: - RELEASE_TAG: ${{ github.event.release.tag_name }} - RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} - RELEASE_COMMIT: ${{ github.sha }} - run: pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + - name: Run tests + run: pnpm test + + - name: Prepare the release files + id: release_files + run: | + set -euo pipefail + pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + release_tarball=".release/pegma-mail-${RELEASE_TAG#v}.tgz" + test -f "${release_tarball}" + test ! -L "${release_tarball}" + printf 'tarball=%s\n' "${release_tarball}" >> "${GITHUB_OUTPUT}" - name: Upload the prepared release uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: mail-release-${{ github.run_id }} - path: .release/ + path: | + .release/package-manifest.json + ${{ steps.release_files.outputs.tarball }} if-no-files-found: error - include-hidden-files: true + include-hidden-files: false overwrite: true retention-days: 30 @@ -90,28 +149,244 @@ jobs: contents: read id-token: write env: - RELEASE_TAG: ${{ github.event.release.tag_name }} + CI: "1" + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_REPOSITORY: https://github.com/${{ github.repository }}.git + RELEASE_TAG: ${{ github.event.release.tag_name }} 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 ref + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases can be published" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.(0|[1-9][0-9]*))\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::The release tag is not a stable package tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The release commit is not an exact object ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers-${GITHUB_RUN_ID}" + scratch="$(mktemp -d "${RUNNER_TEMP}/mail-publish-git.XXXXXX")" + trap 'rm -rf -- "${scratch}"' EXIT + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare "${scratch}" + git -C "${scratch}" remote add origin "${RELEASE_REPOSITORY}" + git -C "${scratch}" config gpg.format ssh + git -C "${scratch}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${scratch}" fetch --no-tags --force origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${scratch}" cat-file -t "refs/tags/${RELEASE_TAG}")" = tag + git -C "${scratch}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${scratch}" rev-parse --verify "refs/tags/${RELEASE_TAG}^{commit}")" + test "${tag_commit}" = "${RELEASE_COMMIT}" + git -C "${scratch}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main - - name: Set up Node.js and npm registry + - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ + - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: mail-release-${{ github.run_id }} path: .release - - name: Publish the exact prepared tarball - run: npm run release:publish -- -- --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + - name: Validate and publish the prepared tarball + shell: bash + run: | + set -euo pipefail + node <<'NODE' + const { spawnSync } = require("node:child_process"); + const { createHash } = require("node:crypto"); + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + + const fail = (message) => { + throw new Error(message); + }; + const exactKeys = (value, expected) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + const actual = Object.keys(value).sort(); + const wanted = [...expected].sort(); + return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]); + }; + const releaseDirectory = path.resolve(".release"); + const entries = fs.readdirSync(releaseDirectory, { withFileTypes: true }); + if (entries.length !== 2 || entries.some((entry) => entry.name.startsWith(".") || !entry.isFile())) { + fail("release output does not match the expected file inventory"); + } + const names = entries.map((entry) => entry.name).sort(); + if (names.filter((name) => name === "package-manifest.json").length !== 1) { + fail("the release manifest is missing"); + } + for (const name of names) { + const metadata = fs.lstatSync(path.join(releaseDirectory, name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) fail("release entries must be regular files"); + } + const manifest = JSON.parse(fs.readFileSync(path.join(releaseDirectory, "package-manifest.json"), "utf8")); + const record = manifest.package; + if (!exactKeys(manifest, ["schemaVersion", "mode", "gitCommit", "releaseTag", "package"]) || + !exactKeys(record, ["name", "version", "tarball", "integrity", "shasum", "sha256", "sha512", "files"]) || + manifest.schemaVersion !== 1 || manifest.mode !== "release" || + !/^[0-9a-f]{40}$/u.test(manifest.gitCommit) || + record.name !== "@pegma/mail" || + !/^(0\.[1-9][0-9]*|[1-9][0-9]*\.(0|[1-9][0-9]*))\.(0|[1-9][0-9]*)$/u.test(record.version) || + manifest.releaseTag !== `v${record.version}` || manifest.releaseTag !== process.env.RELEASE_TAG || + manifest.gitCommit !== process.env.RELEASE_COMMIT || + record.tarball !== `pegma-mail-${record.version}.tgz` || + !Array.isArray(record.files) || record.files.length !== 7 || + record.files.some((file) => !exactKeys(file, ["path", "size"]) || typeof file.path !== "string" || !Number.isSafeInteger(file.size) || file.size < 0)) { + fail("prepared package manifest is invalid"); + } + if (!names.includes(record.tarball)) fail("the prepared tarball is missing"); + const expectedFiles = ["LICENSE", "README.md", "dist/index.d.ts", "dist/index.d.ts.map", "dist/index.js", "dist/index.js.map", "package.json"]; + const actualFiles = record.files.map((file) => file.path).sort(); + if (actualFiles.some((name, index) => name !== expectedFiles[index])) fail("package file inventory is invalid"); + const tarball = path.resolve(releaseDirectory, record.tarball); + if (path.dirname(tarball) !== releaseDirectory) fail("the tarball path is invalid"); + const bytes = fs.readFileSync(tarball); + const sha1 = createHash("sha1").update(bytes).digest("hex"); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha512 = createHash("sha512").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (record.shasum !== sha1 || record.sha256 !== sha256 || record.sha512 !== sha512 || record.integrity !== integrity) { + fail("prepared tarball digests do not match"); + } + if (process.argv.includes("--validate-only")) { + process.stdout.write("Prepared release files are valid.\n"); + process.exit(0); + } + + const npmLookup = spawnSync( + process.platform === "win32" ? "where.exe" : "which", + process.platform === "win32" ? ["npm.cmd"] : ["-a", "npm"], + { encoding: "utf8", shell: false }, + ); + if (npmLookup.status !== 0) fail("npm is unavailable"); + const npmCandidates = npmLookup.stdout.trim().split(/\r?\n/u).filter(Boolean).map((executable) => + process.platform === "win32" + ? path.join(path.dirname(executable), "node_modules", "npm", "bin", "npm-cli.js") + : fs.realpathSync(executable), + ); + npmCandidates.push( + process.platform === "win32" + ? path.join(path.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") + : path.join(path.dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"), + ); + const temporaryRoot = fs.mkdtempSync(path.join(process.env.RUNNER_TEMP || os.tmpdir(), "mail-publish-")); + try { + const cwd = path.join(temporaryRoot, "work"); + const userConfig = path.join(temporaryRoot, "user.npmrc"); + const globalConfig = path.join(temporaryRoot, "global.npmrc"); + fs.mkdirSync(cwd, { mode: 0o700 }); + fs.writeFileSync(userConfig, "", { mode: 0o600 }); + fs.writeFileSync(globalConfig, "", { mode: 0o600 }); + fs.chmodSync(userConfig, 0o600); + fs.chmodSync(globalConfig, 0o600); + const environment = {}; + for (const [key, value] of Object.entries(process.env)) { + const lower = key.toLowerCase(); + const blocked = lower.startsWith("npm_config_") || lower === "npm_token" || + lower === "npm_auth_token" || lower === "node_auth_token" || lower === "node_options" || + lower === "node_extra_ca_certs" || lower.endsWith("_proxy"); + const allowed = key === "CI" || key === "PATH" || key === "HOME" || + key === "SystemRoot" || key === "RUNNER_TEMP" || key === "TMP" || + key === "TEMP" || key === "TMPDIR" || key.startsWith("GITHUB_") || + key === "ACTIONS_ID_TOKEN_REQUEST_URL" || key === "ACTIONS_ID_TOKEN_REQUEST_TOKEN"; + if (!blocked && allowed && value !== undefined) environment[key] = value; + } + const npmCli = [...new Set(npmCandidates)].filter((candidate) => fs.existsSync(candidate)).find((candidate) => { + const npmVersion = spawnSync(process.execPath, [candidate, "--version"], { + cwd, env: environment, encoding: "utf8", shell: false, + }); + return npmVersion.status === 0 && String(npmVersion.stdout || "").trim() === "11.18.0"; + }); + if (npmCli === undefined) fail("npm 11.18.0 is required"); + const registryArguments = ["--registry", "https://registry.npmjs.org/", + "--userconfig", userConfig, "--globalconfig", globalConfig]; + const queryRegistryIntegrity = () => { + const result = spawnSync(process.execPath, [npmCli, "view", + `${record.name}@${record.version}`, "dist.integrity", "--json", + "--prefer-online", ...registryArguments], { + cwd, env: environment, encoding: "utf8", shell: false, + }); + if (result.error) throw result.error; + if (result.status === 0) { + const publishedIntegrity = JSON.parse(result.stdout); + if (typeof publishedIntegrity !== "string" || publishedIntegrity.length === 0) { + fail("the registry version has no integrity value"); + } + return publishedIntegrity; + } + const output = `${result.stdout || ""}\n${result.stderr || ""}`; + if (/\bE404\b/u.test(output)) return null; + fail(`npm registry lookup exited with ${String(result.status)}: ${output.trim()}`); + }; + const existingIntegrity = queryRegistryIntegrity(); + if (existingIntegrity !== null && existingIntegrity !== record.integrity) { + fail("the registry version has different tarball integrity"); + } + if (existingIntegrity === record.integrity) { + process.stdout.write("The exact package version is already published.\n"); + } else { + const result = spawnSync(process.execPath, [npmCli, "publish", tarball, + "--access", "public", "--registry", "https://registry.npmjs.org/", + "--provenance", "--ignore-scripts", "--userconfig", userConfig, + "--globalconfig", globalConfig], { cwd, env: environment, stdio: "inherit", shell: false }); + if (result.error) throw result.error; + if (result.status !== 0) fail(`npm publish exited with ${String(result.status)}`); + const postPublishDelays = [0, 1000, 2000, 4000, 8000]; + let lastRegistryError = null; + let confirmed = false; + for (const delay of postPublishDelays) { + if (delay > 0) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay); + } + try { + const publishedIntegrity = queryRegistryIntegrity(); + if (publishedIntegrity === record.integrity) { + confirmed = true; + break; + } + lastRegistryError = new Error( + publishedIntegrity === null + ? "the registry has not returned the package version" + : "the registry returned different tarball integrity", + ); + } catch (error) { + lastRegistryError = error; + } + } + if (!confirmed) { + const detail = lastRegistryError instanceof Error + ? `: ${lastRegistryError.message}` + : ""; + fail(`the registry did not return the prepared tarball integrity${detail}`); + } + } + } finally { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index af1c6f8..2a6192f 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -157,21 +157,25 @@ signed annotated `vX.Y.Z` tag at the exact `origin/main` commit, then run: gh release create vX.Y.Z --verify-tag ``` -The workflow runs `release:check` before preparation, and the packer, prepared -manifest verifier, registry decision, and minimal publisher independently -enforce the same `>=0.1.0` boundary. - -The preparation job has no OIDC authority. It verifies the signer, tag, -release-event commit, main ancestry, complete gate, package inventory, -dependencies, audit, npm hashes, and clean-consumer import. It packs once. - -The ordinary format, type, and test gate runs before `RELEASE_TAG`, -`RELEASE_PRERELEASE`, and `RELEASE_COMMIT` are introduced. Those release-event -variables are scoped only to the immediately following pack step, so a tagged -workflow cannot change the meaning of repository tests. - -Only the final environment-scoped job receives `id-token: write`. It installs -no dependencies and publishes the exact prepared tarball with provenance. +Before either job reads repository files, workflow-owned commands validate the +stable tag syntax, event commit, annotated SSH signature, and containment in +protected main from a disposable bare repository. The preparation job then +checks out the verified commit by its exact object ID with stored credentials +disabled. It runs the metadata, format, type, and test gates before packing. + +The packer removes prior build output and TypeScript incremental state, runs the +package build once with isolated npm configuration, and packs those exact files +with lifecycle scripts disabled. It records SHA-256 and SHA-512 digests, +requires the exact two-file release directory, checks the package inventory and +dependencies, and imports the tarball from a clean consumer. Empty private npm +configuration files and a fresh working directory isolate each npm operation. + +Only the final environment-scoped job receives `id-token: write`. It never +checks out repository contents and does not execute package scripts. Its +workflow-owned validation repeats the tag checks, requires the exact manifest +and tarball file inventory, validates the manifest identity and commit, and +recomputes both digests before publishing the absolute tarball path with +provenance and lifecycle scripts disabled. ## Registry safety diff --git a/docs/securityscan.md b/docs/securityscan.md index 1251719..593f98c 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -29,10 +29,10 @@ evidence, exploitability assessment, and file references. - **[OK] `.github/workflows/*.yml`** — reviewed. All actions pinned by full commit SHA, least-privilege `permissions` (`contents: read`, with `id-token: write` only in the publish job), no - `pull_request_target`, no script injection from event context (release tag - used only as a `ref` string and in artifact names, not interpolated into - shell), protected-environment gate (`environment: npm-publish`). No findings - yet. + `pull_request_target`; release values pass through scoped environment + variables and canonical validation before quoted refspec use; prepared files + are checked by workflow-owned logic covered by executable tests; and the + protected-environment gate is `environment: npm-publish`. No findings yet. - **[OK] `test/azurite.ts`** — reviewed. Local emulator harness; binds to 127.0.0.1, spawns node with fixed args, no secrets. No findings. diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index b07cb2f..ca70391 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -47,6 +47,7 @@ export function publicRegistryArguments( arguments_: readonly string[], registry?: string, ): string[]; +export function resolveNpmCli(): string; export function parseArguments( arguments_: readonly string[], ): ValidationOptions; @@ -55,6 +56,10 @@ export function validateRepository( ): Promise; export function verifyPreparedManifest(path: string): Promise; export function verifyPreparedBootstrapManifest(path: string): Promise; +export function verifyReleaseDirectory( + directory: string, + expectedTarball?: string, +): Promise<{ tarball: string }>; export function verifyBootstrapPreparation( options?: ValidationOptions, ): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 05ca02a..53a2d25 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,7 +1,15 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { + existsSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { + lstat, mkdtemp, mkdir, readFile, @@ -26,6 +34,7 @@ const BOOTSTRAP_TAG = `v${BOOTSTRAP_VERSION}`; const FIRST_RELEASE_VERSION = "0.1.0"; const RELEASE_MODE = "release"; const BOOTSTRAP_MODE = "bootstrap"; +const INVOCATION_EXEC_PATH = process.env.npm_execpath; export const RELEASE_PACKAGES = [PACKAGE]; export const PACKAGE_FILES = [ @@ -58,6 +67,18 @@ async function readJson(path) { return JSON.parse(await readFile(path, "utf8")); } +function hasExactKeys(value, keys) { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const actual = Object.keys(value).sort(); + const expected = [...keys].sort(); + return ( + actual.length === expected.length && + actual.every((key, index) => key === expected[index]) + ); +} + function safeEqual(left, right) { const leftBytes = Buffer.from(left); const rightBytes = Buffer.from(right); @@ -95,14 +116,69 @@ function isPnpmCli(path) { ); } +export function resolveNpmCli() { + const configured = process.env.npm_execpath; + if ( + configured !== undefined && + !isPnpmCli(configured) && + existsSync(configured) + ) { + return configured; + } + const candidates = []; + const lookup = spawnSync( + process.platform === "win32" ? "where.exe" : "which", + [process.platform === "win32" ? "npm.cmd" : "npm"], + { encoding: "utf8", shell: false }, + ); + if (lookup.status === 0) { + for (const executable of lookup.stdout.split(/\r?\n/u).filter(Boolean)) { + if (process.platform !== "win32") { + candidates.push(realpathSync(executable)); + } else { + candidates.push( + join(dirname(executable), "node_modules", "npm", "bin", "npm-cli.js"), + ); + } + } + } + candidates.push( + process.platform === "win32" + ? join( + dirname(process.execPath), + "node_modules", + "npm", + "bin", + "npm-cli.js", + ) + : join( + dirname(process.execPath), + "..", + "lib", + "node_modules", + "npm", + "bin", + "npm-cli.js", + ), + ); + const cli = [...new Set(candidates)] + .filter((candidate) => existsSync(candidate)) + .find((candidate) => { + const version = spawnSync(process.execPath, [candidate, "--version"], { + encoding: "utf8", + env: isolatedNpmEnvironment(), + shell: false, + }); + return ( + version.status === 0 && version.stdout.trim() === REVIEWED_NPM_VERSION + ); + }); + if (cli === undefined) fail("could not resolve the npm CLI"); + return cli; +} + function runNpm(arguments_, options = {}) { - const npmExecPath = process.env.npm_execpath; - return npmExecPath === undefined || isPnpmCli(npmExecPath) - ? run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { - ...options, - shell: process.platform === "win32", - }) - : run(process.execPath, [npmExecPath, ...arguments_], options); + return run(process.execPath, [resolveNpmCli(), ...arguments_], options); } function isolatedNpmEnvironment() { @@ -117,7 +193,10 @@ function isolatedNpmEnvironment() { normalized === "npm_execpath" || normalized === "npm_lifecycle_event" || normalized === "npm_lifecycle_script" || - normalized === "npm_command" + normalized === "npm_command" || + normalized === "node_options" || + normalized === "node_extra_ca_certs" || + normalized.endsWith("_proxy") ) { continue; } @@ -152,14 +231,29 @@ function runPublicRegistryPnpm(arguments_, options = {}) { ); writeFileSync(globalConfig, "", { mode: 0o600 }); try { + const pnpmExecPath = [process.env.npm_execpath, INVOCATION_EXEC_PATH].find( + (candidate) => + candidate !== undefined && + isPnpmCli(candidate) && + existsSync(candidate), + ); + const environment = { + ...isolatedNpmEnvironment(), + npm_config_userconfig: userConfig, + npm_config_globalconfig: globalConfig, + }; + const cwd = runOptions.cwd ?? configDirectory; + if (pnpmExecPath !== undefined) { + return run(process.execPath, [pnpmExecPath, ...arguments_], { + ...runOptions, + cwd, + env: environment, + }); + } return run(process.platform === "win32" ? "pnpm.cmd" : "pnpm", arguments_, { ...runOptions, - cwd: runOptions.cwd ?? configDirectory, - env: { - ...isolatedNpmEnvironment(), - npm_config_userconfig: userConfig, - npm_config_globalconfig: globalConfig, - }, + cwd, + env: environment, shell: process.platform === "win32", }); } finally { @@ -169,9 +263,11 @@ function runPublicRegistryPnpm(arguments_, options = {}) { function runPublicRegistryNpm(arguments_, options = {}) { const { registry = PUBLIC_NPM_REGISTRY, ...runOptions } = options; - const configDirectory = mkdtempSync(join(tmpdir(), "pegma-mail-npm-config-")); + const configDirectory = mkdtempSync(join(tmpdir(), "pegma-mail-npm-")); const userConfig = join(configDirectory, "user.npmrc"); const globalConfig = join(configDirectory, "global.npmrc"); + const workingDirectory = join(configDirectory, "work"); + mkdirSync(workingDirectory); writeFileSync(userConfig, "", { mode: 0o600 }); writeFileSync(globalConfig, "", { mode: 0o600 }); try { @@ -188,7 +284,7 @@ function runPublicRegistryNpm(arguments_, options = {}) { ), { ...runOptions, - cwd: runOptions.cwd ?? configDirectory, + cwd: runOptions.cwd ?? workingDirectory, env: isolatedNpmEnvironment(), }, ); @@ -208,6 +304,8 @@ function rootDirectory() { function hashTarball(bytes) { return { shasum: createHash("sha1").update(bytes).digest("hex"), + sha256: createHash("sha256").update(bytes).digest("hex"), + sha512: createHash("sha512").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, }; } @@ -550,7 +648,7 @@ function validateSignedTag(options, releaseTag) { options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; 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"); } @@ -600,7 +698,10 @@ function validateSignedTag(options, releaseTag) { export function validateReleaseTag(options = {}) { const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; - if (releaseTag === undefined || !/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { + if ( + releaseTag === undefined || + !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(releaseTag) + ) { fail("a stable release tag is required"); } requireNormalReleaseVersion(releaseTag.slice(1)); @@ -777,6 +878,41 @@ function verifyPackedFiles(manifest, files) { } } +export async function verifyReleaseDirectory(directory, expectedTarball) { + const root = resolve(directory); + const entries = await readdir(root, { withFileTypes: true }); + if ( + entries.length !== 2 || + entries.some( + (entry) => + entry.name.startsWith(".") || + !entry.isFile() || + (entry.name !== "package-manifest.json" && + !/^pegma-mail-(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.tgz$/u.test( + entry.name, + )), + ) + ) { + fail("release output does not match the expected file inventory"); + } + const names = entries.map(({ name }) => name).sort(); + const tarballs = names.filter((name) => name.endsWith(".tgz")); + if ( + !names.includes("package-manifest.json") || + tarballs.length !== 1 || + (expectedTarball !== undefined && tarballs[0] !== expectedTarball) + ) { + fail("release output does not match the expected file inventory"); + } + for (const name of names) { + const metadata = await lstat(join(root, name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) { + fail("release output must contain regular files only"); + } + } + return { tarball: tarballs[0] }; +} + async function smokeTestTarball(tarball, manifest, registry) { const directory = await mkdtemp(join(tmpdir(), "mail-release-smoke-")); try { @@ -802,13 +938,20 @@ async function smokeTestTarball(tarball, manifest, registry) { "--eval", `await import(${JSON.stringify(manifest.name)})`, ], - { cwd: directory, capture: true }, + { cwd: directory, capture: true, env: isolatedNpmEnvironment() }, ); } finally { await rm(directory, { recursive: true, force: true }); } } +async function cleanPackageBuildOutputs(packageDirectory) { + await Promise.all([ + rm(join(packageDirectory, "dist"), { recursive: true, force: true }), + rm(join(packageDirectory, "tsconfig.tsbuildinfo"), { force: true }), + ]); +} + export async function prepareRelease(options = {}) { const { root, manifest, packageDirectory, releaseTag } = await validateRepository(options); @@ -829,13 +972,20 @@ export async function prepareRelease(options = {}) { cwd: root, registry: options.registry, }); - runPublicRegistryNpm(["run", "build"], { - cwd: root, + await cleanPackageBuildOutputs(packageDirectory); + runPublicRegistryNpm(["--prefix", packageDirectory, "run", "build"], { registry: options.registry, }); const packedResult = runPublicRegistryNpm( - ["pack", packageDirectory, "--json", "--pack-destination", output], - { cwd: root, capture: true, registry: options.registry }, + [ + "pack", + packageDirectory, + "--ignore-scripts", + "--json", + "--pack-destination", + output, + ], + { capture: true, registry: options.registry }, ); const [packed] = JSON.parse(packedResult.stdout); if ( @@ -867,6 +1017,8 @@ export async function prepareRelease(options = {}) { tarball: basename(tarballPath), integrity: hashes.integrity, shasum: hashes.shasum, + sha256: hashes.sha256, + sha512: hashes.sha512, files: packed.files .map(({ path, size }) => ({ path, size })) .sort( @@ -878,6 +1030,7 @@ export async function prepareRelease(options = {}) { }; const manifestPath = join(output, "package-manifest.json"); await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); + await verifyReleaseDirectory(output, basename(tarballPath)); return { manifestPath, manifest: prepared }; } @@ -959,9 +1112,7 @@ function validPreparedFiles(files) { const paths = []; for (const file of files) { if ( - file === null || - typeof file !== "object" || - Array.isArray(file) || + !hasExactKeys(file, ["path", "size"]) || typeof file.path !== "string" || !Number.isSafeInteger(file.size) || file.size < 0 @@ -975,6 +1126,10 @@ function validPreparedFiles(files) { } async function verifyPrepared(path, mode) { + const manifestPath = resolve(path); + if (basename(manifestPath) !== "package-manifest.json") { + fail("prepared manifest must use the expected filename"); + } const prepared = await readJson(path); const record = prepared.package; const releaseVersion = @@ -987,16 +1142,32 @@ async function verifyPrepared(path, mode) { : bootstrapVersion && (prepared.releaseTag === null || prepared.releaseTag === BOOTSTRAP_TAG); if ( + !hasExactKeys(prepared, [ + "schemaVersion", + "mode", + "gitCommit", + "releaseTag", + "package", + ]) || prepared.schemaVersion !== 1 || prepared.mode !== mode || - !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || - record === null || - typeof record !== "object" || - Array.isArray(record) || + !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || + !hasExactKeys(record, [ + "name", + "version", + "tarball", + "integrity", + "shasum", + "sha256", + "sha512", + "files", + ]) || !validTag || record?.name !== PACKAGE.name || typeof record.integrity !== "string" || typeof record.shasum !== "string" || + !/^[0-9a-f]{64}$/u.test(record.sha256) || + !/^[0-9a-f]{128}$/u.test(record.sha512) || !validPreparedFiles(record.files) ) { fail("prepared package manifest is invalid"); @@ -1005,6 +1176,7 @@ async function verifyPrepared(path, mode) { if (record.tarball !== expectedTarball) { fail("prepared tarball name is invalid"); } + await verifyReleaseDirectory(dirname(manifestPath), expectedTarball); const currentCommit = run(gitCommand(), ["rev-parse", "HEAD"], { cwd: rootDirectory(), capture: true, @@ -1012,14 +1184,16 @@ async function verifyPrepared(path, mode) { if (!safeEqual(currentCommit, prepared.gitCommit)) { fail("prepared package manifest commit does not match the checkout"); } - const tarball = resolve(dirname(path), record.tarball); - if (dirname(tarball) !== resolve(dirname(path))) { + const tarball = resolve(dirname(manifestPath), record.tarball); + if (dirname(tarball) !== resolve(dirname(manifestPath))) { fail("prepared tarball must be beside the package manifest"); } const hashes = hashTarball(await readFile(tarball)); if ( !safeEqual(hashes.integrity, record.integrity) || - !safeEqual(hashes.shasum, record.shasum) + !safeEqual(hashes.shasum, record.shasum) || + !safeEqual(hashes.sha256, record.sha256) || + !safeEqual(hashes.sha512, record.sha512) ) { fail("prepared tarball has changed"); } @@ -1086,7 +1260,7 @@ export async function publishPreparedRelease(options = {}) { if ( releaseTag !== prepared.releaseTag || expectedCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedCommit) || + !/^[0-9a-f]{40}$/u.test(expectedCommit) || !safeEqual(expectedCommit, prepared.gitCommit) ) { fail("prepared package must match the release event tag and commit"); @@ -1097,16 +1271,14 @@ export async function publishPreparedRelease(options = {}) { queryRegistryIntegrity(record.name, record.version), ); if (decision === "skip") return; - runPublicRegistryNpm( - [ - "publish", - resolve(dirname(manifestPath), record.tarball), - "--access", - "public", - "--provenance", - ], - { cwd: dirname(manifestPath) }, - ); + runPublicRegistryNpm([ + "publish", + resolve(dirname(manifestPath), record.tarball), + "--access", + "public", + "--provenance", + "--ignore-scripts", + ]); const published = queryRegistryIntegrity(record.name, record.version); if (published === null || !safeEqual(published, record.integrity)) { fail("registry did not expose the exact prepared tarball integrity"); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index b317291..113f1bd 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,9 +1,17 @@ import { spawn, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; -import { cp, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { + chmod, + cp, + mkdir, + mkdtemp, + rm, + symlink, + writeFile, +} from "node:fs/promises"; import { tmpdir } from "node:os"; -import { basename, dirname, join } from "node:path"; +import { basename, delimiter, dirname, join } from "node:path"; import { describe, expect, it } from "vitest"; import { PACKAGE_FILES, @@ -21,12 +29,14 @@ import { pnpmLockImporterHasSection, requirePnpmLockDependencies, requirePublicPackageLockDependencies, + resolveNpmCli, resolvedVersionMatchesSpecifier, validateBootstrapTag, validateReleaseTag, validateRepository, verifyPreparedBootstrapManifest, verifyPreparedManifest, + verifyReleaseDirectory, } from "../scripts/release-packages.mjs"; async function startTestRegistry( @@ -60,35 +70,8 @@ async function startTestRegistry( }; } -function isPnpmCli(path: string) { - const normalized = path.replaceAll("\\", "/").toLowerCase(); - return ( - normalized.includes("/pnpm/") || - normalized.endsWith("/pnpm") || - normalized.endsWith("/pnpm.cjs") || - normalized.endsWith("/pnpm.js") - ); -} - function reviewedNpmExecPath() { - const fromEnv = process.env["npm_execpath"]; - if (fromEnv !== undefined && !isPnpmCli(fromEnv)) return fromEnv; - const bundled = join( - dirname(process.execPath), - "node_modules", - "npm", - "bin", - "npm-cli.js", - ); - if (existsSync(bundled)) return bundled; - const which = spawnSync("which", ["npm"], { encoding: "utf8" }); - const npmBin = which.stdout.trim().split("\n")[0]; - if (which.status === 0 && npmBin !== undefined && npmBin.length > 0) { - const nearby = join(dirname(npmBin), "..", "npm", "bin", "npm-cli.js"); - if (existsSync(nearby)) return nearby; - return npmBin; - } - return bundled; + return resolveNpmCli(); } function cleanNpmEnvironment() { @@ -105,6 +88,45 @@ function cleanNpmEnvironment() { ); } +function workflowRunScripts(workflow: string) { + const lines = workflow.split("\n"); + const scripts: string[] = []; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index] ?? ""; + const match = /^(\s*)run:\s*(.*)$/u.exec(line); + if (match === null) continue; + const indent = match[1]?.length ?? 0; + const value = match[2] ?? ""; + if (value !== "|") { + scripts.push(value); + continue; + } + const body: string[] = []; + while (index + 1 < lines.length) { + const next = lines[index + 1] ?? ""; + const nextIndent = /^\s*/u.exec(next)?.[0].length ?? 0; + if (next.trim() !== "" && nextIndent <= indent) break; + body.push(next); + index += 1; + } + scripts.push(body.join("\n")); + } + return scripts; +} + +function workflowPublishValidator(workflow: string) { + const match = / node <<'NODE'\n([\s\S]*?)\n NODE/u.exec( + workflow, + ); + if (match?.[1] === undefined) { + throw new Error("publish validator was not found"); + } + return match[1] + .split("\n") + .map((line) => (line.startsWith(" ") ? line.slice(10) : line)) + .join("\n"); +} + async function writePreparedReleaseFixture(directory: string, version: string) { const tarball = `pegma-mail-${version}.tgz`; const tarballBytes = Buffer.from("prepared release fixture\n"); @@ -132,6 +154,8 @@ async function writePreparedReleaseFixture(directory: string, version: string) { .update(tarballBytes) .digest("base64")}`, shasum: createHash("sha1").update(tarballBytes).digest("hex"), + sha256: createHash("sha256").update(tarballBytes).digest("hex"), + sha512: createHash("sha512").update(tarballBytes).digest("hex"), files: PACKAGE_FILES.map((path) => ({ path, size: 1 })), }, }), @@ -139,6 +163,58 @@ async function writePreparedReleaseFixture(directory: string, version: string) { return manifestPath; } +async function writeWorkflowNpmFixture(directory: string) { + const shimDirectory = join(directory, "shim"); + const binDirectory = join(directory, "bin"); + const npmCli = + process.platform === "win32" + ? join(binDirectory, "node_modules", "npm", "bin", "npm-cli.js") + : join(binDirectory, "npm"); + await mkdir(dirname(npmCli), { recursive: true }); + await writeFile( + npmCli, + `#!/usr/bin/env node +const fs = require("node:fs"); +const statePath = process.env.GITHUB_TEST_NPM_STATE; +if (!statePath) throw new Error("test state is unavailable"); +const arguments_ = process.argv.slice(2); +if (arguments_[0] === "--version") { + process.stdout.write("11.18.0\\n"); + process.exit(0); +} +const state = JSON.parse(fs.readFileSync(statePath, "utf8")); +if (arguments_[0] === "view") { + const response = state.views.shift(); + fs.writeFileSync(statePath, JSON.stringify(state)); + if (response === "missing") { + process.stderr.write("npm ERR! code E404\\n"); + process.exit(1); + } + process.stdout.write(JSON.stringify(response)); + process.exit(0); +} +if (arguments_[0] === "publish") { + state.publishCount += 1; + fs.writeFileSync(statePath, JSON.stringify(state)); + process.exit(0); +} +throw new Error(\`unexpected npm arguments: \${arguments_.join(" ")}\`); +`, + ); + if (process.platform === "win32") { + await mkdir(shimDirectory); + await writeFile(join(shimDirectory, "npm.cmd"), "@echo off\r\n"); + await writeFile(join(binDirectory, "npm.cmd"), "@echo off\r\n"); + } else { + await mkdir(shimDirectory); + const shim = join(shimDirectory, "npm"); + await writeFile(shim, "#!/bin/sh\nexit 1\n"); + await chmod(shim, 0o755); + await chmod(npmCli, 0o755); + } + return `${shimDirectory}${delimiter}${binDirectory}`; +} + async function writeReleaseRepositoryFixture( directory: string, version = "0.1.0", @@ -209,6 +285,7 @@ async function writeBootstrapRepositoryFixture(directory: string) { symlink( join(sourceRoot, "packages", "mail", "node_modules"), join(directory, "packages", "mail", "node_modules"), + process.platform === "win32" ? "junction" : "dir", ), ]); return directory; @@ -393,6 +470,25 @@ describe("release package metadata", () => { }); }); + it("resolves the PATH npm when invoked through pnpm", () => { + const original = process.env["npm_execpath"]; + try { + process.env["npm_execpath"] = join(tmpdir(), "pnpm", "pnpm.cjs"); + const version = spawnSync( + process.execPath, + [resolveNpmCli(), "--version"], + { + encoding: "utf8", + }, + ); + expect(version.status).toBe(0); + expect(version.stdout.trim()).toBe("11.18.0"); + } finally { + if (original === undefined) delete process.env["npm_execpath"]; + else process.env["npm_execpath"] = original; + } + }); + it("gives every bootstrap shortcut its safe artifact default", () => { const rootManifest = JSON.parse( readFileSync(join(process.cwd(), "package.json"), "utf8"), @@ -407,7 +503,7 @@ describe("release package metadata", () => { }); }); - it("keeps every resolved uuid past the buffer-bounds advisory", () => { + it("keeps every resolved uuid at the required version", () => { const rootManifest = JSON.parse( readFileSync(join(process.cwd(), "package.json"), "utf8"), ) as { overrides: Record }; @@ -673,6 +769,55 @@ describe("release package metadata", () => { } }); + it.each(["extra.txt", ".extra"])( + "rejects an unexpected release entry named %s", + async (entry) => { + const directory = await mkdtemp( + join(tmpdir(), "pegma-mail-release-inventory-test-"), + ); + try { + await writePreparedReleaseFixture(directory, "0.1.0"); + await writeFile(join(directory, entry), "unexpected\n"); + await expect(verifyReleaseDirectory(directory)).rejects.toThrow( + "expected file inventory", + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }, + ); + + it("rejects a linked release entry", async () => { + const directory = await mkdtemp( + join(tmpdir(), "pegma-mail-release-inventory-test-"), + ); + const releaseDirectory = join(directory, "release"); + try { + await mkdir(releaseDirectory); + const manifest = await writePreparedReleaseFixture( + releaseDirectory, + "0.1.0", + ); + const record = JSON.parse(readFileSync(manifest, "utf8")) as { + package: { tarball: string }; + }; + const tarball = join(releaseDirectory, record.package.tarball); + const target = join(directory, "target"); + await mkdir(target); + await rm(tarball); + await symlink( + target, + tarball, + process.platform === "win32" ? "junction" : "dir", + ); + await expect(verifyReleaseDirectory(releaseDirectory)).rejects.toThrow( + "expected file inventory", + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + it("verifies every supplied manifest before the first registry query", async () => { const directory = await mkdtemp( join(tmpdir(), "pegma-mail-registry-order-test-"), @@ -814,10 +959,19 @@ describe("release package metadata", () => { const root = join(directory, "repository"); try { await writeBootstrapRepositoryFixture(root); + const staleOutput = join(root, "packages", "mail", "dist", "stale.js"); + const buildState = join(root, "packages", "mail", "tsconfig.tsbuildinfo"); + await mkdir(dirname(staleOutput), { recursive: true }); + await writeFile(staleOutput, "stale output\n"); + await writeFile(buildState, "stale build state\n"); const prepared = await prepareBootstrap({ root, output: join(directory, "output"), }); + expect(existsSync(staleOutput)).toBe(false); + expect(readFileSync(buildState, "utf8")).not.toContain( + "stale build state", + ); const record = prepared.manifest as { package: { integrity: string }; }; @@ -870,7 +1024,10 @@ describe("release package metadata", () => { ' return normalized.startsWith("npm_config_") ||', ' normalized === "node_auth_token" ||', ' normalized === "npm_token" ||', - ' normalized === "npm_auth_token";', + ' normalized === "npm_auth_token" ||', + ' normalized === "node_options" ||', + ' normalized === "node_extra_ca_certs" ||', + ' normalized.endsWith("_proxy");', "});", "if (leaked) {", ' process.stderr.write("npm credentials or configuration leaked\\n");', @@ -891,6 +1048,10 @@ describe("release package metadata", () => { "NODE_AUTH_TOKEN", "NPM_TOKEN", "NPM_AUTH_TOKEN", + "NODE_OPTIONS", + "NODE_EXTRA_CA_CERTS", + "HTTP_PROXY", + "HTTPS_PROXY", ]; const originalHostileEnvironment = new Map( hostileEnvironment.map((key) => [key, process.env[key]]), @@ -902,6 +1063,10 @@ describe("release package metadata", () => { process.env["NODE_AUTH_TOKEN"] = "must-not-leak"; process.env["NPM_TOKEN"] = "must-not-leak"; process.env["NPM_AUTH_TOKEN"] = "must-not-leak"; + process.env["NODE_OPTIONS"] = "--require=must-not-load"; + process.env["NODE_EXTRA_CA_CERTS"] = "must-not-load.pem"; + process.env["HTTP_PROXY"] = "http://127.0.0.1:1"; + process.env["HTTPS_PROXY"] = "http://127.0.0.1:1"; process.env["FAKE_NPM_INTEGRITY"] = "absent"; await expect( checkBootstrapRegistry({ root, manifest: prepared.manifestPath }), @@ -1035,6 +1200,10 @@ describe("release package metadata", () => { "NODE_AUTH_TOKEN", "NPM_TOKEN", "NPM_AUTH_TOKEN", + "NODE_OPTIONS", + "NODE_EXTRA_CA_CERTS", + "HTTP_PROXY", + "HTTPS_PROXY", ]; const originalEnvironment = new Map( environmentKeys.map((key) => [key, process.env[key]]), @@ -1054,6 +1223,11 @@ describe("release package metadata", () => { process.env["NODE_AUTH_TOKEN"] = "must-not-leak"; process.env["NPM_TOKEN"] = "must-not-leak"; process.env["NPM_AUTH_TOKEN"] = "must-not-leak"; + process.env["NODE_OPTIONS"] = "--require=must-not-load"; + process.env["NODE_EXTRA_CA_CERTS"] = "must-not-load.pem"; + process.env["HTTP_PROXY"] = hostile.url; + process.env["HTTPS_PROXY"] = hostile.url; + process.env["npm_execpath"] = join(directory, "pnpm", "pnpm.cjs"); const isolated = await prepareBootstrap({ root, output: join(directory, "isolated"), @@ -1142,18 +1316,37 @@ describe("release package metadata", () => { expect(prepare).not.toContain("id-token: write"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("npm ci"); - expect(publish).not.toContain("npm install"); + expect(publish).toContain( + "npm install --global npm@11.18.0 --ignore-scripts", + ); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("corepack"); expect(publish).not.toContain("pnpm run"); - expect(publish).toContain("npm run release:publish"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).toContain("node <<'NODE'"); + expect(publish).toContain('"--ignore-scripts"'); + expect(publish).toContain('"--provenance"'); + expect(publish).toContain('"--registry", "https://registry.npmjs.org/"'); + expect(publish).toContain( + 'fs.writeFileSync(userConfig, "", { mode: 0o600 })', + ); + expect(publish).toContain('lower.endsWith("_proxy")'); + expect(publish).toContain( + 'String(npmVersion.stdout || "").trim() === "11.18.0"', + ); + expect(publish).toContain("queryRegistryIntegrity"); + expect(publish).toContain("existingIntegrity === record.integrity"); + expect(publish).toContain("publishedIntegrity === record.integrity"); + expect(publish).toContain( + "postPublishDelays = [0, 1000, 2000, 4000, 8000]", + ); expect(prepare).toContain("pnpm run release:check"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).not.toContain("NODE_AUTH_TOKEN"); expect(workflow).not.toContain("bootstrap:"); }); - it("checks the release version before every registry-backed workflow step", () => { + it("verifies release refs before checking out repository files", () => { const workflow = readFileSync( join(process.cwd(), ".github", "workflows", "publish.yml"), "utf8", @@ -1162,20 +1355,207 @@ describe("release package metadata", () => { workflow.indexOf(" prepare:"), workflow.indexOf("\n publish:"), ); - const setupNode = prepare.indexOf("- name: Set up Node.js"); - const releaseCheck = prepare.indexOf( - "- name: Require an advertised release version", + const verification = prepare.indexOf("- name: Verify the release ref"); + const checkout = prepare.indexOf("- name: Check out the verified commit"); + expect(verification).toBeGreaterThan(-1); + expect(checkout).toBeGreaterThan(verification); + expect(prepare.slice(verification, checkout)).toContain("git init --bare"); + expect(prepare.slice(verification, checkout)).toContain("verify-tag"); + expect(prepare.slice(verification, checkout)).toContain( + "merge-base --is-ancestor", + ); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(prepare.indexOf("pnpm install --frozen-lockfile")).toBeGreaterThan( + checkout, ); - const installNpm = prepare.indexOf("- name: Use the reviewed npm release"); - const installDependencies = prepare.indexOf("- name: Install dependencies"); - const completeGate = prepare.indexOf("- name: Run the complete gate"); - expect(setupNode).toBeGreaterThan(-1); - expect(releaseCheck).toBeGreaterThan(setupNode); - for (const laterStep of [installNpm, installDependencies, completeGate]) { - expect(laterStep).toBeGreaterThan(releaseCheck); + }); + + it("passes workflow expressions outside run scripts", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + expect(workflow).toContain( + "RELEASE_TAG: ${{ github.event.release.tag_name }}", + ); + expect(workflow).toContain( + "RELEASE_PRERELEASE: ${{ github.event.release.prerelease }}", + ); + expect(workflow).toContain("RELEASE_COMMIT: ${{ github.sha }}"); + expect(workflow).toContain( + "RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }}", + ); + expect(workflowRunScripts(workflow)).not.toEqual([]); + for (const script of workflowRunScripts(workflow)) { + expect(script).not.toContain("${{"); + } + }); + + it("keeps release validation and exact file upload in the workflow", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + expect(workflow.match(/git init --bare/gu)).toHaveLength(2); + expect(workflow.match(/git -C "\$\{scratch\}" verify-tag/gu)).toHaveLength( + 2, + ); + expect(workflow).toContain("include-hidden-files: false"); + expect(workflow).toContain(".release/package-manifest.json"); + expect(workflow).toContain("${{ steps.release_files.outputs.tarball }}"); + expect(workflow).not.toContain(".release/pegma-mail-*.tgz"); + expect(workflow).toContain('createHash("sha256")'); + expect(workflow).toContain('createHash("sha512")'); + }); + + it("executes the workflow-owned release validator", async () => { + const directory = await mkdtemp( + join(tmpdir(), "pegma-mail-workflow-validator-test-"), + ); + const releaseDirectory = join(directory, ".release"); + try { + await mkdir(releaseDirectory); + const manifestPath = await writePreparedReleaseFixture( + releaseDirectory, + "0.1.0", + ); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { + gitCommit: string; + releaseTag: string; + package: { sha256: string }; + }; + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const validator = join(directory, "publish-validator.cjs"); + await writeFile(validator, `${workflowPublishValidator(workflow)}\n`); + const validate = () => + spawnSync(process.execPath, [validator, "--validate-only"], { + cwd: directory, + encoding: "utf8", + env: { + ...process.env, + RELEASE_COMMIT: manifest.gitCommit, + RELEASE_TAG: manifest.releaseTag, + }, + }); + + const valid = validate(); + expect(valid.status, valid.stderr).toBe(0); + expect(valid.stdout).toContain("Prepared release files are valid."); + + const extra = join(releaseDirectory, ".extra"); + await writeFile(extra, "unexpected\n"); + const unexpected = validate(); + expect(unexpected.status).not.toBe(0); + expect(unexpected.stderr).toContain("expected file inventory"); + await rm(extra); + + manifest.package.sha256 = "0".repeat(64); + await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + const changed = validate(); + expect(changed.status).not.toBe(0); + expect(changed.stderr).toContain("digests do not match"); + } finally { + await rm(directory, { recursive: true, force: true }); } }); + it("executes the workflow-owned registry decision paths", async () => { + const directory = await mkdtemp( + join(tmpdir(), "pegma-mail-workflow-publish-test-"), + ); + const releaseDirectory = join(directory, ".release"); + try { + await mkdir(releaseDirectory); + const manifestPath = await writePreparedReleaseFixture( + releaseDirectory, + "0.1.0", + ); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { + gitCommit: string; + releaseTag: string; + package: { integrity: string }; + }; + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const validator = join(directory, "publish-validator.cjs"); + const statePath = join(directory, "npm-state.json"); + const npmPath = await writeWorkflowNpmFixture(directory); + await writeFile(validator, `${workflowPublishValidator(workflow)}\n`); + const environment = Object.fromEntries( + Object.entries(process.env).filter( + ([key]) => key.toLowerCase() !== "path", + ), + ); + environment["PATH"] = + `${npmPath}${delimiter}${process.env["PATH"] ?? ""}`; + environment["RELEASE_COMMIT"] = manifest.gitCommit; + environment["RELEASE_TAG"] = manifest.releaseTag; + environment["GITHUB_TEST_NPM_STATE"] = statePath; + const run = async (views: string[]) => { + await writeFile(statePath, JSON.stringify({ publishCount: 0, views })); + const result = spawnSync(process.execPath, [validator], { + cwd: directory, + encoding: "utf8", + env: environment, + }); + const state = JSON.parse(readFileSync(statePath, "utf8")) as { + publishCount: number; + views: string[]; + }; + return { result, state }; + }; + + const alreadyPublished = await run([manifest.package.integrity]); + expect( + alreadyPublished.result.status, + alreadyPublished.result.stderr, + ).toBe(0); + expect(alreadyPublished.result.stdout).toContain( + "The exact package version is already published.", + ); + expect(alreadyPublished.state.publishCount).toBe(0); + + const different = await run(["sha512-different"]); + expect(different.result.status).not.toBe(0); + expect(different.result.stderr).toContain( + "the registry version has different tarball integrity", + ); + expect(different.state.publishCount).toBe(0); + + const published = await run(["missing", manifest.package.integrity]); + expect(published.result.status, published.result.stderr).toBe(0); + expect(published.state.publishCount).toBe(1); + expect(published.state.views).toEqual([]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("cleans once, builds once, and packs without lifecycle scripts", () => { + const source = readFileSync( + join(process.cwd(), "scripts", "release-packages.mjs"), + "utf8", + ); + const prepare = source.slice( + source.indexOf("export async function prepareRelease"), + source.indexOf("export async function prepareBootstrap"), + ); + expect(prepare.match(/cleanPackageBuildOutputs/gu)).toHaveLength(1); + expect(prepare.indexOf('"run", "build"')).toBeGreaterThan( + prepare.indexOf("cleanPackageBuildOutputs"), + ); + expect(prepare.indexOf('"pack"')).toBeGreaterThan( + prepare.indexOf('"run", "build"'), + ); + expect(prepare).toContain('"--ignore-scripts"'); + }); + it("installs the reviewed npm before every CI matrix gate", () => { const workflow = readFileSync( join(process.cwd(), ".github", "workflows", "ci.yml"), @@ -1184,8 +1564,9 @@ describe("release package metadata", () => { expect(workflow).toContain(" - 22"); expect(workflow).toContain(" - 24"); expect(workflow).toContain("run: corepack enable"); + expect(workflow).toContain("run: pnpm run release:check"); const installNpm = workflow.indexOf( - "run: npm install --global npm@11.18.0", + "run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/", ); const installDependencies = workflow.indexOf( "run: pnpm install --frozen-lockfile",