From f49907f42cf122edd4f36782adeb52ff15d42814 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:42:28 -0500 Subject: [PATCH] Isolate pinned Cursor ACP configuration and preserve typed failures Co-Authored-By: Paperclip --- .../runner-cursor-capabilities.md | 57 +++++++++++- .../cursor-distributions.json | 18 ++-- .../scripts/cursor-runtime-patch.mjs | 58 +++++++++++++ .../materialize-cursor-distribution.mjs | 9 +- .../materialize-cursor-distribution.test.mjs | 31 ++++++- .../scripts/qualify-cursor-runtime-patch.mjs | 86 +++++++++++++++++++ .../src/drivers/acpx/cursor-installation.ts | 6 +- .../runtime-patch-initialization.json | 29 +++++++ .../runtime-patch-offline-proof.json | 50 +++++++++++ 9 files changed, 327 insertions(+), 17 deletions(-) create mode 100644 packages/paperclip-runner/scripts/cursor-runtime-patch.mjs create mode 100644 packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs create mode 100644 packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json create mode 100644 packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json diff --git a/doc/architecture/runner-cursor-capabilities.md b/doc/architecture/runner-cursor-capabilities.md index d08fa048837..cbaadb2e709 100644 --- a/doc/architecture/runner-cursor-capabilities.md +++ b/doc/architecture/runner-cursor-capabilities.md @@ -1,6 +1,6 @@ # Cursor ACP capability inventory -Evidence date: 2026-09-28. Candidate: `2026.09.26-dd393fe`. This profile is **not live-qualified**. One authorized task-context prompt on the initial free account returned an upgrade requirement, invoked no semantic tools, and supplied no usage receipt. Its cost is unknown; the account dashboard remained unchanged at coarse precision. The user then selected another account, whose exact-model local Runner Eval passed task-context and history tools with clean terminal settlement. Its dashboard attributed 56K rounded tokens to included usage and no incremental charge; ACP still supplied no token or dollar receipt. The local Product hello subsequently passed through the real browser, server, database, native runner, and authenticated completion tool. A second local Product case passed file creation, editing, command validation, an independent exact-byte matcher, and visible workspace artifact presentation. The merged-source local Product question and revision-bound Plan approval also passed browser response and semantic-tool continuation. A serialized follow-up passed pending semantic-question recovery across a server restart. A verified native ACP probe also denied a shell write before any observed side effect. Native Cursor questions/plans and their recovery, durable permission presentation, interruption, and Daytona execution remain required qualification gates. +Evidence updated: 2026-09-29. Candidate: `2026.09.26-dd393fe`. This profile is **not live-qualified**. One authorized task-context prompt on the initial free account returned an upgrade requirement, invoked no semantic tools, and supplied no usage receipt. Its cost is unknown; the account dashboard remained unchanged at coarse precision. The user then selected another account, whose exact-model local Runner Eval passed task-context and history tools with clean terminal settlement. Its dashboard attributed 56K rounded tokens to included usage and no incremental charge; ACP still supplied no token or dollar receipt. The local Product hello subsequently passed through the real browser, server, database, native runner, and authenticated completion tool. A second local Product case passed file creation, editing, command validation, an independent exact-byte matcher, and visible workspace artifact presentation. The merged-source local Product question and revision-bound Plan approval also passed browser response and semantic-tool continuation. A serialized follow-up passed pending semantic-question recovery across a server restart. A verified native ACP probe also denied a shell write before any observed side effect. Native Cursor questions/plans and their recovery, durable permission presentation, interruption, and Daytona execution remain required qualification gates. The reference is the runner's Codex app-server integration and its closed thread-item inventory in `src/provider-events.ts`. Cursor ACP and its private extension methods are the transport; the legacy Cursor adapter is unchanged. @@ -41,7 +41,7 @@ The reference is the runner's Codex app-server integration and its closed thread | Available commands | `available_commands_update`, including skills/slash commands | ACPX persists command metadata; runner canonical mapper deliberately emits no display event | Command picker and bounded command-discovery surface are not implemented | | Session metadata | `session_info_update` title after automatic naming | Capability documented | Runner owns normalized session identity; provider title is currently not surfaced | | Prompt media | Image=true, audio=false, embeddedContext=false in observed initialize | The shared runner turn contract accepts text only; it does not forward image attachment blocks to ACP | P1: implement bounded, validated attachment-to-ACP conversion with capability checks, then qualify the exact model. Audio/embedded context are explicitly unsupported by this advertisement | -| MCP and semantic tools | Session MCP injection supports stdio/HTTP/SSE; user/project config also loaded | Runner-owned authenticated MCP bridge only; fail closed on ambient project MCP | Exact tool discovery and company/token boundary remain live tests | +| MCP and semantic tools | Session MCP injection supports stdio/HTTP/SSE; user/project config also loaded | Runner-owned authenticated MCP bridge only; the owned distribution patch never initializes ambient MCP | Exact tool discovery and company/token boundary remain live tests | | Usage/cost | No `usage_update`/token-usage emission found in pinned ACP implementation; prompt result contains stopReason | Must report usage unavailable, never zero or estimates presented as actual | Dollar accounting unavailable without another explicit measured source. Live spend needs a measurable bound before starting | | Reviews, compaction, hooks, memory | Native mode changes, hooks present internally; no dedicated ACP counterparts to Codex context/hook/memory lifecycle found | No fabricated event families | Distinguish confirmed absence of ACP event mapping from unverified native internals | | Goal controls / lineage | No ACP goal or fork lineage protocol found | Unsupported | No equivalent of Codex native goals/thread lineage | @@ -54,7 +54,7 @@ Question and plan requests lack a session ID. The shared hook binds them to the Fixed launch arguments are `--disable-project-configs --disable-auto-update acp`, using the verified bundled Node and absolute verified `index.js`. Private HOME/XDG roots are required together with CURSOR_CONFIG_DIR, CURSOR_DATA_DIR, disabled compilation caching, `AGENT_CLI_CREDENTIAL_STORE=memory`, and `NO_OPEN_BROWSER=1`. Only explicitly bound CURSOR_API_KEY or CURSOR_AUTH_TOKEN may enter. The controller creates a provider/session-scoped credential-name binding from the explicit task environment, ignoring inherited or caller-supplied markers. Rust forwards it through the closed sidecar environment boundary. Before host admission, the sidecar rejects missing, stale, wrong-provider or unbound credentials and removes the marker before provider launch. Tests cover this full boundary and preserve legacy credential behavior. Do not use `--force`, `--trust`, or `--approve-mcps` to paper over governance. -`--disable-project-configs` only suppresses `.cursor/cli.json`. It does not suppress project MCP, Cursor/Claude hooks, or installed plugins. `assertCursorWorkspacePolicy` refuses ambient project execution config from the workspace through its nearest Git root, including symlinks and unreadable configuration. Ordinary Claude settings with neither hooks nor plugins remain admissible. Enterprise system hooks are checked too. The host repeats admission checks before native launch. Continuous protection of these config paths during execution remains a qualification requirement. Admission alone cannot prevent a concurrent file mutation. Team-provided remote hooks are another upstream boundary and remain unqualified under restrictive execution. +`--disable-project-configs` only suppresses `.cursor/cli.json`. It does not suppress project MCP, Cursor/Claude hooks, or installed plugins. `assertCursorWorkspacePolicy` refuses ambient project execution config from the workspace through its nearest Git root, including symlinks and unreadable configuration. Ordinary Claude settings with neither hooks nor plugins remain admissible. Enterprise system hooks are checked too. The host repeats admission checks before native launch. The vendor admission check alone cannot prevent a concurrent file mutation. The `paperclip-cursor-isolation-v1` distribution patch now removes local hook loading, asynchronous team hook synchronization, ambient MCP loader initialization, and ambient-client merging from the ACP source. The retained admission check remains defense in depth. This closes those discovery paths independently of filesystem polling; authenticated validation on the patched final runtime remains required. Artifact paths are never automatically read or uploaded. References require a present regular file under the physical workspace, reject traversal and symbolic links, and retain `registered:false`. Private/outside paths are omitted and produce a visible warning. This is metadata validation, not durable file ownership or a replacement for artifact registration checks. @@ -116,7 +116,7 @@ Credential setup uses [Cursor's documented browser login](https://cursor.com/doc `test/fixtures/cursor-acp/authenticated-qualification-attempts.json` retains sanitized per-attempt source, package, daemon, model, timing, cleanup, and cost evidence. The first canonical `get-task-context` attempt used pack source `e5159fb67ad28bf6a691bfa64ffddb332d96f8be`, exact Luna selection, one turn, a 60-second limit, a $0.50 declared envelope inside a $2 reservation, and zero retries. This is a Runner Eval against the mock control plane, not Product E2E or restrictive-permission qualification. -The provider returned only an upgrade requirement and then normal completion. Source inspection of pinned `5672.index.js` confirms that actionable authentication/entitlement errors are rendered as ordinary assistant text and lose their typed failure before ACP settlement. No text-matching terminal heuristic is used. This is a P1 native-wrapper gap: preserve typed errors upstream or through a verified owned hook. The semantic oracle must still fail a response that did not invoke the required tool. +The provider returned only an upgrade requirement and then normal completion. Source inspection of pinned `5672.index.js` confirms that actionable authentication/entitlement errors are rendered as ordinary assistant text and lose their typed failure before ACP settlement. No text-matching terminal heuristic is used. This was a native-wrapper gap in that unmodified candidate. The owned distribution patch described below preserves those typed errors as failed ACP RPC responses; the historical attempt is unchanged. The semantic oracle must still fail a response that did not invoke the required tool. The replacement-account attempt passed all four canonical `get-task-context` checks at source `01959b8a602683f13706807983f02c3cba9d36a0`, using newly rebuilt daemon source `f77ae83aeb6d802c73f1c955760017ae272eba29`. Both `get_task_context` and `get_task_history` returned successful authenticated semantic results. It took 29.291 seconds and exited cleanly. The Usage page showed a new `gpt-5.6-luna-medium` row at 19:28:55 UTC with 56K tokens, marked Included. Incremental cash was zero for that row; metered dollars remain unavailable. A conservative $0.07 list-price bound assumes at most 57K rounded tokens at the maximum listed $1.20/M rate and is not an invoice amount. There was no retry. @@ -162,3 +162,52 @@ This source audit follows pinned native update → ACPX runtime → `canonicalPr | Session list, model parameters, generic mode control | Confirmed native ACP methods | No operator UI or cross-session discovery API in this integration; recovery loads only the runner-owned exact session | P2: explicit company-scoped controls; authenticated model catalog first | True steering, native queueing, fork/resume, native usage receipts and interactive child questions are absent from this pinned ACP implementation as described above. Their absence is distinct from the implemented-but-unused fields in this table. Remote team hooks, provider-native artifact traces, interruption settlement and authenticated Linux/Daytona behavior remain unverified, not confirmed absent. + +## Owned runtime patch (2026-09-29) + +The candidate now materializes `paperclip-cursor-isolation-v1` on top of the +unchanged vendor `2026.09.26-dd393fe` archives. The materializer first verifies +the archive and **vendor** execution closure, requires exact single-occurrence +source anchors in an input-digest-pinned ACP chunk, applies the owned patch, +then verifies a separately pinned **patched** execution closure. Both identities +remain in the distribution manifest. Unknown, changed, already-patched, or +ambiguously matched source fails closed. The patch does not change the legacy +Cursor adapter or the vendor interactive CLI. + +The ACP shared-services initializer no longer initializes or loads its ambient +MCP loader. Each ACP session starts with an empty client lease and adds only the +explicit session MCP definitions, preserving native last-definition-wins behavior. +It never borrows an earlier or ambient lease, including when the session MCP list +is empty or invalid. Local hook config is an empty snapshot, and the remote team +hook fetch/install/update path cannot start. Newly created project config during +a session therefore cannot enter either removed discovery path. This is source +isolation, not an operating-system sandbox: explicitly allowed native shell +commands still have their granted filesystem/network powers. + +Typed `ActionRequiredError` instances now produce a failed JSON-RPC response +with data schema `paperclip.cursor.provider-error.v1`, kind `action_required`, +and the closed action enum `login`, `upgrade`, `payment`, `config`, or `unknown`. +Login and native `ConnectError` with the Unauthenticated code use ACP error +`-32000`; other action requirements use `-32603`. Provider-private error detail +is not copied into these responses. Ordinary assistant text is never examined to +infer an entitlement failure. Generic provider exceptions outside these typed +branches retain the vendor behavior and remain an upstream audit item. + +`qualify-cursor-runtime-patch.mjs` executes expressions extracted from each actual +input-digest-verified platform chunk. Its poisoned ambient loaders prove no +ambient access while owned MCP, empty sessions, and duplicate definitions work; +it also executes all typed error branches and ignores entitlement-shaped ordinary +errors. The entire patched chunks compile for macOS ARM64/x64 and Linux x64. +`runtime-patch-offline-proof.json` records these checks with zero provider calls. +All three authentic archives separately passed materialization and post-patch +closure verification. Seven materializer tests cover drift, ambiguous anchors, +closure tampering, links, archive tampering, identity consistency, and overwrites. +Both patched macOS binaries also returned ACP v1 from credential-free real-process +initialization and exited after explicit SIGTERM; x64 ran through the ARM host +compatibility layer. `runtime-patch-initialization.json` retains this distinction. +These are offline checks, not authenticated macOS x64 or Linux/Daytona qualification. + +Prior Product/Runner results above measured the earlier unpatched runtime. The +profile must retain pending qualification until the rebuilt final foundation +runtime passes the remaining native interaction, durable approval, cancellation, +recovery, accounting, and authenticated target-platform gates. diff --git a/packages/paperclip-runner/cursor-distributions.json b/packages/paperclip-runner/cursor-distributions.json index 5aee5d15fcd..64280bbb777 100644 --- a/packages/paperclip-runner/cursor-distributions.json +++ b/packages/paperclip-runner/cursor-distributions.json @@ -5,23 +5,27 @@ "darwin-arm64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/arm64/agent-cli-package.tar.gz", "archiveSha256": "538827d96a779bab854a865c8e42859e8e87db34b5f69770261b90fc8cfff191", - "closureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25", + "closureSha256": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25" }, "darwin-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/x64/agent-cli-package.tar.gz", "archiveSha256": "ed1771c44cbf0f8059c67cac0d939e6a60eb730bd066d7dc4cbb14de314cfb6e", - "closureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f", + "closureSha256": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f" }, "linux-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/linux/x64/agent-cli-package.tar.gz", "archiveSha256": "8085fd120f5c71f4eae7fea26a043718e5644e3071e4fab3220a0e58c51f9593", - "closureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9", + "closureSha256": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9" } - } + }, + "patchVersion": "paperclip-cursor-isolation-v1" } diff --git a/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs new file mode 100644 index 00000000000..439529e9ba5 --- /dev/null +++ b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs @@ -0,0 +1,58 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +// This is an owned ACP-only patch of the immutable vendor archive. The legacy +// Cursor adapter and the vendor's interactive CLI are not changed. +export const CURSOR_RUNTIME_PATCH_VERSION = "paperclip-cursor-isolation-v1"; +export const CURSOR_RUNTIME_PATCH_PINS = Object.freeze({ + "darwin-arm64": { file: "5672.index.js", before: "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", after: "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432" }, + "darwin-x64": { file: "9841.index.js", before: "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", after: "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a" }, + "linux-x64": { file: "1699.index.js", before: "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", after: "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a" }, +}); +const digest = value => createHash("sha256").update(value).digest("hex"); + +export function replaceCursorPatchAnchor(source, before, after) { + if (source.split(before).length !== 2) throw new Error("Cursor runtime patch requires exactly one source anchor"); + return source.replace(before, () => after); +} + +/** Never exported as a general-purpose runtime hook; bytes are checked first. */ +export function patchCursorRuntimeSource(source, platform) { + const pin = CURSOR_RUNTIME_PATCH_PINS[platform]; + if (!pin || digest(source) !== pin.before) throw new Error("Cursor runtime patch input digest mismatch"); + const replace = (before, after) => { source = replaceCursorPatchAnchor(source, before, after); }; + // Do not even initialize the ambient loader: load() can start subprocesses. + replace(`te=r.aK.init(X,W.projectRoot,W.projectDir,!1,ee,new ${platform === "darwin-x64" ? "m" : "f"}.v)`, "te=null"); + replace("se=yield te.load(e),ie=new u.uz(se)", "se=new u.i9({}),ie=new u.uz(se)"); + // Session-scoped owned MCP stays functional, including an explicitly empty + // list. It never borrows clients from an earlier session or ambient lease. + const sessionMcp = platform === "darwin-arm64" ? "A" : "x"; + replace("if(0===i.length)return t.mcpLease;", `if(0===i.length)return new ${sessionMcp}.uz(new ${sessionMcp}.i9({}));`); + replace("if(0===r.length)return t.mcpLease;", `if(0===r.length)return new ${sessionMcp}.uz(new ${sessionMcp}.i9({}));`); + replace("u=Object.assign({},yield t.mcpLease.getClients(e))", "u=Object.create(null)"); + // Stop hook discovery at the source, including the asynchronous remote team + // refresh. A filesystem watcher would leave an execution race here. + replace("null!=re&&n.dashboardClient&&(ae=(0,y.a)({dashboardClient:n.dashboardClient,teamId:re}));", "void re;"); + replace("let ue=yield ce.load();", "let ue={errors:[],configDirs:{}};"); + // Use the exact SDK module already present in this verified vendor chunk. + const sdk = [...source.matchAll(/n\("([^"\n]+@agentclientprotocol\/sdk\/dist\/acp\.js)"\)/g)].map(match => match[1]); + if (new Set(sdk).size !== 1) throw new Error("Cursor runtime patch SDK identity is ambiguous"); + const errorType = `n(${JSON.stringify(sdk[0])}).GI`; + const oldAction = 'if(e instanceof r.ao){const t=null!==(u={login:"Please sign in to continue",upgrade:"Upgrade your plan to continue",payment:"Add a payment method to continue",config:"Check your settings to continue"}[e.action])&&void 0!==u?u:e.message;return void(yield this.sendAgentMessageChunk(`\\n\\n${t}`))}'; + const newAction = `if(e instanceof r.ao){const action=["login","upgrade","payment","config"].includes(e.action)?e.action:"unknown";throw new (${errorType})(action==="login"?-32000:-32603,"Cursor provider action required: "+action,{schema:"paperclip.cursor.provider-error.v1",kind:"action_required",action})}`; + replace(oldAction, newAction); + replace('if(e instanceof g.T&&e.code===m.C.Unauthenticated)return void(yield this.sendAgentMessageChunk("\\n\\nError: [unauthenticated] Backend rejected authentication. Verify this is a User API Key for the same endpoint/environment, then rerun with --debug for request-level auth logs."));'.replace('m.C.Unauthenticated', `${platform === "darwin-x64" ? "f" : "m"}.C.Unauthenticated`), + `if(e instanceof g.T&&e.code===${platform === "darwin-x64" ? "f" : "m"}.C.Unauthenticated)throw new (${errorType})(-32000,"Cursor provider authentication rejected",{schema:"paperclip.cursor.provider-error.v1",kind:"authentication_required"});`); + return source; +} + +export async function applyCursorRuntimePatch(directory, platform) { + const pin = CURSOR_RUNTIME_PATCH_PINS[platform]; + if (!pin) throw new Error("Cursor runtime patch platform is unsupported"); + const path = join(directory, pin.file); + const patched = patchCursorRuntimeSource(await readFile(path, "utf8"), platform); + if (digest(patched) !== pin.after) throw new Error("Cursor runtime patch output digest mismatch"); + await writeFile(path, patched); + return { patchVersion: CURSOR_RUNTIME_PATCH_VERSION, file: pin.file, sha256: pin.after }; +} diff --git a/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs b/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs index ef961305545..c34d99499a7 100644 --- a/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs +++ b/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs @@ -4,6 +4,8 @@ import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile import { dirname, join, resolve, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyCursorRuntimePatch, CURSOR_RUNTIME_PATCH_VERSION } from "./cursor-runtime-patch.mjs"; + const MANIFEST_PATH = fileURLToPath(new URL("../cursor-distributions.json", import.meta.url)); const MAX_ARCHIVE_BYTES = 256 * 1024 * 1024; const MAX_TREE_BYTES = 1024 * 1024 * 1024; @@ -14,7 +16,8 @@ export async function cursorDistribution(platform = process.platform, architectu const manifest = JSON.parse(await readFile(MANIFEST_PATH, "utf8")); const distribution = manifest.platforms[`${platform}-${architecture}`]; if (!distribution) throw new Error(`Cursor has no pinned distribution for ${platform}/${architecture}`); - return { ...distribution, version: manifest.version, platform, architecture }; + if (manifest.patchVersion !== CURSOR_RUNTIME_PATCH_VERSION || !/^[a-f0-9]{64}$/.test(distribution.vendorClosureSha256)) throw new Error("Cursor distribution must pin its owned runtime patch and vendor closure"); + return { ...distribution, version: manifest.version, patchVersion: manifest.patchVersion, platform, architecture }; } /** Hash every runtime file, including bundled Node, native addons and workers. */ @@ -102,6 +105,8 @@ export async function materializePinnedCursorDistribution(options = {}) { const extraction = spawnSync("/usr/bin/tar", ["-xzf", archivePath, "-C", unpacked, "--no-same-owner"], { encoding: "utf8", timeout: 120_000 }); if (extraction.status !== 0) throw new Error("Cursor archive extraction failed"); const packageRoot = join(unpacked, "dist-package"); + await verifyCursorDistribution(packageRoot, { ...distribution, closureSha256: distribution.vendorClosureSha256 }); + await applyCursorRuntimePatch(packageRoot, `${distribution.platform}-${distribution.architecture}`); const closure = await verifyCursorDistribution(packageRoot, distribution); // Record the pinned inventory for a later runtime lease. Its digest must be // checked against the checked-in distribution pin before trusting entries. @@ -109,7 +114,7 @@ export async function materializePinnedCursorDistribution(options = {}) { for (const entry of closure.entries) await chmod(join(packageRoot, ...entry.path.split("/")), entry.executable ? 0o500 : 0o400); await chmod(packageRoot, 0o700); await rename(packageRoot, destination); - return { version: distribution.version, platform: distribution.platform, architecture: distribution.architecture, destination, executable: join(destination, distribution.executable), entrypoint: join(destination, distribution.entrypoint), archiveSha256: distribution.archiveSha256, closureSha256: closure.sha256 }; + return { version: distribution.version, patchVersion: distribution.patchVersion, platform: distribution.platform, architecture: distribution.architecture, destination, executable: join(destination, distribution.executable), entrypoint: join(destination, distribution.entrypoint), archiveSha256: distribution.archiveSha256, closureSha256: closure.sha256 }; } finally { await rm(temporary, { recursive: true, force: true }); } } diff --git a/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs index 14b45bf10a9..529f3c43f65 100644 --- a/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs @@ -1,10 +1,12 @@ import assert from "node:assert/strict"; -import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { cursorDistribution, cursorDistributionClosure, materializePinnedCursorDistribution, verifyCursorDistribution } from "./materialize-cursor-distribution.mjs"; +import { CURSOR_RUNTIME_PATCH_VERSION, CURSOR_RUNTIME_PATCH_PINS, patchCursorRuntimeSource, replaceCursorPatchAnchor } from "./cursor-runtime-patch.mjs"; + const roots = []; afterEach(async () => { await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); }); async function fixture() { const path = await mkdtemp(join(tmpdir(), "cursor-distribution-test-")); roots.push(path); return path; } @@ -15,6 +17,9 @@ test("pins complete archives and closures for every supported platform", async ( assert.equal(distribution.version, "2026.09.26-dd393fe"); assert.match(distribution.archiveSha256, /^[a-f0-9]{64}$/); assert.match(distribution.closureSha256, /^[a-f0-9]{64}$/); + assert.match(distribution.vendorClosureSha256, /^[a-f0-9]{64}$/); + assert.notEqual(distribution.closureSha256, distribution.vendorClosureSha256); + assert.equal(distribution.patchVersion, CURSOR_RUNTIME_PATCH_VERSION); assert.equal(distribution.url, `https://downloads.cursor.com/lab/${distribution.version}/${platform}/${architecture}/agent-cli-package.tar.gz`); } await assert.rejects(cursorDistribution("linux", "arm64"), /no pinned distribution/); @@ -52,3 +57,27 @@ test("refuses to overwrite any existing destination", async () => { const root = await fixture(); await writeFile(join(root, "existing"), "keep"); await assert.rejects(materializePinnedCursorDistribution({ destination: join(root, "existing") }), /already exists/); }); + + +test("the isolation patch refuses unsupported, drifted, missing or repeated vendor bytes", () => { + assert.throws(() => patchCursorRuntimeSource("not vendor bytes", "darwin-arm64"), /input digest mismatch/); + assert.throws(() => patchCursorRuntimeSource("not vendor bytes", "linux-arm64"), /input digest mismatch/); + assert.throws(() => replaceCursorPatchAnchor("absent", "anchor", "replacement"), /exactly one/); + assert.throws(() => replaceCursorPatchAnchor("anchor anchor", "anchor", "replacement"), /exactly one/); + assert.equal(replaceCursorPatchAnchor("before anchor after", "anchor", "$&"), "before $& after"); +}); + +test("retained executable vendor proof matches every checked-in patch identity", async () => { + const proof = JSON.parse(await readFile(new URL("../test/fixtures/cursor-acp/runtime-patch-offline-proof.json", import.meta.url), "utf8")); + assert.equal(proof.patchVersion, CURSOR_RUNTIME_PATCH_VERSION); + assert.equal(proof.providerCalls, 0); + assert.equal(proof.qualification, "offline-only"); + assert.deepEqual(proof.platforms.map(row => row.platform).sort(), Object.keys(CURSOR_RUNTIME_PATCH_PINS).sort()); + for (const row of proof.platforms) { + const pin = CURSOR_RUNTIME_PATCH_PINS[row.platform]; + assert.equal(row.sourceSha256, pin.before); + assert.equal(row.patchedSha256, pin.after); + for (const field of ["driftRejected", "fullChunkCompiles", "ownedMcpPreserved", "typedActionErrors", "assistantProseIgnored"]) assert.equal(row[field], true); + for (const field of ["ambientMcpAccesses", "hookConfigReads", "remoteTeamHookFetches"]) assert.equal(row[field], 0); + } +}); diff --git a/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs new file mode 100644 index 00000000000..8cda60b5e9c --- /dev/null +++ b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { runInNewContext } from "node:vm"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { CURSOR_RUNTIME_PATCH_PINS, CURSOR_RUNTIME_PATCH_VERSION, patchCursorRuntimeSource } from "./cursor-runtime-patch.mjs"; + +const runGenerator = (_self, _args, _promise, fn) => (async () => { + const generator = fn(); let value; + while (true) { const next = generator.next(value); if (next.done) return next.value; value = await next.value; } +})(); +const trap = () => { throw new Error("Ambient configuration was accessed"); }; +function segment(source, start, end) { + const first = source.indexOf(start); assert.ok(first >= 0, `Missing ${start}`); + const last = source.indexOf(end, first); assert.ok(last > first, `Missing ${end}`); + return source.slice(first, last); +} + +/** Executes relevant expressions from the actual digest-verified vendor chunk. + * This is offline proof of the patch, not provider/tool availability evidence. */ +export async function qualifyCursorRuntimePatch(vendorRoot) { + const platforms = []; + for (const [platform, pin] of Object.entries(CURSOR_RUNTIME_PATCH_PINS)) { + const original = await readFile(join(vendorRoot, platform, "dist-package", pin.file), "utf8"); + const source = patchCursorRuntimeSource(original, platform); + assert.equal(createHash("sha256").update(source).digest("hex"), pin.after); + assert.throws(() => patchCursorRuntimeSource(original + "\n", platform), /digest mismatch/); + assert.throws(() => patchCursorRuntimeSource(source, platform), /digest mismatch/); + // Compiling the entire chunk catches minifier/scope syntax errors on every + // platform without loading native code or executing provider entrypoints. + const exported = {}; + runInNewContext(source, { exports: exported }); + assert.ok(exported.modules["./src/acp/shared-services.ts"]); + const Lease = class { constructor(value) { this.value = value; } }; + // Both formerly ambient expressions are evaluated with poisoned loaders. + const loader = segment(source, "te=null", ",ne="); + assert.equal(runInNewContext(`let ${loader};te`, { r: { aK: { init: trap } } }), null); + const empty = segment(source, "se=new u.i9({})", ",re=[]"); + assert.ok(runInNewContext(`let ${empty};ie`, { u: { i9: Lease, uz: Lease }, te: { load: trap } }) instanceof Lease); + // Execute the complete pinned session MCP merge function. Any access to the + // ambient lease fails, while owned injection and duplicate semantics survive. + const mcpSource = segment(source, "ee=yield function(e,t,n,o)", "}(e,n,").slice("ee=yield ".length) + "}"; + const make = runInNewContext(`(${mcpSource})`, { + j: runGenerator, R: runGenerator, A: { uz: Lease, i9: Lease, debugLog() {} }, + F: value => value.valid === false ? null : { serverName: value.name, config: value.config }, + x: { debugLog() {}, uz: Lease, i9: Lease }, N: name => `owned:${name}`, + $: async ({ serverName, serverConfig }) => ({ serverName, serverConfig }), + }); + const ambient = { get mcpLease() { return trap(); } }; + assert.deepEqual(Object.keys((await make({}, ambient, { mcpServers: [] }, "/workspace")).value.value), []); + assert.deepEqual(Object.keys((await make({}, ambient, { mcpServers: [{ valid: false }] }, "/workspace")).value.value), []); + const owned = (await make({}, ambient, { mcpServers: [{ name: "paperclip", config: "old" }, { name: "paperclip", config: "owned" }] }, "/workspace")).value.value; + assert.equal(owned.paperclip.serverConfig, "owned"); + assert.deepEqual(Object.keys(owned), ["paperclip"]); + // The remote team fetch and local config read are never evaluated, even + // after a caller mutates their simulated config during this active session. + const localHooks = segment(source, "let ue={errors:[],configDirs:{}};", "const he="); + for (let mutation = 0; mutation < 2; mutation++) { + const hooks = runInNewContext(`${localHooks}ue`, { ce: { load: trap } }); + assert.deepEqual(Object.keys(hooks), ["errors", "configDirs"]); + } + assert.ok(!source.includes("ae=(0,y.a)({dashboardClient:n.dashboardClient,teamId:re})")); + // Exercise typed native errors; ordinary assistant prose is never inspected. + const actionStart = "if(e instanceof r.ao)"; + const errors = segment(source, actionStart, "yield this.sendAgentMessageChunk(`\\n\\nError:"); + class ActionRequired extends Error { constructor(action) { super("private provider detail"); this.action = action; } } + class ConnectError extends Error { constructor() { super("private auth detail"); this.code = 16; } } + class ResponseError extends Error { constructor(code, message, data) { super(message); this.code = code; this.data = data; } } + const evaluate = error => runInNewContext(`(function(){${errors}})()`, { e: error, r: { ao: ActionRequired }, g: { T: ConnectError }, m: { C: { Unauthenticated: 16 } }, f: { C: { Unauthenticated: 16 } }, n: () => ({ GI: ResponseError }) }); + for (const action of ["login", "upgrade", "payment", "config", "other"]) { + assert.throws(() => evaluate(new ActionRequired(action)), error => error instanceof ResponseError + && error.code === (action === "login" ? -32000 : -32603) + && error.data.action === (action === "other" ? "unknown" : action) + && !error.message.includes("private")); + } + assert.throws(() => evaluate(new ConnectError()), error => error.code === -32000 && error.data.kind === "authentication_required"); + evaluate(new Error("Upgrade your plan to continue")); + platforms.push({ platform, file: pin.file, sourceSha256: pin.before, patchedSha256: pin.after, driftRejected: true, fullChunkCompiles: true, ambientMcpAccesses: 0, ownedMcpPreserved: true, hookConfigReads: 0, remoteTeamHookFetches: 0, typedActionErrors: true, assistantProseIgnored: true }); + } + return { schema: "paperclip.cursor.runtime-patch-proof.v1", patchVersion: CURSOR_RUNTIME_PATCH_VERSION, providerCalls: 0, qualification: "offline-only", platforms }; +} +if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) { + assert.equal(process.argv.length, 3, `Usage: node ${fileURLToPath(import.meta.url)} `); + console.log(JSON.stringify(await qualifyCursorRuntimePatch(process.argv[2]), null, 2)); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts index edda80afbbc..3924e814416 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts @@ -8,9 +8,9 @@ import { resolveRunnerProviderAssetsRoot } from "./provider-assets-root.js"; export const CURSOR_PINNED_VERSION = "2026.09.26-dd393fe"; const CLOSURE_PINS = Object.freeze({ - "darwin-arm64": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25", - "darwin-x64": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f", - "linux-x64": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9", + "darwin-arm64": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", + "darwin-x64": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", + "linux-x64": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", }); /** Trusted package assets only: no workspace, PATH, executable override or env root. */ diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json new file mode 100644 index 00000000000..bd751db3ce7 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json @@ -0,0 +1,29 @@ +{ + "schema": "paperclip.cursor.patch-initialize-proof.v1", + "observedAt": "2026-09-29", + "patchVersion": "paperclip-cursor-isolation-v1", + "hostPlatform": "darwin-arm64", + "providerCalls": 0, + "authenticated": false, + "scope": "Direct patched vendor process initialization only; not a rebuilt Runner pack qualification. macOS x64 used host compatibility execution. Processes received SIGTERM after initialization.", + "results": [ + { + "platform": "darwin-arm64", + "providerCalls": 0, + "initialize": "passed", + "protocolVersion": 1, + "exitCode": 143, + "signal": null, + "error": "" + }, + { + "platform": "darwin-x64", + "providerCalls": 0, + "initialize": "passed", + "protocolVersion": 1, + "exitCode": 143, + "signal": null, + "error": "" + } + ] +} diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json new file mode 100644 index 00000000000..d6fc6bc9118 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json @@ -0,0 +1,50 @@ +{ + "schema": "paperclip.cursor.runtime-patch-proof.v1", + "patchVersion": "paperclip-cursor-isolation-v1", + "providerCalls": 0, + "qualification": "offline-only", + "platforms": [ + { + "platform": "darwin-arm64", + "file": "5672.index.js", + "sourceSha256": "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", + "patchedSha256": "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + }, + { + "platform": "darwin-x64", + "file": "9841.index.js", + "sourceSha256": "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", + "patchedSha256": "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + }, + { + "platform": "linux-x64", + "file": "1699.index.js", + "sourceSha256": "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", + "patchedSha256": "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + } + ] +}