From cf7d4b47c2dff1c763dc02e930e09e0444980100 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 16 Nov 2026 01:16:22 -0500 Subject: [PATCH] Install attested releases automatically with manual update policy --- README.md | 20 +- docs/ARCHITECTURE.md | 8 +- docs/SECURITY-REVIEW.md | 17 +- package-lock.json | 672 +++++++++++++++++++++- package.json | 10 +- scripts/verify-release.mjs | 2 +- src/runtime/claude-code-adapter.ts | 2 +- src/runtime/cli.ts | 2 +- src/runtime/cli/core.ts | 23 +- src/runtime/codex-adapter.ts | 2 +- src/runtime/local-runtime.ts | 67 ++- src/runtime/release-attestation.ts | 132 +++++ src/runtime/runtime-auto-update.ts | 98 ++-- tests/runtime/adapter-utils.test.ts | 19 + tests/runtime/release-attestation.test.ts | 90 +++ tests/runtime/runtime-auto-update.test.ts | 156 ++++- 16 files changed, 1211 insertions(+), 109 deletions(-) create mode 100644 src/runtime/release-attestation.ts create mode 100644 tests/runtime/release-attestation.test.ts diff --git a/README.md b/README.md index 038200e..e080414 100644 --- a/README.md +++ b/README.md @@ -90,13 +90,19 @@ scope change. Source excerpts are off for new bindings unless you choose Other hosts use `crosshead quickstart --adapter pi|omp|hermes|opencode`. The installer downloads one release tarball, checks its SHA-256 against the -installer script, installs three npm dependencies (`@noble/curves`, -`nostr-tools`, `tar`) with install scripts disabled, and writes the wrappers -into `~/.crosshead/bin`. Installed runtimes check the fixed -`https://crosshead.sh` release origin and notify when an update is available. -They do not install remote code unattended. After obtaining the digest from an -independent release channel, install with `crosshead update --sha256 `. -`crosshead update --pin` disables automatic update checks. +installer script, installs the runtime npm dependencies with install scripts +disabled, and writes the wrappers into `~/.crosshead/bin`. + +`crosshead update --auto` enables automatic updates on idle host launches +(the default), checking for a new release about once an hour and retrying failed checks after 30 minutes. Before installing, Crosshead verifies GitHub's signed +build attestation for the exact archive digest and this repository's release +workflow. If verification or download fails, the host still launches and the +update is retried later. `crosshead update --manual` disables automatic +updates. `crosshead update --policy` shows the current setting. The older +`--pin` option remains an alias for `--manual`. + +For a manual install, obtain the digest from an independent release channel +and run `crosshead update --sha256 `. To check that a release matches this source, compare the installer's `RELEASE_SHA256` with `SHA256SUMS` on the matching GitHub release. Public diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 265cbe6..de2ebc8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -88,9 +88,11 @@ npm run typecheck && npm test Compatibility constraints from already-installed clients: - The installer and `crosshead update` read `RELEASE_ID`, `RELEASE_URL` and - `RELEASE_SHA256` from `/install`; the release URL must be on the same origin. - The updater additionally requires the operator to supply that SHA-256 from - an independent channel and never performs unattended installation. + `RELEASE_SHA256` from `/install`. The updater accepts only the official hosted + origin or the matching GitHub release asset. In `auto` mode, the updater + verifies GitHub's signed build attestation, release workflow identity, tag + and archive digest before installing on an idle host launch. In `manual` + mode, the operator supplies the trusted digest independently. - The tarball must contain `package.json`, `package-lock.json` and `dist/runtime/{cli,daemon,local-runtime,codex-adapter,claude-code-adapter,pi-adapter,codex-bridge,codex-hook,claude-code-bridge,claude-code-hook}.js`. Older clients `require()` some of these modules directly during updates. diff --git a/docs/SECURITY-REVIEW.md b/docs/SECURITY-REVIEW.md index df5dfd7..a28db28 100644 --- a/docs/SECURITY-REVIEW.md +++ b/docs/SECURITY-REVIEW.md @@ -63,13 +63,16 @@ from it is in scope. ## Trust boundaries and entry points -1. **Install and self-update.** The production installer still reads release - metadata and the tarball from one TLS origin. The client updater is pinned - to `https://crosshead.sh`, requires a SHA-256 supplied through an independent - channel, validates archive entries and runs - `npm ci --omit=dev --ignore-scripts`. Background checks are notification- - only. See `parseInstallerReleaseMetadata`, `validateRuntimeReleaseArchive` - and `src/runtime/runtime-auto-update.ts`. +1. **Install and self-update.** The production installer reads release metadata + and checks the tarball digest. The updater reads metadata only from + `https://crosshead.sh`. In `auto` mode, an idle host launch verifies a + Sigstore build attestation for the exact digest, GitHub Actions release + workflow and tag before installing. In `manual` mode, the operator supplies + a trusted SHA-256 from an independent channel. Both paths validate archive + entries and run `npm ci --omit=dev --ignore-scripts` with install scripts + disabled. A failed update check does not prevent the host from launching. + See `src/runtime/release-attestation.ts`, `runtime-auto-update.ts`, and + `validateRuntimeReleaseArchive`. 2. **Local daemon HTTP API.** It binds `127.0.0.1` on a configurable port (`src/runtime/local-runtime.ts:2042`). Requests require the `x-onlybots-local-token` header, including `/health`. The federation-status diff --git a/package-lock.json b/package-lock.json index 5bb1469..11c1c88 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,25 @@ { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.13", + "version": "0.5.0-alpha.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.13", + "version": "0.5.0-alpha.14", "license": "Apache-2.0", "dependencies": { "@noble/curves": "^1.9.7", "nostr-tools": "^2.25.5", + "semver": "7.8.6", + "sigstore": "5.0.1", + "snappyjs": "0.7.0", "tar": "^7.5.22" }, "devDependencies": { "@types/node": "^22.20.2", + "@types/semver": "7.8.0", + "@types/snappyjs": "0.7.1", "ajv": "^8.18.0", "typescript": "^5.9.3", "vitest": "^4.1.12" @@ -23,6 +28,15 @@ "node": "^22.23.4 || ^24.22.1 || >=26.12.1" } }, + "node_modules/@gar/promise-retry": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@gar/promise-retry/-/promise-retry-1.0.3.tgz", + "integrity": "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA==", + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", @@ -35,6 +49,12 @@ "node": ">=18.0.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", @@ -81,6 +101,43 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@npmcli/agent": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-5.0.2.tgz", + "integrity": "sha512-EkzGmEsgbQ1rqWkRJe2P0oQHx/ylZozDUNPMXCklLuSFL3GY+QyEfBUjhjCsgGXzh4OGpnHvkboSQgczjP/jJg==", + "license": "ISC", + "dependencies": { + "agent-base": "^9.0.0", + "http-proxy-agent": "^9.0.0", + "https-proxy-agent": "^9.0.0", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^10.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/fs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-6.0.0.tgz", + "integrity": "sha512-AheOs4swKka/XLtht6xxJDPezlQ7K2IYQ9Y8lST4JLDjnralnWuMM9AE2CdVcgQJ5omrXhsRzM7F7aYmeZBvKQ==", + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-5.0.0.tgz", + "integrity": "sha512-3zcN5Q3yEmeyxXBzqB6fXPQFzYa2ROsGFSr69W0ArXIAGJqxl/aFECOVPD2kbkYPm0U/EHxFKgclK3UA9WQg5A==", + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/@oxc-project/types": { "version": "0.155.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", @@ -446,6 +503,80 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@sigstore/bundle": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-5.0.1.tgz", + "integrity": "sha512-7q8DOObFzN+/eQrvL2O0cylDp95ssgBCAomQxSYfGAMO9+q4xceRbg0L3L0G2/8NyideoYCs7HuVxWKCdn/maQ==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.2" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@sigstore/core": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-4.0.1.tgz", + "integrity": "sha512-9v5hRjujn5NXq8o7XFEUgLyAtdr5Iisb4pzM05u3K61IS5q3hP3luWAndk0RkPPLTUFoTbg7Vb84UQ1ZQeajWQ==", + "license": "Apache-2.0", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@sigstore/protobuf-specs": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.5.2.tgz", + "integrity": "sha512-SQqvFMt4V78fdjcDdYX6HbiVSOR4QK3ZgwCa2KOsopAgPIHy1rU5UDUmzLl02r5oyyaYcYHR1hpwDRk/yUe+Mw==", + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/sign": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-5.1.0.tgz", + "integrity": "sha512-obt7Ukh6juytRSKFsUM0keWK/eRbasdkIh7s1ZszFFvCW1eNNeVe14EvQDsmCgfHrV41gN/y2qbAz2IiwUiFjw==", + "license": "Apache-2.0", + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^5.0.1", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.2", + "make-fetch-happen": "^16.0.1", + "proc-log": "^7.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@sigstore/tuf": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-5.0.1.tgz", + "integrity": "sha512-ofwYu9iXeMm85zPh0cauUXzXtIFNfHI1o9Ux1e0Eil6shsbx+8bAe58fhiU1FcHdOIxOkyDhZzD6Gu6uPnzoUg==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.2", + "tuf-js": "^6.0.2" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@sigstore/verify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-4.1.3.tgz", + "integrity": "sha512-V2ik+fLz2YTZOV4USVnjvLJWDjmBMWi7XhFR8CNp1tj7y09OrogDxPZZdbSWXIA7IpenJTyGukIgF2CFtH/8rA==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.1", + "@sigstore/core": "^4.0.1", + "@sigstore/protobuf-specs": "^0.5.2" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -453,6 +584,28 @@ "dev": true, "license": "MIT" }, + "node_modules/@tufjs/canonical-json": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz", + "integrity": "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA==", + "license": "MIT", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@tufjs/models": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-5.0.2.tgz", + "integrity": "sha512-YzKuFwBcH+m4/YIN0magcH5AjgYVnNFUGhP14vCs+Ckanqz86dDn6K0anjjb730Iu6SSqjzXQCo3FzVqYyT+wg==", + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^10.2.6" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -488,6 +641,20 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/snappyjs": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/@types/snappyjs/-/snappyjs-0.7.1.tgz", + "integrity": "sha512-OxjzJ6cQZstysMh6PEwZWmK9qlKZyezHJKOkcUkZDooSFuog2votUEKkxMaTq51UQF3cJkXKQ+XGlj4FSl8JQQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@vitest/expect": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", @@ -601,6 +768,15 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, "node_modules/ajv": { "version": "8.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", @@ -628,6 +804,48 @@ "node": ">=12" } }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/cacache": { + "version": "21.0.2", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-21.0.2.tgz", + "integrity": "sha512-P1W9H2p3vBmvDhk5g/82aKTOxB3RpHK55IdiH2cAjX7Ts0bE/3OJI9F8HHoNTrCqsZq9XM3XB+ZblaDL8Ycd/g==", + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^6.0.0", + "fs-minipass": "^3.0.0", + "glob": "^14.0.3", + "lru-cache": "^11.1.0", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^7.0.2", + "ssri": "^14.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -647,6 +865,19 @@ "node": ">=18" } }, + "node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -654,6 +885,23 @@ "dev": true, "license": "MIT" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -733,6 +981,18 @@ } } }, + "node_modules/fs-minipass": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", + "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -748,6 +1008,83 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/glob": { + "version": "14.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz", + "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^11.0.5", + "minipass": "^7.1.3", + "path-scurry": "^3.0.0" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz", + "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==", + "license": "BSD-2-Clause" + }, + "node_modules/http-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", + "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/https-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -1028,6 +1365,15 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1038,6 +1384,45 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/make-fetch-happen": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-16.0.1.tgz", + "integrity": "sha512-uUv1yxHzaKVVEPfcFeGSNov/Cehjv08ovlY8ImTljgL7Q+SiA0dAYLQ6SYVa2kkKqNj4Y3aZEI7xv2teadie0A==", + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^5.0.0", + "@npmcli/redact": "^5.0.0", + "cacache": "^21.0.0", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^6.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^7.0.0", + "ssri": "^14.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -1047,6 +1432,107 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/minipass-collect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", + "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-fetch": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-6.0.1.tgz", + "integrity": "sha512-wV03kbBre0q+NJLfcUswkG+6vGn/atIdXOMiD0uKIqdWpevHiCFg3ML9V8jolPoKM7H/kmDV9Xsk0j7/FDRyhA==", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.7.tgz", + "integrity": "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-flush/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/minipass-sized": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-2.0.0.tgz", + "integrity": "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA==", + "license": "ISC", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/minizlib": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", @@ -1059,6 +1545,12 @@ "node": ">= 18" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -1078,6 +1570,22 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/nostr-tools": { "version": "2.25.5", "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.25.5.tgz", @@ -1145,6 +1653,34 @@ "node": ">=12.20.0" } }, + "node_modules/p-map": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.1.1.tgz", + "integrity": "sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-scurry": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -1201,6 +1737,32 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/proc-log": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-7.0.0.tgz", + "integrity": "sha512-FYgfaA69XZ93zaXLoMNQ+ViDXGGBgR8aLh03txzcFhV+9xOXx7+8DLCULrKKpR9+GsH9ZfHm82aSUPpozX0Ztg==", + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/proxy-agent-negotiate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", + "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -1245,6 +1807,25 @@ "@rolldown/binding-win32-x64-msvc": "1.2.15" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT", + "optional": true + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -1252,6 +1833,67 @@ "dev": true, "license": "ISC" }, + "node_modules/sigstore": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-5.0.1.tgz", + "integrity": "sha512-LNdyRQ9ex5Nola93z1Xfm9WewHiy1v3XDH8SVizrWzPcGTuHpi3C5U6EQuCNH7Oo7G3j+16cnNf9Vd3VZxpafA==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^5.0.1", + "@sigstore/core": "^4.0.0", + "@sigstore/protobuf-specs": "^0.5.2", + "@sigstore/sign": "^5.1.0", + "@sigstore/tuf": "^5.0.1", + "@sigstore/verify": "^4.1.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/snappyjs": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/snappyjs/-/snappyjs-0.7.0.tgz", + "integrity": "sha512-u5iEEXkMe2EInQio6Wv9LWHOQYRDbD2O9hzS27GpT/lwfIQhTCnHCTqedqHIHe9ZcvQo+9au6vngQayipz1NYw==", + "license": "MIT" + }, + "node_modules/socks": { + "version": "2.8.10", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", + "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-10.1.0.tgz", + "integrity": "sha512-WlMj/67cEJ6MDI1OcsnjuYKDNDoyPCCYZ249kuuXPiMDw9F8PXkVaQ7YWu3siTydfQ/4BEZcvGzu+aYvz7dDCQ==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 20" + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", @@ -1262,6 +1904,18 @@ "node": ">=0.10.0" } }, + "node_modules/ssri": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-14.0.0.tgz", + "integrity": "sha512-jQxKI0yx0ZnTKrqjKkLDV2DXkBQn3k49JVmVqDGcDwKDtGDbImD/GXsq04KD0VVzCQQ9wZJYal3RwR1GzWTSow==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -1336,6 +1990,20 @@ "node": ">=14.0.0" } }, + "node_modules/tuf-js": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-6.0.2.tgz", + "integrity": "sha512-k78oXrR/Ssi2kTXgP0paoQ7efyw/fO2RBgxXnTQTfoyZRM72XuT8D0ylG9NkJgdnYtx4LWo+qpGdpI4o7FIiJA==", + "license": "MIT", + "dependencies": { + "@gar/promise-retry": "^1.0.3", + "@tufjs/models": "5.0.2", + "debug": "^4.4.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", diff --git a/package.json b/package.json index 2cc8b61..da456db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.13", + "version": "0.5.0-alpha.14", "description": "Crosshead local runtime: persistent memory for Claude Code, Codex, Pi, Hermes and OpenCode. CLI, daemon, host adapters and hooks.", "license": "Apache-2.0", "private": true, @@ -33,12 +33,20 @@ "dependencies": { "@noble/curves": "^1.9.7", "nostr-tools": "^2.25.5", + "semver": "7.8.6", + "sigstore": "5.0.1", + "snappyjs": "0.7.0", "tar": "^7.5.22" }, "devDependencies": { "@types/node": "^22.20.2", + "@types/semver": "7.8.0", + "@types/snappyjs": "0.7.1", "ajv": "^8.18.0", "typescript": "^5.9.3", "vitest": "^4.1.12" + }, + "overrides": { + "minimatch": "11.0.8" } } diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index eb2228c..eb42550 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -73,7 +73,7 @@ await tar.t({ const pkg = JSON.parse(text); if (pkg.version !== manifest.version) fail("package.json version does not match manifest"); if (pkg.license !== "Apache-2.0") fail("install package.json must declare Apache-2.0"); - const allowed = new Set(["@noble/curves", "nostr-tools", "tar"]); + const allowed = new Set(["@noble/curves", "nostr-tools", "tar", "sigstore", "snappyjs", "semver"]); for (const dep of Object.keys(pkg.dependencies ?? {})) { if (!allowed.has(dep)) fail(`unexpected runtime dependency ${dep}; review and update the allowlist deliberately`); } diff --git a/src/runtime/claude-code-adapter.ts b/src/runtime/claude-code-adapter.ts index cf97e94..0b21622 100644 --- a/src/runtime/claude-code-adapter.ts +++ b/src/runtime/claude-code-adapter.ts @@ -475,7 +475,7 @@ export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 + ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2 fi exec ${shellQuote(config.claudeBinary)} "$@" `; diff --git a/src/runtime/cli.ts b/src/runtime/cli.ts index 57170bd..a750d81 100644 --- a/src/runtime/cli.ts +++ b/src/runtime/cli.ts @@ -312,7 +312,7 @@ export const runOnlyBotsCtlCli = async ( "crosshead check-updates [--home ] [--channel stable|beta|canary] [--json]", "crosshead apply [--home ] [--manifest ]", "crosshead update --sha256 [--home ] [--no-restart]", - "crosshead update --pin|--auto|--policy [--home ]", + "crosshead update --manual|--auto|--policy [--home ]", "crosshead update [adapter] [--home ] [--channel stable|beta|canary] [--version ]", "crosshead rollback [adapter] --to [--home ]", "crosshead doctor [--home ] [--workspace-root ] [--json]", diff --git a/src/runtime/cli/core.ts b/src/runtime/cli/core.ts index 3cbae19..1dae2f4 100644 --- a/src/runtime/cli/core.ts +++ b/src/runtime/cli/core.ts @@ -2,7 +2,7 @@ import { OnlyBotsLocalRuntimeDaemon, RuntimeAdapterName, RuntimeChannel, Runtime import path from "path"; import { RUNTIME_ADAPTER_NAMES, ensureRuntimeHomeLayout, loadAdapterRecord, loadRuntimeConfig, resolveRuntimeHome } from "../runtime-persistence"; import { billingFromCli } from "./billing"; -import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy } from "../runtime-auto-update"; +import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, withRuntimeUpdateLock } from "../runtime-auto-update"; import { DEFAULT_CHECKOUT_CREDIT_UNITS } from "../billing-remediation"; import { inspectHostHookRegistrations } from "../host-hook-doctor"; import { inspectWorkspaceHooks, workspaceBindingStatus } from "../workspace-hooks"; @@ -53,9 +53,11 @@ export const updateFromCli = async (argv: string[]): Promise => { const { positionals, flags } = parseArgs(argv); const home = typeof flags.home === "string" ? flags.home : undefined; if (flags["check-on-launch"]) return maintainRuntimeBeforeLaunch(home, Number(flags["host-pid"])); - if (flags.pin || flags.auto || flags.policy) { - if (flags.pin && flags.auto) throw new Error("Choose --pin or --auto"); - return JSON.stringify(runtimeUpdatePolicy(home, flags.pin ? "pinned" : flags.auto ? "auto" : undefined), null, 2); + if (flags.manual || flags.pin || flags.auto || flags.policy) { + if (flags.auto && (flags.manual || flags.pin)) throw new Error("Choose --auto or --manual"); + const mode = flags.manual || flags.pin ? "manual" : flags.auto ? "auto" : undefined; + const policy = mode ? await withRuntimeUpdateLock(home, () => runtimeUpdatePolicy(home, mode)) : runtimeUpdatePolicy(home); + return JSON.stringify(policy, null, 2); } const paths = ensureRuntimeHomeLayout(home); const config = loadRuntimeConfig(paths); @@ -76,12 +78,15 @@ export const updateFromCli = async (argv: string[]): Promise => { } if (typeof flags["base-url"] === "string" || typeof flags.baseUrl === "string" || (!versionOverride && typeof flags.channel !== "string")) { - const result = await updateManagedRuntimeRelease(paths.home, { - baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : typeof flags.baseUrl === "string" ? flags.baseUrl : undefined, - trustedSha256: typeof flags.sha256 === "string" ? flags.sha256 : undefined, - restart: !flags["no-restart"], + const result = await withRuntimeUpdateLock(paths.home, async () => { + const updated = await updateManagedRuntimeRelease(paths.home, { + baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : typeof flags.baseUrl === "string" ? flags.baseUrl : undefined, + trustedSha256: typeof flags.sha256 === "string" ? flags.sha256 : undefined, + restart: !flags["no-restart"], + }); + if (runtimeUpdatePolicy(paths.home).mode === "manual") runtimeUpdatePolicy(paths.home, "manual"); + return updated; }); - if (runtimeUpdatePolicy(paths.home).mode === "pinned") runtimeUpdatePolicy(paths.home, "pinned"); return formatRuntimeReleaseUpdate(result); } diff --git a/src/runtime/codex-adapter.ts b/src/runtime/codex-adapter.ts index a04836c..0d2b51e 100644 --- a/src/runtime/codex-adapter.ts +++ b/src/runtime/codex-adapter.ts @@ -468,7 +468,7 @@ export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 + ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2 fi exec ${shellQuote(config.codexBinary)} --enable hooks "$@" `; diff --git a/src/runtime/local-runtime.ts b/src/runtime/local-runtime.ts index 70e27e0..bab6c51 100644 --- a/src/runtime/local-runtime.ts +++ b/src/runtime/local-runtime.ts @@ -24,6 +24,7 @@ import { spawn } from "child_process"; import { schnorr } from "@noble/curves/secp256k1"; import { finalizeEvent, generateSecretKey, getPublicKey, nip19 } from "nostr-tools"; import * as tar from "tar"; +import semver from "semver"; import { OperatorRuntimePolicyBroker, type OperatorWorkspaceManifest } from "./operator-policy"; import { HOSTED_PI_CONTROLLER_ADAPTER, HOSTED_PI_CONTROLLER_MANIFEST, hostedControllerProcessIsLive, type HostedControllerProcess } from "./hosted-pi-controller-manifest"; @@ -929,12 +930,12 @@ const fetchBuffer = async ( } }; -export const fetchRuntimeReleaseArtifact = async (releaseUrl: string): Promise => { +export const fetchRuntimeReleaseArtifact = async (releaseUrl: string, timeoutMs = 120_000): Promise => { const parsed = new URL(releaseUrl); return fetchBuffer( releaseUrl, RUNTIME_RELEASE_MAX_BYTES, - 120_000, + timeoutMs, parsed.hostname === "github.com" ? { allowedHosts: GITHUB_RELEASE_REDIRECT_HOSTS, maxRedirects: 3 } : undefined @@ -954,8 +955,9 @@ const parseInstallerReleaseMetadata = ( if (!releaseId || !releaseUrl || !releaseSha256) { throw new Error("Installer script did not expose valid release id, URL, and SHA-256 metadata"); } - if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(releaseId) || releaseId === "." || releaseId === "..") { - throw new Error("Installer script exposed an invalid release id"); + const parsedId = releaseId.match(/^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?)-([a-f0-9]{12})$/); + if (!parsedId || !semver.valid(parsedId[1]) || parsedId[2] !== releaseSha256.slice(0, 12)) { + throw new Error("Installer script release ID does not match its version and SHA-256 digest"); } return { releaseId, releaseUrl, releaseSha256 }; }; @@ -1001,7 +1003,7 @@ const validateRuntimeReleaseArchive = async (tarballPath: string): Promise } }; -const runCommand = async (command: string, args: string[], cwd: string): Promise => +export const runRuntimeInstallCommand = async (command: string, args: string[], cwd: string, timeoutMs = 120_000): Promise => await new Promise((resolve, reject) => { const env = { ...process.env }; delete env.NODE_OPTIONS; @@ -1011,20 +1013,36 @@ const runCommand = async (command: string, args: string[], cwd: string): Promise cwd, env, stdio: ["ignore", "pipe", "pipe"], + detached: process.platform !== "win32", }); let stderr = ""; + let timedOut = false; + let closed = false; + const stop = (signal: NodeJS.Signals) => { + if (!child.pid || closed) return; + try { + if (process.platform === "win32") child.kill(signal); + else process.kill(-child.pid, signal); + } catch { /* Already stopped. */ } + }; + const timer = setTimeout(() => { + timedOut = true; + stop("SIGTERM"); + const killTimer = setTimeout(() => stop("SIGKILL"), 2_000); + killTimer.unref(); + }, timeoutMs); child.stdout.resume(); child.stderr.on("data", (chunk: Buffer | string) => { stderr += typeof chunk === "string" ? chunk : chunk.toString("utf8"); if (stderr.length > 1024 * 1024) stderr = stderr.slice(-1024 * 1024); }); - child.on("error", reject); - child.on("close", (code) => { - if (code === 0) { - resolve(); - return; - } - reject(new Error(stderr.trim().length > 0 ? stderr.trim() : `${command} exited with code ${code ?? "unknown"}`)); + child.on("error", error => { closed = true; clearTimeout(timer); reject(error); }); + child.on("close", code => { + closed = true; + clearTimeout(timer); + if (timedOut) reject(new Error("Runtime dependency installation timed out")); + else if (code === 0) resolve(); + else reject(new Error(stderr.trim().length > 0 ? stderr.trim() : `${command} exited with code ${code ?? "unknown"}`)); }); }); @@ -1610,7 +1628,9 @@ export const resolveReleaseUpdateBaseUrl = (paths: RuntimePaths, explicitBaseUrl const downloadRuntimeRelease = async ( paths: RuntimePaths, explicitBaseUrl?: string, - trustedSha256?: string + trustedSha256?: string, + timeoutMs = 120_000, + expectedReleaseId?: string ): Promise => { const baseUrl = resolveReleaseUpdateBaseUrl(paths, explicitBaseUrl); if (!trustedSha256 || !/^[a-f0-9]{64}$/.test(trustedSha256)) { @@ -1621,6 +1641,9 @@ const downloadRuntimeRelease = async ( if (trustedSha256 !== releaseSha256) { throw new Error("Trusted runtime release SHA-256 does not match the official release metadata"); } + if (expectedReleaseId && releaseId !== expectedReleaseId) { + throw new Error("Published runtime release changed after attestation verification"); + } let parsedReleaseUrl: URL; try { parsedReleaseUrl = new URL(releaseUrl); @@ -1641,7 +1664,7 @@ const downloadRuntimeRelease = async ( // Never trust an existing release directory merely because its name matches // server metadata. Re-download and verify the operator-trusted digest before // any file from that directory can be required or launched. - const tarball = await fetchRuntimeReleaseArtifact(releaseUrl); + const tarball = await fetchRuntimeReleaseArtifact(releaseUrl, timeoutMs); const actualSha256 = createHash("sha256").update(tarball).digest("hex"); if (actualSha256 !== releaseSha256) { throw new Error("Runtime release SHA-256 verification failed"); @@ -1671,9 +1694,14 @@ const downloadRuntimeRelease = async ( throw new Error(`Runtime release is missing required file ${requiredPath}`); } } + const expectedVersion = releaseId.slice(0, -13); + let packagedVersion: unknown; + try { packagedVersion = JSON.parse(readFileSync(path.join(stageRoot, "package.json"), "utf8")).version; } + catch { throw new Error("Runtime release package.json is invalid"); } + if (packagedVersion !== expectedVersion) throw new Error("Runtime release package version does not match the release ID"); const npmExecutable = path.join(path.dirname(process.execPath), process.platform === "win32" ? "npm.cmd" : "npm"); if (!existsSync(npmExecutable)) throw new Error(`Runtime update cannot find npm beside ${process.execPath}`); - await runCommand(npmExecutable, ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"], stageRoot); + await runRuntimeInstallCommand(npmExecutable, ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-timeout=15000", "--fetch-retries=1"], stageRoot, timeoutMs); rmSync(releaseRoot, { recursive: true, force: true }); renameSync(stageRoot, releaseRoot); } finally { @@ -1695,11 +1723,12 @@ const downloadRuntimeRelease = async ( }; }; -export const inspectPublishedRuntimeRelease = async (home?: string): Promise<{ installed: string | null; available: string }> => { +export const inspectPublishedRuntimeRelease = async (home?: string): Promise<{ installed: string | null; available: string; sha256: string }> => { const paths = ensureRuntimeHomeLayout(home); const baseUrl = resolveReleaseUpdateBaseUrl(paths); const script = (await fetchBuffer(`${baseUrl}/install`, INSTALLER_SCRIPT_MAX_BYTES, 5000)).toString("utf8"); - return { installed: inspectInstalledRuntimeRelease(paths).releaseId, available: parseInstallerReleaseMetadata(script).releaseId }; + const release = parseInstallerReleaseMetadata(script); + return { installed: inspectInstalledRuntimeRelease(paths).releaseId, available: release.releaseId, sha256: release.releaseSha256 }; }; export const reapplyManagedRuntimeRelease = async ( @@ -1857,13 +1886,15 @@ export const updateManagedRuntimeRelease = async ( baseUrl?: string; trustedSha256?: string; restart?: boolean; + timeoutMs?: number; + expectedReleaseId?: string; } = {} ): Promise => { readWorkspaceHookPolicy(resolveRuntimePaths(home)); const paths = ensureRuntimeHomeLayout(home); const previousRelease = inspectInstalledRuntimeRelease(paths); const specs = await collectManagedAdapterReinstallSpecs(paths); - const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256); + const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256, options.timeoutMs, options.expectedReleaseId); // A release must not leave launchers pointing at a half-applied installation. // Keep credentials, memory and queued writes outside this file-level rollback. const protectedFiles = new Set([ diff --git a/src/runtime/release-attestation.ts b/src/runtime/release-attestation.ts new file mode 100644 index 0000000..85f850f --- /dev/null +++ b/src/runtime/release-attestation.ts @@ -0,0 +1,132 @@ +import { verify } from "sigstore"; +import { uncompress } from "snappyjs"; + +const REPOSITORY = "https://github.com/FriendMachine/crosshead"; +const WORKFLOW = ".github/workflows/release.yml"; +const ISSUER = "https://token.actions.githubusercontent.com"; +const REPOSITORY_ID = 1443704033; +const MAX_API_BYTES = 256 * 1024; +const MAX_BUNDLE_BYTES = 1024 * 1024; +const MAX_BUNDLES = 5; +const VERIFY_DEADLINE_MS = 30_000; +const EXACT_VERSION = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$/; +const SHA256 = /^[a-f0-9]{64}$/; + +type BundleVerifier = typeof verify; +type Fetcher = typeof fetch; + +const fetchBounded = async (url: string, maxBytes: number, fetcher: Fetcher, deadline: number): Promise => { + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error("GitHub release attestation verification timed out"); + let response: Response; + try { + response = await fetcher(url, { + redirect: "error", + signal: AbortSignal.timeout(Math.min(10_000, remaining)), + headers: { Accept: "application/vnd.github+json", "User-Agent": "crosshead-runtime-updater" }, + }); + } catch { + throw new Error("Could not fetch GitHub release attestation"); + } + if (!response.ok || !response.body) throw new Error("GitHub release attestation is unavailable"); + const length = Number(response.headers.get("content-length")); + if (Number.isFinite(length) && length > maxBytes) throw new Error("GitHub release attestation exceeds size limit"); + const reader = response.body.getReader(); + const chunks: Buffer[] = []; + let size = 0; + try { + while (true) { + const part = await reader.read(); + if (part.done) break; + size += part.value.byteLength; + if (size > maxBytes) throw new Error("GitHub release attestation exceeds size limit"); + chunks.push(Buffer.from(part.value)); + } + } finally { + await reader.cancel().catch(() => undefined); + } + return Buffer.concat(chunks); +}; + +const allowedBundleUrl = (raw: string): boolean => { + try { + const url = new URL(raw); + return url.protocol === "https:" && url.hostname === "tmaproduction.blob.core.windows.net" && + url.port === "" && !url.username && !url.password && url.pathname.endsWith(".json.sn") && !url.hash; + } catch { return false; } +}; + +const statementMatches = (bundle: any, version: string, digest: string): boolean => { + if (!bundle || typeof bundle !== "object" || Array.isArray(bundle) || + Object.keys(bundle).length !== 3 || !Object.hasOwn(bundle, "verificationMaterial") || + !Object.hasOwn(bundle, "dsseEnvelope") || Object.hasOwn(bundle, "messageSignature") || + bundle.mediaType !== "application/vnd.dev.sigstore.bundle.v0.3+json" || + bundle.dsseEnvelope?.payloadType !== "application/vnd.in-toto+json" || + typeof bundle.dsseEnvelope.payload !== "string") return false; + let statement: any; + try { statement = JSON.parse(Buffer.from(bundle.dsseEnvelope.payload, "base64").toString("utf8")); } + catch { return false; } + const ref = `refs/tags/v${version}`; + const identity = `${REPOSITORY}/${WORKFLOW}@${ref}`; + return statement?._type === "https://in-toto.io/Statement/v1" && + statement.predicateType === "https://slsa.dev/provenance/v1" && + statement.predicate?.runDetails?.builder?.id === identity && + statement.predicate?.buildDefinition?.buildType === "https://actions.github.io/buildtypes/workflow/v1" && + statement.predicate?.buildDefinition?.externalParameters?.workflow?.repository === REPOSITORY && + statement.predicate?.buildDefinition?.externalParameters?.workflow?.path === WORKFLOW && + statement.predicate?.buildDefinition?.externalParameters?.workflow?.ref === ref && + Array.isArray(statement.subject) && statement.subject.some((subject: any) => + subject?.name === `crosshead-runtime-install-${version}.tgz` && subject?.digest?.sha256 === digest); +}; + +/** Verify the exact release asset was built by this repository's release workflow. + * The hosted install page and GitHub API may select a candidate, but cannot + * authorize code installation without a valid Sigstore bundle and provenance. */ +export const verifyGitHubReleaseAttestation = async ( + version: string, + digest: string, + deps: { fetcher?: Fetcher; verifyBundle?: BundleVerifier } = {} +): Promise => { + if (!EXACT_VERSION.test(version) || !SHA256.test(digest)) throw new Error("Invalid attested release version or digest"); + const fetcher = deps.fetcher ?? fetch; + const verifyBundle = deps.verifyBundle ?? verify; + const deadline = Date.now() + VERIFY_DEADLINE_MS; + const url = `https://api.github.com/repos/FriendMachine/crosshead/attestations/sha256:${digest}?per_page=${MAX_BUNDLES}`; + let listing: any; + try { listing = JSON.parse((await fetchBounded(url, MAX_API_BYTES, fetcher, deadline)).toString("utf8")); } + catch (error) { + if (error instanceof SyntaxError) throw new Error("GitHub release attestation response was invalid"); + throw error; + } + if (!Array.isArray(listing?.attestations) || listing.attestations.length > MAX_BUNDLES) { + throw new Error("GitHub release attestation response was invalid"); + } + const identity = `${REPOSITORY}/${WORKFLOW}@refs/tags/v${version}`; + const escapedIdentity = identity.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + for (const entry of listing.attestations) { + if (entry?.repository_id !== REPOSITORY_ID || typeof entry.bundle_url !== "string" || !allowedBundleUrl(entry.bundle_url)) continue; + try { + const compressed = await fetchBounded(entry.bundle_url, MAX_BUNDLE_BYTES, fetcher, deadline); + const bundle = JSON.parse(Buffer.from(uncompress(compressed, MAX_BUNDLE_BYTES)).toString("utf8")); + if (!statementMatches(bundle, version, digest)) continue; + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error("GitHub release attestation verification timed out"); + let timer: NodeJS.Timeout | undefined; + try { + const signer = await Promise.race([ + verifyBundle(bundle, { + certificateIssuer: ISSUER, + certificateIdentityURI: `^${escapedIdentity}$`, + tlogThreshold: 1, + ctLogThreshold: 1, + timeout: Math.min(5_000, remaining), + retry: 0, + }), + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Sigstore verification timed out")), remaining); }), + ]); + if (signer.identity?.subjectAlternativeName === identity && signer.identity.extensions?.issuer === ISSUER) return; + } finally { if (timer) clearTimeout(timer); } + } catch { /* A malformed or untrusted bundle cannot authorize installation. */ } + } + throw new Error("No valid signed Crosshead release attestation matched the archive digest"); +}; diff --git a/src/runtime/runtime-auto-update.ts b/src/runtime/runtime-auto-update.ts index b36ed8a..0dbcb12 100644 --- a/src/runtime/runtime-auto-update.ts +++ b/src/runtime/runtime-auto-update.ts @@ -1,10 +1,13 @@ import { existsSync, openSync, closeSync, readFileSync, readdirSync, rmSync, mkdirSync, writeFileSync } from "fs"; import path from "path"; import { execFileSync } from "child_process"; -import { ensureRuntimeHomeLayout, loadRuntimeConfig, writeJsonFile, sanitizeLogValue } from "./runtime-persistence"; +import { ensureRuntimeHomeLayout, writeJsonFile, sanitizeLogValue } from "./runtime-persistence"; import { inspectInstalledRuntimeRelease, inspectPublishedRuntimeRelease, updateManagedRuntimeRelease } from "./local-runtime"; +import { verifyGitHubReleaseAttestation } from "./release-attestation"; +import semver from "semver"; -export type RuntimeUpdatePolicy = { mode: "auto" | "pinned"; releaseId: string | null }; +export type RuntimeUpdatePolicy = { mode: "auto" | "manual"; releaseId: string | null }; +const RELEASE_ID = /^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?)-([a-f0-9]{12})$/; const alive = (pid: number): boolean => { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; } }; @@ -14,15 +17,17 @@ export const runtimeUpdatePolicy = (home?: string, mode?: string): RuntimeUpdate const paths = ensureRuntimeHomeLayout(home); const file = path.join(paths.config, "updates.json"); if (mode !== undefined) { - if (mode !== "auto" && mode !== "pinned") throw new Error("Update policy must be auto or pinned"); - const releaseId = inspectInstalledRuntimeRelease(paths).releaseId; - if (mode === "pinned" && !releaseId) throw new Error("Only a published runtime installation can be pinned"); - writeJsonFile(file, { mode, releaseId: mode === "pinned" ? releaseId : null }); + if (mode !== "auto" && mode !== "manual" && mode !== "pinned") throw new Error("Update policy must be auto or manual"); + const normalized = mode === "pinned" ? "manual" : mode; + const releaseId = normalized === "manual" ? inspectInstalledRuntimeRelease(paths).releaseId : null; + writeJsonFile(file, { mode: normalized, releaseId }); + if (normalized === "auto") rmSync(path.join(paths.state, "release-update.json"), { force: true }); } if (!existsSync(file)) return { mode: "auto", releaseId: null }; const policy = read(file); - if (!["auto", "pinned"].includes(policy.mode)) throw new Error("Invalid runtime update policy; automatic updates are disabled until repaired"); - return policy; + if (policy.mode === "pinned") return { mode: "manual", releaseId: typeof policy.releaseId === "string" ? policy.releaseId : null }; + if (policy.mode !== "auto" && policy.mode !== "manual") throw new Error("Invalid runtime update policy; automatic updates are disabled until repaired"); + return { mode: policy.mode, releaseId: typeof policy.releaseId === "string" ? policy.releaseId : null }; }; /** Hooks may never receive Stop after a cancelled turn. Keep their saved state, @@ -57,26 +62,17 @@ export const runtimeHasActiveWork = (home: string, hostRunning = () => true): bo return false; }; -/** A launcher holds its PID for its entire host lifetime (the shell uses exec). - * Concurrent launchers serialize maintenance, and an existing live host prevents - * automatic replacement even while it is idle between prompts. */ -export const maintainRuntimeBeforeLaunch = async (home: string | undefined, hostPid: number, deps = { - inspect: inspectPublishedRuntimeRelease, - update: updateManagedRuntimeRelease, - alive, - nativeHostsRunning: nativeHostProcessesRunning, - now: () => Date.now(), -}): Promise => { - if (!Number.isInteger(hostPid) || hostPid <= 1) throw new Error("A valid launcher PID is required"); +/** Serializes all release installs and update-policy writes across CLI processes. */ +export const withRuntimeUpdateLock = async (home: string | undefined, action: () => Promise | T, ownerAlive = alive): Promise => { const paths = ensureRuntimeHomeLayout(home); - const leases = path.join(paths.state, "host-processes"); - mkdirSync(leases, { recursive: true, mode: 0o700 }); const lock = path.join(paths.state, "release-update.lock"); let fd: number | undefined; const waitStarted = Date.now(); while (fd === undefined) { - try { fd = openSync(lock, "wx", 0o600); writeFileSync(fd, JSON.stringify({ pid: process.pid })); } + let created: number | undefined; + try { created = openSync(lock, "wx", 0o600); writeFileSync(created, JSON.stringify({ pid: process.pid })); fd = created; } catch (error) { + if (created !== undefined) { closeSync(created); rmSync(lock, { force: true }); } if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; // Serialize dead-owner recovery too: two waiters must not unlink a // replacement lock acquired between their reads of the dead owner. @@ -84,13 +80,33 @@ export const maintainRuntimeBeforeLaunch = async (home: string | undefined, host try { recovery = openSync(`${lock}.recovery`, "wx", 0o600); const owner = read(lock); - if (Number.isInteger(owner.pid) && !deps.alive(owner.pid)) rmSync(lock); + if (Number.isInteger(owner.pid) && !ownerAlive(owner.pid)) rmSync(lock); } catch { /* Partial or unavailable locks require conservative waiting. */ } finally { if (recovery !== undefined) { closeSync(recovery); rmSync(`${lock}.recovery`, { force: true }); } } if (Date.now() - waitStarted > 180_000) throw new Error("Crosshead update is still running; retry launching after it finishes"); await new Promise(resolve => setTimeout(resolve, 100)); } } + try { return await action(); } + finally { closeSync(fd); rmSync(lock, { force: true }); } +}; + +/** A launcher holds its PID for its entire host lifetime (the shell uses exec). + * Concurrent launchers serialize maintenance, and an existing live host prevents + * automatic replacement even while it is idle between prompts. */ +export const maintainRuntimeBeforeLaunch = async (home: string | undefined, hostPid: number, deps = { + inspect: inspectPublishedRuntimeRelease, + update: updateManagedRuntimeRelease, + verify: verifyGitHubReleaseAttestation, + alive, + nativeHostsRunning: nativeHostProcessesRunning, + now: () => Date.now(), +}): Promise => { + if (!Number.isInteger(hostPid) || hostPid <= 1) throw new Error("A valid launcher PID is required"); + const paths = ensureRuntimeHomeLayout(home); + const leases = path.join(paths.state, "host-processes"); + mkdirSync(leases, { recursive: true, mode: 0o700 }); + return withRuntimeUpdateLock(paths.home, async () => { try { let activeHost = false; for (const file of readdirSync(leases)) { @@ -101,27 +117,41 @@ export const maintainRuntimeBeforeLaunch = async (home: string | undefined, host } const policy = runtimeUpdatePolicy(paths.home); const installed = inspectInstalledRuntimeRelease(paths).releaseId; - if (policy.mode === "pinned" || (process.env.CROSSHEAD_AUTO_UPDATE ?? process.env.ONLYBOTS_AUTO_UPDATE) === "0" || !installed || loadRuntimeConfig(paths).channel !== "stable") return ""; + if (policy.mode === "manual" || (process.env.CROSSHEAD_AUTO_UPDATE ?? process.env.ONLYBOTS_AUTO_UPDATE) === "0") return ""; + if (!installed) return "Crosshead automatic update skipped: this install does not identify a managed release. Repair it with crosshead update --sha256 ."; const hasActiveWork = () => runtimeHasActiveWork(paths.home, () => deps.nativeHostsRunning(hostPid)); - if (activeHost || hasActiveWork()) return ""; + if (activeHost || deps.nativeHostsRunning(hostPid) || hasActiveWork()) return ""; const stateFile = path.join(paths.state, "release-update.json"); const state = existsSync(stateFile) ? read(stateFile) : {}; - if (deps.now() - (state.checkedAtMs ?? 0) < 12 * 60 * 60 * 1000) return ""; + if (deps.now() - (state.checkedAtMs ?? 0) < (state.status === "failed" ? 30 * 60 * 1000 : 60 * 60 * 1000)) return ""; try { const release = await deps.inspect(paths.home); - writeJsonFile(stateFile, { checkedAtMs: deps.now(), ...release, status: "checked" }); - if (release.available === release.installed) return ""; + if (release.available === installed) { + writeJsonFile(stateFile, { checkedAtMs: deps.now(), ...release, status: "current" }); + return ""; + } + const candidate = release.available.match(RELEASE_ID); + const current = installed.match(RELEASE_ID); + if (!candidate || !current || !semver.valid(candidate[1]) || !semver.valid(current[1]) || + !semver.gt(candidate[1], current[1]) || !/^[a-f0-9]{64}$/.test(release.sha256) || + candidate[2] !== release.sha256.slice(0, 12)) { + throw new Error("Published release metadata is invalid or is not newer than the installed release"); + } // Check again after network I/O for hooks started outside the launcher. - if (hasActiveWork()) return "Crosshead update available; deferred while another turn is active."; - writeJsonFile(stateFile, { checkedAtMs: deps.now(), ...release, status: "available" }); - return `Crosshead update ${release.available.slice(0, 12)} is available. Automatic code installation is disabled until signed releases are deployed; verify the release digest independently, then run: crosshead update --sha256 `; + if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead update available; deferred while another host is active."; + await deps.verify(candidate[1], release.sha256); + if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead verified update available; deferred while another host is active."; + const updated = await deps.update(paths.home, { trustedSha256: release.sha256, timeoutMs: 45_000, expectedReleaseId: release.available }); + if (updated.releaseId !== release.available) throw new Error("Installed release did not match the verified release"); + writeJsonFile(stateFile, { checkedAtMs: deps.now(), installed: release.available, available: release.available, status: "updated" }); + return `Crosshead automatically updated to ${candidate[1]} (signed release verified).`; } catch (error) { const message = sanitizeLogValue(error instanceof Error ? error.message : String(error)); writeJsonFile(stateFile, { checkedAtMs: deps.now(), status: "failed", error: message }); - return `Crosshead automatic update failed: ${message}. Check with crosshead doctor; retry with crosshead update.`; + return `Crosshead automatic update failed: ${message}. Check with crosshead doctor; retry with crosshead update --sha256 .`; } } finally { - try { writeJsonFile(path.join(leases, `${hostPid}.json`), { pid: hostPid, startedAt: new Date().toISOString() }); } - finally { closeSync(fd); rmSync(lock, { force: true }); } + writeJsonFile(path.join(leases, `${hostPid}.json`), { pid: hostPid, startedAt: new Date().toISOString() }); } + }, deps.alive); }; diff --git a/tests/runtime/adapter-utils.test.ts b/tests/runtime/adapter-utils.test.ts index b0b9052..a334bd2 100644 --- a/tests/runtime/adapter-utils.test.ts +++ b/tests/runtime/adapter-utils.test.ts @@ -196,6 +196,25 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" " }, ); + it.each(["codex", "claude"])("launches %s when the update check fails", host => { + const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-failed-update-check-")); + try { + const runtimeHome = path.join(fixture, "runtime"); + const hostBinary = path.join(fixture, "host-stub"); + const wrapper = path.join(fixture, "launcher"); + mkdirSync(path.join(runtimeHome, "bin"), { recursive: true }); + writeFileSync(path.join(runtimeHome, "bin", "onlybotsctl"), "#!/bin/sh\nexit 23\n", { mode: 0o755 }); + writeFileSync(hostBinary, "#!/bin/sh\nprintf 'host launched\n'\n", { mode: 0o755 }); + const common = { marker: "test", adapterVersion: "test", runtimeHome, hostHome: path.join(fixture, "host"), + profileName: "default", installedAt: "now", updatedAt: "now" }; + writeFileSync(wrapper, host === "codex" + ? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" }) + : renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture })); + const output = execFileSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } }); + expect(output).toContain("host launched"); + } finally { rmSync(fixture, { recursive: true, force: true }); } + }); + it("quotes every configured Codex and Claude path as a single shell word", () => { const hostile = `/tmp/host'$(touch /tmp/crosshead-shell-injection)`; const common = { marker: "test", adapterVersion: "test", runtimeHome: hostile, hostHome: hostile, diff --git a/tests/runtime/release-attestation.test.ts b/tests/runtime/release-attestation.test.ts new file mode 100644 index 0000000..080f4c7 --- /dev/null +++ b/tests/runtime/release-attestation.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it, vi } from "vitest"; +import { compress } from "snappyjs"; +import { verifyGitHubReleaseAttestation } from "../../src/runtime/release-attestation"; + +const version = "0.5.0-alpha.14"; +const digest = "b".repeat(64); +const identity = `https://github.com/FriendMachine/crosshead/.github/workflows/release.yml@refs/tags/v${version}`; +const bundleUrl = "https://tmaproduction.blob.core.windows.net/test.json.sn?sig=secret"; +const statement = () => ({ + _type: "https://in-toto.io/Statement/v1", + predicateType: "https://slsa.dev/provenance/v1", + subject: [{ name: `crosshead-runtime-install-${version}.tgz`, digest: { sha256: digest } }], + predicate: { + runDetails: { builder: { id: identity } }, + buildDefinition: { + buildType: "https://actions.github.io/buildtypes/workflow/v1", + externalParameters: { workflow: { + ref: `refs/tags/v${version}`, + repository: "https://github.com/FriendMachine/crosshead", + path: ".github/workflows/release.yml", + } }, + }, + }, +}); +const bundle = (payload = statement()) => ({ + mediaType: "application/vnd.dev.sigstore.bundle.v0.3+json", + verificationMaterial: {}, + dsseEnvelope: { + payloadType: "application/vnd.in-toto+json", + payload: Buffer.from(JSON.stringify(payload)).toString("base64"), + }, +}); +const fixture = (options: { payload?: ReturnType; url?: string; compressed?: Buffer; signer?: string } = {}) => { + const compressed = options.compressed ?? Buffer.from(compress(Buffer.from(JSON.stringify(bundle(options.payload))))); + const fetcher = vi.fn(async (url: string) => new Response( + url.startsWith("https://api.github.com/") + ? JSON.stringify({ attestations: [{ repository_id: 1443704033, bundle_url: options.url ?? bundleUrl }] }) + : compressed + )) as unknown as typeof fetch; + const verifyBundle = vi.fn(async () => ({ identity: { + subjectAlternativeName: options.signer ?? identity, + extensions: { issuer: "https://token.actions.githubusercontent.com" }, + } })) as unknown as typeof import("sigstore").verify; + return { fetcher, verifyBundle }; +}; + +describe("signed GitHub release attestation", () => { + it("accepts only the exact release workflow, archive digest, and Sigstore signer", async () => { + const deps = fixture(); + await verifyGitHubReleaseAttestation(version, digest, deps); + expect(deps.fetcher).toHaveBeenCalledTimes(2); + expect(deps.verifyBundle).toHaveBeenCalledOnce(); + expect(vi.mocked(deps.verifyBundle).mock.calls[0]?.[1]).toMatchObject({ + certificateIssuer: "https://token.actions.githubusercontent.com", + certificateIdentityURI: expect.stringContaining("refs/tags/v0\\.5\\.0-alpha\\.14$"), + tlogThreshold: 1, + ctLogThreshold: 1, + }); + }); + it("rejects a provenance subject or workflow that differs from the target release", async () => { + for (const changed of [ + { ...statement(), subject: [{ name: `crosshead-runtime-install-${version}.tgz`, digest: { sha256: "a".repeat(64) } }] }, + { ...statement(), predicate: { ...statement().predicate, runDetails: { builder: { id: identity.replace("FriendMachine", "attacker") } } } }, + ]) { + const deps = fixture({ payload: changed }); + await expect(verifyGitHubReleaseAttestation(version, digest, deps)).rejects.toThrow("No valid signed"); + expect(deps.verifyBundle).not.toHaveBeenCalled(); + } + }); + it("rejects a mismatched certificate identity or unsafe bundle URL", async () => { + const wrongSigner = fixture({ signer: identity.replace("FriendMachine", "attacker") }); + await expect(verifyGitHubReleaseAttestation(version, digest, wrongSigner)).rejects.toThrow("No valid signed"); + for (const url of ["http://tmaproduction.blob.core.windows.net/test.json.sn", "https://evil.example/test.json.sn", "https://user:secret@tmaproduction.blob.core.windows.net/test.json.sn"]) { + const deps = fixture({ url }); + await expect(verifyGitHubReleaseAttestation(version, digest, deps)).rejects.toThrow("No valid signed"); + expect(deps.fetcher).toHaveBeenCalledTimes(1); + } + }); + it("rejects a bundle with both DSSE and message-signature content", async () => { + const mixed = { ...bundle(), messageSignature: { messageDigest: { algorithm: "SHA2_256", digest: "" }, signature: "" } }; + const deps = fixture({ compressed: Buffer.from(compress(Buffer.from(JSON.stringify(mixed)))) }); + await expect(verifyGitHubReleaseAttestation(version, digest, deps)).rejects.toThrow("No valid signed"); + expect(deps.verifyBundle).not.toHaveBeenCalled(); + }); + it("rejects a compressed bundle that expands beyond the limit before verifying it", async () => { + const deps = fixture({ compressed: Buffer.from(compress(Buffer.alloc(1024 * 1024 + 1))) }); + await expect(verifyGitHubReleaseAttestation(version, digest, deps)).rejects.toThrow("No valid signed"); + expect(deps.verifyBundle).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/runtime/runtime-auto-update.test.ts b/tests/runtime/runtime-auto-update.test.ts index dc6999f..f04b4ae 100644 --- a/tests/runtime/runtime-auto-update.test.ts +++ b/tests/runtime/runtime-auto-update.test.ts @@ -3,7 +3,8 @@ import os from "os"; import path from "path"; import { describe, expect, it, vi } from "vitest"; import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, nativeHostProcessesRunning } from "../../src/runtime/runtime-auto-update"; -import { fetchRuntimeReleaseArtifact, inspectInstalledRuntimeRelease, isAllowedRuntimeReleaseUrl, parseWrapperScriptTarget, resolveReleaseUpdateBaseUrl, updateManagedRuntimeRelease } from "../../src/runtime/local-runtime"; +import { updateFromCli } from "../../src/runtime/cli/core"; +import { fetchRuntimeReleaseArtifact, inspectInstalledRuntimeRelease, isAllowedRuntimeReleaseUrl, parseWrapperScriptTarget, resolveReleaseUpdateBaseUrl, updateManagedRuntimeRelease, runRuntimeInstallCommand } from "../../src/runtime/local-runtime"; import { shellQuote } from "../../src/runtime/adapter-utils"; import { ensureRuntimeHomeLayout, writeJsonFile } from "../../src/runtime/runtime-persistence"; @@ -19,6 +20,7 @@ const setup = () => { const deps = { inspect: vi.fn(async () => ({ installed: "old", available: "new" })), update: vi.fn(async () => ({ releaseId: "new" }) as any), + verify: vi.fn(async () => {}), alive: (pid: number) => pid === 2001, nativeHostsRunning: vi.fn(() => true), now: () => Date.now(), @@ -26,6 +28,23 @@ const setup = () => { return { home, p, deps }; }; +const oldRelease = `0.5.0-alpha.13-${"a".repeat(12)}`; +const newRelease = `0.5.0-alpha.14-${"b".repeat(12)}`; +const newDigest = "b".repeat(64); +const autoSetup = () => { + const fixture = setup(); + const runtime = path.join(fixture.p.libRuntime, oldRelease, "dist", "runtime"); + mkdirSync(runtime, { recursive: true }); + writeFileSync(path.join(runtime, "cli.js"), ""); + writeFileSync(path.join(runtime, "daemon.js"), ""); + writeFileSync(path.join(fixture.p.bin, "onlybotsctl"), `#!/bin/sh\nnode '${path.join(runtime, "cli.js")}' "$@"\n`); + writeFileSync(path.join(fixture.p.bin, "onlybotsd"), `#!/bin/sh\nnode '${path.join(runtime, "daemon.js")}' "$@"\n`); + fixture.deps.inspect.mockResolvedValue({ installed: oldRelease, available: newRelease, sha256: newDigest }); + fixture.deps.update.mockResolvedValue({ releaseId: newRelease } as any); + fixture.deps.nativeHostsRunning.mockReturnValue(false); + return fixture; +}; + describe("published runtime automatic updates", () => { it("detects the single-quoted wrapper emitted by the real installer", () => { const { home, p } = setup(); @@ -37,6 +56,27 @@ describe("published runtime automatic updates", () => { writeFileSync(path.join(p.bin, "onlybotsctl"), `#!/bin/sh\n${shellQuote(process.execPath)} ${shellQuote(target)} "$@"\n`); expect(parseWrapperScriptTarget(path.join(p.bin, "onlybotsctl"))).toBe(target); }); + it("rejects hosted metadata that changes the attested release ID before downloading", async () => { + const { home } = setup(); + const sha256 = "b".repeat(64); + const script = `RELEASE_ID="0.5.0-alpha.15-${sha256.slice(0, 12)}"\nRELEASE_URL="https://crosshead.sh/install/releases/crosshead-runtime.tgz"\nRELEASE_SHA256="${sha256}"\n`; + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(script)); + try { + await expect(updateManagedRuntimeRelease(home, { trustedSha256: sha256, expectedReleaseId: newRelease })) + .rejects.toThrow("changed after attestation"); + expect(fetchMock).toHaveBeenCalledOnce(); + } finally { fetchMock.mockRestore(); } + }); + it("rejects an installer release ID with a digest suffix that does not match metadata", async () => { + const { home } = setup(); + const sha256 = "b".repeat(64); + const script = `RELEASE_ID="0.5.0-alpha.14-${"a".repeat(12)}"\nRELEASE_URL="https://crosshead.sh/install/releases/crosshead-runtime.tgz"\nRELEASE_SHA256="${sha256}"\n`; + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(script)); + try { + await expect(updateManagedRuntimeRelease(home, { trustedSha256: sha256 })).rejects.toThrow("release ID does not match"); + expect(fetchMock).toHaveBeenCalledOnce(); + } finally { fetchMock.mockRestore(); } + }); it("rejects wrapper command substitution and custom executable update origins", async () => { const { home, p } = setup(); writeFileSync(path.join(p.bin, "onlybotsctl"), '#!/bin/sh\nnode "$(touch /tmp/owned)" "$@"\n'); @@ -147,31 +187,43 @@ describe("published runtime automatic updates", () => { expect(fetchMock).toHaveBeenCalledTimes(4); fetchMock.mockRestore(); }); - it("checks on the next idle launch, reports a trusted-install command, and throttles repeated checks", async () => { - const { home, deps } = setup(); - expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("crosshead update --sha256 "); + it("installs a signed newer release on an idle launch and throttles subsequent checks", async () => { + const { home, deps } = autoSetup(); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("automatically updated"); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).toHaveBeenCalledTimes(1); - expect(deps.update).not.toHaveBeenCalled(); + expect(deps.verify).toHaveBeenCalledExactlyOnceWith("0.5.0-alpha.14", newDigest); + expect(deps.update).toHaveBeenCalledExactlyOnceWith(home, { trustedSha256: newDigest, timeoutMs: 45_000, expectedReleaseId: newRelease }); + }); + it("offers auto and manual CLI settings and migrates the legacy pinned mode", async () => { + const { home, p, deps } = autoSetup(); + expect(JSON.parse(await updateFromCli(["--manual", "--home", home]))).toEqual({ mode: "manual", releaseId: oldRelease }); + await maintainRuntimeBeforeLaunch(home, 2000, deps); + expect(deps.inspect).not.toHaveBeenCalled(); + writeJsonFile(path.join(p.config, "updates.json"), { mode: "pinned", releaseId: oldRelease }); + expect(runtimeUpdatePolicy(home)).toEqual({ mode: "manual", releaseId: oldRelease }); + expect(JSON.parse(await updateFromCli(["--auto", "--home", home]))).toEqual({ mode: "auto", releaseId: null }); + await maintainRuntimeBeforeLaunch(home, 2000, deps); + expect(deps.update).toHaveBeenCalledOnce(); }); - it("pins the installed release and permits switching back to automatic updates", async () => { - const { home, deps } = setup(); - expect(runtimeUpdatePolicy(home, "pinned")).toEqual({ mode: "pinned", releaseId: "old" }); + it("rechecking auto explicitly clears a previous update check cooldown", async () => { + const { home, p, deps } = autoSetup(); + writeJsonFile(path.join(p.state, "release-update.json"), { checkedAtMs: Date.now(), status: "current" }); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).not.toHaveBeenCalled(); runtimeUpdatePolicy(home, "auto"); await maintainRuntimeBeforeLaunch(home, 2000, deps); - expect(deps.inspect).toHaveBeenCalledOnce(); - expect(deps.update).not.toHaveBeenCalled(); + expect(deps.update).toHaveBeenCalledOnce(); }); it.each(["codex", "claude-code"])("defers while %s has an active hooked turn", async host => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); writeJsonFile(path.join(p.state, `${host}-hook.json`), { activeTurns: { active: { turnId: "t" } } }); + deps.nativeHostsRunning.mockReturnValue(true); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).not.toHaveBeenCalled(); }); it("defers for a live idle host, but removes dead process leases", async () => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); const leases = path.join(p.state, "host-processes"); mkdirSync(leases); writeJsonFile(path.join(leases, "2001.json"), { pid: 2001 }); await maintainRuntimeBeforeLaunch(home, 2000, deps); @@ -179,28 +231,28 @@ describe("published runtime automatic updates", () => { deps.alive = () => false; await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).toHaveBeenCalledOnce(); - expect(deps.update).not.toHaveBeenCalled(); + expect(deps.update).toHaveBeenCalledOnce(); }); it("reports an update after an interrupted host exits without deleting its saved hook state", async () => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); const file = path.join(p.state, "codex-hook.json"); writeJsonFile(file, { activeTurns: { interrupted: { turnId: "old" } } }); const before = readFileSync(file, "utf8"); deps.nativeHostsRunning.mockReturnValue(false); - expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("is available"); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("automatically updated"); expect(readFileSync(file, "utf8")).toBe(before); }); it("waits for queued writes even when the interrupted host has exited", async () => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); writeJsonFile(path.join(p.state, "queue.json"), { items: [{}] }); deps.nativeHostsRunning.mockReturnValue(false); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.update).not.toHaveBeenCalled(); }); it("rechecks legacy host liveness after inspecting the release", async () => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); writeJsonFile(path.join(p.state, "codex-hook.json"), { activeTurns: { old: {} } }); - deps.nativeHostsRunning.mockReturnValueOnce(false).mockReturnValue(true); + deps.nativeHostsRunning.mockReturnValueOnce(false).mockReturnValueOnce(false).mockReturnValue(true); expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("deferred"); expect(deps.update).not.toHaveBeenCalled(); }); @@ -213,29 +265,85 @@ describe("published runtime automatic updates", () => { expect(nativeHostProcessesRunning(2000, () => { throw new Error("ps unavailable"); })).toBe(true); }); it("does not replace a release already current", async () => { - const { home, deps } = setup(); deps.inspect.mockResolvedValue({ installed: "old", available: "old" }); + const { home, deps } = autoSetup(); deps.inspect.mockResolvedValue({ installed: oldRelease, available: oldRelease, sha256: "a".repeat(64) }); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.update).not.toHaveBeenCalled(); }); it("continues offline and records a throttled failure instead of blocking every launch", async () => { - const { home, deps } = setup(); deps.inspect.mockRejectedValue(new Error("offline")); + const { home, deps } = autoSetup(); deps.inspect.mockRejectedValue(new Error("offline")); expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("offline"); await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).toHaveBeenCalledOnce(); expect(deps.update).not.toHaveBeenCalled(); }); it("rechecks active work after fetching release metadata", async () => { - const { home, p, deps } = setup(); - deps.inspect.mockImplementation(async () => { writeJsonFile(path.join(p.state, "queue.json"), { items: [{}] }); return { installed: "old", available: "new" }; }); + const { home, p, deps } = autoSetup(); + deps.inspect.mockImplementation(async () => { writeJsonFile(path.join(p.state, "queue.json"), { items: [{}] }); return { installed: oldRelease, available: newRelease, sha256: newDigest }; }); expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("deferred"); expect(deps.update).not.toHaveBeenCalled(); }); + it("never installs when the signed attestation cannot be verified", async () => { + const { home, p, deps } = autoSetup(); + deps.verify.mockRejectedValue(new Error("untrusted signature")); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("untrusted signature"); + expect(deps.update).not.toHaveBeenCalled(); + expect(JSON.parse(readFileSync(path.join(p.state, "release-update.json"), "utf8")).status).toBe("failed"); + }); + it.each([ + { available: `0.5.0-alpha.12-${"b".repeat(12)}`, sha256: newDigest }, + { available: `0.5.0-alpha.13-${"b".repeat(12)}`, sha256: newDigest }, + { available: newRelease, sha256: "c".repeat(64) }, + ])("rejects rollback, same-version replacement, or a release-ID digest mismatch", async release => { + const { home, deps } = autoSetup(); + deps.inspect.mockResolvedValue({ installed: oldRelease, ...release }); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("metadata is invalid"); + expect(deps.verify).not.toHaveBeenCalled(); + expect(deps.update).not.toHaveBeenCalled(); + }); + it("defers when a native host starts during signature verification without hook state", async () => { + const { home, deps } = autoSetup(); + deps.nativeHostsRunning.mockReturnValueOnce(false).mockReturnValueOnce(false).mockReturnValue(true); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("deferred"); + expect(deps.verify).toHaveBeenCalledOnce(); + expect(deps.update).not.toHaveBeenCalled(); + }); + it("defers when active work begins during signature verification", async () => { + const { home, p, deps } = autoSetup(); + deps.verify.mockImplementation(async () => { writeJsonFile(path.join(p.state, "queue.json"), { items: [{}] }); }); + expect(await maintainRuntimeBeforeLaunch(home, 2000, deps)).toContain("deferred"); + expect(deps.update).not.toHaveBeenCalled(); + }); + it("defers automatic installs while a different native host is running even without a lease", async () => { + const { home, deps } = autoSetup(); + deps.nativeHostsRunning.mockReturnValue(true); + await maintainRuntimeBeforeLaunch(home, 2000, deps); + expect(deps.inspect).not.toHaveBeenCalled(); + }); + it("serializes policy changes with a running automatic install", async () => { + const { home, deps } = autoSetup(); + let finish!: (value: any) => void; + deps.update.mockImplementation(() => new Promise(resolve => { finish = resolve; })); + const launch = maintainRuntimeBeforeLaunch(home, 2000, deps); + await vi.waitFor(() => expect(deps.update).toHaveBeenCalledOnce()); + let changed = false; + const manual = updateFromCli(["--manual", "--home", home]).then(() => { changed = true; }); + await new Promise(resolve => setTimeout(resolve, 30)); + expect(changed).toBe(false); + finish({ releaseId: newRelease }); + await launch; + await manual; + expect(runtimeUpdatePolicy(home).mode).toBe("manual"); + }); + it("bounds a stalled dependency installer and reaps its child", async () => { + await expect(runRuntimeInstallCommand(process.execPath, ["-e", "setInterval(() => {}, 1000)"], process.cwd(), 100)) + .rejects.toThrow("timed out"); + }); it("serializes concurrent launchers recovering a dead updater lock", async () => { - const { home, p, deps } = setup(); + const { home, p, deps } = autoSetup(); deps.alive = pid => pid === process.pid || pid === 2000 || pid === 2001; writeJsonFile(path.join(p.state, "release-update.lock"), { pid: 999999 }); await Promise.all([maintainRuntimeBeforeLaunch(home, 2000, deps), maintainRuntimeBeforeLaunch(home, 2001, deps)]); expect(deps.inspect).toHaveBeenCalledOnce(); - expect(deps.update).not.toHaveBeenCalled(); + expect(deps.update).toHaveBeenCalledOnce(); }); });