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-oai8d02bd9fd69b
diff --git a/README.md b/README.mdindex 2e0b7d3fa..bb5a2bd78 100644--- a/README.md+++ b/README.md@@ -302,8 +302,10 @@ for a completed policy violation, `2` for invalid input, incomplete coverage, ora runtime/export error, `130` for interruption, and `143` for termination.Use `--dry-run` or `await security.preflight(...)` to validate local scan-inputs without initializing Codex, loading credentials, or starting a scan. Dry-runs do not inspect the plugin or probe Python.+inputs and report the selected credential source without initializing Codex,+loading credentials, or starting a scan. Dry runs do not inspect the plugin,+probe Python, or contact the network; their authentication metadata is not+verified.## TypeScript SDKdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 3b6b0e63c..cc0a113f7 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -213,7 +213,9 @@ a runtime/export error, `130` for interruption, and `143` for termination.Use `--dry-run` or `await security.preflight(...)` to validate the repository,target, mode, output location, and Codex overrides without initializing theruntime or loading credentials. Dry runs do not inspect the plugin or probe its-Python interpreter.+Python interpreter. The preflight result includes the selected authentication+method and, for an environment API key, its variable name. Authentication and+model access remain unverified until a real scan starts.## SDKdiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 5771c2e04..49e8cabab 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -152,12 +152,13 @@ export interface ScanPreflight {knowledgeBasePaths?: string[];outputDir: string | null;archiveDir?: string;+ authentication: ScanAuthentication;model: string;reasoningEffort: string;}interface LocalScanInputs- extends Omit<ScanPreflight, "model" | "reasoningEffort"> {+ extends Omit<ScanPreflight, "model" | "reasoningEffort" | "authentication"> {protectedRoot: string;}@@ -253,6 +254,7 @@ export class CodexSecurity {: {}),outputDir: inputs.outputDir,...(archiveDir === null ? {} : { archiveDir }),+ authentication: scanAuthentication(this.#dependencies.environment),...scanModelConfiguration(configuration),};}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex d6eb76715..8e3dca491 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -18,6 +18,7 @@ import {relative,resolve,sep,+ win32,} from "node:path";import { cwd } from "node:process";import { createInterface } from "node:readline";@@ -77,6 +78,9 @@ const MAX_CODEX_OVERRIDE_VALUE_LENGTH = 64 * 1_024;const MAX_CODEX_OVERRIDE_DEPTH = 64;const MAX_SKILL_INPUT_BYTES = 1_024 * 1_024;const MAX_SKILL_INPUT_COUNT = 64;+const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;+const WINDOWS_LOCAL_DEVICE_ROOT =+ /^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;const HIDE_CURSOR = "\u001B[?25l";const SHOW_CURSOR = "\u001B[?25h";@@ -1363,6 +1367,20 @@ function validateCliArguments(}}+function staysWithinWindowsDeviceRoot(input: string, root: string): boolean {+ let depth = 0;+ for (const segment of input.slice(root.length).split(/[\\/]+/u)) {+ if (segment.length === 0 || segment === ".") continue;+ if (segment === "..") {+ if (depth === 0) return false;+ depth -= 1;+ continue;+ }+ depth += 1;+ }+ return true;+}+async function runSkill(skill: "validation" | "fix-finding",inputs: readonly string[],@@ -1399,44 +1417,62 @@ async function runSkill(if (Buffer.byteLength(input, "utf8") > MAX_SKILL_INPUT_BYTES) {throw new CodexSecurityError("Skill input exceeds the 1 MiB limit.");}- const path = resolve(directory, input);- const metadata = await stat(path).catch((error: unknown) => {- if (- typeof error === "object" &&- error !== null &&- "code" in error &&- (error.code === "ENOENT" ||- error.code === "ENOTDIR" ||- error.code === "ENAMETOOLONG" ||- error.code === "EINVAL")- ) {- return undefined;- }- throw new CodexSecurityError(- "Could not read the finding or issue input.",- );- });let contentsOrLiteral = input;- if (metadata !== undefined) {- if (!metadata.isFile()) {- throw new CodexSecurityError(- "Finding and issue inputs must be files or literal text.",- );- }- if (metadata.size > MAX_SKILL_INPUT_BYTES) {- throw new CodexSecurityError("Skill input exceeds the 1 MiB limit.");- }- try {- contentsOrLiteral = await readFile(path, "utf8");- } catch {+ const windowsNamespace =+ process.platform === "win32" || input.startsWith("\\");+ const rawDeviceRoot = WINDOWS_LOCAL_DEVICE_ROOT.exec(input)?.[0];+ const localDeviceRoot = rawDeviceRoot?.replaceAll("/", "\\").toLowerCase();+ const normalizedDeviceRoot =+ localDeviceRoot === undefined+ ? undefined+ : WINDOWS_LOCAL_DEVICE_ROOT.exec(win32.resolve(input))?.[0]+ .replaceAll("/", "\\")+ .toLowerCase();+ const windowsNetworkPath =+ windowsNamespace &&+ WINDOWS_NETWORK_PATH.test(input) &&+ (rawDeviceRoot === undefined ||+ !staysWithinWindowsDeviceRoot(input, rawDeviceRoot) ||+ localDeviceRoot !== normalizedDeviceRoot);+ if (!windowsNetworkPath) {+ const path = resolve(directory, input);+ const metadata = await stat(path).catch((error: unknown) => {+ if (+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ (error.code === "ENOENT" ||+ error.code === "ENOTDIR" ||+ error.code === "ENAMETOOLONG" ||+ error.code === "EINVAL")+ ) {+ return undefined;+ }throw new CodexSecurityError("Could not read the finding or issue input.",);- }- if (contentsOrLiteral.trim().length === 0) {- throw new CodexSecurityError(- "Finding or issue inputs must not be empty.",- );+ });+ if (metadata !== undefined) {+ if (!metadata.isFile()) {+ throw new CodexSecurityError(+ "Finding and issue inputs must be files or literal text.",+ );+ }+ if (metadata.size > MAX_SKILL_INPUT_BYTES) {+ throw new CodexSecurityError("Skill input exceeds the 1 MiB limit.");+ }+ try {+ contentsOrLiteral = await readFile(path, "utf8");+ } catch {+ throw new CodexSecurityError(+ "Could not read the finding or issue input.",+ );+ }+ if (contentsOrLiteral.trim().length === 0) {+ throw new CodexSecurityError(+ "Finding or issue inputs must not be empty.",+ );+ }}}totalBytes += Buffer.byteLength(contentsOrLiteral, "utf8");diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 472071c43..82a8396fe 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -28,6 +28,7 @@ import {InvalidTargetError,OutputDirectoryError,OutputInsideProtectedRootError,+ type ScanAuthentication,type ScanOptions,ScanInterruptedError,type ScanWorkerStatus,@@ -873,6 +874,11 @@ describe("CodexSecurity orchestration", () => {target: { kind: "paths", paths: ["src"] },mode: "deep",outputDir: output,+ authentication: {+ method: "api_key",+ source: "OPENAI_API_KEY",+ verified: false,+ },model: "gpt-5.6-sol",reasoningEffort: "xhigh",});@@ -980,6 +986,44 @@ describe("CodexSecurity orchestration", () => {}});+ test("reports selected credentials without checking them during preflight", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);++ for (const [environment, expected] of [+ [+ { OPENAI_API_KEY: "synthetic-openai-key", CODEX_API_KEY: "other-key" },+ { method: "api_key", source: "OPENAI_API_KEY", verified: false },+ ],+ [+ { openai_api_key: " ", Codex_Api_Key: "synthetic-codex-key" },+ { method: "api_key", source: "CODEX_API_KEY", verified: false },+ ],+ [{}, { method: "stored_credentials", verified: false }],+ ] as const) {+ let runtimeStarted = false;+ const client = new TestClient(+ {},+ {+ environment,+ prepareRuntime: async () => {+ runtimeStarted = true;+ throw new Error("runtime should not initialize");+ },+ },+ );++ const preflight = await client.preflight(repository);+ const authentication: ScanAuthentication = preflight.authentication;++ expect(authentication).toEqual(expected);+ expect(JSON.stringify(preflight)).not.toContain("synthetic-");+ expect(runtimeStarted).toBe(false);+ await client.close();+ }+ });+test("previews an existing output archive without changing files", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex b43545cff..be3034ef1 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -177,6 +177,7 @@ function fakePreflight(repository = "/current/repository"): ScanPreflight {target: { kind: "repository", paths: [] },mode: "standard",outputDir: null,+ authentication: { method: "stored_credentials", verified: false },model: "gpt-5.6-sol",reasoningEffort: "xhigh",};@@ -1143,6 +1144,110 @@ describe("CLI", () => {}});+ test("preserves Windows network paths without probing them as finding files", async () => {+ const directory = await mkdtemp(+ join(tmpdir(), "codex-security-network-input-"),+ );+ try {+ const localFile = join(directory, "local finding.txt");+ const localDrivePaths =+ process.platform === "win32"+ ? [+ `\\\\?\\${join(directory, "drive finding.txt")}`,+ `\\\\?\\${join(directory, "nested")}\\..\\safe drive finding.txt`,+ ]+ : [+ String.raw`\\?\C:\drive finding.txt`,+ String.raw`\\.\C:\device drive finding.txt`,+ String.raw`\\?\C:\folder\..\safe drive finding.txt`,+ String.raw`\\.\C:\folder\.\safe device finding.txt`,+ String.raw`\\?\Volume{12345678-1234-1234-1234-123456789abc}\folder\..\volume finding.txt`,+ String.raw`\\?\GLOBALROOT\Device\HarddiskVolume1\folder\..\volume finding.txt`,+ ];+ const posixDoubleSlashPaths =+ process.platform === "win32"+ ? []+ : [`/${localFile}`, `//.${localFile}`];+ const networkPaths = [+ String.raw`\\server\share\finding.txt`,+ ...(process.platform === "win32"+ ? [+ "//server/share/finding.txt",+ "//?/globalroot/device/lanmanredirector/server/share/finding.txt",+ "//?/C:/../UNC/server/share/finding.txt",+ ]+ : []),+ String.raw`\\?\UNC\server\share\finding.txt`,+ String.raw`\\.\UNC\server\share\finding.txt`,+ String.raw`\\?\GLOBALROOT\Device\LanmanRedirector\server\share\finding.txt`,+ String.raw`\\.\GLOBALROOT\Device\Mup\server\share\finding.txt`,+ String.raw`\\.\server\share\finding.txt`,+ String.raw`\\?\unc/server\share\finding.txt`,+ String.raw`\\?\C:\..\GLOBALROOT\Device\LanmanRedirector\server\share\finding.txt`,+ String.raw`\\.\C:\..\GLOBALROOT\Device\Mup\server\share\finding.txt`,+ String.raw`\\?\C:\.\..\GLOBALROOT\Device\LanmanRedirector\server\share\finding.txt`,+ String.raw`\\?\Volume{12345678-1234-1234-1234-123456789abc}\..\GLOBALROOT\Device\LanmanRedirector\server\share\finding.txt`,+ String.raw`\\?\GLOBALROOT\Device\HarddiskVolume1\..\LanmanRedirector\server\share\finding.txt`,+ ];+ await writeFile(localFile, "local finding contents\n");+ await mkdir(join(directory, "nested"));+ await Promise.all(+ localDrivePaths.map(async (localDrivePath, index) =>+ writeFile(+ resolve(directory, localDrivePath),+ `local drive ${index + 1} contents\n`,+ ),+ ),+ );+ if (process.platform !== "win32") {+ for (const networkPath of networkPaths) {+ if (networkPath.startsWith("\\") && !networkPath.includes("/")) {+ await writeFile(+ join(directory, networkPath),+ "must not read a network-path decoy\n",+ );+ }+ }+ }++ let invocation: readonly string[] = [];+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "validate",+ localFile,+ ...localDrivePaths,+ ...posixDoubleSlashPaths,+ ...networkPaths,+ ],+ stdout.stream,+ stderr.stream,+ dependencies({+ currentDirectory: directory,+ onCodex: (args) => {+ invocation = args;+ return 0;+ },+ }),+ ),+ ).toBe(0);+ expect(JSON.parse(invocation.at(-1)!.split("\n").at(-1)!)).toEqual([+ "local finding contents\n",+ ...localDrivePaths.map(+ (_, index) => `local drive ${index + 1} contents\n`,+ ),+ ...posixDoubleSlashPaths.map(() => "local finding contents\n"),+ ...networkPaths,+ ]);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toBe("");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ });+test("applies bounded model and reasoning overrides to validation and patching", async () => {for (const command of ["validate", "patch"] as const) {let invocation: readonly string[] = [];@@ -2304,7 +2409,17 @@ describe("CLI", () => {const preload = join(root, "unavailable-cwd.mjs");await writeFile(preload,- 'Object.defineProperty(process, "cwd", { value() { throw new Error("working directory is unavailable"); } });\n',+ [+ "const originalCwd = process.cwd;",+ 'Object.defineProperty(process, "cwd", {',+ " value() {",+ ' if (/[\\\\/]dist[\\\\/]cli\\.js:/u.test(new Error().stack ?? "")) {',+ ' throw new Error("working directory is unavailable");',+ " }",+ " return originalCwd.call(process);",+ " },",+ "});\n",+ ].join("\n"),);const failed = spawnSync("node",@@ -2916,6 +3031,29 @@ describe("CLI", () => {expect(stderr.text()).not.toContain("Running scan");});+ test("keeps selected dry-run authentication metadata safe and machine readable", async () => {+ const stdout = capture();+ const stderr = capture();+ const authentication = {+ method: "api_key" as const,+ source: "CODEX_API_KEY" as const,+ verified: false as const,+ };+ expect(+ await main(+ ["scan", "repo", "--dry-run", "--json"],+ stdout.stream,+ stderr.stream,+ dependencies({+ environment: { CODEX_API_KEY: "synthetic-private-key" },+ preflight: { ...fakePreflight("repo"), authentication },+ }),+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toMatchObject({ authentication });+ expect(`${stdout.text()}${stderr.text()}`).not.toContain("synthetic");+ });+test("renders dry-run output with Incur structured formats", async () => {for (const [format, marker] of [["toon", "dryRun: true"],