diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e1b2071 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,152 @@ +name: CI + +on: + push: + branches: [main, julien@release-v1, julien@opencode-v2, maintenance/opencode-v1, maintenance/opencode-v2] + pull_request: + branches: [main, julien@opencode-v2, maintenance/opencode-v1, maintenance/opencode-v2] + workflow_dispatch: # Evidence-only dry run; never publishes or creates refs/releases. + +permissions: + contents: read + +jobs: + profile: + runs-on: ubuntu-24.04 + outputs: + lines: ${{ steps.config.outputs.lines }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - id: config + run: printf 'lines=%s\n' "$(bun scripts/release/policy.ts matrix)" >> "$GITHUB_OUTPUT" + + quality: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: mkdir -p /tmp/opencode + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run build + - name: Prepare owned tmpfs fixtures (not a disk-durability gate) + id: fixtures + run: | + test "$(stat -f -c %T /dev/shm)" = tmpfs + fixture_root="$(mktemp -d /dev/shm/agentbus-tests.XXXXXX)" + printf 'root=%s\n' "$fixture_root" >> "$GITHUB_OUTPUT" + echo 'Unit/integration fixtures use tmpfs; disk durability is not established by these tests.' + - run: bun run test:unit + env: + TMPDIR: ${{ steps.fixtures.outputs.root }} + - run: bun run test:integration + env: + TMPDIR: ${{ steps.fixtures.outputs.root }} + - run: bun run typecheck + - run: bun run lint + - run: bun run format-check + - run: bun run audit:static + - run: bun run package-smoke + + dependency-audit: + name: Workspace dependency audit (blocking) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun scripts/security/workspace-audit.ts --out release-artifacts/workspace-audit + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: workspace-audit-evidence + path: release-artifacts/workspace-audit/ + if-no-files-found: warn + retention-days: 14 + + archives: + name: Tested archive (${{ matrix.line }}) + needs: profile + strategy: + fail-fast: false + matrix: + line: ${{ fromJSON(needs.profile.outputs.lines) }} + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: mkdir -p /tmp/opencode + - name: Pin npm on this ephemeral runner only + run: | + npm install --prefix "$RUNNER_TEMP/release-tools" --ignore-scripts --no-audit --no-fund --package-lock=false npm@12.2.0 + printf '%s\n' "$RUNNER_TEMP/release-tools/node_modules/.bin" >> "$GITHUB_PATH" + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run build + - name: Pack the configured line + env: + RELEASE_LINE: ${{ matrix.line }} + run: bun scripts/release/package.ts --line "$RELEASE_LINE" --out release-artifacts + - name: Smoke actual installed tarball and record production audit + env: + RELEASE_LINE: ${{ matrix.line }} + run: bun scripts/release/smoke.ts --manifest "release-artifacts/$RELEASE_LINE/manifest.json" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: tested-${{ matrix.line }} + path: release-artifacts/${{ matrix.line }}/ + if-no-files-found: error + retention-days: 14 + + production-audit: + name: Installed production dependency audit (${{ matrix.line }}, blocking) + needs: [profile, archives] + strategy: + fail-fast: false + matrix: + line: ${{ fromJSON(needs.profile.outputs.lines) }} + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + digest-mismatch: error + name: tested-${{ matrix.line }} + path: release-artifacts/${{ matrix.line }} + - env: + RELEASE_LINE: ${{ matrix.line }} + run: bun scripts/release/policy.ts audit "release-artifacts/$RELEASE_LINE/manifest.json" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..60515dc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,201 @@ +name: Release tested archive + +on: + release: + types: [published] + +permissions: + contents: read + +# Manual prerequisites: protected main and maintenance/opencode-v1|v2 branches; +# protected annotated opencode-v1/v* and opencode-v2/v* tags; reviewed npm-v1/npm-v2 +# environments with exact allowed release tags; npm namespace ownership and trusted +# publishers bound to THIS release.yml + corresponding environment. No token fallback. +# This workflow never creates releases, tags or maintenance branches. Repository +# visibility stays unchanged; our public-provenance policy blocks private sources. +concurrency: + group: release-${{ github.event.release.tag_name }} + cancel-in-progress: false + +jobs: + source: + if: github.repository == 'atacama-dev/opencode-agentbus' + runs-on: ubuntu-24.04 + outputs: + line: ${{ steps.source.outputs.line }} + sourceCommit: ${{ steps.source.outputs.sourceCommit }} + environment: ${{ steps.source.outputs.environment }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: refs/tags/${{ github.event.release.tag_name }} + fetch-depth: 0 + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - id: source + run: bun scripts/release/policy.ts source + + build: + needs: source + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.source.outputs.sourceCommit }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: mkdir -p /tmp/opencode + - name: Pin npm without lifecycle scripts (unprivileged build only) + run: | + npm install --prefix "$RUNNER_TEMP/release-tools" --ignore-scripts --no-audit --no-fund --package-lock=false npm@12.2.0 + printf '%s\n' "$RUNNER_TEMP/release-tools/node_modules/.bin" >> "$GITHUB_PATH" + - run: bun scripts/release/policy.ts source + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run build + - name: Prepare owned tmpfs fixtures (not a disk-durability gate) + id: fixtures + run: | + test "$(stat -f -c %T /dev/shm)" = tmpfs + fixture_root="$(mktemp -d /dev/shm/agentbus-tests.XXXXXX)" + printf 'root=%s\n' "$fixture_root" >> "$GITHUB_OUTPUT" + echo 'Unit/integration fixtures use tmpfs; disk durability is not established by these tests.' + - run: bun run test:unit + env: + TMPDIR: ${{ steps.fixtures.outputs.root }} + - run: bun run test:integration + env: + TMPDIR: ${{ steps.fixtures.outputs.root }} + - run: bun run typecheck + - run: bun run lint + - run: bun run format-check + - run: bun run audit:static + - run: bun run package-smoke + - env: + RELEASE_LINE: ${{ needs.source.outputs.line }} + run: bun scripts/release/package.ts --line "$RELEASE_LINE" --out release-artifacts + - env: + RELEASE_LINE: ${{ needs.source.outputs.line }} + run: bun scripts/release/smoke.ts --manifest "release-artifacts/$RELEASE_LINE/manifest.json" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: release-tested-${{ github.run_id }} + path: release-artifacts/${{ needs.source.outputs.line }}/ + if-no-files-found: error + retention-days: 30 + + production-audit: + name: Installed production audit (blocks ALL release writes) + needs: [source, build] + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.source.outputs.sourceCommit }} + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + digest-mismatch: error + name: release-tested-${{ github.run_id }} + path: release-artifacts/${{ needs.source.outputs.line }} + - env: + RELEASE_LINE: ${{ needs.source.outputs.line }} + run: bun scripts/release/policy.ts audit "release-artifacts/$RELEASE_LINE/manifest.json" + + dependency-audit: + name: Workspace audit (blocking) + needs: source + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.source.outputs.sourceCommit }} + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun scripts/security/workspace-audit.ts --out release-artifacts/workspace-audit + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: release-workspace-audit-${{ github.run_id }} + path: release-artifacts/workspace-audit/ + if-no-files-found: warn + retention-days: 30 + + authorization: + name: Readiness and public-provenance policy (blocking) + needs: source + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.source.outputs.sourceCommit }} + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - run: bun scripts/release/policy.ts authorize + + publication: + needs: [source, build, production-audit, dependency-audit, authorization] + if: github.repository == 'atacama-dev/opencode-agentbus' && github.event_name == 'release' && github.event.action == 'published' + runs-on: ubuntu-24.04 + environment: ${{ needs.source.outputs.environment }} + # Serialize this repository/line across versions. Pending jobs are not FIFO and + # may be superseded: retry cancelled jobs after checking current registry state. + # External npm administrators must coordinate; registry reads are not a CAS. + concurrency: + group: npm-publication-${{ github.repository }}-${{ needs.source.outputs.line }} + cancel-in-progress: false + permissions: + contents: write + id-token: write + steps: + # No source build, dependency install or package lifecycle in this job. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.source.outputs.sourceCommit }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - name: Capture official Node distribution path before downloading build data + id: runtime + run: printf 'node=%s\n' "$(command -v node)" >> "$GITHUB_OUTPUT" + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.9 + no-cache: true + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + digest-mismatch: error + name: release-tested-${{ github.run_id }} + path: release-artifacts/${{ needs.source.outputs.line }} + - name: Verify policy and publish exact tested bytes (OIDC only) + env: + GH_TOKEN: ${{ github.token }} + RELEASE_LINE: ${{ needs.source.outputs.line }} + RELEASE_SOURCE_COMMIT: ${{ needs.source.outputs.sourceCommit }} + RELEASE_NODE_BINARY: ${{ steps.runtime.outputs.node }} + run: bun scripts/release/publication.ts --manifest "release-artifacts/$RELEASE_LINE/manifest.json" diff --git a/.gitignore b/.gitignore index cec106c..57a4aa7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ dist/ coverage/ .local/ .agentbus-installed-smoke-*/ +/release-artifacts/ *.log *.db *.db-shm diff --git a/README.md b/README.md index 1492d16..0044bcd 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ The system combines: Status: implemented and end-to-end QA-validated on Linux with Bun 1.3.9 and OpenCode 1.18.19. Built integration tests cover server-root/attached-workspace behavior through a simulated OpenCode host API, and compatibility tests cover the session-status map shape observed on the currently installed OpenCode 1.18.23 runtime. The opt-in real `opencode-server` attached-client wake, TUI navigation, and approval-flow gate remains outstanding. +[Installable V1 archives and release automation](docs/releasing.md) are prepared and tested. V1 `0.1.0` is selected for the initial release; the maintainer has accepted deferring fresh manual native-host acceptance, as recorded in [QA evidence](docs/qa.md#initial-v1-010-release-decision). This is not a claim that the outstanding native tests passed. Dependency findings remain visible under an [expiring risk-acceptance policy](docs/dependency-exceptions.md), not a clean-audit claim. + ## Security model - Peer bodies remain in the broker until the receiving session passes native OpenCode approval. @@ -157,6 +159,8 @@ Installing the plugin for a project opts in up to 256 newest sessions returned b ## Verify +Release preparation uses separate OpenCode V1/V2 package profiles and tests the actual npm archives in independent consumers. See the [release procedure](docs/releasing.md) for local commands, guarded GitHub/npm automation, and the planned V1 preservation followed by the V2 transition. Publication is disabled initially; producing a development archive is not release approval. + ```bash bun run test bun run typecheck @@ -193,3 +197,5 @@ See: Copyright (C) 2026 Julien Tesson . OpenCode Agent Bus is free software: you can redistribute it and/or modify it under the GNU General Public License, version 3 or (at your option) any later version. It is distributed without any warranty, including the implied warranties of merchantability or fitness for a particular purpose. See [LICENSE](LICENSE) for the full terms and [dependency licensing notes](docs/licensing.md) for redistribution constraints. + +Partly developed using [Roster](https://github.com/mathiasbourgoin/roster). diff --git a/biome.json b/biome.json index 147c711..297bc7c 100644 --- a/biome.json +++ b/biome.json @@ -2,7 +2,13 @@ "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "files": { "ignoreUnknown": true, - "ignore": ["**/dist/**", "**/coverage/**", "**/node_modules/**", "scripts/fixtures/**"] + "ignore": [ + "**/dist/**", + "**/coverage/**", + "**/node_modules/**", + "scripts/fixtures/**", + ".local/**" + ] }, "formatter": { "enabled": true, diff --git a/bun.lock b/bun.lock index 43234fd..ca65013 100644 --- a/bun.lock +++ b/bun.lock @@ -17,16 +17,16 @@ "opencode-agentbus-broker": "./dist/cli.js", }, "dependencies": { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/protocol": "workspace:0.1.0", - "zod": "3.25.76", + "zod": "4.6.7", }, }, "packages/plugin": { "name": "@opencode-agentbus/plugin", "version": "0.1.0", "dependencies": { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/broker": "workspace:0.1.0", "@opencode-agentbus/protocol": "workspace:0.1.0", "@opencode-ai/plugin": "1.18.19", @@ -36,7 +36,7 @@ "name": "@opencode-agentbus/protocol", "version": "0.1.0", "dependencies": { - "zod": "3.25.76", + "zod": "4.6.7", }, }, }, @@ -61,21 +61,21 @@ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@1.9.4", "", { "os": "win32", "cpu": "x64" }, "sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA=="], - "@hono/node-server": ["@hono/node-server@2.1.1", "", { "peerDependencies": { "hono": "^4" } }, "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg=="], + "@hono/node-server": ["@hono/node-server@2.1.8", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-jdf7FHh6A1lzjpHHQUgxsg2GeER2vMetnAOfeActzcoli6jamlK+NAwL6Dsr5Fl3BS3tYUQzCdtZjU8Qxv7bEA=="], - "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.30.0", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], - "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="], + "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2zPHLn+MuGJ6GP/5jDrwa9Jy0CI+D3Ibpvopf5SFfmc1G9gdofR4uB7YrJAAp4vodn/7iDOciyv8bgkRPLw7cA=="], - "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="], + "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-of1miwFfEdgs5nythewsEoocfpbjzUf8PC996YDe3kAyv0ZJiMJs5NXlYhE6IdjxfNEPqUXj/BYBnpD8kRdfeQ=="], - "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="], + "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.7", "", { "os": "linux", "cpu": "arm" }, "sha512-aDPbiEkFHs3H68705JKxJ15IT41wFdvDhba1pL8ygfdoshboL5dsXtiu76/CqhLWYneE+9hwBE+0abqNOiQ4Bw=="], - "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="], + "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-jcRydYARTW0gX5idJhxV7m3KkRUD7KtZLYFF1ZY18HrPqpGY0TCqPUTJCwka2kVfVOwfKs3ZmlPSmQb4S6xj7w=="], - "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="], + "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.7", "", { "os": "linux", "cpu": "x64" }, "sha512-A9xOmARctmUvHrBj5GGzGAigsZFnqE4kld5oprX3PyPbkVALV4jwBc17gPZrhSOvnXQc81hE9K7S2hDUCgialA=="], - "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="], + "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.7", "", { "os": "win32", "cpu": "x64" }, "sha512-PRBiOqK4mcR0rvm6nybO7pSOYRR2Zza0+43UK2IvbVGelzMqZViiZJmOWGuWOX678QKESO6YrHx36z43nSS6iQ=="], "@opencode-agentbus/broker": ["@opencode-agentbus/broker@workspace:packages/broker"], @@ -101,7 +101,7 @@ "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], - "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], "bun-types": ["bun-types@1.1.37", "", { "dependencies": { "@types/node": "~20.12.8", "@types/ws": "~8.5.10" } }, "sha512-C65lv6eBr3LPJWFZ2gswyrGZ82ljnH8flVE03xeXxKhi2ZGtFiO4isRKTKnitbSqtRAcaqYSR6djt1whI66AbA=="], @@ -111,7 +111,7 @@ "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], - "content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="], + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], @@ -135,7 +135,7 @@ "effect": ["effect@4.0.0-beta.83", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-0wsak8RtgGAr9UWSbVDgJHZcUqMSvicHcvaZv1MbMM7MCGgW4Rn/137J1MHQbwYPcwYGxT/IqehFd+UbYuj78w=="], - "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], + "encodeurl": ["encodeurl@2.0.3", "", {}, "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w=="], "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], @@ -151,15 +151,15 @@ "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], - "express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="], + "express": ["express@5.3.0", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.8", "qs": "^6.16.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.1.0", "vary": "^1.1.2" } }, "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g=="], - "express-rate-limit": ["express-rate-limit@8.6.2", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A=="], + "express-rate-limit": ["express-rate-limit@8.7.4", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-LKBXzX700wz3zAGNNmVnjRI5mEbYkLv7UbMI4+9Xa+JPcg2UZh6AgY/2CZh9RrJjFM5ttC/N1lD+KzyFoZITCw=="], - "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="], + "fast-check": ["fast-check@4.10.2", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw=="], "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], - "fast-uri": ["fast-uri@3.1.5", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="], + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], @@ -181,7 +181,7 @@ "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], - "hono": ["hono@4.13.3", "", {}, "sha512-r8AO2mYHoLxSHkgafNeC/BXyb2vWRxD3jem4Ts+ptav8oTG5FIRifAjuJEmZI4bSvvc2ns0GxmIYiZnHqN3mMw=="], + "hono": ["hono@4.13.18", "", {}, "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA=="], "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], @@ -191,7 +191,7 @@ "ini": ["ini@7.0.0", "", {}, "sha512-ifK0CgjALofS5bkrcTy4RaQ9Vx2Knf/eLeIO+NaswQEpH1UblrtTSCIvN71qQDMq0PeQ/SSPojvEJp9vvvfr+w=="], - "ip-address": ["ip-address@10.5.0", "", {}, "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g=="], + "ip-address": ["ip-address@10.7.6", "", {}, "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg=="], "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], @@ -199,7 +199,7 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - "jose": ["jose@6.2.9", "", {}, "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA=="], + "jose": ["jose@6.2.17", "", {}, "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg=="], "json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="], @@ -221,13 +221,13 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "msgpackr": ["msgpackr@2.0.5", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.4" } }, "sha512-cef05H/dSYpLpqp3sj/qyZh5vhUYCalnaLO7j1yOmpsR0y/XwLVtK7r5gn+U/F7CTEfMowcGhlUQJDLcLf7jcA=="], + "msgpackr": ["msgpackr@2.1.4", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.6" } }, "sha512-TvP18sX5U3MXoHHSUZen/FagaNTEJObyb8OlnJcNbqN6Ux/oCwYJrHhCOzi31bItyW/Efz1IDnRDKQ23j4ZuvA=="], - "msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="], + "msgpackr-extract": ["msgpackr-extract@3.0.7", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.7", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.7", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.7", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.7", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.7", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.7" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-/dOQboWnkR1cjm88XyH/cGSivECGgyQu3814+bNUAq5wACQC8Ya/CViB9WApvWJ5Hya/JJQQmUeBFOZj8MLjGA=="], - "multipasta": ["multipasta@0.2.8", "", {}, "sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q=="], + "multipasta": ["multipasta@0.2.9", "", {}, "sha512-kAovZHgxryqb0xTFz7OTCPxbas8UBTTwCDhfrlaNecp1/z6xcMfp5PVhDxsW7jONHyDF10/ccp30MxA2+66GJw=="], - "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], @@ -235,7 +235,7 @@ "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], - "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], + "on-finished": ["on-finished@2.4.2", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ=="], "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], @@ -247,11 +247,11 @@ "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], - "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], - "qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="], + "qs": ["qs@6.17.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA=="], "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], @@ -295,7 +295,7 @@ "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], - "uuid": ["uuid@14.0.2", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ=="], + "uuid": ["uuid@14.0.3", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw=="], "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], @@ -303,9 +303,9 @@ "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - "yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], - "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], @@ -313,6 +313,10 @@ "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "express/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], } } diff --git a/docs/README.md b/docs/README.md index 61dea00..a497b7c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,5 +12,9 @@ This directory is the project knowledge base. Keep it aligned with implemented a | [`qa.md`](qa.md) | Verified acceptance evidence and remaining release gates | | [`manual-qa.md`](manual-qa.md) | Opt-in attached-client procedure with operator-supplied paths and service settings | | [`licensing.md`](licensing.md) | GPL choice, dependency compatibility evidence, and redistribution limits | +| [`releasing.md`](releasing.md) | Release-line packaging, publication gates, and the V1 → V2 transition | +| [`dependency-exceptions.md`](dependency-exceptions.md) | Expiring, exact-scope dependency risk acceptance and its regression evidence | `README.md` at the repository root is the operator guide. If an operational example conflicts with the requirements or security invariants, the requirements and invariants take precedence. + +Partly developed using [Roster](https://github.com/mathiasbourgoin/roster). diff --git a/docs/architecture.md b/docs/architecture.md index 7d0779e..d87f611 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -50,6 +50,8 @@ See [`broker-lifecycle-decision.md`](broker-lifecycle-decision.md) for the accep ## Transport and credentials +The HTTP input boundary authenticates before reading a body and reserves a finite per-principal/global in-flight request slot first, using the configured MCP ceilings. Existing sessions remain marked busy for reaping purposes during body reads. The broker caps actual streamed input at 128 KiB, checks any declared length, rejects malformed UTF-8/JSON and all JSON-RPC batches, and rechecks current credentials and lifecycle before SDK dispatch. Disconnect, stop, rotation and a 30-second read deadline cancel held reads; request slots are released on all exits. These application limits remain in place with MCP SDK 1.32.2 rather than relying on high-level SDK tool-server defaults that this low-level custom-method server does not use. + - MCP Streamable HTTP binds only to literal loopback (`127.0.0.1` or `::1`); the default is `http://127.0.0.1:4097`. - The client performs normal MCP initialize/initialized negotiation. Custom JSON-RPC methods and envelopes are defined by `@opencode-agentbus/protocol` v2. - Protocol v2 is a deliberate lockstep compatibility break: strict v1 method and envelope unions cannot accept direct reply or its linkage fields. The MCP connection must complete a successful v2 application handshake before registration or any message operation. A successful handshake also marks the current authenticated principal event-ready; the separate SSE endpoint returns conflict before that point, and credential rotation clears readiness. diff --git a/docs/dependency-exceptions.md b/docs/dependency-exceptions.md new file mode 100644 index 0000000..8f5a40a --- /dev/null +++ b/docs/dependency-exceptions.md @@ -0,0 +1,43 @@ +# Temporary dependency risk acceptance + +This policy permits only explicitly reviewed dependency findings to pass the audit gate while keeping the raw vulnerabilities visible. **An accepted finding is not a false positive, a fix, or proof that the installed dependency is harmless.** + +The maintainer approved temporary, narrowly scoped exceptions on 2026-11-15. They expire at **2026-12-15 00:00 UTC**, 30 days later, and must not renew automatically. The machine-readable ledger is [`security/audit-exceptions.json`](../security/audit-exceptions.json). + +## Review boundary + +Each exception identifies an advisory, severity, affected package, exact installed versions and reviewed SDK dependency chains. Production scopes also identify the release line. Its rationale and evidence must remain applicable. A matching package name or vulnerable version range alone is insufficient: a new route or release line is a new exposure to review. + +V1's ledger covers only these six legacy-SDK advisory records. It contains no V2-only glob/minimatch scopes or evidence references. + +| Dependency | Advisory | Current exposure and evidence | +|---|---|---| +| Legacy SDK Zod | `GHSA-mrhx-c7xc-m3w5` | The SDK's vulnerable copy remains installed, but the four legacy tool argument schemas accept only scalar strings/numbers and optional scalars. The regression guard inspects the actual tool definitions and checks rejection of collection inputs. Broker/protocol collection validation uses patched Zod 4.6.7. | +| Legacy Effect cookies | `GHSA-chp3-j5qr-2vfr` | Agent Bus does not use the affected cookie serialization API. The vulnerable beta is pulled in by the legacy SDK. | +| Legacy TOML | `GHSA-h895-cgqg-jf52`, `GHSA-4qx8-w7c3-pj3p`, `GHSA-9j65-hcg3-gc64`, `GHSA-9qmh-m7c6-f92p` | The legacy SDK/Effect chain installs the affected TOML parser; Agent Bus does not parse peer data or configuration through it. | + +The exact versions and chains in the ledger govern acceptance; the table is explanatory, not an additional allowlist. Installed dependency copies outside those chains are not covered. The V2 development line reviews its public-SDK findings independently. + +[`advisory-exposure.test.ts`](../packages/plugin/test/advisory-exposure.test.ts) guards the actual legacy argument schema shapes and direct parser/import exposure. This is a current-call-surface regression guard, **not** whole-program analysis of OpenCode or a sandbox against co-resident plugins. Changes to caller behavior or SDK APIs require another exposure review even if a dependency version stays the same. + +## Audit gate behavior + +- Retain the original Bun/npm reports and installed-dependency evidence. Report accepted risks separately; never rewrite a raw report into a clean result. +- Match leaf advisory records and actual affected instances. npm's dependent-package propagation must not conceal a new leaf finding. +- Fail on an uncovered advisory, a critical finding, changed severity/version/chain/line, invalid or missing evidence, and applicable expired or not-yet-active exceptions. +- Use the real UTC clock in CI and immediately before publication writes; unit tests may inject time solely to prove boundary behavior. +- Preserve failure for registry errors, malformed audit output and inconsistent installed graphs. An unavailable audit is not an accepted risk. + +Run the workspace audit with `bun run audit`. Its raw report, installed context, exit status and separate decision are retained under `.local/audit-evidence/workspace/`. CI retains corresponding evidence as workflow artifacts. + +After packaging and consumer smoke, recheck an archive with `bun scripts/release/policy.ts audit release-artifacts/v1/manifest.json`. The matching `audit.json`, `audit-context.json` and `audit-exit.json` must be beside the manifest. Context records the build-observed installed dependency instances against the source commit, profile, package identity and archive digest. It is build-produced evidence, not an independent cryptographic attestation or a fresh installation in the publication job. A saved `audit-decision.json` is explanatory evidence, not publication authority: publication recomputes the decision from the raw evidence and source ledger before each write. + +The summary distinguishes raw findings from accepted findings. A successful `accepted-temporary-risk` result still means vulnerabilities are installed. There is no `continue-on-error`, global package exclusion, or incompatible dependency override in this policy. + +## Responsibility and follow-up + +Responsible maintainer: **Julien Tesson**. Before expiry, obtain compatible upstream fixes, remove genuinely unnecessary dependencies through a reviewed design, or perform and record a new risk review. Delete obsolete exceptions when fixes remove the finding. Do not broaden a chain or version entry just because a new install no longer matches. + +Historical release retries are subject to the current clock as well: an expired exception must not become valid merely by replaying an old CI decision. Do not move an immutable release tag to renew its acceptance. + +Passing this audit policy does **not** mark either release line ready, enable npm publication, make the repository public, or establish native OpenCode acceptance. The existing release configuration, protected refs/environments, source/archive checks and product acceptance requirements remain separate gates. diff --git a/docs/licensing.md b/docs/licensing.md index f156e18..985f703 100644 --- a/docs/licensing.md +++ b/docs/licensing.md @@ -6,9 +6,11 @@ Agent Bus's own code is licensed under **GPL-3.0-or-later**; the local dependenc On 2026-11-12, a read-only review inspected the workspace manifests, `bun.lock`, installed runtime dependency metadata, and available license texts. It covered 113 installed third-party runtime package/version pairs; the locked runtime closure contains 118 pairs, including five optional platform packages not installed locally. Development tools were considered separately. +That inventory describes the baseline before the shared dependency-security refresh to MCP SDK 1.32.2 and direct Zod 4.6.7. The legacy OpenCode plugin still pins Zod 4.1.8. The refreshed graph needs a renewed full inventory and notice review before redistribution; the baseline counts above are not a current package-clearance claim. + | Dependencies | License / compatibility basis | |---|---| -| `@modelcontextprotocol/sdk@1.30.0`, `@opencode-ai/plugin@1.18.19`, `@opencode-ai/sdk@1.18.19`, both resolved Zod versions | MIT; compatible with GPLv3 | +| `@modelcontextprotocol/sdk@1.32.2`, `@opencode-ai/plugin@1.18.19`, `@opencode-ai/sdk@1.18.19`, both resolved Zod versions (4.6.7 and legacy-pinned 4.1.8) | MIT; compatible with GPLv3 | | `@ai-sdk/provider@3.0.8`, `detect-libc@2.1.2`, `kubernetes-types@1.30.0` | Apache-2.0; compatible with GPLv3, not GPLv2-only | | `json-schema@0.4.0` | `(AFL-2.1 OR BSD-3-Clause)`; use the BSD-3-Clause option | | Other inspected runtime dependencies | MIT, ISC, BSD-2-Clause, or BSD-3-Clause | diff --git a/docs/qa.md b/docs/qa.md index c392b8a..19dafbb 100644 --- a/docs/qa.md +++ b/docs/qa.md @@ -6,6 +6,16 @@ Original messaging flow approved on 2026-08-20. Plugin-managed broker lifecycle ## Automated gates +### Initial V1 0.1.0 release decision + +On 2026-11-16, the maintainer authorized publishing V1 `0.1.0` using the existing historical native evidence and current automated/installed-archive checks, without repeating manual native-host acceptance. The maintainer no longer has the V1 test setup and accepts evaluating subsequent reports. The attached-client wake/focus, routing and approval observations below remain **unrun on the current release source**, not passed or certified. This decision does not change native permission enforcement or authorize a V2 release. + +The initial npm publication bootstraps the real, exact tagged CI-tested archive through interactive authentication; it is **not an OIDC-provenance publication**. The normal guarded OIDC publisher remains unchanged. See the [one-time bootstrap boundary](releasing.md#initial-v1-010-bootstrap). + +### Historical automated baseline + +This section records the historical baseline, not a clean audit of the current dependencies. Current dependency findings and the temporary acceptance criteria are documented in [dependency exceptions](dependency-exceptions.md); a passing policy does not remove those findings. + - 467 unit tests (2,217 assertions) passed; one wrong-owner database test was skipped because execution was non-root. - 27 integration scenarios (260 assertions) passed using the built plugin, production MCP SDK channel, live broker, SQLite/WAL, SSE, independent plugin clients, detached subprocesses, and a compatible simulated OpenCode host API for server-root/attached-workspace routing. - Strict typecheck, dependency-ordered builds, lint, format, package smoke, dependency audit, and static plugin audit passed. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..2ca5404 --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,104 @@ +# Release preparation and the OpenCode V1 → V2 transition + +This procedure keeps an installable OpenCode V1 release available while `main` later moves to OpenCode V2. It separates building a package from authorizing its distribution. **No release, tag, merge, or npm publication is performed by preparing these files.** + +The host generations called **V1/V2** here are different from Agent Bus's application protocol v2, which both adapters use. + +## Source lines and packages + +`release.config.json` is the source of truth for the active release line, exact package version, package names, supported build profiles and publication gates. + +| Source state | Active release | Package | Tag example | +|---|---|---|---| +| Reviewed V1 preparation merged into `main`, then preserved on `maintenance/opencode-v1` | `v1` | `@atacama-dev/opencode-agentbus-v1` | `opencode-v1/v0.1.0` | +| Reviewed V2 integration merged into `main`, then preserved on `maintenance/opencode-v2` | `v2` | `@atacama-dev/opencode-agentbus-v2` | `opencode-v2/v0.1.0` | + +The npm names are **proposed configuration, not reserved or owned by this workflow**. Confirm the npm organization and package rights before enabling publication. A GitHub organization does not automatically own the matching npm scope. + +The V1 preparation is built from the existing V1 `main` source, with shared security/build corrections backported. It must not acquire V2 runtime dependencies or V2 ancestry merely to obtain packaging scripts. The V2 source can build both adapters for compatibility checks, but its active release line remains `v2`: that does not authorize a V1 release from the V2 line. + +Each published release selects **one** package matching the active line. Branch/PR builds may produce both profiles where supported. Versions are plugin versions; `0.1.0` does not claim compatibility with OpenCode 0.1 or every release of its host generation. + +## What the package contains + +The artifact is prebuilt JavaScript with matching declarations, GPL license and installation instructions. Our broker/protocol packages are included as real bundled dependencies, not workspace symlinks or unpublished `workspace:` references. Third-party dependencies remain explicit; bundling must not hide vulnerable third-party code from the audit. + +V1 loads the legacy plugin function. V2 loads the public stock adapter, **not** the paired-host server or its unsupported terminal/RPC companion. The stock adapter remains experimental and requires its explicit experimental option until the compatibility gates are accepted. Packaging does not add missing native `always` portability, wake recovery, discovery or UI behavior. + +The user still needs Linux, Bun and a compatible OpenCode version. The broker is provided with the plugin and can autostart; the package does not install or replace OpenCode or Bun. Keep V1/V2 test credentials, endpoints and databases independent unless a shared deployment has been deliberately validated. + +A previously running detached broker survives a plugin upgrade. Installing a package does not replace or stop it, even when its application protocol is still compatible. To activate bundled broker security fixes, the operator must deliberately stop the old user-owned broker and then let the new bundled broker start, preserving the intended credential and database. This procedure does not restart any existing service automatically. + +## Local preparation and CI evidence + +From a checkout with dependencies installed and product build complete: + +```bash +bun install --frozen-lockfile --ignore-scripts +bun run build +bun run release:pack --line v1 --out release-artifacts +bun run release:smoke --manifest release-artifacts/v1/manifest.json +``` + +On a V2-capable source, repeat with `--line v2` and the matching manifest. A V1-only source must reject that profile rather than importing V2 modules. + +The packer creates an actual npm `.tgz` and a manifest identifying its line, name, version, source commit and SHA-256. The smoke test installs **that archive** into an independent consumer without dependency lifecycle scripts, checks the packaged entry/broker behavior, and type-checks the installed public entry and bundled broker declarations with `skipLibCheck: false`. The V2 profile explicitly supplies the JSON Schema declaration package needed by its upstream SDK's public types. These checks are not a substitute for acceptance on a real OpenCode host. + +CI checks the source and packages on pushes and pull requests. Build evidence may be produced while publication is disabled. Raw audit findings remain visible. Uncovered findings, invalid evidence and expired applicable exceptions block distribution; the only accepted findings are those matching the [temporary risk-acceptance policy](dependency-exceptions.md). Do not silently drop findings or force incompatible dependency versions. + +Do not compare unlike audit counters: Bun's saved workspace report counts advisory records; npm also reports affected packages and their dependent ancestors. The first isolated package installs reported six distinct advisory records for V1 and two for V2, shown by npm as five high-affected packages and 25 moderately affected packages respectively. This does not mean packaging introduced 25 new vulnerabilities. Raw reports remain nonzero even when all their exact instances meet the temporary exception policy. + +The archive digest fixes our distributed package bytes, not every future registry resolution: direct third-party dependencies are pinned, but their own compatible ranges can resolve differently for a later consumer. CI retains the inspected production graph and re-audits each release install. A fully locked transitive distribution would require a separate reviewed shrinkwrap/offline-install design; it is not claimed here. + +Local artifacts built from a dirty checkout are development previews, not evidence that a tag contains those exact changes. The release path requires a clean, verified checkout of the annotated tag and distributes the same archive that passed its gates. Artifacts are ignored by Git. + +## Before the first release + +All of the following are owner-controlled prerequisites, not actions the workflow takes on your behalf: + +1. Confirm the package names and npm scope ownership. Complete any required first-package registration/bootstrap without publishing an unreviewed placeholder under the intended release version. +2. Configure npm trusted publishing for this repository and the exact `release.yml` workflow filename, with the protected environment used by that release line. Follow [npm's trusted-publisher instructions](https://docs.npmjs.com/trusted-publishers/). No permanent write token belongs in the repository. +3. Configure required review for the publication environments and protect `main`, the maintenance branches and both release-tag prefixes against unauthorized changes. **An annotated tag alone is not immutable**: repository rules must prevent moving or deleting accepted release tags. +4. Decide when the repository becomes public. OIDC publishing itself can work from private repositories, but npm's automatic public provenance cannot. Our public-publication policy requires a public repository; preparation must not change visibility automatically. +5. Resolve all uncovered production findings and complete the line-specific functional/security gates. Temporary acceptance is limited to the exact advisory/version/chain entries and dates in the reviewed exception ledger; it is not a clean dependency audit. Review the actual production install of each package separately and re-evaluate the policy at publication time. +6. Record the reviewed version and explicitly mark the selected line ready in `release.config.json`; enable npm publication only after external setup and owner review. The initial readiness and publication switches are deliberately false. + +The [V2 integration status](https://github.com/atacama-dev/opencode-agentbus/blob/julien%40opencode-v2/docs/v2-port.md) and [manual V2 procedure](https://github.com/atacama-dev/opencode-agentbus/blob/julien%40opencode-v2/docs/manual-v2-qa.md) are maintained on the V2 development line and record its limitations and native-host acceptance gaps. The V1 [QA record](qa.md) remains applicable to its own source; do not copy a V2 test result to qualify a V1 backport. + +## Rollout, when everything is ready + +### Initial V1 0.1.0 bootstrap + +The maintainer authorized the first V1 `0.1.0` publication on 2026-11-16, explicitly accepting the [deferred fresh manual native-host checks](qa.md#initial-v1-010-release-decision). V1 readiness/publication switches record that release decision, not a claim that those checks passed; V2 readiness stays false. + +npm requires an existing package before trusted publishing can be configured. For this first real package only, the approved bootstrap is an interactive publication of the **exact archive downloaded from a fully successful CI run on the protected annotated release tag**, with lifecycle scripts disabled. Verify its source commit, manifest, archive hash and installed-audit decision before publishing, then verify registry SHA-512 integrity. Do not publish a placeholder or use a permanent write token. This initial publication has **no OIDC provenance** and must not be described as trusted-published. + +Publish the GitHub release on that same tag only after the registry integrity matches. The unchanged release workflow must recognize the existing identical npm version and attach verified assets without another npm publication; any byte mismatch stops the workflow. Configure trusted publishing when a subsequent real publication is ready, accounting for npm's two-day first-use deadline. This one-time bootstrap does not add a token fallback or relax subsequent publication checks. + +### 1. Release V1 from `main` + +Integrate and review the main-based V1 preparation first. Check that its release line is `v1`, its package name and version are correct, and its gates pass on that exact source. + +Create and push an **annotated** `opencode-v1/v` tag on the reviewed commit. In GitHub, publish a release selecting that existing tag. Mark a semantic prerelease such as `0.1.0-beta.1` as a GitHub prerelease; it maps to npm `next`. A final version maps to npm `latest`. + +The workflow builds/verifies the tagged source, not whatever `main` happens to contain later. It must confirm the tag's commit belongs to the approved source line and that the archive name/version/digest match before external writes. It does not create extra release tags or branches. + +### 2. Preserve V1 + +After the V1 release is accepted, create `maintenance/opencode-v1` at that release's commit. Keep the annotated release tag. This branch is where any later V1 fixes are reviewed; its active release line remains `v1`. + +### 3. Integrate V2 into `main` + +Prepare a reviewed integration against the then-current `main`, including its V1 release preparation and security backports. Do not blindly merge duplicated backports or rewrite an already-published branch history. Resolve the release configuration deliberately: `main` now selects `v2` and the V2 package, without changing the frozen V1 tag. + +### 4. Release and preserve V2 + +After the V2 gates pass, create/push the reviewed annotated `opencode-v2/v` tag and publish its GitHub release. Preserve the accepted commit on `maintenance/opencode-v2` as well. Both maintenance lines can retain their own tags and package versions without replacing the other generation's npm package. + +## Failed or repeated publication + +Keep the tested archive and its manifest. Do not rebuild inside a privileged publication job or overwrite an existing asset blindly. An npm version is immutable: an existing identical package may be recognized on retry, while a different archive for the same name/version must stop for operator investigation. Existing GitHub release assets likewise must match before being reused. + +If one external write succeeds and another fails, resume from the verified artifact rather than changing or deleting the released version. Do not move an old version back onto `latest` merely because a historical workflow was retried. Never delete, force-update or replace a release tag to repair a pipeline. + +Publication jobs must serialize per package/host line, not merely per release tag. Before a first publish of a version, compare it to the current `latest` or `next` target and refuse an older version. npm does not provide a compare-and-swap guarantee for this operation: any manual or other external publishers must coordinate with the single CI writer. GitHub concurrency may replace pending jobs; retry the intended job with its existing tested archive rather than assuming every queued release will run in order. diff --git a/docs/requirements.md b/docs/requirements.md index 1027800..f8b92c8 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -42,7 +42,7 @@ OpenCode Agent Bus provides secure, local, asynchronous messaging between opted- | SR-01 | Broker transport binds only to literal loopback and authenticates every client before protected operations. | | SR-02 | The plugin verifies a fresh nonce/HMAC broker challenge immediately before every bearer-bearing MCP or SSE request. | | SR-03 | Credential, database, and sidecar files fail closed on unsafe ownership, mode, link, or path conditions. | -| SR-04 | Broker limits cover message size, TTL, rates, active sessions, durable rows, authentication challenges, per-principal and global MCP/SSE connections, replay windows, and retained terminal state. Active and derived session/transport quotas use finite hard maxima and overflow-safe arithmetic. The unauthenticated challenge endpoint remains loopback-only and rate-limited before request validation. | +| SR-04 | Broker limits cover message size, TTL, rates, active sessions, durable rows, authentication challenges, per-principal and global MCP/SSE connections, replay windows, and retained terminal state. Active and derived session/transport quotas use finite hard maxima and overflow-safe arithmetic. Each authenticated MCP request reserves a bounded in-flight request slot before reading its body; per-principal/global request ceilings use the corresponding validated MCP connection ceilings. Body reads and existing-session work count until completion and release on every exit. Actual HTTP bodies are limited to 128 KiB before JSON validation or dispatch; JSON-RPC batches are rejected. Disconnect, stop, credential rotation, and a 30-second read deadline cancel pending reads. Current authentication, availability and session validity are rechecked before dispatch. The unauthenticated challenge endpoint remains loopback-only and rate-limited before request validation. | | SR-05 | Autostart passes a minimal allowlisted child environment and never accepts a model-controlled command, executable, endpoint, credential path, database path, or session limit. The trusted plugin option is parsed before launch and its exact active-session value is passed explicitly; an arbitrary inherited manual-CLI capacity variable is not forwarded. | | SR-06 | An occupied unknown endpoint, insecure credential, malformed configuration, or genuine child startup failure fails closed without listener replacement. | | SR-07 | Message consume and reject transitions are transactional, target-bound, hash-bound, and replay-safe. | diff --git a/package.json b/package.json index 3fec5fa..de49602 100644 --- a/package.json +++ b/package.json @@ -27,8 +27,11 @@ "format-check": "biome format .", "broker:start": "bun run --cwd packages/broker start", "package-smoke": "bun scripts/package-smoke.ts", - "audit": "bun audit && bun run audit:static", - "audit:static": "bun scripts/audit-plugin-source.ts" + "audit": "bun scripts/security/workspace-audit.ts --out .local/audit-evidence/workspace && bun run audit:static", + "audit:static": "bun scripts/audit-plugin-source.ts", + "release:pack": "bun scripts/release/package.ts", + "release:smoke": "bun scripts/release/smoke.ts", + "release:check": "bun scripts/release/policy.ts" }, "devDependencies": { "@biomejs/biome": "1.9.4", diff --git a/packages/broker/package.json b/packages/broker/package.json index 1e383e7..e3a9be7 100644 --- a/packages/broker/package.json +++ b/packages/broker/package.json @@ -29,8 +29,8 @@ "start": "bun ./dist/cli.js" }, "dependencies": { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/protocol": "workspace:0.1.0", - "zod": "3.25.76" + "zod": "4.6.7" } } diff --git a/packages/broker/src/server.ts b/packages/broker/src/server.ts index d2abdb2..f6c1029 100644 --- a/packages/broker/src/server.ts +++ b/packages/broker/src/server.ts @@ -163,6 +163,13 @@ interface McpContext { closing: boolean; } +interface McpUpload { + readonly principal: AuthenticatedClientPrincipal; + readonly abort: AbortController; + readonly done: Promise; + release(): void; +} + interface EventConnection { readonly principal: AuthenticatedClientPrincipal; close(): void; @@ -241,7 +248,7 @@ function customRequestSchema(method: Method) { return z .object({ method: z.literal(method), - params: z.record(z.unknown()), + params: z.record(z.string(), z.unknown()), }) .passthrough(); } @@ -297,6 +304,7 @@ export class BrokerDaemon { private authChallengeLastRefillMs: number; private readonly mcpSessions = new Map(); private readonly mcpContexts = new Set(); + private readonly mcpUploads = new Set(); private readonly eventConnections = new Set(); private applicationHandshakeComplete = false; private listener: ReturnType | undefined; @@ -443,7 +451,9 @@ export class BrokerDaemon { if (this.rotating || this.stopping) throw new Error("Broker is not available for rotation."); this.rotating = true; try { + this.cancelMcpUploads(); await this.closeConnections(); + await Promise.all([...this.mcpUploads].map((upload) => upload.done)); this.applicationHandshakeComplete = false; return this.service.rotateCredential(); } finally { @@ -454,6 +464,7 @@ export class BrokerDaemon { async stop(): Promise { if (this.stopping) return; this.stopping = true; + this.cancelMcpUploads(); if (this.reapTimer) clearInterval(this.reapTimer); if (this.maintenanceTimer) clearInterval(this.maintenanceTimer); this.reapTimer = undefined; @@ -465,6 +476,7 @@ export class BrokerDaemon { this.listener = undefined; const stopped = listener?.stop(true); await this.closeConnections(); + await Promise.all([...this.mcpUploads].map((upload) => upload.done)); await stopped; this.service.close(); } @@ -473,6 +485,19 @@ export class BrokerDaemon { return { mcp: this.mcpContexts.size, sse: this.eventConnections.size }; } + uploadCountsForTesting(): { readonly total: number; readonly byPrincipal: number[] } { + const counts = new Map(); + for (const { principal } of this.mcpUploads) { + const key = `${principal.principalId}:${principal.serverId}`; + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return { total: this.mcpUploads.size, byPrincipal: [...counts.values()] }; + } + + private cancelMcpUploads(): void { + for (const upload of this.mcpUploads) upload.abort.abort(); + } + authChallengeRateStateForTesting(): { readonly capacity: number; readonly availableTokens: number; @@ -566,6 +591,24 @@ export class BrokerDaemon { this.authChallengeLastRefillMs = now; } + private mcpRequestAuthorized( + request: Request, + principal: AuthenticatedClientPrincipal, + upload: McpUpload | undefined, + context: McpContext | undefined, + sessionId: string | null, + ): boolean { + if (this.stopping || this.rotating || request.signal.aborted || upload?.abort.signal.aborted) { + return false; + } + const current = this.service.authenticate(request.headers.get("authorization")); + return ( + current !== undefined && + principalsEqual(current, principal) && + (!context || (!context.closing && this.mcpSessions.get(sessionId ?? "") === context)) + ); + } + private async handleMcp( request: Request, principal: AuthenticatedClientPrincipal, @@ -573,54 +616,179 @@ export class BrokerDaemon { if (request.method !== MCP_HTTP_CONTRACT.method && request.method !== "DELETE") { return plainError(405); } - if (request.method === MCP_HTTP_CONTRACT.method) { - const length = request.headers.get("content-length"); - if (length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_HTTP_BODY_BYTES)) { - return jsonRpcError(413, -32600, "Request body is too large."); - } - } - - await this.reapIdleSessions(); const sessionId = request.headers.get(MCP_INITIALIZATION_CONTRACT.sessionHeader); - let context: McpContext; + let context = sessionId ? this.mcpSessions.get(sessionId) : undefined; + if ( + sessionId && + (!context || context.closing || !principalsEqual(context.principal, principal)) + ) { + return jsonRpcError(404, -32001, "Session not found."); + } + if (!sessionId && request.method === "DELETE") { + return jsonRpcError(400, -32600, "MCP session header is required."); + } + if ( + this.mcpUploads.size >= this.maxMcpSessionsGlobal || + [...this.mcpUploads].filter((upload) => principalsEqual(upload.principal, principal)) + .length >= this.maxMcpSessionsPerPrincipal || + (!context && + (this.mcpContexts.size >= this.maxMcpSessionsGlobal || + this.mcpCountForPrincipal(principal) >= this.maxMcpSessionsPerPrincipal)) + ) { + return jsonRpcError(429, -32000, "Connection limit exceeded."); + } + let releaseUpload = () => {}; + const upload: McpUpload = { + principal, + abort: new AbortController(), + done: new Promise((resolve) => { + releaseUpload = resolve; + }), + release: () => releaseUpload(), + }; + this.mcpUploads.add(upload); + if (context) { + context.inFlight += 1; + context.lastUsedMs = this.clock.now(); + } + let markedContext = context; let transient = false; - if (sessionId) { - const existing = this.mcpSessions.get(sessionId); - if (!existing || !principalsEqual(existing.principal, principal)) { - return jsonRpcError(404, -32001, "Session not found."); + try { + let dispatchRequest = request; + if (request.method === MCP_HTTP_CONTRACT.method) { + const length = request.headers.get("content-length"); + if (length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_HTTP_BODY_BYTES)) { + return jsonRpcError(413, -32600, "Request body is too large."); + } + // The low-level SDK Server does not inherit McpServer's batch/member limits. + // Bound the actual stream before JSON parsing or creating an MCP context. + const reader = request.body?.getReader(); + const chunks: Uint8Array[] = []; + let received = 0; + if (reader) { + const cancel = () => { + void reader.cancel().catch(() => undefined); + }; + let interruptRead = () => {}; + const interrupted = new Promise((_, reject) => { + interruptRead = () => { + cancel(); + reject(new Error("MCP read interrupted")); + }; + }); + const timer = setTimeout(() => upload.abort.abort(), 30_000); + timer.unref?.(); + upload.abort.signal.addEventListener("abort", interruptRead, { once: true }); + request.signal.addEventListener("abort", interruptRead, { once: true }); + try { + while (true) { + if (upload.abort.signal.aborted || request.signal.aborted) { + return jsonRpcError( + this.rotating || this.stopping ? 503 : 408, + -32000, + "Request interrupted.", + ); + } + const part = await Promise.race([reader.read(), interrupted]); + if (upload.abort.signal.aborted || request.signal.aborted) { + return jsonRpcError( + this.rotating || this.stopping ? 503 : 408, + -32000, + "Request interrupted.", + ); + } + if (part.done) break; + received += part.value.byteLength; + if (received > MAX_HTTP_BODY_BYTES) { + cancel(); + return jsonRpcError(413, -32600, "Request body is too large."); + } + chunks.push(part.value); + } + } catch { + if (this.rotating || this.stopping) + return jsonRpcError(503, -32000, "Request interrupted."); + if (request.signal.aborted || upload.abort.signal.aborted) { + return jsonRpcError(408, -32000, "Request interrupted."); + } + return jsonRpcError(400, -32700, "Parse error."); + } finally { + clearTimeout(timer); + upload.abort.signal.removeEventListener("abort", interruptRead); + request.signal.removeEventListener("abort", interruptRead); + reader.releaseLock(); + } + } + if (length !== null && Number(length) !== received) { + return jsonRpcError(400, -32600, "Invalid request body length."); + } + const bytes = new Uint8Array(received); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + const json: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); + if (Array.isArray(json)) { + return jsonRpcError(400, -32600, "JSON-RPC batches are not supported."); + } + } catch { + return jsonRpcError(400, -32700, "Parse error."); + } + dispatchRequest = new Request(request, { body: bytes, signal: request.signal }); } - context = existing; - } else { - if (request.method === "DELETE") { - return jsonRpcError(400, -32600, "MCP session header is required."); + + if (!this.mcpRequestAuthorized(request, principal, upload, context, sessionId)) { + return jsonRpcError(503, -32000, "Broker is unavailable."); + } + await this.reapIdleSessions(); + if (!context) { + if ( + this.mcpContexts.size >= this.maxMcpSessionsGlobal || + this.mcpCountForPrincipal(principal) >= this.maxMcpSessionsPerPrincipal + ) { + return jsonRpcError(429, -32000, "Connection limit exceeded."); + } + transient = true; + context = await this.createMcpContext(principal); + markedContext = context; + context.inFlight += 1; } if ( - this.mcpContexts.size >= this.maxMcpSessionsGlobal || - this.mcpCountForPrincipal(principal) >= this.maxMcpSessionsPerPrincipal + !this.mcpRequestAuthorized( + request, + principal, + upload, + sessionId ? context : undefined, + sessionId, + ) || + context.closing ) { - return jsonRpcError(429, -32000, "Connection limit exceeded."); - } - transient = true; - context = await this.createMcpContext(principal); - } - - context.inFlight += 1; - context.lastUsedMs = this.clock.now(); - try { - const response = await context.transport.handleRequest(request); - if (transient && context.transport.sessionId === undefined) { - await this.closeMcpContext(context); + if (transient) await this.closeMcpContext(context); + return jsonRpcError(503, -32000, "Broker is unavailable."); } - if (request.method === "DELETE") { - await this.closeMcpContext(context); + context.lastUsedMs = this.clock.now(); + try { + const response = await context.transport.handleRequest(dispatchRequest); + if (transient && context.transport.sessionId === undefined) { + await this.closeMcpContext(context); + } + if (request.method === "DELETE") { + await this.closeMcpContext(context); + } + return withSafeHeaders(response); + } catch { + if (transient) await this.closeMcpContext(context); + return jsonRpcError(400, -32700, "Parse error."); } - return withSafeHeaders(response); - } catch { - if (transient) await this.closeMcpContext(context); - return jsonRpcError(400, -32700, "Parse error."); } finally { - context.inFlight = Math.max(0, context.inFlight - 1); - if (!context.closing) context.lastUsedMs = this.clock.now(); + if (markedContext) { + markedContext.inFlight -= 1; + if (!markedContext.closing) markedContext.lastUsedMs = this.clock.now(); + } + this.mcpUploads.delete(upload); + upload.release(); } } diff --git a/packages/broker/test/sdk-transport.test.ts b/packages/broker/test/sdk-transport.test.ts index 50fa1d9..419c327 100644 --- a/packages/broker/test/sdk-transport.test.ts +++ b/packages/broker/test/sdk-transport.test.ts @@ -57,6 +57,14 @@ class CorrelatedSdkTransport implements Transport { } async send(message: JSONRPCMessage, options?: TransportSendOptions): Promise { + const sdkOptions = options && { + ...(options.resumptionToken === undefined + ? {} + : { resumptionToken: options.resumptionToken }), + ...(options.onresumptiontoken === undefined + ? {} + : { onresumptiontoken: options.onresumptiontoken }), + }; if ( typeof message === "object" && message !== null && @@ -69,10 +77,10 @@ class CorrelatedSdkTransport implements Transport { const sdkId = messageId(message); if (sdkId === undefined) throw new Error("SDK request ID is unavailable."); this.correlations.set(wire.id, { sdkId, request }); - await this.inner.send(wire, options); + await this.inner.send(wire, sdkOptions); return; } - await this.inner.send(message, options); + await this.inner.send(message, sdkOptions); } async close(): Promise { diff --git a/packages/broker/test/server.test.ts b/packages/broker/test/server.test.ts index ec368e0..77fa1cf 100644 --- a/packages/broker/test/server.test.ts +++ b/packages/broker/test/server.test.ts @@ -1,4 +1,5 @@ import { readFileSync } from "node:fs"; +import { connect } from "node:net"; import { afterEach, describe, expect, test } from "bun:test"; import { AuthenticatedClientPrincipalSchema, @@ -125,6 +126,443 @@ function initializeBody(id: string): string { }); } +test("MCP HTTP boundary rejects oversized, inconsistent and batched bodies before dispatch", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ service: harness.service, hostname: "127.0.0.1", port: 0 }); + try { + const endpoint = await daemon.start(); + const credential = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + const headers = { + Authorization: `Bearer ${credential.token}`, + Host: new URL(endpoint).host, + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + }; + const invalid = async (body: string, extra: Record = {}) => + daemon.handleRequest( + new Request(`${endpoint}/mcp`, { method: "POST", headers: { ...headers, ...extra }, body }), + ); + const secret = "never-echo-token-or-body"; + const cases = [ + () => invalid("x".repeat(128 * 1024 + 1)), + () => invalid(initializeBody(secret), { "Content-Length": "3" }), + () => invalid(JSON.stringify([JSON.parse(initializeBody(secret))])), + () => invalid(initializeBody(secret), { "Content-Length": String(128 * 1024 + 1) }), + ]; + for (const send of cases) { + const response = await send(); + expect([400, 413]).toContain(response.status); + const text = await response.text(); + expect(text).not.toContain(secret); + expect(text).not.toContain(credential.token); + expect(daemon.connectionCounts().mcp).toBe(0); + } + let consumedChunks = 0; + const chunked = new Request(`${endpoint}/mcp`, { + method: "POST", + headers, + body: new ReadableStream({ + pull(controller) { + consumedChunks += 1; + controller.enqueue(new Uint8Array(64 * 1024)); + }, + }), + }); + const chunkedResponse = await daemon.handleRequest(chunked); + expect(chunkedResponse.status).toBe(413); + // ReadableStream may prefetch one extra chunk before cancellation settles. + expect(consumedChunks).toBeLessThanOrEqual(4); + expect(daemon.connectionCounts().mcp).toBe(0); + const unauthorized = await daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + headers: { ...headers, Authorization: "Bearer invalid" }, + body: "x".repeat(128 * 1024 + 1), + }), + ); + expect(unauthorized.status).toBe(401); + expect(daemon.connectionCounts().mcp).toBe(0); + // Bun's socket-level cap may reject before the application authentication handler. + const overSocket = await post(endpoint, credential, "x".repeat(128 * 1024 + 1)); + expect(overSocket.status).toBe(413); + expect(daemon.connectionCounts().mcp).toBe(0); + const healthy = await invalid(initializeBody("healthy")); + expect(healthy.status).toBe(200); + expect(healthy.headers.get("MCP-Session-Id")).toBeTruthy(); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +test("paused authenticated uploads reserve per-request capacity and protect existing sessions from reaping", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ + service: harness.service, + hostname: "127.0.0.1", + port: 0, + clock: harness.clock, + maxMcpSessionsPerPrincipal: 1, + maxMcpSessionsGlobal: 1, + mcpSessionIdleMs: 1_000, + }); + try { + const endpoint = await daemon.start(); + const credential = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + const session = await initialize(endpoint, credential); + const headers = { + Authorization: `Bearer ${credential.token}`, + Host: new URL(endpoint).host, + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + "MCP-Session-Id": session.sessionId, + "MCP-Protocol-Version": session.protocolVersion, + }; + let controller: ReadableStreamDefaultController | undefined; + const paused = daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + headers, + body: new ReadableStream({ + start(value) { + controller = value; + }, + }), + }), + ); + const rejected = await daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + headers, + body: initializeBody("blocked"), + }), + ); + expect(rejected.status).toBe(429); + harness.clock.advance(1_000); + expect(await daemon.reapIdleSessions()).toBe(0); + expect(daemon.connectionCounts().mcp).toBe(1); + controller?.enqueue( + new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: "ping", method: "ping" })), + ); + controller?.close(); + expect((await paused).status).toBe(200); + expect( + ( + await post( + endpoint, + credential, + JSON.stringify({ jsonrpc: "2.0", id: "next", method: "ping" }), + session, + ) + ).status, + ).toBe(200); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +test("rotation cancels a paused authenticated upload without admitting the old credential", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ + service: harness.service, + hostname: "127.0.0.1", + port: 0, + maxMcpSessionsPerPrincipal: 1, + maxMcpSessionsGlobal: 1, + }); + try { + const endpoint = await daemon.start(); + const old = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + let controller: ReadableStreamDefaultController | undefined; + const paused = daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + headers: { + Host: new URL(endpoint).host, + Authorization: `Bearer ${old.token}`, + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + body: new ReadableStream({ + start(value) { + controller = value; + }, + }), + }), + ); + const replacement = await daemon.rotateCredential(); + try { + controller?.enqueue(new TextEncoder().encode(initializeBody("old"))); + controller?.close(); + } catch { + /* rotation cancels the reader */ + } + expect((await paused).status).toBe(503); + expect(daemon.connectionCounts().mcp).toBe(0); + expect((await post(endpoint, old, initializeBody("old-again"))).status).toBe(401); + expect((await post(endpoint, replacement, initializeBody("new"))).status).toBe(200); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +test("rotation invalidates a paused request on an existing MCP session", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ service: harness.service, port: 0 }); + try { + const endpoint = await daemon.start(); + const old = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + const session = await initialize(endpoint, old); + const abort = new AbortController(); + const paused = daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + signal: abort.signal, + headers: { + Host: new URL(endpoint).host, + Authorization: `Bearer ${old.token}`, + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + "MCP-Session-Id": session.sessionId, + }, + body: new ReadableStream({ start() {} }), + }), + ); + expect(daemon.uploadCountsForTesting().total).toBe(1); + const replacement = await daemon.rotateCredential(); + expect((await paused).status).toBe(503); + expect(daemon.uploadCountsForTesting().total).toBe(0); + expect(daemon.connectionCounts().mcp).toBe(0); + expect((await post(endpoint, replacement, initializeBody("new-session"))).status).toBe(200); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +test("upload reservation has a global ceiling, and aborted reads release all slots", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ + service: harness.service, + port: 0, + maxMcpSessionsPerPrincipal: 2, + maxMcpSessionsGlobal: 2, + }); + try { + const endpoint = await daemon.start(); + const credential = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + const headers = { + Host: new URL(endpoint).host, + Authorization: `Bearer ${credential.token}`, + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + }; + const controllers: AbortController[] = []; + const pending = Array.from({ length: 2 }, (_, index) => { + const controller = new AbortController(); + controllers.push(controller); + return daemon.handleRequest( + new Request(`${endpoint}/mcp`, { + method: "POST", + headers, + signal: controller.signal, + body: new ReadableStream({ + start() {}, + // A non-cooperative producer must not hold an admission slot after abort. + ...(index === 0 ? { cancel: () => new Promise(() => {}) } : {}), + }), + }), + ); + }); + expect(daemon.uploadCountsForTesting()).toEqual({ total: 2, byPrincipal: [2] }); + const overflow = await daemon.handleRequest( + new Request(`${endpoint}/mcp`, { method: "POST", headers, body: initializeBody("overflow") }), + ); + expect(overflow.status).toBe(429); + expect(daemon.uploadCountsForTesting().total).toBe(2); + for (const controller of controllers) controller.abort(); + expect((await Promise.all(pending)).map((response) => response.status)).toEqual([408, 408]); + expect(daemon.uploadCountsForTesting().total).toBe(0); + expect((await post(endpoint, credential, initializeBody("healthy"))).status).toBe(200); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +async function rawHttp(endpoint: string, wire: Uint8Array, halfClose = false): Promise { + const port = Number(new URL(endpoint).port); + return new Promise((resolve, reject) => { + const socket = connect({ host: "127.0.0.1", port }); + const chunks: Uint8Array[] = []; + socket.setTimeout(2_000, () => socket.destroy(new Error("Raw fixture timeout"))); + socket.once("connect", () => { + if (halfClose) socket.end(wire); + else socket.write(wire); + }); + socket.on("data", (chunk: Buffer) => { + chunks.push(Uint8Array.from(chunk)); + if (chunks.reduce((length, part) => length + part.length, 0) > 32 * 1024) + socket.destroy(new Error("Unbounded raw response")); + }); + socket.once("error", reject); + socket.once("close", () => { + const result = new Uint8Array(chunks.reduce((length, part) => length + part.length, 0)); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.length; + } + resolve(new TextDecoder().decode(result)); + }); + }); +} + +test("raw loopback HTTP rejects chunked overflow, truncation and malformed framing without breaking SDK", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ service: harness.service, port: 0 }); + try { + const endpoint = await daemon.start(); + const credential = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + const prefix = `POST /mcp HTTP/1.1\r\nHost: ${new URL(endpoint).host}\r\nAuthorization: Bearer ${credential.token}\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nConnection: close\r\n`; + const secret = "never-echo-raw-body"; + const overflow = `${prefix}Transfer-Encoding: chunked\r\n\r\n${(64 * 1024).toString(16)}\r\n${"x".repeat(64 * 1024)}\r\n${(64 * 1024 + 1).toString(16)}\r\n${"x".repeat(64 * 1024 + 1)}\r\n0\r\n\r\n`; + const truncated = `${prefix}Content-Length: 200\r\n\r\n${initializeBody(secret)}`; + const wrongLength = `${prefix}Content-Length: 3\r\n\r\n${initializeBody(secret)}`; + const invalidUtf8 = Uint8Array.from([ + ...new TextEncoder().encode(`${prefix}Content-Length: 2\r\n\r\n`), + 0xc3, + 0x28, + ]); + const malformedJson = `${prefix}Content-Length: 3\r\n\r\n{xx`; + for (const [index, input] of [ + new TextEncoder().encode(overflow), + new TextEncoder().encode(truncated), + new TextEncoder().encode(wrongLength), + invalidUtf8, + new TextEncoder().encode(malformedJson), + ].entries()) { + const text = await rawHttp(endpoint, input, index === 1); + for ( + let attempt = 0; + attempt < 20 && daemon.uploadCountsForTesting().total > 0; + attempt += 1 + ) { + await Bun.sleep(10); + } + if (index === 0) expect(text).toMatch(/^HTTP\/1\.1 413 /); + if (index === 1) expect(text).toBe(""); // Bun closes a truncated upload before an application response. + if (index >= 2) expect(text).toMatch(/^HTTP\/1\.1 400 /); + expect(text).not.toContain(credential.token); + expect(text).not.toContain(secret); + expect(daemon.uploadCountsForTesting().total).toBe(0); + expect(daemon.connectionCounts().mcp).toBe(0); + } + const session = await initialize(endpoint, credential); + expect( + ( + await post( + endpoint, + credential, + JSON.stringify({ jsonrpc: "2.0", id: "ping-healthy", method: "ping" }), + session, + ) + ).status, + ).toBe(200); + } finally { + await daemon.stop(); + harness.close(); + } +}); + +test("raw paused upload cannot exceed the per-principal capacity and disconnect restores it", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ + service: harness.service, + port: 0, + maxMcpSessionsPerPrincipal: 1, + maxMcpSessionsGlobal: 1, + }); + let socket: ReturnType | undefined; + try { + const endpoint = await daemon.start(); + const credential = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + socket = connect({ host: "127.0.0.1", port: Number(new URL(endpoint).port) }); + await new Promise((resolve, reject) => { + socket?.once("connect", resolve); + socket?.once("error", reject); + }); + socket.write( + `POST /mcp HTTP/1.1\r\nHost: ${new URL(endpoint).host}\r\nAuthorization: Bearer ${credential.token}\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n`, + ); + for (let attempt = 0; attempt < 30 && daemon.uploadCountsForTesting().total === 0; attempt += 1) + await Bun.sleep(10); + expect(daemon.uploadCountsForTesting().total).toBe(1); + const capped = await post(endpoint, credential, initializeBody("capped")); + expect(capped.status).toBe(429); + expect(daemon.uploadCountsForTesting().total).toBe(1); + socket.destroy(); + for (let attempt = 0; attempt < 30 && daemon.uploadCountsForTesting().total > 0; attempt += 1) + await Bun.sleep(10); + expect(daemon.uploadCountsForTesting().total).toBe(0); + expect((await post(endpoint, credential, initializeBody("recovered"))).status).toBe(200); + } finally { + socket?.destroy(); + await daemon.stop(); + harness.close(); + } +}); + +test("credential rotation cancels an in-flight raw socket upload before old-token dispatch", async () => { + const harness = createHarness(); + const daemon = new BrokerDaemon({ service: harness.service, port: 0 }); + let socket: ReturnType | undefined; + try { + const endpoint = await daemon.start(); + const old = CredentialFileSchema.parse( + JSON.parse(readFileSync(harness.credentialFilePath, "utf8")), + ); + socket = connect({ host: "127.0.0.1", port: Number(new URL(endpoint).port) }); + await new Promise((resolve, reject) => { + socket?.once("connect", resolve); + socket?.once("error", reject); + }); + socket.write( + `POST /mcp HTTP/1.1\r\nHost: ${new URL(endpoint).host}\r\nAuthorization: Bearer ${old.token}\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n`, + ); + for (let attempt = 0; attempt < 30 && daemon.uploadCountsForTesting().total === 0; attempt += 1) + await Bun.sleep(10); + expect(daemon.uploadCountsForTesting().total).toBe(1); + const fresh = await daemon.rotateCredential(); + for (let attempt = 0; attempt < 30 && daemon.uploadCountsForTesting().total > 0; attempt += 1) + await Bun.sleep(10); + expect(daemon.uploadCountsForTesting().total).toBe(0); + expect(daemon.connectionCounts().mcp).toBe(0); + expect((await post(endpoint, old, initializeBody("old"))).status).toBe(401); + expect((await post(endpoint, fresh, initializeBody("new"))).status).toBe(200); + } finally { + socket?.destroy(); + await daemon.stop(); + harness.close(); + } +}); + function eventRequest(endpoint: string, credential: CredentialFile): Request { const host = new URL(endpoint).host; return new Request(`${endpoint}/events`, { @@ -144,6 +582,14 @@ function testPrincipal(index: number): AuthenticatedClientPrincipal { }); } +function enableSyntheticCapacityPrincipals(harness: Harness): void { + const original = harness.service.authenticate.bind(harness.service); + harness.service.authenticate = (header) => { + const match = /^Bearer capacity-principal-(\d+)$/.exec(header ?? ""); + return match ? testPrincipal(Number(match[1])) : original(header); + }; +} + interface PrivateMcpAdmission { handleMcp(request: Request, principal: AuthenticatedClientPrincipal): Promise; } @@ -165,6 +611,7 @@ async function initializeForPrincipal( headers: { Accept: "application/json, text/event-stream", "Content-Type": "application/json", + Authorization: `Bearer ${principal.principalId}`, }, body: initializeBody(id), }), @@ -191,6 +638,7 @@ async function terminateForPrincipal( headers: { "MCP-Protocol-Version": session.protocolVersion, "MCP-Session-Id": session.sessionId, + Authorization: `Bearer ${principal.principalId}`, }, }), principal, @@ -529,6 +977,7 @@ describe("local MCP daemon", () => { test("accepts exactly 20 default MCP sessions per principal and releases capacity", async () => { harness = createHarness(); + enableSyntheticCapacityPrincipals(harness); daemon = new BrokerDaemon({ service: harness.service, hostname: "127.0.0.1", port: 0 }); const endpoint = await daemon.start(); const principal = testPrincipal(1); @@ -571,6 +1020,7 @@ describe("local MCP daemon", () => { test("accepts exactly 40 default MCP sessions globally and releases capacity", async () => { harness = createHarness(); + enableSyntheticCapacityPrincipals(harness); daemon = new BrokerDaemon({ service: harness.service, hostname: "127.0.0.1", port: 0 }); const endpoint = await daemon.start(); const principals = [testPrincipal(1), testPrincipal(2)]; diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 2f557ab..8c64f9f 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -20,7 +20,7 @@ "build": "bun ../../scripts/run-package-tsc.ts build" }, "dependencies": { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/broker": "workspace:0.1.0", "@opencode-agentbus/protocol": "workspace:0.1.0", "@opencode-ai/plugin": "1.18.19" diff --git a/packages/plugin/test/advisory-exposure.test.ts b/packages/plugin/test/advisory-exposure.test.ts new file mode 100644 index 0000000..9ebb625 --- /dev/null +++ b/packages/plugin/test/advisory-exposure.test.ts @@ -0,0 +1,323 @@ +import { describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { tool } from "@opencode-ai/plugin"; +import type { PluginInput } from "@opencode-ai/plugin"; +import ts from "typescript"; + +import { createAgentBusPlugin } from "../src/plugin"; +import type { AgentBusRuntime } from "../src/runtime"; + +// Use the legacy SDK's own Zod classes, not the patched broker/protocol copy. +function assertScalarArgument( + schema: unknown, +): asserts schema is InstanceType< + typeof tool.schema.ZodString | typeof tool.schema.ZodNumber | typeof tool.schema.ZodOptional +> { + const scalar = schema instanceof tool.schema.ZodOptional ? schema.unwrap() : schema; + if (!(scalar instanceof tool.schema.ZodString || scalar instanceof tool.schema.ZodNumber)) { + throw new Error("Legacy tool arguments must be strings/numbers, optionally wrapped once."); + } +} + +function isEffectModule(name: string): boolean { + return name === "effect" || name.startsWith("effect/") || name.startsWith("@effect/"); +} + +function isCookieName(name: string): boolean { + return /^(?:Http)?Cookies?$/u.test(name); +} + +function forbiddenModule(name: string): boolean { + return ( + /^(?:toml|glob|minimatch)(?:\/|$)/u.test(name) || + (isEffectModule(name) && + name.split("/").some((part) => isCookieName(part.replace(/\.js$/u, "")))) + ); +} + +function literalText(node: ts.Node | undefined): string | undefined { + return node && ts.isStringLiteralLike(node) ? node.text : undefined; +} + +function loadedModule(node: ts.Expression): string | undefined { + if (ts.isAwaitExpression(node) || ts.isParenthesizedExpression(node)) { + return loadedModule(node.expression); + } + if ( + ts.isCallExpression(node) && + (node.expression.kind === ts.SyntaxKind.ImportKeyword || + (ts.isIdentifier(node.expression) && node.expression.text === "require")) + ) { + return literalText(node.arguments[0]); + } + return undefined; +} + +// A deliberately local import-surface guard, not interprocedural taint analysis +// or a claim about the SDK/host's own TOML, Cookie, glob, or minimatch execution. +function exposureViolations(source: string): string[] { + const file = ts.createSourceFile("product.ts", source, ts.ScriptTarget.Latest, true); + const violations: string[] = []; + const effectNamespaces = new Set(); + const visit = (node: ts.Node, inspect: (node: ts.Node) => void): void => { + inspect(node); + ts.forEachChild(node, (child) => visit(child, inspect)); + }; + const inspectModule = (name: string | undefined): void => { + if (name !== undefined && forbiddenModule(name)) violations.push(`affected module: ${name}`); + }; + visit(file, (node) => { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + const name = literalText(node.moduleSpecifier); + inspectModule(name); + if (name === undefined || !isEffectModule(name)) return; + if (ts.isImportDeclaration(node)) { + const clause = node.importClause; + if (clause?.name) effectNamespaces.add(clause.name.text); + const bindings = clause?.namedBindings; + if (bindings && ts.isNamespaceImport(bindings)) effectNamespaces.add(bindings.name.text); + if (bindings && ts.isNamedImports(bindings)) { + for (const binding of bindings.elements) { + if (isCookieName((binding.propertyName ?? binding.name).text)) { + violations.push("Effect Cookie named import"); + } + } + } + } else if (node.exportClause && ts.isNamedExports(node.exportClause)) { + for (const binding of node.exportClause.elements) { + if (isCookieName((binding.propertyName ?? binding.name).text)) { + violations.push("Effect Cookie named export"); + } + } + } + } + if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) { + const name = literalText(node.moduleReference.expression); + inspectModule(name); + if (name !== undefined && isEffectModule(name)) effectNamespaces.add(node.name.text); + } + if (ts.isCallExpression(node)) inspectModule(loadedModule(node)); + if (ts.isVariableDeclaration(node) && node.initializer && ts.isIdentifier(node.name)) { + const name = loadedModule(node.initializer); + if (name !== undefined && isEffectModule(name)) effectNamespaces.add(node.name.text); + } + }); + const fromEffectNamespace = (node: ts.Expression): boolean => { + if (ts.isIdentifier(node)) return effectNamespaces.has(node.text); + if (ts.isAwaitExpression(node) || ts.isParenthesizedExpression(node)) { + return fromEffectNamespace(node.expression); + } + const name = loadedModule(node); + return name !== undefined && isEffectModule(name); + }; + visit(file, (node) => { + if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + const member = ts.isPropertyAccessExpression(node) + ? node.name.text + : literalText(node.argumentExpression); + if (member && isCookieName(member) && fromEffectNamespace(node.expression)) { + violations.push("Effect Cookie namespace access"); + } + } + if ( + ts.isVariableDeclaration(node) && + node.initializer && + fromEffectNamespace(node.initializer) && + ts.isObjectBindingPattern(node.name) + ) { + for (const binding of node.name.elements) { + const key = binding.propertyName ?? binding.name; + if ((ts.isIdentifier(key) || ts.isStringLiteralLike(key)) && isCookieName(key.text)) { + violations.push("Effect Cookie destructuring"); + } + } + } + }); + return violations; +} + +async function productSources(directory: string): Promise { + const paths: string[] = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (entry.name === "node_modules") continue; + const path = join(directory, entry.name); + if (entry.isSymbolicLink()) throw new Error(`Unexpected product-source symlink: ${path}`); + if (entry.isDirectory()) paths.push(...(await productSources(path))); + else if (entry.isFile() && /\.[cm]?[jt]sx?$/u.test(entry.name)) paths.push(path); + } + return paths.sort(); +} + +describe("SDK-chain advisory exposure regressions", () => { + test("rejects synthetic collection/expanding schemas before checking product arguments", () => { + const z = tool.schema; + for (const schema of [ + z.array(z.string()), + z.object({ value: z.string() }), + z.record(z.string(), z.string()), + z.map(z.string(), z.string()), + z.set(z.string()), + z.tuple([z.string()]), + z.union([z.string(), z.number()]), + z.lazy(() => z.string()), + z.custom(() => true), + z.array(z.string()).optional(), + ]) { + expect(() => assertScalarArgument(schema)).toThrow("Legacy tool arguments"); + } + // Small positive control for the issue-allocation mechanism (GHSA-mrhx-c7xc-m3w5). + const expanded = z.array(z.string()).safeParse(Array(1024).fill(null)); + expect(expanded.success).toBe(false); + if (expanded.success) throw new Error("Expected invalid collection."); + expect(expanded.error.issues.length).toBeGreaterThan(2); + for (const schema of [z.string(), z.number(), z.string().optional(), z.number().optional()]) { + expect(() => assertScalarArgument(schema)).not.toThrow(); + } + }); + + test("all four actual legacy tools reject collection inputs with one bounded field issue", async () => { + const unexpectedCalls: string[] = []; + const fail = (name: string): never => { + unexpectedCalls.push(name); + throw new Error(`Unexpected fixture I/O: ${name}`); + }; + const callbacks = new Map, () => void>(); + let disposals = 0; + const plugin = createAgentBusPlugin({ + brokerBootstrapFactory: () => ({ ensureReady: async () => fail("broker readiness") }), + runtimeFactory: () => + ({ + dispose: async () => { + disposals += 1; + }, + }) as unknown as AgentBusRuntime, + bootstrapScheduler: { + set: (callback) => { + const handle = { unref: () => undefined } as unknown as ReturnType; + callbacks.set(handle, callback); + return handle; + }, + clear: (handle) => { + callbacks.delete(handle); + }, + }, + }); + const input = { + client: new Proxy({}, { get: (_target, name) => fail(`host client ${String(name)}`) }), + directory: "/worktree", + worktree: "/worktree", + serverUrl: new URL("http://127.0.0.1:4096"), + project: { id: "project_01" }, + experimental_workspace: { register: () => fail("workspace registration") }, + $: {}, + } as unknown as PluginInput; + const hooks = await plugin(input, { + credentialFilePath: "/does/not/read/credentials/in/schema-fixture", + autoStartBroker: false, + wakeOnMessage: false, + }); + try { + const tools = hooks.tool ?? {}; + expect(Object.keys(tools).sort()).toEqual([ + "agentbus_receive", + "agentbus_reply", + "agentbus_search_sessions", + "agentbus_send", + ]); + expect(callbacks.size).toBe(1); + let fields = 0; + for (const definition of Object.values(tools)) { + expect(Object.keys(definition.args).length).toBeLessThanOrEqual(3); + for (const schema of Object.values(definition.args)) { + fields += 1; + assertScalarArgument(schema); + const result = schema.safeParse(Array(1024).fill(null)); + expect(result.success).toBe(false); + if (result.success) throw new Error("Collection accepted by scalar argument."); + expect(result.error.issues).toHaveLength(1); + } + } + expect(fields).toBe(8); + expect(tools.agentbus_receive?.args).toEqual({}); + expect(unexpectedCalls).toEqual([]); + } finally { + await hooks.dispose?.(); + } + expect(callbacks.size).toBe(0); + expect(disposals).toBe(1); + expect(unexpectedCalls).toEqual([]); + }); + + test("detects synthetic affected imports, literal loads, and Effect Cookie aliases", () => { + for (const source of [ + 'import "toml";', + 'import { parse as decode } from "toml"; decode(peer);', + 'const { parse: decode } = require("toml"); decode(peer);', + 'await import("toml");', + 'import glob from "glob"; glob(peer);', + 'const { minimatch: match } = require("minimatch"); match(peer, peer);', + "await import(`glob/sync`);", + 'import matcher = require("minimatch");', + 'export * from "glob";', + 'import * as C from "effect/unstable/http/Cookies"; C.parseHeader(peer);', + 'import { Cookies as C } from "effect/unstable/http"; C.parseHeader(peer);', + 'import { HttpCookies as C } from "@effect/platform"; C.fromInput(peer);', + 'export { Cookies as C } from "effect/unstable/http";', + 'import * as H from "effect/unstable/http"; H.Cookies.parseHeader(peer);', + 'const H = require("effect/unstable/http"); H["Cookies"].parseHeader(peer);', + 'const { Cookies: C } = await import("effect/unstable/http"); C.parseHeader(peer);', + '(await import("effect/unstable/http")).Cookies.parseHeader(peer);', + ]) { + expect(exposureViolations(source).length, source).toBeGreaterThan(0); + } + expect( + exposureViolations(` + // import "toml"; glob(peer); Cookies.parseHeader(peer); + const message = 'require("minimatch")'; + import { Effect, Exit, Stream } from "effect"; + import { parse } from "./toml-not-a-package"; + const unrelated = { Cookies: () => undefined }; unrelated.Cookies(); + `), + ).toEqual([]); + }); + + test("owned product sources have no direct affected TOML/glob/minimatch/Cookie entrypoints", async () => { + for (const name of ["plugin", "broker", "protocol"]) { + const paths = await productSources(join(import.meta.dir, "..", "..", name, "src")); + expect(paths.length).toBeGreaterThan(0); + for (const path of paths) { + expect(exposureViolations(await readFile(path, "utf8")), path).toEqual([]); + } + } + }); + + test("source traversal rejects symlinked product sources", async () => { + const root = await mkdtemp(join(tmpdir(), "agentbus-exposure-symlink-")); + try { + await writeFile(join(root, "target.ts"), 'import "toml";'); + await symlink("target.ts", join(root, "alias.ts")); + await expect(productSources(root)).rejects.toThrow("Unexpected product-source symlink"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + test("source traversal includes generated and test-named code inside a product root", async () => { + const root = await mkdtemp(join(tmpdir(), "agentbus-exposure-sources-")); + try { + for (const directory of ["generated", "test"]) { + await mkdir(join(root, directory)); + await writeFile(join(root, directory, "caller.test.ts"), 'import "toml";'); + } + const paths = await productSources(root); + expect(paths).toHaveLength(2); + for (const path of paths) + expect(exposureViolations(await readFile(path, "utf8"))).not.toEqual([]); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 2a17527..26468cc 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -19,6 +19,6 @@ "build": "tsc -p tsconfig.build.json" }, "dependencies": { - "zod": "3.25.76" + "zod": "4.6.7" } } diff --git a/packages/protocol/src/connection.ts b/packages/protocol/src/connection.ts index f462c20..a6a581d 100644 --- a/packages/protocol/src/connection.ts +++ b/packages/protocol/src/connection.ts @@ -45,7 +45,9 @@ export const CredentialFilePathSchema = z /** Trusted local plugin configuration. The path is sensitive and must never reach model context. */ export const TrustedConnectionConfigSchema = z .object({ - endpoint: LoopbackBrokerEndpointSchema.default(DEFAULT_BROKER_ENDPOINT), + endpoint: LoopbackBrokerEndpointSchema.default(() => + LoopbackBrokerEndpointSchema.parse(DEFAULT_BROKER_ENDPOINT), + ), timeoutMs: z .number() .int() diff --git a/packages/protocol/src/constants.ts b/packages/protocol/src/constants.ts index 0da5f73..dd386a5 100644 --- a/packages/protocol/src/constants.ts +++ b/packages/protocol/src/constants.ts @@ -55,7 +55,7 @@ export const MCP_INITIALIZATION_CONTRACT = Object.freeze({ initializeRequestMethod: "initialize", initializedNotificationMethod: "notifications/initialized", sessionHeader: "MCP-Session-Id", - sessionManagedBy: "@modelcontextprotocol/sdk@1.30.0", + sessionManagedBy: "@modelcontextprotocol/sdk@1.32.2", } as const); export const MCP_HTTP_CONTRACT = Object.freeze({ diff --git a/packages/protocol/test/wire.test.ts b/packages/protocol/test/wire.test.ts index 573f469..cd7654f 100644 --- a/packages/protocol/test/wire.test.ts +++ b/packages/protocol/test/wire.test.ts @@ -9,6 +9,7 @@ import { CREDENTIAL_PROVISIONING_CONTRACT, CONNECTION_SECURITY_CONTRACT, CredentialFileSchema, + HandshakeRequestSchema, DEFAULT_ACTIVE_SESSIONS_PER_PRINCIPAL, DEFAULT_BROKER_ENDPOINT, DEFAULT_BROKER_STARTUP_TIMEOUT_MS, @@ -34,6 +35,8 @@ import { PrincipalSessionBindingSchema, SSE_HTTP_CONTRACT, SessionIdentitySchema, + SessionMetadataSchema, + BodyHashSchema, TOKEN_ROTATION_CONTRACT, TrustedConnectionConfigSchema, bodySha256, @@ -72,13 +75,32 @@ const request = EnqueueMessageRequestSchema.parse({ params: { source, target, body: "hello", ttlSeconds: 60 }, }); +test("patched Zod bounds collections and preserves strict wire validation", () => { + expect( + SessionMetadataSchema.safeParse({ labels: Array.from({ length: 1_024 }, () => "label") }) + .success, + ).toBe(false); + expect( + HandshakeRequestSchema.safeParse({ + protocolVersion: PROTOCOL_VERSION, + requestId: "request_01", + method: METHODS.HANDSHAKE, + params: { supportedProtocolVersions: Array.from({ length: 1_024 }, () => 2) }, + }).success, + ).toBe(false); + expect(SessionIdentitySchema.safeParse({ ...source, unexpected: true }).success).toBe(false); + expect(BodyHashSchema.safeParse("f".repeat(64)).success).toBe(true); + expect(BodyHashSchema.safeParse("f".repeat(63)).success).toBe(false); + expect(SessionMetadataSchema.safeParse({ title: "\ud800" }).success).toBe(false); +}); + describe("exact MCP Streamable HTTP mapping", () => { test("freezes SDK initialization, content type, session, and custom-method semantics", () => { expect(MCP_INITIALIZATION_CONTRACT).toEqual({ initializeRequestMethod: "initialize", initializedNotificationMethod: "notifications/initialized", sessionHeader: "MCP-Session-Id", - sessionManagedBy: "@modelcontextprotocol/sdk@1.30.0", + sessionManagedBy: "@modelcontextprotocol/sdk@1.32.2", }); expect(MCP_HTTP_CONTRACT).toEqual({ method: "POST", diff --git a/release.config.json b/release.config.json new file mode 100644 index 0000000..8385a82 --- /dev/null +++ b/release.config.json @@ -0,0 +1,12 @@ +{ + "schemaVersion": 1, + "releaseLine": "v1", + "version": "0.1.0", + "supportedLines": ["v1"], + "packageNames": { + "v1": "@atacama-dev/opencode-agentbus-v1", + "v2": "@atacama-dev/opencode-agentbus-v2" + }, + "readiness": { "v1": true, "v2": false }, + "publishEnabled": true +} diff --git a/scripts/package-smoke.ts b/scripts/package-smoke.ts index 1ad7c7f..a353776 100644 --- a/scripts/package-smoke.ts +++ b/scripts/package-smoke.ts @@ -647,18 +647,18 @@ try { const expectedDependencies: Readonly>>> = { broker: { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/protocol": "workspace:0.1.0", - zod: "3.25.76", + zod: "4.6.7", }, plugin: { - "@modelcontextprotocol/sdk": "1.30.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opencode-agentbus/broker": "workspace:0.1.0", "@opencode-agentbus/protocol": "workspace:0.1.0", "@opencode-ai/plugin": "1.18.19", }, protocol: { - zod: "3.25.76", + zod: "4.6.7", }, }; diff --git a/scripts/release/config.test.ts b/scripts/release/config.test.ts new file mode 100644 index 0000000..901e900 --- /dev/null +++ b/scripts/release/config.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import { isReleaseVersion, parseReleaseConfig, parseReleaseTag, readReleaseConfig } from "./config"; + +test("release versions reject ambiguous tags and shell/control characters", () => { + for (const version of ["0.1.0", "1.2.3-beta.1", "2.0.0-rc.0", "1.0.0-beta-test"]) + expect(isReleaseVersion(version)).toBe(true); + for (const version of [ + "01.0.0", + "1.0", + "1.0.0-", + "1.0.0-01", + "1.0.0-a..b", + "1.0.0+local", + "1.0.0\n", + "1.0.0;id", + "999999999999999999999.0.0", + ]) + expect(isReleaseVersion(version)).toBe(false); +}); + +test("source release line, exact version and prerelease channel are explicit", () => { + const config = readReleaseConfig(); + const v1 = parseReleaseConfig({ ...config, releaseLine: "v1", supportedLines: ["v1"] }); + expect(parseReleaseTag(`opencode-v1/v${v1.version}`, v1)).toMatchObject({ + line: "v1", + npmTag: "latest", + packageName: v1.packageNames.v1, + }); + expect(() => parseReleaseTag(`opencode-v2/v${v1.version}`, v1)).toThrow(); + expect(() => parseReleaseTag("opencode-v1/v99.0.0", v1)).toThrow(); + const beta = parseReleaseConfig({ ...config, version: "0.1.0-beta.1" }); + expect(parseReleaseTag(`opencode-${beta.releaseLine}/v${beta.version}`, beta)).toMatchObject({ + prerelease: true, + npmTag: "next", + }); +}); + +test("publication is not enabled by absent, extra or malformed configuration", () => { + const config = parseReleaseConfig({ + ...readReleaseConfig(), + readiness: { v1: false, v2: false }, + publishEnabled: false, + }); + expect(config.publishEnabled).toBe(false); + expect(Object.values(config.readiness)).toEqual([false, false]); + for (const malformed of [ + { ...config, publishEnabled: "true" }, + { ...config, token: "not-a-config-field" }, + { ...config, packageNames: { ...config.packageNames, v2: config.packageNames.v1 } }, + { ...config, supportedLines: ["v1", "v1"] }, + { ...config, readiness: { v1: true } }, + ]) + expect(() => parseReleaseConfig(malformed)).toThrow(); +}); diff --git a/scripts/release/config.ts b/scripts/release/config.ts new file mode 100644 index 0000000..2e3f2ae --- /dev/null +++ b/scripts/release/config.ts @@ -0,0 +1,126 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; + +export type ReleaseLine = "v1" | "v2"; + +export interface ReleaseConfig { + readonly schemaVersion: 1; + readonly releaseLine: ReleaseLine; + readonly version: string; + readonly supportedLines: readonly ReleaseLine[]; + readonly packageNames: Readonly>; + readonly readiness: Readonly>; + readonly publishEnabled: boolean; +} + +export interface PackageArtifact { + readonly schemaVersion: 1; + readonly line: ReleaseLine; + readonly packageName: string; + readonly version: string; + readonly tarball: string; + readonly sha256: string; + readonly sourceCommit: string; +} + +export const REPOSITORY_ROOT = resolve(import.meta.dir, "../.."); + +function object(value: unknown): Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) + throw new Error("Release configuration must contain JSON objects."); + return value as Record; +} + +export function releaseLine(value: unknown): ReleaseLine { + if (value !== "v1" && value !== "v2") throw new Error("Release line must be v1 or v2."); + return value; +} + +export function isReleaseVersion(value: unknown): value is string { + if (typeof value !== "string" || value.length > 128 || !/^[0-9A-Za-z.-]+$/u.test(value)) + return false; + const separator = value.indexOf("-"); + const core = separator < 0 ? value : value.slice(0, separator); + const prerelease = separator < 0 ? undefined : value.slice(separator + 1); + return ( + core.split(".").length === 3 && + core + .split(".") + .every((part) => /^(0|[1-9][0-9]*)$/u.test(part) && Number.isSafeInteger(Number(part))) && + (prerelease === undefined || + prerelease + .split(".") + .every( + (part) => + /^[0-9A-Za-z-]+$/u.test(part) && + (!/^[0-9]+$/u.test(part) || /^(0|[1-9][0-9]*)$/u.test(part)), + )) + ); +} + +export function parseReleaseConfig(value: unknown): ReleaseConfig { + const data = object(value); + const keys = [ + "schemaVersion", + "releaseLine", + "version", + "supportedLines", + "packageNames", + "readiness", + "publishEnabled", + ]; + if ( + Object.keys(data).length !== keys.length || + Object.keys(data).some((key) => !keys.includes(key)) + ) + throw new Error("Unexpected or missing release configuration field."); + const line = releaseLine(data.releaseLine); + const names = object(data.packageNames); + const ready = object(data.readiness); + if ( + data.schemaVersion !== 1 || + !isReleaseVersion(data.version) || + !Array.isArray(data.supportedLines) || + data.supportedLines.length < 1 || + data.supportedLines.length > 2 || + new Set(data.supportedLines).size !== data.supportedLines.length || + !data.supportedLines.includes(line) || + data.supportedLines.some((item) => item !== "v1" && item !== "v2") || + Object.keys(names).sort().join(",") !== "v1,v2" || + Object.keys(ready).sort().join(",") !== "v1,v2" || + names.v1 === names.v2 || + [names.v1, names.v2].some( + (name) => + typeof name !== "string" || !/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/u.test(name), + ) || + typeof ready.v1 !== "boolean" || + typeof ready.v2 !== "boolean" || + typeof data.publishEnabled !== "boolean" + ) + throw new Error("Invalid release configuration."); + return data as unknown as ReleaseConfig; +} + +export function readReleaseConfig(root = REPOSITORY_ROOT): ReleaseConfig { + return parseReleaseConfig(JSON.parse(readFileSync(resolve(root, "release.config.json"), "utf8"))); +} + +export function parseReleaseTag(tag: string, config: ReleaseConfig) { + const match = /^opencode-(v[12])\/v(.+)$/u.exec(tag); + if (!match || !isReleaseVersion(match[2])) throw new Error("Invalid Agent Bus release tag."); + const line = releaseLine(match[1]); + const version = match[2]; + if ( + line !== config.releaseLine || + !config.supportedLines.includes(line) || + version !== config.version + ) + throw new Error("Release tag does not match this source's release line and version."); + return { + line, + version, + packageName: config.packageNames[line], + prerelease: version.includes("-"), + npmTag: version.includes("-") ? "next" : "latest", + } as const; +} diff --git a/scripts/release/fixtures/probe.ts b/scripts/release/fixtures/probe.ts new file mode 100644 index 0000000..be5726f --- /dev/null +++ b/scripts/release/fixtures/probe.ts @@ -0,0 +1,224 @@ +// Executed only inside an independently installed temporary consumer. +import { createRequire } from "node:module"; +import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const [packageName, line] = process.argv.slice(2); +if (!packageName || (line !== "v1" && line !== "v2")) throw new Error("Invalid probe arguments"); +const require = createRequire(import.meta.url); +const root = require.resolve(packageName); +const cli = require.resolve("@opencode-agentbus/broker/cli", { paths: [root] }); +if ( + !root.includes("/consumer/node_modules/") || + !cli.includes("/consumer/node_modules/") || + !(statSync(cli).mode & 0o100) || + !readFileSync(cli, "utf8").startsWith("#!/usr/bin/env bun\n") +) + throw new Error( + `Installed broker CLI is missing or not executable: ${root}, ${cli}, ${statSync(cli).mode.toString(8)}`, + ); +const plugin = await import(pathToFileURL(root).href); +if (Object.keys(plugin).join(",") !== "default") throw new Error("Unexpected plugin exports"); +if (line === "v1" && typeof plugin.default !== "function") + throw new Error("V1 default async factory missing"); +if ( + line === "v2" && + (plugin.default?.id !== "agentbus-stock-experimental" || + typeof plugin.default.effect !== "function") +) + throw new Error("V2 stock Effect definition missing"); +if (line === "v2") { + const { Effect, Stream } = await import( + pathToFileURL(require.resolve("effect", { paths: [root] })).href + ); + const names: string[] = []; + const context = { + options: { + experimentalStock: true, + deploymentNamespace: "package_probe", + endpoint: "http://127.0.0.1:1", + credentialFilePath: "/unused/credential", + brokerDatabasePath: "/unused/broker.sqlite", + autoStartBroker: false, + focusOnReceiveApproval: false, + }, + location: { + directory: "/probe", + workspaceID: "wsp_probe", + project: { id: "project_probe", directory: "/probe", canonical: "/probe" }, + }, + event: { subscribe: () => Stream.never }, + session: { get: () => Effect.fail(new Error("No session query expected")) }, + tool: { + hook: () => Effect.succeed({ dispose: Effect.void }), + transform: (callback: (editor: { add(tool: { name: string }): void }) => void) => { + callback({ + add(tool) { + names.push(tool.name); + }, + }); + return Effect.succeed({ dispose: Effect.void }); + }, + }, + }; + await Effect.runPromise(Effect.scoped(plugin.default.effect(context))); + if ( + names.sort().join(",") !== + "agentbus_receive,agentbus_reply,agentbus_search_sessions,agentbus_send" + ) + throw new Error("Installed V2 did not register only the four model tools"); +} +const state = join(import.meta.dir, "isolated-state"); +mkdirSync(state, { mode: 0o700 }); +const broker = await import(pathToFileURL(cli).href); +const daemon = await broker.launchBrokerDaemon( + { + databasePath: join(state, "broker.sqlite"), + credentialFilePath: join(state, "credential.json"), + hostname: "127.0.0.1", + port: 0, + maxActiveSessionsPerPrincipal: 300, + }, + { info() {}, warn() {}, error() {} }, +); +try { + const response = await fetch(`${daemon.endpoint}/mcp`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{}", + }); + if (response.status !== 401 || !existsSync(join(state, "credential.json"))) + throw new Error("Broker auth boundary unavailable"); + if (line === "v1") { + const options = { + endpoint: daemon.endpoint, + credentialFilePath: join(state, "credential.json"), + autoStartBroker: false, + timeoutMs: 500, + maxActiveSessionsPerPrincipal: 300, + }; + const host = (id: string, title: string) => ({ + client: { + session: { + list: async () => ({ + data: [ + { + id, + projectID: "smoke_project", + directory: state, + title, + version: "1.18.19", + time: { created: 1, updated: 1 }, + }, + ], + }), + status: async () => ({ data: { [id]: { type: "idle" } } }), + }, + project: { + current: async () => ({ + data: { id: "smoke_project", worktree: state, time: { created: 1 } }, + }), + }, + tui: { showToast: async () => ({ data: true }), publish: async () => ({ data: true }) }, + }, + directory: state, + worktree: state, + serverUrl: new URL(daemon.endpoint), + project: { id: "smoke_project", worktree: state, time: { created: 1 } }, + experimental_workspace: { register() {} }, + $: {}, + }); + const hooksA = await plugin.default(host("installed_host_a", "Installed A"), options); + const hooksB = await plugin.default(host("installed_host_b", "Installed B"), options); + try { + const approvalsA: string[] = []; + const approvalsB: string[] = []; + const ctx = (id: string, approvals: string[]) => ({ + sessionID: id, + messageID: `message_${id}`, + agent: "build", + directory: state, + worktree: state, + abort: new AbortController().signal, + metadata() {}, + ask: async (request: { permission: string }) => { + approvals.push(request.permission); + }, + }); + const a = ctx("installed_host_a", approvalsA); + const b = ctx("installed_host_b", approvalsB); + const tool = async ( + hooks: typeof hooksA, + name: string, + args: object, + context: typeof a, + ): Promise> => + JSON.parse((await hooks.tool[name].execute(args, context)).output); + const retry = async (action: () => Promise): Promise => { + let failure: unknown; + for (let n = 0; n < 120; n++) { + try { + return await action(); + } catch (error) { + failure = error; + await Bun.sleep(25); + } + } + throw failure; + }; + const handle = await retry(async () => { + const result = await tool( + hooksA, + "agentbus_search_sessions", + { query: "Installed B", limit: 1 }, + a, + ); + const matches = result.matches as Array<{ handle?: unknown }> | undefined; + if (typeof matches?.[0]?.handle !== "string") throw new Error("No recipient"); + return matches[0].handle; + }); + const sent = await tool( + hooksA, + "agentbus_send", + { target: handle, body: "A to B", ttlSeconds: 60 }, + a, + ); + if (typeof sent.messageId !== "string" || "body" in sent) + throw new Error("Invalid send receipt"); + const received = await retry(() => tool(hooksB, "agentbus_receive", {}, b)); + if (received.messageId !== sent.messageId || received.body !== "A to B") + throw new Error("Receive mismatch"); + const reply = await tool( + hooksB, + "agentbus_reply", + { messageId: received.messageId, body: "B to A", ttlSeconds: 60 }, + b, + ); + if ( + reply.messageId === sent.messageId || + reply.replyToMessageId !== sent.messageId || + "body" in reply + ) + throw new Error("Invalid reply receipt"); + const returned = await retry(() => tool(hooksA, "agentbus_receive", {}, a)); + if ( + returned.messageId !== reply.messageId || + returned.replyToMessageId !== sent.messageId || + returned.body !== "B to A" + ) + throw new Error("Return mismatch"); + if ( + !approvalsA.includes("agentbus_search_sessions") || + !approvalsA.includes("agentbus_receive") || + !approvalsB.includes("agentbus_receive") + ) + throw new Error("Fixture approval hooks missing"); + } finally { + await Promise.all([hooksA.dispose?.(), hooksB.dispose?.()]); + } + } +} finally { + await daemon.stop(); +} +console.log(`Installed ${line} archive fixture passed (not real native host acceptance)`); diff --git a/scripts/release/package.test.ts b/scripts/release/package.test.ts new file mode 100644 index 0000000..16dabdb --- /dev/null +++ b/scripts/release/package.test.ts @@ -0,0 +1,83 @@ +import { expect, test } from "bun:test"; +import { readReleaseConfig } from "./config"; +import { + assertPackageLine, + assertDeclaredBundleImports, + assertSourcePins, + publicDependencies, + validatePackedManifest, +} from "./package"; + +test("supported lines are selected without readiness or publication approval", () => { + const config = readReleaseConfig(); + expect(assertPackageLine(config, "v1")).toBe("v1"); + expect(assertPackageLine({ ...config, supportedLines: ["v1", "v2"] }, "v2")).toBe("v2"); + expect(() => assertPackageLine({ ...config, supportedLines: ["v1"] }, "v2")).toThrow(); + expect(() => assertPackageLine(config, "../v1")).toThrow(); +}); + +test("bundle import scan rejects undeclared bare static imports and literal dynamic imports", () => { + const declared = { "@opencode-agentbus/broker": "0.1.0", "@opencode/plugin": "2.2.7" }; + expect(() => + assertDeclaredBundleImports( + 'import "node:fs"; import "@opencode/plugin/effect"; import("@opencode-agentbus/broker/cli")', + declared, + ), + ).not.toThrow(); + expect(() => assertDeclaredBundleImports('import "@opencode/client"', declared)).toThrow( + "@opencode/client", + ); + expect(() => assertDeclaredBundleImports('import("effect")', declared)).toThrow("effect"); + expect(() => assertDeclaredBundleImports('import "./missing.js"', declared)).toThrow( + "./missing.js", + ); +}); + +test("archive dependency pins cannot drift from source dependency pins", () => { + const plugin = { dependencies: publicDependencies("v1") }; + const broker = { dependencies: { "@modelcontextprotocol/sdk": "1.32.2", zod: "4.6.7" } }; + const protocol = { dependencies: { zod: "4.6.7" } }; + expect(() => assertSourcePins("v1", plugin, broker, protocol)).not.toThrow(); + const legacyPlugin = { + dependencies: { "@modelcontextprotocol/sdk": "1.32.2", "@opencode-ai/plugin": "1.18.19" }, + }; + expect(() => assertSourcePins("v1", legacyPlugin, broker, protocol)).not.toThrow(); + expect(() => + assertSourcePins( + "v1", + { dependencies: { ...plugin.dependencies, zod: "4.6.8" } }, + broker, + protocol, + ), + ).toThrow("pins differ"); + expect(() => assertSourcePins("v2", plugin, broker, protocol)).toThrow("pins differ"); +}); + +test("public dependency profiles exclude the opposite OpenCode SDK", () => { + expect(publicDependencies("v1")).toEqual({ + "@modelcontextprotocol/sdk": "1.32.2", + zod: "4.6.7", + "@opencode-ai/plugin": "1.18.19", + }); + expect(publicDependencies("v2")).toEqual({ + "@modelcontextprotocol/sdk": "1.32.2", + zod: "4.6.7", + "@opencode/plugin": "2.2.7", + "@opencode/client": "2.2.7", + "@opencode/schema": "2.2.7", + effect: "4.1.0", + "@types/json-schema": "7.0.15", + }); +}); + +test("packed manifest rejects workspace paths and lifecycle scripts", () => { + const manifest = { name: "example", version: "0.1.0", dependencies: { zod: "4.6.7" } }; + expect(() => validatePackedManifest(manifest)).not.toThrow(); + expect(() => + validatePackedManifest({ ...manifest, dependencies: { zod: "workspace:4.6.7" } }), + ).toThrow(); + expect(() => + validatePackedManifest({ ...manifest, dependencies: { zod: "file:../foo" } }), + ).toThrow(); + expect(() => validatePackedManifest({ ...manifest, scripts: { prepack: "echo hi" } })).toThrow(); +}); diff --git a/scripts/release/package.ts b/scripts/release/package.ts new file mode 100644 index 0000000..e8c53fc --- /dev/null +++ b/scripts/release/package.ts @@ -0,0 +1,344 @@ +import { createHash } from "node:crypto"; +import { builtinModules } from "node:module"; +import { + chmodSync, + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { join, resolve, basename } from "node:path"; +import { + readReleaseConfig, + releaseLine, + REPOSITORY_ROOT, + type PackageArtifact, + type ReleaseConfig, + type ReleaseLine, +} from "./config"; + +const internalVersion = "0.1.0"; +const common = { "@modelcontextprotocol/sdk": "1.32.2", zod: "4.6.7" }; +const internal = { + "@opencode-agentbus/broker": internalVersion, + "@opencode-agentbus/protocol": internalVersion, +}; +const lifecycle = /^(pre|post)?(install|pack|publish|version)$|^prepare$|^prepublishOnly$/u; +const builtins = new Set(builtinModules.map((name) => name.replace(/^node:/u, ""))); + +/** Covers literal static/dynamic imports and require calls, not computed runtime specifiers. */ +export function assertDeclaredBundleImports( + bundle: string, + dependencies: Readonly>, +): void { + for (const item of new Bun.Transpiler({ loader: "js" }).scanImports(bundle)) { + const specifier = item.path; + if (specifier.startsWith("node:") || specifier.startsWith("bun:") || builtins.has(specifier)) + continue; + const parts = specifier.split("/"); + const packageName = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + if (!packageName || !Object.hasOwn(dependencies, packageName)) + throw new Error(`Undeclared bundled JS import: ${specifier}`); + } +} + +export function assertPackageLine(config: ReleaseConfig, input: unknown): ReleaseLine { + const line = releaseLine(input); + if (!config.supportedLines.includes(line)) throw new Error(`Unsupported release line: ${line}`); + return line; +} + +function runtimeDependencies(line: ReleaseLine): Record { + return line === "v1" + ? { ...common, "@opencode-ai/plugin": "1.18.19" } + : { + ...common, + "@opencode/plugin": "2.2.7", + "@opencode/client": "2.2.7", + "@opencode/schema": "2.2.7", + effect: "4.1.0", + }; +} + +export function publicDependencies(line: ReleaseLine): Record { + return { + ...runtimeDependencies(line), + // The public V2 SDK exposes JSON Schema types without declaring this dependency. + ...(line === "v2" ? { "@types/json-schema": "7.0.15" } : {}), + }; +} + +export function assertSourcePins( + line: ReleaseLine, + plugin: { dependencies?: Record }, + broker: { dependencies?: Record }, + protocol: { dependencies?: Record }, +): void { + if ( + Object.entries(runtimeDependencies(line)).some( + ([name, version]) => + !(line === "v1" && name === "zod" && plugin.dependencies?.zod === undefined) && + plugin.dependencies?.[name] !== version, + ) || + Object.entries(common).some(([name, version]) => broker.dependencies?.[name] !== version) || + protocol.dependencies?.zod !== common.zod + ) + throw new Error("Release dependency pins differ from the tested source manifests."); +} + +export function validatePackedManifest(value: unknown): void { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Invalid package manifest"); + const manifest = value as Record; + if (typeof manifest.name !== "string" || typeof manifest.version !== "string") + throw new Error("Invalid package identity"); + for (const section of [ + "dependencies", + "optionalDependencies", + "peerDependencies", + "devDependencies", + ] as const) { + const deps = manifest[section]; + if (deps === undefined) continue; + if (!deps || typeof deps !== "object" || Array.isArray(deps)) + throw new Error("Invalid dependencies"); + for (const version of Object.values(deps)) + if ( + typeof version !== "string" || + /^(?:workspace|file|link):/u.test(version) || + version.startsWith("/") || + version.startsWith(".") + ) + throw new Error("Local/workspace dependency forbidden"); + } + if ( + manifest.scripts && + (typeof manifest.scripts !== "object" || + Object.keys(manifest.scripts).some((key) => lifecycle.test(key))) + ) + throw new Error("Lifecycle scripts forbidden"); +} + +function checkedDist(root: string, destination: string): void { + const source = join(root, "dist"); + if (!existsSync(source)) throw new Error(`Build required: ${source}`); + mkdirSync(destination, { recursive: true }); + for (const entry of readdirSync(source, { withFileTypes: true })) { + if (!entry.isFile() || !/^[a-z0-9-]+\.(?:js|d\.ts)$/u.test(entry.name)) continue; + const content = readFileSync(join(source, entry.name), "utf8").replace( + /^\/\/# sourceMappingURL=.*$/gmu, + "", + ); + writeFileSync(join(destination, entry.name), content, { + mode: entry.name === "cli.js" ? 0o755 : 0o644, + }); + if (entry.name === "cli.js") chmodSync(join(destination, entry.name), 0o755); + } +} + +function internalManifest(name: "broker" | "protocol") { + const source = JSON.parse( + readFileSync(join(REPOSITORY_ROOT, "packages", name, "package.json"), "utf8"), + ); + if (source.version !== internalVersion) throw new Error(`Unexpected ${name} internal version`); + const { main, types, exports, bin } = source; + const result = { + name: `@opencode-agentbus/${name}`, + version: internalVersion, + license: "GPL-3.0-or-later", + type: "module", + main, + types, + exports, + ...(bin ? { bin } : {}), + dependencies: + name === "broker" + ? { ...common, "@opencode-agentbus/protocol": internalVersion } + : { zod: "4.6.7" }, + }; + validatePackedManifest(result); + return result; +} + +function stageInternal(stage: string, name: "broker" | "protocol"): void { + const target = join(stage, "node_modules", "@opencode-agentbus", name); + checkedDist(join(REPOSITORY_ROOT, "packages", name), join(target, "dist")); + writeFileSync( + join(target, "package.json"), + `${JSON.stringify(internalManifest(name), null, 2)}\n`, + ); + copyFileSync(join(REPOSITORY_ROOT, "LICENSE"), join(target, "LICENSE")); +} + +function stageManifest(line: ReleaseLine, config: ReleaseConfig) { + const result = { + name: config.packageNames[line], + version: config.version, + license: "GPL-3.0-or-later", + author: { name: "Julien Tesson", email: "julien@atacama.tech" }, + type: "module", + description: `OpenCode Agent Bus ${line.toUpperCase()} adapter${line === "v2" ? " (experimental stock Effect)" : ""}`, + repository: { type: "git", url: "https://github.com/atacama-dev/opencode-agentbus.git" }, + os: ["linux"], + engines: { bun: ">=1.3.9" }, + main: "./dist/index.js", + types: "./dist/index.d.ts", + exports: { + ".": { types: "./dist/index.d.ts", import: "./dist/index.js", default: "./dist/index.js" }, + }, + files: ["dist", "node_modules/@opencode-agentbus", "LICENSE", "README.md"], + bundledDependencies: ["@opencode-agentbus/broker", "@opencode-agentbus/protocol"], + dependencies: { ...publicDependencies(line), ...internal }, + ...(line === "v2" + ? { experimental: true, experimentalStock: true, focusOnReceiveApproval: false } + : {}), + }; + validatePackedManifest(result); + return result; +} + +async function checkedCommand(command: string[], cwd: string): Promise { + const process = Bun.spawn(command, { + cwd, + stdout: "pipe", + stderr: "pipe", + env: { + PATH: processEnvPath(), + HOME: join(cwd, ".npm-home"), + npm_config_cache: join(cwd, ".npm-cache"), + }, + }); + const [stdout, stderr, exit] = await Promise.all([ + new Response(process.stdout).text(), + new Response(process.stderr).text(), + process.exited, + ]); + if (exit !== 0) throw new Error(`${command[0]} failed (${exit}): ${stderr.slice(0, 2000)}`); + return stdout.trim(); +} +function processEnvPath(): string { + return process.env.PATH ?? "/usr/bin:/bin"; +} + +export async function packageLine( + lineInput: unknown, + outputRoot: string, + root = REPOSITORY_ROOT, +): Promise { + if (resolve(root) !== REPOSITORY_ROOT) + throw new Error("Packaging a different source root is not supported"); + const config = readReleaseConfig(root); + const line = assertPackageLine(config, lineInput); + const sourceManifest = (name: "plugin" | "broker" | "protocol") => + JSON.parse(readFileSync(join(root, "packages", name, "package.json"), "utf8")); + assertSourcePins( + line, + sourceManifest("plugin"), + sourceManifest("broker"), + sourceManifest("protocol"), + ); + const destination = resolve(outputRoot, line); + const sourceCommit = (await checkedCommand(["git", "rev-parse", "HEAD"], root)).trim(); + if (!/^[a-f0-9]{40}$/u.test(sourceCommit)) throw new Error("Invalid source commit"); + mkdirSync("/tmp/opencode", { recursive: true, mode: 0o700 }); + const stage = mkdtempSync("/tmp/opencode/agentbus-pack-"); + try { + const built = await Bun.build({ + entrypoints: [join(root, "packages/plugin/src", line === "v1" ? "index.ts" : "stock-v2.ts")], + packages: "external", + target: "bun", + format: "esm", + outdir: join(stage, "dist"), + naming: "index.js", + }); + if (!built.success) throw new Error(`Bun bundle failed: ${built.logs.map(String).join("; ")}`); + const bundle = readFileSync(join(stage, "dist/index.js"), "utf8"); + if ( + line === "v1" && + /@opencode\/(?:plugin|client|schema)|agentbus-stock-experimental/u.test(bundle) + ) + throw new Error("V2 runtime in V1 bundle"); + if (line === "v2" && /@opencode-ai\/plugin|createAgentBusPlugin\(/u.test(bundle)) + throw new Error("V1 runtime in V2 bundle"); + const declaration = readFileSync( + join(root, "packages/plugin/dist", line === "v1" ? "index.d.ts" : "stock-v2.d.ts"), + "utf8", + ).replace(/^\/\/# sourceMappingURL=.*$/gmu, ""); + writeFileSync(join(stage, "dist/index.d.ts"), declaration); + for (const name of ["protocol", "broker"] as const) stageInternal(stage, name); + writeFileSync( + join(stage, "package.json"), + `${JSON.stringify(stageManifest(line, config), null, 2)}\n`, + ); + assertDeclaredBundleImports(bundle, stageManifest(line, config).dependencies); + copyFileSync(join(root, "LICENSE"), join(stage, "LICENSE")); + writeFileSync( + join(stage, "README.md"), + `# OpenCode Agent Bus ${line.toUpperCase()}\n\nGPL-3.0-or-later. Requires Linux, Bun >=1.3.9 and OpenCode ${line === "v1" ? "1.18.19" : "2.2.7"}.\n\n${line === "v2" ? "EXPERIMENTAL stock V2 Effect plugin only: supply experimentalStock: true; focusOnReceiveApproval: false. This is not the paired server/TUI/RPC adapter. Native approval is required before receiving peer bodies. Native cross-project always approval can re-prompt.\n\n" : "V1 default async plugin. Native disclosure/search approvals are required. Cross-project always grants and manual attached-client acceptance remain outstanding.\n\n"}Publication, dependency-audit remediation and manual native-host acceptance remain gated; this archive is not a security certification. The bundled broker starts via its declared CLI; do not bypass native approval.\n\nCopyright (C) 2026 Julien Tesson . You may redistribute and modify this program under the GNU GPL version 3 or, at your option, any later version. It comes without any warranty; see LICENSE for the full terms.\n\nPartly developed using [Roster](https://github.com/mathiasbourgoin/roster).\n`, + ); + const packedOutput = JSON.parse( + await checkedCommand( + ["npm", "pack", "--ignore-scripts", "--json", "--pack-destination", stage], + stage, + ), + ); + const packed = Array.isArray(packedOutput) + ? packedOutput[0] + : packedOutput?.[config.packageNames[line]]; + if ( + typeof packed?.filename !== "string" || + !Array.isArray(packed.bundled) || + !["@opencode-agentbus/broker", "@opencode-agentbus/protocol"].every((name) => + packed.bundled.includes(name), + ) + ) + throw new Error( + `Invalid npm pack result or missing bundled dependencies: ${JSON.stringify(packedOutput).slice(0, 1200)}`, + ); + const archive = join(stage, packed.filename); + if (!existsSync(archive)) throw new Error("npm pack did not create archive"); + const sha256 = createHash("sha256") + .update(new Uint8Array(readFileSync(archive))) + .digest("hex"); + const manifest: PackageArtifact = { + schemaVersion: 1, + line, + packageName: config.packageNames[line], + version: config.version, + tarball: basename(archive), + sha256, + sourceCommit, + }; + mkdirSync(destination, { recursive: true }); + const target = join(destination, manifest.tarball); + if ( + existsSync(target) && + createHash("sha256") + .update(new Uint8Array(readFileSync(target))) + .digest("hex") !== sha256 + ) + throw new Error("Different archive already exists; use a new output directory"); + const oldManifest = join(destination, "manifest.json"); + if ( + existsSync(oldManifest) && + readFileSync(oldManifest, "utf8") !== `${JSON.stringify(manifest, null, 2)}\n` + ) + throw new Error("Different manifest already exists; use a new output directory"); + if (!existsSync(target)) copyFileSync(archive, target); + writeFileSync(oldManifest, `${JSON.stringify(manifest, null, 2)}\n`); + return manifest; + } finally { + rmSync(stage, { recursive: true, force: true }); + } +} + +if (import.meta.main) { + const args = process.argv.slice(2); + if (args.length !== 4 || args[0] !== "--line" || args[2] !== "--out" || !args[3]) + throw new Error("Usage: bun scripts/release/package.ts --line v1|v2 --out release-artifacts"); + console.log(JSON.stringify(await packageLine(args[1], args[3]), null, 2)); +} diff --git a/scripts/release/policy.test.ts b/scripts/release/policy.test.ts new file mode 100644 index 0000000..03120d6 --- /dev/null +++ b/scripts/release/policy.test.ts @@ -0,0 +1,281 @@ +import { expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseReleaseConfig, readReleaseConfig } from "./config"; +import { + assertCleanAudit, + assertPublicationAllowed, + readArtifact, + releaseEvent, + validateManifest, + verifySource, +} from "./policy"; + +const config = parseReleaseConfig({ + ...readReleaseConfig(), + releaseLine: "v2", + supportedLines: ["v1", "v2"], + version: "0.1.0", + readiness: { v1: true, v2: true }, + publishEnabled: true, +}); +const sourceCommit = "a".repeat(40); +const event = { + action: "published", + repository: { full_name: "atacama-dev/opencode-agentbus", private: false }, + release: { id: 7, tag_name: "opencode-v2/v0.1.0", draft: false, prerelease: false }, +}; +const cleanAudit = { + auditReportVersion: 2, + vulnerabilities: {}, + metadata: { + dependencies: { prod: 4 }, + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: 0 }, + }, +}; + +test("release policy accepts only canonical published, matching releases", () => { + expect(releaseEvent("release", event, config)).toMatchObject({ line: "v2", npmTag: "latest" }); + for (const name of ["push", "pull_request", "workflow_dispatch"]) + expect(() => releaseEvent(name, event, config)).toThrow(); + for (const bad of [ + { ...event, action: "created" }, + { ...event, repository: { ...event.repository, full_name: "fork/opencode-agentbus" } }, + { ...event, repository: { full_name: event.repository.full_name } }, + { ...event, release: { ...event.release, draft: true } }, + { ...event, release: { ...event.release, prerelease: true } }, + { ...event, release: { ...event.release, id: -1 } }, + { ...event, release: { ...event.release, tag_name: "opencode-v1/v0.1.0" } }, + { ...event, release: { ...event.release, tag_name: "opencode-v2/v9.9.9" } }, + { ...event, release: { ...event.release, tag_name: "opencode-v2/v0.1.0;echo" } }, + ]) + expect(() => releaseEvent("release", bad, config)).toThrow(); + const beta = { ...config, version: "0.1.0-rc.1" }; + expect( + releaseEvent( + "release", + { + ...event, + release: { ...event.release, tag_name: "opencode-v2/v0.1.0-rc.1", prerelease: true }, + }, + beta, + ), + ).toMatchObject({ prerelease: true, npmTag: "next" }); +}); + +test("readiness, publication switch, and public-provenance policy fail closed independently", () => { + const release = releaseEvent("release", event, config); + expect(() => assertPublicationAllowed(config, release)).not.toThrow(); + expect(() => + assertPublicationAllowed({ ...config, readiness: { v1: true, v2: false } }, release), + ).toThrow("readiness"); + expect(() => assertPublicationAllowed({ ...config, publishEnabled: false }, release)).toThrow( + "disabled", + ); + expect(() => assertPublicationAllowed(config, { ...release, privateRepository: true })).toThrow( + "repository policy", + ); +}); + +test("production audit rejects every severity, malformed reports, empty graphs and API failures", () => { + expect(() => assertCleanAudit(cleanAudit)).not.toThrow(); + for (const key of ["info", "low", "moderate", "high", "critical", "total"]) + expect(() => + assertCleanAudit({ + ...cleanAudit, + metadata: { + ...cleanAudit.metadata, + vulnerabilities: { ...cleanAudit.metadata.vulnerabilities, [key]: 1 }, + }, + }), + ).toThrow(); + for (const bad of [ + {}, + { ...cleanAudit, error: {} }, + { ...cleanAudit, auditReportVersion: 1 }, + { ...cleanAudit, vulnerabilities: { hidden: {} } }, + { ...cleanAudit, metadata: { ...cleanAudit.metadata, dependencies: { prod: 0 } } }, + { ...cleanAudit, metadata: { ...cleanAudit.metadata, vulnerabilities: { total: 0 } } }, + ]) + expect(() => assertCleanAudit(bad)).toThrow(); +}); + +test("manifest rejects traversal, wrong identity, digest and source commit", () => { + const manifest = { + schemaVersion: 1, + line: "v2", + packageName: config.packageNames.v2, + version: config.version, + tarball: "agentbus.tgz", + sha256: "b".repeat(64), + sourceCommit, + } as const; + expect(validateManifest(manifest, config, "v2", sourceCommit)).toEqual(manifest); + for (const change of [ + { tarball: "../agentbus.tgz" }, + { tarball: "/agentbus.tgz" }, + { tarball: "dir/agentbus.tgz" }, + { tarball: "x\\agentbus.tgz" }, + { tarball: "--option.tgz" }, + { tarball: "x.tgz\n" }, + { sha256: "cafe" }, + { sourceCommit: "c".repeat(40) }, + { line: "v1" }, + { packageName: config.packageNames.v1 }, + { version: "0.2.0" }, + { unexpected: true }, + ]) + expect(() => + validateManifest({ ...manifest, ...change }, config, "v2", sourceCommit), + ).toThrow(); +}); + +test("actual archive digest, regular-file containment and package metadata are rechecked", () => { + const root = mkdtempSync(join(tmpdir(), "agentbus-artifact-policy-")); + try { + mkdirSync(join(root, "package")); + const metadata = join(root, "package/package.json"); + writeFileSync( + metadata, + JSON.stringify({ name: config.packageNames.v2, version: config.version }), + ); + const tarball = join(root, "agentbus.tgz"); + execFileSync("tar", ["-czf", tarball, "-C", root, "package"]); + const manifest = { + schemaVersion: 1, + line: "v2", + packageName: config.packageNames.v2, + version: config.version, + tarball: "agentbus.tgz", + sourceCommit, + sha256: createHash("sha256") + .update(new Uint8Array(readFileSync(tarball))) + .digest("hex"), + } as const; + const path = join(root, "manifest.json"); + writeFileSync(path, JSON.stringify(manifest)); + expect(readArtifact(path, config, "v2", sourceCommit).manifest).toEqual(manifest); + writeFileSync(tarball, "corrupt"); + expect(() => readArtifact(path, config, "v2", sourceCommit)).toThrow("SHA-256"); + writeFileSync(metadata, JSON.stringify({ name: "@wrong/name", version: config.version })); + execFileSync("tar", ["-czf", tarball, "-C", root, "package"]); + writeFileSync( + path, + JSON.stringify({ + ...manifest, + sha256: createHash("sha256") + .update(new Uint8Array(readFileSync(tarball))) + .digest("hex"), + }), + ); + expect(() => readArtifact(path, config, "v2", sourceCommit)).toThrow("package metadata"); + rmSync(tarball); + symlinkSync(metadata, tarball); + expect(() => readArtifact(path, config, "v2", sourceCommit)).toThrow("regular file"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("source proof requires annotated tag, exact HEAD, clean tree and protected-branch ancestry", () => { + // All refs below exist only inside this disposable fixture, never in the checkout. + const root = mkdtempSync(join(tmpdir(), "agentbus-source-policy-")); + const git = (...args: string[]) => + execFileSync("git", args, { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); + const tag = "opencode-v2/v0.1.0"; + try { + git("init", "--initial-branch=main"); + writeFileSync(join(root, "source"), "fixture"); + git("add", "source"); + git( + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-m", + "fixture", + ); + const commit = git("rev-parse", "HEAD"); + git("tag", tag); + git("update-ref", "refs/remotes/origin/main", commit); + expect(() => verifySource(root, tag, "v2")).toThrow("annotated"); + git("tag", "-d", tag); + git( + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "tag", + "-a", + tag, + "-m", + "fixture", + ); + expect(verifySource(root, tag, "v2")).toBe(commit); + expect(() => verifySource(root, tag, "v2", "a".repeat(40))).toThrow(); + writeFileSync(join(root, "source"), "changed"); + expect(() => verifySource(root, tag, "v2")).toThrow("clean"); + writeFileSync(join(root, "source"), "fixture"); + git("update-ref", "-d", "refs/remotes/origin/main"); + expect(() => verifySource(root, tag, "v2")).toThrow("protected branch"); + git("update-ref", "refs/remotes/origin/maintenance/opencode-v1", commit); + expect(() => verifySource(root, tag, "v2")).toThrow("protected branch"); + git("update-ref", "refs/remotes/origin/maintenance/opencode-v2", commit); + expect(verifySource(root, tag, "v2")).toBe(commit); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("workflow authority remains isolated from read-only builds and PR evidence", () => { + const ci = readFileSync(new URL("../../.github/workflows/ci.yml", import.meta.url), "utf8"); + const release = readFileSync( + new URL("../../.github/workflows/release.yml", import.meta.url), + "utf8", + ); + expect(ci).not.toMatch(/pull_request_target|id-token: write|contents: write|secrets\./u); + expect(ci).not.toContain("continue-on-error"); + expect(release).not.toContain("continue-on-error"); + for (const workflow of [ci, release]) { + for (const match of workflow.matchAll(/uses: ([^\s]+)/gu)) + expect(match[1]).toMatch(/^[\w/-]+@[a-f0-9]{40}$/u); + expect(workflow).toContain("bun install --frozen-lockfile --ignore-scripts"); + expect(workflow).toContain("persist-credentials: false"); + expect(workflow).toContain("mktemp -d /dev/shm/agentbus-tests.XXXXXX"); + expect(workflow).toContain('test "$(stat -f -c %T /dev/shm)" = tmpfs'); + expect(workflow).toContain("disk durability is not established"); + expect(workflow.match(/TMPDIR: \$\{\{ steps.fixtures.outputs.root \}\}/gu)).toHaveLength(2); + } + const publication = release.slice(release.indexOf("\n publication:")); + expect(publication).toContain("environment: ${{ needs.source.outputs.environment }}"); + expect(publication).toContain("id-token: write"); + expect(publication).toContain( + "group: npm-publication-${{ github.repository }}-${{ needs.source.outputs.line }}", + ); + expect(publication).toContain("cancel-in-progress: false"); + expect(publication).not.toMatch(/npm install|bun install|bun run build|npm publish|npm pack/u); + expect(publication).toContain("release-tested-${{ github.run_id }}"); + expect(release).not.toContain("release-npm"); + expect(release).not.toContain("RELEASE_NPM_CLI"); + expect(publication.match(/uses: actions\/download-artifact@/gu)).toHaveLength(1); + expect(publication).toContain("RELEASE_NODE_BINARY: ${{ steps.runtime.outputs.node }}"); + expect(publication.indexOf("id: runtime")).toBeLessThan( + publication.indexOf("uses: actions/download-artifact@"), + ); + expect(publication).toContain("package-manager-cache: false"); + const publisher = readFileSync(new URL("./publication.ts", import.meta.url), "utf8"); + expect(publisher).not.toContain("RELEASE_NPM_CLI"); + expect(publisher).not.toContain("release-npm"); + expect(publisher).toContain("execFileSync(tools.node, [tools.npmCli"); + expect(release.slice(0, release.indexOf("\n publication:"))).not.toMatch( + /contents: write|id-token: write/u, + ); +}); diff --git a/scripts/release/policy.ts b/scripts/release/policy.ts new file mode 100644 index 0000000..a30e461 --- /dev/null +++ b/scripts/release/policy.ts @@ -0,0 +1,240 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFileSync, lstatSync, readFileSync, realpathSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { + type PackageArtifact, + REPOSITORY_ROOT, + type ReleaseConfig, + type ReleaseLine, + parseReleaseTag, + readReleaseConfig, +} from "./config"; +import { evaluateAudit, type AuditContext } from "../security/audit"; + +export const RELEASE_REPOSITORY = "atacama-dev/opencode-agentbus"; + +export function record(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Expected a JSON object."); + return value as Record; +} + +export function releaseEvent(eventName: string, value: unknown, config: ReleaseConfig) { + const event = record(value); + const repository = record(event.repository); + const release = record(event.release); + if ( + eventName !== "release" || + event.action !== "published" || + repository.full_name !== RELEASE_REPOSITORY || + typeof repository.private !== "boolean" || + release.draft !== false || + !Number.isSafeInteger(release.id) || + (release.id as number) <= 0 || + typeof release.tag_name !== "string" + ) + throw new Error("Only an existing published release in the canonical repository is eligible."); + const parsed = parseReleaseTag(release.tag_name, config); + if (release.prerelease !== parsed.prerelease) + throw new Error("GitHub prerelease status must match the semantic version."); + return { + ...parsed, + tag: release.tag_name, + releaseId: release.id as number, + privateRepository: repository.private, + }; +} + +export function assertPublicationAllowed( + config: ReleaseConfig, + release: ReturnType, +) { + if (!config.readiness[release.line]) + throw new Error("Release readiness is false; building evidence is not release approval."); + if (!config.publishEnabled) throw new Error("Publication is disabled in release.config.json."); + if (release.privateRepository) + throw new Error( + "Public publication is blocked by repository policy until the repository is public (provenance).", + ); +} + +export function assertCleanAudit(value: unknown) { + const audit = record(value); + const metadata = record(audit.metadata); + const dependencies = record(metadata.dependencies); + const counts = record(metadata.vulnerabilities); + if ( + audit.auditReportVersion !== 2 || + "error" in audit || + !Number.isSafeInteger(dependencies.prod) || + (dependencies.prod as number) < 1 || + Object.keys(record(audit.vulnerabilities)).length !== 0 || + ["info", "low", "moderate", "high", "critical", "total"].some((key) => counts[key] !== 0) + ) + throw new Error("Production install audit is missing, malformed, or contains vulnerabilities."); +} + +/** Recompute from raw evidence, never trust an artifact's prior verdict. */ +export function assertAuditedArtifact( + manifest: PackageArtifact, + config: ReleaseConfig, + sourceCommit: string, + audit: unknown, + context: AuditContext, + exitCode: number, + ledger: unknown, +) { + validateManifest(manifest, config, manifest.line, sourceCommit); + if (!Number.isSafeInteger(exitCode) || (exitCode !== 0 && exitCode !== 1)) + throw new Error("Missing or invalid raw npm audit exit status"); + const expected = { + line: manifest.line, + packageName: manifest.packageName, + version: manifest.version, + sha256: manifest.sha256, + sourceCommit: manifest.sourceCommit, + }; + return evaluateAudit(audit, context, ledger, { expected, profile: "production", exitCode }); +} + +export function validateManifest( + value: unknown, + config: ReleaseConfig, + line: ReleaseLine, + sourceCommit: string, +): PackageArtifact { + const data = record(value); + if ( + Object.keys(data).sort().join(",") !== + "line,packageName,schemaVersion,sha256,sourceCommit,tarball,version" || + data.schemaVersion !== 1 || + data.line !== line || + !config.supportedLines.includes(line) || + data.packageName !== config.packageNames[line] || + data.version !== config.version || + typeof data.tarball !== "string" || + !/^[a-zA-Z0-9][a-zA-Z0-9._-]*\.tgz$/u.test(data.tarball) || + typeof data.sha256 !== "string" || + !/^[a-f0-9]{64}$/u.test(data.sha256) || + !/^[a-f0-9]{40}$/u.test(sourceCommit) || + data.sourceCommit !== sourceCommit + ) + throw new Error("Artifact manifest does not match the verified source, line, name or version."); + return data as unknown as PackageArtifact; +} + +export function readArtifact( + manifestPath: string, + config: ReleaseConfig, + line: ReleaseLine, + sourceCommit: string, +) { + const manifest = validateManifest( + JSON.parse(readFileSync(manifestPath, "utf8")), + config, + line, + sourceCommit, + ); + const folder = realpathSync(dirname(manifestPath)); + const tarballPath = resolve(folder, manifest.tarball); + if (!lstatSync(tarballPath).isFile() || realpathSync(tarballPath) !== tarballPath) + throw new Error("Archive must be a regular file inside the artifact directory."); + const bytes = readFileSync(tarballPath); + if (createHash("sha256").update(new Uint8Array(bytes)).digest("hex") !== manifest.sha256) + throw new Error("Archive SHA-256 does not match the tested manifest."); + const metadata = JSON.parse( + execFileSync("tar", ["-xOf", tarballPath, "package/package.json"], { + encoding: "utf8", + maxBuffer: 1024 * 1024, + }), + ); + if (metadata.name !== manifest.packageName || metadata.version !== manifest.version) + throw new Error("Archive package metadata differs from the manifest."); + return { manifest, tarballPath, bytes }; +} + +export function verifySource(root: string, tag: string, line: ReleaseLine, expected?: string) { + if (!/^opencode-v[12]\/v[0-9A-Za-z.-]+$/u.test(tag)) throw new Error("Invalid tag."); + const git = (...args: string[]) => + execFileSync("git", args, { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); + const commit = git("rev-parse", "HEAD"); + if ( + !/^[a-f0-9]{40}$/u.test(commit) || + (expected !== undefined && commit !== expected) || + git("cat-file", "-t", `refs/tags/${tag}`) !== "tag" || + git("rev-parse", `refs/tags/${tag}^{commit}`) !== commit || + git("status", "--porcelain", "--untracked-files=normal") !== "" + ) + throw new Error("Release requires a clean checkout of the exact annotated tag commit."); + const allowed = ["refs/remotes/origin/main", `refs/remotes/origin/maintenance/opencode-${line}`]; + const reachable = allowed.some((branch) => { + try { + git("merge-base", "--is-ancestor", commit, branch); + return true; + } catch { + return false; + } + }); + if (!reachable) throw new Error("Release source is not on an allowed protected branch."); + return commit; +} + +export function eventFromEnvironment(config: ReleaseConfig) { + return releaseEvent( + process.env.GITHUB_EVENT_NAME ?? "", + JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH ?? "", "utf8")), + config, + ); +} + +if (import.meta.main) { + const config = readReleaseConfig(); + const args = process.argv.slice(2); + const [command, path] = args; + if (command === "matrix" && args.length === 1) { + console.log(JSON.stringify(config.supportedLines)); + } else if (command === "audit" && path && args.length === 2) { + const folder = dirname(resolve(path)); + const manifest = JSON.parse(readFileSync(path, "utf8")); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: REPOSITORY_ROOT, + encoding: "utf8", + }).trim(); + const decision = assertAuditedArtifact( + manifest, + config, + commit, + JSON.parse(readFileSync(resolve(folder, "audit.json"), "utf8")), + JSON.parse(readFileSync(resolve(folder, "audit-context.json"), "utf8")), + record(JSON.parse(readFileSync(resolve(folder, "audit-exit.json"), "utf8"))) + .exitCode as number, + JSON.parse(readFileSync(resolve(REPOSITORY_ROOT, "security/audit-exceptions.json"), "utf8")), + ); + console.log( + JSON.stringify({ + status: decision.status, + rawAffectedPackages: decision.rawAffectedPackages, + rawAdvisories: decision.rawAdvisories, + acceptedRoutes: decision.accepted.length, + }), + ); + } else if (command === "authorize" && args.length === 1) { + assertPublicationAllowed(config, eventFromEnvironment(config)); + } else if (command === "source" && args.length === 1) { + const release = eventFromEnvironment(config); + const sourceCommit = verifySource(REPOSITORY_ROOT, release.tag, release.line); + const output = process.env.GITHUB_OUTPUT; + if (!output) throw new Error("GITHUB_OUTPUT is required."); + appendFileSync( + output, + `line=${release.line}\nsourceCommit=${sourceCommit}\nenvironment=npm-${release.line}\n`, + ); + } else { + throw new Error("Usage: policy.ts matrix | source | authorize | audit "); + } +} diff --git a/scripts/release/publication.test.ts b/scripts/release/publication.test.ts new file mode 100644 index 0000000..a4ed78e --- /dev/null +++ b/scripts/release/publication.test.ts @@ -0,0 +1,596 @@ +import { expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { type PackageArtifact, parseReleaseConfig, readReleaseConfig } from "./config"; +import { + type PublicationIO, + assertTrustedPublishingVersions, + compareReleaseVersions, + npmEnvironment, + publishRelease, + trustedRuntimePaths, + versionAtLeast, +} from "./publication"; + +test("channel ordering follows supported SemVer, including arbitrarily large numeric prereleases", () => { + const ordered = [ + "1.0.0-alpha", + "1.0.0-alpha.1", + "1.0.0-alpha.beta", + "1.0.0-beta", + "1.0.0-beta.2", + "1.0.0-beta.10", + "1.0.0-beta.a", + "1.0.0-rc.900719925474099200", + "1.0.0-rc.900719925474099201", + "1.0.0", + "1.0.1-alpha", + "1.0.1", + "1.1.0", + "2.0.0", + ]; + for (const [leftIndex, left] of ordered.entries()) { + for (const [rightIndex, right] of ordered.entries()) { + const expected = leftIndex === rightIndex ? 0 : leftIndex < rightIndex ? -1 : 1; + expect(compareReleaseVersions(left, right)).toBe(expected); + } + } + for (const bad of [ + "1.0", + "01.0.0", + "1.0.0+build", + "1.0.0-beta.01", + "9007199254740992.0.0", + "1.0.0\n", + ]) + expect(() => compareReleaseVersions("1.0.0", bad)).toThrow("Unsupported"); +}); + +test("trusted publishing version minima compare numeric stable semver", () => { + for (const [node, npm] of [ + ["v22.14.0", "11.5.1"], + ["24.1.0", "11.10.0"], + ["24.0.0", "12.0.0"], + ]) + expect(() => assertTrustedPublishingVersions(node ?? "", npm ?? "")).not.toThrow(); + for (const [node, npm] of [ + ["22.13.9", "12.2.0"], + ["21.99.99", "12.2.0"], + ["24.0.0", "11.5.0"], + ["24.0.0", "10.99.99"], + ["24.0.0-rc.1", "12.2.0"], + ["24.0.0", "11.5.1-beta.1"], + ]) + expect(() => assertTrustedPublishingVersions(node ?? "", npm ?? "")).toThrow(); + expect(versionAtLeast("11.10.0", [11, 5, 1])).toBe(true); + for (const bad of [ + "11.5", + "011.5.1", + "11.5.1;id", + "11.5.1\n", + "11.5.1+build", + "9007199254740992.0.0", + ]) + expect(versionAtLeast(bad, [11, 5, 1])).toBe(false); +}); + +test("runtime paths are confined to the official Node tool cache, never downloaded tools", () => { + const cache = "/opt/hostedtoolcache"; + const node = `${cache}/node/24.1.0/x64/bin/node`; + expect(trustedRuntimePaths(cache, node)).toEqual({ + node, + npmCli: `${cache}/node/24.1.0/x64/lib/node_modules/npm/bin/npm-cli.js`, + }); + for (const bad of [ + "/workspace/release-artifacts/node", + "/workspace/node_modules/.bin/node", + `${cache}/node/24.1.0/x64/bin/../bin/node`, + `${cache}/../untrusted/node`, + `${cache}/node/24.1.0/x64/lib/node_modules/npm/bin/npm-cli.js`, + `${cache}/node/24.1.0-rc.1/x64/bin/node`, + `${cache}-other/node/24.1.0/x64/bin/node`, + "node", + ]) + expect(() => trustedRuntimePaths(cache, bad)).toThrow("tool cache"); + expect(() => trustedRuntimePaths("", node)).toThrow(); +}); + +test("version probes have no ambient authority; only trusted publication gets OIDC", () => { + const source = { + GH_TOKEN: "github-secret", + GITHUB_TOKEN: "another-secret", + NPM_TOKEN: "npm-secret", + NODE_AUTH_TOKEN: "npm-auth", + NODE_OPTIONS: "--require=untrusted", + NODE_PATH: "/untrusted", + PATH: "/workspace/node_modules/.bin", + npm_config_userconfig: "/untrusted/.npmrc", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://oidc.invalid", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "oidc-secret", + GITHUB_REPOSITORY: "atacama-dev/opencode-agentbus", + GITHUB_ACTIONS: "true", + }; + for (const publish of [false, true]) { + const env = npmEnvironment( + source, + "/opt/hostedtoolcache/node/24.1.0/x64/bin/node", + "/isolated", + publish, + ); + for (const key of [ + "GH_TOKEN", + "GITHUB_TOKEN", + "NPM_TOKEN", + "NODE_AUTH_TOKEN", + "NODE_OPTIONS", + "NODE_PATH", + "npm_config_userconfig", + ]) + expect(env[key]).toBeUndefined(); + expect(env.PATH).toBe("/opt/hostedtoolcache/node/24.1.0/x64/bin:/usr/bin:/bin"); + expect(env.HOME).toBe("/isolated"); + expect(env.GITHUB_REPOSITORY).toBe(source.GITHUB_REPOSITORY); + if (publish) { + expect(env.ACTIONS_ID_TOKEN_REQUEST_TOKEN).toBe(source.ACTIONS_ID_TOKEN_REQUEST_TOKEN); + expect(env.ACTIONS_ID_TOKEN_REQUEST_URL).toBe(source.ACTIONS_ID_TOKEN_REQUEST_URL); + } else { + expect(env.ACTIONS_ID_TOKEN_REQUEST_TOKEN).toBeUndefined(); + expect(env.ACTIONS_ID_TOKEN_REQUEST_URL).toBeUndefined(); + } + } +}); + +function fixture(version = "0.1.0", line: "v1" | "v2" = "v2") { + const config = parseReleaseConfig({ + ...readReleaseConfig(), + releaseLine: line, + version, + supportedLines: ["v1", "v2"], + readiness: { v1: true, v2: true }, + publishEnabled: true, + }); + const bytes = new TextEncoder().encode("exact tested archive bytes"); + const sourceCommit = "a".repeat(40); + const manifest: PackageArtifact = { + schemaVersion: 1, + line, + packageName: config.packageNames[line], + version: config.version, + tarball: "agentbus.tgz", + sourceCommit, + sha256: createHash("sha256").update(bytes).digest("hex"), + }; + const event = { + action: "published", + repository: { full_name: "atacama-dev/opencode-agentbus", private: false }, + release: { + id: 7, + tag_name: `opencode-${line}/v${version}`, + draft: false, + prerelease: version.includes("-"), + }, + }; + const audit = { + auditReportVersion: 2, + vulnerabilities: {}, + metadata: { + dependencies: { prod: 3 }, + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: 0 }, + }, + }; + const input = { config, event, eventName: "release", manifest, bytes, sourceCommit, audit }; + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + const state = { + npm: undefined as string | undefined, + publishCalls: [] as string[][], + writes: [] as string[], + reads: [] as string[], + assets: new Map(), + failUpload: false, + failPublish: false, + privateRepository: false, + movedTag: false, + moveAfterPrecheck: false, + badRegistry: false, + protectedBranch: true, + ancestor: true, + registryName: manifest.packageName, + channel: undefined as unknown, + channelStatus: undefined as number | undefined, + malformedChannel: false, + channelReads: 0, + effects: [] as string[], + }; + const response = (value: unknown, status = 200) => Response.json(value, { status }); + const io: PublicationIO = { + github: async (url, init) => { + if (init?.method === "POST") { + state.writes.push(url); + if (state.failUpload) { + state.failUpload = false; + return response({}, 500); + } + const name = new URL(url).searchParams.get("name"); + if (!name || !(init.body instanceof Blob)) throw new Error("Bad test upload"); + state.assets.set(name, new Uint8Array(await init.body.arrayBuffer())); + return response({ id: 1 }, 201); + } + state.reads.push(url); + state.effects.push("github"); + if (url.endsWith("/opencode-agentbus")) + return response({ ...event.repository, private: state.privateRepository }); + if (url.endsWith("/releases/7")) return response(event.release); + if (url.includes("/git/ref/tags/")) + return response({ object: { type: "tag", sha: "b".repeat(40) } }); + if (url.includes("/git/tags/")) + return response({ + tag: event.release.tag_name, + object: { + type: "commit", + sha: state.movedTag ? "c".repeat(40) : sourceCommit, + }, + }); + if (url.includes("/branches/")) + return response({ + name: decodeURIComponent(url.split("/").at(-1) ?? ""), + protected: state.protectedBranch, + commit: { sha: sourceCommit }, + }); + if (url.includes("/compare/")) + return response({ + status: state.ancestor ? "identical" : "diverged", + merge_base_commit: { sha: state.ancestor ? sourceCommit : "d".repeat(40) }, + }); + if (url.includes("/releases/7/assets?")) + return response([...state.assets.keys()].map((name, index) => ({ name, id: index + 1 }))); + if (url.includes("/releases/assets/")) { + const index = Number(url.split("/").at(-1)) - 1; + return new Response([...state.assets.values()][index]); + } + throw new Error(`Unexpected fixture request ${url}`); + }, + registry: async (url) => { + const packageUrl = `https://registry.npmjs.org/${encodeURIComponent(manifest.packageName)}`; + if (url === `${packageUrl}/${version.includes("-") ? "next" : "latest"}`) { + state.channelReads++; + state.effects.push("channel"); + if (state.malformedChannel) return new Response("not JSON", { status: 200 }); + return response( + state.channel ?? {}, + state.channelStatus ?? (state.channel === undefined ? 404 : 200), + ); + } + expect(url).toBe(`${packageUrl}/${manifest.version}`); + state.effects.push("version"); + if (state.moveAfterPrecheck) state.movedTag = true; + if (state.badRegistry) return response({}, 503); + return state.npm === undefined + ? response({}, 404) + : response({ + name: state.registryName, + version: manifest.version, + dist: { integrity: state.npm }, + }); + }, + publish: async (args) => { + state.effects.push("publish"); + state.publishCalls.push([...args]); + if (state.failPublish) throw new Error("simulated npm failure"); + state.npm = integrity; + state.channel = { name: manifest.packageName, version: manifest.version }; + }, + }; + return { input, state, io, integrity }; +} + +test("publication uses exact tgz, OIDC-compatible CLI flags and existing release only", async () => { + const { input, state, io } = fixture(); + expect(await publishRelease(input, io)).toEqual({ alreadyPublished: false, uploadedAssets: 4 }); + expect(state.publishCalls).toHaveLength(1); + expect(state.channelReads).toBe(1); // Missing channel (404) permits a first publication. + expect(state.publishCalls[0]).toEqual([ + "publish", + "agentbus.tgz", + "--ignore-scripts", + "--access", + "public", + "--tag", + "latest", + "--provenance", + "--registry=https://registry.npmjs.org", + "--userconfig=/dev/null", + "--globalconfig=/dev/null", + ]); + expect([...state.assets.keys()]).toEqual([ + "agentbus.tgz", + "manifest.json", + "audit.json", + "SHA256SUMS", + ]); + expect(state.assets.get("agentbus.tgz")).toEqual(input.bytes); + expect( + state.writes.every((url) => + url.startsWith( + "https://uploads.github.com/repos/atacama-dev/opencode-agentbus/releases/7/assets?name=", + ), + ), + ).toBe(true); +}); + +test("an identical immutable npm version is skipped without moving old latest", async () => { + const { input, state, io, integrity } = fixture(); + state.npm = integrity; + state.channel = { name: input.manifest.packageName, version: "2.0.0" }; + state.channelStatus = 503; // Asset-only retries do not even need to read the channel. + expect(await publishRelease(input, io)).toMatchObject({ alreadyPublished: true }); + expect(state.publishCalls).toHaveLength(0); + expect(state.channelReads).toBe(0); +}); + +test("absent older or inconsistently equal versions cannot roll back latest or next", async () => { + for (const [candidate, current] of [ + ["0.1.0", "0.2.0"], + ["0.1.0", "0.1.0"], + ["0.1.0-beta.2", "0.1.0-beta.10"], + ["0.1.0-rc.1", "0.1.0"], + ["0.1.0-beta.900719925474099200", "0.1.0-beta.900719925474099201"], + ]) { + const { input, state, io } = fixture(candidate); + state.channel = { name: input.manifest.packageName, version: current }; + await expect(publishRelease(input, io)).rejects.toThrow("would not advance"); + expect(state.npm).toBeUndefined(); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + expect(state.channelReads).toBe(1); + } +}); + +test("newer versions advance the channel only after live verification and an adjacent channel read", async () => { + for (const [candidate, current] of [ + ["0.2.0", "0.1.0"], + ["0.1.0", "0.1.0-rc.1"], + ["0.1.0-beta.10", "0.1.0-beta.2"], + ["0.2.0-alpha", "0.1.0"], + ]) { + const { input, state, io } = fixture(candidate); + state.channel = { name: input.manifest.packageName, version: current }; + await publishRelease(input, io); + expect(state.publishCalls).toHaveLength(1); + const publicationIndex = state.effects.indexOf("publish"); + expect(state.effects.slice(publicationIndex - 2, publicationIndex + 1)).toEqual([ + "github", + "channel", + "publish", + ]); + expect( + state.effects.slice(state.effects.indexOf("version") + 1, publicationIndex - 1), + ).toContain("github"); + } +}); + +test("channel read errors and unsupported or mismatched metadata block all writes", async () => { + for (const bad of [ + { name: "@wrong/package", version: "0.0.1" }, + { name: "@atacama-dev/opencode-agentbus-v2", version: "0.0.1+build" }, + { name: "@atacama-dev/opencode-agentbus-v2", version: "0.0.1-beta.01" }, + { name: "@atacama-dev/opencode-agentbus-v2", version: 1 }, + {}, + [], + "unexpected JSON", + ]) { + const { input, state, io } = fixture(); + state.channel = bad; + await expect(publishRelease(input, io)).rejects.toThrow(); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + } + for (const reason of ["unavailable", "forbidden", "malformed"]) { + const { input, state, io } = fixture(); + state.channelStatus = reason === "forbidden" ? 403 : 503; + state.malformedChannel = reason === "malformed"; + await expect(publishRelease(input, io)).rejects.toThrow(); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + } +}); + +test("prereleases publish exclusively to next, never latest", async () => { + const { input, state, io } = fixture("0.1.0-rc.1"); + await publishRelease(input, io); + expect(state.publishCalls[0]?.slice(5, 7)).toEqual(["--tag", "next"]); + expect(state.publishCalls[0]).not.toContain("latest"); +}); + +test("wrong npm integrity or identity and unavailable registry block all writes", async () => { + for (const reason of ["integrity", "identity", "unavailable"]) { + const { input, state, io, integrity } = fixture(); + state.npm = reason === "integrity" ? "sha512-different" : integrity; + if (reason === "identity") state.registryName = "@wrong/name"; + if (reason === "unavailable") state.badRegistry = true; + await expect(publishRelease(input, io)).rejects.toThrow(); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + } +}); + +test("npm success and asset failure retry reuses bytes and never republishes", async () => { + const { input, state, io } = fixture(); + state.failUpload = true; + await expect(publishRelease(input, io)).rejects.toThrow("retry this job"); + expect(state.publishCalls).toHaveLength(1); + expect(await publishRelease(input, io)).toEqual({ alreadyPublished: true, uploadedAssets: 4 }); + expect(state.publishCalls).toHaveLength(1); + expect(await publishRelease(input, io)).toEqual({ alreadyPublished: true, uploadedAssets: 0 }); + expect(state.publishCalls).toHaveLength(1); +}); + +test("different existing GitHub asset fails before npm, without clobber", async () => { + const { input, state, io } = fixture(); + state.assets.set("agentbus.tgz", new TextEncoder().encode("different archive")); + await expect(publishRelease(input, io)).rejects.toThrow("differs"); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); +}); + +test("npm failure cannot attach release assets", async () => { + const { input, state, io } = fixture(); + state.failPublish = true; + await expect(publishRelease(input, io)).rejects.toThrow("simulated npm failure"); + expect(state.writes).toHaveLength(0); +}); + +test("tag movement, including after registry precheck, blocks writes", async () => { + for (const afterPrecheck of [false, true]) { + const { input, state, io } = fixture(); + state.movedTag = !afterPrecheck; + state.moveAfterPrecheck = afterPrecheck; + await expect(publishRelease(input, io)).rejects.toThrow("verified source commit"); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + } +}); + +test("live private repository blocks writes even with a stale public event", async () => { + const { input, state, io } = fixture(); + state.privateRepository = true; + await expect(publishRelease(input, io)).rejects.toThrow("canonical and public"); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); +}); + +test("live protected branch ancestry is required even after local source proof", async () => { + for (const reason of ["unprotected", "diverged"]) { + const { input, state, io } = fixture(); + if (reason === "unprotected") state.protectedBranch = false; + if (reason === "diverged") state.ancestor = false; + await expect(publishRelease(input, io)).rejects.toThrow("allowed protected branch"); + expect(state.publishCalls).toHaveLength(0); + expect(state.writes).toHaveLength(0); + } +}); + +test("readiness, disabled publication, audit findings and digest corruption stop before external access", async () => { + for (const reason of ["readiness", "disabled", "audit", "digest", "source", "fork"]) { + const { input, state, io } = fixture(); + if (reason === "readiness") + input.config = { ...input.config, readiness: { v1: true, v2: false } }; + if (reason === "disabled") input.config = { ...input.config, publishEnabled: false }; + if (reason === "audit") input.audit.metadata.vulnerabilities.high = 1; + if (reason === "digest") input.bytes = new TextEncoder().encode("corrupt archive"); + if (reason === "source") input.sourceCommit = "d".repeat(40); + if (reason === "fork") input.event.repository.full_name = "fork/opencode-agentbus"; + await expect(publishRelease(input, io)).rejects.toThrow(); + expect(state.reads).toHaveLength(0); + expect(state.writes).toHaveLength(0); + expect(state.publishCalls).toHaveLength(0); + } +}); + +function temporaryRiskFixture() { + const { input, state, io } = fixture("0.1.0", "v1"); + const name = "zod"; + const chain = ["@opencode-ai/plugin@1.18.19", "zod@4.1.8"]; + const manifest = input.manifest; + const identity = { + line: manifest.line, + packageName: manifest.packageName, + version: manifest.version, + sha256: manifest.sha256, + sourceCommit: manifest.sourceCommit, + }; + const report = { + auditReportVersion: 2, + vulnerabilities: { + zod: { + name, + severity: "high", + via: [ + { + url: "https://github.com/advisories/GHSA-mrhx-c7xc-m3w5", + name, + dependency: name, + severity: "high", + range: "<4.6.6", + }, + ], + nodes: ["node_modules/zod"], + }, + }, + metadata: { + dependencies: { prod: 2 }, + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 1, critical: 0, total: 1 }, + }, + }; + const auditContext = { + schemaVersion: 1 as const, + profile: "production" as const, + sourceCommit: input.sourceCommit, + manifest: identity, + nodes: [{ path: "node_modules/zod", name, version: "4.1.8", chains: [chain] }], + }; + return { input: { ...input, audit: report, auditContext, auditExit: 1 }, state, io }; +} + +test("an expired temporary exception blocks publication before any network or registry access", async () => { + const { input, state, io } = temporaryRiskFixture(); + const originalDate = globalThis.Date; + globalThis.Date = class extends originalDate { + constructor(value?: string | number) { + super(value ?? "2026-12-16T00:00:00.000Z"); + } + } as DateConstructor; + try { + await expect(publishRelease(input, io)).rejects.toThrow("date"); + } finally { + globalThis.Date = originalDate; + } + expect(state.reads).toHaveLength(0); + expect(state.writes).toHaveLength(0); + expect(state.publishCalls).toHaveLength(0); +}); + +test("temporary risk acceptance is rechecked at every publication write boundary", async () => { + const OriginalDate = globalThis.Date; + let clock = "2026-12-14T23:59:59.999Z"; + globalThis.Date = class extends OriginalDate { + constructor(value?: string | number) { + super(value ?? clock); + } + } as DateConstructor; + try { + for (const boundary of ["none", "npm", "first-asset", "next-asset"]) { + clock = "2026-12-14T23:59:59.999Z"; + const { input, state, io } = temporaryRiskFixture(); + const wrapped: PublicationIO = { + ...io, + registry: async (url) => { + const response = await io.registry(url); + if (boundary === "npm" && url.endsWith("/latest")) clock = "2026-12-15T00:00:00Z"; + return response; + }, + publish: async (args) => { + await io.publish(args); + if (boundary === "first-asset") clock = "2026-12-15T00:00:00Z"; + }, + github: async (url, init) => { + const response = await io.github(url, init); + if (boundary === "next-asset" && init?.method === "POST") clock = "2026-12-15T00:00:00Z"; + return response; + }, + }; + if (boundary === "none") { + expect(await publishRelease(input, wrapped)).toEqual({ + alreadyPublished: false, + uploadedAssets: 7, + }); + } else { + await expect(publishRelease(input, wrapped)).rejects.toThrow("date"); + } + expect(state.publishCalls).toHaveLength(boundary === "npm" ? 0 : 1); + expect(state.writes).toHaveLength( + boundary === "none" ? 7 : boundary === "next-asset" ? 1 : 0, + ); + } + } finally { + globalThis.Date = OriginalDate; + } +}); diff --git a/scripts/release/publication.ts b/scripts/release/publication.ts new file mode 100644 index 0000000..8c56a9b --- /dev/null +++ b/scripts/release/publication.ts @@ -0,0 +1,475 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { lstatSync, mkdtempSync, readFileSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, isAbsolute, join, relative, resolve } from "node:path"; +import { + type PackageArtifact, + REPOSITORY_ROOT, + type ReleaseConfig, + isReleaseVersion, + readReleaseConfig, +} from "./config"; +import { + RELEASE_REPOSITORY, + assertCleanAudit, + assertAuditedArtifact, + assertPublicationAllowed, + eventFromEnvironment, + readArtifact, + record, + releaseEvent, + validateManifest, + verifySource, +} from "./policy"; +import type { AuditContext } from "../security/audit"; + +interface PublicationInput { + config: ReleaseConfig; + event: unknown; + eventName: string; + manifest: PackageArtifact; + bytes: Uint8Array; + audit: unknown; + auditContext?: AuditContext; + auditExit?: number; + sourceCommit: string; +} + +export interface PublicationIO { + github(url: string, init?: RequestInit): Promise; + registry(url: string): Promise; + publish(args: readonly string[]): Promise; +} + +const API = `https://api.github.com/repos/${RELEASE_REPOSITORY}`; +const UPLOADS = `https://uploads.github.com/repos/${RELEASE_REPOSITORY}`; + +export function compareReleaseVersions(left: string, right: string): -1 | 0 | 1 { + if (!isReleaseVersion(left) || !isReleaseVersion(right)) + throw new Error("Unsupported release version in npm channel metadata."); + const parts = (version: string) => { + const separator = version.indexOf("-"); + return { + core: (separator < 0 ? version : version.slice(0, separator)).split("."), + prerelease: separator < 0 ? undefined : version.slice(separator + 1).split("."), + }; + }; + const compareParts = (a: string[], b: string[]): -1 | 0 | 1 => { + for (let index = 0; index < Math.max(a.length, b.length); index++) { + const first = a[index]; + const second = b[index]; + if (first === undefined) return -1; + if (second === undefined) return 1; + if (first === second) continue; + const numericFirst = /^[0-9]+$/u.test(first); + const numericSecond = /^[0-9]+$/u.test(second); + if (numericFirst && numericSecond) return BigInt(first) < BigInt(second) ? -1 : 1; + if (numericFirst !== numericSecond) return numericFirst ? -1 : 1; + return first < second ? -1 : 1; + } + return 0; + }; + const a = parts(left); + const b = parts(right); + const core = compareParts(a.core, b.core); + if (core !== 0) return core; + if (!a.prerelease) return b.prerelease ? 1 : 0; + if (!b.prerelease) return -1; + return compareParts(a.prerelease, b.prerelease); +} + +export function versionAtLeast(value: string, minimum: readonly [number, number, number]) { + const match = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/u.exec(value); + if (!match) return false; + const parts = match.slice(1).map(Number); + if (parts.some((part) => !Number.isSafeInteger(part))) return false; + for (let index = 0; index < 3; index++) { + if (parts[index] !== minimum[index]) return (parts[index] ?? -1) > (minimum[index] ?? 0); + } + return true; +} + +export function assertTrustedPublishingVersions(node: string, npm: string) { + if (!versionAtLeast(node, [22, 14, 0]) || !versionAtLeast(npm, [11, 5, 1])) + throw new Error("Trusted publication requires stable Node >=22.14.0 and npm >=11.5.1."); +} + +/** Only the official setup-node tool-cache layout is executable, never a build artifact. */ +export function trustedRuntimePaths(toolCache: string, node: string) { + if ( + !isAbsolute(toolCache) || + resolve(toolCache) !== toolCache || + !isAbsolute(node) || + resolve(node) !== node || + !/^node\/(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\/x64\/bin\/node$/u.test( + relative(toolCache, node), + ) + ) + throw new Error("Publication runtime must come from the official setup-node tool cache."); + return { node, npmCli: join(dirname(node), "../lib/node_modules/npm/bin/npm-cli.js") }; +} + +/** Version probes get no credentials; only the real publish receives short-lived OIDC authority. */ +export function npmEnvironment( + source: NodeJS.ProcessEnv, + node: string, + cwd: string, + publish: boolean, +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + PATH: `${dirname(node)}:/usr/bin:/bin`, + HOME: cwd, + npm_config_cache: join(cwd, ".npm-cache"), + CI: "true", + }; + for (const key of [ + "GITHUB_ACTIONS", + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_WORKFLOW_REF", + "GITHUB_WORKFLOW_SHA", + "GITHUB_WORKFLOW", + "GITHUB_JOB", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "GITHUB_SHA", + "GITHUB_REF", + "GITHUB_EVENT_NAME", + "RUNNER_ENVIRONMENT", + ...(publish ? ["ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"] : []), + ]) { + if (source[key] !== undefined) env[key] = source[key]; + } + return env; +} + +function sha256(bytes: Uint8Array) { + return createHash("sha256").update(bytes).digest("hex"); +} + +async function json(response: Response) { + if (!response.ok) throw new Error(`Release API request failed (HTTP ${response.status}).`); + return record(await response.json()); +} + +function id(value: unknown): number { + if (!Number.isSafeInteger(value) || (value as number) <= 0) + throw new Error("Invalid GitHub resource ID."); + return value as number; +} + +/** All external effects are injectable; tests never invoke npm or GitHub writes. */ +export async function publishRelease(input: PublicationInput, io: PublicationIO) { + const release = releaseEvent(input.eventName, input.event, input.config); + assertPublicationAllowed(input.config, release); + const verifyAudit = () => { + if (input.auditContext !== undefined) + return assertAuditedArtifact( + input.manifest, + input.config, + input.sourceCommit, + input.audit, + input.auditContext, + input.auditExit as number, + JSON.parse(readFileSync(join(REPOSITORY_ROOT, "security/audit-exceptions.json"), "utf8")), + ); + assertCleanAudit(input.audit); + }; + const auditDecision = verifyAudit(); + const manifest = validateManifest(input.manifest, input.config, release.line, input.sourceCommit); + if (sha256(input.bytes) !== manifest.sha256) throw new Error("Archive digest mismatch."); + const integrity = `sha512-${createHash("sha512").update(input.bytes).digest("base64")}`; + const assets = [ + { name: manifest.tarball, bytes: input.bytes, contentType: "application/octet-stream" }, + { + name: "manifest.json", + bytes: new TextEncoder().encode(`${JSON.stringify(manifest, null, 2)}\n`), + contentType: "application/json", + }, + { + name: "audit.json", + bytes: new TextEncoder().encode(`${JSON.stringify(input.audit, null, 2)}\n`), + contentType: "application/json", + }, + { + name: "SHA256SUMS", + bytes: new TextEncoder().encode(`${manifest.sha256} ${manifest.tarball}\n`), + contentType: "text/plain", + }, + ]; + if (input.auditContext !== undefined && auditDecision !== undefined) { + for (const [name, value] of [ + ["audit-context.json", input.auditContext], + ["audit-exit.json", { exitCode: input.auditExit }], + ["audit-decision.json", auditDecision], + ] as const) + assets.push({ + name, + bytes: new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`), + contentType: "application/json", + }); + } + + const verifyLive = async () => { + const repository = await json(await io.github(API)); + if (repository.full_name !== RELEASE_REPOSITORY || repository.private !== false) + throw new Error("Live repository must be canonical and public before any release write."); + const current = await json(await io.github(`${API}/releases/${release.releaseId}`)); + const live = releaseEvent( + "release", + { action: "published", repository, release: current }, + input.config, + ); + if (live.releaseId !== release.releaseId || live.tag !== release.tag) + throw new Error("Published release identity changed."); + const reference = await json( + await io.github(`${API}/git/ref/tags/${encodeURIComponent(release.tag)}`), + ); + const tagObject = record(reference.object); + if (tagObject.type !== "tag" || !/^[a-f0-9]{40}$/u.test(String(tagObject.sha))) + throw new Error("Release reference must still be an annotated tag."); + const tag = await json(await io.github(`${API}/git/tags/${tagObject.sha}`)); + const target = record(tag.object); + if (tag.tag !== release.tag || target.type !== "commit" || target.sha !== input.sourceCommit) + throw new Error("Annotated release tag no longer points to the verified source commit."); + let protectedAncestor = false; + for (const name of ["main", `maintenance/opencode-${release.line}`]) { + const response = await io.github(`${API}/branches/${encodeURIComponent(name)}`); + if (response.status === 404) continue; + const branch = await json(response); + if (branch.name !== name || branch.protected !== true) continue; + const tip = record(branch.commit).sha; + if (typeof tip !== "string" || !/^[a-f0-9]{40}$/u.test(tip)) + throw new Error("Invalid protected branch commit."); + const comparison = await json( + await io.github(`${API}/compare/${input.sourceCommit}...${tip}`), + ); + if ( + ["ahead", "identical"].includes(String(comparison.status)) && + record(comparison.merge_base_commit).sha === input.sourceCommit + ) { + protectedAncestor = true; + break; + } + } + if (!protectedAncestor) + throw new Error("Live source ancestry on an allowed protected branch is required."); + }; + await verifyLive(); + + // Preflight *all* existing assets before the first immutable npm write. + const existing: Record = {}; + for (let page = 1; ; page++) { + if (page > 10) throw new Error("Too many release assets; manual inspection required."); + const response = await io.github( + `${API}/releases/${release.releaseId}/assets?per_page=100&page=${page}`, + ); + if (!response.ok) throw new Error("Cannot list existing release assets."); + const rows: unknown = await response.json(); + if (!Array.isArray(rows)) throw new Error("Malformed release asset list."); + for (const value of rows) { + const asset = record(value); + if (typeof asset.name !== "string") throw new Error("Malformed release asset name."); + if (!assets.some((item) => item.name === asset.name)) continue; + if (Object.hasOwn(existing, asset.name)) throw new Error("Duplicate release asset name."); + existing[asset.name] = id(asset.id); + } + if (rows.length < 100) break; + } + for (const asset of assets) { + if (!Object.hasOwn(existing, asset.name)) continue; + const response = await io.github(`${API}/releases/assets/${existing[asset.name]}`, { + headers: { Accept: "application/octet-stream" }, + }); + if ( + !response.ok || + sha256(new Uint8Array(await response.arrayBuffer())) !== sha256(asset.bytes) + ) + throw new Error( + "Existing release asset differs; never overwrite an immutable release asset.", + ); + } + + const version = await io.registry( + `https://registry.npmjs.org/${encodeURIComponent(manifest.packageName)}/${encodeURIComponent(manifest.version)}`, + ); + let alreadyPublished = false; + if (version.status === 200) { + const entry = await json(version); + if ( + entry.name !== manifest.packageName || + entry.version !== manifest.version || + record(entry.dist).integrity !== integrity + ) + throw new Error( + "npm version already exists with different integrity; operator intervention required.", + ); + alreadyPublished = true; + } else if (version.status !== 404) { + throw new Error("Unable to establish npm name/version state; refusing publication."); + } + if (!alreadyPublished) { + await verifyLive(); + // The per-line workflow lock serializes our publishers, not external npm administrators. + // Keep this channel read immediately adjacent to publish; npm offers no registry CAS. + const channel = await io.registry( + `https://registry.npmjs.org/${encodeURIComponent(manifest.packageName)}/${release.npmTag}`, + ); + if (channel.status === 200) { + const current = await json(channel); + if ( + current.name !== manifest.packageName || + !isReleaseVersion(current.version) || + compareReleaseVersions(manifest.version, current.version) <= 0 + ) + throw new Error( + "npm channel identity/version is invalid or publication would not advance it.", + ); + } else if (channel.status !== 404) { + throw new Error("Unable to establish the current npm channel; refusing publication."); + } + verifyAudit(); + await io.publish([ + "publish", + manifest.tarball, + "--ignore-scripts", + "--access", + "public", + "--tag", + release.npmTag, + "--provenance", + "--registry=https://registry.npmjs.org", + "--userconfig=/dev/null", + "--globalconfig=/dev/null", + ]); + const published = await json( + await io.registry( + `https://registry.npmjs.org/${encodeURIComponent(manifest.packageName)}/${encodeURIComponent(manifest.version)}`, + ), + ); + if ( + published.name !== manifest.packageName || + published.version !== manifest.version || + record(published.dist).integrity !== integrity + ) + throw new Error( + "Published npm integrity did not match the tested archive; stop and investigate.", + ); + } + // A retry after npm success only attaches missing matching assets; it never moves old dist-tags. + for (const asset of assets) { + if (Object.hasOwn(existing, asset.name)) continue; + await verifyLive(); + verifyAudit(); + const response = await io.github( + `${UPLOADS}/releases/${release.releaseId}/assets?name=${encodeURIComponent(asset.name)}`, + { + method: "POST", + headers: { "Content-Type": asset.contentType }, + body: new Blob([asset.bytes]), + }, + ); + if (!response.ok) + throw new Error("Release asset upload failed; retry this job with the same tested artifact."); + } + return { + alreadyPublished, + uploadedAssets: assets.filter((asset) => !Object.hasOwn(existing, asset.name)).length, + }; +} + +if (import.meta.main) { + const [flag, manifestPath] = process.argv.slice(2); + if (flag !== "--manifest" || !manifestPath || process.argv.length !== 4) + throw new Error("Usage: publication.ts --manifest "); + const config = readReleaseConfig(); + const release = eventFromEnvironment(config); + assertPublicationAllowed(config, release); + const expectedCommit = process.env.RELEASE_SOURCE_COMMIT; + if (!expectedCommit || !/^[a-f0-9]{40}$/u.test(expectedCommit)) + throw new Error("The verified source job's exact commit is required."); + const sourceCommit = verifySource(REPOSITORY_ROOT, release.tag, release.line, expectedCommit); + const artifact = readArtifact(resolve(manifestPath), config, release.line, sourceCommit); + const audit = JSON.parse( + readFileSync(join(dirname(resolve(manifestPath)), "audit.json"), "utf8"), + ); + const auditContext = JSON.parse( + readFileSync(join(dirname(resolve(manifestPath)), "audit-context.json"), "utf8"), + ); + const auditExit = record( + JSON.parse(readFileSync(join(dirname(resolve(manifestPath)), "audit-exit.json"), "utf8")), + ).exitCode as number; + const token = process.env.GH_TOKEN; + if (!token || process.env.NPM_TOKEN || process.env.NODE_AUTH_TOKEN) + throw new Error("GitHub token required; long-lived npm tokens are forbidden."); + const tools = trustedRuntimePaths( + process.env.RUNNER_TOOL_CACHE ?? "", + process.env.RELEASE_NODE_BINARY ?? "", + ); + for (const path of [tools.node, tools.npmCli]) { + if (!lstatSync(path).isFile() || realpathSync(path) !== path) + throw new Error("Trusted Node/npm files must be regular, canonical tool-cache files."); + } + const cwd = mkdtempSync(join(process.env.RUNNER_TEMP ?? tmpdir(), "agentbus-publish-")); + const probeOptions = { + cwd, + env: npmEnvironment(process.env, tools.node, cwd, false), + encoding: "utf8" as const, + stdio: ["ignore", "pipe", "ignore"] as ["ignore", "pipe", "ignore"], + }; + assertTrustedPublishingVersions( + execFileSync(tools.node, ["--version"], probeOptions).trim(), + execFileSync( + tools.node, + [tools.npmCli, "--version", "--userconfig=/dev/null", "--globalconfig=/dev/null"], + probeOptions, + ).trim(), + ); + await publishRelease( + { + config, + event: JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH ?? "", "utf8")), + eventName: process.env.GITHUB_EVENT_NAME ?? "", + manifest: artifact.manifest, + bytes: new Uint8Array(artifact.bytes), + sourceCommit, + audit, + auditContext, + auditExit, + }, + { + github: (url, init) => { + if (!url.startsWith(`${API}/`) && url !== API && !url.startsWith(`${UPLOADS}/`)) + throw new Error("Unexpected GitHub endpoint."); + const headers = new Headers(init?.headers); + headers.set("Authorization", `Bearer ${token}`); + if (!headers.has("Accept")) headers.set("Accept", "application/vnd.github+json"); + headers.set("X-GitHub-Api-Version", "2022-11-28"); + return fetch(url, { ...init, headers }); + }, + registry: (url) => { + if (!url.startsWith("https://registry.npmjs.org/")) throw new Error("Unexpected registry."); + return fetch(url, { redirect: "error" }); + }, + publish: async (args) => { + const absolute = [...args]; + absolute[1] = artifact.tarballPath; + try { + execFileSync(tools.node, [tools.npmCli, ...absolute], { + cwd, + stdio: "ignore", + env: npmEnvironment(process.env, tools.node, cwd, true), + }); + } catch { + throw new Error( + "npm trusted publication failed; retry the same archive after checking registry state.", + ); + } + }, + }, + ); +} diff --git a/scripts/release/smoke.test.ts b/scripts/release/smoke.test.ts new file mode 100644 index 0000000..9d2162d --- /dev/null +++ b/scripts/release/smoke.test.ts @@ -0,0 +1,68 @@ +import { expect, test } from "bun:test"; +import { parseArtifact, validateArchiveNames, validateAuditEvidence } from "./smoke"; + +const artifact = { + schemaVersion: 1 as const, + line: "v1" as const, + packageName: "@atacama-dev/opencode-agentbus-v1", + version: "0.1.0", + tarball: "archive.tgz", + sha256: "a".repeat(64), + sourceCommit: "b".repeat(40), +}; +test("manifest forbids traversal and malformed hashes", () => { + expect(parseArtifact(artifact)).toEqual(artifact); + expect(() => parseArtifact({ ...artifact, tarball: "../archive.tgz" })).toThrow(); + expect(() => parseArtifact({ ...artifact, sha256: "bad" })).toThrow(); +}); + +test("audit evidence rejects errors, missing or inconsistent counts, malformed JSON and mismatched status", () => { + const counts = { info: 0, low: 0, moderate: 0, high: 1, critical: 0, total: 1 }; + const report = { + auditReportVersion: 2, + vulnerabilities: { zod: { severity: "high" } }, + metadata: { vulnerabilities: counts }, + }; + expect(validateAuditEvidence(JSON.stringify(report), 1)).toEqual(counts); + expect(() => + validateAuditEvidence(JSON.stringify({ ...report, error: { message: "registry offline" } }), 1), + ).toThrow(); + expect(() => validateAuditEvidence(JSON.stringify({ ...report, metadata: {} }), 1)).toThrow(); + expect(() => + validateAuditEvidence( + JSON.stringify({ ...report, metadata: { vulnerabilities: { ...counts, total: "1" } } }), + 1, + ), + ).toThrow(); + expect(() => + validateAuditEvidence( + JSON.stringify({ ...report, metadata: { vulnerabilities: { ...counts, total: 2 } } }), + 1, + ), + ).toThrow(); + expect(() => validateAuditEvidence("not JSON", 1)).toThrow(); + expect(() => validateAuditEvidence(JSON.stringify(report), 0)).toThrow(); + expect(() => validateAuditEvidence(JSON.stringify(report), 2)).toThrow(); + const clean = { + auditReportVersion: 2, + vulnerabilities: {}, + metadata: { vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: 0 } }, + }; + expect(validateAuditEvidence(JSON.stringify(clean), 0).total).toBe(0); + expect(() => validateAuditEvidence(JSON.stringify(clean), 1)).toThrow(); +}); +test("archive allowlist rejects symlinks, credentials and extra package entries", () => { + const contents = [ + "package/package.json", + "package/dist/index.js", + "package/dist/index.d.ts", + "package/LICENSE", + "package/README.md", + "package/node_modules/@opencode-agentbus/broker/package.json", + "package/node_modules/@opencode-agentbus/protocol/package.json", + ]; + expect(() => validateArchiveNames(contents)).not.toThrow(); + expect(() => validateArchiveNames([...contents, "package/.env"])).toThrow(); + expect(() => validateArchiveNames([...contents, "package/package.json"])).toThrow("Duplicate"); + expect(() => validateArchiveNames([...contents, "package/dist/private.test.js"])).toThrow(); +}); diff --git a/scripts/release/smoke.ts b/scripts/release/smoke.ts new file mode 100644 index 0000000..2281afb --- /dev/null +++ b/scripts/release/smoke.ts @@ -0,0 +1,400 @@ +import { createHash } from "node:crypto"; +import { + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; +import { + readReleaseConfig, + REPOSITORY_ROOT, + type PackageArtifact, + type ReleaseLine, +} from "./config"; +import { publicDependencies, validatePackedManifest } from "./package"; +import { evaluateAudit, installedContext } from "../security/audit"; + +export function parseArtifact(value: unknown): PackageArtifact { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Invalid artifact manifest"); + const obj = value as Record; + if ( + Object.keys(obj).sort().join(",") !== + "line,packageName,schemaVersion,sha256,sourceCommit,tarball,version" || + obj.schemaVersion !== 1 || + (obj.line !== "v1" && obj.line !== "v2") || + typeof obj.packageName !== "string" || + typeof obj.version !== "string" || + typeof obj.tarball !== "string" || + !/^[a-z0-9][a-z0-9.-]*\.tgz$/u.test(obj.tarball) || + basename(obj.tarball) !== obj.tarball || + typeof obj.sha256 !== "string" || + !/^[a-f0-9]{64}$/u.test(obj.sha256) || + typeof obj.sourceCommit !== "string" || + !/^[a-f0-9]{40}$/u.test(obj.sourceCommit) + ) + throw new Error("Invalid artifact manifest fields"); + return obj as unknown as PackageArtifact; +} + +export function validateArchiveNames(names: string[]): void { + if (new Set(names).size !== names.length) throw new Error("Duplicate archive entries"); + const required = [ + "package/package.json", + "package/dist/index.js", + "package/dist/index.d.ts", + "package/LICENSE", + "package/README.md", + "package/node_modules/@opencode-agentbus/broker/package.json", + "package/node_modules/@opencode-agentbus/protocol/package.json", + ]; + if (!required.every((name) => names.includes(name))) throw new Error("Missing archive entries"); + for (const name of names) { + if (required.includes(name)) continue; + if ( + !/^package\/node_modules\/@opencode-agentbus\/(?:broker|protocol)\/(?:dist\/[a-z0-9-]+\.(?:js|d\.ts)|LICENSE)$/u.test( + name, + ) + ) + throw new Error(`Forbidden archive entry: ${name}`); + } +} + +export interface AuditCounts { + readonly info: number; + readonly low: number; + readonly moderate: number; + readonly high: number; + readonly critical: number; + readonly total: number; +} + +export function validateAuditEvidence(output: string, exitCode: number): AuditCounts { + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + throw new Error("Invalid npm audit JSON"); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + throw new Error("Invalid npm audit report"); + const report = parsed as Record; + const metadata = report.metadata as Record | undefined; + const counts = metadata?.vulnerabilities as Record | undefined; + const vulnerabilities = report.vulnerabilities; + if ( + report.error !== undefined || + report.auditReportVersion !== 2 || + !vulnerabilities || + typeof vulnerabilities !== "object" || + Array.isArray(vulnerabilities) || + !counts || + typeof counts !== "object" || + Array.isArray(counts) + ) + throw new Error("npm audit returned an error or incomplete evidence"); + const levels = ["info", "low", "moderate", "high", "critical"] as const; + if ( + [...levels, "total"].some( + (key) => !Number.isSafeInteger(counts[key]) || (counts[key] as number) < 0, + ) + ) + throw new Error("npm audit returned invalid vulnerability counts"); + const total = levels.reduce((sum, level) => sum + (counts[level] as number), 0); + if ( + counts.total !== total || + Object.keys(vulnerabilities).length !== total || + (exitCode !== 0 && exitCode !== 1) || + (exitCode === 0) !== (total === 0) + ) + throw new Error("npm audit exit status and vulnerability counts disagree"); + return counts as unknown as AuditCounts; +} + +async function typecheckConsumer( + scratch: string, + consumer: string, + installedRoot: string, + packageName: string, + line: ReleaseLine, +): Promise<{ exitCode: number; output: string }> { + const compiler = join(REPOSITORY_ROOT, "node_modules/typescript/bin/tsc"); + const compilerVersion = JSON.parse( + readFileSync(join(REPOSITORY_ROOT, "node_modules/typescript/package.json"), "utf8"), + ).version; + if (compilerVersion !== "5.7.2" || !existsSync(compiler)) + throw new Error("Pinned TypeScript 5.7.2 build tool is unavailable"); + const tooling = join(scratch, "type-toolchain"); + mkdirSync(tooling); + writeFileSync( + join(tooling, "package.json"), + JSON.stringify({ + private: true, + name: "agentbus-type-toolchain", + version: "0.0.0", + devDependencies: { "@types/node": "22.15.30" }, + }), + ); + await command(["npm", "install", "--ignore-scripts", "--no-audit", "--no-fund"], tooling); + writeFileSync( + join(consumer, "type-consumer.ts"), + line === "v1" + ? `import entry from "${packageName}";\nimport type { Plugin } from "@opencode-ai/plugin";\nconst plugin: Plugin = entry;\nvoid plugin;\n` + : `import entry from "${packageName}";\nimport type { Plugin } from "@opencode/plugin/effect";\nconst plugin: Plugin.Plugin = entry;\nvoid plugin;\n`, + ); + const internalFixture = join(installedRoot, "__type_probe__.ts"); + writeFileSync( + internalFixture, + 'import type { BrokerDaemon } from "@opencode-agentbus/broker";\nimport { launchBrokerDaemon } from "@opencode-agentbus/broker/cli";\nconst launch: typeof launchBrokerDaemon = launchBrokerDaemon;\nconst daemon: BrokerDaemon | undefined = undefined;\nvoid launch; void daemon;\n', + ); + writeFileSync( + join(consumer, "tsconfig.release-smoke.json"), + JSON.stringify({ + compilerOptions: { + noEmit: true, + strict: true, + skipLibCheck: false, + target: "ES2022", + module: "ESNext", + moduleResolution: "Bundler", + lib: ["ES2022", "DOM"], + types: ["node"], + typeRoots: [join(consumer, "node_modules/@types"), join(tooling, "node_modules/@types")], + }, + files: ["./type-consumer.ts", internalFixture], + }), + ); + const check = await command( + ["node", compiler, "--project", "tsconfig.release-smoke.json", "--pretty", "false"], + consumer, + true, + ); + return { exitCode: check.code, output: check.output }; +} + +async function command( + argv: string[], + cwd: string, + allowFailure = false, +): Promise<{ output: string; code: number }> { + const child = Bun.spawn(argv, { + cwd, + stdout: "pipe", + stderr: "pipe", + env: { + PATH: process.env.PATH ?? "/usr/bin:/bin", + HOME: join(cwd, ".npm-home"), + npm_config_cache: join(cwd, ".npm-cache"), + TMPDIR: "/tmp/opencode", + }, + }); + const [output, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (!allowFailure && code !== 0) + throw new Error( + `${argv[0]} failed (${code}): ${stderr.slice(0, 2500)} ${output.slice(0, 1000)}`, + ); + return { output, code }; +} + +export async function smokeArchive(manifestPath: string): Promise { + const absolute = resolve(manifestPath); + const artifact = parseArtifact(JSON.parse(readFileSync(absolute, "utf8"))); + const config = readReleaseConfig(); + if ( + artifact.packageName !== config.packageNames[artifact.line] || + artifact.version !== config.version || + !config.supportedLines.includes(artifact.line) + ) + throw new Error("Artifact identity does not match release config"); + const archive = join(dirname(absolute), artifact.tarball); + if ( + createHash("sha256") + .update(new Uint8Array(readFileSync(archive))) + .digest("hex") !== artifact.sha256 + ) + throw new Error("Archive SHA-256 mismatch"); + mkdirSync("/tmp/opencode", { recursive: true, mode: 0o700 }); + const scratch = mkdtempSync("/tmp/opencode/agentbus-consumer-"); + try { + const listing = (await command(["tar", "-tzf", archive], scratch)).output.trim().split("\n"); + validateArchiveNames(listing); + const verbose = (await command(["tar", "-tvzf", archive], scratch)).output.trim().split("\n"); + if (verbose.some((row) => !/^[\-d]/u.test(row))) + throw new Error("Archive has symlinks or nonstandard entries"); + const unpack = join(scratch, "unpacked"); + mkdirSync(unpack); + await command(["tar", "-xzf", archive, "-C", unpack], scratch); + const packedRoot = join(unpack, "package"); + const rootManifest = JSON.parse(readFileSync(join(packedRoot, "package.json"), "utf8")); + if ( + rootManifest.main !== "./dist/index.js" || + rootManifest.types !== "./dist/index.d.ts" || + rootManifest.exports?.["."]?.types !== rootManifest.types || + rootManifest.exports?.["."]?.import !== rootManifest.main || + rootManifest.exports?.["."].default !== rootManifest.main + ) + throw new Error("Incorrect root JS/type export"); + const declarations = readFileSync(join(packedRoot, "dist/index.d.ts"), "utf8"); + if ( + declarations.includes("sourceMappingURL") || + /\bfrom ["']\./u.test(declarations) || + (artifact.line === "v1" && + (!declarations.includes("@opencode-ai/plugin") || + declarations.includes("@opencode/plugin"))) || + (artifact.line === "v2" && + (!declarations.includes("@opencode/plugin/effect") || + !declarations.includes("effect/Scope") || + declarations.includes("@opencode-ai/plugin"))) + ) + throw new Error("Incorrect or dangling root declarations"); + const expected = artifact.line === "v1" ? "@opencode-ai/plugin" : "@opencode/plugin"; + const unwanted = + artifact.line === "v1" + ? ["@opencode/plugin", "@opencode/client", "@opencode/schema", "effect"] + : ["@opencode-ai/plugin"]; + if ( + rootManifest.name !== artifact.packageName || + rootManifest.version !== artifact.version || + Object.keys(rootManifest.exports ?? {}).join(",") !== "." || + Object.keys(rootManifest.dependencies ?? {}) + .sort() + .join(",") !== + [ + ...Object.keys(publicDependencies(artifact.line)), + "@opencode-agentbus/broker", + "@opencode-agentbus/protocol", + ] + .sort() + .join(",") || + !rootManifest.dependencies?.[expected] || + unwanted.some((name) => name in rootManifest.dependencies) || + Object.entries(publicDependencies(artifact.line)).some( + ([name, version]) => rootManifest.dependencies[name] !== version, + ) || + JSON.stringify(rootManifest.bundledDependencies?.slice().sort()) !== + JSON.stringify(["@opencode-agentbus/broker", "@opencode-agentbus/protocol"].sort()) + ) + throw new Error("Wrong packed dependency profile"); + for (const name of [ + "", + "node_modules/@opencode-agentbus/broker", + "node_modules/@opencode-agentbus/protocol", + ]) + validatePackedManifest( + JSON.parse(readFileSync(join(packedRoot, name, "package.json"), "utf8")), + ); + if ( + artifact.line === "v2" && + (rootManifest.experimentalStock !== true || + rootManifest.focusOnReceiveApproval !== false || + Object.keys(rootManifest.exports).join(",") !== ".") + ) + throw new Error("V2 stock experiment metadata invalid"); + const consumer = join(scratch, "consumer"); + mkdirSync(consumer); + writeFileSync( + join(consumer, "package.json"), + JSON.stringify({ + name: "agentbus-independent-consumer", + private: true, + type: "module", + dependencies: { [artifact.packageName]: archive }, + }), + ); + await command( + ["npm", "install", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund"], + consumer, + ); + const installedRoot = join(consumer, "node_modules", ...artifact.packageName.split("/")); + if (!existsSync(join(installedRoot, "node_modules/@opencode-agentbus/broker/dist/cli.js"))) + throw new Error("Bundled broker not installed"); + copyFileSync(join(import.meta.dir, "fixtures/probe.ts"), join(consumer, "probe.ts")); + await command(["bun", "probe.ts", artifact.packageName, artifact.line], consumer); + const graph = await command(["npm", "ls", "--all", "--json"], consumer, true); + writeFileSync(join(dirname(absolute), "consumer-graph.json"), graph.output); + if (graph.code !== 0) throw new Error("Installed production dependency graph is invalid"); + const audit = await command(["npm", "audit", "--omit=dev", "--json"], consumer, true); + writeFileSync(join(dirname(absolute), "audit.json"), audit.output); + writeFileSync( + join(dirname(absolute), "audit-exit.json"), + JSON.stringify({ exitCode: audit.code }), + ); + const vulnerabilities = validateAuditEvidence(audit.output, audit.code); + const identity = { + line: artifact.line, + packageName: artifact.packageName, + version: artifact.version, + sha256: artifact.sha256, + sourceCommit: artifact.sourceCommit, + }; + const context = installedContext(consumer, "production", artifact.sourceCommit, identity); + writeFileSync(join(dirname(absolute), "audit-context.json"), JSON.stringify(context, null, 2)); + const decision = evaluateAudit( + JSON.parse(audit.output), + context, + JSON.parse(readFileSync(join(REPOSITORY_ROOT, "security/audit-exceptions.json"), "utf8")), + { expected: identity, profile: "production", exitCode: audit.code }, + ); + writeFileSync( + join(dirname(absolute), "audit-decision.json"), + JSON.stringify(decision, null, 2), + ); + console.log( + `Production audit: ${decision.rawAffectedPackages} affected packages, ${decision.rawAdvisories.length} distinct advisories; ${decision.status}`, + ); + const types = await typecheckConsumer( + scratch, + consumer, + installedRoot, + artifact.packageName, + artifact.line, + ); + writeFileSync( + join(dirname(absolute), "typecheck.json"), + JSON.stringify( + { compiler: "TypeScript 5.7.2", strict: true, skipLibCheck: false, ...types }, + null, + 2, + ), + ); + if (types.exitCode !== 0) + throw new Error( + `Independent consumer strict typecheck failed: ${types.output.slice(0, 3500)}`, + ); + console.log( + JSON.stringify( + { + line: artifact.line, + package: artifact.packageName, + archive: artifact.tarball, + sha256: artifact.sha256, + runtime: "passed", + hostAcceptance: "not tested (isolated fixture)", + auditExit: audit.code, + vulnerabilities, + graphExit: graph.code, + typecheck: "passed (strict, skipLibCheck:false)", + }, + null, + 2, + ), + ); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +if (import.meta.main) { + const args = process.argv.slice(2); + if (args.length !== 2 || args[0] !== "--manifest") + throw new Error("Usage: bun scripts/release/smoke.ts --manifest /manifest.json"); + await smokeArchive(args[1] as string); +} diff --git a/scripts/run-package-tsc.test.ts b/scripts/run-package-tsc.test.ts new file mode 100644 index 0000000..52ec70d --- /dev/null +++ b/scripts/run-package-tsc.test.ts @@ -0,0 +1,55 @@ +import { expect, test } from "bun:test"; +import { + chmodSync, + mkdtempSync, + mkdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +test("a clean package build makes declared CLI entries owner-executable", () => { + const directory = mkdtempSync(join(tmpdir(), "agentbus-build-bin-")); + try { + mkdirSync(join(directory, "src")); + writeFileSync( + join(directory, "src/cli.ts"), + "#!/usr/bin/env bun\nexport const fixture: boolean = true;\n", + ); + writeFileSync( + join(directory, "package.json"), + JSON.stringify({ name: "build-fixture", private: true, bin: { fixture: "./dist/cli.js" } }), + ); + writeFileSync( + join(directory, "tsconfig.build.json"), + JSON.stringify({ + // Exercise CLI output permissions without loading unrelated browser declarations. + compilerOptions: { + target: "ES2022", + module: "ESNext", + outDir: "dist", + lib: ["ES2022"], + types: [], + }, + include: ["src/**/*.ts"], + }), + ); + const executable = join(directory, "dist/cli.js"); + for (let build = 0; build < 2; build++) { + if (build > 0) chmodSync(executable, 0o600); + const result = Bun.spawnSync( + [process.execPath, resolve(import.meta.dir, "run-package-tsc.ts"), "build"], + { cwd: directory, stdout: "pipe", stderr: "pipe" }, + ); + expect(result.exitCode, result.stderr.toString()).toBe(0); + expect(statSync(executable).mode & 0o100).toBe(0o100); + expect(readFileSync(executable, "utf8")).toStartWith("#!/usr/bin/env bun\n"); + expect(readFileSync(executable, "utf8")).toContain("export const fixture = true;"); + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/scripts/run-package-tsc.ts b/scripts/run-package-tsc.ts index 96ed311..1e540f7 100644 --- a/scripts/run-package-tsc.ts +++ b/scripts/run-package-tsc.ts @@ -1,4 +1,4 @@ -import { existsSync, readdirSync } from "node:fs"; +import { chmodSync, existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { resolve } from "node:path"; const mode = Bun.argv[2]; @@ -36,4 +36,13 @@ if (!hasInputs) { stderr: "inherit", }); if (!result.success) process.exitCode = result.exitCode; + else if (mode === "build") { + const manifest = JSON.parse( + readFileSync(resolve(packageDirectory, "package.json"), "utf8"), + ) as { bin?: Readonly> }; + for (const entry of Object.values(manifest.bin ?? {})) { + const executable = resolve(packageDirectory, entry); + chmodSync(executable, statSync(executable).mode | 0o100); + } + } } diff --git a/scripts/security/audit.test.ts b/scripts/security/audit.test.ts new file mode 100644 index 0000000..82eb57d --- /dev/null +++ b/scripts/security/audit.test.ts @@ -0,0 +1,703 @@ +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { evaluateAudit, installedContext, type AuditContext } from "./audit"; + +const commit = "a".repeat(40); +const manifest = { + line: "v2", + packageName: "@atacama-dev/opencode-agentbus-v2", + version: "0.1.0", + sha256: "b".repeat(64), + sourceCommit: commit, +}; +const chain = ["@opencode/plugin@2.2.7", "@opencode/util@2.2.7", "glob@13.0.5"]; +const context: AuditContext = { + schemaVersion: 1, + profile: "production", + sourceCommit: commit, + manifest, + nodes: [{ path: "node_modules/glob", name: "glob", version: "13.0.5", chains: [chain] }], +}; +const advisory = { + url: "https://github.com/advisories/GHSA-3g3m-2fjr-6pw4", + name: "glob", + severity: "moderate", + range: ">=9.0.0 <=14.0.1", +}; +const via = { ...advisory, source: 1, dependency: "glob", title: "test" }; +const npmReport = { + auditReportVersion: 2, + vulnerabilities: { + glob: { name: "glob", severity: "moderate", via: [via], nodes: ["node_modules/glob"] }, + }, + metadata: { + dependencies: { prod: 3 }, + vulnerabilities: { info: 0, low: 0, moderate: 1, high: 0, critical: 0, total: 1 }, + }, +}; +const ledger = { + schemaVersion: 1, + exceptions: [ + { + id: "GHSA-3g3m-2fjr-6pw4", + severity: "moderate", + package: "glob", + scopes: [{ version: "13.0.5", profile: "production", line: "v2", chains: [chain] }], + acceptedOn: "2026-11-15", + expiresOn: "2026-12-15", + responsible: "Julien Tesson", + reason: "SDK installed but own code does not invoke glob", + evidence: ["packages/plugin/test/advisory-exposure.test.ts"], + }, + ], +}; +const now = new Date("2026-11-15T12:00:00Z"); + +test("specific production leaf is a visible accepted risk, not a clean audit", () => { + expect( + evaluateAudit(npmReport, context, ledger, { now, exitCode: 1, expected: manifest }).accepted, + ).toHaveLength(1); +}); +test("exception expiry is an exclusive UTC instant, never an inclusive extra day", () => { + const check = (time: Date) => + evaluateAudit(npmReport, context, ledger, { now: time, exitCode: 1, expected: manifest }); + expect(() => check(new Date("2026-12-14T23:59:59.999Z"))).not.toThrow(); + expect(() => check(new Date("2026-12-15T00:00:00.000Z"))).toThrow("date"); + expect(() => check(new Date(Number.NaN))).toThrow("clock"); + const sameDay = { + ...ledger, + exceptions: [{ ...ledger.exceptions[0], expiresOn: "2026-11-15" }], + }; + expect(() => + evaluateAudit(npmReport, context, sameDay, { now, exitCode: 1, expected: manifest }), + ).toThrow("date"); +}); +test("Bun workspace JSON requires genuine advisory objects and matching observed exit status", () => { + const exception = ledger.exceptions.at(0); + if (!exception) throw new Error("Missing test exception"); + const { line: _line, ...scope } = { ...exception.scopes[0], profile: "workspace" }; + const workspaceLedger = { + ...ledger, + exceptions: [{ ...exception, scopes: [scope] }], + }; + const workspaceContext: AuditContext = { + schemaVersion: 1, + profile: "workspace", + sourceCommit: commit, + nodes: context.nodes, + }; + const finding = { + url: advisory.url, + severity: advisory.severity, + vulnerable_versions: advisory.range, + }; + const evaluate = (report: unknown, exitCode: number) => + evaluateAudit(report, workspaceContext, workspaceLedger, { + now, + exitCode, + expected: { sourceCommit: commit }, + profile: "workspace", + }); + expect(evaluate({ glob: [finding] }, 1).rawAdvisories).toEqual(["GHSA-3g3m-2fjr-6pw4"]); + expect(evaluate({}, 0).status).toBe("no-findings"); + for (const [report, exit] of [ + [{}, 1], + [{ glob: [finding] }, 0], + [{ glob: [finding] }, 2], + [{ glob: ["glob"] }, 1], + [{ glob: [] }, 1], + [{ error: { message: "registry offline" } }, 1], + ] as const) + expect(() => evaluate(report, exit)).toThrow(); +}); +test("unknown, escalated, changed version/path, critical and incomplete evidence block", () => { + for (const report of [ + { + ...npmReport, + vulnerabilities: { + glob: { + ...npmReport.vulnerabilities.glob, + via: [{ ...via, url: "https://github.com/advisories/GHSA-aaaa-bbbb-cccc" }], + }, + }, + }, + { + ...npmReport, + vulnerabilities: { + glob: { ...npmReport.vulnerabilities.glob, via: [{ ...via, severity: "high" }] }, + }, + }, + { + ...npmReport, + vulnerabilities: { + glob: { ...npmReport.vulnerabilities.glob, via: [{ ...via, severity: "critical" }] }, + }, + }, + { + ...npmReport, + vulnerabilities: { glob: { ...npmReport.vulnerabilities.glob, severity: "critical" } }, + }, + { + ...npmReport, + vulnerabilities: { glob: { ...npmReport.vulnerabilities.glob, via: ["unknown"] } }, + }, + { + ...npmReport, + vulnerabilities: { + glob: { ...npmReport.vulnerabilities.glob, nodes: ["node_modules/other"] }, + }, + }, + { ...npmReport, error: { message: "offline" } }, + ]) + expect(() => + evaluateAudit(report, context, ledger, { now, exitCode: 1, expected: manifest }), + ).toThrow(); + const baseline = context.nodes.at(0); + if (!baseline) throw new Error("Missing test instance"); + for (const node of [ + { ...baseline, version: "13.0.4" }, + { ...baseline, chains: [["@other/sdk@2.2.7", "glob@13.0.5"]] }, + ]) + expect(() => + evaluateAudit(npmReport, { ...context, nodes: [node] }, ledger, { + now, + exitCode: 1, + expected: manifest, + }), + ).toThrow(); +}); +test("ledger dates, wildcard scope, duplicates and identity are strict", () => { + for (const change of [ + { expiresOn: "2026-12-16" }, + { acceptedOn: "2026-11-16" }, + { expiresOn: "2026-11-14" }, + { expiresOn: "2026-13-01" }, + { acceptedOn: ["2026-11-15"] }, + { responsible: "unknown" }, + { scopes: [{ version: "*", profile: "production", line: "v2", chains: [chain] }] }, + { scopes: [{ version: "13.0.5", profile: ["production"], line: "v2", chains: [chain] }] }, + { scopes: [{ version: "13.0.5", profile: "production", line: "v2", chains: [["*"]] }] }, + { severity: "critical" }, + ]) + expect(() => + evaluateAudit( + npmReport, + context, + { ...ledger, exceptions: [{ ...ledger.exceptions[0], ...change }] }, + { now, exitCode: 1, expected: manifest }, + ), + ).toThrow(); + expect(() => + evaluateAudit( + npmReport, + context, + { ...ledger, exceptions: [...ledger.exceptions, ledger.exceptions[0]] }, + { now, exitCode: 1, expected: manifest }, + ), + ).toThrow(); + expect(() => + evaluateAudit(npmReport, { ...context, sourceCommit: "c".repeat(40) }, ledger, { + now, + exitCode: 1, + expected: manifest, + }), + ).toThrow(); + expect(() => + evaluateAudit(npmReport, context, ledger, { now, exitCode: 0, expected: manifest }), + ).toThrow(); + expect(() => + evaluateAudit(npmReport, context, ledger, { now, exitCode: 2, expected: manifest }), + ).toThrow(); +}); + +test("production exceptions require an exact release line; workspace scopes forbid a line", () => { + const source = ledger.exceptions[0]; + if (!source) throw new Error("Missing test exception"); + const production = source.scopes[0]; + if (!production) throw new Error("Missing test scope"); + for (const scope of [ + { ...production, line: undefined }, + { ...production, line: "*" }, + { ...production, line: "v1" }, + ]) + expect(() => + evaluateAudit( + npmReport, + context, + { + ...ledger, + exceptions: [{ ...source, scopes: [scope] }], + }, + { now, exitCode: 1, expected: manifest }, + ), + ).toThrow(); + const workspaceContext: AuditContext = { + schemaVersion: 1, + profile: "workspace", + sourceCommit: commit, + nodes: context.nodes, + }; + const report = { + glob: [{ url: advisory.url, severity: advisory.severity, vulnerable_versions: advisory.range }], + }; + const workspaceScope = { ...production, profile: "workspace", line: "v2" }; + expect(() => + evaluateAudit( + report, + workspaceContext, + { + ...ledger, + exceptions: [{ ...source, scopes: [workspaceScope] }], + }, + { now, exitCode: 1, expected: { sourceCommit: commit }, profile: "workspace" }, + ), + ).toThrow(); +}); + +test("a V1 legacy SDK exception cannot authorize the identical installed chain in V2 production", () => { + const zod = reviewed.exceptions.find( + (entry: { id: string }) => entry.id === "GHSA-mrhx-c7xc-m3w5", + ); + if (!zod) throw new Error("Missing reviewed legacy advisory"); + const legacyManifest = { + ...manifest, + line: "v1", + packageName: "@atacama-dev/opencode-agentbus-v1", + }; + const legacyContext: AuditContext = { + schemaVersion: 1, + profile: "production", + sourceCommit: commit, + manifest: legacyManifest, + nodes: [ + { + path: "node_modules/zod", + name: "zod", + version: "4.1.8", + chains: [["@opencode-ai/plugin@1.18.19", "zod@4.1.8"]], + }, + ], + }; + const report = { + auditReportVersion: 2, + vulnerabilities: { + zod: { + name: "zod", + severity: "high", + via: [ + { + url: "https://github.com/advisories/GHSA-mrhx-c7xc-m3w5", + name: "zod", + dependency: "zod", + severity: "high", + range: "<4.6.6", + }, + ], + nodes: ["node_modules/zod"], + }, + }, + metadata: { + dependencies: { prod: 2 }, + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 1, critical: 0, total: 1 }, + }, + }; + expect(() => + evaluateAudit( + report, + legacyContext, + { schemaVersion: 1, exceptions: [zod] }, + { now, exitCode: 1, expected: legacyManifest }, + ), + ).not.toThrow(); + const wrongManifest = { + ...legacyManifest, + line: "v2", + packageName: "@atacama-dev/opencode-agentbus-v2", + }; + expect(() => + evaluateAudit( + report, + { ...legacyContext, manifest: wrongManifest }, + { schemaVersion: 1, exceptions: [zod] }, + { now, exitCode: 1, expected: wrongManifest }, + ), + ).toThrow("Uncovered"); +}); + +const reviewed = JSON.parse( + readFileSync(new URL("../../security/audit-exceptions.json", import.meta.url), "utf8"), +); +const ranges: Record = { + effect: ">=4.0.0-beta.0 <4.0.0-beta.103", + toml: "<=5.0.0", + zod: "<4.6.6", + glob: ">=9.0.0 <=14.0.1", + minimatch: ">=7.0.0 <11.0.1", +}; +test("workspace ledger names exactly six legacy advisories; no wildcard covers unknown IDs", () => { + const nodes = new Map(); + const report: Record = {}; + for (const entry of reviewed.exceptions) { + const scope = entry.scopes.find((scope: { profile: string }) => scope.profile === "workspace"); + const name = entry.package; + const path = `node_modules/${name}`; + if (!nodes.has(name)) + nodes.set(name, { path, name, version: scope.version, chains: [scope.chains[0]] }); + if (!report[name]) report[name] = []; + report[name].push({ + url: `https://github.com/advisories/${entry.id}`, + severity: entry.severity, + vulnerable_versions: ranges[name], + }); + } + expect(reviewed.exceptions).toHaveLength(6); + const result = evaluateAudit( + report, + { schemaVersion: 1, profile: "workspace", sourceCommit: commit, nodes: [...nodes.values()] }, + reviewed, + { now, exitCode: 1, expected: { sourceCommit: commit }, profile: "workspace" }, + ); + expect(result.rawAdvisories).toHaveLength(6); + expect(result.accepted).toHaveLength(6); + expect(() => + evaluateAudit( + { + ...report, + unexpected: [ + { + url: "https://github.com/advisories/GHSA-aaaa-bbbb-cccc", + severity: "high", + vulnerable_versions: "*", + }, + ], + }, + { + schemaVersion: 1, + profile: "workspace", + sourceCommit: commit, + nodes: [ + ...nodes.values(), + { + path: "node_modules/unexpected", + name: "unexpected", + version: "1.0.0", + chains: [["@opencode/plugin@2.2.7", "unexpected@1.0.0"]], + }, + ], + }, + reviewed, + { now, exitCode: 1, expected: { sourceCommit: commit }, profile: "workspace" }, + ), + ).toThrow("Uncovered"); +}); + +test("npm ancestor propagation resolves six leaf advisories, distinguishes patched and vulnerable copies", () => { + const first = (name: string) => + reviewed.exceptions.find((entry: { package: string }) => entry.package === name); + const leaf = (name: string, version: string, path: string, chain: string[]) => ({ + path, + name, + version, + chains: [chain], + }); + const zod = first("zod"); + const effect = first("effect"); + const tomlEntries = reviewed.exceptions.filter( + (entry: { package: string }) => entry.package === "toml", + ); + const sdk = "@opencode-ai/plugin"; + const manifestV1 = { ...manifest, line: "v1", packageName: "@atacama-dev/opencode-agentbus-v1" }; + const nodes = [ + leaf(manifestV1.packageName, "0.1.0", `node_modules/${manifestV1.packageName}`, [ + `${manifestV1.packageName}@0.1.0`, + ]), + leaf(sdk, "1.18.19", `node_modules/${sdk}`, [`${sdk}@1.18.19`]), + leaf("effect", "4.0.0-beta.83", "node_modules/effect", [ + `${sdk}@1.18.19`, + "effect@4.0.0-beta.83", + ]), + leaf("toml", "4.3.0", "node_modules/toml", [ + `${sdk}@1.18.19`, + "effect@4.0.0-beta.83", + "toml@4.3.0", + ]), + leaf("zod", "4.1.8", "node_modules/legacy/zod", [`${sdk}@1.18.19`, "zod@4.1.8"]), + leaf("zod", "4.6.7", "node_modules/zod", ["@opencode-agentbus/broker@0.1.0", "zod@4.6.7"]), + ]; + const advisory = (entry: { id: string; package: string; severity: string }) => ({ + url: `https://github.com/advisories/${entry.id}`, + name: entry.package, + dependency: entry.package, + severity: entry.severity, + range: ranges[entry.package], + }); + const report = { + auditReportVersion: 2, + vulnerabilities: { + [manifestV1.packageName]: { + name: manifestV1.packageName, + severity: "high", + via: [sdk], + nodes: [`node_modules/${manifestV1.packageName}`], + }, + [sdk]: { + name: sdk, + severity: "high", + via: ["effect", "zod"], + nodes: [`node_modules/${sdk}`], + }, + effect: { + name: "effect", + severity: "high", + via: [advisory(effect), "toml"], + nodes: ["node_modules/effect"], + }, + toml: { + name: "toml", + severity: "high", + via: tomlEntries.map(advisory), + nodes: ["node_modules/toml"], + }, + zod: { + name: "zod", + severity: "high", + via: [advisory(zod)], + nodes: ["node_modules/legacy/zod"], + }, + }, + metadata: { + dependencies: { prod: 20 }, + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 5, critical: 0, total: 5 }, + }, + }; + const contextV1: AuditContext = { + schemaVersion: 1, + profile: "production", + sourceCommit: commit, + manifest: manifestV1, + nodes, + }; + expect( + evaluateAudit(report, contextV1, reviewed, { now, expected: manifestV1, exitCode: 1 }) + .rawAdvisories, + ).toHaveLength(6); + expect(() => + evaluateAudit( + report, + { + ...contextV1, + nodes: [ + ...nodes, + leaf("zod", "4.1.8", "node_modules/new/zod", [`${sdk}@1.18.19`, "zod@4.1.8"]), + ], + }, + reviewed, + { now, expected: manifestV1, exitCode: 1 }, + ), + ).toThrow("omitted"); + expect(() => + evaluateAudit( + { + ...report, + vulnerabilities: { + ...report.vulnerabilities, + [sdk]: { ...report.vulnerabilities[sdk], via: ["missing"] }, + }, + }, + contextV1, + reviewed, + { now, expected: manifestV1, exitCode: 1 }, + ), + ).toThrow(); + expect(() => + evaluateAudit(report, { ...contextV1, manifest }, reviewed, { + now, + expected: manifestV1, + exitCode: 1, + }), + ).toThrow("mismatch"); +}); + +test("context capture retains an additional first-party dependency route even if the same physical copy is already reachable through the SDK", () => { + const root = mkdtempSync(join(tmpdir(), "agentbus-audit-graph-")); + const writePackage = ( + path: string, + name: string, + version: string, + dependencies: Record, + ) => { + mkdirSync(join(root, path), { recursive: true }); + writeFileSync( + join(root, path, "package.json"), + JSON.stringify({ name, version, dependencies }), + ); + }; + try { + writePackage(`node_modules/${manifest.packageName}`, manifest.packageName, manifest.version, { + "@opencode/plugin": "2.2.7", + glob: "13.0.5", + }); + writePackage("node_modules/@opencode/plugin", "@opencode/plugin", "2.2.7", { glob: "13.0.5" }); + writePackage("node_modules/glob", "glob", "13.0.5", {}); + const captured = installedContext(root, "production", commit, manifest); + const node = captured.nodes.find((entry) => entry.name === "glob"); + expect(node?.chains).toEqual( + expect.arrayContaining([ + ["@opencode/plugin@2.2.7", "glob@13.0.5"], + [`${manifest.packageName}@0.1.0`, "glob@13.0.5"], + ]), + ); + expect(() => + evaluateAudit(npmReport, captured, ledger, { now, exitCode: 1, expected: manifest }), + ).toThrow("Uncovered"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); +test("installed required peer reaches the same physical vulnerable copy through a new first-party route", () => { + const root = mkdtempSync(join(tmpdir(), "agentbus-audit-peers-")); + const writePackage = (path: string, value: Record) => { + mkdirSync(join(root, path), { recursive: true }); + writeFileSync(join(root, path, "package.json"), JSON.stringify(value)); + }; + try { + writePackage(`node_modules/${manifest.packageName}`, { + name: manifest.packageName, + version: manifest.version, + dependencies: { "@opencode/plugin": "2.2.7" }, + peerDependencies: { glob: "13.0.5" }, + }); + writePackage("node_modules/@opencode/plugin", { + name: "@opencode/plugin", + version: "2.2.7", + dependencies: { "@opencode/util": "2.2.7" }, + }); + writePackage("node_modules/@opencode/util", { + name: "@opencode/util", + version: "2.2.7", + dependencies: { glob: "13.0.5" }, + }); + writePackage("node_modules/glob", { name: "glob", version: "13.0.5" }); + const captured = installedContext(root, "production", commit, manifest); + expect(captured.nodes.find((node) => node.name === "glob")?.chains).toEqual( + expect.arrayContaining([chain, [`${manifest.packageName}@0.1.0`, "glob@13.0.5"]]), + ); + expect(() => + evaluateAudit(npmReport, captured, ledger, { now, exitCode: 1, expected: manifest }), + ).toThrow("Uncovered"); + writePackage(`node_modules/${manifest.packageName}`, { + name: manifest.packageName, + version: manifest.version, + dependencies: { "@opencode/plugin": "2.2.7" }, + peerDependencies: { missing: "1.0.0" }, + }); + expect(() => installedContext(root, "production", commit, manifest)).toThrow("Unresolved"); + writePackage(`node_modules/${manifest.packageName}`, { + name: manifest.packageName, + version: manifest.version, + dependencies: { "@opencode/plugin": "2.2.7" }, + peerDependencies: { missing: "1.0.0" }, + peerDependenciesMeta: { missing: { optional: true } }, + }); + expect(() => installedContext(root, "production", commit, manifest)).not.toThrow(); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("npm propagation reports two SDK leaves rather than counting dependent ancestors as new advisories", () => { + const names = ["glob", "minimatch"]; + // Synthetic engine-only public-SDK graph; V1's committed ledger has no public-SDK exceptions. + const globException = ledger.exceptions.at(0); + if (!globException) throw new Error("Missing synthetic public exception"); + const entries = [ + globException, + { + ...globException, + id: "GHSA-g3hv-75wg-m249", + package: "minimatch", + scopes: [ + { + profile: "production", + line: "v2", + version: "10.2.5", + chains: [["@opencode/plugin@2.2.7", "@opencode/util@2.2.7", "minimatch@10.2.5"]], + }, + ], + }, + ]; + const nodes = [ + { + path: "node_modules/@opencode/plugin", + name: "@opencode/plugin", + version: "2.2.7", + chains: [["@opencode/plugin@2.2.7"]], + }, + { + path: "node_modules/@opencode/util", + name: "@opencode/util", + version: "2.2.7", + chains: [["@opencode/plugin@2.2.7", "@opencode/util@2.2.7"]], + }, + ...entries.map((entry: { package: string }) => ({ + path: `node_modules/${entry.package}`, + name: entry.package, + version: entry.package === "glob" ? "13.0.5" : "10.2.5", + chains: [ + [ + "@opencode/plugin@2.2.7", + "@opencode/util@2.2.7", + `${entry.package}@${entry.package === "glob" ? "13.0.5" : "10.2.5"}`, + ], + ], + })), + ]; + const vulnerabilities: Record = { + "@opencode/plugin": { + name: "@opencode/plugin", + severity: "moderate", + via: ["@opencode/util"], + nodes: ["node_modules/@opencode/plugin"], + }, + "@opencode/util": { + name: "@opencode/util", + severity: "moderate", + via: names, + nodes: ["node_modules/@opencode/util"], + }, + }; + for (const entry of entries) + vulnerabilities[entry.package] = { + name: entry.package, + severity: "moderate", + nodes: [`node_modules/${entry.package}`], + via: [ + { + url: `https://github.com/advisories/${entry.id}`, + name: entry.package, + dependency: entry.package, + severity: "moderate", + range: ranges[entry.package], + }, + ], + }; + const report = { + auditReportVersion: 2, + vulnerabilities, + metadata: { + dependencies: { prod: 5 }, + vulnerabilities: { info: 0, low: 0, moderate: 4, high: 0, critical: 0, total: 4 }, + }, + }; + const decision = evaluateAudit( + report, + { schemaVersion: 1, profile: "production", sourceCommit: commit, manifest, nodes }, + { schemaVersion: 1, exceptions: entries }, + { now, expected: manifest, exitCode: 1 }, + ); + expect(decision.rawAffectedPackages).toBe(4); + expect(decision.rawAdvisories).toHaveLength(2); + expect(decision.uncovered).toBe(0); +}); diff --git a/scripts/security/audit.ts b/scripts/security/audit.ts new file mode 100644 index 0000000..3d74dba --- /dev/null +++ b/scripts/security/audit.ts @@ -0,0 +1,499 @@ +import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs"; +import { dirname, join, relative, resolve } from "node:path"; + +type Json = Record; +export interface AuditNode { + path: string; + name: string; + version: string; + chains: string[][]; +} +export interface AuditContext { + schemaVersion: 1; + profile: "workspace" | "production"; + sourceCommit: string; + manifest?: { + line: string; + packageName: string; + version: string; + sha256: string; + sourceCommit: string; + }; + nodes: AuditNode[]; +} +interface Exception { + id: string; + severity: string; + package: string; + version: string; + profile: string; + line?: "v1" | "v2"; + chain: string[]; + acceptedOn: string; + expiresOn: string; + responsible: string; + reason: string; + evidence: string[]; +} +const levels = ["info", "low", "moderate", "high", "critical"]; +const ghsa = /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u; +const packageName = /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u; +const version = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9a-zA-Z.-]+)?$/u; +const key = (chain: string[]) => JSON.stringify(chain); +function object(value: unknown): Json { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Invalid audit JSON object"); + return value as Json; +} +function date(value: string): number { + if (!/^\d{4}-\d{2}-\d{2}$/u.test(value)) throw new Error("Invalid audit exception date"); + const time = Date.parse(`${value}T00:00:00.000Z`); + if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) + throw new Error("Invalid audit exception date"); + return time; +} +function exceptions(value: unknown, now: Date): Exception[] { + const observed = now.getTime(); + if (!Number.isFinite(observed)) throw new Error("Invalid audit policy clock"); + const source = object(value); + if (source.schemaVersion !== 1 || !Array.isArray(source.exceptions)) + throw new Error("Invalid audit exception ledger"); + const seen = new Set(); + const ids = new Set(); + return source.exceptions.flatMap((entry: unknown) => { + const e = object(entry); + if ( + typeof e.id !== "string" || + !ghsa.test(e.id) || + ids.has(e.id) || + typeof e.severity !== "string" || + !levels.includes(e.severity) || + e.severity === "critical" || + typeof e.package !== "string" || + !packageName.test(e.package) || + e.responsible !== "Julien Tesson" || + typeof e.acceptedOn !== "string" || + typeof e.expiresOn !== "string" || + typeof e.reason !== "string" || + !e.reason.trim() || + !Array.isArray(e.evidence) || + e.evidence.length === 0 || + e.evidence.some((item) => typeof item !== "string" || !item.trim()) || + !Array.isArray(e.scopes) || + e.scopes.length === 0 + ) + throw new Error("Invalid audit exception scope or documentation"); + ids.add(e.id); + const start = date(e.acceptedOn); + const end = date(e.expiresOn); + if (end <= start || end - start > 30 * 86_400_000 || observed < start || observed >= end) + throw new Error(`Audit exception date outside active 30-day window: ${e.id}`); + return e.scopes.flatMap((scope: unknown) => { + const s = object(scope); + if ( + typeof s.profile !== "string" || + !["workspace", "production"].includes(s.profile) || + (s.profile === "production" && s.line !== "v1" && s.line !== "v2") || + (s.profile === "workspace" && Object.hasOwn(s, "line")) || + typeof s.version !== "string" || + !version.test(s.version) || + !Array.isArray(s.chains) || + s.chains.length === 0 + ) + throw new Error("Invalid audit exception version/profile"); + return s.chains.map((chain: unknown) => { + if ( + !Array.isArray(chain) || + chain.length < 2 || + chain.some( + (part) => + typeof part !== "string" || + !/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+@(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9a-zA-Z.-]+)?$/u.test( + part, + ), + ) || + chain.at(-1) !== `${e.package}@${s.version}` || + !["@opencode-ai/plugin@1.18.19", "@opencode/plugin@2.2.7"].includes(chain[0]) + ) + throw new Error("Invalid audit exception dependency chain"); + const identity = key([ + s.profile as string, + String(s.line ?? ""), + e.id as string, + s.version as string, + ...chain, + ]); + if (seen.has(identity)) throw new Error("Duplicate audit exception chain"); + seen.add(identity); + return { ...e, ...s, chain } as Exception; + }); + }); + }); +} + +/** Capture physical installed versions and all logical first-party-to-leaf routes. No foreign code is executed. */ +export function installedContext( + root: string, + profile: AuditContext["profile"], + sourceCommit: string, + manifest?: AuditContext["manifest"], +): AuditContext { + const base = resolve(root); + if ( + profile === "workspace" && + JSON.stringify( + object(JSON.parse(readFileSync(join(base, "package.json"), "utf8"))).workspaces, + ) !== JSON.stringify(["packages/*"]) + ) + throw new Error("Unreviewed workspace layout for dependency audit"); + const roots = + profile === "workspace" + ? [ + ".", + ...readdirSync(join(base, "packages"), { withFileTypes: true }) + .filter((entry) => { + if (entry.isSymbolicLink()) + throw new Error("Symlinked workspace package is not auditable"); + return ( + entry.isDirectory() && + existsSync(join(base, "packages", entry.name, "package.json")) + ); + }) + .map((entry) => `packages/${entry.name}`), + ] + : [`node_modules/${manifest?.packageName}`]; + const entries = new Map(); + let traversals = 0; + function visit(path: string, chain: string[], ancestors: Set) { + if (++traversals > 200_000 || chain.length > 50) + throw new Error("Installed dependency graph exceeds bounded audit traversal"); + const file = join(base, path, "package.json"); + if (!existsSync(file)) throw new Error(`Missing installed dependency metadata: ${path}`); + const canonical = realpathSync(file); + if (!canonical.startsWith(`${base}/`)) + throw new Error("Installed dependency escaped workspace"); + const pkg = object(JSON.parse(readFileSync(canonical, "utf8"))); + if ( + typeof pkg.name !== "string" || + !packageName.test(pkg.name) || + typeof pkg.version !== "string" || + !version.test(pkg.version) + ) + throw new Error("Invalid installed package identity"); + const logical = [...chain, `${pkg.name}@${pkg.version}`]; + let node = entries.get(path); + if (!node) { + node = { path, name: pkg.name, version: pkg.version, chains: [] }; + entries.set(path, node); + } + if (node.name !== pkg.name || node.version !== pkg.version) + throw new Error("Installed path identity changed"); + const sdkIndex = logical.findIndex( + (p) => p.startsWith("@opencode-ai/plugin@") || p.startsWith("@opencode/plugin@"), + ); + const trustedRoot = + profile === "workspace" + ? "@opencode-agentbus/plugin@0.1.0" + : `${manifest?.packageName}@${manifest?.version}`; + const reviewedPath = sdkIndex === 1 && logical[0] === trustedRoot ? logical.slice(1) : logical; + if (!node.chains.some((c) => key(c) === key(reviewedPath))) node.chains.push(reviewedPath); + if (ancestors.has(canonical)) return; // Peer cycles never produce a new dependency path. + const next = new Set(ancestors); + next.add(canonical); + const peers = object(pkg.peerDependencies ?? {}); + const peerMeta = object(pkg.peerDependenciesMeta ?? {}); + for (const [name, value] of Object.entries(peerMeta)) { + if (!packageName.test(name) || typeof object(value).optional !== "boolean") + throw new Error("Invalid installed peer metadata"); + } + const deps = { + ...object(pkg.dependencies ?? {}), + ...object(pkg.optionalDependencies ?? {}), + ...(profile === "workspace" && roots.includes(path) ? object(pkg.devDependencies ?? {}) : {}), + ...peers, + }; + for (const name of Object.keys(deps).sort()) { + if (!packageName.test(name)) throw new Error("Invalid installed dependency name"); + let parent = dirname(canonical); + let candidate: string | undefined; + while (parent.startsWith(base)) { + const local = join(parent, "node_modules", name); + if (existsSync(join(local, "package.json"))) { + candidate = relative(base, local); + break; + } + if (parent === base) break; + parent = dirname(parent); + } + if (!candidate) { + // Optional dependencies may be omitted by platform, but mandatory ones must resolve. + if ( + Object.hasOwn(object(pkg.dependencies ?? {}), name) || + (Object.hasOwn(peers, name) && + object(peerMeta[name] ?? { optional: false }).optional !== true) + ) + throw new Error(`Unresolved installed dependency ${name} from ${path}`); + continue; + } + visit(candidate, logical, next); + } + } + for (const path of roots) visit(path, [], new Set()); + return { + schemaVersion: 1, + profile, + sourceCommit, + ...(manifest ? { manifest } : {}), + nodes: [...entries.values()].sort((a, b) => a.path.localeCompare(b.path)), + }; +} + +export function evaluateAudit( + report: unknown, + context: AuditContext, + ledger: unknown, + options: { + now?: Date; + exitCode?: number; + expected: { + sourceCommit: string; + line?: string; + packageName?: string; + version?: string; + sha256?: string; + }; + profile?: AuditContext["profile"]; + }, +) { + const now = options.now ?? new Date(); + const allowed = exceptions(ledger, now); + if ( + context.schemaVersion !== 1 || + context.profile !== (options.profile ?? "production") || + context.sourceCommit !== options.expected.sourceCommit || + !/^[a-f0-9]{40}$/u.test(context.sourceCommit) || + (context.profile === "production" && + JSON.stringify(context.manifest) !== JSON.stringify(options.expected)) + ) + throw new Error("Audit context profile/source/manifest mismatch"); + const audit = object(report); + const vulnerabilities = context.profile === "workspace" ? audit : object(audit.vulnerabilities); + const metadata = context.profile === "workspace" ? {} : object(audit.metadata); + const counts = context.profile === "workspace" ? {} : object(metadata.vulnerabilities); + if ( + audit.error !== undefined || + (context.profile === "production" && audit.auditReportVersion !== 2) || + (context.profile === "production" && + (!Number.isSafeInteger(object(metadata.dependencies).prod) || + Number(object(metadata.dependencies).prod) < 1)) + ) + throw new Error("Missing, malformed or error audit report"); + if (context.profile === "production") { + if ( + Number(counts.critical) !== 0 || + levels.some((level) => !Number.isSafeInteger(counts[level]) || Number(counts[level]) < 0) || + counts.total !== levels.reduce((n, level) => n + Number(counts[level]), 0) || + Object.keys(vulnerabilities).length !== counts.total || + levels.some( + (level) => + Object.values(vulnerabilities).filter((row) => object(row).severity === level).length !== + counts[level], + ) || + (options.exitCode !== undefined && + ((options.exitCode !== 0 && options.exitCode !== 1) || + (options.exitCode === 0) !== (counts.total === 0))) + ) + throw new Error("npm audit counts or exit status disagree"); + } + if ( + context.profile === "workspace" && + ((options.exitCode !== 0 && options.exitCode !== 1) || + (options.exitCode === 0) !== (Object.keys(vulnerabilities).length === 0)) + ) + throw new Error("Bun audit exit status and findings disagree"); + if (!Array.isArray(context.nodes)) throw new Error("Missing installed audit nodes"); + const nodes = new Map(); + for (const node of context.nodes) { + if ( + typeof node.path !== "string" || + node.path.startsWith("/") || + node.path.includes("..") || + !packageName.test(node.name) || + !version.test(node.version) || + nodes.has(node.path) || + !Array.isArray(node.chains) || + node.chains.some( + (chain) => + !Array.isArray(chain) || + chain.at(-1) !== `${node.name}@${node.version}` || + chain.some( + (part) => + typeof part !== "string" || + !/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+@(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9a-zA-Z.-]+)?$/u.test( + part, + ), + ), + ) + ) + throw new Error("Invalid installed audit node"); + nodes.set(node.path, node); + } + const accepted: { + id: string; + package: string; + version: string; + path: string; + chain: string[]; + expiresOn: string; + }[] = []; + const leaves = new Set(); + const advisoryIds = new Set(); + const refs = new Map(); + for (const [name, raw] of Object.entries(vulnerabilities)) { + if (!packageName.test(name)) throw new Error("Invalid audit package name"); + const entry = context.profile === "workspace" ? raw : object(raw).via; + if ( + !Array.isArray(entry) || + (context.profile === "workspace" && entry.length === 0) || + (context.profile === "production" && + (!Array.isArray(object(raw).nodes) || + object(raw).name !== name || + !levels.includes(String(object(raw).severity)) || + object(raw).severity === "critical")) + ) + throw new Error("Malformed audit vulnerability"); + const dependencies: string[] = []; + for (const item of entry) { + if (typeof item === "string" && context.profile === "production") { + dependencies.push(item); + continue; + } + const advisory = object(item); + const id = String(advisory.url ?? "").replace("https://github.com/advisories/", ""); + const range = context.profile === "workspace" ? advisory.vulnerable_versions : advisory.range; + if ( + !ghsa.test(id) || + advisory.url !== `https://github.com/advisories/${id}` || + advisory.severity === "critical" || + !levels.includes(String(advisory.severity)) || + typeof range !== "string" || + !range || + (context.profile === "production" && + (advisory.name !== name || advisory.dependency !== name)) + ) + throw new Error("Malformed or critical audit advisory"); + if (advisoryIds.has(`${name}:${id}`)) throw new Error("Duplicate audit advisory"); + advisoryIds.add(`${name}:${id}`); + if ( + context.profile === "production" && + levels.indexOf(String(object(raw).severity)) < levels.indexOf(String(advisory.severity)) + ) + throw new Error("npm audit severity contradicts leaf advisory"); + leaves.add(name); + const instances = + context.profile === "workspace" + ? [...nodes.values()].filter((node) => node.name === name) + : (object(raw).nodes as string[]).map((path) => nodes.get(path)); + if (instances.length === 0 || instances.some((node) => !node || node.name !== name)) + throw new Error("Missing installed audit instance"); + if (context.profile === "production") { + const reported = new Set(object(raw).nodes as string[]); + if ( + reported.size !== (object(raw).nodes as string[]).length || + [...nodes.values()].some( + (node) => + node.name === name && + node.chains.length > 0 && + Bun.semver.satisfies(node.version, range) && + !reported.has(node.path), + ) + ) + throw new Error(`npm audit omitted an affected installed instance: ${name}`); + } + let matched = 0; + for (const node of instances) { + if (!node || !Bun.semver.satisfies(node.version, range)) continue; + matched++; + if (!node.chains.length) + throw new Error(`Unreviewed affected instance: ${name}@${node.version}`); + for (const chain of node.chains) { + const waiver = allowed.find( + (e) => + e.profile === context.profile && + (context.profile === "workspace" || e.line === context.manifest?.line) && + e.id === id && + e.severity === advisory.severity && + e.package === name && + e.version === node.version && + key(e.chain) === key(chain), + ); + if (!waiver) + throw new Error(`Uncovered ${id} ${name}@${node.version} via ${chain.join(" > ")}`); + accepted.push({ + id, + package: name, + version: node.version, + path: node.path, + chain, + expiresOn: waiver.expiresOn, + }); + } + } + if (!matched) throw new Error(`No affected installed instance for ${id}`); + } + refs.set(name, dependencies); + } + if (context.profile === "production") { + const visited = new Set(); + const visiting = new Set(); + const resolves = (name: string): boolean => { + if (visiting.has(name)) throw new Error("Cyclic npm audit via references"); + if (visited.has(name)) return true; + if (!refs.has(name)) throw new Error(`Unresolved npm audit via: ${name}`); + visiting.add(name); + for (const dependency of refs.get(name) ?? []) resolves(dependency); + visiting.delete(name); + visited.add(name); + return leaves.has(name) || (refs.get(name)?.length ?? 0) > 0; + }; + for (const [name, raw] of Object.entries(vulnerabilities)) { + if (!resolves(name)) throw new Error(`Orphan npm audit entry: ${name}`); + for (const path of object(raw).nodes as string[]) + if (nodes.get(path)?.name !== name) throw new Error(`Unresolved npm audit node: ${path}`); + for (const dependency of refs.get(name) ?? []) { + if ( + levels.indexOf(String(object(raw).severity)) < + levels.indexOf(String(object(vulnerabilities[dependency]).severity)) + ) + throw new Error("npm audit ancestor severity contradicts dependency"); + if ( + !( + name === options.expected.packageName && + [...nodes.values()].some((node) => + node.chains.some((chain) => chain[0]?.startsWith(`${dependency}@`)), + ) + ) && + ![...nodes.values()].some((node) => + node.chains.some((chain) => + chain.some( + (part, index) => + part.startsWith(`${name}@`) && chain[index + 1]?.startsWith(`${dependency}@`), + ), + ), + ) + ) + throw new Error( + `npm audit via edge absent from installed graph: ${name} -> ${dependency}`, + ); + } + } + } + return { + profile: context.profile, + rawAffectedPackages: Object.keys(vulnerabilities).length, + rawAdvisories: [...new Set(accepted.map((row) => row.id))], + accepted, + uncovered: 0, + status: accepted.length ? "accepted-temporary-risk" : "no-findings", + }; +} diff --git a/scripts/security/workspace-audit.ts b/scripts/security/workspace-audit.ts new file mode 100644 index 0000000..ab5b21d --- /dev/null +++ b/scripts/security/workspace-audit.ts @@ -0,0 +1,57 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { evaluateAudit, installedContext } from "./audit"; + +if (import.meta.main) { + const [flag, directory] = process.argv.slice(2); + if (flag !== "--out" || !directory || process.argv.length !== 4) + throw new Error("Usage: workspace-audit.ts --out "); + const root = resolve(import.meta.dir, "../.."); + const output = resolve(directory); + mkdirSync(output, { recursive: true }); + const sourceCommit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: root, + encoding: "utf8", + }).trim(); + const result = Bun.spawnSync(["bun", "audit", "--json"], { + cwd: root, + stdout: "pipe", + stderr: "pipe", + }); + const raw = result.stdout.toString(); + writeFileSync(resolve(output, "audit.json"), raw); + writeFileSync(resolve(output, "audit.stderr"), result.stderr.toString()); + writeFileSync(resolve(output, "audit-exit.json"), JSON.stringify({ exitCode: result.exitCode })); + const context = installedContext(root, "workspace", sourceCommit); + writeFileSync(resolve(output, "audit-context.json"), JSON.stringify(context, null, 2)); + try { + if (result.exitCode !== 0 && result.exitCode !== 1) + throw new Error(`bun audit failed (${result.exitCode})`); + const decision = evaluateAudit( + JSON.parse(raw), + context, + JSON.parse(readFileSync(resolve(root, "security/audit-exceptions.json"), "utf8")), + { expected: { sourceCommit }, profile: "workspace", exitCode: result.exitCode }, + ); + writeFileSync(resolve(output, "audit-decision.json"), JSON.stringify(decision, null, 2)); + console.log( + JSON.stringify( + { + status: decision.status, + rawAffectedPackages: decision.rawAffectedPackages, + rawAdvisories: decision.rawAdvisories, + acceptedRoutes: decision.accepted.length, + }, + null, + 2, + ), + ); + } catch (error) { + writeFileSync( + resolve(output, "audit-decision.json"), + JSON.stringify({ status: "blocked", reason: String(error) }, null, 2), + ); + throw error; + } +} diff --git a/security/audit-exceptions.json b/security/audit-exceptions.json new file mode 100644 index 0000000..974421b --- /dev/null +++ b/security/audit-exceptions.json @@ -0,0 +1,161 @@ +{ + "schemaVersion": 1, + "exceptions": [ + { + "id": "GHSA-4qx8-w7c3-pj3p", + "severity": "high", + "package": "toml", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK Effect installs TOML; own plugin does not parse TOML input.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + }, + { + "profile": "workspace", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + } + ] + }, + { + "id": "GHSA-9j65-hcg3-gc64", + "severity": "high", + "package": "toml", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK Effect installs TOML; own plugin does not parse TOML input.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + }, + { + "profile": "workspace", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + } + ] + }, + { + "id": "GHSA-9qmh-m7c6-f92p", + "severity": "high", + "package": "toml", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK Effect installs TOML; own plugin does not parse TOML input.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + }, + { + "profile": "workspace", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + } + ] + }, + { + "id": "GHSA-chp3-j5qr-2vfr", + "severity": "moderate", + "package": "effect", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK installs beta Effect; own plugin does not call its Cookie API.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.0.0-beta.83", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83"]] + }, + { + "profile": "workspace", + "version": "4.0.0-beta.83", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83"]] + } + ] + }, + { + "id": "GHSA-h895-cgqg-jf52", + "severity": "high", + "package": "toml", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK Effect installs TOML; own plugin does not parse TOML input.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + }, + { + "profile": "workspace", + "version": "4.3.0", + "chains": [["@opencode-ai/plugin@1.18.19", "effect@4.0.0-beta.83", "toml@4.3.0"]] + } + ] + }, + { + "id": "GHSA-mrhx-c7xc-m3w5", + "severity": "high", + "package": "zod", + "acceptedOn": "2026-11-15", + "expiresOn": "2026-12-15", + "responsible": "Julien Tesson", + "reason": "Legacy SDK pins vulnerable Zod; own legacy tool arguments are scalar-only; broker/protocol use patched Zod 4.6.7.", + "evidence": [ + "packages/plugin/test/advisory-exposure.test.ts", + "packages/plugin/src/plugin.ts" + ], + "scopes": [ + { + "profile": "production", + "line": "v1", + "version": "4.1.8", + "chains": [["@opencode-ai/plugin@1.18.19", "zod@4.1.8"]] + }, + { + "profile": "workspace", + "version": "4.1.8", + "chains": [["@opencode-ai/plugin@1.18.19", "zod@4.1.8"]] + } + ] + } + ] +} diff --git a/tests/integration/agentbus.integration.test.ts b/tests/integration/agentbus.integration.test.ts index 1d34911..6870450 100644 --- a/tests/integration/agentbus.integration.test.ts +++ b/tests/integration/agentbus.integration.test.ts @@ -1056,6 +1056,10 @@ describe("built Agent Bus production composition", () => { const originalFetch = globalThis.fetch; const eventRequests: Array<{ readonly cursor: string | null; readonly status: number }> = []; + let releaseReconnect: (() => void) | undefined; + const reconnectHeld = new Promise((resolve) => { + releaseReconnect = resolve; + }); globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => { const url = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input); @@ -1067,12 +1071,17 @@ describe("built Agent Bus production composition", () => { world.trace.push(first ? "sse:forced-stale" : "sse:watermark-reconnect"); const response = await originalFetch(input, { ...init, headers }); eventRequests.push({ cursor: headers.get("Last-Event-ID"), status: response.status }); + if (!first) await reconnectHeld; return response; }; try { hooks = await world.loadPlugin(host); await waitFor(() => eventRequests.length >= 2, 3_000); + expect(host.toasts).toEqual([]); + releaseReconnect?.(); + await waitFor(() => host.toasts.length > 0); } finally { + releaseReconnect?.(); globalThis.fetch = originalFetch; } @@ -1192,6 +1201,10 @@ describe("built Agent Bus production composition", () => { const eventRequests: Array<{ readonly cursor: string | null; readonly controlled: boolean }> = []; let controlledStream: ReadableStreamDefaultController | undefined; + let releaseReconnect: (() => void) | undefined; + const reconnectHeld = new Promise((resolve) => { + releaseReconnect = resolve; + }); globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => { const url = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input); @@ -1210,6 +1223,7 @@ describe("built Agent Bus production composition", () => { }); } eventRequests.push({ cursor: headers.get("Last-Event-ID"), controlled: false }); + await reconnectHeld; return originalFetch(input, init); }; @@ -1222,6 +1236,10 @@ describe("built Agent Bus production composition", () => { world.trace.filter((entry) => entry === `rpc:${METHODS.LIST_PENDING_MESSAGES}`).length >= 3, ); + const initialRegistry = registryMatches( + await eventually(() => search(hooks, host, permissions, "host_principal_a", "Principal B")), + ); + expect(initialRegistry.map(({ metadata }) => metadata.title)).toEqual(["Principal B"]); const service = world.service; if (!service) throw new Error("Missing live broker service."); const targetResponse = service.dispatch(service.principal, { @@ -1245,7 +1263,7 @@ describe("built Agent Bus production composition", () => { } controlledStream?.close(); - await Bun.sleep(20); + await waitFor(() => eventRequests.length === 2); const racedBody = "B event committed while the principal stream is disconnected"; const enqueueResponse = service.dispatch(service.principal, { protocolVersion: 2, @@ -1259,6 +1277,7 @@ describe("built Agent Bus production composition", () => { }, }); if (!enqueueResponse.ok) throw new Error("Principal-gap enqueue failed."); + releaseReconnect?.(); permissions.decide("agentbus_search_sessions", "once"); await search(hooks, host, permissions, "host_principal_a", "no matching principal session"); @@ -1277,6 +1296,7 @@ describe("built Agent Bus production composition", () => { racedBody, ); } finally { + releaseReconnect?.(); globalThis.fetch = originalFetch; } });