diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc754c3..cfb410a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,11 @@ jobs: run: git diff --exit-code -- pnpm-lock.yaml - name: Validate repository foundation run: pnpm check:foundation + - name: Prove required suite and consumer fixture omission fails + run: pnpm check:presence + - name: Test release preflight without registry access + if: matrix.os == 'ubuntu-latest' + run: pnpm check:release-preflight - name: Typecheck run: pnpm typecheck - name: Check Biome formatting and lint diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9679c37..0f90535 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,51 +25,11 @@ jobs: actions: read id-token: write steps: - - name: Verify approval and quality run - env: - GH_TOKEN: ${{ github.token }} - RUN_ID: ${{ inputs.quality_run_id }} - APPROVED_RUN_ID: ${{ vars.ASSAY_STAGE_RUN_ID }} - APPROVED_SHA: ${{ vars.ASSAY_STAGE_COMMIT }} - APPROVED_DIGEST: ${{ vars.ASSAY_STAGE_SHA256 }} - run: | - set -euo pipefail - [[ "$RUN_ID" =~ ^[1-9][0-9]*$ ]] - [[ "$APPROVED_RUN_ID" == "$RUN_ID" ]] - [[ "$APPROVED_SHA" =~ ^[a-f0-9]{40}$ && "$APPROVED_SHA" == "$GITHUB_SHA" ]] - [[ "$APPROVED_DIGEST" =~ ^[a-f0-9]{64}$ ]] - [[ "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" == "$GITHUB_SHA" ]] - run_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID")" - jq -e --arg sha "$GITHUB_SHA" --arg repo "$GITHUB_REPOSITORY" ' - .head_sha == $sha and .head_branch == "main" and - .head_repository.full_name == $repo and .repository.full_name == $repo and - .path == ".github/workflows/ci.yml" and .event == "push" and - .status == "completed" and .conclusion == "success" - ' <<< "$run_json" >/dev/null - attempt="$(jq -er '.run_attempt' <<< "$run_json")" - [[ "$attempt" =~ ^[1-9][0-9]*$ ]] - gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" \ - --name "assay-verified-$GITHUB_SHA-$attempt" \ - --dir "$RUNNER_TEMP/assay-release" - cd "$RUNNER_TEMP/assay-release" - [[ -f assay.tgz && ! -L assay.tgz && -f manifest.json && ! -L manifest.json ]] - [[ "$(find . -mindepth 1 -maxdepth 1 | wc -l)" -eq 2 ]] - [[ "$(sha256sum assay.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] - jq -e --arg digest "$APPROVED_DIGEST" --argjson size "$(wc -c < assay.tgz)" ' - .name == "@0xbuff/assay" and .version == "0.0.1" and - .sha256 == $digest and .bytes == $size and - ([.files[].path] | sort) == [ - "CHANGELOG.md", "COPYRIGHT.md", "LICENSE", "README.md", - "dist/index.d.ts", "dist/index.js", "dist/index.js.map", "package.json" - ] - ' manifest.json >/dev/null - tar -xOzf assay.tgz package/package.json | jq -e ' - .name == "@0xbuff/assay" and .version == "0.0.1" and - .private == false and .publishConfig.access == "public" and - .publishConfig.registry == "https://registry.npmjs.org/" - ' >/dev/null - tar -xOzf assay.tgz package/CHANGELOG.md > "$RUNNER_TEMP/assay-release-notes.md" - grep -Eq '^## \[0\.0\.1\] - [0-9]{4}-[0-9]{2}-[0-9]{2}$' "$RUNNER_TEMP/assay-release-notes.md" + - name: Check out exact staging commit + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.sha }} + persist-credentials: false - name: Set up Node.js uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 @@ -77,17 +37,12 @@ jobs: node-version: 24.22.3 package-manager-cache: false - - name: Stage exact approved archive + - name: Verify and stage exact approved archive env: GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.quality_run_id }} + APPROVED_RUN_ID: ${{ vars.ASSAY_STAGE_RUN_ID }} + APPROVED_SHA: ${{ vars.ASSAY_STAGE_COMMIT }} APPROVED_DIGEST: ${{ vars.ASSAY_STAGE_SHA256 }} NPM_CONFIG_REGISTRY: https://registry.npmjs.org/ - working-directory: ${{ runner.temp }}/assay-release - run: | - set -euo pipefail - [[ "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" == "$GITHUB_SHA" ]] - [[ "$(sha256sum assay.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] - unset NODE_AUTH_TOKEN NPM_TOKEN - node --version - npm --version - npm stage publish ./assay.tgz --access public --tag latest --ignore-scripts --registry https://registry.npmjs.org/ + run: bash scripts/stage-release.sh diff --git a/docs/development.md b/docs/development.md index 7fcd338..044a5dd 100644 --- a/docs/development.md +++ b/docs/development.md @@ -17,6 +17,7 @@ Run: corepack enable pnpm install --frozen-lockfile pnpm check:foundation +pnpm check:presence pnpm typecheck pnpm format:check pnpm lint @@ -26,7 +27,7 @@ pnpm verify:package # See docs/integrity.md for authored definition digest vectors and guarded APIs ``` -To apply formatting run `pnpm format`. `pnpm check` runs the foundation, type, style, test, build and offline package checks. CI executes equivalent read-only checks; no workflow publishes a package. +To apply formatting run `pnpm format`. `pnpm check` runs the foundation, omission probes, type, style, test, build and offline package checks. Quality CI runs these checks on Ubuntu and Windows, plus the release-preflight regression on Ubuntu. No quality workflow publishes a package. ## Import convention @@ -46,7 +47,7 @@ Use the [source organization](architecture.md#source-organization) to locate the ## Scope of the current checks -Tests cover contract validation, comparator boundaries, deterministic replay, required/advisory precedence, evidence coverage, provenance, truncation, malformed inputs and protected-data disclosure. The distribution verifier checks executable ESM and declarations. The offline package verifier checks the exact archive, Apache-2.0 notice, dependencies, hostile inputs and installed ESM/TypeScript consumer. Both Ubuntu and Windows run these checks. The verifier invokes npm's JavaScript CLI through the active Node executable to avoid platform-specific shell shims. +Tests cover contract validation, comparator boundaries, deterministic replay, required/advisory precedence, evidence coverage, provenance, truncation, malformed inputs and protected-data disclosure. The distribution verifier checks executable ESM and declarations. The offline package verifier checks the exact archive, Apache-2.0 notice, dependencies, hostile inputs and installed ESM/TypeScript consumers. The TypeScript gate covers both Bundler and NodeNext resolution with no ambient types; the NodeNext consumer also executes the emitted README example and rejects internal package subpaths. Both Ubuntu and Windows run these checks. The verifier invokes npm's JavaScript CLI through the active Node executable to avoid platform-specific shell shims. Assay is Apache-2.0 licensed. See the [release policy](releasing.md) for publication requirements. @@ -263,3 +264,30 @@ The verifier requires success markers for both sets of runtime scenarios and sca actual source SHA and CI output, including the isolated TypeScript marker. The examples do not prove real reviewer authority, actual citation validity, execution isolation or academic credit. Release approval is a separate decision. + +## Release verification regression checks + +Quality CI checks that removing any mandatory conformance, adversarial, resource +or packed-consumer fixture causes the foundation gate to fail. The omission probes run against a temporary copy of the source and fixtures, +leaving the working tree untouched. They are included in `pnpm check`: + +```sh +pnpm check:presence +``` + +The Ubuntu job also tests the release preflight and complete staging control +path using synthetic approval records, quality-run metadata, archives and fake +GitHub/npm commands. For complete release verification, run this separately +from `pnpm check` on Ubuntu with Bash, jq and GNU tar/coreutils. Windows and +macOS are not supported for this regression; record it as not run locally on +those platforms and obtain Ubuntu CI evidence. No registry access, credentials +or protected environment is needed: + +```sh +pnpm check:release-preflight +``` + +The standalone NodeNext check installs the same verified archive in a separate +ESM consumer, checks the installed declarations with strict typechecking, +executes the compiled quick start and rejects non-exported subpaths. These +checks do not authorize a release. diff --git a/docs/releasing.md b/docs/releasing.md index f34d7b1..42b4e6f 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -15,7 +15,13 @@ pnpm install --frozen-lockfile pnpm check ``` -The read-only quality workflow runs the equivalent checks on Ubuntu and Windows. Preserve the run, tested commit and tree identity. Package verification builds on the source checks and records the local tarball SHA-256, size and file manifest. +The read-only quality workflow runs these checks, including the omission probes, on Ubuntu and Windows. Complete release verification additionally requires the following on Ubuntu with Bash, jq and GNU tar/coreutils: + +```sh +pnpm check:release-preflight +``` + +On Windows or macOS, this additional regression is unsupported; record it as not run locally and require successful Ubuntu CI evidence. Preserve the run, tested commit and tree identity. Package verification builds on the source checks and records the local tarball SHA-256, size and file manifest. The package must contain exactly: @@ -23,7 +29,7 @@ The package must contain exactly: - `LICENSE`, `COPYRIGHT.md` - `dist/index.js`, `dist/index.js.map`, `dist/index.d.ts` -The verifier checks package metadata, licensing, no runtime dependencies, no lifecycle scripts, and known synthetic canaries in compiled payloads. It packs locally, installs offline with scripts disabled in an independent temporary directory, runs the ESM scenarios and typechecks the installed declarations. It removes the temporary archive and consumer on exit. Set `ASSAY_ARCHIVE_DIR` to a new absolute directory to retain the verified tarball and manifest. Main-push quality runs retain the Ubuntu archive for 30 days; PR runs exercise the same retention path without uploading it. The verifier does not publish anything. +The verifier checks package metadata, licensing, no runtime dependencies, no lifecycle scripts, and known synthetic canaries in compiled payloads. It packs locally, installs offline with scripts disabled in an independent temporary directory, runs the ESM scenarios and typechecks the installed declarations under Bundler and NodeNext resolution. The independent NodeNext consumer also executes the compiled quick start and checks the root-only export boundary. It removes the temporary archive and consumer on exit. Set `ASSAY_ARCHIVE_DIR` to a new absolute directory to retain the verified tarball and manifest. Main-push quality runs retain the Ubuntu archive for 30 days; PR runs exercise the same retention path without uploading it. The verifier does not publish anything. ## Publication checklist @@ -38,7 +44,7 @@ For a public package, prefer [npm trusted publishing](https://docs.npmjs.com/tru ## Protected staging -The `Stage npm package` workflow (`.github/workflows/release.yml`) runs only by manual dispatch on `main`. It uses the existing successful main quality run and stages its verified archive without rebuilding it. The environment must be configured before use. +The `Stage npm package` workflow (`.github/workflows/release.yml`) runs only by manual dispatch on `main`. It uses the existing successful main quality run and stages its verified archive without rebuilding it. The environment must be configured before use. The read-only preflight script checks the approved run, actual archive file list and regular-file types, metadata, digest and dated changelog. The protected workflow calls one staging script that validates the selected artifact and rechecks main and its digest immediately before staging. Quality CI exercises the same control path with synthetic inputs and stubbed GitHub/npm commands, including rejected candidates and late changes. It never requests real staging. 1. In repository Settings > Environments, create `npm-stage`. Restrict deployments to `main`, require reviewers and disallow administrator bypass. Enable prevention of self-review if another reviewer is available. 2. After independent inspection and explicit release approval, set environment variables `ASSAY_STAGE_COMMIT`, `ASSAY_STAGE_RUN_ID` and `ASSAY_STAGE_SHA256` to the approved current main SHA, successful main quality run ID and tarball digest. Leave them unset until approval. Finalize dated release notes and reverify any resulting changes before setting these values. diff --git a/package.json b/package.json index a637c4f..3888567 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,8 @@ }, "scripts": { "check:foundation": "node scripts/check-foundation.mjs", + "check:presence": "node scripts/test-foundation-presence.mjs", + "check:release-preflight": "bash tests/release-preflight.sh", "typecheck": "tsc --noEmit", "generate:version": "node scripts/version-metadata.mjs --write", "build": "node scripts/version-metadata.mjs && tsdown && node scripts/verify-dist.mjs", @@ -35,7 +37,7 @@ "format:check": "biome format .", "lint": "biome lint .", "check:style": "biome check .", - "check": "pnpm check:foundation && pnpm typecheck && pnpm check:style && pnpm test && pnpm build && pnpm verify:package", + "check": "pnpm check:foundation && pnpm check:presence && pnpm typecheck && pnpm check:style && pnpm test && pnpm build && pnpm verify:package", "verify:package": "node scripts/verify-package.mjs" }, "files": [ diff --git a/scripts/check-foundation.mjs b/scripts/check-foundation.mjs index ada9b09..68e2f13 100644 --- a/scripts/check-foundation.mjs +++ b/scripts/check-foundation.mjs @@ -29,6 +29,11 @@ assert.ok( assert.equal(pkg.engines.node, ">=24"); assert.equal(pkg.scripts["verify:package"], "node scripts/verify-package.mjs"); assert.match(pkg.scripts.check, /verify:package/, "Pack must be included in full quality checks"); +assert.match( + pkg.scripts.check, + /check:presence/, + "Omission probes must run in full quality checks", +); assert.equal(ts.compilerOptions.moduleResolution, "bundler"); assert.equal(ts.compilerOptions.module, "ESNext"); assert.equal(Object.keys(pkg.dependencies ?? {}).length, 0, "Pure core must have no runtime deps"); @@ -116,6 +121,9 @@ for (const file of [ "tests/foundation.test.ts", "tests/aggregation.test.ts", "tests/qualitative.test.ts", + "tests/conformance.test.ts", + "tests/adversarial.test.ts", + "tests/resources.test.ts", "tests/expanded-conformance.test.ts", "tests/expanded-resources.test.ts", "tests/objective-comparators.test.ts", @@ -126,9 +134,15 @@ for (const file of [ "scripts/verify-package.mjs", "tests/consumer/consumer.mjs", "tests/consumer/consumer.ts.txt", + "scripts/test-foundation-presence.mjs", + "scripts/release-preflight.sh", + "scripts/stage-release.sh", + "tests/release-preflight.sh", + ".github/workflows/release.yml", ".github/workflows/ci.yml", ]) { - assert.ok((await stat(locate(file))).isFile(), `Missing required file: ${file}`); + const info = await stat(locate(file)).catch(() => undefined); + assert.ok(info?.isFile(), `Missing required file: ${file}`); } const entry = await readFile(locate("src/index.ts"), "utf8"); diff --git a/scripts/release-preflight.sh b/scripts/release-preflight.sh new file mode 100644 index 0000000..883e0bf --- /dev/null +++ b/scripts/release-preflight.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Read-only candidate validation; no credentials, network, or npm operations. +set -euo pipefail + +fail() { + printf 'Release preflight: %s\n' "$1" >&2 + exit 1 +} + +approval() { + [[ "$GITHUB_REPOSITORY" == "0xbuffdev/assay" ]] || fail repository + [[ "$GITHUB_REF" == "refs/heads/main" ]] || fail branch + [[ "$RUN_ID" =~ ^[1-9][0-9]*$ ]] || fail run-id + [[ "$APPROVED_RUN_ID" == "$RUN_ID" ]] || fail approved-run-id + [[ "$APPROVED_SHA" =~ ^[a-f0-9]{40}$ && "$APPROVED_SHA" == "$GITHUB_SHA" ]] || fail approved-sha + [[ "$APPROVED_DIGEST" =~ ^[a-f0-9]{64}$ ]] || fail approved-digest +} + +archive_files() { + printf '%s\n' CHANGELOG.md COPYRIGHT.md LICENSE README.md \ + dist/index.d.ts dist/index.js dist/index.js.map package.json +} + +approval +case "$1" in + approval) + [[ "$#" == 1 ]] || fail arguments + ;; + run) + [[ "$#" == 3 ]] || fail arguments + [[ "$2" == "$GITHUB_SHA" ]] || fail stale-main + jq -e --arg sha "$GITHUB_SHA" --arg repo "$GITHUB_REPOSITORY" --arg id "$RUN_ID" ' + (.id | tostring) == $id and + .head_sha == $sha and .head_branch == "main" and + .head_repository.full_name == $repo and .repository.full_name == $repo and + .path == ".github/workflows/ci.yml" and .event == "push" and + .status == "completed" and .conclusion == "success" and + (.run_attempt | type == "number" and . >= 1 and floor == .) + ' "$3" >/dev/null || fail quality-run + attempt="$(jq -er '.run_attempt' "$3")" + [[ "$attempt" =~ ^[1-9][0-9]*$ ]] || fail run-attempt + printf '%s\n' "$attempt" + ;; + archive) + [[ "$#" == 4 ]] || fail arguments + [[ "$3" =~ ^[1-9][0-9]*$ ]] || fail run-attempt + [[ "$4" == "assay-verified-$GITHUB_SHA-$3" ]] || fail artifact-name + cd "$2" + [[ -f assay.tgz && ! -L assay.tgz && -f manifest.json && ! -L manifest.json ]] || fail artifact-files + [[ "$(find . -mindepth 1 -maxdepth 1 | wc -l)" -eq 2 ]] || fail artifact-files + [[ "$(sha256sum assay.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] || fail archive-digest + jq -e --arg digest "$APPROVED_DIGEST" --argjson size "$(wc -c < assay.tgz)" ' + .name == "@0xbuff/assay" and .version == "0.0.1" and + .sha256 == $digest and .bytes == $size and + ([.files[].path] | sort) == [ + "CHANGELOG.md", "COPYRIGHT.md", "LICENSE", "README.md", + "dist/index.d.ts", "dist/index.js", "dist/index.js.map", "package.json" + ] + ' manifest.json >/dev/null || fail archive-manifest + expected="$(archive_files | sed 's|^|package/|')" + actual="$(tar -tzf assay.tgz | LC_ALL=C sort)" + [[ "$actual" == "$expected" ]] || fail archive-contents + # Require regular files only; no symlink, hardlink or directory entries. + tar -tvzf assay.tgz | awk 'substr($0,1,1) != "-" { bad=1 } END { exit bad }' || fail archive-types + tar -xOzf assay.tgz package/package.json | jq -e ' + .name == "@0xbuff/assay" and .version == "0.0.1" and + .private == false and .publishConfig.access == "public" and + .publishConfig.registry == "https://registry.npmjs.org/" + ' >/dev/null || fail package-metadata + notes="$(tar -xOzf assay.tgz package/CHANGELOG.md)" + heading="$(grep -E '^## \[0\.0\.1\] - [0-9]{4}-[0-9]{2}-[0-9]{2}$' <<< "$notes")" || fail dated-notes + release_date="$(cut -d ' ' -f 4 <<< "$heading")" + [[ "$release_date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || fail dated-notes + [[ "$(date -u -d "$release_date" +%F)" == "$release_date" ]] || fail dated-notes + printf '%s\n' "Release preflight passed" + ;; + *) fail mode ;; +esac diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh new file mode 100644 index 0000000..022cd7e --- /dev/null +++ b/scripts/stage-release.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Invoked only by the separately authorized protected manual workflow. +set -euo pipefail +root="$(cd "$(dirname "$0")/.." && pwd)" +preflight="$root/scripts/release-preflight.sh" + +bash "$preflight" approval +workspace="$(mktemp -d "$RUNNER_TEMP/assay-release.XXXXXXXX")" +trap 'rm -rf "$workspace"' EXIT +archive_dir="$workspace/artifact" +main_sha="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" +gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" > "$workspace/run.json" +attempt="$(bash "$preflight" run "$main_sha" "$workspace/run.json")" +artifact_name="assay-verified-$GITHUB_SHA-$attempt" +gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" \ + --name "$artifact_name" --dir "$archive_dir" +bash "$preflight" archive "$archive_dir" "$attempt" "$artifact_name" + +cd "$archive_dir" +unset NODE_AUTH_TOKEN NPM_TOKEN +node --version +npm --version +# Keep both rechecks immediately before the single staging invocation. +[[ "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" == "$GITHUB_SHA" ]] +[[ -f assay.tgz && ! -L assay.tgz ]] +[[ "$(sha256sum assay.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] +npm stage publish ./assay.tgz --access public --tag latest --ignore-scripts --registry https://registry.npmjs.org/ diff --git a/scripts/test-foundation-presence.mjs b/scripts/test-foundation-presence.mjs new file mode 100644 index 0000000..4c3a316 --- /dev/null +++ b/scripts/test-foundation-presence.mjs @@ -0,0 +1,78 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { cp, mkdtemp, rename, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const files = [ + "tests/conformance.test.ts", + "tests/adversarial.test.ts", + "tests/resources.test.ts", + "tests/expanded-conformance.test.ts", + "tests/expanded-resources.test.ts", + "tests/consumer/consumer.mjs", + "tests/consumer/consumer.ts.txt", + "tests/consumer/version-vectors.mjs", + "tests/consumer/standalone-assessments.mjs", +]; + +// Probe an isolated copy, not the maintainer's working tree. +const workspace = await mkdtemp(path.join(tmpdir(), "assay-presence-")); +try { + for (const entry of [ + ".github", + "docs", + "scripts", + "src", + "tests", + "AGENTS.md", + "README.md", + "LICENSE", + "COPYRIGHT.md", + "CONTRIBUTING.md", + "CODE_OF_CONDUCT.md", + "SECURITY.md", + "CHANGELOG.md", + "package.json", + "pnpm-lock.yaml", + "biome.json", + "tsconfig.json", + "tsconfig.build.json", + "tsdown.config.ts", + "vitest.config.ts", + ]) { + await cp(path.join(root, entry), path.join(workspace, entry), { recursive: true }); + } + // Only the installed authoring toolchain is shared; the guard reads copied sources. + await symlink(path.join(root, "node_modules"), path.join(workspace, "node_modules"), "junction"); + + const foundation = () => { + const result = spawnSync(process.execPath, ["scripts/check-foundation.mjs"], { + cwd: workspace, + encoding: "utf8", + }); + assert.ifError(result.error); + return result; + }; + + const baseline = foundation(); + assert.equal(baseline.status, 0, baseline.stderr); + for (const file of files) { + const original = path.join(workspace, file); + const hidden = `${original}.presence-probe`; + await rename(original, hidden); + try { + const result = foundation(); + assert.equal(result.status, 1, `Missing suite must fail: ${file}`); + assert.ok(result.stderr.includes(`Missing required file: ${file}`), result.stderr); + } finally { + await rename(hidden, original); + } + } + assert.equal(foundation().status, 0, "Foundation must pass after restoring all fixtures"); + console.log("Mandatory suite and consumer fixture omission probes passed"); +} finally { + await rm(workspace, { recursive: true, force: true }); +} diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index 04320a5..61c47c6 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -8,7 +8,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; -import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -302,6 +302,110 @@ try { // module/type resolution starts in the isolated consumer directory. command(process.execPath, [compiler, "--project", "tsconfig.json"], consumerDir); console.log("AY-I28 installed expanded TypeScript contracts verified"); + // Native Node ESM resolution is a separate consumer of the same archive. + // Do not execute the negative type fixture: only the emitted quick start. + const nativeDir = path.join(workspace, "native-consumer"); + await mkdir(nativeDir); + await writeFile( + path.join(nativeDir, "package.json"), + `${JSON.stringify(consumerManifest, null, 2)}\n`, + ); + command( + process.execPath, + [ + npmEntry, + "install", + "--offline", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--no-package-lock", + "--no-save", + "--omit=dev", + archive, + ], + nativeDir, + ); + const nativeModules = path.join(nativeDir, "node_modules"); + assert.deepEqual((await readdir(nativeModules)).filter((name) => !name.startsWith(".")).sort(), [ + "@0xbuff", + ]); + assert.deepEqual(await readdir(path.join(nativeModules, "@0xbuff")), ["assay"]); + const nativeDeclaration = path.join(nativeModules, "@0xbuff", "assay", "dist", "index.d.ts"); + assert.equal( + await readFile(nativeDeclaration, "utf8"), + await readFile(path.join(installed, "dist/index.d.ts"), "utf8"), + ); + await writeFile( + path.join(nativeDir, "consumer.ts"), + await readFile(path.join(fixtureDir, "consumer.ts.txt"), "utf8"), + ); + await writeFile( + path.join(nativeDir, "quick-start.ts"), + `declare const console: { log(value: unknown): void };\n${quickStart}`, + ); + await writeFile( + path.join(nativeDir, "tsconfig.json"), + `${JSON.stringify( + { + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + strict: true, + noEmitOnError: true, + skipLibCheck: false, + types: [], + lib: ["ES2022"], + outDir: "out", + }, + include: ["consumer.ts", "quick-start.ts"], + }, + null, + 2, + )}\n`, + ); + const listed = command( + process.execPath, + [compiler, "--project", "tsconfig.json", "--listFiles"], + nativeDir, + ); + const resolvedFiles = await Promise.all( + listed + .trim() + .split(/\r?\n/) + .map((file) => realpath(file)), + ); + const expectedDeclaration = await realpath(nativeDeclaration); + const libRoot = await realpath(path.join(root, "node_modules", "typescript", "lib")); + const fixturePaths = await Promise.all( + ["consumer.ts", "quick-start.ts"].map((file) => realpath(path.join(nativeDir, file))), + ); + assert.ok(resolvedFiles.includes(expectedDeclaration), "Resolve the installed declaration"); + for (const file of resolvedFiles) { + assert.ok( + file === expectedDeclaration || + fixturePaths.includes(file) || + (path.dirname(file) === libRoot && /^lib\..*\.d\.ts$/.test(path.basename(file))), + "Native consumer must not resolve repository sources or ambient types", + ); + } + assert.equal(command(process.execPath, ["out/quick-start.js"], nativeDir).trim(), "pass"); + await writeFile( + path.join(nativeDir, "native-boundary.mjs"), + [ + 'import assert from "node:assert/strict";', + 'import { realpath } from "node:fs/promises";', + 'import { fileURLToPath } from "node:url";', + 'const resolved = import.meta.resolve("@0xbuff/assay");', + "assert.equal(await realpath(fileURLToPath(resolved)),", + ' await realpath("node_modules/@0xbuff/assay/dist/index.js"));', + 'await assert.rejects(import("@0xbuff/assay/dist/index.js"),', + ' { code: "ERR_PACKAGE_PATH_NOT_EXPORTED" });', + ].join("\n"), + ); + command(process.execPath, ["native-boundary.mjs"], nativeDir); + console.log("Installed NodeNext declarations and emitted ESM verified"); const archiveBytes = await readFile(archive); const archiveMetadata = { name: item.name, diff --git a/tests/consumer/consumer.ts.txt b/tests/consumer/consumer.ts.txt index 9193099..98efece 100644 --- a/tests/consumer/consumer.ts.txt +++ b/tests/consumer/consumer.ts.txt @@ -602,3 +602,6 @@ if (expandedReference.ok) { void badGroup; void oldPolicy; } + +// @ts-expect-error the export map does not expose the installed dist subpath +export type InternalEntry = typeof import("@0xbuff/assay/dist/index.js"); diff --git a/tests/observation.test.ts b/tests/observation.test.ts index 9cc4c9b..e0d4ad3 100644 --- a/tests/observation.test.ts +++ b/tests/observation.test.ts @@ -864,6 +864,60 @@ describe("AY-I19 cooperative cancellation", () => { await Promise.resolve(); }); + it("isolates overlapping collections, cancellation, and independent evaluation", async () => { + const firstDefinition = definition(); + const secondDefinition = sealDefinition({ + ...firstDefinition, + assessmentId: "overlapping-second", + }); + const firstEvidence = evidence(firstDefinition); + const secondEvidence = evidence(secondDefinition); + const firstSnapshot = JSON.stringify(firstEvidence); + const secondSnapshot = JSON.stringify(secondEvidence); + const controller = new AbortController(); + let finishFirst!: (value: unknown) => void; + let finishSecond!: (value: unknown) => void; + const firstPending = new Promise((resolve) => { + finishFirst = resolve; + }); + const secondPending = new Promise((resolve) => { + finishSecond = resolve; + }); + const observe = vi.fn((request: ObservationPortRequest) => { + if (request.definition.assessmentId === firstDefinition.assessmentId) { + return firstPending; + } + expect(request.definition).toEqual(referenceOf(secondDefinition)); + return secondPending; + }); + const port = { observe }; + const first = collectObservations(firstDefinition, firstEvidence, port, { + signal: controller.signal, + }); + const second = collectObservations(secondDefinition, secondEvidence, port); + expect(observe).toHaveBeenCalledTimes(2); + + const before = evaluate(secondDefinition, secondEvidence); + expect(before.outcome).toBe("inconclusive"); + controller.abort(); + expect(await first).toEqual(cancelled); + finishSecond(report({ definition: referenceOf(secondDefinition) })); + const collected = successful(await second); + expect(collected.receipt?.definition).toEqual(referenceOf(secondDefinition)); + const result = evaluate(secondDefinition, collected.evidence); + expect(result.outcome).toBe("pass"); + expect(evaluate(firstDefinition, collected.evidence).outcome).toBe("invalid_evidence"); + + finishFirst(report()); + await firstPending; + expect(await first).toEqual(cancelled); + expect(await second).toEqual(collected); + expect(evaluate(secondDefinition, collected.evidence)).toEqual(result); + expect(evaluate(secondDefinition, secondEvidence)).toEqual(before); + expect(JSON.stringify(firstEvidence)).toBe(firstSnapshot); + expect(JSON.stringify(secondEvidence)).toBe(secondSnapshot); + }); + it("reports synchronous exceptions and removes listeners on success", async () => { const controller = new AbortController(); const remove = vi.spyOn(AbortSignal.prototype, "removeEventListener"); diff --git a/tests/release-preflight.sh b/tests/release-preflight.sh new file mode 100644 index 0000000..1f634cf --- /dev/null +++ b/tests/release-preflight.sh @@ -0,0 +1,243 @@ +#!/usr/bin/env bash +# Synthetic candidate only. Run with Bash, jq and GNU tar/coreutils on Ubuntu. +set -euo pipefail +if [[ "$(uname -s)" != Linux ]]; then + echo "Release preflight regression requires Ubuntu/Linux with GNU utilities" >&2 + exit 1 +fi +root="$(cd "$(dirname "$0")/.." && pwd)" +preflight="$root/scripts/release-preflight.sh" +workspace="$(mktemp -d)" +trap 'rm -rf "$workspace"' EXIT + +export GITHUB_REPOSITORY=0xbuffdev/assay GITHUB_REF=refs/heads/main +export GITHUB_SHA=0123456789abcdef0123456789abcdef01234567 +export APPROVED_SHA="$GITHUB_SHA" RUN_ID=42 APPROVED_RUN_ID=42 +artifact_name="assay-verified-$GITHUB_SHA-2" +mkdir -p "$workspace/package/dist" "$workspace/artifact" +cd "$workspace" +for file in CHANGELOG.md COPYRIGHT.md LICENSE README.md dist/index.d.ts dist/index.js dist/index.js.map package.json; do + printf 'synthetic\n' > "package/$file" +done +printf '# Changelog\n\n## [0.0.1] - 2026-11-28\n' > package/CHANGELOG.md +printf '%s\n' '{"name":"@0xbuff/assay","version":"0.0.1","private":false,"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"}}' > package/package.json +cp package/package.json metadata-good.json +cp package/CHANGELOG.md notes-good.md + +jq -n --arg sha "$GITHUB_SHA" --arg repo "$GITHUB_REPOSITORY" '{ + id:42, head_sha:$sha, head_branch:"main", + head_repository:{full_name:$repo}, repository:{full_name:$repo}, + path:".github/workflows/ci.yml", event:"push", + status:"completed", conclusion:"success", run_attempt:2 +}' > run-good.json + +pack() { + tar -czf artifact/assay.tgz package/CHANGELOG.md package/COPYRIGHT.md \ + package/LICENSE package/README.md package/dist/index.d.ts package/dist/index.js \ + package/dist/index.js.map package/package.json "$@" + export APPROVED_DIGEST + APPROVED_DIGEST="$(sha256sum artifact/assay.tgz | cut -d ' ' -f 1)" + jq -n --arg digest "$APPROVED_DIGEST" --argjson bytes "$(wc -c < artifact/assay.tgz)" '{ + name:"@0xbuff/assay", version:"0.0.1", sha256:$digest, bytes:$bytes, + files: (["CHANGELOG.md","COPYRIGHT.md","LICENSE","README.md","dist/index.d.ts", + "dist/index.js","dist/index.js.map","package.json"] | map({path:.})) + }' > artifact/manifest.json +} + +reject() { + local reason="$1" output + shift + if output="$("$@" 2>&1)"; then + printf 'Unexpected preflight acceptance: %s\n' "$reason" >&2 + exit 1 + fi + if ! grep -Fq "Release preflight: $reason" <<< "$output"; then + printf 'Wrong preflight rejection for %s: %s\n' "$reason" "$output" >&2 + exit 1 + fi +} + +pack +[[ "$(bash "$preflight" run "$GITHUB_SHA" run-good.json)" == 2 ]] +bash "$preflight" archive artifact 2 "$artifact_name" + +reject repository env GITHUB_REPOSITORY=other/assay bash "$preflight" run "$GITHUB_SHA" run-good.json +reject branch env GITHUB_REF=refs/heads/other bash "$preflight" run "$GITHUB_SHA" run-good.json +reject run-id env RUN_ID=0 bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-run-id env APPROVED_RUN_ID= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-sha env APPROVED_SHA= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-digest env APPROVED_DIGEST= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject stale-main bash "$preflight" run 1111111111111111111111111111111111111111 run-good.json +for mutation in \ + '.id=43' '.head_sha="wrong"' '.head_branch="other"' \ + '.head_repository.full_name="other/assay"' '.repository.full_name="other/assay"' \ + '.path=".github/workflows/other.yml"' '.event="pull_request"' \ + '.status="in_progress"' '.conclusion="failure"' '.conclusion=null' \ + '.run_attempt=0' '.run_attempt=1.5' '.run_attempt="2"'; do + jq "$mutation" run-good.json > run-bad.json + reject quality-run bash "$preflight" run "$GITHUB_SHA" run-bad.json +done +reject artifact-name bash "$preflight" archive artifact 3 "$artifact_name" +reject run-attempt bash "$preflight" archive artifact 0 "$artifact_name" +reject archive-digest env APPROVED_DIGEST=1111111111111111111111111111111111111111111111111111111111111111 \ + bash "$preflight" archive artifact 2 "$artifact_name" + +cp artifact/manifest.json manifest-good.json +for mutation in \ + '.bytes+=1' '.sha256="wrong"' '.name="other"' '.version="0.0.2"' \ + '.files|=.[1:]' '.files += [{path:"extra"}]'; do + jq "$mutation" manifest-good.json > artifact/manifest.json + reject archive-manifest bash "$preflight" archive artifact 2 "$artifact_name" +done +cp manifest-good.json artifact/manifest.json +touch artifact/extra +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +rm artifact/extra +mv artifact/manifest.json manifest-moved.json +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +ln -s ../manifest-moved.json artifact/manifest.json +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +rm artifact/manifest.json +mv manifest-moved.json artifact/manifest.json + +# The manifest may claim the right files even when the tarball differs. +touch package/extra +pack package/extra +reject archive-contents bash "$preflight" archive artifact 2 "$artifact_name" +rm package/extra +pack package/README.md +reject archive-contents bash "$preflight" archive artifact 2 "$artifact_name" +rm package/README.md +ln -s LICENSE package/README.md +pack +reject archive-types bash "$preflight" archive artifact 2 "$artifact_name" +rm package/README.md +printf 'synthetic\n' > package/README.md + +for mutation in \ + '.name="other"' '.version="0.0.2"' '.private=true' \ + '.publishConfig.access="restricted"' '.publishConfig.registry="https://example.invalid/"'; do + jq "$mutation" metadata-good.json > package/package.json + pack + reject package-metadata bash "$preflight" archive artifact 2 "$artifact_name" +done +cp metadata-good.json package/package.json + +for heading in '## [Unreleased]' '## [0.0.1] - 2026-02-30' '## [0.0.1] - 2026-11-99'; do + printf '%s\n' "$heading" > package/CHANGELOG.md + pack + reject dated-notes bash "$preflight" archive artifact 2 "$artifact_name" +done +cp notes-good.md package/CHANGELOG.md +pack +[[ "$(bash "$preflight" run "$GITHUB_SHA" run-good.json)" == 2 ]] +bash "$preflight" archive artifact 2 "$artifact_name" +printf '%s\n' 'Release preflight positive and negative matrix passed' + +# Exercise the exact staging entry point with an isolated environment and fake +# GitHub/npm commands. Only the stubs can see these synthetic candidate files. +mkdir "$workspace/bin" "$workspace/runner" +cat > "$workspace/bin/gh" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$*" == "api repos/0xbuffdev/assay/git/ref/heads/main --jq .object.sha" ]]; then + if grep -qx main "$TRACE"; then + echo final-main >> "$TRACE" + if [[ "$CASE" == stale-final ]]; then + echo 1111111111111111111111111111111111111111 + exit 0 + fi + if [[ "$CASE" == changed-final ]]; then + printf 'changed after validation\n' >> "$(cat "$TRACE.archive")/assay.tgz" + fi + else + echo main >> "$TRACE" + if [[ "$CASE" == stale-initial ]]; then + echo 1111111111111111111111111111111111111111 + exit 0 + fi + fi + echo "$GITHUB_SHA" +elif [[ "$*" == "api repos/0xbuffdev/assay/actions/runs/42" ]]; then + echo run >> "$TRACE" + if [[ "$CASE" == rejected-run ]]; then + jq '.conclusion="failure"' "$FIXTURE/run-good.json" + else + cat "$FIXTURE/run-good.json" + fi +elif [[ "$#" == 9 && "$1 $2 $3 $4 $5 $6 $7 $8" == \ + "run download 42 --repo 0xbuffdev/assay --name assay-verified-$GITHUB_SHA-2 --dir" ]]; then + echo download >> "$TRACE" + [[ "$CASE" != failed-download ]] || exit 7 + [[ "$9" == "$RUNNER_TEMP"/assay-release.*/artifact ]] + mkdir "$9" + cp "$FIXTURE/artifact/assay.tgz" "$FIXTURE/artifact/manifest.json" "$9/" + printf '%s\n' "$9" > "$TRACE.archive" + if [[ "$CASE" == rejected-archive ]]; then + jq '.bytes+=1' "$FIXTURE/artifact/manifest.json" > "$9/manifest.json" + fi +else + echo unexpected-gh >> "$TRACE" + exit 99 +fi +STUB +cat > "$workspace/bin/npm" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$#" == 1 && "$1" == --version ]]; then + echo npm-version >> "$TRACE" + echo synthetic-npm + exit 0 +fi +# Record any attempt before checking its arguments. +echo stage >> "$TRACE" +[[ "$*" == "stage publish ./assay.tgz --access public --tag latest --ignore-scripts --registry https://registry.npmjs.org/" ]] +[[ "$PWD" == "$(cat "$TRACE.archive")" ]] +[[ "$(sha256sum ./assay.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] +[[ -z "${NODE_AUTH_TOKEN+x}" && -z "${NPM_TOKEN+x}" ]] +STUB +cat > "$workspace/bin/node" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +[[ "$#" == 1 && "$1" == --version ]] +echo synthetic-node +STUB +chmod +x "$workspace/bin/gh" "$workspace/bin/npm" "$workspace/bin/node" + +orchestrate() { + local scenario="$1" expected="$2" trace="$workspace/trace-$1" status=0 + : > "$trace" + # Start with no inherited credentials (including OIDC). Restrict command + # lookup to the stub directory and standard Ubuntu system binaries. + env -i PATH="$workspace/bin:/usr/bin:/bin" \ + GITHUB_REPOSITORY="$GITHUB_REPOSITORY" GITHUB_REF="$GITHUB_REF" \ + GITHUB_SHA="$GITHUB_SHA" RUN_ID="$RUN_ID" APPROVED_RUN_ID="$APPROVED_RUN_ID" \ + APPROVED_SHA="$APPROVED_SHA" APPROVED_DIGEST="$APPROVED_DIGEST" \ + RUNNER_TEMP="$workspace/runner" FIXTURE="$workspace" TRACE="$trace" CASE="$scenario" \ + NODE_AUTH_TOKEN=synthetic NPM_TOKEN=synthetic \ + bash "$root/scripts/stage-release.sh" > "$trace.output" 2>&1 || status=$? + if [[ "$scenario" == approved ]]; then + [[ "$status" == 0 ]] || { cat "$trace.output" >&2; exit 1; } + else + [[ "$status" != 0 ]] || { echo "Unexpected staging success: $scenario" >&2; exit 1; } + if grep -qx stage "$trace"; then + echo "Rejected candidate reached staging: $scenario" >&2 + exit 1 + fi + fi + [[ "$(cat "$trace")" == "$expected" ]] || { + printf 'Unexpected orchestration trace for %s:\n' "$scenario" >&2 + cat "$trace" "$trace.output" >&2 + exit 1 + } + [[ -z "$(find "$workspace/runner" -mindepth 1 -maxdepth 1 -print -quit)" ]] +} + +orchestrate approved $'main\nrun\ndownload\nnpm-version\nfinal-main\nstage' +orchestrate stale-initial $'main\nrun' +orchestrate rejected-run $'main\nrun' +orchestrate failed-download $'main\nrun\ndownload' +orchestrate rejected-archive $'main\nrun\ndownload' +orchestrate stale-final $'main\nrun\ndownload\nnpm-version\nfinal-main' +orchestrate changed-final $'main\nrun\ndownload\nnpm-version\nfinal-main' +printf '%s\n' 'Protected staging orchestration passed with synthetic GitHub and npm stubs'