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: make scan authentication and state failures actionable (#22)
Dane Schneiderb1e2af91f5cb
diff --git a/README.md b/README.mdindex 0708db9a0..43887e9a5 100644--- a/README.md+++ b/README.md@@ -16,6 +16,26 @@ npx codex-security scan .For CI, set `OPENAI_API_KEY` instead of signing in.+If both a ChatGPT sign-in and an API key are available, interactive scans ask+which credential to use. CI and other noninteractive scans keep the existing+API-key precedence. Select a credential explicitly when needed:++```bash+npx codex-security scan . --auth chatgpt+npx codex-security scan . --auth api-key+```++To make your ChatGPT sign-in the automatic default, unset any configured API+keys:++```bash+unset OPENAI_API_KEY CODEX_API_KEY+```++Scan history is stored in the Codex Security workbench state directory. If that+directory cannot be written, set `CODEX_SECURITY_STATE_DIR` to a writable+directory outside the repository.+## TypeScript SDK```tsdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 571a38f37..8cdbbf89c 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -86,11 +86,36 @@ Check or remove the stored sign-in with `npx codex-security login status` andsign-in. If Codex stores credentials in the system keyring, run`npx codex-security login` once before scanning.-An environment API key takes precedence over a stored sign-in. Unset both-`OPENAI_API_KEY` and `CODEX_API_KEY` to use your ChatGPT sign-in. When an-environment key is configured, `codex-security login status` identifies the-effective credential source without printing its value, including when no-stored sign-in exists.+An environment API key takes precedence over a stored sign-in by default.+When both a stored ChatGPT sign-in and an environment API key are available, an+interactive scan asks which credential to use. JSON output, dry runs, CI, and+other noninteractive scans never prompt and retain automatic API-key+precedence. Select the credential source explicitly with `--auth`:++```bash+npx codex-security scan . --auth chatgpt+npx codex-security scan . --auth api-key+```++`--auth chatgpt` uses the stored sign-in and ignores `OPENAI_API_KEY` and+`CODEX_API_KEY`. `--auth api-key` requires one of those environment variables.+Omit `--auth`, or pass `--auth auto`, to preserve automatic API-key precedence+for existing CI and unattended scans. The SDK accepts the same selection as+`security.run(repository, { auth: "chatgpt" })` and+`security.preflight(repository, { auth: "chatgpt" })`.++To make the stored ChatGPT sign-in the automatic default instead, unset any+configured API-key variables:++```bash+unset OPENAI_API_KEY CODEX_API_KEY+```++The interactive choice applies only to the current scan and is not persisted.++When an environment key is configured, ChatGPT login and+`codex-security login status` identify the effective scan credential source+without printing its value, including when no stored sign-in exists.## CLI@@ -216,6 +241,14 @@ Scan history uses the existing Codex Security workbench database at`CODEX_SECURITY_STATE_DIR` to place the database elsewhere. Scan credentialsare never stored in the scan configuration.+The scan sandbox permits writes to the selected state directory so SQLite can+maintain its database and journal files. If the host itself cannot write to the+default directory, select a writable directory outside the scanned repository:++```bash+export CODEX_SECURITY_STATE_DIR=/path/to/writable/codex-security-state+```+`scans rerun SCAN_ID` repeats the original configuration against the currentcheckout so a fixed vulnerability can be checked again.@@ -291,10 +324,11 @@ method and, for an environment API key, its variable name. Authentication andmodel 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 environment-API key overrides the stored sign-in. Progress remains on stderr so JSON output-stays machine readable. Recoverable failures include safe retry causes and,-when available, the server-provided retry delay.+Terminals and noninteractive CI logs also show how to retry with+`--auth chatgpt` when an environment API key overrides the stored sign-in.+Progress remains on stderr so JSON output stays machine readable. Network+failures and rate limits remain retryable; definitive authentication and model+authorization failures stop immediately.## Documentation and securitydiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex a4029ab65..470554c79 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -112,6 +112,7 @@ interface PreparedRuntime {}export interface ScanOptions {+ auth?: ScanAuthMode;target?: ScanTarget;mode?: ScanMode;knowledgeBasePaths?: string[];@@ -136,6 +137,8 @@ export interface ScanOptions {signal?: AbortSignal;}+export type ScanAuthMode = "auto" | "chatgpt" | "api-key";+export type ScanAuthentication =| {method: "api_key";@@ -222,6 +225,7 @@ export class CodexSecurity {#activeOperation: Promise<unknown> | null = null;#runtimePromise: Promise<PreparedRuntime> | null = null;#runtime: PreparedRuntime | null = null;+ #runtimeCredentialSource: "api_key" | "stored_credentials" | null = null;#closed = false;#closePromise: Promise<void> | null = null;@@ -273,7 +277,10 @@ export class CodexSecurity {: {}),outputDir: inputs.outputDir,...(archiveDir === null ? {} : { archiveDir }),- authentication: scanAuthentication(this.#dependencies.environment),+ authentication: scanAuthentication(+ this.#dependencies.environment,+ options.auth,+ ),...model,...(options.maxCostUsd === undefined? {}@@ -341,8 +348,20 @@ export class CodexSecurity {}checkOpen();- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) =>- requireOutputOutsideRepository(protectedRoot, path, "runtime"),+ const authentication = scanAuthentication(+ this.#dependencies.environment,+ options.auth,+ );+ const scanEnvironment = selectedScanEnvironment(+ this.#dependencies.environment,+ options.auth,+ );+ const runtime = await this.#ensureRuntime(+ signal,+ temporaryRoot,+ (path) =>+ requireOutputOutsideRepository(protectedRoot, path, "runtime"),+ options.auth,);const runtimeHome = await realpath(runtime.codexHome);requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");@@ -355,7 +374,25 @@ export class CodexSecurity {);}checkOpen();- const apiKey = environmentApiKey(this.#dependencies.environment);+ if (+ authentication.method === "stored_credentials" &&+ this.#runtimeCredentialSource === "api_key"+ ) {+ const ambientHome =+ environmentValue(this.#dependencies.environment, "CODEX_HOME") ??+ join(homedir(), ".codex");+ runtime.credentialsAvailable = await importAmbientAuth(+ ambientHome,+ runtime.codexHome,+ );+ this.#runtimeCredentialSource = runtime.credentialsAvailable+ ? "stored_credentials"+ : null;+ }+ const apiKey =+ authentication.method === "api_key"+ ? environmentApiKey(this.#dependencies.environment)+ : null;if (apiKey !== null) {const codexCommand = this.#codexCommand();const login = await persistApiKey(@@ -370,6 +407,7 @@ export class CodexSecurity {);}runtime.credentialsAvailable = true;+ this.#runtimeCredentialSource = "api_key";}if (!runtime.credentialsAvailable) {throw new AuthenticationRequiredError(@@ -382,13 +420,13 @@ export class CodexSecurity {"onAuthentication",options.onAuthentication,options.onObserverError,- scanAuthentication(this.#dependencies.environment),+ authentication,);const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({configuredPath: this.config.pythonPath,- environment: this.#dependencies.environment,+ environment: scanEnvironment,protectedRoot,signal,});@@ -500,7 +538,7 @@ export class CodexSecurity {python,pluginRoot: runtime.plugin.pluginRoot,environment: {- ...runtime.environment,+ ...selectedScanEnvironment(runtime.environment, options.auth),CODEX_SECURITY_STATE_DIR: stateDirectory,},signal,@@ -561,7 +599,9 @@ export class CodexSecurity {const environment = {...pluginExecutionEnvironment(python,- withoutCodexHome(runtime.environment),+ withoutCodexHome(+ selectedScanEnvironment(runtime.environment, options.auth),+ ),),CODEX_HOME: runtime.codexHome,...runtimePaths,@@ -688,6 +728,7 @@ export class CodexSecurity {);}runtime.credentialsAvailable = true;+ this.#runtimeCredentialSource = "api_key";}public async loginChatGPT(): Promise<CodexLoginHandle> {@@ -700,6 +741,7 @@ export class CodexSecurity {runtime.environment,() => {runtime.credentialsAvailable = true;+ this.#runtimeCredentialSource = "stored_credentials";},),);@@ -718,6 +760,7 @@ export class CodexSecurity {runtime.environment,() => {runtime.credentialsAvailable = true;+ this.#runtimeCredentialSource = "stored_credentials";},),);@@ -755,6 +798,7 @@ export class CodexSecurity {},);runtime.credentialsAvailable = false;+ this.#runtimeCredentialSource = null;}public async close(): Promise<void> {@@ -835,6 +879,7 @@ export class CodexSecurity {signal?: AbortSignal,temporaryRoot?: string,validateLocation?: (path: string) => void,+ auth: ScanAuthMode = "auto",): Promise<PreparedRuntime> {this.#requireOpen();if (this.#runtime !== null) return this.#runtime;@@ -843,6 +888,7 @@ export class CodexSecurity {signal ?? this.#abortController.signal,temporaryRoot,validateLocation,+ auth,);this.#runtimePromise = runtimePromise;void runtimePromise.catch(() => {@@ -854,6 +900,9 @@ export class CodexSecurity {const runtime = await this.#runtimePromise;this.#requireOpen();this.#runtime = runtime;+ this.#runtimeCredentialSource = runtime.credentialsAvailable+ ? "stored_credentials"+ : null;return this.#runtime;}@@ -914,6 +963,7 @@ export class CodexSecurity {signal: AbortSignal,temporaryRoot?: string,validateLocation?: (path: string) => void,+ auth: ScanAuthMode = "auto",): Promise<PreparedRuntime> {if (this.#dependencies.prepareRuntime !== undefined) {return await this.#dependencies.prepareRuntime(this.config, signal);@@ -931,7 +981,10 @@ export class CodexSecurity {bootstrapWorkspace,signal,);- const processEnvironment = this.#dependencies.environment;+ const processEnvironment = selectedScanEnvironment(+ this.#dependencies.environment,+ auth,+ );const nodeAmbientHome = join(homedir(), ".codex");const configuredAmbientHome = environmentValue(processEnvironment,@@ -939,7 +992,10 @@ export class CodexSecurity {);const ambientHome = configuredAmbientHome ?? nodeAmbientHome;const mergedConfig = await mergedCodexConfig(this.config);- const codexConfig = scanRuntimeCodexConfig(mergedConfig);+ const codexConfig = scanRuntimeCodexConfig(+ mergedConfig,+ codexSecurityStateDirectory(processEnvironment),+ );await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);const configPath = join(bootstrapWorkspace, "config-preflight.toml");await writeCodexConfig(@@ -1091,6 +1147,13 @@ export async function runScanEvents(typeof event["message"] === "string") {const message = event["message"];+ const classification = classifyConnectionFailure(message);+ if (+ classification === "unauthorized" ||+ classification === "forbidden"+ ) {+ throw new CodexSecurityError(message);+ }const reconnect = reconnectAttempt(message);if (reconnect === null) throw new CodexSecurityError(message);lastStreamError = message;@@ -1328,13 +1391,37 @@ async function collectResult(export function scanAuthentication(environment: ProcessEnvironment,+ auth: ScanAuthMode = "auto",): ScanAuthentication {+ if (auth === "chatgpt") {+ return { method: "stored_credentials", verified: false };+ }const key = environmentApiKeyEntry(environment);+ if (auth === "api-key" && key === null) {+ throw new AuthenticationRequiredError(+ "API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY. " ++ "Set a valid API key or use '--auth chatgpt'.",+ );+ }return key === null? { method: "stored_credentials", verified: false }: { method: "api_key", source: key.source, verified: false };}+function selectedScanEnvironment(+ environment: ProcessEnvironment,+ auth: ScanAuthMode = "auto",+): ProcessEnvironment {+ if (auth !== "chatgpt") return environment;+ return Object.fromEntries(+ Object.entries(environment).filter(+ ([name]) =>+ name.toUpperCase() !== "OPENAI_API_KEY" &&+ name.toUpperCase() !== "CODEX_API_KEY",+ ),+ );+}+function notifyObserver<Arguments extends unknown[]>(observerName: ScanObserverName,observer: ((...args: Arguments) => void) | undefined,@@ -1416,6 +1503,9 @@ export function classifyConnectionFailure(| "timeout"| "unknown" {const message = error instanceof Error ? error.message : String(error);+ if (/\b(?:sqlite3?|database|workbench)\b/iu.test(message)) {+ return "unknown";+ }if (/\brate[_ -]?limit(?:ed|[_ -]exceeded)?\b|\b429\b|\btoo many requests\b/iu.test(message,@@ -1448,7 +1538,10 @@ export function classifyConnectionFailure(return "unknown";}-export function scanRuntimeCodexConfig(config: JsonObject): JsonObject {+export function scanRuntimeCodexConfig(+ config: JsonObject,+ stateDirectory: string,+): JsonObject {const hardened = structuredClone(config);delete hardened["sandbox_mode"];const configuredPermissions = isRecord(hardened["permissions"])@@ -1464,6 +1557,7 @@ export function scanRuntimeCodexConfig(config: JsonObject): JsonObject {filesystem: {":root": "read",":workspace_roots": "write",+ [stateDirectory]: "write",},},},diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 2c0bad86f..3307fd2c9 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -31,13 +31,17 @@ import {classifyConnectionFailure,CodexSecurity,scanAuthentication,+ type ScanAuthMode,+ type ScanAuthentication,type ScanOptions,type ScanPreflight,} from "./api.js";+import { accountStatus } from "./auth.js";import {createBulkScanDiscoveryDependencies,runBulkScanWizard,type BulkScanDiscoveryDependencies,+ type BulkScanPrompt,} from "./bulk-scan-discovery.js";import {DEFAULT_CODEX_CONFIG,@@ -120,6 +124,7 @@ const EXPORT_DEFAULT_OUTPUTS = {sarif: "results.sarif",} as const;const VALUE_OPTIONS = new Set([+ "--auth","--path","--knowledge-base","--diff",@@ -150,6 +155,7 @@ function optionValue(flag: string) {}interface ScanArguments {+ auth?: ScanAuthMode;repository?: string;paths: string[];knowledgeBasePaths: string[];@@ -211,6 +217,8 @@ interface CliDependencies {config: CodexSecurityConfig,): Pick<CodexSecurity, "run" | "preflight" | "close">;environment: NodeJS.ProcessEnv;+ hasStoredChatGPTSignIn?: () => Promise<boolean>;+ scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;currentDirectory(): string;now(): number;setInterval(callback: () => void, milliseconds: number): NodeJS.Timeout;@@ -235,6 +243,17 @@ interface CliDependencies {const DEFAULT_DEPENDENCIES: CliDependencies = {createSecurity: (config) => new CodexSecurity(config),environment: process.env,+ hasStoredChatGPTSignIn: async () => {+ const environment = Object.fromEntries(+ Object.entries(process.env).filter(+ ([name]) =>+ name.toUpperCase() !== "OPENAI_API_KEY" &&+ name.toUpperCase() !== "CODEX_API_KEY",+ ),+ );+ const status = await accountStatus(resolveCodexCommand(), environment);+ return status.authenticated && /\bchatgpt\b/iu.test(status.details);+ },currentDirectory: cwd,now: Date.now,setInterval: (callback, milliseconds) => setInterval(callback, milliseconds),@@ -776,6 +795,10 @@ export async function main(}),options: z.object({+ auth: z+ .enum(["auto", "chatgpt", "api-key"])+ .default("auto")+ .describe("Select automatic, ChatGPT, or API-key authentication."),path: z.array(optionValue("--path")).default([])@@ -880,6 +903,7 @@ export async function main(}const outcome = await runScan({+ auth: options.auth,repository: args.repository,paths: options.path,knowledgeBasePaths: options.knowledgeBase,@@ -1276,6 +1300,30 @@ export async function main("To use a ChatGPT sign-in, unset OPENAI_API_KEY and CODEX_API_KEY.\n",);}+ } else if (+ exitCode === 0 &&+ !options.withApiKey &&+ !options.withAccessToken+ ) {+ const authentication = scanAuthentication(dependencies.environment);+ if (authentication.method === "api_key") {+ const configuredApiKeyVariables = Object.entries(+ dependencies.environment,+ )+ .filter(+ ([name, value]) =>+ value?.trim() &&+ (name.toUpperCase() === "OPENAI_API_KEY" ||+ name.toUpperCase() === "CODEX_API_KEY"),+ )+ .map(([name]) => name);+ errorOutput.write(+ "ChatGPT login succeeded. Interactive scans will ask which account to use; " ++ `noninteractive scans will use ${authentication.source}.\n` ++ "To use your ChatGPT sign-in, pass '--auth chatgpt' or run " ++ `'unset ${configuredApiKeyVariables.join(" ")}'.\n`,+ );+ }}},})@@ -2120,6 +2168,7 @@ async function runScan(null;let result: ScanResult | null = null;let preflight: ScanPreflight | null = null;+ let selectedAuthentication: ScanAuthentication | null = null;let failed = false;let failure: unknown;try {@@ -2132,6 +2181,43 @@ async function runScan(arguments_.codexOverrides ??parseCodexOverrides(arguments_.codex, arguments_.model),};+ let auth = arguments_.auth;+ selectedAuthentication = scanAuthentication(dependencies.environment, auth);+ if (+ (auth === undefined || auth === "auto") &&+ !arguments_.dryRun &&+ interactive &&+ errorOutput.isTTY === true &&+ selectedAuthentication.method === "api_key"+ ) {+ const prompt =+ dependencies.scanAuthenticationPrompt ??+ createBulkScanDiscoveryDependencies({+ output: errorOutput,+ now: dependencies.now,+ currentDirectory: dependencies.currentDirectory,+ }).prompt;+ if (+ prompt.isInteractive() &&+ (await dependencies.hasStoredChatGPTSignIn?.()) === true+ ) {+ const source = selectedAuthentication.source;+ errorOutput.write(+ `Both a ChatGPT sign-in and an API key from ${source} are available.\n`,+ );+ auth = await prompt.select<ScanAuthMode>(+ "How would you like to authenticate this scan?",+ [+ { label: "ChatGPT subscription", value: "chatgpt" },+ { label: `API key from ${source}`, value: "api-key" },+ ],+ );+ selectedAuthentication = scanAuthentication(+ dependencies.environment,+ auth,+ );+ }+ }progress = new Progress(errorOutput, dependencies, interactive);const scope = scanScope(arguments_);const runningMessage = (): string =>@@ -2145,6 +2231,7 @@ async function runScan();security = dependencies.createSecurity(config);const options: ScanOptions = {+ auth,target,knowledgeBasePaths: arguments_.knowledgeBasePaths,mode: arguments_.mode,@@ -2175,18 +2262,15 @@ async function runScan(scanDir = path;},onAuthentication: (authentication) => {+ selectedAuthentication = authentication;progress?.stopTimer();if (authentication.method === "api_key") {progress?.stage(`Authentication: API key from ${authentication.source}.`,);- if (errorOutput.isTTY === true) {- progress?.stage(- process.platform === "win32"- ? "To use a ChatGPT sign-in, unset OPENAI_API_KEY and CODEX_API_KEY, then retry the scan."- : "Retry with ChatGPT: env -u OPENAI_API_KEY -u CODEX_API_KEY codex-security scan ...",- );- }+ progress?.stage(+ "To use your ChatGPT sign-in, retry with --auth chatgpt.",+ );} else {progress?.stage("Authentication: stored Codex credentials.");}@@ -2272,7 +2356,7 @@ async function runScan(const message =failure instanceof OutputInsideProtectedRootError? cliErrorMessage(protectedRootErrorMessage(failure))- : scanFailureMessage(failure);+ : scanFailureMessage(failure, selectedAuthentication);if (failure instanceof OutputInsideProtectedRootError) {errorOutput.write(`${message}\n`);} else {@@ -2322,12 +2406,24 @@ async function runScan(return { exitCode: blockingCount > 0 ? 1 : 0, data: result.toJSON() };}-function scanFailureMessage(error: unknown): string {+function scanFailureMessage(+ error: unknown,+ authentication: ScanAuthentication | null,+): string {switch (classifyConnectionFailure(error)) {case "unauthorized":- return "Authentication failed. Sign in again or provide a valid API key.";+ return authentication?.method === "api_key"+ ? `Authentication failed using ${authentication.source}. ` ++ "Your ChatGPT sign-in was not used. " ++ "Retry with '--auth chatgpt' or provide a valid API key."+ : "Authentication failed using stored ChatGPT credentials. " ++ "Sign in again with 'codex-security login' 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.";+ return authentication?.method === "api_key"+ ? `The API key from ${authentication.source} cannot access the configured model. ` ++ "Retry with '--auth chatgpt' or use an API key with model access."+ : "The stored ChatGPT 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":diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 00fb3bb3a..dc1c64df2 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -3,6 +3,7 @@ export { estimateScanCost } from "./cost.js";export type { ScanCost } from "./cost.js";export type {CodexSecurityMetadata,+ ScanAuthMode,ScanAuthentication,ScanOptions,ScanPreflight,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex e9551e56a..35e3c9605 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -148,8 +148,20 @@ export async function runWorkbench());} catch (error) {if (options.signal?.aborted) throw error;+ const detail = processErrorDetail(error);+ const databaseFailure =+ /\b(?:unable to open database file|attempt to write a readonly database|readonly database|disk i\/o error)\b/iu.test(+ detail,+ );+ const failure =+ options.failureMessage ?? "Could not run the Codex Security workbench";throw new CodexSecurityError(- `${options.failureMessage ?? "Could not run the Codex Security workbench"}: ${processErrorDetail(error)}`,+ databaseFailure+ ? `${failure}: cannot open the workbench database at ${join(+ codexSecurityStateDirectory(options.environment),+ "workbench.sqlite3",+ )}. Ensure the state directory and SQLite journal files are writable, or set CODEX_SECURITY_STATE_DIR to a writable directory outside the scanned repository.`+ : `${failure}: ${detail}`,{ cause: error },);}diff --git a/sdk/typescript/tests-ts/api-events.test.ts b/sdk/typescript/tests-ts/api-events.test.tsindex 6d906f1d5..2f0ac0fe0 100644--- a/sdk/typescript/tests-ts/api-events.test.ts+++ b/sdk/typescript/tests-ts/api-events.test.ts@@ -374,7 +374,7 @@ describe("one-shot scan events", () => {expect(JSON.stringify(reconnects)).not.toContain("org-private");});- test("classifies reconnect causes without exposing provider details", async () => {+ test("classifies retryable reconnect causes without exposing provider details", async () => {const scanDir = await copyCompletedScan(await temporaryDirectory());const reconnects: ScanReconnectDetails[] = [];@@ -385,11 +385,7 @@ describe("one-shot scan events", () => {};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)",+ message: "Reconnecting... 2/5 (429 rate limit reached org-private)",};yield* completedEvents();}@@ -405,12 +401,43 @@ describe("one-shot scan events", () => {expect(reconnects).toEqual([{ reason: "network" },- { reason: "authentication" },- { reason: "authorization" },+ { reason: "rate_limit" },]);expect(JSON.stringify(reconnects)).not.toContain("org-private");});+ test("fails immediately on definitive authentication and authorization errors", async () => {+ for (const message of [+ "Reconnecting... 1/5 (401 invalid API key org-private)",+ "Reconnecting... 1/5 (403 model access denied org-private)",+ ]) {+ const scanDir = join(await temporaryDirectory(), "partial-scan");+ await mkdir(scanDir, { mode: 0o700 });+ const reconnects: Array<[number, number]> = [];+ let advancedPastFailure = false;++ async function* events(): AsyncGenerator<ThreadEvent> {+ yield { type: "thread.started", thread_id: "thread-1" };+ yield { type: "error", message };+ advancedPastFailure = true;+ yield { type: "error", message: "Reconnecting... 2/5" };+ }++ await expect(+ runEvents(+ scanDir,+ events(),+ new AbortController(),+ (attempt, maxAttempts) => {+ reconnects.push([attempt, maxAttempts]);+ },+ ),+ ).rejects.toMatchObject({ name: CodexSecurityError.name, message });+ expect(reconnects).toEqual([]);+ expect(advancedPastFailure).toBe(false);+ }+ });+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/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 7f0bc6831..80327a62e 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -19,6 +19,7 @@ import { basename, join } from "node:path";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 { parse as parseToml } from "smol-toml";import {AuthenticationRequiredError,CodexSecurity,@@ -32,6 +33,7 @@ import {ScanInterruptedError,} from "../src/index.js";import {+ classifyConnectionFailure,environmentValue,initialCredentialsAvailable,scanPreflightCodexConfig,@@ -163,6 +165,23 @@ function preparedRuntime(codexHome: string): Record<string, unknown> {}describe("CodexSecurity orchestration", () => {+ test("distinguishes local workbench and database errors from model transport failures", () => {+ for (const message of [+ "sqlite3.OperationalError: unable to open database file\nwith closing(connect()) as connection:",+ "Could not save the Codex Security scan: database connection failed",+ "Codex Security workbench: permission denied",+ ]) {+ expect(classifyConnectionFailure(message)).toBe("unknown");+ }+ expect(classifyConnectionFailure("ECONNRESET")).toBe("network_error");+ expect(classifyConnectionFailure("401 invalid API key")).toBe(+ "unauthorized",+ );+ expect(classifyConnectionFailure("403 model access denied")).toBe(+ "forbidden",+ );+ });+test("treats empty environment variables as unset and finds case variants", () => {expect(environmentValue({ CODEX_HOME: "" }, "CODEX_HOME")).toBeUndefined();expect(@@ -179,7 +198,8 @@ describe("CodexSecurity orchestration", () => {);});- test("uses a root-read, workspace-write filesystem profile", () => {+ test("uses a root-read filesystem profile with writable workspace and workbench state", () => {+ const stateDirectory = join(tmpdir(), "codex-security-persistent-state");const original = {sandbox_mode: "workspace-write",allow_login_shell: true,@@ -193,7 +213,7 @@ describe("CodexSecurity orchestration", () => {},};- expect(scanRuntimeCodexConfig(original)).toEqual({+ expect(scanRuntimeCodexConfig(original, stateDirectory)).toEqual({allow_login_shell: false,default_permissions: "codex_security_scan",permissions: {@@ -202,6 +222,7 @@ describe("CodexSecurity orchestration", () => {filesystem: {":root": "read",":workspace_roots": "write",+ [stateDirectory]: "write",},},},@@ -656,6 +677,145 @@ describe("CodexSecurity orchestration", () => {}});+ test("honors explicit authentication selection without initializing the runtime", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);+ let runtimeStarted = false;+ const client = new TestClient(+ {},+ {+ environment: {+ OPENAI_API_KEY: "synthetic-openai-key",+ CODEX_API_KEY: "synthetic-codex-key",+ },+ prepareRuntime: async () => {+ runtimeStarted = true;+ throw new Error("runtime should not initialize");+ },+ },+ );++ await expect(+ client.preflight(repository, { auth: "chatgpt" }),+ ).resolves.toMatchObject({+ authentication: { method: "stored_credentials", verified: false },+ });+ await expect(+ client.preflight(repository, { auth: "api-key" }),+ ).resolves.toMatchObject({+ authentication: {+ method: "api_key",+ source: "OPENAI_API_KEY",+ verified: false,+ },+ });+ await expect(+ client.preflight(repository, { auth: "auto" }),+ ).resolves.toMatchObject({+ authentication: {+ method: "api_key",+ source: "OPENAI_API_KEY",+ verified: false,+ },+ });+ expect(runtimeStarted).toBe(false);+ await client.close();+ });++ test("rejects explicit API-key authentication without a configured key before runtime initialization", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);+ let runtimeStarted = false;+ const client = new TestClient(+ {},+ {+ environment: { OPENAI_API_KEY: " " },+ prepareRuntime: async () => {+ runtimeStarted = true;+ throw new Error("runtime should not initialize");+ },+ },+ );++ await expect(+ client.preflight(repository, { auth: "api-key" }),+ ).rejects.toBeInstanceOf(AuthenticationRequiredError);+ await expect(+ client.run(repository, { auth: "api-key" }),+ ).rejects.toBeInstanceOf(AuthenticationRequiredError);+ expect(runtimeStarted).toBe(false);+ await client.close();+ });++ test("removes ambient API keys from explicitly selected ChatGPT scans", 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 codexOptions: CodexOptions | null = null;+ let pythonEnvironment: Record<string, string | undefined> | undefined;+ let selectedAuthentication: ScanAuthentication | undefined;+ const client = new TestClient(+ {},+ {+ environment: {+ OPENAI_API_KEY: "synthetic-openai-key",+ Codex_Api_Key: "synthetic-codex-key",+ },+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ environment: {+ CODEX_HOME: codexHome,+ OpenAi_Api_Key: "synthetic-forwarded-openai-key",+ codex_api_key: "synthetic-forwarded-codex-key",+ },+ }),+ resolvePluginPython: async (options: {+ environment?: Record<string, string | undefined>;+ }) => {+ pythonEnvironment = options.environment;+ return "/managed/python";+ },+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => {+ codexOptions = options;+ throw new Error("ChatGPT scan reached");+ },+ },+ );++ await expect(+ client.run(repository, {+ auth: "chatgpt",+ onAuthentication: (authentication) => {+ selectedAuthentication = authentication;+ },+ }),+ ).rejects.toThrow("ChatGPT scan reached");+ expect(selectedAuthentication).toEqual({+ method: "stored_credentials",+ verified: false,+ });+ for (const environment of [+ pythonEnvironment,+ (codexOptions as CodexOptions | null)?.env,+ ]) {+ expect(environment).toBeDefined();+ expect(+ Object.keys(environment!).some((name) =>+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),+ ),+ ).toBe(false);+ }+ await client.close();+ });+test("isolates authentication observer failures from scan startup", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");@@ -1681,6 +1841,22 @@ describe("CodexSecurity orchestration", () => {capturedConfigPath = configPath;capturedCodexHome = codexHome;expect(configPath!.startsWith(`${codexHome!}/`)).toBe(false);+ expect(+ parseToml(+ await readFile(join(codexHome!, "config.toml"), "utf8"),+ ),+ ).toMatchObject({+ permissions: {+ codex_security_scan: {+ filesystem: {+ ":root": "read",+ ":workspace_roots": "write",+ [join(ambientHome, "state", "plugins", "codex-security")]:+ "write",+ },+ },+ },+ });if (process.platform !== "win32") {expect((await stat(configPath!)).mode & 0o777).toBe(0o600);}@@ -2370,6 +2546,95 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {).resolves.toBe(true);});+ test("restores stored ChatGPT credentials when switching from an API-key scan", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const ambientHome = join(root, "ambient-home");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ const fakeCodex = join(root, "codex.mjs");+ const ambientAuthentication = '{"auth_mode":"chatgpt"}\n';+ await mkdir(repository);+ await mkdir(ambientHome);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(join(ambientHome, "auth.json"), ambientAuthentication);+ await writeFile(+ fakeCodex,+ `+import { writeFileSync } from "node:fs";+let apiKey = "";+for await (const chunk of process.stdin) apiKey += chunk;+writeFileSync(${JSON.stringify(join(codexHome, "auth.json"))}, JSON.stringify({+ auth_mode: "api-key",+ configured: apiKey.trim().length > 0,+}));+`,+ );+ const authentications: ScanAuthentication[] = [];+ const codexEnvironments: Array<Record<string, string> | undefined> = [];+ const client = new TestClient(+ {},+ {+ environment: {+ CODEX_HOME: ambientHome,+ OPENAI_API_KEY: "synthetic-openai-key",+ },+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ credentialsAvailable: false,+ }),+ resolveCodexCommand: () => ({+ command: process.execPath,+ prefixArgs: [fakeCodex],+ }),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => {+ codexEnvironments.push(options.env);+ throw new Error("scan reached");+ },+ },+ );++ await expect(+ client.run(repository, {+ onAuthentication: (authentication) => {+ authentications.push(authentication);+ },+ }),+ ).rejects.toThrow("scan reached");+ expect(+ JSON.parse(await readFile(join(codexHome, "auth.json"), "utf8")),+ ).toEqual({+ auth_mode: "api-key",+ configured: true,+ });++ await expect(+ client.run(repository, {+ auth: "chatgpt",+ onAuthentication: (authentication) => {+ authentications.push(authentication);+ },+ }),+ ).rejects.toThrow("scan reached");+ expect(await readFile(join(codexHome, "auth.json"), "utf8")).toBe(+ ambientAuthentication,+ );+ expect(authentications).toEqual([+ { method: "api_key", source: "OPENAI_API_KEY", verified: false },+ { method: "stored_credentials", verified: false },+ ]);+ expect(+ Object.keys(codexEnvironments.at(-1) ?? {}).some((name) =>+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),+ ),+ ).toBe(false);+ await client.close();+ });+test("uses a rotated environment API key on the next scan", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex f022300bf..7f1975db0 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, test } from "bun:test";import { main } from "../src/cli.js";+import { CodexSecurityError, type ScanOptions } from "../src/index.js";import {capture,dependencies,@@ -70,6 +71,245 @@ describe("CLI authentication", () => {}});+ test("explains interactive choice and how to unset every shadowing key after ChatGPT login", async () => {+ for (const [argv, environment, source, unsetCommand] of [+ [+ ["login"],+ { OPENAI_API_KEY: "sk-proj-SYNTHETIC_SECRET_123" },+ "OPENAI_API_KEY",+ "unset OPENAI_API_KEY",+ ],+ [+ ["login", "--device-auth"],+ { Codex_Api_Key: "sk-proj-SYNTHETIC_SECRET_456" },+ "CODEX_API_KEY",+ "unset Codex_Api_Key",+ ],+ [+ ["login"],+ {+ OPENAI_API_KEY: "sk-proj-SYNTHETIC_SECRET_123",+ CODEX_API_KEY: "sk-proj-SYNTHETIC_SECRET_456",+ },+ "OPENAI_API_KEY",+ "unset OPENAI_API_KEY CODEX_API_KEY",+ ],+ ] as const) {+ const stdout = capture();+ const stderr = capture();++ expect(+ await main(+ argv,+ stdout.stream,+ stderr.stream,+ dependencies({ environment }),+ ),+ ).toBe(0);+ expect(stderr.text()).toContain(+ "ChatGPT login succeeded. Interactive scans will ask which account to use;",+ );+ expect(stderr.text()).toContain(+ `noninteractive scans will use ${source}.`,+ );+ expect(stderr.text()).toContain("--auth chatgpt");+ expect(stderr.text()).toContain(`'${unsetCommand}'`);+ expect(stderr.text()).not.toContain("SYNTHETIC_SECRET");+ }+ });++ test("does not report a ChatGPT login warning for failed or API-key logins", async () => {+ const environment = { OPENAI_API_KEY: "synthetic-private-key" };++ for (const [argv, exitCode] of [+ [["login"], 2],+ [["login", "--with-api-key"], 0],+ [["login", "--with-access-token"], 0],+ ] as const) {+ const stderr = capture();++ expect(+ await main(+ argv,+ capture().stream,+ stderr.stream,+ dependencies({ environment, onCodex: () => exitCode }),+ ),+ ).toBe(exitCode);+ expect(stderr.text()).not.toContain("ChatGPT login succeeded");+ expect(stderr.text()).not.toContain("synthetic-private-key");+ }+ });++ test("forwards explicit and automatic scan authentication selection", async () => {+ for (const [argv, expected] of [+ [["scan", "--auth", "chatgpt"], "chatgpt"],+ [["scan", "--auth", "api-key"], "api-key"],+ [["scan", "--auth", "auto"], "auto"],+ [["scan"], "auto"],+ ] as const) {+ let selected: ScanOptions["auth"];+ const stderr = capture();++ expect(+ await main(+ argv,+ capture().stream,+ stderr.stream,+ dependencies({+ environment: { OPENAI_API_KEY: "synthetic-private-key" },+ onTurn: (_repository, options) => {+ selected = (options as ScanOptions).auth;+ },+ }),+ ),+ ).toBe(0);+ expect(selected).toBe(expected);+ expect(stderr.text()).not.toContain("synthetic-private-key");+ }+ });++ test("offers the existing interactive prompt when both sign-ins are available", async () => {+ for (const selection of ["chatgpt", "api-key"] as const) {+ const stderr = capture(true);+ let selected: ScanOptions["auth"];+ let question = "";+ let choices: readonly { label: string; value: string }[] = [];+ const deps = dependencies({+ environment: { OPENAI_API_KEY: "sk-proj-SYNTHETIC_SECRET_123" },+ onTurn: (_repository, options) => {+ selected = (options as ScanOptions).auth;+ },+ });+ deps.hasStoredChatGPTSignIn = async () => true;+ deps.scanAuthenticationPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ question = message;+ choices = options;+ return options.find((option) => option.value === selection)!.value;+ },+ };++ expect(await main(["scan"], capture().stream, stderr.stream, deps)).toBe(+ 0,+ );+ expect(selected).toBe(selection);+ expect(question).toBe("How would you like to authenticate this scan?");+ expect(choices).toEqual([+ { label: "ChatGPT subscription", value: "chatgpt" },+ { label: "API key from OPENAI_API_KEY", value: "api-key" },+ ]);+ expect(stderr.text()).toContain(+ "Both a ChatGPT sign-in and an API key from OPENAI_API_KEY are available.",+ );+ expect(stderr.text()).not.toContain("SYNTHETIC_SECRET");+ }+ });++ test("never prompts during automation, explicit selection, or unavailable credentials", async () => {+ for (const scenario of [+ { argv: ["scan", "--json"], terminal: true, stored: true, key: true },+ {+ argv: ["scan", "--format", "jsonl"],+ terminal: true,+ stored: true,+ key: true,+ },+ {+ argv: ["scan", "--dry-run"],+ terminal: true,+ stored: true,+ key: true,+ },+ {+ argv: ["scan", "--auth", "chatgpt"],+ terminal: true,+ stored: true,+ key: true,+ },+ {+ argv: ["scan", "--auth", "api-key"],+ terminal: true,+ stored: true,+ key: true,+ },+ { argv: ["scan"], terminal: false, stored: true, key: true },+ { argv: ["scan"], terminal: true, stored: false, key: true },+ { argv: ["scan"], terminal: true, stored: true, key: false },+ {+ argv: ["scan"],+ terminal: true,+ stored: true,+ key: true,+ inputInteractive: false,+ },+ ]) {+ const stderr = capture(scenario.terminal);+ let selected: ScanOptions["auth"];+ let prompts = 0;+ const deps = dependencies({+ environment: scenario.key+ ? { OPENAI_API_KEY: "synthetic-private-key" }+ : {},+ onTurn: (_repository, options) => {+ selected = (options as ScanOptions).auth;+ },+ });+ deps.hasStoredChatGPTSignIn = async () => scenario.stored;+ deps.scanAuthenticationPrompt = {+ isInteractive: () => scenario.inputInteractive !== false,+ select: async <Value extends string>(+ _message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ prompts += 1;+ return options[0]!.value;+ },+ };++ expect(+ await main(scenario.argv, capture().stream, stderr.stream, deps),+ ).toBe(0);+ expect(prompts).toBe(0);+ if (!scenario.argv.includes("--dry-run")) {+ expect(selected).toBe(+ scenario.argv.includes("chatgpt")+ ? "chatgpt"+ : scenario.argv.includes("api-key")+ ? "api-key"+ : "auto",+ );+ }+ expect(stderr.text()).not.toContain("synthetic-private-key");+ }+ });++ test("rejects explicit API-key authentication before initializing a scan when no key is set", async () => {+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => {+ throw new Error("must not initialize Codex Security");+ };++ expect(+ await main(+ ["scan", "--auth", "api-key"],+ capture().stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY.",+ );+ expect(stderr.text()).toContain("--auth chatgpt");+ expect(stderr.text()).not.toContain("must not initialize");+ });+test("keeps stored-login status unchanged when no environment key is set", async () => {const stdout = capture();const stderr = capture();@@ -230,12 +470,68 @@ describe("CLI authentication", () => {"Authentication: API key from OPENAI_API_KEY.",);expect(stderr.text()).toContain(- process.platform === "win32"- ? "unset OPENAI_API_KEY and CODEX_API_KEY, then retry the scan"- : "env -u OPENAI_API_KEY -u CODEX_API_KEY codex-security scan ...",+ "To use your ChatGPT sign-in, retry with --auth chatgpt.",);});+ test("prints the ChatGPT recovery hint on noninteractive scan output", async () => {+ const stdout = capture();+ const stderr = capture(false);+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onAuthentication?.({+ method: "api_key",+ source: "OPENAI_API_KEY",+ verified: false,+ });+ 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("API key from OPENAI_API_KEY");+ expect(stderr.text()).toContain("retry with --auth chatgpt");+ });++ test("identifies the rejected API-key source without exposing its value", async () => {+ for (const [environment, source, message] of [+ [+ { OPENAI_API_KEY: "sk-proj-SYNTHETIC_SECRET_123" },+ "OPENAI_API_KEY",+ "401 invalid API key for org-private",+ ],+ [+ { Codex_Api_Key: "sk-proj-SYNTHETIC_SECRET_456" },+ "CODEX_API_KEY",+ "403 model access denied for org-private",+ ],+ ] as const) {+ const stderr = capture(false);+ const deps = dependencies({ environment });+ deps.createSecurity = () => ({+ run: async () => {+ throw new CodexSecurityError(message);+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(await main(["scan"], capture().stream, stderr.stream, deps)).toBe(+ 2,+ );+ expect(stderr.text()).toContain(source);+ expect(stderr.text()).toContain("--auth chatgpt");+ expect(stderr.text()).not.toContain("SYNTHETIC_SECRET");+ expect(stderr.text()).not.toContain("org-private");+ }+ });+test("reports stored and secondary-key scan authentication on stderr", async () => {for (const [authentication, expected] of [[diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 2235d9bad..81d243d8f 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -1532,6 +1532,33 @@ describe("CLI", () => {}});+ test("reports database connection failures without claiming the model network failed", async () => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async () => {+ throw new CodexSecurityError(+ [+ "Could not save the Codex Security scan: Traceback (most recent call last):",+ " with closing(connect()) as connection:",+ "sqlite3.OperationalError: unable to open database file",+ "token=sk-proj-SYNTHETIC_DATABASE_SECRET_123",+ ].join("\n"),+ );+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(await main(["scan"], stdout.stream, stderr.stream, deps)).toBe(2);+ expect(stderr.text()).toContain("Could not save the Codex Security scan");+ expect(stderr.text()).toContain("unable to open database file");+ expect(stderr.text()).not.toContain("model service could not be reached");+ expect(stderr.text()).not.toContain("Check your network connection");+ expect(stderr.text()).not.toContain("SYNTHETIC_DATABASE_SECRET");+ });+test("renders scan output with the Incur default format", async () => {const stdout = capture();const stderr = capture();diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 4b6e3860d..42e072732 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -882,6 +882,47 @@ describe("runtime directories and plugin Python boundary", () => {expect(result).toEqual({ ok: true });});+ test("reports an unwritable SQLite state directory without a Python traceback", async () => {+ const root = await temporaryDirectory();+ const pluginRoot = join(root, "plugin");+ const stateDirectory = join(root, "persistent-state");+ await mkdir(join(pluginRoot, "scripts"), { recursive: true });+ await writeFile(+ join(pluginRoot, "scripts", "workbench_db.py"),+ [+ "import sqlite3",+ "def connect():",+ " raise sqlite3.OperationalError('unable to open database file')",+ "connect()",+ ].join("\n"),+ );+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();++ let failure: unknown;+ try {+ await runWorkbench(+ {+ python: python!,+ pluginRoot,+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },+ failureMessage: "Could not save the Codex Security scan",+ },+ ["register-cli-scan"],+ );+ } catch (error) {+ failure = error;+ }++ expect(failure).toBeInstanceOf(Error);+ const message = (failure as Error).message;+ expect(message).toContain("Could not save the Codex Security scan");+ expect(message).toContain(join(stateDirectory, "workbench.sqlite3"));+ expect(message).toContain("SQLite journal files are writable");+ expect(message).toContain("CODEX_SECURITY_STATE_DIR");+ expect(message).not.toContain("Traceback");+ });+testPosix("rejects private output directories owned by another user", () => {expect(() =>requirePrivateOutputDirectory(