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(cli): validate scan inputs and verify hook installation (#2578)
Michael D'Angeloa16853f06254
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex f3779b5fb..5c22e6bc6 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -494,6 +494,10 @@ show requested paths and exclusions. `coverage.deferred` records unfinishedrequested work separately from optional `coverage.openQuestions` follow-up.Human-readable output quotes ambiguous paths, while JSON retains their original strings.+A dry run reports `stateDirectory`, the root for saved scan state. It checks the+storage location without creating a scan directory. Pass boolean scan options+as bare flags or use lowercase `=true` or `=false`.+When a cost limit is configured, `scan --dry-run` shows the resolved`maxCostUsd` and a `costLimitNote` explaining how the scan measures usageagainst the limit and why in-flight requests can exceed it.@@ -2419,6 +2423,8 @@ with `--fail-on-severity` set to its original threshold. It recognizes the legac`npx` hook and supported earlier templates with matching absolute Node and CLIpaths. If it refuses to overwrite the verified hook, back it up, remove it andreinstall with the same threshold. Restore the backup if installation fails.+On POSIX, reinstalling a recognized hook restores its owner execute bit if Git+could not execute it. The installer checks that the resulting hook is executable.The installer uses host Git for the selected repository and respects`core.hooksPath`.@@ -2447,6 +2453,13 @@ codex-security patch --scan SCAN_ID --severity high --jsoncodex-security patch --scan SCAN_ID --assess-patch-risk --create-pr```+For `validate`, `patch`, and `verify-fix`, an explicit local file URL such as+`file:///home/reviewer/finding.md` (Windows: `file:///C:/reviews/finding.md`)+requires the file to exist. A missing file stops the command before the model+runs. Use `pathToFileURL(absolutePath).href` in Node to encode spaces and+special characters correctly. Existing plain paths and inline finding text+keep their original behavior.+Context inputs are optional and can be combined:- `--context TEXT` adds inline security context or reviewer feedback.diff --git a/sdk/typescript/docs/sdk.md b/sdk/typescript/docs/sdk.mdindex 5be8b9247..157da213f 100644--- a/sdk/typescript/docs/sdk.md+++ b/sdk/typescript/docs/sdk.md@@ -305,7 +305,7 @@ const plan = await security.preflight("/path/to/repository", {console.log(plan);```-`preflight()` checks local inputs without starting Codex or using the network.+`preflight()` checks local inputs without starting Codex or using the network. The returned `stateDirectory` identifies the checked storage root, including when the final scan directory will be allocated automatically.It does not verify credentials, model access, Python, or the plugin. The CLIequivalent is `scan --dry-run`.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 7cca33b05..6a0b231e2 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -263,6 +263,7 @@ import {credentialHomeUsesFileStorage,codexSecurityCredentialHome,codexSecurityHasStoredFileCredentials,+ checkScanStorage,codexSecurityStateDirectory,codexExecutableReadPaths,copyPluginTree,@@ -701,6 +702,7 @@ export interface ScanPreflight extends DeepScanOptions, ScanModelConfiguration {mode: ScanMode;knowledgeBasePaths?: string[];outputDir: string | null;+ stateDirectory?: string;archiveDir?: string;authentication: ScanAuthentication;modelProvider?: string;@@ -1709,10 +1711,19 @@ export class CodexSecurity {options: ScanOptions = {},): Promise<ScanPreflight> {this.#requireOpen();- return await this.#preflightInputs(- await this.#prepareLocalInputs(repository, options, options.signal),+ const inputs = await this.#prepareLocalInputs(+ repository,options,+ options.signal,+ );+ await checkScanStorage(+ inputs.stateDirectory,+ inputs.outputDir === null &&+ this.#dependencies.prepareOutputDir === undefined+ ? basename(inputs.repository)+ : undefined,);+ return await this.#preflightInputs(inputs, options);}async #preflightInputs(@@ -1759,6 +1770,7 @@ export class CodexSecurity {? { knowledgeBasePaths: options.knowledgeBasePaths }: {}),outputDir: inputs.outputDir,+ stateDirectory: inputs.stateDirectory,...(archiveDir === null ? {} : { archiveDir }),authentication: scanAuthentication(this.#dependencies.environment,diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex be7d72a48..54b2bc9db 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -30,6 +30,7 @@ import {writeSync,} from "node:fs";import {+ access,chmod,lstat,mkdir,@@ -5394,6 +5395,32 @@ export async function main(} else if (existing !== contents) {await writeFile(hook, contents, { flag: "w" });}+ if (process.platform !== "win32") {+ try {+ await access(hook, constants.X_OK);+ } catch {+ const file = await open(+ hook,+ constants.O_RDONLY |+ constants.O_NOFOLLOW |+ constants.O_NONBLOCK,+ );+ try {+ const metadata = await file.stat();+ if (+ !metadata.isFile() ||+ (await file.readFile("utf8")) !== contents+ )+ throw new Error(+ `Cannot make an unrecognized pre-commit hook executable: ${hook}`,+ );+ await file.chmod((metadata.mode & 0o777) | 0o100);+ } finally {+ await file.close();+ }+ await access(hook, constants.X_OK);+ }+ }return {hook,failOnSeverity: options.failOnSeverity,@@ -6486,7 +6513,9 @@ export async function main("findings...": z.string().min(1, "A finding must not be empty.")- .describe("Finding text or a file containing findings."),+ .describe(+ "Finding text, an existing path, or an explicit local file URL (file:///path/to/findings).",+ ),}),options: z.object({records: z@@ -6561,7 +6590,9 @@ export async function main(.string().min(1, "A finding must not be empty.").optional()- .describe("Finding text, a file, or a saved finding identifier."),+ .describe(+ "Finding text, a file path or local file URL, or a saved finding identifier.",+ ),}),options: z.object({host: z@@ -6792,7 +6823,9 @@ export async function main(.string().min(1, "An issue must not be empty.").optional()- .describe("Issue text, a file, or a saved finding identifier."),+ .describe(+ "Issue text, a file path or local file URL, or a saved finding identifier.",+ ),}),options: z.object({host: z@@ -7558,6 +7591,14 @@ export async function main(}}}+ const entry = commands.get(command)!;+ const selected =+ "_group" in entry+ ? subcommand === undefined+ ? entry.root+ : entry.commands.get(subcommand)+ : entry;+ let lastPositionalIndex = -1;for (let index = commandIndex + (nestedCommand ? 2 : 1);index < argv.length;@@ -7566,6 +7607,7 @@ export async function main(const value = argv[index]!;if (!value.startsWith("-")) {positionals.push(value);+ lastPositionalIndex = index;continue;}const equals = value.indexOf("=");@@ -7574,6 +7616,21 @@ export async function main(/[A-Z]/g,(letter) => `-${letter.toLowerCase()}`,);+ if (equals >= 0 && selected && "options" in selected) {+ const name = option+ .slice(2)+ .replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());+ const shape = selected.options?.shape;+ const field =+ shape && Object.hasOwn(shape, name) ? shape[name] : undefined;+ if (+ field &&+ z.toJSONSchema(field, { io: "input" }).type === "boolean" &&+ !["true", "false"].includes(value.slice(equals + 1))+ ) {+ return `Invalid boolean value for ${option}: ${diagnosticValue(value.slice(equals + 1))}. Use ${option}, ${option}=true, or ${option}=false.`;+ }+ }if (equals >= 0 ||(!valueOptions.has(canonicalOption) &&@@ -7610,7 +7667,11 @@ export async function main(? 2: 1)) {- return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;+ const previous = argv[lastPositionalIndex - 1]?.split("=", 1)[0];+ const hint = previous?.startsWith("-")+ ? ` Check the flag ${diagnosticValue(previous)} and whether it takes a value.`+ : "";+ return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.${hint}`;}}const firstImportOption = scanImport ? commandIndex + 2 : argv.length;@@ -9525,6 +9586,14 @@ async function runSkill();}let contentsOrLiteral = input;+ const explicitFile = /^file:\/\//iu.test(input)+ ? new URL(input)+ : undefined;+ if (explicitFile?.hostname) {+ throw new CodexSecurityError(+ "Finding file URLs must refer to local files.",+ );+ }const windowsNamespace =process.platform === "win32" || input.startsWith("\\");const rawDeviceRoot = WINDOWS_LOCAL_DEVICE_ROOT.exec(input)?.[0];@@ -9542,9 +9611,13 @@ async function runSkill(!staysWithinWindowsDeviceRoot(input, rawDeviceRoot) ||localDeviceRoot !== normalizedDeviceRoot);if (!windowsNetworkPath) {- const path = resolveCliPath(directory, input);+ const path = resolveCliPath(+ directory,+ explicitFile ? fileURLToPath(explicitFile) : input,+ );const metadata = await lstat(path, { bigint: true }).catch((error: unknown) => {+ if (explicitFile) throw error;if (typeof error === "object" &&error !== null &&diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex d4bf700d4..03a0d9ca2 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -34,6 +34,7 @@ import {type Stats,} from "node:fs";import {+ access,chmod,cp,copyFile,@@ -1905,6 +1906,51 @@ export function requireOutputOutsideRepositories(requireOutputOutsideRepository(repository, outputDirectory, pathKind);}+/** Check where the scan will create state and default artifacts without creating them. */+export async function checkScanStorage(+ stateDirectory: string,+ defaultOutputRepository?: string,+): Promise<void> {+ try {+ let root = await canonicalConfigPath(stateDirectory);+ await requireWritableDirectoryOrParent(root);+ if (defaultOutputRepository === undefined) return;++ for (const name of ["scans", safePrefix(defaultOutputRepository)]) {+ root = join(root, name);+ const metadata = await lstat(root).catch(nullIfMissingFileError);+ if (metadata !== null && !metadata.isDirectory()) {+ throw new OutputDirectoryError(+ `Persistent scan output must use real directories: ${root}`,+ );+ }+ }+ await requireWritableDirectoryOrParent(root);+ // New per-scan directories are created beneath this root.+ await requireSecureOutputAncestry(+ join(root, `codex-security-${randomUUID()}`),+ );+ } catch (error) {+ throw new OutputDirectoryError(+ `Cannot use scan state directory ${stateDirectory}. Check CODEX_SECURITY_STATE_DIR: ${errorMessage(error)}`,+ { cause: error },+ );+ }+}++async function requireWritableDirectoryOrParent(path: string): Promise<void> {+ const metadata = await lstat(path).catch(nullIfMissingFileError);+ if (metadata === null) {+ const parent = dirname(path);+ if (parent === path)+ throw new OutputDirectoryError(`Directory does not exist: ${path}`);+ return requireWritableDirectoryOrParent(parent);+ }+ if (!metadata.isDirectory())+ throw new OutputDirectoryError(`Expected a directory: ${path}`);+ await access(path, constants.W_OK | constants.X_OK);+}+export async function preparePersistentOutputRoot(stateDirectory: string,category: "scans" | "policies" | "validations" | "imports",diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 9f58dac2d..228476342 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -616,6 +616,13 @@ describe("CodexSecurity orchestration", () => {maxTimeHours: "default",},outputDir: output,+ stateDirectory: join(+ root,+ "ambient",+ "state",+ "plugins",+ "codex-security",+ ),authentication: {method: "api_key",source: "OPENAI_API_KEY",@@ -645,6 +652,36 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("checks default storage without creating state or scan directories", async () => {+ const { root, repository } = await repositoryDirectories();+ const state = join(root, "private", "state");+ const { client, prepareRuntime } = localClient(+ {},+ { CODEX_SECURITY_STATE_DIR: state },+ );+ try {+ await expect(client.preflight(repository)).resolves.toMatchObject({+ outputDir: null,+ stateDirectory: state,+ });+ expect(existsSync(join(root, "private"))).toBe(false);+ await mkdir(dirname(state));+ await writeFile(state, "not a directory");+ await expect(client.preflight(repository)).rejects.toThrow(+ /CODEX_SECURITY_STATE_DIR/,+ );+ await rm(state);+ await mkdir(state);+ await writeFile(join(state, "scans"), "not a directory");+ await expect(client.preflight(repository)).rejects.toThrow(+ /Persistent scan output must use real directories/,+ );+ expect(prepareRuntime).not.toHaveBeenCalled();+ } finally {+ await client.close();+ }+ });+test("reports configured model and reasoning during local-only preflight", async () => {const { repository } = await repositoryDirectories();const { client, prepareRuntime } = localClient(diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.tsindex c640acf5f..fb1835572 100644--- a/sdk/typescript/tests-ts/cli-skills.test.ts+++ b/sdk/typescript/tests-ts/cli-skills.test.ts@@ -4,6 +4,7 @@ import { mkdir, rm, symlink, writeFile } from "node:fs/promises";import * as filesystem from "node:fs/promises";import { join, posix, resolve, win32 } from "node:path";import { Writable } from "node:stream";+import { pathToFileURL } from "node:url";import { setTimeout as delay } from "node:timers/promises";import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";import { parse as parseToml } from "smol-toml";@@ -969,6 +970,36 @@ describe("CLI skill commands", () => {expect(stderr.text()).toBe("");});+ test("explicit local finding file URLs resolve escapes and fail before model work when missing", async () => {+ await using temp = await scopedTemporaryDirectory(+ "codex-security-file-url-",+ );+ const directory = temp.path;+ const file = join(directory, "finding #1.md");+ const url = pathToFileURL(file).href;+ const onCodex = mock<OnCodex>().mockReturnValue(0);+ const deps = dependencies({ currentDirectory: directory, onCodex });+ for (const command of ["validate", "patch", "verify-fix"]) {+ const stderr = captureCli(main, "stderr");+ expect(await stderr.run([command, url], deps)).toBe(2);+ expect(stderr.text()).toContain("finding #1.md");+ }+ const stderr = captureCli(main, "stderr");+ expect(+ await stderr.run(+ ["validate", "file://example.invalid/share/finding"],+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain("must refer to local files");+ expect(onCodex).not.toHaveBeenCalled();+ await writeFile(file, "Finding supplied through a file URL.");+ expect(await runCapturedCli(main, ["validate", url], deps)).toBe(0);+ expect(onCodex.mock.lastCall?.[3]).toContain(+ "Finding supplied through a file URL.",+ );+ });+test("applies bounded model and reasoning overrides to validation and patching", async () => {for (const command of ["validate", "patch"] as const) {const onCodex = mock<OnCodex>().mockReturnValue(0);diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex ead2b1add..e2b2dbb72 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -2,6 +2,7 @@ import { resolving } from "./support/promises.js";import { parseJsonLines } from "./support/json.js";import { writeFileSync } from "node:fs";import {+ chmod,mkdir,mkdtemp,readFile,@@ -1195,6 +1196,38 @@ describe("CLI", () => {});});+ test("rejects malformed boolean options before running the command", async () => {+ const onRun = mock(() => {});+ const deps = dependencies({ onRun });+ for (const args of [+ ["scan", ".", "--working-tree=1", "--dry-run"],+ ["scan", ".", "--workingTree=treu", "--dry-run"],+ ["scan", "--mock", "--dry-run=1"],+ ["scan", "--working-tree=1", "--schema"],+ ["scan", "import", "--csv", "unread.csv", "--dry-run=TRUE"],+ ["publish", "findings", "unread.sarif", "--yes=maybe"],+ ]) {+ const stderr = captureCli(main, "stderr");+ expect(await stderr.run(args, deps)).toBe(2);+ expect(stderr.text()).toContain("Invalid boolean value for");+ }+ const typo = captureCli(main, "stderr");+ expect(+ await typo.run(["scan", ".", "--max-cots", "1", "--dry-run"], deps),+ ).toBe(2);+ expect(typo.text()).toContain("--max-cots");+ expect(onRun).not.toHaveBeenCalled();+ const out = captureCli(main, "stdout");+ expect(+ await out.run(+ ["scan", ".", "--dry-run=true", "--working-tree=false", "--json"],+ deps,+ ),+ ).toBe(0);+ expect(JSON.parse(out.text()).dryRun).toBe(true);+ expect(onRun).not.toHaveBeenCalled();+ });+test("installs a pre-commit hook that blocks failed diff scans", async () => {const root = await realpath(await temporaryDirectory("codex-security-cli-pre-commit-"),@@ -1228,6 +1261,10 @@ describe("CLI", () => {};expect(normalize(result.hook)).toBe(hook);expect(result.failOnSeverity).toBe("medium");+ if (process.platform !== "win32") {+ expect((await stat(hook)).mode & 0o100).toBe(0o100);+ if (attempt === 0) await chmod(hook, 0o600);+ }}expect(await readFile(hook, "utf8")).toContain("--working-tree --fail-on-severity medium",