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

chore(codex-security): sync public projection

mldangelo-oai3e9875d123ea
diff --git a/README.md b/README.md
index 929bd96df..552cc4264 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,10 @@ incomplete coverage and runtime errors still exit nonzero:
npx codex-security scan . --diff origin/main --json --fail-on-severity high > codex-security.json
```
+JSON scans remain noninteractive, including when stderr is a terminal. Commands
+that run Codex interactively (`validate`, `patch`, `login`, and `logout`) reject
+`--json`. Write CSV exports to a file when JSON output is selected.
+
Scans use `gpt-5.6-sol` with extra-high reasoning effort by default. To override
either setting, pass valid TOML values (including quotes for strings):
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index d03777512..b7d8a44de 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -161,6 +161,11 @@ incomplete coverage and runtime errors still exit nonzero:
npx codex-security scan . --diff origin/main --json --fail-on-severity high > codex-security.json
```
+JSON scans never use interactive terminal controls, even when stderr is a TTY.
+The `validate`, `patch`, `login`, and `logout` commands run Codex interactively
+and reject `--json` rather than mixing its terminal output with machine data.
+CSV exports cannot be written to stdout while JSON output is requested.
+
Use `export` to create CSV, JSON, or SARIF from a completed, sealed scan without
starting Codex or loading credentials. JSON preserves the sealed findings
document. CSV uses the portable findings columns, marks findings as open, and
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index d084f0568..8ac1b760c 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -662,14 +662,18 @@ export class CodexSecurity {
}
async #finishClose(): Promise<void> {
- this.#abortController.abort();
+ const activeOperation = this.#activeOperation;
const loginHandles = [...this.#loginHandles];
+ if (
+ activeOperation !== null ||
+ loginHandles.length > 0 ||
+ (this.#runtime === null && this.#runtimePromise !== null)
+ ) {
+ this.#abortController.abort();
+ }
for (const handle of loginHandles) handle.cancel();
await Promise.allSettled(
- [
- this.#activeOperation,
- ...loginHandles.map((handle) => handle.wait()),
- ].filter(
+ [activeOperation, ...loginHandles.map((handle) => handle.wait())].filter(
(operation): operation is Promise<unknown> => operation !== null,
),
);
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index a2ff09b7b..8740862ba 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -642,6 +642,7 @@ export async function main(
},
errorOutput,
dependencies,
+ format !== "json" && format !== "jsonl",
);
exitCode = outcome.exitCode;
if (outcome.error !== undefined) {
@@ -1094,7 +1095,40 @@ function validateCliArguments(
].includes(value),
);
if (commandIndex < 0) return undefined;
- const command = argv[commandIndex];
+ const command = argv[commandIndex]!;
+ const structuredOutput = argv.some(
+ (value, index) =>
+ value === "--json" ||
+ ((value === "--format" ||
+ value === "--format=json" ||
+ value === "--format=jsonl") &&
+ (value.endsWith("=json") ||
+ value.endsWith("=jsonl") ||
+ argv[index + 1] === "json" ||
+ argv[index + 1] === "jsonl")),
+ );
+ if (
+ structuredOutput &&
+ ["validate", "patch", "login", "logout"].includes(command)
+ ) {
+ return `${command} does not support noninteractive JSON output; run it without --json or --format json.`;
+ }
+ if (
+ command === "export" &&
+ structuredOutput &&
+ argv.some(
+ (value, index) =>
+ value === "--output=-" ||
+ (value === "--output" && argv[index + 1] === "-"),
+ ) &&
+ argv.some(
+ (value, index) =>
+ value === "--export-format=csv" ||
+ (value === "--export-format" && argv[index + 1] === "csv"),
+ )
+ ) {
+ return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
+ }
if (command === "scan" && !argv.includes("--schema")) {
if (
argv.some(
@@ -1304,6 +1338,7 @@ async function runScan(
arguments_: ScanArguments,
errorOutput: Writable,
dependencies: CliDependencies,
+ interactive = true,
): Promise<ScanOutcome> {
let scanDir: string | null = null;
let requestedSignal: SignalName | null = null;
@@ -1322,7 +1357,7 @@ async function runScan(
}
requestedSignal = signal;
progress?.stopTimer();
- if (errorOutput.isTTY === true) {
+ if (progress?.interactive === true) {
try {
dependencies.writeSynchronously(errorOutput, SHOW_CURSOR);
} catch {
@@ -1361,7 +1396,7 @@ async function runScan(
codexOverrides:
arguments_.codexOverrides ?? parseCodexOverrides(arguments_.codex),
};
- progress = new Progress(errorOutput, dependencies);
+ progress = new Progress(errorOutput, dependencies, interactive);
progress.startTimer(
arguments_.dryRun ? "Validating scan inputs" : "Preparing scan",
);
@@ -1657,6 +1692,7 @@ export class Progress {
"now" | "setInterval" | "clearInterval"
>;
readonly #startedAt: number;
+ readonly #interactive: boolean;
#timer: NodeJS.Timeout | null = null;
#timerLineActive = false;
#cursorHidden = false;
@@ -1667,10 +1703,16 @@ export class Progress {
CliDependencies,
"now" | "setInterval" | "clearInterval"
> = DEFAULT_DEPENDENCIES,
+ interactive = true,
) {
this.#stream = stream;
this.#dependencies = dependencies;
this.#startedAt = dependencies.now();
+ this.#interactive = interactive;
+ }
+
+ public get interactive(): boolean {
+ return this.#interactive && this.#stream.isTTY === true;
}
public stage(message: string): void {
@@ -1678,7 +1720,7 @@ export class Progress {
}
public startTimer(message: string): void {
- if (this.#stream.isTTY !== true) {
+ if (!this.interactive) {
this.stage(message);
return;
}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 5b1156c39..0c852b4c3 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -15,8 +15,8 @@ import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import type { CodexOptions, ThreadEvent } from "@openai/codex-sdk";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { Codex, type CodexOptions, type ThreadEvent } from "@openai/codex-sdk";
import { afterEach, describe, expect, mock, test } from "bun:test";
import {
AuthenticationRequiredError,
@@ -2675,6 +2675,103 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");
expect(createCodexCalled).toBe(false);
});
+ test("does not abort a settled scan signal during idle client cleanup", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ let scanSignal: AbortSignal | undefined;
+
+ const client = new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => preparedRuntime(codexHome),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: () => ({
+ startThread: () => ({
+ id: null,
+ async runStreamed(
+ _input: string,
+ options: { signal: AbortSignal },
+ ) {
+ scanSignal = options.signal;
+ async function* failedEvents(): AsyncGenerator<ThreadEvent> {
+ yield { type: "thread.started", thread_id: "thread-1" };
+ yield {
+ type: "turn.failed",
+ error: { message: "upstream authentication failed" },
+ };
+ }
+ return { events: failedEvents() };
+ },
+ }),
+ }),
+ },
+ );
+
+ await expect(client.run(repository)).rejects.toThrow(
+ "upstream authentication failed",
+ );
+ expect(scanSignal?.aborted).toBe(false);
+ await client.close();
+ expect(scanSignal?.aborted).toBe(false);
+ });
+
+ test("closes a real Codex subprocess cleanly after a streamed terminal failure", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ const preload = join(root, "fake-codex.mjs");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ await writeFile(
+ preload,
+ [
+ 'process.stdout.write(`${JSON.stringify({type:"thread.started",thread_id:"thread-1"})}\\n`);',
+ 'process.stdout.write(`${JSON.stringify({type:"turn.failed",error:{message:"401 invalid API key"}})}\\n`);',
+ "setInterval(() => {}, 1_000);",
+ "await new Promise(() => {});",
+ ].join("\n"),
+ );
+ const nodeExecutable = execFileSync("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ }).trim();
+ const client = new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment: { CODEX_HOME: codexHome },
+ }),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options: CodexOptions) =>
+ new Codex({
+ ...options,
+ codexPathOverride: nodeExecutable,
+ env: {
+ ...options.env,
+ NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`,
+ },
+ }),
+ },
+ );
+
+ await expect(client.run(repository)).rejects.toThrow("401 invalid API key");
+ await expect(client.close()).resolves.toBeUndefined();
+ await expect(client.close()).resolves.toBeUndefined();
+ });
+
test("cleans the bootstrap workspace when credential-home cleanup fails", async () => {
const root = await temporaryDirectory();
const codexHome = join(root, "codex-home");
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index d0e58663a..b1f762eb6 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -907,6 +907,96 @@ describe("CLI", () => {
expect(timers).toBe(0);
});
+ test("keeps structured scans noninteractive even when stderr is a terminal", async () => {
+ for (const options of [
+ ["--json"],
+ ["--format", "json"],
+ ["--format", "jsonl"],
+ ]) {
+ const stdout = capture();
+ const stderr = capture(true);
+ let timers = 0;
+ const deps = dependencies();
+ deps.setInterval = () => {
+ timers += 1;
+ return {} as NodeJS.Timeout;
+ };
+
+ expect(
+ await main(
+ ["scan", ".", ...options],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual(fakeResult().toJSON());
+ expect(stderr.text()).toContain("Preparing scan");
+ expect(stderr.text()).toContain("Running scan");
+ expect(stderr.text()).not.toContain("\u001B");
+ expect(stderr.text()).not.toContain("\r");
+ expect(timers).toBe(0);
+ }
+ });
+
+ test("rejects structured modes before starting interactive Codex commands", async () => {
+ for (const [command, arguments_] of [
+ ["validate", ["finding", "--json"]],
+ ["patch", ["issue", "--format", "json"]],
+ ["login", ["--json"]],
+ ["login", ["status", "--format", "jsonl"]],
+ ["logout", ["--json"]],
+ ] as const) {
+ let invoked = false;
+ const stdout = capture();
+ const stderr = capture(true);
+
+ expect(
+ await main(
+ [command, ...arguments_],
+ stdout.stream,
+ stderr.stream,
+ dependencies({
+ onCodex: () => {
+ invoked = true;
+ return 0;
+ },
+ }),
+ ),
+ ).toBe(2);
+ expect(invoked).toBe(false);
+ expect(stdout.text()).toBe("");
+ expect(stderr.text()).toContain(
+ `${command} does not support noninteractive JSON output`,
+ );
+ }
+ });
+
+ test("rejects CSV stdout when JSON output is requested", async () => {
+ let exported = false;
+ const stdout = capture();
+ const stderr = capture();
+ const deps = dependencies();
+ deps.exportFindings = async () => {
+ exported = true;
+ return new Uint8Array();
+ };
+
+ expect(
+ await main(
+ ["export", "scan", "--export-format", "csv", "--output", "-", "--json"],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(2);
+ expect(exported).toBe(false);
+ expect(stdout.text()).toBe("");
+ expect(stderr.text()).toContain(
+ "CSV stdout cannot be combined with JSON output",
+ );
+ });
+
test("prints export help without initializing Codex", async () => {
const stdout = capture();
const stderr = capture();