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
chore(codex-security): sync public projection
mldangelo-oaie83201758c59
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 8ac1b760c..4c2be106a 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -297,7 +297,7 @@ export class CodexSecurity {const codexCommand = this.#codexCommand();const login = await persistApiKey(codexCommand,- withoutApiKeys(runtime.environment),+ runtime.environment,apiKey,signal,);@@ -319,7 +319,7 @@ export class CodexSecurity {this.#dependencies.resolvePluginPython ?? resolvePluginPython)({configuredPath: this.config.pythonPath,- environment: withoutApiKeys(this.#dependencies.environment),+ environment: this.#dependencies.environment,protectedRoot,signal,});@@ -457,30 +457,10 @@ export class CodexSecurity {? {}: { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),};- const configuredProfiles = this.config.codexOverrides?.["profiles"];- const profilePolicies = isCodexConfigObject(configuredProfiles)- ? Object.fromEntries(- Object.entries(configuredProfiles).map(([name, profile]) =>- isCodexConfigObject(profile) &&- isCodexConfigObject(profile["shell_environment_policy"])- ? [- name,- {- ...profile,- shell_environment_policy: shellEnvironmentPolicy(- profile["shell_environment_policy"],- runtimePaths,- ),- },- ]- : [name, profile],- ),- )- : {};const environment = {...pluginExecutionEnvironment(python,- withoutCodexHome(withoutApiKeys(runtime.environment)),+ withoutCodexHome(runtime.environment),),CODEX_HOME: runtime.codexHome,...runtimePaths,@@ -490,13 +470,6 @@ export class CodexSecurity {config: {default_permissions: SCAN_PERMISSION_PROFILE,allow_login_shell: false,- shell_environment_policy: shellEnvironmentPolicy(- this.config.codexOverrides?.["shell_environment_policy"],- runtimePaths,- ),- ...(Object.keys(profilePolicies).length > 0- ? { profiles: profilePolicies }- : {}),},});const thread = codex.startThread({@@ -573,7 +546,7 @@ export class CodexSecurity {runtime: preparedRuntime,result: await persistApiKey(this.#codexCommand(),- withoutApiKeys(preparedRuntime.environment),+ preparedRuntime.environment,apiKey,signal,),@@ -851,7 +824,7 @@ export class CodexSecurity {configPath,plugin,environment: {- ...withoutCodexHome(withoutApiKeys(processEnvironment)),+ ...withoutCodexHome(processEnvironment),CODEX_HOME: codexHome,CODEX_SECURITY_STATE_DIR:codexSecurityStateDirectory(processEnvironment),@@ -1204,12 +1177,6 @@ function reconnectAttempt(message: string): [number, number] | null {return attempt <= maxAttempts ? [attempt, maxAttempts] : null;}-function isCodexConfigObject(- value: unknown,-): value is NonNullable<CodexOptions["config"]> {- return isRecord(value);-}-export function scanRuntimeCodexConfig(config: JsonObject): JsonObject {const hardened = structuredClone(config);delete hardened["sandbox_mode"];@@ -1344,87 +1311,6 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {return result;}-function shellEnvironmentPolicy(- policy: unknown,- runtimePaths: Record<string, string>,-): NonNullable<CodexOptions["config"]> {- const configured = isCodexConfigObject(policy) ? policy : {};- const configuredSet = isCodexConfigObject(configured["set"])- ? configured["set"]- : {};- const includeOnly = configured["include_only"];- const exclude = configured["exclude"];- return {- ...configured,- ignore_default_excludes: false,- exclude: [- ...new Set([- ...(Array.isArray(exclude)- ? exclude.filter(- (value): value is string => typeof value === "string",- )- : []),- "CODEX_HOME",- "*KEY*",- "*SECRET*",- "*TOKEN*",- ]),- ],- set: {- ...Object.fromEntries(- Object.entries(configuredSet).filter(([key]) =>- safeShellEnvironmentName(key),- ),- ),- ...runtimePaths,- },- include_only: [- ...new Set([- ...(Array.isArray(includeOnly)- ? includeOnly.filter(- (value): value is string =>- typeof value === "string" && safeShellEnvironmentPattern(value),- )- : [- "PATH",- "HOME",- "USER",- "USERPROFILE",- "HOMEDRIVE",- "HOMEPATH",- "TMP",- "TEMP",- "TMPDIR",- "SYSTEMROOT",- "WINDIR",- "COMSPEC",- "PATHEXT",- "LANG",- "LC_*",- ]),- ...Object.keys(runtimePaths),- ]),- ],- };-}--function safeShellEnvironmentName(value: string): boolean {- const upper = value.toUpperCase();- return (- upper !== "CODEX_HOME" &&- !upper.includes("KEY") &&- !upper.includes("SECRET") &&- !upper.includes("TOKEN")- );-}--function safeShellEnvironmentPattern(value: string): boolean {- return (- safeShellEnvironmentName(value) &&- (/^[A-Za-z_][A-Za-z0-9_]*$/.test(value) || value === "LC_*")- );-}-function requireOutputOutsideRepository(repository: string,outputDirectory: string,@@ -1463,18 +1349,6 @@ function definedEnvironment();}-function withoutApiKeys(- environment: ProcessEnvironment,-): Record<string, string> {- return Object.fromEntries(- Object.entries(definedEnvironment(environment)).filter(- ([name]) =>- name.toUpperCase() !== "OPENAI_API_KEY" &&- name.toUpperCase() !== "CODEX_API_KEY",- ),- );-}-function withoutCodexHome(environment: ProcessEnvironment,): Record<string, string> {diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex cfc77b7f4..e9551e56a 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -133,7 +133,13 @@ export async function runWorkbench(...args,],{- env: withoutApiKeyCredentials(options.environment),+ env: Object.fromEntries(+ Object.entries(options.environment).filter(+ ([name]) =>+ name.toUpperCase() !== "OPENAI_API_KEY" &&+ name.toUpperCase() !== "CODEX_API_KEY",+ ),+ ),encoding: "utf8",maxBuffer: 4 * 1024 * 1024,windowsHide: true,@@ -769,7 +775,7 @@ export async function bootstrapPlugin(const marketplace = await createMarketplace(codexHome, root, options.signal);const command = options.codexCommand ?? resolveCodexCommand();const environment = {- ...withoutApiKeyCredentials(options.environment ?? process.env),+ ...(options.environment ?? process.env),CODEX_HOME: codexHome,};const run = options.runCodex ?? runCodex;@@ -803,21 +809,6 @@ export async function bootstrapPlugin(};}-function withoutApiKeyCredentials(- environment: ProcessEnvironment,-): ProcessEnvironment {- const sanitized = { ...environment };- for (const name of Object.keys(sanitized)) {- if (- name.toUpperCase() === "OPENAI_API_KEY" ||- name.toUpperCase() === "CODEX_API_KEY"- ) {- delete sanitized[name];- }- }- return sanitized;-}-export async function pluginMetadata(root: string,): Promise<{ name: typeof PLUGIN_NAME; version: string }> {diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 0c852b4c3..7b1206191 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1337,43 +1337,6 @@ describe("CodexSecurity orchestration", () => {expect((codexOptions as CodexOptions | null)?.config).toMatchObject({default_permissions: "codex_security_scan",allow_login_shell: false,- shell_environment_policy: {- include_only: [- "PATH",- "HOME",- "USER",- "USERPROFILE",- "HOMEDRIVE",- "HOMEPATH",- "TMP",- "TEMP",- "TMPDIR",- "SYSTEMROOT",- "WINDIR",- "COMSPEC",- "PATHEXT",- "LANG",- "LC_*",- "PYTHON",- "CODEX_SECURITY_STARTED_AT",- "CODEX_SECURITY_REPOSITORY",- "CODEX_SECURITY_SCAN_DIR",- "CODEX_SECURITY_PLUGIN_ROOT",- "CODEX_SECURITY_STATE_DIR",- "CODEX_SECURITY_SCAN_ID",- "CODEX_SECURITY_TARGET_ID",- ],- set: {- PYTHON: "/managed/python",- CODEX_SECURITY_STARTED_AT: startedAt,- CODEX_SECURITY_REPOSITORY: repository,- CODEX_SECURITY_SCAN_DIR: scanDir,- CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,- CODEX_SECURITY_STATE_DIR: expect.any(String),- CODEX_SECURITY_SCAN_ID: expect.any(String),- CODEX_SECURITY_TARGET_ID: expect.any(String),- },- },});expect(threadOptions as Record<string, unknown> | null).toEqual({workingDirectory: scanDir,@@ -1622,12 +1585,7 @@ describe("CodexSecurity orchestration", () => {expect(serialized).not.toContain("shell_environment_policy");expect(input).toContain('--config "$CODEX_SECURITY_CONFIG_PATH"');expect(input).toContain("--effective-config");- const configured = options.config as Record<string, unknown>;- const policy = configured["shell_environment_policy"] as Record<- string,- unknown- >;- const shellEnvironment = policy["set"] as Record<string, string>;+ const shellEnvironment = options.env as Record<string, string>;const helper = execFileSync(interpreter!,[@@ -1882,7 +1840,6 @@ describe("CodexSecurity orchestration", () => {CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,});expect(environment).not.toHaveProperty("CODEX_SECURITY_TARGET_PATHS_JSON");- const startedAt = environment?.["CODEX_SECURITY_STARTED_AT"];const targetPathsFile = environment?.["CODEX_SECURITY_TARGET_PATHS_FILE"];expect(typeof targetPathsFile).toBe("string");if (typeof targetPathsFile !== "string")@@ -1907,120 +1864,6 @@ describe("CodexSecurity orchestration", () => {if (process.platform !== "win32") {expect((await stat(capturedTargetPathsFile)).mode & 0o777).toBe(0o400);}- const shellPolicy = (- (codexOptions as CodexOptions | null)?.config as {- shell_environment_policy?: {- inherit?: string;- ignore_default_excludes?: boolean;- exclude?: string[];- set?: Record<string, string>;- include_only?: string[];- };- profiles?: Record<- string,- {- shell_environment_policy?: {- inherit?: string;- ignore_default_excludes?: boolean;- exclude?: string[];- set?: Record<string, string>;- include_only?: string[];- };- }- >;- }- ).shell_environment_policy;- expect(shellPolicy).toMatchObject({- inherit: "none",- ignore_default_excludes: false,- exclude: [- "OPENAI_*",- "CUSTOM_SECRET",- "CODEX_HOME",- "*KEY*",- "*SECRET*",- "*TOKEN*",- ],- set: {- CUSTOM_REQUIRED: "top-level",- PYTHON: python,- CODEX_SECURITY_STARTED_AT: startedAt,- CODEX_SECURITY_REPOSITORY: repository,- CODEX_SECURITY_SCAN_DIR: scanDir,- CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,- CODEX_SECURITY_STATE_DIR: expect.any(String),- CODEX_SECURITY_SCAN_ID: expect.any(String),- CODEX_SECURITY_TARGET_ID: expect.any(String),- CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile,- },- include_only: [- "PATH",- "HOME",- "PYTHON",- "CODEX_SECURITY_STARTED_AT",- "CODEX_SECURITY_REPOSITORY",- "CODEX_SECURITY_SCAN_DIR",- "CODEX_SECURITY_PLUGIN_ROOT",- "CODEX_SECURITY_STATE_DIR",- "CODEX_SECURITY_SCAN_ID",- "CODEX_SECURITY_TARGET_ID",- "CODEX_SECURITY_TARGET_PATHS_FILE",- ],- });- const profiles = (- (codexOptions as CodexOptions | null)?.config as {- profiles?: Record<- string,- {- model?: string;- model_reasoning_effort?: string;- shell_environment_policy?: {- inherit?: string;- ignore_default_excludes?: boolean;- exclude?: string[];- set?: Record<string, string>;- include_only?: string[];- };- }- >;- }- ).profiles;- expect(profiles).toMatchObject({- locked: { model: "locked-model", model_reasoning_effort: "low" },- inherited: { model: "inherited-model", model_reasoning_effort: "high" },- });- expect(profiles?.["inherited"]).not.toHaveProperty(- "shell_environment_policy",- );- const profilePolicy = profiles?.["locked"]?.shell_environment_policy;- expect(profilePolicy).toMatchObject({- inherit: "none",- ignore_default_excludes: false,- exclude: ["PROFILE_SECRET", "CODEX_HOME", "*KEY*", "*SECRET*", "*TOKEN*"],- set: {- PROFILE_REQUIRED: "profile-level",- PYTHON: python,- CODEX_SECURITY_STARTED_AT: startedAt,- CODEX_SECURITY_REPOSITORY: repository,- CODEX_SECURITY_SCAN_DIR: scanDir,- CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,- CODEX_SECURITY_STATE_DIR: expect.any(String),- CODEX_SECURITY_SCAN_ID: expect.any(String),- CODEX_SECURITY_TARGET_ID: expect.any(String),- CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile,- },- include_only: [- "PYTHON",- "CODEX_SECURITY_STARTED_AT",- "CODEX_SECURITY_REPOSITORY",- "CODEX_SECURITY_SCAN_DIR",- "CODEX_SECURITY_PLUGIN_ROOT",- "CODEX_SECURITY_STATE_DIR",- "CODEX_SECURITY_SCAN_ID",- "CODEX_SECURITY_TARGET_ID",- "CODEX_SECURITY_TARGET_PATHS_FILE",- ],- });expect(prompt).toContain('Repository root: "$CODEX_SECURITY_REPOSITORY"');expect(prompt).toContain('Use this exact scan directory for all scan output: "$CODEX_SECURITY_SCAN_DIR"',@@ -2061,7 +1904,7 @@ describe("CodexSecurity orchestration", () => {env: {PATH: process.env["PATH"],HOME: process.env["HOME"],- ...shellPolicy?.set,+ ...environment,CODEX_SECURITY_TARGET_PATHS_FILE: capturedTargetPathsFile,},encoding: "utf8",@@ -2289,7 +2132,7 @@ describe("CodexSecurity orchestration", () => {await client.close();});- test("persists an ambient API key without exposing it to scan commands", async () => {+ test("persists an ambient API key without filtering Codex-owned credentials", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");@@ -2333,8 +2176,8 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {},environment: {CODEX_HOME: codexHome,- OpenAi_Api_Key: "must-not-reach-a-child",- codex_api_key: "must-not-reach-a-child",+ OpenAi_Api_Key: "forwarded-openai-key",+ codex_api_key: "forwarded-codex-key",},credentialsAvailable: false,}),@@ -2372,20 +2215,15 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {expect((codexOptions as CodexOptions | null)?.codexPathOverride,).toBeUndefined();- expect(- Object.keys((codexOptions as CodexOptions | null)?.env ?? {}).some(- (name) =>- name.toUpperCase() === "OPENAI_API_KEY" ||- name.toUpperCase() === "CODEX_API_KEY",- ),- ).toBe(false);- expect(- Object.keys(pythonEnvironment ?? {}).some(- (name) =>- name.toUpperCase() === "OPENAI_API_KEY" ||- name.toUpperCase() === "CODEX_API_KEY",- ),- ).toBe(false);+ expect((codexOptions as CodexOptions | null)?.env).toMatchObject({+ OpenAi_Api_Key: "forwarded-openai-key",+ codex_api_key: "forwarded-codex-key",+ });+ expect(pythonEnvironment).toMatchObject({+ openai_api_key: "stale-key",+ OPENAI_API_KEY: "ambient-key",+ Codex_Api_Key: "secondary-key",+ });expect(pythonProtectedRoot).toBe(await realpath(repository));await client.close();});@@ -2921,7 +2759,7 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");await expect(login.wait()).resolves.toMatchObject({ success: false });});- test("clears a cached API key after successful ChatGPT login", async () => {+ test("keeps ambient credentials available after successful ChatGPT login", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");@@ -2993,12 +2831,10 @@ if (args === "login --with-api-key") {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?.["OPENAI_API_KEY"],- ).toBeUndefined();- expect(- (codexOptions as CodexOptions | null)?.env?.["CODEX_API_KEY"],- ).toBeUndefined();+ expect((codexOptions as CodexOptions | null)?.env).toMatchObject({+ OPENAI_API_KEY: "ambient-key",+ CODEX_API_KEY: "secondary-ambient-key",+ });await client.close();});diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 3b6c16fef..c13a34097 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -60,6 +60,7 @@ const SYNTHETIC_CREDENTIALS = ["ghs_SYNTHETIC_GITHUB_TOKEN_123","OPENAI_API_KEY=SYNTHETIC_OPENAI_VALUE_123","CODEX_API_KEY=SYNTHETIC_CODEX_VALUE_123",+ "CODEX_ACCESS_TOKEN=SYNTHETIC_CODEX_ACCESS_TOKEN_123","GITHUB_TOKEN=SYNTHETIC_GITHUB_VALUE_123","GH_TOKEN=SYNTHETIC_GH_VALUE_123",'{"OPENAI_API_KEY":"SYNTHETIC_JSON_OPENAI_123","CODEX_API_KEY":"SYNTHETIC_JSON_CODEX_123"}',@@ -111,6 +112,7 @@ const REDACTED_CREDENTIALS = ["[redacted]","OPENAI_API_KEY=[redacted]","CODEX_API_KEY=[redacted]",+ "CODEX_ACCESS_TOKEN=[redacted]","GITHUB_TOKEN=[redacted]","GH_TOKEN=[redacted]",'{"OPENAI_API_KEY":"[redacted]","CODEX_API_KEY":"[redacted]"}',diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 4602a6286..597d01676 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -575,19 +575,13 @@ describe("plugin runtime preparation", () => {const install = await bootstrapPlugin(home, selected, {codexCommand: { command: "/codex", prefixArgs: [] },environment: {- CODEX_API_KEY: "codex-secret",- OPENAI_API_KEY: "openai-secret",- CoDeX_ApI_KeY: "mixed-secret",- openai_api_key: "lowercase-secret",SAFE_VALUE: "kept",},runCodex: async (_command, args, environment) => {- expect(environment["CODEX_HOME"]).toBe(home);- expect(environment["CODEX_API_KEY"]).toBeUndefined();- expect(environment["OPENAI_API_KEY"]).toBeUndefined();- expect(environment["CoDeX_ApI_KeY"]).toBeUndefined();- expect(environment["openai_api_key"]).toBeUndefined();- expect(environment["SAFE_VALUE"]).toBe("kept");+ expect(environment).toMatchObject({+ CODEX_HOME: home,+ SAFE_VALUE: "kept",+ });calls.push([...args]);if (args[1] === "marketplace") {await writeFile(