From 050d1a3cdc9025f7c54fe287c31265c493947319 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 09:19:07 -0500 Subject: [PATCH 1/3] chore: tighten release artifact inventory and isolated npm publish invocation --- .github/workflows/ci.yml | 5 + .github/workflows/publish.yml | 32 ++- scripts/release-package.mjs | 161 ++++++++++---- scripts/release-package.test.mjs | 361 +++++++++++++++++++++++++++++++ vitest.config.ts | 2 +- 5 files changed, 513 insertions(+), 48 deletions(-) create mode 100644 scripts/release-package.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ebf6ce..9a9eca9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,8 @@ jobs: validate: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest + env: + CI: 1 strategy: fail-fast: false matrix: @@ -49,5 +51,8 @@ jobs: - name: Check types run: pnpm run check + - name: Check release metadata + run: pnpm run release:check + - name: Run tests run: pnpm test diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index bdbfaa7..cdd3e14 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,6 +18,7 @@ jobs: prepare: runs-on: ubuntu-latest env: + CI: 1 RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} @@ -29,6 +30,7 @@ jobs: with: ref: refs/tags/${{ github.event.release.tag_name }} fetch-depth: 0 + persist-credentials: false - name: Fetch the protected release branch run: git fetch --no-tags origin main:refs/remotes/origin/main @@ -66,15 +68,20 @@ jobs: run: pnpm run format:check && pnpm run check && 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}" + id: prepare-release + shell: bash + run: | + pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" + printf 'tarball=%s\n' ".release/pegma-webhooks-${RELEASE_TAG#v}.tgz" >> "${GITHUB_OUTPUT}" - name: Upload the prepared release uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: webhooks-release-${{ github.run_id }} - path: .release/ + path: | + .release/package-manifest.json + ${{ steps.prepare-release.outputs.tarball }} if-no-files-found: error - include-hidden-files: true overwrite: true retention-days: 30 @@ -90,24 +97,33 @@ jobs: RELEASE_COMMIT: ${{ github.sha }} steps: - - name: Check out the exact release tag + - name: Check out the release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: ${{ github.sha }} fetch-depth: 1 + persist-credentials: false - name: Set up Node.js and npm uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - name: Download the prepared release uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: webhooks-release-${{ github.run_id }} - path: .release + path: ${{ runner.temp }}/webhooks-release-${{ github.run_id }} + + - name: Create a clean publisher directory + id: publisher-directory + shell: bash + run: printf 'path=%s\n' "$(mktemp -d "${RUNNER_TEMP}/webhooks-publisher-XXXXXX")" >> "${GITHUB_OUTPUT}" - name: Publish the verified prepared tarball - run: node scripts/release-package.mjs publish --expected-release-commit "${RELEASE_COMMIT}" + working-directory: ${{ steps.publisher-directory.outputs.path }} + run: >- + node "${GITHUB_WORKSPACE}/scripts/release-package.mjs" publish + --manifest "${RUNNER_TEMP}/webhooks-release-${GITHUB_RUN_ID}/package-manifest.json" + --expected-release-commit "${RELEASE_COMMIT}" diff --git a/scripts/release-package.mjs b/scripts/release-package.mjs index 2df258d..bc413df 100644 --- a/scripts/release-package.mjs +++ b/scripts/release-package.mjs @@ -18,12 +18,11 @@ const PACKAGE_DIRECTORY = "packages/webhooks"; const PACKAGE_MANAGER = "pnpm@10.34.5"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/webhooks.git"; const NODE_RANGE = ">=22"; +const NPM_REGISTRY = "https://registry.npmjs.org/"; const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; const WORKSPACE_PACKAGES = ["packages/*"]; -const REQUIRED_DEPENDENCIES = { - "@pegma/spine": "0.1.1", - "@pegma/storage-core": "0.4.0", -}; +const REQUIRED_DEPENDENCY_NAMES = ["@pegma/spine", "@pegma/storage-core"]; +const PREPARED_MANIFEST_NAME = "package-manifest.json"; function fail(message) { throw new Error(message); @@ -33,7 +32,7 @@ function run(command, arguments_, options = {}) { const result = spawnSync(command, arguments_, { cwd: options.cwd, encoding: "utf8", - env: process.env, + env: options.env ?? process.env, shell: options.shell ?? false, stdio: options.capture ? "pipe" : "inherit", }); @@ -281,6 +280,18 @@ export async function validateRepository(options = {}) { ) .filter((entry) => entry.isDirectory()) .map((entry) => entry.name); + const runtimeDependencies = manifest.dependencies; + const runtimeDependenciesAreExact = + runtimeDependencies !== null && + typeof runtimeDependencies === "object" && + !Array.isArray(runtimeDependencies) && + sameJson( + Object.keys(runtimeDependencies).sort(), + [...REQUIRED_DEPENDENCY_NAMES].sort(), + ) && + Object.values(runtimeDependencies).every( + (pin) => typeof pin === "string" && EXACT_PIN.test(pin), + ); if ( rootManifest.name !== "webhooks" || @@ -308,11 +319,8 @@ export async function validateRepository(options = {}) { fail(`${PACKAGE_DIRECTORY}/package.json has invalid public metadata`); } if ( - !sameJson(manifest.dependencies, REQUIRED_DEPENDENCIES) || - !lockDependenciesMatch( - lockDependencies?.dependencies, - REQUIRED_DEPENDENCIES, - ) + !runtimeDependenciesAreExact || + !lockDependenciesMatch(lockDependencies?.dependencies, runtimeDependencies) ) { fail("Pegma runtime dependencies must match the reviewed exact pins"); } @@ -493,6 +501,24 @@ async function smokeTest(tarball) { } } +function expectedTarballName(version) { + return `pegma-webhooks-${version}.tgz`; +} + +async function verifyReleaseArtifactInventory(directory, tarballName) { + const expectedNames = [PREPARED_MANIFEST_NAME, tarballName].sort(); + const entries = await readdir(directory, { withFileTypes: true }); + const actualNames = entries.map((entry) => entry.name).sort(); + if ( + !sameJson(actualNames, expectedNames) || + entries.some((entry) => !entry.isFile()) + ) { + fail( + `release artifact directory must contain only regular files named ${expectedNames.join(" and ")}`, + ); + } +} + export async function prepareRelease(options = {}) { const { manifest, root } = await validateRepository(options); const output = resolve(root, options.output ?? ".release"); @@ -546,15 +572,24 @@ export async function prepareRelease(options = {}) { .sort((left, right) => left.path.localeCompare(right.path)), }, }; - const preparedPath = join(output, "package-manifest.json"); + const preparedPath = join(output, PREPARED_MANIFEST_NAME); await writeFile(preparedPath, `${JSON.stringify(prepared, null, 2)}\n`); + await verifyReleaseArtifactInventory(output, basename(tarball)); return preparedPath; } -function registryIntegrity(name, version) { +function registryIntegrity(name, version, options = {}) { const result = runNpm( - ["view", `${name}@${version}`, "dist.integrity", "--json"], + [ + "view", + `${name}@${version}`, + "dist.integrity", + "--json", + "--registry", + NPM_REGISTRY, + ], { + ...options, allowFailure: true, capture: true, }, @@ -572,8 +607,11 @@ function registryIntegrity(name, version) { fail("npm registry lookup failed"); } -function requireTrustedPublishingNpm() { - const version = runNpm(["--version"], { capture: true }).stdout.trim(); +function requireTrustedPublishingNpm(options = {}) { + const version = runNpm(["--version"], { + ...options, + capture: true, + }).stdout.trim(); const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); if (match === null) { fail(`could not parse npm version ${version}`); @@ -593,9 +631,9 @@ function wait(milliseconds) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); } -function confirmRegistryIntegrity(name, version, expected) { +function confirmRegistryIntegrity(name, version, expected, options = {}) { for (let attempt = 0; attempt < 6; attempt += 1) { - const actual = registryIntegrity(name, version); + const actual = registryIntegrity(name, version, options); if (actual !== null && safeEqual(actual, expected)) { return; } @@ -607,13 +645,19 @@ function confirmRegistryIntegrity(name, version, expected) { } async function verifyPreparedArtifact(options = {}) { + const root = resolve(options.root ?? defaultRoot()); const path = resolve( - options.manifest ?? join(".release", "package-manifest.json"), + options.manifest ?? join(root, ".release", PREPARED_MANIFEST_NAME), ); - const prepared = await readJson(path); const sourceManifest = await readJson( - join(defaultRoot(), PACKAGE_DIRECTORY, "package.json"), + join(root, PACKAGE_DIRECTORY, "package.json"), ); + const expectedTarball = expectedTarballName(sourceManifest.version); + if (basename(path) !== PREPARED_MANIFEST_NAME) { + fail(`prepared manifest must be named ${PREPARED_MANIFEST_NAME}`); + } + await verifyReleaseArtifactInventory(dirname(path), expectedTarball); + const prepared = await readJson(path); if ( prepared.schemaVersion !== 1 || prepared.package?.name !== PACKAGE_NAME || @@ -630,13 +674,12 @@ async function verifyPreparedArtifact(options = {}) { } const currentCommit = run("git", ["rev-parse", "HEAD"], { capture: true, - cwd: defaultRoot(), + cwd: root, }).stdout.trim(); if (!safeEqual(currentCommit, prepared.gitCommit)) { fail("prepared release commit does not match the checkout"); } verifyPackedFiles(sourceManifest, prepared.package.files); - const expectedTarball = `pegma-webhooks-${prepared.package.version}.tgz`; if (prepared.package.tarball !== expectedTarball) { fail("prepared tarball name does not match its package version"); } @@ -670,6 +713,30 @@ export async function inspectPreparedRegistry(options = {}) { return "exact"; } +async function withIsolatedNpmEnvironment(callback) { + const directory = await mkdtemp(join(tmpdir(), "pegma-webhooks-publish-")); + const cwd = join(directory, "work"); + const userconfig = join(directory, "user.npmrc"); + const globalconfig = join(directory, "global.npmrc"); + try { + await mkdir(cwd); + await Promise.all([ + writeFile(userconfig, "", { mode: 0o600 }), + writeFile(globalconfig, "", { mode: 0o600 }), + ]); + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => !/^npm_config_/iu.test(name), + ), + ); + env.NPM_CONFIG_USERCONFIG = userconfig; + env.NPM_CONFIG_GLOBALCONFIG = globalconfig; + return await callback({ cwd, env }); + } finally { + await rm(directory, { force: true, recursive: true }); + } +} + export async function publishPrepared(options = {}) { if ( process.env.GITHUB_ACTIONS !== "true" || @@ -677,9 +744,7 @@ export async function publishPrepared(options = {}) { ) { fail("release publishing is restricted to a GitHub release workflow"); } - requireTrustedPublishingNpm(); - const { digest, path, prepared, tarball } = - await verifyPreparedArtifact(options); + const { digest, prepared, tarball } = await verifyPreparedArtifact(options); const expectedCommit = options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; @@ -691,22 +756,40 @@ export async function publishPrepared(options = {}) { ) { fail("prepared release metadata does not match the release event"); } - const existing = registryIntegrity(PACKAGE_NAME, prepared.package.version); - if (existing !== null) { - if (!safeEqual(existing, digest.integrity)) { - fail("the registry version exists with different integrity"); + await withIsolatedNpmEnvironment(async (npmOptions) => { + requireTrustedPublishingNpm(npmOptions); + const existing = registryIntegrity( + PACKAGE_NAME, + prepared.package.version, + npmOptions, + ); + if (existing !== null) { + if (!safeEqual(existing, digest.integrity)) { + fail("the registry version exists with different integrity"); + } + process.stdout.write("Registry integrity matches; skipping publish.\n"); + return; } - process.stdout.write("Registry integrity matches; skipping publish.\n"); - return; - } - runNpm(["publish", tarball, "--access", "public", "--provenance"], { - cwd: dirname(path), + runNpm( + [ + "publish", + tarball, + "--access", + "public", + "--provenance", + "--ignore-scripts", + "--registry", + NPM_REGISTRY, + ], + npmOptions, + ); + confirmRegistryIntegrity( + PACKAGE_NAME, + prepared.package.version, + digest.integrity, + npmOptions, + ); }); - confirmRegistryIntegrity( - PACKAGE_NAME, - prepared.package.version, - digest.integrity, - ); } function parseArguments(arguments_) { diff --git a/scripts/release-package.test.mjs b/scripts/release-package.test.mjs new file mode 100644 index 0000000..9ec3cea --- /dev/null +++ b/scripts/release-package.test.mjs @@ -0,0 +1,361 @@ +import { createHash } from "node:crypto"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { spawnSyncMock } = vi.hoisted(() => ({ + spawnSyncMock: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + spawnSync: spawnSyncMock, +})); + +const { prepareRelease, publishPrepared } = + await import("./release-package.mjs"); + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const PACKAGE_MANIFEST = JSON.parse( + readFileSync(join(ROOT, "packages/webhooks/package.json"), "utf8"), +); +const PACKAGE_VERSION = PACKAGE_MANIFEST.version; +const TARBALL_NAME = `pegma-webhooks-${PACKAGE_VERSION}.tgz`; +const RELEASE_TAG = `v${PACKAGE_VERSION}`; +const COMMIT = "a".repeat(40); +const NPM_REGISTRY = "https://registry.npmjs.org/"; +const PACKED_FILES = [ + { path: "LICENSE", size: 1 }, + { path: "README.md", size: 1 }, + { path: "dist/index.d.ts", size: 1 }, + { path: "dist/index.js", size: 1 }, + { path: "package.json", size: 1 }, +]; +const INVENTORY_CASES = [ + { label: "a hidden config file", kind: "file", name: ".npmrc" }, + { label: "package metadata", kind: "file", name: "package.json" }, + { label: "an extra regular file", kind: "file", name: "notes.txt" }, + { label: "a subdirectory", kind: "directory", name: "nested" }, + { label: "a linked entry", kind: "link", name: "linked-entry" }, +]; + +const temporaryDirectories = []; + +function makeTemporaryDirectory() { + const directory = mkdtempSync(join(tmpdir(), "webhooks-release-test-")); + temporaryDirectories.push(directory); + return directory; +} + +function hashes(bytes) { + return { + integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + shasum: createHash("sha1").update(bytes).digest("hex"), + }; +} + +function processResult({ status = 0, stdout = "", stderr = "" } = {}) { + return { status, stdout, stderr }; +} + +function isNpmCommand(command) { + return /(^|[\\/])npm(?:\.cmd)?$/iu.test(String(command)); +} + +function addInventoryEntry(directory, fixtureRoot, fixture) { + const path = join(directory, fixture.name); + if (fixture.kind === "file") { + writeFileSync(path, "extra\n"); + return; + } + if (fixture.kind === "directory") { + mkdirSync(path); + return; + } + const target = join(fixtureRoot, `target-${fixture.name}`); + mkdirSync(target); + symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir"); +} + +function writePreparedArtifact(directory) { + mkdirSync(directory, { recursive: true }); + const tarball = join(directory, TARBALL_NAME); + const bytes = Buffer.from("prepared release tarball\n"); + const digest = hashes(bytes); + writeFileSync(tarball, bytes); + const manifest = join(directory, "package-manifest.json"); + writeFileSync( + manifest, + `${JSON.stringify( + { + schemaVersion: 1, + gitCommit: COMMIT, + releaseTag: RELEASE_TAG, + package: { + name: "@pegma/webhooks", + version: PACKAGE_VERSION, + tarball: TARBALL_NAME, + ...digest, + files: PACKED_FILES, + }, + }, + null, + 2, + )}\n`, + ); + return { digest, manifest, tarball }; +} + +function useReleaseEnvironment() { + vi.stubEnv("GITHUB_ACTIONS", "true"); + vi.stubEnv("GITHUB_EVENT_NAME", "release"); + vi.stubEnv("RELEASE_COMMIT", COMMIT); + vi.stubEnv("RELEASE_TAG", RELEASE_TAG); +} + +function installPrepareProcessDouble(output, addEntry) { + let smokeInstallRan = false; + spawnSyncMock.mockImplementation((command, arguments_) => { + if (isNpmCommand(command) && arguments_[0] === "pack") { + const destination = + arguments_[arguments_.indexOf("--pack-destination") + 1]; + expect(resolve(destination)).toBe(resolve(output)); + const bytes = Buffer.from("packed release tarball\n"); + const digest = hashes(bytes); + writeFileSync(join(output, TARBALL_NAME), bytes); + return processResult({ + stdout: JSON.stringify([ + { + name: "@pegma/webhooks", + version: PACKAGE_VERSION, + filename: TARBALL_NAME, + files: PACKED_FILES, + ...digest, + }, + ]), + }); + } + if (isNpmCommand(command) && arguments_[0] === "install") { + smokeInstallRan = true; + addEntry(); + return processResult(); + } + if ( + command === process.execPath && + arguments_[0] === "--input-type=module" + ) { + return processResult(); + } + if ( + command === "git" && + arguments_[0] === "rev-parse" && + arguments_[1] === "HEAD" + ) { + return processResult({ stdout: `${COMMIT}\n` }); + } + throw new Error( + `unexpected process call: ${command} ${arguments_.join(" ")}`, + ); + }); + return () => smokeInstallRan; +} + +beforeEach(() => { + spawnSyncMock.mockReset(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }); + } +}); + +describe("release artifact inventory", () => { + for (const fixture of INVENTORY_CASES) { + it(`rejects ${fixture.label} after preparation`, async () => { + const fixtureRoot = makeTemporaryDirectory(); + const output = join(fixtureRoot, "artifact"); + const smokeInstallRan = installPrepareProcessDouble(output, () => { + addInventoryEntry(output, fixtureRoot, fixture); + }); + + await expect(prepareRelease({ root: ROOT, output })).rejects.toThrow( + /must contain only regular files/u, + ); + + expect(smokeInstallRan()).toBe(true); + expect(existsSync(join(output, "package-manifest.json"))).toBe(true); + }); + + it(`rejects ${fixture.label} before publishing`, async () => { + useReleaseEnvironment(); + const fixtureRoot = makeTemporaryDirectory(); + const artifact = join(fixtureRoot, "artifact"); + const { manifest } = writePreparedArtifact(artifact); + addInventoryEntry(artifact, fixtureRoot, fixture); + + await expect( + publishPrepared({ + expectedReleaseCommit: COMMIT, + manifest, + releaseTag: RELEASE_TAG, + }), + ).rejects.toThrow(/must contain only regular files/u); + + expect(spawnSyncMock).not.toHaveBeenCalled(); + }); + } +}); + +describe("prepared publishing", () => { + it("uses a clean working directory and controlled npm configuration", async () => { + useReleaseEnvironment(); + vi.stubEnv("npm_config_registry", "https://registry.example.invalid/"); + vi.stubEnv("NPM_CONFIG_CACHE", join(makeTemporaryDirectory(), "cache")); + const fixtureRoot = makeTemporaryDirectory(); + const artifact = join(fixtureRoot, "artifact"); + const { digest, manifest, tarball } = writePreparedArtifact(artifact); + let registryLookupCount = 0; + let publishCall; + + spawnSyncMock.mockImplementation((command, arguments_, options) => { + if ( + command === "git" && + arguments_[0] === "rev-parse" && + arguments_[1] === "HEAD" + ) { + return processResult({ stdout: `${COMMIT}\n` }); + } + if (isNpmCommand(command) && arguments_[0] === "--version") { + return processResult({ stdout: "11.18.0\n" }); + } + if (isNpmCommand(command) && arguments_[0] === "view") { + registryLookupCount += 1; + if (registryLookupCount === 1) { + return processResult({ status: 1, stderr: "E404\n" }); + } + return processResult({ + stdout: `${JSON.stringify(digest.integrity)}\n`, + }); + } + if (isNpmCommand(command) && arguments_[0] === "publish") { + const npmConfigKeys = Object.keys(options.env) + .filter((name) => /^npm_config_/iu.test(name)) + .sort(); + publishCall = { + arguments: [...arguments_], + cwd: options.cwd, + cwdEntries: readdirSync(options.cwd), + globalconfig: options.env.NPM_CONFIG_GLOBALCONFIG, + globalconfigContents: readFileSync( + options.env.NPM_CONFIG_GLOBALCONFIG, + "utf8", + ), + npmConfigKeys, + userconfig: options.env.NPM_CONFIG_USERCONFIG, + userconfigContents: readFileSync( + options.env.NPM_CONFIG_USERCONFIG, + "utf8", + ), + }; + return processResult(); + } + throw new Error( + `unexpected process call: ${command} ${arguments_.join(" ")}`, + ); + }); + + await publishPrepared({ + expectedReleaseCommit: COMMIT, + manifest, + releaseTag: RELEASE_TAG, + }); + + expect(publishCall).toBeDefined(); + expect(publishCall.arguments).toEqual([ + "publish", + resolve(tarball), + "--access", + "public", + "--provenance", + "--ignore-scripts", + "--registry", + NPM_REGISTRY, + ]); + expect(publishCall.cwdEntries).toEqual([]); + expect(resolve(publishCall.cwd)).not.toBe(resolve(artifact)); + expect( + resolve(publishCall.cwd).startsWith(`${resolve(artifact)}${sep}`), + ).toBe(false); + expect(publishCall.npmConfigKeys).toEqual([ + "NPM_CONFIG_GLOBALCONFIG", + "NPM_CONFIG_USERCONFIG", + ]); + expect(publishCall.userconfigContents).toBe(""); + expect(publishCall.globalconfigContents).toBe(""); + expect(dirname(publishCall.userconfig)).toBe(dirname(publishCall.cwd)); + expect(dirname(publishCall.globalconfig)).toBe(dirname(publishCall.cwd)); + expect(publishCall.userconfig).not.toBe(publishCall.globalconfig); + expect(registryLookupCount).toBe(2); + }); +}); + +describe("release workflow invariants", () => { + const publishWorkflow = readFileSync( + join(ROOT, ".github/workflows/publish.yml"), + "utf8", + ); + const ciWorkflow = readFileSync( + join(ROOT, ".github/workflows/ci.yml"), + "utf8", + ); + + it("uploads only the named manifest and tarball", () => { + const uploadStep = publishWorkflow.match( + /- name: Upload the prepared release[\s\S]*?retention-days: 30/u, + )?.[0]; + expect(uploadStep).toBeDefined(); + const uploadPaths = uploadStep + .match(/path: \|\r?\n((?:\s{12}.+\r?\n){2})/u)?.[1] + .trim() + .split(/\r?\n/u) + .map((line) => line.trim()); + expect(uploadPaths).toEqual([ + ".release/package-manifest.json", + "${{ steps.prepare-release.outputs.tarball }}", + ]); + expect(uploadStep).not.toContain("include-hidden-files"); + }); + + it("uses the release commit and an external artifact directory", () => { + const publishJob = publishWorkflow.slice( + publishWorkflow.indexOf(" publish:"), + ); + expect(publishJob).toContain("ref: ${{ github.sha }}"); + expect(publishJob).toContain("persist-credentials: false"); + expect(publishJob).toContain( + "path: ${{ runner.temp }}/webhooks-release-${{ github.run_id }}", + ); + expect(publishJob).toContain( + "working-directory: ${{ steps.publisher-directory.outputs.path }}", + ); + expect(publishJob).toContain( + 'node "${GITHUB_WORKSPACE}/scripts/release-package.mjs" publish', + ); + }); + + it("runs the release metadata check in CI", () => { + expect(ciWorkflow).toContain("run: pnpm run release:check"); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index f0c70f2..e2958bd 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { - include: ["packages/*/src/**/*.test.ts"], + include: ["packages/*/src/**/*.test.ts", "scripts/**/*.test.mjs"], exclude: ["**/dist/**", "**/node_modules/**"], globalSetup: ["./test/azurite.ts"], testTimeout: 30_000, From 2441278a5b4953c11c0e9f583a4252330eca7d1d Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 09:44:40 -0500 Subject: [PATCH 2/3] chore: address release workflow review feedback --- .github/workflows/ci.yml | 2 +- .github/workflows/publish.yml | 10 +- scripts/release-package.mjs | 96 +++++++-- scripts/release-package.test.mjs | 330 ++++++++++++++++++++++++++++--- vitest.config.ts | 19 +- 5 files changed, 401 insertions(+), 56 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a9eca9..f990a5e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest env: - CI: 1 + CI: "1" strategy: fail-fast: false matrix: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index cdd3e14..04722f2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,7 +18,7 @@ jobs: prepare: runs-on: ubuntu-latest env: - CI: 1 + CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} @@ -52,7 +52,7 @@ jobs: uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org + registry-url: https://registry.npmjs.org/ package-manager-cache: false - name: Enable Corepack @@ -116,13 +116,13 @@ jobs: name: webhooks-release-${{ github.run_id }} path: ${{ runner.temp }}/webhooks-release-${{ github.run_id }} - - name: Create a clean publisher directory - id: publisher-directory + - name: Create a clean Node invocation directory + id: node-invocation-directory shell: bash run: printf 'path=%s\n' "$(mktemp -d "${RUNNER_TEMP}/webhooks-publisher-XXXXXX")" >> "${GITHUB_OUTPUT}" - name: Publish the verified prepared tarball - working-directory: ${{ steps.publisher-directory.outputs.path }} + working-directory: ${{ steps.node-invocation-directory.outputs.path }} run: >- node "${GITHUB_WORKSPACE}/scripts/release-package.mjs" publish --manifest "${RUNNER_TEMP}/webhooks-release-${GITHUB_RUN_ID}/package-manifest.json" diff --git a/scripts/release-package.mjs b/scripts/release-package.mjs index bc413df..a6a6b6e 100644 --- a/scripts/release-package.mjs +++ b/scripts/release-package.mjs @@ -21,8 +21,35 @@ const NODE_RANGE = ">=22"; const NPM_REGISTRY = "https://registry.npmjs.org/"; const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; const WORKSPACE_PACKAGES = ["packages/*"]; -const REQUIRED_DEPENDENCY_NAMES = ["@pegma/spine", "@pegma/storage-core"]; +const REQUIRED_DEPENDENCIES = Object.freeze({ + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", +}); const PREPARED_MANIFEST_NAME = "package-manifest.json"; +const PUBLISH_ENVIRONMENT_NAMES = [ + "PATH", + "HOME", + "USERPROFILE", + "TEMP", + "TMP", + "TMPDIR", + "CI", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REF", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_RUN_ATTEMPT", + "GITHUB_RUN_ID", + "GITHUB_SERVER_URL", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "RUNNER_ENVIRONMENT", +]; +const WINDOWS_PUBLISH_ENVIRONMENT_NAMES = ["SystemRoot", "ComSpec"]; function fail(message) { throw new Error(message); @@ -261,6 +288,22 @@ function lockDependenciesMatch(lockDependencies, required) { }); } +function dependencyPinsMatch(actual, required) { + if (actual === null || typeof actual !== "object" || Array.isArray(actual)) { + return false; + } + const requiredNames = Object.keys(required).sort(); + if (!sameJson(Object.keys(actual).sort(), requiredNames)) { + return false; + } + return requiredNames.every( + (name) => + typeof actual[name] === "string" && + EXACT_PIN.test(actual[name]) && + actual[name] === required[name], + ); +} + export async function validateRepository(options = {}) { const root = resolve(options.root ?? defaultRoot()); const rootManifest = await readJson(join(root, "package.json")); @@ -280,18 +323,6 @@ export async function validateRepository(options = {}) { ) .filter((entry) => entry.isDirectory()) .map((entry) => entry.name); - const runtimeDependencies = manifest.dependencies; - const runtimeDependenciesAreExact = - runtimeDependencies !== null && - typeof runtimeDependencies === "object" && - !Array.isArray(runtimeDependencies) && - sameJson( - Object.keys(runtimeDependencies).sort(), - [...REQUIRED_DEPENDENCY_NAMES].sort(), - ) && - Object.values(runtimeDependencies).every( - (pin) => typeof pin === "string" && EXACT_PIN.test(pin), - ); if ( rootManifest.name !== "webhooks" || @@ -319,8 +350,11 @@ export async function validateRepository(options = {}) { fail(`${PACKAGE_DIRECTORY}/package.json has invalid public metadata`); } if ( - !runtimeDependenciesAreExact || - !lockDependenciesMatch(lockDependencies?.dependencies, runtimeDependencies) + !dependencyPinsMatch(manifest.dependencies, REQUIRED_DEPENDENCIES) || + !lockDependenciesMatch( + lockDependencies?.dependencies, + REQUIRED_DEPENDENCIES, + ) ) { fail("Pegma runtime dependencies must match the reviewed exact pins"); } @@ -513,8 +547,20 @@ async function verifyReleaseArtifactInventory(directory, tarballName) { !sameJson(actualNames, expectedNames) || entries.some((entry) => !entry.isFile()) ) { + const actualEntries = entries + .map((entry) => { + const type = entry.isFile() + ? "file" + : entry.isDirectory() + ? "directory" + : entry.isSymbolicLink() + ? "link" + : "other"; + return `${entry.name} (${type})`; + }) + .sort(); fail( - `release artifact directory must contain only regular files named ${expectedNames.join(" and ")}`, + `release artifact inventory mismatch: expected regular files ${JSON.stringify(expectedNames)}; found ${JSON.stringify(actualEntries)}`, ); } } @@ -724,11 +770,19 @@ async function withIsolatedNpmEnvironment(callback) { writeFile(userconfig, "", { mode: 0o600 }), writeFile(globalconfig, "", { mode: 0o600 }), ]); - const env = Object.fromEntries( - Object.entries(process.env).filter( - ([name]) => !/^npm_config_/iu.test(name), - ), - ); + const names = [ + ...PUBLISH_ENVIRONMENT_NAMES, + ...(process.platform === "win32" + ? WINDOWS_PUBLISH_ENVIRONMENT_NAMES + : []), + ]; + const env = {}; + for (const name of names) { + const value = process.env[name]; + if (value !== undefined) { + env[name] = value; + } + } env.NPM_CONFIG_USERCONFIG = userconfig; env.NPM_CONFIG_GLOBALCONFIG = globalconfig; return await callback({ cwd, env }); diff --git a/scripts/release-package.test.mjs b/scripts/release-package.test.mjs index 9ec3cea..43f9a53 100644 --- a/scripts/release-package.test.mjs +++ b/scripts/release-package.test.mjs @@ -22,7 +22,7 @@ vi.mock("node:child_process", () => ({ spawnSync: spawnSyncMock, })); -const { prepareRelease, publishPrepared } = +const { prepareRelease, publishPrepared, validateRepository } = await import("./release-package.mjs"); const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); @@ -34,6 +34,65 @@ const TARBALL_NAME = `pegma-webhooks-${PACKAGE_VERSION}.tgz`; const RELEASE_TAG = `v${PACKAGE_VERSION}`; const COMMIT = "a".repeat(40); const NPM_REGISTRY = "https://registry.npmjs.org/"; +const REVIEWED_DEPENDENCIES = { + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", +}; +const PUBLISH_ENVIRONMENT_NAMES = [ + "PATH", + "HOME", + "USERPROFILE", + "TEMP", + "TMP", + "TMPDIR", + "CI", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REF", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_RUN_ATTEMPT", + "GITHUB_RUN_ID", + "GITHUB_SERVER_URL", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "RUNNER_ENVIRONMENT", + ...(process.platform === "win32" ? ["SystemRoot", "ComSpec"] : []), + "NPM_CONFIG_GLOBALCONFIG", + "NPM_CONFIG_USERCONFIG", +]; +const PROVENANCE_ENVIRONMENT = { + ACTIONS_ID_TOKEN_REQUEST_URL: "https://actions.example.test/id-token", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "workflow-token", + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_REF: "refs/tags/v0.1.1", + GITHUB_REPOSITORY: "pegma-dev/webhooks", + GITHUB_REPOSITORY_ID: "1234", + GITHUB_REPOSITORY_OWNER_ID: "5678", + GITHUB_RUN_ATTEMPT: "1", + GITHUB_RUN_ID: "9012", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_SHA: COMMIT, + GITHUB_WORKFLOW_REF: + "pegma-dev/webhooks/.github/workflows/publish.yml@refs/tags/v0.1.1", + RUNNER_ENVIRONMENT: "github-hosted", +}; +const DISCARDED_ENVIRONMENT = { + ALL_PROXY: "http://proxy.example.test", + HTTP_PROXY: "http://proxy.example.test", + HTTPS_PROXY: "http://proxy.example.test", + NODE_EXTRA_CA_CERTS: "C:/untrusted/ca.pem", + NODE_OPTIONS: "--require=C:/untrusted/setup.cjs", + NO_PROXY: "registry.example.test", + NPM_CONFIG_CACHE: "C:/untrusted/cache", + NPM_TOKEN: "ambient-token", + npm_config_registry: "https://registry.example.invalid/", + UNRELATED_RELEASE_VALUE: "discarded", +}; const PACKED_FILES = [ { path: "LICENSE", size: 1 }, { path: "README.md", size: 1 }, @@ -68,6 +127,43 @@ function processResult({ status = 0, stdout = "", stderr = "" } = {}) { return { status, stdout, stderr }; } +function workflowStep(workflow, name) { + const lines = workflow.split(/\r?\n/u); + const start = lines.findIndex((line) => line.trim() === `- name: ${name}`); + if (start === -1) { + throw new Error(`workflow step not found: ${name}`); + } + const stepIndent = /^\s*/u.exec(lines[start])[0].length; + let end = start + 1; + while (end < lines.length) { + const line = lines[end]; + if (line.trim() !== "" && /^\s*/u.exec(line)[0].length <= stepIndent) { + break; + } + end += 1; + } + return lines.slice(start, end); +} + +function blockScalarValues(step, key) { + const start = step.findIndex((line) => line.trim() === `${key}: |`); + if (start === -1) { + throw new Error(`workflow block not found: ${key}`); + } + const keyIndent = /^\s*/u.exec(step[start])[0].length; + const values = []; + for (const line of step.slice(start + 1)) { + if (line.trim() === "") { + continue; + } + if (/^\s*/u.exec(line)[0].length <= keyIndent) { + break; + } + values.push(line.trim()); + } + return values; +} + function isNpmCommand(command) { return /(^|[\\/])npm(?:\.cmd)?$/iu.test(String(command)); } @@ -87,13 +183,16 @@ function addInventoryEntry(directory, fixtureRoot, fixture) { symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir"); } -function writePreparedArtifact(directory) { +function writePreparedArtifact( + directory, + { manifestName = "package-manifest.json" } = {}, +) { mkdirSync(directory, { recursive: true }); const tarball = join(directory, TARBALL_NAME); const bytes = Buffer.from("prepared release tarball\n"); const digest = hashes(bytes); writeFileSync(tarball, bytes); - const manifest = join(directory, "package-manifest.json"); + const manifest = join(directory, manifestName); writeFileSync( manifest, `${JSON.stringify( @@ -116,6 +215,57 @@ function writePreparedArtifact(directory) { return { digest, manifest, tarball }; } +function lockDependenciesFromPins(pins) { + return Object.fromEntries( + Object.entries(pins).map(([name, pin]) => [ + name, + { specifier: pin, version: pin }, + ]), + ); +} + +function writeRepositoryFixture({ + manifestDependencies = REVIEWED_DEPENDENCIES, + lockDependencies = lockDependenciesFromPins(manifestDependencies), +} = {}) { + const fixtureRoot = makeTemporaryDirectory(); + const packageRoot = join(fixtureRoot, "packages/webhooks"); + mkdirSync(packageRoot, { recursive: true }); + writeFileSync( + join(fixtureRoot, "package.json"), + readFileSync(join(ROOT, "package.json"), "utf8"), + ); + writeFileSync( + join(fixtureRoot, "pnpm-workspace.yaml"), + readFileSync(join(ROOT, "pnpm-workspace.yaml"), "utf8"), + ); + writeFileSync( + join(packageRoot, "package.json"), + `${JSON.stringify( + { ...PACKAGE_MANIFEST, dependencies: manifestDependencies }, + null, + 2, + )}\n`, + ); + writeFileSync(join(packageRoot, "README.md"), "# Fixture\n"); + writeFileSync(join(packageRoot, "LICENSE"), "MIT\n"); + writeFileSync( + join(packageRoot, "tsconfig.json"), + '{"exclude":["src/**/*.test.ts"]}\n', + ); + const lockEntries = Object.entries(lockDependencies) + .map( + ([name, { specifier, version }]) => + ` '${name}':\n specifier: ${specifier}\n version: ${version}`, + ) + .join("\n"); + writeFileSync( + join(fixtureRoot, "pnpm-lock.yaml"), + `lockfileVersion: '9.0'\n\nimporters:\n\n packages/webhooks:\n dependencies:\n${lockEntries}\n`, + ); + return fixtureRoot; +} + function useReleaseEnvironment() { vi.stubEnv("GITHUB_ACTIONS", "true"); vi.stubEnv("GITHUB_EVENT_NAME", "release"); @@ -181,6 +331,70 @@ afterEach(() => { } }); +describe("release dependency pins", () => { + it("rejects matching package and lock pins outside the reviewed set", async () => { + const dependencies = { + ...REVIEWED_DEPENDENCIES, + "@pegma/spine": "0.1.3", + }; + const root = writeRepositoryFixture({ + manifestDependencies: dependencies, + lockDependencies: lockDependenciesFromPins(dependencies), + }); + + await expect(validateRepository({ root })).rejects.toThrow( + /must match the reviewed exact pins/u, + ); + }); + + it("rejects a lock pin that differs from the reviewed set", async () => { + const lockDependencies = lockDependenciesFromPins(REVIEWED_DEPENDENCIES); + lockDependencies["@pegma/spine"] = { + specifier: "0.1.3", + version: "0.1.3", + }; + const root = writeRepositoryFixture({ lockDependencies }); + + await expect(validateRepository({ root })).rejects.toThrow( + /must match the reviewed exact pins/u, + ); + }); + + it("rejects a non-exact package pin", async () => { + const dependencies = { + ...REVIEWED_DEPENDENCIES, + "@pegma/spine": "^0.1.2", + }; + const lockDependencies = lockDependenciesFromPins(REVIEWED_DEPENDENCIES); + lockDependencies["@pegma/spine"] = { + specifier: "^0.1.2", + version: "0.1.2", + }; + const root = writeRepositoryFixture({ + manifestDependencies: dependencies, + lockDependencies, + }); + + await expect(validateRepository({ root })).rejects.toThrow( + /must match the reviewed exact pins/u, + ); + }); +}); + +describe("release preparation", () => { + it("rejects a non-empty output directory before packing", async () => { + const fixtureRoot = makeTemporaryDirectory(); + const output = join(fixtureRoot, "artifact"); + mkdirSync(output); + writeFileSync(join(output, "notes.txt"), "existing\n"); + + await expect(prepareRelease({ root: ROOT, output })).rejects.toThrow( + /release output directory must be empty/u, + ); + expect(spawnSyncMock).not.toHaveBeenCalled(); + }); +}); + describe("release artifact inventory", () => { for (const fixture of INVENTORY_CASES) { it(`rejects ${fixture.label} after preparation`, async () => { @@ -191,7 +405,7 @@ describe("release artifact inventory", () => { }); await expect(prepareRelease({ root: ROOT, output })).rejects.toThrow( - /must contain only regular files/u, + /expected regular files .* found/u, ); expect(smokeInstallRan()).toBe(true); @@ -211,7 +425,7 @@ describe("release artifact inventory", () => { manifest, releaseTag: RELEASE_TAG, }), - ).rejects.toThrow(/must contain only regular files/u); + ).rejects.toThrow(/expected regular files .* found/u); expect(spawnSyncMock).not.toHaveBeenCalled(); }); @@ -219,10 +433,34 @@ describe("release artifact inventory", () => { }); describe("prepared publishing", () => { + it("requires the canonical prepared manifest name", async () => { + useReleaseEnvironment(); + const fixtureRoot = makeTemporaryDirectory(); + const artifact = join(fixtureRoot, "artifact"); + const { manifest } = writePreparedArtifact(artifact, { + manifestName: "prepared.json", + }); + + await expect( + publishPrepared({ + expectedReleaseCommit: COMMIT, + manifest, + releaseTag: RELEASE_TAG, + }), + ).rejects.toThrow( + /prepared manifest must be named package-manifest\.json/u, + ); + expect(spawnSyncMock).not.toHaveBeenCalled(); + }); + it("uses a clean working directory and controlled npm configuration", async () => { useReleaseEnvironment(); - vi.stubEnv("npm_config_registry", "https://registry.example.invalid/"); - vi.stubEnv("NPM_CONFIG_CACHE", join(makeTemporaryDirectory(), "cache")); + for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { + vi.stubEnv(name, value); + } + for (const [name, value] of Object.entries(DISCARDED_ENVIRONMENT)) { + vi.stubEnv(name, value); + } const fixtureRoot = makeTemporaryDirectory(); const artifact = join(fixtureRoot, "artifact"); const { digest, manifest, tarball } = writePreparedArtifact(artifact); @@ -262,6 +500,7 @@ describe("prepared publishing", () => { options.env.NPM_CONFIG_GLOBALCONFIG, "utf8", ), + environment: { ...options.env }, npmConfigKeys, userconfig: options.env.NPM_CONFIG_USERCONFIG, userconfigContents: readFileSync( @@ -302,6 +541,19 @@ describe("prepared publishing", () => { "NPM_CONFIG_GLOBALCONFIG", "NPM_CONFIG_USERCONFIG", ]); + expect( + Object.keys(publishCall.environment).filter( + (name) => !PUBLISH_ENVIRONMENT_NAMES.includes(name), + ), + ).toEqual([]); + for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { + expect(publishCall.environment[name]).toBe(value); + } + for (const name of Object.keys(DISCARDED_ENVIRONMENT)) { + expect(publishCall.environment).not.toHaveProperty(name); + } + expect(publishCall.environment).not.toHaveProperty("RELEASE_COMMIT"); + expect(publishCall.environment).not.toHaveProperty("RELEASE_TAG"); expect(publishCall.userconfigContents).toBe(""); expect(publishCall.globalconfigContents).toBe(""); expect(dirname(publishCall.userconfig)).toBe(dirname(publishCall.cwd)); @@ -322,40 +574,64 @@ describe("release workflow invariants", () => { ); it("uploads only the named manifest and tarball", () => { - const uploadStep = publishWorkflow.match( - /- name: Upload the prepared release[\s\S]*?retention-days: 30/u, - )?.[0]; - expect(uploadStep).toBeDefined(); - const uploadPaths = uploadStep - .match(/path: \|\r?\n((?:\s{12}.+\r?\n){2})/u)?.[1] - .trim() - .split(/\r?\n/u) - .map((line) => line.trim()); - expect(uploadPaths).toEqual([ + const uploadStep = workflowStep( + publishWorkflow, + "Upload the prepared release", + ); + expect(blockScalarValues(uploadStep, "path")).toEqual([ ".release/package-manifest.json", "${{ steps.prepare-release.outputs.tarball }}", ]); - expect(uploadStep).not.toContain("include-hidden-files"); + expect(uploadStep.join("\n")).not.toContain("include-hidden-files"); }); it("uses the release commit and an external artifact directory", () => { - const publishJob = publishWorkflow.slice( - publishWorkflow.indexOf(" publish:"), + const checkoutStep = workflowStep( + publishWorkflow, + "Check out the release commit", ); - expect(publishJob).toContain("ref: ${{ github.sha }}"); - expect(publishJob).toContain("persist-credentials: false"); - expect(publishJob).toContain( + expect(checkoutStep.join("\n")).toContain("ref: ${{ github.sha }}"); + expect(checkoutStep.join("\n")).toContain("persist-credentials: false"); + + const downloadStep = workflowStep( + publishWorkflow, + "Download the prepared release", + ); + expect(downloadStep.join("\n")).toContain( "path: ${{ runner.temp }}/webhooks-release-${{ github.run_id }}", ); - expect(publishJob).toContain( - "working-directory: ${{ steps.publisher-directory.outputs.path }}", + + const invocationStep = workflowStep( + publishWorkflow, + "Create a clean Node invocation directory", + ); + expect(invocationStep.join("\n")).toContain( + "id: node-invocation-directory", + ); + + const publishStep = workflowStep( + publishWorkflow, + "Publish the verified prepared tarball", ); - expect(publishJob).toContain( + expect(publishStep.join("\n")).toContain( + "working-directory: ${{ steps.node-invocation-directory.outputs.path }}", + ); + expect(publishStep.join("\n")).toContain( 'node "${GITHUB_WORKSPACE}/scripts/release-package.mjs" publish', ); }); + it("uses string CI flags and one registry URL", () => { + const setupStep = workflowStep(publishWorkflow, "Set up Node.js"); + expect(setupStep.join("\n")).toContain(`registry-url: ${NPM_REGISTRY}`); + expect(ciWorkflow).toContain('CI: "1"'); + expect(publishWorkflow).toContain('CI: "1"'); + }); + it("runs the release metadata check in CI", () => { - expect(ciWorkflow).toContain("run: pnpm run release:check"); + const releaseCheckStep = workflowStep(ciWorkflow, "Check release metadata"); + expect(releaseCheckStep.join("\n")).toContain( + "run: pnpm run release:check", + ); }); }); diff --git a/vitest.config.ts b/vitest.config.ts index e2958bd..102adcd 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,9 +2,24 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { - include: ["packages/*/src/**/*.test.ts", "scripts/**/*.test.mjs"], exclude: ["**/dist/**", "**/node_modules/**"], - globalSetup: ["./test/azurite.ts"], testTimeout: 30_000, + projects: [ + { + extends: true, + test: { + name: "webhooks", + include: ["packages/*/src/**/*.test.ts"], + globalSetup: ["./test/azurite.ts"], + }, + }, + { + extends: true, + test: { + name: "release", + include: ["scripts/**/*.test.mjs"], + }, + }, + ], }, }); From dbf0bba382e802edd5181409fb5759b7ecfd8ab0 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 10:00:47 -0500 Subject: [PATCH 3/3] chore: isolate remaining release npm operations --- scripts/release-package.mjs | 55 +++++---- scripts/release-package.test.mjs | 191 ++++++++++++++++++++++--------- 2 files changed, 167 insertions(+), 79 deletions(-) diff --git a/scripts/release-package.mjs b/scripts/release-package.mjs index a6a6b6e..c0382fd 100644 --- a/scripts/release-package.mjs +++ b/scripts/release-package.mjs @@ -26,7 +26,7 @@ const REQUIRED_DEPENDENCIES = Object.freeze({ "@pegma/storage-core": "0.4.0", }); const PREPARED_MANIFEST_NAME = "package-manifest.json"; -const PUBLISH_ENVIRONMENT_NAMES = [ +const ISOLATED_NPM_ENVIRONMENT_NAMES = [ "PATH", "HOME", "USERPROFILE", @@ -49,7 +49,7 @@ const PUBLISH_ENVIRONMENT_NAMES = [ "GITHUB_WORKFLOW_REF", "RUNNER_ENVIRONMENT", ]; -const WINDOWS_PUBLISH_ENVIRONMENT_NAMES = ["SystemRoot", "ComSpec"]; +const WINDOWS_NPM_ENVIRONMENT_NAMES = ["SystemRoot", "ComSpec"]; function fail(message) { throw new Error(message); @@ -506,10 +506,9 @@ function verifyPackedFiles(manifest, files) { } async function smokeTest(tarball) { - const directory = await mkdtemp(join(tmpdir(), "pegma-webhooks-smoke-")); - try { + await withIsolatedNpmEnvironment(async ({ cwd, env }) => { await writeFile( - join(directory, "package.json"), + join(cwd, "package.json"), '{"private":true,"type":"module"}\n', ); runNpm( @@ -519,20 +518,20 @@ async function smokeTest(tarball) { "--no-audit", "--no-fund", "--package-lock=false", + "--registry", + NPM_REGISTRY, tarball, ], - { capture: true, cwd: directory }, + { capture: true, cwd, env }, ); for (const specifier of [PACKAGE_NAME]) { run( process.execPath, ["--input-type=module", "--eval", `await import("${specifier}")`], - { capture: true, cwd: directory }, + { capture: true, cwd, env }, ); } - } finally { - await rm(directory, { force: true, recursive: true }); - } + }); } function expectedTarballName(version) { @@ -745,22 +744,30 @@ async function verifyPreparedArtifact(options = {}) { export async function inspectPreparedRegistry(options = {}) { const { digest, prepared } = await verifyPreparedArtifact(options); - const existing = registryIntegrity(PACKAGE_NAME, prepared.package.version); - if (existing === null) { + return withIsolatedNpmEnvironment(async (npmOptions) => { + const existing = registryIntegrity( + PACKAGE_NAME, + prepared.package.version, + npmOptions, + ); + if (existing === null) { + process.stdout.write( + `${PACKAGE_NAME}@${prepared.package.version}: absent\n`, + ); + return "absent"; + } + if (!safeEqual(existing, digest.integrity)) { + fail("the registry version exists with different integrity"); + } process.stdout.write( - `${PACKAGE_NAME}@${prepared.package.version}: absent\n`, + `${PACKAGE_NAME}@${prepared.package.version}: exact\n`, ); - return "absent"; - } - if (!safeEqual(existing, digest.integrity)) { - fail("the registry version exists with different integrity"); - } - process.stdout.write(`${PACKAGE_NAME}@${prepared.package.version}: exact\n`); - return "exact"; + return "exact"; + }); } async function withIsolatedNpmEnvironment(callback) { - const directory = await mkdtemp(join(tmpdir(), "pegma-webhooks-publish-")); + const directory = await mkdtemp(join(tmpdir(), "pegma-webhooks-npm-")); const cwd = join(directory, "work"); const userconfig = join(directory, "user.npmrc"); const globalconfig = join(directory, "global.npmrc"); @@ -771,10 +778,8 @@ async function withIsolatedNpmEnvironment(callback) { writeFile(globalconfig, "", { mode: 0o600 }), ]); const names = [ - ...PUBLISH_ENVIRONMENT_NAMES, - ...(process.platform === "win32" - ? WINDOWS_PUBLISH_ENVIRONMENT_NAMES - : []), + ...ISOLATED_NPM_ENVIRONMENT_NAMES, + ...(process.platform === "win32" ? WINDOWS_NPM_ENVIRONMENT_NAMES : []), ]; const env = {}; for (const name of names) { diff --git a/scripts/release-package.test.mjs b/scripts/release-package.test.mjs index 43f9a53..3ff2700 100644 --- a/scripts/release-package.test.mjs +++ b/scripts/release-package.test.mjs @@ -22,8 +22,12 @@ vi.mock("node:child_process", () => ({ spawnSync: spawnSyncMock, })); -const { prepareRelease, publishPrepared, validateRepository } = - await import("./release-package.mjs"); +const { + inspectPreparedRegistry, + prepareRelease, + publishPrepared, + validateRepository, +} = await import("./release-package.mjs"); const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const PACKAGE_MANIFEST = JSON.parse( @@ -38,7 +42,7 @@ const REVIEWED_DEPENDENCIES = { "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0", }; -const PUBLISH_ENVIRONMENT_NAMES = [ +const ISOLATED_NPM_ENVIRONMENT_NAMES = [ "PATH", "HOME", "USERPROFILE", @@ -90,6 +94,8 @@ const DISCARDED_ENVIRONMENT = { NO_PROXY: "registry.example.test", NPM_CONFIG_CACHE: "C:/untrusted/cache", NPM_TOKEN: "ambient-token", + RELEASE_COMMIT: COMMIT, + RELEASE_TAG, npm_config_registry: "https://registry.example.invalid/", UNRELATED_RELEASE_VALUE: "discarded", }; @@ -273,9 +279,60 @@ function useReleaseEnvironment() { vi.stubEnv("RELEASE_TAG", RELEASE_TAG); } -function installPrepareProcessDouble(output, addEntry) { +function useNpmEnvironmentFixtures() { + for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { + vi.stubEnv(name, value); + } + for (const [name, value] of Object.entries(DISCARDED_ENVIRONMENT)) { + vi.stubEnv(name, value); + } +} + +function captureNpmCall(arguments_, options) { + return { + arguments: [...arguments_], + cwd: options.cwd, + cwdEntries: readdirSync(options.cwd), + environment: { ...options.env }, + globalconfig: options.env.NPM_CONFIG_GLOBALCONFIG, + globalconfigContents: readFileSync( + options.env.NPM_CONFIG_GLOBALCONFIG, + "utf8", + ), + npmConfigKeys: Object.keys(options.env) + .filter((name) => /^npm_config_/iu.test(name)) + .sort(), + userconfig: options.env.NPM_CONFIG_USERCONFIG, + userconfigContents: readFileSync(options.env.NPM_CONFIG_USERCONFIG, "utf8"), + }; +} + +function expectIsolatedNpmEnvironment(call) { + expect(call.npmConfigKeys).toEqual([ + "NPM_CONFIG_GLOBALCONFIG", + "NPM_CONFIG_USERCONFIG", + ]); + expect( + Object.keys(call.environment).filter( + (name) => !ISOLATED_NPM_ENVIRONMENT_NAMES.includes(name), + ), + ).toEqual([]); + for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { + expect(call.environment[name]).toBe(value); + } + for (const name of Object.keys(DISCARDED_ENVIRONMENT)) { + expect(call.environment).not.toHaveProperty(name); + } + expect(call.userconfigContents).toBe(""); + expect(call.globalconfigContents).toBe(""); + expect(dirname(call.userconfig)).toBe(dirname(call.cwd)); + expect(dirname(call.globalconfig)).toBe(dirname(call.cwd)); + expect(call.userconfig).not.toBe(call.globalconfig); +} + +function installPrepareProcessDouble(output, onSmokeInstall = () => {}) { let smokeInstallRan = false; - spawnSyncMock.mockImplementation((command, arguments_) => { + spawnSyncMock.mockImplementation((command, arguments_, options) => { if (isNpmCommand(command) && arguments_[0] === "pack") { const destination = arguments_[arguments_.indexOf("--pack-destination") + 1]; @@ -297,7 +354,7 @@ function installPrepareProcessDouble(output, addEntry) { } if (isNpmCommand(command) && arguments_[0] === "install") { smokeInstallRan = true; - addEntry(); + onSmokeInstall({ arguments_, options }); return processResult(); } if ( @@ -393,6 +450,34 @@ describe("release preparation", () => { ); expect(spawnSyncMock).not.toHaveBeenCalled(); }); + + it("uses isolated npm settings for the smoke install", async () => { + useNpmEnvironmentFixtures(); + const fixtureRoot = makeTemporaryDirectory(); + const output = join(fixtureRoot, "artifact"); + let installCall; + const smokeInstallRan = installPrepareProcessDouble( + output, + ({ arguments_, options }) => { + installCall = captureNpmCall(arguments_, options); + }, + ); + + await prepareRelease({ root: ROOT, output }); + + expect(smokeInstallRan()).toBe(true); + expect(installCall).toBeDefined(); + expect(installCall.arguments).toContain("--ignore-scripts"); + expect(installCall.arguments).toContain(resolve(output, TARBALL_NAME)); + const registryIndex = installCall.arguments.indexOf("--registry"); + expect(registryIndex).toBeGreaterThan(-1); + expect(installCall.arguments[registryIndex + 1]).toBe(NPM_REGISTRY); + expect(installCall.cwdEntries).toEqual(["package.json"]); + expect( + resolve(installCall.cwd).startsWith(`${resolve(output)}${sep}`), + ).toBe(false); + expectIsolatedNpmEnvironment(installCall); + }); }); describe("release artifact inventory", () => { @@ -432,6 +517,49 @@ describe("release artifact inventory", () => { } }); +describe("prepared registry inspection", () => { + it("uses isolated npm settings and the fixed registry", async () => { + useNpmEnvironmentFixtures(); + const fixtureRoot = makeTemporaryDirectory(); + const artifact = join(fixtureRoot, "artifact"); + const { digest, manifest } = writePreparedArtifact(artifact); + let registryCall; + + spawnSyncMock.mockImplementation((command, arguments_, options) => { + if ( + command === "git" && + arguments_[0] === "rev-parse" && + arguments_[1] === "HEAD" + ) { + return processResult({ stdout: `${COMMIT}\n` }); + } + if (isNpmCommand(command) && arguments_[0] === "view") { + registryCall = captureNpmCall(arguments_, options); + return processResult({ + stdout: `${JSON.stringify(digest.integrity)}\n`, + }); + } + throw new Error( + `unexpected process call: ${command} ${arguments_.join(" ")}`, + ); + }); + + await expect(inspectPreparedRegistry({ manifest })).resolves.toBe("exact"); + + expect(registryCall).toBeDefined(); + expect(registryCall.arguments).toEqual([ + "view", + `@pegma/webhooks@${PACKAGE_VERSION}`, + "dist.integrity", + "--json", + "--registry", + NPM_REGISTRY, + ]); + expect(registryCall.cwdEntries).toEqual([]); + expectIsolatedNpmEnvironment(registryCall); + }); +}); + describe("prepared publishing", () => { it("requires the canonical prepared manifest name", async () => { useReleaseEnvironment(); @@ -455,12 +583,7 @@ describe("prepared publishing", () => { it("uses a clean working directory and controlled npm configuration", async () => { useReleaseEnvironment(); - for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { - vi.stubEnv(name, value); - } - for (const [name, value] of Object.entries(DISCARDED_ENVIRONMENT)) { - vi.stubEnv(name, value); - } + useNpmEnvironmentFixtures(); const fixtureRoot = makeTemporaryDirectory(); const artifact = join(fixtureRoot, "artifact"); const { digest, manifest, tarball } = writePreparedArtifact(artifact); @@ -488,26 +611,7 @@ describe("prepared publishing", () => { }); } if (isNpmCommand(command) && arguments_[0] === "publish") { - const npmConfigKeys = Object.keys(options.env) - .filter((name) => /^npm_config_/iu.test(name)) - .sort(); - publishCall = { - arguments: [...arguments_], - cwd: options.cwd, - cwdEntries: readdirSync(options.cwd), - globalconfig: options.env.NPM_CONFIG_GLOBALCONFIG, - globalconfigContents: readFileSync( - options.env.NPM_CONFIG_GLOBALCONFIG, - "utf8", - ), - environment: { ...options.env }, - npmConfigKeys, - userconfig: options.env.NPM_CONFIG_USERCONFIG, - userconfigContents: readFileSync( - options.env.NPM_CONFIG_USERCONFIG, - "utf8", - ), - }; + publishCall = captureNpmCall(arguments_, options); return processResult(); } throw new Error( @@ -537,28 +641,7 @@ describe("prepared publishing", () => { expect( resolve(publishCall.cwd).startsWith(`${resolve(artifact)}${sep}`), ).toBe(false); - expect(publishCall.npmConfigKeys).toEqual([ - "NPM_CONFIG_GLOBALCONFIG", - "NPM_CONFIG_USERCONFIG", - ]); - expect( - Object.keys(publishCall.environment).filter( - (name) => !PUBLISH_ENVIRONMENT_NAMES.includes(name), - ), - ).toEqual([]); - for (const [name, value] of Object.entries(PROVENANCE_ENVIRONMENT)) { - expect(publishCall.environment[name]).toBe(value); - } - for (const name of Object.keys(DISCARDED_ENVIRONMENT)) { - expect(publishCall.environment).not.toHaveProperty(name); - } - expect(publishCall.environment).not.toHaveProperty("RELEASE_COMMIT"); - expect(publishCall.environment).not.toHaveProperty("RELEASE_TAG"); - expect(publishCall.userconfigContents).toBe(""); - expect(publishCall.globalconfigContents).toBe(""); - expect(dirname(publishCall.userconfig)).toBe(dirname(publishCall.cwd)); - expect(dirname(publishCall.globalconfig)).toBe(dirname(publishCall.cwd)); - expect(publishCall.userconfig).not.toBe(publishCall.globalconfig); + expectIsolatedNpmEnvironment(publishCall); expect(registryLookupCount).toBe(2); }); });