Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

refactor(sdk): use one Codex executable for all operations (#365)

ianw-oaib6e3f71db970
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index c46f521b9..e32c4e8da 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -420,6 +420,7 @@ The CLI and SDK recognize the following user-configurable environment:
| `LOG_LEVEL` | CLI-only fallback when `CODEX_SECURITY_LOG_LEVEL` is unset. |
| `CODEX_SECURITY_STATE_DIR` | Override the private scan-history, workbench, and default artifact directory. |
| `CODEX_HOME` | Set the ambient Codex home for file-backed sign-in and default state; defaults to `~/.codex`. |
+| `CODEX_CLI_PATH` | Use another Codex executable for authentication, plugin setup, scans, and nested workers. |
| `PYTHON` | Select a Python interpreter when `--python` or SDK `pythonPath` is not set. |
| `GH_HOST` | Select a GitHub Enterprise host during interactive `bulk-scan` discovery. |
| `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Disable interactive update notices when either variable is defined. |
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 9bcac10de..ef73a7f55 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -1003,7 +1003,12 @@ export class CodexSecurity {
};
const sdkCodexConfig = { ...preflightConfig };
delete sdkCodexConfig["projects"];
+ const codexPathOverride = environmentValue(
+ this.#dependencies.environment,
+ "CODEX_CLI_PATH",
+ )?.trim();
const codex = this.#dependencies.createCodex({
+ ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
env: definedEnvironment(
selectedScanEnvironment(environment, "chatgpt"),
@@ -1602,7 +1607,10 @@ export class CodexSecurity {
}
#codexCommand(): CodexCommand {
- return (this.#dependencies.resolveCodexCommand ?? resolveCodexCommand)();
+ return (
+ this.#dependencies.resolveCodexCommand?.() ??
+ resolveCodexCommand(this.#dependencies.environment)
+ );
}
async #refreshPersistentRuntime(
@@ -1625,6 +1633,7 @@ export class CodexSecurity {
runtime.codexHome,
runtime.plugin.pluginRoot,
{
+ codexCommand: this.#codexCommand(),
environment: withoutCodexHome(environment),
signal,
},
@@ -1730,6 +1739,7 @@ export class CodexSecurity {
const configPath = join(bootstrapWorkspace, "config-preflight.toml");
throwIfAborted(signal);
const plugin = await bootstrapPlugin(codexHome, pluginRoot, {
+ codexCommand: this.#codexCommand(),
environment: withoutCodexHome(processEnvironment),
signal,
});
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index aa3c3a6b6..e45a0ea71 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -1,7 +1,11 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { isIP } from "node:net";
import { PluginBootstrapError } from "./errors.js";
-import type { CodexCommand, ProcessEnvironment } from "./runtime.js";
+import {
+ runCodexCommand,
+ type CodexCommand,
+ type ProcessEnvironment,
+} from "./runtime.js";
const LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;
@@ -43,7 +47,7 @@ export class CodexLoginHandle {
) {
void this.#urlReady.promise.catch(() => undefined);
void this.#deviceReady.promise.catch(() => undefined);
- this.#child = spawn(command.command, [...command.prefixArgs, ...args], {
+ this.#child = spawn(command.command, [...args], {
env: environment,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
@@ -183,7 +187,7 @@ export async function loginApiKey(
if (apiKey.trim().length === 0) {
throw new PluginBootstrapError("The API key must be non-empty.");
}
- return await runCodex(
+ return await runCodexCommand(
command,
["login", "--with-api-key"],
environment,
@@ -197,7 +201,7 @@ export async function accountStatus(
environment: ProcessEnvironment,
signal?: AbortSignal,
): Promise<AccountStatus> {
- const result = await runCodex(
+ const result = await runCodexCommand(
command,
["login", "status"],
environment,
@@ -219,7 +223,7 @@ export async function logout(
environment: ProcessEnvironment,
signal?: AbortSignal,
): Promise<void> {
- const result = await runCodex(
+ const result = await runCodexCommand(
command,
["logout"],
environment,
@@ -233,81 +237,6 @@ export async function logout(
}
}
-export async function runCodex(
- command: CodexCommand,
- args: readonly string[],
- environment: ProcessEnvironment,
- input?: string,
- signal?: AbortSignal,
-): Promise<LoginResult> {
- const child = spawn(command.command, [...command.prefixArgs, ...args], {
- env: environment,
- stdio: ["pipe", "pipe", "pipe"],
- windowsHide: true,
- signal,
- });
- let stdout = "";
- let stderr = "";
- let processError: Error | null = null;
- let forcedTermination: ReturnType<typeof setTimeout> | undefined;
- const terminate = (): void => {
- if (child.exitCode !== null || child.signalCode !== null) {
- child.stdin.destroy();
- child.stdout.destroy();
- child.stderr.destroy();
- return;
- }
- child.kill("SIGTERM");
- if (forcedTermination !== undefined) return;
- forcedTermination = setTimeout(() => {
- forcedTermination = undefined;
- if (child.exitCode === null && child.signalCode === null) {
- child.kill("SIGKILL");
- }
- child.stdin.destroy();
- child.stdout.destroy();
- child.stderr.destroy();
- }, LOGIN_CHILD_TERMINATION_GRACE_MS);
- };
- child.stdout.setEncoding("utf8");
- child.stderr.setEncoding("utf8");
- child.stdout.on("data", (chunk: string) => {
- stdout += chunk;
- });
- child.stderr.on("data", (chunk: string) => {
- stderr += chunk;
- });
- const completion = new Promise<LoginResult>((resolve, reject) => {
- child.once("error", (error) => {
- processError ??= error;
- terminate();
- });
- child.stdin.on("error", (error: NodeJS.ErrnoException) => {
- // A short-lived command can close stdin before Node flushes the input.
- // Its exit status remains authoritative; the stream error must not escape
- // as an uncaught exception.
- if (
- error.code !== "EPIPE" &&
- error.code !== "ECONNRESET" &&
- error.code !== "EOF" &&
- error.code !== "ERR_STREAM_DESTROYED"
- ) {
- processError ??= error;
- }
- });
- child.once("close", (exitCode) => {
- if (forcedTermination !== undefined) clearTimeout(forcedTermination);
- if (processError !== null) {
- reject(processError);
- } else {
- resolve({ success: exitCode === 0, exitCode, stdout, stderr });
- }
- });
- });
- child.stdin.end(input);
- return await completion;
-}
-
function preferredAuthUrl(value: string): string | null {
for (const match of plainTerminalText(value).matchAll(
/https?:\/\/[^\s<>"']+/g,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index b626d942c..e8483157d 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -383,7 +383,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
name.toUpperCase() !== "CODEX_API_KEY",
),
);
- const command = resolveCodexCommand();
+ const command = resolveCodexCommand(environment);
if (existsSync(codexSecurityCredentialHome(process.env))) {
const dedicatedStatus = await accountStatus(command, {
...environment,
@@ -417,7 +417,12 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
},
forceExit: (signal) => process.kill(process.pid, signal),
runCodex: (args, output, environment) =>
- runCodexSkillCommand(args, output, resolveCodexCommand(), environment),
+ runCodexSkillCommand(
+ args,
+ output,
+ resolveCodexCommand(environment),
+ environment,
+ ),
exportFindings: async (arguments_, output) => {
const environment = exportEnvironment();
const python = await resolvePluginPython({
@@ -514,7 +519,7 @@ export async function runCodexSkillCommand(
if (configuredHome?.trim()) {
environment["CODEX_HOME"] = resolve(expandHome(configuredHome));
}
- const invocation = spawn(command.command, [...command.prefixArgs, ...args], {
+ const invocation = spawn(command.command, [...args], {
env: environment,
cwd: parse(process.execPath).root,
stdio: output === undefined ? "inherit" : ["ignore", "pipe", "pipe"],
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index b0b684b88..760e4e31a 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1,6 +1,6 @@
import { execFile as execFileCallback, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { constants, existsSync, type Stats } from "node:fs";
+import { constants, existsSync, readdirSync, type Stats } from "node:fs";
import {
chmod,
cp,
@@ -67,7 +67,13 @@ export interface PluginInstall {
export interface CodexCommand {
command: string;
- prefixArgs: readonly string[];
+}
+
+interface CodexCommandResult {
+ success: boolean;
+ exitCode: number | null;
+ stdout: string;
+ stderr: string;
}
export type ProcessEnvironment = Record<string, string | undefined>;
@@ -89,21 +95,26 @@ export interface WorkbenchCommandOptions {
failureMessage?: string;
}
+function environmentValue(
+ environment: ProcessEnvironment,
+ requested: string,
+): string | undefined {
+ const exact = environment[requested]?.trim();
+ if (exact) return exact;
+ return Object.entries(environment)
+ .find(
+ ([name, value]) => name.toUpperCase() === requested && value?.trim(),
+ )?.[1]
+ ?.trim();
+}
+
export function codexSecurityStateDirectory(
environment: ProcessEnvironment = process.env,
): string {
- const environmentValue = (requested: string): string | undefined => {
- const exact = environment[requested]?.trim();
- if (exact) return exact;
- return Object.entries(environment)
- .find(
- ([name, value]) => name.toUpperCase() === requested && value?.trim(),
- )?.[1]
- ?.trim();
- };
- const configured = environmentValue("CODEX_SECURITY_STATE_DIR");
+ const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR");
if (configured !== undefined) return resolve(expandHome(configured));
- const codexHome = environmentValue("CODEX_HOME") ?? join(homedir(), ".codex");
+ const codexHome =
+ environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex");
return resolve(expandHome(codexHome), "state", "plugins", "codex-security");
}
@@ -1967,8 +1978,14 @@ export async function createMarketplace(
return marketplace;
}
-export function resolveCodexCommand(): CodexCommand {
- const { packageName, targetTriple } = codexPlatformPackage();
+export function resolveCodexCommand(
+ environment: ProcessEnvironment = process.env,
+): CodexCommand {
+ const configured = environmentValue(environment, "CODEX_CLI_PATH");
+ if (configured) return { command: resolve(configured) };
+
+ const platform = process.platform === "android" ? "linux" : process.platform;
+ const packageName = `@openai/codex-${platform}-${process.arch}`;
let packageJson: string;
try {
const require = createRequire(import.meta.url);
@@ -1982,45 +1999,22 @@ export function resolveCodexCommand(): CodexCommand {
{ cause: error },
);
}
+ const vendor = join(dirname(packageJson), "vendor");
+ const target = readdirSync(vendor, { withFileTypes: true }).find((entry) =>
+ entry.isDirectory(),
+ );
const command = join(
- dirname(packageJson),
- "vendor",
- targetTriple,
+ vendor,
+ target?.name ?? "",
"bin",
process.platform === "win32" ? "codex.exe" : "codex",
);
- if (!existsSync(command)) {
+ if (target === undefined || !existsSync(command)) {
throw new PluginBootstrapError(
- `The ${packageName} package does not contain the Codex executable for ${targetTriple}. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,
+ `The ${packageName} package does not contain the Codex executable. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,
);
}
- return { command, prefixArgs: [] };
-}
-
-export function codexPlatformPackage(
- platform: NodeJS.Platform = process.platform,
- architecture: string = process.arch,
-): { packageName: string; targetTriple: string } {
- const key = `${platform}:${architecture}`;
- const target: readonly [string, string] | undefined = {
- "android:arm64": [
- "@openai/codex-linux-arm64",
- "aarch64-unknown-linux-musl",
- ],
- "android:x64": ["@openai/codex-linux-x64", "x86_64-unknown-linux-musl"],
- "darwin:arm64": ["@openai/codex-darwin-arm64", "aarch64-apple-darwin"],
- "darwin:x64": ["@openai/codex-darwin-x64", "x86_64-apple-darwin"],
- "linux:arm64": ["@openai/codex-linux-arm64", "aarch64-unknown-linux-musl"],
- "linux:x64": ["@openai/codex-linux-x64", "x86_64-unknown-linux-musl"],
- "win32:arm64": ["@openai/codex-win32-arm64", "aarch64-pc-windows-msvc"],
- "win32:x64": ["@openai/codex-win32-x64", "x86_64-pc-windows-msvc"],
- }[key] as readonly [string, string] | undefined;
- if (target === undefined) {
- throw new PluginBootstrapError(
- `Codex does not support this platform: ${platform} (${architecture}).`,
- );
- }
- return { packageName: target[0], targetTriple: target[1] };
+ return { command };
}
export async function bootstrapPlugin(
@@ -2042,12 +2036,13 @@ export async function bootstrapPlugin(
const { name, version } = await pluginMetadata(root);
const marketplace = join(codexHome, "sdk-marketplace");
throwIfSignalAborted(options.signal);
- const command = options.codexCommand ?? resolveCodexCommand();
+ const command =
+ options.codexCommand ?? resolveCodexCommand(options.environment);
const environment = {
...(options.environment ?? process.env),
CODEX_HOME: codexHome,
};
- const run = options.runCodex ?? runCodex;
+ const run = options.runCodex ?? runPluginCommand;
const existing = await lstat(marketplace).catch((error: unknown) => {
if (nodeErrorCode(error) === "ENOENT") return null;
throw error;
@@ -2234,8 +2229,7 @@ export function pluginExecutionEnvironment(
return {
...environment,
PYTHON: python,
- CODEX_CLI_PATH:
- environment["CODEX_CLI_PATH"]?.trim() || resolveCodexCommand().command,
+ CODEX_CLI_PATH: resolveCodexCommand(environment).command,
};
}
@@ -2243,22 +2237,73 @@ export async function cleanupSdkDirectory(path: string): Promise<void> {
await rm(path, { recursive: true, force: true });
}
-async function runCodex(
+export async function runCodexCommand(
+ command: CodexCommand,
+ args: readonly string[],
+ environment: ProcessEnvironment,
+ input?: string,
+ signal?: AbortSignal,
+): Promise<CodexCommandResult> {
+ const child = spawn(command.command, [...args], {
+ env: environment,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ signal,
+ });
+ let stdout = "";
+ let stderr = "";
+ let processError: Error | undefined;
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ const completion = new Promise<CodexCommandResult>((resolve, reject) => {
+ child.once("error", (error) => {
+ processError = error;
+ });
+ child.stdin.on("error", (error: NodeJS.ErrnoException) => {
+ if (
+ !["EPIPE", "ECONNRESET", "EOF", "ERR_STREAM_DESTROYED"].includes(
+ error.code ?? "",
+ )
+ )
+ processError = error;
+ });
+ child.once("close", (exitCode) =>
+ processError === undefined
+ ? resolve({ success: exitCode === 0, exitCode, stdout, stderr })
+ : reject(processError),
+ );
+ });
+ child.stdin.end(input);
+ return await completion;
+}
+
+async function runPluginCommand(
command: CodexCommand,
args: readonly string[],
environment: ProcessEnvironment,
signal?: AbortSignal,
): Promise<string> {
try {
- const { stdout } = await execFile(
- command.command,
- [...command.prefixArgs, ...args],
- {
- env: environment,
- encoding: "utf8",
- signal,
- },
+ const { success, exitCode, stdout, stderr } = await runCodexCommand(
+ command,
+ args,
+ environment,
+ undefined,
+ signal,
);
+ if (!success) {
+ throw new Error(
+ stderr.trim() ||
+ stdout.trim() ||
+ `Codex exited with status ${exitCode}.`,
+ );
+ }
return stdout;
} catch (error) {
const detail = processErrorDetail(error);
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 3d2cd09b0..520f38e27 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -319,7 +319,7 @@ export async function comparisonEnvironment(
}
}
const status = await nativeAccountStatus(
- resolveCodexCommand(),
+ resolveCodexCommand(source),
storedEnvironment,
signal,
);
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 517220710..824ef785b 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -195,6 +195,20 @@ async function temporaryDirectory(): Promise<string> {
return path;
}
+function nodeCodex(script: string): {
+ command: { command: string };
+ environment: Record<string, string>;
+} {
+ return {
+ command: {
+ command: execFileSync("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ }).trim(),
+ },
+ environment: { NODE_OPTIONS: `--import=${pathToFileURL(script).href}` },
+ };
+}
+
async function copyCompletedScan(root: string): Promise<string> {
const scanDir = join(root, "scan");
await cp(EXAMPLE, scanDir, { recursive: true });
@@ -5077,23 +5091,76 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
+ test("uses one configured Codex executable for scans and nested workers", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ const executable = join(root, "custom codex");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ let codexOptions: CodexOptions | null = null;
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ OPENAI_API_KEY: "ambient-key",
+ CODEX_CLI_PATH: ` ${executable} `,
+ },
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment: {
+ CODEX_HOME: codexHome,
+ CODEX_CLI_PATH: ` ${executable} `,
+ },
+ }),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options: CodexOptions) => {
+ codexOptions = options;
+ return {
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ await copyCompletedScan(root);
+ return { events: completedEvents() };
+ },
+ }),
+ };
+ },
+ },
+ );
+
+ await client.run(repository);
+ expect((codexOptions as CodexOptions | null)?.codexPathOverride).toBe(
+ executable,
+ );
+ expect((codexOptions as CodexOptions | null)?.env?.["CODEX_CLI_PATH"]).toBe(
+ executable,
+ );
+ await client.close();
+ });
+
test("authenticates without initializing the plugin runtime", async () => {
const root = await temporaryDirectory();
const stateDirectory = join(root, "state");
const codexHome = join(stateDirectory, "codex-home");
const fakeCodex = join(root, "codex.mjs");
await writeFile(fakeCodex, "process.exitCode = 1;\n");
+ const fakeCommand = nodeCodex(fakeCodex);
const client = new TestClient(
{ pluginPath: join(root, "missing-plugin") },
{
- environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },
+ environment: {
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ ...fakeCommand.environment,
+ },
prepareRuntime: async () => {
throw new Error("authentication must not initialize the plugin");
},
- resolveCodexCommand: () => ({
- command: process.execPath,
- prefixArgs: [fakeCodex],
- }),
+ resolveCodexCommand: () => fakeCommand.command,
},
);
@@ -5125,9 +5192,10 @@ describe("CodexSecurity orchestration", () => {
`
import { writeFileSync } from "node:fs";
writeFileSync(${JSON.stringify(nativeLoginMarker)}, "native login was invoked");
-process.exitCode = 2;
+process.exit(2);
`,
);
+ const fakeCommand = nodeCodex(fakeCodex);
let codexOptions: CodexOptions | null = null;
let selectedAuthentication: unknown;
let pythonEnvironment: Record<string, string | undefined> | undefined;
@@ -5154,13 +5222,11 @@ process.exitCode = 2;
CODEX_HOME: codexHome,
OpenAi_Api_Key: "forwarded-openai-key",
codex_api_key: "forwarded-codex-key",
+ ...fakeCommand.environment,
},
credentialsAvailable: false,
}),
- resolveCodexCommand: () => ({
- command: process.execPath,
- prefixArgs: [fakeCodex],
- }),
+ resolveCodexCommand: () => fakeCommand.command,
resolvePluginPython: async (options: {
environment?: Record<string, string | undefined>;
protectedRoot?: string;
@@ -5228,15 +5294,19 @@ process.exitCode = 2;
await writeFile(
fakeCodex,
`
-if (process.argv.slice(2).join(" ") !== "login status") {
- process.exitCode = 2;
+import { basename } from "node:path";
+
+if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login status") {
+ process.exit(2);
} else if (process.env.CODEX_HOME !== ${JSON.stringify(codexHome)}) {
- process.exitCode = 3;
+ process.exit(3);
} else {
console.log("Logged in using ChatGPT");
+ process.exit(0);
}
`,
);
+ const fakeCommand = nodeCodex(fakeCodex);
const client = new TestClient(
{},
@@ -5244,13 +5314,10 @@ if (process.argv.slice(2).join(" ") !== "login status") {
environment: { CODEX_SECURITY_STATE_DIR: join(root, "state") },
prepareRuntime: async () => ({
...preparedRuntime(codexHome),
- environment: { CODEX_HOME: codexHome },
+ environment: { CODEX_HOME: codexHome, ...fakeCommand.environment },
credentialsAvailable: false,
}),
- resolveCodexCommand: () => ({
- command: process.execPath,
- prefixArgs: [fakeCodex],
- }),
+ resolveCodexCommand: () => fakeCommand.command,
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
@@ -5961,10 +6028,14 @@ if (process.argv.slice(2).join(" ") !== "login status") {
fakeCodex,
'console.error("Open https://auth.example.test/device");\nconsole.error("User code: ABCD-EFGH");\nprocess.on("SIGTERM", () => {});\nsetInterval(() => {}, 1000);\n',
);
+ const fakeCommand = nodeCodex(fakeCodex);
const client = new TestClient(
{},
{
- environment: { CODEX_SECURITY_STATE_DIR: root },
+ environment: {
+ CODEX_SECURITY_STATE_DIR: root,
+ ...fakeCommand.environment,
+ },
prepareRuntime: async () => ({
codexHome,
plugin: {
@@ -5975,13 +6046,10 @@ if (process.argv.slice(2).join(" ") !== "login status") {
name: "codex-security",
version: "0.1.0",
},
- environment: {},
+ environment: fakeCommand.environment,
credentialsAvailable: false,
}),
- resolveCodexCommand: () => ({
- command: process.execPath,
- prefixArgs: [fakeCodex],
- }),
+ resolveCodexCommand: () => fakeCommand.command,
createCodex: () => {
throw new Error("not used");
},
@@ -6090,10 +6158,14 @@ for await (const _chunk of process.stdin) {}
setInterval(() => {}, 1000);
`,
);
+ const fakeCommand = nodeCodex(fakeCodex);
const client = new TestClient(
{},
{
- environment: { CODEX_SECURITY_STATE_DIR: root },
+ environment: {
+ CODEX_SECURITY_STATE_DIR: root,
+ ...fakeCommand.environment,
+ },
prepareRuntime: async () => ({
codexHome,
plugin: {
@@ -6104,13 +6176,10 @@ setInterval(() => {}, 1000);
name: "codex-security",
version: "0.1.0",
},
- environment: {},
+ environment: fakeCommand.environment,
credentialsAvailable: false,
}),
- resolveCodexCommand: () => ({
- command: process.execPath,
- prefixArgs: [fakeCodex],
- }),
+ resolveCodexCommand: () => fakeCommand.command,
createCodex: () => {
throw new Error("not used");
},
diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.ts
index dc622e5e5..1aca9a3fb 100644
--- a/sdk/typescript/tests-ts/auth.test.ts
+++ b/sdk/typescript/tests-ts/auth.test.ts
@@ -1,16 +1,18 @@
+import { execFileSync } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
+import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, test } from "bun:test";
import {
accountStatus,
CodexLoginHandle,
loginApiKey,
logout,
- runCodex,
} from "../src/auth.js";
import { PluginBootstrapError } from "../src/index.js";
+import { runCodexCommand } from "../src/runtime.js";
import type { CodexCommand } from "../src/index.js";
const temporaryDirectories: string[] = [];
@@ -23,14 +25,19 @@ afterEach(async () => {
);
});
-async function fakeCodex(): Promise<CodexCommand> {
+async function fakeCodex(): Promise<{
+ command: CodexCommand;
+ environment: NodeJS.ProcessEnv;
+}> {
const root = await mkdtemp(join(tmpdir(), "codex-security-auth-"));
temporaryDirectories.push(root);
const script = join(root, "codex.mjs");
await writeFile(
script,
`
-const args = process.argv.slice(2);
+import { basename } from "node:path";
+
+const args = [basename(process.argv[1]), ...process.argv.slice(2)];
if (args.join(" ") === "login --with-api-key") {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -65,19 +72,30 @@ if (args.join(" ") === "login --with-api-key") {
console.error("unexpected args: " + args.join(" "));
process.exitCode = 3;
}
+process.exit(process.exitCode ?? 0);
`,
);
- return { command: process.execPath, prefixArgs: [script] };
+ return {
+ command: {
+ command: execFileSync("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ }).trim(),
+ },
+ environment: {
+ ...process.env,
+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
+ },
+ };
}
describe("Codex authentication process boundary", () => {
test("persists API keys through the exact public Codex executable", async () => {
- const command = await fakeCodex();
- await expect(loginApiKey(command, process.env, "")).rejects.toBeInstanceOf(
+ const { command, environment } = await fakeCodex();
+ await expect(loginApiKey(command, environment, "")).rejects.toBeInstanceOf(
PluginBootstrapError,
);
await expect(
- loginApiKey(command, process.env, "secret-key"),
+ loginApiKey(command, environment, "secret-key"),
).resolves.toMatchObject({
success: true,
exitCode: 0,
@@ -90,9 +108,9 @@ describe("Codex authentication process boundary", () => {
const script = join(root, "exit.mjs");
await writeFile(script, "process.exit(1);\n");
await expect(
- runCodex(
- { command: process.execPath, prefixArgs: [script] },
- [],
+ runCodexCommand(
+ { command: process.execPath },
+ [script],
process.env,
"x".repeat(16 * 1024 * 1024),
),
@@ -109,9 +127,9 @@ describe("Codex authentication process boundary", () => {
script,
`process.${stream}.write(${JSON.stringify(output)}, () => process.exit(0));\n`,
);
- const result = await runCodex(
- { command: process.execPath, prefixArgs: [script] },
- [],
+ const result = await runCodexCommand(
+ { command: process.execPath },
+ [script],
process.env,
);
expect(result.success).toBe(true);
@@ -120,21 +138,21 @@ describe("Codex authentication process boundary", () => {
});
test("reports account state and performs logout", async () => {
- const command = await fakeCodex();
- await expect(accountStatus(command, process.env)).resolves.toMatchObject({
+ const { command, environment } = await fakeCodex();
+ await expect(accountStatus(command, environment)).resolves.toMatchObject({
authenticated: true,
details: "Logged in using ChatGPT",
});
- await expect(logout(command, process.env)).resolves.toBeUndefined();
+ await expect(logout(command, environment)).resolves.toBeUndefined();
});
test("captures quoted interactive login metadata and completion", async () => {
- const command = await fakeCodex();
+ const { command, environment } = await fakeCodex();
let succeeded = false;
const handle = new CodexLoginHandle(
command,
["login", "--device-auth"],
- process.env,
+ environment,
() => {
succeeded = true;
},
@@ -163,8 +181,8 @@ setTimeout(() => {
);
let succeeded = false;
const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
+ { command: process.execPath },
+ [script, "login", "--device-auth"],
process.env,
() => {
succeeded = true;
@@ -191,8 +209,8 @@ setTimeout(() => {
);
const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login"],
+ { command: process.execPath },
+ [script, "login"],
process.env,
() => {},
);
@@ -275,8 +293,8 @@ grandchild.once("error", (error) => {
);
const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login"],
+ { command: process.execPath },
+ [script, "login"],
process.env,
() => {},
);
@@ -304,8 +322,8 @@ setInterval(() => {}, 1000);
);
let succeeded = false;
const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
+ { command: process.execPath },
+ [script, "login", "--device-auth"],
process.env,
() => {
succeeded = true;
@@ -339,8 +357,8 @@ setInterval(() => {}, 1000);
);
let succeeded = false;
const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
+ { command: process.execPath },
+ [script, "login", "--device-auth"],
process.env,
() => {
succeeded = true;
diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.ts
index f705898a8..822750c80 100644
--- a/sdk/typescript/tests-ts/cli-skills.test.ts
+++ b/sdk/typescript/tests-ts/cli-skills.test.ts
@@ -511,15 +511,12 @@ describe("CLI skill commands", () => {
const stderr = capture();
await expect(
runCodexSkillCommand(
- [],
+ [
+ "-e",
+ 'process.stdout.write(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:"x".repeat(1024*1024+1)}})+"\\n")',
+ ],
{ command: "validate", stdout: stdout.stream, stderr: stderr.stream },
- {
- command: process.execPath,
- prefixArgs: [
- "-e",
- 'process.stdout.write(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:"x".repeat(1024*1024+1)}})+"\\n")',
- ],
- },
+ { command: process.execPath },
),
).resolves.toBe(0);
expect(stdout.text()).toBe(`${"x".repeat(1024 * 1024 + 1)}\n`);
@@ -583,9 +580,9 @@ describe("CLI skill commands", () => {
const stderr = capture();
expect(
await runCodexSkillCommand(
- [],
+ ["-e", scenario.source],
{ command: "validate", stdout: stdout.stream, stderr: stderr.stream },
- { command: process.execPath, prefixArgs: ["-e", scenario.source] },
+ { command: process.execPath },
),
).toBe(scenario.status);
expect(stdout.text()).toBe(scenario.stdout);
@@ -631,9 +628,9 @@ setInterval(() => {}, 1000);
`
import { runCodexSkillCommand } from ${JSON.stringify(new URL("../src/cli.ts", import.meta.url).href)};
const status = await runCodexSkillCommand(
- [],
+ [${JSON.stringify(child)}],
{ command: "validate", stdout: process.stdout, stderr: process.stderr },
- { command: process.execPath, prefixArgs: [${JSON.stringify(child)}] },
+ { command: process.execPath },
);
process.exit(status);
`,
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 95a540fb9..9d9c149be 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -55,7 +55,6 @@ import {
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
- codexPlatformPackage,
inspectWindowsCredentialAcl,
inspectWindowsCredentialAclSnapshot,
isPythonPathCandidate,
@@ -1054,7 +1053,7 @@ describe("plugin runtime preparation", () => {
await expect(
bootstrapPlugin(home, selected, {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
signal: controller.signal,
runCodex: async () => {
registrationCalls += 1;
@@ -1363,7 +1362,7 @@ describe("plugin runtime preparation", () => {
"1.2.3",
);
const install = await bootstrapPlugin(home, selected, {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
environment: {
SAFE_VALUE: "kept",
},
@@ -1407,7 +1406,7 @@ describe("plugin runtime preparation", () => {
"print('updated')\n",
);
const reused = await bootstrapPlugin(home, selected, {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
runCodex: async (_command, args) => {
calls.push([...args]);
return JSON.stringify({ installedPath: installed, version: "1.2.3" });
@@ -1440,7 +1439,7 @@ describe("plugin runtime preparation", () => {
await expect(
bootstrapPlugin(home, selected, {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
runCodex: async () => output,
}),
).rejects.toThrow(PluginBootstrapError);
@@ -1472,7 +1471,7 @@ describe("plugin runtime preparation", () => {
const calls: string[][] = [];
const result = await bootstrapPlugin(home, selected, {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
runCodex: async (_command, args) => {
calls.push([...args]);
if (args[1] === "marketplace") {
@@ -1574,7 +1573,7 @@ describe("plugin runtime preparation", () => {
}
};
const options = {
- codexCommand: { command: "/codex", prefixArgs: [] },
+ codexCommand: { command: "/codex" },
runCodex,
};
@@ -1620,16 +1619,12 @@ describe("plugin runtime preparation", () => {
OPENAI_API_KEY: undefined,
CODEX_API_KEY: undefined,
};
- const login = spawnSync(
- command.command,
- [...command.prefixArgs, "login", "--with-api-key"],
- {
- env: environment,
- input: "synthetic-key\n",
- encoding: "utf8",
- windowsHide: true,
- },
- );
+ const login = spawnSync(command.command, ["login", "--with-api-key"], {
+ env: environment,
+ input: "synthetic-key\n",
+ encoding: "utf8",
+ windowsHide: true,
+ });
expect(login.status).toBe(0);
const credentials = await readFile(join(home, "auth.json"), "utf8");
@@ -1642,7 +1637,7 @@ describe("plugin runtime preparation", () => {
expect(upgraded.version).toBe("1.2.4");
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(credentials);
expect(
- spawnSync(command.command, [...command.prefixArgs, "login", "status"], {
+ spawnSync(command.command, ["login", "status"], {
env: environment,
encoding: "utf8",
windowsHide: true,
@@ -1652,18 +1647,30 @@ describe("plugin runtime preparation", () => {
test("resolves the exact npm Codex executable", () => {
const command = resolveCodexCommand();
- const target = codexPlatformPackage();
- expect(command.prefixArgs).toEqual([]);
- expect(command.command).toContain(
- join(
- "vendor",
- target.targetTriple,
- "bin",
- process.platform === "win32" ? "codex.exe" : "codex",
- ),
+ expect(isAbsolute(command.command)).toBe(true);
+ expect(command.command).toContain(`${sep}vendor${sep}`);
+ expect(command.command).toEndWith(
+ join("bin", process.platform === "win32" ? "codex.exe" : "codex"),
);
});
+ test("uses an explicit Codex executable override", () => {
+ const configured = join(tmpdir(), "custom codex", "codex");
+
+ expect(resolveCodexCommand({ CODEX_CLI_PATH: ` ${configured} ` })).toEqual({
+ command: configured,
+ });
+ expect(resolveCodexCommand({ CODEX_CLI_PATH: " " })).toEqual(
+ resolveCodexCommand({}),
+ );
+ expect(resolveCodexCommand({ CODEX_CLI_PATH: "./bin/codex" })).toEqual({
+ command: join(process.cwd(), "bin", "codex"),
+ });
+ expect(resolveCodexCommand({ Codex_Cli_Path: configured })).toEqual({
+ command: configured,
+ });
+ });
+
test("launches the bundled Codex through the Deep Scan MCP environment without a global executable", async () => {
const configuration = JSON.parse(
await readFile(join(PLUGIN_ROOT, ".mcp.json"), "utf8"),
@@ -1724,13 +1731,6 @@ describe("plugin runtime preparation", () => {
})["CODEX_CLI_PATH"],
).toBe(resolveCodexCommand().command);
});
-
- test("selects the native Windows Codex executable package", () => {
- expect(codexPlatformPackage("win32", "x64")).toEqual({
- packageName: "@openai/codex-win32-x64",
- targetTriple: "x86_64-pc-windows-msvc",
- });
- });
});
describe("runtime directories and plugin Python boundary", () => {