From 0dc1ca980d9999638befc05e3d9c542659d3c390 Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 8 Oct 2026 10:08:01 -0500 Subject: [PATCH] fix: install Codex platform binaries from npm instead of bundling them Co-Authored-By: Paperclip --- Dockerfile | 6 +- doc/plans/2026-10-06-default-agent-runner.md | 17 ++ packages/paperclip-runner/README.md | 16 +- .../acpx/installation-integrity.test.ts | 86 ++++++ .../drivers/acpx/installation-integrity.ts | 51 +++- .../acpx/qualified-runtime-artifacts.json | 17 -- .../codex/codex-security-config.test.ts | 11 +- .../grok-public-install-sandbox.test.mjs | 80 +++++- scripts/acpx-patch-packaging.test.mjs | 176 ++++++------ scripts/grok-public-install-sandbox.mjs | 95 ++++++- scripts/prepare-bundled-package.mjs | 252 ++++++++---------- scripts/verify-grok-npm-install.mjs | 13 +- 12 files changed, 544 insertions(+), 276 deletions(-) delete mode 100644 packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json diff --git a/Dockerfile b/Dockerfile index 986282521b2..f0a25cd06b5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -145,8 +145,10 @@ RUN test -f server/dist/index.js || (echo "ERROR: server build output missing" & RUN rm -rf packages/paperclip-runner/runner/target # Vendored Codex ACPX execution binds package authority to server/node_modules. # pnpm links into the workspace store cannot satisfy that boundary. Reuse the -# public-package producer to materialize only this image's existing qualified -# native target, with dependency scripts disabled and runtime authority intact. +# public-package producer for the pinned JavaScript graph, then install only +# this image's qualified native dependency from npm. Keep dependency scripts +# disabled and runtime authority intact. npm release tarballs contain no Codex +# native binaries; the image preinstalls its own runtime dependency. # ARM64 remains usable through legacy adapters while native qualification is # limited to the source-owned supported targets. ARG TARGETARCH diff --git a/doc/plans/2026-10-06-default-agent-runner.md b/doc/plans/2026-10-06-default-agent-runner.md index 4d6a798b19e..69d628f93ed 100644 --- a/doc/plans/2026-10-06-default-agent-runner.md +++ b/doc/plans/2026-10-06-default-agent-runner.md @@ -38,6 +38,23 @@ It does not change agent defaults, the harness picker, provider qualification, database schema, experimental feature policy, or existing agent configuration. The large execution and setup changes stay in the later slices. +### Codex distribution correction, 2026-10-08 + +The user requested removal of pre-bundled Codex binaries from this PR. +Retain the pinned Codex JavaScript graph and let npm install the exact official +platform dependency for the consumer's host. Strip producer-host binaries from +the prepared package as well as the added cross-platform payloads. Docker images +still preinstall their own qualified runtime dependencies. Paperclip's own +runner release assets remain in scope. + +Reopen packaging and installed-consumer verification for this correction. +The green checks at `36d9eb0c3c6b9ca5234432b97349dc7317cfa916` are historical; +they do not verify the changed dependency distribution. Reuse the existing +packaging tests and public npm consumer sandbox to prove an empty Codex binary +payload in Paperclip tarballs, host-only npm resolution, pinned execution, and +unchanged integrity checks. Record the final revision and hosted results in the +canonical PR description before handoff. + ## Evidence and gates | Gate | Status | Evidence | diff --git a/packages/paperclip-runner/README.md b/packages/paperclip-runner/README.md index 2c0c3f5ebb4..319c725212b 100644 --- a/packages/paperclip-runner/README.md +++ b/packages/paperclip-runner/README.md @@ -61,16 +61,18 @@ closure pins are generated from `cursor-distributions.json`. Packaged Codex startup and browser login resolve the Codex CLI from the installed ACP bridge dependency graph. They verify the qualified version and the executable path before launch. An explicit execution command still takes precedence. A -missing or mismatched bundled runtime returns an installation error; it does not +missing or mismatched installed runtime returns an installation error; it does not borrow a different Codex installation from `PATH`. Linux ARM64 retains its existing legacy login path because native execution is not qualified there. -Release packages stage the qualified Codex dependency graph and native platform -artifacts. The Linux artifact digest is recorded in -`src/drivers/acpx/qualified-runtime-artifacts.json`. macOS payloads must match the -pinned package version and host architecture. Release assembly also checks the -source revision and runner binary identities before publication. This packaging -does not change agent defaults or the selected runner of an existing agent. +Release packages retain the pinned Codex JavaScript dependency graph, but do not +bundle Codex native binaries. The published manifest declares the official, +exact-version platform packages as optional dependencies. npm installs the +package for the consumer's operating system and architecture. Docker images +preinstall their qualified runtime dependencies during the image build. +Release assembly checks the source revision and Paperclip runner binary +identities before publication. This packaging does not change agent defaults or +the selected runner of an existing agent. The npm Linux daemon is built for `x86_64-unknown-linux-musl` with static linking. Release validation rejects an ELF interpreter or required shared libraries, then diff --git a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts index 547b12a1d78..c0c0fe4cf16 100644 --- a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts @@ -54,6 +54,92 @@ afterEach(async () => { }); describe("ACPX installation integrity", () => { + it("admits only the declared qualified Codex platform in its npm-hoisted slot", async () => { + const parent = await realpath(await mkdtemp(join(tmpdir(), "paperclip-codex-npm-hoist-"))); + temporaryDirectories.push(parent); + const root = join(parent, "node_modules/@paperclipai/server"); + const runtime = join(root, "node_modules/@openai/codex/package.json"); + const platformRoot = join(parent, "node_modules/@openai/codex-linux-x64"); + const platform = join(platformRoot, "package.json"); + const alias = "npm:@openai/codex@0.160.0-linux-x64"; + const selected = { name: "@paperclipai/server", optionalDependencies: { "@openai/codex-linux-x64": alias } }; + const runtimeMetadata = { name: "@openai/codex", version: "0.160.0", optionalDependencies: selected.optionalDependencies }; + const platformMetadata = { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] }; + await mkdir(dirname(runtime), { recursive: true }); + await mkdir(platformRoot, { recursive: true }); + const reset = async () => Promise.all([ + writeFile(join(root, "package.json"), JSON.stringify(selected)), + writeFile(runtime, JSON.stringify(runtimeMetadata)), + writeFile(platform, JSON.stringify(platformMetadata)), + ]); + await reset(); + const resolver = createAcpxPackageJsonResolver(root); + expect(resolver("@openai/codex-linux-x64", runtime)).toBe(platform); + // Direct provider discovery remains closed; only the selected runtime can + // hand off its explicitly declared, qualified executable dependency. + expect(() => resolver("@openai/codex-linux-x64")).toThrow("outside the selected provider root"); + for (const [file, metadata] of [ + [join(root, "package.json"), { ...selected, optionalDependencies: {} }], + [join(root, "package.json"), { ...selected, optionalDependencies: { "@openai/codex-linux-x64": "latest" } }], + [runtime, { ...runtimeMetadata, version: "0.159.0" }], + [runtime, { ...runtimeMetadata, optionalDependencies: {} }], + [platform, { ...platformMetadata, version: "0.159.0-linux-x64" }], + [platform, { ...platformMetadata, name: "unqualified-provider" }], + [platform, { ...platformMetadata, cpu: ["arm64"] }], + ] as const) { + await writeFile(file, JSON.stringify(metadata)); + expect(() => resolver("@openai/codex-linux-x64", runtime)).toThrow("outside the selected provider root"); + await reset(); + } + const outside = join(parent, "outside-platform"); + await mkdir(outside); + await writeFile(join(outside, "package.json"), JSON.stringify(platformMetadata)); + await rm(platformRoot, { recursive: true }); + await symlink(outside, platformRoot); + expect(() => resolver("@openai/codex-linux-x64", runtime)).toThrow("outside the selected provider root"); + }); + + it.each([false, true])("retains Codex executable version and byte admission for the hoisted platform (stale bundled alias: %s)", async (staleBundledAlias) => { + const parent = await realpath(await mkdtemp(join(tmpdir(), "paperclip-codex-npm-admission-"))); + temporaryDirectories.push(parent); + const root = join(parent, "node_modules/@paperclipai/server"); + const bridge = join(root, "node_modules/@agentclientprotocol/codex-acp"); + const runtime = join(bridge, "node_modules/@openai/codex"); + const platformRoot = join(parent, "node_modules/@openai/codex-linux-x64"); + const native = join(platformRoot, "vendor/x86_64-unknown-linux-musl/bin/codex"); + const optionalDependencies = { "@openai/codex-linux-x64": "npm:@openai/codex@0.160.0-linux-x64" }; + await Promise.all([mkdir(runtime, { recursive: true }), mkdir(dirname(native), { recursive: true })]); + const command = 'process.stdout.write("unexecuted fixture");'; + await Promise.all([ + writeFile(join(root, "package.json"), JSON.stringify({ name: "@paperclipai/server", optionalDependencies })), + writeFile(join(bridge, "package.json"), JSON.stringify({ name: "@agentclientprotocol/codex-acp", version: "1.6.2", bin: "server.js" })), + writeFile(join(bridge, "server.js"), command), + writeFile(join(runtime, "package.json"), JSON.stringify({ name: "@openai/codex", version: "0.160.0", optionalDependencies })), + writeFile(native, "unqualified native bytes", { mode: 0o755 }), + ]); + const profile = { ...resolveQualifiedAcpxProfile("codex", "gpt-5.6-sol"), commandDigest: `sha256:${createHash("sha256").update(command).digest("hex")}` }; + const resolver = createAcpxPackageJsonResolver(root); + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const archSpy = vi.spyOn(process, "arch", "get").mockReturnValue("x64"); + try { + const metadata = { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] }; + await writeFile(join(platformRoot, "package.json"), JSON.stringify(metadata)); + // A stale in-bundle package shadows the correct declared npm slot and + // must fail rather than falling through to the hoisted installation. + if (staleBundledAlias) { + const stale = join(runtime, "node_modules/@openai/codex-linux-x64"); + await mkdir(stale, { recursive: true }); + await writeFile(join(stale, "package.json"), JSON.stringify({ ...metadata, version: "0.159.0-linux-x64" })); + } + await expect(verifyQualifiedAcpxInstallation(profile, resolver)).rejects.toThrow(staleBundledAlias + ? /runtime executable package version mismatch/ + : /digest mismatch/); + } finally { + platformSpy.mockRestore(); + archSpy.mockRestore(); + } + }); + it.each([["linux", "arm64"], ["darwin", "ia32"], ["freebsd", "x64"]] as const)( "rejects the actual Claude runtime probe on unsupported %s %s", async (platform, arch) => { diff --git a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts index f015d60799d..f904f75d393 100644 --- a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts @@ -7,7 +7,7 @@ import { type ChildProcess, type SpawnOptionsWithoutStdio, } from "node:child_process"; -import { constants, existsSync, realpathSync } from "node:fs"; +import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; import { lstat, open, @@ -345,7 +345,8 @@ export function createAcpxPackageJsonResolver( const packageJsonPath = realpathSync( resolvePackageJsonFromIssuer(packageName, canonicalIssuer), ); - if (!pathIsInside(canonicalNodeModules, packageJsonPath)) { + if (!pathIsInside(canonicalNodeModules, packageJsonPath) + && !isDeclaredHoistedCodexPlatform(canonicalRoot, canonicalManifest, canonicalIssuer, packageName, packageJsonPath)) { throw new Error( `ACPX provider package ${packageName} resolves outside the selected provider root`, ); @@ -354,6 +355,52 @@ export function createAcpxPackageJsonResolver( }; } +// npm installs an optional platform alias outside a bundled server graph. +// Admit only the qualified executable package through its declared npm slot; +// all executable bytes still pass the existing digest/no-follow admission. +function isDeclaredHoistedCodexPlatform(root: string, manifest: string, issuer: string, packageName: string, packageJsonPath: string): boolean { + const qualified = QUALIFIED_CODEX_LINUX_X64_RUNTIME; + if (packageName !== qualified.packageName || issuer === manifest) return false; + try { + const selected = readResolverPackageJson(manifest); + const runtime = readResolverPackageJson(issuer); + const optional = (value: Record) => value.optionalDependencies as Record | undefined; + if (selected.name !== "@paperclipai/server" || runtime.name !== qualified.runtimePackageName + || runtime.version !== qualified.runtimePackageVersion + || optional(selected)?.[packageName] !== qualified.dependencyDeclaration + || optional(runtime)?.[packageName] !== qualified.dependencyDeclaration) return false; + if (realpathSync(resolvePackageJsonFromIssuer(packageName, manifest)) !== packageJsonPath) return false; + const declaredSlot = (createRequire(manifest).resolve.paths(packageName) ?? []).some((directory) => { + if (!pathIsInside(dirname(directory), root)) return false; + try { + return realpathSync(directory) === directory + && pathIsInside(directory, packageJsonPath) + && realpathSync(resolve(directory, packageName, "package.json")) === packageJsonPath + && realpathSync(resolve(directory, packageName)) === resolve(directory, packageName); + } catch { return false; } + }); + if (!declaredSlot) return false; + const platform = readResolverPackageJson(packageJsonPath); + return [qualified.packageName, qualified.runtimePackageName].includes(String(platform.name)) + && platform.version === qualified.packageVersion + && Array.isArray(platform.os) && platform.os.includes("linux") + && Array.isArray(platform.cpu) && platform.cpu.includes("x64"); + } catch { return false; } +} + +function readResolverPackageJson(path: string): Record { + const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const before = fstatSync(fd, { bigint: true }); + if (!before.isFile() || before.size < 1n || before.size > BigInt(MAX_PACKAGE_JSON_BYTES)) throw new Error("Invalid provider package manifest"); + const bytes = readFileSync(fd), after = fstatSync(fd, { bigint: true }); + if (bytes.length !== Number(before.size) || !sameIdentity(fileIdentity(before), fileIdentity(after))) throw new Error("Provider package manifest changed during resolution"); + const value: unknown = JSON.parse(bytes.toString("utf8")); + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid provider package metadata"); + return value as Record; + } finally { closeSync(fd); } +} + function resolvePackageJsonFromIssuer( packageName: string, issuerPackageJsonPath: string, diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json b/packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json deleted file mode 100644 index 98e926efc13..00000000000 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schema": "paperclip.acpx-runtime-artifacts.v1", - "codex": { - "platforms": { - "linux-x64": { - "runtimePackageName": "@openai/codex", - "runtimePackageVersion": "0.160.0", - "packageName": "@openai/codex-linux-x64", - "packageVersion": "0.160.0-linux-x64", - "dependencyDeclaration": "npm:@openai/codex@0.160.0-linux-x64", - "relativeExecutable": "vendor/x86_64-unknown-linux-musl/bin/codex", - "executableDigest": "sha256:12eb3e81114588aca3b7998f4f19e8997b056aca08e57a7ca7c8a3ec8c652aad", - "environmentVariable": "CODEX_PATH" - } - } - } -} diff --git a/packages/paperclip-runner/src/drivers/codex/codex-security-config.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-security-config.test.ts index 34a5165cdf3..e9d546c7136 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-security-config.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-security-config.test.ts @@ -32,13 +32,17 @@ describe("Codex security configuration", () => { import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { resolvePinnedCodexCommand } from ${JSON.stringify(new URL("./codex-command.ts", import.meta.url).href)}; + import { codexExecutableReadOnlyRoots } from ${JSON.stringify(new URL("./codex-security-config.ts", import.meta.url).href)}; const root = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-pinned-codex-test-"))); const issuer = join(root, "node_modules/@paperclipai/server/dist/vendor/paperclip-runner/drivers/codex/codex-command.js"); const adapter = join(root, "node_modules/@paperclipai/adapter-codex-local"); const bridge = join(adapter, "node_modules/@agentclientprotocol/codex-acp"); const codex = join(bridge, "node_modules/@openai/codex"); const executable = join(codex, "bin/codex.js"); - const metadata = { name: "@openai/codex", version: "0.160.0", bin: { codex: "bin/codex.js" } }; + const platformName = "@openai/codex-" + process.platform + "-" + process.arch; + const platform = join(root, "node_modules", platformName), vendor = join(platform, "vendor"); + const metadata = { name: "@openai/codex", version: "0.160.0", bin: { codex: "bin/codex.js" }, + optionalDependencies: { [platformName]: "npm:@openai/codex@0.160.0-" + process.platform + "-" + process.arch } }; try { mkdirSync(dirname(issuer), { recursive: true }); mkdirSync(join(codex, "bin"), { recursive: true }); @@ -46,8 +50,13 @@ describe("Codex security configuration", () => { writeFileSync(join(adapter, "server.js"), ""); writeFileSync(join(bridge, "package.json"), JSON.stringify({ name: "@agentclientprotocol/codex-acp", version: "1.6.2" })); writeFileSync(join(codex, "package.json"), JSON.stringify(metadata)); + mkdirSync(vendor, { recursive: true }); + writeFileSync(join(platform, "package.json"), JSON.stringify({ name: "@openai/codex", version: "0.160.0-" + process.platform + "-" + process.arch })); writeFileSync(executable, "#!" + process.execPath + "\\nif (process.argv.slice(2).join(' ') !== '--version') process.exit(9); console.log('codex-cli 0.160.0');\\n", { mode: 0o755 }); assert.equal(resolvePinnedCodexCommand(issuer), executable); + const roots = codexExecutableReadOnlyRoots({ PATH: "/missing-codex-command" }, executable); + assert.ok(roots.includes(vendor), "The npm-hoisted native vendor directory remains readable"); + assert.ok(!roots.includes(platform) && !roots.includes(root), "Hoisting must not expose npm ancestry"); assert.equal(execFileSync(resolvePinnedCodexCommand(issuer), ["--version"], { env: { PATH: "/missing-codex-command" }, encoding: "utf8", timeout: 5_000 }).trim(), "codex-cli 0.160.0"); diff --git a/scripts/__tests__/grok-public-install-sandbox.test.mjs b/scripts/__tests__/grok-public-install-sandbox.test.mjs index b2ffa291e42..7942052cab8 100644 --- a/scripts/__tests__/grok-public-install-sandbox.test.mjs +++ b/scripts/__tests__/grok-public-install-sandbox.test.mjs @@ -4,7 +4,7 @@ import { spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; -import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, grokConsumerDockerArgs, installedCodexProbeSource } from '../grok-public-install-sandbox.mjs'; +import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertInstalledCodexPlatformProvenance, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from '../grok-public-install-sandbox.mjs'; const paths = { assets: '/private/staging/assets', consumer: '/private/staging/consumer', cache: '/private/staging/cache', uid: 1001, gid: 1001 }; const values = (args, flag) => args.flatMap((value, index) => value === flag ? [args[index + 1]] : []); @@ -58,7 +58,28 @@ test('the installed Codex probe exercises the public export and rejects incomple const root = mkdtempSync(join(tmpdir(), 'installed-codex-probe-')); try { const consumer = join(root, 'consumer'); mkdirSync(consumer); - const index = join(consumer, 'index.mjs'), command = join(consumer, 'codex'), probe = join(root, 'probe.mjs'); + const target = `${process.platform}-${process.arch}`; + const platformPath = `node_modules/@openai/codex-${target}`; + const platform = join(consumer, platformPath); mkdirSync(platform, { recursive: true }); + const manifest = { name: '@openai/codex', version: `0.160.0-${target}`, os: [process.platform], cpu: [process.arch] }; + writeFileSync(join(platform, 'package.json'), JSON.stringify(manifest)); + const entry = { name: manifest.name, version: manifest.version, + resolved: `https://registry.npmjs.org/@openai/codex/-/codex-${manifest.version}.tgz`, integrity: `sha512-${Buffer.alloc(64, 1).toString('base64')}` }; + const lock = { lockfileVersion: 3, packages: { [platformPath]: entry } }; + writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock)); + const server = join(consumer, 'node_modules/@paperclipai/server'); + const vendor = join(server, 'dist/vendor/paperclip-runner'), drivers = join(vendor, 'drivers/acpx'); mkdirSync(drivers, { recursive: true }); + writeFileSync(join(server, 'package.json'), JSON.stringify({ name: '@paperclipai/server', type: 'module' })); + const integrity = join(drivers, 'installation-integrity.js'); + const moduleSource = `import assert from 'node:assert/strict'; import { writeFileSync } from 'node:fs'; + export function createAcpxPackageJsonResolver(root, manifest) { assert.equal(root, ${JSON.stringify(server)}); assert.equal(manifest, root + '/package.json'); return () => 'selected-authority'; } + export async function verifyQualifiedAcpxInstallation(profile, resolver) { assert.deepEqual(profile, { agent: 'codex', model: 'gpt-5.4' }); assert.equal(resolver(), 'selected-authority'); + return { openCommand: async () => ({ close: async () => { writeFileSync(${JSON.stringify(join(server, 'lease-closed'))}, 'ok'); } }) }; }`; + writeFileSync(integrity, moduleSource); + writeFileSync(join(drivers, 'qualified-profiles.js'), "export const resolveQualifiedAcpxProfile = (agent, model) => ({ agent, model });"); + const wrapper = join(consumer, 'node_modules/@openai/codex/bin'); mkdirSync(wrapper, { recursive: true }); + writeFileSync(join(wrapper, '../package.json'), JSON.stringify({ name: '@openai/codex', version: '0.160.0' })); + const index = join(vendor, 'index.mjs'), command = join(wrapper, 'codex.js'), probe = join(root, 'probe.mjs'); const executable = version => writeFileSync(command, `#!/bin/sh\n[ "$1" = --version ] || exit 65\nprintf '%s\\n' 'codex-cli ${version}'\n`, { mode: 0o755 }); writeFileSync(probe, installedCodexProbeSource(index, consumer, '0.160.0')); const run = () => spawnSync(process.execPath, [probe], { encoding: 'utf8', timeout: 10_000, env: { PATH: '/usr/bin:/bin', NODE_PATH: '' } }); @@ -66,7 +87,26 @@ test('the installed Codex probe exercises the public export and rejects incomple executable('0.160.0'); let result = run(); assert.equal(result.status, 0, result.stderr); assert.equal(JSON.parse(result.stdout).pinnedCodexCommandVerified, true); + assert.equal(JSON.parse(result.stdout).codexPlatformPackageSource, 'official npm'); + assert.equal(JSON.parse(result.stdout).codexConsumerPlatform, target); + assert.equal(JSON.parse(result.stdout).codexQualifiedInstallationVerified, true); + assert.equal(JSON.parse(result.stdout).codexCommandLeaseVerified, true); + assert.equal(readFileSync(join(server, 'lease-closed'), 'utf8'), 'ok'); assert.equal(JSON.parse(result.stdout).providerCalls, 0); + writeFileSync(integrity, moduleSource.replace('assert.deepEqual(profile,', "throw new Error('qualified executable digest mismatch'); assert.deepEqual(profile,")); + result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /qualified executable digest mismatch/); + writeFileSync(integrity, moduleSource.replace("writeFileSync(", "throw new Error('command lease close failed'); writeFileSync(")); + result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /command lease close failed/); + writeFileSync(integrity, moduleSource); + lock.packages[platformPath].inBundle = true; + writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock)); + result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /downloaded, not bundled/); + delete lock.packages[platformPath].inBundle; + writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock)); + const foreign = join(consumer, 'node_modules/@openai/codex-win32-arm64'); mkdirSync(foreign); + writeFileSync(join(foreign, 'package.json'), JSON.stringify({ name: '@openai/codex', version: '0.160.0-win32-arm64' })); + result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /only the host/); + rmSync(foreign, { recursive: true }); executable('9.9.9'); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /qualified pin/); rmSync(command); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /ENOENT/); const outside = join(root, 'outside'); writeFileSync(outside, '#!/bin/sh\nexit 0\n', { mode: 0o755 }); @@ -75,3 +115,39 @@ test('the installed Codex probe exercises the public export and rejects incomple writeFileSync(index, 'export const unrelated = true;'); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /must export the pinned Codex resolver/); } finally { rmSync(root, { recursive: true, force: true }); } }); + +test('actual tar member checks allow Codex JavaScript but reject nested platform packages and native vendor payloads', () => { + const javascript = ['package/package.json', 'package/node_modules/@openai/codex/package.json', + 'package/node_modules/@openai/codex/bin/codex.js', 'package/dist/vendor/paperclip-runner/index.js']; + assert.doesNotThrow(() => assertNoBundledCodexPayloads(javascript)); + for (const payload of [ + 'package/node_modules/@openai/codex-linux-x64/package.json', + 'package/node_modules/bridge/node_modules/@openai/codex-darwin-arm64/package.json', + 'package/node_modules/@openai/codex-win32-x64/package.json', + 'package/node_modules/@openai/codex/vendor/x86_64-unknown-linux-musl/codex/codex', + 'package/dist/vendor/aarch64-apple-darwin/bin/codex', + 'package/dist/vendor/x86_64-pc-windows-msvc/bin/codex.exe', + ]) assert.throws(() => assertNoBundledCodexPayloads([...javascript, payload]), /must not bundle/); + assert.throws(() => assertNoBundledCodexPayloads(['package/../outside']), /inside the package/); + const source = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8'); + assert.match(source, /assertNoBundledCodexPayloads\(run\('tar', \['-tzf', tarball\]\)/); +}); + +test('consumer provenance rejects bundled, foreign, unpinned and non-official Codex payloads', () => { + const path = 'node_modules/@openai/codex-linux-x64'; + const manifest = { name: '@openai/codex', version: '0.160.0-linux-x64', os: ['linux'], cpu: ['x64'] }; + const entry = { version: manifest.version, resolved: `https://registry.npmjs.org/@openai/codex/-/codex-${manifest.version}.tgz`, + integrity: `sha512-${Buffer.alloc(64, 1).toString('base64')}` }; + const check = (value = entry, installed = [{ path, manifest }]) => assertInstalledCodexPlatformProvenance({ packages: { [path]: value } }, installed, '0.160.0', 'linux-x64'); + assert.equal(check().codexConsumerHostOnly, true); + for (const change of [ + { inBundle: true }, { link: true }, { version: '0.156.1-linux-x64' }, + { resolved: 'https://example.com/@openai/codex/-/codex-0.160.0-linux-x64.tgz' }, + { resolved: 'https://registry.npmjs.org/@openai/codex/-/codex-0.156.1-linux-x64.tgz' }, + { resolved: 'https://user@registry.npmjs.org/@openai/codex/-/codex-0.160.0-linux-x64.tgz' }, + { integrity: undefined }, { integrity: 'sha512-AA==' }, + ]) assert.throws(() => check({ ...entry, ...change })); + assert.throws(() => check(entry, []), /must install its host/); + assert.throws(() => check(entry, [{ path: 'node_modules/@openai/codex-darwin-arm64', manifest }]), /only the host/); + assert.throws(() => check(entry, [{ path, manifest: { ...manifest, name: 'untrusted' } }]), /identity/); +}); diff --git a/scripts/acpx-patch-packaging.test.mjs b/scripts/acpx-patch-packaging.test.mjs index a474cc0af4c..1bd7b283dfd 100644 --- a/scripts/acpx-patch-packaging.test.mjs +++ b/scripts/acpx-patch-packaging.test.mjs @@ -1,6 +1,5 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { createHash } from "node:crypto"; import { existsSync, lstatSync, @@ -25,7 +24,6 @@ import { createBundledInstallManifest, configureBundledProviderOverrides, dockerBundledProviderTarget, - inspectBundledNativeArtifact, materializePublishManifest, mergeBundledProviderGraph, selectBundledDependencyPatches, @@ -35,7 +33,6 @@ import { const rootPackage = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")); const profileData = JSON.parse(await readFile(new URL("../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8")); -const runtimeData = JSON.parse(await readFile(new URL("../packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json", import.meta.url), "utf8")); const nativeTargets = ["linux-x64", "darwin-arm64", "darwin-x64"]; function esbuildFixture(t) { const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-esbuild-"))); @@ -59,21 +56,27 @@ function esbuildFixture(t) { dependencies: { acpx: "0.13.1" }, optionalDependencies: { unrelated: "1.0.0" } }; return { directory, graph, esbuild, producerBinary, publish, writePackage }; } -function nativeFixture(directory, profile, target, data) { - const [os, cpu] = target.split("-"); - const name = `${profile.agentRuntimePackage}-${target}`; - const packageRoot = join(directory, name); - mkdirSync(packageRoot, { recursive: true }); - writeFileSync(join(packageRoot, "package.json"), JSON.stringify({ name, version: `${profile.agentRuntimeVersion}-${target}`, os: [os], cpu: [cpu] })); - const qualification = data[profile.agent].platforms[target]; - const executable = qualification?.relativeExecutable ?? `vendor/${cpu === "arm64" ? "aarch64" : "x86_64"}-apple-darwin/bin/codex`; - const bytes = Buffer.alloc(32); - if (os === "linux") { bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); bytes.writeUInt16LE(62, 18); } - else { bytes.writeUInt32LE(0xfeedfacf, 0); bytes.writeUInt32LE(cpu === "arm64" ? 0x0100000c : 0x01000007, 4); } - mkdirSync(join(packageRoot, executable, ".."), { recursive: true }); - writeFileSync(join(packageRoot, executable), bytes, { mode: 0o755 }); - if (qualification) qualification.executableDigest = `sha256:${createHash("sha256").update(bytes).digest("hex")}`; - return packageRoot; +const codexTargets = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64"]; +const codexOptional = Object.fromEntries(codexTargets.map(target => [`@openai/codex-${target}`, `npm:@openai/codex@0.160.0-${target}`])); +function codexFixture(t) { + const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-codex-"))); + t.after(() => rmSync(directory, { recursive: true, force: true })); + const graph = join(directory, "node_modules"); + const writePackage = (location, metadata) => { + mkdirSync(location, { recursive: true }); writeFileSync(join(location, "package.json"), JSON.stringify(metadata)); return location; + }; + const bridge = writePackage(join(graph, "@agentclientprotocol/codex-acp"), { name: "@agentclientprotocol/codex-acp", version: "1.6.2", dependencies: { "@openai/codex": "0.160.0" } }); + writeFileSync(join(bridge, "index.js"), "export {};\n"); + const runtime = writePackage(join(graph, "@openai/codex"), { name: "@openai/codex", version: "0.160.0", bin: { codex: "bin/codex.js" }, optionalDependencies: codexOptional }); + mkdirSync(join(runtime, "bin")); writeFileSync(join(runtime, "bin/codex.js"), "// official JavaScript fixture, never executed\n"); + mkdirSync(join(runtime, "vendor")); writeFileSync(join(runtime, "vendor/codex"), "producer fallback binary fixture, never executed"); + const producer = writePackage(join(graph, "@openai/codex-linux-x64"), { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] }); + mkdirSync(join(producer, "vendor")); writeFileSync(join(producer, "vendor/codex"), "producer optional binary fixture, never executed"); + const nested = writePackage(join(bridge, "node_modules/@openai/codex-darwin-arm64"), { name: "@openai/codex", version: "0.160.0-darwin-arm64", os: ["darwin"], cpu: ["arm64"] }); + writePackage(join(graph, "unrelated-linux-x64"), { name: "unrelated-linux-x64", version: "1.0.0" }); + const profiles = [{ agent: "codex", ...profileData.profiles.codex }]; + const publish = { name: "paperclip-codex-pack-fixture", version: "1.0.0", dependencies: { "@agentclientprotocol/codex-acp": "1.6.2" }, bundleDependencies: ["@agentclientprotocol/codex-acp"] }; + return { directory, graph, bridge, runtime, producer, nested, profiles, publish, writePackage }; } const adapterUtilsPackage = JSON.parse( await readFile(new URL("../packages/adapter-utils/package.json", import.meta.url), "utf8"), @@ -200,60 +203,51 @@ test("published Codex bridge uses its qualified producer closure without consume assert.throws(() => configureBundledProviderOverrides(conflict, serverPackage.bundleDependencies, rootPackage, profileData), /conflicting producer override/); }); -test("Linux-produced Codex bridge tarballs retain all three contained artifacts and preserve runtime declarations", (t) => { - const destination = mkdtempSync(join(tmpdir(), "paperclip-bundled-provider-")); - t.after(() => rmSync(destination, { recursive: true, force: true })); - const graph = join(destination, "node_modules"); - const artifacts = join(destination, "artifacts"), data = structuredClone(runtimeData); - mkdirSync(artifacts); - const { profiles } = configureBundledProviderOverrides( - createBundledInstallManifest(serverPackage, serverPackage.bundleDependencies), serverPackage.bundleDependencies, rootPackage, profileData, - ); - const writePackage = (name, metadata) => { - const directory = join(graph, name); - mkdirSync(directory, { recursive: true }); - writeFileSync(join(directory, "package.json"), JSON.stringify({ name, ...metadata })); - return directory; - }; - for (const profile of profiles) { - writePackage(profile.agentServerPackage, { version: profile.agentServerVersion, - dependencies: { [profile.agentRuntimePackage]: profile.agentRuntimeVersion } }); - const optional = Object.fromEntries(nativeTargets.map(target => [`${profile.agentRuntimePackage}-${target}`, - `npm:@openai/codex@${profile.agentRuntimeVersion}-${target}`])); - writePackage(profile.agentRuntimePackage, { version: profile.agentRuntimeVersion, optionalDependencies: optional }); - writePackage(`${profile.agentRuntimePackage}-linux-x64`, { version: "0.160.0-linux-x64" }); - for (const target of nativeTargets) nativeFixture(artifacts, profile, target, data); - } - writePackage("unrelated-linux-x64", { version: "1.0.0" }); - const before = readFileSync(join(graph, "@agentclientprotocol/codex-acp/package.json"), "utf8"); - const stage = manifest => stageBundledProviderOptionalDependencies(destination, manifest, profiles, data, { nativeArtifactsDirectory: artifacts }); - const staged = stage(serverPackage); - assert.equal(staged.overrides, undefined); - assert.equal(staged.optionalDependencies["@openai/codex-darwin-arm64"], "npm:@openai/codex@0.160.0-darwin-arm64"); - for (const profile of profiles) { - for (const target of nativeTargets) { - assert.equal(existsSync(join(graph, `${profile.agentRuntimePackage}-${target}`)), true); - assert.ok(staged.bundleDependencies.includes(`${profile.agentRuntimePackage}-${target}`)); - } - assert.equal(existsSync(join(graph, profile.agentRuntimePackage, "package.json")), true); - } +test("Codex bundles retain pinned JavaScript and publish all official consumer platform aliases without native payloads", (t) => { + const { directory, graph, bridge, runtime, producer, nested, profiles, publish } = codexFixture(t); + const before = [bridge, runtime].map(path => readFileSync(join(path, "package.json"), "utf8")); + const staged = stageBundledProviderOptionalDependencies(directory, publish, profiles); + assert.deepEqual(staged.optionalDependencies, codexOptional); + assert.deepEqual(staged.bundleDependencies, publish.bundleDependencies); + assert.equal(staged.paperclipProviderArtifacts, undefined); + assert.equal(existsSync(producer), false); + assert.equal(existsSync(nested), false, "Transitive producer platform packages must also be removed"); + assert.equal(existsSync(join(runtime, "vendor")), false, "Wrapper fallback native payload must be removed"); assert.equal(existsSync(join(graph, "unrelated-linux-x64")), true); - assert.equal(readFileSync(join(graph, "@agentclientprotocol/codex-acp/package.json"), "utf8"), before); - const sdkPath = join(graph, "@openai/codex/package.json"); - const sdk = JSON.parse(readFileSync(sdkPath, "utf8")); - writeFileSync(sdkPath, JSON.stringify({ ...sdk, version: "0.156.1" })); - assert.throws(() => stage(serverPackage), /runtime version mismatch/); - writeFileSync(sdkPath, JSON.stringify(sdk)); - assert.throws(() => stage({ ...serverPackage, - optionalDependencies: { "@openai/codex-darwin-arm64": "npm:@openai/codex@0.156.1-darwin-arm64" } }), /conflicts with published/); - writeFileSync(sdkPath, JSON.stringify({ ...sdk, optionalDependencies: { "@openai/codex-untrusted": "0.160.0" } })); - assert.throws(() => stage(serverPackage), /not qualified/); - writeFileSync(sdkPath, JSON.stringify(sdk)); - const codex = profiles.find(value => value.agent === "codex"); - const artifact = join(artifacts, "@openai/codex-linux-x64"); - assert.equal(inspectBundledNativeArtifact(artifact, codex, "linux-x64", data).target, "linux-x64"); - writeFileSync(join(artifact, "package.json"), JSON.stringify({ name: "@openai/codex-linux-x64", version: "0.160.0-linux-x64", os: ["darwin"], cpu: ["x64"] })); - assert.throws(() => inspectBundledNativeArtifact(artifact, codex, "linux-x64", data), /identity mismatch/); + assert.deepEqual([bridge, runtime].map(path => readFileSync(join(path, "package.json"), "utf8")), before); + assert.deepEqual(stageBundledProviderOptionalDependencies(directory, staged, profiles), staged); + writeFileSync(join(directory, "package.json"), JSON.stringify(staged)); + const packs = JSON.parse(execFileSync("npm", ["pack", "--ignore-scripts", "--offline", "--json"], { + cwd: directory, encoding: "utf8", timeout: 30_000, + env: { ...process.env, HOME: directory, npm_config_cache: join(directory, "cache"), npm_config_update_notifier: "false" }, + })); + const paths = packs[0].files.map(file => file.path); + assert.ok(paths.some(path => path.endsWith("@openai/codex/bin/codex.js")), "The actual npm tarball retains its pinned JS runtime"); + assert.equal(paths.some(path => /@openai\/codex-(?:linux|darwin|win32)-|@openai\/codex\/vendor\//.test(path)), false, + "Actual npm pack must contain no native Codex payload on any platform"); +}); + +test("Codex bundle validation fails before deleting producer binaries for altered pins or optional declarations", (t) => { + const { directory, runtime, producer, profiles, publish } = codexFixture(t); + const file = join(runtime, "package.json"), original = JSON.parse(readFileSync(file, "utf8")); + writeFileSync(file, JSON.stringify({ ...original, version: "0.156.1" })); + assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /runtime version mismatch/); + writeFileSync(file, JSON.stringify({ ...original, optionalDependencies: { ...codexOptional, "@openai/codex-untrusted": "0.160.0" } })); + assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /not qualified/); + writeFileSync(file, JSON.stringify(original)); + assert.throws(() => stageBundledProviderOptionalDependencies(directory, { ...publish, + optionalDependencies: { "@openai/codex-darwin-arm64": "npm:@openai/codex@0.156.1-darwin-arm64" } }, profiles), /conflicts with published/); + assert.equal(existsSync(producer), true); +}); + +test("Codex stripping rejects linked native payloads and wrapper fallback directories without touching external files", (t) => { + const { directory, runtime, producer, profiles, publish, writePackage } = codexFixture(t); + const outside = writePackage(join(directory, "outside"), { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] }); + rmSync(producer, { recursive: true }); symlinkSync(outside, producer, "dir"); + assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /escapes its producer graph/); + rmSync(producer); rmSync(join(runtime, "vendor"), { recursive: true }); symlinkSync(outside, join(runtime, "vendor"), "dir"); + assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /escapes its producer graph/); + assert.equal(existsSync(join(outside, "package.json")), true); }); test("Linux-produced esbuild bundles publish exact consumer platform dependencies and retain their hooks", (t) => { @@ -317,19 +311,10 @@ test("bundled esbuild cannot follow a platform payload or package namespace outs assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /escapes its producer graph/); }); -test("Codex runtime artifact data preserves the existing Linux qualification without adding targets", () => { - assert.deepEqual(Object.keys(runtimeData).sort(), ["codex", "schema"]); - assert.deepEqual(Object.keys(runtimeData.codex.platforms), ["linux-x64"]); - assert.equal(runtimeData.codex.platforms["linux-x64"].executableDigest, "sha256:12eb3e81114588aca3b7998f4f19e8997b056aca08e57a7ca7c8a3ec8c652aad"); - assert.equal(runtimeData.codex.platforms["linux-x64"].environmentVariable, "CODEX_PATH"); -}); - test("Docker provider graphs use qualified targets and contain only native entry bindings without changing server dependencies", (t) => { assert.equal(dockerBundledProviderTarget("amd64"), "linux-x64"); assert.equal(dockerBundledProviderTarget("arm64"), null, "Unqualified native ARM64 must not break legacy images"); assert.throws(() => dockerBundledProviderTarget("x64"), /declared supported target/); - const missing = structuredClone(runtimeData); delete missing.codex.platforms["linux-x64"]; - assert.equal(dockerBundledProviderTarget("amd64", missing), null, "The existing Codex qualification contract is required"); const fixture = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-docker-provider-graph-"))); t.after(() => rmSync(fixture, { recursive: true, force: true })); const server = join(fixture, "server"), staged = join(fixture, "staged"), store = join(fixture, "workspace-store"); @@ -523,7 +508,6 @@ test("server package staging applies every bundled runtime patch and preserves t const callLog = join(fixtureDir, "calls.log"); const fixtureSourceRoot = join(fixtureDir, "repo"); const fixtureArtifacts = join(fixtureDir, "native-artifacts"); - const fixtureRuntimeData = structuredClone(runtimeData); mkdirSync(sourceDir); mkdirSync(join(sourceDir, "dist")); writeFileSync(join(sourceDir, "dist", "index.js"), "export {};\n"); @@ -535,13 +519,13 @@ test("server package staging applies every bundled runtime patch and preserves t ); writeFileSync(callLog, ""); mkdirSync(fixtureArtifacts); - for (const [agent, profile] of Object.entries(profileData.profiles).filter(([agent]) => agent === "codex")) { - for (const target of nativeTargets) nativeFixture(fixtureArtifacts, { agent, ...profile }, target, fixtureRuntimeData); - } + const nativePackage = join(fixtureArtifacts, "@openai/codex-linux-x64"); + mkdirSync(join(nativePackage, "vendor"), { recursive: true }); + writeFileSync(join(nativePackage, "package.json"), JSON.stringify({ name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] })); + writeFileSync(join(nativePackage, "vendor/codex"), "npm-installed Docker host fixture; never executed"); mkdirSync(join(fixtureSourceRoot, "packages/paperclip-runner/src/drivers/acpx"), { recursive: true }); writeFileSync(join(fixtureSourceRoot, "package.json"), JSON.stringify(rootPackage)); writeFileSync(join(fixtureSourceRoot, "packages/paperclip-runner/acpx-profiles.json"), JSON.stringify(profileData)); - writeFileSync(join(fixtureSourceRoot, "packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json"), JSON.stringify(fixtureRuntimeData)); mkdirSync(join(fixtureSourceRoot, "patches")); for (const patchPath of Object.values(rootPackage.pnpm.patchedDependencies)) { writeFileSync(join(fixtureSourceRoot, patchPath), readFileSync(new URL(`../${patchPath}`, import.meta.url))); @@ -566,9 +550,10 @@ mkdir -p "$destination/node_modules/.pnpm" `#!/usr/bin/env bash set -euo pipefail printf 'npm %s\\n' "$*" >> "$FAKE_CALL_LOG" -[ "$*" = "install --omit=dev --ignore-scripts --no-audit --no-fund" ] || [ "$*" = "install --force --omit=dev --ignore-scripts --no-audit --no-fund" ] -node -e 'const fs = require("node:fs"); const path=require("node:path"); const pkg = require("./package.json"); if ("devDependencies" in pkg) process.exit(1); if(pkg.name === "paperclip-native-artifact-staging"){for(const name of Object.keys(pkg.dependencies)){fs.cpSync(path.join(process.env.FAKE_NATIVE_ARTIFACTS,name),path.join("node_modules",name),{recursive:true});}process.exit(0);} for (const [name, version] of Object.entries(pkg.dependencies)) { const dir = "node_modules/" + name; fs.mkdirSync(dir + "/dist", { recursive: true }); fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version })); } for (const [bridge, runtimes] of Object.entries(pkg.overrides ?? {})) { for (const [name, version] of Object.entries(runtimes)) { const dir = "node_modules/" + name; fs.mkdirSync(dir, { recursive: true }); const native = name === "@openai/codex"; const optionalDependencies = native ? Object.fromEntries(["linux-x64","darwin-arm64","darwin-x64"].map(target => [name+"-"+target,"npm:"+name+"@"+version+"-"+target])) : undefined; fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version, optionalDependencies })); } }' -if [ -f package.json ] && node -e 'process.exit(require("./package.json").name === "paperclip-native-artifact-staging" ? 0 : 1)'; then exit 0; fi +[ "$*" = "install --omit=dev --ignore-scripts --no-audit --no-fund" ] +node -e 'const fs = require("node:fs"); const path=require("node:path"); const pkg = require("./package.json"); if ("devDependencies" in pkg) process.exit(1); if(pkg.name === "paperclip-docker-codex-runtime"){for(const name of Object.keys(pkg.dependencies)){fs.cpSync(path.join(process.env.FAKE_NATIVE_ARTIFACTS,name),path.join("node_modules",name),{recursive:true});}process.exit(0);} for (const [name, version] of Object.entries(pkg.dependencies)) { const dir = "node_modules/" + name; fs.mkdirSync(dir + "/dist", { recursive: true }); fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version })); } for (const [bridge, runtimes] of Object.entries(pkg.overrides ?? {})) { for (const [name, version] of Object.entries(runtimes)) { const dir = "node_modules/" + name; fs.mkdirSync(dir, { recursive: true }); const native = name === "@openai/codex"; const optionalDependencies = native ? Object.fromEntries(["linux-x64","linux-arm64","darwin-x64","darwin-arm64","win32-x64","win32-arm64"].map(target => [name+"-"+target,"npm:"+name+"@"+version+"-"+target])) : undefined; fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version, optionalDependencies })); } }' +if [ -f package.json ] && node -e 'process.exit(require("./package.json").name === "paperclip-docker-codex-runtime" ? 0 : 1)'; then exit 0; fi +node -e 'const fs=require("node:fs");fs.cpSync(process.env.FAKE_NATIVE_ARTIFACTS+"/@openai/codex-linux-x64","node_modules/@openai/codex-linux-x64",{recursive:true});fs.mkdirSync("node_modules/@openai/codex/vendor",{recursive:true});fs.writeFileSync("node_modules/@openai/codex/vendor/codex","producer fallback fixture");' mkdir -p node_modules/acpx/dist node -e 'const fs=require("node:fs");fs.mkdirSync("node_modules/esbuild",{recursive:true});fs.writeFileSync("node_modules/esbuild/package.json",JSON.stringify({name:"esbuild",version:"0.28.2",scripts:{postinstall:"node install.js"},optionalDependencies:Object.fromEntries(["linux-x64","darwin-arm64","darwin-x64"].map(target=>["@esbuild/"+target,"0.28.2"]))}));fs.mkdirSync("node_modules/@esbuild/linux-x64",{recursive:true});fs.writeFileSync("node_modules/@esbuild/linux-x64/package.json",JSON.stringify({name:"@esbuild/linux-x64",version:"0.28.2",os:["linux"],cpu:["x64"]}));' printf 'unpatched runtime\\n' > node_modules/acpx/dist/runtime.js @@ -627,6 +612,13 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js" assert.equal(lstatSync(stagedAcpxDir).isSymbolicLink(), false); assert.equal(existsSync(join(destinationDir, "node_modules/.pnpm")), false); const stagedManifest = JSON.parse(readFileSync(join(destinationDir, "package.json"), "utf8")); + for (const [name, version] of Object.entries(codexOptional)) { + assert.equal(stagedManifest.optionalDependencies[name], version); + assert.equal(existsSync(join(destinationDir, "node_modules", name)), false); + assert.equal(stagedManifest.bundleDependencies.includes(name), false); + } + assert.equal(existsSync(join(destinationDir, "node_modules/@openai/codex/vendor")), false); + assert.equal(stagedManifest.paperclipProviderArtifacts, undefined); assert.equal(stagedManifest.optionalDependencies["@esbuild/darwin-arm64"], "0.28.2"); assert.equal(stagedManifest.optionalDependencies["@esbuild/darwin-x64"], "0.28.2"); assert.equal(existsSync(join(destinationDir, "node_modules/@esbuild/linux-x64")), false); @@ -669,8 +661,12 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js" imageServer, fixtureSourceRoot], { env: { ...process.env, PATH: `${binDir}:${process.env.PATH}`, FAKE_CALL_LOG: callLog, FAKE_NATIVE_ARTIFACTS: fixtureArtifacts }, encoding: "utf8" }).trim().split("\n").at(-1)); assert.equal(imageReceipt.materialized, true); - assert.equal(imageReceipt.artifacts.artifacts.length, 1, "Image must stage only its existing qualified Linux target"); - assert.equal(imageReceipt.artifacts.artifacts.every(artifact => artifact.target === "linux-x64"), true); + assert.equal(imageReceipt.installedBy, "npm"); + assert.equal(imageReceipt.packageName, "@openai/codex-linux-x64"); + assert.equal(imageReceipt.packageVersion, "0.160.0-linux-x64"); + const imageGraph = join(imageServer, "node_modules/.paperclip-native-providers/node_modules"); + assert.equal(existsSync(join(imageGraph, "@openai/codex-linux-x64/vendor/codex")), true); + for (const target of codexTargets.filter(target => target !== "linux-x64")) assert.equal(existsSync(join(imageGraph, `@openai/codex-${target}`)), false); assert.equal(readFileSync(join(imageServer, "node_modules/unrelated-marker"), "utf8"), "keep existing application graph"); for (const name of ["@agentclientprotocol/codex-acp"]) { assert.match(realpathSync(join(imageServer, "node_modules", name)), /image-server\/node_modules\/\.paperclip-native-providers\/node_modules/); diff --git a/scripts/grok-public-install-sandbox.mjs b/scripts/grok-public-install-sandbox.mjs index e53a8fb2530..35595b58425 100644 --- a/scripts/grok-public-install-sandbox.mjs +++ b/scripts/grok-public-install-sandbox.mjs @@ -1,3 +1,5 @@ +import assert from 'node:assert/strict'; + // Keep public-package lifecycle code off the verification host. Resolve and // cache the public npm graph without scripts, then execute it offline. export const GROK_PUBLIC_INSTALL_IMAGE = @@ -7,17 +9,88 @@ export const GROK_PUBLIC_INSTALL_LIFECYCLE = [ 'npm', 'rebuild', '--offline', '--ignore-scripts=false', '--dangerously-allow-all-scripts', ]; +// Inspect the actual npm archive, independently of the staging helper. +export function assertNoBundledCodexPayloads(entries) { + assert.ok(Array.isArray(entries) && entries.length > 0, 'Packed package must have tar members'); + for (const entry of entries) { + assert.equal(typeof entry, 'string'); + assert.ok(!entry.startsWith('/') && !entry.split('/').includes('..'), 'Tar member must remain inside the package'); + assert.doesNotMatch(entry, /(?:^|\/)node_modules\/@openai\/codex-(?:linux|darwin|win32)-(?:x64|arm64)(?:\/|$)/, + 'Paperclip tarballs must not bundle Codex platform packages'); + assert.doesNotMatch(entry, /(?:^|\/)node_modules\/@openai\/codex\/vendor(?:\/|$)/, + 'Paperclip tarballs must not bundle the Codex wrapper vendor payload'); + if (!entry.endsWith('/')) assert.doesNotMatch(entry, /(?:^|\/)codex(?:\.exe)?$/, + 'Paperclip tarballs must not bundle native Codex executables'); + } +} + +// This same pure check is embedded in the offline installed consumer below. +export function assertInstalledCodexPlatformProvenance(lock, installed, expectedVersion, target) { + assert.match(target, /^(linux|darwin|win32)-(x64|arm64)$/); + assert.ok(Array.isArray(installed) && installed.length > 0, 'Consumer must install its host Codex platform package'); + const alias = `@openai/codex-${target}`; + for (const { path, manifest } of installed) { + assert.ok(path.endsWith(`/node_modules/${alias}`) || path === `node_modules/${alias}`, + 'Consumer must contain only the host Codex platform payload'); + const version = `${expectedVersion}-${target}`; + assert.ok([alias, '@openai/codex'].includes(manifest.name), 'Installed Codex platform package identity must match its alias'); + assert.equal(manifest.version, version, 'Installed Codex platform version must match the qualified pin'); + const [os, cpu] = target.split('-'); + assert.deepEqual(manifest.os, [os]); + assert.deepEqual(manifest.cpu, [cpu]); + const entry = lock.packages?.[path]; + assert.ok(entry, 'Installed Codex platform must have a consumer lock entry'); + assert.notEqual(entry.inBundle, true, 'Codex platform package must be downloaded, not bundled'); + assert.notEqual(entry.link, true, 'Codex platform package must not be a local link'); + assert.equal(entry.version, version, 'Consumer lock must pin the host Codex platform version'); + const url = new URL(entry.resolved); + assert.equal(url.protocol, 'https:'); + assert.equal(url.host, 'registry.npmjs.org', 'Codex platform must resolve from official npm'); + assert.equal(url.username + url.password + url.search + url.hash, '', 'Codex npm URL must not have credentials or modifiers'); + assert.equal(decodeURIComponent(url.pathname), `/@openai/codex/-/codex-${version}.tgz`, 'Codex platform must use its exact official npm tarball'); + assert.match(entry.integrity ?? '', /^sha512-[A-Za-z0-9+/]+={0,2}$/, 'Codex platform must have npm integrity'); + assert.equal(Buffer.from(entry.integrity.slice(7), 'base64').length, 64, 'Codex npm integrity must be a SHA-512 digest'); + } + return { codexConsumerHostOnly: true, codexConsumerPlatform: target, codexPlatformPackageSource: 'official npm', + codexPlatformPackages: installed.map(({ path, manifest }) => ({ path, name: manifest.name, version: manifest.version, + resolved: lock.packages[path].resolved, integrity: lock.packages[path].integrity, inBundle: false })) }; +} + // Execute this in the existing offline public consumer, never in the checkout. // The public index and returned command must both come from the installed graph. export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersion) { return ` import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; - import { accessSync, constants, realpathSync, statSync } from 'node:fs'; - import { isAbsolute, relative, sep } from 'node:path'; + import { createRequire } from 'node:module'; + import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'; + import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; const root = realpathSync(${JSON.stringify(consumerRoot)}); const contained = path => { const value = relative(root, realpathSync(path)); return value !== '' && value !== '..' && !value.startsWith('..' + sep) && !isAbsolute(value); }; + const lock = JSON.parse(readFileSync(join(root, 'package-lock.json'), 'utf8')); + const installed = [], pending = [join(root, 'node_modules')]; + let visited = 0; + while (pending.length) { + const directory = pending.pop(); + assert.ok(contained(directory), 'Installed dependency directory must remain in the consumer'); + for (const entry of readdirSync(directory, { withFileTypes: true })) { + if (entry.name.startsWith('.') || !(entry.isDirectory() || entry.isSymbolicLink())) continue; + const namespace = join(directory, entry.name); + const packages = entry.name.startsWith('@') ? readdirSync(namespace, { withFileTypes: true }) + .filter(value => value.isDirectory() || value.isSymbolicLink()).map(value => join(namespace, value.name)) : [namespace]; + for (const packageRoot of packages) { + assert.ok(++visited <= 10000 && contained(packageRoot), 'Installed dependency graph must be bounded and contained'); + const path = relative(root, packageRoot).split(sep).join('/'); + if (${/(?:^|\/)node_modules\/@openai\/codex-(?:linux|darwin|win32)-(?:x64|arm64)$/.toString()}.test(path)) { + installed.push({ path, manifest: JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) }); + } + const nested = join(packageRoot, 'node_modules'); + if (existsSync(nested)) pending.push(nested); + } + } + } + const provenance = (${assertInstalledCodexPlatformProvenance.toString()})(lock, installed, ${JSON.stringify(expectedVersion)}, process.platform + '-' + process.arch); const index = ${JSON.stringify(indexPath)}; assert.ok(contained(index), 'Codex public index must be installed in the consumer'); const { resolvePinnedCodexCommand } = await import(pathToFileURL(index).href); @@ -26,10 +99,26 @@ export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersi assert.ok(isAbsolute(command) && contained(command), 'Pinned Codex must resolve inside the installed consumer'); assert.ok(statSync(command).isFile(), 'Pinned Codex must be a regular executable'); accessSync(command, constants.X_OK); + const selectedPlatformManifest = realpathSync(createRequire(command).resolve('@openai/codex-' + process.platform + '-' + process.arch + '/package.json')); + assert.ok(installed.some(({ path }) => realpathSync(join(root, path, 'package.json')) === selectedPlatformManifest), + 'Codex wrapper must resolve an official host platform package from its installed graph'); const version = execFileSync(command, ['--version'], { timeout: 30_000, maxBuffer: 128 * 1024, encoding: 'utf8', env: { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/tmp', NODE_PATH: '' } }).trim(); assert.equal(version, 'codex-cli ' + ${JSON.stringify(expectedVersion)}, 'Installed Codex version must match the qualified pin'); - console.log(JSON.stringify({ pinnedCodexCommandVerified: true, pinnedCodexVersion: ${JSON.stringify(expectedVersion)}, providerCalls: 0 })); + const vendor = dirname(index); + const integrityPath = join(vendor, 'drivers/acpx/installation-integrity.js'); + const profilesPath = join(vendor, 'drivers/acpx/qualified-profiles.js'); + assert.ok(contained(integrityPath) && contained(profilesPath), 'Codex integrity modules must come from the installed consumer'); + const { createAcpxPackageJsonResolver, verifyQualifiedAcpxInstallation } = await import(pathToFileURL(integrityPath).href); + const { resolveQualifiedAcpxProfile } = await import(pathToFileURL(profilesPath).href); + const serverRoot = resolve(vendor, '../../..'); + assert.ok(contained(serverRoot), 'Codex package authority must be the installed server'); + const installation = await verifyQualifiedAcpxInstallation(resolveQualifiedAcpxProfile('codex', 'gpt-5.4'), + createAcpxPackageJsonResolver(serverRoot, join(serverRoot, 'package.json'))); + const lease = await installation.openCommand(); + await lease.close(); + console.log(JSON.stringify({ pinnedCodexCommandVerified: true, pinnedCodexVersion: ${JSON.stringify(expectedVersion)}, + ...provenance, codexQualifiedInstallationVerified: true, codexCommandLeaseVerified: true, providerCalls: 0 })); `; } diff --git a/scripts/prepare-bundled-package.mjs b/scripts/prepare-bundled-package.mjs index 463f1bd5bfa..0081cfa36cd 100644 --- a/scripts/prepare-bundled-package.mjs +++ b/scripts/prepare-bundled-package.mjs @@ -1,7 +1,6 @@ #!/usr/bin/env node import { execFileSync } from "node:child_process"; -import { createHash } from "node:crypto"; import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path"; @@ -9,9 +8,7 @@ import { tmpdir } from "node:os"; import { fileURLToPath } from "node:url"; const repoRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); -const runtimeDataPath = "packages/paperclip-runner/src/drivers/acpx/qualified-runtime-artifacts.json"; const nativeTargets = ["linux-x64", "darwin-arm64", "darwin-x64"]; -const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; export function materializePublishManifest(pkg) { const publishConfig = pkg.publishConfig ?? {}; @@ -57,8 +54,7 @@ export function createBundledInstallManifest(publishManifest, bundledDependencie // npm consumers cannot inherit the workspace's pnpm overrides or patches. // Materialize the already-qualified Codex bridge closure in the tarball, // with overrides confined to the temporary, scripts-disabled producer graph. -export function configureBundledProviderOverrides(installManifest, bundledDependencies, rootPackage, profileData, - runtimeData = JSON.parse(readFileSync(resolve(repoRoot, runtimeDataPath), "utf8"))) { +export function configureBundledProviderOverrides(installManifest, bundledDependencies, rootPackage, profileData) { const result = structuredClone(installManifest); const selected = []; for (const [agent, serverPackage, runtimePackage] of [ @@ -92,151 +88,98 @@ const inside = (root, candidate) => { return value !== "" && value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value); }; -export function inspectBundledNativeArtifact(directory, profile, target, runtimeData) { - if (profile.agent !== "codex" || !nativeTargets.includes(target) || runtimeData?.schema !== "paperclip.acpx-runtime-artifacts.v1") throw new Error("Bundled native artifact has no supported target contract"); - const rootStat = lstatSync(directory), manifestStat = lstatSync(resolve(directory, "package.json")); - if (!rootStat.isDirectory() || rootStat.isSymbolicLink() || !manifestStat.isFile() || manifestStat.nlink !== 1 || manifestStat.size > 256 * 1024) { - throw new Error("Bundled native artifact manifest is not a bounded regular file"); - } - const [platform, architecture] = target.split("-"); - const metadata = JSON.parse(readFileSync(resolve(directory, "package.json"), "utf8")); - const name = `${profile.agentRuntimePackage}-${target}`; - const version = `${profile.agentRuntimeVersion}-${target}`; - if (![name, profile.agentRuntimePackage].includes(metadata.name) || metadata.version !== version - || !Array.isArray(metadata.os) || !metadata.os.includes(platform) || !Array.isArray(metadata.cpu) || !metadata.cpu.includes(architecture) - || Object.keys(metadata.dependencies ?? {}).length || Object.keys(metadata.optionalDependencies ?? {}).length || Object.keys(metadata.scripts ?? {}).length) { - throw new Error(`Bundled ${profile.agent} native artifact identity mismatch: ${target}`); - } - const qualification = runtimeData?.[profile.agent]?.platforms?.[target]; - if (!qualification && !(profile.agent === "codex" && platform === "darwin")) throw new Error("Bundled native artifact omitted its existing executable qualification"); - const relativeExecutable = qualification?.relativeExecutable ?? (profile.agent === "codex" && platform === "darwin" - ? `vendor/${architecture === "arm64" ? "aarch64" : "x86_64"}-apple-darwin/bin/codex` : undefined); - if (!relativeExecutable || relativeExecutable.split("/").some(value => !value || value === "..") || isAbsolute(relativeExecutable)) { - throw new Error("Bundled native artifact has no recognized executable"); - } - const entries = []; - let bytes = 0; - const walk = (root, prefix = "") => { - if (!lstatSync(root).isDirectory() || lstatSync(root).isSymbolicLink()) throw new Error("Bundled native artifact contains a linked directory"); - for (const entry of readdirSync(root).sort()) { - const path = prefix ? `${prefix}/${entry}` : entry; - if (/[\u0000-\u001f\u007f\\]/.test(path)) throw new Error("Bundled native artifact contains an unsafe path"); - const file = resolve(root, entry), stat = lstatSync(file); - if (stat.isDirectory()) walk(file, path); - else { - if (!stat.isFile() || stat.nlink !== 1 || stat.mode & 0o7000) throw new Error("Bundled native artifact contains links or special files"); - bytes += stat.size; - if (bytes > 1024 * 1024 * 1024 || entries.length >= 4096) throw new Error("Bundled native artifact exceeds size limits"); - entries.push({ path, size: stat.size, sha256: digest(readFileSync(file)), executable: Boolean(stat.mode & 0o111) }); - } +// Bundle the pinned JavaScript closure, never the producer's Codex executable. +// npm installs the official optional package for the consumer's own platform. +export function stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles) { + const graphRoot = resolve(destinationDir, "node_modules"); + if (realpathSync(graphRoot) !== graphRoot) throw new Error("Bundled Codex graph must be a canonical owned directory"); + const result = structuredClone(publishManifest), remove = new Set(), optional = {}; + const profile = profiles.find(value => value.agent === "codex"); + if (profiles.length !== 1 || !profile) throw new Error("Bundled provider graph must contain its qualified Codex profile"); + const targets = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64"]; + const declarations = Object.fromEntries(targets.map(target => [`${profile.agentRuntimePackage}-${target}`, + `npm:${profile.agentRuntimePackage}@${profile.agentRuntimeVersion}-${target}`])); + const ownedDirectory = directory => { + const stat = lstatSync(directory); + if (!stat.isDirectory() || stat.isSymbolicLink() || !inside(graphRoot, realpathSync(directory))) { + throw new Error("Bundled Codex dependency escapes its producer graph"); } }; - walk(directory); - const executable = entries.find(entry => entry.path === relativeExecutable); - if (!executable?.executable) throw new Error("Bundled native artifact has no executable payload"); - const header = readFileSync(resolve(directory, relativeExecutable)); - const correctArchitecture = platform === "linux" - ? header.length >= 20 && header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) && header[4] === 2 && header[5] === 1 && header.readUInt16LE(18) === 62 - : header.length >= 8 && header.readUInt32LE(0) === 0xfeedfacf && header.readUInt32LE(4) === (architecture === "arm64" ? 0x0100000c : 0x01000007); - if (!correctArchitecture) throw new Error(`Bundled native artifact architecture mismatch: ${target}`); - if (qualification && (qualification.packageName !== name || qualification.packageVersion !== version - || qualification.runtimePackageName !== profile.agentRuntimePackage || qualification.runtimePackageVersion !== profile.agentRuntimeVersion - || qualification.executableDigest !== executable.sha256)) throw new Error(`Bundled native artifact qualified digest mismatch: ${name}`); - return { agent: profile.agent, target, packageName: name, packageVersion: version, size: bytes, - executable: relativeExecutable, executableDigest: executable.sha256, qualification: qualification ? "existing executable hash" : "native Codex package/version; ACPX qualification unchanged", - closureDigest: digest(JSON.stringify(entries)), entries }; -} - -export function stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles, - runtimeData = JSON.parse(readFileSync(resolve(repoRoot, runtimeDataPath), "utf8")), { nativeArtifactsDirectory, targets = nativeTargets } = {}) { - if (!Array.isArray(targets) || targets.length === 0 || new Set(targets).size !== targets.length - || targets.some(target => !nativeTargets.includes(target))) throw new Error("Invalid bundled native target selection"); - const result = structuredClone(publishManifest); - const graphRoot = realpathSync(resolve(destinationDir, "node_modules")); - const artifacts = [], nativeDependencies = {}; - for (const profile of profiles) { - const bridgeManifestPath = resolve(graphRoot, profile.agentServerPackage, "package.json"); - const bridge = JSON.parse(readFileSync(bridgeManifestPath, "utf8")); - if (bridge.name !== profile.agentServerPackage || bridge.version !== profile.agentServerVersion) { - throw new Error(`Bundled ${profile.agent} bridge version mismatch`); + const manifestAt = directory => { + const path = resolve(directory, "package.json"), stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024) { + throw new Error("Bundled Codex dependency manifest must be a bounded regular file"); } - const bridgeRequire = createRequire(bridgeManifestPath); - const runtimeManifestPath = realpathSync(bridgeRequire.resolve(`${profile.agentRuntimePackage}/package.json`)); - if (!inside(graphRoot, runtimeManifestPath)) throw new Error("Bundled Codex runtime escapes its producer graph"); - const runtime = JSON.parse(readFileSync(runtimeManifestPath, "utf8")); - if (runtime.name !== profile.agentRuntimePackage || runtime.version !== profile.agentRuntimeVersion) { - throw new Error(`Bundled ${profile.agent} runtime version mismatch`); - } - const optional = Object.entries(runtime.optionalDependencies ?? {}); - if (optional.length === 0) throw new Error(`Bundled ${profile.agent} runtime omitted platform artifacts`); - const runtimeRequire = createRequire(runtimeManifestPath); - for (const [name, specifier] of optional) { - const suffix = name.slice(profile.agentRuntimePackage.length + 1); - const recognized = profile.agent === "codex" && name.startsWith(`${profile.agentRuntimePackage}-`) && /^(linux|darwin|win32)-(x64|arm64)$/.test(suffix); - const version = `${runtime.version}-${suffix}`; - const expected = `npm:${runtime.name}@${version}`; - if (!recognized || specifier !== expected) throw new Error(`Bundled ${profile.agent} platform artifact is not qualified: ${name}`); - if (result.optionalDependencies?.[name] !== undefined && result.optionalDependencies[name] !== expected) { - throw new Error(`Bundled ${profile.agent} platform artifact conflicts with published dependency: ${name}`); - } - if (targets.includes(suffix)) { - result.optionalDependencies = { ...result.optionalDependencies, [name]: expected }; - nativeDependencies[name] = expected; - } - // Remove only recognized producer-platform payloads before staging the - // bounded supported target set. Preserve the original runtime manifest. - for (const lookup of runtimeRequire.resolve.paths(name) ?? []) { - const candidate = resolve(lookup, name); - if (!inside(graphRoot, candidate) || !existsSync(candidate)) continue; - if (lstatSync(candidate).isSymbolicLink() || !inside(graphRoot, realpathSync(candidate))) { - throw new Error(`Bundled ${profile.agent} platform artifact escapes its producer graph`); + return JSON.parse(readFileSync(path, "utf8")); + }; + const bridgeDirectory = resolve(graphRoot, profile.agentServerPackage); + ownedDirectory(bridgeDirectory); + const bridge = manifestAt(bridgeDirectory); + if (bridge.name !== profile.agentServerPackage || bridge.version !== profile.agentServerVersion) throw new Error("Bundled Codex bridge version mismatch"); + const issuer = createRequire(resolve(bridgeDirectory, "package.json")); + const runtimeManifest = realpathSync(issuer.resolve(`${profile.agentRuntimePackage}/package.json`)); + if (!inside(graphRoot, runtimeManifest)) throw new Error("Bundled Codex runtime escapes its producer graph"); + let runtimeCount = 0, packageCount = 0; + const pending = [{ directory: graphRoot, depth: 0 }]; + while (pending.length) { + const { directory, depth } = pending.pop(); + if (depth > 64) throw new Error("Bundled Codex graph exceeds its depth limit"); + const packages = []; + for (const entry of readdirSync(directory)) { + if (entry.startsWith(".")) continue; + const candidate = resolve(directory, entry); ownedDirectory(candidate); + if (entry.startsWith("@")) { + for (const child of readdirSync(candidate)) { + const scoped = resolve(candidate, child); ownedDirectory(scoped); packages.push(scoped); } - const artifact = JSON.parse(readFileSync(resolve(candidate, "package.json"), "utf8")); - if (![name, runtime.name].includes(artifact.name) || artifact.version !== version) { - throw new Error(`Bundled ${profile.agent} installed platform artifact version mismatch: ${name}`); + } else packages.push(candidate); + } + for (const packageDirectory of packages) { + if (++packageCount > 20_000) throw new Error("Bundled Codex graph exceeds its package limit"); + const metadata = manifestAt(packageDirectory); + const binding = basename(dirname(packageDirectory)) === "@openai" ? `@openai/${basename(packageDirectory)}` : null; + if (binding?.startsWith("@openai/codex-")) { + const target = binding.slice("@openai/codex-".length), [os, cpu] = target.split("-"); + if (!Object.hasOwn(declarations, binding) || ![binding, profile.agentRuntimePackage].includes(metadata.name) + || metadata.version !== `${profile.agentRuntimeVersion}-${target}` || !metadata.os?.includes(os) || !metadata.cpu?.includes(cpu)) { + throw new Error("Bundled Codex installed platform identity mismatch"); } - rmSync(candidate, { recursive: true, force: true }); + remove.add(packageDirectory); + continue; } + const nested = resolve(packageDirectory, "node_modules"); + if (lstatExists(nested)) { ownedDirectory(nested); pending.push({ directory: nested, depth: depth + 1 }); } + if (binding !== profile.agentRuntimePackage) continue; + if (metadata.name !== profile.agentRuntimePackage || metadata.version !== profile.agentRuntimeVersion) throw new Error("Bundled Codex runtime version mismatch"); + runtimeCount++; + if (Object.keys(metadata.optionalDependencies ?? {}).length !== targets.length + || targets.some(target => metadata.optionalDependencies?.[`${profile.agentRuntimePackage}-${target}`] !== declarations[`${profile.agentRuntimePackage}-${target}`])) { + throw new Error("Bundled Codex platform declaration is not qualified"); + } + const vendor = resolve(packageDirectory, "vendor"); + if (lstatExists(vendor)) { ownedDirectory(vendor); remove.add(vendor); } } - } - if (Object.keys(nativeDependencies).length !== profiles.length * targets.length) throw new Error("Bundled provider omitted a supported native target"); - const temporary = mkdtempSync(resolve(destinationDir, ".paperclip-native-artifacts-")); - try { - writeFileSync(resolve(temporary, "package.json"), JSON.stringify({ private: true, name: "paperclip-native-artifact-staging", version: "1.0.0", dependencies: nativeDependencies })); - if (!nativeArtifactsDirectory) execFileSync("npm", ["install", "--force", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"], - { cwd: temporary, stdio: "inherit", timeout: 180_000 }); - for (const profile of profiles) for (const target of targets) { - const name = `${profile.agentRuntimePackage}-${target}`; - const input = resolve(nativeArtifactsDirectory ?? resolve(temporary, "node_modules"), name); - const artifact = inspectBundledNativeArtifact(input, profile, target, runtimeData); - const output = resolve(graphRoot, name); - if (existsSync(output)) throw new Error("Bundled native artifact destination already exists"); - cpSync(input, output, { recursive: true, dereference: false }); - for (const entry of artifact.entries) chmodSync(resolve(output, entry.path), entry.executable ? 0o755 : 0o644); - const copied = inspectBundledNativeArtifact(output, profile, target, runtimeData); - if (copied.closureDigest !== artifact.closureDigest) throw new Error("Bundled native artifact changed during staging"); - artifacts.push(copied); - result.bundleDependencies = [...new Set([...(result.bundleDependencies ?? result.bundledDependencies ?? []), name])]; - } - const total = artifacts.reduce((size, artifact) => size + artifact.size, 0); - if (total > 2 * 1024 * 1024 * 1024) throw new Error("Bundled native provider payload exceeds release size limit"); - result.paperclipProviderArtifacts = { schema: "paperclip.bundled-provider-artifacts.v1", providerCalls: 0, lifecycleScriptsRun: false, - totalBytes: total, artifacts: artifacts.map(({ entries, ...artifact }) => artifact) }; - } finally { rmSync(temporary, { recursive: true, force: true }); } + if (!runtimeCount) throw new Error("Bundled Codex runtime omitted its platform declarations"); + for (const [name, specifier] of Object.entries(declarations)) { + if (result.optionalDependencies?.[name] !== undefined && result.optionalDependencies[name] !== specifier) throw new Error(`Bundled Codex platform conflicts with published dependency: ${name}`); + optional[name] = specifier; + } + // Validate the complete graph before deleting any producer payload. + for (const directory of remove) rmSync(directory, { recursive: true, force: true }); + result.optionalDependencies = { ...result.optionalDependencies, ...optional }; + for (const field of ["bundleDependencies", "bundledDependencies"]) { + if (Array.isArray(result[field])) result[field] = result[field].filter(name => !Object.hasOwn(declarations, name)); + } + delete result.paperclipProviderArtifacts; return result; } -export function dockerBundledProviderTarget(architecture, - runtimeData = JSON.parse(readFileSync(resolve(repoRoot, runtimeDataPath), "utf8"))) { - const architectures = { amd64: "x64", arm64: "arm64" }; - if (!Object.hasOwn(architectures, architecture) || runtimeData?.schema !== "paperclip.acpx-runtime-artifacts.v1") { - throw new Error("Docker provider materialization requires a declared supported target architecture and qualification contract"); - } - const target = `linux-${architectures[architecture]}`; - // A Docker target selects an already-qualified artifact; it cannot qualify - // a new platform. Unqualified native targets retain their normal legacy CLI. - return runtimeData.codex?.platforms?.[target] ? target : null; +export function dockerBundledProviderTarget(architecture) { + if (!["amd64", "arm64"].includes(architecture)) throw new Error("Docker provider materialization requires a declared supported target architecture"); + // Only Linux x64 has an existing native Codex executable qualification. + // The runtime resolver retains that digest authority; ARM64 stays legacy. + return architecture === "amd64" ? "linux-x64" : null; } export function mergeBundledProviderGraph(stagedDirectory, serverDirectory) { @@ -363,8 +306,7 @@ export function stageBundledEsbuildOptionalDependencies(destinationDir, publishM } export function materializeDockerProviderGraph(serverDirectory, architecture, { sourceRoot = repoRoot } = {}) { - const runtimeData = JSON.parse(readFileSync(resolve(sourceRoot, runtimeDataPath), "utf8")); - const target = dockerBundledProviderTarget(architecture, runtimeData); + const target = dockerBundledProviderTarget(architecture); if (!target) return { target: `linux-${architecture === "arm64" ? "arm64" : "x64"}`, materialized: false, reason: "Native providers are not qualified for this target; legacy installation preserved" }; const metadata = JSON.parse(readFileSync(resolve(serverDirectory, "package.json"), "utf8")); const names = ["@agentclientprotocol/codex-acp"]; @@ -373,10 +315,25 @@ export function materializeDockerProviderGraph(serverDirectory, architecture, { const source = resolve(temporary, "source"), staged = resolve(temporary, "staged"); mkdirSync(source); writeFileSync(resolve(source, "package.json"), JSON.stringify({ name: metadata.name, version: metadata.version, type: "module", files: [], dependencies: Object.fromEntries(names.map(name => [name, metadata.dependencies?.[name]])), bundleDependencies: names })); - prepareBundledPackage(source, staged, { sourceRoot, targets: [target] }); + prepareBundledPackage(source, staged, { sourceRoot }); + const profile = JSON.parse(readFileSync(resolve(sourceRoot, "packages/paperclip-runner/acpx-profiles.json"), "utf8")).profiles.codex; + const packageName = `${profile.agentRuntimePackage}-${target}`, packageVersion = `${profile.agentRuntimeVersion}-${target}`; + // Docker alone preinstalls its host binary. Keep npm's normal platform check + // and isolate this install so it cannot rewrite the pinned JavaScript graph. + const native = resolve(temporary, "host-runtime"); mkdirSync(native); + writeFileSync(resolve(native, "package.json"), JSON.stringify({ private: true, name: "paperclip-docker-codex-runtime", version: "1.0.0", + dependencies: { [packageName]: `npm:${profile.agentRuntimePackage}@${packageVersion}` } })); + execFileSync("npm", ["install", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"], { cwd: native, stdio: "inherit", timeout: 180_000 }); + const installed = resolve(native, "node_modules", packageName), installedManifest = resolve(installed, "package.json"); + const directoryStat = lstatSync(installed), manifestStat = lstatSync(installedManifest); + if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || realpathSync(installed) !== installed + || !manifestStat.isFile() || manifestStat.isSymbolicLink() || manifestStat.nlink !== 1 || manifestStat.size > 256 * 1024) throw new Error("Docker Codex host package is not an owned npm dependency"); + const installedMetadata = JSON.parse(readFileSync(installedManifest, "utf8")); + if (![packageName, profile.agentRuntimePackage].includes(installedMetadata.name) || installedMetadata.version !== packageVersion + || !installedMetadata.os?.includes("linux") || !installedMetadata.cpu?.includes("x64")) throw new Error("Docker Codex host package identity mismatch"); + cpSync(installed, resolve(staged, "node_modules", packageName), { recursive: true, dereference: false }); mergeBundledProviderGraph(staged, serverDirectory); - const stagedMetadata = JSON.parse(readFileSync(resolve(staged, "package.json"), "utf8")); - return { target, materialized: true, artifacts: stagedMetadata.paperclipProviderArtifacts, providerCalls: 0, lifecycleScriptsRun: false }; + return { target, materialized: true, packageName, packageVersion, installedBy: "npm", providerCalls: 0, lifecycleScriptsRun: false }; } finally { rmSync(temporary, { recursive: true, force: true }); } } @@ -468,7 +425,7 @@ export function applyBundledDependencyPatches(destinationDir, bundledDependencie } } -export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot = repoRoot, targets = nativeTargets } = {}) { +export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot = repoRoot } = {}) { const sourcePackagePath = resolve(sourceDir, "package.json"); const sourcePackage = JSON.parse(readFileSync(sourcePackagePath, "utf8")); const bundledDependencies = sourcePackage.bundleDependencies ?? sourcePackage.bundledDependencies ?? []; @@ -492,9 +449,8 @@ export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot = const rootPackage = JSON.parse(readFileSync(resolve(sourceRoot, "package.json"), "utf8")); const profileData = bundledDependencies.includes("@agentclientprotocol/codex-acp") ? JSON.parse(readFileSync(resolve(sourceRoot, "packages/paperclip-runner/acpx-profiles.json"), "utf8")) : undefined; - const runtimeData = profileData ? JSON.parse(readFileSync(resolve(sourceRoot, runtimeDataPath), "utf8")) : undefined; const { installManifest, profiles } = configureBundledProviderOverrides( - createBundledInstallManifest(publishManifest, bundledDependencies), bundledDependencies, rootPackage, profileData, runtimeData, + createBundledInstallManifest(publishManifest, bundledDependencies), bundledDependencies, rootPackage, profileData, ); writeFileSync(deployedPackagePath, `${JSON.stringify(installManifest, null, 2)}\n`); @@ -505,7 +461,7 @@ export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot = ); writeFileSync(deployedPackagePath, `${JSON.stringify(publishManifest, null, 2)}\n`); applyBundledDependencyPatches(destinationDir, bundledDependencies, sourceRoot); - if (profiles.length) writeFileSync(deployedPackagePath, `${JSON.stringify(stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles, runtimeData, { targets }), null, 2)}\n`); + if (profiles.length) writeFileSync(deployedPackagePath, `${JSON.stringify(stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles), null, 2)}\n`); if (bundledDependencies.includes("acpx")) { const acpxPackage = JSON.parse( diff --git a/scripts/verify-grok-npm-install.mjs b/scripts/verify-grok-npm-install.mjs index a113dde548c..e71085b64af 100644 --- a/scripts/verify-grok-npm-install.mjs +++ b/scripts/verify-grok-npm-install.mjs @@ -9,7 +9,7 @@ import { tmpdir } from 'node:os'; import { basename, dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { materializePublishManifest, prepareBundledPackage } from './prepare-bundled-package.mjs'; -import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, grokConsumerDockerArgs, installedCodexProbeSource } from './grok-public-install-sandbox.mjs'; +import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from './grok-public-install-sandbox.mjs'; const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..'); assert.equal(process.platform, 'linux', 'Run this verification on disposable EC2 Linux, not a developer host'); const root = mkdtempSync(join(tmpdir(), 'paperclip-grok-public-install-')); @@ -57,7 +57,10 @@ try { } run('npm', ['pack', '--ignore-scripts', '--pack-destination', root], target); const packed = readdirSync(root).filter(f => f.endsWith('.tgz') && !tarballs.includes(join(root, f))); - assert.equal(packed.length, 1); tarballs.push(join(root, packed[0])); + assert.equal(packed.length, 1); + const tarball = join(root, packed[0]); + assertNoBundledCodexPayloads(run('tar', ['-tzf', tarball]).toString().trim().split('\n')); + tarballs.push(tarball); } const assets = join(root, 'assets'); mkdirSync(assets, { mode: 0o755 }); const consumer = join(root, 'consumer'); mkdirSync(consumer); @@ -98,7 +101,9 @@ try { assert.match(codexVersion, /^\d+\.\d+\.\d+$/); writeFileSync(join(assets, 'codex-probe.mjs'), installedCodexProbeSource( '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/index.js', '/consumer', codexVersion), { mode: 0o644 }); - isolated(['node', '/packages/codex-probe.mjs']); + const codex = JSON.parse(isolated(['node', '/packages/codex-probe.mjs']).toString().trim()); + assert.equal(codex.codexConsumerHostOnly, true); + assert.equal(codex.codexPlatformPackageSource, 'official npm'); assert.ok(existsSync(join(installed, 'providers/grok/launcher.cjs'))); assert.equal(existsSync(join(consumer, 'node_modules/@paperclipai/grok-acp')), false); assert.equal(existsSync(join(installed, 'providers/grok/bin')), false); @@ -119,7 +124,7 @@ try { // Only the positive probe sees this file at the canonical sandbox path. run(process.execPath, [join(repo, 'packages/paperclip-runner/scripts/provision-grok.mjs'), prerequisite]); isolated(['node', '/packages/probe.mjs', 'present'], { prerequisite }); - console.log(JSON.stringify({ schema: 'paperclip.grok.public-npm-install.v1', sourceRevision, releaseVersion, lifecycleScriptsEnabled: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'none', consumerImage: GROK_PUBLIC_INSTALL_IMAGE, consumerUid, consumerLockPreserved: true, cleanNpmInstall: true, packageCount: needed.size, pinnedCodexCommandVerified: true, pinnedCodexVersion: codexVersion, builtinLauncherPresent: true, separateGrokPackage: false, npmProvisionedBinary: false, missingPrerequisiteRejected: true, provisionedBinaryVerified: true, commandLeaseVerified: true, providerCalls: 0 })); + console.log(JSON.stringify({ schema: 'paperclip.grok.public-npm-install.v1', sourceRevision, releaseVersion, lifecycleScriptsEnabled: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'none', consumerImage: GROK_PUBLIC_INSTALL_IMAGE, consumerUid, consumerLockPreserved: true, cleanNpmInstall: true, packageCount: needed.size, codexPackedPayloadsOmitted: true, codexPackedPackagesChecked: tarballs.length, ...codex, builtinLauncherPresent: true, separateGrokPackage: false, npmProvisionedBinary: false, missingPrerequisiteRejected: true, provisionedBinaryVerified: true, commandLeaseVerified: true, providerCalls: 0 })); } finally { rmSync(root, { recursive: true, force: true }); }