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
fix(cli): emit structured JSON errors for failed scans (#709)
HughChaw70d5b2edae13
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 7607d382a..28b74074c 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -587,6 +587,23 @@ Scans are report-only by default. Set `--fail-on-severity high` to exit with`1` if a completed scan finds high or critical issues. Incomplete scans exitwith `2`, writing available results to stdout and a coverage warning to stderr.+For machine-readable scan output (`--format json` or `--format jsonl`), a scan+execution failure writes one structured object to stdout:++```json+{+ "status": "failed",+ "code": "SCAN_FAILED",+ "message": "..."+}+```++The command still exits with `2` for runtime, export, invalid-input, or+incomplete-scan failures, and human-readable diagnostics remain on stderr.+Use `scan --schema --format json` to discover this failure variant alongside+the successful scan output. Cancellation and termination retain their `130`+and `143` exit codes.+### Import findings as a saved scanImport an existing findings CSV or JSON file into local scan history and SQLite:diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex bb4e56d38..4957f7cbe 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -1003,6 +1003,17 @@ interface ScanOutcome {error?: string;}+const scanOutputSchema = z+ .union([+ z.record(z.string(), z.unknown()),+ z.object({+ status: z.literal("failed"),+ code: z.literal("SCAN_FAILED"),+ message: z.string(),+ }),+ ])+ .optional();+interface ExportArguments {scanDir: string;format: keyof typeof EXPORT_DEFAULT_OUTPUTS;@@ -3573,7 +3584,7 @@ export async function main(},},],- output: z.record(z.string(), z.unknown()).optional(),+ output: scanOutputSchema,async run({ args, error: incurError, format, options }) {if (format === "md") {errorOutput.write(@@ -3665,6 +3676,13 @@ export async function main(}exitCode = outcome.exitCode;if (outcome.error !== undefined) {+ if (format === "json" || format === "jsonl") {+ return {+ status: "failed",+ code: "SCAN_FAILED",+ message: safeErrorMessage(outcome.error),+ };+ }return incurError({code: "SCAN_FAILED",message: outcome.error,diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex c27b96d00..ade062b24 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -932,7 +932,10 @@ describe("CLI authentication", () => {deps,),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ });expect(stderr.text()).toContain("workspace-managed policies");expect(stderr.text()).toContain("API key is selected for model authentication",@@ -967,7 +970,11 @@ describe("CLI authentication", () => {expect(await main(["scan", "--json"], stdout.stream, stderr.stream, deps),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ message: message.includes("access token") ? "[redacted]" : message,+ });expect(stderr.text()).toContain(`${message}\n`);expect(stderr.text()).not.toContain("PRIVATE_UPSTREAM_DETAIL");expect(stderr.text()).not.toContain("npx @openai/codex-security logout");diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.tsindex 8b993b721..0db633e8d 100644--- a/sdk/typescript/tests-ts/cli-project-config.test.ts+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts@@ -1031,7 +1031,11 @@ test("a malformed selected file fails before constructing a client", async () =>).toBe(2);expect(initialized).toBe(false);expect(stderr.text()).toContain("Cannot parse project configuration");- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toEqual({+ status: "failed",+ code: "SCAN_FAILED",+ message: `Cannot parse project configuration at ${input.config}.`,+ });});test("dry-run uses the real SDK without initializing its runtime and reports provenance", async () => {diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex d853d1a94..56ad5004c 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -136,7 +136,18 @@ describe("CLI", () => {dependencies(),),).toBe(0);- expect(JSON.parse(schema.text())).toMatchObject({+ const scanSchema = JSON.parse(schema.text()) as {+ args: Record<string, unknown>;+ options: Record<string, unknown>;+ output?: {+ anyOf?: Array<{+ properties?: Record<string, { const?: string; type?: string }>;+ required?: string[];+ additionalProperties?: boolean;+ }>;+ };+ };+ expect(scanSchema).toMatchObject({args: { properties: { repository: { type: "string" } } },options: {properties: {@@ -164,6 +175,18 @@ describe("CLI", () => {},},});+ const failureSchema = scanSchema.output?.anyOf?.find(+ (variant) => variant.properties?.["code"]?.const === "SCAN_FAILED",+ );+ expect(failureSchema).toMatchObject({+ properties: {+ status: { const: "failed" },+ code: { const: "SCAN_FAILED" },+ message: { type: "string" },+ },+ required: ["status", "code", "message"],+ additionalProperties: false,+ });const rerunSchema = capture();expect(@@ -3644,7 +3667,10 @@ describe("CLI", () => {expect(stderr.text()).toContain("Provider failed for");expect(stderr.text()).toContain("tenant-private");expect(stderr.text()).toContain("req-internal");- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ });});test("preserves provider identifier variants in scan failures", async () => {@@ -3737,7 +3763,10 @@ describe("CLI", () => {deps,),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ });expect(stderr.text()).toContain("Provider failed for");for (const identifier of identifiers) {expect(stderr.text()).toContain(identifier);@@ -3957,7 +3986,10 @@ describe("CLI", () => {expect(stderr.text()).toContain("Cleanup failed for");expect(stderr.text()).toContain("tenant-private");expect(stderr.text()).toContain("req-internal");- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ });});test("reports reconnect progress on stderr and keeps JSON output clean", async () => {@@ -4063,6 +4095,41 @@ describe("CLI", () => {}});+ test("emits structured failures for machine-readable scan output", async () => {+ const message = "This content was flagged for possible cybersecurity risk.";+ for (const formatArgs of [+ ["--json"],+ ["--format", "json"],+ ["--format", "jsonl"],+ ] 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", ".", ...formatArgs],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(stdout.text().trim())).toEqual({+ status: "failed",+ code: "SCAN_FAILED",+ message,+ });+ expect(stderr.text()).toContain(`${message}\n`);+ }+ });+test("surfaces underlying scanner errors instead of inventing a model outage", async () => {for (const message of ["Could not save the Codex Security scan: UNIQUE constraint failed: scans.scan_dir",@@ -4085,7 +4152,11 @@ describe("CLI", () => {expect(await main(["scan", ".", "--json"], stdout.stream, stderr.stream, deps),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toEqual({+ status: "failed",+ code: "SCAN_FAILED",+ message,+ });expect(stderr.text()).toContain(`${message}\n`);expect(stderr.text()).not.toContain("codex-security:");expect(stderr.text()).not.toContain("model service could not be reached");@@ -4209,7 +4280,11 @@ describe("CLI", () => {expect(await main(["scan", ".", "--json"], stdout.stream, stderr.stream, deps),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toEqual({+ status: "failed",+ code: "SCAN_FAILED",+ message: "[redacted]",+ });expect(stderr.text()).toContain(`network failure ECONNRESET ${SYNTHETIC_CREDENTIALS}`,);@@ -4925,7 +5000,11 @@ describe("CLI", () => {}),),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ message: expect.stringContaining("estimated cost"),+ });expect(stderr.text()).toContain("Scan stopped: short-context budget baseline $0.00488 exceeded the $0.004 limit; estimated cost $0.00488–$0.01156 (standard, context unknown, cache writes unknown); partial output remains at /tmp/scan.",);@@ -5344,7 +5423,13 @@ describe("CLI", () => {failing,),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ message: expect.stringContaining(+ "Scan output directory must be outside",+ ),+ });expect(stderr.text()).toContain("Scan output directory must be outside the scanned directory and any enclosing Git worktree.",);@@ -5451,7 +5536,10 @@ describe("CLI", () => {failing,),).toBe(2);- expect(stdout.text()).toBe("");+ expect(JSON.parse(stdout.text())).toMatchObject({+ status: "failed",+ code: "SCAN_FAILED",+ });expect(stderr.text()).toContain(`Resolved path: ${output}`);expect(stderr.text()).toContain(`Protected root: ${protectedRoot}`);});@@ -5532,7 +5620,15 @@ describe("CLI", () => {}),),).toBe(2);- expect(stdout.text()).toBe("");+ if (json) {+ expect(JSON.parse(stdout.text())).toEqual({+ status: "failed",+ code: "SCAN_FAILED",+ message: "SYNTHETIC_AUTH_HOME_CLEANUP_FAILED",+ });+ } else {+ expect(stdout.text()).toBe("");+ }expect(stderr.text()).toContain("SYNTHETIC_AUTH_HOME_CLEANUP_FAILED");expect(stderr.text()).toContain("Partial output was kept at /tmp/scan.");}