diff --git a/.github/actions/setup-release-npm/action.yml b/.github/actions/setup-release-npm/action.yml new file mode 100644 index 0000000..8b8decf --- /dev/null +++ b/.github/actions/setup-release-npm/action.yml @@ -0,0 +1,26 @@ +name: Set up reviewed release npm +description: Verify and extract the pinned npm CLI without installing project dependencies. +runs: + using: composite + steps: + - name: Verify and extract pinned npm + shell: bash + env: + NPM_VERSION: 11.18.0 + NPM_TARBALL_SHA256: 73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e + run: | + set -euo pipefail + tarball="${RUNNER_TEMP}/npm-${NPM_VERSION}.tgz" + npm_root="${RUNNER_TEMP}/release-npm-${NPM_VERSION}" + curl --fail --silent --show-error --location --retry 3 \ + "https://registry.npmjs.org/npm/-/npm-${NPM_VERSION}.tgz" \ + --output "${tarball}" + echo "${NPM_TARBALL_SHA256} ${tarball}" | sha256sum --check --strict --quiet + mkdir "${npm_root}" + tar --extract --gzip --file "${tarball}" --directory "${npm_root}" + npm_cli="${npm_root}/package/bin/npm-cli.js" + if [[ "$(node "${npm_cli}" --version)" != "${NPM_VERSION}" ]]; then + echo "::error::The reviewed npm version is not active" + exit 1 + fi + printf 'RELEASE_NPM_CLI=%s\nRELEASE_NPM_VERSION=%s\n' "${npm_cli}" "${NPM_VERSION}" >> "${GITHUB_ENV}" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..ce6d233 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,327 @@ +# Publishes only the exact four-package artifact prepared from a verified tag. +# A manual dispatch prepares artifacts without entering the OIDC publish job. +name: Publish + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: Protected signed annotated stable tag to prepare (vX.Y.Z) + required: true + type: string + expected_commit: + description: Exact full commit SHA targeted by the tag + required: true + type: string + +permissions: + contents: read + +concurrency: + group: npm-publish + cancel-in-progress: false + +jobs: + identity: + name: Verify signed release identity + if: >- + github.repository == 'pegma-dev/knowledge-base' && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && !github.event.release.draft && !github.event.release.prerelease)) + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + tag: ${{ steps.identity.outputs.tag }} + commit: ${{ steps.identity.outputs.commit }} + env: + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.tag }} + RELEASE_COMMIT: ${{ github.event_name == 'release' && github.sha || inputs.expected_commit }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + steps: + # Do not execute project code or install dependencies before this check. + - name: Validate release event inputs + shell: bash + run: | + set -euo pipefail + if [[ ! "${RELEASE_TAG}" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::The release tag must be stable vX.Y.Z" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then + echo "::error::The release must supply its exact full commit SHA" + exit 1 + fi + if [[ "${GITHUB_EVENT_NAME}" == "release" && "${GITHUB_REF}" != "refs/tags/${RELEASE_TAG}" ]]; then + echo "::error::The release event must identify the requested tag" + exit 1 + fi + + - name: Check out the requested tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: refs/tags/${{ env.RELEASE_TAG }} + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main + + - name: Verify the approved tag signer and main ancestry + id: identity + shell: bash + env: + GIT_NO_REPLACE_OBJECTS: "1" + run: | + set -euo pipefail + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + git config --local gpg.format ssh + git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + tag_ref="refs/tags/${RELEASE_TAG}" + if [[ "$(git cat-file -t "${tag_ref}")" != "tag" ]]; then + echo "::error::The release requires an annotated tag" + exit 1 + fi + if [[ "$(git rev-parse HEAD)" != "${RELEASE_COMMIT}" || "$(git rev-parse "${tag_ref}^{commit}")" != "${RELEASE_COMMIT}" ]]; then + echo "::error::The checkout, tag target, and expected release commit must match" + exit 1 + fi + git verify-tag --raw "${tag_ref}" + git merge-base --is-ancestor "${RELEASE_COMMIT}" refs/remotes/origin/main + printf 'tag=%s\ncommit=%s\n' "${RELEASE_TAG}" "${RELEASE_COMMIT}" >> "${GITHUB_OUTPUT}" + + validate: + name: Release gate / Node.js ${{ matrix.node-version }} + needs: identity + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + node-version: [22, 24] + steps: + - name: Check out the verified release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.34.5 + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: ${{ matrix.node-version }} + cache: pnpm + - 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 including release regressions + run: pnpm test + - name: Run synthetic composition + run: pnpm example + - name: Check package artifacts + run: pnpm run release:check + - name: Prove authenticated agent protocol + run: pnpm run agent:proof + + prepare: + name: Prepare exact signed-tag artifacts + needs: [identity, validate] + runs-on: ubuntu-latest + timeout-minutes: 30 + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + manifest-sha256: ${{ steps.manifest.outputs.sha256 }} + env: + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + steps: + - name: Check out the verified release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main + + - name: Configure approved release signers + shell: bash + run: | + set -euo pipefail + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + git config --local gpg.format ssh + git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.34.5 + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Prepare and strictly verify the signed-tag release + id: prepared + run: >- + node scripts/release-packages.mjs prepare + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" + --out "${RUNNER_TEMP}/knowledge-base-prepared" + + # This independent digest travels through job outputs, never through the + # artifact whose manifest it authenticates. + - name: Record the independent manifest digest + id: manifest + shell: bash + env: + PREPARED_MANIFEST_SHA256: ${{ steps.prepared.outputs.manifest-sha256 }} + run: | + set -euo pipefail + read -r manifest_sha256 _ < <(sha256sum "${RUNNER_TEMP}/knowledge-base-prepared/manifest.json") + if [[ ! "${manifest_sha256}" =~ ^[0-9a-f]{64}$ || "${manifest_sha256}" != "${PREPARED_MANIFEST_SHA256}" ]]; then + echo "::error::The prepared manifest digest did not match its independent hash" + exit 1 + fi + printf 'sha256=%s\n' "${manifest_sha256}" >> "${GITHUB_OUTPUT}" + + - name: Upload the immutable prepared release + id: upload + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: knowledge-base-release-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/knowledge-base-prepared/ + if-no-files-found: error + overwrite: false + retention-days: 30 + + - name: Record prepared artifact identity + env: + ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }} + ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} + MANIFEST_SHA256: ${{ steps.manifest.outputs.sha256 }} + run: | + printf 'Prepared artifact ID: %s\n\nArtifact SHA-256: %s\n\nManifest SHA-256: %s\n' \ + "${ARTIFACT_ID}" "${ARTIFACT_DIGEST}" "${MANIFEST_SHA256}" >> "${GITHUB_STEP_SUMMARY}" + + publish: + name: Publish exact prepared artifacts + needs: [identity, prepare] + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: npm-publish + permissions: + contents: read + id-token: write + env: + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_MANIFEST_SHA256: ${{ needs.prepare.outputs.manifest-sha256 }} + steps: + - name: Check out the exact verified release source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + # Extract only the reviewed npm CLI; never install project dependencies + # or run package builds with OIDC authority. + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm + + - name: Download the exact immutable prepared artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/knowledge-base-prepared + + - name: Publish the exact prepared release + run: >- + node scripts/release-packages.mjs publish + --prepared-dir "${RUNNER_TEMP}/knowledge-base-prepared" + --manifest-sha256 "${RELEASE_MANIFEST_SHA256}" + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" + + verify: + name: Verify registry release and consumer + needs: [identity, prepare, publish] + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + id-token: none + env: + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_MANIFEST_SHA256: ${{ needs.prepare.outputs.manifest-sha256 }} + steps: + - name: Check out the exact verified release source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm + + - name: Download the exact immutable prepared artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/knowledge-base-prepared + + # Registry availability requires this unprivileged job to pass. Consumer + # installation and provenance verification never receive OIDC authority. + - name: Verify registry bytes, provenance, and the public consumer + run: >- + node scripts/release-packages.mjs verify + --prepared-dir "${RUNNER_TEMP}/knowledge-base-prepared" + --manifest-sha256 "${RELEASE_MANIFEST_SHA256}" + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" diff --git a/AGENTS.md b/AGENTS.md index dd3fe04..641f8e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,10 +14,10 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. optional `@pegma/knowledge-base-mcp` package for the shared five-operation dispatcher, versioned HTTP contract, and MCP transport. Live host interfaces remain host work; do not create later packages early. -- Independent partial KB-05 source preparation adds local D1 conformance and - a public synthetic composition. It does not complete KB-04 credentials or - the full KB-05 release/publication task. KB-04 source is in progress; all four - packages remain unpublished at synchronized version `0.1.0`. +- KB-04 source is merged. KB-05 source preparation adds local D1 conformance, + a public synthetic composition, and exact-artifact release tooling. All four + packages remain unpublished at synchronized version `0.1.0`; source readiness + does not complete first publication, registry verification, or host acceptance. - Never implement a database, authorization role model, identity/session/token system, audit log, request limiter, or durable scheduler here. Compose the corresponding Pegma package in the owning later task. @@ -87,8 +87,21 @@ published package engines remain `>=22`, and CI tracks current Node 22/24. Each published package needs its own README and MIT LICENSE, a build-on-prepack script, and compiled-test exclusion. Merging source does not publish packages. -See [release operations](docs/RELEASING.md); first publication and external -trusted-publisher configuration are separate maintainer operations. +Release preparation requires a clean checkout at an approved signed annotated +`vX.Y.Z` tag matching the synchronized version, exact event commit, and protected +`origin/main` ancestry. A schema-2 manifest binds that identity and all four +tarballs. Independently retain its SHA-256 digest; never trust a digest taken +only from the downloaded artifact. Preflight all four registry versions before +any publish, and recover only by accepting byte-identical existing artifacts. +See [release operations](docs/RELEASING.md) and the +[first-publication handoff](docs/BOOTSTRAP.md). Maintainer 2FA bootstrap and +external package ownership, signer, tag, environment, and trusted-publisher +settings remain separate gates. OIDC publishing receives only verified prepared +artifacts; it installs nothing, rebuilds no packages, and has no token fallback. +A separate unprivileged job installs registry packages in an isolated temporary +consumer with lifecycle scripts disabled and verifies signatures/provenance. +`pnpm test` includes `test:release`'s release identity, manifest, argument, and +registry regressions; these must execute on both Node lanes. The protocol proof may build the reviewed, pinned public AUTH-01 source in an isolated temporary consumer with all four KB tarballs and the official SDK. That test-only exception never authorizes an unpublished production dependency. @@ -109,5 +122,6 @@ layout before changing query work, citations, or repair. For KB-04, read the [agent API](docs/AGENT_API.md) and [agent workflow](docs/AGENT_WORKFLOW.md) before changing transport, credential, client, or evidence-proof boundaries. -For partial KB-05, read [source preparation](docs/SOURCE_PREPARATION.md) before -changing local D1 fixtures, synthetic composition, or release-readiness claims. +For KB-05, read [source preparation](docs/SOURCE_PREPARATION.md) before changing +local D1 fixtures, synthetic composition, or release-readiness claims, and +[release operations](docs/RELEASING.md) before changing release tooling. diff --git a/README.md b/README.md index b10160b..210d7b5 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,13 @@ and exact publication approval. It requires no GitHub connection or AI provider. > Development status: KB-01 through KB-03 provide contracts, pure domain > transitions, authorized application/persistence, and bounded retrieval/repair. -> Independent partial KB-05 preparation adds local D1 conformance and a public -> synthetic example. KB-04 source work adds the optional five-operation HTTP/MCP -> adapter and authenticated protocol proof; it is in progress until current-head -> gates and review pass. All four packages are unpublished at `0.1.0`. -> KB-05 publication and actual two-host existing-login/client acceptance remain -> separate gates. This repository is not an operational hosted KB or a -> production dependency. +> [Merged KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) adds +> the optional five-operation HTTP/MCP adapter and authenticated protocol proof. +> KB-05 source preparation supplies local D1 conformance, a public synthetic +> example, and exact-artifact release tooling. All four packages are unpublished +> at `0.1.0`. First publication, trusted-publisher setup, registry verification, +> and actual two-host existing-login/client acceptance remain separate gates. +> This repository is not an operational hosted KB or a production dependency. | Package | Scope | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | @@ -67,7 +67,7 @@ bot-answer uses have separate safe citations; bot-only knowledge does not grant an article browse capability. Read [retrieval](docs/RETRIEVAL.md) for physical work/source budgets, whole-article token accounting, and repair. -Partial [source preparation](docs/SOURCE_PREPARATION.md) runs shared public KB +[Source preparation](docs/SOURCE_PREPARATION.md) runs shared public KB conformance against memory, local Azurite, and real local Miniflare D1 through the released D1 adapter. The [synthetic composition](examples/composition/README.md) demonstrates author/test/review/publish/retrieve with fictional trust inputs. @@ -110,9 +110,15 @@ gates. The two hosts keep separate stores and policies without a shared control plane. Read [AGENTS.md](AGENTS.md) before changing code and -[release operations](docs/RELEASING.md) before preparing artifacts. Merging -source does not publish a package. Each of the four npm names needs the -maintainer's first publication and its own trusted-publisher setup before host -consumption; Agent Access follows its separate release process. +[release operations](docs/RELEASING.md) before preparing artifacts. Development +pack checks are separate from signed-tag release preparation. The release path +binds all four tarballs to source identity and an independently retained manifest +digest, preflights the full registry set, and verifies released consumers. +Merging source does not publish a package. Follow the +[maintainer bootstrap handoff](docs/BOOTSTRAP.md) for the four new npm names, +then configure their individual trusted publishers for later releases. Agent +Access follows its separate release process. SD-02 and host installation wait +for actual published dependencies; source and synthetic proof cannot satisfy +real host acceptance. Built in the open by RetireGolden, LLC. diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md new file mode 100644 index 0000000..1cf0bc8 --- /dev/null +++ b/docs/BOOTSTRAP.md @@ -0,0 +1,101 @@ +# First-publication handoff + +## Current state and owner + +The maintainer owns npm's first-publication and external configuration steps. +All four KB package names are unpublished at synchronized source version +`0.1.0`. No tag, GitHub release, npm publication, publisher setting, or protection +setting is created by merging KB-05 source. Agent Access has its own separate +first-publication process. + +This handoff deliberately separates creating the npm names from the first +advertised trusted release. Manual maintainer 2FA publication does not establish +OIDC provenance. It cannot be substituted for the strict `verify` result in +[release operations](RELEASING.md). + +## Prepare the initial exact set + +1. Confirm ownership and publishing permission for all four names. Record the + maintainer responsible for each package and its 2FA publication. Keep + credentials and one-time codes out of repository files and logs. +2. Merge reviewed source and exact pins to protected `origin/main`. Record the + full commit and passing current-head Node 22/24 gates, clean OpenRouter + review, and applicable security results. Configure approved signers and + protected immutable `v*` tags outside this source change. +3. The maintainer creates the approved signed annotated `v0.1.0` tag targeting + that merged commit. In a clean complete checkout at the tag, configure the + approved signer verification. Before standalone preparation, extract the + reviewed npm `11.18.0` tarball after checking the SHA-256 pinned in the + [npm setup action](../.github/actions/setup-release-npm/action.yml). + Explicitly set `RELEASE_NPM_CLI` to the extracted regular `npm-cli.js` file's + canonical absolute path and set `RELEASE_NPM_VERSION=11.18.0`; both are + required, and linked paths are rejected. Alternatively use the workflow's + prepare-only dispatch, which supplies both variables. Then run strict + preparation: + + ```sh + node scripts/release-packages.mjs prepare --tag v0.1.0 --expected-commit FULL_COMMIT_SHA + ``` + +4. Independently record the emitted manifest SHA-256, source identity, artifact + directory, and the four tarball hashes. Retain the prepared directory intact. + Obtain the digest from the trusted preparation output, not from a file + bundled alongside downloaded tarballs. The workflow's prepare-only manual + dispatch can supply immutable artifacts and independent job outputs. +5. Run read-only full-set preflight with that independent digest: + + ```sh + node scripts/release-packages.mjs preflight --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag v0.1.0 --expected-commit FULL_COMMIT_SHA + ``` + + Every existing exact version must match the prepared metadata and downloaded + tarball bytes. Only HTTP 404 establishes absence. Stop for any mismatch, + access failure, or uncertain registry response. + +## Maintainer 2FA bootstrap + +Publish only the exact prepared tarballs, in this order, using the maintainer's +interactive npm login and 2FA. Commands below are the handoff for that operator; +they are not CI steps and must not be run by a source-preparation agent: + +```sh +npm publish PREPARED_DIRECTORY/pegma-knowledge-base-contracts-0.1.0.tgz --access public --ignore-scripts --tag bootstrap +npm publish PREPARED_DIRECTORY/pegma-knowledge-base-core-0.1.0.tgz --access public --ignore-scripts --tag bootstrap +npm publish PREPARED_DIRECTORY/pegma-knowledge-base-application-0.1.0.tgz --access public --ignore-scripts --tag bootstrap +npm publish PREPARED_DIRECTORY/pegma-knowledge-base-mcp-0.1.0.tgz --access public --ignore-scripts --tag bootstrap +``` + +Use the filenames from the verified manifest. Do not publish from source +directories or add a token fallback. Rerun full-set preflight before continuing +an interrupted bootstrap. Skip an existing member only after preflight confirms +the identical prepared bytes; npm versions are immutable. After all four exist, +repeat preflight to record the registry metadata and downloaded-byte match. +Retain the manual publication receipts and bootstrap integrity record, with +provenance explicitly recorded as absent. Do not advertise this bootstrap as +the released dependency set or authorize host installation from it. + +## First advertised trusted release + +After the names exist, the maintainer configures all four trusted publishers, +the protected `npm-publish` environment, approved signers, and immutable tag +protection as described in [release operations](RELEASING.md). Each npm publisher +must name this repository's exact `publish.yml` workflow and environment and +explicitly permit direct publishing. Time new configurations to the prepared +trusted release so their first-use expiry does not strand the release. + +The first advertised release needs a separately reviewed synchronized version +and exact dependency-pin change. This source change chooses no future version +and performs no bump. A previously manually published version cannot be +republished through OIDC to add provenance. Run the full review/Node 22/24 gate +for the newly reviewed commit, create its approved signed annotated version tag +on `origin/main`, then create its GitHub release with `--verify-tag` to trigger +the trusted workflow. It prepares once, checks the independent artifact binding, +preflights all four names, and publishes only missing exact tarballs. + +Advertise availability only after its separate unprivileged strict `verify` job +succeeds for the entire set: +registry bytes/dependencies, clean exact-version registry consumer, registry +signatures, and matching source/workflow/tag/commit provenance. Preserve those +results with the release identity and independent manifest digest. SD-02 waits +for this published KB set; both hosts additionally require published Agent +Access and their retained actual login/Admin-consent/client/staging acceptance. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index bf2af65..581bdd4 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,38 +1,35 @@ # Release operations -## Source status - -`@pegma/knowledge-base-contracts`, `@pegma/knowledge-base-core`, -`@pegma/knowledge-base-application`, and `@pegma/knowledge-base-mcp` use -synchronized source version `0.1.0`. All four package names are unpublished. -KB-01 through KB-03 establish domain, authorized application, and bounded -retrieval source. KB-04 adds the optional five-operation HTTP/MCP adapter and -authenticated source protocol proof; this work remains in progress until its -current-head gates and review pass. Source changes do not publish, create -tags/releases, configure production credentials, or enable a publish workflow. - -Independent partial KB-05 [source preparation](SOURCE_PREPARATION.md) adds the -local Miniflare D1 consumer fixture, shared three-backend conformance, and a -public synthetic example. That earlier slice added no package. KB-04 now adds -the fourth package; full KB-05 publication remains pending. - -[AUTH-01 merged source](https://github.com/pegma-dev/agent-access/pull/1) is the -KB-04 source prerequisite. `agent:proof` builds its reviewed public commit -`a444e2113db98455b638b2ef8aa7c2faccb16b62` only in an isolated temporary -consumer with all four KB tarballs and official MCP SDK `1.32.2`. This proves -source protocol behavior when its current-head gate passes, without publishing -Agent Access. Its first publication and trusted-publisher setup belong to its -own release process, not this repository's four-package release. - -Hosts must wait for an exact public registry release. Git branches, copied -source, local paths, and unpublished production tarballs are not substitutes. -The temporary tarball consumer below is a packaging test only. - -## Artifact checks - -Use Node 22.6.0+ or 24 for the repository gate and source example, with the -pinned pnpm version. CI continues to track current Node 22 and 24; published -package engines remain `>=22`. +## Status and release boundary + +The release set is exactly these packages, in dependency order: + +1. `@pegma/knowledge-base-contracts` +2. `@pegma/knowledge-base-core` +3. `@pegma/knowledge-base-application` +4. `@pegma/knowledge-base-mcp` + +All four have synchronized source version `0.1.0` and remain unpublished. +[KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) is merged at +`b61fc77aedd22e888ac7292c3597f93e54fcda8e`; its Node 22/24 lanes passed 372 tests +each and the official-SDK authenticated synthetic protocol proof. KB-05's source +candidate supplies local D1 conformance, public synthetic composition, and the +release tooling. +Changed source still needs all current-head gates before release preparation. +No source merge configures publishers, creates a tag/release, or publishes npm +packages. Follow the [maintainer bootstrap handoff](BOOTSTRAP.md) for first use. + +[Agent Access](https://github.com/pegma-dev/agent-access/pull/1) is a separate +release. Its reviewed commit `a444e2113db98455b638b2ef8aa7c2faccb16b62` is built +only in `agent:proof`'s isolated test consumer with the four KB tarballs and +official MCP SDK `1.32.2`. Its merged 123-test source result does not publish it. +Production hosts require exact published versions of both components. + +## Repository and development artifact gates + +Use Node 22.6.0+ or 24 with `pnpm@10.34.5`. Published package engines remain +`>=22`; the development floor supports the source example's type stripping. +The complete gate runs on current Node 22 and 24: ```sh pnpm install --frozen-lockfile @@ -44,98 +41,219 @@ pnpm run release:check pnpm run agent:proof ``` -`release:check` packs contracts, core, application, then MCP using npm. Each package's -`prepack` builds its own output, so a package cannot silently ship a stale -distribution. The checker verifies: - -- synchronized stable versions, exact internal/Spine pins, ESM/public metadata, - and each package's declared runtime/type entry points; -- a package-local README and MIT LICENSE, a build-on-prepack script, and - exclusion of `src/**/*.test.ts` from compilation; -- npm's artifact inventory containing only package metadata, README, LICENSE, - and JavaScript/declaration output and maps under `dist`, with compiled tests - excluded and both entry-point files present; -- the actual tarball bytes against npm's reported SHA-1 and SHA-512 integrity; -- an isolated consumer installation of all four tarballs and successful ESM - imports of all four public packages, including the optional adapter's SDK - dependency resolution. - -The consumer disables install scripts, audit, and funding requests and obtains -released external dependencies from the public npm registry. It has no workspace -links. The checker locates `npm-cli.js` and invokes it with Node directly on -Windows and Unix; it does not interpolate commands through a shell. Temporary -files are removed only after checking their resolved directory is the generated -child of the system temporary root. No user npm configuration is inspected or -printed. - -To keep the same verified tarballs for maintainer inspection: +Require clean current-head OpenRouter review with zero actionable findings and +all applicable security checks. Absent, skipped, pending, or failing gates do +not authorize release. `pnpm test` includes `pnpm run test:release`, which covers +release identity, manifest integrity, strict arguments, and registry failure and +recovery cases. Both Node lanes must execute those regressions. + +`release:check` builds on each package's `prepack`, packs all four using npm, +and verifies synchronized stable versions, exact dependency pins, ESM exports, +package-local README/MIT LICENSE, and compiled-test exclusion. It checks the +artifact file allowlist, runtime/type entry points, SHA-1, and SHA-512 integrity. +An isolated consumer outside the workspaces installs all four tarballs with +scripts disabled, resolves released external dependencies, imports the public +packages, and initializes the MCP adapter to check its packed name/version. +`agent:proof` separately exercises authenticated OAuth/tool/evidence behavior. +Neither check establishes real requested-client or host acceptance. + +`pnpm run release:pack` preserves those development artifacts in a new +`.release/knowledge-base-*` directory with a schema-1 manifest. It requires no +release tag and supplies no release identity or provenance. Publication rejects +this development manifest. Use strict `prepare` for a releasable artifact set. + +## Strict release preparation + +Merge reviewed release source and synchronized version/pin changes to protected +`origin/main` first. Configure immutable protected `v*` tags and approved release +signers outside this source change. A stable `vX.Y.Z` must be a signed annotated +tag whose target matches the synchronized package version and exact expected +commit. The checkout must be clean, at that commit, in the fixed public source +repository, with complete ancestry and the commit contained in `origin/main`. +Signature verification must use independently approved signer configuration. +Neither a lightweight tag nor a tag at an unmerged commit qualifies. + +After the complete gate, prepare from that exact clean checkout. The example +uses the current source version; substitute the full approved commit SHA: + +Strict `prepare` requires both `RELEASE_NPM_CLI` and +`RELEASE_NPM_VERSION=11.18.0`. The CLI path must be canonical, absolute, and name +a regular `npm-cli.js` file; linked paths are rejected. Extract the reviewed npm +tarball after checking the SHA-256 pinned in the +[npm setup action](../.github/actions/setup-release-npm/action.yml), then set +both variables before standalone preparation. The workflow configures them +automatically. Development `check` and `pack` continue to use ambient npm. ```sh -pnpm run release:pack +node scripts/release-packages.mjs prepare --tag v0.1.0 --expected-commit FULL_COMMIT_SHA ``` -This runs the same checks, then writes a new `.release/knowledge-base-*` -directory containing the four tarballs and `manifest.json` with their inventory -and integrity values. Existing artifact directories are preserved. These files -are local preparation artifacts, not proof of a released version or provenance. -The checker does not verify a source tag, main ancestry, registry publication, -or trusted-publisher configuration. Those are release prerequisites below. - -`agent:proof` is a separate gate from artifact inventory/import checks. It uses -the real Agent Access implementation and official SDK against a test-only -synthetic composition for OAuth, the five draft/evidence operations, HTTP/MCP -parity, and rejected credential/evidence cases. It establishes neither actual -requested-client compatibility nor real existing-login/host staging acceptance. -Both source gates and the synthetic composition run on Node 22 and 24, with a -clean current-head OpenRouter review containing zero actionable findings and -the applicable security checks before source exit. - -## Maintainer prerequisites before first publication - -These operations remain pending and must be recorded when completed: -Recheck npm's current [trusted-publishing guidance](https://docs.npmjs.com/trusted-publishers/) -when implementing the release workflow; this checklist records the Pegma -release procedure, not proof that external publisher settings exist. - -- [ ] Confirm ownership and organization publishing permissions for all four - package names. -- [ ] Complete KB-05's advertised package/adapter and dual-store release - criteria. Partial source preparation supplies a real local D1 consumer - fixture and synthetic composition subject to current-head gates. KB-04 - must close its separate source exit with actual-SDK synthetic transport - proof. Actual requested-client/existing-login/host acceptance remains a - later PG-01/RG-01 activation gate; no source run can close it. - Do not publish empty packages. -- [ ] Merge reviewed release source and exact version/pin changes to protected - `origin/main`; require every current-head review, test, build, security, - and artifact check to pass. -- [ ] Configure protection for immutable `v*` tags and approved release signers. -- [ ] Prepare and verify the exact artifacts from a protected signed annotated - `vX.Y.Z` tag whose commit is already on `origin/main`. -- [ ] The maintainer performs each of the four new package names' one-time - manual 2FA publication of those exact verified tarballs. Choose and document the - bootstrap/first advertised release procedure before this operation. -- [ ] Separately configure an npm trusted publisher for each of the four package - names, this repository's reviewed future publish workflow, and its - protected publishing environment. -- [ ] Establish the future workflow: unprivileged signature/main/gate/pack - preparation, followed by a minimal environment-approved OIDC publish job - receiving only the exact prepared artifacts. -- [ ] Verify registry versions, tarball integrity, provenance, and a clean - public consumer installation before marking the packages available. - -The first-publication procedure is a maintainer operation, not a command hidden -in CI. Do not add an npm token or token-based fallback to this repository. -Merging a PR does not publish. Later releases must use the protected signed -annotated tag and trusted-publisher path, preserve published version immutability, -and recover partial publication by verifying identical existing artifacts rather -than overwriting a version. Define that workflow in the release task before -enabling publication. - -Before real host assembly, verify both the exact KB release set and the -separately published Agent Access dependency. Preserve P-00 and PG-01/RG-01's -actual existing-login/current-Admin consent, every requested client/mode, -host-attested staging evidence, and failure-case acceptance until both hosts -record it. Those gates, staff review/publication, privacy, isolation, bounded -work, and full human workflows remain required before activation, A-01, and -either supervised pilot. No release artifact alone proves host readiness. +An optional `--out EMPTY_DIRECTORY` selects a new empty output directory. +Preparation repeats the strict identity checks and package/consumer checks, +then preserves the four exact tarballs plus `manifest.json`. Its schema is 2: + +- `identity`: fixed repository, tag, exact commit, and synchronized version; +- `artifacts`: exactly the four packages in dependency order, with name, + version, safe filename, byte size, SHA-1, SHA-512 integrity, exact dependencies, + and bounded file inventory. + +The producer emits `prepared-dir`, `manifest-path`, and `manifest-sha256`. +Retain the SHA-256 independently with the approved source identity and job +outputs. A digest copied only from a downloaded artifact provides no independent +binding. Consumers require the digest, tag, and expected commit as explicit +inputs and rehash every tarball. They reject extra or malformed manifest data, +unsafe paths, symlinks, missing files, wrong package order/pins, and changed bytes. +Preparing artifacts does not establish registry availability or provenance. + +## Protected trusted-publisher workflow + +[Publish](../.github/workflows/publish.yml) prepares on a stable published GitHub +release. The release is created only after the protected signed annotated tag +exists on `origin/main`, using `gh release create vX.Y.Z --verify-tag`. +Its manual `workflow_dispatch` accepts `tag` and `expected_commit` to prepare +and inspect artifacts; manual dispatch cannot publish. + +The workflow first verifies tag/event identity, complete main ancestry, and the +approved SSH signature before running repository source. Node 22/24 jobs run +the full gate. The unprivileged preparation job repeats strict verification, +packs once, uploads an immutable artifact, and exposes its artifact ID and +manifest SHA-256 independently. Only the protected `npm-publish` job receives +`id-token: write`. It downloads that exact artifact ID and checks the independent +digest/tag/commit before npm writes. It installs no repository dependencies, +executes no package lifecycle scripts, and does not rebuild or repack. +A separate unprivileged `verify` job has `id-token: none` and installs only +registry packages in its temporary consumer. It verifies bytes, signatures, and +provenance using the same immutable artifact ID and independent digest. Manual +dispatch skips both publishing and registry verification. + +These external settings must be configured and recorded by the maintainer: + +- ownership and organization publishing permission for all four npm names; +- protected `origin/main`, immutable release tags, and approved SSH signers in + the reviewed `RELEASE_ALLOWED_SIGNERS` repository variable; +- the GitHub `npm-publish` environment with required approval and release-ref + restrictions; +- a separate npm trusted publisher for each package, bound to + `pegma-dev/knowledge-base`, `publish.yml`, and `npm-publish`; +- explicit permission for direct `npm publish`, plus restrictions disallowing + token-based publishing. There is no repository npm token or token fallback. + +As checked on 2026-11-07, npm requires Node 22.14.0+ and npm 11.5.1+ for trusted +publishing. New publisher configurations allow staged publishing by default; +direct publishing needs its own permission. A new configuration expires unless +its first successful publish occurs within two days. Create it when the reviewed +trusted release is ready; recreate an expired configuration. The workflow pins +npm `11.18.0`. Recheck the [official npm guidance](https://docs.npmjs.com/trusted-publishers/) +before changing these external settings. + +## Preflight, publication, and interrupted-release recovery + +The read-only preflight is also the first-publication inspection command: + +```sh +node scripts/release-packages.mjs preflight --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag v0.1.0 --expected-commit FULL_COMMIT_SHA +``` + +It validates the schema-2 artifact set, then checks every exact package version +in the public npm registry before any publishing operation. Only an exact +version's HTTP 404 means absent. Authentication/network/server errors, invalid +metadata, wrong names/versions/dependencies, or changed registry tarball bytes +stop the release. Every existing version must match the prepared SHA-1, +SHA-512 integrity, and downloaded bytes. + +The protected OIDC job runs: + +```sh +node scripts/release-packages.mjs publish --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag vX.Y.Z --expected-commit FULL_COMMIT_SHA +``` + +The workflow supplies `RELEASE_NPM_CLI` as an absolute path to its reviewed npm +`11.18.0` `npm-cli.js` and `RELEASE_NPM_VERSION=11.18.0`. Standalone `prepare` +and `verify` also need both variables and the canonical regular CLI path; use +the npm artifact and SHA-256 pinned in the +[npm setup action](../.github/actions/setup-release-npm/action.yml). +The read-only `preflight` command needs no npm authentication. +`publish` additionally requires the matching GitHub release OIDC environment; +local interactive bootstrap uses the maintainer procedure instead. + +`publish` repeats full-set preflight before its first npm write. It skips only +identical existing versions and publishes missing packages in the stated +dependency order using the prepared tarballs. A partial release is incomplete. +Preserve its original source identity, independent digest, and artifact bytes; +retry only after the full preflight accepts that same set. Never overwrite a +published version, rebuild a missing member from another checkout, move a tag, +or treat an npm error as proof of absence. Any conflicting existing artifact +requires maintainer investigation and a separately reviewed release decision. + +## Registry verification and availability + +After `publish`, the separate unprivileged workflow job runs strict verification. +The same command is available independently: + +```sh +node scripts/release-packages.mjs verify --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag vX.Y.Z --expected-commit FULL_COMMIT_SHA +``` + +All four exact registry versions must exist and match the approved artifact +metadata and downloaded bytes. A fresh consumer installs the four exact +versions from the public registry, without workspace links, local tarballs, or +lifecycle scripts, then checks their public imports. +The pinned npm CLI verifies registry signatures and provenance attestations; +the release verifier requires the attested source repository, workflow, tag, +and source commit to match the prepared identity. Package availability requires +these complete-set results, not a successful upload of one tarball. Preserve +the prepared artifact/digest, source identity, workflow run and verification +results in the release record. + +Manual first publication cannot satisfy this trusted-provenance gate. The +[bootstrap handoff](BOOTSTRAP.md) records the required two-step release boundary; +bootstrap integrity checks must not be reported as OIDC provenance. + +## Observed npm audit shape: 2026-11-07 + +A real isolated registry consumer used the installed npm `11.18.0` CLI and exact +`@pegma/spine@0.1.2`, with its known integrity checked and lifecycle scripts +disabled. No package runtime was imported. The command +`npm audit signatures --json --include-attestations` succeeded; the +[official npm audit documentation](https://docs.npmjs.com/cli/v11/commands/npm-audit/#audit-signatures) +documents that flag and its attestation output. + +The sanitized observed shape was: + +```text +top-level keys: invalid, missing, verified +counts: invalid=0, missing=0, verified=1 +verified entry keys: attestationBundles, attestations, location, name, registry, version +attestationBundles: 2 bundles, including one SLSA v1 provenance bundle +bundle keys: dsseEnvelope, mediaType, verificationMaterial +verificationMaterial: certificate.rawBytes, timestampVerificationData, tlogEntries +``` + +A second isolated run installed all seven exact external runtime pins used by +the two components, resolving 102 packages. Root lock versions and public +registry URLs matched; the real audit reported `invalid=0`, `missing=0`, +and `verified=21`. Lifecycle scripts and runtime imports remained disabled. +This checks the existing external dependency graph without publishing either +new component. + +The observed public source was [pegma-dev/spine](https://github.com/pegma-dev/spine) +at `refs/tags/v0.1.2`. This records the pinned CLI's working flag, output, and +certificate shape. It proves no provenance for unpublished KB or Agent Access +packages and performs no publisher operation. Their own exact repository, +workflow, tag, and source-commit post-release verification remains mandatory. +Raw bundles and certificate bytes are intentionally omitted. + +## Consumers and retained host gates + +KB publication precedes SD-02. Before real host assembly, verify both the exact +KB release set and the separately published Agent Access dependency. Git +branches, copied source, local paths, and unpublished production tarballs do +not substitute for registry releases. + +P-00 and PG-01/RG-01 still require actual existing-login/current-Admin consent, +every requested client/mode, host-attested staging evidence, and credential and +evidence failure cases on both hosts. Source, emulator, SDK, registry, and +provenance results cannot close those gates. Staff approval/publication, +privacy, isolation, bounded work, and full human workflows remain required +before activation, A-01, and either supervised pilot. Keep private host +configuration and operational evidence in the owning private systems. diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index 244d153..bd0fdee 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -2,23 +2,25 @@ ## Scope and readiness -This is an independent, partial KB-05 source-preparation slice. It adds a real -local D1 consumer fixture and a public synthetic composition example over the -existing contracts/core/application packages. It does not finish KB-04 or the -full KB-05 release task. KB-04 now adds the optional HTTP/MCP package and its -separate authenticated protocol proof; that source work is in progress until -current-head gates and review pass. All four KB packages remain unpublished at -synchronized source version `0.1.0`. +KB-05 source preparation supplies a real local D1 consumer fixture, a public +synthetic composition, and exact-artifact release tooling. The earlier fixture +slice is [merged](https://github.com/pegma-dev/knowledge-base/pull/4), and +[KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) is merged at +`b61fc77aedd22e888ac7292c3597f93e54fcda8e`. That source passed 372 tests on each +Node 22/24 lane and the separate authenticated official-SDK protocol proof. +These are historical merged-source results; current changes require fresh +current-head gates. All four KB packages remain unpublished at synchronized +source version `0.1.0`. | Evidence area | This source slice | Separate remaining proof | | ---------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | | Storage consumer | Shared public KB suites on memory, local Azurite, and local Miniflare D1 | Production Azure/Workers configuration, operations, and host acceptance | | Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, existing-login/client acceptance, and UI | -| Artifacts | Four-package pack/import checks, extended by KB-04 | First publication, trusted-publisher setup, registry integrity/provenance, and released consumers | -| Task readiness | Current-head repository gates establish this slice's evidence | KB-04 source exit, actual two-host/client acceptance, and remaining KB-05 exit criteria | +| Artifacts | Four-package checks and signed-tag preparation with a schema-2 manifest | First publication, trusted-publisher setup, registry integrity/provenance, and released consumers | +| Task readiness | Current-head repository gates establish source readiness | Actual publication and two-host/client acceptance remain separately recorded | -No test counts or pass verdicts are implied by this document. Record verified -current-head gate results before treating the source slice as validated. +The historical result above does not certify this working tree. Record verified +current-head gate results before treating changed source as validated. Local emulator and fixture results are not production or live Workers proof. ## Pinned local D1 consumer @@ -157,24 +159,35 @@ evidence flow, shared HTTP/MCP behavior, and rejection cases. The evidence attester must bind the authenticated actor and runner to the exact article revision/content hash, staging build, execution result, and opaque receipt; an authenticated agent's claimed `passed` result remains untrusted data. -Current-head results establish execution; this document claims no passing run. +KB-04's merged-source result records execution; changed source requires fresh +current-head results. See [agent workflow](AGENT_WORKFLOW.md) for the retained source and host gates. ## Remaining gates -KB-04's source exit needs its implementation, Node 22/24 gates, clean review, -and security checks. Actual clients and two-host authentication/staging -acceptance remain open in P-00 and PG-01/RG-01. Every requested client/mode must +KB-04's source exit is merged; it does not establish actual clients or two-host +authentication/staging acceptance. Those gates remain open in P-00 and +PG-01/RG-01. Every requested client/mode must record discovery, existing-login/current-Admin consent, the five operations, and credential/evidence failures on each host using published dependencies. Synthetic source/SDK success cannot close those activation prerequisites. -The full KB-05 release candidate still needs its advertised package/adapter -and client criteria, reviewed bootstrap/trusted-publisher configuration, exact -registry publication, artifact/provenance verification, and released consumer -checks. See [release operations](RELEASING.md). KB-04 implements the fourth -package rather than an empty adapter; neither source slice creates a release -tag, publication, or host activation. Agent Access has its own first-publication -and trusted-publisher prerequisites, also required before host assembly. +KB-05's release tooling separates development pack checks from strict release +preparation. The latter verifies a clean checkout, approved signed annotated +version tag, exact commit and main ancestry; a schema-2 manifest binds all four +tarballs and must be checked against an independently retained digest. Registry +preflight covers the complete release set before a publish, permits recovery +only for identical existing artifacts, and released-consumer checks use the +public registry. See [release operations](RELEASING.md) and the concrete +[bootstrap handoff](BOOTSTRAP.md). + +Source readiness leaves package ownership, protected tags/environments, approved +signers, first maintainer 2FA publication, per-package trusted publishers, +registry integrity/provenance verification, and released consumers pending. +Manual bootstrap is not OIDC provenance. Agent Access has its own publication +prerequisites, also required before host assembly; AUTH-01's merged source at +`a444e2113db98455b638b2ef8aa7c2faccb16b62` and its 123-test source result do +not publish it. SD-02 waits for KB publication, and both hosts wait for exact +published KB and Agent Access dependencies before their retained acceptance. Hosts must wait for exact released artifacts rather than adopting branches, copied source, local paths, or unpublished production tarballs. diff --git a/package.json b/package.json index 7f515c7..01c2864 100644 --- a/package.json +++ b/package.json @@ -17,9 +17,14 @@ "clean": "tsc -b --clean", "format": "prettier --write .", "format:check": "prettier --check .", - "test": "pnpm run build && vitest run", + "test": "pnpm run build && vitest run && pnpm run test:release", + "test:release": "node scripts/test-release.mjs", "release:check": "node scripts/release-packages.mjs check", "release:pack": "node scripts/release-packages.mjs pack", + "release:prepare": "node scripts/release-packages.mjs prepare", + "release:preflight": "node scripts/release-packages.mjs preflight", + "release:publish": "node scripts/release-packages.mjs publish", + "release:verify": "node scripts/release-packages.mjs verify", "example": "pnpm run build && node --experimental-strip-types examples/composition/run.ts", "agent:proof": "node scripts/agent-protocol-proof.mjs" }, diff --git a/scripts/release-contract.mjs b/scripts/release-contract.mjs new file mode 100644 index 0000000..c062a86 --- /dev/null +++ b/scripts/release-contract.mjs @@ -0,0 +1,208 @@ +import { spawnSync } from "node:child_process"; +import { realpathSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const RELEASE_REPOSITORY = "pegma-dev/knowledge-base"; +export const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +export const RELEASE_PACKAGES = Object.freeze( + [ + { + directory: "contracts", + name: "@pegma/knowledge-base-contracts", + runtimeExport: "knowledgePermissions", + runtimeExportType: "object", + }, + { + directory: "core", + name: "@pegma/knowledge-base-core", + runtimeExport: "createArticle", + runtimeExportType: "function", + }, + { + directory: "application", + name: "@pegma/knowledge-base-application", + runtimeExport: "createKnowledgeBaseApplication", + runtimeExportType: "function", + }, + { + directory: "mcp", + name: "@pegma/knowledge-base-mcp", + runtimeExport: "createKnowledgeAgentDispatcher", + runtimeExportType: "function", + }, + ].map((entry) => Object.freeze(entry)), +); + +export function releaseDependencies(directory, version) { + if (typeof version !== "string" || !STABLE_VERSION.test(version)) { + throw new Error("release version must be stable semver"); + } + if (!RELEASE_PACKAGES.some((entry) => entry.directory === directory)) { + throw new Error("release package is not in the reviewed package set"); + } + const contracts = { "@pegma/spine": "0.1.2" }; + const core = { "@pegma/knowledge-base-contracts": version }; + const application = { + "@pegma/audit": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-contracts": version, + "@pegma/knowledge-base-core": version, + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", + }; + const mcp = { + "@cfworker/json-schema": "4.1.6", + "@modelcontextprotocol/sdk": "1.32.2", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-application": version, + "@pegma/knowledge-base-contracts": version, + "@pegma/knowledge-base-core": version, + zod: "4.6.7", + }; + const dependencies = { contracts, core, application, mcp }[directory]; + return Object.freeze(dependencies); +} + +function fail(message) { + throw new Error(message); +} + +function git(root, arguments_, allowFailure = false) { + const env = { ...process.env }; + // Preserve the host's approved local/global signer configuration, including + // GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM. Command-scope config injection + // must not override that policy or select another repository/object database. + const excluded = new Set([ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_CONFIG", + "GIT_CONFIG_COUNT", + "GIT_CONFIG_PARAMETERS", + "GIT_NO_REPLACE_OBJECTS", + ]); + for (const key of Object.keys(env)) { + // Environment names are case-insensitive on Windows. Inspect the copied + // keys as well as their canonical spelling before spawning native Git. + const normalized = key.toUpperCase(); + if ( + excluded.has(normalized) || + /^GIT_CONFIG_(?:KEY|VALUE)_/u.test(normalized) + ) { + delete env[key]; + } + } + env.GIT_NO_REPLACE_OBJECTS = "1"; + const result = spawnSync( + process.platform === "win32" ? "git.exe" : "git", + ["--no-replace-objects", ...arguments_], + { + cwd: root, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + maxBuffer: 4 * 1024 * 1024, + timeout: 30_000, + }, + ); + if (result.error || (!allowFailure && result.status !== 0)) { + fail("release identity Git verification failed"); + } + return result; +} + +export function verifyReleaseIdentity({ + root = fileURLToPath(new URL("../", import.meta.url)), + tag, + expectedCommit, + version, +} = {}) { + if ( + typeof version !== "string" || + !STABLE_VERSION.test(version) || + tag !== `v${version}` + ) { + fail("release tag must match the stable package version"); + } + if ( + typeof expectedCommit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(expectedCommit) + ) { + fail("release event must supply the exact expected commit"); + } + let checkout; + try { + checkout = realpathSync(resolve(root)); + const gitRoot = git(checkout, [ + "rev-parse", + "--show-toplevel", + ]).stdout.trim(); + if (realpathSync(gitRoot) !== checkout) { + fail("release identity requires the checkout root"); + } + } catch { + fail("release identity requires the checkout root"); + } + const origin = git(checkout, ["remote", "get-url", "origin"]).stdout.trim(); + if ( + !/^(?:https:\/\/github\.com\/pegma-dev\/knowledge-base(?:\.git)?|git@github\.com:pegma-dev\/knowledge-base(?:\.git)?|ssh:\/\/git@github\.com\/pegma-dev\/knowledge-base(?:\.git)?)$/u.test( + origin, + ) + ) { + fail("release origin must be the reviewed source repository"); + } + if ( + git(checkout, ["rev-parse", "--is-shallow-repository"]).stdout.trim() !== + "false" + ) { + fail("release identity requires complete Git ancestry"); + } + if ( + git(checkout, [ + "status", + "--porcelain=v1", + "--untracked-files=all", + "--ignore-submodules=none", + ]).stdout !== "" + ) { + fail("release preparation requires a clean checkout"); + } + const tagRef = `refs/tags/${tag}`; + const type = git(checkout, ["cat-file", "-t", tagRef], true); + if (type.status !== 0 || type.stdout.trim() !== "tag") { + fail("release ref must be an annotated tag object"); + } + const commit = git(checkout, ["rev-parse", "HEAD"]).stdout.trim(); + const tagCommit = git(checkout, [ + "rev-parse", + `${tagRef}^{commit}`, + ]).stdout.trim(); + if (commit !== expectedCommit || tagCommit !== expectedCommit) { + fail("release checkout, tag target, and event commit must match"); + } + // Signer approval comes from the workflow's reviewed Git verification + // configuration (for example SSH allowedSignersFile), never from this script. + if (git(checkout, ["verify-tag", "--raw", tagRef], true).status !== 0) { + fail("release tag signature is not valid for an approved signer"); + } + if ( + git( + checkout, + ["merge-base", "--is-ancestor", commit, "refs/remotes/origin/main"], + true, + ).status !== 0 + ) { + fail("release tag commit must be contained in origin/main"); + } + return Object.freeze({ + repository: RELEASE_REPOSITORY, + tag, + commit, + version, + }); +} diff --git a/scripts/release-manifest.mjs b/scripts/release-manifest.mjs new file mode 100644 index 0000000..8784bbd --- /dev/null +++ b/scripts/release-manifest.mjs @@ -0,0 +1,327 @@ +import { constants } from "node:fs"; +import { lstat, open, realpath, writeFile } from "node:fs/promises"; +import { createHash, timingSafeEqual } from "node:crypto"; +import { basename, dirname, join, resolve } from "node:path"; +import { + RELEASE_PACKAGES, + RELEASE_REPOSITORY, + STABLE_VERSION, + releaseDependencies, +} from "./release-contract.mjs"; + +export const PREPARED_MANIFEST_LIMITS = Object.freeze({ + manifestBytes: 2 * 1024 * 1024, + artifactBytes: 16 * 1024 * 1024, + totalArtifactBytes: 64 * 1024 * 1024, + filesPerArtifact: 4096, + fileBytes: 32 * 1024 * 1024, + unpackedBytesPerArtifact: 64 * 1024 * 1024, +}); + +function fail() { + throw new Error("prepared release manifest or artifact verification failed"); +} + +function exactKeys(value, expected) { + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) + ) { + fail(); + } + const keys = Reflect.ownKeys(value); + if ( + keys.length !== expected.length || + keys.some((key) => typeof key !== "string" || !expected.includes(key)) + ) { + fail(); + } +} + +function boundedInteger(value, maximum, minimum = 0) { + if (!Number.isSafeInteger(value) || value < minimum || value > maximum) { + fail(); + } +} + +function safeEqual(left, right) { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} + +function hash(bytes, algorithm, encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +function validateIdentity(identity) { + exactKeys(identity, ["repository", "tag", "commit", "version"]); + if ( + identity.repository !== RELEASE_REPOSITORY || + typeof identity.version !== "string" || + !STABLE_VERSION.test(identity.version) || + identity.tag !== `v${identity.version}` || + typeof identity.commit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(identity.commit) + ) { + fail(); + } +} + +function validateFiles(files) { + if ( + !Array.isArray(files) || + files.length < 5 || + files.length > PREPARED_MANIFEST_LIMITS.filesPerArtifact + ) { + fail(); + } + const paths = new Set(); + let total = 0; + for (const file of files) { + exactKeys(file, ["path", "size"]); + if ( + typeof file.path !== "string" || + file.path.length > 256 || + paths.has(file.path) || + file.path + .split("/") + .some((part) => part === "" || part === "." || part === "..") || + (!["package.json", "README.md", "LICENSE"].includes(file.path) && + (!/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( + file.path, + ) || + /\.(?:test|spec)\./u.test(file.path))) + ) { + fail(); + } + boundedInteger(file.size, PREPARED_MANIFEST_LIMITS.fileBytes); + total += file.size; + if (total > PREPARED_MANIFEST_LIMITS.unpackedBytesPerArtifact) fail(); + paths.add(file.path); + } + for (const required of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.js", + "dist/index.d.ts", + ]) { + if (!paths.has(required)) fail(); + } +} + +function deepFreeze(value) { + for (const child of Object.values(value)) { + if (child !== null && typeof child === "object") deepFreeze(child); + } + return Object.freeze(value); +} + +export function validatePreparedManifest(manifest) { + exactKeys(manifest, ["schemaVersion", "identity", "artifacts"]); + if (manifest.schemaVersion !== 2) fail(); + validateIdentity(manifest.identity); + if ( + !Array.isArray(manifest.artifacts) || + manifest.artifacts.length !== RELEASE_PACKAGES.length + ) { + fail(); + } + let total = 0; + for (const [index, record] of manifest.artifacts.entries()) { + const specification = RELEASE_PACKAGES[index]; + exactKeys(record, [ + "name", + "version", + "filename", + "size", + "shasum", + "integrity", + "dependencies", + "files", + ]); + const filename = `${specification.name.slice(1).replace("/", "-")}-${manifest.identity.version}.tgz`; + if ( + record.name !== specification.name || + record.version !== manifest.identity.version || + record.filename !== filename || + basename(record.filename) !== record.filename || + record.filename.length > 200 || + typeof record.shasum !== "string" || + !/^[0-9a-f]{40}$/u.test(record.shasum) || + typeof record.integrity !== "string" || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) + ) { + fail(); + } + boundedInteger(record.size, PREPARED_MANIFEST_LIMITS.artifactBytes, 1); + total += record.size; + if (total > PREPARED_MANIFEST_LIMITS.totalArtifactBytes) fail(); + const dependencies = releaseDependencies( + specification.directory, + record.version, + ); + exactKeys(record.dependencies, Object.keys(dependencies)); + for (const [name, version] of Object.entries(dependencies)) { + if (record.dependencies[name] !== version) fail(); + } + validateFiles(record.files); + } + return deepFreeze(manifest); +} + +async function canonicalDirectory(preparedDir) { + if (typeof preparedDir !== "string" || preparedDir.length === 0) fail(); + const directory = resolve(preparedDir); + const metadata = await lstat(directory); + if (!metadata.isDirectory() || metadata.isSymbolicLink()) fail(); + return realpath(directory); +} + +async function readBoundedFile(path, directory, maximum) { + if (dirname(resolve(path)) !== directory) fail(); + const metadata = await lstat(path); + if (!metadata.isFile() || metadata.isSymbolicLink()) fail(); + if ((await realpath(path)) !== join(directory, basename(path))) fail(); + boundedInteger(metadata.size, maximum, 1); + 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(); + } + // Read no more than the validated size plus one byte, including if a file + // grows concurrently. No archive contents or package scripts are executed. + 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 === 0) break; + length += read.bytesRead; + } + if (length !== metadata.size) fail(); + return bytes.subarray(0, length); + } finally { + await handle.close(); + } +} + +async function verifyArtifacts(manifest, directory) { + const artifacts = []; + for (const record of manifest.artifacts) { + const path = join(directory, record.filename); + const bytes = await readBoundedFile( + path, + directory, + PREPARED_MANIFEST_LIMITS.artifactBytes, + ); + if ( + bytes.length !== record.size || + !safeEqual(hash(bytes, "sha1"), record.shasum) || + !safeEqual(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail(); + } + artifacts.push(Object.freeze({ ...record, path })); + } + return Object.freeze(artifacts); +} + +export async function writePreparedManifest({ + preparedDir, + identity, + artifacts, +} = {}) { + try { + // Copy the approved data before freezing it; never freeze the producer's + // npm metadata or mutable source package manifests as a side effect. + const manifest = validatePreparedManifest( + structuredClone({ schemaVersion: 2, identity, artifacts }), + ); + const directory = await canonicalDirectory(preparedDir); + await verifyArtifacts(manifest, directory); + const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + if (bytes.length > PREPARED_MANIFEST_LIMITS.manifestBytes) fail(); + const manifestPath = join(directory, "manifest.json"); + await writeFile(manifestPath, bytes, { flag: "wx", mode: 0o644 }); + return Object.freeze({ + manifestPath, + manifest, + manifestSha256: hash(bytes, "sha256"), + }); + } catch { + fail(); + } +} + +export async function verifyPreparedManifest({ + preparedDir, + manifestPath, + expectedManifestSha256, + expectedTag, + expectedCommit, + expectedVersion, +} = {}) { + try { + if ( + typeof expectedManifestSha256 !== "string" || + !/^[0-9a-f]{64}$/u.test(expectedManifestSha256) || + typeof expectedTag !== "string" || + typeof expectedCommit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(expectedCommit) + ) { + fail(); + } + const directory = await canonicalDirectory(preparedDir); + const path = + manifestPath === undefined + ? join(directory, "manifest.json") + : resolve(manifestPath); + if (basename(path) !== "manifest.json") fail(); + const bytes = await readBoundedFile( + path, + directory, + PREPARED_MANIFEST_LIMITS.manifestBytes, + ); + const manifestSha256 = hash(bytes, "sha256"); + if (!safeEqual(manifestSha256, expectedManifestSha256)) fail(); + const manifest = validatePreparedManifest( + JSON.parse(bytes.toString("utf8")), + ); + if ( + manifest.identity.tag !== expectedTag || + manifest.identity.commit !== expectedCommit || + (expectedVersion !== undefined && + manifest.identity.version !== expectedVersion) + ) { + fail(); + } + const artifacts = await verifyArtifacts(manifest, directory); + return Object.freeze({ + manifestPath: path, + manifest, + manifestSha256, + artifacts, + }); + } catch { + // Do not include parsed contents, paths, environment values, native command + // output, or registry credentials in release errors. + fail(); + } +} diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 947d212..c160d0b 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,48 +1,44 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; +import { constants } from "node:fs"; import { access, + appendFile, copyFile, + lstat, mkdtemp, mkdir, readFile, + readdir, realpath, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { basename, delimiter, dirname, join } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + resolve, +} from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { + RELEASE_PACKAGES, + STABLE_VERSION, + releaseDependencies, + verifyReleaseIdentity, +} from "./release-contract.mjs"; +import { + verifyPreparedManifest, + writePreparedManifest, +} from "./release-manifest.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); -const packages = [ - { - directory: "contracts", - name: "@pegma/knowledge-base-contracts", - runtimeExport: "knowledgePermissions", - runtimeExportType: "object", - }, - { - directory: "core", - name: "@pegma/knowledge-base-core", - runtimeExport: "createArticle", - runtimeExportType: "function", - }, - { - directory: "application", - name: "@pegma/knowledge-base-application", - runtimeExport: "createKnowledgeBaseApplication", - runtimeExportType: "function", - }, - { - directory: "mcp", - name: "@pegma/knowledge-base-mcp", - runtimeExport: "createKnowledgeAgentDispatcher", - runtimeExportType: "function", - }, -]; -const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +const packages = RELEASE_PACKAGES; +export { RELEASE_PACKAGES, releaseDependencies }; function run(command, arguments_, cwd, env = process.env) { const result = spawnSync(command, arguments_, { @@ -70,7 +66,64 @@ async function exists(path) { } } -async function npmCliPath() { +export async function resolveReleaseNpmCli(env = process.env) { + const candidate = env.RELEASE_NPM_CLI; + assert.ok( + typeof candidate === "string" && + isAbsolute(candidate) && + basename(candidate) === "npm-cli.js", + "The reviewed release npm CLI must be an explicit absolute npm-cli.js path.", + ); + assert.equal( + env.RELEASE_NPM_VERSION, + "11.18.0", + "Release preparation requires the reviewed npm version.", + ); + const path = resolve(candidate); + const metadata = await lstat(path); + assert.ok( + metadata.isFile() && !metadata.isSymbolicLink(), + "The release npm CLI must be a regular file.", + ); + const canonical = await realpath(path); + assert.equal( + canonical, + path, + "The release npm CLI must use its canonical path.", + ); + return canonical; +} + +async function npmCliPath(preparedRelease = false) { + if (preparedRelease) { + const candidate = await resolveReleaseNpmCli(); + const [major, minor] = process.versions.node.split(".").map(Number); + assert.ok( + major > 22 || (major === 22 && minor >= 14), + "Release preparation requires Node 22.14 or newer.", + ); + const versionEnvironment = {}; + for (const [key, value] of Object.entries(process.env)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) + ) { + versionEnvironment[key] = value; + } + } + assert.equal( + run( + process.execPath, + [candidate, "--version"], + tmpdir(), + versionEnvironment, + ), + "11.18.0", + "Release preparation npm CLI differs from the reviewed version.", + ); + return candidate; + } const directories = [ dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean), @@ -104,7 +157,7 @@ async function validatePackages() { const directory = join(root, "packages", specification.directory); const manifest = await json(join(directory, "package.json")); assert.equal(manifest.name, specification.name); - assert.match(manifest.version, stableVersion); + assert.match(manifest.version, STABLE_VERSION); assert.equal(manifest.version, manifests[0]?.version ?? manifest.version); assert.equal( manifest.private, @@ -113,8 +166,13 @@ async function validatePackages() { ); assert.equal(manifest.type, "module"); assert.equal(manifest.license, "MIT"); - assert.equal(manifest.publishConfig?.access, "public"); + assert.deepEqual(manifest.publishConfig, { access: "public" }); assert.equal(manifest.engines?.node, ">=22"); + assert.deepEqual(manifest.repository, { + type: "git", + url: "git+https://github.com/pegma-dev/knowledge-base.git", + directory: `packages/${specification.directory}`, + }); assert.ok( ["pnpm run build", "pnpm run --silent build"].includes( manifest.scripts?.prepack, @@ -126,29 +184,16 @@ async function validatePackages() { }); assert.deepEqual( manifest.dependencies, - specification.directory === "mcp" - ? { - "@cfworker/json-schema": "4.1.6", - "@modelcontextprotocol/sdk": "1.32.2", - "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": manifest.version, - "@pegma/knowledge-base-contracts": manifest.version, - "@pegma/knowledge-base-core": manifest.version, - zod: "4.6.7", - } - : specification.directory === "application" - ? { - "@pegma/audit": "0.2.0", - "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-contracts": manifest.version, - "@pegma/knowledge-base-core": manifest.version, - "@pegma/spine": "0.1.2", - "@pegma/storage-core": "0.4.0", - } - : specification.directory === "core" - ? { "@pegma/knowledge-base-contracts": manifest.version } - : { "@pegma/spine": "0.1.2" }, + releaseDependencies(specification.directory, manifest.version), ); + for (const kind of [ + "peerDependencies", + "optionalDependencies", + "bundledDependencies", + "bundleDependencies", + ]) { + assert.equal(manifest[kind], undefined); + } for (const document of ["README.md", "LICENSE"]) { const content = await readFile(join(directory, document), "utf8"); assert.ok( @@ -164,6 +209,21 @@ async function validatePackages() { ); manifests.push(manifest); } + const publicPackages = []; + for (const entry of await readdir(join(root, "packages"), { + withFileTypes: true, + })) { + if (!entry.isDirectory()) continue; + const manifest = await json( + join(root, "packages", entry.name, "package.json"), + ); + if (manifest.private !== true) publicPackages.push(manifest.name); + } + assert.deepEqual( + publicPackages.sort(), + packages.map(({ name }) => name).sort(), + "The public workspace must contain exactly the reviewed release packages.", + ); return manifests; } @@ -192,18 +252,18 @@ function validateInventory(metadata) { } } -async function prepare(mode) { - assert.ok( - ["check", "pack"].includes(mode), - "Usage: release-packages.mjs check|pack", - ); - assert.equal( - process.argv.length, - 3, - "No additional arguments are supported.", - ); +async function prepareArtifacts(mode, options = {}) { const manifests = await validatePackages(); - const npm = await npmCliPath(); + const identity = + mode === "prepare" + ? verifyReleaseIdentity({ + root, + tag: options.tag, + expectedCommit: options.expectedCommit, + version: manifests[0].version, + }) + : undefined; + const npm = await npmCliPath(mode === "prepare"); const temporaryParent = await realpath(tmpdir()); const temporary = await mkdtemp(join(temporaryParent, "pegma-kb-release-")); try { @@ -214,6 +274,20 @@ async function prepare(mode) { npm_config_userconfig: npmrc, npm_config_registry: "https://registry.npmjs.org/", }; + await cleanBuildOutputs(); + run( + process.execPath, + [ + join(root, "node_modules", "typescript", "bin", "tsc"), + "-b", + "--force", + ...packages.map(({ directory }) => + join(root, "packages", directory, "tsconfig.json"), + ), + ], + root, + env, + ); const artifacts = []; for (const [index, specification] of packages.entries()) { const output = run( @@ -235,8 +309,13 @@ async function prepare(mode) { assert.equal(metadata.name, specification.name); assert.equal(metadata.version, manifests[index].version); assert.equal(basename(metadata.filename), metadata.filename); + assert.equal( + metadata.filename, + `${specification.name.slice(1).replace("/", "-")}-${manifests[index].version}.tgz`, + ); validateInventory(metadata); const bytes = await readFile(join(temporary, metadata.filename)); + assert.equal(bytes.length, metadata.size); assert.equal( createHash("sha1").update(bytes).digest("hex"), metadata.shasum, @@ -372,6 +451,44 @@ assert.equal(initializedBody.result.serverInfo.version, mcpManifest.version); ); console.log(`Prepared verified artifacts in ${destination}`); } + if (mode === "prepare") { + // Check the reviewed source again after build and consumer execution, + // before creating any output directory that could dirty the checkout. + assert.deepEqual( + verifyReleaseIdentity({ + root, + tag: options.tag, + expectedCommit: options.expectedCommit, + version: identity.version, + }), + identity, + ); + const preparedDir = await preparedDirectory(options.output); + for (const { filename } of artifacts) { + await copyFile( + join(temporary, filename), + join(preparedDir, filename), + constants.COPYFILE_EXCL, + ); + } + const prepared = await writePreparedManifest({ + preparedDir, + identity, + artifacts: artifacts.map((artifact, index) => ({ + name: artifact.name, + version: artifact.version, + filename: artifact.filename, + size: artifact.size, + shasum: artifact.shasum, + integrity: artifact.integrity, + dependencies: manifests[index].dependencies, + files: artifact.files + .map(({ path, size }) => ({ path, size })) + .sort((left, right) => left.path.localeCompare(right.path)), + })), + }); + return { preparedDir, ...prepared }; + } console.log( `Verified packaging and clean-consumer imports for ${artifacts.length} packages, including MCP server metadata.`, ); @@ -383,7 +500,255 @@ assert.equal(initializedBody.result.serverInfo.version, mcpManifest.version); } } -prepare(process.argv[2]).catch((error) => { - console.error(error.message); - process.exitCode = 1; -}); +async function optionalMetadata(path) { + try { + return await lstat(path); + } catch (error) { + if (error.code === "ENOENT") return undefined; + throw error; + } +} + +async function canonicalNode(path, kind) { + const metadata = await lstat(path); + assert.ok( + !metadata.isSymbolicLink() && + (kind === "directory" ? metadata.isDirectory() : metadata.isFile()), + "Release build output paths must not contain symlinks or special files.", + ); + assert.equal( + await realpath(path), + path, + "Release build output paths must stay inside their canonical package.", + ); +} + +async function validateOutputTree(path) { + await canonicalNode(path, "directory"); + for (const entry of await readdir(path, { withFileTypes: true })) { + const child = join(path, entry.name); + assert.equal(dirname(child), path); + if (entry.isDirectory()) { + await validateOutputTree(child); + } else { + await canonicalNode(child, "file"); + } + } +} + +export async function cleanBuildOutputs(checkoutRoot = root) { + const checkout = resolve(checkoutRoot); + await canonicalNode(checkout, "directory"); + const packageRoot = join(checkout, "packages"); + await canonicalNode(packageRoot, "directory"); + const outputs = []; + // Preflight every target before removing any file. Output names are fixed by + // this reviewed producer; never turn tsconfig values into deletion targets. + for (const specification of packages) { + const packageDirectory = join(packageRoot, specification.directory); + assert.equal(dirname(packageDirectory), packageRoot); + await canonicalNode(packageDirectory, "directory"); + const configurationPath = join(packageDirectory, "tsconfig.json"); + await canonicalNode(configurationPath, "file"); + const configuration = await json(configurationPath); + assert.equal(configuration.compilerOptions?.outDir, "dist"); + assert.equal(configuration.compilerOptions?.rootDir, "src"); + assert.equal( + configuration.compilerOptions?.tsBuildInfoFile, + "tsconfig.tsbuildinfo", + ); + const directory = join(packageDirectory, "dist"); + const buildInfo = join(packageDirectory, "tsconfig.tsbuildinfo"); + assert.equal(dirname(directory), packageDirectory); + assert.equal(dirname(buildInfo), packageDirectory); + if (await optionalMetadata(directory)) await validateOutputTree(directory); + if (await optionalMetadata(buildInfo)) + await canonicalNode(buildInfo, "file"); + outputs.push({ directory, buildInfo }); + } + for (const { directory, buildInfo } of outputs) { + // Recheck the exact targets immediately before deletion as well. Do not + // follow junctions/symlinks even when they point back inside the checkout. + if (await optionalMetadata(directory)) { + await validateOutputTree(directory); + await rm(directory, { recursive: true, force: true }); + } + if (await optionalMetadata(buildInfo)) { + await canonicalNode(buildInfo, "file"); + await rm(buildInfo); + } + } +} + +async function preparedDirectory(output) { + if (output === undefined) { + const releases = join(root, ".release"); + await mkdir(releases, { recursive: true }); + return realpath(await mkdtemp(join(releases, "knowledge-base-"))); + } + assert.equal(typeof output, "string", "Release output must be a directory."); + assert.ok(output.length > 0, "Release output must be a directory."); + const destination = resolve(root, output); + await mkdir(destination, { recursive: true }); + const metadata = await lstat(destination); + assert.ok( + metadata.isDirectory() && !metadata.isSymbolicLink(), + "Release output must be a regular directory.", + ); + assert.equal( + (await readdir(destination)).length, + 0, + "Release output directory must be empty.", + ); + return realpath(destination); +} + +export async function prepareRelease(options = {}) { + return prepareArtifacts("prepare", options); +} + +export async function preflightRelease(options = {}) { + const verified = await verifyPreparedManifest(options); + const { preflightRegistry } = await import("./release-registry.mjs"); + return preflightRegistry(verified); +} + +export async function publishPreparedRelease(options = {}) { + await verifyPreparedManifest(options); + const { publishPreparedRelease: publish } = + await import("./release-registry.mjs"); + return publish(options); +} + +export async function verifyRelease(options = {}) { + await verifyPreparedManifest(options); + const { verifyRegistryRelease } = await import("./release-registry.mjs"); + return verifyRegistryRelease(options); +} + +const usage = + "Usage: release-packages.mjs check|pack|prepare|preflight|publish|verify [options]"; + +export function parseArguments(arguments_) { + const [command, ...flags] = arguments_; + assert.ok( + ["check", "pack", "prepare", "preflight", "publish", "verify"].includes( + command, + ), + usage, + ); + if (command === "check" || command === "pack") { + assert.equal(flags.length, 0, "No additional arguments are supported."); + return { command, options: {} }; + } + const keys = + command === "prepare" + ? { + "--tag": "tag", + "--expected-commit": "expectedCommit", + "--out": "output", + } + : { + "--prepared-dir": "preparedDir", + "--manifest-sha256": "expectedManifestSha256", + "--tag": "expectedTag", + "--expected-commit": "expectedCommit", + }; + const options = {}; + for (let index = 0; index < flags.length; index += 2) { + const key = Object.hasOwn(keys, flags[index]) + ? keys[flags[index]] + : undefined; + const value = flags[index + 1]; + assert.ok( + key !== undefined && + !Object.hasOwn(options, key) && + typeof value === "string" && + value.length > 0 && + !value.startsWith("--") && + !/[\u0000-\u001f\u007f]/u.test(value), + "Unknown, repeated, or incomplete release argument.", + ); + options[key] = value; + } + const tag = command === "prepare" ? options.tag : options.expectedTag; + assert.ok( + typeof tag === "string" && + tag.startsWith("v") && + STABLE_VERSION.test(tag.slice(1)), + "An exact stable release tag is required.", + ); + assert.ok( + typeof options.expectedCommit === "string" && + /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(options.expectedCommit), + "An exact release event commit is required.", + ); + if (command !== "prepare") { + assert.equal( + typeof options.preparedDir, + "string", + "A prepared release directory is required.", + ); + assert.ok( + typeof options.expectedManifestSha256 === "string" && + /^[0-9a-f]{64}$/u.test(options.expectedManifestSha256), + "An independent prepared manifest SHA-256 is required.", + ); + } + return { command, options }; +} + +async function reportPrepared(prepared) { + const values = { + "prepared-dir": prepared.preparedDir, + "manifest-path": prepared.manifestPath, + "manifest-sha256": prepared.manifestSha256, + }; + const output = Object.entries(values) + .map(([key, value]) => { + assert.ok( + !/[\u0000-\u001f\u007f]/u.test(value), + "Release output must be single-line.", + ); + return `${key}=${value}\n`; + }) + .join(""); + process.stdout.write(output); + if (process.env.GITHUB_ACTIONS === "true" && process.env.GITHUB_OUTPUT) { + await appendFile(process.env.GITHUB_OUTPUT, output); + } +} + +async function main() { + const { command, options } = parseArguments(process.argv.slice(2)); + if (command === "check" || command === "pack") { + await prepareArtifacts(command); + } else if (command === "prepare") { + await reportPrepared(await prepareRelease(options)); + } else if (command === "preflight") { + const plan = await preflightRelease(options); + for (const record of plan) { + console.log(`${record.name}@${record.version}: ${record.action}`); + } + } else if (command === "publish") { + const result = await publishPreparedRelease(options); + console.log( + `Verified publication of ${result.published.length} packages; ${result.skipped.length} already identical.`, + ); + } else { + const result = await verifyRelease(options); + console.log( + `Verified registry release and clean consumer for ${result.packages.length} packages.`, + ); + } +} + +if ( + process.argv[1] !== undefined && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs new file mode 100644 index 0000000..83333da --- /dev/null +++ b/scripts/release-registry.mjs @@ -0,0 +1,691 @@ +import { spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual, X509Certificate } from "node:crypto"; +import { + copyFile, + lstat, + mkdtemp, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { RELEASE_PACKAGES, RELEASE_REPOSITORY } from "./release-contract.mjs"; +import { + validatePreparedManifest, + verifyPreparedManifest, +} from "./release-manifest.mjs"; + +export const RELEASE_NPM_VERSION = "11.18.0"; +export const RELEASE_WORKFLOW = ".github/workflows/publish.yml"; +const registry = "https://registry.npmjs.org/"; +const provenanceType = "https://slsa.dev/provenance/v1"; +const temporaryPrefix = "knowledge-base-registry-"; + +function fail(message) { + // Never surface native command output, registry response bodies, or credentials. + throw new Error(message); +} + +function equal(left, right) { + if (typeof left !== "string" || typeof right !== "string") return false; + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} + +function hash(bytes, algorithm, encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +function sameDependencies(actual, expected) { + return ( + actual !== null && + typeof actual === "object" && + !Array.isArray(actual) && + Object.keys(actual).length === Object.keys(expected).length && + Object.entries(expected).every( + ([name, version]) => actual[name] === version, + ) + ); +} + +function tarballUrl(record) { + return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; +} + +async function responseBytes(response, maximum) { + const length = response.headers?.get("content-length"); + if ( + length !== null && + length !== undefined && + (!/^\d+$/u.test(length) || Number(length) > maximum) + ) { + await response.body?.cancel(); + fail("registry response exceeded its release verification limit"); + } + const chunks = []; + let size = 0; + if (response.body === null || response.body === undefined) + return Buffer.alloc(0); + for await (const chunk of response.body) { + size += chunk.length; + if (size > maximum) { + fail("registry response exceeded its release verification limit"); + } + chunks.push(Buffer.from(chunk)); + } + return Buffer.concat(chunks, size); +} + +async function request(url, fetch) { + try { + return await fetch(url, { + redirect: "error", + signal: AbortSignal.timeout(30_000), + headers: { accept: "application/json" }, + }); + } catch { + fail("registry lookup failed; package availability is unknown"); + } +} + +async function registryRecord(record, fetch) { + const response = await request( + `${registry}${encodeURIComponent(record.name)}/${record.version}`, + fetch, + ); + // Authentication errors, throttling, server errors, redirects, and malformed + // responses are unknown states. Only this exact response establishes absence. + if (response.status === 404) { + await response.body?.cancel(); + return null; + } + if (response.status !== 200) { + await response.body?.cancel(); + fail("registry lookup failed; package availability is unknown"); + } + let metadata; + try { + metadata = JSON.parse( + (await responseBytes(response, 2 * 1024 * 1024)).toString("utf8"), + ); + } catch { + fail("registry package metadata verification failed"); + } + if ( + metadata?.name !== record.name || + metadata.version !== record.version || + !sameDependencies(metadata.dependencies, record.dependencies) || + !equal(metadata.dist?.integrity, record.integrity) || + !equal(metadata.dist?.shasum, record.shasum) || + metadata.dist?.tarball !== tarballUrl(record) || + [ + "optionalDependencies", + "peerDependencies", + "bundledDependencies", + "bundleDependencies", + ].some((key) => metadata[key] !== undefined) + ) { + fail("registry version conflicts with the prepared release"); + } + const tarball = await request(metadata.dist.tarball, fetch); + if (tarball.status !== 200) { + await tarball.body?.cancel(); + fail("registry tarball verification failed"); + } + let bytes; + try { + bytes = await responseBytes(tarball, record.size); + } catch { + fail("registry tarball verification failed"); + } + if ( + bytes.length !== record.size || + !equal(hash(bytes, "sha1"), record.shasum) || + !equal(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail("registry tarball conflicts with the prepared release"); + } + return metadata; +} + +export async function preflightRegistry( + verified, + { fetch = globalThis.fetch } = {}, +) { + const manifest = validatePreparedManifest(verified?.manifest); + const decisions = []; + // Finish the entire set before the caller can publish even the first package. + for (const record of manifest.artifacts) { + const metadata = await registryRecord(record, fetch); + decisions.push( + Object.freeze({ + name: record.name, + version: record.version, + action: metadata === null ? "publish" : "skip", + ...(metadata === null ? {} : { metadata }), + }), + ); + } + return Object.freeze(decisions); +} + +export function assertTrustedPublishingEnvironment(env, identity) { + const workflow = `${RELEASE_REPOSITORY}/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}`; + let oidcUrl; + try { + oidcUrl = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL); + } catch { + fail("publishing requires the approved GitHub Actions OIDC environment"); + } + if ( + env.GITHUB_ACTIONS !== "true" || + env.GITHUB_EVENT_NAME !== "release" || + env.GITHUB_REPOSITORY !== RELEASE_REPOSITORY || + env.GITHUB_SERVER_URL !== "https://github.com" || + env.GITHUB_REF !== `refs/tags/${identity.tag}` || + env.GITHUB_SHA !== identity.commit || + env.GITHUB_WORKFLOW_REF !== workflow || + env.GITHUB_WORKFLOW_SHA !== identity.commit || + env.RUNNER_ENVIRONMENT !== "github-hosted" || + oidcUrl.protocol !== "https:" || + oidcUrl.username !== "" || + oidcUrl.password !== "" || + !/^(?:[A-Za-z0-9-]+\.)*actions\.githubusercontent\.com$/u.test( + oidcUrl.hostname, + ) || + typeof env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== "string" || + env.ACTIONS_ID_TOKEN_REQUEST_TOKEN.length === 0 + ) { + fail("publishing requires the approved GitHub Actions OIDC environment"); + } + if ( + Object.entries(env).some( + ([key, value]) => + value !== undefined && + value !== "" && + (/^(?:NODE_AUTH_TOKEN|NPM_TOKEN|NPM_AUTH_TOKEN|NPM_AUTH|YARN_NPM_AUTH_TOKEN)$/iu.test( + key, + ) || + /^npm_config_/iu.test(key)), + ) + ) { + fail("publishing rejects npm credentials and inherited npm configuration"); + } +} + +async function nativeRun(command, arguments_, { cwd, env }) { + const result = spawnSync(command, arguments_, { + cwd, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + maxBuffer: 16 * 1024 * 1024, + timeout: 5 * 60_000, + }); + if (result.error || result.status !== 0) { + fail("release npm or consumer verification command failed"); + } + return result; +} + +async function temporary(action) { + const parent = await realpath(tmpdir()); + const directory = await mkdtemp(join(parent, temporaryPrefix)); + try { + return await action(directory); + } finally { + const target = await realpath(directory); + if ( + dirname(target) !== parent || + !basename(target).startsWith(temporaryPrefix) + ) { + fail("registry consumer cleanup refused an unexpected directory"); + } + await rm(target, { recursive: true, force: true }); + } +} + +function isolatedEnvironment(env, directory, publishing) { + const clean = {}; + // Pinned npm needs public provenance metadata and its OIDC request credential. + const publishingKeys = 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(env)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) || + (publishing && publishingKeys.has(key)) + ) { + clean[key] = value; + } + } + return { + ...clean, + 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", + ...(publishing ? { GITHUB_ACTIONS: "true" } : {}), + }; +} + +async function npmContext(options, seams, directory, publishing) { + const sourceEnv = seams.env ?? process.env; + const cli = options.npmCli ?? sourceEnv.RELEASE_NPM_CLI; + const version = + options.npmVersion ?? sourceEnv.RELEASE_NPM_VERSION ?? RELEASE_NPM_VERSION; + const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number); + if (nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 14)) { + fail("trusted release verification requires Node 22.14 or newer"); + } + if ( + typeof cli !== "string" || + !isAbsolute(cli) || + basename(cli) !== "npm-cli.js" || + version !== RELEASE_NPM_VERSION + ) { + fail("release operations require the reviewed pinned npm CLI"); + } + const resolvedCli = resolve(cli); + const metadata = await lstat(resolvedCli); + if ( + !metadata.isFile() || + metadata.isSymbolicLink() || + (await realpath(resolvedCli)) !== resolvedCli + ) { + fail("release operations require the reviewed pinned npm CLI"); + } + await writeFile(join(directory, "user.npmrc"), "", { flag: "wx" }); + await writeFile(join(directory, "global.npmrc"), "", { flag: "wx" }); + await writeFile(join(directory, ".npmrc"), `registry=${registry}\n`, { + flag: "wx", + }); + const env = isolatedEnvironment(sourceEnv, directory, publishing); + const run = seams.run ?? nativeRun; + const invoke = async (arguments_) => { + let result; + try { + result = await run(process.execPath, [resolvedCli, ...arguments_], { + cwd: directory, + env, + }); + } catch { + fail("release npm or consumer verification command failed"); + } + if (result?.status !== 0 || typeof result.stdout !== "string") { + fail("release npm or consumer verification command failed"); + } + return result.stdout; + }; + if ((await invoke(["--version"])).trim() !== version) { + fail("release operations require the reviewed pinned npm CLI"); + } + return { invoke, env, run }; +} + +function derValue(bytes, start) { + const tag = bytes[start]; + const initialLength = bytes[start + 1]; + if (initialLength === undefined) fail("invalid provenance certificate"); + let offset = start + 2; + let length = initialLength; + if (initialLength > 127) { + const count = initialLength & 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) { + // Fulcio's OIDC issuer extension (1.3.6.1.4.1.57264.1.1) distinguishes + // GitHub identities from other OIDC providers trusted by Sigstore. Parse DER + // structure, rather than searching for attacker-controlled certificate text. + const outer = derValue(certificate.raw, 0); + const 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 verifyCertificateIdentity(bundle, identity) { + try { + 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}/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}` || + certificateIssuer(certificate) !== + "https://token.actions.githubusercontent.com" + ) { + fail("invalid provenance certificate"); + } + } catch { + fail( + "verified provenance signer does not match the approved release workflow", + ); + } +} + +export function verifyProvenanceAudit(audit, manifest) { + validatePreparedManifest(manifest); + if ( + !Array.isArray(audit?.invalid) || + audit.invalid.length !== 0 || + !Array.isArray(audit.missing) || + audit.missing.length !== 0 || + !Array.isArray(audit.verified) + ) { + fail("registry signatures or provenance verification failed"); + } + const identity = manifest.identity; + for (const record of manifest.artifacts) { + const matches = audit.verified.filter( + (entry) => + entry.name === record.name && + entry.version === record.version && + entry.location === `node_modules/${record.name}` && + entry.registry === registry, + ); + if (matches.length !== 1 || !Array.isArray(matches[0].attestationBundles)) { + fail("release package is missing verified source provenance"); + } + const bundles = matches[0].attestationBundles.filter( + (entry) => entry.predicateType === provenanceType, + ); + if (bundles.length !== 1) + fail("release package is missing verified source provenance"); + verifyCertificateIdentity(bundles[0].bundle, identity); + let statement; + try { + const envelope = bundles[0].bundle.dsseEnvelope; + if ( + envelope.payloadType !== "application/vnd.in-toto+json" || + typeof envelope.payload !== "string" || + envelope.payload.length > 1024 * 1024 + ) { + fail("invalid provenance statement"); + } + statement = JSON.parse( + Buffer.from(envelope.payload, "base64").toString("utf8"), + ); + } catch { + fail("release source provenance verification failed"); + } + const definition = statement.predicate?.buildDefinition; + const workflow = definition?.externalParameters?.workflow; + const dependencies = definition?.resolvedDependencies; + const expectedDigest = Buffer.from( + record.integrity.slice(7), + "base64", + ).toString("hex"); + 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, expectedDigest) || + definition?.buildType !== + "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1" || + workflow?.repository !== `https://github.com/${RELEASE_REPOSITORY}` || + workflow.path !== RELEASE_WORKFLOW || + workflow.ref !== `refs/tags/${identity.tag}` || + definition.internalParameters?.github?.event_name !== "release" || + !Array.isArray(dependencies) || + dependencies.length !== 1 || + dependencies[0].uri !== + `git+https://github.com/${RELEASE_REPOSITORY}@refs/tags/${identity.tag}` || + !equal(dependencies[0].digest?.gitCommit, identity.commit) || + statement.predicate?.runDetails?.builder?.id !== + "https://github.com/actions/runner/github-hosted" + ) { + fail("release source provenance does not match the prepared identity"); + } + } +} + +async function registryConsumer(verified, options, seams) { + return temporary(async (directory) => { + const { invoke, env, run } = await npmContext( + options, + seams, + directory, + false, + ); + const dependencies = Object.fromEntries( + verified.manifest.artifacts.map((record) => [ + record.name, + record.version, + ]), + ); + await writeFile( + join(directory, "package.json"), + `${JSON.stringify({ + name: "knowledge-base-registry-proof", + private: true, + type: "module", + dependencies, + })}\n`, + { flag: "wx" }, + ); + // Exact registry specifiers only. No tarballs, workspace links, source build, + // project dependency installation, lifecycle scripts, or inherited npmrc. + await 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 verified.manifest.artifacts) { + const installed = lock.packages?.[`node_modules/${record.name}`]; + if ( + installed?.version !== record.version || + installed.link === true || + !equal(installed.integrity, record.integrity) || + installed.resolved !== tarballUrl(record) + ) { + fail("registry consumer did not install the prepared exact release"); + } + } + let audit; + try { + // npm performs the Sigstore/TUF cryptographic verification; the additional + // source checks below constrain the verified statement to this exact tag. + // https://docs.npmjs.com/generating-provenance-statements/#verifying-provenance-attestations + audit = JSON.parse( + await invoke([ + "audit", + "signatures", + "--json", + "--include-attestations", + "--registry", + registry, + ]), + ); + } catch { + fail("registry signatures or provenance verification failed"); + } + verifyProvenanceAudit(audit, verified.manifest); + // Authenticate all installed artifacts before executing any consumer import; + // imported package code must not be able to forge the preceding npm audit. + const source = `import assert from "node:assert/strict";\n${RELEASE_PACKAGES.map( + (entry) => + `assert.equal(typeof (await import(${JSON.stringify(entry.name)}))[${JSON.stringify(entry.runtimeExport)}], ${JSON.stringify(entry.runtimeExportType)});`, + ).join("\n")}\n`; + const consumer = join(directory, "consumer.mjs"); + await writeFile(consumer, source, { flag: "wx" }); + let imported; + try { + imported = await run(process.execPath, [consumer], { + cwd: directory, + env, + }); + } catch { + fail("registry consumer public imports failed"); + } + if (imported?.status !== 0) fail("registry consumer public imports failed"); + }); +} + +async function confirmRegistry(record, seams) { + const sleep = + seams.sleep ?? + ((milliseconds) => + new Promise((resolve_) => setTimeout(resolve_, milliseconds))); + for (let attempt = 0; attempt < 6; attempt += 1) { + if ( + (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null + ) + return; + if (attempt < 5) await sleep(2 ** attempt * 1000); + } + fail("published registry version was not visible after bounded verification"); +} + +async function verifyPublishedBytes(verified, seams) { + const plan = await preflightRegistry(verified, seams); + if (plan.some((entry) => entry.action !== "skip")) { + fail("the complete release set is not available from the registry"); + } + return Object.freeze({ + verified: true, + packages: Object.freeze(plan.map((entry) => entry.name)), + }); +} + +export async function verifyRegistryRelease(options = {}, seams = {}) { + const verified = await verifyPreparedManifest(options); + const result = await verifyPublishedBytes(verified, seams); + await registryConsumer(verified, options, seams); + return result; +} + +export async function publishPreparedRelease(options = {}, seams = {}) { + const verified = await verifyPreparedManifest(options); + assertTrustedPublishingEnvironment( + seams.env ?? process.env, + verified.manifest.identity, + ); + const plan = await preflightRegistry(verified, seams); + const published = []; + const skipped = []; + await temporary(async (directory) => { + const { invoke } = await npmContext(options, seams, directory, true); + // Snapshot the already verified bytes outside the checkout. Npm cannot read + // project .npmrc or run source/prepack scripts in this privileged job. + for (const record of verified.artifacts) { + const destination = join(directory, record.filename); + await copyFile(record.path, destination); + const bytes = await readFile(destination); + if ( + bytes.length !== record.size || + !equal(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail("prepared publish artifact changed after verification"); + } + } + for (const [index, decision] of plan.entries()) { + const record = verified.artifacts[index]; + if (decision.action === "skip") { + skipped.push(record.name); + continue; + } + const destination = join(directory, record.filename); + // Recheck immutable versions immediately before publication to recover + // another run's successful publication without overwriting anything. + if ( + (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null + ) { + skipped.push(record.name); + continue; + } + await invoke([ + "publish", + destination, + "--ignore-scripts", + "--access", + "public", + "--provenance", + "--registry", + registry, + ]); + published.push(record.name); + await confirmRegistry(record, seams); + } + }); + await verifyPublishedBytes(verified, seams); + return Object.freeze({ + published: Object.freeze(published), + skipped: Object.freeze(skipped), + verified: true, + }); +} diff --git a/scripts/test-release.mjs b/scripts/test-release.mjs new file mode 100644 index 0000000..509a439 --- /dev/null +++ b/scripts/test-release.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readdir } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const directory = fileURLToPath(new URL("../tests/release/", import.meta.url)); +const entries = await readdir(directory, { withFileTypes: true }); +const files = entries + .filter((entry) => entry.name.endsWith(".test.mjs")) + .map((entry) => { + assert.ok( + entry.isFile(), + "Release regression entries must be regular files.", + ); + return join(directory, entry.name); + }) + .sort(); +assert.ok(files.length > 0, "No release regression tests were found."); +const result = spawnSync(process.execPath, ["--test", ...files], { + shell: false, + stdio: "inherit", + timeout: 300_000, +}); +if (result.error) + throw new Error("Release regression tests could not complete."); +process.exitCode = result.status ?? 1; diff --git a/tests/release/arguments.test.mjs b/tests/release/arguments.test.mjs new file mode 100644 index 0000000..c928efb --- /dev/null +++ b/tests/release/arguments.test.mjs @@ -0,0 +1,242 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + mkdir, + readFile, + realpath, + symlink, + writeFile, +} from "node:fs/promises"; +import { join, sep } from "node:path"; +import { + parseArguments, + resolveReleaseNpmCli, +} from "../../scripts/release-packages.mjs"; +import { temporaryDirectory } from "./fixtures.mjs"; + +const commit = "a".repeat(40); +const manifestSha256 = "b".repeat(64); + +test("existing check and pack commands accept no publication options", () => { + for (const command of ["check", "pack"]) { + assert.deepEqual(parseArguments([command]), { command, options: {} }); + assert.throws(() => parseArguments([command, "--tag", "v0.1.0"])); + } +}); + +test("prepare requires an exact stable tag and independent commit before any work", () => { + assert.deepEqual( + parseArguments(["prepare", "--tag", "v0.1.0", "--expected-commit", commit]), + { command: "prepare", options: { tag: "v0.1.0", expectedCommit: commit } }, + ); + assert.deepEqual( + parseArguments([ + "prepare", + "--out", + "synthetic output", + "--expected-commit", + "c".repeat(64), + "--tag", + "v1.2.3", + ]), + { + command: "prepare", + options: { + output: "synthetic output", + expectedCommit: "c".repeat(64), + tag: "v1.2.3", + }, + }, + ); +}); + +test("preflight, publish, and verify require the same prepared artifact identity", () => { + for (const command of ["preflight", "publish", "verify"]) { + assert.deepEqual( + parseArguments([ + command, + "--prepared-dir", + "synthetic/prepared", + "--manifest-sha256", + manifestSha256, + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ]), + { + command, + options: { + preparedDir: "synthetic/prepared", + expectedManifestSha256: manifestSha256, + expectedTag: "v0.1.0", + expectedCommit: commit, + }, + }, + ); + } +}); + +test("missing, duplicate, unknown, malformed, and credential options fail closed", () => { + const prepare = ["prepare", "--tag", "v0.1.0", "--expected-commit", commit]; + const publish = [ + "publish", + "--prepared-dir", + "synthetic", + "--manifest-sha256", + manifestSha256, + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ]; + for (const arguments_ of [ + [], + ["unknown"], + ["prepare"], + ["prepare", "--tag", "v0.1.0"], + ["prepare", "--expected-commit", commit], + ["prepare", "--tag", "v0.1.0-rc.1", "--expected-commit", commit], + ["prepare", "--tag", "0.1.0", "--expected-commit", commit], + ["prepare", "--tag", "v01.1.0", "--expected-commit", commit], + ["prepare", "--tag", "v0.1.0", "--expected-commit", "HEAD"], + [...prepare, "--tag", "v0.1.0"], + [...prepare, "--out"], + [...prepare, "--out", ""], + [...prepare, "--out", "--tag"], + [...prepare, "--out", "synthetic\u0000directory"], + [...prepare, "--out", "synthetic\ndirectory"], + [...prepare, "--force", "true"], + [...prepare, "--__proto__", "value"], + [...prepare, "unexpected"], + [...publish, "--manifest-sha256", manifestSha256], + [...publish, "--npm-token", "synthetic-credential"], + [...publish, "--out", "synthetic"], + publish.filter( + (value) => value !== "--manifest-sha256" && value !== manifestSha256, + ), + [ + "verify", + "--prepared-dir", + "synthetic", + "--manifest-sha256", + "B".repeat(64), + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ], + ]) { + assert.throws(() => parseArguments(arguments_)); + } +}); + +function releaseNpmEnvironment(cli) { + return { RELEASE_NPM_CLI: cli, RELEASE_NPM_VERSION: "11.18.0" }; +} + +async function npmCliFixture(t) { + const directory = await temporaryDirectory(t); + const cli = join(directory, "npm-cli.js"); + // The resolver is a filesystem boundary. Executing this file would fail the + // success case; no installed npm or version subprocess belongs in these tests. + await writeFile( + cli, + "throw new Error('synthetic npm fixture must not execute');\n", + ); + return { directory, cli }; +} + +test("strict preparation resolves a canonical reviewed CLI without executing it", async (t) => { + const { directory, cli } = await npmCliFixture(t); + await mkdir(join(directory, "nested")); + const candidate = `${directory}${sep}nested${sep}..${sep}npm-cli.js`; + const env = Object.freeze(releaseNpmEnvironment(candidate)); + assert.equal(await resolveReleaseNpmCli(env), await realpath(cli)); + assert.equal(env.RELEASE_NPM_CLI, candidate); +}); + +test("strict preparation requires an explicit absolute CLI and never uses ambient npm discovery", async (t) => { + const { directory, cli } = await npmCliFixture(t); + for (const candidate of [undefined, "", "npm-cli.js", "../npm-cli.js"]) { + await assert.rejects( + resolveReleaseNpmCli({ + ...releaseNpmEnvironment(candidate), + npm_execpath: cli, + PATH: directory, + }), + ); + } + await assert.rejects(resolveReleaseNpmCli({})); +}); + +test("strict preparation requires the exact independently configured npm version", async (t) => { + const { cli } = await npmCliFixture(t); + for (const version of [ + undefined, + "", + "11.17.0", + "^11.18.0", + "11.18.0-rc.1", + "11.18.0\n", + ]) { + await assert.rejects( + resolveReleaseNpmCli({ + ...releaseNpmEnvironment(cli), + RELEASE_NPM_VERSION: version, + }), + ); + } +}); + +test("strict preparation rejects non-CLI names, missing files, and CLI-named directories", async (t) => { + const { directory } = await npmCliFixture(t); + const nonCli = join(directory, "not-npm-cli.js"); + await writeFile(nonCli, "// synthetic non-CLI file\n"); + const cliDirectory = join(directory, "directory", "npm-cli.js"); + await mkdir(cliDirectory, { recursive: true }); + for (const candidate of [ + nonCli, + join(directory, "missing", "npm-cli.js"), + cliDirectory, + ]) { + await assert.rejects( + resolveReleaseNpmCli(releaseNpmEnvironment(candidate)), + ); + } +}); + +test("strict preparation rejects a leaf npm-cli.js symlink even to matching regular bytes", async (t) => { + const { directory, cli } = await npmCliFixture(t); + const linkedDirectory = join(directory, "leaf-link"); + await mkdir(linkedDirectory); + const linkedCli = join(linkedDirectory, "npm-cli.js"); + try { + await symlink(cli, linkedCli, "file"); + } catch (error) { + if (process.platform === "win32" && error.code === "EPERM") { + t.skip("Windows file symlinks require Developer Mode or elevation"); + return; + } + throw error; + } + await assert.rejects(resolveReleaseNpmCli(releaseNpmEnvironment(linkedCli))); +}); + +test("strict preparation rejects a CLI reached through a linked ancestor directory", async (t) => { + const { directory, cli } = await npmCliFixture(t); + const linkedDirectory = join(directory, "ancestor-link"); + const actualDirectory = join(directory, "actual-cli-directory"); + await mkdir(actualDirectory); + await writeFile(join(actualDirectory, "npm-cli.js"), await readFile(cli)); + await symlink( + actualDirectory, + linkedDirectory, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects( + resolveReleaseNpmCli( + releaseNpmEnvironment(join(linkedDirectory, "npm-cli.js")), + ), + ); +}); diff --git a/tests/release/contract.test.mjs b/tests/release/contract.test.mjs new file mode 100644 index 0000000..a221c8f --- /dev/null +++ b/tests/release/contract.test.mjs @@ -0,0 +1,252 @@ +import assert from "node:assert/strict"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { + RELEASE_PACKAGES, + RELEASE_REPOSITORY, + releaseDependencies, + verifyReleaseIdentity, +} from "../../scripts/release-contract.mjs"; +import { + signedGitFixture, + specifications, + withGitEnvironment, +} from "./fixtures.mjs"; + +test("the reviewed release package order and exact dependency pins are fixed", () => { + assert.equal(RELEASE_REPOSITORY, "pegma-dev/knowledge-base"); + assert.deepEqual( + RELEASE_PACKAGES.map(({ name, directory }) => ({ name, directory })), + specifications.map(({ name, directory }) => ({ name, directory })), + ); + for (const specification of specifications) { + assert.deepEqual( + releaseDependencies(specification.directory, "0.1.0"), + specification.dependencies, + ); + } + assert.throws(() => releaseDependencies("unknown", "0.1.0")); + for (const version of [ + "v0.1.0", + "0.1.0-rc.1", + "01.1.0", + "1.0", + "1.0.0+build", + ]) { + assert.throws(() => releaseDependencies("contracts", version)); + } +}); + +function verify(fixture, overrides = {}) { + return verifyReleaseIdentity({ + root: fixture.root, + tag: "v0.1.0", + expectedCommit: fixture.commit, + version: "0.1.0", + ...overrides, + }); +} + +test("an approved SSH signed annotated tag at the exact clean main commit verifies", async (t) => { + const fixture = await signedGitFixture(t); + const result = verify(fixture); + assert.deepEqual(result, { + repository: "pegma-dev/knowledge-base", + tag: "v0.1.0", + commit: fixture.commit, + version: "0.1.0", + }); + assert.ok(Object.isFrozen(result)); +}); + +test("release identity rejects a wrong tag, version, or event commit", async (t) => { + const fixture = await signedGitFixture(t); + for (const overrides of [ + { tag: "v0.2.0" }, + { version: "0.1.0-rc.1" }, + { expectedCommit: "0".repeat(40) }, + { expectedCommit: fixture.commit.toUpperCase() }, + { expectedCommit: "HEAD" }, + ]) { + assert.throws(() => verify(fixture, overrides)); + } +}); + +test("a lightweight tag cannot satisfy the signed annotated release contract", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("tag", "-d", "v0.1.0"); + fixture.git("tag", "v0.1.0"); + assert.throws(() => verify(fixture), /annotated tag object/u); +}); + +test("an unsigned annotated tag cannot satisfy the release contract", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("tag", "-d", "v0.1.0"); + fixture.git("tag", "-a", "v0.1.0", "-m", "Unsigned fixture"); + assert.throws(() => verify(fixture), /signature/u); +}); + +test("a cryptographic signature from an unapproved signer is rejected", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(fixture.allowedSigners, ""); + assert.throws(() => verify(fixture), /signature/u); +}); + +async function signerConfig(path, allowedSigners) { + await writeFile( + path, + `[gpg "ssh"]\n\tallowedSignersFile = ${JSON.stringify(allowedSigners.replaceAll("\\", "/"))}\n`, + ); +} + +function injectedSignerEnvironments(allowedSigners, config) { + const parameter = `gpg.ssh.allowedSignersFile=${allowedSigners}`; + const environments = [ + { + name: "indexed command config", + env: { + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "gpg.ssh.allowedSignersFile", + GIT_CONFIG_VALUE_0: allowedSigners, + }, + }, + { + name: "serialized command config", + env: { + GIT_CONFIG_PARAMETERS: `'${parameter.replaceAll("'", "'\\''")}'`, + }, + }, + { + name: "direct config path", + env: { GIT_CONFIG: config }, + }, + ]; + return environments.flatMap((entry) => + process.platform === "win32" + ? [ + entry, + { + name: `${entry.name} with Windows environment casing`, + env: Object.fromEntries( + Object.entries(entry.env).map(([key, value]) => [ + key.toLowerCase(), + value, + ]), + ), + }, + ] + : [entry], + ); +} + +test("inherited Git config cannot approve a signer rejected by local policy", async (t) => { + const fixture = await signedGitFixture(t); + const alternateSigners = join( + fixture.directory, + "environment-allowed-signers", + ); + const alternateConfig = join(fixture.directory, "environment-gitconfig"); + await writeFile( + alternateSigners, + await readFile(fixture.allowedSigners, "utf8"), + ); + await signerConfig(alternateConfig, alternateSigners); + await writeFile(fixture.allowedSigners, ""); + for (const injection of injectedSignerEnvironments( + alternateSigners, + alternateConfig, + )) { + withGitEnvironment({ ...fixture.env, ...injection.env }, () => { + assert.throws(() => verify(fixture), /signature/u, injection.name); + }); + } +}); + +test("inherited Git config cannot replace an approved local signer policy", async (t) => { + const fixture = await signedGitFixture(t); + const alternateSigners = join(fixture.directory, "environment-empty-signers"); + const alternateConfig = join(fixture.directory, "environment-gitconfig"); + await writeFile(alternateSigners, ""); + await signerConfig(alternateConfig, alternateSigners); + for (const injection of injectedSignerEnvironments( + alternateSigners, + alternateConfig, + )) { + withGitEnvironment({ ...fixture.env, ...injection.env }, () => { + assert.equal(verify(fixture).commit, fixture.commit, injection.name); + }); + } +}); + +test("trusted global signer configuration remains available to verification", async (t) => { + const fixture = await signedGitFixture(t); + const globalConfig = join(fixture.directory, "trusted-global-gitconfig"); + await signerConfig(globalConfig, fixture.allowedSigners); + fixture.git("config", "--unset", "gpg.ssh.allowedSignersFile"); + withGitEnvironment({ ...fixture.env, GIT_CONFIG_GLOBAL: globalConfig }, () => + assert.equal(verify(fixture).commit, fixture.commit), + ); +}); + +test("a tag targeting an older commit is rejected even when HEAD matches the event", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile( + join(fixture.root, "README.md"), + "Synthetic second commit.\n", + ); + fixture.git("add", "README.md"); + fixture.git("commit", "-m", "Advance fixture main"); + const commit = fixture.git("rev-parse", "HEAD"); + fixture.git("update-ref", "refs/remotes/origin/main", commit); + assert.throws( + () => verify(fixture, { expectedCommit: commit }), + /must match/u, + ); +}); + +test("tracked modifications and untracked files each block release preparation", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(join(fixture.root, "README.md"), "Unreviewed source edit.\n"); + assert.throws(() => verify(fixture), /clean checkout/u); + fixture.git("restore", "README.md"); + await writeFile(join(fixture.root, "untracked.txt"), "Unreviewed file.\n"); + assert.throws(() => verify(fixture), /clean checkout/u); +}); + +test("a signed clean commit outside origin/main is rejected", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("checkout", "--orphan", "unrelated"); + fixture.git("commit", "-m", "Unrelated synthetic main"); + const unrelated = fixture.git("rev-parse", "HEAD"); + fixture.git("update-ref", "refs/remotes/origin/main", unrelated); + fixture.git("checkout", "--detach", fixture.commit); + assert.throws(() => verify(fixture), /contained in origin\/main/u); +}); + +test("a shallow checkout is rejected before tag ancestry can be trusted", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(join(fixture.root, ".git", "shallow"), `${fixture.commit}\n`); + assert.throws(() => verify(fixture), /complete Git ancestry/u); +}); + +test("a different remote or a package subdirectory cannot supply release identity", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git( + "remote", + "set-url", + "origin", + "https://github.com/other/knowledge-base.git", + ); + assert.throws(() => verify(fixture), /reviewed source repository/u); + fixture.git( + "remote", + "set-url", + "origin", + "https://github.com/pegma-dev/knowledge-base.git", + ); + assert.throws( + () => verify(fixture, { root: join(fixture.root, ".git") }), + /checkout root/u, + ); +}); diff --git a/tests/release/fixtures.mjs b/tests/release/fixtures.mjs new file mode 100644 index 0000000..097df36 --- /dev/null +++ b/tests/release/fixtures.mjs @@ -0,0 +1,288 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash, generateKeyPairSync, sign } from "node:crypto"; +import { + mkdir, + mkdtemp, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; + +const temporaryPrefix = "pegma-kb-release-test-"; + +export const identity = Object.freeze({ + repository: "pegma-dev/knowledge-base", + tag: "v0.1.0", + commit: "a".repeat(40), + version: "0.1.0", +}); + +export const specifications = [ + { + directory: "contracts", + name: "@pegma/knowledge-base-contracts", + dependencies: { "@pegma/spine": "0.1.2" }, + }, + { + directory: "core", + name: "@pegma/knowledge-base-core", + dependencies: { "@pegma/knowledge-base-contracts": "0.1.0" }, + }, + { + directory: "application", + name: "@pegma/knowledge-base-application", + dependencies: { + "@pegma/audit": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-contracts": "0.1.0", + "@pegma/knowledge-base-core": "0.1.0", + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", + }, + }, + { + directory: "mcp", + name: "@pegma/knowledge-base-mcp", + dependencies: { + "@cfworker/json-schema": "4.1.6", + "@modelcontextprotocol/sdk": "1.32.2", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-application": "0.1.0", + "@pegma/knowledge-base-contracts": "0.1.0", + "@pegma/knowledge-base-core": "0.1.0", + zod: "4.6.7", + }, + }, +]; + +export function digest(bytes, algorithm = "sha256", encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +const certificates = new Map(); + +export function syntheticCertificate({ + workflow = ".github/workflows/publish.yml", + issuer = "https://token.actions.githubusercontent.com", +} = {}) { + const identityKey = `${workflow}:${issuer}`; + if (certificates.has(identityKey)) return certificates.get(identityKey); + const der = (tag, ...parts) => { + const value = Buffer.concat(parts); + let length; + if (value.length < 128) { + length = Buffer.from([value.length]); + } else { + let hexadecimal = value.length.toString(16); + if (hexadecimal.length % 2 !== 0) hexadecimal = `0${hexadecimal}`; + const bytes = Buffer.from(hexadecimal, "hex"); + length = Buffer.concat([Buffer.from([0x80 | bytes.length]), bytes]); + } + return Buffer.concat([Buffer.from([tag]), length, value]); + }; + const oid = (hexadecimal) => der(0x06, Buffer.from(hexadecimal, "hex")); + const sequence = (...parts) => der(0x30, ...parts); + const text = (value) => Buffer.from(value, "utf8"); + const algorithm = sequence(oid("2a8648ce3d040302")); + const name = sequence( + der( + 0x31, + sequence(oid("550403"), der(0x0c, text("Synthetic fixture only"))), + ), + ); + const { publicKey, privateKey } = generateKeyPairSync("ec", { + namedCurve: "prime256v1", + }); + const extensions = sequence( + sequence( + oid("551d11"), + der( + 0x04, + sequence( + der( + 0x86, + text( + `https://github.com/pegma-dev/knowledge-base/${workflow}@refs/tags/v0.1.0`, + ), + ), + ), + ), + ), + sequence(oid("2b0601040183bf300101"), der(0x04, text(issuer))), + ); + const body = sequence( + der(0xa0, der(0x02, Buffer.from([2]))), + der(0x02, Buffer.from([1])), + algorithm, + name, + sequence( + der(0x17, text("260101000000Z")), + der(0x17, text("350101000000Z")), + ), + name, + publicKey.export({ type: "spki", format: "der" }), + der(0xa3, extensions), + ); + // A real, self-signed X.509 fixture lets the parser inspect DER and SANs. + // It establishes no Sigstore trust: npm's cryptographic audit is a run seam. + const certificate = sequence( + body, + algorithm, + der(0x03, Buffer.from([0]), sign("sha256", body, privateKey)), + ).toString("base64"); + certificates.set(identityKey, certificate); + return certificate; +} + +export async function temporaryDirectory(t) { + const parent = await realpath(tmpdir()); + const directory = await mkdtemp(join(parent, temporaryPrefix)); + t.after(async () => { + const target = resolve(directory); + assert.equal(dirname(target), resolve(parent)); + assert.ok(basename(target).startsWith(temporaryPrefix)); + assert.notEqual(target, resolve(parent)); + await rm(target, { recursive: true, force: true }); + }); + return directory; +} + +export async function preparedFixture(t) { + const directory = await temporaryDirectory(t); + const preparedDir = join(directory, "prepared"); + await mkdir(preparedDir); + const artifacts = []; + for (const specification of specifications) { + // Manifest verification treats tarballs as opaque, previously reviewed + // blobs. These fixtures exercise its byte boundary without executing npm. + const bytes = Buffer.from(`synthetic artifact: ${specification.name}\n`); + const filename = `${specification.name.slice(1).replace("/", "-")}-0.1.0.tgz`; + await writeFile(join(preparedDir, filename), bytes); + artifacts.push({ + name: specification.name, + version: "0.1.0", + filename, + size: bytes.length, + shasum: digest(bytes, "sha1"), + integrity: `sha512-${digest(bytes, "sha512", "base64")}`, + dependencies: structuredClone(specification.dependencies), + files: [ + { path: "package.json", size: 250 }, + { path: "README.md", size: 32 }, + { path: "LICENSE", size: 1_000 }, + { path: "dist/index.js", size: 64 }, + { path: "dist/index.d.ts", size: 64 }, + ], + }); + } + return { directory, preparedDir, identity: { ...identity }, artifacts }; +} + +export async function rewriteManifest(preparedDir, change) { + const manifestPath = join(preparedDir, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + change(manifest); + const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(manifestPath, bytes); + return digest(bytes); +} + +export function run(command, arguments_, cwd, env) { + const result = spawnSync(command, arguments_, { + cwd, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + timeout: 30_000, + maxBuffer: 1024 * 1024, + }); + assert.ifError(result.error); + assert.equal(result.status, 0, `${command}: ${result.stderr}`); + return result.stdout.trim(); +} + +export function withGitEnvironment(env, operation) { + const isGit = (key) => key.toUpperCase().startsWith("GIT_"); + const original = Object.entries(process.env).filter(([key]) => isGit(key)); + const clear = () => { + for (const key of Object.keys(process.env)) { + if (isGit(key)) delete process.env[key]; + } + }; + // The release verifier is synchronous, so the environment is restored before + // any other asynchronous test work can observe these scoped fixture values. + clear(); + try { + for (const [key, value] of Object.entries(env)) { + if (isGit(key)) process.env[key] = value; + } + return operation(); + } finally { + clear(); + for (const [key, value] of original) process.env[key] = value; + } +} + +export async function signedGitFixture(t) { + const directory = await temporaryDirectory(t); + const root = join(directory, "checkout"); + const signingKey = join(directory, "signing-key"); + const allowedSigners = join(directory, "allowed-signers"); + const emptyConfig = join(directory, "empty-gitconfig"); + await mkdir(root); + await writeFile(emptyConfig, ""); + const env = { ...process.env }; + for (const key of Object.keys(env)) { + if (key.toUpperCase().startsWith("GIT_")) delete env[key]; + } + Object.assign(env, { + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: "1", + GIT_TERMINAL_PROMPT: "0", + }); + const git = (...arguments_) => + run( + process.platform === "win32" ? "git.exe" : "git", + ["--no-replace-objects", ...arguments_], + root, + env, + ); + run( + process.platform === "win32" ? "ssh-keygen.exe" : "ssh-keygen", + ["-q", "-t", "ed25519", "-N", "", "-f", signingKey], + directory, + env, + ); + const publicKey = (await readFile(`${signingKey}.pub`, "utf8")).trim(); + await writeFile( + allowedSigners, + `release-fixture@example.invalid ${publicKey}\n`, + ); + git("init", "--initial-branch=main"); + git("config", "user.name", "Synthetic Release Fixture"); + git("config", "user.email", "release-fixture@example.invalid"); + git("config", "commit.gpgsign", "false"); + git("config", "core.autocrlf", "false"); + git("config", "core.hooksPath", join(directory, "unused-hooks")); + git("config", "gpg.format", "ssh"); + git("config", "user.signingkey", signingKey); + git("config", "gpg.ssh.allowedSignersFile", allowedSigners); + await writeFile(join(root, "README.md"), "Synthetic release fixture.\n"); + git("add", "README.md"); + git("commit", "-m", "Create synthetic release fixture"); + const commit = git("rev-parse", "HEAD"); + git( + "remote", + "add", + "origin", + "https://github.com/pegma-dev/knowledge-base.git", + ); + git("update-ref", "refs/remotes/origin/main", commit); + git("tag", "-s", "v0.1.0", "-m", "Synthetic signed release"); + return { directory, root, git, env, commit, allowedSigners }; +} diff --git a/tests/release/manifest.test.mjs b/tests/release/manifest.test.mjs new file mode 100644 index 0000000..7318040 --- /dev/null +++ b/tests/release/manifest.test.mjs @@ -0,0 +1,415 @@ +import assert from "node:assert/strict"; +import { + mkdir, + readFile, + rename, + symlink, + unlink, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { + PREPARED_MANIFEST_LIMITS, + validatePreparedManifest, + verifyPreparedManifest, + writePreparedManifest, +} from "../../scripts/release-manifest.mjs"; +import { + digest, + identity, + preparedFixture, + rewriteManifest, +} from "./fixtures.mjs"; + +const failure = /prepared release manifest or artifact verification failed/u; + +async function prepare(t) { + const fixture = await preparedFixture(t); + const written = await writePreparedManifest(fixture); + return { + ...fixture, + written, + options: { + preparedDir: fixture.preparedDir, + expectedManifestSha256: written.manifestSha256, + expectedTag: identity.tag, + expectedCommit: identity.commit, + expectedVersion: identity.version, + }, + }; +} + +test("prepared manifest is frozen, digest-bound, ordered, and independent of mutable producer metadata", async (t) => { + const fixture = await prepare(t); + const bytes = await readFile(fixture.written.manifestPath); + assert.equal(fixture.written.manifestSha256, digest(bytes)); + assert.ok(bytes.toString("utf8").endsWith("\n")); + const result = await verifyPreparedManifest(fixture.options); + assert.deepEqual(result.manifest.identity, identity); + assert.deepEqual( + result.artifacts.map(({ name }) => name), + fixture.artifacts.map(({ name }) => name), + ); + for (const artifact of result.artifacts) { + assert.equal(artifact.path, join(fixture.preparedDir, artifact.filename)); + assert.ok(Object.isFrozen(artifact)); + } + assert.ok(Object.isFrozen(result.manifest.artifacts[0].dependencies)); + assert.ok(Object.isFrozen(result.manifest.artifacts[0].files[0])); + assert.ok(Object.isFrozen(result.artifacts)); + assert.equal(Object.isFrozen(fixture.artifacts[0]), false); + fixture.identity.commit = "b".repeat(40); + fixture.artifacts[0].dependencies["@pegma/spine"] = "99.0.0"; + assert.deepEqual(result.manifest.identity, identity); + assert.equal(result.artifacts[0].dependencies["@pegma/spine"], "0.1.2"); +}); + +test("manifest digest and expected source identity come from independent trusted inputs", async (t) => { + const fixture = await prepare(t); + for (const overrides of [ + { expectedManifestSha256: undefined }, + { expectedManifestSha256: "0".repeat(64) }, + { expectedManifestSha256: fixture.written.manifestSha256.toUpperCase() }, + { expectedTag: "v0.2.0" }, + { expectedCommit: "b".repeat(40) }, + { expectedCommit: "HEAD" }, + { expectedVersion: "0.2.0" }, + ]) { + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, ...overrides }), + failure, + ); + } + await rewriteManifest(fixture.preparedDir, (manifest) => { + manifest.identity.commit = "b".repeat(40); + }); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("artifact byte tampering is rejected even when the blob size is unchanged", async (t) => { + const fixture = await prepare(t); + const artifact = join(fixture.preparedDir, fixture.artifacts[0].filename); + const bytes = await readFile(artifact); + bytes[0] ^= 1; + await writeFile(artifact, bytes); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("artifact size and both independent hash encodings must match the exact blob", async (t) => { + for (const [name, change] of [ + [ + "size", + (record) => { + record.size += 1; + }, + ], + [ + "SHA-1", + (record) => { + record.shasum = "0".repeat(40); + }, + ], + [ + "SHA-512", + (record) => { + record.integrity = `sha512-${Buffer.alloc(64).toString("base64")}`; + }, + ], + ]) { + await t.test(name, async (t) => { + const fixture = await prepare(t); + const expectedManifestSha256 = await rewriteManifest( + fixture.preparedDir, + (manifest) => { + change(manifest.artifacts[0]); + }, + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, expectedManifestSha256 }), + failure, + ); + }); + } +}); + +test("recomputed manifest hashes cannot authorize altered package sets, order, pins, or source identity", async (t) => { + const mutations = [ + [ + "missing package", + (manifest) => { + manifest.artifacts.pop(); + }, + ], + [ + "duplicate package", + (manifest) => { + manifest.artifacts[1] = manifest.artifacts[0]; + }, + ], + [ + "wrong order", + (manifest) => { + manifest.artifacts.reverse(); + }, + ], + [ + "unexpected dependency", + (manifest) => { + manifest.artifacts[0].dependencies.extra = "1.0.0"; + }, + ], + [ + "wrong external pin", + (manifest) => { + manifest.artifacts[0].dependencies["@pegma/spine"] = "^0.1.2"; + }, + ], + [ + "wrong internal pin", + (manifest) => { + manifest.artifacts[1].dependencies["@pegma/knowledge-base-contracts"] = + "0.2.0"; + }, + ], + [ + "wrong package version", + (manifest) => { + manifest.artifacts[0].version = "0.2.0"; + }, + ], + [ + "prerelease", + (manifest) => { + manifest.identity.version = "0.1.0-rc.1"; + }, + ], + [ + "different repository", + (manifest) => { + manifest.identity.repository = "other/knowledge-base"; + }, + ], + [ + "different source commit", + (manifest) => { + manifest.identity.commit = "b".repeat(40); + }, + ], + [ + "different release tag", + (manifest) => { + manifest.identity.tag = "v0.2.0"; + }, + ], + [ + "schema downgrade", + (manifest) => { + manifest.schemaVersion = 1; + }, + ], + [ + "unreviewed source field", + (manifest) => { + manifest.source = "copied-local-source"; + }, + ], + [ + "unreviewed record field", + (manifest) => { + manifest.artifacts[0].path = "../source/package.tgz"; + }, + ], + ]; + for (const [name, change] of mutations) { + await t.test(name, async (t) => { + const fixture = await prepare(t); + const expectedManifestSha256 = await rewriteManifest( + fixture.preparedDir, + change, + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, expectedManifestSha256 }), + failure, + ); + }); + } +}); + +test("package inventories reject unsafe paths, tests, duplicates, missing exports, and invalid bounds", async (t) => { + const mutations = [ + [ + "parent traversal", + (record) => { + record.files.push({ path: "dist/../escape.js", size: 1 }); + }, + ], + [ + "absolute path", + (record) => { + record.files.push({ path: "/dist/escape.js", size: 1 }); + }, + ], + [ + "Windows path", + (record) => { + record.files.push({ path: "dist\\escape.js", size: 1 }); + }, + ], + [ + "compiled test", + (record) => { + record.files.push({ path: "dist/index.test.js", size: 1 }); + }, + ], + [ + "duplicate inventory", + (record) => { + record.files.push(record.files[0]); + }, + ], + [ + "missing runtime export", + (record) => { + record.files = record.files.filter( + ({ path }) => path !== "dist/index.js", + ); + }, + ], + [ + "negative size", + (record) => { + record.files[0].size = -1; + }, + ], + [ + "fractional size", + (record) => { + record.files[0].size = 1.5; + }, + ], + [ + "oversized file", + (record) => { + record.files[0].size = PREPARED_MANIFEST_LIMITS.fileBytes + 1; + }, + ], + [ + "artifact filename traversal", + (record) => { + record.filename = `../${record.filename}`; + }, + ], + [ + "artifact too large", + (record) => { + record.size = PREPARED_MANIFEST_LIMITS.artifactBytes + 1; + }, + ], + ]; + for (const [name, change] of mutations) { + await t.test(name, async (t) => { + const fixture = await preparedFixture(t); + change(fixture.artifacts[0]); + assert.throws( + () => + validatePreparedManifest({ + schemaVersion: 2, + identity, + artifacts: fixture.artifacts, + }), + failure, + ); + }); + } +}); + +test("prepared manifests are created once and invalid blobs never produce a manifest", async (t) => { + const fixture = await prepare(t); + await assert.rejects(writePreparedManifest(fixture), failure); + const invalid = await preparedFixture(t); + await writeFile( + join(invalid.preparedDir, invalid.artifacts[0].filename), + "different bytes", + ); + await assert.rejects(writePreparedManifest(invalid), failure); + await assert.rejects(readFile(join(invalid.preparedDir, "manifest.json")), { + code: "ENOENT", + }); +}); + +test("the verifier rejects missing blobs and artifact directories", async (t) => { + const fixture = await prepare(t); + const artifact = join(fixture.preparedDir, fixture.artifacts[0].filename); + await unlink(artifact); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); + await mkdir(artifact); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("a manifest outside the prepared directory is rejected even with the exact trusted digest", async (t) => { + const fixture = await prepare(t); + const manifestPath = join(fixture.directory, "manifest.json"); + await writeFile(manifestPath, await readFile(fixture.written.manifestPath)); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, manifestPath }), + failure, + ); +}); + +test("oversized and malformed manifests fail without disclosing paths or contents", async (t) => { + const fixture = await prepare(t); + for (const bytes of [ + Buffer.alloc(PREPARED_MANIFEST_LIMITS.manifestBytes + 1, 32), + Buffer.from('{"synthetic-secret":"do-not-echo"'), + ]) { + await writeFile(fixture.written.manifestPath, bytes); + await assert.rejects( + verifyPreparedManifest({ + ...fixture.options, + expectedManifestSha256: digest(bytes), + }), + (error) => + error.message === + "prepared release manifest or artifact verification failed", + ); + } +}); + +test("a linked prepared directory is rejected", async (t) => { + const fixture = await prepare(t); + const preparedDir = join(fixture.directory, "linked-prepared"); + await symlink( + fixture.preparedDir, + preparedDir, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, preparedDir }), + failure, + ); +}); + +test("artifact and manifest file symlinks are rejected even when their bytes match", async (t) => { + for (const target of ["artifact", "manifest"]) { + await t.test(target, async (t) => { + const fixture = await prepare(t); + const path = + target === "artifact" + ? join(fixture.preparedDir, fixture.artifacts[0].filename) + : fixture.written.manifestPath; + const moved = join(fixture.directory, `${target}-target`); + await rename(path, moved); + try { + await symlink(moved, path, "file"); + } catch (error) { + if (process.platform === "win32" && error.code === "EPERM") { + t.skip("Windows file symlinks require Developer Mode or elevation"); + return; + } + throw error; + } + await assert.rejects(verifyPreparedManifest(fixture.options), failure); + }); + } +}); diff --git a/tests/release/outputs.test.mjs b/tests/release/outputs.test.mjs new file mode 100644 index 0000000..9909102 --- /dev/null +++ b/tests/release/outputs.test.mjs @@ -0,0 +1,166 @@ +import assert from "node:assert/strict"; +import { + access, + mkdir, + readFile, + rename, + symlink, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { cleanBuildOutputs } from "../../scripts/release-packages.mjs"; +import { specifications, temporaryDirectory } from "./fixtures.mjs"; + +async function outputFixture(t) { + const directory = await temporaryDirectory(t); + const root = join(directory, "checkout"); + for (const { directory: name } of specifications) { + const packageRoot = join(root, "packages", name); + await mkdir(join(packageRoot, "src"), { recursive: true }); + await mkdir(join(packageRoot, "dist", "nested"), { recursive: true }); + await writeFile( + join(packageRoot, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + rootDir: "src", + outDir: "dist", + tsBuildInfoFile: "tsconfig.tsbuildinfo", + }, + }), + ); + await writeFile( + join(packageRoot, "src", "index.ts"), + "export const reviewed = true;\n", + ); + await writeFile( + join(packageRoot, "dist", "index.js"), + "export const reviewed = false; // tampered ignored output\n", + ); + await writeFile( + join(packageRoot, "dist", "extra.js"), + "throw new Error('unreviewed extra');\n", + ); + await writeFile( + join(packageRoot, "dist", "nested", "stale.js"), + "// stale nested output\n", + ); + await writeFile( + join(packageRoot, "tsconfig.tsbuildinfo"), + "stale incremental cache", + ); + } + await writeFile(join(root, "tsconfig.tsbuildinfo"), "unowned root cache"); + const unrelated = join(root, "packages", "unrelated", "dist"); + await mkdir(unrelated, { recursive: true }); + await writeFile(join(unrelated, "keep.js"), "// unowned output\n"); + return { directory, root }; +} + +test("fresh packaging removes tampered ignored dist trees and incremental caches for all four owned packages", async (t) => { + const fixture = await outputFixture(t); + await cleanBuildOutputs(fixture.root); + for (const { directory } of specifications) { + const packageRoot = join(fixture.root, "packages", directory); + await assert.rejects(access(join(packageRoot, "dist")), { code: "ENOENT" }); + await assert.rejects(access(join(packageRoot, "tsconfig.tsbuildinfo")), { + code: "ENOENT", + }); + assert.equal( + await readFile(join(packageRoot, "src", "index.ts"), "utf8"), + "export const reviewed = true;\n", + ); + await access(join(packageRoot, "tsconfig.json")); + } + assert.equal( + await readFile(join(fixture.root, "tsconfig.tsbuildinfo"), "utf8"), + "unowned root cache", + ); + await access(join(fixture.root, "packages", "unrelated", "dist", "keep.js")); + await cleanBuildOutputs(fixture.root); +}); + +test("unsafe output configuration in the last package fails the complete preflight before any cleanup", async (t) => { + const fixture = await outputFixture(t); + const configuration = join(fixture.root, "packages", "mcp", "tsconfig.json"); + await writeFile( + configuration, + JSON.stringify({ + compilerOptions: { + rootDir: "src", + outDir: "../outside", + tsBuildInfoFile: "tsconfig.tsbuildinfo", + }, + }), + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(fixture.root, "packages", "contracts", "dist", "extra.js")); + await access( + join(fixture.root, "packages", "contracts", "tsconfig.tsbuildinfo"), + ); +}); + +test("a linked owned output directory is rejected without touching its target or earlier packages", async (t) => { + const fixture = await outputFixture(t); + const target = join(fixture.directory, "outside-output"); + await mkdir(target); + await writeFile(join(target, "keep.js"), "synthetic outside sentinel\n"); + const output = join(fixture.root, "packages", "mcp", "dist"); + await rename(output, join(fixture.directory, "original-mcp-dist")); + await symlink( + target, + output, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + assert.equal( + await readFile(join(target, "keep.js"), "utf8"), + "synthetic outside sentinel\n", + ); + await access(join(fixture.root, "packages", "contracts", "dist", "extra.js")); +}); + +test("a link nested inside an output tree is rejected before recursive cleanup", async (t) => { + const fixture = await outputFixture(t); + const target = join(fixture.directory, "outside-nested"); + await mkdir(target); + await writeFile(join(target, "keep.js"), "synthetic nested sentinel\n"); + const output = join(fixture.root, "packages", "mcp", "dist", "linked"); + await symlink( + target, + output, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(target, "keep.js")); + await access(join(fixture.root, "packages", "contracts", "dist", "extra.js")); +}); + +test("a non-file incremental cache is rejected rather than recursively removed", async (t) => { + const fixture = await outputFixture(t); + const cache = join(fixture.root, "packages", "mcp", "tsconfig.tsbuildinfo"); + await rename(cache, join(fixture.directory, "original-mcp-cache")); + await mkdir(cache); + await writeFile( + join(cache, "keep.txt"), + "must not recursively delete a cache directory\n", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(cache, "keep.txt")); + await access(join(fixture.root, "packages", "contracts", "dist", "extra.js")); +}); + +test("a linked package directory cannot redirect cleanup outside the checkout", async (t) => { + const fixture = await outputFixture(t); + const packageRoot = join(fixture.root, "packages", "mcp"); + const target = join(fixture.directory, "outside-mcp"); + await rename(packageRoot, target); + await symlink( + target, + packageRoot, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(target, "dist", "extra.js")); + await access(join(fixture.root, "packages", "contracts", "dist", "extra.js")); +}); diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs new file mode 100644 index 0000000..1b31008 --- /dev/null +++ b/tests/release/registry.test.mjs @@ -0,0 +1,1049 @@ +import assert from "node:assert/strict"; +import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; +import test from "node:test"; +import { + assertTrustedPublishingEnvironment, + preflightRegistry, + publishPreparedRelease, + RELEASE_WORKFLOW, + verifyProvenanceAudit, + verifyRegistryRelease, +} from "../../scripts/release-registry.mjs"; +import { + verifyPreparedManifest, + writePreparedManifest, +} from "../../scripts/release-manifest.mjs"; +import { + identity, + preparedFixture, + syntheticCertificate, +} from "./fixtures.mjs"; + +const registry = "https://registry.npmjs.org/"; + +function tarballUrl(record) { + return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; +} + +function metadata(record) { + return { + name: record.name, + version: record.version, + dependencies: structuredClone(record.dependencies), + dist: { + shasum: record.shasum, + integrity: record.integrity, + tarball: tarballUrl(record), + }, + }; +} + +function jsonResponse(value, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "content-type": "application/json" }, + }); +} + +async function fixture(t) { + const prepared = await preparedFixture(t); + const written = await writePreparedManifest(prepared); + const npmCli = join(prepared.directory, "npm-cli.js"); + await writeFile(npmCli, "// Synthetic seam: never executed.\n"); + const options = { + preparedDir: prepared.preparedDir, + expectedManifestSha256: written.manifestSha256, + expectedTag: identity.tag, + expectedCommit: identity.commit, + npmCli, + }; + const verified = await verifyPreparedManifest(options); + const blobs = new Map(); + for (const record of verified.artifacts) { + blobs.set(record.name, await readFile(record.path)); + } + return { ...prepared, options, verified, blobs }; +} + +function fakeRegistry( + fixture, + present = fixture.verified.artifacts.map(({ name }) => name), +) { + const state = { + present: new Set(present), + requests: [], + metadata: undefined, + blob: undefined, + beforeRequest: undefined, + }; + state.fetch = async (input, options) => { + const url = String(input); + assert.equal(options.redirect, "error"); + assert.ok(options.signal instanceof AbortSignal); + const record = fixture.verified.artifacts.find( + (record) => + url === + `${registry}${encodeURIComponent(record.name)}/${record.version}` || + url === tarballUrl(record), + ); + assert.ok(record, `Unexpected registry URL: ${url}`); + const kind = url === tarballUrl(record) ? "tarball" : "metadata"; + state.requests.push({ kind, name: record.name }); + await state.beforeRequest?.(kind, record); + if (kind === "metadata") { + const overridden = await state.metadata?.(record); + if (overridden !== undefined) return overridden; + return state.present.has(record.name) + ? jsonResponse(metadata(record)) + : jsonResponse({ error: "Not found" }, 404); + } + const overridden = await state.blob?.(record); + return overridden ?? new Response(fixture.blobs.get(record.name)); + }; + return state; +} + +function trustedEnvironment() { + return { + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_REPOSITORY: "pegma-dev/knowledge-base", + GITHUB_REPOSITORY_ID: "123456789", + GITHUB_REPOSITORY_OWNER_ID: "987654321", + GITHUB_RUN_ID: "1234567890", + GITHUB_RUN_ATTEMPT: "1", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_REF: `refs/tags/${identity.tag}`, + GITHUB_SHA: identity.commit, + GITHUB_WORKFLOW_REF: `pegma-dev/knowledge-base/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}`, + GITHUB_WORKFLOW_SHA: identity.commit, + RUNNER_ENVIRONMENT: "github-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://pipelines.actions.githubusercontent.com/synthetic", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "synthetic-oidc-request-token", + SYNTHETIC_SOURCE_SECRET: "must-not-reach-npm", + GITHUB_TOKEN: "synthetic-github-token", + GH_TOKEN: "synthetic-gh-token", + GITHUB_CUSTOM_SECRET: "synthetic-github-secret", + GITHUB_APP_PRIVATE_KEY: "synthetic-github-app-key", + RUNNER_CUSTOM_SECRET: "synthetic-runner-secret", + ACTIONS_ID_TOKEN_REQUEST_CUSTOM_SECRET: "synthetic-oidc-extra-secret", + PATH: "synthetic-os-path", + TEMP: "synthetic-os-temp", + }; +} + +function publisher(fixture, state) { + const calls = []; + const sleeps = []; + const seams = { + env: trustedEnvironment(), + fetch: state.fetch, + sleep: async (milliseconds) => { + sleeps.push(milliseconds); + }, + run: async (command, arguments_, context) => { + calls.push({ command, arguments_, context }); + assert.equal(command, process.execPath); + assert.equal(arguments_[0], fixture.options.npmCli); + assert.equal(context.env.SYNTHETIC_SOURCE_SECRET, undefined); + assert.equal(context.env.npm_config_ignore_scripts, "true"); + assert.equal(context.env.npm_config_registry, registry); + assert.notEqual(context.cwd, fixture.preparedDir); + if (arguments_[1] === "--version") { + return { status: 0, stdout: "11.18.0\n", stderr: "" }; + } + assert.equal(arguments_[1], "publish"); + const record = fixture.verified.artifacts.find( + ({ filename }) => filename === basename(arguments_[2]), + ); + assert.ok(record); + assert.equal(dirname(arguments_[2]), context.cwd); + assert.deepEqual( + await readFile(arguments_[2]), + fixture.blobs.get(record.name), + ); + assert.deepEqual(arguments_.slice(3), [ + "--ignore-scripts", + "--access", + "public", + "--provenance", + "--registry", + registry, + ]); + const initialLookups = new Set( + state.requests + .filter(({ kind }) => kind === "metadata") + .map(({ name }) => name), + ); + assert.equal( + initialLookups.size, + 4, + "every version must be checked before the first npm publish", + ); + state.present.add(record.name); + return { status: 0, stdout: "synthetic publication\n", stderr: "" }; + }, + }; + return { seams, calls, sleeps }; +} + +test("only explicit version 404s produce an ordered all-package publication plan", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const plan = await preflightRegistry(prepared.verified, { + fetch: state.fetch, + }); + assert.deepEqual( + plan, + prepared.artifacts.map(({ name, version }) => ({ + name, + version, + action: "publish", + })), + ); + assert.ok(Object.isFrozen(plan)); + assert.ok(plan.every(Object.isFrozen)); + assert.equal(state.requests.length, 4); + assert.ok(state.requests.every(({ kind }) => kind === "metadata")); +}); + +test("existing versions require exact metadata plus downloaded tarball bytes before recovery can skip them", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const plan = await preflightRegistry(prepared.verified, { + fetch: state.fetch, + }); + assert.deepEqual( + plan.map(({ action }) => action), + ["skip", "skip", "skip", "skip"], + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 4, + ); +}); + +test("unknown metadata responses and network errors never establish absence", async (t) => { + for (const status of [ + 204, + 301, + 400, + 401, + 403, + 409, + 429, + 500, + 503, + "network", + "malformed", + ]) { + await t.test(String(status), async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + state.metadata = (record) => { + if (record.name !== prepared.artifacts[3].name) return undefined; + if (status === "network") + throw new Error("synthetic-credential-do-not-echo"); + if (status === "malformed") + return new Response("synthetic-credential-do-not-echo", { + status: 200, + }); + return new Response(null, { status }); + }; + const publishing = publisher(prepared, state); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + (error) => !error.message.includes("synthetic-credential-do-not-echo"), + ); + assert.equal(publishing.calls.length, 0); + }); + } +}); + +test("a conflicting final version prevents publication of every earlier absent package", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, [prepared.artifacts[3].name]); + state.metadata = (record) => { + if (record.name !== prepared.artifacts[3].name) return undefined; + const value = metadata(record); + value.dependencies.zod = "99.0.0"; + return jsonResponse(value); + }; + const publishing = publisher(prepared, state); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /conflicts/u, + ); + assert.equal(publishing.calls.length, 0); +}); + +test("matching integrity alone cannot authorize wrong metadata or a foreign tarball URL", async (t) => { + const changes = [ + [ + "name", + (value) => { + value.name = "@other/knowledge-base-contracts"; + }, + ], + [ + "version", + (value) => { + value.version = "0.2.0"; + }, + ], + [ + "dependency", + (value) => { + value.dependencies["@pegma/spine"] = "^0.1.2"; + }, + ], + [ + "extra dependency", + (value) => { + value.dependencies.extra = "1.0.0"; + }, + ], + [ + "SHA-1", + (value) => { + value.dist.shasum = "0".repeat(40); + }, + ], + [ + "SHA-512", + (value) => { + value.dist.integrity = "sha512-unreviewed"; + }, + ], + [ + "foreign host", + (value) => { + value.dist.tarball = "https://example.invalid/package.tgz"; + }, + ], + [ + "foreign registry path", + (value) => { + value.dist.tarball = `${registry}other/-/other-0.1.0.tgz`; + }, + ], + [ + "optional dependency", + (value) => { + value.optionalDependencies = { extra: "1.0.0" }; + }, + ], + [ + "peer dependency", + (value) => { + value.peerDependencies = { extra: "1.0.0" }; + }, + ], + ]; + for (const [name, change] of changes) { + await t.test(name, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + state.metadata = (record) => { + const value = metadata(record); + change(value); + return jsonResponse(value); + }; + await assert.rejects( + preflightRegistry(prepared.verified, { fetch: state.fetch }), + /conflicts/u, + ); + assert.equal( + state.requests.some(({ kind }) => kind === "tarball"), + false, + ); + }); + } +}); + +test("registry tarball bytes, length, and response status are independently verified", async (t) => { + for (const problem of [ + "changed bytes", + "too short", + "too large", + "404", + "redirect", + "declared too large", + ]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + state.blob = (record) => { + const bytes = Buffer.from(prepared.blobs.get(record.name)); + if (problem === "404") return new Response(null, { status: 404 }); + if (problem === "redirect") return new Response(null, { status: 302 }); + if (problem === "too short") return new Response(bytes.subarray(1)); + if (problem === "too large") + return new Response(Buffer.concat([bytes, Buffer.from("extra")])); + if (problem === "declared too large") + return new Response(bytes, { + headers: { "content-length": String(bytes.length + 1) }, + }); + bytes[0] ^= 1; + return new Response(bytes); + }; + await assert.rejects( + preflightRegistry(prepared.verified, { fetch: state.fetch }), + /tarball/u, + ); + }); + } +}); + +test("publishing inherits approved provenance and OIDC variables without GitHub credentials", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + await publishPreparedRelease(prepared.options, publishing.seams); + assert.ok(publishing.calls.length > 0); + for (const { context } of publishing.calls) { + for (const key of [ + "GITHUB_TOKEN", + "GH_TOKEN", + "GITHUB_CUSTOM_SECRET", + "GITHUB_APP_PRIVATE_KEY", + "RUNNER_CUSTOM_SECRET", + "ACTIONS_ID_TOKEN_REQUEST_CUSTOM_SECRET", + ]) { + assert.equal(context.env[key], undefined, key); + } + for (const key of [ + "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", + "PATH", + "TEMP", + ]) { + assert.equal(context.env[key], publishing.seams.env[key], key); + } + } +}); + +test("a first publication checks the full set then publishes prepared blobs in dependency order", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result, { + published: prepared.artifacts.map(({ name }) => name), + skipped: [], + verified: true, + }); + assert.deepEqual( + publishing.calls + .filter(({ arguments_ }) => arguments_[1] === "publish") + .map(({ arguments_ }) => basename(arguments_[2])), + prepared.artifacts.map(({ filename }) => filename), + ); + assert.equal(publishing.sleeps.length, 0); + assert.ok(Object.isFrozen(result.published)); +}); + +test("partial publication recovers by skipping verified versions and a rerun performs no writes", async (t) => { + const prepared = await fixture(t); + const names = prepared.artifacts.map(({ name }) => name); + const state = fakeRegistry(prepared, names.slice(0, 2)); + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result.published, names.slice(2)); + assert.deepEqual(result.skipped, names.slice(0, 2)); + const rerun = publisher(prepared, state); + const recovered = await publishPreparedRelease(prepared.options, rerun.seams); + assert.deepEqual(recovered.published, []); + assert.deepEqual(recovered.skipped, names); + assert.equal( + rerun.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); +}); + +test("a matching version published concurrently is reverified and skipped immediately before publication", async (t) => { + const prepared = await fixture(t); + const names = prepared.artifacts.map(({ name }) => name); + const state = fakeRegistry(prepared, names.slice(1)); + let lookups = 0; + state.beforeRequest = (kind, record) => { + if (kind === "metadata" && record.name === names[0] && ++lookups === 2) + state.present.add(names[0]); + }; + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result.published, []); + assert.deepEqual(result.skipped, names); + assert.equal( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); +}); + +test("post-publication absence has a bounded retry budget and unknown states fail immediately", async (t) => { + for (const problem of ["404", "network"]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + let published = false; + const publishing = publisher(prepared, state); + const originalRun = publishing.seams.run; + publishing.seams.run = async (...arguments_) => { + const result = await originalRun(...arguments_); + if (arguments_[1][1] === "publish") published = true; + return result; + }; + state.metadata = () => { + if (!published) return undefined; + if (problem === "network") + throw new Error("synthetic unknown network state"); + return jsonResponse({ error: "Not found" }, 404); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.deepEqual( + publishing.sleeps, + problem === "404" ? [1000, 2000, 4000, 8000, 16000] : [], + ); + }); + } +}); + +test("privileged publication requires the exact hosted release workflow identity and rejects inherited npm authority", () => { + assert.doesNotThrow(() => + assertTrustedPublishingEnvironment(trustedEnvironment(), identity), + ); + for (const [key, value] of Object.entries({ + GITHUB_ACTIONS: "false", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REPOSITORY: "other/knowledge-base", + GITHUB_SERVER_URL: "https://example.invalid", + GITHUB_REF: "refs/heads/main", + GITHUB_SHA: "b".repeat(40), + GITHUB_WORKFLOW_REF: "other/workflow@refs/heads/main", + GITHUB_WORKFLOW_SHA: "b".repeat(40), + RUNNER_ENVIRONMENT: "self-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.invalid/oidc", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "", + NPM_TOKEN: "synthetic-token", + NODE_AUTH_TOKEN: "synthetic-token", + npm_config_registry: "https://example.invalid/", + NPM_CONFIG_USERCONFIG: "synthetic-npmrc", + })) { + assert.throws(() => + assertTrustedPublishingEnvironment( + { ...trustedEnvironment(), [key]: value }, + identity, + ), + ); + } +}); + +function provenanceAudit(manifest) { + return { + invalid: [], + missing: [], + verified: manifest.artifacts.map((record) => { + const statement = { + _type: "https://in-toto.io/Statement/v1", + predicateType: "https://slsa.dev/provenance/v1", + subject: [ + { + name: `pkg:npm/${record.name.split("/").map(encodeURIComponent).join("/")}@${record.version}`, + digest: { + sha512: Buffer.from(record.integrity.slice(7), "base64").toString( + "hex", + ), + }, + }, + ], + predicate: { + buildDefinition: { + buildType: + "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1", + externalParameters: { + workflow: { + repository: "https://github.com/pegma-dev/knowledge-base", + path: RELEASE_WORKFLOW, + ref: `refs/tags/${identity.tag}`, + }, + }, + internalParameters: { github: { event_name: "release" } }, + resolvedDependencies: [ + { + uri: `git+https://github.com/pegma-dev/knowledge-base@refs/tags/${identity.tag}`, + digest: { gitCommit: identity.commit }, + }, + ], + }, + runDetails: { + builder: { id: "https://github.com/actions/runner/github-hosted" }, + }, + }, + }; + return { + name: record.name, + version: record.version, + location: `node_modules/${record.name}`, + registry, + attestationBundles: [ + { + predicateType: "https://slsa.dev/provenance/v1", + bundle: { + verificationMaterial: { + certificate: { rawBytes: syntheticCertificate() }, + }, + dsseEnvelope: { + payloadType: "application/vnd.in-toto+json", + payload: Buffer.from(JSON.stringify(statement)).toString( + "base64", + ), + }, + }, + }, + ], + }; + }), + }; +} + +test("cryptographically verified provenance must still bind every prepared package to the exact source workflow", async (t) => { + const prepared = await fixture(t); + assert.doesNotThrow(() => + verifyProvenanceAudit( + provenanceAudit(prepared.verified.manifest), + prepared.verified.manifest, + ), + ); + const changes = [ + [ + "missing package", + (audit) => { + audit.verified.pop(); + }, + ], + [ + "invalid signature", + (audit) => { + audit.invalid.push({ name: "synthetic" }); + }, + ], + [ + "missing attestation", + (audit) => { + audit.missing.push({ name: "synthetic" }); + }, + ], + [ + "duplicate package", + (audit) => { + audit.verified.push(audit.verified[0]); + }, + ], + [ + "foreign registry", + (audit) => { + audit.verified[0].registry = "https://example.invalid/"; + }, + ], + [ + "absent source bundle", + (audit) => { + audit.verified[0].attestationBundles = []; + }, + ], + [ + "missing certificate", + (audit) => { + delete audit.verified[0].attestationBundles[0].bundle + .verificationMaterial; + }, + ], + [ + "wrong certificate workflow", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ workflow: ".github/workflows/other.yml" }); + }, + ], + [ + "wrong certificate issuer", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ issuer: "https://example.invalid" }); + }, + ], + ]; + for (const [name, change] of changes) { + const audit = provenanceAudit(prepared.verified.manifest); + change(audit); + assert.throws( + () => verifyProvenanceAudit(audit, prepared.verified.manifest), + undefined, + name, + ); + } + for (const [name, change] of [ + [ + "wrong commit", + (statement) => { + statement.predicate.buildDefinition.resolvedDependencies[0].digest.gitCommit = + "b".repeat(40); + }, + ], + [ + "wrong tag", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.ref = + "refs/tags/v0.2.0"; + }, + ], + [ + "wrong workflow", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.path = + ".github/workflows/other.yml"; + }, + ], + [ + "wrong repository", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.repository = + "https://github.com/other/knowledge-base"; + }, + ], + [ + "wrong artifact digest", + (statement) => { + statement.subject[0].digest.sha512 = "0".repeat(128); + }, + ], + [ + "self hosted builder", + (statement) => { + statement.predicate.runDetails.builder.id = "synthetic-self-hosted"; + }, + ], + ]) { + const audit = provenanceAudit(prepared.verified.manifest); + const envelope = + audit.verified[0].attestationBundles[0].bundle.dsseEnvelope; + const statement = JSON.parse( + Buffer.from(envelope.payload, "base64").toString("utf8"), + ); + change(statement); + envelope.payload = Buffer.from(JSON.stringify(statement)).toString( + "base64", + ); + assert.throws( + () => verifyProvenanceAudit(audit, prepared.verified.manifest), + undefined, + name, + ); + } +}); + +test("registry verification uses exact released dependencies, script-free installation, public imports, and npm signature audit", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const operations = []; + const result = await verifyRegistryRelease(prepared.options, { + fetch: state.fetch, + env: { + SYNTHETIC_SOURCE_SECRET: "must-not-reach-consumer", + NPM_TOKEN: "must-not-reach-consumer", + }, + run: async (command, arguments_, { cwd, env }) => { + assert.equal(command, process.execPath); + assert.equal(env.SYNTHETIC_SOURCE_SECRET, undefined); + assert.equal(env.NPM_TOKEN, undefined); + assert.equal(env.npm_config_ignore_scripts, "true"); + const operation = + arguments_[0] === prepared.options.npmCli + ? arguments_[1] + : "public-imports"; + operations.push(operation); + if (operation === "--version") return { status: 0, stdout: "11.18.0\n" }; + if (operation === "install") { + assert.deepEqual(arguments_.slice(1), [ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry", + registry, + ]); + const consumer = JSON.parse( + await readFile(join(cwd, "package.json"), "utf8"), + ); + assert.deepEqual( + consumer.dependencies, + Object.fromEntries( + prepared.artifacts.map(({ name, version }) => [name, version]), + ), + ); + await writeFile( + join(cwd, "package-lock.json"), + JSON.stringify({ + packages: Object.fromEntries( + prepared.artifacts.map((record) => [ + `node_modules/${record.name}`, + { + version: record.version, + integrity: record.integrity, + resolved: tarballUrl(record), + }, + ]), + ), + }), + ); + return { status: 0, stdout: "" }; + } + if (operation === "public-imports") { + const source = await readFile(arguments_[0], "utf8"); + for (const { name } of prepared.artifacts) + assert.ok(source.includes(name)); + return { status: 0, stdout: "" }; + } + assert.equal(operation, "audit"); + assert.ok(arguments_.includes("--include-attestations")); + return { + status: 0, + stdout: JSON.stringify(provenanceAudit(prepared.verified.manifest)), + }; + }, + }); + assert.deepEqual(operations, [ + "--version", + "install", + "audit", + "public-imports", + ]); + assert.deepEqual( + result.packages, + prepared.artifacts.map(({ name }) => name), + ); + assert.equal(result.verified, true); +}); + +test("registry verification stops before npm when any release package is absent", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry( + prepared, + prepared.artifacts.slice(0, 3).map(({ name }) => name), + ); + const publishing = publisher(prepared, state); + await assert.rejects( + verifyRegistryRelease(prepared.options, publishing.seams), + /complete release set/u, + ); + assert.equal(publishing.calls.length, 0); +}); + +test("local prepared blob tampering fails before registry access or npm execution", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + await writeFile( + prepared.verified.artifacts[3].path, + "unreviewed prepared bytes", + ); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.equal(state.requests.length, 0); + assert.equal(publishing.calls.length, 0); +}); + +test("all four snapshot blobs are rehashed before the first privileged publish", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const originalRun = publishing.seams.run; + publishing.seams.run = async (...arguments_) => { + const result = await originalRun(...arguments_); + if (arguments_[1][1] === "--version") { + const record = prepared.verified.artifacts[3]; + const bytes = Buffer.from(prepared.blobs.get(record.name)); + bytes[0] ^= 1; + await writeFile(record.path, bytes); + } + return result; + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /changed after verification/u, + ); + assert.equal( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); +}); + +test("a linked npm CLI ancestor is rejected before any npm subprocess", async (t) => { + for (const mode of ["publish", "verify"]) { + await t.test(mode, async (t) => { + const prepared = await fixture(t); + const canonicalDirectory = join(prepared.directory, "canonical-npm"); + await mkdir(canonicalDirectory); + await writeFile( + join(canonicalDirectory, "npm-cli.js"), + "// Synthetic seam: never executed.\n", + ); + const linkedDirectory = join(prepared.directory, "linked-npm"); + await symlink( + canonicalDirectory, + linkedDirectory, + process.platform === "win32" ? "junction" : "dir", + ); + const options = { + ...prepared.options, + npmCli: join(linkedDirectory, "npm-cli.js"), + }; + const state = fakeRegistry(prepared, mode === "publish" ? [] : undefined); + const calls = []; + const operation = + mode === "publish" ? publishPreparedRelease : verifyRegistryRelease; + await assert.rejects( + operation(options, { + env: trustedEnvironment(), + fetch: state.fetch, + run: async (...arguments_) => { + calls.push(arguments_); + throw new Error("Unexpected npm subprocess."); + }, + }), + /pinned npm CLI/u, + ); + assert.deepEqual(calls, []); + assert.equal( + state.present.size, + mode === "publish" ? 0 : prepared.artifacts.length, + ); + }); + } +}); + +test("an unexpected npm version cannot publish any prepared package", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + publishing.seams.run = async () => ({ status: 0, stdout: "11.17.0\n" }); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /pinned npm CLI/u, + ); + assert.equal(state.present.size, 0); +}); + +test("the supported certificate-chain attestation shape binds the same source identity", async (t) => { + const prepared = await fixture(t); + const audit = provenanceAudit(prepared.verified.manifest); + audit.verified[0].attestationBundles[0].bundle.verificationMaterial = { + x509CertificateChain: { + certificates: [{ rawBytes: syntheticCertificate() }], + }, + }; + assert.doesNotThrow(() => + verifyProvenanceAudit(audit, prepared.verified.manifest), + ); +}); + +test("consumer lock and provenance failures stop verification before package runtime imports", async (t) => { + for (const problem of [ + "wrong version", + "workspace link", + "invalid crypto audit", + "wrong provenance source", + ]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const operations = []; + await assert.rejects( + verifyRegistryRelease(prepared.options, { + fetch: state.fetch, + env: {}, + run: async (_command, arguments_, { cwd }) => { + const operation = + arguments_[0] === prepared.options.npmCli + ? arguments_[1] + : "public-imports"; + operations.push(operation); + if (operation === "--version") + return { status: 0, stdout: "11.18.0\n" }; + if (operation === "install") { + const packages = Object.fromEntries( + prepared.artifacts.map((record) => [ + `node_modules/${record.name}`, + { + version: record.version, + integrity: record.integrity, + resolved: tarballUrl(record), + }, + ]), + ); + const installed = + packages[`node_modules/${prepared.artifacts[3].name}`]; + if (problem === "wrong version") installed.version = "0.2.0"; + if (problem === "workspace link") installed.link = true; + await writeFile( + join(cwd, "package-lock.json"), + JSON.stringify({ packages }), + ); + return { status: 0, stdout: "" }; + } + assert.equal( + operation, + "audit", + "package imports cannot precede a valid exact provenance audit", + ); + if (problem === "invalid crypto audit") + return { status: 1, stdout: "synthetic failure" }; + const audit = provenanceAudit(prepared.verified.manifest); + audit.verified[3].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ workflow: ".github/workflows/other.yml" }); + return { status: 0, stdout: JSON.stringify(audit) }; + }, + }), + ); + assert.equal(operations.includes("public-imports"), false); + assert.deepEqual( + operations, + problem === "wrong version" || problem === "workspace link" + ? ["--version", "install"] + : ["--version", "install", "audit"], + ); + }); + } +});