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: support managed Codex credential keyrings (#101)
mldangelo-oaidd74cdb4ac00
diff --git a/README.md b/README.mdindex a8cf26b18..517aaa4d1 100644--- a/README.md+++ b/README.md@@ -17,7 +17,13 @@ npx @openai/codex-security scan .npx @openai/codex-security scan . --model gpt-5.6-terra --effort high```-For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY` instead of signing in.+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 never stored in Codex's credential+home or system keyring.++Local sign-in honors Codex's configured credential backend, including a system+keyring required by a managed device. Codex Security keeps login and scan+credentials in the same private, persistent state directory.If both a ChatGPT sign-in and an API key are available, interactive scans askwhich credential to use. CI and other noninteractive scans keep the existingdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 5bb93d8e8..2582c7bfa 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -111,6 +111,10 @@ pass it on stdin:printenv OPENAI_API_KEY | npx @openai/codex-security login --with-api-key```+Environment API keys are supplied directly to the current scan and are never+saved to the Codex credential home or system keyring. Only an explicit+`login --with-api-key` stores an API key.+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.@@ -122,10 +126,16 @@ $env:OPENAI_API_KEY = "<your-api-key>"npx @openai/codex-security scan C:\code\repository```-Check or remove the stored sign-in with `npx @openai/codex-security login status` and-`npx @openai/codex-security logout`. Codex Security reuses an existing file-based Codex-sign-in. If Codex stores credentials in the system keyring, run-`npx @openai/codex-security login` once before scanning.+Check or remove the stored sign-in with `npx @openai/codex-security login status`+and `npx @openai/codex-security logout`. Codex Security keeps its sign-in in a+private, stable Codex home at `$CODEX_SECURITY_STATE_DIR/codex-home`, or at+`$CODEX_HOME/state/plugins/codex-security/codex-home` when no state directory is+configured. Login, status, logout, and scans use the same home. Codex manages+credentials using its configured file or system-keyring backend and honors+managed-device policies. An existing file-based Codex sign-in is imported only+when the dedicated home does not already contain stored credentials. Logging+out prevents later scans from automatically reimporting that ambient sign-in+until you explicitly log in again.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, andiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 2699a634b..d2381d3dc 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -47,11 +47,16 @@ import {} from "./worker-progress.js";import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";import {+ acquireCodexSecurityCredentialHomeLock,bootstrapPlugin,cleanupSdkDirectory,+ codexSecurityCredentialAllowsAmbientImport,+ codexSecurityHasStoredFileCredentials,codexSecurityStateDirectory,createIsolatedHome,importAmbientAuth,+ prepareCodexSecurityCredentialHome,+ preserveCodexSecurityPluginRegistration,pluginExecutionEnvironment,planOutputArchive,prepareOutputDir,@@ -61,6 +66,7 @@ import {resolvePluginPath,resolvePluginPython,runWorkbench,+ setCodexSecurityCredentialLogout,type CodexCommand,type PluginInstall,type ProcessEnvironment,@@ -103,6 +109,7 @@ interface CodexClientLike {interface PreparedRuntime {codexHome: string;+ persistentCredentialHome?: boolean;bootstrapWorkspace?: string;configPath?: string;plugin: PluginInstall;@@ -303,6 +310,7 @@ export class CodexSecurity {let targetPathsFile: string | null = null;let knowledgeBase: PreparedKnowledgeBase | null = null;let costTracker: ScanCostTracker | null = null;+ let releaseCredentialHome: (() => Promise<void>) | null = null;let completionCost: ScanCost | null = null;let activeScan: {id: string;@@ -360,6 +368,21 @@ export class CodexSecurity {this.#dependencies.environment,options.auth,);+ if (+ authentication.method === "stored_credentials" &&+ this.#dependencies.prepareRuntime === undefined+ ) {+ const credentialHome = await prepareCodexSecurityCredentialHome(+ scanEnvironment,+ (path) =>+ requireOutputOutsideRepository(protectedRoot, path, "runtime"),+ );+ releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(+ credentialHome,+ signal,+ );+ }+ const previousRuntime = this.#runtime;const runtime = await this.#ensureRuntime(signal,temporaryRoot,@@ -367,6 +390,13 @@ export class CodexSecurity {requireOutputOutsideRepository(protectedRoot, path, "runtime"),options.auth,);+ if (+ runtime === previousRuntime &&+ runtime.persistentCredentialHome === true &&+ this.#dependencies.prepareRuntime === undefined+ ) {+ await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal);+ }const runtimeHome = await realpath(runtime.codexHome);requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");if (@@ -398,22 +428,23 @@ export class CodexSecurity {? environmentApiKey(this.#dependencies.environment): null;if (apiKey !== null) {- const codexCommand = this.#codexCommand();- const login = await persistApiKey(- codexCommand,+ this.#runtimeCredentialSource = "api_key";+ }+ if (+ !runtime.credentialsAvailable &&+ authentication.method === "stored_credentials"+ ) {+ const status = await accountStatus(+ this.#codexCommand(),runtime.environment,- apiKey,signal,);- if (!login.success) {- throw new CodexSecurityError(- `Codex API-key login failed: ${login.stderr.trim() || login.stdout.trim() || "unknown error"}`,- );- }- runtime.credentialsAvailable = true;- this.#runtimeCredentialSource = "api_key";+ runtime.credentialsAvailable = status.authenticated;+ this.#runtimeCredentialSource = status.authenticated+ ? "stored_credentials"+ : null;}- if (!runtime.credentialsAvailable) {+ if (!runtime.credentialsAvailable && apiKey === null) {throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +"'codex-security login --device-auth' on a remote or headless machine, or set " +@@ -706,7 +737,10 @@ export class CodexSecurity {...runtimePaths,};const codex = this.#dependencies.createCodex({- env: definedEnvironment(environment),+ ...(apiKey === null ? {} : { apiKey }),+ env: definedEnvironment(+ selectedScanEnvironment(environment, "chatgpt"),+ ),config: {default_permissions: SCAN_PERMISSION_PROFILE,allow_login_shell: false,@@ -826,10 +860,14 @@ export class CodexSecurity {}throw failure;} finally {- await Promise.all([- knowledgeBase?.cleanup(),- removeTargetPathsFile(targetPathsFile),- ]);+ try {+ await Promise.all([+ knowledgeBase?.cleanup(),+ removeTargetPathsFile(targetPathsFile),+ ]);+ } finally {+ await releaseCredentialHome?.();+ }}}@@ -844,18 +882,27 @@ export class CodexSecurity {signal,),}),+ "chatgpt",);if (!result.success) {throw new CodexSecurityError(`Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,);}+ if (runtime.persistentCredentialHome === true) {+ await setCodexSecurityCredentialLogout(runtime.codexHome, false);+ }runtime.credentialsAvailable = true;this.#runtimeCredentialSource = "api_key";}public async loginChatGPT(): Promise<CodexLoginHandle> {- const runtime = await this.#ensureRuntime();+ const runtime = await this.#ensureRuntime(+ undefined,+ undefined,+ undefined,+ "chatgpt",+ );this.#requireOpen();const handle = this.#trackLoginHandle(new CodexLoginHandle(@@ -874,7 +921,12 @@ export class CodexSecurity {}public async loginChatGPTDeviceCode(): Promise<CodexLoginHandle> {- const runtime = await this.#ensureRuntime();+ const runtime = await this.#ensureRuntime(+ undefined,+ undefined,+ undefined,+ "chatgpt",+ );this.#requireOpen();const handle = this.#trackLoginHandle(new CodexLoginHandle(@@ -919,7 +971,11 @@ export class CodexSecurity {);return preparedRuntime;},+ "chatgpt",);+ if (runtime.persistentCredentialHome === true) {+ await setCodexSecurityCredentialLogout(runtime.codexHome, true);+ }runtime.credentialsAvailable = false;this.#runtimeCredentialSource = null;}@@ -952,14 +1008,21 @@ export class CodexSecurity {this.#runtime = null;this.#runtimePromise = null;if (runtime !== null && runtime !== undefined) {- const cleanupResults = await Promise.allSettled(- [runtime.codexHome, runtime.bootstrapWorkspace]- .filter((path): path is string => path !== undefined)- .map((path) => cleanupSdkDirectory(path)),- );- for (const result of cleanupResults) {- if (result.status === "rejected") throw result.reason;- }+ await this.#cleanupRuntime(runtime);+ }+ }++ async #cleanupRuntime(runtime: PreparedRuntime): Promise<void> {+ const cleanupResults = await Promise.allSettled(+ [+ runtime.persistentCredentialHome ? undefined : runtime.codexHome,+ runtime.bootstrapWorkspace,+ ]+ .filter((path): path is string => path !== undefined)+ .map((path) => cleanupSdkDirectory(path)),+ );+ for (const result of cleanupResults) {+ if (result.status === "rejected") throw result.reason;}}@@ -969,10 +1032,16 @@ export class CodexSecurity {async #runOperation<T>(operation: (runtime: PreparedRuntime, signal: AbortSignal) => Promise<T>,+ auth: ScanAuthMode = "auto",): Promise<T> {return await this.#trackOperation(async () => {const signal = this.#abortController.signal;- const runtime = await this.#ensureRuntime(signal);+ const runtime = await this.#ensureRuntime(+ signal,+ undefined,+ undefined,+ auth,+ );this.#requireOpen();const result = await operation(runtime, signal);this.#requireOpen();@@ -1005,7 +1074,23 @@ export class CodexSecurity {auth: ScanAuthMode = "auto",): Promise<PreparedRuntime> {this.#requireOpen();- if (this.#runtime !== null) return this.#runtime;+ if (this.#runtime !== null) {+ const usePersistentCredentials =+ scanAuthentication(this.#dependencies.environment, auth).method ===+ "stored_credentials";+ if (+ this.#dependencies.prepareRuntime !== undefined ||+ this.#runtime.persistentCredentialHome === undefined ||+ this.#runtime.persistentCredentialHome === usePersistentCredentials+ ) {+ return this.#runtime;+ }+ await this.#cleanupRuntime(this.#runtime);+ this.#runtime = null;+ this.#runtimePromise = null;+ this.#runtimeCredentialSource = null;+ this.#requireOpen();+ }if (this.#runtimePromise === null) {const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal,@@ -1042,6 +1127,39 @@ export class CodexSecurity {return (this.#dependencies.resolveCodexCommand ?? resolveCodexCommand)();}+ async #refreshPersistentRuntime(+ runtime: PreparedRuntime,+ environment: ProcessEnvironment,+ signal: AbortSignal,+ ): Promise<void> {+ throwIfAborted(signal);+ const mergedConfig = await mergedCodexConfig(this.config);+ const config = await preserveCodexSecurityPluginRegistration(+ runtime.codexHome,+ scanRuntimeCodexConfig(+ mergedConfig,+ codexSecurityStateDirectory(environment),+ runtime.codexHome,+ ),+ );+ await writeCodexConfig(join(runtime.codexHome, "config.toml"), config);+ if (runtime.configPath !== undefined) {+ await writeCodexConfig(+ runtime.configPath,+ scanPreflightCodexConfig(mergedConfig),+ );+ }+ runtime.plugin = await bootstrapPlugin(+ runtime.codexHome,+ runtime.plugin.pluginRoot,+ {+ environment: withoutCodexHome(environment),+ signal,+ },+ );+ runtime.effectiveConfig = mergedConfig;+ }+async #validateLocalInputs(repository: string,options: ScanOptions,@@ -1091,12 +1209,24 @@ export class CodexSecurity {if (this.#dependencies.prepareRuntime !== undefined) {return await this.#dependencies.prepareRuntime(this.config, signal);}- const codexHome = await createIsolatedHome(temporaryRoot, validateLocation);+ const processEnvironment = selectedScanEnvironment(+ this.#dependencies.environment,+ auth,+ );+ const persistentCredentialHome =+ scanAuthentication(this.#dependencies.environment, auth).method ===+ "stored_credentials";+ const codexHome = persistentCredentialHome+ ? await prepareCodexSecurityCredentialHome(+ processEnvironment,+ validateLocation,+ )+ : await createIsolatedHome(temporaryRoot, validateLocation);let bootstrapWorkspace: string | undefined;try {throwIfAborted(signal);bootstrapWorkspace = await createIsolatedHome(- dirname(codexHome),+ temporaryRoot,validateLocation,);const pluginRoot = await resolvePluginPath(@@ -1104,10 +1234,6 @@ export class CodexSecurity {bootstrapWorkspace,signal,);- const processEnvironment = selectedScanEnvironment(- this.#dependencies.environment,- auth,- );const nodeAmbientHome = join(homedir(), ".codex");const configuredAmbientHome = environmentValue(processEnvironment,@@ -1115,9 +1241,13 @@ export class CodexSecurity {);const ambientHome = configuredAmbientHome ?? nodeAmbientHome;const mergedConfig = await mergedCodexConfig(this.config);- const codexConfig = scanRuntimeCodexConfig(- mergedConfig,- codexSecurityStateDirectory(processEnvironment),+ const codexConfig = await preserveCodexSecurityPluginRegistration(+ codexHome,+ scanRuntimeCodexConfig(+ mergedConfig,+ codexSecurityStateDirectory(processEnvironment),+ persistentCredentialHome ? codexHome : undefined,+ ),);await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);const configPath = join(bootstrapWorkspace, "config-preflight.toml");@@ -1137,6 +1267,7 @@ export class CodexSecurity {);return {codexHome,+ persistentCredentialHome,bootstrapWorkspace,configPath,plugin,@@ -1151,7 +1282,7 @@ export class CodexSecurity {};} catch (error) {const cleanupResults = await Promise.allSettled(- [bootstrapWorkspace, codexHome]+ [bootstrapWorkspace, persistentCredentialHome ? undefined : codexHome].filter((path): path is string => path !== undefined).map((path) => cleanupSdkDirectory(path)),);@@ -1181,6 +1312,10 @@ export async function initialCredentialsAvailable(importer: typeof importAmbientAuth = importAmbientAuth,): Promise<boolean> {if (environmentApiKey(environment) !== null) return false;+ if (!(await codexSecurityCredentialAllowsAmbientImport(isolatedHome))) {+ return false;+ }+ if (await codexSecurityHasStoredFileCredentials(isolatedHome)) return true;return await importer(ambientHome, isolatedHome);}@@ -1671,6 +1806,7 @@ export function classifyConnectionFailure(export function scanRuntimeCodexConfig(config: JsonObject,stateDirectory: string,+ protectedCredentialHome?: string,): JsonObject {const hardened = structuredClone(config);delete hardened["sandbox_mode"];@@ -1688,6 +1824,9 @@ export function scanRuntimeCodexConfig(":root": "read",":workspace_roots": "write",[stateDirectory]: "write",+ ...(protectedCredentialHome === undefined+ ? {}+ : { [protectedCredentialHome]: "read" }),},},},diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 3f69e4325..6e9d40b66 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -4,6 +4,7 @@ import { execFileSync, spawn } from "node:child_process";import {accessSync,constants,+ existsSync,lstatSync,realpathSync,writeSync,@@ -63,11 +64,14 @@ import { runMultiscan } from "./multiscan.js";import type { ScanResult } from "./result.js";import {bundledPluginRoot,+ codexSecurityCredentialHome,codexSecurityStateDirectory,expandHome,+ prepareCodexSecurityCredentialHome,resolveCodexCommand,resolvePluginPython,runWorkbench,+ setCodexSecurityCredentialLogout,type CodexCommand,} from "./runtime.js";import {@@ -251,6 +255,9 @@ interface CliDependencies {config: CodexSecurityConfig,): Pick<CodexSecurity, "run" | "preflight" | "close">;environment: NodeJS.ProcessEnv;+ prepareAuthenticationHome?: (+ environment: NodeJS.ProcessEnv,+ ) => Promise<string>;hasStoredChatGPTSignIn?: () => Promise<boolean>;scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;currentDirectory(): string;@@ -268,6 +275,7 @@ interface CliDependencies {runCodex(args: readonly string[],output?: SkillCommandOutput,+ environment?: NodeJS.ProcessEnv,): Promise<number>;bulkScan?: BulkScanDiscoveryDependencies;runWorkbench(args: readonly string[]): Promise<JsonObject>;@@ -278,6 +286,7 @@ interface CliDependencies {const DEFAULT_DEPENDENCIES: CliDependencies = {createSecurity: (config) => new CodexSecurity(config),environment: process.env,+ prepareAuthenticationHome: prepareCodexSecurityCredentialHome,checkForUpdate: () => checkForUpdate({ environment: process.env }),hasStoredChatGPTSignIn: async () => {const environment = Object.fromEntries(@@ -287,8 +296,23 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {name.toUpperCase() !== "CODEX_API_KEY",),);- const status = await accountStatus(resolveCodexCommand(), environment);- return status.authenticated && /\bchatgpt\b/iu.test(status.details);+ const command = resolveCodexCommand();+ if (existsSync(codexSecurityCredentialHome(process.env))) {+ const dedicatedStatus = await accountStatus(command, {+ ...environment,+ CODEX_HOME: await prepareCodexSecurityCredentialHome(process.env),+ });+ if (+ dedicatedStatus.authenticated &&+ /\bchatgpt\b/iu.test(dedicatedStatus.details)+ ) {+ return true;+ }+ }+ const ambientStatus = await accountStatus(command, environment);+ return (+ ambientStatus.authenticated && /\bchatgpt\b/iu.test(ambientStatus.details)+ );},currentDirectory: cwd,now: Date.now,@@ -305,7 +329,8 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {writeSync(stream.fd, value);},forceExit: (signal) => process.kill(process.pid, signal),- runCodex: runCodexSkillCommand,+ runCodex: (args, output, environment) =>+ runCodexSkillCommand(args, output, resolveCodexCommand(), environment),exportFindings: async (arguments_, output) => {const environment = exportEnvironment();const python = await resolvePluginPython({@@ -391,9 +416,10 @@ export async function runCodexSkillCommand(args: readonly string[],output?: SkillCommandOutput,command: CodexCommand = resolveCodexCommand(),+ processEnvironment: NodeJS.ProcessEnv = process.env,): Promise<number> {- const configuredHome = process.env["CODEX_HOME"];- const environment = { ...process.env };+ const configuredHome = processEnvironment["CODEX_HOME"];+ const environment = { ...processEnvironment };for (const name of Object.keys(environment)) {if (name.toUpperCase() === "CODEX_HOME") delete environment[name];}@@ -1459,15 +1485,34 @@ export async function main(.describe("Read an access token from stdin."),}),async run({ args, options }) {- exitCode = await dependencies.runCodex([- "login",- ...(args.action === undefined ? [] : [args.action]),- ...(options.deviceAuth ? ["--device-auth"] : []),- ...(options.withApiKey ? ["--with-api-key"] : []),- ...(options.withAccessToken ? ["--with-access-token"] : []),- "-c",- 'cli_auth_credentials_store="file"',- ]);+ const credentialHome =+ dependencies.prepareAuthenticationHome !== undefined+ ? await dependencies.prepareAuthenticationHome(+ dependencies.environment,+ )+ : codexSecurityCredentialHome(dependencies.environment);+ const authenticationEnvironment = {+ ...dependencies.environment,+ CODEX_HOME: credentialHome,+ };+ exitCode = await dependencies.runCodex(+ [+ "login",+ ...(args.action === undefined ? [] : [args.action]),+ ...(options.deviceAuth ? ["--device-auth"] : []),+ ...(options.withApiKey ? ["--with-api-key"] : []),+ ...(options.withAccessToken ? ["--with-access-token"] : []),+ ],+ undefined,+ authenticationEnvironment,+ );+ if (+ args.action === undefined &&+ exitCode === 0 &&+ dependencies.prepareAuthenticationHome !== undefined+ ) {+ await setCodexSecurityCredentialLogout(credentialHome, false);+ }if (args.action === "status") {const authentication = scanAuthentication(dependencies.environment);if (@@ -1516,11 +1561,27 @@ export async function main(destructive: true,mcp: false,async run() {- exitCode = await dependencies.runCodex([- "logout",- "-c",- 'cli_auth_credentials_store="file"',- ]);+ const credentialHome =+ dependencies.prepareAuthenticationHome !== undefined+ ? await dependencies.prepareAuthenticationHome(+ dependencies.environment,+ )+ : codexSecurityCredentialHome(dependencies.environment);+ const authenticationEnvironment = {+ ...dependencies.environment,+ CODEX_HOME: credentialHome,+ };+ exitCode = await dependencies.runCodex(+ ["logout"],+ undefined,+ authenticationEnvironment,+ );+ if (+ exitCode === 0 &&+ dependencies.prepareAuthenticationHome !== undefined+ ) {+ await setCodexSecurityCredentialLogout(credentialHome, true);+ }},}).command("info", {diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.tsindex adf712a47..2fa18a6e4 100644--- a/sdk/typescript/src/config.ts+++ b/sdk/typescript/src/config.ts@@ -22,7 +22,7 @@ export interface ScanModelConfiguration {}export const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = {- cli_auth_credentials_store: "file",+ cli_auth_credentials_store: "auto",model: "gpt-5.6-sol",model_reasoning_effort: "xhigh",features: {diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 35e3c9605..93b98c5eb 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -1,5 +1,5 @@import { execFile as execFileCallback } from "node:child_process";-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import { constants, existsSync, type Stats } from "node:fs";import {chmod,@@ -32,6 +32,7 @@ import {import { fileURLToPath } from "node:url";import { promisify } from "node:util";import { crc32 } from "node:zlib";+import { setTimeout as delay } from "node:timers/promises";import extractZip from "extract-zip";import { parse } from "smol-toml";import {@@ -57,6 +58,10 @@ const MAX_PLUGIN_COPY_ENTRIES = 4_096;const MAX_PLUGIN_COPY_FILE_SIZE = 128 * 1024 * 1024;const MAX_PLUGIN_COPY_SIZE = 512 * 1024 * 1024;const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;+const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";+const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";+const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;+const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;export interface PluginInstall {pluginRoot: string;@@ -109,6 +114,335 @@ export function codexSecurityStateDirectory(return resolve(expandHome(codexHome), "state", "plugins", "codex-security");}+export function codexSecurityCredentialHome(+ environment: ProcessEnvironment = process.env,+): string {+ return join(codexSecurityStateDirectory(environment), "codex-home");+}++export async function prepareCodexSecurityCredentialHome(+ environment: ProcessEnvironment = process.env,+ validateLocation?: (path: string) => void,+): Promise<string> {+ const path = codexSecurityCredentialHome(environment);+ try {+ try {+ await mkdir(path, { recursive: true, mode: 0o700 });+ } catch (error) {+ if (nodeErrorCode(error) === "EEXIST") {+ const existing = await lstat(path).catch(() => null);+ if (+ existing !== null &&+ (!existing.isDirectory() || existing.isSymbolicLink())+ ) {+ throw new OutputDirectoryError(+ `Codex Security credential home is not a directory: ${path}`,+ { cause: error },+ );+ }+ }+ throw error;+ }+ if ((process.umask() & 0o700) !== 0) await chmod(path, 0o700);+ const metadata = await lstat(path);+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {+ throw new OutputDirectoryError(+ `Codex Security credential home is not a directory: ${path}`,+ );+ }+ const canonical = await realpath(path);+ requireModelSafeOutputDir(canonical);+ validateLocation?.(canonical);+ await requirePrivateCredentialHome(metadata, canonical);+ return canonical;+ } catch (error) {+ if (error instanceof OutputDirectoryError) throw error;+ throw new OutputDirectoryError(+ `Unable to prepare the Codex Security credential home: ${path}`,+ { cause: error },+ );+ }+}++export async function requirePrivateCredentialHome(+ metadata: Pick<Stats, "mode" | "uid">,+ path: string,+ options: {+ platform?: NodeJS.Platform;+ secureWindowsHome?: (path: string) => Promise<void>;+ } = {},+): Promise<void> {+ if ((options.platform ?? process.platform) !== "win32") {+ requirePrivateOutputDirectory(metadata, path);+ return;+ }++ try {+ await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);+ } catch (error) {+ throw new OutputDirectoryError(+ `Unable to create a private Windows credential home: ${path}`,+ { cause: error },+ );+ }+}++async function secureWindowsCredentialHome(path: string): Promise<void> {+ const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";+ const powershell = join(+ systemRoot,+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ );+ const script = [+ "$ErrorActionPreference = 'Stop'",+ "$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_CREDENTIAL_ACL_PATH', 'Process')",+ "$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",+ "if ($null -eq $identity.User) { throw 'Unable to identify the current Windows user' }",+ "$acl = New-Object System.Security.AccessControl.DirectorySecurity",+ "$acl.SetAccessRuleProtection($true, $false)",+ "$inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit",+ "$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity.User, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)",+ "$acl.SetOwner($identity.User)",+ "$acl.SetAccessRule($rule)",+ "[System.IO.Directory]::SetAccessControl($path, $acl)",+ "$verified = [System.IO.Directory]::GetAccessControl($path)",+ "if (-not $verified.AreAccessRulesProtected) { throw 'Credential ACL still inherits access rules' }",+ "$unexpected = @($verified.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity.User.Value })",+ "if ($unexpected.Count -ne 0) { throw 'Credential ACL grants access to another identity' }",+ ].join("; ");+ await execFile(+ powershell,+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],+ {+ env: {+ ...process.env,+ CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,+ },+ encoding: "utf8",+ windowsHide: true,+ maxBuffer: 1024 * 1024,+ },+ );+}++export async function acquireCodexSecurityCredentialHomeLock(+ codexHome: string,+ signal?: AbortSignal,+): Promise<() => Promise<void>> {+ const lock = join(codexHome, CREDENTIAL_LOCK_NAME);+ const ownerPath = join(lock, "owner.json");+ const token = randomUUID();++ while (true) {+ throwIfSignalAborted(signal);+ try {+ await mkdir(lock, { mode: 0o700 });+ } catch (error) {+ if (nodeErrorCode(error) !== "EEXIST") throw error;+ if (await recoverStaleCredentialHomeLock(lock)) continue;+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });+ continue;+ }++ try {+ await writeFile(+ ownerPath,+ `${JSON.stringify({ pid: process.pid, token })}\n`,+ { encoding: "utf8", flag: "wx", mode: 0o600 },+ );+ } catch (error) {+ await rm(lock, { recursive: true, force: true }).catch(() => undefined);+ throw error;+ }++ let released = false;+ return async () => {+ if (released) return;+ const owner = JSON.parse(await readFile(ownerPath, "utf8")) as {+ token?: unknown;+ };+ if (owner.token !== token) {+ throw new PluginBootstrapError(+ "The Codex Security credential-home lock is no longer owned by this scan.",+ );+ }+ await rm(lock, { recursive: true, force: true });+ released = true;+ };+ }+}++async function recoverStaleCredentialHomeLock(lock: string): Promise<boolean> {+ const metadata = await lstat(lock).catch((error: unknown) => {+ if (nodeErrorCode(error) === "ENOENT") return null;+ throw error;+ });+ if (metadata === null) return true;+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {+ throw new OutputDirectoryError(+ `Codex Security credential-home lock is not a directory: ${lock}`,+ );+ }++ let owner: unknown;+ try {+ owner = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));+ } catch (error) {+ if (nodeErrorCode(error) !== "ENOENT" && !(error instanceof SyntaxError)) {+ throw error;+ }+ if (+ Date.now() - metadata.mtimeMs <+ INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS+ ) {+ return false;+ }+ }++ if (isRecord(owner) && typeof owner["pid"] === "number") {+ try {+ process.kill(owner["pid"], 0);+ return false;+ } catch (error) {+ if (nodeErrorCode(error) !== "ESRCH") {+ if (nodeErrorCode(error) === "EPERM") return false;+ throw error;+ }+ }+ } else if (+ Date.now() - metadata.mtimeMs <+ INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS+ ) {+ return false;+ }++ const quarantine = `${lock}.stale-${randomUUID()}`;+ try {+ await rename(lock, quarantine);+ } catch (error) {+ if (nodeErrorCode(error) === "ENOENT") return true;+ throw error;+ }+ await rm(quarantine, { recursive: true, force: true });+ return true;+}++export async function setCodexSecurityCredentialLogout(+ codexHome: string,+ loggedOut: boolean,+): Promise<void> {+ const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);+ if (!loggedOut) {+ await rm(marker, { force: true });+ return;+ }++ const temporary = join(+ codexHome,+ `.codex-security-logout-${randomUUID()}.tmp`,+ );+ try {+ const handle = await open(temporary, "wx", 0o600);+ try {+ await handle.chmod(0o600);+ await handle.writeFile("logged out\n", "utf8");+ await handle.sync();+ } finally {+ await handle.close();+ }+ await rename(temporary, marker);+ } finally {+ await rm(temporary, { force: true });+ }+}++export async function codexSecurityCredentialAllowsAmbientImport(+ codexHome: string,+): Promise<boolean> {+ try {+ const marker = await lstat(join(codexHome, CREDENTIAL_LOGOUT_MARKER));+ if (!marker.isFile() || marker.isSymbolicLink()) {+ throw new OutputDirectoryError(+ `Codex Security logout marker is not a regular file: ${codexHome}`,+ );+ }+ return false;+ } catch (error) {+ if (nodeErrorCode(error) === "ENOENT") return true;+ throw error;+ }+}++export async function codexSecurityHasStoredFileCredentials(+ codexHome: string,+): Promise<boolean> {+ const path = join(codexHome, "auth.json");+ let metadata: Stats;+ try {+ metadata = await lstat(path);+ } catch (error) {+ if (nodeErrorCode(error) === "ENOENT") return false;+ throw error;+ }+ if (!metadata.isFile() || metadata.isSymbolicLink()) {+ throw new OutputDirectoryError(+ `Codex Security stored authentication is not a regular file: ${path}`,+ );+ }+ return true;+}++export async function preserveCodexSecurityPluginRegistration(+ codexHome: string,+ config: JsonObject,+): Promise<JsonObject> {+ let existing: unknown;+ try {+ existing = parse(await readFile(join(codexHome, "config.toml"), "utf8"));+ } catch (error) {+ if (nodeErrorCode(error) === "ENOENT") return config;+ throw new PluginBootstrapError(+ "Unable to read the existing Codex Security plugin registration.",+ { cause: error },+ );+ }++ const marketplaces = isRecord(existing)+ ? existing["marketplaces"]+ : undefined;+ const plugins = isRecord(existing) ? existing["plugins"] : undefined;+ const marketplace = isRecord(marketplaces)+ ? marketplaces[MARKETPLACE_NAME]+ : undefined;+ const plugin = isRecord(plugins)+ ? plugins[`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]+ : undefined;+ const source = isRecord(marketplace) ? marketplace["source"] : undefined;+ if (+ !isRecord(marketplace) ||+ marketplace["source_type"] !== "local" ||+ typeof source !== "string" ||+ !(await sameFile(source, join(codexHome, "sdk-marketplace"))) ||+ !isRecord(plugin) ||+ plugin["enabled"] !== true+ ) {+ return config;+ }++ return {+ ...config,+ marketplaces: {+ [MARKETPLACE_NAME]: { source_type: "local", source },+ },+ plugins: {+ [`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]: { enabled: true },+ },+ };+}+export async function preparePersistentScanRoot(stateDirectory: string,repositoryName: string,@@ -444,25 +778,34 @@ export async function importAmbientAuth(return false;}await mkdir(isolatedHome, { recursive: true, mode: 0o700 });+ if (await codexSecurityHasStoredFileCredentials(isolatedHome)) return true;const destination = join(isolatedHome, "auth.json");- const temporary = join(- isolatedHome,- `.auth-${process.pid}-${Date.now()}.tmp`,- );+ const temporary = join(isolatedHome, `.auth-${randomUUID()}.tmp`);try {await copyFile(source, temporary, constants.COPYFILE_EXCL);await chmod(temporary, 0o600);- await rename(temporary, destination);+ try {+ await copyFile(temporary, destination, constants.COPYFILE_EXCL);+ } catch (error) {+ if (+ nodeErrorCode(error) === "EEXIST" &&+ (await codexSecurityHasStoredFileCredentials(isolatedHome))+ ) {+ return true;+ }+ throw error;+ }await chmod(destination, 0o600);return true;} catch (error) {- await rm(temporary, { force: true }).catch(() => undefined);throw new PluginBootstrapError("Unable to copy ambient Codex authentication.",{cause: error,},);+ } finally {+ await rm(temporary, { force: true }).catch(() => undefined);}}@@ -719,6 +1062,162 @@ export async function createMarketplace(return marketplace;}+async function pluginProjectionFingerprint(+ root: string,+ signal?: AbortSignal,+): Promise<string> {+ throwIfSignalAborted(signal);+ const canonical = await realpath(root);+ const contractPath = join(+ canonical,+ ".internal",+ "external-promotion",+ "external-projection-contract.json",+ );+ let paths: string[];++ if (+ canonical === (await bundledPluginRoot()) &&+ (await isRegularFile(contractPath))+ ) {+ let contract: unknown;+ try {+ contract = JSON.parse(await readFile(contractPath, "utf8"));+ } catch (error) {+ throw new PluginBootstrapError(+ `Invalid plugin projection contract: ${contractPath}`,+ { cause: error },+ );+ }+ const shipped = isRecord(contract) ? contract["shippedExact"] : undefined;+ if (+ !Array.isArray(shipped) ||+ !shipped.every((path) => typeof path === "string")+ ) {+ throw new PluginBootstrapError(+ "Plugin projection contract must contain shippedExact paths.",+ );+ }+ paths = [+ ...new Set(+ [".codex-plugin/plugin.json", ...shipped]+ .filter((path) => !path.startsWith("sdk/"))+ .map((path) => safeArchivePath(path)),+ ),+ ];+ } else {+ paths = [];+ const pending = [canonical];+ let entries = 0;+ while (pending.length > 0) {+ throwIfSignalAborted(signal);+ const path = pending.pop()!;+ const metadata = await lstat(path);+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {+ throw new PluginBootstrapError(+ `Plugin source exceeds the copy entry limit: ${path}`,+ );+ }+ if (metadata.isSymbolicLink()) {+ throw new PluginBootstrapError(+ `Plugin contains an unsafe source path: ${path}`,+ );+ }+ if (metadata.isDirectory()) {+ for (const entry of await readdir(path)) {+ pending.push(join(path, entry));+ }+ } else if (metadata.isFile()) {+ paths.push(relative(canonical, path).split(sep).join("/"));+ } else {+ throw new PluginBootstrapError(+ `Plugin contains a non-regular file: ${path}`,+ );+ }+ }+ }++ paths.sort();+ const fingerprint = createHash("sha256");+ let totalSize = 0;+ for (const relativePath of paths) {+ throwIfSignalAborted(signal);+ const path = join(canonical, ...relativePath.split("/"));+ const metadata = await lstat(path);+ if (!metadata.isFile() || metadata.isSymbolicLink()) {+ throw new PluginBootstrapError(+ `Plugin projection contains an unsafe source path: ${path}`,+ );+ }+ if (metadata.size > MAX_PLUGIN_COPY_FILE_SIZE) {+ throw new PluginBootstrapError(+ `Plugin source exceeds the per-file safety limit: ${path}`,+ );+ }+ totalSize += metadata.size;+ if (totalSize > MAX_PLUGIN_COPY_SIZE) {+ throw new PluginBootstrapError(+ "Plugin source exceeds the copy safety limit.",+ );+ }+ const handle = await open(+ path,+ constants.O_RDONLY |+ (process.platform === "win32"+ ? 0+ : constants.O_NOFOLLOW | constants.O_NONBLOCK),+ );+ try {+ if (!samePluginFile(metadata, await handle.stat())) {+ throw new PluginBootstrapError(+ `Plugin source changed before its integrity could be verified: ${path}`,+ );+ }+ const contents = await readExactly(handle, metadata.size, 0, signal);+ if (!samePluginFile(metadata, await handle.stat())) {+ throw new PluginBootstrapError(+ `Plugin source changed while its integrity was being verified: ${path}`,+ );+ }+ fingerprint.update(relativePath);+ fingerprint.update("\0");+ fingerprint.update(String(metadata.size));+ fingerprint.update("\0");+ fingerprint.update(contents);+ fingerprint.update("\0");+ } finally {+ await handle.close();+ }+ }+ return fingerprint.digest("hex");+}++async function codexSecurityPluginRegistration(+ codexHome: string,+): Promise<{ marketplace: boolean; plugin: boolean }> {+ let config: unknown;+ try {+ config = parse(await readFile(join(codexHome, "config.toml"), "utf8"));+ } catch (error) {+ if (nodeErrorCode(error) === "ENOENT") {+ return { marketplace: false, plugin: false };+ }+ throw new PluginBootstrapError(+ "Unable to inspect the existing Codex Security plugin registration.",+ { cause: error },+ );+ }+ const marketplaces = isRecord(config) ? config["marketplaces"] : undefined;+ const plugins = isRecord(config) ? config["plugins"] : undefined;+ return {+ marketplace:+ isRecord(marketplaces) && isRecord(marketplaces[MARKETPLACE_NAME]),+ plugin:+ isRecord(plugins) &&+ isRecord(plugins[`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]),+ };+}+export function resolveCodexCommand(): CodexCommand {const { packageName, targetTriple } = codexPlatformPackage();const require = createRequire(import.meta.url);@@ -784,13 +1283,97 @@ export async function bootstrapPlugin(): Promise<PluginInstall> {const root = await realpath(pluginRoot);const { name, version } = await pluginMetadata(root);- const marketplace = await createMarketplace(codexHome, root, options.signal);+ const existingMarketplace = join(codexHome, "sdk-marketplace");+ let upgradeExistingPlugin = false;+ let repairIncompletePlugin = false;+ let installedRoot: string | null = null;+ try {+ await verifyPluginRegistration(codexHome, existingMarketplace);+ installedRoot = await findInstalledPlugin(codexHome);+ } catch (error) {+ throwIfSignalAborted(options.signal);+ if (+ !(error instanceof PluginBootstrapError) &&+ nodeErrorCode(error) !== "ENOENT"+ ) {+ throw error;+ }+ const marketplace = await lstat(existingMarketplace).catch(+ (failure: unknown) => {+ if (nodeErrorCode(failure) === "ENOENT") return null;+ throw failure;+ },+ );+ if (+ marketplace !== null &&+ (!marketplace.isDirectory() || marketplace.isSymbolicLink())+ ) {+ throw new PluginBootstrapError(+ `Codex Security marketplace is not a safe directory: ${existingMarketplace}`,+ );+ }+ const registration = await codexSecurityPluginRegistration(codexHome);+ repairIncompletePlugin =+ marketplace !== null || registration.marketplace || registration.plugin;+ }++ if (installedRoot !== null) {+ const installed = await pluginMetadata(installedRoot);+ if (installed.name === name && installed.version === version) {+ const [selectedFingerprint, marketplaceFingerprint] = await Promise.all([+ pluginProjectionFingerprint(root, options.signal),+ pluginProjectionFingerprint(+ join(existingMarketplace, "plugins", PLUGIN_NAME),+ options.signal,+ ),+ ]);+ if (selectedFingerprint === marketplaceFingerprint) {+ return {+ pluginRoot: root,+ marketplaceRoot: existingMarketplace,+ installedRoot,+ marketplaceName: MARKETPLACE_NAME,+ name,+ version,+ };+ }+ }+ upgradeExistingPlugin = true;+ }++ throwIfSignalAborted(options.signal);const command = options.codexCommand ?? resolveCodexCommand();const environment = {...(options.environment ?? process.env),CODEX_HOME: codexHome,};const run = options.runCodex ?? runCodex;+ if (upgradeExistingPlugin || repairIncompletePlugin) {+ const registration = await codexSecurityPluginRegistration(codexHome);+ if (registration.plugin) {+ await run(+ command,+ ["plugin", "remove", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`],+ environment,+ options.signal,+ );+ throwIfSignalAborted(options.signal);+ }+ if (registration.marketplace) {+ await run(+ command,+ ["plugin", "marketplace", "remove", MARKETPLACE_NAME],+ environment,+ options.signal,+ );+ throwIfSignalAborted(options.signal);+ }+ throwIfSignalAborted(options.signal);+ await rm(existingMarketplace, { recursive: true, force: true });+ throwIfSignalAborted(options.signal);+ }++ const marketplace = await createMarketplace(codexHome, root, options.signal);await run(command,["plugin", "marketplace", "add", marketplace],@@ -804,8 +1387,8 @@ export async function bootstrapPlugin(options.signal,);await verifyPluginRegistration(codexHome, marketplace);- const installedRoot = await findInstalledPlugin(codexHome);- const installed = await pluginMetadata(installedRoot);+ const verifiedInstalledRoot = await findInstalledPlugin(codexHome);+ const installed = await pluginMetadata(verifiedInstalledRoot);if (installed.name !== name || installed.version !== version) {throw new PluginBootstrapError("Installed Codex Security plugin metadata does not match the selected plugin.",@@ -814,7 +1397,7 @@ export async function bootstrapPlugin(return {pluginRoot: root,marketplaceRoot: marketplace,- installedRoot,+ installedRoot: verifiedInstalledRoot,marketplaceName: MARKETPLACE_NAME,name,version,diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.tsindex 12230c3f6..bcea7ed94 100644--- a/sdk/typescript/src/scan-comparison.ts+++ b/sdk/typescript/src/scan-comparison.ts@@ -8,7 +8,13 @@ import {type TurnOptions,} from "@openai/codex-sdk";import { z } from "incur";+import { accountStatus } from "./auth.js";import { CodexSecurityError } from "./errors.js";+import {+ codexSecurityCredentialHome,+ prepareCodexSecurityCredentialHome,+ resolveCodexCommand,+} from "./runtime.js";type Finding = { occurrenceId: string } & Record<string, unknown>;@@ -73,7 +79,11 @@ export async function matchScanFindings(const codex =options.codex ??new Codex({- env: comparisonEnvironment(options.environment),+ env: await comparisonEnvironment(+ options.environment,+ accountStatus,+ options.signal,+ ),config: {allow_login_shell: false,"features.apps": false,@@ -134,14 +144,47 @@ function comparisonPrompt(input: ScanComparisonInput): string {].join("\n");}-function comparisonEnvironment(+export async function comparisonEnvironment(source: NodeJS.ProcessEnv = process.env,-): Record<string, string> {+ nativeAccountStatus: typeof accountStatus = accountStatus,+ signal?: AbortSignal,+): Promise<Record<string, string>> {+ signal?.throwIfAborted();const environment = Object.fromEntries(Object.entries(source).filter((entry): entry is [string, string] => entry[1] !== undefined,),);+ if (+ Object.entries(environment).some(+ ([name, value]) =>+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()) &&+ value.trim().length > 0,+ )+ ) {+ return environment;+ }+ const credentialHome = codexSecurityCredentialHome(source);+ if (existsSync(credentialHome)) {+ const canonicalCredentialHome =+ await prepareCodexSecurityCredentialHome(source);+ signal?.throwIfAborted();+ const storedEnvironment: Record<string, string> = {+ ...environment,+ CODEX_HOME: canonicalCredentialHome,+ };+ for (const key of Object.keys(storedEnvironment)) {+ if (["OPENAI_API_KEY", "CODEX_API_KEY"].includes(key.toUpperCase())) {+ delete storedEnvironment[key];+ }+ }+ const status = await nativeAccountStatus(+ resolveCodexCommand(),+ storedEnvironment,+ signal,+ );+ if (status.authenticated) return storedEnvironment;+ }const configuredHome = environment["CODEX_HOME"]?.trim();const codexHome = configuredHome? configuredHome === "~"diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex d835e2a99..13e731523 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -40,7 +40,10 @@ import {scanRuntimeCodexConfig,} from "../src/api.js";import { writeCodexConfig, type JsonObject } from "../src/config.js";-import { runWorkbench } from "../src/runtime.js";+import {+ runWorkbench,+ setCodexSecurityCredentialLogout,+} from "../src/runtime.js";import { normalizeTarget } from "../src/targets.js";import { INTEGRATION_TARGET, PLUGIN_ROOT } from "./plugin-root.js";@@ -268,6 +271,25 @@ describe("CodexSecurity orchestration", () => {});});+ test("keeps persistent credentials read-only within writable scan state", () => {+ const stateDirectory = join(tmpdir(), "codex-security-persistent-state");+ const credentialHome = join(stateDirectory, "codex-home");+ const config = scanRuntimeCodexConfig({}, stateDirectory, credentialHome);++ expect(config).toMatchObject({+ permissions: {+ codex_security_scan: {+ filesystem: {+ ":root": "read",+ ":workspace_roots": "write",+ [stateDirectory]: "write",+ [credentialHome]: "read",+ },+ },+ },+ });+ });+test("projects only capability and trust metadata into the readable preflight config", async () => {const root = await temporaryDirectory();const configPath = join(root, "config-preflight.toml");@@ -2232,7 +2254,7 @@ describe("CodexSecurity orchestration", () => {await client.close();});- test("creates a private readable preflight snapshot outside the credential home for a real runtime", async () => {+ test("keeps a private preflight snapshot isolated from persistent credentials", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const ambientHome = join(root, "ambient-codex-home");@@ -2290,6 +2312,13 @@ describe("CodexSecurity orchestration", () => {":workspace_roots": "write",[join(ambientHome, "state", "plugins", "codex-security")]:"write",+ [join(+ ambientHome,+ "state",+ "plugins",+ "codex-security",+ "codex-home",+ )]: "read",},},},@@ -2370,7 +2399,143 @@ describe("CodexSecurity orchestration", () => {await client.close();}expect(existsSync(capturedConfigPath!)).toBe(false);- expect(existsSync(capturedCodexHome!)).toBe(false);+ expect(capturedCodexHome).toBe(+ join(ambientHome, "state", "plugins", "codex-security", "codex-home"),+ );+ expect(existsSync(capturedCodexHome!)).toBe(true);+ });++ test("reuses keyring-compatible credentials across separate scan clients", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const ambientHome = join(root, "ambient-codex-home");+ const stateDirectory = join(root, "state");+ const credentialHome = join(stateDirectory, "codex-home");+ const runtimeHomes: string[] = [];+ await mkdir(repository);+ await mkdir(ambientHome);+ await writeFile(join(ambientHome, "auth.json"), "{}\n");++ for (const index of [0, 1]) {+ const scanDir = join(root, `scan-${index}`);+ await mkdir(scanDir, { mode: 0o700 });+ const client = new TestClient(+ { pluginPath: PLUGIN_ROOT },+ {+ environment: {+ CODEX_HOME: ambientHome,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ },+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => {+ runtimeHomes.push(options.env?.["CODEX_HOME"] ?? "");+ throw new Error("persistent credential scan reached");+ },+ },+ );++ try {+ await expect(client.run(repository)).rejects.toThrow(+ "persistent credential scan reached",+ );+ } finally {+ await client.close();+ }+ expect(existsSync(credentialHome)).toBe(true);+ }++ expect(runtimeHomes).toEqual([credentialHome, credentialHome]);+ });++ test("serializes parallel scans sharing a managed credential home", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const ambientHome = join(root, "ambient-codex-home");+ const stateDirectory = join(root, "state");+ const credentialHome = join(stateDirectory, "codex-home");+ await mkdir(repository);+ await mkdir(ambientHome);+ await writeFile(join(ambientHome, "auth.json"), "{}\n");+ let activeScans = 0;+ let maximumActiveScans = 0;++ const clients = await Promise.all(+ [0, 1].map(async (index) => {+ const scanDir = join(root, `parallel-scan-${index}`);+ await mkdir(scanDir, { mode: 0o700 });+ return new TestClient(+ {+ pluginPath: PLUGIN_ROOT,+ codexOverrides: {+ model: index === 0 ? "gpt-5.6-sol" : "gpt-5.6-terra",+ },+ },+ {+ environment: {+ CODEX_HOME: ambientHome,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ },+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => {+ expect(options.env?.["CODEX_HOME"]).toBe(credentialHome);+ return {+ startThread: () => ({+ id: null,+ async runStreamed() {+ activeScans += 1;+ maximumActiveScans = Math.max(+ maximumActiveScans,+ activeScans,+ );+ try {+ const expectedModel =+ index === 0 ? "gpt-5.6-sol" : "gpt-5.6-terra";+ const before = parseToml(+ await readFile(+ join(credentialHome, "config.toml"),+ "utf8",+ ),+ );+ expect(before["model"]).toBe(expectedModel);+ await new Promise((resolve) => setTimeout(resolve, 40));+ const after = parseToml(+ await readFile(+ join(credentialHome, "config.toml"),+ "utf8",+ ),+ );+ expect(after["model"]).toBe(expectedModel);+ throw new Error("parallel managed scan reached");+ } finally {+ activeScans -= 1;+ }+ },+ }),+ };+ },+ },+ );+ }),+ );++ try {+ await Promise.all(+ clients.map(+ async (client) =>+ await expect(client.run(repository)).rejects.toThrow(+ "parallel managed scan reached",+ ),+ ),+ );+ expect(existsSync(credentialHome)).toBe(true);+ expect(maximumActiveScans).toBe(1);+ } finally {+ await Promise.all(clients.map(async (client) => await client.close()));+ }});test("rejects a shell-visible plugin root inside CODEX_HOME", async () => {@@ -2852,11 +3017,12 @@ describe("CodexSecurity orchestration", () => {await client.close();});- test("persists an ambient API key without filtering Codex-owned credentials", async () => {+ test("passes environment API keys transiently without native login or keyring persistence", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");const fakeCodex = join(root, "codex.mjs");+ const nativeLoginMarker = join(root, "native-api-key-login");const scanDir = join(root, "scan");await mkdir(repository);await mkdir(codexHome);@@ -2864,13 +3030,9 @@ describe("CodexSecurity orchestration", () => {await writeFile(fakeCodex,`-if (process.argv.slice(2).join(" ") !== "login --with-api-key") {- process.exitCode = 2;-} else {- let apiKey = "";- for await (const chunk of process.stdin) apiKey += chunk;- if (apiKey.trim() !== "ambient-key") process.exitCode = 3;-}+import { writeFileSync } from "node:fs";+writeFileSync(${JSON.stringify(nativeLoginMarker)}, "native login was invoked");+process.exitCode = 2;`,);let codexOptions: CodexOptions | null = null;@@ -2941,14 +3103,17 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {source: "OPENAI_API_KEY",verified: false,});- expect((codexOptions as CodexOptions | null)?.apiKey).toBeUndefined();+ expect((codexOptions as CodexOptions | null)?.apiKey).toBe("ambient-key");expect((codexOptions as CodexOptions | null)?.codexPathOverride,).toBeUndefined();- expect((codexOptions as CodexOptions | null)?.env).toMatchObject({- OpenAi_Api_Key: "forwarded-openai-key",- codex_api_key: "forwarded-codex-key",- });+ expect(+ Object.keys((codexOptions as CodexOptions | null)?.env ?? {}).some(+ (name) =>+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),+ ),+ ).toBe(false);+ expect(existsSync(nativeLoginMarker)).toBe(false);expect(pythonEnvironment).toMatchObject({openai_api_key: "stale-key",OPENAI_API_KEY: "ambient-key",@@ -2958,6 +3123,125 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {await client.close();});+ test("accepts native keyring authentication without an auth.json file", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "managed-codex-home");+ const scanDir = join(root, "scan");+ const fakeCodex = join(root, "managed-codex.mjs");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(+ fakeCodex,+ `+if (process.argv.slice(2).join(" ") !== "login status") {+ process.exitCode = 2;+} else if (process.env.CODEX_HOME !== ${JSON.stringify(codexHome)}) {+ process.exitCode = 3;+} else {+ console.log("Logged in using ChatGPT");+}+`,+ );++ const client = new TestClient(+ {},+ {+ environment: { CODEX_SECURITY_STATE_DIR: join(root, "state") },+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ environment: { CODEX_HOME: codexHome },+ credentialsAvailable: false,+ }),+ resolveCodexCommand: () => ({+ command: process.execPath,+ prefixArgs: [fakeCodex],+ }),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: () => {+ throw new Error("managed keyring scan reached");+ },+ },+ );++ try {+ await expect(client.run(repository, { auth: "chatgpt" })).rejects.toThrow(+ "managed keyring scan reached",+ );+ expect(existsSync(join(codexHome, "auth.json"))).toBe(false);+ } finally {+ await client.close();+ }+ });++ test("recreates isolated and managed runtimes when scan authentication changes", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const ambientHome = join(root, "ambient-codex-home");+ const stateDirectory = join(root, "state");+ const dedicatedHome = join(stateDirectory, "codex-home");+ const scanDir = join(root, "scan");+ const ambientAuthentication = '{"auth_mode":"chatgpt"}\n';+ await mkdir(repository);+ await mkdir(ambientHome);+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(join(ambientHome, "auth.json"), ambientAuthentication);+ const runs: Array<{ home: string; apiKey?: string }> = [];+ const client = new TestClient(+ { pluginPath: PLUGIN_ROOT },+ {+ environment: {+ CODEX_HOME: ambientHome,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ OPENAI_API_KEY: "synthetic-transient-key",+ },+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => {+ runs.push({+ home: options.env?.["CODEX_HOME"] ?? "",+ ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),+ });+ throw new Error("authentication-selected scan reached");+ },+ },+ );++ try {+ await expect(client.run(repository, { auth: "api-key" })).rejects.toThrow(+ "authentication-selected scan reached",+ );+ const firstIsolatedHome = runs[0]?.home;+ expect(firstIsolatedHome).toBeDefined();+ expect(firstIsolatedHome).not.toBe(dedicatedHome);+ expect(runs[0]?.apiKey).toBe("synthetic-transient-key");++ await expect(client.run(repository, { auth: "chatgpt" })).rejects.toThrow(+ "authentication-selected scan reached",+ );+ expect(runs[1]).toEqual({ home: dedicatedHome });+ expect(await readFile(join(dedicatedHome, "auth.json"), "utf8")).toBe(+ ambientAuthentication,+ );+ expect(existsSync(firstIsolatedHome!)).toBe(false);++ await expect(client.run(repository, { auth: "api-key" })).rejects.toThrow(+ "authentication-selected scan reached",+ );+ expect(runs[2]?.home).not.toBe(dedicatedHome);+ expect(runs[2]?.apiKey).toBe("synthetic-transient-key");+ expect(await readFile(join(dedicatedHome, "auth.json"), "utf8")).toBe(+ ambientAuthentication,+ );+ } finally {+ await client.close();+ }+ });+test("does not cache an environment key as reusable file authentication", async () => {let imported = false;await expect(@@ -2983,32 +3267,75 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {).resolves.toBe(true);});+ test("preserves an explicit stored sign-in instead of reimporting ambient authentication", async () => {+ const root = await temporaryDirectory();+ const ambientHome = join(root, "ambient-home");+ const credentialHome = join(root, "credential-home");+ await mkdir(ambientHome);+ await mkdir(credentialHome);+ await writeFile(join(ambientHome, "auth.json"), '{"token":"ambient"}\n');+ await writeFile(+ join(credentialHome, "auth.json"),+ '{"token":"explicit"}\n',+ );+ let imported = false;++ await expect(+ initialCredentialsAvailable({}, ambientHome, credentialHome, async () => {+ imported = true;+ return true;+ }),+ ).resolves.toBe(true);++ expect(imported).toBe(false);+ expect(await readFile(join(credentialHome, "auth.json"), "utf8")).toBe(+ '{"token":"explicit"}\n',+ );+ });++ test("does not reimport ambient credentials after an explicit logout", async () => {+ const root = await temporaryDirectory();+ const ambientHome = join(root, "ambient-home");+ const credentialHome = join(root, "credential-home");+ await mkdir(ambientHome);+ await mkdir(credentialHome);+ await writeFile(join(ambientHome, "auth.json"), '{"token":"ambient"}\n');+ await setCodexSecurityCredentialLogout(credentialHome, true);+ let imported = false;++ await expect(+ initialCredentialsAvailable({}, ambientHome, credentialHome, async () => {+ imported = true;+ return true;+ }),+ ).resolves.toBe(false);+ expect(imported).toBe(false);++ await setCodexSecurityCredentialLogout(credentialHome, false);+ await expect(+ initialCredentialsAvailable(+ {},+ ambientHome,+ credentialHome,+ async () => true,+ ),+ ).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 selectedApiKeys: Array<string | undefined> = [];const codexEnvironments: Array<Record<string, string> | undefined> = [];const client = new TestClient({},@@ -3021,14 +3348,11 @@ writeFileSync(${JSON.stringify(join(codexHome, "auth.json"))}, JSON.stringify({...preparedRuntime(codexHome),credentialsAvailable: false,}),- resolveCodexCommand: () => ({- command: process.execPath,- prefixArgs: [fakeCodex],- }),resolvePluginPython: async () => "/managed/python",prepareOutputDir: async () => scanDir,repositoryRevision: async () => "deadbeef",createCodex: (options: CodexOptions) => {+ selectedApiKeys.push(options.apiKey);codexEnvironments.push(options.env);throw new Error("scan reached");},@@ -3042,12 +3366,8 @@ writeFileSync(${JSON.stringify(join(codexHome, "auth.json"))}, JSON.stringify({},}),).rejects.toThrow("scan reached");- expect(- JSON.parse(await readFile(join(codexHome, "auth.json"), "utf8")),- ).toEqual({- auth_mode: "api-key",- configured: true,- });+ expect(existsSync(join(codexHome, "auth.json"))).toBe(false);+ expect(selectedApiKeys).toEqual(["synthetic-openai-key"]);await expect(client.run(repository, {@@ -3064,6 +3384,7 @@ writeFileSync(${JSON.stringify(join(codexHome, "auth.json"))}, JSON.stringify({{ method: "api_key", source: "OPENAI_API_KEY", verified: false },{ method: "stored_credentials", verified: false },]);+ expect(selectedApiKeys).toEqual(["synthetic-openai-key", undefined]);expect(Object.keys(codexEnvironments.at(-1) ?? {}).some((name) =>["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),@@ -3076,24 +3397,14 @@ writeFileSync(${JSON.stringify(join(codexHome, "auth.json"))}, JSON.stringify({const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");- const fakeCodex = join(root, "codex.mjs");- const keyLog = join(root, "keys.txt");const scanDir = join(root, "scan");await mkdir(repository);await mkdir(codexHome);await mkdir(scanDir, { mode: 0o700 });- await writeFile(- fakeCodex,- `-import { appendFileSync } from "node:fs";-let apiKey = "";-for await (const chunk of process.stdin) apiKey += chunk;-appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");-`,- );const environment: Record<string, string | undefined> = {OPENAI_API_KEY: "first-key",};+ const selectedKeys: Array<string | undefined> = [];const client = new TestClient({},{@@ -3102,14 +3413,11 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");...preparedRuntime(codexHome),credentialsAvailable: false,}),- resolveCodexCommand: () => ({- command: process.execPath,- prefixArgs: [fakeCodex],- }),resolvePluginPython: async () => "/managed/python",prepareOutputDir: async () => scanDir,repositoryRevision: async () => "deadbeef",- createCodex: () => {+ createCodex: (options: CodexOptions) => {+ selectedKeys.push(options.apiKey);throw new Error("scan reached");},},@@ -3119,7 +3427,7 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");environment["OPENAI_API_KEY"] = "second-key";await expect(client.run(repository)).rejects.toThrow("scan reached");- expect(await readFile(keyLog, "utf8")).toBe("first-key\nsecond-key\n");+ expect(selectedKeys).toEqual(["first-key", "second-key"]);await client.close();});@@ -3495,9 +3803,10 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");return await originalRm(...args);},}));+ const stateDirectory = join(root, "state");const client = new TestClient({ pluginPath: join(root, "missing-plugin") },- { environment: {} },+ { environment: { CODEX_SECURITY_STATE_DIR: stateDirectory } },);try {@@ -3520,7 +3829,8 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");}),]),);- expect(attempted).toHaveLength(2);+ expect(attempted).toHaveLength(1);+ expect(existsSync(join(stateDirectory, "codex-home"))).toBe(true);} finally {mock.module("node:fs/promises", () => ({...fsPromises,@@ -3658,12 +3968,14 @@ if (args === "login --with-api-key") {const login = await client.loginChatGPT();await expect(login.wait()).resolves.toMatchObject({ success: true });await client.run(repository);- expect((codexOptions as CodexOptions | null)?.apiKey).toBeUndefined();- expect((codexOptions as CodexOptions | null)?.env).toMatchObject({- OPENAI_API_KEY: "ambient-key",- CODEX_API_KEY: "secondary-ambient-key",- });- expect(await readFile(keyLog, "utf8")).toBe("secret-key\nambient-key\n");+ expect((codexOptions as CodexOptions | null)?.apiKey).toBe("ambient-key");+ expect(+ Object.keys((codexOptions as CodexOptions | null)?.env ?? {}).some(+ (name) =>+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),+ ),+ ).toBe(false);+ expect(await readFile(keyLog, "utf8")).toBe("secret-key\n");} finally {await client.close();}diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex 210848b4c..40f12a271 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -1,10 +1,22 @@import { spawnSync } from "node:child_process";-import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";+import {+ mkdir,+ mkdtemp,+ realpath,+ rm,+ stat,+ symlink,+ writeFile,+} from "node:fs/promises";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 {+ codexSecurityCredentialAllowsAmbientImport,+ prepareCodexSecurityCredentialHome,+} from "../src/runtime.js";import {capture,dependencies,@@ -13,7 +25,7 @@ import {} from "./support/cli.js";describe("CLI authentication", () => {- test("delegates login and logout to bundled Codex without starting a scan", async () => {+ test("delegates login and logout without overriding managed credential storage", async () => {const cases = [["login"],["login", "--device-auth"],@@ -35,17 +47,90 @@ describe("CLI authentication", () => {return 17;};expect(await main(argv, stdout.stream, stderr.stream, deps)).toBe(17);- expect(forwarded).toEqual([- argv[0],- ...argv.slice(1),- "-c",- 'cli_auth_credentials_store="file"',- ]);+ expect(forwarded).toEqual([argv[0], ...argv.slice(1)]);expect(stdout.text()).toBe("");expect(stderr.text()).toBe("");}});+ test("uses the same stable credential home for login, status, and logout", async () => {+ const stateDirectory = join(tmpdir(), "codex-security-managed-auth-state");+ const expectedHome = join(stateDirectory, "codex-home");++ for (const argv of [["login"], ["login", "status"], ["logout"]] as const) {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },+ });+ let forwarded: readonly string[] | undefined;+ let environment: NodeJS.ProcessEnv | undefined;+ deps.runCodex = async (args, _output, authEnvironment) => {+ forwarded = args;+ environment = authEnvironment;+ return 0;+ };++ expect(await main(argv, stdout.stream, stderr.stream, deps)).toBe(0);+ expect(forwarded).toEqual([...argv]);+ expect(environment?.["CODEX_HOME"]).toBe(expectedHome);+ expect(environment?.["CODEX_SECURITY_STATE_DIR"]).toBe(stateDirectory);+ }+ });++ test.skipIf(process.platform === "win32")(+ "validates and canonicalizes the credential home for status and logout",+ async () => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-cli-managed-auth-")),+ );+ try {+ const actualState = join(root, "actual-state");+ const linkedState = join(root, "linked-state");+ await mkdir(actualState, { mode: 0o700 });+ await symlink(actualState, linkedState, "dir");+ const expectedHome = join(actualState, "codex-home");++ for (const argv of [["login", "status"], ["logout"]] as const) {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: { CODEX_SECURITY_STATE_DIR: linkedState },+ });+ deps.prepareAuthenticationHome = prepareCodexSecurityCredentialHome;+ let forwardedHome: string | undefined;+ deps.runCodex = async (_args, _output, environment) => {+ forwardedHome = environment?.["CODEX_HOME"];+ return 0;+ };++ expect(await main(argv, stdout.stream, stderr.stream, deps)).toBe(0);+ expect(forwardedHome).toBe(expectedHome);+ }++ expect(+ await codexSecurityCredentialAllowsAmbientImport(expectedHome),+ ).toBe(false);++ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: { CODEX_SECURITY_STATE_DIR: linkedState },+ });+ deps.prepareAuthenticationHome = prepareCodexSecurityCredentialHome;+ deps.runCodex = async () => 0;+ expect(await main(["login"], stdout.stream, stderr.stream, deps)).toBe(+ 0,+ );+ expect(+ await codexSecurityCredentialAllowsAmbientImport(expectedHome),+ ).toBe(true);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ },+ );+test("explains when an environment API key overrides the stored login", async () => {for (const [environment, expectedSource] of [[{ OPENAI_API_KEY: "sk-proj-SYNTHETIC_SECRET_123" }, "OPENAI_API_KEY"],@@ -481,6 +566,18 @@ describe("CLI authentication", () => {[" ", defaultHome, root],] as const)),] as const) {+ const credentialHome = join(+ expectedHome,+ "state",+ "plugins",+ "codex-security",+ "codex-home",+ );+ await mkdir(credentialHome, { recursive: true, mode: 0o700 });+ await writeFile(+ join(credentialHome, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );const environment = {...process.env,HOME: userHome,@@ -501,7 +598,7 @@ describe("CLI authentication", () => {},).status;expect(run(["login", "--with-api-key"], "synthetic-key\n")).toBe(0);- expect(await stat(join(expectedHome, "auth.json"))).toBeDefined();+ expect(await stat(join(credentialHome, "auth.json"))).toBeDefined();await expect(stat(join(repository, "auth.json"))).rejects.toThrow();expect(run(["login", "status"])).toBe(0);expect(run(["logout"])).toBe(0);diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.tsindex cdfa1ec38..a03839f3f 100644--- a/sdk/typescript/tests-ts/config.test.ts+++ b/sdk/typescript/tests-ts/config.test.ts@@ -62,6 +62,13 @@ function runPinnedCodex(codexHome: string, arguments_: readonly string[]) {}describe("Codex configuration", () => {+ test("lets Codex honor native and managed credential storage", async () => {+ expect(DEFAULT_CODEX_CONFIG["cli_auth_credentials_store"]).toBe("auto");+ expect((await mergedCodexConfig({}))["cli_auth_credentials_store"]).toBe(+ "auto",+ );+ });+test("deep-merges native multi-agent v2 defaults", async () => {const merged = await mergedCodexConfig({codexOverrides: {diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex e6e167722..aa334915e 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -45,14 +45,20 @@ import {validateOutputDir,} from "../src/index.js";import {+ acquireCodexSecurityCredentialHomeLock,bundledPluginCandidates,+ codexSecurityCredentialAllowsAmbientImport,+ codexSecurityCredentialHome,codexSecurityStateDirectory,codexPlatformPackage,isPythonPathCandidate,planOutputArchive,+ prepareCodexSecurityCredentialHome,preparePersistentScanRoot,+ requirePrivateCredentialHome,requirePrivateOutputDirectory,runWorkbench,+ setCodexSecurityCredentialLogout,} from "../src/runtime.js";import { PLUGIN_ROOT } from "./plugin-root.js";@@ -732,6 +738,43 @@ describe("plugin runtime preparation", () => {}});+ test("never replaces an explicitly stored sign-in with ambient credentials", async () => {+ const root = await temporaryDirectory();+ const ambient = join(root, "ambient");+ const isolated = join(root, "isolated");+ await mkdir(ambient);+ await mkdir(isolated);+ await writeFile(join(ambient, "auth.json"), '{"token":"ambient"}\n');+ await writeFile(join(isolated, "auth.json"), '{"token":"explicit"}\n');++ expect(await importAmbientAuth(ambient, isolated)).toBe(true);+ expect(await readFile(join(isolated, "auth.json"), "utf8")).toBe(+ '{"token":"explicit"}\n',+ );+ });++ test("uses unique temporary files for parallel ambient credential imports", async () => {+ const root = await temporaryDirectory();+ const ambient = join(root, "ambient");+ const isolated = join(root, "isolated");+ await mkdir(ambient);+ await writeFile(join(ambient, "auth.json"), '{"token":"ambient"}\n');++ const imports = await Promise.all(+ Array.from({ length: 8 }, async () =>+ importAmbientAuth(ambient, isolated),+ ),+ );++ expect(imports).toEqual(Array.from({ length: 8 }, () => true));+ expect(await readFile(join(isolated, "auth.json"), "utf8")).toBe(+ '{"token":"ambient"}\n',+ );+ expect(+ (await readdir(isolated)).filter((path) => path.startsWith(".auth-")),+ ).toEqual([]);+ });+test.skipIf(process.platform === "win32")("imports symlink-backed ambient auth",async () => {@@ -803,6 +846,319 @@ describe("plugin runtime preparation", () => {]);expect(install.installedRoot).toBe(installed);expect(install.version).toBe("1.2.3");++ const reused = await bootstrapPlugin(home, selected, {+ codexCommand: { command: "/codex", prefixArgs: [] },+ runCodex: async () => {+ throw new Error("must not reinstall an existing Codex Security plugin");+ },+ });+ expect(reused.installedRoot).toBe(installed);+ expect(reused.version).toBe("1.2.3");+ expect(calls).toHaveLength(2);+ });++ test("repairs an interrupted marketplace without deleting stored credentials", async () => {+ const root = await temporaryDirectory();+ const selected = await plugin(root);+ const home = join(root, "home");+ const marketplace = join(home, "sdk-marketplace");+ const installed = join(+ home,+ "plugins",+ "cache",+ "codex-security-sdk",+ "codex-security",+ "1.2.3",+ );+ await mkdir(join(marketplace, ".agents", "plugins"), {+ recursive: true,+ });+ await writeFile(+ join(marketplace, ".agents", "plugins", "marketplace.json"),+ "interrupted installation\n",+ );+ await writeFile(join(home, "config.toml"), "[features]\nplugins = true\n");+ await writeFile(join(home, "auth.json"), '{"token":"preserved"}\n');+ const calls: string[][] = [];++ const result = await bootstrapPlugin(home, selected, {+ codexCommand: { command: "/codex", prefixArgs: [] },+ runCodex: async (_command, args) => {+ calls.push([...args]);+ if (args[1] === "marketplace") {+ await writeFile(+ join(home, "config.toml"),+ `\n[marketplaces.codex-security-sdk]\nsource_type = "local"\nsource = ${JSON.stringify(marketplace)}\n`,+ { flag: "a" },+ );+ } else {+ await writeFile(+ join(home, "config.toml"),+ '\n[plugins."codex-security@codex-security-sdk"]\nenabled = true\n',+ { flag: "a" },+ );+ await mkdir(join(installed, ".codex-plugin"), { recursive: true });+ await writeFile(+ join(installed, ".codex-plugin", "plugin.json"),+ JSON.stringify({ name: "codex-security", version: "1.2.3" }),+ );+ }+ return "";+ },+ });++ expect(result.installedRoot).toBe(installed);+ expect(await readFile(join(home, "auth.json"), "utf8")).toBe(+ '{"token":"preserved"}\n',+ );+ expect(calls).toEqual([+ ["plugin", "marketplace", "add", marketplace],+ ["plugin", "add", "codex-security@codex-security-sdk"],+ ]);+ });++ test("reinstalls changed plugin contents even when the version is unchanged", async () => {+ const root = await temporaryDirectory();+ const previous = await plugin(join(root, "previous"), "1.2.3");+ const next = await plugin(join(root, "next"), "1.2.3");+ await writeFile(join(next, "scripts", "helper.py"), "print('updated')\n");+ const home = join(root, "home");+ const marketplace = join(home, "sdk-marketplace");+ const cache = join(+ home,+ "plugins",+ "cache",+ "codex-security-sdk",+ "codex-security",+ );+ await mkdir(home);+ let marketplaceRegistered = false;+ let pluginRegistered = false;+ const updateConfig = async () => {+ const sections = ["[features]\nplugins = true\n"];+ if (marketplaceRegistered) {+ sections.push(+ `[marketplaces.codex-security-sdk]\nsource_type = "local"\nsource = ${JSON.stringify(marketplace)}\n`,+ );+ }+ if (pluginRegistered) {+ sections.push(+ '[plugins."codex-security@codex-security-sdk"]\nenabled = true\n',+ );+ }+ await writeFile(join(home, "config.toml"), sections.join("\n"));+ };+ await updateConfig();+ const calls: string[][] = [];+ const options = {+ codexCommand: { command: "/codex", prefixArgs: [] },+ runCodex: async (+ _command: { command: string; prefixArgs: readonly string[] },+ args: readonly string[],+ ) => {+ calls.push([...args]);+ if (args[1] === "marketplace" && args[2] === "add") {+ marketplaceRegistered = true;+ } else if (args[1] === "marketplace" && args[2] === "remove") {+ marketplaceRegistered = false;+ } else if (args[1] === "remove") {+ pluginRegistered = false;+ await rm(cache, { recursive: true, force: true });+ } else if (args[1] === "add") {+ const installed = join(cache, "1.2.3");+ await mkdir(join(installed, ".codex-plugin"), { recursive: true });+ await writeFile(+ join(installed, ".codex-plugin", "plugin.json"),+ JSON.stringify({ name: "codex-security", version: "1.2.3" }),+ );+ pluginRegistered = true;+ } else {+ throw new Error(`Unexpected plugin command: ${args.join(" ")}`);+ }+ await updateConfig();+ return "";+ },+ };++ await bootstrapPlugin(home, previous, options);+ const result = await bootstrapPlugin(home, next, options);++ expect(result.pluginRoot).toBe(next);+ expect(+ await readFile(+ join(marketplace, "plugins", "codex-security", "scripts", "helper.py"),+ "utf8",+ ),+ ).toBe("print('updated')\n");+ expect(calls).toEqual([+ ["plugin", "marketplace", "add", marketplace],+ ["plugin", "add", "codex-security@codex-security-sdk"],+ ["plugin", "remove", "codex-security@codex-security-sdk"],+ ["plugin", "marketplace", "remove", "codex-security-sdk"],+ ["plugin", "marketplace", "add", marketplace],+ ["plugin", "add", "codex-security@codex-security-sdk"],+ ]);+ });++ test("upgrades a cached plugin without deleting persistent credentials", async () => {+ const root = await temporaryDirectory();+ const previous = await plugin(join(root, "previous"), "1.2.3");+ const next = await plugin(join(root, "next"), "1.2.4");+ const home = join(root, "home");+ const configPath = join(home, "config.toml");+ const marketplace = join(home, "sdk-marketplace");+ const pluginCache = join(+ home,+ "plugins",+ "cache",+ "codex-security-sdk",+ "codex-security",+ );+ await mkdir(home);+ await writeFile(join(home, "auth.json"), '{"token":"preserved"}\n');+ await writeFile(join(home, "unrelated-state"), "preserved\n");++ let marketplaceRegistered = false;+ let pluginRegistered = false;+ const updateConfig = async () => {+ const sections = [+ "[features]\nplugins = true\n",+ `[projects.${JSON.stringify(join(root, "unrelated-project"))}]\ntrust_level = "trusted"\n`,+ ];+ if (marketplaceRegistered) {+ sections.push(+ `[marketplaces.codex-security-sdk]\nsource_type = "local"\nsource = ${JSON.stringify(marketplace)}\n`,+ );+ }+ if (pluginRegistered) {+ sections.push(+ '[plugins."codex-security@codex-security-sdk"]\nenabled = true\n',+ );+ }+ await writeFile(configPath, sections.join("\n"));+ };+ await updateConfig();++ const calls: string[][] = [];+ const runCodex: NonNullable<+ NonNullable<Parameters<typeof bootstrapPlugin>[2]>["runCodex"]+ > = async (_command, args, environment) => {+ expect(environment["CODEX_HOME"]).toBe(home);+ calls.push([...args]);++ if (args[1] === "marketplace" && args[2] === "add") {+ marketplaceRegistered = true;+ } else if (args[1] === "marketplace" && args[2] === "remove") {+ marketplaceRegistered = false;+ } else if (args[1] === "remove") {+ pluginRegistered = false;+ await rm(pluginCache, { recursive: true, force: true });+ } else if (args[1] === "add") {+ const manifest = JSON.parse(+ await readFile(+ join(+ marketplace,+ "plugins",+ "codex-security",+ ".codex-plugin",+ "plugin.json",+ ),+ "utf8",+ ),+ ) as { version: string };+ const installed = join(pluginCache, manifest.version);+ await mkdir(join(installed, ".codex-plugin"), { recursive: true });+ await writeFile(+ join(installed, ".codex-plugin", "plugin.json"),+ JSON.stringify({ name: "codex-security", version: manifest.version }),+ );+ pluginRegistered = true;+ } else {+ throw new Error(`Unexpected plugin command: ${args.join(" ")}`);+ }++ await updateConfig();+ return "";+ };+ const options = {+ codexCommand: { command: "/codex", prefixArgs: [] },+ runCodex,+ };++ expect((await bootstrapPlugin(home, previous, options)).version).toBe(+ "1.2.3",+ );+ const upgraded = await bootstrapPlugin(home, next, options);++ expect(upgraded.version).toBe("1.2.4");+ expect(upgraded.installedRoot).toBe(join(pluginCache, "1.2.4"));+ expect(await readFile(join(home, "auth.json"), "utf8")).toBe(+ '{"token":"preserved"}\n',+ );+ expect(await readFile(join(home, "unrelated-state"), "utf8")).toBe(+ "preserved\n",+ );+ expect(await readFile(configPath, "utf8")).toContain(+ `[projects.${JSON.stringify(join(root, "unrelated-project"))}]`,+ );+ expect(existsSync(join(pluginCache, "1.2.3"))).toBe(false);+ expect(calls).toEqual([+ ["plugin", "marketplace", "add", marketplace],+ ["plugin", "add", "codex-security@codex-security-sdk"],+ ["plugin", "remove", "codex-security@codex-security-sdk"],+ ["plugin", "marketplace", "remove", "codex-security-sdk"],+ ["plugin", "marketplace", "add", marketplace],+ ["plugin", "add", "codex-security@codex-security-sdk"],+ ]);+ });++ test("upgrades a plugin with the real bundled Codex executable", async () => {+ const root = await temporaryDirectory();+ const previous = await plugin(join(root, "previous"), "1.2.3");+ const next = await plugin(join(root, "next"), "1.2.4");+ const home = join(root, "home");+ await mkdir(home, { mode: 0o700 });+ await writeFile(+ join(home, "config.toml"),+ 'cli_auth_credentials_store = "file"\n\n[features]\nplugins = true\n',+ );++ const command = resolveCodexCommand();+ const environment = {+ ...process.env,+ CODEX_HOME: home,+ OPENAI_API_KEY: undefined,+ CODEX_API_KEY: undefined,+ };+ const login = spawnSync(+ command.command,+ [...command.prefixArgs, "login", "--with-api-key"],+ {+ env: environment,+ input: "synthetic-key\n",+ encoding: "utf8",+ windowsHide: true,+ },+ );+ expect(login.status).toBe(0);+ const credentials = await readFile(join(home, "auth.json"), "utf8");++ const options = { codexCommand: command, environment };+ expect((await bootstrapPlugin(home, previous, options)).version).toBe(+ "1.2.3",+ );+ const upgraded = await bootstrapPlugin(home, next, options);++ expect(upgraded.version).toBe("1.2.4");+ expect(await readFile(join(home, "auth.json"), "utf8")).toBe(credentials);+ expect(+ spawnSync(command.command, [...command.prefixArgs, "login", "status"], {+ env: environment,+ encoding: "utf8",+ windowsHide: true,+ }).status,+ ).toBe(0);});test("resolves the exact npm Codex executable", () => {@@ -828,6 +1184,213 @@ describe("plugin runtime preparation", () => {});describe("runtime directories and plugin Python boundary", () => {+ test("prepares one private, reusable managed-credential home", async () => {+ const root = await temporaryDirectory();+ const environment = { CODEX_SECURITY_STATE_DIR: join(root, "state") };+ const expectedHome = join(root, "state", "codex-home");++ expect(codexSecurityCredentialHome(environment)).toBe(expectedHome);+ expect(await prepareCodexSecurityCredentialHome(environment)).toBe(+ expectedHome,+ );+ await writeFile(join(expectedHome, "existing-state"), "preserved\n");+ expect(await prepareCodexSecurityCredentialHome(environment)).toBe(+ expectedHome,+ );+ expect(await readFile(join(expectedHome, "existing-state"), "utf8")).toBe(+ "preserved\n",+ );+ if (process.platform !== "win32") {+ expect((await stat(expectedHome)).mode & 0o777).toBe(0o700);+ }+ });++ testPosix("rejects unsafe persistent credential homes", async () => {+ const root = await temporaryDirectory();+ const stateDirectory = join(root, "state");+ const environment = { CODEX_SECURITY_STATE_DIR: stateDirectory };+ const credentialHome =+ await prepareCodexSecurityCredentialHome(environment);+ await chmod(credentialHome, 0o755);+ await expect(+ prepareCodexSecurityCredentialHome(environment),+ ).rejects.toThrow("must not be accessible to other users");+ await chmod(credentialHome, 0o700);+ await rm(credentialHome, { recursive: true, force: true });++ const redirectedHome = join(root, "redirected-home");+ await mkdir(redirectedHome, { mode: 0o700 });+ await symlink(redirectedHome, credentialHome);+ await expect(+ prepareCodexSecurityCredentialHome(environment),+ ).rejects.toThrow("credential home is not a directory");+ });++ test("identifies a credential home that already exists as a regular file", async () => {+ const root = await temporaryDirectory();+ const stateDirectory = join(root, "state");+ await mkdir(stateDirectory);+ await writeFile(join(stateDirectory, "codex-home"), "not a directory\n");++ await expect(+ prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ }),+ ).rejects.toThrow("credential home is not a directory");+ });++ test("serializes and releases persistent credential-home locks", async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const releaseFirst = await acquireCodexSecurityCredentialHomeLock(home);+ let secondAcquired = false;+ const second = acquireCodexSecurityCredentialHomeLock(home).then(+ (release) => {+ secondAcquired = true;+ return release;+ },+ );++ await new Promise((resolve) => setTimeout(resolve, 40));+ expect(secondAcquired).toBe(false);+ await releaseFirst();+ const releaseSecond = await second;+ expect(secondAcquired).toBe(true);+ await releaseSecond();+ expect(existsSync(join(home, ".codex-security-scan.lock"))).toBe(false);+ });++ test("cancels a scan waiting for the persistent credential-home lock", async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const release = await acquireCodexSecurityCredentialHomeLock(home);+ const controller = new AbortController();+ const waiting = acquireCodexSecurityCredentialHomeLock(+ home,+ controller.signal,+ );+ controller.abort(new DOMException("canceled", "AbortError"));++ try {+ await expect(waiting).rejects.toMatchObject({ name: "AbortError" });+ } finally {+ await release();+ }+ });++ test("recovers credential-home locks left by exited processes", async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const exited = spawnSync(process.execPath, ["--eval", ""], {+ encoding: "utf8",+ windowsHide: true,+ });+ expect(exited.status).toBe(0);+ expect(typeof exited.pid).toBe("number");+ const lock = join(home, ".codex-security-scan.lock");+ await mkdir(lock, { mode: 0o700 });+ await writeFile(+ join(lock, "owner.json"),+ `${JSON.stringify({ pid: exited.pid, token: "exited-process" })}\n`,+ { mode: 0o600 },+ );++ const release = await acquireCodexSecurityCredentialHomeLock(home);+ expect(existsSync(lock)).toBe(true);+ await release();+ expect(existsSync(lock)).toBe(false);+ });++ test("prevents ambient credential imports after an explicit logout", async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });++ expect(await codexSecurityCredentialAllowsAmbientImport(home)).toBe(true);+ await setCodexSecurityCredentialLogout(home, true);+ expect(await codexSecurityCredentialAllowsAmbientImport(home)).toBe(false);+ if (process.platform !== "win32") {+ expect(+ (await stat(join(home, ".codex-security-logged-out"))).mode & 0o777,+ ).toBe(0o600);+ }+ await setCodexSecurityCredentialLogout(home, false);+ expect(await codexSecurityCredentialAllowsAmbientImport(home)).toBe(true);+ });++ test("requires a real private-ACL operation for Windows credential homes", async () => {+ const root = await temporaryDirectory();+ const home = join(root, "home");+ await mkdir(home);+ const metadata = await lstat(home);+ const secured: string[] = [];++ await requirePrivateCredentialHome(metadata, home, {+ platform: "win32",+ secureWindowsHome: async (path) => {+ secured.push(path);+ },+ });++ expect(secured).toEqual([home]);+ await expect(+ requirePrivateCredentialHome(metadata, home, {+ platform: "win32",+ secureWindowsHome: async () => {+ throw new Error("ACL could not be secured");+ },+ }),+ ).rejects.toThrow("private Windows credential home");+ });++ test.skipIf(process.platform !== "win32")(+ "creates credential homes with a verified current-user-only Windows ACL",+ async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const powershell = join(+ process.env["SystemRoot"] ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ );+ const command = [+ "$ErrorActionPreference = 'Stop'",+ "$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_TEST_ACL_PATH', 'Process')",+ "$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",+ "$acl = [System.IO.Directory]::GetAccessControl($path)",+ "$unexpected = @($acl.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity })",+ "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; unexpected = $unexpected.Count } | ConvertTo-Json -Compress",+ ].join("; ");+ const result = spawnSync(+ powershell,+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command],+ {+ encoding: "utf8",+ env: { ...process.env, CODEX_SECURITY_TEST_ACL_PATH: home },+ timeout: 15_000,+ windowsHide: true,+ },+ );++ expect(result.status).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ protected: true,+ unexpected: 0,+ });+ },+ );+test("derives persistent state from the ambient home or explicit override", async () => {const root = await temporaryDirectory();expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe(diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.tsindex 5da93ccb3..b3db112c9 100644--- a/sdk/typescript/tests-ts/scan-comparison.test.ts+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts@@ -1,12 +1,26 @@+import { mkdir, mkdtemp, realpath, rm, symlink } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import type { ThreadOptions, TurnOptions } from "@openai/codex-sdk";-import { describe, expect, test } from "bun:test";+import { afterEach, describe, expect, test } from "bun:test";import {+ comparisonEnvironment,matchScanFindings,type ScanComparisonInput,type ScanComparisonOptions,type ScanComparisonResult,} from "../src/scan-comparison.js";+const temporaryDirectories: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});+function finding(occurrenceId: string): ScanComparisonInput["before"][number] {return { occurrenceId };}@@ -38,6 +52,144 @@ function fakeCodex(response: unknown) {}describe("semantic scan comparison", () => {+ test("preserves environment API-key precedence over managed credentials", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-comparison-"));+ temporaryDirectories.push(root);+ const stateDirectory = join(root, "state");+ const credentialHome = join(stateDirectory, "codex-home");+ await mkdir(credentialHome, { recursive: true, mode: 0o700 });+ let statusProbed = false;++ const environment = await comparisonEnvironment(+ {+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ OPENAI_API_KEY: "synthetic-key-must-not-be-used",+ CODEX_API_KEY: "synthetic-secondary-must-not-be-used",+ },+ async () => {+ statusProbed = true;+ return {+ authenticated: true,+ details: "Logged in using ChatGPT",+ };+ },+ );++ expect(environment["CODEX_SECURITY_STATE_DIR"]).toBe(stateDirectory);+ expect(environment["OPENAI_API_KEY"]).toBe(+ "synthetic-key-must-not-be-used",+ );+ expect(environment["CODEX_API_KEY"]).toBe(+ "synthetic-secondary-must-not-be-used",+ );+ expect(environment["CODEX_HOME"]).toBeUndefined();+ expect(statusProbed).toBe(false);+ });++ test("reuses managed keyring credentials when no environment key is present", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-comparison-"));+ temporaryDirectories.push(root);+ const stateDirectory = join(root, "state");+ const credentialHome = join(stateDirectory, "codex-home");+ await mkdir(credentialHome, { recursive: true, mode: 0o700 });+ let probedHome: string | undefined;++ const environment = await comparisonEnvironment(+ { CODEX_SECURITY_STATE_DIR: stateDirectory },+ async (_command, storedEnvironment) => {+ probedHome = storedEnvironment["CODEX_HOME"];+ return { authenticated: true, details: "Logged in using ChatGPT" };+ },+ );++ expect(environment["CODEX_HOME"]).toBe(await realpath(credentialHome));+ expect(probedHome).toBe(await realpath(credentialHome));+ });++ test.skipIf(process.platform === "win32")(+ "uses the canonical keyring identity when the state parent is symlinked",+ async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-comparison-"));+ temporaryDirectories.push(root);+ const actualState = join(root, "actual-state");+ const linkedState = join(root, "linked-state");+ const credentialHome = join(actualState, "codex-home");+ await mkdir(credentialHome, { recursive: true, mode: 0o700 });+ await symlink(actualState, linkedState, "dir");+ let probedHome: string | undefined;++ const environment = await comparisonEnvironment(+ { CODEX_SECURITY_STATE_DIR: linkedState },+ async (_command, storedEnvironment) => {+ probedHome = storedEnvironment["CODEX_HOME"];+ return { authenticated: true, details: "Logged in using ChatGPT" };+ },+ );++ expect(environment["CODEX_HOME"]).toBe(await realpath(credentialHome));+ expect(probedHome).toBe(await realpath(credentialHome));+ },+ );++ test("forwards cancellation to managed credential-status checks", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-comparison-"));+ temporaryDirectories.push(root);+ const stateDirectory = join(root, "state");+ await mkdir(join(stateDirectory, "codex-home"), {+ recursive: true,+ mode: 0o700,+ });+ const controller = new AbortController();+ let observedSignal: AbortSignal | undefined;+ let statusStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ statusStarted = resolve;+ });++ const waiting = comparisonEnvironment(+ { CODEX_SECURITY_STATE_DIR: stateDirectory },+ async (_command, _environment, signal) => {+ observedSignal = signal;+ statusStarted();+ return await new Promise((_resolve, reject) => {+ signal?.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ });+ });+ },+ controller.signal,+ );+ await started;+ controller.abort(new DOMException("canceled", "AbortError"));++ await expect(waiting).rejects.toMatchObject({ name: "AbortError" });+ expect(observedSignal).toBe(controller.signal);+ });++ test("retains API-key authentication when the managed home is not signed in", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-comparison-"));+ temporaryDirectories.push(root);+ const stateDirectory = join(root, "state");+ const ambientHome = join(root, "ambient-codex-home");+ await mkdir(ambientHome, { mode: 0o700 });+ await mkdir(join(stateDirectory, "codex-home"), {+ recursive: true,+ mode: 0o700,+ });++ const environment = await comparisonEnvironment(+ {+ CODEX_HOME: ambientHome,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ OPENAI_API_KEY: "synthetic-comparison-key",+ },+ async () => ({ authenticated: false, details: "Not logged in" }),+ );++ expect(environment["OPENAI_API_KEY"]).toBe("synthetic-comparison-key");+ expect(environment["CODEX_HOME"]).toBe(ambientHome);+ });+test("compares all findings with one restricted structured-output turn", async () => {const input: ScanComparisonInput = {before: [finding("before-1"), finding("before-2")],