mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
<!-- Written in ASD-STE100 style: short sentences, active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner and the Codex adapters run agent shell commands inside a sandboxed Codex session with a strict environment allowlist > - The controller builds `shell_environment_policy.include_only` before the sandbox injects certificate-trust variables such as `SSL_CERT_FILE` and `GIT_SSL_CAINFO` > - The allowlist drops the injected variables, so managed `git` and `gh` commands cannot verify HTTPS against a runtime-provided CA > - This pull request allows the certificate-trust variable names through every environment policy stage, from the Rust process supervisor to the shell allowlist > - The benefit is that managed `git` and `gh` work again in sandboxes that require a runtime CA, while provider-credential isolation and the bounded allowlist stay in place ## Linked Issues or Issue Description - Fixes: #20019 - Refs #20038 — community pull request for the same defect. This change reviews the approach independently. The commit credits the community author as co-author. ## What Changed - Add `CERTIFICATE_ENVIRONMENT_KEYS` (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `GIT_SSL_CAINFO`, `NODE_EXTRA_CA_CERTS`, `DENO_CERT`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`) to `packages/paperclip-runner/src/configured-environment.ts` - Native Codex shell policy (`codex-security-config.ts`): always put the certificate names in `include_only`; set inheritance to `"all"` with `ignore_default_excludes=true`, bounded by the explicit allowlist - Pass the certificate names through the app-server environment filter, the ACPX spawn environment filter, the ACPX runtime sandbox `include_only`, the runner platform environment keys, and the Rust process supervisor base key list - Legacy and ACPX-engine Codex shell allowlists (`packages/adapter-utils/src/codex-shell-environment.ts`): always include the certificate names - Add a synthetic private-CA HTTPS journey test: a real `git ls-remote` fails TLS verification without the injected CA and succeeds with it, through the policy-filtered child environment - Document the contract in `doc/sandbox-shell-environment.md` and link it from `doc/DEVELOPING.md` ## Verification - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/codex/codex-security-config.test.ts src/configured-environment.test.ts src/drivers/codex/codex-shell-certificate-trust.test.ts src/drivers/codex/codex-app-server-driver.context-control.test.ts src/drivers/acpx/runtime-sandbox.test.ts` — 104 tests pass - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/codex-shell-environment.test.ts src/acpx-engine/execute.test.ts` — 270 tests pass - `pnpm --filter @paperclipai/adapter-codex-local exec vitest run src/server/execute.test.ts` — 10 tests pass - Codex driver lifecycle, conformance, recovery, and boundaries suites pass (103 tests); environment-builder suites pass (307 tests) - Red proof: with only the source fix reverted, the new regressions fail. The journey test shows `GIT_SSL_CAINFO` is undefined in the shell environment, and `git` fails TLS verification against the private-CA fixture - `cargo check` passes for `paperclip-runner-core`; `rustfmt --check` passes for the edited Rust file - The journey test needs `git` and `openssl`; it skips when either tool is absent ## Risks - The native shell policy now always sets `shell_environment_policy.inherit="all"` with `ignore_default_excludes=true`. Before, it set `"none"` when no credentials or task keys were projected. The explicit `include_only` allowlist still bounds every inherited name, so no new secret names can cross - The allowlist grows by seven non-secret certificate-trust names. Their values point at CA files. The sandbox filesystem policy still controls access to those files; this change grants no filesystem access - No persisted run, session, or launch identity changes shape. Sessions saved by the previous release resume unchanged; the new policy applies when the next launch builds its arguments - Provider credentials keep their existing exclusions at every stage ## Model Used - Claude Fable 5 (Anthropic, model ID `claude-fable-5`), extended thinking, agentic tool use, run through Claude Code. The implementation was written and reviewed independently against the community design in #20038; the community author is credited as co-author in the commit. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green (pending: checks run after this PR opens) - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (pending review) - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: everlastingcrown <everlastingcrown@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
421 lines
21 KiB
TypeScript
421 lines
21 KiB
TypeScript
import { usesPreconfiguredHome } from "../preconfigured-home.js";
|
|
import { CERTIFICATE_ENVIRONMENT_KEYS, configuredEnvironmentKeys } from "../../configured-environment.js";
|
|
import { resolve, isAbsolute, join, dirname, delimiter, relative, sep } from "node:path";
|
|
import { closeSync, constants, existsSync, fstatSync, openSync, realpathSync, readFileSync, statSync } from "node:fs";
|
|
import { createRequire } from "node:module";
|
|
import { QUALIFIED_ACPX_PROFILES } from "../acpx/qualified-profiles.js";
|
|
|
|
import {
|
|
githubCredentialEnvironmentKeys,
|
|
} from "../../github-credential-environment.js";
|
|
|
|
/** DNS and CA files can point outside the minimal /etc filesystem (systemd). */
|
|
export function codexNetworkReadOnlyRoots(source: NodeJS.ProcessEnv): string[] {
|
|
if (!codexNetworkAccess(source)) return [];
|
|
const roots = new Set<string>();
|
|
if (source.PAPERCLIP_RUNNER_NETWORK_ROOTS !== undefined) {
|
|
try {
|
|
const projected: unknown = JSON.parse(source.PAPERCLIP_RUNNER_NETWORK_ROOTS);
|
|
if (Array.isArray(projected)) for (const root of projected) {
|
|
if (typeof root === "string" && isAbsolute(root) && resolve(root) !== "/") roots.add(resolve(root));
|
|
}
|
|
} catch { /* A malformed controller projection must not expand access. */ }
|
|
} else {
|
|
for (const file of ["/etc/resolv.conf", "/etc/hosts", "/etc/nsswitch.conf", "/etc/ssl/certs", "/etc/ssl/cert.pem"]) {
|
|
try { roots.add(realpathSync(file)); } catch { /* Platform-specific optional resource. */ }
|
|
}
|
|
}
|
|
return [...roots];
|
|
}
|
|
|
|
/** Resolve executable resources only, without exposing their enclosing home. */
|
|
export function codexExecutableReadOnlyRoots(source: NodeJS.ProcessEnv, command = "codex"): string[] {
|
|
const roots = new Set<string>();
|
|
const add = (path: string) => {
|
|
try {
|
|
if (!isAbsolute(path) || resolve(path) === "/" || !existsSync(path)) return;
|
|
roots.add(resolve(path));
|
|
roots.add(realpathSync(path));
|
|
} catch { /* Missing resources remain a normal executable-resolution error. */ }
|
|
};
|
|
add(process.execPath);
|
|
const candidates = isAbsolute(command) ? [command]
|
|
: (source.PATH ?? "").split(delimiter).filter(isAbsolute).map(root => resolve(root, command));
|
|
const executable = candidates.find(path => {
|
|
try { const stat = statSync(path); return stat.isFile() && (process.platform === "win32" || (stat.mode & 0o111) !== 0); } catch { return false; }
|
|
});
|
|
if (!executable) return [...roots];
|
|
add(executable);
|
|
try {
|
|
const canonical = realpathSync(executable);
|
|
const manifestPath = resolve(dirname(canonical), "../package.json");
|
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.codex;
|
|
if (manifest.name !== "@openai/codex" || typeof bin !== "string"
|
|
|| realpathSync(resolve(dirname(manifestPath), bin)) !== canonical) return [...roots];
|
|
// The npm entrypoint launches the platform package's native executable,
|
|
// which Codex invokes again inside bwrap when starting each shell command.
|
|
const platformPackage = `@openai/codex-${process.platform}-${process.arch}`;
|
|
const normalizedPlatformManifest = manifest.optionalDependencies === undefined
|
|
? normalizedCodexPlatformManifest(manifestPath, platformPackage)
|
|
: undefined;
|
|
if (manifest.optionalDependencies?.[platformPackage] || normalizedPlatformManifest) {
|
|
const platformManifest = normalizedPlatformManifest
|
|
?? createRequire(manifestPath).resolve(`${platformPackage}/package.json`);
|
|
const packageRoot = realpathSync(dirname(platformManifest));
|
|
const vendor = realpathSync(resolve(packageRoot, "vendor"));
|
|
if (vendor.startsWith(`${packageRoot}/`)) add(vendor);
|
|
} else {
|
|
const packageRoot = realpathSync(dirname(manifestPath));
|
|
const vendor = realpathSync(resolve(packageRoot, "vendor"));
|
|
if (vendor.startsWith(`${packageRoot}/`)) add(vendor);
|
|
}
|
|
} catch { /* Standalone executable installations need no npm resources. */ }
|
|
return [...roots];
|
|
}
|
|
|
|
/** The published server, rather than its bundled JS wrapper, declares npm's host package. */
|
|
function normalizedCodexPlatformManifest(runtimeManifest: string, platformPackage: string): string | undefined {
|
|
const profile = QUALIFIED_ACPX_PROFILES.codex;
|
|
const runtime = readCodexPackageManifest(runtimeManifest);
|
|
if (runtime.name !== profile.agentRuntimePackage || runtime.optionalDependencies !== undefined) return undefined;
|
|
for (let root = dirname(dirname(runtimeManifest)), depth = 0; depth < 24; depth += 1) {
|
|
const serverManifest = resolve(root, "package.json");
|
|
if (existsSync(serverManifest)) {
|
|
const server = readCodexPackageManifest(serverManifest);
|
|
if (server.name === "@paperclipai/server") {
|
|
const bridgeDeclaration = server.dependencies?.[profile.agentServerPackage];
|
|
const platformDeclaration = server.optionalDependencies?.[platformPackage];
|
|
const declarationPrefix = `npm:${profile.agentRuntimePackage}@`;
|
|
const declarationSuffix = `-${process.platform}-${process.arch}`;
|
|
if (typeof bridgeDeclaration !== "string" || !bridgeDeclaration.trim()
|
|
|| typeof platformDeclaration !== "string" || !platformDeclaration.startsWith(declarationPrefix)
|
|
|| !platformDeclaration.endsWith(declarationSuffix)
|
|
|| !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(platformDeclaration.slice(declarationPrefix.length, -declarationSuffix.length))
|
|
|| !codexPathInside(resolve(root, "node_modules"), runtimeManifest)) return undefined;
|
|
const bridgeManifest = createRequire(serverManifest).resolve(`${profile.agentServerPackage}/package.json`);
|
|
if (!codexPathInside(resolve(root, "node_modules"), bridgeManifest)
|
|
|| realpathSync(bridgeManifest) !== bridgeManifest) return undefined;
|
|
const bridge = readCodexPackageManifest(bridgeManifest);
|
|
if (bridge.name !== profile.agentServerPackage
|
|
|| createRequire(bridgeManifest).resolve(`${profile.agentRuntimePackage}/package.json`) !== runtimeManifest) return undefined;
|
|
const runtimeSelection = createRequire(runtimeManifest).resolve(`${platformPackage}/package.json`);
|
|
const selected = createRequire(serverManifest).resolve(`${platformPackage}/package.json`);
|
|
if (runtimeSelection !== selected || realpathSync(selected) !== selected) return undefined;
|
|
const slot = (createRequire(serverManifest).resolve.paths(platformPackage) ?? []).some(directory => {
|
|
try {
|
|
return (dirname(directory) === root || codexPathInside(dirname(directory), root))
|
|
&& realpathSync(directory) === directory
|
|
&& selected === resolve(directory, platformPackage, "package.json")
|
|
&& realpathSync(dirname(selected)) === dirname(selected);
|
|
} catch { return false; }
|
|
});
|
|
if (!slot) return undefined;
|
|
const native = readCodexPackageManifest(selected);
|
|
if ((native.name !== platformPackage && native.name !== profile.agentRuntimePackage)
|
|
|| !Array.isArray(native.os) || !native.os.includes(process.platform)
|
|
|| !Array.isArray(native.cpu) || !native.cpu.includes(process.arch)) return undefined;
|
|
return selected;
|
|
}
|
|
}
|
|
const parent = dirname(root);
|
|
if (parent === root) break;
|
|
root = parent;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function codexPathInside(root: string, path: string): boolean {
|
|
const value = relative(root, path);
|
|
return value !== "" && value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value);
|
|
}
|
|
|
|
function readCodexPackageManifest(path: string): Record<string, unknown> & {
|
|
dependencies?: Record<string, unknown>;
|
|
optionalDependencies?: Record<string, unknown>;
|
|
} {
|
|
const descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
try {
|
|
const before = fstatSync(descriptor, { bigint: true });
|
|
if (!before.isFile() || before.nlink !== 1n || before.size < 1n || before.size > 256n * 1024n) throw new Error("Unsafe Codex package manifest");
|
|
const bytes = readFileSync(descriptor), after = fstatSync(descriptor, { bigint: true });
|
|
if (bytes.length !== Number(before.size) || before.dev !== after.dev || before.ino !== after.ino
|
|
|| before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) throw new Error("Codex package manifest changed during lookup");
|
|
const value: unknown = JSON.parse(bytes.toString("utf8"));
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Codex package manifest");
|
|
return value as ReturnType<typeof readCodexPackageManifest>;
|
|
} finally { closeSync(descriptor); }
|
|
}
|
|
|
|
export const CODEX_SKILLLESS_PERMISSION_PROFILE =
|
|
"paperclip-runner-workspace-only";
|
|
export const CODEX_PLANNING_PERMISSION_PROFILE =
|
|
"paperclip-runner-workspace-read-only";
|
|
export const CODEX_EXTERNAL_SANDBOX_PERMISSION_PROFILE =
|
|
"paperclip-runner-external-sandbox";
|
|
|
|
export function codexNetworkAccess(source: NodeJS.ProcessEnv = process.env): boolean {
|
|
return source.PAPERCLIP_RUNNER_NETWORK_ACCESS === "enabled";
|
|
}
|
|
|
|
function gitFilesystemRoots(source: NodeJS.ProcessEnv): { read: string[]; write: string[] } {
|
|
const read: string[] = [];
|
|
const write: string[] = [];
|
|
try {
|
|
const roots: unknown = JSON.parse(source.PAPERCLIP_GIT_METADATA_ROOTS ?? "[]");
|
|
if (Array.isArray(roots)) for (const root of roots) {
|
|
if (typeof root === "string" && isAbsolute(root) && resolve(root) !== "/") write.push(resolve(root));
|
|
}
|
|
} catch { /* Older controllers do not project Git metadata roots. */ }
|
|
if (source.PAPERCLIP_GITHUB_AUTH_MODE === "host" && source.PAPERCLIP_GITHUB_HOST_HOME) {
|
|
for (const relative of [".gitconfig", ".git-credentials", ".config/git", ".config/gh", ".ssh"]) {
|
|
read.push(join(source.PAPERCLIP_GITHUB_HOST_HOME, relative));
|
|
}
|
|
for (const root of [source.GH_CONFIG_DIR, source.GIT_CONFIG_GLOBAL, source.GIT_CONFIG_SYSTEM, source.SSH_AUTH_SOCK]) {
|
|
if (root && isAbsolute(root) && resolve(root) !== "/") read.push(resolve(root));
|
|
}
|
|
}
|
|
return { read: [...new Set(read)], write: [...new Set(write)] };
|
|
}
|
|
|
|
export const CODEX_PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS: readonly string[] = [
|
|
"OPENAI_API_KEY", "CODEX_API_KEY", "PAPERCLIP_AI_PROVIDER_KEY",
|
|
"OTEL_EXPORTER_OTLP_LOGS_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
|
|
];
|
|
|
|
export function usesExternalRunnerSandbox(source: NodeJS.ProcessEnv): boolean {
|
|
return source.PAPERCLIP_RUNNER_EXTERNAL_SANDBOX === "1";
|
|
}
|
|
|
|
const SKILLLESS_BASE_CONFIG = {
|
|
"skills.include_instructions": false,
|
|
include_apps_instructions: false,
|
|
include_collaboration_mode_instructions: true,
|
|
"features.apps": false,
|
|
"features.plugins": false,
|
|
"features.multi_agent": false,
|
|
"features.memories": false,
|
|
// Image generation stays on: Codex's built-in tool runs in the trusted
|
|
// app-server with the agent's existing provider auth. Disabling it makes the
|
|
// agent fall back to an OPENAI_API_KEY script the sandboxed shell cannot see,
|
|
// so it asks the user for a second key (N-12).
|
|
} as const;
|
|
|
|
export function codexCommandEnvironment(
|
|
source: NodeJS.ProcessEnv = process.env,
|
|
): Record<string, string> {
|
|
const environment: Record<string, string> = {};
|
|
for (const key of [
|
|
"PATH",
|
|
"PATHEXT",
|
|
"SystemRoot",
|
|
"WINDIR",
|
|
"LANG",
|
|
"LC_ALL",
|
|
] as const) {
|
|
const value = source[key];
|
|
if (value !== undefined) environment[key] = value;
|
|
}
|
|
if (usesPreconfiguredHome(source) && source.HOME) {
|
|
environment.HOME = source.HOME;
|
|
} else if (source.PAPERCLIP_GITHUB_AUTH_MODE === "host" && source.PAPERCLIP_GITHUB_HOST_HOME) {
|
|
environment.HOME = source.PAPERCLIP_GITHUB_HOST_HOME;
|
|
} else if (source.PAPERCLIP_GITHUB_LAUNCHER_DIR) {
|
|
environment.HOME = source.PAPERCLIP_GITHUB_LAUNCHER_DIR;
|
|
environment.ZDOTDIR = source.PAPERCLIP_GITHUB_LAUNCHER_DIR;
|
|
environment.BASH_ENV = `${source.PAPERCLIP_GITHUB_LAUNCHER_DIR}/.bashrc`;
|
|
}
|
|
return environment;
|
|
}
|
|
|
|
export function createSkilllessCodexThreadConfig(
|
|
_workingDirectory: string,
|
|
_source: NodeJS.ProcessEnv = process.env,
|
|
includeCollaborationModeInstructions = true,
|
|
): Record<string, unknown> {
|
|
return {
|
|
...SKILLLESS_BASE_CONFIG,
|
|
include_collaboration_mode_instructions:
|
|
includeCollaborationModeInstructions,
|
|
};
|
|
}
|
|
|
|
function collaborationThreadConfig(
|
|
includeCollaborationModeInstructions = true,
|
|
includeSkillInstructions = false,
|
|
) {
|
|
return {
|
|
...SKILLLESS_BASE_CONFIG,
|
|
"skills.include_instructions": includeSkillInstructions,
|
|
include_collaboration_mode_instructions:
|
|
includeCollaborationModeInstructions,
|
|
};
|
|
}
|
|
|
|
function tomlString(value: string): string {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
export const CODEX_UPDATE_PLAN_TOOL_CONFIG = "tools.update_plan.enabled=true";
|
|
|
|
export function createIsolatedCodexAppServerArgs(
|
|
source: NodeJS.ProcessEnv | undefined = undefined,
|
|
readOnlyRoots: string[] = [],
|
|
/** Server-registered run copy, never an environment/config-supplied root. */
|
|
instructionWorkingCopyRoot?: string,
|
|
protectedPaths: string[] = [],
|
|
disableWebSearch = false,
|
|
): string[] {
|
|
const explicitSource = source;
|
|
source ??= process.env;
|
|
const gitRoots = gitFilesystemRoots(source);
|
|
readOnlyRoots = [...new Set([...readOnlyRoots, ...codexNetworkReadOnlyRoots(source)])];
|
|
const networkAccess = codexNetworkAccess(source);
|
|
const externalRunnerSandbox = usesExternalRunnerSandbox(source);
|
|
const inheritedEnvironmentKeys = [
|
|
// Certificate-trust names stay inheritable: sandboxes inject their values
|
|
// into the execution environment after this policy is constructed.
|
|
...CERTIFICATE_ENVIRONMENT_KEYS,
|
|
...githubCredentialEnvironmentKeys(source),
|
|
...configuredEnvironmentKeys(explicitSource),
|
|
...["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"].filter(key => source[key] !== undefined),
|
|
];
|
|
// Codex filters the configured `set` values through include_only as well.
|
|
// Retain the explicit command PATH/HOME/locale settings, not ambient secrets.
|
|
const commandEnvironment = codexCommandEnvironment(source);
|
|
// Selected task values are inherited, never serialized into configuration argv.
|
|
for (const key of configuredEnvironmentKeys(explicitSource)) delete commandEnvironment[key];
|
|
if (instructionWorkingCopyRoot && source.AGENT_HOME === instructionWorkingCopyRoot) commandEnvironment.AGENT_HOME = instructionWorkingCopyRoot;
|
|
const shellEnvironmentKeys = [...new Set([...inheritedEnvironmentKeys, ...Object.keys(commandEnvironment)])].sort();
|
|
if (source.PAPERCLIP_GITHUB_LAUNCHER_DIR) readOnlyRoots = [...readOnlyRoots, source.PAPERCLIP_GITHUB_LAUNCHER_DIR];
|
|
const deniedHostRoots = usesPreconfiguredHome(source) ? [] : [
|
|
...new Set(
|
|
[source.HOME, source.CODEX_HOME]
|
|
.filter(
|
|
(value): value is string =>
|
|
typeof value === "string" && value.trim().length > 0,
|
|
)
|
|
.map((value) => resolve(value)),
|
|
),
|
|
];
|
|
// Codex saves built-in image results under CODEX_HOME/generated_images and
|
|
// tells the agent to copy them into the workspace. Expose only that folder.
|
|
// A preconfigured HOME is already granted, so add the rule only when the
|
|
// Codex home sits outside it (never narrow an existing HOME write grant).
|
|
const generatedImagesRoot = typeof source.CODEX_HOME === "string" && source.CODEX_HOME.trim()
|
|
? join(resolve(source.CODEX_HOME), "generated_images") : undefined;
|
|
const preconfiguredHome = usesPreconfiguredHome(source) && source.HOME ? resolve(source.HOME) : undefined;
|
|
const generatedImageRoots = generatedImagesRoot
|
|
&& !(preconfiguredHome && codexPathInside(preconfiguredHome, generatedImagesRoot))
|
|
? [generatedImagesRoot] : [];
|
|
const filesystemRules = [
|
|
`":root"="none"`,
|
|
`":minimal"="read"`,
|
|
`":tmpdir"="none"`,
|
|
...deniedHostRoots.map((path) => `${tomlString(path)}="none"`),
|
|
...protectedPaths.map((path) => `${tomlString(resolve(path))}="none"`),
|
|
...(usesPreconfiguredHome(source) && source.HOME ? [`${tomlString(source.HOME)}="write"`] : []),
|
|
...readOnlyRoots.map((path) => `${tomlString(resolve(path))}="read"`),
|
|
...generatedImageRoots.map((path) => `${tomlString(path)}="read"`),
|
|
...gitRoots.read.map((path) => `${tomlString(path)}="read"`),
|
|
...gitRoots.write.map((path) => `${tomlString(path)}="write"`),
|
|
...(instructionWorkingCopyRoot ? [`${tomlString(resolve(instructionWorkingCopyRoot))}="write"`] : []),
|
|
...(source.PAPERCLIP_GITHUB_BROKER_TOKEN && source.GH_CONFIG_DIR
|
|
? [`${tomlString(resolve(source.GH_CONFIG_DIR))}="write"`] : []),
|
|
`":workspace_roots"={"."="write"}`,
|
|
].join(",");
|
|
const planningFilesystemRules = externalRunnerSandbox ? [
|
|
`":root"="read"`,
|
|
...(source.PAPERCLIP_GITHUB_BROKER_TOKEN && source.GH_CONFIG_DIR
|
|
? [`${tomlString(resolve(source.GH_CONFIG_DIR))}="write"`] : []),
|
|
].join(",") : [
|
|
`":root"="none"`,
|
|
`":minimal"="read"`,
|
|
`":tmpdir"="none"`,
|
|
...deniedHostRoots.map((path) => `${tomlString(path)}="none"`),
|
|
...protectedPaths.map((path) => `${tomlString(resolve(path))}="none"`),
|
|
...(usesPreconfiguredHome(source) && source.HOME ? [`${tomlString(source.HOME)}="read"`] : []),
|
|
...readOnlyRoots.map((path) => `${tomlString(resolve(path))}="read"`),
|
|
...generatedImageRoots.map((path) => `${tomlString(path)}="read"`),
|
|
...[...gitRoots.read, ...gitRoots.write].map((path) => `${tomlString(path)}="read"`),
|
|
...(instructionWorkingCopyRoot ? [`${tomlString(resolve(instructionWorkingCopyRoot))}="read"`] : []),
|
|
...(source.PAPERCLIP_GITHUB_BROKER_TOKEN && source.GH_CONFIG_DIR
|
|
? [`${tomlString(resolve(source.GH_CONFIG_DIR))}="write"`] : []),
|
|
`":workspace_roots"={"."="read"}`,
|
|
].join(",");
|
|
const commandEnv = Object.entries(commandEnvironment)
|
|
.map(([key, value]) => `${key}=${tomlString(value)}`)
|
|
.join(",");
|
|
const defaultPermissionProfile = externalRunnerSandbox
|
|
? CODEX_EXTERNAL_SANDBOX_PERMISSION_PROFILE
|
|
: CODEX_SKILLLESS_PERMISSION_PROFILE;
|
|
return [
|
|
"-c",
|
|
`default_permissions=${tomlString(defaultPermissionProfile)}`,
|
|
"-c",
|
|
`permissions.${CODEX_SKILLLESS_PERMISSION_PROFILE}.filesystem={${filesystemRules}}`,
|
|
"-c",
|
|
`permissions.${CODEX_SKILLLESS_PERMISSION_PROFILE}.network.enabled=${networkAccess}`,
|
|
...(externalRunnerSandbox
|
|
? [
|
|
"-c",
|
|
`permissions.${CODEX_EXTERNAL_SANDBOX_PERMISSION_PROFILE}.filesystem={":root"="write"}`,
|
|
"-c",
|
|
`permissions.${CODEX_EXTERNAL_SANDBOX_PERMISSION_PROFILE}.network.enabled=${networkAccess}`,
|
|
]
|
|
: []),
|
|
"-c",
|
|
`permissions.${CODEX_PLANNING_PERMISSION_PROFILE}.filesystem={${planningFilesystemRules}}`,
|
|
"-c",
|
|
`permissions.${CODEX_PLANNING_PERMISSION_PROFILE}.network.enabled=${networkAccess}`,
|
|
...(externalRunnerSandbox
|
|
? ["-c", 'shell_environment_policy.inherit="all"',
|
|
"-c", "shell_environment_policy.ignore_default_excludes=true",
|
|
"-c", `shell_environment_policy.exclude=${JSON.stringify(CODEX_PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS)}`]
|
|
// Inheritance stays enabled so execution-side injected values (sandbox
|
|
// certificate trust) reach shells; include_only is the strict bound.
|
|
// Codex applies include_only after inheritance. Always emit the bounded
|
|
// allowlist: neither host mode nor a broker enables ambient secret access.
|
|
// Keep values in the process environment, never in argv/config diagnostics.
|
|
: ["-c", 'shell_environment_policy.inherit="all"',
|
|
"-c", "shell_environment_policy.ignore_default_excludes=true",
|
|
"-c", `shell_environment_policy.include_only=${JSON.stringify(shellEnvironmentKeys)}`]),
|
|
...(commandEnv.length > 0
|
|
? ["-c", `shell_environment_policy.set={${commandEnv}}`]
|
|
: []),
|
|
// Codex ships its update_plan checklist tool disabled. Paperclip renders it
|
|
// as the turn plan (`turn/plan/updated` -> `plan.updated`).
|
|
"-c",
|
|
CODEX_UPDATE_PLAN_TOOL_CONFIG,
|
|
...(externalRunnerSandbox
|
|
? ["--dangerously-bypass-approvals-and-sandbox"]
|
|
: []),
|
|
...(disableWebSearch ? ["-c", 'web_search="disabled"'] : []),
|
|
"app-server",
|
|
];
|
|
}
|
|
|
|
export function createSecuredCodexThreadParams(
|
|
workingDirectory: string,
|
|
mode: "default" | "plan" = "default",
|
|
includeCollaborationModeInstructions = true,
|
|
includeSkillInstructions = false,
|
|
source: NodeJS.ProcessEnv = process.env,
|
|
): Record<string, unknown> {
|
|
const permissionProfile =
|
|
mode === "default" && usesExternalRunnerSandbox(source)
|
|
? CODEX_EXTERNAL_SANDBOX_PERMISSION_PROFILE
|
|
: mode === "plan"
|
|
? CODEX_PLANNING_PERMISSION_PROFILE
|
|
: CODEX_SKILLLESS_PERMISSION_PROFILE;
|
|
return {
|
|
cwd: workingDirectory,
|
|
config: usesPreconfiguredHome(source) ? { "skills.include_instructions": true, include_collaboration_mode_instructions: includeCollaborationModeInstructions } : collaborationThreadConfig(
|
|
includeCollaborationModeInstructions,
|
|
includeSkillInstructions,
|
|
),
|
|
permissions: permissionProfile,
|
|
runtimeWorkspaceRoots: [workingDirectory],
|
|
};
|
|
}
|