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 inputs and make plans and hooks reusable (#2594)
Michael D'Angeloae291b2af35d
diff --git a/docs/project-configuration.md b/docs/project-configuration.mdindex c04333d9c..7db58f06c 100644--- a/docs/project-configuration.md+++ b/docs/project-configuration.md@@ -186,8 +186,8 @@ The resolver maps file keys to the existing SDK options:| `scan.deep.stop_after_no_new` | `stopAfterNoNew` | `--stop-after-no-new` || `scan.deep.stop_after_consecutive_errors` | `stopAfterConsecutiveErrors` | No flag || `scan.deep.max_discovery_runs` | `maxDiscoveryRuns` | `--max-discovery-runs` |-| `scan.deep.max_time_hours` | `maxTimeHours` | `--max-time-hours` |-| `scan.max_time_minutes` | `maxTimeMinutes` | `--max-time` |+| `scan.deep.max_time_hours` | `maxTimeHours` | Legacy `--max-time-hours` (hours) |+| `scan.max_time_minutes` | `maxTimeMinutes` | `--max-time` (minutes, preferred) || `limits.max_cost_usd_per_scan` | `maxCostUsd` | `--max-cost` || `policy.fail_on_severity` | `failureSeverity` | `--fail-on-severity` || `output.directory` | `outputDir` | `--output-dir` |diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 427a7c8f5..0fcf06c44 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -403,11 +403,11 @@ Add context with `--knowledge-base`:codex-security policy . --knowledge-base architecture.md```-| Invocation | Result |-| ---------------------------- | -------------------------------------------------------- |-| `policy . --headless --json` | Generate without prompts; return paths and review notes. |-| `policy . --format md` | Generate and write the draft to stdout. |-| `policy . --dry-run --json` | Check local inputs without calling Codex. |+| Invocation | Result |+| --------------------------- | -------------------------------------------------------- |+| `policy . --json` | Generate without prompts; return paths and review notes. |+| `policy . --format md` | Generate and write the draft to stdout. |+| `policy . --dry-run --json` | Check local inputs without calling Codex. |`--headless` leaves unanswered questions in the review notes. By default, filesgo in the Codex Security state directory. To choose a location, use an empty@@ -852,6 +852,13 @@ codex-security scan-components . \--output-dir /path/outside/project/results```+`--plan-only` with `--component` or `--components-file` validates local paths+without signing in. The CLI prints a command to scan the saved plan into a fresh+`results` directory inside the plan directory. Running that command starts scans.+Run it from the original working directory to reuse relative paths. The command+includes the selected project configuration and scan flags. Reapply any inline+`--codex` overrides yourself, since these can contain credentials.+Plans use literal repository-relative paths, so `~/src` selects a directorynamed `~` inside the repository rather than expanding the home directory.Existing absolute paths inside the repository are also accepted.@@ -914,6 +921,7 @@ opted in. The SDK accepts `rubricPath` or a `severityRubric` snapshot with`markdown`, a positive integer `revision`, and the SHA-256 of the exact UTF-8Markdown. A supplied snapshot takes precedence over a file.+A dry run reads and validates an explicit rubric before reporting a successful preflight.The scan saves the rubric text in its local launch recipe. Retrying a Standardscan with the same `--workflow-id`, resuming a Deep scan, or rerunning a scanwith a saved rubric reuses that copy even if the remote default or file changes.@@ -1363,7 +1371,8 @@ the campaign a joint source review across repositories. For that workflow, useRun `gh auth login`, then `codex-security bulk-scan` for interactive GitHubselection. It lists repositories pushed in the last 90 days, excluding forks-and archives, asks for output, and saves the selection as `repositories.csv`.+and archives, asks where to save results, and saves the selection as `repositories.csv`.+Pass `--output-dir DIR` to set the initial answer in the wizard.Private checkouts use your GitHub CLI login.For CI, provide CSV with `id`, `repository`, and a full commit `revision`.@@ -2491,10 +2500,9 @@ codex-security install-hook /path/to/repositoryTo migrate an existing generated hook, verify it is a regular file used only bythis repository and contains only the generated commands. Rerun `install-hook`-with `--fail-on-severity` set to its original threshold. It recognizes the legacy-`npx` hook and supported earlier templates with matching absolute Node and CLI-paths. If it refuses to overwrite the verified hook, back it up, remove it and-reinstall with the same threshold. Restore the backup if installation fails.+with the desired `--fail-on-severity` level to change the threshold. The installer+recognizes the legacy `npx` hook and earlier generated templates with matching+absolute Node and CLI paths. It refuses to replace a hand-edited hook.On POSIX, reinstalling a recognized hook restores its owner execute bit if Gitcould not execute it. The installer checks that the resulting hook is executable.The installer uses host Git for the selected repository and respects@@ -2529,8 +2537,9 @@ 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 modelruns. Use `pathToFileURL(absolutePath).href` in Node to encode spaces and-special characters correctly. Existing plain paths and inline finding text-keep their original behavior.+special characters correctly. Absolute paths and paths starting with `~/`, `./`, or `../`+also require an existing file. Use `text:/path is exposed` to pass path-shaped+prose verbatim, or `text:text:example` for a finding that starts with `text:`.Context inputs are optional and can be combined:diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex 0575ade4f..0d69258a9 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -14,6 +14,7 @@ const distModules = ["cli-argument","cli-daybreak","cli-help",+ "cli-hook","cli-integrations","cli-mcp","cli-scan-logs-json",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex fe9007ce5..8f8ab763d 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -1738,6 +1738,18 @@ export class CodexSecurity {await realpath(tmpdir()),"temporary",);+ if (+ this.#dependencies.hostedScan === undefined &&+ options.rubricPath !== undefined &&+ options.severityRubric === undefined &&+ inputs.retryRecipe === undefined &&+ options.resumeScanId === undefined+ ) {+ await readSeverityRubricFile(+ resolve(expandHome(options.rubricPath)),+ inputs.protectedRoot,+ );+ }if (options.knowledgeBasePaths?.length) {const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBaseSnapshot ?? options.knowledgeBasePaths,diff --git a/sdk/typescript/src/cli-hook.ts b/sdk/typescript/src/cli-hook.tsnew file mode 100644index 000000000..ce1dd6e35--- /dev/null+++ b/sdk/typescript/src/cli-hook.ts@@ -0,0 +1,104 @@+import { randomUUID } from "node:crypto";+import { constants } from "node:fs";+import {+ access,+ lstat,+ mkdir,+ open,+ rename,+ rm,+ writeFile,+} from "node:fs/promises";+import { dirname } from "node:path";+import {+ REPORTABLE_SEVERITIES,+ type FailureSeverity,+} from "./scan-settings.js";+import { UNSUPPORTED_GIT_ENVIRONMENT } from "./targets.js";++export async function installManagedHook(+ hook: string,+ command: string,+ threshold: FailureSeverity,+): Promise<void> {+ const header = "#!/bin/sh\nset -eu\n";+ const unset = `unset ${[...UNSUPPORTED_GIT_ENVIRONMENT].join(" ")}\n`;+ const scan = (launcher: string, level: FailureSeverity) =>+ `exec ${launcher} scan . --working-tree --fail-on-severity ${level}\n`;+ const contents = header + unset + scan(command, threshold);+ await mkdir(dirname(hook), { recursive: true });+ try {+ await writeFile(hook, contents, { flag: "wx", mode: 0o755 });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ }++ const refuse = () =>+ new Error(`A pre-commit hook already exists at ${hook}.`);+ const templates = REPORTABLE_SEVERITIES.flatMap((level) => [+ header + unset + scan(command, level),+ header ++ "unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE\n" ++ scan(command, level),+ header + scan(command, level),+ header + scan("npx --no-install codex-security", level),+ ]);+ const selected = await lstat(hook, { bigint: true });+ if (!selected.isFile()) throw refuse();+ const file = await open(+ hook,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,+ );+ try {+ const opened = await file.stat({ bigint: true });+ if (+ !opened.isFile() ||+ opened.dev !== selected.dev ||+ opened.ino !== selected.ino ||+ opened.nlink !== 1n ||+ opened.size > Math.max(...templates.map((t) => Buffer.byteLength(t)))+ )+ throw refuse();+ const previous = await file.readFile("utf8");+ if (!templates.includes(previous)) throw refuse();+ if (previous === contents) {+ if (process.platform !== "win32") {+ try {+ await access(hook, constants.X_OK);+ } catch {+ await file.chmod((Number(opened.mode) & 0o777) | 0o100);+ await access(hook, constants.X_OK);+ }+ }+ return;+ }+ } finally {+ // Windows can deny replacement while the destination is open.+ await file.close();+ }++ const staged = `${hook}.${randomUUID()}.tmp`;+ const replacement = await open(staged, "wx", 0o600);+ try {+ try {+ await replacement.writeFile(contents);+ if (process.platform !== "win32")+ await replacement.chmod((Number(selected.mode) & 0o777) | 0o100);+ } finally {+ await replacement.close();+ }+ const current = await lstat(hook, { bigint: true });+ if (+ !current.isFile() ||+ current.dev !== selected.dev ||+ current.ino !== selected.ino ||+ current.ctimeNs !== selected.ctimeNs ||+ current.nlink !== selected.nlink+ )+ throw refuse();+ await rename(staged, hook);+ if (process.platform !== "win32") await access(hook, constants.X_OK);+ } finally {+ await rm(staged, { force: true });+ }+}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 71d8aaab2..db663b8b3 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -30,10 +30,8 @@ import {writeSync,} from "node:fs";import {- access,chmod,lstat,- mkdir,mkdtemp,open,readFile,@@ -389,6 +387,7 @@ import {type PolicyPrompt,type PolicySecurity,} from "./security-policy-cli.js";+import { installManagedHook } from "./cli-hook.js";import { cliShellLabel, quoteCliPath } from "./cli-argument.js";import { formatSecurityPolicyText as escapeTerminalText } from "./security-policy.js";import { commandGitProtectionRoots } from "./local-git-metadata.js";@@ -407,7 +406,6 @@ import {gitMarkerRoot,normalizeRepository,trustedGitCommand,- UNSUPPORTED_GIT_ENVIRONMENT,type ScanTarget,relativePathIsOutside as isOutsidePath,} from "./targets.js";@@ -5259,7 +5257,7 @@ export async function main("Review the diff and notes. Edit the draft, then copy only SECURITY.md to the Policy target shown.\n" +"Your existing policy stays unchanged until you replace it.\n\n" +"Save a draft without answering questions:\n" +- " codex-security policy . --headless --output-dir /path/outside/repository/policy --json",+ " codex-security policy . --output-dir ../policy-draft --json",output: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),@@ -5729,7 +5727,7 @@ export async function main(.command(createScanCommands()).command("install-hook", {description:- "Install a local pre-commit hook that blocks on scan errors or findings at the selected severity threshold.",+ "Install a pre-commit hook that scans staged and unstaged working-tree changes and blocks on errors or findings at the selected severity.",examples: [{ args: { repository: "." }, options: { failOnSeverity: "high" } },],@@ -5774,7 +5772,7 @@ export async function main({ cwd, requestedPaths: [resolve(requested)] },),);- const hook = execFileSync(+ const hooksDirectory = execFileSync(git.executable,["-C",@@ -5782,63 +5780,18 @@ export async function main("rev-parse","--path-format=absolute","--git-path",- "hooks/pre-commit",+ "hooks",],{ encoding: "utf8", env: git.environment },- ).trim();+ ).replace(/\r?\n$/u, "");+ const hook = join(hooksDirectory, "pre-commit");const command = [realpathSync(process.execPath),realpathSync(fileURLToPath(import.meta.url)),].map((path) => `'${path.replaceAll("'", `'"'"'`)}'`).join(" ");- const invocation = `exec ${command} scan . --working-tree --fail-on-severity ${options.failOnSeverity}\n`;- const contents = `#!/bin/sh\nset -eu\nunset ${[...UNSUPPORTED_GIT_ENVIRONMENT].join(" ")}\n${invocation}`;- const previousScopedContents = `#!/bin/sh\nset -eu\nunset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE\n${invocation}`;- const previousContents = `#!/bin/sh\nset -eu\n${invocation}`;- const legacyContents = `#!/bin/sh\nset -eu\nexec npx --no-install codex-security scan . --working-tree --fail-on-severity ${options.failOnSeverity}\n`;- const existing = await readFile(hook, "utf8").catch(() => null);- if (- existing !== null &&- existing !== contents &&- existing !== previousScopedContents &&- existing !== previousContents &&- existing !== legacyContents- ) {- throw new Error(`A pre-commit hook already exists at ${hook}.`);- }- if (existing === null) {- await mkdir(dirname(hook), { recursive: true });- await writeFile(hook, contents, { flag: "wx", mode: 0o755 });- } 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);- }- }+ await installManagedHook(hook, command, options.failOnSeverity);return {hook,failOnSeverity: options.failOnSeverity,@@ -6293,7 +6246,9 @@ export async function main(planOnly: z.boolean().default(false)- .describe("Save components.json without starting scans."),+ .describe(+ "Save components.json and print a command to run it. Explicit plans work offline.",+ ),headless: z.boolean().default(false)@@ -6517,6 +6472,53 @@ export async function main();},});+ if (options.planOnly) {+ const {+ auto,+ component,+ componentsFile,+ planOnly,+ outputDir,+ config,+ codex,+ ...scanOptions+ } = options;+ const supplied = new Set(argv.map((arg) => arg.split("=", 1)[0]));+ const overrides = Object.fromEntries(+ Object.entries(scanOptions).filter(([key]) => {+ const flag = cliOptionFlag(key);+ return (+ supplied.has(flag) ||+ supplied.has(`--${key}`) ||+ supplied.has(`--no-${flag.slice(2)}`)+ );+ }),+ );+ const nextCommand = [+ "codex-security",+ "scan-components",+ quoteCliPath(repository),+ ...cliOptionTokens({+ componentsFile: result.planPath,+ outputDir: join(dirname(result.planPath), "results"),+ config: project?.path,+ ...overrides,+ }),+ ].join(" ");+ const nextCommandNote =+ codex.length > 0+ ? "Reapply your --codex overrides when running this command."+ : undefined;+ errorOutput.write(+ `Run this plan: ${diagnosticValue(nextCommand)}\n`,+ );+ if (nextCommandNote) errorOutput.write(`${nextCommandNote}\n`);+ return {+ ...result,+ nextCommand,+ ...(nextCommandNote && { nextCommandNote }),+ };+ }exitCode =interruptedExitCode(controller.signal) ??(result.failed || result.deduplication?.status === "failed"@@ -6562,7 +6564,7 @@ export async function main(.min(1, "--output-dir must not be empty.").optional().describe(- "Resumable results directory; required with a repository CSV.",+ "Results directory. Required with a CSV and used as the initial directory in the wizard.",),knowledgeBase: z.array(optionValue("--knowledge-base"))@@ -6650,11 +6652,6 @@ export async function main(let outputDir: string;let githubHost: string | undefined;if (args.input === undefined) {- if (options.outputDir !== undefined) {- throw new Error(- "--output-dir can only be used with a repository CSV; omit it to choose an output directory interactively.",- );- }const wizard = await runBulkScanWizard(dependencies.bulkScan ??createBulkScanDiscoveryDependencies({@@ -7019,7 +7016,7 @@ export async function main(.string().min(1, "A finding must not be empty.").describe(- "Finding text, an existing path, or an explicit local file URL (file:///path/to/findings).",+ "Finding text, a local file path or file URL. Use text:VALUE to pass path-shaped prose.",),}),options: z.object({@@ -7102,7 +7099,7 @@ export async function main(.min(1, "A finding must not be empty.").optional().describe(- "Finding text, a file path or local file URL, or a saved finding identifier.",+ "Finding text, a local file path or URL, or a saved finding identifier. Use text:VALUE to pass path-shaped prose.",),}),options: z.object({@@ -7352,7 +7349,7 @@ export async function main(.min(1, "An issue must not be empty.").optional().describe(- "Issue text, a file path or local file URL, or a saved finding identifier.",+ "Issue text, a local file path or URL, or a saved finding identifier. Use text:VALUE to pass path-shaped prose.",),}),options: z.object({@@ -8919,6 +8916,28 @@ function parseFrameworkArguments(};}+function cliOptionFlag(key: string): string {+ return `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;+}++function cliOptionTokens(options: Record<string, unknown>): string[] {+ const tokens: string[] = [];+ for (const [key, value] of Object.entries(options)) {+ if (value === undefined) continue;+ const flag = cliOptionFlag(key);+ for (const item of Array.isArray(value) ? value : [value]) {+ if (typeof item === "boolean") {+ tokens.push(item ? flag : `${flag}=false`);+ } else if (String(item).startsWith("-")) {+ tokens.push(quoteCliPath(`${flag}=${item}`));+ } else {+ tokens.push(flag, quoteCliPath(String(item)));+ }+ }+ }+ return tokens;+}+/** Incur prints example keys verbatim and treats every option as a single value.* Give its shared help, manifest and skill renderers the actual shell tokens.*/@@ -8933,15 +8952,7 @@ function prepareCliExamples(const tokens = Object.values(example.args ?? {}).map((value) =>quoteCliPath(String(value)),);- for (const [key, value] of Object.entries(example.options ?? {})) {- const flag = `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;- for (const item of Array.isArray(value) ? value : [value]) {- tokens.push(item === false ? `${flag}=false` : flag);- if (typeof item !== "boolean")- tokens.push(quoteCliPath(String(item)));- }- }- example.args = tokens;+ example.args = [...tokens, ...cliOptionTokens(example.options ?? {})];delete example.options;}}@@ -10266,6 +10277,15 @@ async function runSkill("Finding or issue inputs must not be empty.",);}+ if (input.startsWith("text:")) {+ const literal = input.slice("text:".length);+ if (!literal.trim())+ throw new CodexSecurityError(+ "Finding or issue inputs must not be empty.",+ );+ contents.push(literal);+ continue;+ }let contentsOrLiteral = input;const explicitFile = /^file:\/\//iu.test(input)? new URL(input)@@ -10298,7 +10318,14 @@ async function runSkill();const metadata = await lstat(path, { bigint: true }).catch((error: unknown) => {- if (explicitFile) throw error;+ if (+ explicitFile ||+ isAbsolute(expandHome(input)) ||+ input.startsWith("./") ||+ input.startsWith("../") ||+ (process.platform === "win32" && /^\.{1,2}\\/u.test(input))+ )+ throw error;if (typeof error === "object" &&error !== null &&diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex 3dc042d23..233af7e6b 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -35,7 +35,11 @@ import type {} from "./cost.js";import type { ScanTokenUsage } from "./cost-model.js";import { readThreatModelPath } from "./artifact-export.js";-import { errorMessage, ScanCostLimitExceededError } from "./errors.js";+import {+ errorMessage,+ OutputDirectoryNotEmptyError,+ ScanCostLimitExceededError,+} from "./errors.js";import type { Finding } from "./models.js";import type { ScanResult } from "./result.js";import type { ScanActivity } from "./scan-activity.js";@@ -170,7 +174,11 @@ export async function runComponentScans(const budget = batchScanBudget(pool?.share, options.scanOptions ?? {});const auth = options.scanOptions?.auth;let environment = options.environment;- if (auth !== undefined && auth !== "auto") {+ if (+ (!options.planOnly || options.auto) &&+ auth !== undefined &&+ auth !== "auto"+ ) {const source = environment ?? process.env;const configuration = await mergedCodexConfig(options.config ?? {},@@ -205,7 +213,11 @@ export async function runComponentScans(basename(repository),undefined,(path) => requireOutputOutsideRepository(protectedRoot, path),- );+ ).catch((error: unknown) => {+ if (error instanceof OutputDirectoryNotEmptyError)+ throw new OutputDirectoryNotEmptyError(error.directory, "component");+ throw error;+ });const plan = await normalizeComponentPlan(repository,options.autodiff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsindex 35939ccaf..cb9627739 100644--- a/sdk/typescript/src/errors.ts+++ b/sdk/typescript/src/errors.ts@@ -54,12 +54,14 @@ export class OutputDirectoryError extends CodexSecurityError {}export class OutputDirectoryNotEmptyError extends OutputDirectoryError {public constructor(public readonly directory: string,- operation: "scan" | "policy" = "scan",+ operation: "scan" | "policy" | "component" = "scan",) {super(- operation === "policy"- ? `Policy output directory is not empty: ${directory}. Choose a new or empty directory.`- : `Scan output directory is not empty: ${directory}. To keep the existing results and start a new scan, add --archive-existing.`,+ operation === "component"+ ? `Component output directory is not empty: ${directory}. Choose a new or empty directory with --output-dir.`+ : operation === "policy"+ ? `Policy output directory is not empty: ${directory}. Choose a new or empty directory.`+ : `Scan output directory is not empty: ${directory}. To keep the existing results and start a new scan, add --archive-existing.`,);}}diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex dde633bd4..cac359e6a 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -869,6 +869,29 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("validates an explicit severity rubric during local preflight", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const rubricPath = join(root, "rubric.md");+ await mkdir(repository);+ const { client, prepareRuntime } = localClient(+ {},+ { CODEX_SECURITY_STATE_DIR: join(root, "state") },+ );+ await expect(+ client.preflight(repository, { rubricPath }),+ ).rejects.toThrow();+ await writeFile(rubricPath, " ");+ await expect(client.preflight(repository, { rubricPath })).rejects.toThrow(+ "Rubric must not be blank",+ );+ await writeFile(rubricPath, "Require a reachable impact.");+ await expect(+ client.preflight(repository, { rubricPath }),+ ).resolves.toMatchObject({ repository });+ expect(prepareRuntime).not.toHaveBeenCalled();+ });+test("validates knowledge-base documents before initializing the runtime", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli-policy.test.ts b/sdk/typescript/tests-ts/cli-policy.test.tsindex ae9f6b788..ba9b9e4d8 100644--- a/sdk/typescript/tests-ts/cli-policy.test.ts+++ b/sdk/typescript/tests-ts/cli-policy.test.ts@@ -173,7 +173,7 @@ describe("policy CLI", () => {expect(stdout.text()).not.toContain("--outputDir");expect(stdout.text()).not.toContain("--write true");expect(stdout.text()).toContain(- "--headless --output-dir /path/outside/repository/policy --json",+ "codex-security policy . --output-dir ../policy-draft --json",);});diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.tsindex 8e5faf145..aadc07b33 100644--- a/sdk/typescript/tests-ts/cli-skills.test.ts+++ b/sdk/typescript/tests-ts/cli-skills.test.ts@@ -283,7 +283,7 @@ describe("CLI skill commands", () => {command,`${command}.txt`,`${command} literal`,- "C:\\tmp\\finding one.txt",+ "text:C:\\tmp\\finding one.txt","\\\\server\\share\\issue.txt",],dependencies({@@ -983,6 +983,17 @@ describe("CLI skill commands", () => {const stderr = captureCli(main, "stderr");expect(await stderr.run([command, url], deps)).toBe(2);expect(stderr.text()).toContain("finding #1.md");+ for (const path of [+ file,+ "./missing.md",+ "../missing.md",+ "~/missing.md",+ ]) {+ expect(await stderr.run([command, path], deps)).toBe(2);+ expect(stderr.text()).toContain(+ path === file ? "finding #1.md" : "missing.md",+ );+ }}const stderr = captureCli(main, "stderr");expect(@@ -993,6 +1004,10 @@ describe("CLI skill commands", () => {).toBe(2);expect(stderr.text()).toContain("must refer to local files");expect(onCodex).not.toHaveBeenCalled();+ expect(+ await runCapturedCli(main, ["validate", "text:./missing.md"], deps),+ ).toBe(0);+ expect(onCodex.mock.lastCall?.[3]).toContain("./missing.md");await writeFile(file, "Finding supplied through a file URL.");expect(await runCapturedCli(main, ["validate", url], deps)).toBe(0);expect(onCodex.mock.lastCall?.[3]).toContain(diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex cad4cb5ab..ec4694f15 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -3,6 +3,7 @@ import { parseJsonLines } from "./support/json.js";import { writeFileSync } from "node:fs";import {chmod,+ link,mkdir,mkdtemp,readFile,@@ -1287,14 +1288,15 @@ describe("CLI", () => {hook,"#!/bin/sh\nset -eu\nexec npx --no-install codex-security scan . --working-tree --fail-on-severity medium\n",);- const migratedHook = captureCli(main, "stdout");+ const migratedHook = createCliTest(main);expect(- await migratedHook.run(+ await migratedHook.runCli(["install-hook", ".", "--fail-on-severity", "medium", "--json"],deps,),+ migratedHook.stderr.text(),).toBe(0);- const migrated = JSON.parse(migratedHook.text()) as {+ const migrated = JSON.parse(migratedHook.stdout.text()) as {hook: string;failOnSeverity: string;};@@ -1307,19 +1309,18 @@ describe("CLI", () => {]) {await writeFile(hook, trustedHook.replace(/^unset .*\n/m, unset));expect(- await migratedHook.run(+ await migratedHook.runCli(["install-hook", ".", "--fail-on-severity", "medium", "--json"],deps,),+ migratedHook.stderr.text(),).toBe(0);expect(await readFile(hook, "utf8")).toBe(trustedHook);}- const existingHook = captureCli(main, "stderr");- expect(await existingHook.run(["install-hook", "."], deps)).toBe(2);- expect(existingHook.text()).toContain("A pre-commit hook already exists");- expect(await readFile(hook, "utf8")).toContain(- "--fail-on-severity medium",+ expect(await runCapturedCli(main, ["install-hook", "."], deps)).toBe(0);+ expect(await readFile(hook, "utf8")).toBe(+ trustedHook.replace("severity medium", "severity high"),);const customHook = "#!/bin/sh\nexit 0\n";@@ -1335,7 +1336,20 @@ describe("CLI", () => {"A pre-commit hook already exists",);expect(await readFile(hook, "utf8")).toBe(customHook);- await writeFile(hook, trustedHook);+ const other = join(root, "other-hook");+ await writeFile(other, trustedHook);+ await rm(hook);+ await link(other, hook);+ expect(await runCapturedCli(main, ["install-hook", "."], deps)).toBe(2);+ expect(await readFile(other, "utf8")).toBe(trustedHook);+ await rm(hook);+ if (process.platform !== "win32") {+ await symlink(other, hook);+ expect(await runCapturedCli(main, ["install-hook", "."], deps)).toBe(2);+ expect(await readFile(other, "utf8")).toBe(trustedHook);+ await rm(hook);+ }+ await writeFile(hook, trustedHook, { mode: 0o755 });const binaries = join(root, "test-binaries");await mkdir(binaries);@@ -1863,6 +1877,7 @@ describe("CLI", () => {"--knowledge-base","/shared/threat-models",],+ ["bulk-scan", "--output-dir", "results"],["bulk-scan", "--provider", "openrouter"],["bulk-scan", "--provider=openrouter", "--model", "openai/gpt-5.4"],["bulk-scan", "--provider", "fireworks"],@@ -1896,19 +1911,6 @@ describe("CLI", () => {expect(stdout.text()).toBe("");});- test("rejects an output directory without a repository CSV", async () => {- const stderr = captureCli(main, "stderr");- expect(- await stderr.run(- ["bulk-scan", "--output-dir", "results"],- dependencies(),- ),- ).toBe(2);- expect(stderr.text()).toContain(- "--output-dir can only be used with a repository CSV",- );- });-test("exposes only typed, read-only SDK metadata over MCP", async () => {const child = await runCommand(process.execPath,diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex f191d082f..b27e51039 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -1971,19 +1971,58 @@ test.each(["auto", "explicit", "file"])(: selection === "file"? ["--components-file", planFile]: selected.flatMap(({ paths }) => ["--component", paths[0]!]);- const result = await cli(paths, [...args, "--plan-only"], {- planComponents: async () => ({ components: selected }),- createSecurity: throwing("unexpected scan"),- });- expect(result.code).toBe(0);+ const result = await cli(+ paths,+ [+ ...args,+ "--plan-only",+ ...(selection === "auto"+ ? []+ : [+ "--auth",+ "api-key",+ "--workers=2",+ "--max-total-cost=3",+ "--max-cost",+ "1.5",+ "--codex",+ 'model_providers.example.http_headers.Example="synthetic-header"',+ ]),+ ],+ {+ environment: {},+ planComponents: async () => ({ components: selected }),+ createSecurity: throwing("unexpected scan"),+ },+ );+ expect(result.code, result.stderr).toBe(0);expect(await json(join(paths.outputDir, "components.json"))).toEqual({components:selection === "explicit"? selected.map(({ paths }) => ({ name: paths[0], paths })): selected,});- expect(JSON.parse(result.stdout).planPath).toBe(- join(paths.outputDir, "components.json"),+ const plan = JSON.parse(result.stdout);+ expect(plan.planPath).toBe(join(paths.outputDir, "components.json"));+ expect(plan.nextCommand).toContain("codex-security scan-components");+ expect(plan.nextCommand).toContain("--components-file");+ expect(plan.nextCommand).toContain(join(paths.outputDir, "results"));+ if (selection !== "auto") {+ expect(plan.nextCommand).toContain("--auth api-key");+ expect(plan.nextCommand).toContain("--workers 2");+ expect(plan.nextCommand).toContain("--max-cost 1.5");+ expect(plan.nextCommand).toContain("--max-total-cost 3");+ expect(plan.nextCommandNote).toContain("--codex");+ expect(result.stdout + result.stderr).not.toContain("synthetic-header");+ }+ const occupied = await cli(paths, [+ "--components-file",+ plan.planPath,+ "--plan-only",+ ]);+ expect(occupied.code).toBe(2);+ expect(occupied.stderr).toContain(+ "Choose a new or empty directory with --output-dir",);},);