diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 70423aa..efdaaab 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,33 +1,24 @@ -# Publishes exact tarballs prepared from a stable GitHub release tag. -# Authentication is npm trusted-publisher OIDC only; no token fallback exists. - +# Publication uses selected source and authenticated original registry archives. name: Publish - on: release: types: [published] - permissions: contents: read - concurrency: group: npm-publish cancel-in-progress: false +env: + CI: "1" + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + REVIEWED_NPM_VERSION: "11.18.0" jobs: - prepare: + identity: runs-on: ubuntu-latest - outputs: - manifest-digest: ${{ steps.seal.outputs.manifest_digest }} - artifact-digest: ${{ steps.upload.outputs['artifact-digest'] }} - env: - CI: "1" - RELEASE_TAG: ${{ github.event.release.tag_name }} - RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} - RELEASE_COMMIT: ${{ github.sha }} - RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} - REVIEWED_NPM_VERSION: "11.18.0" - steps: - name: Verify the release tag shell: bash @@ -68,147 +59,267 @@ jobs: git -C "${verify_directory}" merge-base --is-ancestor \ "${RELEASE_COMMIT}" refs/remotes/origin/main + validate: + needs: identity + name: Node.js ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [22, 24] + steps: - name: Check out the exact release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.sha }} persist-credentials: false fetch-depth: 0 + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: ${{ matrix.node-version }} + package-manager-cache: false + - name: Set up Java for DynamoDB Local + uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 + with: + distribution: temurin + java-version: "21" + - name: Enable Corepack + run: corepack enable + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Check formatting + run: pnpm run format:check + - name: Check types + run: pnpm run check + - name: Run tests + run: pnpm test + - name: Check release metadata + run: pnpm run release:check + prepare: + needs: [identity, validate] + runs-on: ubuntu-latest + outputs: + manifest-digest: ${{ steps.seal.outputs.manifest_digest }} + policy-digest: ${{ steps.seal.outputs.policy_digest }} + policy-base64: ${{ steps.seal.outputs.policy_base64 }} + artifact-id: ${{ steps.upload.outputs.artifact-id }} + artifact-digest: ${{ steps.upload.outputs.artifact-digest }} + steps: + - name: Check out the exact release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 - name: Configure checkout tag verification shell: bash run: | set -euo pipefail allowed_signers="${RUNNER_TEMP}/release-allowed-signers" - [[ -f "${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}" - - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 package-manager-cache: false - - name: Check the npm version shell: bash run: | set -euo pipefail [[ "$(npm --version)" == "${REVIEWED_NPM_VERSION}" ]] - - - name: Set up Java for DynamoDB Local - uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 - with: - distribution: temurin - java-version: "21" - - name: Enable Corepack run: corepack enable - - name: Install dependencies run: pnpm install --frozen-lockfile - - - name: Check formatting - run: pnpm run format:check - - - name: Check types - run: pnpm run check - - - name: Run tests - run: pnpm test - - name: Pack the release files run: >- pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --skip-smoke - --expected-release-commit "${RELEASE_COMMIT}" --output .release - + --expected-release-commit "${RELEASE_COMMIT}" + --output "${RUNNER_TEMP}/storage-prepared" - name: Seal the release inventory id: seal shell: bash run: | set -euo pipefail - manifest_digest="$(sha256sum .release/package-manifest.json | cut -d' ' -f1)" - echo "manifest_digest=${manifest_digest}" >> "${GITHUB_OUTPUT}" - + node --input-type=module <<'SEAL' + import { appendFile, readFile } from "node:fs/promises"; + import { createHash } from "node:crypto"; + import { join } from "node:path"; + import { verifyPreparedManifest } from "./scripts/release-packages.mjs"; + const digest = bytes => createHash("sha256").update(bytes).digest("hex"); + const manifestPath = join(process.env.RUNNER_TEMP, "storage-prepared", "package-manifest.json"); + const manifestBytes = await readFile(manifestPath); + const manifestDigest = digest(manifestBytes); + // Bind the strict schema/source/archive validation to this same buffer. + const manifest = await verifyPreparedManifest(manifestPath, { + root: process.cwd(), + expectedReleaseCommit: process.env.RELEASE_COMMIT, + expectedManifestSha256: manifestDigest, + }); + if (manifest.gitCommit !== process.env.RELEASE_COMMIT || + manifest.releaseTag !== process.env.RELEASE_TAG || + !manifest.packages.every(record => + record.publish === true && record.origin.kind === "source" || + record.publish === false && record.origin.kind === "registryReuse")) + throw new Error("Validated release inventory identity differs"); + const policyBytes = await readFile("scripts/release-reuse-policy.json"); + const policyDigest = digest(policyBytes); + if (policyDigest !== manifest.registryPolicySha256 || + !manifestBytes.equals(await readFile(manifestPath))) + throw new Error("Release inventory changed during sealing"); + const reuseRequired = manifest.packages.some(record => record.origin.kind === "registryReuse"); + await appendFile(process.env.GITHUB_OUTPUT, [ + "manifest_digest=" + manifestDigest, + "policy_digest=" + policyDigest, + "policy_base64=" + policyBytes.toString("base64"), + "reuse_required=" + String(reuseRequired), + ].join("\n") + "\n"); + SEAL - name: Upload the prepared release id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: - name: storage-release-${{ github.run_id }} - path: .release/ + name: storage-release-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/storage-prepared/ if-no-files-found: error include-hidden-files: false - overwrite: true + overwrite: false retention-days: 30 - - - name: Record the prepared artifact digest + - name: Retain genuine registry reuse proof + if: ${{ always() && (steps.seal.outcome != 'success' || steps.seal.outputs.reuse_required != 'false') }} + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: storage-reuse-proof-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/storage-prepared-reuse-verification/ + if-no-files-found: error + include-hidden-files: false + overwrite: false + retention-days: 30 + - name: Record original artifact identity env: - ARTIFACT_DIGEST: ${{ steps.upload.outputs['artifact-digest'] }} - run: echo "Prepared artifact SHA-256 ${ARTIFACT_DIGEST}" >> "${GITHUB_STEP_SUMMARY}" + ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }} + ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} + MANIFEST_DIGEST: ${{ steps.seal.outputs.manifest_digest }} + run: printf 'Original artifact %s ZIP SHA256 %s manifest SHA256 %s\n' "${ARTIFACT_ID}" "${ARTIFACT_DIGEST}" "${MANIFEST_DIGEST}" >> "${GITHUB_STEP_SUMMARY}" smoke: needs: prepare runs-on: ubuntu-latest - permissions: - contents: read env: - CI: "1" - RELEASE_COMMIT: ${{ github.sha }} - EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs['manifest-digest'] }} - RELEASE_DIRECTORY: ${{ github.workspace }}/storage-release - + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} steps: - name: Check out the exact release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.sha }} persist-credentials: false - fetch-depth: 1 - + fetch-depth: 0 - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 package-manager-cache: false - + - name: Set up Java for DynamoDB Local + uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 + with: + distribution: temurin + java-version: "21" - name: Download the prepared release copy uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: storage-release-${{ github.run_id }} - path: ${{ github.workspace }}/storage-release - - - name: Verify the prepared manifest digest - shell: bash - run: | - set -euo pipefail - [[ "${EXPECTED_MANIFEST_DIGEST}" =~ ^[0-9a-f]{64}$ ]] - actual="$(sha256sum "${RELEASE_DIRECTORY}/package-manifest.json" | cut -d' ' -f1)" - [[ "${actual}" == "${EXPECTED_MANIFEST_DIGEST}" ]] - + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/storage-smoke + merge-multiple: true - name: Smoke-test the prepared release copy + env: + RELEASE_DIRECTORY: ${{ runner.temp }}/storage-smoke run: >- node scripts/release-packages.mjs smoke + --manifest "${RELEASE_DIRECTORY}/package-manifest.json" --expected-release-commit "${RELEASE_COMMIT}" + --expected-manifest-sha256 "${EXPECTED_MANIFEST_DIGEST}" + --output "${RUNNER_TEMP}/storage-consumer-proof" + - name: Retain public consumer proof + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: storage-consumer-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/storage-consumer-proof/ + if-no-files-found: error + include-hidden-files: false + overwrite: false + retention-days: 30 + + preflight: + needs: [prepare, smoke] + runs-on: ubuntu-latest + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + artifact-digest: ${{ steps.upload.outputs.artifact-digest }} + preflight-digest: ${{ steps.seal.outputs.preflight_digest }} + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} + steps: + - name: Check out the exact release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + - name: Download the original prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/storage-preflight-input + merge-multiple: true + - name: Verify registry preflight + env: + RELEASE_DIRECTORY: ${{ runner.temp }}/storage-preflight-input + run: >- + node scripts/release-registry-verify.mjs preflight --manifest "${RELEASE_DIRECTORY}/package-manifest.json" + --expected-release-commit "${RELEASE_COMMIT}" + --expected-manifest-sha256 "${EXPECTED_MANIFEST_DIGEST}" + --run-id "${GITHUB_RUN_ID}" --run-attempt "${GITHUB_RUN_ATTEMPT}" + --output "${RUNNER_TEMP}/storage-preflight-proof" + - name: Seal registry preflight + id: seal + run: printf 'preflight_digest=%s\n' "$(sha256sum "${RUNNER_TEMP}/storage-preflight-proof/preflight.json" | cut -d' ' -f1)" >> "${GITHUB_OUTPUT}" + - name: Retain registry preflight + if: always() + id: upload + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: storage-preflight-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/storage-preflight-proof/ + if-no-files-found: error + include-hidden-files: false + overwrite: false + retention-days: 30 publish: - needs: [prepare, smoke] + needs: [prepare, smoke, preflight] runs-on: ubuntu-latest environment: npm-publish permissions: contents: read id-token: write env: - CI: "1" - RELEASE_TAG: ${{ github.event.release.tag_name }} - RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} - RELEASE_COMMIT: ${{ github.sha }} - RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} - REVIEWED_NPM_VERSION: "11.18.0" - EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs['manifest-digest'] }} - RELEASE_DIRECTORY: ${{ github.workspace }}/storage-release - + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} + EXPECTED_POLICY_DIGEST: ${{ needs.prepare.outputs.policy-digest }} + REGISTRY_POLICY_BASE64: ${{ needs.prepare.outputs.policy-base64 }} + EXPECTED_PREFLIGHT_DIGEST: ${{ needs.preflight.outputs.preflight-digest }} steps: - name: Verify the release tag shell: bash @@ -254,20 +365,27 @@ jobs: with: node-version: 24.18.0 package-manager-cache: false - - name: Check the npm version shell: bash run: | set -euo pipefail [[ "$(npm --version)" == "${REVIEWED_NPM_VERSION}" ]] - - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: storage-release-${{ github.run_id }} - path: ${{ github.workspace }}/storage-release - + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/storage-publish + merge-multiple: true + - name: Download sealed registry preflight + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.preflight.outputs.artifact-id }} + path: ${{ runner.temp }}/storage-publish-preflight + merge-multiple: true - name: Verify and publish the prepared release + env: + RELEASE_DIRECTORY: ${{ runner.temp }}/storage-publish + PREFLIGHT_DIRECTORY: ${{ runner.temp }}/storage-publish-preflight shell: bash run: | set -euo pipefail @@ -276,230 +394,273 @@ jobs: cat > "${publisher}" <<'NODE' import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; - import { - chmod, - lstat, - mkdtemp, - readFile, - readdir, - rm, - writeFile, - } from "node:fs/promises"; + import { constants } from "node:fs"; + import { chmod, copyFile, lstat, mkdtemp, open, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises"; + import { basename, dirname, join, resolve } from "node:path"; import { tmpdir } from "node:os"; - import { basename, join, resolve } from "node:path"; - - const registry = "https://registry.npmjs.org/"; - const definitions = [ - ["@pegma/storage-core", "storage-core"], - ["@pegma/storage-azure-tables", "storage-azure-tables"], - ["@pegma/storage-cloudflare-d1", "storage-cloudflare-d1"], - ["@pegma/storage-dynamodb", "storage-dynamodb"], + const repository="pegma-dev/storage-core", registry="https://registry.npmjs.org/"; + const workflow=".github/workflows/publish.yml"; + const definitions=[ + ["@pegma/storage-core","storage-core"], + ["@pegma/storage-azure-tables","storage-azure-tables"], + ["@pegma/storage-cloudflare-d1","storage-cloudflare-d1"], + ["@pegma/storage-dynamodb","storage-dynamodb"], ]; - const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; - const releaseTag = /^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u; - - function fail(message) { - throw new Error(message); - } - - function equal(left, right) { - const leftBytes = Buffer.from(left); - const rightBytes = Buffer.from(right); - return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes); - } - - const releaseDirectory = resolve(process.env.RELEASE_DIRECTORY); - const manifestPath = join(releaseDirectory, "package-manifest.json"); - const manifestBytes = await readFile(manifestPath); - const manifestDigest = createHash("sha256").update(manifestBytes).digest("hex"); - const expectedManifestDigest = process.env.EXPECTED_MANIFEST_DIGEST ?? ""; - if (!/^[0-9a-f]{64}$/u.test(expectedManifestDigest)) { - fail("prepared manifest digest is missing or invalid"); - } - if (!equal(manifestDigest, expectedManifestDigest)) { - fail("prepared manifest digest does not match"); + function fail(message){throw new Error(message);} + function equal(a,b){if(typeof a!=="string"||typeof b!=="string")return false;const x=Buffer.from(a),y=Buffer.from(b);return x.length===y.length&&timingSafeEqual(x,y);} + function digest(bytes,algorithm="sha256",encoding="hex"){return createHash(algorithm).update(bytes).digest(encoding);} + function exact(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||JSON.stringify(Object.keys(value).sort())!==JSON.stringify([...keys].sort()))fail("release data has invalid fields");} + function integer(value){if(!Number.isSafeInteger(value)||value<1)fail("release identity has an invalid integer");} + function originFor(entry){return {kind:"registryReuse",registry,policyEntry:entry.name+"@"+entry.version,tarballUrl:entry.tarballUrl, + sourceCommit:entry.sourceCommit,sourceTag:entry.sourceTag,workflowPath:entry.workflowPath, + originalRunId:entry.originalRunId,originalRunAttempt:entry.originalRunAttempt};} + function same(a,b){return JSON.stringify(a)===JSON.stringify(b);} + async function boundedFile(path,maximum){ + const metadata=await lstat(path); + if(!metadata.isFile()||metadata.isSymbolicLink()||metadata.size<1||metadata.size>maximum||await realpath(path)!==resolve(path))fail("prepared file is invalid"); + const handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)); + try{ + const opened=await handle.stat(); + if(opened.dev!==metadata.dev||opened.ino!==metadata.ino||opened.size!==metadata.size)fail("prepared file changed"); + const bytes=Buffer.alloc(metadata.size+1);let length=0; + while(length tarball)].sort(); - const entries = await readdir(releaseDirectory, { withFileTypes: true }); - if (JSON.stringify(entries.map(({ name }) => name).sort()) !== JSON.stringify(expectedFiles)) { - fail("prepared release inventory is invalid"); + let oidc; + try{oidc=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);}catch{fail("approved OIDC environment is required");} + if(process.env.GITHUB_ACTIONS!=="true"||process.env.GITHUB_EVENT_NAME!=="release"|| + process.env.GITHUB_REPOSITORY!==repository||process.env.GITHUB_SERVER_URL!=="https://github.com"|| + process.env.GITHUB_REPOSITORY_ID!=="1312519623"||process.env.GITHUB_REPOSITORY_OWNER_ID!=="309286193"|| + process.env.GITHUB_REF!=="refs/tags/"+process.env.RELEASE_TAG|| + process.env.GITHUB_SHA!==process.env.RELEASE_COMMIT||process.env.GITHUB_WORKFLOW_SHA!==process.env.RELEASE_COMMIT|| + process.env.GITHUB_WORKFLOW_REF!==repository+"/"+workflow+"@refs/tags/"+process.env.RELEASE_TAG|| + process.env.RUNNER_ENVIRONMENT!=="github-hosted"||oidc.protocol!=="https:"||oidc.username||oidc.password|| + !/^(?:[A-Za-z0-9-]+\.)*actions\.githubusercontent\.com$/u.test(oidc.hostname)|| + !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN|| + Object.entries(process.env).some(([key,value])=>value&&/^(?:NODE_AUTH_TOKEN|NPM_TOKEN|NPM_AUTH_TOKEN|NPM_AUTH|YARN_NPM_AUTH_TOKEN|npm_config_.*)$/iu.test(key))) + fail("token-free github-hosted release OIDC is required"); + const runId=Number(process.env.GITHUB_RUN_ID),runAttempt=Number(process.env.GITHUB_RUN_ATTEMPT);integer(runId);integer(runAttempt); + const releaseDirectory=resolve(process.env.RELEASE_DIRECTORY); + const manifestBytes=await boundedFile(join(releaseDirectory,"package-manifest.json"),1024*1024); + if(!/^[a-f0-9]{64}$/u.test(process.env.EXPECTED_MANIFEST_DIGEST??"")|| + !equal(digest(manifestBytes),process.env.EXPECTED_MANIFEST_DIGEST))fail("independent manifest digest differs"); + const manifest=JSON.parse(manifestBytes); + exact(manifest,["schemaVersion","repository","gitCommit","releaseTag","registryPolicySha256","packages"]); + if(manifest.schemaVersion!==2||manifest.repository!==repository||manifest.gitCommit!==process.env.RELEASE_COMMIT|| + manifest.releaseTag!==process.env.RELEASE_TAG||!/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test(manifest.releaseTag)|| + !Array.isArray(manifest.packages)||manifest.packages.length!==4)fail("prepared release identity differs"); + const policyBytes=Buffer.from(process.env.REGISTRY_POLICY_BASE64??"","base64"); + if(policyBytes.length>32768||!equal(digest(policyBytes),process.env.EXPECTED_POLICY_DIGEST)|| + !equal(digest(policyBytes),manifest.registryPolicySha256))fail("independent registry policy differs"); + const policy=JSON.parse(policyBytes); + exact(policy,["schemaVersion","repository","repositoryId","ownerId","builder","packages"]); + if(policy.schemaVersion!==1||policy.repository!==repository||policy.repositoryId!=="1312519623"|| + policy.ownerId!=="309286193"||policy.builder!=="https://github.com/actions/runner/github-hosted"|| + !Array.isArray(policy.packages)||policy.packages.length>definitions.length)fail("registry policy identity differs"); + let previousPolicyIndex=-1; + for(const entry of policy.packages){ + exact(entry,["name","version","directory","tarballUrl","size","sha256","integrity","shasum", + "sourceCommit","sourceTag","workflowPath","originalRunId","originalRunAttempt"]); + const index=definitions.findIndex(([name])=>name===entry.name); + if(index<=previousPolicyIndex||entry.directory!==definitions[index]?.[1]|| + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(entry.version)|| + entry.tarballUrl!==registry+entry.name+"/-/"+entry.directory+"-"+entry.version+".tgz"|| + !/^[a-f0-9]{64}$/u.test(entry.sha256)||!/^[a-f0-9]{40}$/u.test(entry.shasum)|| + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(entry.integrity)|| + !/^[a-f0-9]{40}$/u.test(entry.sourceCommit)||entry.sourceTag!=="v"+entry.version|| + entry.workflowPath!==workflow)fail("registry policy entry differs"); + integer(entry.size);integer(entry.originalRunId);integer(entry.originalRunAttempt); + if(entry.size>4*1024*1024)fail("registry policy archive is too large"); + previousPolicyIndex=index; } - for (const entry of entries) { - const details = await lstat(join(releaseDirectory, entry.name)); - if (entry.name.startsWith(".") || !entry.isFile() || details.isSymbolicLink()) { - fail("prepared release inventory must contain regular files only"); + if(manifest.packages.some(record=>!record?.publish&&!policy.packages.some(entry=> + entry.name===record?.name&&entry.version===record?.version)))fail("unselected package policy is missing"); + const expectedFiles=["package-manifest.json",...manifest.packages.map(record=>record.tarball)].sort(); + const entries=await readdir(releaseDirectory,{withFileTypes:true}); + if(!same(entries.map(entry=>entry.name).sort(),expectedFiles)||entries.some(entry=>!entry.isFile()||entry.name.startsWith(".")))fail("original five-file inventory differs"); + const versions=new Map(manifest.packages.map(record=>[record.name,record.version])); + let selected=0; + for(const [index,record] of manifest.packages.entries()){ + exact(record,["name","version","directory","tarball","size","shasum","sha256","integrity","publish","files","package","origin"]); + const [name,directory]=definitions[index]; + if(record.name!==name||record.directory!==directory||! /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(record.version)|| + record.tarball!==name.slice(1).replace("/","-")+"-"+record.version+".tgz"||basename(record.tarball)!==record.tarball|| + !Number.isSafeInteger(record.size)||record.size<1||record.size>4*1024*1024|| + !/^[a-f0-9]{64}$/u.test(record.sha256)||!/^[a-f0-9]{40}$/u.test(record.shasum)|| + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity)||typeof record.publish!=="boolean"|| + record.package?.name!==name||record.package.version!==record.version||record.package.license!=="MIT"|| + record.package.type!=="module"||record.package.publishConfig?.access!=="public"|| + record.package.repository?.url!=="git+https://github.com/"+repository+".git"|| + record.package.repository?.directory!=="packages/"+directory)fail("prepared package metadata differs"); + if(record.publish){ + selected++; + if(!same(record.origin,{kind:"source",repository,gitCommit:manifest.gitCommit,releaseTag:manifest.releaseTag,directory})|| + record.version!==manifest.releaseTag.slice(1))fail("source origin differs"); + }else{ + const entry=policy.packages.find(entry=>entry.name===name&&entry.version===record.version); + if(!entry||!same(record.origin,originFor(entry))||record.version===manifest.releaseTag.slice(1)|| + record.size!==entry.size||!equal(record.sha256,entry.sha256)||!equal(record.integrity,entry.integrity)|| + !equal(record.shasum,entry.shasum))fail("original registry origin differs"); } + for(const section of ["dependencies","devDependencies","optionalDependencies","peerDependencies"]) + for(const [dependency,version] of Object.entries(record.package[section]??{})) + if(versions.has(dependency)&&version!==versions.get(dependency))fail("internal dependency pin differs"); + const bytes=await boundedFile(join(releaseDirectory,record.tarball),4*1024*1024); + if(bytes.length!==record.size||!equal(digest(bytes),record.sha256)||!equal(digest(bytes,"sha1"),record.shasum)|| + !equal("sha512-"+digest(bytes,"sha512","base64"),record.integrity))fail("original artifact bytes differ"); } - - const tagVersion = manifest.releaseTag.slice(1); - const packageVersions = new Map(manifest.packages.map(({ name, version }) => [name, version])); - let selected = 0; - for (const [index, record] of manifest.packages.entries()) { - const [name, directory] = definitions[index]; - const expectedTarball = `${name.slice(1).replace("/", "-")}-${record.version}.tgz`; - if ( - JSON.stringify(Object.keys(record).sort()) !== - JSON.stringify(["directory", "files", "integrity", "name", "package", "publish", "sha256", "shasum", "tarball", "version"]) || - record.name !== name || - record.directory !== directory || - !stableVersion.test(record.version) || - record.tarball !== expectedTarball || - basename(record.tarball) !== record.tarball || - record.publish !== (record.version === tagVersion) || - !/^[0-9a-f]{64}$/u.test(record.sha256) || - !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(record.integrity) || - !/^[0-9a-f]{40}$/u.test(record.shasum) || - !Array.isArray(record.files) || - record.package?.name !== record.name || - record.package?.version !== record.version || - record.package?.license !== "MIT" || - record.package?.type !== "module" || - record.package?.publishConfig?.access !== "public" || - record.package?.repository?.url !== "git+https://github.com/pegma-dev/storage-core.git" || - record.package?.repository?.directory !== `packages/${directory}` || - record.files.some( - (file) => - file === null || - typeof file !== "object" || - typeof file.path !== "string" || - !Number.isSafeInteger(file.size) || - file.size < 0, - ) - ) { - fail(`prepared metadata for ${name} is invalid`); - } - selected += record.publish ? 1 : 0; - for (const section of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) { - for (const [dependency, version] of Object.entries(record.package[section] ?? {})) { - if (packageVersions.has(dependency) && version !== packageVersions.get(dependency)) { - fail(`${record.name} has an invalid internal dependency pin`); - } - } + if(!selected)fail("release has no source packages"); + const preflightDirectory=resolve(process.env.PREFLIGHT_DIRECTORY); + const preflightBytes=await boundedFile(join(preflightDirectory,"preflight.json"),4*1024*1024); + if(!/^[a-f0-9]{64}$/u.test(process.env.EXPECTED_PREFLIGHT_DIGEST??"")|| + !equal(digest(preflightBytes),process.env.EXPECTED_PREFLIGHT_DIGEST))fail("independent preflight digest differs"); + const preflight=JSON.parse(preflightBytes); + exact(preflight,["schemaVersion","repository","gitCommit","releaseTag","manifestSha256","runId","runAttempt","decisions","registryProof"]); + if(preflight.schemaVersion!==1||preflight.repository!==repository||preflight.gitCommit!==manifest.gitCommit|| + preflight.releaseTag!==manifest.releaseTag||preflight.manifestSha256!==process.env.EXPECTED_MANIFEST_DIGEST|| + preflight.runId!==runId||!Number.isSafeInteger(preflight.runAttempt)||preflight.runAttempt<1||preflight.runAttempt>runAttempt|| + !Array.isArray(preflight.decisions)||preflight.decisions.length!==4|| + preflight.registryProof?.status!=="REGISTRY_BYTES_CRYPTO_SOURCE_PASS"|| + preflight.registryProof.npmVersion!=="11.18.0"||preflight.registryProof.policySha256!==manifest.registryPolicySha256|| + !equal(preflight.registryProof.auditSha256,digest(await boundedFile(join(preflightDirectory,"npm-audit-signatures.json"),32*1024*1024)))) + fail("authenticated whole-set preflight binding differs"); + for(const [index,record] of manifest.packages.entries()){ + const decision=preflight.decisions[index];exact(decision,["name","version","action"]); + if(decision.name!==record.name||decision.version!==record.version||!["skip","publish"].includes(decision.action)|| + !record.publish&&decision.action!=="skip")fail("preflight decision differs"); + if(decision.action==="skip"){ + const facts=preflight.registryProof.packages?.filter(fact=>fact.name===record.name&&fact.version===record.version); + if(facts?.length!==1)fail("preflight authenticated package fact is missing"); + const fact=facts[0], origin=record.origin; + if(fact.sourceCommit!==(record.publish?manifest.gitCommit:origin.sourceCommit)|| + fact.sourceTag!==(record.publish?manifest.releaseTag:origin.sourceTag)|| + fact.runId!==(record.publish?runId:origin.originalRunId)|| + !Number.isSafeInteger(fact.attempt)||fact.attempt<1|| + (record.publish?fact.attempt>runAttempt:fact.attempt!==origin.originalRunAttempt)) + fail("preflight authenticated original writer differs"); } - const tarballPath = join(releaseDirectory, record.tarball); - const tarball = await readFile(tarballPath); - const sha256 = createHash("sha256").update(tarball).digest("hex"); - const sha512 = `sha512-${createHash("sha512").update(tarball).digest("base64")}`; - const shasum = createHash("sha1").update(tarball).digest("hex"); - if (!equal(sha256, record.sha256) || !equal(sha512, record.integrity) || !equal(shasum, record.shasum)) { - fail(`${record.name} tarball digest does not match`); - } - record.tarballPath = tarballPath; - } - if (selected === 0) { - fail("prepared manifest has no release candidates"); } - - const configDirectory = await mkdtemp(join(process.env.RUNNER_TEMP ?? tmpdir(), "npm-config-")); - await chmod(configDirectory, 0o700); - const userConfig = join(configDirectory, "userconfig"); - const globalConfig = join(configDirectory, "globalconfig"); - await writeFile(userConfig, "", { mode: 0o600 }); - await writeFile(globalConfig, "", { mode: 0o600 }); - await chmod(userConfig, 0o600); - await chmod(globalConfig, 0o600); - - function npmEnvironment() { - const selectedEnvironment = {}; - const exact = new Set(["PATH", "HOME", "CI", "SYSTEMROOT", "RUNNER_TEMP", "RUNNER_TOOL_CACHE", "TEMP", "TMP", "TMPDIR"]); - for (const [key, value] of Object.entries(process.env)) { - const upper = key.toUpperCase(); - if (exact.has(upper) || upper.startsWith("GITHUB_") || upper.startsWith("ACTIONS_ID_TOKEN_")) { - selectedEnvironment[key] = value; - } - } - selectedEnvironment.NPM_CONFIG_USERCONFIG = userConfig; - selectedEnvironment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + const configDirectory=await mkdtemp(join(process.env.RUNNER_TEMP??tmpdir(),"npm-config-")); + await chmod(configDirectory,0o700); + const userConfig=join(configDirectory,"userconfig"),globalConfig=join(configDirectory,"globalconfig"); + await writeFile(userConfig,"",{mode:0o600});await writeFile(globalConfig,"",{mode:0o600}); + function npmEnvironment(){ + const selectedEnvironment={}; + const exact=new Set(["PATH","HOME","CI","SYSTEMROOT","TEMP","TMP","TMPDIR","RUNNER_TEMP","RUNNER_TOOL_CACHE", + "GITHUB_ACTIONS","GITHUB_EVENT_NAME","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_SERVER_URL","GITHUB_REF","GITHUB_SHA","GITHUB_WORKFLOW_REF","GITHUB_WORKFLOW_SHA","GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT","RUNNER_ENVIRONMENT","ACTIONS_ID_TOKEN_REQUEST_URL","ACTIONS_ID_TOKEN_REQUEST_TOKEN"]); + for(const [key,value] of Object.entries(process.env))if(exact.has(key.toUpperCase()))selectedEnvironment[key]=value; + selectedEnvironment.NPM_CONFIG_USERCONFIG=userConfig;selectedEnvironment.NPM_CONFIG_GLOBALCONFIG=globalConfig; + selectedEnvironment.NPM_CONFIG_IGNORE_SCRIPTS="true";selectedEnvironment.NPM_CONFIG_REGISTRY=registry; return selectedEnvironment; } - - function npm(arguments_, options = {}) { - const result = spawnSync("npm", arguments_, { - cwd: options.cwd, - encoding: "utf8", - env: npmEnvironment(), - stdio: options.inherit ? "inherit" : "pipe", - }); - if (result.error) throw result.error; - if (result.status !== 0 && !options.allowFailure) fail(`npm ${arguments_.join(" ")} failed`); - return result; - } - - const npmVersion = npm(["--version"]).stdout.trim(); - const npmMatch = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(npmVersion); - if ( - npmMatch === null || - Number(npmMatch[1]) < 11 || - (Number(npmMatch[1]) === 11 && Number(npmMatch[2]) < 5) || - (Number(npmMatch[1]) === 11 && Number(npmMatch[2]) === 5 && Number(npmMatch[3]) < 1) - ) { - fail("npm 11.5.1 or newer is required"); + function npm(args,cwd,inherit=false){ + const result=spawnSync("npm",args,{cwd,encoding:"utf8",env:npmEnvironment(),shell:false,stdio:inherit?"inherit":"pipe",timeout:120000,maxBuffer:4*1024*1024}); + if(result.error||result.status!==0)fail("reviewed npm operation failed");return result.stdout; } - - function registryIntegrity(record) { - const specifier = `${record.name}@${record.version}`; - const result = npm(["view", specifier, "dist.integrity", "--json", "--registry", registry], { allowFailure: true }); - if (result.status === 0) { - const value = JSON.parse(result.stdout); - if (typeof value !== "string" || value.length === 0) fail(`${specifier} exists without registry integrity`); - return value; + async function registryState(record){ + const options={redirect:"error",signal:AbortSignal.timeout(30000)}; + const response=await fetch(registry+encodeURIComponent(record.name)+"/"+record.version,options); + if(response.status===404){await response.body?.cancel();return "absent";} + if(response.status!==200)fail("registry availability is unknown"); + async function bounded(response,maximum){ + let size=0;const chunks=[]; + for await(const chunk of response.body){size+=chunk.length;if(size>maximum)fail("registry response exceeded its bound");chunks.push(Buffer.from(chunk));} + return Buffer.concat(chunks,size); } - const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`; - if (/\bE404\b/u.test(output)) return null; - fail(`registry lookup failed for ${specifier}`); + const metadata=JSON.parse((await bounded(response,2*1024*1024)).toString("utf8")); + const url=registry+record.name+"/-/"+record.name.split("/")[1]+"-"+record.version+".tgz"; + if(metadata.name!==record.name||metadata.version!==record.version|| + !equal(metadata.dist?.integrity,record.integrity)||!equal(metadata.dist?.shasum,record.shasum)||metadata.dist?.tarball!==url) + fail("registry metadata conflicts with original archive"); + const tar=await fetch(url,options); + if(tar.status===404){await tar.body?.cancel();return "pending";} + if(tar.status!==200)fail("canonical registry bytes are unavailable"); + const bytes=await bounded(tar,record.size); + if(bytes.length!==record.size||!equal(digest(bytes),record.sha256)|| + !equal("sha512-"+digest(bytes,"sha512","base64"),record.integrity))fail("canonical registry bytes differ"); + return "present"; } - - const pause = (milliseconds) => new Promise((resolvePause) => setTimeout(resolvePause, milliseconds)); - try { - for (const record of manifest.packages.filter(({ publish }) => publish)) { - const existing = registryIntegrity(record); - if (existing !== null) { - if (!equal(existing, record.integrity)) fail(`${record.name}@${record.version} has different registry integrity`); - process.stdout.write(`Verified existing ${record.name}@${record.version}; skipping.\n`); - continue; - } - const publishDirectory = await mkdtemp(join(process.env.RUNNER_TEMP ?? tmpdir(), "npm-publish-")); - try { - npm([ - "publish", - record.tarballPath, - "--access", - "public", - "--provenance", - "--ignore-scripts", - "--registry", - registry, - ], { cwd: publishDirectory, inherit: true }); - } finally { - await rm(publishDirectory, { recursive: true, force: true }); + try{ + if(npm(["--version"],configDirectory).trim()!=="11.18.0")fail("reviewed npm version differs"); + const states=[]; + for(const record of manifest.packages)states.push(await registryState(record)); + for(const [index,record] of manifest.packages.entries()){ + const decision=preflight.decisions[index].action,state=states[index]; + if(decision==="skip"&&state!=="present")fail("qualified registry artifact is no longer available"); + if(decision==="publish"&&state!=="absent")fail("registry occupancy changed; rerun unprivileged preflight using the original artifact"); + } + for(const [index,record] of manifest.packages.entries()){ + if(!record.publish||preflight.decisions[index].action==="skip"){ + process.stdout.write("Verified original registry artifact "+record.name+"@"+record.version+"; skipping.\n");continue; } - let confirmed = false; - for (let attempt = 0; attempt < 6; attempt += 1) { - const published = registryIntegrity(record); - if (published !== null && equal(published, record.integrity)) { - confirmed = true; - break; - } - if (attempt < 5) await pause(2 ** attempt * 1000); + const current=await registryState(record); + if(current!=="absent")fail("registry occupancy changed; fresh authenticated preflight is required"); + const publishDirectory=await mkdtemp(join(process.env.RUNNER_TEMP??tmpdir(),"npm-publish-")); + try{ + const destination=join(publishDirectory,record.tarball); + await copyFile(join(releaseDirectory,record.tarball),destination); + if(!equal(digest(await boundedFile(destination,4*1024*1024)),record.sha256))fail("publish copy changed"); + npm(["publish",destination,"--access","public","--provenance","--ignore-scripts","--registry",registry],publishDirectory,true); + }finally{await rm(publishDirectory,{recursive:true,force:true});} + let visible=false; + for(let attempt=0;attempt<6;attempt++){ + if(await registryState(record)==="present"){visible=true;break;} + if(attempt<5)await new Promise(resolvePause=>setTimeout(resolvePause,2**attempt*1000)); } - if (!confirmed) fail(`${record.name}@${record.version} did not become visible`); + if(!visible)fail("published integrity did not become visible; retain original artifact and refresh unprivileged preflight"); } - } finally { - await rm(configDirectory, { recursive: true, force: true }); - } + }finally{await rm(configDirectory,{recursive:true,force:true});} NODE node "${publisher}" + + verify: + needs: [prepare, publish] + runs-on: ubuntu-latest + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} + steps: + - name: Check out the exact release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + - name: Set up Java for DynamoDB Local + uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 + with: + distribution: temurin + java-version: "21" + - name: Download the original prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/storage-final-input + merge-multiple: true + - name: Verify registry bytes provenance and consumer + env: + RELEASE_DIRECTORY: ${{ runner.temp }}/storage-final-input + run: >- + node scripts/release-registry-verify.mjs verify + --manifest "${RELEASE_DIRECTORY}/package-manifest.json" + --expected-release-commit "${RELEASE_COMMIT}" + --expected-manifest-sha256 "${EXPECTED_MANIFEST_DIGEST}" + --run-id "${GITHUB_RUN_ID}" --run-attempt "${GITHUB_RUN_ATTEMPT}" + --output "${RUNNER_TEMP}/storage-final-proof" + - name: Retain final registry proof + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: storage-final-proof-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/storage-final-proof/ + if-no-files-found: error + include-hidden-files: false + overwrite: false + retention-days: 30 diff --git a/.gitignore b/.gitignore index d48a879..d46d82a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ pnpm-debug.log* dist/ coverage/ .release/ +/.release-reuse-verification/ +/.release-consumer-verification/ *.tsbuildinfo .env diff --git a/AGENTS.md b/AGENTS.md index 067c505..0c1beef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,18 +70,34 @@ Work on a `claude/*` branch and open a pull request. The gate is Publishing is trusted-publisher only; no tokens exist. A release starts from a protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by -`gh release create vX.Y.Z --verify-tag`. The unprivileged preparation job runs -the gate and packs the exact artifacts; only the minimal publish job receives -OIDC authority. Publication is integrity-checked, retry-safe, and +`gh release create vX.Y.Z --verify-tag`. Unprivileged validation jobs run the +full gates on Node 22 and 24. Preparation depends on that validation and the +signed-release identity checks, packs only selected source packages, and retains +the independently pinned exact original registry archives for unselected +packages. Only the minimal publish job receives OIDC authority. +Publication is integrity-checked, retry-safe, and dependency-ordered. See `docs/RELEASING.md`. +The sole registration exception is a separately reviewed, metadata-only first +`@pegma/storage-dynamodb@0.4.2` archive under `bootstrap`, which may be published +only by the maintainer with interactive 2FA. It contains no runtime, exports, scripts or +dependencies, is not an SDK/release qualification, and is never a host input. +Actual runtime publication remains trusted-publisher only. + +Schema 2 packs only selected source packages. Unselected packages reuse exact, +independently pinned original registry archives with genuine signature/Sigstore +and historical source checks. Never label unversioned workspace changes as +published code or substitute them for the pinned Core `0.4.0` runtime/error classes. + ## Where things stand All four packages are in this repository. `@pegma/storage-core` and `@pegma/storage-azure-tables` are published at `0.4.0`, `@pegma/storage-cloudflare-d1` carries a `0.4.1` transaction-robustness -patch of its own, and `@pegma/storage-dynamodb` is the AWS adapter at -`0.4.2` (see `docs/AWS_ADAPTER.md`). The port offers keyed access, +patch of its own. DynamoDB `0.4.2` is reserved for registration-only metadata; +`@pegma/storage-dynamodb@0.4.3` is the unpublished first trusted AWS runtime +candidate (see `docs/AWS_ADAPTER.md` and `docs/RELEASING.md`). Do not claim +registration or release before its actual registry evidence. The port offers keyed access, optimistic concurrency through `update`, version-conditional `putIfUnchanged` and `deleteIfUnchanged`, partition reads, bounded authoritative cross-partition scans, and `transact`. diff --git a/docs/AWS_ADAPTER.md b/docs/AWS_ADAPTER.md index 4e381a2..4b7cc7d 100644 --- a/docs/AWS_ADAPTER.md +++ b/docs/AWS_ADAPTER.md @@ -2,10 +2,13 @@ ## Status -Implemented in this repository. It is finished when every conformance case -passes against **Amazon DynamoDB Local**. The first advertised publication is -package version `0.4.2` (the next unused repository-wide release number after -`v0.4.1`). +The runtime adapter is implemented in this repository. It qualifies when every +conformance case passes against **Amazon DynamoDB Local** and the release gates +are satisfied. `@pegma/storage-dynamodb@0.4.3` is the unpublished first trusted +runtime candidate. Version `0.4.2` is reserved for a separately reviewed, +metadata-only registration archive: it contains no runtime, exports, scripts or +dependencies, is not an SDK, and must never be a host input. Registration and +runtime publication remain pending until their actual registry evidence exists. Decided 2026-09-11. This is the assignment record for Storage Core's third real adapter — read `AGENTS.md` first; its hard rules govern everything here. @@ -73,10 +76,19 @@ Node 22 + 24. ## Versioning and publish -The port is unchanged, so `@pegma/storage-core` stays at `0.4.0` and this -adapter pins it exactly. The package's first advertised version is `0.4.2` -because repository-wide tags `v0.4.0` and `v0.4.1` already exist and must -never be reused. +The port is unchanged, so `@pegma/storage-core` stays at `0.4.0` and the runtime +candidate pins it exactly. `0.4.2` is registration-only metadata under `bootstrap`, +not a usable adapter release. The first trusted runtime candidate is `0.4.3`; +its publication requires the reviewed signed-source and trusted-publisher flow. +Existing repository-wide tags `v0.4.0` and `v0.4.1` must never be reused. + +Unprivileged validation runs the full gates on Node 22 and 24 before preparation. +Preparation depends on that validation and signed-release identity checks; it +packs only selected source packages and retains the independently pinned exact +original registry archives for unselected packages. Only the minimal publish job +receives OIDC authority. See [RELEASING.md](RELEASING.md) for the separate +registration exception and runtime release procedure; this document records no +completed registration or runtime publication. ## What it unblocks diff --git a/docs/RELEASING.md b/docs/RELEASING.md index c7ce65e..399412d 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,127 +1,203 @@ # Release operations -Storage Core publishes only from a stable GitHub release. Merging a pull -request never publishes, and the workflow has no manual-dispatch or npm-token -fallback. - -## Required external configuration - -Before the first release through this workflow: - -- configure each public package on npm with the GitHub Actions trusted - publisher `pegma-dev/storage-core`, workflow `publish.yml`, environment - `npm-publish`, and allowed action `npm publish`; -- create the GitHub `npm-publish` environment. A second reviewer is not - required under Pegma's single-maintainer policy; -- create the Actions variable `RELEASE_ALLOWED_SIGNERS` containing the - reviewed Git SSH allowed-signers entry for the maintainer's release key; and -- create an active tag ruleset targeting `v*` that prevents tag updates and - deletions and limits tag creation to the release maintainer. - -Do not add `NODE_AUTH_TOKEN`, an npm automation token, or another credential -fallback. After one trusted-publisher release is verified, disable any -remaining traditional npm publish tokens. - -## Independent package versions - -The repository has independent package versions. A `vX.Y.Z` release publishes -only public workspaces whose manifest version is `X.Y.Z`. Every other -workspace is packed too and must reproduce the exact integrity already on npm; -this prevents an unversioned package change from hiding in another package's -release. Release tags begin at `v0.1.0`; `v0.0.x` tags are not accepted. - -Release version numbers are nevertheless allocated repository-wide because -Git tags share one namespace. Before changing a package version, choose a -stable `X.Y.Z` that has never appeared as a `vX.Y.Z` tag in this repository; -normally use the next version after the highest existing release tag. A -package may therefore skip numeric versions. Packages intentionally released -together may share the same version and tag, but a later package must never -reuse an earlier release's number or move its tag. - -The reviewed release order is: - -1. `@pegma/storage-core` -2. `@pegma/storage-azure-tables` -3. `@pegma/storage-cloudflare-d1` -4. `@pegma/storage-dynamodb` - -This keeps the port ahead of adapters that depend on it. The release script -also requires internal dependencies to be exact workspace-version pins. - -### Authoritative scan release - -The new `CollectionStore.scan` method is a breaking port addition, so -`@pegma/storage-core`, `@pegma/storage-azure-tables`, and -`@pegma/storage-cloudflare-d1` release together at `0.4.0`. Both adapters pin -core exactly at `0.4.0`. - -D1 advances from `0.1.0` directly to `0.4.0`. This is deliberate: -repository-wide tags `v0.2.0` and `v0.3.0` already exist and must never be -reused or moved. A single protected signed `v0.4.0` release selects and -publishes all three changed packages in dependency order. - -### D1 transaction-robustness patch - -`@pegma/storage-cloudflare-d1` goes to `0.4.1` alone: a transaction action cap -matching the Azure adapter's, and exact-match classification of the abort -messages its guard triggers raise. The port is unchanged, so -`@pegma/storage-core` and `@pegma/storage-azure-tables` stay at `0.4.0` and -must reproduce the integrity already on npm. `v0.4.1` therefore selects one -package to publish, and D1 keeps its exact `0.4.0` pin on the port. - -### DynamoDB adapter - -`@pegma/storage-dynamodb` is the AWS record-store adapter. The port is -unchanged, so core and Azure stay at `0.4.0` and D1 stays at `0.4.1`; a -`v0.4.2` release selects this package. It pins `@pegma/storage-core` -exactly at `0.4.0`. See `docs/AWS_ADAPTER.md`. - -## Release procedure - -Change package versions through an ordinary reviewed pull request and run the -complete gate on Node 22 and 24. After merge, create a signed annotated tag at -the exact `origin/main` commit, push and verify that tag, and only then create -the GitHub release with `--verify-tag`. Never let GitHub create, move, or -replace the tag. - -Before checkout, the unprivileged preparation job verifies the stable release -event, tag format, tag signature, exact release-event commit, and -`origin/main` ancestry in a temporary bare repository. It then checks out that -commit without persisted credentials, verifies the bundled npm 11.18.0, -enables Corepack for the pinned pnpm, installs from `pnpm-lock.yaml`, runs the -full gate, removes prior build output, and packs every public workspace exactly -once. The sealed inventory contains only the package manifest and four -tarballs, with the npm SHA-1 shasum plus SHA-256 and SHA-512 digests, and is -uploaded before consumer installation begins. - -A separate unprivileged smoke job downloads a copy, verifies the package -manifest digest, and installs the prepared tarballs into an isolated consumer -directory with lifecycle scripts disabled. Locally, `pnpm release:pack` -retains this smoke check by default; `--skip-smoke` produces the sealed files -for a later `node scripts/release-packages.mjs smoke --manifest ` run. - -Already-published `v0.4.0` and `v0.4.1` are immutable npm-era tags. Checking -those tags out still uses `package-lock.json` and `npm ci`. Do not rewrite -them. Every later tag uses `pnpm-lock.yaml`. - -Only the `npm-publish` job receives `id-token: write`. It checks out no -repository code and runs no release-tag scripts. Workflow-owned verification -rechecks the tag in a temporary bare repository, validates the downloaded -inventory and package manifest digest, and publishes verified absolute -tarball paths in the dependency-first order above with npm provenance. -Registry reads and publishes use empty private npm configuration files, a -small environment allowlist, disabled lifecycle scripts, and a fresh working -directory for each publish. - -## Partial-publish recovery - -The workflow is globally serialized. Re-run failed release jobs against the -same unchanged tag: - -- an absent version is published; -- an existing version with identical `dist.integrity` is verified and skipped; -- a different integrity, or any registry error other than `E404`, stops before - later packages publish. - -After each publish, the workflow waits for npm to expose the expected -integrity before advancing. Never unpublish and reuse a version. +Runtime packages publish only through a stable GitHub release and trusted +publisher OIDC. Merging source never publishes. The workflow has no dispatch or +npm-token fallback. The separately reviewed, metadata-only DynamoDB registration +below is an explicit first-package exception, not a runtime release path. + +## Current versions and source ownership + +Core and Azure are published at `0.4.0`; D1 at `0.4.1`. DynamoDB `0.4.2` is reserved for +registration-only metadata, and `0.4.3` is the unpublished first trusted runtime +candidate. Registration is not adapter code, conformance evidence or a production +dependency. Do not claim an actual registration or release until its public +registry evidence exists. + +Unversioned Core/Azure/D1 changes in current source are **not** the code published +at those versions. Schema 2 deliberately selects source artifacts by the new tag +version and reuses original registry archives for the others. It never rebuilds +those old versions or labels their old provenance as the new source. Hosts retain +the genuine Core `0.4.0` runtime, including StorageError/ConcurrencyError identity; +no Core or host upgrade is implied. + +Versions are independently assigned but release tags share a repository-wide +namespace. Never reuse or move a tag/version, including failed publication or +registration versions. First trusted DynamoDB is planned as `v0.4.3`; the separate +later D1 feature must allocate a fresh unused version, such as `0.4.4`, after rebase +and review. + +## Required configuration + +Configure each runtime package's trusted publisher for pegma-dev/storage-core, +publish.yml, environment npm-publish and action npm publish. Maintain the reviewed +RELEASE_ALLOWED_SIGNERS SSH allowed-signers variable and protected signed, +annotated v* tags. The npm-publish environment requires normal owner approval +and tag-only deployment. Recheck actual ownership, approved signer, tag +protection, environment and npm 2FA/direct-publish policy before each release; +historical attestations do not establish current configuration. + +Only publish receives id-token:write. It checks out no source, installs no +dependencies and runs no release-tag/package code. Both npm environment filters +preserve RUNNER_ENVIRONMENT, and the active publisher requires github-hosted +along with the exact release/source/workflow/OIDC identity. Credentials, +inherited npm config, proxy and CA overrides are excluded. There is no token +fallback or alternative local publisher: release:publish and its retained helper +export refuse before I/O and direct the owner to the protected workflow. + +## DynamoDB namespace registration + +After the policy PR, full gates and normal merge, the maintainer may create and +verify the signed v0.4.3 source tag without creating its GitHub release yet. +That approved immutable source guards the separate registration preparation. + +A registration-only `@pegma/storage-dynamodb@0.4.2` archive contains exactly +package.json, README.md and LICENSE. It has no exports/main/module/types/bin, +runtime files, scripts or dependencies of any kind. Metadata/README say that it +only registers the namespace, is not an SDK and has no OIDC provenance. Inspect +and retain its exact bytes/digests before an explicit maintainer 2FA publication +under bootstrap; never install it for a backend/host proof or describe it as the +latest runtime. Inspect actual registry bytes/dist-tags afterward. No GitHub +v0.4.2 release is needed. + +Then configure and verify trusted publishing and package/account restrictions. +Create the v0.4.3 GitHub release only when this configuration is complete. Never +manually publish the real `0.4.3` artifact first: immutable bytes with missing trusted +provenance cannot later be repaired by a skip. Registration `0.4.2` remains immutable +and explicitly outside runtime qualification. + +## Schema 2 and registry reuse policy + +The exact dependency-first inventory remains: + +1. @pegma/storage-core +2. @pegma/storage-azure-tables +3. @pegma/storage-cloudflare-d1 +4. @pegma/storage-dynamodb + +A prepared artifact contains exactly package-manifest.json and four tgz files. +The schema 2 header binds repository, gitCommit, releaseTag, registryPolicySha256 +and that ordered package inventory. Every record includes its package metadata, +file inventory, compressed byte size, SHA-1, SHA-256, SHA-512 SRI and a closed origin: + +- source binds the selected package's directory, exact new commit and tag; +- registryReuse binds the original official registry URL, independently pinned + policy entry, historical source/tag/workflow and original run/attempt. + +scripts/release-reuse-policy.json is reviewed source, not a digest supplied only +by the downloaded artifact. Its exact old archive hashes and historical source +identities are mandatory. Changing or adding reuse pins requires review and +genuine registry cryptographic proof; availability errors never trigger a source +fallback. Internal runtime pins remain exact, including DynamoDB → Core `0.4.0`. + +The producer downloads unselected original archives verbatim and validates bounded +contents, public metadata, exported files, README/LICENSE and test exclusion. It +never substitutes their current unversioned workspace builds. Genuine npm `11.18.0` +signature/Sigstore verification then authenticates each reused root's matching +SLSA subject, certificate issuer/SAN, repository IDs, source/tag/workflow/event, +original invocation and github-hosted builder. Raw outputs and locks are retained +outside the five-file release inventory. Decoding an attestation is not +cryptographic verification. + +Old schema 1 releases and tags remain immutable. New producer code rejects their +schema rather than guessing an origin. Recover an old release using its original +reviewed producer and retained artifacts; do not repack or rewrite historical +tags under schema 2. + +## Gates and exact preparation + +Run formatting, types, all tests and release metadata on actual Node 22 and 24. +Tests use real Azurite, local Miniflare D1 and Amazon DynamoDB Local with Java 21. +The release workflow verifies the signed stable event identity before source +execution, then runs both Node validation lanes before preparation. + +Preparation requires a clean checkout at the signed annotated tag, exact event +commit and origin/main ancestry. The selected runtime comes from that source; +ordinary workspace builds for types/tests do not become unselected release +artifacts. Development pack without a release tag selects the highest candidate +version but cannot authorize publication. + +The output is nonhidden RUNNER_TEMP/storage-prepared. It is sealed before +consumer execution, uploaded with a unique run/attempt name and overwrite:false, +and retained by immutable artifact ID. Record the upload ZIP digest plus the +independent manifest SHA-256. Every downstream job downloads by ID, not just name. +Owner preapproval independently checks the actual original API artifact/ZIP +digest, source/tag, manifest, five-file inventory and all archive bytes. + +Local `release:pack` defaults to `.release` and retains sibling proof directories +`.release-reuse-verification` and `.release-consumer-verification`. These +default paths are ignored by Git; custom outputs inside the checkout can +still violate `--require-clean`. Prefer a new output outside the checkout, such +as `--output ../storage-prepared-unique`, which keeps the same artifact/proof +sibling layout as `RUNNER_TEMP/storage-prepared` in the release workflow. + +Before repository validation, downloads or builds, preparation requires an +absent or empty regular artifact directory and absent reuse/consumer proof +siblings. An existing proof directory is refused even when empty or when that +invocation uses `--skip-smoke`; these three paths identify one retained evidence +namespace. A repeated explicit smoke `--output` is likewise refused before +manifest verification or consumer execution. Keep earlier artifacts and proofs +and choose a new output path. Removing only `.release` does not make its proof +siblings fresh, and these commands never delete or overwrite previous receipts. + +Smoke installs the selected tar and genuine registry Core `0.4.0`/other roots into an +isolated consumer, scripts disabled and no workspace/source/override fallback. +It imports public roots, executes published Core conformance against DynamoDB +Local, and proves real StorageError/ConcurrencyError identity with Core `0.4.0`. +The fixture is local synthetic backend evidence, not a deployed AWS claim. + +## Preflight and minimal publish + +A separate unprivileged whole-set preflight verifies exact canonical registry +bytes and real signatures/provenance before returning any decisions. An absent +selected version may publish; an existing selected version may skip only after +its original bytes and authenticated source/invocation qualify. A missing reused +version, conflicting bytes, unqualified existing selected version or non404 +registry error stops the release. + +Publisher validates the independently sealed original manifest, policy and +preflight receipts again. It receives only verified original archives and +publishes only selected source tar paths from a fresh private directory, with +ignore-scripts, explicit official registry and provenance. Reused packages are +never republished. Package imports and crypto tool installation remain outside +OIDC authority. + +The verified npm tool is exactly `11.18.0`. By default, unprivileged verification +authenticates the pinned official archive digest, extracts its bounded regular +file tree into an owned temporary directory and executes that CLI. It does not +discover or execute host-bundled npm, whose legitimate extra `.bin` links are +outside the original archive. An explicit `npmCli`/`RELEASE_NPM_CLI` remains a +strict reviewed path: every file must match the verified official tree, without +links or extra files, before execution. The minimal OIDC publisher still installs +nothing and uses its separately pinned Node/npm runtime. +Raw audit output is retained before any public consumer import, and its hashes +are checked afterward. Never let a caller-provided qualified boolean or decoded +bundle substitute for that actual cryptographic command. + +## Unknown outcomes and final qualification + +Registry visibility is polled within a bound. A successful physical publication +can be followed by a visibility failure. Preserve the exact original archive, +manifest, source/tag and writer job; never repack, retag, unpublish or overwrite +the version. + +If occupancy changes from an earlier absent preflight, the publisher refuses an +unqualified skip. Refresh the unprivileged preflight job against the **original** +prepare/smoke artifact, then continue through normal owner approval. It is not a +new preparation. A mere failed-publisher retry with the old absent decision does +not bypass current cryptographic qualification. + +Final unprivileged verification installs exact registry roots, authenticates +ECDSA/Sigstore and certificate/SLSA source identities, and compares canonical +tar bytes to the originals before public imports. Reused entries retain their +historical invocations; selected entries must identify this exact release run +and an actual original attempt no later than the current attempt. It independently +checks the original minimal publisher job, source/event and certificate time +overlap. A failed original job can be the physical writer; the final retry is not +automatically that writer. Retain the explicit package→writer map for independent +owner inspection and distinguish it from final workflow success. + +The public registry consumer and complete workflow must succeed before runtime +qualification or host adoption. Raw artifacts, crypto outputs, source bindings, +original writer IDs and consumer results remain reviewable. Green upload/job +status, metadata-only registration or availability by itself is not a qualified +release. diff --git a/docs/securityscan.md b/docs/securityscan.md index 2b55041..57e9da8 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -1,5 +1,10 @@ # Security Scan — storage-core +> Historical point-in-time review from July 2026, including the dated follow-up +> dispositions below. This is not a current source or command-execution inventory; +> later changes require their own review. See [Release operations](RELEASING.md) +> for the current release process and its required verification gates. + Repository-wide security review performed 2026-07-28. Scope: all first-party source (`packages/*/src`), scripts, CI/CD workflows, diff --git a/packages/storage-dynamodb/README.md b/packages/storage-dynamodb/README.md index 17109bc..ed84284 100644 --- a/packages/storage-dynamodb/README.md +++ b/packages/storage-dynamodb/README.md @@ -3,6 +3,13 @@ Amazon DynamoDB adapter for [`@pegma/storage-core`](https://www.npmjs.com/package/@pegma/storage-core). +Source `0.4.3` is the unpublished first trusted runtime candidate and pins +released Core `0.4.0`. Version `0.4.2` is reserved for registration-only metadata, +with no runtime exports/scripts/dependencies; it is not this adapter or a host +dependency. Source merge and metadata registration do not establish publication, +registry provenance or host acceptance. See the +[release policy](https://github.com/pegma-dev/storage-core/blob/main/docs/RELEASING.md). + It stores every collection in one DynamoDB table. The hash key is the collection name and the range key is `` + unit separator + ``. Record bodies are stored as JSON; optimistic concurrency uses a UUID @@ -105,9 +112,12 @@ required by `@pegma/storage-core`. ## Verification -This adapter passes the conformance suite published by `@pegma/storage-core`, -run against Amazon DynamoDB Local rather than a fake client. An adapter that -agrees only with its author's assumptions is not verified. +Required verification runs conformance against Amazon DynamoDB Local rather +than a fake client. The release consumer uses actual published Core `0.4.0` +and the selected DynamoDB artifact, including real `StorageError` and +`ConcurrencyError` identity. Qualified publication additionally requires exact +registry bytes, authenticated signatures/provenance and a clean public consumer; +neither source tests nor namespace registration replace those gates. ## License diff --git a/packages/storage-dynamodb/package.json b/packages/storage-dynamodb/package.json index c963c10..acc3b04 100644 --- a/packages/storage-dynamodb/package.json +++ b/packages/storage-dynamodb/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/storage-dynamodb", - "version": "0.4.2", + "version": "0.4.3", "description": "Amazon DynamoDB adapter for @pegma/storage-core.", "license": "MIT", "type": "module", diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 6d60198..7619fdc 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -1,3 +1,5 @@ +import type { PreparedManifest } from "./release-registry-verify.mjs"; + export interface ReleasePackageDefinition { readonly directory: string; readonly name: string; @@ -11,6 +13,7 @@ export interface ValidationOptions { readonly requireClean?: boolean; readonly requireMainAncestor?: boolean; readonly requireReleaseTag?: boolean; + readonly expectedManifestSha256?: string; } export interface ReleaseCommandOptions extends ValidationOptions { @@ -80,7 +83,12 @@ export function decidePublication( export function prepareRelease( options?: ReleaseCommandOptions, -): Promise<{ manifestPath: string; manifest: unknown }>; +): Promise<{ manifestPath: string; manifest: PreparedManifest }>; + +export function verifyPreparedManifest( + manifestPath: string, + options?: ValidationOptions, +): Promise; export function verifyReleaseInventory( manifestPath: string, diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index db18843..1c08bba 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,12 +1,20 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { + chmodSync, + constants, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; import { lstat, mkdtemp, mkdir, + open, readFile, readdir, + realpath, rm, stat, writeFile, @@ -14,6 +22,14 @@ import { import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { + downloadRegistryArtifact, + inspectReleaseTarball, + loadReusePolicy, + registryReuseOrigin, + runPublicConsumer, + verifyReusedPackages, +} from "./release-registry-verify.mjs"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/storage-core.git"; const NODE_RANGE = ">=22"; @@ -107,17 +123,28 @@ export function isolatedNpmEnvironment( "SYSTEMROOT", "RUNNER_TEMP", "RUNNER_TOOL_CACHE", + "RUNNER_ENVIRONMENT", "TEMP", "TMP", "TMPDIR", + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_SERVER_URL", + "GITHUB_REF", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "GITHUB_WORKFLOW_SHA", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", ]); for (const [key, value] of Object.entries(source)) { const upper = key.toUpperCase(); - if ( - exact.has(upper) || - upper.startsWith("GITHUB_") || - upper.startsWith("ACTIONS_ID_TOKEN_") - ) { + if (exact.has(upper)) { environment[key] = value; } } @@ -366,19 +393,6 @@ function hashTarball(bytes) { }; } -function exportSpecifiers(manifest) { - if ( - manifest.exports === null || - typeof manifest.exports !== "object" || - Array.isArray(manifest.exports) - ) { - fail(`${manifest.name} must declare object-form exports`); - } - return Object.keys(manifest.exports).map((key) => - key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`, - ); -} - function exportTargets(value) { if (typeof value === "string") { return [value]; @@ -691,72 +705,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", - "--registry", - "https://registry.npmjs.org/", - ], - { - capture: true, - allowFailure: true, - }, - ); - if (result.status === 0) { - const integrity = JSON.parse(result.stdout); - if (typeof integrity !== "string" || integrity.length === 0) { - fail(`${spec} exists without dist.integrity`); - } - return integrity; - } - const output = `${result.stdout}\n${result.stderr}`; - if (/\bE404\b/u.test(output)) { - return null; - } - fail(`npm registry lookup failed for ${spec}:\n${output.trim()}`); -} - export function decidePublication(localIntegrity, registryIntegrity) { if (registryIntegrity === null) { return "publish"; @@ -796,26 +744,143 @@ export async function verifyReleaseInventory(manifestPath, suppliedManifest) { return manifest; } +async function assertArtifactOutputAvailable(output) { + let metadata; + try { + metadata = await lstat(output); + } catch (error) { + if (error?.code === "ENOENT") return; + throw error; + } + if (!metadata.isDirectory() || metadata.isSymbolicLink()) + fail( + `release output must be an empty regular directory: ${output}; preserve existing evidence and choose a fresh --output`, + ); + if ((await readdir(output)).length !== 0) + fail( + `release output directory must be empty: ${output}; preserve existing evidence and choose a fresh --output`, + ); +} + +async function assertProofOutputAbsent(output) { + try { + await lstat(output); + } catch (error) { + if (error?.code === "ENOENT") return; + throw error; + } + fail( + `release proof output already exists: ${output}; preserve existing evidence and choose a fresh --output`, + ); +} + export async function prepareRelease(options = {}) { - const { root, packages, releaseTag } = await validateRepository(options); + const root = resolve(options.root ?? defaultRoot()); + const output = resolve(root, options.output ?? ".release"); + const reuseOutput = output + "-reuse-verification"; + const consumerOutput = output + "-consumer-verification"; + // Check one fresh evidence namespace without deleting or modifying any + // earlier result. Refuse before repository/tool/network/build work, even if + // this invocation skips one of the later proof-producing steps. + await assertArtifactOutputAvailable(output); + await assertProofOutputAbsent(reuseOutput); + await assertProofOutputAbsent(consumerOutput); + const { packages, releaseTag } = await validateRepository({ + ...options, + root, + }); const gitCommit = run(gitCommand(), ["rev-parse", "HEAD"], { cwd: root, capture: true, }).stdout.trim(); - if (!/^[0-9a-f]{40}$/u.test(gitCommit)) { - fail(`git returned an invalid commit SHA: ${gitCommit}`); - } - const output = resolve(root, options.output ?? ".release"); + if (!/^[0-9a-f]{40}$/u.test(gitCommit)) + fail("git returned an invalid source commit"); + const assertSource = () => { + const current = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + if (!safeEqual(current, gitCommit)) + fail("release source changed during preparation"); + if ( + options.requireClean && + run(gitCommand(), ["status", "--porcelain"], { + cwd: root, + capture: true, + }).stdout.trim() + ) + fail("release working source changed during preparation"); + }; await mkdir(output, { recursive: true }); - if ((await readdir(output)).length !== 0) { - fail(`release output directory must be empty: ${output}`); + await assertArtifactOutputAvailable(output); + const { policy, sha256: registryPolicySha256 } = await loadReusePolicy(); + // Development preparation selects the highest candidate version. Only a + // protected signed release tag can authorize actual publication. + const selectedVersion = + releaseTag?.slice(1) ?? + packages + .map(({ manifest }) => manifest.version) + .sort((a, b) => + compareSemver(parseStableSemver(b), parseStableSemver(a)), + )[0]; + const selected = packages.filter( + ({ manifest }) => manifest.version === selectedVersion, + ); + const unselected = packages.filter( + ({ manifest }) => manifest.version !== selectedVersion, + ); + // Admit the complete reuse subset before any archive download or write. + if ( + unselected.some( + ({ manifest }) => + !policy.packages.some( + (entry) => + entry.name === manifest.name && entry.version === manifest.version, + ), + ) + ) + fail("unselected workspace has no approved registry reuse policy"); + const records = []; + for (const { definition, manifest } of packages) { + if (manifest.version === selectedVersion) continue; + const entry = policy.packages.find( + (item) => + item.name === manifest.name && item.version === manifest.version, + ); + if (entry === undefined) + fail("unselected workspace has no approved registry reuse policy"); + const downloaded = await downloadRegistryArtifact(entry); + const tarball = + entry.name.slice(1).replace("/", "-") + "-" + entry.version + ".tgz"; + await writeFile(join(output, tarball), downloaded.bytes, { flag: "wx" }); + records.push({ + name: entry.name, + version: entry.version, + directory: definition.directory, + tarball, + size: downloaded.bytes.length, + shasum: entry.shasum, + sha256: entry.sha256, + integrity: entry.integrity, + publish: false, + files: downloaded.files, + package: downloaded.package, + origin: registryReuseOrigin(entry), + }); } - + if (records.length) { + await verifyReusedPackages( + records, + { gitCommit, releaseTag: releaseTag ?? null }, + { output: reuseOutput }, + ); + } + assertSource(); + // Workspace builds are type/conformance preparation only. Unselected compiled + // output is never packed or substituted for the original registry archives. await cleanWorkspaceBuildArtifacts(root); runNpm(["run", "build"], { cwd: root }); - const records = []; - const tagVersion = releaseTag?.slice(1); - for (const { definition, manifest } of packages) { + for (const { definition, manifest } of selected) { const result = runNpm( [ "pack", @@ -829,85 +894,147 @@ export async function prepareRelease(options = {}) { const [packed] = JSON.parse(result.stdout); if ( packed?.name !== definition.name || - packed?.version !== manifest.version || - typeof packed.filename !== "string" || - !Array.isArray(packed.files) - ) { - fail(`npm pack returned invalid metadata for ${definition.name}`); - } - verifyPackedFiles(manifest, packed.files); - const tarballPath = join(output, basename(packed.filename)); - const hashes = hashTarball(await readFile(tarballPath)); + packed.version !== manifest.version || + typeof packed.filename !== "string" + ) + fail("npm pack returned invalid source metadata"); + const tarball = basename(packed.filename), + bytes = await readFile(join(output, tarball)); + const hashes = hashTarball(bytes), + inspected = inspectReleaseTarball(bytes); if ( !safeEqual(hashes.integrity, packed.integrity) || - !safeEqual(hashes.shasum, packed.shasum) - ) { - fail(`${definition.name} tarball hashes do not match npm pack metadata`); - } + !safeEqual(hashes.shasum, packed.shasum) || + !sameJson(inspected.package, manifest) + ) + fail("source tarball differs from its reviewed metadata"); + verifyPackedFiles(manifest, inspected.files); records.push({ - name: definition.name, + name: manifest.name, version: manifest.version, directory: definition.directory, - tarball: basename(tarballPath), - tarballPath, - integrity: hashes.integrity, - sha256: hashes.sha256, - shasum: hashes.shasum, - publish: tagVersion === undefined || manifest.version === tagVersion, - files: packed.files - .map(({ path, size }) => ({ path, size })) - .sort((left, right) => left.path.localeCompare(right.path)), - manifest, + tarball, + size: bytes.length, + ...hashes, + publish: true, + files: inspected.files, + package: inspected.package, + origin: { + kind: "source", + repository: "pegma-dev/storage-core", + gitCommit, + releaseTag: releaseTag ?? null, + directory: definition.directory, + }, }); } - if (releaseTag !== undefined) { - for (const record of records.filter(({ publish }) => !publish)) { - const registryIntegrity = queryRegistryIntegrity( - record.name, - record.version, - ); - if ( - registryIntegrity === null || - !safeEqual(record.integrity, registryIntegrity) - ) { - fail( - `${record.name}@${record.version} is not selected by ${releaseTag} and must exactly match npm`, - ); - } - } - } - + records.sort( + (a, b) => + RELEASE_PACKAGES.findIndex((p) => p.name === a.name) - + RELEASE_PACKAGES.findIndex((p) => p.name === b.name), + ); + assertSource(); const manifest = { - schemaVersion: 1, + schemaVersion: 2, + repository: "pegma-dev/storage-core", gitCommit, releaseTag: releaseTag ?? null, - packages: records.map( - ({ tarballPath, manifest: packageManifest, ...record }) => ({ - ...record, - package: packageManifest, - }), - ), + registryPolicySha256, + packages: records, }; const manifestPath = join(output, "package-manifest.json"); - await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); - await verifyReleaseInventory(manifestPath, manifest); + await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n", { + flag: "wx", + }); + await verifyPreparedManifest(manifestPath, { + root, + expectedReleaseCommit: gitCommit, + }); if (!options.skipSmoke) { - await smokeTestTarballs(root, records); + await mkdir(consumerOutput); + await runPublicConsumer(manifest, { + manifest: manifestPath, + output: consumerOutput, + }); + assertSource(); + await verifyPreparedManifest(manifestPath, { + root, + expectedReleaseCommit: gitCommit, + }); } return { manifestPath, manifest }; } -async function verifyPreparedManifest(manifestPath) { - const manifest = await verifyReleaseInventory(manifestPath); +async function readPreparedFile(path, maximum) { + const metadata = await lstat(path); + if ( + !metadata.isFile() || + metadata.isSymbolicLink() || + metadata.size < 1 || + metadata.size > maximum || + (await realpath(path)) !== resolve(path) + ) + fail("prepared file is outside its regular-file bound"); + const handle = await open( + path, + constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0), + ); + try { + const opened = await handle.stat(); + if ( + !opened.isFile() || + opened.dev !== metadata.dev || + opened.ino !== metadata.ino || + opened.size !== metadata.size + ) + fail("prepared file changed while opening"); + const bytes = Buffer.alloc(metadata.size + 1); + let length = 0; + while (length < bytes.length) { + const read = await handle.read( + bytes, + length, + bytes.length - length, + length, + ); + if (!read.bytesRead) break; + length += read.bytesRead; + } + if (length !== metadata.size) fail("prepared file changed while reading"); + return bytes.subarray(0, length); + } finally { + await handle.close(); + } +} + +export async function verifyPreparedManifest(manifestPath, options = {}) { + manifestPath = resolve(manifestPath); + const manifestBytes = await readPreparedFile(manifestPath, 1024 * 1024); + if ( + options.expectedManifestSha256 !== undefined && + (!/^[a-f0-9]{64}$/u.test(options.expectedManifestSha256) || + !safeEqual( + createHash("sha256").update(manifestBytes).digest("hex"), + options.expectedManifestSha256, + )) + ) + fail("prepared manifest independent digest differs"); + const manifest = await verifyReleaseInventory( + manifestPath, + JSON.parse(manifestBytes), + ); if ( !sameJson(Object.keys(manifest).sort(), [ "gitCommit", "packages", + "registryPolicySha256", "releaseTag", + "repository", "schemaVersion", ]) || - manifest.schemaVersion !== 1 || - !/^[0-9a-f]{40}$/u.test(manifest.gitCommit) || + manifest.schemaVersion !== 2 || + manifest.repository !== "pegma-dev/storage-core" || + !/^[a-f0-9]{40}$/u.test(manifest.gitCommit) || (manifest.releaseTag !== null && !RELEASE_TAG_PATTERN.test(manifest.releaseTag)) || !Array.isArray(manifest.packages) || @@ -915,69 +1042,105 @@ async function verifyPreparedManifest(manifestPath) { manifest.packages.map(({ name }) => name), RELEASE_PACKAGES.map(({ name }) => name), ) - ) { - fail("prepared package manifest has an invalid package inventory"); - } + ) + fail("prepared schema2 manifest identity or inventory is invalid"); const currentCommit = run(gitCommand(), ["rev-parse", "HEAD"], { - cwd: defaultRoot(), + cwd: options.root ?? defaultRoot(), capture: true, }).stdout.trim(); - if (!safeEqual(currentCommit, manifest.gitCommit)) { - fail("prepared package manifest commit does not match the checkout"); - } - const tagVersion = manifest.releaseTag?.slice(1) ?? null; - if (!manifest.packages.some(({ publish }) => publish)) { - fail("prepared package manifest has no release candidates"); - } - const packageVersions = new Map( - manifest.packages.map(({ name, version }) => [name, version]), - ); + if ( + !safeEqual(currentCommit, manifest.gitCommit) || + (options.expectedReleaseCommit !== undefined && + !safeEqual(options.expectedReleaseCommit, manifest.gitCommit)) + ) + fail("prepared manifest does not match the current approved checkout"); + const { policy, sha256 } = await loadReusePolicy(); + if (!safeEqual(sha256, manifest.registryPolicySha256)) + fail("registry reuse policy digest differs"); + if (!manifest.packages.some((record) => record.publish)) + fail("prepared release has no source candidates"); + const versions = new Map(manifest.packages.map((r) => [r.name, r.version])); for (const [index, record] of manifest.packages.entries()) { const definition = RELEASE_PACKAGES[index]; - const expectedTarball = `${definition.name - .slice(1) - .replace("/", "-")}-${record.version}.tgz`; if ( !sameJson(Object.keys(record).sort(), [ "directory", "files", "integrity", "name", + "origin", "package", "publish", "sha256", "shasum", + "size", "tarball", "version", ]) || - record.directory !== definition.directory || record.name !== definition.name || - record.tarball !== expectedTarball || + record.directory !== definition.directory || !STABLE_SEMVER.test(record.version) || - record.publish !== - (tagVersion === null || record.version === tagVersion) || - !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(record.integrity) || - !/^[0-9a-f]{64}$/u.test(record.sha256) || - !/^[0-9a-f]{40}$/u.test(record.shasum) || + record.tarball !== + record.name.slice(1).replace("/", "-") + + "-" + + record.version + + ".tgz" || + basename(record.tarball) !== record.tarball || + !Number.isSafeInteger(record.size) || + record.size < 1 || + record.size > 4 * 1024 * 1024 || + !/^[a-f0-9]{64}$/u.test(record.sha256) || + !/^[a-f0-9]{40}$/u.test(record.shasum) || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) || + typeof record.publish !== "boolean" || record.package?.name !== record.name || - record.package?.version !== record.version || - record.package?.license !== "MIT" || - record.package?.type !== "module" || - record.package?.publishConfig?.access !== "public" || - record.package?.repository?.url !== REPOSITORY_URL || - record.package?.repository?.directory !== - `packages/${definition.directory}` || - !Array.isArray(record.files) || - record.files.some( - (file) => - file === null || - typeof file !== "object" || - typeof file.path !== "string" || - !Number.isSafeInteger(file.size) || - file.size < 0, + record.package.version !== record.version || + record.package.license !== "MIT" || + record.package.type !== "module" || + record.package.engines?.node !== NODE_RANGE || + record.package.publishConfig?.access !== "public" || + record.package.repository?.url !== REPOSITORY_URL || + record.package.repository?.directory !== "packages/" + record.directory + ) + fail("prepared artifact metadata is invalid"); + if (record.publish) { + if ( + !sameJson(record.origin, { + kind: "source", + repository: manifest.repository, + gitCommit: manifest.gitCommit, + releaseTag: manifest.releaseTag, + directory: record.directory, + }) || + (manifest.releaseTag !== null && + record.version !== manifest.releaseTag.slice(1)) ) - ) { - fail(`${record.name} has invalid prepared metadata`); + fail("selected source origin differs from the release"); + const source = await readJson( + join( + options.root ?? defaultRoot(), + "packages", + record.directory, + "package.json", + ), + ); + if (!sameJson(record.package, source)) + fail("selected package metadata differs from source"); + } else { + const entry = policy.packages.find( + (p) => p.name === record.name && p.version === record.version, + ); + if ( + !entry || + !sameJson(record.origin, registryReuseOrigin(entry)) || + !safeEqual(record.sha256, entry.sha256) || + !safeEqual(record.integrity, entry.integrity) || + !safeEqual(record.shasum, entry.shasum) || + record.size !== entry.size || + (manifest.releaseTag !== null && + record.version === manifest.releaseTag.slice(1)) + ) + fail("registry reuse origin differs from independent policy"); } for (const section of [ "dependencies", @@ -985,162 +1148,84 @@ async function verifyPreparedManifest(manifestPath) { "optionalDependencies", "peerDependencies", ]) { - for (const [dependency, version] of Object.entries( + for (const [name, version] of Object.entries( record.package[section] ?? {}, - )) { - if ( - packageVersions.has(dependency) && - version !== packageVersions.get(dependency) - ) { - fail(`${record.name} has an invalid internal dependency pin`); - } - } + )) + if (versions.has(name) && version !== versions.get(name)) + fail("prepared internal dependency pin differs"); } - const tarball = resolve(dirname(manifestPath), record.tarball); - if (dirname(tarball) !== resolve(dirname(manifestPath))) { - fail(`${record.name} tarball must be beside the package manifest`); - } - const hashes = hashTarball(await readFile(tarball)); + const tarball = join(dirname(manifestPath), record.tarball), + details = await lstat(tarball); + if ( + !details.isFile() || + details.isSymbolicLink() || + details.size !== record.size + ) + fail("prepared artifact is not the original regular file"); + const bytes = await readPreparedFile(tarball, 4 * 1024 * 1024), + hashes = hashTarball(bytes), + inspected = inspectReleaseTarball(bytes); if ( - !safeEqual(hashes.integrity, record.integrity) || !safeEqual(hashes.sha256, record.sha256) || - !safeEqual(hashes.shasum, record.shasum) - ) { - fail(`${record.name} prepared tarball has changed`); - } + !safeEqual(hashes.integrity, record.integrity) || + !safeEqual(hashes.shasum, record.shasum) || + !sameJson(inspected.files, record.files) || + !sameJson(inspected.package, record.package) + ) + fail("prepared artifact bytes or contents differ"); + verifyPackedFiles(record.package, record.files); } return manifest; } export async function smokePreparedRelease(options = {}) { + const output = options.output ? resolve(options.output) : undefined; + if (output !== undefined) await assertProofOutputAbsent(output); const manifestPath = resolve( options.manifest ?? ".release/package-manifest.json", ); - const manifest = await verifyPreparedManifest(manifestPath); - const expectedReleaseCommit = - options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; - if ( - expectedReleaseCommit !== undefined && - (!/^[0-9a-f]{40}$/u.test(expectedReleaseCommit) || - !safeEqual(manifest.gitCommit, expectedReleaseCommit)) - ) { - fail("prepared package manifest must match the release event commit"); - } - await smokeTestTarballs( - defaultRoot(), - manifest.packages.map((record) => ({ - ...record, - manifest: record.package, - tarballPath: resolve(dirname(manifestPath), record.tarball), - })), - ); -} - -function requireTrustedPublishingNpm() { - const version = runNpm(["--version"], { capture: true }).stdout.trim(); - const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); - if (match === null) { - fail(`could not parse npm version ${version}`); - } - const [, majorText, minorText, patchText] = match; - const [major, minor, patch] = [majorText, minorText, patchText].map(Number); - if ( - major < 11 || - (major === 11 && minor < 5) || - (major === 11 && minor === 5 && patch < 1) - ) { - fail("trusted publishing requires npm 11.5.1 or newer"); - } -} - -function wait(milliseconds) { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); + const manifest = await verifyPreparedManifest(manifestPath, options); + if (output !== undefined) await mkdir(output); + const consumer = await runPublicConsumer(manifest, { + ...options, + manifest: manifestPath, + }); + await verifyPreparedManifest(manifestPath, options); + if (output !== undefined) + await writeFile( + join(output, "verification.json"), + JSON.stringify( + { + status: "PREPARED_PUBLIC_CONSUMER_PASS", + gitCommit: manifest.gitCommit, + releaseTag: manifest.releaseTag, + manifestSha256: options.expectedManifestSha256, + consumer, + }, + null, + 2, + ) + "\n", + { flag: "wx" }, + ); } -function confirmRegistryIntegrity(record) { - for (let attempt = 0; attempt < 6; attempt += 1) { - const integrity = queryRegistryIntegrity(record.name, record.version); - if (integrity !== null && safeEqual(record.integrity, integrity)) { - return; - } - if (attempt < 5) { - wait(2 ** attempt * 1000); - } - } +/** Publication is exclusively workflow-owned; retained as a refusing compatibility export. */ +export async function publishPreparedRelease() { fail( - `${record.name}@${record.version} did not become visible with the prepared integrity`, - ); -} - -export async function publishPreparedRelease(options = {}) { - if ( - process.env.GITHUB_ACTIONS !== "true" || - process.env.GITHUB_EVENT_NAME !== "release" - ) { - fail("release:publish is restricted to a GitHub release workflow"); - } - requireTrustedPublishingNpm(); - const manifestPath = resolve( - options.manifest ?? ".release/package-manifest.json", + "release:publish is disabled; use the protected GitHub release workflow", ); - const manifest = await verifyPreparedManifest(manifestPath); - const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; - const expectedReleaseCommit = - options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; - if (releaseTag !== manifest.releaseTag) { - fail("prepared manifest must match the release tag"); - } - if ( - expectedReleaseCommit === undefined || - !/^[0-9a-f]{40}$/u.test(expectedReleaseCommit) || - !safeEqual(manifest.gitCommit, expectedReleaseCommit) - ) { - fail("prepared package manifest must match the release event commit"); - } - for (const record of manifest.packages.filter(({ publish }) => publish)) { - const registryIntegrity = queryRegistryIntegrity( - record.name, - record.version, - ); - const decision = decidePublication(record.integrity, registryIntegrity); - if (decision === "skip") { - process.stdout.write( - `Verified existing ${record.name}@${record.version}; skipping.\n`, - ); - continue; - } - const tarball = resolve(dirname(manifestPath), record.tarball); - const publishDirectory = await mkdtemp( - join(tmpdir(), "pegma-release-publish-"), - ); - try { - runNpm( - [ - "publish", - tarball, - "--access", - "public", - "--provenance", - "--ignore-scripts", - "--registry", - "https://registry.npmjs.org/", - ], - { cwd: publishDirectory }, - ); - } finally { - await rm(publishDirectory, { recursive: true, force: true }); - } - confirmRegistryIntegrity(record); - } } export function parseArguments(arguments_) { const options = {}; + const seen = new Set(); for (let index = 0; index < arguments_.length; index += 1) { const argument = arguments_[index]; if (argument === "--") { continue; } + if (seen.has(argument)) fail(`duplicate argument: ${argument}`); + seen.add(argument); if (argument === "--require-main-ancestor") { options.requireMainAncestor = true; continue; @@ -1166,8 +1251,16 @@ export function parseArguments(arguments_) { ? "manifest" : argument === "--expected-release-commit" ? "expectedReleaseCommit" - : null; - if (key === null || arguments_[index + 1] === undefined) { + : argument === "--expected-manifest-sha256" + ? "expectedManifestSha256" + : argument === "--release-tag" + ? "releaseTag" + : null; + if ( + key === null || + arguments_[index + 1] === undefined || + arguments_[index + 1].startsWith("--") + ) { fail(`unknown or incomplete argument: ${argument}`); } options[key] = arguments_[index + 1]; diff --git a/scripts/release-registry-verify.d.mts b/scripts/release-registry-verify.d.mts new file mode 100644 index 0000000..0d922ab --- /dev/null +++ b/scripts/release-registry-verify.d.mts @@ -0,0 +1,200 @@ +import type { + PublicPackageManifest, + ValidationOptions, +} from "./release-packages.mjs"; + +export interface PackageFile { + readonly path: string; + readonly size: number; +} +export interface SourceOrigin { + readonly kind: "source"; + readonly repository: "pegma-dev/storage-core"; + readonly gitCommit: string; + readonly releaseTag: string | null; + readonly directory: string; +} +export interface RegistryReuseOrigin { + readonly kind: "registryReuse"; + readonly registry: "https://registry.npmjs.org/"; + readonly policyEntry: string; + readonly tarballUrl: string; + readonly sourceCommit: string; + readonly sourceTag: string; + readonly workflowPath: ".github/workflows/publish.yml"; + readonly originalRunId: number; + readonly originalRunAttempt: number; +} +export interface RegistryDownloadExpectation { + readonly name: string; + readonly version: string; + readonly size: number; + readonly sha256: string; + readonly shasum: string; + readonly integrity: string; +} +export interface ReusePolicyEntry extends RegistryDownloadExpectation { + readonly directory: string; + readonly tarballUrl: string; + readonly sourceCommit: string; + readonly sourceTag: string; + readonly workflowPath: ".github/workflows/publish.yml"; + readonly originalRunId: number; + readonly originalRunAttempt: number; +} +export interface ReusePolicy { + readonly schemaVersion: 1; + readonly repository: "pegma-dev/storage-core"; + readonly repositoryId: "1312519623"; + readonly ownerId: "309286193"; + readonly builder: "https://github.com/actions/runner/github-hosted"; + readonly packages: readonly ReusePolicyEntry[]; +} +export interface PreparedPackage extends RegistryDownloadExpectation { + readonly directory: string; + readonly tarball: string; + readonly publish: boolean; + readonly files: readonly PackageFile[]; + readonly package: PublicPackageManifest; + readonly origin: SourceOrigin | RegistryReuseOrigin; +} +export interface PreparedManifest { + readonly schemaVersion: 2; + readonly repository: "pegma-dev/storage-core"; + readonly gitCommit: string; + readonly releaseTag: string | null; + readonly registryPolicySha256: string; + readonly packages: readonly PreparedPackage[]; +} +export interface ReleaseIdentity { + readonly gitCommit: string; + readonly releaseTag: string | null; +} +export interface PublicationIdentity extends ReleaseIdentity { + readonly releaseTag: string; + readonly runId: number; + readonly runAttempt: number; +} +export interface VerificationOptions extends ValidationOptions { + readonly manifest?: string; + readonly output: string; + readonly expectedManifestSha256?: string; + readonly runId?: string | number; + readonly runAttempt?: string | number; + /** Explicit CLI must exactly match the verified archive tree. Omission (and + * no RELEASE_NPM_CLI) runs the pinned official tool from owned temporary files. */ + readonly npmCli?: string; +} +export interface VerificationSeams { + readonly fetch?: typeof globalThis.fetch; + readonly env?: NodeJS.ProcessEnv; + readonly run?: ( + command: string, + args: readonly string[], + options: { readonly cwd: string; readonly env: NodeJS.ProcessEnv }, + ) => Promise<{ + readonly status: number | null; + readonly stdout: string; + readonly stderr?: string; + }>; +} +export interface AuthenticatedPackage { + readonly name: string; + readonly version: string; + readonly sourceCommit: string; + readonly sourceTag: string; + readonly runId: number; + readonly attempt: number; + readonly invocation: string; + readonly certificate: { + readonly validFrom: string; + readonly validTo: string; + }; +} +export interface PublishingJob { + readonly id: number; + readonly runId: number; + readonly attempt: number; + readonly sourceCommit: string; + readonly sourceTag: string; + readonly packages: readonly string[]; + readonly stepName: + | "Publish verified prepared tarballs" + | "Verify and publish the prepared release"; + readonly conclusion: "success" | "failure"; + readonly startedAt: string; + readonly completedAt: string; + readonly stepStartedAt: string; + readonly stepCompletedAt: string; +} +export const REGISTRY: "https://registry.npmjs.org/"; +export const RELEASE_REPOSITORY: "pegma-dev/storage-core"; +export const RELEASE_NPM_VERSION: "11.18.0"; +/** Validates a unique canonical inventory subset; does not authenticate pins. */ +export function validateReusePolicy(policy: unknown): ReusePolicy; +export function loadReusePolicy(): Promise<{ + readonly policy: ReusePolicy; + readonly sha256: string; +}>; +export function registryReuseOrigin( + entry: ReusePolicyEntry, +): RegistryReuseOrigin; +export function canonicalTarball( + record: Pick, +): string; +export function inspectReleaseTarball(bytes: Uint8Array): { + readonly package: PublicPackageManifest; + readonly files: readonly PackageFile[]; +}; +export function downloadRegistryArtifact( + entry: RegistryDownloadExpectation, + seams?: Pick, +): Promise<{ + readonly bytes: Uint8Array; + readonly metadata: Record; + readonly package: PublicPackageManifest; + readonly files: readonly PackageFile[]; +}>; +export function isolatedVerificationEnvironment( + source: NodeJS.ProcessEnv, + directory: string, + publishing?: boolean, +): NodeJS.ProcessEnv; +export function assertTrustedPublishingEnvironment( + env: NodeJS.ProcessEnv, + identity: ReleaseIdentity, +): void; +/** Input must be genuine npm-cryptographically-verified audit output. */ +export function verifyProvenanceAudit( + audit: unknown, + records: readonly PreparedPackage[], + identity: PublicationIdentity, + policy: ReusePolicy, +): readonly AuthenticatedPackage[]; +/** Facts must already come from npm's genuine verified SLSA audit. */ +export function verifyPublishingJobs( + facts: readonly AuthenticatedPackage[], + seams?: Pick, + output?: string, +): Promise; +export function verifyReusedPackages( + records: readonly PreparedPackage[], + identity: ReleaseIdentity, + options: VerificationOptions, + seams?: VerificationSeams, +): Promise>; +export function preflightRegistry( + manifest: PreparedManifest, + options: VerificationOptions, + seams?: VerificationSeams, +): Promise>; +export function runPublicConsumer( + manifest: PreparedManifest, + options?: Partial, + seams?: VerificationSeams, +): Promise>; +export function verifyRegistryRelease( + manifest: PreparedManifest, + options: VerificationOptions, + seams?: VerificationSeams, +): Promise>; diff --git a/scripts/release-registry-verify.mjs b/scripts/release-registry-verify.mjs new file mode 100644 index 0000000..ebc2f53 --- /dev/null +++ b/scripts/release-registry-verify.mjs @@ -0,0 +1,1467 @@ +import { spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual, X509Certificate } from "node:crypto"; +import { gunzipSync } from "node:zlib"; +import { + chmod, + copyFile, + lstat, + mkdir, + mkdtemp, + readFile, + readdir, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +export const REGISTRY = "https://registry.npmjs.org/"; +export const RELEASE_REPOSITORY = "pegma-dev/storage-core"; +export const RELEASE_NPM_VERSION = "11.18.0"; +const workflowPath = ".github/workflows/publish.yml"; +const provenanceType = "https://slsa.dev/provenance/v1"; +const root = fileURLToPath(new URL("../", import.meta.url)); +const npmArchiveUrl = "https://registry.npmjs.org/npm/-/npm-11.18.0.tgz"; +const npmArchiveSha256 = + "73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e"; +const maximumTarBytes = 4 * 1024 * 1024; +// The release consumer's direct SDK root is bound to the reviewed pnpm lock, +// independently of the adapter's supported runtime range. Transitives are not +// claimed reproducible, and this pin does not claim AWS SLSA provenance. +const consumerAwsSdk = { + name: "@aws-sdk/client-dynamodb", + version: "3.1130.0", + integrity: + "sha512-yPEc9TWLY1McM6xA9wlxA9rM0ZeS8RAeyi1t7rdHPNxq0TpyCDn6z651ccRJ1RrMU4k2aiVzNCaBYUZA4aaA/w==", + tarballUrl: + "https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.1130.0.tgz", +}; + +function fail(message) { + throw new Error(message); +} +function hash(bytes, algorithm = "sha256", encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} +function equal(left, right) { + if (typeof left !== "string" || typeof right !== "string") return false; + const a = Buffer.from(left), + b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} +function exact(value, keys) { + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + JSON.stringify(Object.keys(value).sort()) !== + JSON.stringify([...keys].sort()) + ) + fail("release data contains invalid fields"); +} +function integer(value, maximum = Number.MAX_SAFE_INTEGER, minimum = 1) { + if (!Number.isSafeInteger(value) || value < minimum || value > maximum) + fail("release data contains an invalid bound"); +} +export function validateReusePolicy(policy) { + exact(policy, [ + "schemaVersion", + "repository", + "repositoryId", + "ownerId", + "builder", + "packages", + ]); + if ( + policy.schemaVersion !== 1 || + policy.repository !== RELEASE_REPOSITORY || + policy.repositoryId !== "1312519623" || + policy.ownerId !== "309286193" || + policy.builder !== "https://github.com/actions/runner/github-hosted" || + !Array.isArray(policy.packages) || + policy.packages.length > 4 + ) + fail("registry reuse policy is invalid"); + const names = [ + "@pegma/storage-core", + "@pegma/storage-azure-tables", + "@pegma/storage-cloudflare-d1", + "@pegma/storage-dynamodb", + ]; + let previousIndex = -1; + for (const record of policy.packages) { + exact(record, [ + "name", + "version", + "directory", + "tarballUrl", + "size", + "sha256", + "integrity", + "shasum", + "sourceCommit", + "sourceTag", + "workflowPath", + "originalRunId", + "originalRunAttempt", + ]); + const index = names.indexOf(record.name); + if ( + index <= previousIndex || + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(record.version) || + record.directory !== record.name.split("/")[1] || + record.tarballUrl !== canonicalTarball(record) || + !/^[a-f0-9]{64}$/u.test(record.sha256) || + !/^[a-f0-9]{40}$/u.test(record.shasum) || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) || + !/^[a-f0-9]{40}$/u.test(record.sourceCommit) || + record.sourceTag !== "v" + record.version || + record.workflowPath !== workflowPath + ) + fail("registry reuse policy entry is invalid"); + integer(record.size, maximumTarBytes); + integer(record.originalRunId); + integer(record.originalRunAttempt); + previousIndex = index; + } + return policy; +} +export async function loadReusePolicy() { + const bytes = await readFile( + new URL("./release-reuse-policy.json", import.meta.url), + ); + const policy = validateReusePolicy(JSON.parse(bytes)); + return { policy, sha256: hash(bytes) }; +} +export function registryReuseOrigin(entry) { + return { + kind: "registryReuse", + registry: REGISTRY, + policyEntry: entry.name + "@" + entry.version, + tarballUrl: entry.tarballUrl, + sourceCommit: entry.sourceCommit, + sourceTag: entry.sourceTag, + workflowPath: entry.workflowPath, + originalRunId: entry.originalRunId, + originalRunAttempt: entry.originalRunAttempt, + }; +} +export function canonicalTarball(record) { + return ( + REGISTRY + + record.name + + "/-/" + + record.name.split("/")[1] + + "-" + + record.version + + ".tgz" + ); +} +async function responseBytes(response, maximum) { + const declared = response.headers?.get("content-length"); + if ( + declared !== undefined && + declared !== null && + (!/^\d+$/u.test(declared) || Number(declared) > maximum) + ) { + await response.body?.cancel(); + fail("registry response exceeded its limit"); + } + let size = 0; + const chunks = []; + if (response.body) + for await (const chunk of response.body) { + size += chunk.length; + if (size > maximum) { + await response.body.cancel().catch(() => {}); + fail("registry response exceeded its limit"); + } + chunks.push(Buffer.from(chunk)); + } + return Buffer.concat(chunks, size); +} +async function request(url, fetch = globalThis.fetch) { + try { + return await fetch(url, { + redirect: "error", + signal: AbortSignal.timeout(30_000), + headers: { accept: "application/json" }, + }); + } catch { + fail("registry availability is unknown"); + } +} +export async function downloadRegistryArtifact(entry, seams = {}) { + const metadataResponse = await request( + REGISTRY + encodeURIComponent(entry.name) + "/" + entry.version, + seams.fetch, + ); + if (metadataResponse.status !== 200) { + await metadataResponse.body?.cancel(); + fail("required registry artifact is unavailable"); + } + const metadata = JSON.parse( + (await responseBytes(metadataResponse, 2 * 1024 * 1024)).toString("utf8"), + ); + if ( + metadata.name !== entry.name || + metadata.version !== entry.version || + !equal(metadata.dist?.integrity, entry.integrity) || + !equal(metadata.dist?.shasum, entry.shasum) || + metadata.dist?.tarball !== canonicalTarball(entry) || + !Array.isArray(metadata.dist.signatures) || + metadata.dist.signatures.length === 0 || + !metadata.dist.signatures.every( + (s) => + typeof s.keyid === "string" && + s.keyid.length > 0 && + typeof s.sig === "string" && + s.sig.length > 0, + ) + ) + fail("registry metadata conflicts with the pinned artifact"); + const response = await request(metadata.dist.tarball, seams.fetch); + if (response.status !== 200) { + await response.body?.cancel(); + fail("canonical registry tarball is unavailable"); + } + const bytes = await responseBytes(response, entry.size); + if ( + bytes.length !== entry.size || + !equal(hash(bytes), entry.sha256) || + !equal(hash(bytes, "sha1"), entry.shasum) || + !equal("sha512-" + hash(bytes, "sha512", "base64"), entry.integrity) + ) + fail("registry tarball conflicts with the original bytes"); + const inspected = inspectReleaseTarball(bytes); + if ( + inspected.package.name !== entry.name || + inspected.package.version !== entry.version + ) + fail("registry archive identity conflicts with its policy"); + return { bytes, metadata, ...inspected }; +} +function tarText(bytes) { + const zero = bytes.indexOf(0); + return bytes.subarray(0, zero === -1 ? bytes.length : zero).toString("utf8"); +} +export function inspectReleaseTarball(bytes) { + integer(bytes.length, maximumTarBytes); + const tar = gunzipSync(bytes, { maxOutputLength: 16 * 1024 * 1024 }); + const files = [], + contents = new Map(); + let offset = 0, + ended = false; + while (offset + 512 <= tar.length) { + const header = tar.subarray(offset, offset + 512); + if (header.every((byte) => byte === 0)) { + if (!tar.subarray(offset).every((byte) => byte === 0)) + fail("invalid archive terminator"); + ended = true; + break; + } + const checksumText = tarText(header.subarray(148, 156)).trim(); + if (!/^[0-7]+$/u.test(checksumText)) fail("invalid archive checksum"); + const checksum = header.reduce( + (total, byte, i) => total + (i >= 148 && i < 156 ? 32 : byte), + 0, + ); + if (checksum !== Number.parseInt(checksumText, 8)) + fail("invalid archive checksum"); + const prefix = tarText(header.subarray(345, 500)); + const path = + (prefix ? prefix + "/" : "") + tarText(header.subarray(0, 100)); + const type = header[156], + sizeText = tarText(header.subarray(124, 136)).trim(); + if ( + (type !== 0 && type !== 48) || + !/^[0-7]+$/u.test(sizeText) || + !path.startsWith("package/") || + path.includes("\\") || + /[\u0000-\u001f\u007f]/u.test(path) || + path.split("/").some((p) => p === "" || p === "." || p === "..") + ) + fail("archive must contain only safe regular files"); + const size = Number.parseInt(sizeText, 8), + name = path.slice(8); + integer(size, 4 * 1024 * 1024, 0); + const start = offset + 512; + if (start + size > tar.length || contents.has(name) || files.length >= 1000) + fail("archive bounds or identities are invalid"); + if ( + !["package.json", "README.md", "LICENSE"].includes(name) && + (!/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( + name, + ) || + /\.(?:test|spec)\./u.test(name)) + ) + fail("archive contains an unreviewed file"); + files.push({ path: name, size }); + contents.set(name, tar.subarray(start, start + size)); + offset = start + Math.ceil(size / 512) * 512; + } + if (!ended) fail("archive is missing its terminator"); + for (const name of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.js", + "dist/index.d.ts", + ]) + if (!contents.has(name)) fail("archive is missing a required public file"); + const metadata = JSON.parse(contents.get("package.json").toString("utf8")); + if ( + ![ + "@pegma/storage-core", + "@pegma/storage-azure-tables", + "@pegma/storage-cloudflare-d1", + "@pegma/storage-dynamodb", + ].includes(metadata.name) || + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(metadata.version) || + metadata.license !== "MIT" || + metadata.type !== "module" || + metadata.engines?.node !== ">=22" || + metadata.publishConfig?.access !== "public" || + metadata.repository?.url !== + "git+https://github.com/pegma-dev/storage-core.git" || + metadata.repository?.directory !== + "packages/" + metadata.name.split("/")[1] || + metadata.exports === null || + typeof metadata.exports !== "object" || + Array.isArray(metadata.exports) + ) + fail("archive public metadata is invalid"); + for (const target of Object.values(metadata.exports ?? {}).flatMap( + function targets(value) { + return typeof value === "string" + ? [value] + : value && typeof value === "object" + ? Object.values(value).flatMap(targets) + : []; + }, + )) + if (!target.startsWith("./dist/") || !contents.has(target.slice(2))) + fail("archive exported entry is missing"); + if (Object.keys(metadata.exports ?? {}).length === 0) + fail("archive has no public exports"); + return { + package: metadata, + files: files.sort((a, b) => a.path.localeCompare(b.path)), + }; +} +export function isolatedVerificationEnvironment( + source, + directory, + publishing = false, +) { + const env = {}; + const provenance = new Set([ + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_SERVER_URL", + "GITHUB_REF", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "GITHUB_WORKFLOW_SHA", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "RUNNER_ENVIRONMENT", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + ]); + for (const [key, value] of Object.entries(source)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) || + (publishing && provenance.has(key)) + ) + env[key] = value; + } + return { + ...env, + CI: "true", + npm_config_userconfig: join(directory, "user.npmrc"), + npm_config_globalconfig: join(directory, "global.npmrc"), + npm_config_cache: join(directory, "cache"), + npm_config_registry: REGISTRY, + npm_config_ignore_scripts: "true", + npm_config_audit: "false", + npm_config_fund: "false", + }; +} +export function assertTrustedPublishingEnvironment(env, identity) { + let url; + try { + url = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL); + } catch { + fail("approved OIDC authority is required"); + } + if ( + env.GITHUB_ACTIONS !== "true" || + env.GITHUB_EVENT_NAME !== "release" || + env.GITHUB_REPOSITORY !== RELEASE_REPOSITORY || + env.GITHUB_SERVER_URL !== "https://github.com" || + env.GITHUB_REPOSITORY_ID !== "1312519623" || + env.GITHUB_REPOSITORY_OWNER_ID !== "309286193" || + env.GITHUB_SHA !== identity.gitCommit || + env.GITHUB_REF !== "refs/tags/" + identity.releaseTag || + env.GITHUB_WORKFLOW_SHA !== identity.gitCommit || + env.GITHUB_WORKFLOW_REF !== + RELEASE_REPOSITORY + + "/" + + workflowPath + + "@refs/tags/" + + identity.releaseTag || + env.RUNNER_ENVIRONMENT !== "github-hosted" || + url.protocol !== "https:" || + url.username || + url.password || + !/^(?:[A-Za-z0-9-]+\.)*actions\.githubusercontent\.com$/u.test( + url.hostname, + ) || + typeof env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== "string" || + !env.ACTIONS_ID_TOKEN_REQUEST_TOKEN || + Object.entries(env).some( + ([key, value]) => + value && + /^(?:NODE_AUTH_TOKEN|NPM_TOKEN|NPM_AUTH_TOKEN|NPM_AUTH|YARN_NPM_AUTH_TOKEN|npm_config_.*)$/iu.test( + key, + ), + ) + ) + fail("approved token-free github-hosted OIDC authority is required"); +} +async function nativeRun(command, args, { cwd, env }) { + const result = spawnSync(command, args, { + cwd, + env, + shell: false, + encoding: "utf8", + maxBuffer: 32 * 1024 * 1024, + timeout: 10 * 60_000, + }); + if (result.error) + fail("isolated release verification command failed to start"); + return result; +} +async function temporary(action) { + const parent = await realpath(tmpdir()), + directory = await mkdtemp(join(parent, "storage-release-proof-")); + await chmod(directory, 0o700); + try { + return await action(directory); + } finally { + const actual = await realpath(directory); + if ( + actual !== directory || + dirname(actual) !== parent || + !basename(actual).startsWith("storage-release-proof-") + ) + fail("temporary cleanup refused an unexpected directory"); + await rm(actual, { recursive: true, force: true }); + } +} +async function treeFiles(directory) { + const files = new Map(); + let directories = 0, + total = 0; + async function visit(current, prefix) { + if (++directories > 6000 || prefix.split("/").length > 32) + fail("reviewed npm tree exceeds its bound"); + for (const entry of await readdir(current, { withFileTypes: true })) { + const path = join(current, entry.name), + key = prefix + entry.name; + const details = await lstat(path); + if (details.isSymbolicLink()) fail("reviewed npm tree contains a link"); + if (details.isDirectory()) await visit(path, key + "/"); + else if (details.isFile()) { + total += details.size; + if ( + files.size >= 3000 || + details.size > 16 * 1024 * 1024 || + total > 40 * 1024 * 1024 + ) + fail("reviewed npm tree exceeds its bound"); + files.set(key, await readFile(path)); + } else fail("reviewed npm tree contains an unsupported file"); + } + } + await visit(directory, ""); + return files; +} +async function npmContext(directory, options, seams) { + let cli = options.npmCli ?? process.env.RELEASE_NPM_CLI; + if ( + cli !== undefined && + (typeof cli !== "string" || + !isAbsolute(cli) || + basename(cli) !== "npm-cli.js" || + (await realpath(cli)) !== resolve(cli) || + !(await lstat(cli)).isFile() || + (await lstat(cli)).isSymbolicLink()) + ) + fail("an absolute reviewed npm CLI is required"); + const toolResponse = await request(npmArchiveUrl, seams.fetch); + if (toolResponse.status !== 200) + fail("the reviewed npm tool archive is unavailable"); + const toolBytes = await responseBytes(toolResponse, 16 * 1024 * 1024); + if (!equal(hash(toolBytes), npmArchiveSha256)) + fail("the reviewed npm tool archive differs"); + // Authenticate the exact official archive before extraction or execution. + // The default runs this owned tool, never a host-bundled npm tree whose + // legitimate extra .bin links are not part of the published archive. + gunzipSync(toolBytes, { maxOutputLength: 40 * 1024 * 1024 }); + const archive = join(directory, "npm-tool.tgz"), + expected = join(directory, "npm-tool"); + await writeFile(archive, toolBytes, { flag: "wx" }); + await mkdir(expected); + const run = seams.run ?? nativeRun; + const extracted = await run("tar", ["-xzf", archive, "-C", expected], { + cwd: directory, + env: isolatedVerificationEnvironment(process.env, directory), + }); + if (extracted?.status !== 0) fail("reviewed npm archive extraction failed"); + const expectedTree = await treeFiles(join(expected, "package")); + if ( + !expectedTree.has("bin/npm-cli.js") || + JSON.parse(expectedTree.get("package.json").toString("utf8")).version !== + RELEASE_NPM_VERSION + ) + fail("npm tool files differ from the pinned official release"); + if (cli === undefined) { + cli = join(expected, "package", "bin", "npm-cli.js"); + } else { + // An explicitly reviewed CLI remains an exact-tree contract. Do not + // permit links, extra installed files, or another npm implementation. + const actualTree = await treeFiles(dirname(dirname(cli))); + if ( + expectedTree.size !== actualTree.size || + [...expectedTree].some( + ([name, bytes]) => !actualTree.get(name)?.equals(bytes), + ) + ) + fail("npm tool files differ from the pinned official release"); + } + await writeFile(join(directory, "user.npmrc"), "", { + flag: "wx", + mode: 0o600, + }); + await writeFile(join(directory, "global.npmrc"), "", { + flag: "wx", + mode: 0o600, + }); + const env = isolatedVerificationEnvironment( + seams.env ?? process.env, + directory, + ); + async function invoke(args) { + const result = await run(process.execPath, [cli, ...args], { + cwd: directory, + env, + }); + if (options.output && result && typeof result.stdout === "string") { + const label = + args[0] === "audit" + ? "npm-audit-signatures" + : args[0] === "install" + ? "npm-install" + : "npm-version"; + await writeFile( + join( + resolve(options.output), + (options.proofPrefix ?? "") + label + ".stdout", + ), + result.stdout, + { flag: "wx" }, + ); + await writeFile( + join( + resolve(options.output), + (options.proofPrefix ?? "") + label + ".stderr", + ), + result.stderr ?? "", + { flag: "wx" }, + ); + } + if (result?.status !== 0 || typeof result.stdout !== "string") + fail("reviewed npm command failed"); + return result.stdout; + } + if ((await invoke(["--version"])).trim() !== RELEASE_NPM_VERSION) + fail("reviewed npm version differs"); + return { invoke, run, env, cli }; +} +function derValue(bytes, start) { + const tag = bytes[start], + initial = bytes[start + 1]; + if (initial === undefined) fail("invalid provenance certificate"); + let offset = start + 2, + length = initial; + if (initial > 127) { + const count = initial & 127; + if (count < 1 || count > 4 || offset + count > bytes.length) + fail("invalid provenance certificate"); + length = 0; + for (let index = 0; index < count; index += 1) + length = length * 256 + bytes[offset++]; + } + if (offset + length > bytes.length) fail("invalid provenance certificate"); + return { + tag, + value: bytes.subarray(offset, offset + length), + end: offset + length, + }; +} +function certificateIssuer(certificate) { + const outer = derValue(certificate.raw, 0), + tbs = derValue(outer.value, 0); + if (outer.tag !== 0x30 || tbs.tag !== 0x30) + fail("invalid provenance certificate"); + let extensions; + for (let offset = 0; offset < tbs.value.length;) { + const field = derValue(tbs.value, offset); + if (field.tag === 0xa3) extensions = derValue(field.value, 0); + offset = field.end; + } + if (extensions?.tag !== 0x30) fail("invalid provenance certificate"); + let issuer; + for (let offset = 0; offset < extensions.value.length;) { + const extension = derValue(extensions.value, offset); + const oid = derValue(extension.value, 0); + let value = derValue(extension.value, oid.end); + if (value.tag === 0x01) value = derValue(extension.value, value.end); + if (extension.tag !== 0x30 || oid.tag !== 0x06 || value.tag !== 0x04) + fail("invalid provenance certificate"); + if (oid.value.toString("hex") === "2b0601040183bf300101") { + if (issuer !== undefined) fail("invalid provenance certificate"); + issuer = value.value.toString("utf8"); + } + offset = extension.end; + } + return issuer; +} +function certificateIdentity(bundle, tag) { + const material = bundle?.verificationMaterial; + const encoded = + material?.certificate?.rawBytes ?? + material?.x509CertificateChain?.certificates?.[0]?.rawBytes; + if (typeof encoded !== "string" || encoded.length > 64 * 1024) + fail("invalid provenance certificate"); + const certificate = new X509Certificate(Buffer.from(encoded, "base64")); + if ( + certificate.subjectAltName !== + "URI:https://github.com/" + + RELEASE_REPOSITORY + + "/" + + workflowPath + + "@refs/tags/" + + tag || + certificateIssuer(certificate) !== + "https://token.actions.githubusercontent.com" + ) + fail("authenticated certificate identity differs"); + return { validFrom: certificate.validFrom, validTo: certificate.validTo }; +} +/** Only call with npm's genuine cryptographically verified audit output. */ +export function verifyProvenanceAudit(audit, records, identity, policy) { + if ( + !Array.isArray(audit?.invalid) || + audit.invalid.length || + !Array.isArray(audit.missing) || + audit.missing.length || + !Array.isArray(audit.verified) + ) + fail("npm signatures or Sigstore verification failed"); + const facts = []; + for (const record of records) { + const entries = audit.verified.filter( + (e) => + e.name === record.name && + e.version === record.version && + e.location === "node_modules/" + record.name && + e.registry === REGISTRY, + ); + if (entries.length !== 1 || !Array.isArray(entries[0].attestationBundles)) + fail("verified registry root is missing"); + const bundles = entries[0].attestationBundles.filter( + (e) => e.predicateType === provenanceType, + ); + if (bundles.length !== 1) + fail("verified SLSA bundle is missing or ambiguous"); + const origin = record.origin; + if (!origin || !["registryReuse", "source"].includes(origin.kind)) + fail("provenance origin is invalid"); + const tag = + origin.kind === "registryReuse" ? origin.sourceTag : identity.releaseTag; + const commit = + origin.kind === "registryReuse" + ? origin.sourceCommit + : identity.gitCommit; + const certificate = certificateIdentity(bundles[0].bundle, tag); + const envelope = bundles[0].bundle.dsseEnvelope; + if ( + envelope?.payloadType !== "application/vnd.in-toto+json" || + typeof envelope.payload !== "string" || + envelope.payload.length > 1024 * 1024 + ) + fail("verified SLSA statement is invalid"); + const statement = JSON.parse( + Buffer.from(envelope.payload, "base64").toString("utf8"), + ); + const definition = statement.predicate?.buildDefinition, + workflow = definition?.externalParameters?.workflow; + const deps = definition?.resolvedDependencies; + const invocation = statement.predicate?.runDetails?.metadata?.invocationId; + const match = + typeof invocation === "string" && + /^https:\/\/github\.com\/pegma-dev\/storage-core\/actions\/runs\/([1-9][0-9]*)\/attempts\/([1-9][0-9]*)$/u.exec( + invocation, + ); + if ( + statement._type !== "https://in-toto.io/Statement/v1" || + statement.predicateType !== provenanceType || + !Array.isArray(statement.subject) || + statement.subject.length !== 1 || + statement.subject[0].name !== + "pkg:npm/" + + record.name.split("/").map(encodeURIComponent).join("/") + + "@" + + record.version || + !equal( + statement.subject[0].digest?.sha512, + Buffer.from(record.integrity.slice(7), "base64").toString("hex"), + ) || + definition?.buildType !== + "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1" || + workflow?.repository !== "https://github.com/" + RELEASE_REPOSITORY || + workflow.path !== workflowPath || + workflow.ref !== "refs/tags/" + tag || + definition.internalParameters?.github?.event_name !== "release" || + definition.internalParameters?.github?.repository_id !== + policy.repositoryId || + definition.internalParameters?.github?.repository_owner_id !== + policy.ownerId || + !Array.isArray(deps) || + deps.length !== 1 || + deps[0].uri !== + "git+https://github.com/" + RELEASE_REPOSITORY + "@refs/tags/" + tag || + !equal(deps[0].digest?.gitCommit, commit) || + statement.predicate?.runDetails?.builder?.id !== policy.builder || + !match + ) + fail("authenticated SLSA source identity differs"); + const runId = Number(match[1]), + attempt = Number(match[2]); + integer(runId); + integer(attempt); + if (origin.kind === "registryReuse") { + if ( + runId !== origin.originalRunId || + attempt !== origin.originalRunAttempt + ) + fail("authenticated original registry invocation differs"); + } else if (runId !== identity.runId || attempt > identity.runAttempt) { + fail("authenticated publishing invocation differs"); + } + facts.push({ + name: record.name, + version: record.version, + sourceCommit: commit, + sourceTag: tag, + runId, + attempt, + invocation, + certificate, + }); + } + return facts; +} +async function githubJson(path, seams, output, filename) { + const response = await request( + "https://api.github.com/repos/" + RELEASE_REPOSITORY + "/" + path, + seams.fetch, + ); + if (response.status !== 200) + fail("publishing workflow identity is unavailable"); + const bytes = await responseBytes(response, 4 * 1024 * 1024); + if (output) await writeFile(join(output, filename), bytes, { flag: "wx" }); + return JSON.parse(bytes.toString("utf8")); +} +// These reviewed historical publishers predate the minimal schema 2 job. +// Future reuse entries still need genuine provenance and an actual modern +// publisher; adding another legacy workflow requires a reviewed binding here. +const historicalPublishers = [ + { + sourceCommit: "647702464ec60ee688c8d16aea5922b0b1b600fc", + sourceTag: "v0.4.0", + runId: 30334062325, + attempt: 1, + jobId: 90195221537, + }, + { + sourceCommit: "68798f74d2f1a545a35a4e3fc3c2225543c9dcf7", + sourceTag: "v0.4.1", + runId: 30504107513, + attempt: 1, + jobId: 90750106220, + }, +]; +/** Facts must already come from npm's genuine verified SLSA audit. */ +export async function verifyPublishingJobs(facts, seams = {}, output) { + if (!Array.isArray(facts) || facts.length > 4) + fail("authenticated package set is invalid"); + const groups = new Map(), + names = new Set(); + for (const fact of facts) { + integer(fact.runId); + integer(fact.attempt); + if ( + !/^@pegma\/storage-(?:core|azure-tables|cloudflare-d1|dynamodb)$/u.test( + fact.name, + ) || + names.has(fact.name) || + !/^[a-f0-9]{40}$/u.test(fact.sourceCommit) || + !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(fact.sourceTag) + ) + fail("authenticated package identity is invalid"); + names.add(fact.name); + const key = JSON.stringify([ + fact.sourceCommit, + fact.sourceTag, + fact.runId, + fact.attempt, + ]); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(fact); + } + const runs = new Map(); + const jobs = []; + for (const group of groups.values()) { + const { sourceCommit, sourceTag, runId, attempt } = group[0]; + if (!runs.has(runId)) + runs.set( + runId, + await githubJson( + "actions/runs/" + runId, + seams, + output, + "github-original-run-" + runId + ".json", + ), + ); + const run = runs.get(runId); + if ( + run.id !== runId || + run.head_sha !== sourceCommit || + run.head_branch !== sourceTag || + run.event !== "release" || + run.path !== workflowPath || + !Number.isSafeInteger(run.run_attempt) || + run.run_attempt < attempt || + String(run.repository?.id) !== "1312519623" || + String(run.repository?.owner?.id) !== "309286193" + ) + fail("original publishing run does not match the approved source"); + const page = await githubJson( + "actions/runs/" + runId + "/attempts/" + attempt + "/jobs?per_page=100", + seams, + output, + "github-original-run-" + runId + "-attempt-" + attempt + "-jobs.json", + ); + if ( + !Array.isArray(page.jobs) || + !Number.isSafeInteger(page.total_count) || + page.total_count !== page.jobs.length || + page.total_count > 100 + ) + fail("publisher job set is unavailable"); + const legacy = historicalPublishers.find((entry) => entry.runId === runId); + if ( + legacy && + (legacy.sourceCommit !== sourceCommit || + legacy.sourceTag !== sourceTag || + legacy.attempt !== attempt) + ) + fail("historical publisher binding differs"); + const stepName = legacy + ? "Publish verified prepared tarballs" + : "Verify and publish the prepared release"; + const matches = page.jobs.filter((job) => job.name === "publish"); + if ( + matches.length !== 1 || + matches[0].status !== "completed" || + !["success", "failure"].includes(matches[0].conclusion) || + matches[0].run_id !== runId || + matches[0].run_attempt !== attempt || + matches[0].head_sha !== sourceCommit || + matches[0].head_branch !== sourceTag || + (legacy && matches[0].id !== legacy.jobId) || + !Array.isArray(matches[0].steps) || + matches[0].steps.length > 1000 + ) + fail("original publisher job is unavailable or ambiguous"); + const job = matches[0]; + integer(job.id); + const steps = job.steps.filter((step) => + [ + "Publish verified prepared tarballs", + "Verify and publish the prepared release", + ].includes(step.name), + ); + if ( + steps.length !== 1 || + steps[0].name !== stepName || + steps[0].status !== "completed" || + !["success", "failure"].includes(steps[0].conclusion) + ) + fail("original publishing step is unavailable or ambiguous"); + const step = steps[0], + start = Date.parse(job.started_at), + end = Date.parse(job.completed_at), + stepStart = Date.parse(step.started_at), + stepEnd = Date.parse(step.completed_at); + if ( + ![start, end, stepStart, stepEnd].every(Number.isFinite) || + start > stepStart || + stepStart > stepEnd || + stepEnd > end + ) + fail("original publisher time bounds are invalid"); + for (const fact of group) { + const validFrom = Date.parse(fact.certificate?.validFrom), + validTo = Date.parse(fact.certificate?.validTo); + if ( + !Number.isFinite(validFrom) || + !Number.isFinite(validTo) || + validFrom > validTo || + validFrom > stepEnd || + validTo < stepStart + ) + fail("authenticated certificate does not overlap the actual publisher"); + } + jobs.push({ + id: job.id, + runId, + attempt, + sourceCommit, + sourceTag, + packages: group.map((fact) => fact.name), + stepName, + conclusion: job.conclusion, + startedAt: job.started_at, + completedAt: job.completed_at, + stepStartedAt: step.started_at, + stepCompletedAt: step.completed_at, + }); + } + return jobs; +} +async function freshProof(directory) { + if (typeof directory !== "string" || directory.length === 0) + fail("a fresh proof directory is required"); + const result = resolve(directory); + await mkdir(result, { recursive: false }); + return result; +} +async function verifyRegistryRecords(records, identity, options, seams = {}) { + const output = await freshProof(options.output); + return temporary(async (directory) => { + const context = await npmContext(directory, options, seams); + const packageJson = { + name: "storage-registry-proof", + private: true, + type: "module", + dependencies: Object.fromEntries(records.map((r) => [r.name, r.version])), + }; + await writeFile( + join(directory, "package.json"), + JSON.stringify(packageJson) + "\n", + { flag: "wx" }, + ); + await context.invoke([ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry", + REGISTRY, + ]); + const lockBytes = await readFile(join(directory, "package-lock.json")); + await writeFile(join(output, "package-lock.json"), lockBytes, { + flag: "wx", + }); + const lock = JSON.parse(lockBytes); + for (const record of records) { + const installed = lock.packages?.["node_modules/" + record.name]; + if ( + installed?.version !== record.version || + installed.link === true || + installed.resolved !== canonicalTarball(record) || + !equal(installed.integrity, record.integrity) + ) + fail("registry consumer dependency identity differs"); + } + const auditText = await context.invoke([ + "audit", + "signatures", + "--json", + "--include-attestations", + "--registry", + REGISTRY, + ]); + await writeFile(join(output, "npm-audit-signatures.json"), auditText, { + flag: "wx", + }); + const audit = JSON.parse(auditText); + const { policy, sha256: policySha256 } = await loadReusePolicy(); + const facts = verifyProvenanceAudit(audit, records, identity, policy); + const jobs = await verifyPublishingJobs(facts, seams, output); + await writeFile( + join(output, "publishing-jobs.json"), + JSON.stringify(jobs, null, 2) + "\n", + { flag: "wx" }, + ); + const result = { + status: "REGISTRY_BYTES_CRYPTO_SOURCE_PASS", + repository: RELEASE_REPOSITORY, + identity, + policySha256, + npmVersion: RELEASE_NPM_VERSION, + npmArchiveSha256, + lockSha256: hash(lockBytes), + auditSha256: hash(Buffer.from(auditText)), + packages: facts, + publishingJobs: jobs, + }; + await writeFile( + join(output, "verification.json"), + JSON.stringify(result, null, 2) + "\n", + { flag: "wx" }, + ); + return result; + }); +} +export async function verifyReusedPackages( + records, + identity, + options, + seams = {}, +) { + return verifyRegistryRecords( + records.filter((r) => r.origin.kind === "registryReuse"), + identity, + options, + seams, + ); +} +function publicationIdentity(options, manifest) { + const runId = Number(options.runId ?? process.env.GITHUB_RUN_ID); + const runAttempt = Number( + options.runAttempt ?? process.env.GITHUB_RUN_ATTEMPT, + ); + integer(runId); + integer(runAttempt); + if (manifest.releaseTag === null) + fail("registry release qualification requires the exact stable tag"); + return { + gitCommit: manifest.gitCommit, + releaseTag: manifest.releaseTag, + runId, + runAttempt, + }; +} +export async function preflightRegistry(verified, options, seams = {}) { + if ( + typeof options.manifest !== "string" || + !/^[a-f0-9]{64}$/u.test(options.expectedManifestSha256 ?? "") + ) + fail("preflight requires the original independently sealed manifest"); + const { verifyPreparedManifest } = await import("./release-packages.mjs"); + const original = await verifyPreparedManifest(options.manifest, options); + if (JSON.stringify(original) !== JSON.stringify(verified)) + fail("preflight manifest differs from original bytes"); + const { policy } = await loadReusePolicy(); + const existing = [], + decisions = []; + for (const record of verified.packages) { + const response = await request( + REGISTRY + encodeURIComponent(record.name) + "/" + record.version, + seams.fetch, + ); + if (response.status === 404) { + await response.body?.cancel(); + if (record.origin.kind !== "source") + fail("required original registry package is missing"); + decisions.push({ + name: record.name, + version: record.version, + action: "publish", + }); + continue; + } + if (response.status !== 200) { + await response.body?.cancel(); + fail("registry package availability is unknown"); + } + await response.body?.cancel(); + await downloadRegistryArtifact( + { ...record, tarballUrl: canonicalTarball(record) }, + seams, + ); + if (record.origin.kind === "registryReuse") { + const expected = policy.packages.find( + (p) => p.name === record.name && p.version === record.version, + ); + if (!expected || !equal(expected.integrity, record.integrity)) + fail("reuse policy differs"); + } + existing.push(record); + decisions.push({ + name: record.name, + version: record.version, + action: "skip", + }); + } + // Finish cryptographic verification of the entire existing set before a + // caller receives even one publication decision. + const identity = publicationIdentity(options, verified); + const proof = await verifyRegistryRecords(existing, identity, options, seams); + await verifyPreparedManifest(options.manifest, options); + const result = { + schemaVersion: 1, + repository: RELEASE_REPOSITORY, + gitCommit: verified.gitCommit, + releaseTag: verified.releaseTag, + manifestSha256: options.expectedManifestSha256, + runId: identity.runId, + runAttempt: identity.runAttempt, + decisions, + registryProof: proof, + }; + await writeFile( + join(resolve(options.output), "preflight.json"), + JSON.stringify(result, null, 2) + "\n", + { flag: "wx" }, + ); + return result; +} +const publicConsumer = String.raw`import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { createMemoryStore, defineCollection, StorageError, ConcurrencyError } from "@pegma/storage-core"; +import { conformanceCases } from "@pegma/storage-core/conformance"; +import { createDynamoDbStore } from "@pegma/storage-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; +assert.equal(import.meta.resolve("@pegma/storage-core"), + import.meta.resolve("@pegma/storage-core", import.meta.resolve("@pegma/storage-dynamodb"))); +for (const name of ["@pegma/storage-core","@pegma/storage-azure-tables","@pegma/storage-cloudflare-d1","@pegma/storage-dynamodb"]) await import(name); +const client = new DynamoDBClient({ region:"us-east-1", endpoint:"http://127.0.0.1:10103", + credentials:{accessKeyId:"local",secretAccessKey:"local"} }); +let ordinal=0; +const fresh = () => { + const tableName="releasetest"+process.pid+"t"+(++ordinal); + return () => createDynamoDbStore({client,tableName}); +}; +try { + assert.ok(Array.isArray(conformanceCases) && conformanceCases.length > 0); + for(const test of conformanceCases) await test.run(fresh()); + const definition=defineCollection({name:"release_identity",key:v=>({partition:v.partition,id:v.id}), + codec:{encode:v=>({...v}),decode:v=>({...v})}}); + const collection=fresh()().collection(definition); + await assert.rejects(collection.transact("one",[{action:"insert",value:{partition:"two",id:"a",label:"fictional"}}]), e=>e instanceof StorageError); + const value={partition:"one",id:"a",label:"fictional"}; + await collection.put(value); + await assert.rejects(collection.update({partition:"one",id:"a"},async()=>{await collection.put(value);return {action:"write",value};},{maxAttempts:1}),e=>e instanceof ConcurrencyError); + const memory=createMemoryStore().collection(definition); + await memory.put(value); assert.deepEqual(await memory.get({partition:"one",id:"a"}),value); + process.stdout.write(JSON.stringify({status:"PUBLIC_REGISTRY_CORE040_DYNAMO_CONFORMANCE_PASS", + conformanceCases:conformanceCases.length,storageErrorIdentity:true,concurrencyErrorIdentity:true,backend:"DynamoDB Local"})+"\n"); +} finally { client.destroy(); } +`; +async function admitConsumerAwsSdk(options, seams) { + const response = await request( + REGISTRY + + encodeURIComponent(consumerAwsSdk.name) + + "/" + + consumerAwsSdk.version, + seams.fetch, + ); + if (response.status !== 200) { + await response.body?.cancel(); + fail("reviewed consumer AWS SDK metadata is unavailable"); + } + const bytes = await responseBytes(response, 2 * 1024 * 1024); + const metadata = JSON.parse(bytes.toString("utf8")); + if ( + metadata.name !== consumerAwsSdk.name || + metadata.version !== consumerAwsSdk.version || + metadata.dist?.tarball !== consumerAwsSdk.tarballUrl || + !equal(metadata.dist?.integrity, consumerAwsSdk.integrity) + ) + fail("reviewed consumer AWS SDK metadata differs"); + const archiveResponse = await request(consumerAwsSdk.tarballUrl, seams.fetch); + if (archiveResponse.status !== 200) { + await archiveResponse.body?.cancel(); + fail("reviewed consumer AWS SDK archive is unavailable"); + } + const archive = await responseBytes(archiveResponse, maximumTarBytes); + if ( + !equal( + "sha512-" + hash(archive, "sha512", "base64"), + consumerAwsSdk.integrity, + ) + ) + fail("reviewed consumer AWS SDK archive differs"); + if (options.output) { + const output = resolve(options.output); + await writeFile(join(output, "consumer-aws-sdk-metadata.json"), bytes, { + flag: "wx", + }); + await writeFile(join(output, "consumer-aws-sdk.tgz"), archive, { + flag: "wx", + }); + await writeFile( + join(output, "consumer-aws-sdk-admission.json"), + JSON.stringify( + { + ...consumerAwsSdk, + archiveSha256: hash(archive), + archiveBytes: archive.length, + metadataSha256: hash(bytes), + scope: + "Pinned direct consumer root only; no transitive or AWS provenance qualification", + }, + null, + 2, + ) + "\n", + { flag: "wx" }, + ); + } +} +export async function runPublicConsumer(manifest, options = {}, seams = {}) { + return temporary(async (directory) => { + const context = await npmContext( + directory, + { ...options, proofPrefix: "consumer-" }, + seams, + ); + const packed = options.manifest !== undefined; + const dependencies = Object.fromEntries( + manifest.packages.map((r) => [ + r.name, + packed && r.origin.kind === "source" + ? "file:" + resolve(dirname(options.manifest), r.tarball) + : r.version, + ]), + ); + const dynamo = manifest.packages.find( + (r) => r.name === "@pegma/storage-dynamodb", + ); + if ( + !dynamo || + dynamo.package.dependencies?.["@pegma/storage-core"] !== "0.4.0" + ) + fail("Dynamo consumer requires the genuine released Core0.4.0"); + if (dynamo.package.dependencies?.[consumerAwsSdk.name] !== "^3.1097.0") + fail( + "Dynamo consumer AWS SDK declaration differs from the reviewed range", + ); + dependencies[consumerAwsSdk.name] = consumerAwsSdk.version; + await admitConsumerAwsSdk(options, seams); + await writeFile( + join(directory, "package.json"), + JSON.stringify({ + name: "storage-public-consumer", + private: true, + type: "module", + dependencies, + }) + "\n", + { flag: "wx" }, + ); + await context.invoke([ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry", + REGISTRY, + ]); + const lock = JSON.parse( + await readFile(join(directory, "package-lock.json"), "utf8"), + ); + for (const record of manifest.packages) { + const installed = lock.packages?.["node_modules/" + record.name]; + if ( + installed?.version !== record.version || + installed.link || + !equal(installed.integrity, record.integrity) || + ((!packed || record.origin.kind !== "source") && + installed.resolved !== canonicalTarball(record)) + ) + fail("public consumer resolved an unexpected package"); + } + const sdkKey = "node_modules/" + consumerAwsSdk.name; + if (!Object.hasOwn(lock.packages ?? {}, sdkKey)) + fail("public consumer AWS SDK root is missing"); + for (const [key, installed] of Object.entries(lock.packages)) { + if (key !== sdkKey && !key.endsWith("/" + sdkKey)) continue; + if ( + !key.startsWith("node_modules/") || + key.includes("\\") || + key.split("/").some((part) => ["", ".", ".."].includes(part)) || + installed?.version !== consumerAwsSdk.version || + installed.link || + !equal(installed.integrity, consumerAwsSdk.integrity) || + installed.resolved !== consumerAwsSdk.tarballUrl + ) + fail("public consumer resolved an unexpected AWS SDK"); + const sdkDirectory = join(directory, key); + const details = await lstat(sdkDirectory); + const sdkManifest = join(sdkDirectory, "package.json"); + const metadata = await lstat(sdkManifest); + if ( + !details.isDirectory() || + details.isSymbolicLink() || + (await realpath(sdkDirectory)) !== resolve(sdkDirectory) || + !metadata.isFile() || + metadata.isSymbolicLink() || + metadata.size > 1024 * 1024 || + (await realpath(sdkManifest)) !== resolve(sdkManifest) + ) + fail("public consumer AWS SDK files have an unexpected origin"); + const actual = JSON.parse(await readFile(sdkManifest, "utf8")); + if ( + actual.name !== consumerAwsSdk.name || + actual.version !== consumerAwsSdk.version + ) + fail("public consumer AWS SDK file identity differs"); + } + await writeFile(join(directory, "consumer.mjs"), publicConsumer, { + flag: "wx", + }); + // Only the already reviewed local-backend harness is loaded from source. + // All component runtime imports resolve inside the isolated consumer. + const runner = + "import {setup,teardown} from " + + JSON.stringify(pathToFileURL(join(root, "test/dynamodb-local.ts")).href) + + ";\n" + + "try { await setup(); await import(" + + JSON.stringify(pathToFileURL(join(directory, "consumer.mjs")).href) + + "); } finally { await teardown(); }\n"; + await writeFile(join(directory, "run.mjs"), runner, { flag: "wx" }); + const result = await context.run( + process.execPath, + [ + "--experimental-strip-types", + "--experimental-import-meta-resolve", + join(directory, "run.mjs"), + ], + { cwd: directory, env: context.env }, + ); + if (!result || typeof result.stdout !== "string") + fail("public consumer command returned no result"); + if (options.output) { + await writeFile( + join(resolve(options.output), "public-consumer.stdout"), + result.stdout, + { flag: "wx" }, + ); + await writeFile( + join(resolve(options.output), "public-consumer.stderr"), + result.stderr ?? "", + { flag: "wx" }, + ); + await copyFile( + join(directory, "package-lock.json"), + join(resolve(options.output), "public-consumer-lock.json"), + ); + } + if (result?.status !== 0) fail("public DynamoDB consumer did not pass"); + return JSON.parse(result.stdout.trim().split("\n").at(-1)); + }); +} +export async function verifyRegistryRelease(manifest, options, seams = {}) { + const plan = await preflightRegistry(manifest, options, seams); + if (plan.decisions.some((entry) => entry.action !== "skip")) + fail("complete release is not visible"); + const consumer = await runPublicConsumer( + manifest, + { ...options, manifest: undefined }, + seams, + ); + if ( + !equal( + hash( + await readFile( + join(resolve(options.output), "npm-audit-signatures.json"), + ), + ), + plan.registryProof.auditSha256, + ) || + !equal( + hash(await readFile(join(resolve(options.output), "package-lock.json"))), + plan.registryProof.lockSha256, + ) + ) + fail("retained cryptographic proof changed during public imports"); + const { verifyPreparedManifest } = await import("./release-packages.mjs"); + await verifyPreparedManifest(options.manifest, options); + const result = { + ...plan, + status: "STORAGE_REGISTRY_CRYPTO_SOURCE_PUBLIC_CONSUMER_PASS", + consumer, + }; + await writeFile( + join(resolve(options.output), "verification.json"), + JSON.stringify(result, null, 2) + "\n", + ); + return result; +} +function cliOptions(args) { + const result = {}, + seen = new Set(); + const fields = { + "--manifest": "manifest", + "--expected-release-commit": "expectedReleaseCommit", + "--expected-manifest-sha256": "expectedManifestSha256", + "--output": "output", + "--run-id": "runId", + "--run-attempt": "runAttempt", + "--npm-cli": "npmCli", + }; + for (let index = 0; index < args.length; index += 2) { + const key = fields[args[index]], + value = args[index + 1]; + if (!key || !value || value.startsWith("--") || seen.has(key)) + fail("invalid release verifier arguments"); + seen.add(key); + result[key] = value; + } + return result; +} +async function main() { + const [command, ...args] = process.argv.slice(2), + options = cliOptions(args); + if ( + !["preflight", "verify"].includes(command) || + !options.manifest || + !/^[0-9a-f]{40}$/u.test(options.expectedReleaseCommit ?? "") || + !/^[0-9a-f]{64}$/u.test(options.expectedManifestSha256 ?? "") + ) + fail( + "usage: release-registry-verify.mjs preflight|verify --manifest --expected-release-commit --expected-manifest-sha256 --output --run-id --run-attempt", + ); + const { verifyPreparedManifest } = await import("./release-packages.mjs"); + const manifest = await verifyPreparedManifest(options.manifest, options); + if (command === "preflight") await preflightRegistry(manifest, options); + else await verifyRegistryRelease(manifest, options); +} +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) + await main(); diff --git a/scripts/release-reuse-policy.json b/scripts/release-reuse-policy.json new file mode 100644 index 0000000..84fa450 --- /dev/null +++ b/scripts/release-reuse-policy.json @@ -0,0 +1,54 @@ +{ + "schemaVersion": 1, + "repository": "pegma-dev/storage-core", + "repositoryId": "1312519623", + "ownerId": "309286193", + "builder": "https://github.com/actions/runner/github-hosted", + "packages": [ + { + "name": "@pegma/storage-core", + "version": "0.4.0", + "directory": "storage-core", + "tarballUrl": "https://registry.npmjs.org/@pegma/storage-core/-/storage-core-0.4.0.tgz", + "size": 24625, + "sha256": "8fe21519d16f3c94f43c9477714ea08afa9b72fb4a2f0bf0b4c1b1905096a8cf", + "integrity": "sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==", + "shasum": "ba65320d15291c1093b320fbc9ae6a70c04913fb", + "sourceCommit": "647702464ec60ee688c8d16aea5922b0b1b600fc", + "sourceTag": "v0.4.0", + "workflowPath": ".github/workflows/publish.yml", + "originalRunId": 30334062325, + "originalRunAttempt": 1 + }, + { + "name": "@pegma/storage-azure-tables", + "version": "0.4.0", + "directory": "storage-azure-tables", + "tarballUrl": "https://registry.npmjs.org/@pegma/storage-azure-tables/-/storage-azure-tables-0.4.0.tgz", + "size": 10534, + "sha256": "bbe26f50cc60d2f45334bbd3d3455ffff7a541b84485123dfe8925e74be46a60", + "integrity": "sha512-cHVrLyQRf8qu2d83fgO7spPxKxAZlOOfvEi/t38S6l3SD2678khJvUMcvAHm/rAQ8BlReDWd6WSnIZuQiI3A1Q==", + "shasum": "2b7f788759274905e7d395305c2988973eaf3e81", + "sourceCommit": "647702464ec60ee688c8d16aea5922b0b1b600fc", + "sourceTag": "v0.4.0", + "workflowPath": ".github/workflows/publish.yml", + "originalRunId": 30334062325, + "originalRunAttempt": 1 + }, + { + "name": "@pegma/storage-cloudflare-d1", + "version": "0.4.1", + "directory": "storage-cloudflare-d1", + "tarballUrl": "https://registry.npmjs.org/@pegma/storage-cloudflare-d1/-/storage-cloudflare-d1-0.4.1.tgz", + "size": 11967, + "sha256": "5e354776b5260d7c0342389daaeb91856022d7375d599708219d8f43786c3301", + "integrity": "sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==", + "shasum": "888f77cf8bd2e3cdd96904da3c3fe77989202021", + "sourceCommit": "68798f74d2f1a545a35a4e3fc3c2225543c9dcf7", + "sourceTag": "v0.4.1", + "workflowPath": ".github/workflows/publish.yml", + "originalRunId": 30504107513, + "originalRunAttempt": 1 + } + ] +} diff --git a/test/dynamodb-local.ts b/test/dynamodb-local.ts index b8f957d..50ea184 100644 --- a/test/dynamodb-local.ts +++ b/test/dynamodb-local.ts @@ -45,6 +45,7 @@ const DOWNLOAD_TIMEOUT_MS = 120_000; const TARBALL_PATH_ENV = "PEGMA_DYNAMODB_LOCAL_TARBALL_PATH"; let child: ChildProcess | undefined; +let childClosed: Promise | undefined; let distribution: string | undefined; let privateArchiveDirectory: string | undefined; let verifiedTarball: string | undefined; @@ -219,16 +220,42 @@ export async function setup(): Promise { }, ); - child.once("error", (error) => { - throw error; + const ownedChild = child; + // Observe close now, including a child that exits before teardown starts. + // Store errors as outcomes so they cannot reject before teardown awaits them. + childClosed = new Promise((resolve) => { + ownedChild.once("close", () => resolve(undefined)); + ownedChild.once("error", (error) => resolve(error)); }); await waitForPort(DYNAMODB_PORT, 30_000); } export async function teardown(): Promise { - child?.kill(); - child = undefined; + if (child !== undefined) { + const ownedChild = child; + if (childClosed === undefined) { + throw new Error("DynamoDB Local child close observation is missing."); + } + let timeout: ReturnType | undefined; + try { + const expired = new Promise((_, reject) => { + timeout = setTimeout(() => { + reject(new Error("DynamoDB Local did not close within 10000ms.")); + }, 10_000); + }); + if (ownedChild.exitCode === null && ownedChild.signalCode === null) { + ownedChild.kill(); + } + const error = await Promise.race([childClosed, expired]); + if (error !== undefined) throw error; + } finally { + if (timeout !== undefined) clearTimeout(timeout); + } + // Only a confirmed close releases ownership and permits directory removal. + child = undefined; + childClosed = undefined; + } if (distribution !== undefined) { await rm(distribution, { recursive: true, force: true }); distribution = undefined; diff --git a/tests/fixtures/release-registry/README.md b/tests/fixtures/release-registry/README.md new file mode 100644 index 0000000..c1d904a --- /dev/null +++ b/tests/fixtures/release-registry/README.md @@ -0,0 +1,40 @@ +# Public registry parser fixtures + +These immutable public MIT package archives were downloaded from the official npm registry. They are parser and archive test inputs, not a claim that unit tests authenticate their signatures. + +| File | Source URL | SHA256 | +| ------------------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| storage-core-0.4.0.tgz | https://registry.npmjs.org/@pegma/storage-core/-/storage-core-0.4.0.tgz | 8fe21519d16f3c94f43c9477714ea08afa9b72fb4a2f0bf0b4c1b1905096a8cf | +| storage-azure-tables-0.4.0.tgz | https://registry.npmjs.org/@pegma/storage-azure-tables/-/storage-azure-tables-0.4.0.tgz | bbe26f50cc60d2f45334bbd3d3455ffff7a541b84485123dfe8925e74be46a60 | +| storage-cloudflare-d1-0.4.1.tgz | https://registry.npmjs.org/@pegma/storage-cloudflare-d1/-/storage-cloudflare-d1-0.4.1.tgz | 5e354776b5260d7c0342389daaeb91856022d7375d599708219d8f43786c3301 | + +Each archive includes its original package LICENSE. The three archives total 47126 bytes. + +`core040-slsa.json` retains only the genuine public SLSA attestation entry from https://registry.npmjs.org/-/npm/v1/attestations/@pegma%2fstorage-core@0.4.0 (observed 2026-11-09). The original complete response SHA256 was 14a3b4cf38d4df36f50566af0fa59665f69ec36e67e22b6a4f85feab273c5c3a. No authentication headers, tokens or local paths are included. Tests explicitly stub the already-verified npm audit envelope when exercising the pure claim validator. Actual ECDSA/Sigstore authentication must still run through the unprivileged release verifier using the pinned official npm tool. + +Additional genuine SLSA parser fixtures (only the unique SLSA entry is retained): + +| Fixture | Canonical official response | Original complete response SHA256 | +| ------------------ | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| azure040-slsa.json | https://registry.npmjs.org/-/npm/v1/attestations/@pegma%2fstorage-azure-tables@0.4.0 | b551b76f2a7b8c47d63aba1385816bf590c301df04745d71b59d49599d439c5e | +| d1041-slsa.json | https://registry.npmjs.org/-/npm/v1/attestations/@pegma%2fstorage-cloudflare-d1@0.4.1 | 3636da27527d535e6afdd31df0bd6718233d6faba7f507db4b9cd04ebdeeb4b1 | + +Signed base64 payload, certificate and transparency values are preserved unchanged. No auth headers, tokens or local paths are included. Controlled orchestration tests can present these genuine entries as scripted npm audit output to exercise downstream decisions, but that scripted command output is not an actual cryptographic verification or release qualification. The separate real Linux npm audit and public consumer gates remain mandatory. + +## Reviewed AWS consumer root archive + +`aws-client-dynamodb-3.1130.0.tgz` is the genuine 249176-byte public archive from +https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.1130.0.tgz. +Its SHA256 is `b0f2cf96a293592e70a4b0cee40d0ef387c10b0cdc541b0c3fd99a8d4b753335` +and SHA512 SRI is +`sha512-yPEc9TWLY1McM6xA9wlxA9rM0ZeS8RAeyi1t7rdHPNxq0TpyCDn6z651ccRJ1RrMU4k2aiVzNCaBYUZA4aaA/w==`. +The exact version and SRI match the preexisting reviewed `pnpm-lock.yaml`. +The vendor archive retains its own Apache-2.0 license; the three Pegma MIT +archives and their total above are unchanged. + +Tests supply these unchanged vendor bytes through the existing fetch seam to +exercise the real consumer admission and refusal paths. Scripted npm installs +write controlled lock and package metadata, and the consumer command remains an +explicit `UNQUALIFIED_STUBS` observation. These tests do not execute AWS code, +authenticate AWS provenance or qualify transitive dependencies. Genuine npm +verification and the real public consumer/backend release gates remain separate. diff --git a/tests/fixtures/release-registry/aws-client-dynamodb-3.1130.0.tgz b/tests/fixtures/release-registry/aws-client-dynamodb-3.1130.0.tgz new file mode 100644 index 0000000..7964c9a Binary files /dev/null and b/tests/fixtures/release-registry/aws-client-dynamodb-3.1130.0.tgz differ diff --git a/tests/fixtures/release-registry/azure040-slsa.json b/tests/fixtures/release-registry/azure040-slsa.json new file mode 100644 index 0000000..2d2a532 --- /dev/null +++ b/tests/fixtures/release-registry/azure040-slsa.json @@ -0,0 +1,75 @@ +{ + "predicateType": "https://slsa.dev/provenance/v1", + "bundle": { + "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json", + "verificationMaterial": { + "certificate": { + "rawBytes": "MIIHSDCCBs6gAwIBAgIUAhblG4j8gn+gbMsfsMSnqdJbh/cwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNzI4MDYxNDA3WhcNMjYwNzI4MDYyNDA3WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEnB0BzU3uXi2cQ2bbnculR0OQ1U35tYCu/x2Rj+VYlB6Asb31Daucn5q8JR547g3C98uUw/4Mb5iaudrxJhw2AaOCBe0wggXpMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQU/NSYkTyMjLGJYXUTi6rmt9/q/GMwHwYDVR0jBBgwFoAU39Ppz1YkEZb5qNjpKFWixi4YZD8wZgYDVR0RAQH/BFwwWoZYaHR0cHM6Ly9naXRodWIuY29tL3BlZ21hLWRldi9zdG9yYWdlLWNvcmUvLmdpdGh1Yi93b3JrZmxvd3MvcHVibGlzaC55bWxAcmVmcy90YWdzL3YwLjQuMDA5BgorBgEEAYO/MAEBBCtodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tMBUGCisGAQQBg78wAQIEB3JlbGVhc2UwNgYKKwYBBAGDvzABAwQoNjQ3NzAyNDY0ZWM2MGVlNjg4YzhkMTZhZW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MB3JlbGVhc2UwXQYKKwYBBAGDvzABFQRPDE1odHRwczovL2dpdGh1Yi5jb20vcGVnbWEtZGV2L3N0b3JhZ2UtY29yZS9hY3Rpb25zL3J1bnMvMzAzMzQwNjIzMjUvYXR0ZW1wdHMvMTAWBgorBgEEAYO/MAEWBAgMBnB1YmxpYzAbBgorBgEEAYO/MAEXBA0MC25wbS1wdWJsaXNoMFgGCisGAQQBg78wARgESgxIcmVwbzpwZWdtYS1kZXZAMzA5Mjg2MTkzL3N0b3JhZ2UtY29yZUAxMzEyNTE5NjIzOmVudmlyb25tZW50Om5wbS1wdWJsaXNoMIGLBgorBgEEAdZ5AgQCBH0EewB5AHcA3T0wasbHETJjGR4cmWc3AqJKXrjePK3/h4pygC8p7o4AAAGfp1vsNwAABAMASDBGAiEAtPEJz8HljQnnmtT6c1oREY7VR+P4/8wYsXxCzSL83wECIQCbxBtroKxqqU8Msd2EyZh8ip8dz2kuCTSCfGuQeQ2HQTAKBggqhkjOPQQDAwNoADBlAjEAqfttctST1/d4ZTibi01OJi/Q6vJUVZaPjxgtNZ7PiiIn2U4T2FKVIdp6Oqj5yNxlAjA9WTyGkSMtF6bzCE/O7bEcdPvCMR9bZjZtwslL9uNPy6VbLBRVaTGnjnjvMUEsO+M=" + }, + "tlogEntries": [ + { + "logIndex": "2267563125", + "logId": { + "keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0=" + }, + "kindVersion": { + "kind": "dsse", + "version": "0.0.1" + }, + "integratedTime": "1785219247", + "inclusionPromise": { + "signedEntryTimestamp": "MEQCIDXn8PX/WCn7/4aDCLb6OhGrP1Gl/RJta2fOOekrrvYkAiAfWiPbDv4VU734BZLrcRC+2KmBMVtTbVspN3chZt0F7g==" + }, + "inclusionProof": { + "logIndex": "2145658863", + "rootHash": "E+9uAYsd36yNHvXIVjGH9QqUtGAqHdnfyFOa4qN7R6A=", + "treeSize": "2145658867", + "hashes": [ + "s03Wfdg//8OU32g4HZdmM0Mjjx/XeU4BpjzbAZFXevU=", + "HB4qkY+slnO8HSZk641AOWv1kRO4dXBjAJNFLmoB7QY=", + "0NhHU4hzVRTzvkLmRC+cF8eYXBYyRruM0XI1l9uSlzA=", + "6iNfdLv9+mivtfSoHJKk1lam3n5ySQpbLAwAfxL+JKs=", + "RGIviGksJTgqTQ3fXF/FUJa6GAcg/djM9JSG0o06p/c=", + "r1bAFiNMHcyztwdK7gtac0xezgDz0/NaxGSb9UGcUKw=", + "8gyGiL1835gwhlNx0XpUQ2+WavaHMDjsherlVLz2vgY=", + "suFm4I80rqlyKYWjIP1L1tBx4zcI0Spj5AvXzRFrNzI=", + "0oqGzfP9ze4HK/QuLzFTLey9MoAog8CRYNOj+UTNY7Y=", + "ixFz0359CKC6nGqyTMC76jEQ0/LGHYzcQ3SUYKRKoLI=", + "biz0lWUe3TjyRilfa5KSEOiDMvkCDAl3th5zAbJfB8A=", + "Ezq+SbEBqnjsWYiUNeYt5wFUalgBBdYz9RA/GKmiwnY=", + "Rpj2SYk4WaoatiFq5HMBlrSWSz+h90cUzZSiwdpBBcE=", + "ldtLT0bFxBchqakY+wyxy7IMuD59j3iy/T7/zBdpwM4=", + "WV0LnLa1qGlpIEn8L3jrH7gRm9wOY74ZBm2KaiqZJnE=", + "Q4B7myXA0v1DKgYAju5cyI6EIzIAnDMLwgTnCTf6haA=", + "tOodM59bEXvJSJK6LgM8bje97S+dV95F8eemrdUKKoM=", + "sXJcOdBCSAbMlJ+t7sWGAY7emODlu6Tf9jo6KEGpTA8=", + "GxT6+CEXxY8Ak/besnRW/IK3DhneHQ5X5rIcw8L01DQ=", + "Rq/A2aTC9e54ldNjcpsJ26rX/h8JlN6ZHxgw7yEa6C0=", + "+/VZ56MsIPxMiyLAodzKXo5TEWdQp36z89qLhpzloAo=", + "daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=", + "DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU=" + ], + "checkpoint": { + "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NpdG9yeV9vd25lcl9pZCI6IjMwOTI4NjE5MyJ9fSwicmVzb2x2ZWREZXBlbmRlbmNpZXMiOlt7InVyaSI6ImdpdCtodHRwczovL2dpdGh1Yi5jb20vcGVnbWEtZGV2L3N0b3JhZ2UtY29yZUByZWZzL3RhZ3MvdjAuNC4wIiwiZGlnZXN0Ijp7ImdpdENvbW1pdCI6IjY0NzcwMjQ2NGVjNjBlZTY4OGM4ZDE2YWVhNTkyMmIwYjFiNjAwZmMifX1dfSwicnVuRGV0YWlscyI6eyJidWlsZGVyIjp7ImlkIjoiaHR0cHM6Ly9naXRodWIuY29tL2FjdGlvbnMvcnVubmVyL2dpdGh1Yi1ob3N0ZWQifSwibWV0YWRhdGEiOnsiaW52b2NhdGlvbklkIjoiaHR0cHM6Ly9naXRodWIuY29tL3BlZ21hLWRldi9zdG9yYWdlLWNvcmUvYWN0aW9ucy9ydW5zLzMwMzM0MDYyMzI1L2F0dGVtcHRzLzEifX19fQ==", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "sig": "MEYCIQCYigajhvHyly6q1zDnfOC4uOIQobUIGaS5I3Xa8AJAagIhALlWuZLo8zAWD6LL8LZi0CIG7J7S9ZOIoYtklNMlAt/J", + "keyid": "" + } + ] + } + }, + "signedAccessSignatureUrl": "" +} diff --git a/tests/fixtures/release-registry/core040-slsa.json b/tests/fixtures/release-registry/core040-slsa.json new file mode 100644 index 0000000..e2f8be6 --- /dev/null +++ b/tests/fixtures/release-registry/core040-slsa.json @@ -0,0 +1,76 @@ +{ + "predicateType": "https://slsa.dev/provenance/v1", + "bundle": { + "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json", + "verificationMaterial": { + "certificate": { + "rawBytes": "MIIHRjCCBs2gAwIBAgIUUvYS5gVa4x9jNjrpMM31T0Hv1KMwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcN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KrlZOaLt6/pfVDQIhAIuigRRL6OsIzZFvppM+Ye6l2JpIgbVxJuXBe9ytZHVQMAoGCCqGSM49BAMDA2cAMGQCMEVBubQXTH/zdsX3oqaDhzgYwndOhcqmKsKQIYhlSbWbuogM+f9szQnkuqSkOv1e3AIwPBQ2F48c3EeX1wBylEJ9P+Wr6+IPSykCBSbomMp7GK8/G/wGe4E46p4fSuoYgeS3" + }, + "tlogEntries": [ + { + "logIndex": "2267560030", + "logId": { + "keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0=" + }, + "kindVersion": { + "kind": "dsse", + "version": "0.0.1" + }, + "integratedTime": "1785219233", + "inclusionPromise": { + "signedEntryTimestamp": "MEYCIQC9R41nXc0hYndcRIh5YJ0r5mHtR0hne+4PN4aP4mp05QIhAK4bwUNehH7cZHbavMsZiKm6G9trjJhAshs8/Iu+kBzj" + }, + "inclusionProof": { + "logIndex": "2145655768", + "rootHash": "dXODzCWzWo5cQAI9NEyR9uMkcUCsR0N+KPo7jSepYvc=", + "treeSize": "2145655860", + "hashes": [ + "nKLA6X3XQmaXdhnXo+dknWAGih6WGfrqduClC2VQSXs=", + "BGwndhmx239HYlpbL66740TkfbIsv+7XC0HvkXhvfg4=", + "IWnmVzxsorKUi6FPzHkoLn6h4E0QRzm/8aTbsJmRK/4=", + "O7ZwpkvJ9xybuGpelwJeUe5ej1IhQ+c6zuZUdlVI6mE=", + "80ddfZoywB1y8Hm9fxjETDDLB6IqL8H7+l92z0peB84=", + "piF+ooRIqrteAxcfnHMkzCMNHjNbkdiM9qc4V81ACzA=", + "PV6FdCJ1g/zI6xl4q7go0l/vMKujIt8FqarU3U9DumQ=", + "Kj7OYBc5O0Cw9yXR8O/APeDUG9m1Io/JThqihsCN02c=", + "6L+G9sI5yIBuuhD7daINeX/lUTm5XjMRoBTzg+ghb0U=", + "UWFkFa9oQNIxQIRIfobEkNTm2Zhl7l3W978FFPa3Dqw=", + "mGwke0AeTwO1zQfFtBJj6egj1VkxQN39nYNtYcqVf9o=", + "7InbmcYitx3MWDI73+dsezGDU0i5/dWyYSInIHtI9X4=", + "ceuN9RAh69p81QXY4jnotnam22huyHQIiAbIXWfB3D8=", + "Rpj2SYk4WaoatiFq5HMBlrSWSz+h90cUzZSiwdpBBcE=", + "ldtLT0bFxBchqakY+wyxy7IMuD59j3iy/T7/zBdpwM4=", + "WV0LnLa1qGlpIEn8L3jrH7gRm9wOY74ZBm2KaiqZJnE=", + "Q4B7myXA0v1DKgYAju5cyI6EIzIAnDMLwgTnCTf6haA=", + "tOodM59bEXvJSJK6LgM8bje97S+dV95F8eemrdUKKoM=", + "sXJcOdBCSAbMlJ+t7sWGAY7emODlu6Tf9jo6KEGpTA8=", + "GxT6+CEXxY8Ak/besnRW/IK3DhneHQ5X5rIcw8L01DQ=", + "Rq/A2aTC9e54ldNjcpsJ26rX/h8JlN6ZHxgw7yEa6C0=", + "+/VZ56MsIPxMiyLAodzKXo5TEWdQp36z89qLhpzloAo=", + "daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=", + "DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU=" + ], + "checkpoint": { + "envelope": "rekor.sigstore.dev - 1193050959916656506\n2145655860\ndXODzCWzWo5cQAI9NEyR9uMkcUCsR0N+KPo7jSepYvc=\n\n— rekor.sigstore.dev wNI9ajBFAiEA/a7rA43D30Fsgt9TQp9f6zLR9Ntn8yCaNq2grH380KMCIFf40CNwbCeR1tpEe//lXUhFavcOshhc8hzA6ieH/rG6\n" + } + }, + "canonicalizedBody": "eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiZHNzZSIsInNwZWMiOnsiZW52ZWxvcGVIYXNoIjp7ImFsZ29yaXRobSI6InNoYTI1NiIsInZhbHVlIjoiNzgwNzg0MzZhZTZmYjMwY2E5N2UzMDQ4NWMxYmJjMTU4NjU1ZmJhZjgxZmQ0NmM5MDI2Y2NkYmY2NTYzNmYzMy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3JlL2FjdGlvbnMvcnVucy8zMDMzNDA2MjMyNS9hdHRlbXB0cy8xIn19fX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "sig": "MEYCIQCIQBKLhZC/9WOZZhxHGxG/QNp7F676l3UYug32m7DlEQIhAN404Ww6NsVerkclgZ0cDdiC8I5Mnv+F04TZnAguO0BO", + "keyid": "" + } + ] + } + }, + "signedAccessSignatureUrl": "" +} diff --git a/tests/fixtures/release-registry/d1041-slsa.json b/tests/fixtures/release-registry/d1041-slsa.json new file mode 100644 index 0000000..81973a3 --- /dev/null +++ b/tests/fixtures/release-registry/d1041-slsa.json @@ -0,0 +1,69 @@ +{ + "predicateType": "https://slsa.dev/provenance/v1", + "bundle": { + "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json", + "verificationMaterial": { + "certificate": { + "rawBytes": "MIIHRzCCBs2gAwIBAgIUJpDlQy3+5j5R8vLUG8YVWX6IpJcwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNzMwMDA1NTQwWhcNMjYwNzMwMDEwNTQwWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAElapHQBMK9E6r8X1zPOueQSaS2Fft3XbI3hJ2+Re82EQu3eGW1gRIkMda0tI1lX1iew77o/I5LgoSusCQzKyazqOCBewwggXoMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUP6v8mXSwK1CChwrY5ccoOq+eUCIwHwYDVR0jBBgwFoAU39Ppz1YkEZb5qNjpKFWixi4YZD8wZgYDVR0RAQH/BFwwWoZYaHR0cHM6Ly9naXRodWIuY29tL3BlZ21hLWRldi9zdG9yYWdlLWNvcmUvLmdpdGh1Yi93b3JrZmxvd3MvcHVibGlzaC55bWxAcmVmcy90YWdzL3YwLjQuMTA5BgorBgEEAYO/MAEBB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bG93cy9wdWJsaXNoLnltbEByZWZzL3RhZ3MvdjAuNC4xMDgGCisGAQQBg78wARMEKgwoNjg3OThmNzRkMmYxYTU0NWEzNWE0ZTNmYzNjMjIyNTU0M2M5ZGNmNzAXBgorBgEEAYO/MAEUBAkMB3JlbGVhc2UwXQYKKwYBBAGDvzABFQRPDE1odHRwczovL2dpdGh1Yi5jb20vcGVnbWEtZGV2L3N0b3JhZ2UtY29yZS9hY3Rpb25zL3J1bnMvMzA1MDQxMDc1MTMvYXR0ZW1wdHMvMTAWBgorBgEEAYO/MAEWBAgMBnB1YmxpYzAbBgorBgEEAYO/MAEXBA0MC25wbS1wdWJsaXNoMFgGCisGAQQBg78wARgESgxIcmVwbzpwZWdtYS1kZXZAMzA5Mjg2MTkzL3N0b3JhZ2UtY29yZUAxMzEyNTE5NjIzOmVudmlyb25tZW50Om5wbS1wdWJsaXNoMIGKBgorBgEEAdZ5AgQCBHwEegB4AHYA3T0wasbHETJjGR4cmWc3AqJKXrjePK3/h4pygC8p7o4AAAGfsIUXOwAABAMARzBFAiAuT5XmZPOk0hlpiE6Jvzd9Xrpm00kO1YBAP/SvscHPZgIhAJvyvWYqbrgVpZaumfZE4owWH0epvkjCfTpT0vH20rciMAoGCCqGSM49BAMDA2gAMGUCMEnpd7DRZUC6dhTDktJTr+0vNak/cAUxOdCg3eu2OSaMt6XEJx4ptN+njk1OHkH3IAIxAOdj2UPUr6mgaKDospRmUIKYTgi1Baz2CPeOFxOo59eSWna/zKFa5ATJ3Li3ZkI2Bw==" + }, + "tlogEntries": [ + { + "logIndex": "2285569427", + "logId": { + "keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0=" + }, + "kindVersion": { + "kind": "dsse", + "version": "0.0.1" + }, + "integratedTime": "1785372940", + "inclusionPromise": { + "signedEntryTimestamp": "MEYCIQDAJoTjzPtS2hF1fswKxhXBHo/lXj2IB3MvDJawnZpPfwIhAOpBy+xZ/3MHCoSJJmGfcTnbtFEwhgVgVmgIzRsMk5yL" + }, + "inclusionProof": { + "logIndex": "2163665165", + "rootHash": "Nq2sTYb0r9yItTMLe6oBMcoRLaIwDQAVpne1Uc3apAU=", + "treeSize": "2163665181", + "hashes": [ + "Mw2cZcRb5F3ilJJ1LRC2UfjLwPs1+vdbnAATu20ccR0=", + "DEOLXtmvnQFJ1bwTE6zLpbGIsSQHW2sJHnMT01YB3PM=", + "KtBjsBYAyVy0b0Hb5T0wFJk8oXEkPgCw6dZxllc8XfY=", + "3AMqUVCoGBu+HazUlKxmVGvfAaZsm1wjaqhIBjw7uH0=", + "aLPOSO1AV8aoZbY8LgxszdEpaF7aOSzzCFiauFPb/AA=", + "xndR3MbgbalCD7BemiXcyUWU33/EU1ENDPvqvodlmbA=", + "AWRM2nHC7YtSFL+S3VXFeDdbkRn/e7lYvlz/mmS7B54=", + "xKSY/yPZE4Qpp5r0lYUT0M+9IkVMil6IWb8bHCEcWBM=", + "1AKiW4FzMdfivPG5J03AlVuy8EKLEeititjbw7+H9po=", + "KMiof7Y4O3uRlcxVKzJHkCJ0Lq1o7w6/sPZ9Azjp12k=", + "37d5Pi5xt11F9UZW98yy1Rkamie4fCtBKAaP7O8sFkc=", + "eTtConlWDvxkiAt63ROihvXyVDPQuDksIyE613IriNk=", + "WmnRZ4JXDHfuEXVEQ2VavnQH/2BNUuaOicMan3AdsA8=", + "9mFMp9UIXC7PdGhyWFHOEcugh8ANSizr3XfpFJ0sJLE=", + "VIsBkyayDqbZb+Hr7KQxmu1/cZ0lBfDN0lwjmUlvtv0=", + "OVsvZCKnWA+498QUIaQCtitUT6huDbC7SmhH1l8MxXI=", + "xH/DCseLHr9eKoYT8qsORZK7zVdEGYWHuVtsVrD95wY=" + ], + "checkpoint": { + "envelope": "rekor.sigstore.dev - 1193050959916656506\n2163665181\nNq2sTYb0r9yItTMLe6oBMcoRLaIwDQAVpne1Uc3apAU=\n\n— rekor.sigstore.dev wNI9ajBGAiEAm5DY7NlN5Bh9J+OMcKIwMM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LWNvcmVAcmVmcy90YWdzL3YwLjQuMSIsImRpZ2VzdCI6eyJnaXRDb21taXQiOiI2ODc5OGY3NGQyZjFhNTQ1YTM1YTRlM2ZjM2MyMjI1NTQzYzlkY2Y3In19XX0sInJ1bkRldGFpbHMiOnsiYnVpbGRlciI6eyJpZCI6Imh0dHBzOi8vZ2l0aHViLmNvbS9hY3Rpb25zL3J1bm5lci9naXRodWItaG9zdGVkIn0sIm1ldGFkYXRhIjp7Imludm9jYXRpb25JZCI6Imh0dHBzOi8vZ2l0aHViLmNvbS9wZWdtYS1kZXYvc3RvcmFnZS1jb3JlL2FjdGlvbnMvcnVucy8zMDUwNDEwNzUxMy9hdHRlbXB0cy8xIn19fX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "sig": "MEQCIGm9pkoopFJFZBFdoQgdx30dJiBTTxEc851biyF56H4aAiATQ3BnjMLhUlK/uBYYJEfTT0+FFNMjcgSgNR5vsGEKUw==", + "keyid": "" + } + ] + } + }, + "signedAccessSignatureUrl": "" +} diff --git a/tests/fixtures/release-registry/storage-azure-tables-0.4.0.tgz b/tests/fixtures/release-registry/storage-azure-tables-0.4.0.tgz new file mode 100644 index 0000000..582bc1a Binary files /dev/null and b/tests/fixtures/release-registry/storage-azure-tables-0.4.0.tgz differ diff --git a/tests/fixtures/release-registry/storage-cloudflare-d1-0.4.1.tgz b/tests/fixtures/release-registry/storage-cloudflare-d1-0.4.1.tgz new file mode 100644 index 0000000..5ca8880 Binary files /dev/null and b/tests/fixtures/release-registry/storage-cloudflare-d1-0.4.1.tgz differ diff --git a/tests/fixtures/release-registry/storage-core-0.4.0.tgz b/tests/fixtures/release-registry/storage-core-0.4.0.tgz new file mode 100644 index 0000000..650fe08 Binary files /dev/null and b/tests/fixtures/release-registry/storage-core-0.4.0.tgz differ diff --git a/tests/publish-workflow.test.ts b/tests/publish-workflow.test.ts index 8acce87..5f03720 100644 --- a/tests/publish-workflow.test.ts +++ b/tests/publish-workflow.test.ts @@ -1,10 +1,14 @@ +import { execFileSync } from "node:child_process"; import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { describe, expect, it } from "vitest"; -const workflow = await readFile( - new URL("../.github/workflows/publish.yml", import.meta.url), - "utf8", -); +const workflow = ( + await readFile( + new URL("../.github/workflows/publish.yml", import.meta.url), + "utf8", + ) +).replace(/\r\n/gu, "\n"); function workflowJob(name: string): string { const jobsMarker = "\njobs:\n"; @@ -28,73 +32,290 @@ function workflowStep(job: string, name: string): string { return job.slice(start, end === -1 ? undefined : end); } +function inlinePublisher(): string { + const step = workflowStep( + workflowJob("publish"), + "Verify and publish the prepared release", + ); + const match = /<<'NODE'\n([^]*?)\n NODE/u.exec(step); + if (!match) + throw new Error("Actual workflow publisher heredoc was not found."); + return match[1]! + .split("\n") + .map((line) => line.replace(/^ {10}/u, "")) + .join("\n"); +} + describe("publish workflow", () => { - it("verifies the tag before checkout and seals before smoke", () => { + it.each([ + { outcome: "success", reuseRequired: "false", upload: false }, + { outcome: "success", reuseRequired: "true", upload: true }, + { outcome: "success", reuseRequired: undefined, upload: true }, + { outcome: "success", reuseRequired: "unknown", upload: true }, + { outcome: "failure", reuseRequired: "false", upload: true }, + { outcome: "skipped", reuseRequired: undefined, upload: true }, + ])( + "retains reuse proof for seal=$outcome, reuse_required=$reuseRequired: $upload", + ({ outcome, reuseRequired, upload }) => { + const step = workflowStep( + workflowJob("prepare"), + "Retain genuine registry reuse proof", + ); + const condition = /^\s+if: \$\{\{ (.+) \}\}$/mu.exec(step)?.[1]; + if (condition === undefined) + throw new Error("Actual reuse-proof upload condition was not found."); + // The actual seal emits canonical boolean strings; do not use this JS + // evaluator to claim GitHub's string case-comparison semantics. + // Evaluate the actual condition with its two GitHub contexts supplied. + // This does not pretend to execute upload-artifact or its file globbing. + const evaluate = new Function( + "always", + "steps", + `return (${condition});`, + ) as ( + always: () => boolean, + steps: { + seal: { outcome: string; outputs: { reuse_required?: string } }; + }, + ) => boolean; + expect( + evaluate(() => true, { + seal: { + outcome, + outputs: + reuseRequired === undefined + ? {} + : { reuse_required: reuseRequired }, + }, + }), + ).toBe(upload); + expect(step).toContain("if-no-files-found: error"); + expect(step).toContain("overwrite: false"); + expect(step).toContain( + "actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4", + ); + }, + ); + + it("resolves runner paths only in the consuming step context", () => { + for (const name of [ + "identity", + "validate", + "prepare", + "smoke", + "preflight", + "publish", + "verify", + ]) { + const job = workflowJob(name); + expect(job.slice(0, job.indexOf("\n steps:"))).not.toMatch( + /\$\{\{\s*runner\./u, + ); + } + for (const [job, step, directory] of [ + ["smoke", "Smoke-test the prepared release copy", "storage-smoke"], + ["preflight", "Verify registry preflight", "storage-preflight-input"], + ["publish", "Verify and publish the prepared release", "storage-publish"], + [ + "verify", + "Verify registry bytes provenance and consumer", + "storage-final-input", + ], + ]) { + expect(workflowStep(workflowJob(job!), step!)).toContain( + "RELEASE_DIRECTORY: ${{ runner.temp }}/" + directory, + ); + } + expect( + workflowStep( + workflowJob("publish"), + "Verify and publish the prepared release", + ), + ).toContain( + "PREFLIGHT_DIRECTORY: ${{ runner.temp }}/storage-publish-preflight", + ); + }); + + it("requires actual Node22 and Node24 full gates before preparation", () => { + const validation = workflowJob("validate"), + prepare = workflowJob("prepare"); + expect(validation).toContain("matrix.node-version"); + const matrix = /node-version:\s*\[([^\]]+)\]/u.exec(validation)?.[1]; + expect(matrix).toMatch(/\b22(?:\.|\b)/u); + expect(matrix).toMatch(/\b24(?:\.|\b)/u); + for (const command of [ + "pnpm run format:check", + "pnpm run check", + "pnpm test", + ]) + expect(validation).toContain(command); + expect(validation).toContain('java-version: "21"'); + expect(validation).not.toContain("id-token: write"); + expect(prepare).toMatch(/needs:.*validate/u); + const jobHeader = prepare.slice(0, prepare.indexOf("\n steps:")); + expect(jobHeader).not.toContain("always()"); + // Failure-only proof retention may legitimately run after a failed step; + // it cannot make the prepare job bypass the required validation dependency. + }); + + it("runs the actual YAML environment filter through a real child process", () => { + const publisher = inlinePublisher(); + expect(publisher).toMatch(/env:\s*npmEnvironment\(\)/u); + const filter = /function npmEnvironment\(\)\s*\{[^]*?\n\}/u.exec( + publisher, + )?.[0]; + if (!filter) + throw new Error("Actual publisher npmEnvironment was not found."); + const poisons = { + GITHUB_ACTIONS: "true", + GITHUB_SHA: "a".repeat(40), + GITHUB_WORKFLOW_REF: + "pegma-dev/storage-core/.github/workflows/publish.yml@refs/tags/v0.4.3", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://fictional.actions.githubusercontent.com/oidc", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "fictional-oidc-value", + RUNNER_ENVIRONMENT: "github-hosted", + NPM_TOKEN: "poison", + NODE_AUTH_TOKEN: "poison", + NODE_OPTIONS: "poison", + NODE_EXTRA_CA_CERTS: "poison", + HTTPS_PROXY: "poison", + npm_config_registry: "https://evil.invalid", + }; + const script = `import {spawnSync} from "node:child_process"; +const userConfig="/fixture/empty-user",globalConfig="/fixture/empty-global",registry="https://registry.npmjs.org/"; +${filter} +Object.assign(process.env,${JSON.stringify(poisons)}); +const result=spawnSync(process.execPath,["--input-type=module","-e","process.stdout.write(JSON.stringify(process.env))"],{env:npmEnvironment(),encoding:"utf8"}); +if(result.status!==0)throw new Error("Filtered child failed"); +process.stdout.write(result.stdout);`; + const result = JSON.parse( + execFileSync(process.execPath, ["--input-type=module", "-e", script], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + HOME: tmpdir(), + TMP: tmpdir(), + }, + }), + ) as Record; + expect(result.RUNNER_ENVIRONMENT).toBe("github-hosted"); + expect(result.GITHUB_SHA).toBe(poisons.GITHUB_SHA); + expect(result.ACTIONS_ID_TOKEN_REQUEST_TOKEN).toBe( + poisons.ACTIONS_ID_TOKEN_REQUEST_TOKEN, + ); + for (const key of [ + "NPM_TOKEN", + "NODE_AUTH_TOKEN", + "NODE_OPTIONS", + "NODE_EXTRA_CA_CERTS", + "HTTPS_PROXY", + "npm_config_registry", + ]) + expect(result).not.toHaveProperty(key); + expect(result.NPM_CONFIG_USERCONFIG).toBe("/fixture/empty-user"); + expect(result.NPM_CONFIG_GLOBALCONFIG).toBe("/fixture/empty-global"); + }); + + it("requires github-hosted authority before the actual version probe and physical publish", () => { + const publisher = inlinePublisher(); + const guard = /RUNNER_ENVIRONMENT\s*!==\s*"github-hosted"/u.exec( + publisher, + )?.index; + const version = /npm\(\s*\[\s*"--version"/u.exec(publisher)?.index; + const upload = /npm\(\s*\[\s*"publish"/u.exec(publisher)?.index; + expect(guard).toBeDefined(); + expect(version).toBeDefined(); + expect(upload).toBeDefined(); + expect(guard!).toBeLessThan(version!); + expect(guard!).toBeLessThan(upload!); + }); + + it("pins real artifact actions to the original immutable preparation ID", () => { const prepare = workflowJob("prepare"); - expect(prepare.indexOf("- name: Verify the release tag")).toBeLessThan( - prepare.indexOf("- name: Check out the exact release commit"), + const upload = workflowStep(prepare, "Upload the prepared release"); + expect(upload).toContain( + "actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4", ); - expect(prepare).toContain("git init --bare"); - expect(prepare).toContain("fetch --no-tags origin"); + expect(upload).toContain("storage-prepared"); + expect(upload).toContain("include-hidden-files: false"); + expect(upload).toContain("if-no-files-found: error"); + expect(upload).toContain("overwrite: false"); + expect(upload).toContain("github.run_attempt"); + expect(prepare).toContain("artifact-id:"); + for (const name of ["smoke", "preflight", "publish", "verify"]) { + const job = workflowJob(name); + expect(job).toContain( + "actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c", + ); + expect(job).toMatch(/artifact-ids:.*needs\.prepare\.outputs/u); + expect(job).not.toMatch(/^\s+name: storage-release-/mu); + } + // Executing this pinned upload action and inspecting its exact ZIP is a + // separate mandatory release acceptance gate, not a readdir/glob imitation. + }); + it("verifies the tag before checkout and seals before smoke", () => { + const prepare = workflowJob("prepare"); + const identity = workflowJob("identity"); + expect(identity).not.toContain("actions/checkout"); + expect(identity).toContain("git init --bare"); + expect(identity).toContain("fetch --no-tags origin"); + expect(prepare).toMatch(/needs:.*identity/u); expect(prepare).toContain("Configure checkout tag verification"); expect(prepare).toContain("git config --local gpg.format ssh"); - expect(prepare).toContain('REVIEWED_NPM_VERSION: "11.18.0"'); + expect(workflow).toContain('REVIEWED_NPM_VERSION: "11.18.0"'); expect(prepare).toContain("--skip-smoke"); expect(prepare).toContain("include-hidden-files: false"); expect(prepare).toContain("manifest-digest:"); expect(prepare).toContain("artifact-digest:"); - expect(workflowStep(prepare, "Verify the release tag")).toBe( - workflowStep(workflowJob("publish"), "Verify the release tag"), - ); + for (const job of [identity, workflowJob("publish")]) { + const identity = workflowStep(job, "Verify the release tag"); + expect(identity).toContain("verify-tag"); + expect(identity).toContain("merge-base --is-ancestor"); + expect(identity).toContain("RELEASE_COMMIT"); + } }); it("pins the embedded publisher invariants", () => { const publish = workflowJob("publish"); - const environment = /const exact = new Set\(\[(.*?)\]\);/su.exec(publish); - expect(environment).not.toBeNull(); - expect( - Array.from( - environment![1]!.matchAll(/"([A-Z_]+)"/gu), - (match) => match[1], - ), - ).toEqual([ - "PATH", - "HOME", - "CI", - "SYSTEMROOT", - "RUNNER_TEMP", - "RUNNER_TOOL_CACHE", - "TEMP", - "TMP", - "TMPDIR", - ]); - expect(publish).toContain( - 'JSON.stringify(["gitCommit", "packages", "releaseTag", "schemaVersion"])', - ); - expect(publish).toContain( - 'JSON.stringify(["directory", "files", "integrity", "name", "package", "publish", "sha256", "shasum", "tarball", "version"])', - ); - expect(publish).toContain('upper.startsWith("GITHUB_")'); - expect(publish).toContain('upper.startsWith("ACTIONS_ID_TOKEN_")'); - expect(publish).toContain("await chmod(configDirectory, 0o700)"); + expect(publish).toMatch(/manifest\.schemaVersion\s*!==\s*2/u); + expect(publish).toContain("registryPolicySha256"); + expect(publish).toContain("registryReuse"); + expect(publish).toContain("originalRunId"); + expect(publish).toContain("sourceCommit"); + expect(publish).toContain("origin"); + expect(publish).toContain('"GITHUB_WORKFLOW_REF"'); + expect(publish).toContain('"ACTIONS_ID_TOKEN_REQUEST_TOKEN"'); + expect(publish).toMatch(/await chmod\(configDirectory,\s*0o700\)/u); }); it("keeps smoke unprivileged and publish independent of a checkout", () => { const smoke = workflowJob("smoke"); const publish = workflowJob("publish"); - expect(smoke).toContain("permissions:\n contents: read"); + expect(workflow.slice(0, workflow.indexOf("\njobs:\n"))).toContain( + "permissions:\n contents: read", + ); expect(smoke).not.toContain("id-token: write"); expect(smoke).toContain("release-packages.mjs smoke"); expect(smoke.indexOf("actions/checkout")).toBeLessThan( smoke.indexOf("actions/download-artifact"), ); - expect(publish).toContain("needs: [prepare, smoke]"); + expect(publish).toMatch(/needs:.*preflight/u); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("actions/checkout"); expect(publish).not.toContain("scripts/release-packages.mjs"); expect(publish).toContain('"--ignore-scripts"'); expect(publish).toContain('"--provenance"'); + const preflight = workflowJob("preflight"), + verify = workflowJob("verify"); + expect(preflight).not.toContain("id-token: write"); + expect(preflight).toContain("release-registry-verify.mjs preflight"); + expect(preflight).toContain("--expected-manifest-sha256"); + expect(verify).not.toContain("id-token: write"); + expect(verify).toContain("release-registry-verify.mjs verify"); + expect(verify).toContain("--run-id"); }); it("passes release event values through job environments", () => { @@ -102,12 +323,12 @@ describe("publish workflow", () => { workflow.match( /RELEASE_TAG: \$\{\{ github\.event\.release\.tag_name \}\}/gu, ), - ).toHaveLength(2); + ).not.toBeNull(); expect( workflow.match( /RELEASE_PRERELEASE: \$\{\{ github\.event\.release\.prerelease \}\}/gu, ), - ).toHaveLength(2); + ).not.toBeNull(); const lines = workflow.split("\n"); for (let index = 0; index < lines.length; index += 1) { diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 24ea806..d19f0da 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,4 +1,5 @@ import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { existsSync, mkdirSync, @@ -9,7 +10,8 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { gzipSync } from "node:zlib"; +import { describe, expect, it, vi } from "vitest"; import { RELEASE_PACKAGES, decidePublication, @@ -17,11 +19,21 @@ import { lockVersionSatisfiesSpecifier, parseArguments, parsePnpmLockfileImporters, + prepareRelease, + publishPreparedRelease, + smokePreparedRelease, validateLockImporter, validateReleaseTag, validateRepository, verifyReleaseInventory, + verifyPreparedManifest, } from "../scripts/release-packages.mjs"; +import { + inspectReleaseTarball, + loadReusePolicy, + preflightRegistry, + registryReuseOrigin, +} from "../scripts/release-registry-verify.mjs"; const git = process.platform === "win32" ? "git.exe" : "git"; const releaseVersion = ( @@ -79,14 +91,14 @@ describe("release package metadata", () => { scripts?: { prepack?: string }; }>; - // The scan contract released core, Azure, and D1 at 0.4.0. D1 carries - // a patch of its own; DynamoDB is the next unused repository-wide - // number. Every adapter pins the port exactly where it was published. + // Core/Azure040 and D1041 retain their original registry bytes. Dynamo043 + // is the reviewed runtime candidate; registration-only042 is no SDK. + // Every adapter pins the port exactly where it was published. expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ { name: "@pegma/storage-core", version: "0.4.0" }, { name: "@pegma/storage-azure-tables", version: "0.4.0" }, { name: "@pegma/storage-cloudflare-d1", version: "0.4.1" }, - { name: "@pegma/storage-dynamodb", version: "0.4.2" }, + { name: "@pegma/storage-dynamodb", version: "0.4.3" }, ]); for (const adapter of manifests.slice(1)) { expect(adapter.dependencies?.["@pegma/storage-core"]).toBe("0.4.0"); @@ -381,7 +393,11 @@ describe("release source authentication", () => { expect(prepareStart).toBeGreaterThanOrEqual(0); expect(publishStart).toBeGreaterThan(prepareStart); const prepare = jobs.slice(prepareStart, publishStart); - const publish = jobs.slice(publishStart); + const nextJob = jobs.indexOf("\n verify:", publishStart); + const publish = jobs.slice( + publishStart, + nextJob === -1 ? undefined : nextJob, + ); expect(prepare).not.toContain("id-token: write"); expect(prepare).toContain("--skip-smoke"); expect(prepare).toContain("include-hidden-files: false"); @@ -409,7 +425,7 @@ describe("prepared release files", () => { "pegma-storage-core-0.4.0.tgz", "pegma-storage-azure-tables-0.4.0.tgz", "pegma-storage-cloudflare-d1-0.4.1.tgz", - "pegma-storage-dynamodb-0.4.2.tgz", + "pegma-storage-dynamodb-0.4.3.tgz", ].map((tarball) => ({ tarball })); for (const { tarball } of packages) { writeFileSync(join(root, tarball), tarball); @@ -460,6 +476,7 @@ describe("prepared release files", () => { HOME: "home", CI: "1", GITHUB_ACTIONS: "true", + RUNNER_ENVIRONMENT: "github-hosted", ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.invalid", NPM_TOKEN: "not-kept", NODE_AUTH_TOKEN: "not-kept", @@ -477,6 +494,7 @@ describe("prepared release files", () => { HOME: "home", CI: "1", GITHUB_ACTIONS: "true", + RUNNER_ENVIRONMENT: "github-hosted", ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.invalid", NPM_CONFIG_USERCONFIG: "/private/userconfig", NPM_CONFIG_GLOBALCONFIG: "/private/globalconfig", @@ -501,3 +519,478 @@ describe("retry-safe publication", () => { ); }); }); + +interface PreparedRecord { + name: string; + version: string; + directory: string; + tarball: string; + size: number; + shasum: string; + sha256: string; + integrity: string; + publish: boolean; + package: Record; + files: Array<{ path: string; size: number }>; + origin: Record; +} + +interface PreparedManifest { + schemaVersion: number; + repository: string; + gitCommit: string; + releaseTag: string; + registryPolicySha256: string; + packages: PreparedRecord[]; +} + +function sourceArchive(metadata: Record): Buffer { + const files = new Map([ + ["package/package.json", JSON.stringify(metadata)], + ["package/README.md", "Unsigned source-archive parser fixture"], + ["package/LICENSE", "MIT"], + ["package/dist/index.js", "export const fixture = true;"], + ["package/dist/index.d.ts", "export declare const fixture: true;"], + ]); + const chunks: Buffer[] = []; + for (const [path, text] of files) { + const body = Buffer.from(text), + header = Buffer.alloc(512); + header.write(path, 0, 100, "utf8"); + header.write("0000644\0", 100, "ascii"); + header.write("0000000\0", 108, "ascii"); + header.write("0000000\0", 116, "ascii"); + header.write( + `${body.length.toString(8).padStart(11, "0")}\0`, + 124, + "ascii", + ); + header.write("00000000000\0", 136, "ascii"); + header.fill(32, 148, 156); + header.write("0", 156, "ascii"); + header.write("ustar\0", 257, "ascii"); + header.write("00", 263, "ascii"); + const sum = header.reduce((total, byte) => total + byte, 0); + header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, "ascii"); + chunks.push(header, body, Buffer.alloc((512 - (body.length % 512)) % 512)); + } + return gzipSync(Buffer.concat([...chunks, Buffer.alloc(1024)])); +} + +async function preparedSchema2() { + const root = mkdtempSync(join(tmpdir(), "storage-schema2-")); + const output = join(root, "prepared"); + mkdirSync(output); + run(git, ["init", "--quiet"], root); + run(git, ["config", "user.name", "Release Fixture"], root); + run(git, ["config", "user.email", "release@example.invalid"], root); + writeFileSync(join(root, "README.md"), "Fictional release source\n"); + run(git, ["add", "README.md"], root); + run( + git, + ["-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "fixture"], + root, + ); + const gitCommit = run(git, ["rev-parse", "HEAD"], root); + const { policy, sha256: registryPolicySha256 } = await loadReusePolicy(); + const packages: PreparedRecord[] = []; + for (const entry of policy.packages) { + const bytes = readFileSync( + new URL( + `./fixtures/release-registry/${entry.directory}-${entry.version}.tgz`, + import.meta.url, + ), + ); + const inspected = inspectReleaseTarball(bytes); + const tarball = `${entry.name.slice(1).replace("/", "-")}-${entry.version}.tgz`; + writeFileSync(join(output, tarball), bytes); + packages.push({ + name: entry.name, + version: entry.version, + directory: entry.directory, + tarball, + size: bytes.length, + shasum: entry.shasum, + sha256: entry.sha256, + integrity: entry.integrity, + publish: false, + package: inspected.package, + files: [...inspected.files], + origin: { ...registryReuseOrigin(entry) }, + }); + } + const metadata = JSON.parse( + readFileSync( + new URL("../packages/storage-dynamodb/package.json", import.meta.url), + "utf8", + ), + ) as Record; + const sourceDirectory = join(root, "packages", "storage-dynamodb"); + mkdirSync(sourceDirectory, { recursive: true }); + writeFileSync( + join(sourceDirectory, "package.json"), + JSON.stringify(metadata), + ); + const bytes = sourceArchive(metadata), + inspected = inspectReleaseTarball(bytes); + const tarball = "pegma-storage-dynamodb-0.4.3.tgz"; + writeFileSync(join(output, tarball), bytes); + packages.push({ + name: "@pegma/storage-dynamodb", + version: "0.4.3", + directory: "storage-dynamodb", + tarball, + size: bytes.length, + shasum: createHash("sha1").update(bytes).digest("hex"), + sha256: createHash("sha256").update(bytes).digest("hex"), + integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + publish: true, + files: [...inspected.files], + package: inspected.package, + origin: { + kind: "source", + repository: "pegma-dev/storage-core", + gitCommit, + releaseTag: "v0.4.3", + directory: "storage-dynamodb", + }, + }); + const manifest: PreparedManifest = { + schemaVersion: 2, + repository: "pegma-dev/storage-core", + gitCommit, + releaseTag: "v0.4.3", + registryPolicySha256, + packages, + }; + const manifestPath = join(output, "package-manifest.json"); + const save = () => + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + save(); + return { root, output, manifest, manifestPath, save }; +} + +describe("selected-source schema2 archives", () => { + it.each(["reuse-verification", "consumer-verification"] as const)( + "refuses a retained default %s namespace before repository or tool work", + async (suffix) => { + const root = mkdtempSync(join(tmpdir(), "storage-fresh-admission-")); + const proof = join(root, `.release-${suffix}`); + mkdirSync(proof); + try { + // This deliberately incomplete root has no package.json or Git state: + // reaching repository admission would fail for a different reason. + await expect( + prepareRelease({ root, requireClean: true, skipSmoke: true }), + ).rejects.toThrow( + /release proof output already exists:.*preserve existing evidence and choose a fresh --output/u, + ); + expect(existsSync(proof)).toBe(true); + expect(existsSync(join(root, ".release"))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, + ); + + it("refuses occupied artifacts and explicit smoke proof before reading a repository or manifest", async () => { + const root = mkdtempSync(join(tmpdir(), "storage-fresh-artifact-")); + const output = join(root, ".release"); + mkdirSync(output); + writeFileSync(join(output, "retained.txt"), "preserve me"); + const proof = join(root, "prior-proof"); + mkdirSync(proof); + try { + await expect( + prepareRelease({ root, requireClean: true }), + ).rejects.toThrow(/release output directory must be empty/u); + await expect( + smokePreparedRelease({ + manifest: join(root, "missing-manifest.json"), + output: proof, + }), + ).rejects.toThrow( + /preserve existing evidence and choose a fresh --output/u, + ); + expect(readFileSync(join(output, "retained.txt"), "utf8")).toBe( + "preserve me", + ); + expect(existsSync(proof)).toBe(true); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("keeps exactly the default proof siblings ignored in a real clean checkout", () => { + const root = mkdtempSync(join(tmpdir(), "storage-default-ignore-")); + try { + const ignore = readFileSync( + new URL("../.gitignore", import.meta.url), + "utf8", + ); + expect(ignore.split(/\r?\n/u)).toContain("/.release-reuse-verification/"); + expect(ignore.split(/\r?\n/u)).toContain( + "/.release-consumer-verification/", + ); + expect(ignore).not.toContain("/.release-*/"); + run(git, ["init", "--quiet"], root); + run(git, ["config", "user.name", "Release Fixture"], root); + run(git, ["config", "user.email", "release@example.invalid"], root); + writeFileSync(join(root, ".gitignore"), ignore); + run(git, ["add", ".gitignore"], root); + run( + git, + ["-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "fixture"], + root, + ); + for (const name of [ + ".release", + ".release-reuse-verification", + ".release-consumer-verification", + ]) { + mkdirSync(join(root, name)); + writeFileSync(join(root, name, "proof.json"), "{}\n"); + } + expect(run(git, ["status", "--porcelain"], root)).toBe(""); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("withholds every preflight decision when a reused package is unavailable after original-manifest verification", async () => { + const f = await preparedSchema2(); + try { + const expectedManifestSha256 = createHash("sha256") + .update(readFileSync(f.manifestPath)) + .digest("hex"); + const options = { + root: f.root, + manifest: f.manifestPath, + expectedReleaseCommit: f.manifest.gitCommit, + expectedManifestSha256, + runId: 12345, + runAttempt: 2, + output: join(f.root, "proof"), + }; + const verified = await verifyPreparedManifest(f.manifestPath, options); + const fetch = vi.fn(async () => new Response(null, { status: 404 })); + const run = vi.fn(); + await expect( + preflightRegistry(verified, options, { fetch, run }), + ).rejects.toThrow(/original registry package is missing/u); + expect(fetch).toHaveBeenCalledTimes(1); + expect(fetch.mock.calls[0]).toEqual([ + "https://registry.npmjs.org/%40pegma%2Fstorage-core/0.4.0", + expect.objectContaining({ redirect: "error" }), + ]); + expect(run).not.toHaveBeenCalled(); + expect(existsSync(options.output)).toBe(false); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("rejects Core043 source labeling over the genuine Core040 archive and package metadata", async () => { + const f = await preparedSchema2(); + try { + const record = f.manifest.packages[0]!; + expect(record.package.version).toBe("0.4.0"); + const originalPath = join(f.output, record.tarball); + record.version = "0.4.3"; + record.tarball = "pegma-storage-core-0.4.3.tgz"; + record.publish = true; + record.origin = { + kind: "source", + repository: f.manifest.repository, + gitCommit: f.manifest.gitCommit, + releaseTag: f.manifest.releaseTag, + directory: record.directory, + }; + // Preserve the genuine old archive/hash and make the independent source + // metadata agree with its old package.json, so those later comparisons + // cannot mask the required record.version <-> package.version refusal. + writeFileSync(join(f.output, record.tarball), readFileSync(originalPath)); + rmSync(originalPath); + const sourceDirectory = join(f.root, "packages", "storage-core"); + mkdirSync(sourceDirectory, { recursive: true }); + writeFileSync( + join(sourceDirectory, "package.json"), + JSON.stringify(record.package), + ); + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow("prepared artifact metadata is invalid"); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("verifies exactly three pinned originals and one source candidate without rebuilding the originals", async () => { + const f = await preparedSchema2(); + try { + const expectedManifestSha256 = createHash("sha256") + .update(readFileSync(f.manifestPath)) + .digest("hex"); + const actual = await verifyPreparedManifest(f.manifestPath, { + root: f.root, + expectedReleaseCommit: f.manifest.gitCommit, + expectedManifestSha256, + }); + expect(actual).toEqual(f.manifest); + expect(f.manifest.packages.map(({ publish }) => publish)).toEqual([ + false, + false, + false, + true, + ]); + expect(f.manifest.packages[0]!.origin.sourceCommit).not.toBe( + f.manifest.gitCommit, + ); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("rejects independent artifact-digest, current-source and policy swaps", async () => { + const f = await preparedSchema2(); + try { + await expect( + verifyPreparedManifest(f.manifestPath, { + root: f.root, + expectedManifestSha256: "0".repeat(64), + }), + ).rejects.toThrow(/digest/u); + await expect( + verifyPreparedManifest(f.manifestPath, { + root: f.root, + expectedReleaseCommit: "0".repeat(40), + }), + ).rejects.toThrow(/checkout/u); + f.manifest.registryPolicySha256 = "0".repeat(64); + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/policy digest/u); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("enforces every closed origin key and the source/original-source distinction", async () => { + const f = await preparedSchema2(); + try { + for (const record of f.manifest.packages) { + const original = structuredClone(record.origin); + for (const key of Object.keys(original)) { + record.origin = { ...original }; + delete record.origin[key]; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/origin/u); + } + record.origin = { ...original, extra: "not admitted" }; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/origin/u); + record.origin = original; + } + f.manifest.packages[0]!.origin.sourceCommit = f.manifest.gitCommit; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/independent policy/u); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("rejects source/reuse relabeling, package-order swaps and unexpected top-level fields", async () => { + const f = await preparedSchema2(); + try { + f.manifest.packages[0]!.publish = true; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/source origin/u); + f.manifest.packages[0]!.publish = false; + [f.manifest.packages[0], f.manifest.packages[1]] = [ + f.manifest.packages[1]!, + f.manifest.packages[0]!, + ]; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/inventory/u); + [f.manifest.packages[0], f.manifest.packages[1]] = [ + f.manifest.packages[1]!, + f.manifest.packages[0]!, + ]; + writeFileSync( + f.manifestPath, + JSON.stringify({ ...f.manifest, trusted: true }), + ); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/identity/u); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("rejects changed selected exports/dependencies and changed literal original tar bytes", async () => { + const f = await preparedSchema2(); + try { + const selected = f.manifest.packages[3]!; + const original = structuredClone(selected.package); + selected.package = { + ...original, + dependencies: { "@pegma/storage-core": "0.4.1" }, + }; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/source/u); + selected.package = { ...original, exports: { ".": "./private.js" } }; + f.save(); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(/source/u); + selected.package = original; + f.save(); + const first = f.manifest.packages[0]!, + path = join(f.output, first.tarball), + bytes = readFileSync(path); + bytes[0] = bytes[0]! ^ 1; + writeFileSync(path, bytes); + await expect( + verifyPreparedManifest(f.manifestPath, { root: f.root }), + ).rejects.toThrow(); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }); + + it("refuses the alternate publisher before even reading a malicious or missing artifact", async () => { + await expect( + publishPreparedRelease({ + manifest: "does-not-exist", + root: "does-not-exist", + }), + ).rejects.toThrow(/disabled.*protected GitHub release workflow/u); + const source = readFileSync( + new URL("../scripts/release-packages.mjs", import.meta.url), + "utf8", + ); + const body = + /export async function publishPreparedRelease\([^]*?\n\}/u.exec( + source, + )?.[0]; + expect(body).toBeDefined(); + expect(body).not.toContain("runNpm"); + expect(body).not.toContain("readFile"); + expect(body).not.toContain("queryRegistry"); + }); +}); diff --git a/tests/release-registry.test.ts b/tests/release-registry.test.ts new file mode 100644 index 0000000..adb86ab --- /dev/null +++ b/tests/release-registry.test.ts @@ -0,0 +1,2628 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual } from "node:crypto"; +import * as fsPromises from "node:fs/promises"; +import { + lstatSync, + constants, + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, relative, resolve } from "node:path"; +import { gzipSync } from "node:zlib"; +import { describe, expect, it, vi } from "vitest"; +import { + REGISTRY, + assertTrustedPublishingEnvironment, + canonicalTarball, + downloadRegistryArtifact, + inspectReleaseTarball, + isolatedVerificationEnvironment, + loadReusePolicy, + preflightRegistry, + registryReuseOrigin, + runPublicConsumer, + verifyProvenanceAudit, + verifyPublishingJobs, + verifyReusedPackages, + validateReusePolicy, + verifyRegistryRelease, +} from "../scripts/release-registry-verify.mjs"; +import type { + PreparedManifest, + PreparedPackage, + VerificationSeams, +} from "../scripts/release-registry-verify.mjs"; + +const fixture = (name: string): Buffer => + readFileSync(new URL(`./fixtures/release-registry/${name}`, import.meta.url)); +const awsClient = { + name: "@aws-sdk/client-dynamodb", + version: "3.1130.0", + integrity: + "sha512-yPEc9TWLY1McM6xA9wlxA9rM0ZeS8RAeyi1t7rdHPNxq0TpyCDn6z651ccRJ1RrMU4k2aiVzNCaBYUZA4aaA/w==", + tarballUrl: + "https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.1130.0.tgz", + archiveSha256: + "b0f2cf96a293592e70a4b0cee40d0ef387c10b0cdc541b0c3fd99a8d4b753335", +} as const; +type AwsConsumerFault = + | "metadata-name" + | "metadata-version" + | "metadata-url" + | "metadata-integrity" + | "archive-bytes" + | "lock-missing" + | "lock-version" + | "lock-link" + | "lock-url" + | "lock-integrity" + | "installed-name" + | "installed-version" + | "installed-directory-link" + | "nested-version"; +const commit = "a".repeat(40); +const identity = { + gitCommit: commit, + releaseTag: "v0.4.3", + runId: 12345, + runAttempt: 2, +}; +const digest = ( + bytes: Buffer, + algorithm = "sha256", + encoding: "hex" | "base64" = "hex", +) => createHash(algorithm).update(bytes).digest(encoding); + +function packageJson() { + return { + name: "@pegma/storage-dynamodb", + version: "0.4.3", + license: "MIT", + type: "module", + engines: { node: ">=22" }, + publishConfig: { access: "public" }, + repository: { + type: "git", + url: "git+https://github.com/pegma-dev/storage-core.git", + directory: "packages/storage-dynamodb", + }, + exports: { ".": { import: "./dist/index.js", types: "./dist/index.d.ts" } }, + dependencies: { "@pegma/storage-core": "0.4.0" }, + }; +} + +// These small unsigned archives exercise the real bounded tar parser. They +// never stand in for the pinned original archives or a provenance audit. +function archive( + additions: Array<{ path: string; body: string; type?: string }> = [], + metadata: object = packageJson(), +): Buffer { + const entries = [ + { path: "package/package.json", body: JSON.stringify(metadata) }, + { path: "package/README.md", body: "Fictional parser fixture" }, + { path: "package/LICENSE", body: "MIT" }, + { path: "package/dist/index.js", body: "export const fixture = true;" }, + { + path: "package/dist/index.d.ts", + body: "export declare const fixture: true;", + }, + ...additions, + ]; + const parts: Buffer[] = []; + for (const entry of entries) { + const body = Buffer.from(entry.body); + const header = Buffer.alloc(512); + header.write(entry.path, 0, 100, "utf8"); + header.write("0000644\0", 100, "ascii"); + header.write("0000000\0", 108, "ascii"); + header.write("0000000\0", 116, "ascii"); + header.write( + `${body.length.toString(8).padStart(11, "0")}\0`, + 124, + "ascii", + ); + header.write("00000000000\0", 136, "ascii"); + header.fill(32, 148, 156); + header.write(entry.type ?? "0", 156, "ascii"); + header.write("ustar\0", 257, "ascii"); + header.write("00", 263, "ascii"); + const checksum = header.reduce((total, byte) => total + byte, 0); + header.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, "ascii"); + parts.push(header, body, Buffer.alloc((512 - (body.length % 512)) % 512)); + } + return gzipSync(Buffer.concat([...parts, Buffer.alloc(1024)])); +} + +function syntheticRecord(bytes = archive()) { + const metadata = packageJson(); + return { + name: metadata.name, + version: metadata.version, + size: bytes.length, + sha256: digest(bytes), + shasum: digest(bytes, "sha1"), + integrity: `sha512-${digest(bytes, "sha512", "base64")}`, + tarballUrl: canonicalTarball(metadata), + }; +} + +function downloadPorts(record = syntheticRecord(), bytes = archive()) { + const metadata = { + name: record.name, + version: record.version, + dist: { + integrity: record.integrity, + shasum: record.shasum, + tarball: record.tarballUrl, + // Presence is not authentication; npm's real signature audit is separate. + signatures: [ + { keyid: "parser-fixture", sig: "not-a-verified-signature" }, + ], + }, + }; + const fetch = vi.fn(async (url: string | URL | Request) => + String(url) === record.tarballUrl + ? new Response(new Uint8Array(bytes)) + : Response.json(metadata), + ); + return { metadata, fetch }; +} + +interface BundleFixture { + predicateType: string; + bundle: { + dsseEnvelope: { + payloadType: string; + payload: string; + signatures?: unknown[]; + }; + verificationMaterial: unknown; + }; +} + +async function provenanceFixture() { + const { policy } = await loadReusePolicy(); + const entry = policy.packages[0]!; + const record = { + ...entry, + origin: registryReuseOrigin(entry), + publish: false, + tarball: `${entry.name.slice(1).replace("/", "-")}-${entry.version}.tgz`, + ...inspectReleaseTarball( + fixture(`${entry.directory}-${entry.version}.tgz`), + ), + }; + const bundle = JSON.parse( + fixture("core040-slsa.json").toString("utf8"), + ) as BundleFixture; + // Deliberately a trusted-audit stub at the pure claim-validator boundary. + // The genuine public bundle is not cryptographically verified by this test. + const audit = { + invalid: [] as unknown[], + missing: [] as unknown[], + verified: [ + { + name: entry.name, + version: entry.version, + location: `node_modules/${entry.name}`, + registry: REGISTRY, + attestationBundles: [bundle], + }, + ], + }; + return { audit, record, policy }; +} + +function changeClaim(bundle: BundleFixture, path: string[], value: unknown) { + const statement = JSON.parse( + Buffer.from(bundle.bundle.dsseEnvelope.payload, "base64").toString("utf8"), + ) as Record; + let target = statement; + for (const key of path.slice(0, -1)) + target = target[key] as Record; + target[path.at(-1)!] = value; + bundle.bundle.dsseEnvelope.payload = Buffer.from( + JSON.stringify(statement), + ).toString("base64"); +} + +async function historicalWriterFixture() { + const { policy } = await loadReusePolicy(); + const bundleFiles = [ + "core040-slsa.json", + "azure040-slsa.json", + "d1041-slsa.json", + ]; + const records = policy.packages.map((entry) => ({ + ...entry, + origin: registryReuseOrigin(entry), + publish: false, + tarball: `${entry.name.slice(1).replace("/", "-")}-${entry.version}.tgz`, + ...inspectReleaseTarball( + fixture(`${entry.directory}-${entry.version}.tgz`), + ), + })); + // A scripted trusted npm-output boundary, NOT a claim that this test ran + // ECDSA/Sigstore. Every nested signed bundle is the genuine public fixture. + const audit = { + invalid: [], + missing: [], + verified: records.map((record, index) => ({ + name: record.name, + version: record.version, + location: `node_modules/${record.name}`, + registry: REGISTRY, + attestationBundles: [ + JSON.parse(fixture(bundleFiles[index]!).toString("utf8")), + ], + })), + }; + const facts = verifyProvenanceAudit(audit, records, identity, policy); + const responses = new Map>(); + for (const runId of new Set(facts.map((fact) => fact.runId))) { + const group = facts.filter((fact) => fact.runId === runId); + const first = group[0]!; + const start = new Date( + Math.min(...group.map((fact) => Date.parse(fact.certificate.validFrom))) - + 1000, + ).toISOString(); + const end = new Date( + Math.max(...group.map((fact) => Date.parse(fact.certificate.validTo))) + + 1000, + ).toISOString(); + const runUrl = `https://api.github.com/repos/pegma-dev/storage-core/actions/runs/${runId}`; + responses.set(runUrl, { + id: runId, + head_sha: first.sourceCommit, + head_branch: first.sourceTag, + run_attempt: 1, + event: "release", + path: ".github/workflows/publish.yml", + repository: { id: 1312519623, owner: { id: 309286193 } }, + }); + responses.set(`${runUrl}/attempts/1/jobs?per_page=100`, { + total_count: 1, + jobs: [ + { + id: runId === 30334062325 ? 90195221537 : 90750106220, + run_id: runId, + run_attempt: 1, + head_branch: first.sourceTag, + name: "publish", + status: "completed", + conclusion: "success", + head_sha: first.sourceCommit, + started_at: start, + completed_at: end, + steps: [ + { + name: "Publish verified prepared tarballs", + status: "completed", + conclusion: "success", + started_at: start, + completed_at: end, + }, + ], + }, + ], + }); + } + const fetch = vi.fn(async (url: string | URL | Request) => { + const response = responses.get(String(url)); + return response + ? Response.json(response) + : new Response(null, { status: 404 }); + }); + return { records, audit, facts, responses, fetch }; +} + +describe("registry reuse source policy", () => { + it("accepts only a unique canonical inventory subset without inventing a future runtime pin", async () => { + const { policy } = await loadReusePolicy(); + expect(validateReusePolicy({ ...policy, packages: [] }).packages).toEqual( + [], + ); + expect( + validateReusePolicy({ + ...policy, + packages: [policy.packages[0], policy.packages[2]], + }).packages, + ).toEqual([policy.packages[0], policy.packages[2]]); + expect(() => + validateReusePolicy({ + ...policy, + packages: [policy.packages[0], policy.packages[0]], + }), + ).toThrow(); + expect(() => + validateReusePolicy({ + ...policy, + packages: [policy.packages[2], policy.packages[0]], + }), + ).toThrow(); + expect(() => + validateReusePolicy({ + ...policy, + packages: [{ ...policy.packages[0], name: "@other/storage" }], + }), + ).toThrow(); + expect( + policy.packages.some(({ name }) => name === "@pegma/storage-dynamodb"), + ).toBe(false); + }); + + it("pins the original literal archives and their original publishing sources", async () => { + const { policy, sha256 } = await loadReusePolicy(); + expect(sha256).toMatch(/^[a-f0-9]{64}$/u); + expect(policy.repository).toBe("pegma-dev/storage-core"); + expect( + policy.packages.map(({ name, version }) => `${name}@${version}`), + ).toEqual([ + "@pegma/storage-core@0.4.0", + "@pegma/storage-azure-tables@0.4.0", + "@pegma/storage-cloudflare-d1@0.4.1", + ]); + let total = 0; + for (const entry of policy.packages) { + const bytes = fixture(`${entry.directory}-${entry.version}.tgz`); + total += bytes.length; + expect(bytes.length).toBe(entry.size); + expect(digest(bytes)).toBe(entry.sha256); + expect(digest(bytes, "sha1")).toBe(entry.shasum); + expect(`sha512-${digest(bytes, "sha512", "base64")}`).toBe( + entry.integrity, + ); + const inspected = inspectReleaseTarball(bytes); + expect(inspected.package.name).toBe(entry.name); + expect(inspected.package.version).toBe(entry.version); + expect(registryReuseOrigin(entry)).toEqual({ + kind: "registryReuse", + registry: REGISTRY, + policyEntry: `${entry.name}@${entry.version}`, + tarballUrl: entry.tarballUrl, + sourceCommit: entry.sourceCommit, + sourceTag: entry.sourceTag, + workflowPath: ".github/workflows/publish.yml", + originalRunId: entry.originalRunId, + originalRunAttempt: entry.originalRunAttempt, + }); + expect(entry.sourceCommit).not.toBe(commit); + } + expect(total).toBe(47126); + }); + + it("inspects the actual public exports and excludes packed tests", () => { + const inspected = inspectReleaseTarball(archive()); + expect(inspected.package.dependencies).toEqual({ + "@pegma/storage-core": "0.4.0", + }); + expect(inspected.files.map(({ path }) => path)).toEqual( + [ + "dist/index.d.ts", + "dist/index.js", + "LICENSE", + "package.json", + "README.md", + ].sort((a, b) => a.localeCompare(b)), + ); + }); + + it.each([ + "package/../escape.js", + "package/dist/../escape.js", + "package/dist/test.test.js", + "elsewhere/index.js", + ])("rejects unreviewed archive entry %s", (path) => { + expect(() => + inspectReleaseTarball(archive([{ path, body: "unsafe" }])), + ).toThrow(); + }); + + it("rejects links and duplicate entries rather than extracting them", () => { + expect(() => + inspectReleaseTarball( + archive([{ path: "package/dist/link.js", body: "", type: "2" }]), + ), + ).toThrow(/safe regular/u); + expect(() => + inspectReleaseTarball( + archive([{ path: "package/LICENSE", body: "duplicate" }]), + ), + ).toThrow(/identities/u); + }); + + it("rejects missing exports, missing exported files and registration-only metadata", () => { + expect(() => + inspectReleaseTarball(archive([], { ...packageJson(), exports: {} })), + ).toThrow(/exports/u); + expect(() => + inspectReleaseTarball( + archive([], { + ...packageJson(), + exports: { ".": "./dist/missing.js" }, + }), + ), + ).toThrow(/entry/u); + expect(() => + inspectReleaseTarball( + archive([], { + name: "@pegma/storage-dynamodb", + version: "0.4.2", + license: "MIT", + }), + ), + ).toThrow(); + }); + + it("bounds compressed input and expanded archive records", () => { + expect(() => + inspectReleaseTarball(Buffer.alloc(4 * 1024 * 1024 + 1)), + ).toThrow(/bound/u); + expect(() => + inspectReleaseTarball( + archive([ + { + path: "package/dist/large.js", + body: "x".repeat(4 * 1024 * 1024 + 1), + }, + ]), + ), + ).toThrow(/bound/u); + }); +}); + +describe("canonical registry bytes", () => { + it("accepts only the exact canonical metadata and literal archive", async () => { + const bytes = archive(), + record = syntheticRecord(bytes), + ports = downloadPorts(record, bytes); + const result = await downloadRegistryArtifact(record, ports); + expect(Buffer.from(result.bytes).equals(bytes)).toBe(true); + expect(ports.fetch.mock.calls.map(([url]) => String(url))).toEqual([ + `${REGISTRY}${encodeURIComponent(record.name)}/${record.version}`, + record.tarballUrl, + ]); + }); + + it.each(["name", "version", "integrity", "shasum", "tarball", "signatures"])( + "refuses changed registry %s before accepting bytes", + async (field) => { + const bytes = archive(), + record = syntheticRecord(bytes), + ports = downloadPorts(record, bytes); + if (field === "name" || field === "version") + ports.metadata[field] = "changed"; + else if (field === "signatures") ports.metadata.dist.signatures = []; + else (ports.metadata.dist as Record)[field] = "changed"; + await expect(downloadRegistryArtifact(record, ports)).rejects.toThrow( + /metadata/u, + ); + expect(ports.fetch).toHaveBeenCalledTimes(1); + }, + ); + + it("refuses altered tar bytes even when self-declared metadata agrees", async () => { + const bytes = archive(), + record = syntheticRecord(bytes); + const changed = Buffer.from(bytes); + changed[changed.length - 1] = 1; + await expect( + downloadRegistryArtifact(record, downloadPorts(record, changed)), + ).rejects.toThrow(/original bytes/u); + }); + + it("refuses missing reused versions and non404 registry outages", async () => { + for (const status of [404, 429, 500]) { + await expect( + downloadRegistryArtifact(syntheticRecord(), { + fetch: async () => new Response(null, { status }), + }), + ).rejects.toThrow(/unavailable/u); + } + await expect( + downloadRegistryArtifact(syntheticRecord(), { + fetch: async () => { + throw new Error("fictional transport outage"); + }, + }), + ).rejects.toThrow(/availability is unknown/u); + }); +}); + +describe("trusted npm audit claim boundary", () => { + it("uses the genuine original certificate/SLSA fixture and preserves its old source and physical writer", async () => { + const { audit, record, policy } = await provenanceFixture(); + const facts = verifyProvenanceAudit(audit, [record], identity, policy); + expect(facts).toHaveLength(1); + expect(facts[0]).toMatchObject({ + name: record.name, + sourceCommit: record.origin.sourceCommit, + sourceTag: "v0.4.0", + runId: 30334062325, + attempt: 1, + }); + }); + + it("rejects missing or failed npm ECDSA/Sigstore verification results", async () => { + const { audit, record, policy } = await provenanceFixture(); + for (const changed of [ + undefined, + {}, + { ...audit, invalid: [{}] }, + { ...audit, missing: [{}] }, + { ...audit, verified: [] }, + ]) { + expect(() => + verifyProvenanceAudit(changed, [record], identity, policy), + ).toThrow(); + } + }); + + it.each([ + [ + "repository", + [ + "predicate", + "buildDefinition", + "externalParameters", + "workflow", + "repository", + ], + "https://github.com/other/repo", + ], + [ + "workflow", + [ + "predicate", + "buildDefinition", + "externalParameters", + "workflow", + "path", + ], + ".github/workflows/other.yml", + ], + [ + "tag", + ["predicate", "buildDefinition", "externalParameters", "workflow", "ref"], + "refs/tags/v0.4.3", + ], + [ + "owner", + [ + "predicate", + "buildDefinition", + "internalParameters", + "github", + "repository_owner_id", + ], + "1", + ], + [ + "repository ID", + [ + "predicate", + "buildDefinition", + "internalParameters", + "github", + "repository_id", + ], + "1", + ], + [ + "source", + [ + "predicate", + "buildDefinition", + "resolvedDependencies", + "0", + "digest", + "gitCommit", + ], + commit, + ], + [ + "builder", + ["predicate", "runDetails", "builder", "id"], + "https://example.invalid/runner", + ], + [ + "writer", + ["predicate", "runDetails", "metadata", "invocationId"], + "https://github.com/pegma-dev/storage-core/actions/runs/30334062325/attempts/2", + ], + ] as const)( + "rejects a mismatched authenticated %s claim", + async (_name, path, value) => { + const { audit, record, policy } = await provenanceFixture(); + changeClaim(audit.verified[0]!.attestationBundles[0]!, [...path], value); + expect(() => + verifyProvenanceAudit(audit, [record], identity, policy), + ).toThrow(/identity|invocation/u); + }, + ); + + it("rejects wrong subject bytes, absent certificates and ambiguous SLSA bundles", async () => { + const first = await provenanceFixture(); + changeClaim( + first.audit.verified[0]!.attestationBundles[0]!, + ["subject", "0", "digest", "sha512"], + "0".repeat(128), + ); + expect(() => + verifyProvenanceAudit( + first.audit, + [first.record], + identity, + first.policy, + ), + ).toThrow(); + const second = await provenanceFixture(); + second.audit.verified[0]!.attestationBundles[0]!.bundle.verificationMaterial = + {}; + expect(() => + verifyProvenanceAudit( + second.audit, + [second.record], + identity, + second.policy, + ), + ).toThrow(/certificate/u); + const third = await provenanceFixture(); + third.audit.verified[0]!.attestationBundles.push( + third.audit.verified[0]!.attestationBundles[0]!, + ); + expect(() => + verifyProvenanceAudit( + third.audit, + [third.record], + identity, + third.policy, + ), + ).toThrow(/ambiguous/u); + }); + + it("refuses relabeling a historical certificate as the new release source", async () => { + const { audit, record, policy } = await provenanceFixture(); + const relabeled = { + ...record, + origin: { + kind: "source" as const, + repository: "pegma-dev/storage-core" as const, + gitCommit: commit, + releaseTag: "v0.4.3", + directory: record.directory, + }, + }; + expect(() => + verifyProvenanceAudit(audit, [relabeled], identity, policy), + ).toThrow(/certificate identity/u); + }); + + it("keeps the original physical writer distinct from a later verification attempt", async () => { + const { audit, record, policy } = await provenanceFixture(); + const historicalIdentity = { + gitCommit: record.origin.sourceCommit, + releaseTag: record.origin.sourceTag, + runId: record.origin.originalRunId, + runAttempt: 2, + }; + const sourceRecord = { + ...record, + origin: { + kind: "source" as const, + repository: "pegma-dev/storage-core" as const, + gitCommit: historicalIdentity.gitCommit, + releaseTag: historicalIdentity.releaseTag, + directory: record.directory, + }, + }; + const facts = verifyProvenanceAudit( + audit, + [sourceRecord], + historicalIdentity, + policy, + ); + expect(facts[0]!.attempt).toBe(1); + expect(() => + verifyProvenanceAudit( + audit, + [sourceRecord], + { ...historicalIdentity, runId: historicalIdentity.runId + 1 }, + policy, + ), + ).toThrow(/publishing invocation/u); + }); +}); + +describe("all authenticated historical writer observations", () => { + it("checks both actual historical runs and their exact legacy writer jobs for all three reused packages", async () => { + const f = await historicalWriterFixture(); + const jobs = await verifyPublishingJobs(f.facts, { fetch: f.fetch }); + expect(jobs.map(({ id }) => id).sort()).toEqual([90195221537, 90750106220]); + expect( + jobs.every( + ({ stepName }) => stepName === "Publish verified prepared tarballs", + ), + ).toBe(true); + expect(jobs.map(({ runId }) => runId).sort()).toEqual([ + 30334062325, 30504107513, + ]); + expect(jobs.flatMap(({ packages }) => packages).join(" ")).toContain( + "@pegma/storage-core", + ); + expect(jobs.flatMap(({ packages }) => packages).join(" ")).toContain( + "@pegma/storage-azure-tables", + ); + expect(jobs.flatMap(({ packages }) => packages).join(" ")).toContain( + "@pegma/storage-cloudflare-d1", + ); + expect(f.fetch).toHaveBeenCalledTimes(4); + expect(f.fetch.mock.calls.map(([url]) => String(url))).toEqual([ + ...f.responses.keys(), + ]); + }); + + it.each([ + "run-source", + "known-job-id", + "legacy-step", + "step-window", + "incomplete-page", + "unavailable", + ] as const)( + "refuses a historical %s mismatch instead of accepting an empty job-proof set", + async (fault) => { + const f = await historicalWriterFixture(); + const runUrl = + "https://api.github.com/repos/pegma-dev/storage-core/actions/runs/30334062325"; + const page = f.responses.get(`${runUrl}/attempts/1/jobs?per_page=100`)!; + const job = (page.jobs as Array>)[0]!; + const step = (job.steps as Array>)[0]!; + if (fault === "run-source") + f.responses.get(runUrl)!.head_sha = "0".repeat(40); + else if (fault === "known-job-id") job.id = 90195221538; + else if (fault === "legacy-step") + step.name = "Verify and publish the prepared release"; + else if (fault === "step-window") { + step.started_at = "2020-01-01T00:00:00.000Z"; + step.completed_at = "2020-01-01T00:01:00.000Z"; + } else if (fault === "incomplete-page") page.total_count = 101; + else f.fetch.mockResolvedValueOnce(new Response(null, { status: 503 })); + await expect( + verifyPublishingJobs(f.facts, { fetch: f.fetch }), + ).rejects.toThrow(); + expect(f.fetch).toHaveBeenCalled(); + }, + ); +}); + +describe("publishing authority", () => { + function environment(): NodeJS.ProcessEnv { + return { + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_REPOSITORY: "pegma-dev/storage-core", + GITHUB_REPOSITORY_ID: "1312519623", + GITHUB_REPOSITORY_OWNER_ID: "309286193", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_SHA: commit, + GITHUB_REF: "refs/tags/v0.4.3", + GITHUB_WORKFLOW_SHA: commit, + GITHUB_WORKFLOW_REF: + "pegma-dev/storage-core/.github/workflows/publish.yml@refs/tags/v0.4.3", + RUNNER_ENVIRONMENT: "github-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://fixture.actions.githubusercontent.com/oidc", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "fictional-oidc-test-value", + }; + } + + it("requires the exact github-hosted source-bound token-free publishing environment", () => { + expect(() => + assertTrustedPublishingEnvironment(environment(), identity), + ).not.toThrow(); + for (const changes of [ + { RUNNER_ENVIRONMENT: undefined }, + { RUNNER_ENVIRONMENT: "self-hosted" }, + { GITHUB_SHA: "b".repeat(40) }, + { GITHUB_REPOSITORY_ID: "1" }, + { GITHUB_REPOSITORY_OWNER_ID: "1" }, + { GITHUB_EVENT_NAME: "workflow_dispatch" }, + { ACTIONS_ID_TOKEN_REQUEST_URL: "https://evil.invalid/oidc" }, + { NPM_TOKEN: "poison" }, + { NODE_AUTH_TOKEN: "poison" }, + ]) + expect(() => + assertTrustedPublishingEnvironment( + { ...environment(), ...changes }, + identity, + ), + ).toThrow(); + }); + + it("isolates local verification from credentials while retaining only explicit publishing identity", () => { + const source = { + ...environment(), + PATH: "bin", + NODE_OPTIONS: "poison", + HTTPS_PROXY: "poison", + NODE_EXTRA_CA_CERTS: "poison", + NPM_TOKEN: "poison", + npm_config_registry: "https://evil.invalid", + }; + const local = isolatedVerificationEnvironment(source, "/fixture"); + expect(local).not.toHaveProperty("RUNNER_ENVIRONMENT"); + expect(local).not.toHaveProperty("ACTIONS_ID_TOKEN_REQUEST_TOKEN"); + const publish = isolatedVerificationEnvironment(source, "/fixture", true); + expect(publish.RUNNER_ENVIRONMENT).toBe("github-hosted"); + expect(publish.GITHUB_SHA).toBe(commit); + for (const key of [ + "NODE_OPTIONS", + "HTTPS_PROXY", + "NODE_EXTRA_CA_CERTS", + "NPM_TOKEN", + ]) + expect(publish).not.toHaveProperty(key); + expect(publish.npm_config_registry).toBe(REGISTRY); + expect(publish.npm_config_ignore_scripts).toBe("true"); + }); +}); + +const npmToolUrl = "https://registry.npmjs.org/npm/-/npm-11.18.0.tgz"; +const npmToolSha256 = + "73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e"; +const maximumNpmToolBytes = 16 * 1024 * 1024; +let npmToolPromise: Promise | undefined; + +/** Real official archive, never a fabricated hash/tree. A supplied bad cache + * is an error, not permission to fetch different bytes or skip the test. */ +function officialNpmTool(): Promise { + npmToolPromise ??= (async () => { + const cached = process.env.PEGMA_TEST_NPM_ARCHIVE_PATH; + let bytes: Buffer; + if (cached !== undefined) { + const metadata = lstatSync(cached); + if ( + !metadata.isFile() || + metadata.isSymbolicLink() || + metadata.size > maximumNpmToolBytes + ) + throw new Error( + "The test npm archive cache is not a bounded regular file.", + ); + bytes = readFileSync(cached); + } else { + const response = await globalThis.fetch(npmToolUrl, { + redirect: "error", + signal: AbortSignal.timeout(20_000), + }); + if (response.status !== 200 || response.body === null) + throw new Error("The pinned official test npm archive is unavailable."); + const reader = response.body.getReader(); + const chunks: Buffer[] = []; + let length = 0; + try { + while (true) { + const next = await reader.read(); + if (next.done) break; + length += next.value.byteLength; + if (length > maximumNpmToolBytes) { + void reader.cancel().catch(() => {}); + throw new Error( + "The official test npm archive exceeds its byte bound.", + ); + } + chunks.push(Buffer.from(next.value)); + } + } finally { + reader.releaseLock(); + } + bytes = Buffer.concat(chunks, length); + } + if (digest(bytes) !== npmToolSha256) + throw new Error( + "The test npm archive differs from the pinned official bytes.", + ); + return bytes; + })(); + return npmToolPromise; +} + +async function withoutExplicitNpm(action: () => Promise): Promise { + const previous = process.env.RELEASE_NPM_CLI; + delete process.env.RELEASE_NPM_CLI; + try { + return await action(); + } finally { + if (previous === undefined) delete process.env.RELEASE_NPM_CLI; + else process.env.RELEASE_NPM_CLI = previous; + } +} + +/** Delegate real extraction, but stop at the first selected npm --version + * command. No npm version, install, signature audit, or consumer is executed, + * and no successful crypto receipt is synthesized. */ +function observingToolPorts( + bytes: Buffer, + selected: (cli: string, cwd: string) => never, +) { + const commands: Array<{ + command: string; + args: readonly string[]; + cwd: string; + }> = []; + const fetch = vi.fn(async (url: string | URL | Request) => { + expect(String(url)).toBe(npmToolUrl); + return new Response(new Uint8Array(bytes)); + }); + const run: NonNullable = async ( + command, + args, + options, + ) => { + commands.push({ command, args: [...args], cwd: options.cwd }); + if (command === "tar") { + const stdout = execFileSync(command, [...args], { + cwd: options.cwd, + env: options.env, + encoding: "utf8", + timeout: 20_000, + }); + return { status: 0, stdout, stderr: "" }; + } + if ( + command === process.execPath && + args.length === 2 && + args[1] === "--version" + ) { + const cli = args[0]; + if (cli === undefined) + throw new Error("No selected npm CLI was supplied."); + return selected(cli, options.cwd); + } + throw new Error( + "Unexpected command after the test tool-selection boundary.", + ); + }; + return { fetch, run, commands }; +} + +describe("verified official npm tool selection", () => { + it("selects the verified owned archive CLI without bundled-tree discovery, before npm execution", async () => { + const bytes = await officialNpmTool(); + const root = mkdtempSync( + join(realpathSync(tmpdir()), "storage-npm-selection-test-"), + ); + const stop = new Error("Stop before executing the selected npm CLI."); + let observed = false; + const ports = observingToolPorts(bytes, (cli, cwd) => { + observed = true; + expect(relative(cwd, cli).replaceAll("\\", "/")).toBe( + "npm-tool/package/bin/npm-cli.js", + ); + expect(realpathSync(cli)).toBe(cli); + expect( + JSON.parse( + readFileSync(join(dirname(dirname(cli)), "package.json"), "utf8"), + ).version, + ).toBe("11.18.0"); + expect(readFileSync(cli).length).toBeGreaterThan(0); + expect(cwd).not.toBe(root); + throw stop; + }); + try { + await withoutExplicitNpm(async () => { + await expect( + verifyReusedPackages( + [], + identity, + { output: join(root, "proof") }, + ports, + ), + ).rejects.toBe(stop); + }); + expect(observed).toBe(true); + expect(ports.commands.map(({ command }) => command)).toEqual([ + "tar", + process.execPath, + ]); + const source = readFileSync( + new URL("../scripts/release-registry-verify.mjs", import.meta.url), + "utf8", + ); + const start = source.indexOf("async function npmContext("); + const context = source.slice( + start, + source.indexOf("\nfunction derValue", start), + ); + expect(start).toBeGreaterThanOrEqual(0); + expect(context).not.toContain("dirname(process.execPath)"); + expect(context).not.toContain("const candidates"); + expect(context).toMatch( + /if \(cli === undefined\)\s*\{\s*cli = join\(expected,\s*"package",\s*"bin",\s*"npm-cli.js"\)/u, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, 60_000); + + it("refuses changed official tool bytes before extraction or npm execution", async () => { + const bytes = Buffer.from(await officialNpmTool()); + bytes[0] = bytes[0]! ^ 1; + const root = mkdtempSync( + join(realpathSync(tmpdir()), "storage-npm-digest-test-"), + ); + const ports = observingToolPorts(bytes, () => { + throw new Error("A changed tool must never execute."); + }); + try { + await withoutExplicitNpm(async () => { + await expect( + verifyReusedPackages( + [], + identity, + { output: join(root, "proof") }, + ports, + ), + ).rejects.toThrow("the reviewed npm tool archive differs"); + }); + expect(ports.fetch).toHaveBeenCalledTimes(1); + expect(ports.commands).toEqual([]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, 60_000); + + it.each([ + { channel: "option", corruption: "link" }, + { channel: "environment", corruption: "link" }, + { channel: "option", corruption: "bytes" }, + { channel: "environment", corruption: "bytes" }, + ] as const)( + "refuses an explicit $channel CLI with unreviewed $corruption before npm execution", + async ({ channel, corruption }) => { + const bytes = await officialNpmTool(); + const root = mkdtempSync( + join(realpathSync(tmpdir()), "storage-npm-explicit-test-"), + ); + try { + const extracted = join(root, "explicit-tool"); + mkdirSync(extracted); + const archive = join(root, "npm-official.tgz"); + writeFileSync(archive, bytes); + execFileSync("tar", ["-xzf", archive, "-C", extracted], { + timeout: 20_000, + }); + const packageRoot = join(extracted, "package"); + const cli = join(packageRoot, "bin", "npm-cli.js"); + if (corruption === "link") { + const target = join(root, "unreviewed-bin"); + mkdirSync(target); + symlinkSync(target, join(packageRoot, "unreviewed-link"), "junction"); + } else { + const metadata = join(packageRoot, "package.json"); + writeFileSync(metadata, readFileSync(metadata, "utf8") + "\n"); + } + const ports = observingToolPorts(bytes, () => { + throw new Error("A changed explicit tool must never execute."); + }); + await withoutExplicitNpm(async () => { + if (channel === "environment") process.env.RELEASE_NPM_CLI = cli; + await expect( + verifyReusedPackages( + [], + identity, + { + output: join(root, "proof"), + ...(channel === "option" ? { npmCli: cli } : {}), + }, + ports, + ), + ).rejects.toThrow( + corruption === "link" + ? "reviewed npm tree contains a link" + : "npm tool files differ from the pinned official release", + ); + }); + expect(ports.commands.map(({ command }) => command)).toEqual(["tar"]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, + 60_000, + ); +}); + +/** Exercises real orchestration over temporary files/Git and genuine archive + * fixtures. npm build/pack/audit and backend execution are CONTROLLED TOOLS: + * these tests do not qualify crypto, runtime SDK behavior or publication. */ +async function pipelineFixture() { + const historical = await historicalWriterFixture(); + const npmBytes = await officialNpmTool(); + const awsBytes = fixture("aws-client-dynamodb-3.1130.0.tgz"); + expect(digest(awsBytes)).toBe(awsClient.archiveSha256); + expect("sha512-" + digest(awsBytes, "sha512", "base64")).toBe( + awsClient.integrity, + ); + const root = mkdtempSync( + join(realpathSync(tmpdir()), "storage-pipeline-test-"), + ); + for (const file of ["package.json", "pnpm-lock.yaml", ".gitignore"]) + copyFileSync(new URL(`../${file}`, import.meta.url), join(root, file)); + for (const directory of [ + "storage-core", + "storage-azure-tables", + "storage-cloudflare-d1", + "storage-dynamodb", + ]) { + mkdirSync(join(root, "packages", directory), { recursive: true }); + for (const file of ["package.json", "README.md", "LICENSE"]) + copyFileSync( + new URL(`../packages/${directory}/${file}`, import.meta.url), + join(root, "packages", directory, file), + ); + } + const git = process.platform === "win32" ? "git.exe" : "git"; + const gitRun = (args: string[]) => + execFileSync(git, args, { cwd: root, encoding: "utf8" }).trim(); + gitRun(["init", "--quiet"]); + gitRun(["config", "user.name", "Release Pipeline Fixture"]); + gitRun(["config", "user.email", "release@example.invalid"]); + gitRun(["add", "."]); + gitRun(["-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "fixture"]); + const records = new Map( + historical.records.map((record) => [record.name, record]), + ); + const tarballs = new Map( + historical.records.map((record) => [ + record.name, + fixture(`${record.directory}-${record.version}.tgz`), + ]), + ); + const calls: Array<{ command: string; args: readonly string[] }> = []; + const consumerEvents: string[] = []; + const state = { + auditFails: false, + consumerFails: false, + lockTamper: false, + selected: "absent" as "absent" | "present" | "unknown", + acceptedPublish: false, + publishThrows: false, + auditOutput: historical.audit as unknown, + consumerDependencies: [] as Array>, + afterConsumer: undefined as (() => void) | undefined, + awsFault: undefined as AwsConsumerFault | undefined, + }; + const output = (stdout = "", status = 0) => ({ + pid: 0, + status, + signal: null, + error: undefined, + stdout, + stderr: status ? "controlled test tool failure" : "", + output: [null, stdout, ""], + }); + function command( + command: string, + args: readonly string[], + options: { cwd?: string; env?: NodeJS.ProcessEnv } = {}, + ) { + calls.push({ command, args: [...args] }); + const cwd = options.cwd ?? root; + if (command === "tar" || command === git || command === "git") + return output( + execFileSync(command, [...args], { + cwd, + env: options.env, + encoding: "utf8", + timeout: 20_000, + }), + ); + if (command === "npm" || command === "npm.cmd") { + if (args[0] === "run" && args[1] === "build") return output(); + if (args[0] === "pack") { + const directory = args[1]!; + const metadata = JSON.parse( + readFileSync(join(directory, "package.json"), "utf8"), + ); + const targets = Object.values( + metadata.exports as Record>, + ).flatMap((target) => + typeof target === "string" ? [target] : Object.values(target), + ); + const additional = [...new Set(targets)] + .filter( + (target) => + !["./dist/index.js", "./dist/index.d.ts"].includes(target), + ) + .map((target) => ({ + path: "package/" + target.slice(2), + body: "export {};", + })); + const bytes = archive(additional, metadata); + const inspected = inspectReleaseTarball(bytes); + const tarball = `${metadata.name.slice(1).replace("/", "-")}-${metadata.version}.tgz`; + const destination = args[args.indexOf("--pack-destination") + 1]!; + writeFileSync(join(destination, tarball), bytes); + const record: PreparedPackage = { + name: metadata.name, + version: metadata.version, + directory: basename(directory), + tarball, + size: bytes.length, + sha256: digest(bytes), + shasum: digest(bytes, "sha1"), + integrity: `sha512-${digest(bytes, "sha512", "base64")}`, + publish: true, + package: inspected.package, + files: inspected.files, + origin: { + kind: "source", + repository: "pegma-dev/storage-core", + gitCommit: gitRun(["rev-parse", "HEAD"]), + releaseTag: "v0.4.3", + directory: basename(directory), + }, + }; + records.set(record.name, record); + tarballs.set(record.name, bytes); + return output( + JSON.stringify([ + { + name: record.name, + version: record.version, + filename: tarball, + integrity: record.integrity, + shasum: record.shasum, + }, + ]), + ); + } + if (args[0] === "--version") return output("11.18.0\n"); + if (args[0] === "publish") { + state.acceptedPublish = true; + state.selected = "present"; + return output( + "CONTROLLED_PUBLISH_TOOL_ONLY", + state.publishThrows ? 1 : 0, + ); + } + } + if (command === process.execPath && args[0]?.endsWith("npm-cli.js")) { + if (args[1] === "--version") return output("11.18.0\n"); + if (args[1] === "install") { + const input = JSON.parse( + readFileSync(join(cwd, "package.json"), "utf8"), + ); + if (input.name === "storage-public-consumer") { + consumerEvents.push("consumer-install"); + state.consumerDependencies.push(structuredClone(input.dependencies)); + } + const packages: Record = {}; + for (const record of records.values()) { + if (!Object.hasOwn(input.dependencies, record.name)) continue; + const requested = input.dependencies[record.name] as string; + packages[`node_modules/${record.name}`] = { + version: record.version, + resolved: requested.startsWith("file:") + ? requested + : canonicalTarball(record), + integrity: + state.lockTamper && record.name === "@pegma/storage-core" + ? "sha512-invalid" + : record.integrity, + }; + } + if (input.name === "storage-public-consumer") { + const sdkKey = "node_modules/" + awsClient.name; + const sdkLock = { + version: + state.awsFault === "lock-version" + ? "3.1131.0" + : awsClient.version, + resolved: + state.awsFault === "lock-url" + ? "https://unreviewed.invalid/client.tgz" + : awsClient.tarballUrl, + integrity: + state.awsFault === "lock-integrity" + ? "sha512-unreviewed" + : awsClient.integrity, + ...(state.awsFault === "lock-link" ? { link: true } : {}), + }; + if (state.awsFault !== "lock-missing") packages[sdkKey] = sdkLock; + if (state.awsFault === "nested-version") + packages["node_modules/@pegma/storage-dynamodb/" + sdkKey] = { + ...sdkLock, + version: "3.1131.0", + }; + const sdkDirectory = join(cwd, sdkKey); + mkdirSync(dirname(sdkDirectory), { recursive: true }); + let actualSdkDirectory = sdkDirectory; + if (state.awsFault === "installed-directory-link") { + actualSdkDirectory = join(cwd, "controlled-linked-aws-client"); + mkdirSync(actualSdkDirectory); + symlinkSync( + actualSdkDirectory, + sdkDirectory, + process.platform === "win32" ? "junction" : "dir", + ); + } else mkdirSync(sdkDirectory); + // Controlled install metadata, not executable AWS SDK contents. The + // independent genuine archive admission is exercised separately. + writeFileSync( + join(actualSdkDirectory, "package.json"), + JSON.stringify({ + name: + state.awsFault === "installed-name" + ? "@aws-sdk/other-client" + : awsClient.name, + version: + state.awsFault === "installed-version" + ? "3.1131.0" + : awsClient.version, + }), + ); + } + writeFileSync( + join(cwd, "package-lock.json"), + JSON.stringify({ packages }), + ); + return output("CONTROLLED_INSTALL_TOOL_ONLY"); + } + if (args[1] === "audit") + return output( + JSON.stringify(state.auditOutput), + state.auditFails ? 1 : 0, + ); + } + if ( + command === process.execPath && + args.includes("--experimental-strip-types") + ) { + consumerEvents.push("consumer-command"); + const source = readFileSync(join(cwd, "consumer.mjs"), "utf8"); + expect(source).toContain('from "@pegma/storage-core/conformance"'); + expect(source).toContain('from "@pegma/storage-dynamodb"'); + expect(source).toContain("e instanceof StorageError"); + expect(source).toContain("e instanceof ConcurrencyError"); + state.afterConsumer?.(); + return output( + JSON.stringify({ + status: "TEST_STUB_UNEXECUTED_PUBLIC_CONSUMER", + qualification: "UNQUALIFIED_STUBS", + publicConsumerExecuted: false, + cryptographicVerificationExecuted: false, + }), + state.consumerFails ? 1 : 0, + ); + } + throw new Error( + `Unexpected controlled command: ${command} ${args[0] ?? ""}`, + ); + } + const fetch: typeof globalThis.fetch = async (url) => { + const address = String(url); + if (address === npmToolUrl) return new Response(new Uint8Array(npmBytes)); + if ( + address === + REGISTRY + encodeURIComponent(awsClient.name) + "/" + awsClient.version + ) { + consumerEvents.push("aws-metadata"); + return Response.json({ + name: + state.awsFault === "metadata-name" + ? "@aws-sdk/other-client" + : awsClient.name, + version: + state.awsFault === "metadata-version" + ? "3.1131.0" + : awsClient.version, + dist: { + tarball: + state.awsFault === "metadata-url" + ? "https://unreviewed.invalid/client.tgz" + : awsClient.tarballUrl, + integrity: + state.awsFault === "metadata-integrity" + ? "sha512-unreviewed" + : awsClient.integrity, + }, + }); + } + if (address === awsClient.tarballUrl) { + consumerEvents.push("aws-archive"); + const bytes = Buffer.from(awsBytes); + if (state.awsFault === "archive-bytes") bytes[0] = bytes[0]! ^ 1; + return new Response(new Uint8Array(bytes)); + } + if (historical.responses.has(address)) + return Response.json(historical.responses.get(address)); + for (const record of records.values()) { + if ( + address === + `${REGISTRY}${encodeURIComponent(record.name)}/${record.version}` + ) { + if (record.publish && state.selected !== "present") + return new Response(null, { + status: state.selected === "unknown" ? 503 : 404, + }); + return Response.json({ + name: record.name, + version: record.version, + dist: { + integrity: record.integrity, + shasum: record.shasum, + tarball: canonicalTarball(record), + signatures: [ + { + keyid: "CONTROLLED_METADATA_NOT_SIGNATURE_VERIFICATION", + sig: "unit-fixture", + }, + ], + }, + }); + } + if (address === canonicalTarball(record)) + return new Response(new Uint8Array(tarballs.get(record.name)!)); + } + throw new Error("Unexpected controlled fetch URL."); + }; + const seams: VerificationSeams = { + fetch, + run: async (cmd, args, options) => { + const result = command(cmd, args, options); + return { + status: result.status, + stdout: result.stdout, + stderr: result.stderr, + }; + }, + }; + return { + root, + records, + tarballs, + historical, + state, + calls, + consumerEvents, + command, + seams, + gitRun, + }; +} + +/** Enables only orchestration coverage at the existing scripted npm boundary. + * The selected candidate's certificate/SLSA are deliberately invalidated and + * have NO DSSE signature. This must never be used as registry qualification. */ +function enableUnqualifiedRegistryOnlyStub( + f: Awaited>, + manifest: PreparedManifest, +) { + const selected = manifest.packages.filter(({ publish }) => publish); + expect(selected).toHaveLength(1); + const record = selected[0]!; + expect(record.name).toBe("@pegma/storage-dynamodb"); + expect(manifest.releaseTag).toBe("v0.4.3"); + const bundle = JSON.parse( + fixture("core040-slsa.json").toString("utf8"), + ) as BundleFixture; + const material = bundle.bundle.verificationMaterial as { + certificate: { rawBytes: string }; + }; + const certificate = Buffer.from(material.certificate.rawBytes, "base64"); + const oldSan = Buffer.from( + "https://github.com/pegma-dev/storage-core/.github/workflows/publish.yml@refs/tags/v0.4.0", + ); + const stubSan = Buffer.from( + "https://github.com/pegma-dev/storage-core/.github/workflows/publish.yml@refs/tags/" + + manifest.releaseTag, + ); + // Same-length replacement preserves DER structure for the real claim parser + // while invalidating its signature; no certificate or attestation is signed. + expect(stubSan.length).toBe(oldSan.length); + let replacements = 0; + for ( + let offset = certificate.indexOf(oldSan); + offset !== -1; + offset = certificate.indexOf(oldSan, offset + oldSan.length) + ) { + stubSan.copy(certificate, offset); + replacements += 1; + } + expect(replacements).toBeGreaterThan(0); + material.certificate.rawBytes = certificate.toString("base64"); + bundle.bundle.dsseEnvelope.signatures = []; + changeClaim( + bundle, + ["subject"], + [ + { + name: + "pkg:npm/" + + record.name.split("/").map(encodeURIComponent).join("/") + + "@" + + record.version, + digest: { + sha512: Buffer.from(record.integrity.slice(7), "base64").toString( + "hex", + ), + }, + }, + ], + ); + changeClaim( + bundle, + ["predicate", "buildDefinition", "externalParameters", "workflow", "ref"], + "refs/tags/" + manifest.releaseTag, + ); + changeClaim( + bundle, + ["predicate", "buildDefinition", "resolvedDependencies"], + [ + { + uri: + "git+https://github.com/pegma-dev/storage-core@refs/tags/" + + manifest.releaseTag, + digest: { gitCommit: manifest.gitCommit }, + }, + ], + ); + changeClaim( + bundle, + ["predicate", "runDetails", "metadata", "invocationId"], + "https://github.com/pegma-dev/storage-core/actions/runs/12345/attempts/1", + ); + f.state.auditOutput = { + ...f.historical.audit, + qualification: "UNQUALIFIED_STUBS", + verified: [ + ...f.historical.audit.verified, + { + name: record.name, + version: record.version, + location: "node_modules/" + record.name, + registry: REGISTRY, + attestationBundles: [bundle], + }, + ], + }; + const runUrl = + "https://api.github.com/repos/pegma-dev/storage-core/actions/runs/12345"; + f.historical.responses.set(runUrl, { + id: 12345, + head_sha: manifest.gitCommit, + head_branch: manifest.releaseTag, + run_attempt: 2, + event: "release", + path: ".github/workflows/publish.yml", + repository: { id: 1312519623, owner: { id: 309286193 } }, + }); + f.historical.responses.set(`${runUrl}/attempts/1/jobs?per_page=100`, { + qualification: "UNQUALIFIED_STUBS", + total_count: 1, + jobs: [ + { + id: 1234501, + run_id: 12345, + run_attempt: 1, + head_branch: manifest.releaseTag, + head_sha: manifest.gitCommit, + name: "publish", + status: "completed", + conclusion: "failure", + started_at: "2026-07-28T06:13:43.000Z", + completed_at: "2026-07-28T06:14:49.000Z", + steps: [ + { + name: "Verify and publish the prepared release", + status: "completed", + conclusion: "failure", + started_at: "2026-07-28T06:13:49.000Z", + completed_at: "2026-07-28T06:14:47.000Z", + }, + ], + }, + ], + }); + f.state.selected = "present"; +} + +async function controlledPrepare( + f: Awaited>, + output?: string, + skipSmoke = false, +) { + vi.resetModules(); + vi.doMock("node:child_process", async (importOriginal) => ({ + ...(await importOriginal()), + spawnSync: f.command, + })); + vi.stubGlobal("fetch", f.seams.fetch); + try { + const { prepareRelease } = await import("../scripts/release-packages.mjs"); + return await withoutExplicitNpm(() => + prepareRelease({ + root: f.root, + requireClean: true, + releaseTag: "v0.4.3", + ...(skipSmoke ? { skipSmoke: true } : {}), + ...(output === undefined ? {} : { output }), + }), + ); + } finally { + vi.unstubAllGlobals(); + vi.doUnmock("node:child_process"); + vi.resetModules(); + } +} + +/** Execute the actual workflow SEAL with the real strict manifest reader. + * The temp re-export changes only module location, never validation behavior. + * No upload action, npm audit, SDK runtime or registry qualification is claimed. */ +function actualInventorySeal( + f: Awaited>, + prepared: { manifestPath: string; manifest: PreparedManifest }, + change?: (directory: string, scripts: string) => void, +) { + const runner = mkdtempSync( + join(realpathSync(tmpdir()), "storage-seal-test-"), + ); + try { + const directory = join(runner, "storage-prepared"); + mkdirSync(directory); + for (const name of [ + "package-manifest.json", + ...prepared.manifest.packages.map(({ tarball }) => tarball), + ]) + copyFileSync( + join(dirname(prepared.manifestPath), name), + join(directory, name), + ); + const scripts = join(f.root, "scripts"); + mkdirSync(scripts, { recursive: true }); + const actualReader = new URL( + "../scripts/release-packages.mjs", + import.meta.url, + ).href; + writeFileSync( + join(scripts, "release-packages.mjs"), + `export {verifyPreparedManifest} from ${JSON.stringify(actualReader)};\n`, + ); + copyFileSync( + new URL("../scripts/release-reuse-policy.json", import.meta.url), + join(scripts, "release-reuse-policy.json"), + ); + change?.(directory, scripts); + const workflow = readFileSync( + new URL("../.github/workflows/publish.yml", import.meta.url), + "utf8", + ).replace(/\r\n/gu, "\n"); + const match = /<<'SEAL'\n([^]*?)\n SEAL/u.exec(workflow); + if (match === null) + throw new Error("Actual workflow seal heredoc was not found."); + const source = match[1]! + .split("\n") + .map((line) => line.replace(/^ {10}/u, "")) + .join("\n"); + const output = join(runner, "outputs"); + const result = spawnSync(process.execPath, ["--input-type=module"], { + cwd: f.root, + // A seal must not start unused registry verification, even for all-source. + input: + 'globalThis.fetch = () => { throw new Error("No registry verification is allowed while sealing"); };\n' + + source, + encoding: "utf8", + timeout: 20_000, + env: { + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + HOME: tmpdir(), + TMP: tmpdir(), + RUNNER_TEMP: runner, + RELEASE_COMMIT: prepared.manifest.gitCommit, + RELEASE_TAG: prepared.manifest.releaseTag!, + GITHUB_OUTPUT: output, + }, + }); + const text = existsSync(output) ? readFileSync(output, "utf8") : undefined; + return { + result, + output: text, + outputs: + text === undefined + ? undefined + : Object.fromEntries( + text + .trim() + .split("\n") + .map((line) => { + const separator = line.indexOf("="); + return [line.slice(0, separator), line.slice(separator + 1)]; + }), + ), + files: readdirSync(directory).sort(), + }; + } finally { + rmSync(runner, { recursive: true, force: true }); + } +} + +async function actualInlinePublisher( + f: Awaited>, + manifestPath: string, + manifest: PreparedManifest, + preflightDirectory: string, +) { + const workflow = readFileSync( + new URL("../.github/workflows/publish.yml", import.meta.url), + "utf8", + ); + const match = /<<'NODE'\r?\n([^]*?)\r?\n NODE/u.exec(workflow); + if (!match) throw new Error("The actual minimal publisher was not found."); + const original = match[1]! + .split(/\r?\n/u) + .map((line) => line.replace(/^ {10}/u, "")) + .join("\n"); + const body = original.replace( + /^import\s+\{[^]*?\}\s+from\s+"node:[^"]+";\n/gmu, + "", + ); + expect(body).not.toMatch(/^import /mu); + const policy = readFileSync( + new URL("../scripts/release-reuse-policy.json", import.meta.url), + ); + const env: NodeJS.ProcessEnv = { + PATH: process.env.PATH, + SYSTEMROOT: process.env.SystemRoot, + RUNNER_TEMP: f.root, + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_REPOSITORY: "pegma-dev/storage-core", + GITHUB_REPOSITORY_ID: "1312519623", + GITHUB_REPOSITORY_OWNER_ID: "309286193", + GITHUB_SHA: manifest.gitCommit, + GITHUB_WORKFLOW_SHA: manifest.gitCommit, + GITHUB_REF: "refs/tags/" + manifest.releaseTag, + GITHUB_WORKFLOW_REF: + "pegma-dev/storage-core/.github/workflows/publish.yml@refs/tags/" + + manifest.releaseTag, + GITHUB_RUN_ID: "12345", + GITHUB_RUN_ATTEMPT: "2", + RUNNER_ENVIRONMENT: "github-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://unit-fixture.actions.githubusercontent.com/oidc", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "UNIT_STUB_NOT_AN_OIDC_CREDENTIAL", + RELEASE_TAG: manifest.releaseTag!, + RELEASE_COMMIT: manifest.gitCommit, + RELEASE_DIRECTORY: dirname(manifestPath), + PREFLIGHT_DIRECTORY: preflightDirectory, + EXPECTED_MANIFEST_DIGEST: digest(readFileSync(manifestPath)), + EXPECTED_POLICY_DIGEST: digest(policy), + REGISTRY_POLICY_BASE64: policy.toString("base64"), + EXPECTED_PREFLIGHT_DIGEST: digest( + readFileSync(join(preflightDirectory, "preflight.json")), + ), + }; + const messages: string[] = []; + const bindings = { + spawnSync: f.command, + createHash, + timingSafeEqual, + constants, + chmod: fsPromises.chmod, + copyFile: fsPromises.copyFile, + lstat: fsPromises.lstat, + mkdtemp: fsPromises.mkdtemp, + open: fsPromises.open, + readFile: fsPromises.readFile, + readdir: fsPromises.readdir, + realpath: fsPromises.realpath, + rm: fsPromises.rm, + writeFile: fsPromises.writeFile, + basename, + dirname, + join, + resolve, + tmpdir, + fetch: f.seams.fetch, + process: { + env, + stdout: { + write: (text: string) => { + messages.push(text); + }, + }, + }, + setTimeout: (callback: () => void) => { + callback(); + return 0; + }, + }; + // Execute the actual workflow source with only its external command/network + // ports controlled. The fake OIDC string never leaves this in-process test. + const execute = new Function( + "bindings", + `return (async()=>{const {${Object.keys(bindings).join(",")}}=bindings;\n${body}\n})();`, + ) as (ports: typeof bindings) => Promise; + await execute(bindings); + return messages; +} + +describe("controlled real release orchestration (not release qualification)", () => { + it("prepares an all-selected unsigned fixture without unused reuse verification and seals explicit false", async () => { + const f = await pipelineFixture(); + try { + for (const directory of [ + "storage-core", + "storage-azure-tables", + "storage-cloudflare-d1", + "storage-dynamodb", + ]) { + const path = join(f.root, "packages", directory, "package.json"); + const metadata = JSON.parse(readFileSync(path, "utf8")); + metadata.version = "0.4.3"; + if (metadata.dependencies?.["@pegma/storage-core"] !== undefined) + metadata.dependencies["@pegma/storage-core"] = "0.4.3"; + writeFileSync(path, JSON.stringify(metadata)); + } + const rootManifestPath = join(f.root, "package.json"); + const rootManifest = JSON.parse(readFileSync(rootManifestPath, "utf8")); + rootManifest.devDependencies["@pegma/storage-cloudflare-d1"] = + "workspace:0.4.3"; + writeFileSync(rootManifestPath, JSON.stringify(rootManifest)); + const lockPath = join(f.root, "pnpm-lock.yaml"); + writeFileSync( + lockPath, + readFileSync(lockPath, "utf8") + .replaceAll("workspace:0.4.1", "workspace:0.4.3") + .replaceAll("specifier: 0.4.0", "specifier: 0.4.3"), + ); + f.gitRun(["add", "."]); + f.gitRun([ + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "-m", + "fictional all-selected source", + ]); + // Only future-shaped preparation is exercised. No future Core runtime or + // public-consumer compatibility is claimed by these unsigned archives. + const prepared = await controlledPrepare(f, undefined, true); + expect(prepared.manifest.packages.map(({ publish }) => publish)).toEqual([ + true, + true, + true, + true, + ]); + const expectedFiles = [ + "package-manifest.json", + ...prepared.manifest.packages.map(({ tarball }) => tarball), + ].sort(); + expect(readdirSync(dirname(prepared.manifestPath)).sort()).toEqual( + expectedFiles, + ); + expect(expectedFiles).toHaveLength(5); + expect(f.calls.filter(({ args }) => args[0] === "pack")).toHaveLength(4); + expect( + f.calls.some( + ({ command, args }) => + command === "tar" || + args.includes("audit") || + args.includes("--experimental-strip-types"), + ), + ).toBe(false); + expect(existsSync(join(f.root, ".release-reuse-verification"))).toBe( + false, + ); + expect(existsSync(join(f.root, ".release-consumer-verification"))).toBe( + false, + ); + const sealed = actualInventorySeal(f, prepared); + expect(sealed.result.error).toBeUndefined(); + expect(sealed.result.status, sealed.result.stderr).toBe(0); + expect(sealed.files).toEqual(expectedFiles); + expect(sealed.outputs).toEqual({ + manifest_digest: digest(readFileSync(prepared.manifestPath)), + policy_digest: prepared.manifest.registryPolicySha256, + policy_base64: readFileSync( + new URL("../scripts/release-reuse-policy.json", import.meta.url), + ).toString("base64"), + reuse_required: "false", + }); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it("admits the genuine reviewed AWS archive and pins the direct consumer root without claiming runtime or crypto execution", async () => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + const output = join(f.root, "reviewed-aws-consumer"); + mkdirSync(output); + const eventsBefore = f.consumerEvents.length; + const result = await withoutExplicitNpm(() => + runPublicConsumer(prepared.manifest, { output }, f.seams), + ); + expect(f.consumerEvents.slice(eventsBefore)).toEqual([ + "aws-metadata", + "aws-archive", + "consumer-install", + "consumer-command", + ]); + expect(result).toMatchObject({ + qualification: "UNQUALIFIED_STUBS", + publicConsumerExecuted: false, + cryptographicVerificationExecuted: false, + }); + expect(f.state.consumerDependencies.at(-1)?.[awsClient.name]).toBe( + awsClient.version, + ); + const dynamo = prepared.manifest.packages.find( + ({ name }) => name === "@pegma/storage-dynamodb", + )!; + expect( + (dynamo.package.dependencies as Record)[awsClient.name], + ).toBe("^3.1097.0"); + const admittedArchive = readFileSync( + join(output, "consumer-aws-sdk.tgz"), + ); + expect(admittedArchive).toEqual( + fixture("aws-client-dynamodb-3.1130.0.tgz"), + ); + expect(digest(admittedArchive)).toBe(awsClient.archiveSha256); + const metadata = readFileSync( + join(output, "consumer-aws-sdk-metadata.json"), + ); + expect(JSON.parse(metadata.toString("utf8"))).toEqual({ + name: awsClient.name, + version: awsClient.version, + dist: { tarball: awsClient.tarballUrl, integrity: awsClient.integrity }, + }); + expect( + JSON.parse( + readFileSync(join(output, "consumer-aws-sdk-admission.json"), "utf8"), + ), + ).toEqual({ + name: awsClient.name, + version: awsClient.version, + integrity: awsClient.integrity, + tarballUrl: awsClient.tarballUrl, + archiveSha256: awsClient.archiveSha256, + archiveBytes: admittedArchive.length, + metadataSha256: digest(metadata), + scope: + "Pinned direct consumer root only; no transitive or AWS provenance qualification", + }); + const lock = JSON.parse( + readFileSync(join(output, "public-consumer-lock.json"), "utf8"), + ); + expect(lock.packages["node_modules/" + awsClient.name]).toEqual({ + version: awsClient.version, + resolved: awsClient.tarballUrl, + integrity: awsClient.integrity, + }); + expect(f.calls.some(({ args }) => args[0] === "publish")).toBe(false); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it.each([ + { + fault: "metadata-name", + error: "reviewed consumer AWS SDK metadata differs", + }, + { + fault: "metadata-version", + error: "reviewed consumer AWS SDK metadata differs", + }, + { + fault: "metadata-url", + error: "reviewed consumer AWS SDK metadata differs", + }, + { + fault: "metadata-integrity", + error: "reviewed consumer AWS SDK metadata differs", + }, + { + fault: "archive-bytes", + error: "reviewed consumer AWS SDK archive differs", + }, + { fault: "lock-missing", error: "public consumer AWS SDK root is missing" }, + { + fault: "lock-version", + error: "public consumer resolved an unexpected AWS SDK", + }, + { + fault: "lock-link", + error: "public consumer resolved an unexpected AWS SDK", + }, + { + fault: "lock-url", + error: "public consumer resolved an unexpected AWS SDK", + }, + { + fault: "lock-integrity", + error: "public consumer resolved an unexpected AWS SDK", + }, + { + fault: "installed-name", + error: "public consumer AWS SDK file identity differs", + }, + { + fault: "installed-version", + error: "public consumer AWS SDK file identity differs", + }, + { + fault: "installed-directory-link", + error: "public consumer AWS SDK files have an unexpected origin", + }, + { + fault: "nested-version", + error: "public consumer resolved an unexpected AWS SDK", + }, + ] as const)( + "refuses $fault before any public consumer command", + async ({ fault, error }) => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + const output = join(f.root, "refused-aws-" + fault); + mkdirSync(output); + f.state.awsFault = fault; + const eventsBefore = f.consumerEvents.length; + const callsBefore = f.calls.length; + await withoutExplicitNpm(async () => { + await expect( + runPublicConsumer(prepared.manifest, { output }, f.seams), + ).rejects.toThrow(error); + }); + const beforeInstall = + fault.startsWith("metadata-") || fault === "archive-bytes"; + const events = f.consumerEvents.slice(eventsBefore); + expect(events).toEqual( + fault.startsWith("metadata-") + ? ["aws-metadata"] + : beforeInstall + ? ["aws-metadata", "aws-archive"] + : ["aws-metadata", "aws-archive", "consumer-install"], + ); + expect( + f.calls + .slice(callsBefore) + .filter(({ args }) => args[1] === "install"), + ).toHaveLength(beforeInstall ? 0 : 1); + expect( + f.calls + .slice(callsBefore) + .some(({ args }) => args.includes("--experimental-strip-types")), + ).toBe(false); + expect(existsSync(join(output, "public-consumer.stdout"))).toBe(false); + expect(existsSync(join(output, "verification.json"))).toBe(false); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, + 180_000, + ); + + it("preserves prior evidence on retry and accepts a separately fresh output namespace", async () => { + const f = await pipelineFixture(); + const fresh = f.root + "-fresh-output"; + try { + const first = await controlledPrepare(f); + const before = digest(readFileSync(first.manifestPath)); + const calls = f.calls.length; + await expect(controlledPrepare(f)).rejects.toThrow( + /preserve existing evidence and choose a fresh --output/u, + ); + expect(f.calls).toHaveLength(calls); + const second = await controlledPrepare(f, fresh); + expect(dirname(second.manifestPath)).toBe(fresh); + expect(digest(readFileSync(first.manifestPath))).toBe(before); + expect(f.gitRun(["status", "--porcelain"])).toBe(""); + } finally { + for (const path of [ + fresh, + fresh + "-reuse-verification", + fresh + "-consumer-verification", + f.root, + ]) + rmSync(path, { recursive: true, force: true }); + } + }, 180_000); + + it("prepares selected source only, preserves exact originals, checks all historical writers and runs the public consumer command", async () => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + expect( + f.calls + .filter(({ args }) => args[0] === "pack") + .map(({ args }) => basename(args[1]!)), + ).toEqual(["storage-dynamodb"]); + expect(prepared.manifest.packages.map(({ publish }) => publish)).toEqual([ + false, + false, + false, + true, + ]); + for (const record of prepared.manifest.packages.filter( + ({ publish }) => !publish, + )) + expect( + digest( + readFileSync(join(dirname(prepared.manifestPath), record.tarball)), + ), + ).toBe(record.sha256); + const jobs = JSON.parse( + readFileSync( + join(f.root, ".release-reuse-verification", "publishing-jobs.json"), + "utf8", + ), + ); + expect(jobs).toHaveLength(2); + expect( + readFileSync( + join( + f.root, + ".release-consumer-verification", + "public-consumer.stdout", + ), + "utf8", + ), + ).toContain("TEST_STUB_UNEXECUTED_PUBLIC_CONSUMER"); + expect(f.gitRun(["status", "--porcelain"])).toBe(""); + const options = { + root: f.root, + manifest: prepared.manifestPath, + expectedReleaseCommit: prepared.manifest.gitCommit, + expectedManifestSha256: digest(readFileSync(prepared.manifestPath)), + output: join(f.root, "preflight-proof"), + runId: 12345, + runAttempt: 2, + }; + const preflight = await withoutExplicitNpm(() => + preflightRegistry(prepared.manifest, options, f.seams), + ); + expect(preflight.decisions).toEqual( + prepared.manifest.packages.map(({ name, version, publish }) => ({ + name, + version, + action: publish ? "publish" : "skip", + })), + ); + const callsBefore = f.calls.length; + await withoutExplicitNpm(async () => { + await expect( + verifyRegistryRelease( + prepared.manifest, + { ...options, output: join(f.root, "postflight-proof") }, + f.seams, + ), + ).rejects.toThrow("complete release is not visible"); + }); + expect( + f.calls + .slice(callsBefore) + .some(({ args }) => args.includes("--experimental-strip-types")), + ).toBe(false); + const sealed = actualInventorySeal(f, prepared); + expect(sealed.result.error).toBeUndefined(); + expect(sealed.result.status, sealed.result.stderr).toBe(0); + expect(sealed.files).toEqual( + [ + "package-manifest.json", + ...prepared.manifest.packages.map(({ tarball }) => tarball), + ].sort(), + ); + expect(sealed.files).toHaveLength(5); + expect(sealed.outputs).toEqual({ + manifest_digest: digest(readFileSync(prepared.manifestPath)), + policy_digest: prepared.manifest.registryPolicySha256, + policy_base64: readFileSync( + new URL("../scripts/release-reuse-policy.json", import.meta.url), + ).toString("base64"), + reuse_required: "true", + }); + for (const fault of [ + "extra-file", + "missing-tarball", + "tar-bytes", + "invalid-origin", + "source-identity", + "policy-drift", + ] as const) { + const refused = actualInventorySeal( + f, + prepared, + (directory, scripts) => { + if (fault === "extra-file") + writeFileSync( + join(directory, "unexpected.txt"), + "not in the sealed inventory", + ); + else if (fault === "missing-tarball") + rmSync(join(directory, prepared.manifest.packages[0]!.tarball)); + else if (fault === "tar-bytes") { + const path = join( + directory, + prepared.manifest.packages[0]!.tarball, + ); + writeFileSync( + path, + Buffer.concat([readFileSync(path), Buffer.from("changed")]), + ); + } else if (fault === "policy-drift") { + const path = join(scripts, "release-reuse-policy.json"); + writeFileSync(path, readFileSync(path, "utf8") + "\n"); + } else { + const path = join(directory, "package-manifest.json"); + const malformed = JSON.parse(readFileSync(path, "utf8")); + if (fault === "source-identity") + malformed.gitCommit = "f".repeat(40); + else malformed.packages.at(-1).origin = {}; + writeFileSync(path, JSON.stringify(malformed)); + } + }, + ); + expect(refused.result.error).toBeUndefined(); + expect(refused.result.status).toBe(1); + expect(refused.result.stderr).toContain( + fault === "invalid-origin" + ? "selected source origin differs from the release" + : fault === "source-identity" + ? "prepared manifest does not match the current approved checkout" + : fault === "policy-drift" + ? "Release inventory changed during sealing" + : fault === "tar-bytes" + ? "prepared artifact is not the original regular file" + : "release output inventory does not match the package manifest", + ); + expect(refused.output).toBeUndefined(); + expect(refused.outputs).toBeUndefined(); + } + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it("completes registry-only final receipt orchestration with explicit UNQUALIFIED_STUBS, never release qualification", async () => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + enableUnqualifiedRegistryOnlyStub(f, prepared.manifest); + const output = join(f.root, "unqualified-postflight"); + const callsBefore = f.calls.length; + const consumerInputsBefore = f.state.consumerDependencies.length; + const result = await withoutExplicitNpm(() => + verifyRegistryRelease( + prepared.manifest, + { + root: f.root, + manifest: prepared.manifestPath, + expectedReleaseCommit: prepared.manifest.gitCommit, + expectedManifestSha256: digest(readFileSync(prepared.manifestPath)), + output, + runId: 12345, + runAttempt: 2, + }, + f.seams, + ), + ); + const audited = JSON.parse( + readFileSync(join(output, "npm-audit-signatures.json"), "utf8"), + ); + expect(audited.qualification).toBe("UNQUALIFIED_STUBS"); + expect( + audited.verified.at(-1).attestationBundles[0].bundle.dsseEnvelope + .signatures, + ).toEqual([]); + expect(result).toMatchObject({ + status: "STORAGE_REGISTRY_CRYPTO_SOURCE_PUBLIC_CONSUMER_PASS", + decisions: prepared.manifest.packages.map(({ name, version }) => ({ + name, + version, + action: "skip", + })), + consumer: { + status: "TEST_STUB_UNEXECUTED_PUBLIC_CONSUMER", + qualification: "UNQUALIFIED_STUBS", + publicConsumerExecuted: false, + cryptographicVerificationExecuted: false, + }, + registryProof: { + auditSha256: digest( + readFileSync(join(output, "npm-audit-signatures.json")), + ), + lockSha256: digest(readFileSync(join(output, "package-lock.json"))), + publishingJobs: expect.arrayContaining([ + expect.objectContaining({ + id: 1234501, + attempt: 1, + conclusion: "failure", + sourceCommit: prepared.manifest.gitCommit, + packages: ["@pegma/storage-dynamodb"], + }), + ]), + }, + }); + expect( + JSON.parse(readFileSync(join(output, "verification.json"), "utf8")), + ).toEqual(result); + expect(f.state.consumerDependencies).toHaveLength( + consumerInputsBefore + 1, + ); + const dynamo = prepared.manifest.packages.find( + ({ name }) => name === "@pegma/storage-dynamodb", + )!; + expect(f.state.consumerDependencies.at(-1)).toEqual({ + ...Object.fromEntries( + prepared.manifest.packages.map(({ name, version }) => [ + name, + version, + ]), + ), + "@aws-sdk/client-dynamodb": awsClient.version, + }); + expect( + (dynamo.package.dependencies as Record)[awsClient.name], + ).toBe("^3.1097.0"); + expect( + f.calls + .slice(callsBefore) + .filter(({ args }) => args.includes("--experimental-strip-types")), + ).toHaveLength(1); + expect(f.calls.some(({ args }) => args[0] === "publish")).toBe(false); + const consumerLock = JSON.parse( + readFileSync(join(output, "public-consumer-lock.json"), "utf8"), + ); + for (const record of prepared.manifest.packages) + expect(consumerLock.packages["node_modules/" + record.name]).toEqual({ + version: record.version, + integrity: record.integrity, + resolved: canonicalTarball(record), + }); + expect(consumerLock.packages["node_modules/" + awsClient.name]).toEqual({ + version: awsClient.version, + resolved: awsClient.tarballUrl, + integrity: awsClient.integrity, + }); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it.each(["consumer", "retained-audit", "retained-lock", "manifest"] as const)( + "withholds the final receipt after UNQUALIFIED_STUBS %s failure or post-consumer tampering", + async (fault) => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + enableUnqualifiedRegistryOnlyStub(f, prepared.manifest); + const output = join(f.root, "unqualified-postflight-" + fault); + const manifestHash = digest(readFileSync(prepared.manifestPath)); + f.state.consumerFails = fault === "consumer"; + f.state.afterConsumer = () => { + const path = + fault === "retained-audit" + ? join(output, "npm-audit-signatures.json") + : fault === "retained-lock" + ? join(output, "package-lock.json") + : fault === "manifest" + ? prepared.manifestPath + : undefined; + if (path !== undefined) + writeFileSync(path, readFileSync(path, "utf8") + "\n"); + }; + const callsBefore = f.calls.length; + await withoutExplicitNpm(async () => { + await expect( + verifyRegistryRelease( + prepared.manifest, + { + root: f.root, + manifest: prepared.manifestPath, + expectedReleaseCommit: prepared.manifest.gitCommit, + expectedManifestSha256: manifestHash, + output, + runId: 12345, + runAttempt: 2, + }, + f.seams, + ), + ).rejects.toThrow( + fault === "consumer" + ? "public DynamoDB consumer did not pass" + : fault === "manifest" + ? "prepared manifest independent digest differs" + : "retained cryptographic proof changed during public imports", + ); + }); + expect( + f.calls + .slice(callsBefore) + .filter(({ args }) => args.includes("--experimental-strip-types")), + ).toHaveLength(1); + const retained = JSON.parse( + readFileSync(join(output, "verification.json"), "utf8"), + ); + // Earlier proof remains for diagnosis; the final combined receipt must + // not replace it after a failed consumer, changed proof or manifest. + expect(retained.status).toBe("REGISTRY_BYTES_CRYPTO_SOURCE_PASS"); + expect(retained).not.toHaveProperty("consumer"); + expect( + readFileSync(join(output, "public-consumer.stdout"), "utf8"), + ).toContain("UNQUALIFIED_STUBS"); + expect(f.calls.some(({ args }) => args[0] === "publish")).toBe(false); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, + 180_000, + ); + + it("refuses unknown occupancy, audit failure and byte-identical but unqualified selected source during real preflight", async () => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + const base = { + root: f.root, + manifest: prepared.manifestPath, + expectedReleaseCommit: prepared.manifest.gitCommit, + expectedManifestSha256: digest(readFileSync(prepared.manifestPath)), + runId: 12345, + runAttempt: 2, + }; + for (const fault of [ + "unknown", + "audit", + "unqualified-existing", + ] as const) { + f.state.selected = + fault === "unknown" + ? "unknown" + : fault === "unqualified-existing" + ? "present" + : "absent"; + f.state.auditFails = fault === "audit"; + const output = join(f.root, "preflight-" + fault); + await withoutExplicitNpm(async () => { + await expect( + preflightRegistry(prepared.manifest, { ...base, output }, f.seams), + ).rejects.toThrow(); + }); + expect(existsSync(join(output, "preflight.json"))).toBe(false); + expect(f.calls.some(({ args }) => args[0] === "publish")).toBe(false); + } + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it("executes actual inline skip, publish, changed-occupancy and accepted-unknown decisions without real registry writes", async () => { + const f = await pipelineFixture(); + try { + const prepared = await controlledPrepare(f); + const output = join(f.root, "publisher-preflight"); + await withoutExplicitNpm(() => + preflightRegistry( + prepared.manifest, + { + root: f.root, + manifest: prepared.manifestPath, + expectedReleaseCommit: prepared.manifest.gitCommit, + expectedManifestSha256: digest(readFileSync(prepared.manifestPath)), + runId: 12345, + runAttempt: 2, + output, + }, + f.seams, + ), + ); + const publishCount = () => + f.calls.filter(({ args }) => args[0] === "publish").length; + // Independent scripted registry scenarios share immutable artifacts; + // no live registry, signature verification, token or upload is involved. + f.state.selected = "unknown"; + await expect( + actualInlinePublisher( + f, + prepared.manifestPath, + prepared.manifest, + output, + ), + ).rejects.toThrow("registry availability is unknown"); + expect(publishCount()).toBe(0); + f.state.selected = "present"; + await expect( + actualInlinePublisher( + f, + prepared.manifestPath, + prepared.manifest, + output, + ), + ).rejects.toThrow(/occupancy changed/u); + expect(publishCount()).toBe(0); + f.state.selected = "absent"; + const messages = await actualInlinePublisher( + f, + prepared.manifestPath, + prepared.manifest, + output, + ); + expect( + messages.filter((message) => message.includes("skipping.")).length, + ).toBe(3); + expect(publishCount()).toBe(1); + expect(f.calls.find(({ args }) => args[0] === "publish")!.args).toContain( + "--provenance", + ); + f.state.selected = "absent"; + f.state.publishThrows = true; + await expect( + actualInlinePublisher( + f, + prepared.manifestPath, + prepared.manifest, + output, + ), + ).rejects.toThrow("reviewed npm operation failed"); + expect(f.state.acceptedPublish).toBe(true); + expect(publishCount()).toBe(2); + await expect( + actualInlinePublisher( + f, + prepared.manifestPath, + prepared.manifest, + output, + ), + ).rejects.toThrow(/occupancy changed/u); + expect(publishCount()).toBe(2); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, 180_000); + + it.each(["audit", "consumer", "dependency-lock"] as const)( + "withholds successful producer proof after controlled %s failure", + async (fault) => { + const f = await pipelineFixture(); + f.state.auditFails = fault === "audit"; + f.state.consumerFails = fault === "consumer"; + f.state.lockTamper = fault === "dependency-lock"; + try { + await expect(controlledPrepare(f)).rejects.toThrow(); + expect(f.calls.some(({ args }) => args[0] === "publish")).toBe(false); + expect( + existsSync( + join(f.root, ".release-consumer-verification", "verification.json"), + ), + ).toBe(false); + if (fault !== "consumer") + expect( + f.calls.some(({ args }) => + args.includes("--experimental-strip-types"), + ), + ).toBe(false); + } finally { + rmSync(f.root, { recursive: true, force: true }); + } + }, + 180_000, + ); +});