feat: qualify macOS Codex runner defaults and release artifacts

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-12 07:48:52 -05:00
1 parent 6ca302426b
commit 7b8d29a856
26 files changed
+1185 -111

No files matched your search

@@ -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, assertInstalledCodexPlatformProvenance, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from '../grok-public-install-sandbox.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertInstalledCodexPlatformProvenance, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource, installedDaemonProbeSource, macPublicInstallLifecycleProfile, macInstalledStartupProbeSource } 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]] : []);
@@ -141,6 +141,18 @@ test('the installed Codex probe exercises the public export and rejects incomple
writeFileSync(legacyCommand, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
writeFileSync(index, `export const resolvePinnedCodexCommand = () => ${JSON.stringify(legacyCommand)};`);
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /Selected Codex platform version must match the qualified pin/);
// Native Codex uses protocol compatibility, not the ACPX version allowlist.
// Keep exact official-npm host provenance and the selected resource boundary.
mkdirSync(join(legacy, 'vendor'));
writeFileSync(legacyCommand, '#!/bin/sh\nprintf "codex-cli 0.156.1\\n"\n', { mode: 0o755 });
writeFileSync(security, securitySource.replaceAll(JSON.stringify(nativeVendor), JSON.stringify(join(legacy, 'vendor'))));
writeFileSync(probe, installedCodexProbeSource(index, consumer, undefined, { nativeCodex: true }));
result = run(); assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).installedCodexVersion, 'codex-cli 0.156.1');
assert.equal(JSON.parse(result.stdout).codexQualifiedInstallationVerified, undefined);
writeFileSync(probe, installedCodexProbeSource(index, consumer, '0.160.0'));
writeFileSync(security, securitySource);
writeFileSync(index, `import { writeFileSync } from 'node:fs'; export const resolvePinnedCodexCommand = () => {
writeFileSync(${JSON.stringify(join(platform, 'package.json'))}, ${JSON.stringify(JSON.stringify({ ...manifest, altered: true }))});
return ${JSON.stringify(command)}; };`);
@@ -229,3 +241,47 @@ test('consumer provenance rejects bundled, foreign, inconsistent and non-officia
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/);
});
test('hosted Mac lifecycle denies OS networking and writes outside owned scratch', () => {
const profile = macPublicInstallLifecycleProfile('/Users/runner/work/_temp/owned-check');
assert.match(profile, /\(deny network\*\)/);
assert.match(profile, /\(deny file-write\*/);
assert.match(profile, /subpath "\/Users\/runner\/work\/_temp\/owned-check"/);
assert.throws(() => macPublicInstallLifecycleProfile('relative'), /absolute/);
assert.throws(() => macPublicInstallLifecycleProfile('/tmp/owned\0bad'), /absolute/);
const source = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8');
assert.match(source, /process.env.GITHUB_ACTIONS, 'true'/);
assert.match(source, /networkProbe, 'allowed'/);
assert.match(source, /networkProbe, 'denied'/);
assert.match(source, /error.code,'EPERM'/);
assert.match(source, /'rebuild', '--offline', '--ignore-scripts=false', '--dangerously-allow-all-scripts'/);
assert.match(source, /readFileSync\(sentinel, 'utf8'\), 'ok'/);
assert.match(source, /readFileSync\(join\(consumer, 'package-lock.json'\), 'utf8'\), lock/);
assert.match(source, /finally \{ rmSync\(root, \{ recursive: true, force: true \}\); \}/);
});
test('installed daemon proof uses the production host resolver and complete source-bound manifest', () => {
const source = installedDaemonProbeSource('/consumer/server/dist/vendor/paperclip-runner', '/consumer', 'a'.repeat(40));
assert.match(source, /defaultCapabilityRunnerdBinary\(\)/);
assert.match(source, /Object.keys\(manifest.platforms\).sort\(\), targets.sort\(\)/);
assert.match(source, /manifest.sourceRevision, "a{40}"/);
assert.match(source, /runnerBinaryTarget\(bytes\), target/);
assert.match(source, /createHash\('sha256'\)/);
assert.match(source, /metadata.binaryContractVersion, expected.contracts.runnerdArtifact/);
assert.doesNotMatch(source, /PAPERCLIP_RUNNERD_BINARY|runner\/target\/debug|execFileSync\('paperclip-runnerd'/);
});
test('Mac startup wiring normalizes only validated manifest digests and uses server-scoped tooling', () => {
const source = macInstalledStartupProbeSource('/owned/consumer', '/owned/consumer/server', 'sha256:' + 'a'.repeat(64), '/source/tests/runner-e2e/installed-cli.ts');
assert.match(source, /expectedRunnerSha256:"a{64}"/);
assert.doesNotMatch(source, /expectedRunnerSha256:"sha256:/);
for (const digest of ['a'.repeat(64), 'sha256:bad', 'sha512:' + 'a'.repeat(64), 'sha256:' + 'A'.repeat(64)]) {
assert.throws(() => macInstalledStartupProbeSource('/owned/consumer', '/owned/consumer/server', digest, '/source/helper.ts'), /verified SHA-256/);
}
const verifier = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8');
assert.match(verifier, /\['--import', 'tsx', startupFile\], join\(repo, 'server'\)/);
const closedEnvironment = verifier.match(/const env = \{ PATH: `\$\{tools\}[\s\S]*?\};/)[0];
assert.doesNotMatch(closedEnvironment, /NODE_PATH|NODE_OPTIONS|\.\.\.process.env/);
});
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import test from "node:test";
@@ -38,14 +39,14 @@ test("chaos verification isolates callers that verify the same source commit", (
test("canary reuses exact-source proof while stable keeps full verification", () => {
const releaseWorkflow = readWorkflow("release.yml");
const canary = releaseWorkflow.split(" verify_canary:\n")[1].split("\n publish_canary:")[0];
const canary = releaseWorkflow.match(/ verify_canary:\n[\s\S]*?(?=\n [a-z_]+:)/)[0];
assert.match(canary, /github\.repository == 'paperclipai\/paperclip' && github\.event_name == 'push' && github\.ref == 'refs\/heads\/master'/);
assert.match(canary, /actions: read/);
assert.match(canary, /ref: \$\{\{ github\.sha \}\}/);
assert.match(canary, /SOURCE_SHA: \$\{\{ github\.sha \}\}/);
assert.match(canary, /run: node scripts\/cloud-source-verification\.mjs "\$SOURCE_SHA"/);
assert.doesNotMatch(canary, /release-verify\.yml|continue-on-error|always\(\)/);
assert.match(releaseWorkflow, /publish_canary:\n\s+if: github\.event_name == 'push'\n\s+needs: verify_canary/);
assert.match(releaseWorkflow, /publish_canary:\n\s+if: .*github\.event_name == 'push'.*\n\s+needs: \[verify_canary, release_runner_source, release_runner_binaries\]/);
// The stable lane is gated on the stable channel since the nightly lane
// was added; a `needs:` line (for example a preflight job) may sit between
// the gate and the delegation.
@@ -480,3 +481,85 @@ test("direct protocol concurrency override only lowers the configured ceiling",
if (expected !== null) assert.equal(result.stdout, expected);
}
});
test("release daemon production uses exact-source native hosts and no publisher or provider permissions", () => {
const workflow = readWorkflow("release-verify.yml");
const producer = workflow.split(" runner_binaries:\n")[1];
for (const [target, host] of [["linux-x64", "ubuntu-latest"], ["darwin-arm64", "macos-15"], ["darwin-x64", "macos-15-intel"]]) {
assert.ok(producer.includes(`- target: ${target}\n host: ${host}`));
}
assert.match(producer, /persist-credentials: false/);
assert.match(producer, /contents: read/);
assert.doesNotMatch(producer, /secrets\.|id-token: write|contents: write|npm publish|environment:/);
assert.match(producer, /\[\[ "\$SOURCE_SHA" =~ \^\[a-f0-9\]\{40\}\$ \]\]/);
assert.match(producer, /git rev-parse HEAD/);
assert.match(producer, /process.platform \+ "-" \+ process.arch/);
assert.match(producer, /pnpm build:binary/);
assert.match(producer, /stage-release-runner-binaries.mjs record/);
for (const job of ["runner_chaos_evals", "typecheck", "general_tests", "serialized_tests", "runner_workflow_evals", "verify_paperclip_runner", "build"]) {
assert.ok(workflow.includes(`${job}:\n if: \${{ !inputs.runner_binaries_only }}`));
}
const release = readWorkflow("release.yml");
for (const job of ["publish_canary", "publish_nightly", "publish_beta", "preview_stable", "publish_stable"]) {
const block = release.split(` ${job}:\n`)[1].split(/\n [a-z_]+:\n/)[0];
assert.match(block, /needs: .*release_runner_binaries/);
assert.match(block, /pattern: \$\{\{ needs.release_runner_binaries.outputs.runner_artifact_prefix \}\}-\*/);
assert.match(block, /PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR/);
}
const script = readFileSync(path.join(repoRoot, 'scripts/release.sh'), 'utf8');
assert.ok(script.indexOf('assemble-daemons "$PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR"') < script.indexOf('scripts/build-standalone-public-packages.mjs'));
assert.match(script, /cp -R .*paperclip-runner\/dist\/bin\/\." .*server\/dist\/vendor\/paperclip-runner\/bin\//);
assert.match(script, /elif \[ "\$dry_run" = false \]; then[\s\S]*?release_fail "Public releases require/);
});
test("premerge Mac qualification consumes the same Linux-packed npm bytes without publishing", () => {
const smoke = readWorkflow("release-smoke.yml");
assert.match(smoke, /smoke_service:\n\s+if: inputs.qualification_source_sha == ''/);
assert.match(smoke, /smoke:\n\s+if: inputs.qualification_source_sha == ''/);
const qualification = smoke.split(" qualification_daemons:\n")[1];
assert.doesNotMatch(qualification, /secrets\.|npm publish|id-token: write|contents: write|continue-on-error/);
assert.match(qualification, /runner_binaries_only: true/);
assert.match(qualification, /PAPERCLIP_RUNNER_PUBLIC_PACKS_DIR/);
assert.match(qualification, /if: \$\{\{ !cancelled\(\) && steps.pack_identity.outputs.available == 'true' \}\}/);
assert.match(qualification, /name: \$\{\{ inputs.artifact_name \}\}-public-packages/);
assert.match(qualification, /--mac-consumer/);
assert.match(qualification, /host: macos-15\n/);
assert.match(qualification, /host: macos-15-intel\n/);
assert.match(qualification, /pnpm install --ignore-scripts --no-frozen-lockfile/);
});
test("historical promotion sources keep their packaging path while new sources require daemon assembly", () => {
const workflow = readWorkflow("release.yml");
const selector = workflow.split(' - name: Read the exact source packaging contract')[1].split('\n release_runner_binaries:')[0];
const script = selector.split(' run: |\n')[1].split('\n').map(line => line.startsWith(' ') ? line.slice(10) : line).join('\n');
const root = mkdtempSync(path.join(tmpdir(), 'release-source-contract-'));
try {
const tools = path.join(root, 'tools'); mkdirSync(tools);
writeFileSync(path.join(tools, 'git'), '#!/bin/sh\ncase "$1" in\nrev-parse) printf "%s\\n" "$FIXTURE_HEAD";;\nshow) cat "$FIXTURE_SOURCE";;\n*) exit 3;;\nesac\n', { mode: 0o755 });
const source = path.join(root, 'release.sh'), output = path.join(root, 'outputs');
for (const [contents, required] of [['pnpm build\n', false], ['assemble-daemons "$PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR" "$SOURCE_SHA"\n', true]]) {
writeFileSync(source, contents); writeFileSync(output, '');
const result = spawnSync('bash', ['-euo', 'pipefail', '-c', script], { encoding: 'utf8', env: {
PATH: `${tools}:/usr/bin:/bin`, SOURCE_SHA: 'a'.repeat(40), FIXTURE_HEAD: 'a'.repeat(40), FIXTURE_SOURCE: source, GITHUB_OUTPUT: output,
} });
assert.equal(result.status, 0, result.stderr);
assert.match(readFileSync(output, 'utf8'), new RegExp(`required=${required}`));
}
const result = spawnSync('bash', ['-euo', 'pipefail', '-c', script], { encoding: 'utf8', env: {
PATH: `${tools}:/usr/bin:/bin`, SOURCE_SHA: 'a'.repeat(40), FIXTURE_HEAD: 'b'.repeat(40), FIXTURE_SOURCE: source, GITHUB_OUTPUT: output,
} });
assert.equal(result.status, 1, 'Wrong checkout cannot opt out of mandatory assembly');
const unreadable = spawnSync('bash', ['-euo', 'pipefail', '-c', script], { encoding: 'utf8', env: {
PATH: `${tools}:/usr/bin:/bin`, SOURCE_SHA: 'a'.repeat(40), FIXTURE_HEAD: 'a'.repeat(40), FIXTURE_SOURCE: path.join(root, 'absent'), GITHUB_OUTPUT: output,
} });
assert.equal(unreadable.status, 1, 'A failed immutable source read must not masquerade as a legacy source');
} finally { rmSync(root, { recursive: true, force: true }); }
for (const job of ['publish_canary','publish_nightly','publish_beta','preview_stable','publish_stable']) {
const block = workflow.split(` ${job}:\n`)[1].split(/\n [a-z_]+:\n/)[0];
assert.match(block, /needs.release_runner_source.result == 'success'/);
assert.match(block, /needs.release_runner_source.outputs.required == 'false' \|\| needs.release_runner_binaries.result == 'success'/);
assert.match(block, /Download exact-source release daemon receipts\n\s+if: needs.release_runner_source.outputs.required == 'true'/);
}
});
+13 -3
View File
@@ -43,15 +43,25 @@ export function paperclipRunnerBinaryNeedsBuild({
nativeRunnerRequired,
configuredBinary,
platform = process.platform,
architecture = process.arch,
}) {
if (!nativeRunnerRequired) return false;
if (configuredBinary?.trim()) return false;
const executable = platform === "win32" ? "paperclip-runnerd.exe" : "paperclip-runnerd";
const packageRoot = path.join(repoRoot, "packages", "paperclip-runner");
const stagedBinary = path.join(packageRoot, "dist", "bin", executable);
const binaryStat = statSync(stagedBinary, { throwIfNoEntry: false });
if (!binaryStat?.isFile()) return true;
// Match production resolution: a staged release target takes precedence over
// the flat source-build output. Remote Mac builds must not trigger Cargo just
// because only the normal darwin-<arch> release executable is present.
let binaryStat;
for (const binary of [
path.join(packageRoot, "dist", "bin", `${platform}-${architecture}`, executable),
path.join(packageRoot, "dist", "bin", executable),
]) {
const candidate = statSync(binary, { throwIfNoEntry: false });
if (candidate?.isFile()) { binaryStat = candidate; break; }
}
if (!binaryStat) return true;
const runnerRoot = path.join(packageRoot, "runner");
const buildInputs = [
+71 -9
View File
@@ -60,7 +60,7 @@ export function assertInstalledCodexPlatformProvenance(lock, installed, target)
// 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) {
export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersion, { nativeCodex = false } = {}) {
return `
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
@@ -118,11 +118,11 @@ export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersi
assert.ok(selectedPlatform, 'Codex wrapper must resolve an official host platform package from its installed graph');
const selectedMetadata = JSON.parse(readFileSync(selectedPlatformManifest, 'utf8'));
assert.deepEqual(selectedMetadata, selectedPlatform.manifest, 'Selected Codex platform metadata must match its scanned provenance');
assert.equal(selectedMetadata.version, ${JSON.stringify(expectedVersion)} + '-' + process.platform + '-' + process.arch,
'Selected Codex platform version must match the qualified pin');
${nativeCodex ? '' : `assert.equal(selectedMetadata.version, ${JSON.stringify(expectedVersion)} + '-' + process.platform + '-' + process.arch,
'Selected Codex platform version must match the qualified pin');`}
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');
env: { PATH: process.env.PATH, HOME: process.env.HOME, NODE_PATH: '' } }).trim();
${nativeCodex ? "assert.match(version, /^codex-cli /, 'Installed official Codex command must execute');" : `assert.equal(version, 'codex-cli ' + ${JSON.stringify(expectedVersion)}, 'Installed Codex version must match the qualified pin');`}
const vendor = dirname(index);
const integrityPath = join(vendor, 'drivers/acpx/installation-integrity.js');
const profilesPath = join(vendor, 'drivers/acpx/qualified-profiles.js');
@@ -138,19 +138,81 @@ export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersi
assert.ok(!readRoots.includes(platformRoot) && !readRoots.includes(root) && !readRoots.includes(sandboxSource.HOME), 'Codex sandbox must not grant enclosing npm or credential-home access');
const sandboxArgs = createIsolatedCodexAppServerArgs(sandboxSource, readRoots).join('\\n');
assert.ok(sandboxArgs.includes(JSON.stringify(nativeVendor) + '="read"'), 'Codex sandbox configuration must retain the selected native executable resources');
const { createAcpxPackageJsonResolver, verifyQualifiedAcpxInstallation } = await import(pathToFileURL(integrityPath).href);
${nativeCodex ? '' : `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, codexSelectedPlatformPath: selectedPlatform.path, codexSelectedPlatformVersion: selectedMetadata.version, codexNativeSandboxResourcesVerified: true, codexQualifiedInstallationVerified: true, codexCommandLeaseVerified: true, providerCalls: 0 }));
await lease.close();`}
console.log(JSON.stringify({ pinnedCodexCommandVerified: true, installedCodexVersion: version,
...provenance, codexSelectedPlatformPath: selectedPlatform.path, codexSelectedPlatformVersion: selectedMetadata.version,
codexNativeSandboxResourcesVerified: true,
${nativeCodex ? '' : `pinnedCodexVersion: ${JSON.stringify(expectedVersion)}, codexQualifiedInstallationVerified: true, codexCommandLeaseVerified: true,`}
providerCalls: 0 }));
`;
}
/** The installed consumer must select its packaged host daemon, never PATH. */
export function installedDaemonProbeSource(outputRoot, consumerRoot, sourceRevision) {
return `
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { readFileSync, realpathSync } from 'node:fs';
import { isAbsolute, join, relative, sep } from 'node:path';
import { pathToFileURL } from 'node:url';
const root = realpathSync(${JSON.stringify(consumerRoot)}), output = realpathSync(${JSON.stringify(outputRoot)});
const inside = path => { const value = relative(root, realpathSync(path)); return value !== '' && value !== '..' && !value.startsWith('..' + sep) && !isAbsolute(value); };
assert.ok(inside(output));
const { defaultCapabilityRunnerdBinary } = await import(pathToFileURL(join(output, 'live/runnerd-codex-transport.js')).href);
const { runnerBinaryTarget } = await import(pathToFileURL(join(output, 'live/runner-binary.js')).href);
const { parsePaperclipRunnerdBuildMetadata } = await import(pathToFileURL(join(output, 'evals/runnerd-artifact.js')).href);
const { PAPERCLIP_RUNNER_BUILD_METADATA: expected } = await import(pathToFileURL(join(output, 'evals/build-metadata.js')).href);
const manifest = JSON.parse(readFileSync(join(output, 'bin/release-manifest.json'), 'utf8'));
const targets = ['darwin-arm64', 'darwin-x64', 'linux-x64'];
assert.equal(manifest.schema, 'paperclip.runner.release-binaries.v1');
assert.equal(manifest.sourceRevision, ${JSON.stringify(sourceRevision)});
assert.deepEqual(Object.keys(manifest.platforms).sort(), targets.sort());
for (const target of targets) {
const record = manifest.platforms[target];
assert.equal(record.path, target + '/paperclip-runnerd');
const file = join(output, 'bin', record.path); assert.ok(inside(file));
const bytes = readFileSync(file);
assert.equal(runnerBinaryTarget(bytes), target);
assert.equal('sha256:' + createHash('sha256').update(bytes).digest('hex'), record.sha256);
}
const target = process.platform + '-' + process.arch, selected = defaultCapabilityRunnerdBinary();
assert.ok(inside(selected));
assert.equal(realpathSync(selected), realpathSync(join(output, 'bin', manifest.platforms[target].path)), 'Production must select the packaged host daemon');
const metadata = parsePaperclipRunnerdBuildMetadata(JSON.parse(execFileSync(selected, ['--build-metadata'], {
timeout: 15000, maxBuffer: 64 * 1024, encoding: 'utf8', env: { PATH: process.env.PATH, HOME: process.env.HOME, NODE_PATH: '' },
})));
assert.equal(metadata.binaryContractVersion, expected.contracts.runnerdArtifact);
assert.equal(metadata.nativeExecutionVersion, expected.contracts.nativeExecution);
assert.equal(metadata.harnessDriverVersion, expected.contracts.harnessDriver);
assert.equal(metadata.prp.name, expected.prp.name);
assert.ok(metadata.prp.minimumVersion <= expected.prp.maximumVersion && metadata.prp.maximumVersion >= expected.prp.minimumVersion);
console.log(JSON.stringify({ installedRunnerDaemonVerified: true, target, sourceRevision: manifest.sourceRevision,
sha256: manifest.platforms[target].sha256, buildMetadata: metadata, providerCalls: 0 }));
`;
}
// Hosted, credential-free Mac consumers defer only npm lifecycle execution.
// Offline npm flags are not an OS network boundary; sandbox-exec supplies it.
export function macPublicInstallLifecycleProfile(ownedRoot) {
if (!ownedRoot.startsWith('/') || ownedRoot.includes('\0')) throw new Error('Mac lifecycle requires an absolute owned root');
return `(version 1)\n(allow default)\n(deny network*)\n(deny file-write* (require-all (require-not (subpath ${JSON.stringify(ownedRoot)})) (require-not (literal "/dev/null"))))\n`;
}
export function macInstalledStartupProbeSource(consumerRoot, serverRoot, runnerDigest, helperPath) {
if (!/^sha256:[a-f0-9]{64}$/.test(runnerDigest)) throw new Error('Installed Mac startup requires the verified SHA-256 manifest identity');
return `import { probeInstalledCodexStartup } from ${JSON.stringify(helperPath)};
console.log(JSON.stringify(await probeInstalledCodexStartup({consumerRoot:${JSON.stringify(consumerRoot)},
serverRoot:${JSON.stringify(serverRoot)},expectedRunnerSha256:${JSON.stringify(runnerDigest.slice(7))}})));`;
}
export function grokConsumerDockerArgs({ assets, consumer, cache, command, uid, gid, download = false, prerequisite, temporarySizeMiB = 256, temporaryExecutable = false }) {
if (!Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(gid) || gid <= 0) {
throw new Error('Public-install verification requires an unprivileged host user');
+10
View File
@@ -284,6 +284,16 @@ release_info ""
release_info "==> Step 2/7: Building workspace artifacts..."
cd "$REPO_ROOT"
pnpm build
# Hosted producers supply data-only, hash/source/architecture-bound daemon
# receipts. Assemble after the build (which stages its host binary), before
# public packages are packed. The server vendors this same compiled runner.
if [ -n "${PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR:-}" ]; then
node "$REPO_ROOT/packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs" \
assemble-daemons "$PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR" "$(git rev-parse HEAD)"
cp -R "$REPO_ROOT/packages/paperclip-runner/dist/bin/." "$REPO_ROOT/server/dist/vendor/paperclip-runner/bin/"
elif [ "$dry_run" = false ]; then
release_fail "Public releases require the three hosted runner daemon artifacts; use the supported Release workflow."
fi
node "$REPO_ROOT/scripts/build-standalone-public-packages.mjs"
bash "$REPO_ROOT/scripts/prepare-server-ui-dist.sh"
for pkg_dir in server packages/adapters/claude-local packages/adapters/codex-local; do
+102 -2
View File
@@ -4,14 +4,95 @@
// explicit and separate from npm installation, and is removed in finally.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { createServer } from 'node:net';
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, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from './grok-public-install-sandbox.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource, installedDaemonProbeSource, macPublicInstallLifecycleProfile, macInstalledStartupProbeSource } from './grok-public-install-sandbox.mjs';
import { retainRunnerQualificationPackages } from './retain-runner-qualification-packages.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
async function verifyMacConsumer(packageDirectory, sourceRevision, receiptPath) {
assert.equal(process.env.GITHUB_ACTIONS, 'true', 'Mac clean consumers run only on disposable hosted CI');
assert.equal(process.platform, 'darwin');
assert.ok(['arm64', 'x64'].includes(process.arch));
assert.match(sourceRevision, /^[a-f0-9]{40}$/);
const packages = realpathSync(packageDirectory);
const manifest = JSON.parse(readFileSync(join(packages, 'manifest.json'), 'utf8'));
assert.equal(manifest.schema, 'paperclip.runner.public-packages/v1');
assert.equal(manifest.sourceRevision, sourceRevision);
assert.ok(manifest.archives.some(entry => entry.name === '@paperclipai/server'));
assert.ok(manifest.archives.some(entry => entry.name === 'paperclipai'));
assert.equal(new Set(manifest.archives.map(entry => entry.name)).size, manifest.archives.length);
const root = realpathSync(mkdtempSync(join(tmpdir(), 'paperclip-mac-public-install-')));
try {
const consumer = join(root, 'consumer'), home = join(root, 'home'), tools = join(root, 'tools');
for (const directory of [consumer, home, tools, join(root, 'tmp'), join(root, 'cache')]) mkdirSync(directory);
const npmCli = realpathSync(execFileSync('/usr/bin/which', ['npm'], { encoding: 'utf8' }).trim());
symlinkSync(process.execPath, join(tools, 'node'));
// npm subprocesses get a Node-only owned tool directory; no ambient harness
// command can hide missing installed dependencies.
const env = { PATH: `${tools}:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: home, TMPDIR: join(root, 'tmp'),
npm_config_cache: join(root, 'cache'), npm_config_audit: 'false', npm_config_fund: 'false' };
const run = (command, args, cwd = consumer) => execFileSync(command, args, { cwd, env,
timeout: 10 * 60_000, maxBuffer: 32 * 1024 * 1024, encoding: 'utf8' });
const tarballs = manifest.archives.map(entry => {
assert.match(entry.file, /^[A-Za-z0-9._-]+\.tgz$/); assert.match(entry.sha256, /^[a-f0-9]{64}$/);
const path = join(packages, entry.file);
assert.equal(realpathSync(path), path);
assert.equal(createHash('sha256').update(readFileSync(path)).digest('hex'), entry.sha256);
assertNoBundledCodexPayloads(run('/usr/bin/tar', ['-tzf', path]).trim().split('\n'));
return path;
});
writeFileSync(join(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' }));
const sentinelSource = join(root, 'lifecycle-sentinel'); mkdirSync(sentinelSource);
writeFileSync(join(sentinelSource, 'package.json'), JSON.stringify({ name: 'paperclip-verification-lifecycle-sentinel', version: '1.0.0',
scripts: { postinstall: 'node -e "require(\'node:fs\').writeFileSync(\'lifecycle-ran\', \'ok\')"' } }));
run(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--pack-destination', root], sentinelSource);
const sentinelTar = join(root, readdirSync(root).find(name => name.endsWith('.tgz')));
run(process.execPath, [npmCli, 'install', '--ignore-scripts', '--omit=dev', ...tarballs, sentinelTar]);
const sentinel = join(consumer, 'node_modules/paperclip-verification-lifecycle-sentinel/lifecycle-ran');
assert.equal(existsSync(sentinel), false);
const lock = readFileSync(join(consumer, 'package-lock.json'), 'utf8');
const profile = join(root, 'lifecycle.sb'); writeFileSync(profile, macPublicInstallLifecycleProfile(root));
const listener = createServer(socket => socket.end());
await new Promise((resolve, reject) => { listener.once('error', reject); listener.listen(0, '127.0.0.1', resolve); });
try {
const port = listener.address().port;
const networkProbe = `import assert from 'node:assert/strict'; import net from 'node:net';
const socket = net.connect({host:'127.0.0.1',port:${port}}); socket.setTimeout(3000,()=>process.exit(2));
socket.once('connect',()=>{socket.destroy(); ${"process.argv[1] === 'denied' ? process.exit(3) : process.exit(0)"};});
socket.once('error',error=>{assert.equal(process.argv[1],'denied'); assert.equal(error.code,'EPERM');});`;
run(process.execPath, ['--input-type=module', '-e', networkProbe, 'allowed']);
run('/usr/bin/sandbox-exec', ['-f', profile, process.execPath, '--input-type=module', '-e', networkProbe, 'denied']);
} finally { await new Promise(resolve => listener.close(resolve)); }
run('/usr/bin/sandbox-exec', ['-f', profile, process.execPath, npmCli, 'rebuild', '--offline', '--ignore-scripts=false', '--dangerously-allow-all-scripts', '--foreground-scripts']);
assert.equal(readFileSync(sentinel, 'utf8'), 'ok');
assert.equal(readFileSync(join(consumer, 'package-lock.json'), 'utf8'), lock);
for (const entry of manifest.archives) {
assert.equal(JSON.parse(readFileSync(join(consumer, 'node_modules', entry.name, 'package.json'))).version, manifest.releaseVersion);
}
const server = join(consumer, 'node_modules/@paperclipai/server'), installed = join(server, 'dist/vendor/paperclip-runner');
const probe = (name, source) => { const file = join(root, name); writeFileSync(file, source); return JSON.parse(run(process.execPath, [file]).trim()); };
const daemon = probe('daemon-probe.mjs', installedDaemonProbeSource(installed, consumer, sourceRevision));
const codex = probe('codex-probe.mjs', installedCodexProbeSource(join(installed, 'index.js'), consumer, undefined, { nativeCodex: true }));
const startupScript = macInstalledStartupProbeSource(consumer, server, daemon.sha256, join(repo, 'tests/runner-e2e/installed-cli.ts'));
const startupFile = join(root, 'startup-probe.mts'); writeFileSync(startupFile, startupScript);
const startup = JSON.parse(run(process.execPath, ['--import', 'tsx', startupFile], join(repo, 'server')).trim());
const receipt = { schema: 'paperclip.runner.mac-public-install.v1', sourceRevision, platform: process.platform, architecture: process.arch,
cleanNpmInstall: true, packageCount: manifest.archives.length, codexPackedPayloadsOmitted: true,
consumerLockPreserved: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'sandbox-exec denied (loopback negative control)',
...daemon, ...codex, startup, providerCalls: 0 };
writeFileSync(receiptPath, JSON.stringify(receipt, null, 2) + '\n');
console.log(JSON.stringify(receipt));
} finally { rmSync(root, { recursive: true, force: true }); }
}
if (process.argv[2] === '--mac-consumer') {
assert.equal(process.argv.length, 6, 'Usage: --mac-consumer PACKAGE_DIRECTORY SOURCE_SHA RECEIPT_PATH');
await verifyMacConsumer(process.argv[3], process.argv[4], process.argv[5]);
} else {
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-'));
const prerequisite = join(root, 'native/grok');
@@ -64,6 +145,24 @@ try {
assertNoBundledCodexPayloads(run('tar', ['-tzf', tarball]).toString().trim().split('\n'));
tarballs.push(tarball);
}
// Preserve the exact Linux-produced public tarballs for independent Mac
// consumers even if a later Linux runtime probe fails. This is a packaging
// receipt, never an installation or provider-admission pass.
if (process.env.PAPERCLIP_RUNNER_PUBLIC_PACKS_DIR) {
const output = resolve(process.env.PAPERCLIP_RUNNER_PUBLIC_PACKS_DIR);
assert.equal(JSON.parse(readFileSync(join(repo, 'server/dist/build-info.json'))).commit, sourceRevision);
assert.ok(!existsSync(output), 'Never replace retained public packages');
mkdirSync(output, { recursive: true });
const { createHash } = await import('node:crypto');
const archives = [...needed].map((name, index) => {
const file = basename(tarballs[index]); cpSync(tarballs[index], join(output, file));
return { name, file, sha256: createHash('sha256').update(readFileSync(tarballs[index])).digest('hex') };
});
writeFileSync(join(output, 'manifest.json'), JSON.stringify({
schema: 'paperclip.runner.public-packages/v1', sourceRevision, releaseVersion,
publicInstallationVerified: false, providerCalls: 0, archives,
}, null, 2) + '\n');
}
const assets = join(root, 'assets'); mkdirSync(assets, { mode: 0o755 });
const consumer = join(root, 'consumer'); mkdirSync(consumer);
const cache = join(root, 'cache'); mkdirSync(cache);
@@ -153,3 +252,4 @@ try {
} finally {
rmSync(root, { recursive: true, force: true });
}
}