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
feat: add OpenRouter and Fireworks inference providers (#245)
ianw-oai15b018bd10d9
diff --git a/README.md b/README.mdindex 7d2dcb3f9..b6ea1de14 100644--- a/README.md+++ b/README.md@@ -23,6 +23,16 @@ For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY` instead of signing in.Environment API keys are passed directly to the current scan and are neverstored in Codex's credential home or system keyring.+To use another inference provider, set its API key and select a model:++```bash+export OPENROUTER_API_KEY="<your-openrouter-api-key>"+npx @openai/codex-security scan . --provider openrouter --model anthropic/claude-sonnet-4.5++export FIREWORKS_API_KEY="<your-fireworks-api-key>"+npx @openai/codex-security scan . --provider fireworks --model accounts/fireworks/models/qwen3-235b-a22b+```+Local sign-in honors Codex's configured credential backend, including a systemkeyring required by a managed device. Codex Security keeps login and scancredentials in the same private, persistent state directory.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex abbf9f6d5..6177b7544 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -120,6 +120,16 @@ To pass a Codex access token explicitly, use`login --with-access-token` and provide the token on stdin. An access tokenenvironment variable is not automatically used as a scan API key.+To use another inference provider, set its API key and select its provider:++```bash+export OPENROUTER_API_KEY="<your-openrouter-api-key>"+npx @openai/codex-security scan . --provider openrouter --model anthropic/claude-sonnet-4.5++export FIREWORKS_API_KEY="<your-fireworks-api-key>"+npx @openai/codex-security scan . --provider fireworks --model accounts/fireworks/models/qwen3-235b-a22b+```+On Windows, set the API key in PowerShell:```powershell@@ -402,6 +412,12 @@ Variables such as `CODEX_SECURITY_SCAN_ID`, `CODEX_SECURITY_SCAN_DIR`,`CODEX_SECURITY_TARGET_PATHS_FILE` are generated by an active scan. They areinternal runtime data, not supported user configuration.+Use `--provider openrouter` to send inference through OpenRouter. Set+`OPENROUTER_API_KEY` and specify a supported model with `--model`.++Use `--provider fireworks` to send inference through Fireworks AI. Set+`FIREWORKS_API_KEY` and specify a supported model with `--model`.+Scan progress identifies the requested paths and reports actual ranking,file-review, validation, and attack-path phases as they become available.Completion summarizes findings, severity, coverage, elapsed time, availablediff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 4d0f01bf4..f4033d685 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -26,6 +26,8 @@ import {type AccountStatus,} from "./auth.js";import {+ EXTERNAL_CODEX_PROVIDERS,+ isExternalModelProvider,mergedCodexConfig,scanModelConfiguration,type CodexSecurityConfig,@@ -171,7 +173,11 @@ export type ScanAuthMode = "auto" | "chatgpt" | "api-key";export type ScanAuthentication =| {method: "api_key";- source: "OPENAI_API_KEY" | "CODEX_API_KEY";+ source:+ | "OPENAI_API_KEY"+ | "CODEX_API_KEY"+ | "OPENROUTER_API_KEY"+ | "FIREWORKS_API_KEY";verified: false;}| {@@ -203,6 +209,7 @@ export interface ScanPreflight extends DeepScanOptions {archiveDir?: string;authentication: ScanAuthentication;model: string;+ modelProvider?: string;reasoningEffort: string;maxCostUsd?: number;}@@ -317,8 +324,12 @@ export class CodexSecurity {authentication: scanAuthentication(this.#dependencies.environment,options.auth,+ configuration["model_provider"],),...model,+ ...(typeof configuration["model_provider"] === "string"+ ? { modelProvider: configuration["model_provider"] }+ : {}),...(options.maxCostUsd === undefined? {}: { maxCostUsd: options.maxCostUsd }),@@ -389,13 +400,29 @@ export class CodexSecurity {}checkOpen();+ const requestedConfig = await mergedCodexConfig(this.config);+ const modelProvider = requestedConfig["model_provider"];+ const externalProvider = isExternalModelProvider(modelProvider)+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider]+ : null;const authentication = scanAuthentication(this.#dependencies.environment,options.auth,+ modelProvider,);+ const apiKey =+ authentication.method === "api_key"+ ? environmentApiKey(this.#dependencies.environment, modelProvider)+ : null;+ if (externalProvider !== null && apiKey === null) {+ throw new AuthenticationRequiredError(+ `Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`,+ );+ }const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment,options.auth,+ modelProvider,);if (authentication.method === "stored_credentials" &&@@ -418,6 +445,7 @@ export class CodexSecurity {(path) =>requireOutputOutsideRepository(protectedRoot, path, "runtime"),options.auth,+ modelProvider,);if (runtime === previousRuntime &&@@ -426,8 +454,7 @@ export class CodexSecurity {) {await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal);}- const effectiveConfig =- runtime.effectiveConfig ?? (await mergedCodexConfig(this.config));+ const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;if (runtime.configPath !== undefined) {await writeCodexConfig(runtime.configPath,@@ -468,11 +495,7 @@ export class CodexSecurity {? "stored_credentials": null;}- const apiKey =- authentication.method === "api_key"- ? environmentApiKey(this.#dependencies.environment)- : null;- if (apiKey !== null) {+ if (externalProvider === null && apiKey !== null) {this.#runtimeCredentialSource = "api_key";}if (@@ -620,7 +643,11 @@ export class CodexSecurity {python,pluginRoot: runtime.plugin.pluginRoot,environment: {- ...selectedScanEnvironment(runtime.environment, options.auth),+ ...selectedScanEnvironment(+ runtime.environment,+ options.auth,+ modelProvider,+ ),CODEX_SECURITY_STATE_DIR: stateDirectory,},signal,@@ -775,14 +802,21 @@ export class CodexSecurity {...pluginExecutionEnvironment(python,withoutCodexHome(- selectedScanEnvironment(runtime.environment, options.auth),+ selectedScanEnvironment(+ runtime.environment,+ options.auth,+ modelProvider,+ ),),),+ ...(externalProvider === null+ ? {}+ : { [externalProvider.env_key]: apiKey! }),CODEX_HOME: runtime.codexHome,...runtimePaths,};const codex = this.#dependencies.createCodex({- ...(apiKey === null ? {} : { apiKey }),+ ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt"),),@@ -1143,12 +1177,13 @@ export class CodexSecurity {temporaryRoot?: string,validateLocation?: (path: string) => void,auth: ScanAuthMode = "auto",+ modelProvider?: unknown,): Promise<PreparedRuntime> {this.#requireOpen();if (this.#runtime !== null) {const usePersistentCredentials =- scanAuthentication(this.#dependencies.environment, auth).method ===- "stored_credentials";+ scanAuthentication(this.#dependencies.environment, auth, modelProvider)+ .method === "stored_credentials";if (this.#dependencies.prepareRuntime !== undefined ||this.#runtime.persistentCredentialHome === undefined ||@@ -1168,6 +1203,7 @@ export class CodexSecurity {temporaryRoot,validateLocation,auth,+ modelProvider,);this.#runtimePromise = runtimePromise;void runtimePromise.catch(() => {@@ -1277,6 +1313,7 @@ export class CodexSecurity {temporaryRoot?: string,validateLocation?: (path: string) => void,auth: ScanAuthMode = "auto",+ modelProvider?: unknown,): Promise<PreparedRuntime> {if (this.#dependencies.prepareRuntime !== undefined) {return await this.#dependencies.prepareRuntime(this.config, signal);@@ -1284,10 +1321,11 @@ export class CodexSecurity {const processEnvironment = selectedScanEnvironment(this.#dependencies.environment,auth,+ modelProvider,);const persistentCredentialHome =- scanAuthentication(this.#dependencies.environment, auth).method ===- "stored_credentials";+ scanAuthentication(this.#dependencies.environment, auth, modelProvider)+ .method === "stored_credentials";const codexHome = persistentCredentialHome? await prepareCodexSecurityCredentialHome(processEnvironment,@@ -1332,11 +1370,13 @@ export class CodexSecurity {environment: withoutCodexHome(processEnvironment),signal,});- const credentialsAvailable = await initialCredentialsAvailable(- processEnvironment,- ambientHome,- codexHome,- );+ const credentialsAvailable = isExternalModelProvider(modelProvider)+ ? false+ : await initialCredentialsAvailable(+ processEnvironment,+ ambientHome,+ codexHome,+ );return {codexHome,persistentCredentialHome,@@ -1828,12 +1868,17 @@ async function collectResult(export function scanAuthentication(environment: ProcessEnvironment,auth: ScanAuthMode = "auto",+ modelProvider?: unknown,): ScanAuthentication {- if (auth === "chatgpt") {+ if (auth === "chatgpt" && !isExternalModelProvider(modelProvider)) {return { method: "stored_credentials", verified: false };}- const key = environmentApiKeyEntry(environment);- if (auth === "api-key" && key === null) {+ const key = environmentApiKeyEntry(environment, modelProvider);+ if (+ auth === "api-key" &&+ key === null &&+ !isExternalModelProvider(modelProvider)+ ) {throw new AuthenticationRequiredError("API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY. " +"Set a valid API key or use '--auth chatgpt'.",@@ -1847,14 +1892,22 @@ export function scanAuthentication(function selectedScanEnvironment(environment: ProcessEnvironment,auth: ScanAuthMode = "auto",+ modelProvider?: unknown,): ProcessEnvironment {- if (auth !== "chatgpt") return environment;+ const selectedProviderKey = isExternalModelProvider(modelProvider)+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key+ : null;+ if (auth !== "chatgpt" && selectedProviderKey === null) return environment;return Object.fromEntries(- Object.entries(environment).filter(- ([name]) =>- name.toUpperCase() !== "OPENAI_API_KEY" &&- name.toUpperCase() !== "CODEX_API_KEY",- ),+ Object.entries(environment).filter(([name]) => {+ const key = name.toUpperCase();+ if (key === "OPENAI_API_KEY" || key === "CODEX_API_KEY") return false;+ if (selectedProviderKey === null) return true;+ if (key === "OPENROUTER_API_KEY" || key === "FIREWORKS_API_KEY") {+ return key === selectedProviderKey;+ }+ return true;+ }),);}@@ -1872,21 +1925,30 @@ function notifyObserver<Arguments extends unknown[]>(.catch(() => {});}-function environmentApiKey(environment: ProcessEnvironment): string | null {- return environmentApiKeyEntry(environment)?.value ?? null;+function environmentApiKey(+ environment: ProcessEnvironment,+ modelProvider?: unknown,+): string | null {+ return environmentApiKeyEntry(environment, modelProvider)?.value ?? null;}-function environmentApiKeyEntry(environment: ProcessEnvironment): {- source: "OPENAI_API_KEY" | "CODEX_API_KEY";+function environmentApiKeyEntry(+ environment: ProcessEnvironment,+ modelProvider?: unknown,+): {+ source:+ | "OPENAI_API_KEY"+ | "CODEX_API_KEY"+ | "OPENROUTER_API_KEY"+ | "FIREWORKS_API_KEY";value: string;} | null {- for (const requested of ["OPENAI_API_KEY", "CODEX_API_KEY"] as const) {- const canonical = environment[requested]?.trim();- if (canonical) return { source: requested, value: canonical };- for (const [name, value] of Object.entries(environment)) {- if (name.toUpperCase() === requested && value?.trim())- return { source: requested, value: value.trim() };- }+ const keys = isExternalModelProvider(modelProvider)+ ? [EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]+ : (["OPENAI_API_KEY", "CODEX_API_KEY"] as const);+ for (const requested of keys) {+ const value = environmentValue(environment, requested)?.trim();+ if (value) return { source: requested, value };}return null;}@@ -2107,6 +2169,12 @@ export function scanPreflightCodexConfig(};const result = executionConfig(config);+ const modelProvider = result["model_provider"];+ if (isExternalModelProvider(modelProvider)) {+ result["model_providers"] = {+ [modelProvider]: { ...EXTERNAL_CODEX_PROVIDERS[modelProvider] },+ };+ }const selectedProfile = safeProfileName(config["profile"])? config["profile"]: undefined;diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 2747672f4..1311875d1 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -47,9 +47,12 @@ import {} from "./bulk-scan-discovery.js";import {DEFAULT_CODEX_CONFIG,+ EXTERNAL_CODEX_PROVIDERS,+ isExternalModelProvider,mergedCodexConfig,scanModelConfiguration,type CodexSecurityConfig,+ type ExternalModelProvider,type JsonObject,type JsonValue,} from "./config.js";@@ -168,6 +171,7 @@ const VALUE_OPTIONS = new Set(["--mode","--model","--effort",+ "--provider","--output-dir","--plugin-path","--python",@@ -189,6 +193,10 @@ const VALUE_OPTIONS = new Set(["--scan-root","--reason",]);+const PROVIDER_OPTION = z+ .enum(["openai", "openrouter", "fireworks"])+ .default("openai")+ .describe("Inference provider for scans.");function optionValue(flag: string) {return z.string().min(1, `${flag} must not be empty.`);@@ -245,6 +253,7 @@ interface ScanArguments extends DeepScanOptions {mode: ScanMode;model?: string;effort?: ModelReasoningEffort;+ provider?: "openai" | ExternalModelProvider;outputDir?: string;archiveExisting: boolean;pluginPath?: string;@@ -1049,6 +1058,7 @@ export async function main(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`,),effort: effortOption(),+ provider: PROVIDER_OPTION,outputDir: optionValue("--output-dir").optional().describe(@@ -1162,6 +1172,7 @@ export async function main(maxDiscoveryRuns: options.maxDiscoveryRuns,model: options.model,effort: options.effort,+ provider: options.provider,outputDir: options.outputDir,archiveExisting: options.archiveExisting,pluginPath: options.pluginPath,@@ -1308,6 +1319,7 @@ export async function main(`OpenAI model for each repository (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`,),effort: effortOption(),+ provider: PROVIDER_OPTION,maxAttempts: z.number().int()@@ -1361,6 +1373,7 @@ export async function main(if (argument === "--model" ||argument === "--effort" ||+ argument === "--provider" ||argument === "--codex" ||argument === "--knowledge-base") {@@ -1368,6 +1381,7 @@ export async function main(} else if (argument.startsWith("--model=") ||argument.startsWith("--effort=") ||+ argument.startsWith("--provider=") ||argument.startsWith("--codex=") ||argument.startsWith("--knowledge-base=")) {@@ -1378,7 +1392,7 @@ export async function main(}if (argv[0] !== "bulk-scan" || optionIndex !== argv.length) {throw new Error(- "Run 'codex-security bulk-scan [--model MODEL] [--effort EFFORT] [--codex KEY=VALUE] [--knowledge-base PATH]' to discover repositories, or provide a CSV and --output-dir.",+ "Run 'codex-security bulk-scan [--provider PROVIDER] [--model MODEL] [--effort EFFORT] [--codex KEY=VALUE] [--knowledge-base PATH]' to discover repositories, or provide a CSV and --output-dir.",);}const wizard = await runBulkScanWizard(@@ -1418,6 +1432,7 @@ export async function main(options.codex,options.model,options.effort,+ options.provider,),},createSecurity: dependencies.createSecurity,@@ -2689,6 +2704,7 @@ async function runScan(arguments_.codex,arguments_.model,arguments_.effort,+ arguments_.provider,),};const selectedProfileName = config.codexOverrides?.["profile"];@@ -2698,8 +2714,14 @@ async function runScan(...config.codexOverrides,}));let auth = arguments_.auth;- selectedAuthentication = scanAuthentication(dependencies.environment, auth);+ const provider = config.codexOverrides?.["model_provider"];+ selectedAuthentication = scanAuthentication(+ dependencies.environment,+ auth,+ provider,+ );if (+ !isExternalModelProvider(provider) &&(auth === undefined || auth === "auto") &&!arguments_.dryRun &&interactive &&@@ -2731,6 +2753,7 @@ async function runScan(selectedAuthentication = scanAuthentication(dependencies.environment,auth,+ provider,);}}@@ -3337,10 +3360,17 @@ export function parseCodexOverrides(values: readonly string[],model?: string,effort?: ModelReasoningEffort,+ provider?: "openai" | ExternalModelProvider,): JsonObject {const result = Object.create(null) as JsonObject;if (model !== undefined) result["model"] = model;if (effort !== undefined) result["model_reasoning_effort"] = effort;+ if (isExternalModelProvider(provider)) {+ result["model_provider"] = provider;+ result["model_providers"] = {+ [provider]: { ...EXTERNAL_CODEX_PROVIDERS[provider] },+ };+ }for (const value of values) {const separator = value.indexOf("=");const key = separator < 0 ? "" : value.slice(0, separator);@@ -3396,10 +3426,20 @@ export function parseCodexOverrides("--effort conflicts with --codex model_reasoning_effort",);}+ if (isExternalModelProvider(provider) && key === "model_provider") {+ throw new CodexSecurityError(+ "--provider conflicts with --codex model_provider",+ );+ }throw new CodexSecurityError("Duplicate --codex key");}cursor[final] = parsed;}+ if (isExternalModelProvider(provider) && !("model" in result)) {+ throw new CodexSecurityError(+ `--model is required when using --provider ${provider}`,+ );+ }return result;}diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.tsindex 2527ce207..8ce7033d3 100644--- a/sdk/typescript/src/config.ts+++ b/sdk/typescript/src/config.ts@@ -21,6 +21,36 @@ export interface ScanModelConfiguration {reasoningEffort: string;}+export const OPENROUTER_CODEX_PROVIDER = {+ name: "OpenRouter",+ base_url: "https://openrouter.ai/api/v1",+ env_key: "OPENROUTER_API_KEY",+ wire_api: "responses",+} as const satisfies JsonObject;++export const FIREWORKS_CODEX_PROVIDER = {+ name: "Fireworks AI",+ base_url: "https://api.fireworks.ai/inference/v1",+ env_key: "FIREWORKS_API_KEY",+ wire_api: "responses",+} as const satisfies JsonObject;++export const EXTERNAL_CODEX_PROVIDERS = {+ openrouter: OPENROUTER_CODEX_PROVIDER,+ fireworks: FIREWORKS_CODEX_PROVIDER,+} as const;++export type ExternalModelProvider = keyof typeof EXTERNAL_CODEX_PROVIDERS;++export function isExternalModelProvider(+ provider: unknown,+): provider is ExternalModelProvider {+ return (+ typeof provider === "string" &&+ Object.hasOwn(EXTERNAL_CODEX_PROVIDERS, provider)+ );+}+export const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = {cli_auth_credentials_store: "auto",model: "gpt-5.6-sol",diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 4a09a894b..16283140b 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -609,7 +609,9 @@ export async function runWorkbench(Object.entries(options.environment).filter(([name]) =>name.toUpperCase() !== "OPENAI_API_KEY" &&- name.toUpperCase() !== "CODEX_API_KEY",+ name.toUpperCase() !== "CODEX_API_KEY" &&+ name.toUpperCase() !== "OPENROUTER_API_KEY" &&+ name.toUpperCase() !== "FIREWORKS_API_KEY",),),encoding: "utf8",diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 1e0c947c0..4b7f68824 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -39,7 +39,12 @@ import {scanPreflightCodexConfig,scanRuntimeCodexConfig,} from "../src/api.js";-import { writeCodexConfig, type JsonObject } from "../src/config.js";+import {+ FIREWORKS_CODEX_PROVIDER,+ OPENROUTER_CODEX_PROVIDER,+ writeCodexConfig,+ type JsonObject,+} from "../src/config.js";import { estimateScanCost, type ScanCost } from "../src/cost.js";import {runWorkbench,@@ -57,6 +62,22 @@ const REPOSITORY_ROOT = fileURLToPath(new URL("../../..", import.meta.url));const EXAMPLE = join(PLUGIN_ROOT, "examples", "completed-scan");const temporaryDirectories: string[] = [];const TEST_SNAPSHOT_DIGEST = `codex-security-snapshot/v1:sha256:${"a".repeat(64)}`;+const EXTERNAL_PROVIDER_CASES = [+ [+ "OpenRouter",+ "openrouter",+ "OPENROUTER_API_KEY",+ "anthropic/claude-sonnet-4.5",+ OPENROUTER_CODEX_PROVIDER,+ ],+ [+ "Fireworks AI",+ "fireworks",+ "FIREWORKS_API_KEY",+ "accounts/fireworks/models/qwen3-235b-a22b",+ FIREWORKS_CODEX_PROVIDER,+ ],+] as const;const TestClientBase = CodexSecurity as unknown as new (config: Record<string, unknown>,dependencies: Record<string, unknown>,@@ -1049,6 +1070,155 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test.each(EXTERNAL_PROVIDER_CASES)(+ "keeps the %s provider in sanitized scan configuration",+ (_name, provider, _apiKey, model, providerConfig) => {+ expect(+ scanPreflightCodexConfig({+ model,+ model_provider: provider,+ model_providers: {+ [provider]: providerConfig,+ private: { api_key: "synthetic-secret" },+ },+ }),+ ).toEqual({+ model,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ });+ },+ );++ test.each(EXTERNAL_PROVIDER_CASES)(+ "requires the %s API key instead of accepting another provider's credentials",+ async (name, provider, apiKey, model, providerConfig) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);+ let runtimeStarted = false;+ const client = new TestClient(+ {+ codexOverrides: {+ model,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ },+ },+ {+ environment: {+ OPENAI_API_KEY: "synthetic-openai-key",+ [provider === "openrouter"+ ? "FIREWORKS_API_KEY"+ : "OPENROUTER_API_KEY"]: "synthetic-competing-provider-key",+ },+ prepareRuntime: async () => {+ runtimeStarted = true;+ throw new Error("runtime must not start");+ },+ },+ );++ await expect(client.run(repository)).rejects.toThrow(+ `Set ${apiKey} to run a scan through ${name}.`,+ );+ expect(runtimeStarted).toBe(false);+ await client.close();+ },+ );++ test.each(EXTERNAL_PROVIDER_CASES)(+ "runs %s scans without signing in to OpenAI",+ async (_name, provider, apiKey, model, providerConfig) => {+ 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 authentication: ScanAuthentication | undefined;+ const competingApiKey =+ provider === "openrouter" ? "FIREWORKS_API_KEY" : "OPENROUTER_API_KEY";+ const environment = {+ OPENAI_API_KEY: "synthetic-openai-key",+ [competingApiKey]: "synthetic-competing-provider-key",+ [apiKey]: `synthetic-${provider}-key`,+ };+ const client = new TestClient(+ {+ codexOverrides: {+ model,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ },+ },+ {+ environment,+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ environment,+ credentialsAvailable: false,+ }),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ resolveCodexCommand: () => {+ throw new Error(`${provider} must not sign in to OpenAI`);+ },+ createCodex: (options: CodexOptions) => {+ codexOptions = options;+ return {+ startThread: () => ({+ id: null,+ async runStreamed() {+ await copyCompletedScan(root);+ return { events: completedEvents() };+ },+ }),+ };+ },+ },+ );++ const preflight = await client.preflight(repository);+ expect(preflight).toMatchObject({+ model,+ modelProvider: provider,+ authentication: {+ method: "api_key",+ source: apiKey,+ verified: false,+ },+ });+ expect(JSON.stringify(preflight)).not.toContain("synthetic-");+ await expect(+ client.run(repository, {+ onAuthentication: (selected) => {+ authentication = selected;+ },+ }),+ ).resolves.toMatchObject({ threadId: "thread-1" });+ expect(authentication).toEqual({+ method: "api_key",+ source: apiKey,+ verified: false,+ });+ expect((codexOptions as CodexOptions | null)?.env).toMatchObject({+ [apiKey]: `synthetic-${provider}-key`,+ });+ expect((codexOptions as CodexOptions | null)?.env).not.toHaveProperty(+ "OPENAI_API_KEY",+ );+ expect((codexOptions as CodexOptions | null)?.env).not.toHaveProperty(+ competingApiKey,+ );+ expect((codexOptions as CodexOptions | null)?.apiKey).toBeUndefined();+ await client.close();+ },+ );+test("isolates authentication observer failures from scan startup", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex b1eb88419..0d6ca9fb6 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -36,7 +36,12 @@ import {VERSION,} from "../src/index.js";import { main, parseCodexOverrides, Progress } from "../src/cli.js";-import { DEFAULT_CODEX_CONFIG, scanModelConfiguration } from "../src/config.js";+import {+ DEFAULT_CODEX_CONFIG,+ FIREWORKS_CODEX_PROVIDER,+ OPENROUTER_CODEX_PROVIDER,+ scanModelConfiguration,+} from "../src/config.js";import {FakeSignals,REDACTED_CREDENTIALS,@@ -116,6 +121,7 @@ describe("CLI", () => {model: { type: "string" },verbose: { type: "boolean" },effort: { enum: ["minimal", "low", "medium", "high", "xhigh"] },+ provider: { enum: ["openai", "openrouter", "fireworks"] },failOnSeverity: { enum: ["critical", "high", "medium", "low"] },},},@@ -740,6 +746,81 @@ describe("CLI", () => {}});+ test.each([+ [+ "OpenRouter",+ "openrouter",+ "anthropic/claude-sonnet-4.5",+ OPENROUTER_CODEX_PROVIDER,+ ],+ [+ "Fireworks AI",+ "fireworks",+ "accounts/fireworks/models/qwen3-235b-a22b",+ FIREWORKS_CODEX_PROVIDER,+ ],+ ] as const)(+ "routes bulk scans through %s",+ async (_name, provider, model, providerConfig) => {+ const root = await mkdtemp(join(tmpdir(), `codex-security-${provider}-`));+ try {+ await multiscanInventory(root);+ let config: CodexSecurityConfig | undefined;+ const missingModelError = capture();+ expect(+ await main(+ [+ "bulk-scan",+ "repositories.csv",+ "--output-dir",+ "results",+ "--provider",+ provider,+ ],+ capture().stream,+ missingModelError.stream,+ dependencies({+ currentDirectory: root,+ onConfig: (value) => (config = value),+ }),+ ),+ ).toBe(2);+ expect(missingModelError.text()).toContain(+ `--model is required when using --provider ${provider}`,+ );+ expect(config).toBeUndefined();+ expect(+ await main(+ [+ "bulk-scan",+ "repositories.csv",+ "--output-dir",+ "results",+ "--provider",+ provider,+ "--model",+ model,+ "--json",+ ],+ capture().stream,+ capture().stream,+ dependencies({+ currentDirectory: root,+ onConfig: (value) => (config = value),+ }),+ ),+ ).toBe(0);+ expect(config?.codexOverrides).toMatchObject({+ model,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ },+ );+test("preserves the bulk-scan failure summary and redacts progress errors", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));try {@@ -803,6 +884,15 @@ describe("CLI", () => {"--knowledge-base","/shared/threat-models",],+ ["bulk-scan", "--provider", "openrouter"],+ ["bulk-scan", "--provider=openrouter", "--model", "openai/gpt-5.4"],+ ["bulk-scan", "--provider", "fireworks"],+ [+ "bulk-scan",+ "--provider=fireworks",+ "--model",+ "accounts/fireworks/models/qwen3-235b-a22b",+ ],] as const) {const stdout = capture();const stderr = capture();@@ -1593,6 +1683,7 @@ describe("CLI", () => {expect(help.text()).toContain("--stop-after-no-new <number>");expect(help.text()).toContain("--max-discovery-runs <number>");expect(help.text()).toContain("--model <string>");+ expect(help.text()).toContain("--provider <openai|openrouter|fireworks>");expect(help.text()).toContain(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`,);@@ -1611,7 +1702,6 @@ describe("CLI", () => {expect(help.text()).toContain("codex-security scan . --model gpt-5.6-terra --effort high",);- expect(help.text()).not.toContain("--provider");expect(help.text()).not.toContain("openai:gpt");expect(help.text()).not.toContain("codex-security scan . --path src,tests");expect(help.text()).toContain("--format <toon|json|yaml|md|jsonl>");@@ -1659,7 +1749,7 @@ describe("CLI", () => {);expect(help.text()).not.toContain("--outputDir");expect(help.text()).not.toContain("--maxAttempts");- expect(help.text()).not.toContain("--provider");+ expect(help.text()).toContain("--provider <openai|openrouter|fireworks>");expect(stderr.text()).toBe("");});@@ -1705,6 +1795,49 @@ describe("CLI", () => {}});+ test.each([+ [+ "OpenRouter",+ "openrouter",+ "anthropic/claude-sonnet-4.5",+ "google/gemini-2.5-pro",+ OPENROUTER_CODEX_PROVIDER,+ ],+ [+ "Fireworks AI",+ "fireworks",+ "accounts/fireworks/models/gpt-oss-120b",+ "accounts/fireworks/models/llama-v3p3-70b-instruct",+ FIREWORKS_CODEX_PROVIDER,+ ],+ ] as const)(+ "routes scans through %s",+ async (_name, provider, selectedModel, codexModel, providerConfig) => {+ for (const [options, expectedModel] of [+ [[`--provider=${provider}`, "--model", selectedModel], selectedModel],+ [+ ["--provider", provider, "--codex", `model="${codexModel}"`],+ codexModel,+ ],+ ] as const) {+ let config: CodexSecurityConfig | undefined;+ expect(+ await main(+ ["scan", ".", ...options],+ capture().stream,+ capture().stream,+ dependencies({ onConfig: (value) => (config = value) }),+ ),+ ).toBe(0);+ expect(config?.codexOverrides).toEqual({+ model: expectedModel,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ });+ }+ },+ );+test("parses repeatable options and every scan target through Incur", async () => {const pathOutput = capture();let pathOptions: unknown;@@ -1820,6 +1953,19 @@ describe("CLI", () => {"high",),).toThrow("--effort conflicts with --codex model_reasoning_effort");+ for (const provider of ["openrouter", "fireworks"] as const) {+ expect(() =>+ parseCodexOverrides([], undefined, undefined, provider),+ ).toThrow(`--model is required when using --provider ${provider}`);+ expect(() =>+ parseCodexOverrides(+ ['model_provider="other"'],+ undefined,+ undefined,+ provider,+ ),+ ).toThrow("--provider conflicts with --codex model_provider");+ }});test("redacts malformed and bounded --codex overrides", () => {@@ -1893,6 +2039,14 @@ describe("CLI", () => {"--knowledge-base must not be empty",],[["scan", ".", "--model="], "--model must not be empty"],+ [+ ["scan", ".", "--provider", "openrouter"],+ "--model is required when using --provider openrouter",+ ],+ [+ ["scan", ".", "--provider", "fireworks"],+ "--model is required when using --provider fireworks",+ ],[["scan", ".", "--effort", "ultra"],"--effort must be minimal, low, medium, high, or xhigh",diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 7cb55da38..d3c2fa3f6 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -1839,6 +1839,8 @@ describe("runtime directories and plugin Python boundary", () => {"assert sys.argv[1] == 'test-command'","assert os.environ.get('OPENAI_API_KEY') is None","assert os.environ.get('CODEX_API_KEY') is None",+ "assert os.environ.get('OPENROUTER_API_KEY') is None",+ "assert os.environ.get('FIREWORKS_API_KEY') is None","print(json.dumps({'ok': True}))",].join("\n"),);@@ -1852,6 +1854,8 @@ describe("runtime directories and plugin Python boundary", () => {PATH: process.env["PATH"],OPENAI_API_KEY: "must-not-reach-python",CODEX_API_KEY: "also-must-not-reach-python",+ OPENROUTER_API_KEY: "openrouter-must-not-reach-python",+ FIREWORKS_API_KEY: "fireworks-must-not-reach-python",},},["test-command"],