OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
refactor(runtime): share executable and process helpers (#1581)
Michael D'Angelo70404e7c2fad
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 63caeb288..cfb760909 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -23,8 +23,9 @@ run `node plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs`.The MCP `typecheck` command checks that the generated resources are current.`pnpm --dir sdk/typescript run generate:models` also copies workbench argument-encoding from the plugin source into the SDK. Edit the plugin helper, then-regenerate its SDK copy. Historical finding normalization is maintained in the SDK.+encoding and executable path handling from the plugin source into the SDK. Edit the+plugin helper, then regenerate its SDK copy. Historical finding normalization is+maintained in the SDK.`pnpm --dir sdk/typescript run types` checks freshness.Model-based evaluations live in [`evals/`](evals/README.md), outside the plugindiff --git a/evals/secret-discovery/runtime.mts b/evals/secret-discovery/runtime.mtsindex db10ba522..f2956e1fa 100644--- a/evals/secret-discovery/runtime.mts+++ b/evals/secret-discovery/runtime.mts@@ -14,7 +14,7 @@ export const {} = await importModule({stdin: {contents: `export { DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID, preflightDeepScanWorkerPermissionProfile, deepScanPermissionProfileFallbackError } from "../../plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts";-export { executablePathForSpawn } from "../../plugins/codex-security/mcp-app/src/deep-scan/executable-path.ts";+export { executablePathForSpawn } from "../../plugins/codex-security/mcp-app/src/executable-path.ts";export { inlineToml } from "../../sdk/typescript/src/config.ts";export { bundledCodexSdkEnvironment } from "../../sdk/typescript/src/codex-sdk-environment.ts";`,resolveDir: import.meta.dirname,diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex 0a43cd25b..9e2d3a8d8 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -31,7 +31,7 @@ import {preflightProviderDefinitions,profileConfigOverrides,} from "../../../scripts/codex_profile.mjs";-import { executablePathForSpawn } from "./executable-path.js";+import { executablePathForSpawn } from "../executable-path.js";import { writePrivateFile } from "./artifacts.js";import {classifyCodexWorkerError,@@ -276,17 +276,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {private compactArtifactServer(request: CodexWorkerRequest,includePathsFile?: string,- ): Record<- string,- {- command: string;- args: string[];- env: Record<string, string>;- required: true;- startup_timeout_sec: number;- tool_timeout_sec: number;- }- > {+ ) {const scan = this.modelSettings.artifactContext;if (!scan) return {};diff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.tsindex fe2de4c32..289d22ece 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts@@ -6,7 +6,7 @@ import { createReadStream } from "node:fs";import { isDeepStrictEqual } from "node:util";import { version as MCP_APP_VERSION } from "../../package.json";import { DeepScanNonRetryableError } from "./errors.js";-import { executablePathForSpawn } from "./executable-path.js";+import { executablePathForSpawn } from "../executable-path.js";import { isPermissionProfileFallbackWarning } from "../../../scripts/codex_profile.mjs";/** The stable profile id selected by the worker's raw config overrides. */@@ -227,6 +227,14 @@ class AppServerPreflightClient {private closed = false;private childClosed = false;private readonly removeAbortListener: () => void;+ private readonly onStdioError = (error: Error): void => {+ const failure = codexExecutableStdioError(+ this.options.codexPath,+ this.options.context,+ );+ failure.message += "\n" + error.message;+ this.fail(failure);+ };constructor(private readonly options: RuntimeConfigReadOptions) {const args: string[] = [...(options.commandArgs ?? [])];@@ -257,16 +265,8 @@ class AppServerPreflightClient {crlfDelay: Infinity,});this.stdoutLines.on("line", (line) => this.consumeStdoutLine(line));- const onStdioError = (error: Error) => {- const failure = codexExecutableStdioError(- options.codexPath,- options.context,- );- failure.message += "\n" + error.message;- this.fail(failure);- };- this.stdoutLines.on("error", onStdioError);- this.child.stdin.on("error", onStdioError);+ this.stdoutLines.on("error", this.onStdioError);+ this.child.stdin.on("error", this.onStdioError);this.child.on("error", (error) => {this.fail(codexExecutableStartError(options.codexPath, error, options.context),@@ -410,14 +410,7 @@ class AppServerPreflightClient {return;}this.child.stdin.write(`${JSON.stringify(message)}\n`, (error) => {- if (error) {- const failure = codexExecutableStdioError(- this.options.codexPath,- this.options.context,- );- failure.message += "\n" + error.message;- this.fail(failure);- }+ if (error) this.onStdioError(error);});}diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executable-path.ts b/plugins/codex-security/mcp-app/src/executable-path.tssimilarity index 100%rename from plugins/codex-security/mcp-app/src/deep-scan/executable-path.tsrename to plugins/codex-security/mcp-app/src/executable-path.tsdiff --git a/plugins/codex-security/mcp-app/src/native.ts b/plugins/codex-security/mcp-app/src/native.tsindex 494540038..e954271b4 100644--- a/plugins/codex-security/mcp-app/src/native.ts+++ b/plugins/codex-security/mcp-app/src/native.ts@@ -3,14 +3,8 @@ import type { UnixBinding } from "../../native/binding.mjs";import type { WindowsBinding } from "../../native/windows-binding.mjs";import { nativeTarget } from "../../native/platform.mjs";-export function unixBinding(): UnixBinding {- return createRequire(import.meta.url)(- `./native/${nativeTarget}/unix.node`,- ) as UnixBinding;-}+const binding = (name: string) =>+ createRequire(import.meta.url)(`./native/${nativeTarget}/${name}.node`);-export function windowsBinding(): WindowsBinding {- return createRequire(import.meta.url)(- `./native/${nativeTarget}/windows.node`,- ) as WindowsBinding;-}+export const unixBinding = (): UnixBinding => binding("unix");+export const windowsBinding = (): WindowsBinding => binding("windows");diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.tsindex a77e799c9..cf9d4c94d 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts@@ -681,26 +681,50 @@ async function testUnexpectedTerminationRemainsRetryable() {}async function testStdioFailuresRemainRetryable() {- for (const stream of ["stdin", "stdout"] as const) {+ for (const stream of ["stdin", "stdout", "write callback"] as const) {await withFakeCodex({ hangAt: "initialize" },async ({ codexPath, cwd, readyPath, terminatedPath, children }) => {const running = preflight(codexPath, cwd);await waitForFile(readyPath);assert.equal(children.length, 1);- children[0][stream]!.destroy(- new Error("SECRET_REPOSITORY_PATH=/repo/private"),- );- await assert.rejects(- running,- (error: NodeJS.ErrnoException & { cause?: NodeJS.ErrnoException }) =>- error?.name === "Error" &&- error.message.includes(JSON.stringify(codexPath)) &&- error.message.includes(- "could not exchange app-server JSON-RPC over stdio",- ) &&- error.message.includes("SECRET_REPOSITORY_PATH"),- );+ const stdin = children[0].stdin!;+ const originalWrite = stdin.write;+ try {+ if (stream === "write callback") {+ stdin.write = ((+ _message: unknown,+ callback: (error: Error) => void,+ ) => {+ queueMicrotask(() =>+ callback(new Error("SECRET_REPOSITORY_PATH=/repo/private")),+ );+ return false;+ }) as typeof stdin.write;+ children[0].stdout!.emit(+ "data",+ Buffer.from('{"jsonrpc":"2.0","id":1,"result":{}}\n'),+ );+ } else {+ children[0][stream]!.destroy(+ new Error("SECRET_REPOSITORY_PATH=/repo/private"),+ );+ }+ await assert.rejects(+ running,+ (+ error: NodeJS.ErrnoException & { cause?: NodeJS.ErrnoException },+ ) =>+ error?.name === "Error" &&+ error.message.includes(JSON.stringify(codexPath)) &&+ error.message.includes(+ "could not exchange app-server JSON-RPC over stdio",+ ) &&+ error.message.includes("SECRET_REPOSITORY_PATH"),+ );+ } finally {+ stdin.write = originalWrite;+ }await assertPreflightStopped(children, terminatedPath);},);diff --git a/sdk/typescript/scripts/generate-models.cjs b/sdk/typescript/scripts/generate-models.cjsindex 685b251e8..58128a7d8 100644--- a/sdk/typescript/scripts/generate-models.cjs+++ b/sdk/typescript/scripts/generate-models.cjs@@ -87,7 +87,7 @@ async function generate() {}generate().then((models) => {- const shared = ["workbench-arguments"].map((name) => [+ const shared = ["workbench-arguments", "executable-path"].map((name) => [`${name}.ts`,`/* Generated from plugin ${name}.ts. Run \`pnpm generate:models\`. */\n` +readFileSync(diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex a5ac05635..a268379b2 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -76,6 +76,7 @@ const distModules = ["finding-retrieval","finding-normalization","workbench-arguments",+ "executable-path","finding-workflow","findings-client","findings-errors",diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.tsindex a13c7e147..24ae8b451 100644--- a/sdk/typescript/src/deduplication/codex-review.ts+++ b/sdk/typescript/src/deduplication/codex-review.ts@@ -1,8 +1,4 @@-import {- spawn,- type ChildProcessWithoutNullStreams,- type SpawnOptionsWithoutStdio,-} from "node:child_process";+import { spawn } from "node:child_process";import { mkdtemp, rm } from "node:fs/promises";import { homedir, tmpdir } from "node:os";import { join, resolve } from "node:path";@@ -21,6 +17,7 @@ import {executablePathForSpawn,expandHome,resolveCodexCommand,+ type StartCodex,} from "../runtime.js";import { CODEX_SECURITY_THREAD_SOURCES } from "../thread-source.js";import { VERSION } from "../version.js";@@ -76,12 +73,6 @@ class ReviewAttemptError extends Error {}}-type StartCodex = (- command: string,- args: readonly string[],- options: SpawnOptionsWithoutStdio & { stdio: ["pipe", "pipe", "pipe"] },-) => ChildProcessWithoutNullStreams;-interface Message {id?: string | number;method?: string;diff --git a/sdk/typescript/src/executable-path.ts b/sdk/typescript/src/executable-path.tsnew file mode 100644index 000000000..6bd72d108--- /dev/null+++ b/sdk/typescript/src/executable-path.ts@@ -0,0 +1,12 @@+/* Generated from plugin executable-path.ts. Run `pnpm generate:models`. */+import { win32 } from "node:path";++export function executablePathForSpawn(command: string): string {+ if (process.platform !== "win32" || !win32.isAbsolute(command))+ return command;+ // Root-relative paths still depend on the child's drive and working directory.+ const root = win32.parse(command).root;+ return root === "\\" || root === "/"+ ? command+ : win32.toNamespacedPath(command);+}diff --git a/sdk/typescript/src/feedback.ts b/sdk/typescript/src/feedback.tsindex 71c69f852..13be1e434 100644--- a/sdk/typescript/src/feedback.ts+++ b/sdk/typescript/src/feedback.ts@@ -1,8 +1,4 @@-import {- spawn,- type ChildProcessWithoutNullStreams,- type SpawnOptionsWithoutStdio,-} from "node:child_process";+import { spawn } from "node:child_process";import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -13,6 +9,7 @@ import {codexSecurityCredentialHome,executablePathForSpawn,resolveCodexCommand,+ type StartCodex,} from "./runtime.js";import { readSavedScanLogs, type ScanLogSource } from "./scan-logs.js";import {@@ -31,12 +28,6 @@ interface FeedbackOptions {signal?: AbortSignal;}-type StartCodex = (- command: string,- args: readonly string[],- options: SpawnOptionsWithoutStdio & { stdio: ["pipe", "pipe", "pipe"] },-) => ChildProcessWithoutNullStreams;-export async function sendFeedback(options: FeedbackOptions,startCodex: StartCodex = spawn,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 05c298e56..dd7867934 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -1,7 +1,14 @@+import { executablePathForSpawn } from "./executable-path.js";+export { executablePathForSpawn } from "./executable-path.js";import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";import { gitProtectionRoots } from "./targets.js";import { isNonEmptyString, notify } from "./value.js";-import { execFile as execFileCallback, spawn } from "node:child_process";+import {+ execFile as execFileCallback,+ spawn,+ type ChildProcessWithoutNullStreams,+ type SpawnOptionsWithoutStdio,+} from "node:child_process";import { randomUUID } from "node:crypto";import {chmodSync,@@ -40,7 +47,6 @@ import {relative,resolve,sep,- win32,} from "node:path";import { fileURLToPath } from "node:url";import { promisify } from "node:util";@@ -76,6 +82,12 @@ import {const execFile = promisify(execFileCallback);+export type StartCodex = (+ command: string,+ args: readonly string[],+ options: SpawnOptionsWithoutStdio & { stdio: ["pipe", "pipe", "pipe"] },+) => ChildProcessWithoutNullStreams;+export const MARKETPLACE_NAME = "codex-security-sdk";export const PLUGIN_NAME = "codex-security";const MARKETPLACE_MANIFEST = `${JSON.stringify(@@ -633,10 +645,7 @@ export function inspectWindowsCredentialAcl(};}-function windowsSecurityDescriptorRule(value: string): {- rule: string;- rest: string;-} {+function windowsSecurityDescriptorRule(value: string) {let depth = 0;let quoted = false;let escaped = false;@@ -2693,16 +2702,6 @@ export async function codexExecutableReadPaths(];}-export function executablePathForSpawn(command: string): string {- if (process.platform !== "win32" || !win32.isAbsolute(command))- return command;- // Root-relative paths still depend on the child's drive and working directory.- const root = win32.parse(command).root;- return root === "\\" || root === "/"- ? command- : win32.toNamespacedPath(command);-}-export async function bootstrapPlugin(codexHome: string,pluginRoot: string,