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
feat: add custom scan prompts and follow-up prompts (#297)
ianw-oai0facad0b2bda
diff --git a/README.md b/README.mdindex fa71e84bd..385769fcf 100644--- a/README.md+++ b/README.md@@ -18,6 +18,7 @@ npm install @openai/codex-securitynpx @openai/codex-security loginnpx @openai/codex-security scan .npx @openai/codex-security scan . --model gpt-5.6-terra --effort high+npx @openai/codex-security scan . --scan-prompt-file scan.md --post-scan-prompt-file follow-up.mdnpx @openai/codex-security scan . --mode deep --workers 2 --subagents 0 --stop-after-no-new 3 --max-discovery-runs 10```@@ -113,6 +114,11 @@ hardening.Pass `--knowledge-base PATH` to share security documents with every repository;repeat the option for multiple files or directories.+Use `--scan-prompt-file PATH` to add shared scan instructions, and add a `prompt`+CSV column for repository-specific instructions. Use+`--post-scan-prompt-file PATH` to run a follow-up after each completed,+validated scan.+For complete command help, runtime defaults, native multi-agent worker limits,environment variables, deep-scan configuration, and SDK options, see the[package README](sdk/typescript/README.md) and thediff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex f14e237dc..ce3026841 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -200,6 +200,7 @@ npx @openai/codex-security scan /path/to/repository --model gpt-5.6-terranpx @openai/codex-security scan /path/to/repository --model gpt-5.6-terra --effort highnpx @openai/codex-security scan /path/to/repository --path src --path testsnpx @openai/codex-security scan /path/to/repository --knowledge-base /path/to/threat-models --knowledge-base /path/to/architecture.pdf+npx @openai/codex-security scan /path/to/repository --scan-prompt-file scan.md --post-scan-prompt-file follow-up.mdnpx @openai/codex-security scan /path/to/repository --diff origin/main --jsonnpx @openai/codex-security scan /path/to/repository --output-dir /path/outside/repository/resultsnpx @openai/codex-security scan /path/to/repository --output-dir /path/outside/repository/results --archive-existing@@ -212,6 +213,7 @@ npx @openai/codex-security install-hooknpx @openai/codex-security bulk-scannpx @openai/codex-security bulk-scan --model gpt-5.6-terra --effort highnpx @openai/codex-security bulk-scan repositories.csv --output-dir /path/outside/repositories/security-scans --workers 4 --knowledge-base /path/to/threat-models --knowledge-base /path/to/architecture.pdf+npx @openai/codex-security bulk-scan repositories.csv --output-dir /path/outside/repositories/security-scans --scan-prompt-file scan.md --post-scan-prompt-file follow-up.mdnpx @openai/codex-security scans list /path/to/repositorynpx @openai/codex-security scans list --scan-root /path/outside/repository/resultsnpx @openai/codex-security scans show SCAN_ID@@ -478,13 +480,18 @@ configuration. The selected repositories are saved toTo use an existing repository list or run in CI, pass a CSV with required `id`,`repository`, and `revision` columns. Revisions must be full commit hashes;-optional `scope` and `mode` columns narrow individual scans:+optional `scope`, `mode`, and `prompt` columns customize individual scans:```csv-id,repository,revision,scope,mode-service,https://github.com/acme/service.git,0123456789abcdef0123456789abcdef01234567,src,standard+id,repository,revision,scope,mode,prompt+service,https://github.com/acme/service.git,0123456789abcdef0123456789abcdef01234567,src,standard,Focus on authentication and authorization.```+Use `--scan-prompt-file PATH` to add instructions to a scan or every bulk scan.+Bulk scans append each repository's CSV `prompt` after the shared instructions.+Use `--post-scan-prompt-file PATH` to run a follow-up in the same authenticated+session after each completed scan has been validated.+`--workers` limits concurrent scans and `--max-attempts` retries failures.Results remain under `--output-dir`; rerun the same command to resume.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 3e94f2ddb..38904dffd 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -150,6 +150,8 @@ export interface ScanOptions extends DeepScanOptions {target?: ScanTarget;mode?: ScanMode;knowledgeBasePaths?: string[];+ scanPrompt?: string;+ postScanPrompt?: string;outputDir?: string;archiveExisting?: boolean;parentScanId?: string;@@ -639,6 +641,7 @@ export class CodexSecurity {mode,runtime.configPath !== undefined,knowledgeBase !== null,+ options.scanPrompt,);checkOpen();const expectation: ScanExpectation = {@@ -1038,6 +1041,27 @@ export class CodexSecurity {}}}+ if (+ options.postScanPrompt?.trim() &&+ result.coverage.completeness === "complete"+ ) {+ const followUp = await thread.runStreamed(options.postScanPrompt, {+ signal,+ });+ await runScanEvents({+ thread,+ events: followUp.events,+ signal,+ scanDir,+ pluginRoot: runtime.plugin.installedRoot,+ expectation,+ model,+ onReconnect: options.onReconnect,+ onWorkerStatus: options.onWorkerStatus,+ onObserverError: options.onObserverError,+ });+ checkOpen();+ }return result;} catch (error) {// Recorded first: everything below can throw a different error for this same failed@@ -1955,6 +1979,7 @@ async function scanPrompt(mode: ScanMode,hasConfigPath = false,hasKnowledgeBase = false,+ additionalPrompt?: string,): Promise<string> {const skillName = skillNameFor(target, mode);const skillPath = join(pluginRoot, "skills", skillName, "SKILL.md");@@ -2009,6 +2034,9 @@ async function scanPrompt("Runtime paths are environment-backed; keep them quoted in POSIX shells and use the corresponding $env: names in PowerShell. Do not copy or reparse their values.",targetInstruction(target),"Write the complete canonical scan-manifest.json, findings.json, and coverage.json, but do not finalize or seal them; the SDK workbench owns authoritative metadata, finalization, report generation, and sealing.",+ ...(additionalPrompt?.trim()+ ? ["Additional scan instructions:", additionalPrompt]+ : []),].join("\n");}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex eac5b514d..2ba944810 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -172,6 +172,8 @@ const VALUE_OPTIONS = new Set(["--auth","--path","--knowledge-base",+ "--scan-prompt-file",+ "--post-scan-prompt-file","--diff","--head","--base",@@ -247,12 +249,33 @@ const DEEP_SCAN_OPTION_SCHEMAS = {.describe("Maximum deep-scan discovery runs."),};+async function readPromptFiles(+ directory: string,+ scanPromptFile?: string,+ postScanPromptFile?: string,+): Promise<Pick<ScanOptions, "scanPrompt" | "postScanPrompt">> {+ const [scanPrompt, postScanPrompt] = await Promise.all([+ scanPromptFile === undefined+ ? undefined+ : readFile(resolve(directory, scanPromptFile), "utf8"),+ postScanPromptFile === undefined+ ? undefined+ : readFile(resolve(directory, postScanPromptFile), "utf8"),+ ]);+ return {+ ...(scanPrompt?.trim() ? { scanPrompt } : {}),+ ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),+ };+}+interface ScanArguments extends DeepScanOptions {auth?: ScanAuthMode;verbose?: boolean;repository?: string;paths: string[];knowledgeBasePaths: string[];+ scanPromptFile?: string;+ postScanPromptFile?: string;diff?: string;workingTree: boolean;head?: string;@@ -1042,6 +1065,12 @@ export async function main(.describe("Add security-context files or directories; repeat for multiple paths.",),+ scanPromptFile: optionValue("--scan-prompt-file")+ .optional()+ .describe("Append scan instructions from FILE."),+ postScanPromptFile: optionValue("--post-scan-prompt-file")+ .optional()+ .describe("Run instructions from FILE after a validated scan."),diff: optionValue("--diff").optional().describe("Scan committed Git changes from BASE to --head."),@@ -1175,6 +1204,8 @@ export async function main(repository: args.repository,paths: options.path,knowledgeBasePaths: options.knowledgeBase,+ scanPromptFile: options.scanPromptFile,+ postScanPromptFile: options.postScanPromptFile,diff: options.diff,workingTree: options.workingTree,head: options.head,@@ -1328,6 +1359,12 @@ export async function main(.enum(["standard", "deep"]).default("standard").describe("Default scan mode for repositories without a CSV mode."),+ scanPromptFile: optionValue("--scan-prompt-file")+ .optional()+ .describe("Append instructions from FILE to every scan."),+ postScanPromptFile: optionValue("--post-scan-prompt-file")+ .optional()+ .describe("Run FILE after each completed, validated scan."),model: optionValue("--model").optional().describe(@@ -1378,6 +1415,11 @@ export async function main(dependencies.addSignalListener("SIGTERM", onTerminate);try {const currentDirectory = dependencies.currentDirectory();+ const prompts = await readPromptFiles(+ currentDirectory,+ options.scanPromptFile,+ options.postScanPromptFile,+ );let inputPath: string;let outputDir: string;let githubHost: string | undefined;@@ -1390,7 +1432,9 @@ export async function main(argument === "--effort" ||argument === "--provider" ||argument === "--codex" ||- argument === "--knowledge-base"+ argument === "--knowledge-base" ||+ argument === "--scan-prompt-file" ||+ argument === "--post-scan-prompt-file") {optionIndex += 2;} else if (@@ -1398,7 +1442,9 @@ export async function main(argument.startsWith("--effort=") ||argument.startsWith("--provider=") ||argument.startsWith("--codex=") ||- argument.startsWith("--knowledge-base=")+ argument.startsWith("--knowledge-base=") ||+ argument.startsWith("--scan-prompt-file=") ||+ argument.startsWith("--post-scan-prompt-file=")) {optionIndex += 1;} else {@@ -1440,6 +1486,7 @@ export async function main(mode: options.mode,maxAttempts: options.maxAttempts,knowledgeBasePaths: options.knowledgeBase,+ ...prompts,config: {pluginPath: options.pluginPath,pythonPath: options.python,@@ -2717,6 +2764,11 @@ async function runScan(try {const repository = arguments_.repository ?? dependencies.currentDirectory();const target = targetFromArguments(arguments_);+ const prompts = await readPromptFiles(+ dependencies.currentDirectory(),+ arguments_.scanPromptFile,+ arguments_.postScanPromptFile,+ );const config: CodexSecurityConfig = {pluginPath: arguments_.pluginPath,pythonPath: arguments_.pythonPath,@@ -2868,6 +2920,7 @@ async function runScan(auth,target,knowledgeBasePaths: arguments_.knowledgeBasePaths,+ ...prompts,mode: arguments_.mode,workers: arguments_.workers,subagents: arguments_.subagents,diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex eaed6f288..c0ae08aff 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -39,6 +39,7 @@ interface MultiscanTask {revision: string;mode: ScanMode;scope?: string;+ prompt?: string;}interface MultiscanReceipt extends MultiscanTask {@@ -57,6 +58,8 @@ export interface MultiscanOptions {workers: number;mode: ScanMode;maxAttempts: number;+ scanPrompt?: string;+ postScanPrompt?: string;config: CodexSecurityConfig;createSecurity(config: CodexSecurityConfig,@@ -111,7 +114,7 @@ async function runCampaign(const ledger = join(output, "results.jsonl");await ensureOutputDirectory(join(output, "checkouts"));await ensureOutputDirectory(join(output, "artifacts"));- await ensureManifest(join(output, "manifest.json"), tasks);+ await ensureManifest(join(output, "manifest.json"), tasks, options);const receipts = await readReceipts(ledger);const pending: MultiscanTask[] = [];let completed = 0;@@ -184,6 +187,9 @@ async function runCampaign(throw new Error("Multiscan scope escapes its repository.");}}+ const scanPrompt = [options.scanPrompt?.trim(), task.prompt]+ .filter(Boolean)+ .join("\n\n");const result = await security.run(checkout, {...(task.scope === undefined ? {} : { target: [task.scope] }),...(options.knowledgeBasePaths?.length@@ -191,6 +197,10 @@ async function runCampaign(: {}),mode: task.mode,outputDir: scanDir,+ ...(scanPrompt ? { scanPrompt } : {}),+ ...(options.postScanPrompt === undefined+ ? {}+ : { postScanPrompt: options.postScanPrompt }),...(options.signal === undefined ? {} : { signal: options.signal }),});cost = result.cost;@@ -432,8 +442,22 @@ async function recoverLock(async function ensureManifest(path: string,tasks: MultiscanTask[],+ options: Pick<MultiscanOptions, "scanPrompt" | "postScanPrompt">,): Promise<void> {- const expected = `${JSON.stringify({ version: 1, tasks }, null, 2)}\n`;+ const expected = `${JSON.stringify(+ {+ version: 1,+ tasks,+ ...(options.scanPrompt === undefined+ ? {}+ : { scanPrompt: options.scanPrompt }),+ ...(options.postScanPrompt === undefined+ ? {}+ : { postScanPrompt: options.postScanPrompt }),+ },+ null,+ 2,+ )}\n`;try {await writeFile(path, expected, { flag: "wx", mode: 0o600 });} catch (error) {@@ -531,6 +555,7 @@ function parseInventory(throw new Error("Multiscan mode must be standard or deep.");}const scope = get("scope");+ const prompt = get("prompt");if (scope &&(isAbsolute(scope) ||@@ -546,6 +571,7 @@ function parseInventory(revision,mode,...(scope ? { scope } : {}),+ ...(prompt ? { prompt } : {}),};});}diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex c8045b47a..b5905c0fe 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1745,6 +1745,7 @@ describe("CodexSecurity orchestration", () => {let codexOptions: CodexOptions | null = null;let threadOptions: Record<string, unknown> | null = null;let prompt = "";+ let followUpPrompt = "";let scanStarted = false;const warnings: string[] = [];const warningDetails: Array<{ kind: "target_changed" } | undefined> = [];@@ -1812,6 +1813,11 @@ describe("CodexSecurity orchestration", () => {return {id: null,async runStreamed(input: string) {+ if (prompt !== "") {+ expect(commands.at(-1)?.[0]).toBe("complete-scan");+ followUpPrompt = input;+ return { events: completedEvents() };+ }expect(commands[0]?.[0]).toBe("register-cli-scan");prompt = input;await copyCompletedScan(root);@@ -1830,6 +1836,8 @@ describe("CodexSecurity orchestration", () => {const scanStartedAt = Date.now();const result = await client.run(repository, {+ scanPrompt: "Focus on authentication and authorization.",+ postScanPrompt: "Draft fixes for confirmed findings.",onScanStarted: () => {scanStarted = true;},@@ -1913,6 +1921,10 @@ describe("CodexSecurity orchestration", () => {),),).toBe(false);+ expect(prompt).toContain(+ "Additional scan instructions:\nFocus on authentication and authorization.",+ );+ expect(followUpPrompt).toBe("Draft fixes for confirmed findings.");expect(JSON.parse(commands[0]![commands[0]!.indexOf("--recipe-json") + 1]!),).toMatchObject({@@ -2696,6 +2708,63 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("surfaces post-scan failures without reopening a completed scan", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ const commands: Array<readonly string[]> = [];+ let turns = 0;++ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_options: unknown, args: readonly string[]) => {+ commands.push(args);+ return mockWorkbench(args);+ },+ createCodex: () => ({+ startThread: () => ({+ id: "thread-1",+ async runStreamed() {+ turns += 1;+ if (turns === 1) {+ await copyCompletedScan(root);+ return { events: completedEvents() };+ }+ async function* failedEvents(): AsyncGenerator<ThreadEvent> {+ yield {+ type: "turn.failed",+ error: { message: "Could not draft fixes." },+ };+ }+ return { events: failedEvents() };+ },+ }),+ }),+ },+ );++ await expect(+ client.run(repository, { postScanPrompt: "Draft confirmed fixes." }),+ ).rejects.toThrow("Could not draft fixes.");+ expect(commands.map((command) => command[0])).toEqual([+ "register-cli-scan",+ "get-scan-feedback",+ "prepare-scan-completion",+ "complete-scan",+ ]);+ await client.close();+ });+test("stops and records a scan as soon as its live cost exceeds the limit", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli-scan-prompts.test.ts b/sdk/typescript/tests-ts/cli-scan-prompts.test.tsnew file mode 100644index 000000000..fae386087--- /dev/null+++ b/sdk/typescript/tests-ts/cli-scan-prompts.test.ts@@ -0,0 +1,113 @@+import { spawnSync } from "node:child_process";+import { mkdtemp, rm, 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 { capture, dependencies } from "./cli-fixtures.js";++describe("CLI scan prompts", () => {+ test("loads scan and post-scan prompt files", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-cli-prompts-"));+ try {+ await Promise.all([+ writeFile(join(root, "scan.md"), "Review authentication boundaries.\n"),+ writeFile(join(root, "follow-up.md"), "Draft confirmed fixes.\n"),+ ]);+ let options: unknown;+ expect(+ await main(+ [+ "scan",+ ".",+ "--scan-prompt-file",+ "scan.md",+ "--post-scan-prompt-file",+ "follow-up.md",+ "--json",+ ],+ capture().stream,+ capture().stream,+ dependencies({+ currentDirectory: root,+ onTurn: (_repository, value) => (options = value),+ }),+ ),+ ).toBe(0);+ expect(options).toMatchObject({+ scanPrompt: "Review authentication boundaries.\n",+ postScanPrompt: "Draft confirmed fixes.\n",+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ test("combines shared and repository-specific bulk scan prompts", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-cli-prompts-"));+ try {+ const repository = join(root, "repository");+ for (const args of [+ ["init", "-q", repository],+ [+ "-C",+ repository,+ "-c",+ "[email protected]",+ "-c",+ "user.name=Test",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "--allow-empty",+ "-qm",+ "initial",+ ],+ ]) {+ expect(spawnSync("git", args, { encoding: "utf8" }).status).toBe(0);+ }+ const revision = spawnSync(+ "git",+ ["-C", repository, "rev-parse", "HEAD"],+ { encoding: "utf8" },+ ).stdout.trim();+ await Promise.all([+ writeFile(+ join(root, "repositories.csv"),+ `id,repository,revision,prompt\nsample,${repository},${revision},Focus on authorization.\n`,+ ),+ writeFile(join(root, "scan.md"), "Review authentication boundaries.\n"),+ writeFile(join(root, "follow-up.md"), "Draft confirmed fixes.\n"),+ ]);+ let options: unknown;+ expect(+ await main(+ [+ "bulk-scan",+ "repositories.csv",+ "--output-dir",+ "results",+ "--scan-prompt-file",+ "scan.md",+ "--post-scan-prompt-file",+ "follow-up.md",+ "--json",+ ],+ capture().stream,+ capture().stream,+ dependencies({+ currentDirectory: root,+ onTurn: (_repository, value) => (options = value),+ }),+ ),+ ).toBe(0);+ expect(options).toMatchObject({+ scanPrompt:+ "Review authentication boundaries.\n\nFocus on authorization.",+ postScanPrompt: "Draft confirmed fixes.\n",+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex 3d803096f..21cb3cb6d 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -189,7 +189,7 @@ describe("multiscan", () => {const source = await repository(paths.root, "comma, quoted");await writeFile(paths.input,- `\uFEFF"id","repository","revision","scope","mode","notes"\r\n"payments","${source.path}","${source.revision}","src","deep","contains ""quotes"""\r\n\r\n`,+ `\uFEFF"id","repository","revision","scope","mode","prompt","notes"\r\n"payments","${source.path}","${source.revision}","src","deep","Focus on authentication, authorization.","contains ""quotes"""\r\n\r\n`,);const summary = await runMultiscan(@@ -198,8 +198,16 @@ describe("multiscan", () => {client(async (_repository, scanOptions = {}) => {expect(scanOptions.target).toEqual(["src"]);expect(scanOptions.mode).toBe("deep");+ expect(scanOptions.scanPrompt).toBe(+ "Review boundaries.\n\nFocus on authentication, authorization.",+ );+ expect(scanOptions.postScanPrompt).toBe("Draft confirmed fixes.");return await completedScan(scanOptions.outputDir!);}),+ {+ scanPrompt: "Review boundaries.",+ postScanPrompt: "Draft confirmed fixes.",+ },),);@@ -207,6 +215,15 @@ describe("multiscan", () => {expect(await results(summary.resultsPath)).toMatchObject([{ id: "payments", repository: source.path },]);+ expect(+ JSON.parse(await readFile(join(paths.output, "manifest.json"), "utf8")),+ ).toMatchObject({+ scanPrompt: "Review boundaries.",+ postScanPrompt: "Draft confirmed fixes.",+ tasks: [+ { id: "payments", prompt: "Focus on authentication, authorization." },+ ],+ });});test("records each completed scan's cost in the resumable ledger", async () => {@@ -909,6 +926,15 @@ describe("multiscan", () => {const resumed = await runMultiscan(options(paths, security));expect(resumed).toMatchObject({ completed: 1, failed: 0, skipped: 1 });expect(calls).toBe(1);+ for (const prompts of [+ { scanPrompt: "Review different boundaries." },+ { postScanPrompt: "Draft confirmed fixes." },+ ]) {+ await expect(+ runMultiscan(options(paths, security, prompts)),+ ).rejects.toThrow("manifest does not match");+ }+ expect(calls).toBe(1);const [receipt] = await results(initial.resultsPath);await rm(join(receipt!["outputDir"] as string, "report.md"));