diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 25acea2..309050f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,8 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + outputs: + manifest_digest: ${{ steps.manifest.outputs.digest }} env: RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} @@ -24,40 +26,66 @@ jobs: RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 0 - - - name: Fetch the protected release branch - run: git fetch --no-tags origin main:refs/remotes/origin/main - - - name: Configure approved release signers + - name: Authenticate the release tag shell: bash run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::RELEASE_TAG must be a stable supported version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::RELEASE_COMMIT must be an exact commit" + exit 1 + fi if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then - echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed entries" exit 1 fi - allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + release_repo="$(mktemp -d "${RUNNER_TEMP}/release-git.XXXXXX")" + trap 'rm -rf "${release_repo}"' EXIT + git init --bare "${release_repo}" + git -C "${release_repo}" remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + allowed_signers="${release_repo}/allowed-signers" umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" - git config --local gpg.format ssh - git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${release_repo}" config gpg.format ssh + git -C "${release_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${release_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${release_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${release_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${release_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + [[ "${tag_commit}" == "${RELEASE_COMMIT,,}" ]] + git -C "${release_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + + - name: Set up pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + with: + version: 10.34.5 - 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 + cache: pnpm - 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 @@ -71,25 +99,101 @@ jobs: - name: Run tests run: pnpm test - - name: Prepare and verify release tarballs - run: pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + - name: Prepare release tarballs + run: pnpm run release:pack -- --require-clean --output .release + + - name: Record the package manifest digest + id: manifest + shell: bash + run: | + set -euo pipefail + digest="$(sha256sum .release/package-manifest.json | cut -d ' ' -f 1)" + [[ "${digest}" =~ ^[0-9a-f]{64}$ ]] + printf 'digest=%s\n' "${digest}" >> "${GITHUB_OUTPUT}" - name: Upload the prepared release - id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: scheduler-release-${{ github.run_id }} path: .release/ if-no-files-found: error - include-hidden-files: true + include-hidden-files: false overwrite: true retention-days: 30 - - name: Record the prepared artifact digest - run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + smoke: + needs: prepare + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + 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: scheduler-release-${{ github.run_id }} + path: .release + + - name: Install and import the prepared packages + shell: bash + env: + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + run: | + set -euo pipefail + smoke_dir="$(mktemp -d "${RUNNER_TEMP}/release-smoke.XXXXXX")" + trap 'rm -rf "${smoke_dir}"' EXIT + printf '%s\n' '{"name":"release-smoke","private":true,"type":"module"}' > "${smoke_dir}/package.json" + release_manifest="${GITHUB_WORKSPACE}/.release/package-manifest.json" + tarball_list="${RUNNER_TEMP}/release-tarballs" + export RELEASE_MANIFEST="${release_manifest}" + node --input-type=module > "${tarball_list}" <<'NODE' + import { createHash, timingSafeEqual } from "node:crypto"; + import { readFile } from "node:fs/promises"; + import { dirname, resolve } from "node:path"; + const equal = (left, right) => { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); + }; + const manifestBytes = await readFile(process.env.RELEASE_MANIFEST); + const digest = createHash("sha256").update(manifestBytes).digest("hex"); + if (!equal(digest, process.env.MANIFEST_DIGEST ?? "")) throw new Error("package manifest digest does not match"); + const manifest = JSON.parse(manifestBytes.toString("utf8")); + if (!Array.isArray(manifest.packages) || manifest.packages.length === 0) throw new Error("package manifest inventory is invalid"); + for (const record of manifest.packages) { + if (!Array.isArray(record.imports) || record.imports.length === 0) throw new Error(`${record.name} import inventory is invalid`); + const tarball = resolve(dirname(process.env.RELEASE_MANIFEST), record.tarball); + const bytes = await readFile(tarball); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (!equal(sha256, record.sha256) || !equal(integrity, record.integrity)) throw new Error(`${record.name} package digest does not match`); + console.log(tarball); + } + NODE + mapfile -t tarballs < "${tarball_list}" + [[ "${#tarballs[@]}" -gt 0 ]] + npm install --prefix "${smoke_dir}" --ignore-scripts --no-audit --no-fund \ + --package-lock=false --registry https://registry.npmjs.org/ "${tarballs[@]}" + cd "${smoke_dir}" + node --input-type=module <<'NODE' + import { readFile } from "node:fs/promises"; + const manifest = JSON.parse(await readFile(process.env.RELEASE_MANIFEST, "utf8")); + for (const record of manifest.packages) { + for (const specifier of record.imports) await import(specifier); + } + NODE publish: - needs: prepare + needs: [prepare, smoke] runs-on: ubuntu-latest environment: npm-publish permissions: @@ -97,24 +201,59 @@ jobs: id-token: write env: RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the exact release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 1 + - name: Authenticate the release tag + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::RELEASE_TAG must be a stable supported version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::RELEASE_COMMIT must be an exact commit" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed entries" + exit 1 + fi + release_repo="$(mktemp -d "${RUNNER_TEMP}/release-git.XXXXXX")" + trap 'rm -rf "${release_repo}"' EXIT + git init --bare "${release_repo}" + git -C "${release_repo}" remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + allowed_signers="${release_repo}/allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${release_repo}" config gpg.format ssh + git -C "${release_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${release_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${release_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${release_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${release_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + [[ "${tag_commit}" == "${RELEASE_COMMIT,,}" ]] + git -C "${release_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main - - name: Set up Node.js and the npm registry + - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + 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 @@ -122,5 +261,99 @@ jobs: name: scheduler-release-${{ github.run_id }} path: .release - - name: Publish verified prepared tarballs - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + - name: Verify and publish the prepared packages + env: + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + run: | + node --input-type=module <<'NODE' + import { spawnSync } from "node:child_process"; + import { createHash, timingSafeEqual } from "node:crypto"; + import { lstat, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; + import { tmpdir } from "node:os"; + import { resolve } from "node:path"; + + const fail = (message) => { throw new Error(message); }; + const equal = (left, right) => { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); + }; + const releaseDirectory = resolve(".release"); + const manifestPath = resolve(releaseDirectory, "package-manifest.json"); + const manifestBytes = await readFile(manifestPath); + const digest = createHash("sha256").update(manifestBytes).digest("hex"); + if (!equal(digest, process.env.MANIFEST_DIGEST ?? "")) fail("package manifest digest does not match"); + const manifest = JSON.parse(manifestBytes.toString("utf8")); + const names = ["@pegma/scheduler", "@pegma/scheduler-cloudflare"]; + const releaseCommit = (process.env.RELEASE_COMMIT ?? "").toLowerCase(); + if (manifest.schemaVersion !== 1 || manifest.gitCommit !== releaseCommit || + manifest.releaseTag !== process.env.RELEASE_TAG || !Array.isArray(manifest.packages) || + JSON.stringify(manifest.packages.map(({ name }) => name)) !== JSON.stringify(names)) { + fail("package manifest inventory is invalid"); + } + const expectedFiles = ["package-manifest.json"]; + const directories = ["scheduler", "scheduler-cloudflare"]; + for (const [index, record] of manifest.packages.entries()) { + const expectedTarball = `${names[index].slice(1).replace("/", "-")}-${record.version}.tgz`; + if (record.directory !== directories[index] || record.tarball !== expectedTarball || + !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(record.version) || + record.publish !== (record.version === manifest.releaseTag.slice(1)) || + !/^[0-9a-f]{64}$/.test(record.sha256) || !/^[0-9a-f]{40}$/.test(record.shasum) || + !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(record.integrity) || + !Array.isArray(record.files) || !Array.isArray(record.imports) || record.imports.length === 0) { + fail(`${record.name} package metadata is invalid`); + } + expectedFiles.push(record.tarball); + } + const entries = await readdir(releaseDirectory, { withFileTypes: true }); + if (JSON.stringify(entries.map(({ name }) => name).sort()) !== JSON.stringify(expectedFiles.sort())) { + fail("release artifact inventory is invalid"); + } + for (const entry of entries) { + const metadata = await lstat(resolve(releaseDirectory, entry.name)); + if (entry.name.startsWith(".") || !entry.isFile() || !metadata.isFile() || metadata.isSymbolicLink()) { + fail("release artifact entries must be regular visible files"); + } + } + for (const record of manifest.packages) { + const tarball = resolve(releaseDirectory, record.tarball); + const bytes = await readFile(tarball); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const shasum = createHash("sha1").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (!equal(sha256, record.sha256) || !equal(shasum, record.shasum) || + !equal(integrity, record.integrity)) { + fail(`${record.name} package digest does not match`); + } + } + + const publishDirectory = await mkdtemp(resolve(process.env.RUNNER_TEMP ?? tmpdir(), "npm-publish.")); + const configDirectory = await mkdtemp(resolve(process.env.RUNNER_TEMP ?? tmpdir(), "npm-config.")); + const userConfig = resolve(configDirectory, "userconfig"); + const globalConfig = resolve(configDirectory, "globalconfig"); + await writeFile(userConfig, "", { mode: 0o600 }); + await writeFile(globalConfig, "", { mode: 0o600 }); + const environment = Object.fromEntries(Object.entries(process.env).filter(([key]) => + ["CI", "PATH", "HOME", "RUNNER_TEMP", "SYSTEMROOT"].includes(key) || key.startsWith("TMP") || + key.startsWith("GITHUB_") || key.startsWith("ACTIONS_ID_TOKEN_"))); + environment.NPM_CONFIG_USERCONFIG = userConfig; + environment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + const npm = (args, allowMissing = false) => { + const result = spawnSync("npm", args, { cwd: publishDirectory, encoding: "utf8", env: environment }); + if (result.error) throw result.error; + if (result.status !== 0 && !(allowMissing && /\bE404\b/.test(`${result.stdout}\n${result.stderr}`))) { + fail(`npm ${args[0]} failed: ${result.stderr.trim()}`); + } + return result; + }; + for (const record of manifest.packages.filter(({ publish }) => publish)) { + const specifier = `${record.name}@${record.version}`; + const viewed = npm(["view", specifier, "dist.integrity", "--json", "--registry", "https://registry.npmjs.org/", "--ignore-scripts"], true); + if (viewed.status === 0) { + const registryIntegrity = JSON.parse(viewed.stdout); + if (!equal(registryIntegrity, record.integrity)) fail(`${specifier} registry digest differs`); + continue; + } + npm(["publish", resolve(releaseDirectory, record.tarball), "--tag", "latest", "--registry", "https://registry.npmjs.org/", "--access", "public", "--provenance", "--ignore-scripts"]); + } + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index aa3b4c2..ce6c1f9 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -53,12 +53,18 @@ before tagging. Never unpublish and reuse a version. ``` 4. The workflow: - - verifies the signed tag against `RELEASE_ALLOWED_SIGNERS`; - - runs the full gate; - - packs both packages with `pnpm run release:pack` (npm CLI for `pack` / - registry `view`); - - publishes exact tarballs with provenance via OIDC - (`node scripts/release-packages.mjs publish`). The OIDC job does not + - `prepare` authenticates the signed tag in a temporary bare repository + before checkout, checks out the immutable release commit, runs the full + gate, packs both packages, validates their archived manifests, and uploads + the sealed `.release` inventory; + - `smoke` downloads that inventory without a repository checkout, installs + the tarballs with lifecycle scripts disabled, verifies the recorded + manifest and package digests, and imports every declared package export; + - `publish` authenticates the tag again in a fresh bare repository, downloads + the sealed inventory without checking out source, anchors the manifest to + the SHA-256 output from `prepare`, verifies the tarball digests, and + publishes the exact tarballs with provenance from an empty temporary + working directory. The OIDC job does not run repository scripts or download Corepack pnpm. Local helpers (never substitute for the OIDC lane for advertised releases): diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index bc2e344..f5bef3a 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -81,6 +81,16 @@ export function prepareRelease( options?: ReleaseCommandOptions, ): Promise<{ manifestPath: string; manifest: unknown }>; +export function validatePackedTarball( + tarballPath: string, + expectedManifest: PublicPackageManifest, +): Promise; + +export function verifyReleaseInventory( + directory: string, + expectedTarballs: readonly string[], +): Promise; + export function publishPreparedRelease( options?: ReleaseCommandOptions, ): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index d5a77de..14ad078 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,17 +1,16 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; import { - mkdtemp, + lstat, mkdir, readFile, readdir, - rm, stat, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { gunzipSync } from "node:zlib"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/scheduler.git"; const NODE_RANGE = ">=22"; @@ -38,6 +37,8 @@ export const RELEASE_PACKAGES = [ const RELEASE_NAMES = new Set(RELEASE_PACKAGES.map(({ name }) => name)); const FIRST_RELEASE_VERSION = "0.1.0"; +const MAX_TARBALL_BYTES = 32 * 1024 * 1024; +const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024; export function isNormalReleaseVersion(version) { const match = @@ -109,6 +110,27 @@ function runPnpm(arguments_, options = {}) { }); } +function parseNpmPackJson(text) { + const starts = []; + if (/^\[\r?\n\s*\{/u.test(text)) { + starts.push(0); + } + for (const match of text.matchAll(/\r?\n(?=\[\r?\n\s*\{)/gu)) { + starts.push((match.index ?? 0) + match[0].length); + } + for (const start of starts.reverse()) { + try { + const parsed = JSON.parse(text.slice(start).trim()); + if (Array.isArray(parsed)) { + return parsed; + } + } catch { + // Continue to an earlier npm JSON marker. + } + } + fail("npm pack did not return valid JSON"); +} + function unquoteYamlScalar(value) { if ( (value.startsWith("'") && value.endsWith("'")) || @@ -298,11 +320,122 @@ function gitCommand() { function hashTarball(bytes) { return { + sha256: createHash("sha256").update(bytes).digest("hex"), shasum: createHash("sha1").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, }; } +function tarString(header, offset, length) { + const bytes = header.subarray(offset, offset + length); + const end = bytes.indexOf(0); + return bytes.subarray(0, end === -1 ? bytes.length : end).toString("utf8"); +} + +function tarOctal(header, offset, length, description) { + const value = tarString(header, offset, length).trim(); + if (!/^[0-7]+$/u.test(value)) { + fail(`packed archive has an invalid ${description}`); + } + const parsed = Number.parseInt(value, 8); + if (!Number.isSafeInteger(parsed) || parsed < 0) { + fail(`packed archive has an invalid ${description}`); + } + return parsed; +} + +function verifyTarHeader(header, path) { + const expected = tarOctal(header, 148, 8, `header checksum for ${path}`); + let actual = 0; + for (let index = 0; index < header.length; index += 1) { + actual += index >= 148 && index < 156 ? 32 : header[index]; + } + if (actual !== expected) { + fail(`packed archive has an invalid header checksum for ${path}`); + } +} + +function parsePaxFields(bytes) { + const fields = {}; + for (let offset = 0; offset < bytes.length;) { + const separator = bytes.indexOf(32, offset); + if (separator === -1) { + fail("packed archive has invalid extended metadata"); + } + const lengthText = bytes.subarray(offset, separator).toString("ascii"); + if (!/^[1-9][0-9]*$/u.test(lengthText)) { + fail("packed archive has invalid extended metadata"); + } + const length = Number(lengthText); + const end = offset + length; + if ( + !Number.isSafeInteger(length) || + end > bytes.length || + bytes[end - 1] !== 10 + ) { + fail("packed archive has invalid extended metadata"); + } + const record = bytes.subarray(separator + 1, end - 1).toString("utf8"); + const equals = record.indexOf("="); + if (equals > 0) { + fields[record.slice(0, equals)] = record.slice(equals + 1); + } + offset = end; + } + return fields; +} + +function readTarEntries(bytes) { + if (bytes.length > MAX_TARBALL_BYTES) { + fail("packed archive exceeds the compressed size limit"); + } + const archive = gunzipSync(bytes, { maxOutputLength: MAX_ARCHIVE_BYTES }); + const entries = new Map(); + let globalPax = {}; + let localPax = {}; + let longPath; + for (let offset = 0; offset + 512 <= archive.length;) { + const header = archive.subarray(offset, offset + 512); + if (header.every((byte) => byte === 0)) { + break; + } + const name = tarString(header, 0, 100); + const prefix = tarString(header, 345, 155); + const headerPath = prefix === "" ? name : `${prefix}/${name}`; + verifyTarHeader(header, headerPath); + const size = tarOctal(header, 124, 12, `entry size for ${headerPath}`); + const type = header[156]; + const contentStart = offset + 512; + const contentEnd = contentStart + size; + if (contentEnd > archive.length) { + fail(`packed archive entry extends past the archive: ${headerPath}`); + } + const content = archive.subarray(contentStart, contentEnd); + if (type === 103 || type === 120) { + const fields = parsePaxFields(content); + if (type === 103) { + globalPax = { ...globalPax, ...fields }; + } else { + localPax = fields; + } + } else if (type === 76) { + longPath = tarString(content, 0, content.length).replace(/\r?\n$/u, ""); + } else { + const path = longPath ?? localPax.path ?? globalPax.path ?? headerPath; + if (type === 0 || type === 48) { + if (entries.has(path)) { + fail(`packed archive contains duplicate entry ${path}`); + } + entries.set(path, content); + } + localPax = {}; + longPath = undefined; + } + offset = contentStart + Math.ceil(size / 512) * 512; + } + return entries; +} + function exportSpecifiers(manifest) { if ( manifest.exports === null || @@ -316,6 +449,99 @@ function exportSpecifiers(manifest) { ); } +function pegmaPins(manifest) { + const pins = {}; + for (const section of DEPENDENCY_SECTIONS) { + for (const [name, version] of Object.entries(manifest[section] ?? {})) { + if (name.startsWith("@pegma/")) { + pins[`${section}:${name}`] = version; + } + } + } + return pins; +} + +export async function validatePackedTarball(tarballPath, expectedManifest) { + const entries = readTarEntries(await readFile(tarballPath)); + for (const required of [ + "package/package.json", + "package/README.md", + "package/LICENSE", + ]) { + if (!entries.has(required)) { + fail(`${expectedManifest.name} packed archive is missing ${required}`); + } + } + let packedManifest; + try { + packedManifest = JSON.parse( + entries.get("package/package.json").toString("utf8"), + ); + } catch { + fail(`${expectedManifest.name} packed package.json is not valid JSON`); + } + if ( + packedManifest.name !== expectedManifest.name || + packedManifest.version !== expectedManifest.version + ) { + fail(`${expectedManifest.name} packed name and version must match source`); + } + for (const lifecycle of ["preinstall", "install", "postinstall"]) { + if (Object.hasOwn(packedManifest.scripts ?? {}, lifecycle)) { + fail(`${expectedManifest.name} packed manifest has an install hook`); + } + } + const packedPins = pegmaPins(packedManifest); + if ( + Object.values(packedPins).some( + (version) => typeof version !== "string" || !STABLE_SEMVER.test(version), + ) || + !sameJson(packedPins, pegmaPins(expectedManifest)) + ) { + fail( + `${expectedManifest.name} packed Pegma pins must match source exactly`, + ); + } + if ( + !sameJson( + exportSpecifiers(packedManifest), + exportSpecifiers(expectedManifest), + ) + ) { + fail(`${expectedManifest.name} packed exports must match source exactly`); + } + return packedManifest; +} + +export async function verifyReleaseInventory(directory, expectedTarballs) { + if ( + expectedTarballs.some( + (name) => + typeof name !== "string" || + basename(name) !== name || + name.startsWith(".") || + !name.endsWith(".tgz"), + ) + ) { + fail("release tarball names must be plain visible filenames"); + } + const entries = await readdir(directory, { withFileTypes: true }); + const expected = ["package-manifest.json", ...expectedTarballs].sort(); + const actual = entries.map(({ name }) => name).sort(); + if ( + !sameJson(actual, expected) || + entries.some((entry) => !entry.isFile() || entry.name.startsWith(".")) + ) { + fail("release output inventory does not match the prepared package set"); + } + for (const entry of entries) { + const metadata = await lstat(join(directory, entry.name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) { + fail("release output entries must be regular files"); + } + } +} + function exportTargets(value) { if (typeof value === "string") { return [value]; @@ -447,10 +673,11 @@ export function validateReleaseTag(options = {}) { } if ( expectedReleaseCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) + !/^[0-9a-f]{40,64}$/iu.test(expectedReleaseCommit) ) { fail("an exact release event commit is required"); } + const normalizedReleaseCommit = expectedReleaseCommit.toLowerCase(); const tagRef = `refs/tags/${releaseTag}`; const objectType = run(gitCommand(), ["cat-file", "-t", tagRef], { @@ -471,7 +698,7 @@ export function validateReleaseTag(options = {}) { }).stdout.trim(); if ( !safeEqual(headCommit, tagCommit) || - !safeEqual(headCommit, expectedReleaseCommit) + !safeEqual(headCommit, normalizedReleaseCommit) ) { fail( "the release checkout, signed tag target, and release event commit must match", @@ -595,42 +822,6 @@ function verifyPackedFiles(manifest, files) { } } -async function smokeTestTarballs(root, packageRecords) { - const directory = await mkdtemp(join(tmpdir(), "pegma-release-smoke-")); - try { - await writeFile( - join(directory, "package.json"), - '{"name":"pegma-release-smoke","private":true,"type":"module"}\n', - ); - runNpm( - [ - "install", - "--ignore-scripts", - "--no-audit", - "--no-fund", - "--package-lock=false", - ...packageRecords.map(({ tarballPath }) => tarballPath), - ], - { cwd: directory, capture: true }, - ); - for (const { manifest } of packageRecords) { - for (const specifier of exportSpecifiers(manifest)) { - run( - process.execPath, - [ - "--input-type=module", - "--eval", - `await import(${JSON.stringify(specifier)})`, - ], - { cwd: directory, capture: true }, - ); - } - } - } finally { - await rm(directory, { recursive: true, force: true }); - } -} - function queryRegistryIntegrity(name, version) { const spec = `${name}@${version}`; const result = runNpm(["view", spec, "dist.integrity", "--json"], { @@ -697,7 +888,7 @@ export async function prepareRelease(options = {}) { ], { cwd: root, capture: true }, ); - const [packed] = JSON.parse(result.stdout); + const [packed] = parseNpmPackJson(result.stdout); if ( packed?.name !== definition.name || packed?.version !== manifest.version || @@ -708,6 +899,7 @@ export async function prepareRelease(options = {}) { } verifyPackedFiles(manifest, packed.files); const tarballPath = join(output, basename(packed.filename)); + await validatePackedTarball(tarballPath, manifest); const hashes = hashTarball(await readFile(tarballPath)); if ( !safeEqual(hashes.integrity, packed.integrity) || @@ -721,17 +913,17 @@ export async function prepareRelease(options = {}) { directory: definition.directory, tarball: basename(tarballPath), tarballPath, + sha256: hashes.sha256, integrity: hashes.integrity, shasum: hashes.shasum, publish: tagVersion === undefined || manifest.version === tagVersion, + imports: exportSpecifiers(manifest), files: packed.files .map(({ path, size }) => ({ path, size })) .sort((left, right) => left.path.localeCompare(right.path)), manifest, }); } - await smokeTestTarballs(root, records); - if (releaseTag !== undefined) { for (const record of records.filter(({ publish }) => !publish)) { const registryIntegrity = queryRegistryIntegrity( @@ -759,6 +951,10 @@ export async function prepareRelease(options = {}) { }; const manifestPath = join(output, "package-manifest.json"); await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + await verifyReleaseInventory( + output, + records.map(({ tarball }) => tarball), + ); return { manifestPath, manifest }; } @@ -787,6 +983,10 @@ async function verifyPreparedManifest(manifestPath) { if (!manifest.packages.some(({ publish }) => publish)) { fail("prepared package manifest has no release candidates"); } + await verifyReleaseInventory( + dirname(manifestPath), + manifest.packages.map(({ tarball }) => tarball), + ); for (const [index, record] of manifest.packages.entries()) { const definition = RELEASE_PACKAGES[index]; const expectedTarball = `${definition.name @@ -797,8 +997,12 @@ async function verifyPreparedManifest(manifestPath) { record.tarball !== expectedTarball || !STABLE_SEMVER.test(record.version) || record.publish !== (record.version === tagVersion) || + !/^[0-9a-f]{64}$/u.test(record.sha256) || typeof record.integrity !== "string" || typeof record.shasum !== "string" || + !Array.isArray(record.imports) || + record.imports.length === 0 || + record.imports.some((specifier) => typeof specifier !== "string") || !Array.isArray(record.files) ) { fail(`${record.name} has invalid prepared metadata`); @@ -809,6 +1013,7 @@ async function verifyPreparedManifest(manifestPath) { } const hashes = hashTarball(await readFile(tarball)); if ( + !safeEqual(hashes.sha256, record.sha256) || !safeEqual(hashes.integrity, record.integrity) || !safeEqual(hashes.shasum, record.shasum) ) { @@ -874,8 +1079,8 @@ export async function publishPreparedRelease(options = {}) { } if ( expectedReleaseCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) || - !safeEqual(manifest.gitCommit, expectedReleaseCommit) + !/^[0-9a-f]{40,64}$/iu.test(expectedReleaseCommit) || + !safeEqual(manifest.gitCommit, expectedReleaseCommit.toLowerCase()) ) { fail("prepared package manifest must match the release event commit"); } diff --git a/tests/publish-workflow.test.ts b/tests/publish-workflow.test.ts new file mode 100644 index 0000000..7c9b192 --- /dev/null +++ b/tests/publish-workflow.test.ts @@ -0,0 +1,103 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", +); + +function job(name: string, next?: string) { + const start = workflow.indexOf(` ${name}:\n`); + const end = + next === undefined ? workflow.length : workflow.indexOf(` ${next}:\n`); + expect(start).toBeGreaterThanOrEqual(0); + expect(end).toBeGreaterThan(start); + return workflow.slice(start, end); +} + +describe("publish workflow", () => { + it("authenticates the release tag before repository use", () => { + const prepare = job("prepare", "smoke"); + const publish = job("publish"); + for (const section of [prepare, publish]) { + expect( + section.indexOf("Authenticate the release tag"), + ).toBeGreaterThanOrEqual(0); + expect(section.indexOf("Authenticate the release tag")).toBeLessThan( + section.search(/actions\/checkout|pnpm|npm install|node /u), + ); + expect(section).toContain('[[ "${RELEASE_PRERELEASE}" != "false" ]]'); + expect(section).toContain("git init --bare"); + expect(section).toContain("fetch --no-tags origin"); + expect(section).toContain("cat-file -t"); + expect(section).toContain("verify-tag"); + expect(section).toContain('"${RELEASE_COMMIT,,}"'); + expect(section).toContain("merge-base --is-ancestor"); + } + }); + + it("checks out only the release commit for preparation", () => { + const prepare = job("prepare", "smoke"); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(prepare).not.toContain("ref: refs/tags/"); + }); + + it("separates package smoke checks from publication", () => { + const smoke = job("smoke", "publish"); + const publish = job("publish"); + expect(smoke).toContain("needs: prepare"); + expect(smoke).toContain("permissions:\n contents: read"); + expect(smoke).toContain( + "MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }}", + ); + expect(smoke).toContain("record.imports"); + expect(smoke).toContain("--registry https://registry.npmjs.org/"); + expect(smoke).not.toContain("< <(node"); + expect(publish).toContain("needs: [prepare, smoke]"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).not.toContain("scripts/release-packages.mjs"); + expect(publish).not.toContain("pnpm"); + }); + + it("uploads only visible prepared files and carries the manifest digest", () => { + const prepare = job("prepare", "smoke"); + expect(prepare).toContain( + "manifest_digest: ${{ steps.manifest.outputs.digest }}", + ); + expect(prepare).toContain("include-hidden-files: false"); + expect(prepare).toMatch( + /Record the package manifest digest[\s\S]*?set -euo pipefail[\s\S]*?\^\[0-9a-f\]\{64\}\$/u, + ); + expect(workflow).toContain( + "MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }}", + ); + }); + + it("revalidates the complete package digest set before publication", () => { + const publish = job("publish"); + expect(publish).toContain('createHash("sha256")'); + expect(publish).toContain('createHash("sha1")'); + expect(publish).toContain('createHash("sha512")'); + expect(publish).toContain("timingSafeEqual"); + expect(publish).toContain("record.files"); + expect(publish).toContain("record.imports"); + expect(publish).toContain("record.directory"); + }); + + it("keeps step and runner expressions out of job environments", () => { + const lines = workflow.split(/\r?\n/u); + for (let index = 0; index < lines.length; index += 1) { + if (lines[index] !== " env:") continue; + for ( + index += 1; + index < lines.length && /^ {6,}\S/u.test(lines[index] ?? ""); + index += 1 + ) { + expect(lines[index] ?? "").not.toMatch(/\$\{\{\s*(?:runner|steps)\./u); + } + index -= 1; + } + }); +}); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 448027d..e06aa84 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,5 +1,15 @@ -import { existsSync, readFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; +import { gunzipSync, gzipSync } from "node:zlib"; import { describe, expect, it } from "vitest"; import { @@ -10,8 +20,32 @@ import { parseArguments, parsePnpmLockfileImporters, resolvedVersionSatisfies, + validatePackedTarball, + validateReleaseTag, + verifyReleaseInventory, } from "../scripts/release-packages.mjs"; +function git(root: string, ...arguments_: string[]) { + execFileSync("git", arguments_, { cwd: root, stdio: "ignore" }); +} + +function createTagRepository() { + const root = mkdtempSync(join(tmpdir(), "scheduler-release-tag-")); + git(root, "init", "-b", "main"); + git(root, "config", "user.name", "Release Test"); + git(root, "config", "user.email", "release-test@example.invalid"); + writeFileSync(join(root, "receipt.txt"), "first\n"); + git(root, "add", "receipt.txt"); + git(root, "commit", "-m", "first"); + git(root, "tag", "-a", "v0.1.0", "-m", "v0.1.0"); + git(root, "update-ref", "refs/remotes/origin/main", "HEAD"); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: root, + encoding: "utf8", + }).trim(); + return { root, commit }; +} + describe("release package metadata", () => { it("accepts npm's cross-platform argument separator", () => { expect(parseArguments(["--", "--output", ".release"])).toEqual({ @@ -275,6 +309,135 @@ packages: ); }); + it("rejects an unsigned release tag", () => { + const { root, commit } = createTagRepository(); + try { + expect(() => + validateReleaseTag({ + root, + releaseTag: "v0.1.0", + expectedReleaseCommit: commit, + }), + ).toThrow(/signature/u); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a release tag that no longer identifies the checkout", () => { + const { root } = createTagRepository(); + try { + writeFileSync(join(root, "receipt.txt"), "second\n"); + git(root, "add", "receipt.txt"); + git(root, "commit", "-m", "second"); + git(root, "update-ref", "refs/remotes/origin/main", "HEAD"); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: root, + encoding: "utf8", + }).trim(); + expect(() => + validateReleaseTag({ + root, + releaseTag: "v0.1.0", + expectedReleaseCommit: commit, + }), + ).toThrow(/must match/u); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a changed packed manifest", async () => { + const root = mkdtempSync(join(tmpdir(), "scheduler-packed-manifest-")); + const packageDirectory = join(root, "package"); + const tarball = join(root, "scheduler.tgz"); + const expected = { + name: "@pegma/scheduler", + version: "0.1.0", + dependencies: { "@pegma/spine": "0.1.2" }, + }; + try { + mkdirSync(packageDirectory); + writeFileSync( + join(packageDirectory, "package.json"), + `${JSON.stringify({ + ...expected, + dependencies: { "@pegma/spine": "^0.1.2" }, + })}\n`, + ); + writeFileSync(join(packageDirectory, "README.md"), "# Package\n"); + writeFileSync(join(packageDirectory, "LICENSE"), "MIT\n"); + execFileSync("tar", ["-czf", tarball, "-C", root, "package"], { + stdio: "ignore", + }); + await expect(validatePackedTarball(tarball, expected)).rejects.toThrow( + /pins must match/u, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a packed archive with a changed header", async () => { + const root = mkdtempSync(join(tmpdir(), "scheduler-packed-header-")); + const packageDirectory = join(root, "package"); + const tarball = join(root, "scheduler.tgz"); + const expected = { + name: "@pegma/scheduler", + version: "0.1.0", + dependencies: { "@pegma/spine": "0.1.2" }, + exports: { ".": "./dist/index.js" }, + }; + try { + mkdirSync(packageDirectory); + writeFileSync( + join(packageDirectory, "package.json"), + `${JSON.stringify(expected)}\n`, + ); + writeFileSync(join(packageDirectory, "README.md"), "# Package\n"); + writeFileSync(join(packageDirectory, "LICENSE"), "MIT\n"); + execFileSync("tar", ["-czf", tarball, "-C", root, "package"], { + stdio: "ignore", + }); + const archive = gunzipSync(readFileSync(tarball)); + archive[0] = archive[0] === 112 ? 113 : 112; + writeFileSync(tarball, gzipSync(archive)); + await expect(validatePackedTarball(tarball, expected)).rejects.toThrow( + /header checksum/u, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects extra release output entries", async () => { + const root = mkdtempSync(join(tmpdir(), "scheduler-release-inventory-")); + const tarballs = [ + "pegma-scheduler-0.1.0.tgz", + "pegma-scheduler-cloudflare-0.1.0.tgz", + ]; + try { + for (const name of ["package-manifest.json", ...tarballs]) { + writeFileSync(join(root, name), "prepared\n"); + } + await expect( + verifyReleaseInventory(root, tarballs), + ).resolves.toBeUndefined(); + await expect( + verifyReleaseInventory(root, ["../pegma-scheduler-0.1.0.tgz"]), + ).rejects.toThrow(/plain visible filenames/u); + writeFileSync( + join(root, ".npmrc"), + "registry=https://registry.npmjs.org/\n", + ); + await expect(verifyReleaseInventory(root, tarballs)).rejects.toThrow( + /inventory/u, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + it("skips a byte-identical existing version", () => { const integrity = "sha512-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==";