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
chore(codex-security): sync public projection
mldangelo-oaied53f94c4f94
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 9d2ae101d..7f0bc6831 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1295,18 +1295,24 @@ describe("CodexSecurity orchestration", () => {},);- await expect(- client.run(repository, {+ // The fake Codex stream has no process handle to keep its unref'ed poll alive.+ const keepEventLoopAlive = setTimeout(() => {}, 10_000);+ try {+ await expect(+ client.run(repository, {+ maxCostUsd: 0.005,+ onCost: (cost) => costs.push(cost.estimatedUsd),+ signal: AbortSignal.timeout(5_000),+ }),+ ).rejects.toMatchObject({+ name: ScanCostLimitExceededError.name,maxCostUsd: 0.005,- onCost: (cost) => costs.push(cost.estimatedUsd),- signal: AbortSignal.timeout(5_000),- }),- ).rejects.toMatchObject({- name: ScanCostLimitExceededError.name,- maxCostUsd: 0.005,- scanDir,- cost,- });+ scanDir,+ cost,+ });+ } finally {+ clearTimeout(keepEventLoopAlive);+ }expect(costs.at(-1)).toBe(0.00625);expect(commands[1]).toEqual(["fail-scan",diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.tsindex 39281ec2f..214c50bcf 100644--- a/sdk/typescript/tests-ts/auth.test.ts+++ b/sdk/typescript/tests-ts/auth.test.ts@@ -1,7 +1,8 @@-import { mkdtemp, readFile, rm, watch, writeFile } from "node:fs/promises";+import { ChildProcess } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, describe, expect, test } from "bun:test";+import { afterEach, describe, expect, spyOn, test } from "bun:test";import {accountStatus,CodexLoginHandle,@@ -125,47 +126,18 @@ describe("Codex authentication process boundary", () => {expect(succeeded).toBe(true);});- test("drains inherited stderr before resolving interactive login", async () => {- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-drain-"));+ test("drains native login stderr before resolving authentication", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-auth-stderr-"));temporaryDirectories.push(root);- const script = join(root, "inherited-stderr.mjs");+ const script = join(root, "login-stderr.mjs");const message = "network timeout while authenticating";- const grandchildScript = `-process.once("disconnect", () => {- process.stderr.write(${JSON.stringify(`${message}\n`)});-});-process.send("ready");-`;await writeFile(script,- `-import { spawn } from "node:child_process";--const grandchild = spawn(process.execPath, ["-e", ${JSON.stringify(grandchildScript)}], {- stdio: ["ignore", "ignore", "inherit", "ipc"],- windowsHide: true,-});-const readyTimeout = setTimeout(() => {- grandchild.kill();- console.error("Timed out waiting for the login grandchild.");- process.exit(1);-}, 10_000);-grandchild.once("message", (message) => {- if (message === "ready") {- clearTimeout(readyTimeout);- process.exit(1);- }-});-grandchild.once("error", (error) => {- clearTimeout(readyTimeout);- console.error(error.message);- process.exit(1);-});-`,+ `process.stderr.write(${JSON.stringify(`${message}\n`)}, (error) => process.exit(error ? 2 : 1));\n`,);const handle = new CodexLoginHandle(- { command: process.execPath, prefixArgs: [script] },+ { command: "node", prefixArgs: [script] },["login"],process.env,() => {},@@ -178,105 +150,162 @@ grandchild.once("error", (error) => {});});- test- .skipIf(process.platform !== "win32")- .each([- "releases inherited login pipes when the Windows fallback fires",- "releases inherited login pipes after a native Windows process exits",- ])("%s", async () => {- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-pipes-"));- temporaryDirectories.push(root);- const ready = join(root, "grandchild-ready");- const release = join(root, "release-grandchild");- const done = join(root, "grandchild-done");- const script = join(root, "inherited-pipes.mjs");- const grandchildScript = `-import { existsSync, watch, writeFileSync } from "node:fs";-import { join } from "node:path";+ test.skipIf(process.platform === "win32")(+ "drains inherited stderr before resolving interactive login",+ async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-auth-drain-"));+ temporaryDirectories.push(root);+ const script = join(root, "inherited-stderr.mjs");+ const ready = join(root, "grandchild-ready");+ const release = join(root, "release-grandchild");+ const message = "network timeout while authenticating";+ const grandchildScript = `+import { existsSync, writeFileSync, writeSync } from "node:fs";-const root = process.argv[1];-const release = join(root, "release-grandchild");-const watcher = watch(root, () => {- if (existsSync(release)) {- watcher.close();- writeFileSync(join(root, "grandchild-done"), "done");- process.exit(0);+const ready = process.argv[1];+const release = process.argv[2];+const parentPid = Number(process.argv[3]);+const timeout = setTimeout(() => process.exit(1), 10_000);+const watcher = setInterval(() => {+ if (!existsSync(release)) return;+ try {+ process.kill(parentPid, 0);+ return;+ } catch (error) {+ if (error?.code !== "ESRCH") {+ clearInterval(watcher);+ clearTimeout(timeout);+ process.exit(1);+ }}-});-writeFileSync(join(root, "grandchild-ready"), "ready");-process.send("ready");-if (existsSync(release)) {- watcher.close();- writeFileSync(join(root, "grandchild-done"), "done");+ clearInterval(watcher);+ clearTimeout(timeout);+ writeSync(2, ${JSON.stringify(`${message}\n`)});process.exit(0);-}+}, 25);+writeFileSync(ready, "ready");`;- await writeFile(- script,- `+ await writeFile(+ script,+ `import { spawn } from "node:child_process";+import { existsSync, writeFileSync } from "node:fs";+const ready = ${JSON.stringify(ready)};+const release = ${JSON.stringify(release)};const grandchild = spawn(process.execPath,- ["-e", ${JSON.stringify(grandchildScript)}, ${JSON.stringify(root)}],- { stdio: ["ignore", "ignore", "inherit", "ipc"], windowsHide: true },+ ["-e", ${JSON.stringify(grandchildScript)}, ready, release, String(process.pid)],+ { stdio: ["ignore", "ignore", "inherit"], windowsHide: true },);const readyTimeout = setTimeout(() => {+ clearInterval(readyWatcher);grandchild.kill();- console.error("Timed out waiting for the Windows login grandchild.");+ console.error("Timed out waiting for the login grandchild.");process.exit(1);}, 10_000);-grandchild.once("message", (message) => {- if (message === "ready") {- clearTimeout(readyTimeout);- process.exit(0);- }-});+const readyWatcher = setInterval(() => {+ if (!existsSync(ready)) return;+ clearInterval(readyWatcher);+ clearTimeout(readyTimeout);+ writeFileSync(release, "released");+ process.exit(1);+}, 25);grandchild.once("error", (error) => {+ clearInterval(readyWatcher);clearTimeout(readyTimeout);console.error(error.message);process.exit(1);});`,- );+ );- const completionSignal = AbortSignal.timeout(20_000);- const grandchildDone = (async () => {- try {- for await (const event of watch(root, {- signal: completionSignal,- })) {- if (event.filename === "grandchild-done") {- return await readFile(done, "utf8");- }- }- } catch (error) {- if (completionSignal.aborted) {- throw new Error("The Windows login grandchild did not exit.", {- cause: error,- });- }- throw error;- }- throw new Error("The Windows login grandchild did not exit.");- })();- const handle = new CodexLoginHandle(- { command: process.execPath, prefixArgs: [script] },- ["login"],- process.env,- () => {},- );- try {+ const handle = new CodexLoginHandle(+ { command: "node", prefixArgs: [script] },+ ["login"],+ process.env,+ () => {},+ );+ await expect(handle.waitForInstructions()).rejects.toThrow(message);await expect(handle.wait()).resolves.toMatchObject({- success: true,- exitCode: 0,+ success: false,+ exitCode: 1,+ stderr: expect.stringContaining(message),});- await expect(readFile(ready, "utf8")).resolves.toBe("ready");- } finally {- await writeFile(release, "released");- await expect(grandchildDone).resolves.toBe("done");- }- });+ },+ );++ test.skipIf(process.platform !== "win32")(+ "releases native login pipes when the Windows fallback fires",+ async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-auth-pipes-"));+ temporaryDirectories.push(root);+ const script = join(root, "login-pipes.mjs");+ await writeFile(+ script,+ 'process.stdout.write("ready\\n", () => process.exit(0));\n',+ );++ const originalOnce = ChildProcess.prototype.once;+ let loginChild: ChildProcess | undefined;+ let releaseClose: (() => void) | undefined;+ const processObserver = spyOn(ChildProcess.prototype, "once");+ processObserver.mockImplementation(function (+ this: ChildProcess,+ event: string,+ listener: (...eventArguments: never[]) => void,+ ) {+ if (event === "exit") loginChild = this;+ if (event === "close") {+ return Reflect.apply(originalOnce, this, [+ event,+ (...eventArguments: unknown[]) => {+ releaseClose = () =>+ Reflect.apply(listener, this, eventArguments);+ },+ ]);+ }+ return Reflect.apply(originalOnce, this, [event, listener]);+ });++ let handle: CodexLoginHandle;+ try {+ handle = new CodexLoginHandle(+ { command: "node", prefixArgs: [script] },+ ["login"],+ process.env,+ () => {},+ );+ } finally {+ processObserver.mockRestore();+ }++ try {+ const startedAt = Date.now();+ const timeout = AbortSignal.timeout(5_000);+ const completion = Promise.race([+ handle.wait(),+ new Promise<never>((_, reject) => {+ timeout.addEventListener(+ "abort",+ () => reject(new Error("The Windows login fallback timed out.")),+ { once: true },+ );+ }),+ ]);+ await expect(completion).resolves.toMatchObject({+ success: true,+ exitCode: 0,+ });+ expect(Date.now() - startedAt).toBeGreaterThanOrEqual(900);+ expect(releaseClose).toBeFunction();+ expect(loginChild?.stdout?.destroyed).toBe(true);+ expect(loginChild?.stderr?.destroyed).toBe(true);+ } finally {+ releaseClose?.();+ }+ },+ );test("does not report a canceled interactive login as successful", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-auth-cancel-"));diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 763a9f6b3..2235d9bad 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -11,7 +11,7 @@ import {writeFile,} from "node:fs/promises";import { tmpdir } from "node:os";-import { delimiter, join } from "node:path";+import { delimiter, join, normalize } from "node:path";import { Writable } from "node:stream";import { fileURLToPath, pathToFileURL } from "node:url";import { stripVTControlCharacters } from "node:util";@@ -182,10 +182,12 @@ describe("CLI", () => {deps,),).toBe(0);- expect(JSON.parse(stdout.text())).toEqual({- hook,- failOnSeverity: "medium",- });+ const result = JSON.parse(stdout.text()) as {+ hook: string;+ failOnSeverity: string;+ };+ expect(normalize(result.hook)).toBe(hook);+ expect(result.failOnSeverity).toBe("medium");}expect(await readFile(hook, "utf8")).toContain("--working-tree --fail-on-severity medium",@@ -206,10 +208,12 @@ describe("CLI", () => {deps,),).toBe(0);- expect(JSON.parse(migratedHook.text())).toEqual({- hook,- failOnSeverity: "medium",- });+ const migrated = JSON.parse(migratedHook.text()) as {+ hook: string;+ failOnSeverity: string;+ };+ expect(normalize(migrated.hook)).toBe(hook);+ expect(migrated.failOnSeverity).toBe("medium");expect(await readFile(hook, "utf8")).toBe(trustedHook);const existingHook = capture();@@ -302,7 +306,7 @@ describe("CLI", () => {await expect(stat(maliciousMarker)).rejects.toMatchObject({code: "ENOENT",});- expect(trustedHook).not.toContain("npx");+ expect(trustedHook).not.toMatch(/^exec\s+npx(?:\s|$)/m);expect(trustedHook).toContain(await realpath(process.execPath));expect(trustedHook).toContain(await realpath(