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-oaid63422f2bc78
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 3cef4a33c..ceac26803 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -272,7 +272,8 @@ model access remain unverified until a real scan starts.Scan progress identifies the selected credential source before Codex starts.Interactive terminals also show how to retry with ChatGPT when an environmentAPI key overrides the stored sign-in. Progress remains on stderr so JSON output-stays machine readable.+stays machine readable. Recoverable failures include safe retry causes and,+when available, the server-provided retry delay.## Documentation and securitydiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 862045ca0..79135fed3 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -122,7 +122,11 @@ export interface ScanOptions {onOutputDirReady?: (scanDir: string) => void;onAuthentication?: (authentication: ScanAuthentication) => void;onScanStarted?: () => void;- onReconnect?: (attempt: number, maxAttempts: number) => void;+ onReconnect?: (+ attempt: number,+ maxAttempts: number,+ details?: ScanReconnectDetails,+ ) => void;onWorkerStatus?: (status: ScanWorkerStatus) => void;onObserverError?: (observer: ScanObserverName, error: unknown) => void;signal?: AbortSignal;@@ -139,6 +143,11 @@ export type ScanAuthentication =verified: false;};+export interface ScanReconnectDetails {+ reason: "rate_limit" | "network" | "authentication" | "authorization";+ retryAfterSeconds?: number;+}+type ScanObserverName =| "onAuthentication"| "onOutputArchived"@@ -948,7 +957,11 @@ interface ScanEventRunOptions {expectation: ScanExpectation;onFinalize?: () => Promise<void>;onScanStarted?: () => void;- onReconnect?: (attempt: number, maxAttempts: number) => void;+ onReconnect?: (+ attempt: number,+ maxAttempts: number,+ details?: ScanReconnectDetails,+ ) => void;onWorkerStatus?: (status: ScanWorkerStatus) => void;onObserverError?: (observer: ScanObserverName, error: unknown) => void;}@@ -1013,6 +1026,7 @@ export async function runScanEvents(options.onReconnect,options.onObserverError,...reconnect,+ reconnectDetails(message),);}}@@ -1272,6 +1286,71 @@ function reconnectAttempt(message: string): [number, number] | null {return attempt <= maxAttempts ? [attempt, maxAttempts] : null;}+function reconnectDetails(message: string): ScanReconnectDetails | undefined {+ const classification = classifyConnectionFailure(message);+ if (classification !== "rate_limited") {+ if (classification === "network_error") return { reason: "network" };+ if (classification === "unauthorized") return { reason: "authentication" };+ if (classification === "forbidden") return { reason: "authorization" };+ return undefined;+ }+ const delay =+ /\b(?:try again|retry)\s+in\s+(\d{1,6}(?:\.\d{1,3})?)\s*(?:s\b|seconds?\b)/iu.exec(+ message,+ );+ const retryAfterSeconds = delay === null ? NaN : Number(delay[1]);+ return {+ reason: "rate_limit",+ ...(Number.isFinite(retryAfterSeconds) &&+ retryAfterSeconds > 0 &&+ retryAfterSeconds <= 3_600+ ? { retryAfterSeconds }+ : {}),+ };+}++export function classifyConnectionFailure(+ error: unknown,+):+ | "rate_limited"+ | "unauthorized"+ | "forbidden"+ | "network_error"+ | "timeout"+ | "unknown" {+ const message = error instanceof Error ? error.message : String(error);+ if (+ /\brate[_ -]?limit(?:ed|[_ -]exceeded)?\b|\b429\b|\btoo many requests\b/iu.test(+ message,+ )+ ) {+ return "rate_limited";+ }+ if (+ /\b401\b|\bunauthori[sz]ed\b|\binvalid[_ -](?:api[_ -]?key|authentication|token|credentials?)\b|\b(?:expired|revoked)[_ -](?:api[_ -]?key|token|credentials?)\b|\b(?:api[_ -]?key|token|credentials?)(?: has)? (?:expired|been revoked)\b/iu.test(+ message,+ )+ ) {+ return "unauthorized";+ }+ if (+ /\b403\b|\bforbidden\b|\bpermission denied\b|\b(?:model|organization|project) access\b|\b(?:access denied|do not have access|not authorized|insufficient permissions)\b|\bmodel[_ -]?not[_ -]?found\b/iu.test(+ message,+ )+ ) {+ return "forbidden";+ }+ if (+ /\b(?:ENOTFOUND|ECONNRESET|ECONNREFUSED|EHOSTUNREACH|ETIMEDOUT)\b|\b(?:network|connection|TLS|DNS)\b|\berror sending request\b/iu.test(+ message,+ )+ ) {+ return "network_error";+ }+ if (/\b(?:timed? out|timeout)\b/iu.test(message)) return "timeout";+ return "unknown";+}+export function scanRuntimeCodexConfig(config: JsonObject): JsonObject {const hardened = structuredClone(config);delete hardened["sandbox_mode"];diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex f54e9b115..77d805371 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -28,6 +28,7 @@ import { pathToFileURL } from "node:url";import { Cli, z } from "incur";import { parse as parseToml } from "smol-toml";import {+ classifyConnectionFailure,CodexSecurity,scanAuthentication,type ScanOptions,@@ -1998,11 +1999,23 @@ async function runScan(progress?.stopTimer();progress?.startTimer(runningMessage());},- onReconnect: (attempt, maxAttempts) => {+ onReconnect: (attempt, maxAttempts, details) => {progress?.stopTimer();- progress?.stage(- `Codex connection interrupted; retrying (${attempt}/${maxAttempts})`,- );+ const message =+ details?.reason === "rate_limit"+ ? `Rate limit reached; retrying${+ details.retryAfterSeconds === undefined+ ? ""+ : ` in ${details.retryAfterSeconds}s`+ } (${attempt}/${maxAttempts}).`+ : details?.reason === "network"+ ? `Network connection interrupted; retrying (${attempt}/${maxAttempts}).`+ : details?.reason === "authentication"+ ? `Authentication interrupted; retrying (${attempt}/${maxAttempts}).`+ : details?.reason === "authorization"+ ? `Model access interrupted; retrying (${attempt}/${maxAttempts}).`+ : `Codex connection interrupted; retrying (${attempt}/${maxAttempts})`;+ progress?.stage(message);progress?.startTimer(runningMessage());},onWorkerStatus: (status) => {@@ -2062,7 +2075,7 @@ async function runScan(const message =failure instanceof OutputInsideProtectedRootError? cliErrorMessage(protectedRootErrorMessage(failure))- : cliErrorMessage(failure);+ : scanFailureMessage(failure);if (failure instanceof OutputInsideProtectedRootError) {errorOutput.write(`${message}\n`);} else {@@ -2112,6 +2125,23 @@ async function runScan(return { exitCode: blockingCount > 0 ? 1 : 0, data: result.toJSON() };}+function scanFailureMessage(error: unknown): string {+ switch (classifyConnectionFailure(error)) {+ case "unauthorized":+ return "Authentication failed. Sign in again or provide a valid API key.";+ case "forbidden":+ return "The selected credentials cannot access the configured model. Use an account or API key with model access.";+ case "rate_limited":+ return "The configured account reached its rate limit. Wait and retry.";+ case "network_error":+ return "The model service could not be reached. Check your network connection and try again.";+ case "timeout":+ return "The connection timed out. Check your network connection and try again.";+ case "unknown":+ return cliErrorMessage(error);+ }+}+function scanScope(arguments_: ScanArguments): string | null {if (arguments_.paths.length > 0) {const displayed = arguments_.paths.slice(0, 3).map((path) => {diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex e83a6a281..e0c5af00b 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -4,6 +4,7 @@ export type {ScanAuthentication,ScanOptions,ScanPreflight,+ ScanReconnectDetails,} from "./api.js";export type { ScanWorkerPhase, ScanWorkerStatus } from "./worker-progress.js";export { CodexLoginHandle } from "./auth.js";diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex a62c9fd3f..fdab47adc 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -31,6 +31,7 @@ import {type ScanAuthentication,type ScanOptions,ScanInterruptedError,+ type ScanReconnectDetails,type ScanWorkerStatus,} from "../src/index.js";import {@@ -121,7 +122,11 @@ function runEvents(scanDir: string,events: AsyncGenerator<ThreadEvent>,abortController = new AbortController(),- onReconnect?: (attempt: number, maxAttempts: number) => void,+ onReconnect?: (+ attempt: number,+ maxAttempts: number,+ details?: ScanReconnectDetails,+ ) => void,onWorkerStatus?: (status: ScanWorkerStatus) => void,onScanStarted?: () => void,onObserverError?: (observer: ScanObserverName, error: unknown) => void,@@ -455,6 +460,91 @@ describe("one-shot scan events", () => {});});+ test("extracts bounded rate-limit context from reconnect notifications", async () => {+ const scanDir = await copyCompletedScan(await temporaryDirectory());+ const reconnects: Array<{+ attempt: number;+ maxAttempts: number;+ details?: ScanReconnectDetails;+ }> = [];++ async function* events(): AsyncGenerator<ThreadEvent> {+ yield {+ type: "error",+ message:+ "Reconnecting... 2/5 (Rate limit reached for org-private. Please try again in 1.2s.)",+ };+ yield {+ type: "error",+ message:+ "Reconnecting... 3/5 (Rate limit reached. Please try again in 999999s.)",+ };+ yield { type: "error", message: "Reconnecting... 4/5" };+ yield* completedEvents();+ }++ await runEvents(+ scanDir,+ events(),+ new AbortController(),+ (attempt, maxAttempts, details) => {+ reconnects.push({+ attempt,+ maxAttempts,+ ...(details ? { details } : {}),+ });+ },+ );++ expect(reconnects).toEqual([+ {+ attempt: 2,+ maxAttempts: 5,+ details: { reason: "rate_limit", retryAfterSeconds: 1.2 },+ },+ { attempt: 3, maxAttempts: 5, details: { reason: "rate_limit" } },+ { attempt: 4, maxAttempts: 5 },+ ]);+ expect(JSON.stringify(reconnects)).not.toContain("org-private");+ });++ test("classifies reconnect causes without exposing provider details", async () => {+ const scanDir = await copyCompletedScan(await temporaryDirectory());+ const reconnects: ScanReconnectDetails[] = [];++ async function* events(): AsyncGenerator<ThreadEvent> {+ yield {+ type: "error",+ message: "Reconnecting... 1/5 (ECONNRESET org-private)",+ };+ yield {+ type: "error",+ message: "Reconnecting... 2/5 (401 invalid API key org-private)",+ };+ yield {+ type: "error",+ message: "Reconnecting... 3/5 (403 model access denied org-private)",+ };+ yield* completedEvents();+ }++ await runEvents(+ scanDir,+ events(),+ new AbortController(),+ (_a, _m, detail) => {+ if (detail !== undefined) reconnects.push(detail);+ },+ );++ expect(reconnects).toEqual([+ { reason: "network" },+ { reason: "authentication" },+ { reason: "authorization" },+ ]);+ expect(JSON.stringify(reconnects)).not.toContain("org-private");+ });+test("uses the last reconnect error when Codex ends without a terminal event", async () => {const scanDir = join(await temporaryDirectory(), "partial-scan");await mkdir(scanDir, { mode: 0o700 });diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex a2be0fa84..c7315240a 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -3153,6 +3153,83 @@ describe("CLI", () => {);});+ test("renders bounded rate-limit retry details without leaking provider context", async () => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onScanStarted?.();+ options?.onReconnect?.(2, 5, {+ reason: "rate_limit",+ retryAfterSeconds: 1.2,+ });+ options?.onReconnect?.(3, 5, { reason: "rate_limit" });+ return fakeResult();+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(+ await main(["scan", "--json"], stdout.stream, stderr.stream, deps),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toEqual(fakeResult().toJSON());+ expect(stderr.text()).toContain(+ "Rate limit reached; retrying in 1.2s (2/5).",+ );+ expect(stderr.text()).toContain("Rate limit reached; retrying (3/5).");+ });++ test("renders safe reconnect causes without forwarding provider messages", async () => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onReconnect?.(1, 5, { reason: "network" });+ options?.onReconnect?.(2, 5, { reason: "authentication" });+ options?.onReconnect?.(3, 5, { reason: "authorization" });+ return fakeResult();+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(+ await main(["scan", "--json"], stdout.stream, stderr.stream, deps),+ ).toBe(0);+ expect(stderr.text()).toContain("Network connection interrupted; retrying");+ expect(stderr.text()).toContain("Authentication interrupted; retrying");+ expect(stderr.text()).toContain("Model access interrupted; retrying");+ expect(JSON.parse(stdout.text())).toEqual(fakeResult().toJSON());+ });++ test("turns provider-specific scan failures into actionable safe messages", async () => {+ for (const [message, expected] of [+ ["401 invalid API key for org-private", "provide a valid API key"],+ ["403 model access denied for org-private", "model access"],+ ["429 rate limit reached for org-private", "rate limit"],+ ["network failure ECONNRESET for org-private", "network connection"],+ ["request timed out for org-private", "connection timed out"],+ ] as const) {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async () => {+ throw new CodexSecurityError(message);+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(await main(["scan"], stdout.stream, stderr.stream, deps)).toBe(2);+ expect(stderr.text()).toContain(expected);+ expect(stderr.text()).not.toContain("org-private");+ }+ });+test("reports stored and secondary-key scan authentication on stderr", async () => {for (const [authentication, expected] of [[