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: support per-scan Cyber access programs (#1185)
mldangelo-oaic0f5a5b9400f
diff --git a/docs/project-configuration.md b/docs/project-configuration.mdindex 6433cfdda..1680c8012 100644--- a/docs/project-configuration.md+++ b/docs/project-configuration.md@@ -76,6 +76,7 @@ node sdk/typescript/bin/codex-security.mjs scan . -c docs/examples/codex-securit| ------------------------------ | ---------------------------------------------------------------------------- | ---------------------------------- || `auth` | Credential source: `auto`, `chatgpt`, or `api-key`; never a credential value | `auto` || `scan.mode` | `standard` or `deep` | `standard` |+| `scan.cyber_access_program` | Experimental OpenAI program: `standard`, `daybreak_blue`, or `daybreak_red` | Unset; preserve Codex defaults || `scan.scope` | Exactly one of `paths: [src]`, `diff: {base: HEAD}`, or `working_tree: {}` | Whole repository || `scan.knowledge_base` | Context files or directories | Empty list || `scan.instructions_file` | Additional scan instructions | Unset |@@ -97,26 +98,27 @@ project-file resolution. Project files and typed `ProjectConfigInput` objectsuse `snake_case`; SDK options keep `camelCase`, and CLI flags keep `kebab-case`.The resolver maps file keys to the existing SDK options:-| Project file | SDK option | CLI flag |-| ----------------------------------------- | ------------------------------------- | ------------------------------- |-| `auth` | `auth` | `--auth` |-| `scan.mode` | `mode` | `--mode` |-| `scan.scope.paths` | `target: ["src"]` | `--path` |-| `scan.scope.diff` | `target: DiffTarget.refs(...)` | `--diff`, `--head` |-| `scan.scope.working_tree` | `target: DiffTarget.workingTree(...)` | `--working-tree`, `--base` |-| `scan.knowledge_base` | `knowledgeBasePaths` | `--knowledge-base` |-| `scan.instructions_file` | `scanPromptFile` | `--scan-prompt-file` |-| `scan.validation_file` | `validationPromptFile` | `--validation-prompt-file` |-| `scan.deep.workers` | `workers` | `--workers` |-| `scan.deep.subagents_per_worker` | `subagents` | `--subagents` |-| `scan.deep.stop_after_no_new` | `stopAfterNoNew` | `--stop-after-no-new` |-| `scan.deep.stop_after_consecutive_errors` | `stopAfterConsecutiveErrors` | No flag |-| `scan.deep.max_discovery_runs` | `maxDiscoveryRuns` | `--max-discovery-runs` |-| `scan.deep.max_time_hours` | `maxTimeHours` | `--max-time-hours` |-| `limits.max_cost_usd_per_scan` | `maxCostUsd` | `--max-cost` |-| `policy.fail_on_severity` | `failureSeverity` | `--fail-on-severity` |-| `output.directory` | `outputDir` | `--output-dir` |-| `codex` | Constructor `codexOverrides` | `--codex`, model/provider flags |+| Project file | SDK option | CLI flag |+| ----------------------------------------- | ------------------------------------- | ---------------------------------------------------- |+| `auth` | `auth` | `--auth` |+| `scan.mode` | `mode` | `--mode` |+| `scan.cyber_access_program` | `cyberAccessProgram` | `--cyber-access-program` (`scan`, `scan-components`) |+| `scan.scope.paths` | `target: ["src"]` | `--path` |+| `scan.scope.diff` | `target: DiffTarget.refs(...)` | `--diff`, `--head` |+| `scan.scope.working_tree` | `target: DiffTarget.workingTree(...)` | `--working-tree`, `--base` |+| `scan.knowledge_base` | `knowledgeBasePaths` | `--knowledge-base` |+| `scan.instructions_file` | `scanPromptFile` | `--scan-prompt-file` |+| `scan.validation_file` | `validationPromptFile` | `--validation-prompt-file` |+| `scan.deep.workers` | `workers` | `--workers` |+| `scan.deep.subagents_per_worker` | `subagents` | `--subagents` |+| `scan.deep.stop_after_no_new` | `stopAfterNoNew` | `--stop-after-no-new` |+| `scan.deep.stop_after_consecutive_errors` | `stopAfterConsecutiveErrors` | No flag |+| `scan.deep.max_discovery_runs` | `maxDiscoveryRuns` | `--max-discovery-runs` |+| `scan.deep.max_time_hours` | `maxTimeHours` | `--max-time-hours` |+| `limits.max_cost_usd_per_scan` | `maxCostUsd` | `--max-cost` |+| `policy.fail_on_severity` | `failureSeverity` | `--fail-on-severity` |+| `output.directory` | `outputDir` | `--output-dir` |+| `codex` | Constructor `codexOverrides` | `--codex`, model/provider flags |Use an explicit file with `loadProjectConfig()`:diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex ba0e3579e..9d2177ab5 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -15,7 +15,7 @@ import {resolve,win32,} from "node:path";-import { Codex } from "@openai/codex-sdk";+import { Codex, type CyberAccessProgram } from "@openai/codex-sdk";import { parse as parseToml } from "smol-toml";import { executablePathForSpawn } from "./executable-path.js";import {@@ -52,8 +52,17 @@ export interface CodexSdkWorkerArtifactContext {pythonCommand?: string;}+interface CodexSdkWorkerRuntimeSettings {+ reasoningSummary?: string;+ cyberAccessProgram?: CyberAccessProgram;+ features?: {+ api_key_cyber_access_programs?: boolean;+ api_key_model_discovery?: boolean;+ };+}+export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {- private runtimeReasoningSummary?: Promise<string | undefined>;+ private runtimeSettings?: Promise<CodexSdkWorkerRuntimeSettings>;constructor(private readonly modelSettings: CodexSdkWorkerModelSettings = {},@@ -73,8 +82,8 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {const originalCwd = process.cwd();const childEnv = await snapshotWorkerEnvironment();// Snapshot the SDK's per-scan config once for this coordinator, including resumes.- const reasoningSummary = await (this.runtimeReasoningSummary ??=- workerReasoningSummary(childEnv));+ const runtimeSettings = await (this.runtimeSettings ??=+ workerRuntimeSettings(childEnv));const openAiApiKey = environmentVariable(childEnv,"OPENAI_API_KEY",@@ -109,9 +118,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {// Keep native credentials unless the worker has no configured account....(useOpenAiApiKey ? { apiKey: openAiApiKey } : {}),config: {- ...(reasoningSummary === undefined+ ...(runtimeSettings.reasoningSummary === undefined? {}- : { model_reasoning_summary: reasoningSummary }),+ : { model_reasoning_summary: runtimeSettings.reasoningSummary }),// The CLI can add effort levels before the pinned SDK widens ThreadOptions....(this.modelSettings.reasoningEffort? { model_reasoning_effort: this.modelSettings.reasoningEffort }@@ -122,7 +131,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {"codex-security": { command: "node", enabled: false },...this.compactArtifactServer(request),},- ...workerSubagentConfig(request.subagents),+ ...workerSubagentConfig(request.subagents, runtimeSettings.features),},// Structured SDK config cannot preserve literal filesystem keys such as// ":root" or "/repo/.env"; raw overrides keep this inline TOML intact.@@ -154,6 +163,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {try {const { events } = await thread.runStreamed(input, {signal: controller.signal,+ ...(runtimeSettings.cyberAccessProgram === undefined+ ? {}+ : { cyberAccessProgram: runtimeSettings.cyberAccessProgram }),});let threadId: string | undefined;let turnCompleted = false;@@ -282,13 +294,17 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {}}-function workerSubagentConfig(subagents: number) {+function workerSubagentConfig(+ subagents: number,+ inheritedFeatures: CodexSdkWorkerRuntimeSettings["features"],+) {return {// V1 counts children; V2 counts the root plus its children. Keeping its// feature disabled lets the model choose either runtime without rejecting// inherited agents.max_threads configuration....(subagents > 0 ? { agents: { max_threads: subagents } } : {}),features: {+ ...inheritedFeatures,multi_agent_v2: {enabled: false,max_concurrent_threads_per_session: subagents + 1,@@ -466,15 +482,15 @@ function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null;}-async function workerReasoningSummary(+async function workerRuntimeSettings(environment: Record<string, string>,-): Promise<string | undefined> {+): Promise<CodexSdkWorkerRuntimeSettings> {const configPath = environmentVariable(environment,"CODEX_SECURITY_CONFIG_PATH",process.platform,);- if (!configPath) return undefined;+ if (!configPath) return {};const config = parseToml(await fs.readFile(configPath, "utf8"));const profiles = config.profiles;const profile =@@ -485,7 +501,27 @@ async function workerReasoningSummary(isRecord(profile) && profile.model_reasoning_summary !== undefined? profile.model_reasoning_summary: config.model_reasoning_summary;- return typeof summary === "string" ? summary : undefined;+ const settings: CodexSdkWorkerRuntimeSettings = {+ ...(typeof summary === "string" ? { reasoningSummary: summary } : {}),+ };+ const security = config.codex_security;+ if (isRecord(security) && typeof security.cyber_access_program === "string") {+ settings.cyberAccessProgram =+ security.cyber_access_program as CyberAccessProgram;+ }+ const features = config.features;+ if (isRecord(features)) {+ for (const name of [+ "api_key_cyber_access_programs",+ "api_key_model_discovery",+ ] as const) {+ const value = features[name];+ if (typeof value === "boolean") {+ (settings.features ??= {})[name] = value;+ }+ }+ }+ return settings;}async function snapshotWorkerEnvironment(): Promise<Record<string, string>> {diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjsindex 50440129d..9aff0b304 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs@@ -83,6 +83,7 @@ try {testCodeModeFrameDiagnosticBoundaries();await testOpenAiCredentialsReachWorker();await testWorkerRuntimeSettings();+ await testWorkerCyberAccessSettings();if (process.platform !== "win32") {await testMissingParentSandboxFailsBeforeWorkerLaunch();await testDisallowedWorkerProfileFailsBeforeWorkerLaunch();@@ -1322,6 +1323,171 @@ async function testWorkerRuntimeSettings() {}}+async function testWorkerCyberAccessSettings() {+ const cases = [+ { name: "unset", configuration: "" },+ {+ name: "blue",+ configuration:+ '[codex_security]\ncyber_access_program = "daybreak_blue"\n[features]\napi_key_cyber_access_programs = true\napi_key_model_discovery = true\n',+ program: "daybreak_blue",+ features: {+ api_key_cyber_access_programs: true,+ api_key_model_discovery: true,+ },+ },+ {+ name: "explicit-false",+ configuration:+ '[codex_security]\ncyber_access_program = "daybreak_blue"\n[features]\napi_key_cyber_access_programs = false\napi_key_model_discovery = false\n',+ program: "daybreak_blue",+ features: {+ api_key_cyber_access_programs: false,+ api_key_model_discovery: false,+ },+ },+ {+ name: "other-program",+ configuration:+ '[codex_security]\ncyber_access_program = "standard"\n[features]\napi_key_cyber_access_programs = true\napi_key_model_discovery = false\n',+ program: "standard",+ features: {+ api_key_cyber_access_programs: true,+ api_key_model_discovery: false,+ },+ },+ {+ name: "features-only",+ configuration:+ "[features]\napi_key_cyber_access_programs = false\napi_key_model_discovery = true\n",+ features: {+ api_key_cyber_access_programs: false,+ api_key_model_discovery: true,+ },+ },+ ];+ const saved = Object.fromEntries(+ [+ "CODEX_CLI_PATH",+ "CODEX_HOME",+ "CODEX_SECURITY_CONFIG_PATH",+ "OPENAI_API_KEY",+ "CODEX_API_KEY",+ ].map((name) => [name, process.env[name]]),+ );+ const originalSpawn = childProcess.spawn;+ const fixture = await fakeCodexFixture();+ const promptPath = path.join(fixture.root, "prompt.md");+ const launches = [];+ try {+ delete process.env.OPENAI_API_KEY;+ process.env.CODEX_API_KEY = "synthetic-worker-api-key";+ process.env.CODEX_CLI_PATH = process.execPath;+ process.env.CODEX_HOME = fixture.root;+ await writeFile(promptPath, "CAPTURE_SYNTHETIC_OPENAI_AUTH");+ childProcess.spawn = (command, args, options) => {+ const markerPath = path.join(+ fixture.root,+ `cyber-${launches.length}.json`,+ );+ const environment = {+ ...options.env,+ FAKE_CODEX_MARKER: markerPath,+ FAKE_CODEX_PREFLIGHT_MARKER: markerPath,+ };+ launches.push({ args, markerPath });+ return originalSpawn(command, [fixture.executablePath, ...args], {+ ...options,+ env: environment,+ });+ };+ syncBuiltinESMExports();+ for (const testCase of cases) {+ testCase.configPath = path.join(fixture.root, `${testCase.name}.toml`);+ await writeFile(testCase.configPath, testCase.configuration);+ testCase.executor = new CodexSdkWorkerExecutor({+ model: testCase.name,+ parentSandbox: trustedParentSandbox,+ });+ }+ for (const kind of ["discovery", "dedup"]) {+ for (const resumeThreadId of [undefined, "fixture-resumed-thread"]) {+ launches.length = 0;+ await Promise.all(+ cases.map((testCase) => {+ // Each scan captures its own config before its asynchronous launch.+ process.env.CODEX_SECURITY_CONFIG_PATH = testCase.configPath;+ return testCase.executor.run({+ kind,+ resumeThreadId,+ promptPath,+ workingDirectory: fixture.root,+ subagents: 0,+ signal: new AbortController().signal,+ });+ }),+ );+ const workerLaunches = launches.filter(+ ({ args }) => args[0] === "exec",+ );+ assert.equal(workerLaunches.length, cases.length);+ for (const { name, program, features = {} } of cases) {+ const launch = workerLaunches.find(+ ({ args }) => args[args.indexOf("--model") + 1] === name,+ );+ const invocation = JSON.parse(+ await readFile(launch.markerPath, "utf8"),+ );+ if (program === undefined) {+ assert.equal(+ invocation.argv.includes("--cyber-access-program"),+ false,+ );+ } else {+ assertFlagPair(invocation.argv, "--cyber-access-program", program);+ }+ for (const feature of [+ "api_key_cyber_access_programs",+ "api_key_model_discovery",+ ]) {+ assert.deepEqual(+ invocation.argv.filter((arg) =>+ arg.startsWith(`features.${feature}=`),+ ),+ features[feature] === undefined+ ? []+ : [`features.${feature}=${features[feature]}`],+ );+ }+ assert.equal(+ invocation.openaiAuthentication.CODEX_API_KEY,+ "synthetic-worker-api-key",+ );+ assert.equal(+ invocation.argv.includes("resume"),+ resumeThreadId !== undefined,+ );+ assertReadOnlyWorkerPolicy(invocation.argv);+ assertWorkerSubagentPolicy(invocation.argv, 0);+ }+ // Running coordinators and their resumed workers retain their own settings.+ await Promise.all(+ cases.map(({ configPath }) =>+ writeFile(+ configPath,+ '[codex_security]\ncyber_access_program = "daybreak_red"\n[features]\napi_key_cyber_access_programs = false\napi_key_model_discovery = false\n',+ ),+ ),+ );+ }+ }+ } finally {+ childProcess.spawn = originalSpawn;+ syncBuiltinESMExports();+ for (const [name, value] of Object.entries(saved)) restoreEnv(name, value);+ }+}+async function testBedrockCredentialsReachWorker() {const fixture = await fakeCodexFixture();const mcpConfig = JSON.parse(diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 5d8cbae26..1dd257574 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -45,6 +45,36 @@ make extra model calls; see [Progress and cost](#progress-and-cost).Keep results outside the repository and restrict access: reports can containsource code, vulnerability details, and reproduction steps.+### Select a Cyber access program++For the built-in OpenAI provider, select `standard`, `daybreak_blue`, or+`daybreak_red` per scan:++```ts+await security.run("/path/to/repository", {+ auth: "api-key",+ cyberAccessProgram: "daybreak_blue",+});+```++```sh+codex-security scan . --auth api-key --cyber-access-program daybreak_blue+```++`scan-components` accepts the same flag. Project files use+`scan.cyber_access_program`, including for bulk scans. An explicit CLI or SDK+selection overrides the project setting. Omission preserves Codex defaults;+`standard` explicitly selects the standard program.++The selection applies to Deep Scan discovery and reducer workers, resumed+workers, custom validation, and post-scan turns. Saved scan recipes retain it+for resume and rerun. Automatic component planning and finding matching also+use the selected program. API-key selection enables Codex's experimental Cyber+support unless the effective native configuration explicitly disables+`features.api_key_cyber_access_programs`.+Explicit disables and API entitlement failures remain errors. Selecting a+program does not grant access; the API verifies the key's entitlement.+### Validate an existing finding```tsdiff --git a/sdk/typescript/schemas/project-config.schema.json b/sdk/typescript/schemas/project-config.schema.jsonindex 263de9e6f..522dcdbf6 100644--- a/sdk/typescript/schemas/project-config.schema.json+++ b/sdk/typescript/schemas/project-config.schema.json@@ -21,6 +21,11 @@"type": "string","enum": ["standard", "deep"]},+ "cyber_access_program": {+ "description": "Experimental Cyber access program for scan turns (OpenAI provider only). Omit to preserve Codex defaults.",+ "type": "string",+ "enum": ["standard", "daybreak_blue", "daybreak_red"]+ },"scope": {"description": "One scope variant. Omit for the whole repository. Mode compatibility is checked after overrides.","anyOf": [diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex f7825cc00..14ae03461 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -57,6 +57,7 @@ import {modelProviderConfigOverride,resolveCommandAuthConfig,scanApprovalPolicy,+ scanCyberAccessConfig,scanModelConfiguration,scanModelProvider,type CodexSecurityConfig,@@ -1589,6 +1590,7 @@ export class CodexSecurity {maxCostUsd: options.maxCostUsd,deepScan: deepScanConfiguration?.settings,auth: options.auth,+ cyberAccessProgram: options.cyberAccessProgram,});if (options.scanPrompt?.trim()) recipe["requiresScanPrompt"] = true;if (options.safetyIdentifier !== undefined)@@ -1940,10 +1942,15 @@ export class CodexSecurity {checkOpen();const postScanPrompt = options.postScanPrompt;if (postScanPrompt?.trim()) {- runPostScan = () => thread.runStreamed(postScanPrompt, { signal });+ runPostScan = () =>+ thread.runStreamed(postScanPrompt, {+ signal,+ cyberAccessProgram: options.cyberAccessProgram,+ });}const { events } = await thread.runStreamed(prompt, {signal,+ cyberAccessProgram: options.cyberAccessProgram,});checkOpen();@@ -2019,6 +2026,7 @@ export class CodexSecurity {await validationThread.runStreamed(validationPrompt, {outputSchema,signal,+ cyberAccessProgram: options.cyberAccessProgram,})).events,onReconnect: (message, attempts) =>@@ -2256,6 +2264,7 @@ export class CodexSecurity {),environment,model,+ cyberAccessProgram: options.cyberAccessProgram,signal,});result.repositoryFindings = (await listRepositoryFindings(@@ -2749,6 +2758,7 @@ export class CodexSecurity {options: Pick<ScanOptions,| "auth"+ | "cyberAccessProgram"| "safetyIdentifier"| "expectedPluginVersion"| "onAuthentication"@@ -2828,11 +2838,23 @@ export class CodexSecurity {requestedConfig,);}- const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;+ const effectiveConfig = scanCyberAccessConfig(+ runtime.effectiveConfig ?? requestedConfig,+ options.cyberAccessProgram,+ );const approvalPolicy = scanApprovalPolicy(effectiveConfig);const preflightConfig = scanPreflightCodexConfig(effectiveConfig);if (runtime.configPath !== undefined) {- await writeCodexConfig(runtime.configPath, preflightConfig);+ await writeCodexConfig(runtime.configPath, {+ ...preflightConfig,+ ...(options.cyberAccessProgram === undefined+ ? {}+ : {+ codex_security: {+ cyber_access_program: options.cyberAccessProgram,+ },+ }),+ });}const runtimeHome = await realpath(runtime.codexHome);requireOutputOutsideRepositories(protectedRoots, runtimeHome, "runtime");@@ -3197,6 +3219,7 @@ export class CodexSecurity {knowledgeBasePaths: options.knowledgeBasePaths,maxCostUsd: options.maxCostUsd,auth: options.auth,+ cyberAccessProgram: options.cyberAccessProgram,}),mock: true,},@@ -3342,6 +3365,15 @@ export class CodexSecurity {);}const deep = deepScanOptions(options);+ if (+ !ScanSettingsSchema.shape.cyberAccessProgram.safeParse(+ options.cyberAccessProgram,+ ).success+ ) {+ throw new ConfigurationError(+ "cyberAccessProgram must be standard, daybreak_blue, or daybreak_red.",+ );+ }const identifier = options.safetyIdentifier;if (identifier !== undefined &&@@ -4109,6 +4141,7 @@ function scanRecipe({maxCostUsd,deepScan,auth,+ cyberAccessProgram,}: {repository: string;target: NormalizedTarget;@@ -4121,6 +4154,7 @@ function scanRecipe({maxCostUsd?: number;deepScan?: Required<DeepScanOptions>;auth?: ScanAuthMode;+ cyberAccessProgram?: ScanSettings["cyberAccessProgram"];}): JsonObject {return {repository,@@ -4137,6 +4171,7 @@ function scanRecipe({pluginVersion,config,...(auth === undefined ? {} : { auth }),+ ...(cyberAccessProgram === undefined ? {} : { cyberAccessProgram }),...(failOnSeverity === undefined ? {} : { failOnSeverity }),...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),...(maxCostUsd === undefined ? {} : { maxCostUsd }),@@ -4687,7 +4722,13 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {const capabilityFeatures = (value: unknown): JsonObject => {if (!isRecord(value)) return {};const result: JsonObject = {};- for (const key of ["goals", "multi_agent", "enable_fanout"]) {+ for (const key of [+ "goals",+ "multi_agent",+ "enable_fanout",+ "api_key_cyber_access_programs",+ "api_key_model_discovery",+ ]) {if (typeof value[key] === "boolean") result[key] = value[key];}const multiAgent = value["multi_agent_v2"];@@ -4741,11 +4782,23 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {};const result = executionConfig(config);// Keep the effective summary even when preflight filters the profile name.- const reasoningSummary =- resolveCodexProfile(config)["model_reasoning_summary"];+ const resolved = resolveCodexProfile(config);+ const reasoningSummary = resolved["model_reasoning_summary"];if (safeString(reasoningSummary)) {result["model_reasoning_summary"] = reasoningSummary;}+ const resolvedFeatures = capabilityFeatures(resolved["features"]);+ for (const key of [+ "api_key_cyber_access_programs",+ "api_key_model_discovery",+ ]) {+ if (resolvedFeatures[key] !== undefined) {+ result["features"] = {+ ...(isRecord(result["features"]) ? result["features"] : {}),+ [key]: resolvedFeatures[key],+ };+ }+ }const selectedProfile = safeProfileName(config["profile"])? config["profile"]: undefined;diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 764304da7..2b16e5716 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -346,6 +346,7 @@ const VALUE_OPTIONS = new Set(["--concurrency","--auth","--safety-identifier",+ "--cyber-access-program","--path","--component","--components-file",@@ -3515,6 +3516,7 @@ export async function main(.describe("Reuse completed work in the named local findings workflow.",),+ cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto).",),@@ -3678,6 +3680,7 @@ export async function main({auth: options.auth,target: scope.target,+ cyberAccessProgram: options.cyberAccessProgram,knowledgeBasePaths: options.knowledgeBase,scanPromptFile: options.scanPromptFile,validationPromptFile: options.validationPromptFile,@@ -4145,6 +4148,7 @@ export async function main(options: z.object({config: PROJECT_CONFIG_OPTION,+ cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto).",),@@ -4251,6 +4255,7 @@ export async function main(project,{auth: options.auth,+ cyberAccessProgram: options.cyberAccessProgram,outputDir: options.outputDir,knowledgeBasePaths: options.knowledgeBase,scanPromptFile: options.scanPromptFile,@@ -6178,6 +6183,15 @@ async function prepareScanArgumentsFromRecipe();}const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);+ const cyberAccessProgram =+ ScanSettingsSchema.shape.cyberAccessProgram.safeParse(+ recipe["cyberAccessProgram"],+ );+ if (!cyberAccessProgram.success) {+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid Cyber access program.",+ );+ }if (!auth.success)throw new CodexSecurityError("The saved scan recipe contains an invalid authentication choice.",@@ -6214,6 +6228,7 @@ async function prepareScanArgumentsFromRecipe(return {repository,auth: auth.data ?? DEFAULT_SCAN_AUTH,+ cyberAccessProgram: cyberAccessProgram.data,target:paths.length > 0? pathsdiff --git a/sdk/typescript/src/component-plan.ts b/sdk/typescript/src/component-plan.tsindex eebe72657..4de826a9a 100644--- a/sdk/typescript/src/component-plan.ts+++ b/sdk/typescript/src/component-plan.ts@@ -43,6 +43,8 @@ export interface ComponentPlan {export interface ComponentPlanningOptions {/** @internal Authentication already selected by the calling scan. */auth?: ScanAuthMode;+ /** @internal Cyber access program already selected by the calling scan. */+ cyberAccessProgram?: ReadOnlyCodexOptions["cyberAccessProgram"];config?: CodexSecurityConfig;environment?: NodeJS.ProcessEnv;signal?: AbortSignal;diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex 6ea29edfe..9af86fe95 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -152,6 +152,7 @@ export async function runComponentScans(options.auto? await (options.planComponents ?? planComponents)(repository, {auth,+ cyberAccessProgram: options.scanOptions?.cyberAccessProgram,config: options.config,environment,signal: options.signal,@@ -369,6 +370,7 @@ async function deduplicateFindings({allowHistoricalUncertainty: true,auth: options.scanOptions?.auth,+ cyberAccessProgram: options.scanOptions?.cyberAccessProgram,config: options.config ?? {},environment: options.environment,signal: options.signal,diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.tsindex 199e0636d..490743de2 100644--- a/sdk/typescript/src/config.ts+++ b/sdk/typescript/src/config.ts@@ -1,6 +1,7 @@import { randomUUID } from "node:crypto";import { mkdir, open, rename, unlink } from "node:fs/promises";import { dirname, join, resolve } from "node:path";+import type { CyberAccessProgram } from "@openai/codex-sdk";import { stringify } from "smol-toml";import { ConfigurationError } from "./errors.js";@@ -202,6 +203,26 @@ export function resolveCodexProfile(config: JsonObject): JsonObject {return resolved;}+/** @internal */+export function scanCyberAccessConfig(+ config: JsonObject,+ program: CyberAccessProgram | undefined,+): JsonObject {+ if (program === undefined) return config;+ const resolved = resolveCodexProfile(config);+ const features = isObject(resolved["features"]) ? resolved["features"] : {};+ return {+ ...config,+ features: {+ ...(isObject(config["features"]) ? config["features"] : {}),+ // Explicit selections opt in to upstream API-key support. Keep a user's+ // explicit disable so Codex can report it instead of silently dropping it.+ api_key_cyber_access_programs:+ features["api_key_cyber_access_programs"] ?? true,+ },+ };+}+export async function mergedCodexConfig(config: CodexSecurityConfig,): Promise<JsonObject> {diff --git a/sdk/typescript/src/project-config-schema.ts b/sdk/typescript/src/project-config-schema.tsindex 8e9fbe955..fd49b7c77 100644--- a/sdk/typescript/src/project-config-schema.ts+++ b/sdk/typescript/src/project-config-schema.ts@@ -39,6 +39,7 @@ export const ProjectConfigInputSchema = z.strictObject({scan: z.strictObject({mode: ScanSettingsSchema.shape.mode,+ cyber_access_program: ScanSettingsSchema.shape.cyberAccessProgram,scope: ProjectScopeSchema.optional().describe("One scope variant. Omit for the whole repository. Mode compatibility is checked after overrides.",),diff --git a/sdk/typescript/src/project-config.ts b/sdk/typescript/src/project-config.tsindex 08c2539cc..33d25721d 100644--- a/sdk/typescript/src/project-config.ts+++ b/sdk/typescript/src/project-config.ts@@ -57,6 +57,7 @@ export type ConfigurationSource = "default" | "legacy" | "project" | "cli";const PROJECT_SETTING_KEYS = {auth: "auth",mode: "scan.mode",+ cyberAccessProgram: "scan.cyber_access_program",target: "scan.scope",knowledgeBasePaths: "scan.knowledge_base",scanPromptFile: "scan.instructions_file",@@ -331,6 +332,11 @@ export function resolveScanSettings(const settings: ResolvedScanSettings = {...pickScanSettings(overrides),auth: choose("auth", file?.auth, overrides.auth) ?? DEFAULT_SCAN_AUTH,+ cyberAccessProgram: choose(+ "scan.cyber_access_program",+ file?.scan?.cyber_access_program,+ overrides.cyberAccessProgram,+ ),mode,target,knowledgeBasePaths,diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.tsindex ded5da97d..0fbf172f7 100644--- a/sdk/typescript/src/scan-comparison.ts+++ b/sdk/typescript/src/scan-comparison.ts@@ -4,6 +4,7 @@ import { join } from "node:path";import {Codex,type CodexOptions,+ type CyberAccessProgram,type ModelReasoningEffort,type ThreadOptions,type TurnOptions,@@ -21,7 +22,9 @@ import {hasCommandAuth,mergedCodexConfig,modelProviderConfigOverride,+ resolveCodexProfile,resolveCommandAuthConfig,+ scanCyberAccessConfig,scanModelConfiguration,scanModelProvider,type CodexSecurityConfig,@@ -154,6 +157,8 @@ interface ReadOnlyCodex {export interface ReadOnlyCodexOptions {/** @internal Authentication already selected by the calling scan. */auth?: ScanAuthMode;+ /** @internal Cyber access program already selected by the calling scan. */+ cyberAccessProgram?: CyberAccessProgram;config?: CodexSecurityConfig;/** @internal */codex?: ReadOnlyCodex;@@ -175,6 +180,8 @@ interface CompletedScanMatchingOptions extends Pick<ScanComparisonOptions,"environment" | "model" | "signal"> {+ /** @internal Cyber access program already selected by the calling scan. */+ cyberAccessProgram?: CyberAccessProgram;scanId: string;repository: string;previousFindings: readonly Record<string, unknown>[];@@ -345,6 +352,9 @@ export async function matchScanFindingsInternal(outputSchema: z.toJSONSchema(matchingTurnSchema.required(), {target: "draft-7",}),+ ...(options.cyberAccessProgram === undefined+ ? {}+ : { cyberAccessProgram: options.cyberAccessProgram }),...(options.signal === undefined ? {} : { signal: options.signal }),};let prompt = comparisonPrompt(pages[0]!, 0, pages.length);@@ -565,6 +575,18 @@ async function startReadOnlyCodexThread(}const sdkConfig = { ...config };if (commandAuth) delete sdkConfig["model_providers"];+ const effectiveFeatures = resolveCodexProfile(+ scanCyberAccessConfig(providerConfig, options.cyberAccessProgram),+ )["features"] as JsonObject | undefined;+ const cyberFeatures: JsonObject = {};+ for (const feature of [+ "api_key_cyber_access_programs",+ "api_key_model_discovery",+ ]) {+ if (effectiveFeatures?.[feature] !== undefined) {+ cyberFeatures[feature] = effectiveFeatures[feature];+ }+ }const environment =options.codex === undefined? await comparisonEnvironment(@@ -604,6 +626,7 @@ async function startReadOnlyCodexThread(codex_security_surface: runtimeOptions.surface,},features: {+ ...cyberFeatures,apps: false,code_mode: false,code_mode_only: false,@@ -646,6 +669,9 @@ export async function runReadOnlyCodex(const thread = await startReadOnlyCodexThread(options, runtimeOptions);const turn = await thread.run(prompt, {outputSchema,+ ...(options.cyberAccessProgram === undefined+ ? {}+ : { cyberAccessProgram: options.cyberAccessProgram }),...(options.signal === undefined ? {} : { signal: options.signal }),});return turn.finalResponse;@@ -741,6 +767,7 @@ export async function matchCompletedScan(};const comparison = await (options.matchFindings ?? matchScanFindings)(input, {allowHistoricalUncertainty: true,+ cyberAccessProgram: options.cyberAccessProgram,environment: options.environment,model: options.model,signal: options.signal,diff --git a/sdk/typescript/src/scan-settings.ts b/sdk/typescript/src/scan-settings.tsindex 9f46321d8..7dd1036d3 100644--- a/sdk/typescript/src/scan-settings.ts+++ b/sdk/typescript/src/scan-settings.ts@@ -100,6 +100,12 @@ const inputPath = z.string().min(1);export const ScanSettingsSchema = DeepScanSettingsSchema.extend({auth: z.enum(SCAN_AUTH_MODES).optional().meta({ default: DEFAULT_SCAN_AUTH }),+ cyberAccessProgram: z+ .enum(["standard", "daybreak_blue", "daybreak_red"])+ .optional()+ .describe(+ "Experimental Cyber access program for scan turns (OpenAI provider only). Omit to preserve Codex defaults.",+ ),mode: z.enum(SCAN_MODES).optional().meta({ default: DEFAULT_SCAN_MODE }),knowledgeBasePaths: z.array(inputPath).optional(),scanPrompt: z.string().optional(),diff --git a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts b/sdk/typescript/tests-ts/api-attribution-concurrency.test.tsindex 77b8f50bb..91981c94d 100644--- a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts+++ b/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts@@ -1,6 +1,10 @@import { mkdir, readFile, realpath, symlink } from "node:fs/promises";import { delimiter, join } from "node:path";-import type { CodexOptions, ThreadOptions } from "@openai/codex-sdk";+import type {+ CodexOptions,+ ThreadOptions,+ TurnOptions,+} from "@openai/codex-sdk";import { afterEach, describe, expect, test } from "bun:test";import { parse as parseToml } from "smol-toml";import { CodexSecurity } from "../src/index.js";@@ -31,11 +35,18 @@ describe("delegated scan attribution", () => {await mkdir(ambientHome);let active = 0;let maximumActive = 0;+ const configPaths = new Set<string>();+ const programs = ["daybreak_blue", "standard"] as const;const { promise: concurrentScans, resolve: releaseConcurrentScans } =Promise.withResolvers<void>();const clients = await Promise.all((["cli", "sdk"] as const).map(async (surface) => {+ const program = surface === "cli" ? programs[0] : programs[1];+ const features = {+ api_key_cyber_access_programs: surface === "cli",+ ...(surface === "sdk" ? { api_key_model_discovery: false } : {}),+ };const scanDirectory = join(root, `${surface}-scan`);const gitDirectory = join(root, `${surface}-tools`);await mkdir(gitDirectory);@@ -49,7 +60,10 @@ describe("delegated scan attribution", () => {const expectedGitDirectory = await realpath(gitDirectory);await mkdir(scanDirectory, { mode: 0o700 });return new InternalCodexSecurity(- { pluginPath: PLUGIN_ROOT },+ {+ pluginPath: PLUGIN_ROOT,+ ...(surface === "sdk" ? { codexOverrides: { features } } : {}),+ },{environment: {PATH: gitDirectory,@@ -88,7 +102,10 @@ describe("delegated scan attribution", () => {createCodex: (options: CodexOptions) => ({startThread: (threadOptions: ThreadOptions) => ({id: null,- async runStreamed() {+ async runStreamed(+ _input: unknown,+ turnOptions?: TurnOptions,+ ) {active += 1;maximumActive = Math.max(maximumActive, active);if (active === 2) releaseConcurrentScans();@@ -114,12 +131,24 @@ describe("delegated scan attribution", () => {`synthetic-${surface}-ssh`,);expect(options.env).not.toHaveProperty("OPENAI_API_KEY");+ expect(options.apiKey).toBe(`synthetic-${surface}-key`);+ expect(turnOptions?.cyberAccessProgram).toBe(program);expect(options.config).toMatchObject({+ features,responses_api_metadata: {codex_security_surface: surface,},});expect(threadOptions.threadSource).toBe("security_scan");+ const configPath =+ options.env?.["CODEX_SECURITY_CONFIG_PATH"];+ expect(configPath).toBeString();+ configPaths.add(configPath!);+ const initialConfig = await readFile(configPath!, "utf8");+ expect(parseToml(initialConfig)).toMatchObject({+ codex_security: { cyber_access_program: program },+ features,+ });await concurrentScans;const sharedConfig = parseToml(await readFile(@@ -130,6 +159,22 @@ describe("delegated scan attribution", () => {expect(sharedConfig).not.toHaveProperty("responses_api_metadata",);+ expect(sharedConfig).not.toHaveProperty("codex_security");+ expect(sharedConfig["features"] ?? {}).not.toHaveProperty(+ "api_key_cyber_access_programs",+ );+ expect(sharedConfig["features"] ?? {}).not.toHaveProperty(+ "api_key_model_discovery",+ );+ expect(JSON.stringify(sharedConfig)).not.toContain(+ "synthetic-cli-key",+ );+ expect(JSON.stringify(sharedConfig)).not.toContain(+ "synthetic-sdk-key",+ );+ expect(await readFile(configPath!, "utf8")).toBe(+ initialConfig,+ );expect(options.env).toEqual(initialEnvironment);throw new Error("delegated attribution observed");} finally {@@ -146,8 +191,10 @@ describe("delegated scan attribution", () => {try {const results = await Promise.allSettled(- clients.map((client) =>- client.run(repository, { mode }).finally(releaseConcurrentScans),+ clients.map((client, index) =>+ client+ .run(repository, { mode, cyberAccessProgram: programs[index] })+ .finally(releaseConcurrentScans),),);for (const result of results) {@@ -159,6 +206,7 @@ describe("delegated scan attribution", () => {});}expect(maximumActive).toBe(2);+ expect(configPaths.size).toBe(2);} finally {releaseConcurrentScans();await Promise.all(clients.map(async (client) => await client.close()));diff --git a/sdk/typescript/tests-ts/api-cyber-access.test.ts b/sdk/typescript/tests-ts/api-cyber-access.test.tsnew file mode 100644index 000000000..e6c8e8010--- /dev/null+++ b/sdk/typescript/tests-ts/api-cyber-access.test.ts@@ -0,0 +1,147 @@+import { mkdir, readFile } from "node:fs/promises";+import { join } from "node:path";+import type { CodexOptions, ThreadEvent, TurnOptions } from "@openai/codex-sdk";+import { afterEach, expect, test } from "bun:test";+import { parse as parseToml } from "smol-toml";+import { resolveCodexProfile, type JsonObject } from "../src/config.js";+import type { ScanOptions } from "../src/api.js";+import { TestClient, mockWorkbench } from "./support/api-client.js";+import {+ createApiTestFixtures,+ preparedRuntime,+} from "./support/api-events.js";++const fixtures = createApiTestFixtures();+afterEach(fixtures.cleanup);++const denied = "403: API key is not entitled to the requested Cyber program";+async function* deniedEvents(): AsyncGenerator<ThreadEvent> {+ yield { type: "turn.failed", error: { message: denied } };+}++test.each([+ [undefined, {}],+ ["standard", {}],+ ["daybreak_blue", {}],+ ["daybreak_red", {}],+ ["daybreak_blue", { features: { api_key_cyber_access_programs: false } }],+ [+ "daybreak_blue",+ {+ profile: "selected",+ features: { api_key_model_discovery: true },+ profiles: { selected: { features: { api_key_model_discovery: false } } },+ },+ ],+] as const)(+ "forwards %s and preserves API-key gates %j",+ async (program, overrides) => {+ const root = await fixtures.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 });+ const runtime = {+ ...preparedRuntime(codexHome),+ configPath: join(root, "runtime.toml"),+ environment: { OPENAI_API_KEY: "synthetic-api-key" },+ };+ let clientOptions: CodexOptions | undefined;+ let turnOptions: TurnOptions | undefined;+ let recipe: JsonObject | undefined;+ const client = new TestClient(+ { codexOverrides: overrides as JsonObject },+ {+ environment: { OPENAI_API_KEY: "synthetic-api-key" },+ prepareRuntime: async () => runtime,+ resolvePluginPython: async () =>+ Bun.which("python3") ?? Bun.which("python")!,+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_options, args, input) => {+ if (args[0] === "register-cli-scan")+ recipe = JSON.parse(input!).recipe;+ return mockWorkbench(args, input);+ },+ createCodex: (options) => {+ clientOptions = options;+ return {+ startThread: () => ({+ id: null,+ async runStreamed(_input, options) {+ turnOptions = options;+ return { events: deniedEvents() };+ },+ }),+ };+ },+ },+ );+ try {+ await expect(+ client.run(repository, {+ auth: "api-key",+ cyberAccessProgram: program,+ }),+ ).rejects.toThrow(denied);+ expect(turnOptions?.cyberAccessProgram).toBe(program);+ expect(recipe?.["cyberAccessProgram"]).toBe(program);+ expect(clientOptions?.apiKey).toBe("synthetic-api-key");+ const config = parseToml(await readFile(runtime.configPath, "utf8"));+ if (program === undefined) {+ expect(config).not.toHaveProperty("codex_security");+ expect(config["features"]).not.toHaveProperty(+ "api_key_cyber_access_programs",+ );+ expect(clientOptions?.config?.["features"]).not.toHaveProperty(+ "api_key_cyber_access_programs",+ );+ } else {+ const expected = {+ api_key_cyber_access_programs: !(+ "features" in overrides &&+ "api_key_cyber_access_programs" in overrides.features+ ),+ ...("profile" in overrides ? { api_key_model_discovery: false } : {}),+ };+ expect(config["codex_security"]).toEqual({+ cyber_access_program: program,+ });+ expect(config["features"]).toMatchObject(expected);+ expect(+ resolveCodexProfile(clientOptions!.config as JsonObject)["features"],+ ).toMatchObject(expected);+ if (!("profile" in overrides)) {+ expect(config["features"]).not.toHaveProperty(+ "api_key_model_discovery",+ );+ }+ expect(recipe?.["config"]).not.toHaveProperty("codex_security");+ }+ } finally {+ await client.close();+ }+ },+);++test("rejects an unknown SDK Cyber program before preparing a runtime", async () => {+ const client = new TestClient(+ {},+ {+ prepareRuntime: async () => {+ throw new Error("runtime must not start");+ },+ },+ );+ try {+ await expect(+ client.run(".", {+ cyberAccessProgram: "unknown" as ScanOptions["cyberAccessProgram"],+ }),+ ).rejects.toThrow("cyberAccessProgram must be");+ } finally {+ await client.close();+ }+});diff --git a/sdk/typescript/tests-ts/api-post-scan.test.ts b/sdk/typescript/tests-ts/api-post-scan.test.tsindex 3cc1b7df1..977461a43 100644--- a/sdk/typescript/tests-ts/api-post-scan.test.ts+++ b/sdk/typescript/tests-ts/api-post-scan.test.ts@@ -92,7 +92,8 @@ async function startFailedPostScan(scenario: FailedPostScanScenario) {createCodex: () => ({startThread: () => ({id: "thread-1",- async runStreamed() {+ async runStreamed(_input, options) {+ expect(options.cyberAccessProgram).toBe("daybreak_blue");turns += 1;if (turns === 1) {await copyCompletedScan(root);@@ -126,6 +127,7 @@ async function startFailedPostScan(scenario: FailedPostScanScenario) {);const scan = client.run(repository, {postScanPrompt: "Draft confirmed fixes.",+ cyberAccessProgram: "daybreak_blue",});return {client,diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 777ba9114..322b8da26 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -4170,6 +4170,7 @@ describe("CodexSecurity orchestration", () => {return mockWorkbench(args, input);},async matchFindings(input, options, runtimeOptions) {+ expect(options?.cyberAccessProgram).toBe("daybreak_blue");modelCalled = true;observedSingleTurn = runtimeOptions.singleTurn;if (failure === "matcher") throw new Error("matcher unavailable");@@ -4181,7 +4182,10 @@ describe("CodexSecurity orchestration", () => {codex: {startThread() {return {- async run() {+ async run(_input, turnOptions) {+ expect(turnOptions.cyberAccessProgram).toBe(+ "daybreak_blue",+ );matchingTurns += 1;return {finalResponse: JSON.stringify({@@ -4229,6 +4233,7 @@ describe("CodexSecurity orchestration", () => {const result = await client.run(repository, {...(limited ? { maxCostUsd: 1 } : {}),+ cyberAccessProgram: "daybreak_blue",onWarning: (message) => warnings.push(message),});expect(result.threadId).toBe("thread-1");diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.tsindex 0db633e8d..c28c05764 100644--- a/sdk/typescript/tests-ts/cli-project-config.test.ts+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts@@ -196,6 +196,39 @@ test("an explicit config flag overrides the operator-selected environment file",}});+test.each([undefined, "standard", "daybreak_red"] as const)(+ "scan resolves Cyber selection from project or CLI override: %s",+ async (override) => {+ const input = await fixture({+ scan: { cyber_access_program: "daybreak_blue" },+ });+ let selected: ScanOptions | undefined;+ expect(+ await main(+ [+ "scan",+ input.repository,+ "-c",+ input.config,+ "--json",+ ...(override === undefined+ ? []+ : ["--cyber-access-program", override]),+ ],+ capture().stream,+ capture().stream,+ dependencies({+ currentDirectory: input.repository,+ onTurn: (_target, options) => {+ selected = options as ScanOptions;+ },+ }),+ ),+ ).toBe(0);+ expect(selected?.cyberAccessProgram).toBe(override ?? "daybreak_blue");+ },+);+test("a missing operator-selected environment file fails without falling back", async () => {const input = await fixture({});let initialized = false;@@ -693,6 +726,7 @@ test("rerun accepts replacement scan and validation files relative to the invocaconfig: {},requiresScanPrompt: true,validationMode: "custom",+ cyberAccessProgram: "daybreak_blue",};let selected: ScanOptions | undefined;const stderr = capture();@@ -723,6 +757,7 @@ test("rerun accepts replacement scan and validation files relative to the invocascanPrompt: "Review the synthetic boundary.",validationPrompt: "Validate the synthetic boundary.",parentScanId: "saved",+ cyberAccessProgram: "daybreak_blue",});});diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex 16ca3a2c1..f41488778 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -883,6 +883,7 @@ test("plans from a Git inventory without tools or ignored files", async () => {await mkdir(join(paths.repository, "ignored"));await writeFile(join(paths.repository, "ignored", "secret.txt"), "synthetic");const plan = await planComponents(paths.repository, {+ cyberAccessProgram: "daybreak_blue",codex: {startThread(options) {expect(options).toMatchObject({@@ -896,6 +897,7 @@ test("plans from a Git inventory without tools or ignored files", async () => {expect(prompt).toContain("apps/api");expect(prompt).not.toContain("secret.txt");expect(options.outputSchema).toBeDefined();+ expect(options.cyberAccessProgram).toBe("daybreak_blue");return {finalResponse: JSON.stringify({ components: [components[0]] }),};@@ -966,11 +968,13 @@ test("plans large inventories in separate contexts and fills omissions within eaconst batches: string[][] = [];let threads = 0;const plan = await planComponents(paths.repository, {+ cyberAccessProgram: "daybreak_red",codex: {startThread: () => {threads++;return {- run: async (prompt) => {+ run: async (prompt, options) => {+ expect(options.cyberAccessProgram).toBe("daybreak_red");expect(prompt.length).toBeLessThanOrEqual(1_048_576);const { scopes } = JSON.parse(prompt.split("\n").at(-1)!);batches.push(scopes);@@ -1343,7 +1347,7 @@ test.each(["auto", "explicit", "file"])();test.each(["auto", "chatgpt", "api-key"] as const)(- "CLI uses %s authentication for planning, scans, and matching",+ "CLI uses %s authentication and the selected Cyber program for planning, scans, and matching",async (auth) => {const paths = await fixture();const environment = {@@ -1357,21 +1361,29 @@ test.each(["auto", "chatgpt", "api-key"] as const)(matched = false;const result = await cli(paths,- ["--auto", ...(auth === "auto" ? [] : ["--auth", auth])],+ [+ "--auto",+ "--cyber-access-program",+ "daybreak_blue",+ ...(auth === "auto" ? [] : ["--auth", auth]),+ ],{...dependencies({ currentDirectory: paths.root, environment }),planComponents: async (_repository, options) => {expect(options?.auth).toBe(auth);+ expect(options?.cyberAccessProgram).toBe("daybreak_blue");expect(options?.environment).toEqual(expectedEnvironment);planned = true;return { components: components.slice(0, 2) };},createSecurity: client(async (_repository, options) => {expect(options.auth).toBe(auth);+ expect(options.cyberAccessProgram).toBe("daybreak_blue");return completed(options);}),matchFindings: async (_input, options) => {expect(options?.auth).toBe(auth);+ expect(options?.cyberAccessProgram).toBe("daybreak_blue");expect(options?.environment).toEqual(expectedEnvironment);matched = true;return noMatches;diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.tsindex 50115378d..12476d2ee 100644--- a/sdk/typescript/tests-ts/custom-validation.test.ts+++ b/sdk/typescript/tests-ts/custom-validation.test.ts@@ -564,6 +564,9 @@ describe("custom validation", () => {? "thread-1": "validation-thread",async runStreamed(prompt, turnOptions) {+ expect(turnOptions.cyberAccessProgram).toBe(+ "daybreak_blue",+ );turns += 1;if (turns === 1) {expect(prompt).not.toContain(workflow);@@ -687,6 +690,7 @@ describe("custom validation", () => {);try {const pending = client.run(repository, {+ cyberAccessProgram: "daybreak_blue",...(scenario === "standard"? { validationPromptFile: workflowFile }: { validationPrompt: workflow }),diff --git a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.tsindex bf1ce301f..9ec71e796 100644--- a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts+++ b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts@@ -54,7 +54,7 @@ async function bundledWorkerExecutor("workerPermissionProfile","workerPermissionProfileConfigOverrides","snapshotWorkerEnvironment",- "workerReasoningSummary",+ "workerRuntimeSettings","environmentVariable","preflightDeepScanWorkerPermissionProfile","deepScanPermissionProfileFallbackError",@@ -70,7 +70,7 @@ async function bundledWorkerExecutor(() => ({}),() => [],async () => ({}),- async () => undefined,+ async () => ({}),() => undefined,preflight,() => undefined,diff --git a/sdk/typescript/tests-ts/finding-catalogue.test.ts b/sdk/typescript/tests-ts/finding-catalogue.test.tsindex d40f2a2c7..7c4648b64 100644--- a/sdk/typescript/tests-ts/finding-catalogue.test.ts+++ b/sdk/typescript/tests-ts/finding-catalogue.test.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import type { TurnOptions } from "@openai/codex-sdk";import { describe, expect, test } from "bun:test";import {compactFinding,@@ -51,20 +52,22 @@ function conversation(respond: (prompt: string, index: number) => unknown | Promise<unknown>,) {const prompts: string[] = [];+ const turns: TurnOptions[] = [];let threads = 0;const codex: NonNullable<ScanComparisonOptions["codex"]> = {startThread() {threads += 1;return {- async run(prompt) {+ async run(prompt, options) {prompts.push(prompt);+ turns.push(options);const response = await respond(prompt, prompts.length - 1);return { finalResponse: JSON.stringify(response) };},};},};- return { codex, prompts, threads: () => threads };+ return { codex, prompts, turns, threads: () => threads };}describe("finding catalogue", () => {@@ -457,6 +460,7 @@ describe("finding catalogue", () => {{ before, after, knownFindingGroups: [["identity-a", "identity-b"]] },{codex: observed.codex,+ cyberAccessProgram: "daybreak_blue",onProgress(progress) {phases.push(progress.phase);const error = new Error("Optional observer");@@ -471,6 +475,10 @@ describe("finding catalogue", () => {]);expect(observed.threads()).toBe(1);expect(observed.prompts).toHaveLength(2);+ expect(observed.turns.map((turn) => turn.cyberAccessProgram)).toEqual([+ "daybreak_blue",+ "daybreak_blue",+ ]);expect(phases).toEqual(["catalogue", "evidence", "complete"]);},);@@ -557,9 +565,17 @@ describe("finding catalogue", () => {? { ...empty, request: { kind: "catalogue", page: 2 } }: empty,);- expect(await matchScanFindings(input, { codex: observed.codex })).toEqual(- empty,- );+ expect(+ await matchScanFindings(input, {+ codex: observed.codex,+ cyberAccessProgram: "daybreak_red",+ }),+ ).toEqual(empty);+ expect(observed.turns.map((turn) => turn.cyberAccessProgram)).toEqual([+ "daybreak_red",+ "daybreak_red",+ "daybreak_red",+ ]);expect(observed.threads()).toBe(1);expect(observed.prompts.map((prompt) => data<CatalogueData>(prompt).page),diff --git a/sdk/typescript/tests-ts/project-config.test.ts b/sdk/typescript/tests-ts/project-config.test.tsindex 575de53d3..8082449ea 100644--- a/sdk/typescript/tests-ts/project-config.test.ts+++ b/sdk/typescript/tests-ts/project-config.test.ts@@ -32,6 +32,16 @@ async function temporaryDirectory() {const cases: [string, unknown, boolean][] = [["minimal file", {}, true],+ [+ "Cyber selection",+ { scan: { cyber_access_program: "daybreak_blue" } },+ true,+ ],+ [+ "unknown Cyber selection",+ { scan: { cyber_access_program: "unknown" } },+ false,+ ],["standard path scope",{ scan: { mode: "standard", scope: { paths: ["src"] } } },diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.tsindex 3fbc8cb5d..508c051c7 100644--- a/sdk/typescript/tests-ts/scan-comparison.test.ts+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts@@ -25,6 +25,7 @@ import {matchCompletedScan,matchScanFindings,matchScanFindingsInternal,+ runReadOnlyCodex,type ScanComparisonInput,type ScanComparisonOptions,type ScanComparisonResult,@@ -157,6 +158,97 @@ describe("semantic scan comparison", () => {},);+ test.each(["unselected", "default", "home", "overrides", "override-profile"])(+ "preserves Cyber selection and %s feature gates at read-only SDK boundaries",+ async (selection) => {+ const home = await mkdtemp(+ join(tmpdir(), "codex-security-cyber-helper-"),+ );+ temporaryDirectories.push(home);+ const disabled = {+ api_key_cyber_access_programs: false,+ api_key_model_discovery: false,+ shell_tool: true,+ };+ const profile = {+ profile: "selected",+ features: { api_key_cyber_access_programs: true },+ profiles: { selected: { features: disabled } },+ };+ await writeFile(+ join(home, "config.toml"),+ stringify(selection === "home" ? { features: disabled } : {}),+ );+ const options = {+ cyberAccessProgram:+ selection === "unselected" ? undefined : ("daybreak_blue" as const),+ environment: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(home, "state"),+ OPENAI_API_KEY: "synthetic-key",+ },+ workingDirectory: home,+ ...(selection === "overrides"+ ? { config: { codexOverrides: { features: disabled } } }+ : selection === "override-profile"+ ? { config: { codexOverrides: profile } }+ : {}),+ };+ let captured: CodexOptions | undefined;+ const { codex, calls } = fakeCodex({ matches: [], uncertain: [] });+ const startThread = spyOn(+ Codex.prototype,+ "startThread",+ ).mockImplementation(function (this: Codex, threadOptions) {+ captured = (this as unknown as { options: CodexOptions }).options;+ return codex.startThread(threadOptions!) as ReturnType<+ Codex["startThread"]+ >;+ });+ try {+ for (const helper of ["matching", "planning"]) {+ if (helper === "matching") {+ await matchScanFindings(+ { before: [finding("before")], after: [finding("after")] },+ options,+ );+ } else {+ await runReadOnlyCodex("Plan components.", {}, options, {+ surface: "cli",+ threadSource: "security_scan",+ });+ }+ expect(calls.turnOptions?.cyberAccessProgram).toBe(+ options.cyberAccessProgram,+ );+ const features = captured?.config?.["features"] as Record<+ string,+ unknown+ >;+ expect(features["api_key_cyber_access_programs"]).toBe(+ selection === "unselected" ? undefined : selection === "default",+ );+ expect(features["api_key_model_discovery"]).toBe(+ selection === "unselected" || selection === "default"+ ? undefined+ : false,+ );+ expect(features).toMatchObject({+ shell_tool: false,+ plugins: false,+ multi_agent: false,+ unified_exec: false,+ });+ }+ expect(startThread).toHaveBeenCalledTimes(2);+ } finally {+ startThread.mockRestore();+ }+ },+ );+test.each(["home", "profile", "overrides", "override-away"])("preserves native command auth selection from %s",async (selection) => {@@ -897,6 +989,7 @@ describe("semantic scan comparison", () => {previousFindings: [firstOther, latestShared],falsePositives: [],findings: [after],+ cyberAccessProgram: "daybreak_red",async workbench(args, commandInput) {if (args[0] === "list-unmatched-scan-pairs") {return {@@ -926,6 +1019,7 @@ describe("semantic scan comparison", () => {before: [firstShared, firstOther, latestShared],after: [after],});+ expect(model.calls.turnOptions?.cyberAccessProgram).toBe("daybreak_red");expect([...saved.keys()]).toEqual(["first", "latest"]);for (const [scanId, occurrenceId] of [["first", firstShared.occurrenceId],diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex 0c7abc786..1a6c8ad95 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -11,6 +11,7 @@ import {} from "node:fs/promises";import { join } from "node:path";import { afterEach, expect, test } from "bun:test";+import { parse as parseToml } from "smol-toml";import { main } from "../src/cli.js";import type { ScanOptions } from "../src/api.js";import { runWorkbench } from "../src/runtime.js";@@ -31,7 +32,7 @@ async function interruptedScan(bulk = false,settings: Pick<ScanOptions,- "safetyIdentifier" | "postScanPrompt" | "auth"+ "safetyIdentifier" | "postScanPrompt" | "auth" | "cyberAccessProgram"> = {},resolvedDeep = false,modelProvider?: string,@@ -457,6 +458,7 @@ function resumeClient(environment: f.environment,prepareRuntime: async () => {const runtime = preparedRuntime(f.codexHome);+ runtime.configPath = join(f.root, "resumed-runtime.toml");runtime.environment = Object.fromEntries(Object.entries(f.environment).filter((entry): entry is [string, string] => entry[1] !== undefined,@@ -888,6 +890,7 @@ test.each([async (auth, bulk) => {const settings = {auth,+ cyberAccessProgram: "daybreak_blue" as const,safetyIdentifier:auth === "chatgpt" ? undefined : "synthetic-original-user",postScanPrompt: "Run these exact saved post-scan instructions.\n",@@ -927,6 +930,9 @@ test.each([);expect(options.env?.["OPENAI_API_KEY"]).toBeUndefined();expect(options.env?.["CODEX_API_KEY"]).toBeUndefined();+ expect(options.config?.["features"]).toMatchObject({+ api_key_cyber_access_programs: true,+ });return {startThread() {throw new Error("Resume must use the original session.");@@ -935,7 +941,10 @@ test.each([expect(threadId).toBe(f.threadId);return {id: threadId,- async runStreamed(prompt) {+ async runStreamed(prompt, turnOptions) {+ expect(turnOptions?.cyberAccessProgram).toBe(+ settings.cyberAccessProgram,+ );prompts.push(prompt as string);if (prompts.length === 1) {expect(prompt).toContain(@@ -948,6 +957,30 @@ test.each([expect(deep).toContain("subagents = 0");expect(deep).toContain("stop_after_consecutive_errors = 2");expect(deep).toContain("max_time_hours = 1.5");+ const workerConfigPath =+ options.env?.["CODEX_SECURITY_CONFIG_PATH"];+ expect(workerConfigPath).toBe(+ join(f.root, "resumed-runtime.toml"),+ );+ const workerConfig = parseToml(+ await readFile(workerConfigPath!, "utf8"),+ );+ expect(workerConfig).toMatchObject({+ codex_security: {+ cyber_access_program: settings.cyberAccessProgram,+ },+ features: {+ api_key_cyber_access_programs: true,+ },+ });+ const saved = await f.command([+ "get-scan-recipe",+ "--scan-id",+ f.scanId,+ ]);+ expect(saved["recipe"]).toMatchObject({+ cyberAccessProgram: settings.cyberAccessProgram,+ });await finishDiscovery(f);}return { events: completedEvents(threadId) };