@openai/codex-security 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +228 -18
  2. package/_bundled_plugin/.app.json +1 -1
  3. package/_bundled_plugin/.mcp.json +10 -3
  4. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  6. package/_bundled_plugin/references/config-preflight.md +1 -1
  7. package/_bundled_plugin/references/core-scan.md +1 -1
  8. package/_bundled_plugin/references/final-report.md +4 -2
  9. package/_bundled_plugin/references/sarif-adapter.md +2 -0
  10. package/_bundled_plugin/references/scan-artifacts.md +1 -1
  11. package/_bundled_plugin/references/scan-contract.md +18 -7
  12. package/_bundled_plugin/schemas/scan-manifest.schema.json +2 -2
  13. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +23 -0
  14. package/_bundled_plugin/scripts/deep_scan_workbench.py +122 -7
  15. package/_bundled_plugin/scripts/finalize_scan_contract.py +106 -38
  16. package/_bundled_plugin/scripts/generate_in_scope_files.py +20 -0
  17. package/_bundled_plugin/scripts/generate_rank_input.py +23 -7
  18. package/_bundled_plugin/scripts/launch_codex_security_mcp +32 -0
  19. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +27 -0
  20. package/_bundled_plugin/scripts/report_projection.py +19 -8
  21. package/_bundled_plugin/scripts/workbench_cli.py +35 -15
  22. package/_bundled_plugin/scripts/workbench_db.py +184 -202
  23. package/_bundled_plugin/scripts/workbench_finding_index.py +101 -0
  24. package/_bundled_plugin/scripts/workbench_progress.py +6 -3
  25. package/_bundled_plugin/scripts/workbench_remediation.py +19 -0
  26. package/_bundled_plugin/scripts/workbench_saved_results.py +1289 -0
  27. package/_bundled_plugin/scripts/workbench_scan_history.py +17 -2
  28. package/_bundled_plugin/scripts/workbench_schema.py +28 -0
  29. package/_bundled_plugin/scripts/workbench_target.py +36 -5
  30. package/_bundled_plugin/scripts/workbench_validation.py +9 -0
  31. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +4 -4
  32. package/_bundled_plugin/skills/fix-finding/SKILL.md +17 -1
  33. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +1 -1
  34. package/_bundled_plugin/skills/security-scan/SKILL.md +1 -1
  35. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +1 -1
  36. package/dist/api.d.ts +18 -1
  37. package/dist/api.d.ts.map +1 -1
  38. package/dist/api.js +234 -18
  39. package/dist/api.js.map +1 -1
  40. package/dist/cli.d.ts +5 -3
  41. package/dist/cli.d.ts.map +1 -1
  42. package/dist/cli.js +348 -43
  43. package/dist/cli.js.map +1 -1
  44. package/dist/component-plan.d.ts +15 -0
  45. package/dist/component-plan.d.ts.map +1 -0
  46. package/dist/component-plan.js +145 -0
  47. package/dist/component-plan.js.map +1 -0
  48. package/dist/component-scan.d.ts +83 -0
  49. package/dist/component-scan.d.ts.map +1 -0
  50. package/dist/component-scan.js +279 -0
  51. package/dist/component-scan.js.map +1 -0
  52. package/dist/contract.d.ts +8 -2
  53. package/dist/contract.d.ts.map +1 -1
  54. package/dist/contract.js +27 -8
  55. package/dist/contract.js.map +1 -1
  56. package/dist/cost-model.d.ts +20 -0
  57. package/dist/cost-model.d.ts.map +1 -0
  58. package/dist/cost-model.js +86 -0
  59. package/dist/cost-model.js.map +1 -0
  60. package/dist/cost.d.ts +2 -11
  61. package/dist/cost.d.ts.map +1 -1
  62. package/dist/cost.js +15 -98
  63. package/dist/cost.js.map +1 -1
  64. package/dist/custom-validation-prompt.d.ts +4 -0
  65. package/dist/custom-validation-prompt.d.ts.map +1 -0
  66. package/dist/custom-validation-prompt.js +94 -0
  67. package/dist/custom-validation-prompt.js.map +1 -0
  68. package/dist/custom-validation.d.ts +45 -0
  69. package/dist/custom-validation.d.ts.map +1 -0
  70. package/dist/custom-validation.js +292 -0
  71. package/dist/custom-validation.js.map +1 -0
  72. package/dist/errors.d.ts +1 -1
  73. package/dist/errors.d.ts.map +1 -1
  74. package/dist/errors.js +1 -1
  75. package/dist/errors.js.map +1 -1
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +2 -0
  79. package/dist/index.js.map +1 -1
  80. package/dist/models.d.ts +1 -1
  81. package/dist/models.d.ts.map +1 -1
  82. package/dist/models.js.map +1 -1
  83. package/dist/multiscan.d.ts +1 -0
  84. package/dist/multiscan.d.ts.map +1 -1
  85. package/dist/multiscan.js +53 -5
  86. package/dist/multiscan.js.map +1 -1
  87. package/dist/patch-tui.js +1 -1
  88. package/dist/patch-tui.js.map +1 -1
  89. package/dist/publication.d.ts.map +1 -1
  90. package/dist/publication.js +3 -4
  91. package/dist/publication.js.map +1 -1
  92. package/dist/runtime.d.ts +4 -2
  93. package/dist/runtime.d.ts.map +1 -1
  94. package/dist/runtime.js +109 -38
  95. package/dist/runtime.js.map +1 -1
  96. package/dist/scan-comparison.d.ts +12 -5
  97. package/dist/scan-comparison.d.ts.map +1 -1
  98. package/dist/scan-comparison.js +72 -28
  99. package/dist/scan-comparison.js.map +1 -1
  100. package/dist/scan-dashboard.d.ts +9 -2
  101. package/dist/scan-dashboard.d.ts.map +1 -1
  102. package/dist/scan-dashboard.js +198 -3
  103. package/dist/scan-dashboard.js.map +1 -1
  104. package/dist/scan-logs.d.ts.map +1 -1
  105. package/dist/scan-logs.js +5 -21
  106. package/dist/scan-logs.js.map +1 -1
  107. package/dist/scan-sessions.d.ts +4 -0
  108. package/dist/scan-sessions.d.ts.map +1 -0
  109. package/dist/scan-sessions.js +35 -0
  110. package/dist/scan-sessions.js.map +1 -0
  111. package/dist/targets.d.ts.map +1 -1
  112. package/dist/targets.js +16 -1
  113. package/dist/targets.js.map +1 -1
  114. package/dist/version.d.ts.map +1 -1
  115. package/dist/version.js +2 -20
  116. package/dist/version.js.map +1 -1
  117. package/dist/windows-path.d.ts +3 -0
  118. package/dist/windows-path.d.ts.map +1 -0
  119. package/dist/windows-path.js +16 -0
  120. package/dist/windows-path.js.map +1 -0
  121. package/dist/worker-progress.d.ts +1 -0
  122. package/dist/worker-progress.d.ts.map +1 -1
  123. package/dist/worker-progress.js +12 -0
  124. package/dist/worker-progress.js.map +1 -1
  125. package/package.json +8 -2
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  import { promisify, stripVTControlCharacters } from "node:util";
12
12
  import { Cli, z } from "incur";
13
13
  import { parse as parseToml } from "smol-toml";
14
- import { classifyConnectionFailure, createSecurityInternal, listRepositoryFindings, scanAuthentication, } from "./api.js";
14
+ import { classifyConnectionFailure, createSecurityInternal, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, } from "./api.js";
15
15
  import { accountStatus } from "./auth.js";
16
16
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
17
17
  import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, } from "./config.js";
@@ -19,13 +19,16 @@ import { formatUsd } from "./cost.js";
19
19
  import { CodexSecurityError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
20
20
  import { importLinearIssues, resolveLinearApiKey, } from "./linear.js";
21
21
  import { runMultiscan } from "./multiscan.js";
22
+ import { componentPlanSchema } from "./component-plan.js";
23
+ import { runComponentScans } from "./component-scan.js";
22
24
  import { publishScan, } from "./publish.js";
23
- import { bundledPluginRoot, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
25
+ import { bundledPluginRoot, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
24
26
  import { matchScanFindingsInternal, } from "./scan-comparison.js";
25
27
  import { scanActivitiesFromEvent } from "./scan-activity.js";
26
28
  import { readScanLogs } from "./scan-logs.js";
27
29
  import { renderScanHistory, } from "./scan-history-renderer.js";
28
30
  import { ScanDashboard } from "./scan-dashboard.js";
31
+ import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
29
32
  import { abortable, DiffTarget, } from "./targets.js";
30
33
  import { resolveTrustedExecutable } from "./trusted-executable.js";
31
34
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
@@ -69,9 +72,13 @@ const EXPORT_DEFAULT_OUTPUTS = {
69
72
  };
70
73
  const VALUE_OPTIONS = new Set([
71
74
  "--auth",
75
+ "--safety-identifier",
72
76
  "--path",
77
+ "--component",
78
+ "--components-file",
73
79
  "--knowledge-base",
74
80
  "--scan-prompt-file",
81
+ "--validation-prompt-file",
75
82
  "--post-scan-prompt-file",
76
83
  "--diff",
77
84
  "--head",
@@ -121,7 +128,7 @@ const PROVIDER_OPTION = z
121
128
  const CREATE_PR_OPTION = z
122
129
  .boolean()
123
130
  .default(false)
124
- .describe("Create a GitHub pull request after verified patches.");
131
+ .describe("Create a draft GitHub pull request after verified patches.");
125
132
  function optionValue(flag) {
126
133
  return z.string().min(1, `${flag} must not be empty.`);
127
134
  }
@@ -534,17 +541,24 @@ const DEEP_SCAN_OPTION_SCHEMAS = {
534
541
  .optional()
535
542
  .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
536
543
  };
537
- async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory) {
538
- const [scanPrompt, postScanPrompt] = await Promise.all([
544
+ async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory, validationPromptFile) {
545
+ const [scanPrompt, postScanPrompt, validationPrompt] = await Promise.all([
539
546
  scanPromptFile === undefined
540
547
  ? undefined
541
548
  : readRegularInputFile(resolveCliPath(directory, scanPromptFile), repository),
542
549
  postScanPromptFile === undefined
543
550
  ? undefined
544
551
  : readRegularInputFile(resolveCliPath(directory, postScanPromptFile), repository),
552
+ validationPromptFile === undefined
553
+ ? undefined
554
+ : readRegularInputFile(resolveCliPath(directory, validationPromptFile), repository),
545
555
  ]);
556
+ if (validationPrompt !== undefined && !validationPrompt.trim()) {
557
+ throw new CodexSecurityError("The validation prompt must not be empty.");
558
+ }
546
559
  return {
547
560
  ...(scanPrompt?.trim() ? { scanPrompt } : {}),
561
+ ...(validationPrompt === undefined ? {} : { validationPrompt }),
548
562
  ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
549
563
  };
550
564
  }
@@ -632,7 +646,7 @@ const DEFAULT_DEPENDENCIES = {
632
646
  writeSync(stream.fd, value);
633
647
  },
634
648
  forceExit: (signal) => process.kill(process.pid, signal),
635
- runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment),
649
+ runCodex: (args, output, environment, input) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment, input),
636
650
  runRepositoryCommand: async (command, args, repository) => {
637
651
  const executable = await resolveTrustedExecutable(command, process.env, repository);
638
652
  if (executable === null) {
@@ -654,6 +668,8 @@ const DEFAULT_DEPENDENCIES = {
654
668
  const plugin = await bundledPluginRoot();
655
669
  const invocation = spawn(python, [
656
670
  "-I",
671
+ "-X",
672
+ "utf8",
657
673
  join(plugin, "scripts", "finalize_scan_contract.py"),
658
674
  "--scan-dir",
659
675
  arguments_.scanDir,
@@ -699,7 +715,7 @@ const DEFAULT_DEPENDENCIES = {
699
715
  }
700
716
  return undefined;
701
717
  },
702
- runWorkbench: async (args) => {
718
+ runWorkbench: async (args, input) => {
703
719
  const environment = {
704
720
  ...exportEnvironment(),
705
721
  CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -710,11 +726,11 @@ const DEFAULT_DEPENDENCIES = {
710
726
  pluginRoot: await bundledPluginRoot(),
711
727
  environment,
712
728
  failureMessage: "Could not read Codex Security scan history",
713
- }, args);
729
+ }, args, input);
714
730
  },
715
731
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
716
732
  };
717
- export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env) {
733
+ export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
718
734
  const configuredHome = processEnvironment["CODEX_HOME"];
719
735
  const environment = { ...processEnvironment };
720
736
  for (const name of Object.keys(environment)) {
@@ -728,10 +744,22 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
728
744
  env: environment,
729
745
  cwd: output?.appServer?.directory ?? parse(process.execPath).root,
730
746
  stdio: output === undefined
731
- ? "inherit"
732
- : [output.appServer === undefined ? "ignore" : "pipe", "pipe", "pipe"],
747
+ ? input === undefined
748
+ ? "inherit"
749
+ : ["pipe", "inherit", "inherit"]
750
+ : [
751
+ output.appServer !== undefined || input !== undefined
752
+ ? "pipe"
753
+ : "ignore",
754
+ "pipe",
755
+ "pipe",
756
+ ],
733
757
  windowsHide: true,
734
758
  });
759
+ if (input !== undefined) {
760
+ invocation.stdin?.on("error", () => { });
761
+ invocation.stdin?.end(input);
762
+ }
735
763
  let requestedSignal = null;
736
764
  let forcedTermination;
737
765
  let forceStatusCompletion = null;
@@ -876,7 +904,7 @@ async function writeCliOutput(output, value) {
876
904
  }
877
905
  }
878
906
  export function exportEnvironment(environment = process.env) {
879
- return Object.fromEntries([
907
+ return pythonUtf8Environment(Object.fromEntries([
880
908
  "PATH",
881
909
  "Path",
882
910
  "PATHEXT",
@@ -892,7 +920,7 @@ export function exportEnvironment(environment = process.env) {
892
920
  "LC_CTYPE",
893
921
  ]
894
922
  .filter((key) => environment[key] !== undefined)
895
- .map((key) => [key, environment[key]]));
923
+ .map((key) => [key, environment[key]])));
896
924
  }
897
925
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
898
926
  argv = defaultListCommand(argv);
@@ -932,7 +960,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
932
960
  catch (error) {
933
961
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
934
962
  exitCode = 2;
935
- return undefined;
963
+ throw error;
936
964
  }
937
965
  };
938
966
  const latestScans = async (count = 1, status = "complete") => {
@@ -970,9 +998,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
970
998
  beforeId,
971
999
  "--after-scan-id",
972
1000
  afterId,
973
- "--matches-json",
974
- JSON.stringify(await dependencies.matchFindings(matchingInputs)),
975
- ]);
1001
+ "--matches-json-stdin",
1002
+ ], JSON.stringify(await dependencies.matchFindings(matchingInputs)));
976
1003
  });
977
1004
  const presentHistory = (result, command, format, settings = {}) => {
978
1005
  if (result === undefined ||
@@ -1073,7 +1100,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1073
1100
  const directory = dependencies.currentDirectory();
1074
1101
  const scanRoot = options.scanRoot === undefined
1075
1102
  ? undefined
1076
- : resolveCliPath(directory, options.scanRoot);
1103
+ : process.platform === "win32"
1104
+ ? await canonicalizeModelSafePath(resolveCliPath(directory, options.scanRoot))
1105
+ : resolveCliPath(directory, options.scanRoot);
1077
1106
  const repository = scanRoot !== undefined && args.repository === undefined
1078
1107
  ? undefined
1079
1108
  : resolveCliPath(directory, args.repository ?? directory);
@@ -1167,6 +1196,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1167
1196
  .describe("Saved scan identifier (default: latest completed scan)."),
1168
1197
  }),
1169
1198
  options: z.object({
1199
+ validationPromptFile: optionValue("--validation-prompt-file")
1200
+ .optional()
1201
+ .describe("Use FILE for custom validation; required when rerunning a custom-validation scan."),
1170
1202
  verbose: z
1171
1203
  .boolean()
1172
1204
  .default(false)
@@ -1184,7 +1216,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1184
1216
  "--scan-id",
1185
1217
  scanId,
1186
1218
  ]);
1187
- scanArguments = scanArgumentsFromRecipe(recipe, scanId);
1219
+ scanArguments = scanArgumentsFromRecipe(recipe, scanId, options.validationPromptFile);
1188
1220
  scanArguments.verbose = options.verbose;
1189
1221
  }
1190
1222
  catch (error) {
@@ -1246,7 +1278,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1246
1278
  catch (error) {
1247
1279
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1248
1280
  exitCode = 2;
1249
- return undefined;
1281
+ throw error;
1250
1282
  }
1251
1283
  },
1252
1284
  })
@@ -1574,13 +1606,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1574
1606
  options: z
1575
1607
  .object({
1576
1608
  auth: z
1577
- .enum(["auto", "chatgpt", "api-key"])
1609
+ .enum(SCAN_AUTH_MODES)
1578
1610
  .default("auto")
1579
1611
  .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
1580
1612
  verbose: z
1581
1613
  .boolean()
1582
1614
  .default(false)
1583
1615
  .describe("Print scan diagnostics to stderr."),
1616
+ safetyIdentifier: optionValue("--safety-identifier")
1617
+ .optional()
1618
+ .describe("Stable hashed end-user ID for this scan's model requests (1–64 characters)."),
1584
1619
  path: z
1585
1620
  .array(optionValue("--path"))
1586
1621
  .default([])
@@ -1592,6 +1627,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1592
1627
  scanPromptFile: optionValue("--scan-prompt-file")
1593
1628
  .optional()
1594
1629
  .describe("Append scan instructions from FILE."),
1630
+ validationPromptFile: optionValue("--validation-prompt-file")
1631
+ .optional()
1632
+ .describe("Replace final validation with the workflow in FILE (not Deep)."),
1595
1633
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1596
1634
  .optional()
1597
1635
  .describe("Run FILE after each scan, including failures."),
@@ -1715,11 +1753,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1715
1753
  }
1716
1754
  const outcome = await runScan({
1717
1755
  auth: options.auth,
1756
+ safetyIdentifier: options.safetyIdentifier,
1718
1757
  verbose: options.verbose,
1719
1758
  repository: args.repository,
1720
1759
  paths: options.path,
1721
1760
  knowledgeBasePaths: options.knowledgeBase,
1722
1761
  scanPromptFile: options.scanPromptFile,
1762
+ validationPromptFile: options.validationPromptFile,
1723
1763
  postScanPromptFile: options.postScanPromptFile,
1724
1764
  diff: options.diff,
1725
1765
  workingTree: options.workingTree,
@@ -1831,6 +1871,209 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1831
1871
  .command(scanHistory)
1832
1872
  .command(findingFeedback)
1833
1873
  .command(publication)
1874
+ .command("scan-components", {
1875
+ description: "Run standard scans for project components and combine the results.",
1876
+ destructive: true,
1877
+ mcp: false,
1878
+ args: z.object({
1879
+ repository: z
1880
+ .string()
1881
+ .min(1)
1882
+ .optional()
1883
+ .describe("Project directory (default: current directory)."),
1884
+ }),
1885
+ options: z
1886
+ .object({
1887
+ auth: z
1888
+ .enum(SCAN_AUTH_MODES)
1889
+ .default("auto")
1890
+ .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
1891
+ component: z
1892
+ .array(optionValue("--component"))
1893
+ .default([])
1894
+ .describe("Scan this repository-relative path as a component; repeat for more."),
1895
+ componentsFile: optionValue("--components-file")
1896
+ .optional()
1897
+ .describe("Read a component plan from JSON."),
1898
+ auto: z
1899
+ .boolean()
1900
+ .default(false)
1901
+ .describe("Ask Codex to divide the project into components."),
1902
+ planOnly: z
1903
+ .boolean()
1904
+ .default(false)
1905
+ .describe("Save components.json without starting scans."),
1906
+ headless: z
1907
+ .boolean()
1908
+ .default(false)
1909
+ .describe("Print status lines instead of the interactive dashboard."),
1910
+ outputDir: optionValue("--output-dir").describe("Empty results directory outside the repository."),
1911
+ workers: z
1912
+ .number()
1913
+ .int()
1914
+ .positive()
1915
+ .default(4)
1916
+ .describe("Concurrent standard component scans."),
1917
+ knowledgeBase: z
1918
+ .array(optionValue("--knowledge-base"))
1919
+ .default([])
1920
+ .describe("Read shared security docs for every component."),
1921
+ scanPromptFile: optionValue("--scan-prompt-file")
1922
+ .optional()
1923
+ .describe("Append instructions from FILE to every scan."),
1924
+ postScanPromptFile: optionValue("--post-scan-prompt-file")
1925
+ .optional()
1926
+ .describe("Run FILE after each scan, including failures."),
1927
+ model: optionValue("--model")
1928
+ .optional()
1929
+ .describe("Model for planning and component scans."),
1930
+ effort: effortOption(),
1931
+ provider: PROVIDER_OPTION,
1932
+ maxCost: z
1933
+ .number()
1934
+ .positive()
1935
+ .optional()
1936
+ .describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
1937
+ pluginPath: optionValue("--plugin-path")
1938
+ .optional()
1939
+ .describe(PLUGIN_PATH_DESCRIPTION),
1940
+ python: optionValue("--python")
1941
+ .optional()
1942
+ .describe(PYTHON_PATH_DESCRIPTION),
1943
+ codex: z
1944
+ .array(optionValue("--codex"))
1945
+ .default([])
1946
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
1947
+ })
1948
+ .refine((options) => Number(options.component.length > 0) +
1949
+ Number(options.componentsFile !== undefined) +
1950
+ Number(options.auto) ===
1951
+ 1, {
1952
+ message: "Choose exactly one of --component, --components-file, or --auto.",
1953
+ }),
1954
+ output: z.record(z.string(), z.unknown()).optional(),
1955
+ async run({ args, options }) {
1956
+ const controller = new AbortController();
1957
+ let dashboard = null;
1958
+ const stopDashboard = () => {
1959
+ try {
1960
+ dashboard?.stop();
1961
+ }
1962
+ catch { }
1963
+ };
1964
+ const onInterrupt = () => controller.abort("SIGINT");
1965
+ const onTerminate = () => controller.abort("SIGTERM");
1966
+ const interruptedExitCode = () => controller.signal.reason === "SIGINT"
1967
+ ? 130
1968
+ : controller.signal.reason === "SIGTERM"
1969
+ ? 143
1970
+ : undefined;
1971
+ dependencies.addSignalListener("SIGINT", onInterrupt);
1972
+ dependencies.addSignalListener("SIGTERM", onTerminate);
1973
+ try {
1974
+ const directory = dependencies.currentDirectory();
1975
+ const repository = resolveCliPath(directory, args.repository ?? ".");
1976
+ const config = {
1977
+ pluginPath: options.pluginPath,
1978
+ pythonPath: options.python,
1979
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
1980
+ };
1981
+ const components = options.componentsFile === undefined
1982
+ ? options.component.map((path) => ({ name: path, paths: [path] }))
1983
+ : componentPlanSchema.parse(JSON.parse(await readRegularInputFile(resolveCliPath(directory, options.componentsFile), repository))).components;
1984
+ if (!options.headless &&
1985
+ !options.planOnly &&
1986
+ errorOutput.isTTY === true &&
1987
+ dependencies.environment["CI"] === undefined &&
1988
+ dependencies.environment["TERM"] !== "dumb") {
1989
+ const candidate = new ScanDashboard(errorOutput, {
1990
+ repository,
1991
+ presentation: "components",
1992
+ model: scanModelConfiguration(await mergedCodexConfig(config)),
1993
+ maxCostUsd: options.maxCost,
1994
+ clock: dependencies,
1995
+ color: dependencies.environment["NO_COLOR"] === undefined,
1996
+ sanitize: safeErrorMessage,
1997
+ input: process.stdin,
1998
+ onInterrupt,
1999
+ });
2000
+ candidate.setStage(options.auto ? "Planning components" : "Preparing components");
2001
+ try {
2002
+ candidate.start();
2003
+ dashboard = candidate;
2004
+ }
2005
+ catch {
2006
+ try {
2007
+ candidate.stop();
2008
+ }
2009
+ catch { }
2010
+ }
2011
+ }
2012
+ const result = await runComponentScans({
2013
+ repository,
2014
+ outputDir: resolveCliPath(directory, options.outputDir),
2015
+ ...(options.auto ? { auto: true } : { components }),
2016
+ planOnly: options.planOnly,
2017
+ workers: options.workers,
2018
+ config,
2019
+ scanOptions: {
2020
+ auth: options.auth,
2021
+ knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(directory, path)),
2022
+ ...(await readPromptFiles(directory, options.scanPromptFile, options.postScanPromptFile, repository)),
2023
+ ...(options.maxCost === undefined
2024
+ ? {}
2025
+ : { maxCostUsd: options.maxCost }),
2026
+ },
2027
+ createSecurity: dependencies.createSecurity,
2028
+ planComponents: dependencies.planComponents,
2029
+ matchFindings: dependencies.matchFindings,
2030
+ onPlan: (components) => dashboard?.setComponents(components),
2031
+ onScanEvent: dashboard === null
2032
+ ? undefined
2033
+ : (event) => dashboard?.recordComponentEvent(event),
2034
+ onDeduplicationStarted: () => {
2035
+ if (dashboard !== null)
2036
+ dashboard.showComponents("Combining duplicate findings");
2037
+ else
2038
+ errorOutput.write("codex-security: Matching component findings by root cause...\n");
2039
+ },
2040
+ environment: dependencies.environment,
2041
+ signal: controller.signal,
2042
+ onProgress: (component) => {
2043
+ if (dashboard !== null)
2044
+ dashboard.updateComponent(component);
2045
+ else
2046
+ errorOutput.write(`codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${component.error}`}\n`);
2047
+ },
2048
+ onComplete: (result) => {
2049
+ dashboard?.finishComponents(result);
2050
+ stopDashboard();
2051
+ errorOutput.write(`Component scans: ${result.completed} complete, ${result.incomplete} incomplete, ${result.failed} failed.\n${result.sourceFindingCount} findings → ${result.findingCount} groups${result.deduplication?.status === "incomplete" ? " (matching incomplete)" : ""}.\nReport: ${errorMessage(result.reportPath)}\n`);
2052
+ if (result.retryPlanPath !== undefined)
2053
+ errorOutput.write(`Retry with --components-file ${JSON.stringify(errorMessage(result.retryPlanPath))} and a new --output-dir.\n`);
2054
+ },
2055
+ });
2056
+ exitCode =
2057
+ interruptedExitCode() ??
2058
+ (result.failed ||
2059
+ result.incomplete ||
2060
+ result.deduplication?.status === "incomplete"
2061
+ ? 2
2062
+ : 0);
2063
+ return { ...result };
2064
+ }
2065
+ catch (error) {
2066
+ stopDashboard();
2067
+ exitCode = interruptedExitCode() ?? 2;
2068
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
2069
+ }
2070
+ finally {
2071
+ stopDashboard();
2072
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
2073
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
2074
+ }
2075
+ },
2076
+ })
1834
2077
  .command("bulk-scan", {
1835
2078
  description: "Discover repositories and run resumable bulk security scans.",
1836
2079
  destructive: true,
@@ -1865,6 +2108,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1865
2108
  scanPromptFile: optionValue("--scan-prompt-file")
1866
2109
  .optional()
1867
2110
  .describe("Append instructions from FILE to every scan."),
2111
+ validationPromptFile: optionValue("--validation-prompt-file")
2112
+ .optional()
2113
+ .describe("Replace final validation with FILE for every standard scan."),
1868
2114
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1869
2115
  .optional()
1870
2116
  .describe("Run FILE after each scan, including failures."),
@@ -1919,7 +2165,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1919
2165
  dependencies.addSignalListener("SIGTERM", onTerminate);
1920
2166
  try {
1921
2167
  const currentDirectory = dependencies.currentDirectory();
1922
- const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile);
2168
+ const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile, currentDirectory, options.validationPromptFile);
1923
2169
  let inputPath;
1924
2170
  let outputDir;
1925
2171
  let githubHost;
@@ -2535,10 +2781,14 @@ function defaultListCommand(argv) {
2535
2781
  ...argv.slice(commandIndex + 1),
2536
2782
  ];
2537
2783
  }
2538
- function scanArgumentsFromRecipe(recipe, parentScanId) {
2784
+ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
2539
2785
  if (recipe === undefined || !isJsonObject(recipe)) {
2540
2786
  throw new CodexSecurityError("This scan does not have a saved launch recipe.");
2541
2787
  }
2788
+ if (recipe["validationMode"] === "custom" &&
2789
+ validationPromptFile === undefined) {
2790
+ throw new CodexSecurityError("This scan used custom validation. Supply --validation-prompt-file to rerun it.");
2791
+ }
2542
2792
  const repository = recipe["repository"];
2543
2793
  if (typeof repository !== "string" || repository.length === 0) {
2544
2794
  throw new CodexSecurityError("The saved scan recipe does not contain a repository.");
@@ -2610,6 +2860,7 @@ function scanArgumentsFromRecipe(recipe, parentScanId) {
2610
2860
  repository,
2611
2861
  paths,
2612
2862
  knowledgeBasePaths,
2863
+ validationPromptFile,
2613
2864
  diff: kind === "refs" ? reference : undefined,
2614
2865
  workingTree: kind === "working_tree",
2615
2866
  head: kind === "refs" ? head ?? "HEAD" : undefined,
@@ -2637,6 +2888,7 @@ function validateCliArguments(argv, positionals) {
2637
2888
  "scan",
2638
2889
  "install-hook",
2639
2890
  "bulk-scan",
2891
+ "scan-components",
2640
2892
  "scans",
2641
2893
  "findings",
2642
2894
  "export",
@@ -2785,9 +3037,8 @@ async function matchAllScans(dependencies, force) {
2785
3037
  scanId,
2786
3038
  "--after-scan-id",
2787
3039
  afterScanId,
2788
- "--matches-json",
2789
- JSON.stringify({ matches, uncertain }),
2790
- ]);
3040
+ "--matches-json-stdin",
3041
+ ], JSON.stringify({ matches, uncertain }));
2791
3042
  matchedPairs += 1;
2792
3043
  findingMatches += matches.reduce((count, { beforeOccurrenceIds, afterOccurrenceIds }) => count + beforeOccurrenceIds.length * afterOccurrenceIds.length, 0);
2793
3044
  }
@@ -2947,6 +3198,7 @@ async function publishPatchBranch(repository, branch, stderr, dependencies) {
2947
3198
  url = await run("gh", [
2948
3199
  "pr",
2949
3200
  "create",
3201
+ "--draft",
2950
3202
  "--head",
2951
3203
  branch,
2952
3204
  "--title",
@@ -2998,7 +3250,7 @@ async function createPatchPullRequest(selected, patches, stderr, dependencies) {
2998
3250
  }
2999
3251
  const branch = `codex-security/patch-${selected.scanId.replaceAll(/[^a-z\d._-]/giu, "-")}`;
3000
3252
  const run = (command, args) => dependencies.runRepositoryCommand(command, args, selected.repository);
3001
- stderr.write("Creating a GitHub pull request for verified patches...\n");
3253
+ stderr.write("Creating a draft GitHub pull request for verified patches...\n");
3002
3254
  await run("git", ["switch", "-c", branch]);
3003
3255
  await run("git", ["--literal-pathspecs", "add", "--", ...files]);
3004
3256
  await run("git", [
@@ -3201,6 +3453,12 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
3201
3453
  ...(verify ? ["--config", 'approvals_reviewer="auto_review"'] : []),
3202
3454
  "--config",
3203
3455
  'responses_api_metadata.codex_security_surface="cli"',
3456
+ ...(options.safetyIdentifier === undefined
3457
+ ? []
3458
+ : [
3459
+ "--config",
3460
+ `safety_identifier=${JSON.stringify(options.safetyIdentifier)}`,
3461
+ ]),
3204
3462
  ...(appServer
3205
3463
  ? []
3206
3464
  : [
@@ -3209,7 +3467,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
3209
3467
  "--skip-git-repo-check",
3210
3468
  "--cd",
3211
3469
  directory,
3212
- prompt,
3470
+ "-",
3213
3471
  ]),
3214
3472
  ], {
3215
3473
  command: verify ? "verify-fix" : patch ? "patch" : "validate",
@@ -3227,7 +3485,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
3227
3485
  },
3228
3486
  }
3229
3487
  : {}),
3230
- }, options.environment);
3488
+ }, options.environment, appServer ? undefined : prompt);
3231
3489
  }
3232
3490
  export async function readSkillCommandOutput(stream, appServer) {
3233
3491
  let message;
@@ -3692,7 +3950,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
3692
3950
  const directory = dependencies.currentDirectory();
3693
3951
  repository = arguments_.repository ?? directory;
3694
3952
  const target = targetFromArguments(arguments_);
3695
- const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository));
3953
+ const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository), arguments_.validationPromptFile);
3696
3954
  const config = {
3697
3955
  pluginPath: arguments_.pluginPath,
3698
3956
  pythonPath: arguments_.pythonPath,
@@ -3805,6 +4063,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
3805
4063
  security = dependencies.createSecurity(config);
3806
4064
  const options = {
3807
4065
  auth,
4066
+ safetyIdentifier: arguments_.safetyIdentifier,
3808
4067
  target,
3809
4068
  knowledgeBasePaths: arguments_.knowledgeBasePaths,
3810
4069
  ...prompts,
@@ -4131,10 +4390,16 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
4131
4390
  ? result.toJSON()
4132
4391
  : { ...result.toJSON(), warnings: targetWarnings };
4133
4392
  const incomplete = result.coverage.completeness !== "complete";
4393
+ let deepScanStop;
4394
+ if (arguments_.mode === "deep") {
4395
+ deepScanStop = (await readDeepScanStop(result, arguments_.maxCostUsd, dependencies.runWorkbench).catch(() => undefined)) ?? {
4396
+ reason: "Stop reason unavailable. See the report for details.",
4397
+ };
4398
+ }
4134
4399
  progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
4135
4400
  printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
4136
4401
  dependencies.environment["NO_COLOR"] === undefined &&
4137
- dependencies.environment["TERM"] !== "dumb");
4402
+ dependencies.environment["TERM"] !== "dumb", deepScanStop);
4138
4403
  const completedScan = (exitCode) => {
4139
4404
  diagnostic("scan.completed", {
4140
4405
  coverage: result.coverage.completeness,
@@ -4206,6 +4471,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
4206
4471
  try {
4207
4472
  patches = await runFindingPatches(selected, [`model=${JSON.stringify(effectiveModel)}`], effectiveReasoningEffort, errorOutput, dependencies, {
4208
4473
  ...providerOptions,
4474
+ safetyIdentifier: arguments_.safetyIdentifier,
4209
4475
  environment,
4210
4476
  findingInstructions: patchSelection?.instructions,
4211
4477
  });
@@ -4318,7 +4584,7 @@ function scanScope(arguments_) {
4318
4584
  const scoped = isAbsolute(path) ||
4319
4585
  /^[A-Za-z]:\//u.test(portable) ||
4320
4586
  portable.startsWith("//")
4321
- ? portable.split("/").at(-1) ?? portable
4587
+ ? basename(portable) || portable
4322
4588
  : portable;
4323
4589
  return errorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
4324
4590
  });
@@ -4330,19 +4596,52 @@ function scanScope(arguments_) {
4330
4596
  return "working-tree changes";
4331
4597
  return null;
4332
4598
  }
4333
- function scanPhase(value) {
4599
+ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
4600
+ if (maxCostUsd !== undefined &&
4601
+ result.cost !== null &&
4602
+ result.cost.estimatedUsd > maxCostUsd) {
4603
+ return {
4604
+ reason: `Reached the ${formatUsd(maxCostUsd)} cost limit. More issues may remain.`,
4605
+ nextStep: "To scan further, rerun with a higher --max-cost.",
4606
+ };
4607
+ }
4608
+ const response = await runWorkbench([
4609
+ "get-deep-scan",
4610
+ "--scan-id",
4611
+ result.manifest.scan.id,
4612
+ "--thread-id",
4613
+ result.threadId,
4614
+ ]);
4615
+ const state = response["deepScan"];
4616
+ if (state?.terminalReason === "saturated") {
4617
+ return {
4618
+ reason: `The last ${state.noNewStreak} review rounds found no new issues. More issues may remain.`,
4619
+ };
4620
+ }
4621
+ if (state?.terminalReason !== "capped")
4622
+ return undefined;
4623
+ const { maxDiscoveryRuns, maxTimeHours } = state.config;
4624
+ if (state.dispatchedCount >= maxDiscoveryRuns) {
4625
+ const stillFindingIssues = state.completionSequence > 0 && state.noNewStreak === 0;
4626
+ return {
4627
+ reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${stillFindingIssues ? "The latest review still found new issues." : "More issues may remain."}`,
4628
+ nextStep: `To scan further, rerun with --max-discovery-runs greater than ${maxDiscoveryRuns}.`,
4629
+ };
4630
+ }
4631
+ const elapsedHours = (Date.parse(state.completedAt) - Date.parse(state.createdAt)) / 3_600_000;
4632
+ if (elapsedHours >= maxTimeHours) {
4633
+ return {
4634
+ reason: `Reached the ${maxTimeHours}-hour time limit. More issues may remain.`,
4635
+ nextStep: maxTimeHours < 96
4636
+ ? "To scan further, rerun with a higher --max-time-hours."
4637
+ : "To scan a smaller part of the repository, rerun with --path.",
4638
+ };
4639
+ }
4334
4640
  return {
4335
- preflight: "preflight",
4336
- threat_model: "building threat model",
4337
- discovery: "reviewing files",
4338
- ranking: "ranking scan targets",
4339
- file_review: "reviewing files",
4340
- validation: "validating findings",
4341
- attack_path: "analyzing attack paths",
4342
- reporting: "writing report",
4343
- }[value];
4641
+ reason: "Stopped before the review finished. See the report for details.",
4642
+ };
4344
4643
  }
4345
- function printScanSummary(result, progress, errorOutput, color) {
4644
+ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
4346
4645
  const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
4347
4646
  const repositoryFindings = result.repositoryFindings;
4348
4647
  const findings = repositoryFindings ?? result.findings.findings;
@@ -4382,6 +4681,9 @@ function printScanSummary(result, progress, errorOutput, color) {
4382
4681
  errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(errorMessage(result.reportPath), 4)}\n\n` +
4383
4682
  ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
4384
4683
  ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
4684
+ (deepScanStop === undefined
4685
+ ? ""
4686
+ : ` ${paint("STOPPED", 1)} ${deepScanStop.reason}\n`) +
4385
4687
  ` ${paint("ELAPSED", 1)} ${duration}\n`);
4386
4688
  const tokenSummary = formatTokenUsage(result.turnResult.usage);
4387
4689
  if (tokenSummary !== null) {
@@ -4391,6 +4693,9 @@ function printScanSummary(result, progress, errorOutput, color) {
4391
4693
  errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
4392
4694
  }
4393
4695
  errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
4696
+ if (deepScanStop?.nextStep !== undefined) {
4697
+ errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
4698
+ }
4394
4699
  }
4395
4700
  function formatTokenUsage(usage) {
4396
4701
  if (usage === null || typeof usage !== "object")