@openai/codex-security 0.6.0 → 0.8.0

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 (308) hide show
  1. package/README.md +76 -39
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/examples/completed-scan/findings.json +34 -34
  4. package/_bundled_plugin/examples/completed-scan/report.md +22 -31
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +27 -29
  6. package/_bundled_plugin/examples/{completed-scan → legacy-completed-scan}/coverage.json +1 -0
  7. package/_bundled_plugin/examples/legacy-completed-scan/findings.json +57 -0
  8. package/_bundled_plugin/examples/legacy-completed-scan/report.md +98 -0
  9. package/_bundled_plugin/examples/legacy-completed-scan/scan-manifest.json +43 -0
  10. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  11. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  12. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +1 -1
  13. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  20. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  21. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  22. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  23. package/_bundled_plugin/references/access-advisory.md +11 -0
  24. package/_bundled_plugin/references/core-scan.md +30 -77
  25. package/_bundled_plugin/references/final-report.md +50 -184
  26. package/_bundled_plugin/references/scan-artifacts.md +5 -5
  27. package/_bundled_plugin/references/scan-contract.md +12 -12
  28. package/_bundled_plugin/references/scan-prologue.md +1 -1
  29. package/_bundled_plugin/references/scan-runtime.md +1 -5
  30. package/_bundled_plugin/references/threat-model.md +33 -41
  31. package/_bundled_plugin/schemas/coverage.schema.json +12 -1
  32. package/_bundled_plugin/schemas/scan-manifest.schema.json +37 -11
  33. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +38 -1
  34. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +5 -5
  35. package/_bundled_plugin/scripts/deep_scan_config.py +39 -39
  36. package/_bundled_plugin/scripts/deep_scan_workbench.py +146 -86
  37. package/_bundled_plugin/scripts/finalize_scan_contract.py +249 -76
  38. package/_bundled_plugin/scripts/report_projection.py +49 -17
  39. package/_bundled_plugin/scripts/review_state.py +68 -0
  40. package/_bundled_plugin/scripts/threat_model_projection.py +4 -2
  41. package/_bundled_plugin/scripts/validate_scan_contract.py +1 -2
  42. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -14
  43. package/_bundled_plugin/scripts/workbench/retained_coverage.py +3230 -0
  44. package/_bundled_plugin/scripts/workbench/retained_records.py +627 -0
  45. package/_bundled_plugin/scripts/workbench/saved_coverage.py +651 -8
  46. package/_bundled_plugin/scripts/workbench/saved_outputs.py +72 -0
  47. package/_bundled_plugin/scripts/workbench/saved_sources.py +730 -0
  48. package/_bundled_plugin/scripts/workbench_cli.py +3 -0
  49. package/_bundled_plugin/scripts/workbench_constants.py +0 -1
  50. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +479 -0
  51. package/_bundled_plugin/scripts/workbench_db.py +55 -171
  52. package/_bundled_plugin/scripts/workbench_feedback.py +0 -1
  53. package/_bundled_plugin/scripts/workbench_finding_workflows.py +51 -9
  54. package/_bundled_plugin/scripts/workbench_native_indexes.py +56 -44
  55. package/_bundled_plugin/scripts/workbench_saved_results.py +808 -2389
  56. package/_bundled_plugin/scripts/workbench_scan_history.py +77 -7
  57. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  58. package/_bundled_plugin/scripts/workbench_source_scopes.py +4 -1
  59. package/_bundled_plugin/scripts/workbench_target.py +142 -17
  60. package/_bundled_plugin/scripts/workbench_validation.py +9 -2
  61. package/_bundled_plugin/shared/workbench-history-repairs.json +21 -0
  62. package/_bundled_plugin/shared/workbench-migrations.json +28 -0
  63. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +3 -14
  64. package/_bundled_plugin/skills/assess-patch-risk/references/windows-validation.md +14 -0
  65. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +38 -103
  66. package/_bundled_plugin/skills/attack-path-analysis/references/attack-path-facts.md +11 -73
  67. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +57 -116
  68. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +28 -51
  69. package/_bundled_plugin/skills/define-security-policy/SKILL.md +9 -9
  70. package/_bundled_plugin/skills/finding-discovery/SKILL.md +26 -140
  71. package/_bundled_plugin/skills/fix-finding/SKILL.md +9 -28
  72. package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +28 -218
  73. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +29 -424
  74. package/_bundled_plugin/skills/publish-findings/SKILL.md +32 -24
  75. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +64 -0
  76. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +12 -12
  77. package/_bundled_plugin/skills/security-scan/SKILL.md +29 -17
  78. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +11 -17
  79. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +52 -69
  80. package/_bundled_plugin/skills/threat-model/SKILL.md +16 -9
  81. package/_bundled_plugin/skills/track-findings/SKILL.md +1 -1
  82. package/_bundled_plugin/skills/triage-finding/SKILL.md +5 -15
  83. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -6
  84. package/_bundled_plugin/skills/validation/SKILL.md +42 -104
  85. package/_bundled_plugin/skills/validation/references/validation-guidance.md +21 -106
  86. package/_bundled_plugin/skills/verify-fix/SKILL.md +4 -2
  87. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +21 -159
  88. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +18 -60
  89. package/dist/api.d.ts +5 -3
  90. package/dist/api.d.ts.map +1 -1
  91. package/dist/api.js +359 -53
  92. package/dist/api.js.map +1 -1
  93. package/dist/auth.d.ts.map +1 -1
  94. package/dist/auth.js +4 -1
  95. package/dist/auth.js.map +1 -1
  96. package/dist/cli.d.ts +2 -2
  97. package/dist/cli.d.ts.map +1 -1
  98. package/dist/cli.js +696 -430
  99. package/dist/cli.js.map +1 -1
  100. package/dist/cloud-publish.d.ts.map +1 -1
  101. package/dist/cloud-publish.js +2 -23
  102. package/dist/cloud-publish.js.map +1 -1
  103. package/dist/component-scan.d.ts +8 -2
  104. package/dist/component-scan.d.ts.map +1 -1
  105. package/dist/component-scan.js +2 -0
  106. package/dist/component-scan.js.map +1 -1
  107. package/dist/contract.d.ts +5 -2
  108. package/dist/contract.d.ts.map +1 -1
  109. package/dist/contract.js +93 -45
  110. package/dist/contract.js.map +1 -1
  111. package/dist/cost.d.ts +18 -0
  112. package/dist/cost.d.ts.map +1 -1
  113. package/dist/cost.js +107 -12
  114. package/dist/cost.js.map +1 -1
  115. package/dist/coverage-presentation.d.ts +6 -0
  116. package/dist/coverage-presentation.d.ts.map +1 -0
  117. package/dist/coverage-presentation.js +34 -0
  118. package/dist/coverage-presentation.js.map +1 -0
  119. package/dist/custom-publish.js +2 -2
  120. package/dist/custom-publish.js.map +1 -1
  121. package/dist/custom-validation-prompt.js +5 -5
  122. package/dist/custom-validation-prompt.js.map +1 -1
  123. package/dist/custom-validation.d.ts.map +1 -1
  124. package/dist/custom-validation.js +47 -19
  125. package/dist/custom-validation.js.map +1 -1
  126. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  127. package/dist/deduplication/checkpointed-review.js +3 -1
  128. package/dist/deduplication/checkpointed-review.js.map +1 -1
  129. package/dist/deduplication/codex-review.d.ts.map +1 -1
  130. package/dist/deduplication/codex-review.js +2 -2
  131. package/dist/deduplication/codex-review.js.map +1 -1
  132. package/dist/deduplication/deduplication-prompts.d.ts +1 -0
  133. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  134. package/dist/deduplication/deduplication-prompts.js +3 -0
  135. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  136. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  137. package/dist/deduplication/records-protocol.js +21 -1
  138. package/dist/deduplication/records-protocol.js.map +1 -1
  139. package/dist/deduplication/scan.d.ts.map +1 -1
  140. package/dist/deduplication/scan.js +9 -7
  141. package/dist/deduplication/scan.js.map +1 -1
  142. package/dist/endor-findings.d.ts +4 -3
  143. package/dist/endor-findings.d.ts.map +1 -1
  144. package/dist/endor-findings.js +16 -11
  145. package/dist/endor-findings.js.map +1 -1
  146. package/dist/external-findings-import.d.ts.map +1 -1
  147. package/dist/external-findings-import.js +13 -5
  148. package/dist/external-findings-import.js.map +1 -1
  149. package/dist/external-findings-local.d.ts +1 -0
  150. package/dist/external-findings-local.d.ts.map +1 -1
  151. package/dist/external-findings-local.js +14 -3
  152. package/dist/external-findings-local.js.map +1 -1
  153. package/dist/external-findings-publish.d.ts +2 -1
  154. package/dist/external-findings-publish.d.ts.map +1 -1
  155. package/dist/external-findings-publish.js +64 -28
  156. package/dist/external-findings-publish.js.map +1 -1
  157. package/dist/external-findings-read.d.ts +12 -1
  158. package/dist/external-findings-read.d.ts.map +1 -1
  159. package/dist/external-findings-read.js +25 -6
  160. package/dist/external-findings-read.js.map +1 -1
  161. package/dist/external-findings.d.ts +2 -0
  162. package/dist/external-findings.d.ts.map +1 -1
  163. package/dist/external-findings.js.map +1 -1
  164. package/dist/external-import-contract.d.ts +7 -1
  165. package/dist/external-import-contract.d.ts.map +1 -1
  166. package/dist/external-import-contract.js +63 -31
  167. package/dist/external-import-contract.js.map +1 -1
  168. package/dist/external-imports-feature.d.ts +6 -0
  169. package/dist/external-imports-feature.d.ts.map +1 -0
  170. package/dist/external-imports-feature.js +51 -0
  171. package/dist/external-imports-feature.js.map +1 -0
  172. package/dist/finding-workflow.d.ts +24 -5
  173. package/dist/finding-workflow.d.ts.map +1 -1
  174. package/dist/finding-workflow.js +24 -9
  175. package/dist/finding-workflow.js.map +1 -1
  176. package/dist/github-advisories.d.ts.map +1 -1
  177. package/dist/github-advisories.js +3 -1
  178. package/dist/github-advisories.js.map +1 -1
  179. package/dist/github-findings.d.ts +4 -3
  180. package/dist/github-findings.d.ts.map +1 -1
  181. package/dist/github-findings.js +16 -14
  182. package/dist/github-findings.js.map +1 -1
  183. package/dist/host-protocol.d.ts +1 -1
  184. package/dist/host-protocol.d.ts.map +1 -1
  185. package/dist/host-protocol.js +2 -2
  186. package/dist/host-protocol.js.map +1 -1
  187. package/dist/hosted-remediation.d.ts.map +1 -1
  188. package/dist/hosted-remediation.js +19 -2
  189. package/dist/hosted-remediation.js.map +1 -1
  190. package/dist/hosted-scan.d.ts +1 -1
  191. package/dist/hosted-scan.d.ts.map +1 -1
  192. package/dist/hosted-scan.js +0 -6
  193. package/dist/hosted-scan.js.map +1 -1
  194. package/dist/import-scan.js +17 -17
  195. package/dist/import-scan.js.map +1 -1
  196. package/dist/index.d.ts +4 -3
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js +2 -1
  199. package/dist/index.js.map +1 -1
  200. package/dist/knowledge-base.d.ts +1 -0
  201. package/dist/knowledge-base.d.ts.map +1 -1
  202. package/dist/knowledge-base.js +20 -8
  203. package/dist/knowledge-base.js.map +1 -1
  204. package/dist/mock-scan.d.ts +1 -2
  205. package/dist/mock-scan.d.ts.map +1 -1
  206. package/dist/mock-scan.js +12 -17
  207. package/dist/mock-scan.js.map +1 -1
  208. package/dist/models.d.ts +10 -1
  209. package/dist/models.d.ts.map +1 -1
  210. package/dist/models.js.map +1 -1
  211. package/dist/multiscan.d.ts.map +1 -1
  212. package/dist/multiscan.js +1 -6
  213. package/dist/multiscan.js.map +1 -1
  214. package/dist/native-json-findings.d.ts +30 -0
  215. package/dist/native-json-findings.d.ts.map +1 -0
  216. package/dist/native-json-findings.js +114 -0
  217. package/dist/native-json-findings.js.map +1 -0
  218. package/dist/opengrep-findings.d.ts +10 -0
  219. package/dist/opengrep-findings.d.ts.map +1 -0
  220. package/dist/opengrep-findings.js +198 -0
  221. package/dist/opengrep-findings.js.map +1 -0
  222. package/dist/owner-evidence.d.ts +2 -0
  223. package/dist/owner-evidence.d.ts.map +1 -1
  224. package/dist/owner-evidence.js +2 -1
  225. package/dist/owner-evidence.js.map +1 -1
  226. package/dist/patch-tui.d.ts.map +1 -1
  227. package/dist/patch-tui.js +2 -0
  228. package/dist/patch-tui.js.map +1 -1
  229. package/dist/publication.js +1 -2
  230. package/dist/publication.js.map +1 -1
  231. package/dist/publish.d.ts +2 -0
  232. package/dist/publish.d.ts.map +1 -1
  233. package/dist/publish.js +1 -1
  234. package/dist/publish.js.map +1 -1
  235. package/dist/record.d.ts +1 -0
  236. package/dist/record.d.ts.map +1 -1
  237. package/dist/record.js +10 -0
  238. package/dist/record.js.map +1 -1
  239. package/dist/remediation.d.ts +1 -25
  240. package/dist/remediation.d.ts.map +1 -1
  241. package/dist/remediation.js +3 -24
  242. package/dist/remediation.js.map +1 -1
  243. package/dist/result.d.ts +5 -3
  244. package/dist/result.d.ts.map +1 -1
  245. package/dist/result.js +9 -6
  246. package/dist/result.js.map +1 -1
  247. package/dist/runtime.d.ts.map +1 -1
  248. package/dist/runtime.js +7 -7
  249. package/dist/runtime.js.map +1 -1
  250. package/dist/scan-dashboard.d.ts +5 -3
  251. package/dist/scan-dashboard.d.ts.map +1 -1
  252. package/dist/scan-dashboard.js +79 -26
  253. package/dist/scan-dashboard.js.map +1 -1
  254. package/dist/scan-history-renderer.d.ts.map +1 -1
  255. package/dist/scan-history-renderer.js +9 -3
  256. package/dist/scan-history-renderer.js.map +1 -1
  257. package/dist/scan-owner-suggestions.d.ts +1 -1
  258. package/dist/scan-owner-suggestions.d.ts.map +1 -1
  259. package/dist/scan-owner-suggestions.js +4 -4
  260. package/dist/scan-owner-suggestions.js.map +1 -1
  261. package/dist/scan-usage-display.d.ts +8 -0
  262. package/dist/scan-usage-display.d.ts.map +1 -0
  263. package/dist/scan-usage-display.js +46 -0
  264. package/dist/scan-usage-display.js.map +1 -0
  265. package/dist/scanner-import.d.ts +1 -1
  266. package/dist/scanner-import.d.ts.map +1 -1
  267. package/dist/scanner-import.js +7 -3
  268. package/dist/scanner-import.js.map +1 -1
  269. package/dist/security-policy.d.ts.map +1 -1
  270. package/dist/security-policy.js +17 -22
  271. package/dist/security-policy.js.map +1 -1
  272. package/dist/semgrep-findings.d.ts +4 -3
  273. package/dist/semgrep-findings.d.ts.map +1 -1
  274. package/dist/semgrep-findings.js +22 -89
  275. package/dist/semgrep-findings.js.map +1 -1
  276. package/dist/skill-authentication.d.ts +18 -0
  277. package/dist/skill-authentication.d.ts.map +1 -0
  278. package/dist/skill-authentication.js +82 -0
  279. package/dist/skill-authentication.js.map +1 -0
  280. package/dist/snyk-findings.d.ts +5 -4
  281. package/dist/snyk-findings.d.ts.map +1 -1
  282. package/dist/snyk-findings.js +18 -17
  283. package/dist/snyk-findings.js.map +1 -1
  284. package/dist/suggest-owners.d.ts +4 -1
  285. package/dist/suggest-owners.d.ts.map +1 -1
  286. package/dist/suggest-owners.js +53 -21
  287. package/dist/suggest-owners.js.map +1 -1
  288. package/dist/targets.d.ts.map +1 -1
  289. package/dist/targets.js +4 -1
  290. package/dist/targets.js.map +1 -1
  291. package/dist/wiz-csv.d.ts +2 -1
  292. package/dist/wiz-csv.d.ts.map +1 -1
  293. package/dist/wiz-csv.js +3 -3
  294. package/dist/wiz-csv.js.map +1 -1
  295. package/dist/wiz-findings.d.ts +2 -1
  296. package/dist/wiz-findings.d.ts.map +1 -1
  297. package/dist/wiz-findings.js +27 -23
  298. package/dist/wiz-findings.js.map +1 -1
  299. package/docs/classify-severity-records.md +3 -4
  300. package/docs/cli.md +171 -41
  301. package/docs/dedupe-records.md +15 -1
  302. package/docs/findings-service.md +119 -118
  303. package/docs/hosted-remediation.md +19 -17
  304. package/docs/hosted-scans.md +37 -11
  305. package/package.json +9 -9
  306. package/_bundled_plugin/scripts/generate_in_scope_files.py +0 -277
  307. package/_bundled_plugin/scripts/generate_rank_input.py +0 -350
  308. package/_bundled_plugin/scripts/rank_preview.py +0 -129
package/dist/cli.js CHANGED
@@ -15,9 +15,9 @@ import { withCodexPreflightLock } from "./provider-profile.js";
15
15
  import { isNonEmptyString, notify, parseJson } from "./value.js";
16
16
  import { compareTimestamps } from "./timestamps.js";
17
17
  import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_process";
18
- import { createHash } from "node:crypto";
18
+ import { createHash, randomUUID } from "node:crypto";
19
19
  import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
20
- import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
20
+ import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
21
21
  import { tmpdir } from "node:os";
22
22
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, } from "node:path";
23
23
  import { cwd } from "node:process";
@@ -28,10 +28,12 @@ import { isDeepStrictEqual, parseArgs, promisify, stripVTControlCharacters, } fr
28
28
  import { Cli, z } from "incur";
29
29
  import Ajv2020 from "ajv/dist/2020.js";
30
30
  import { formatCliHelp } from "./cli-help.js";
31
+ import { formatCoverageScope } from "./coverage-presentation.js";
32
+ import { resolveSkillAuthentication } from "./skill-authentication.js";
31
33
  import { scanLogsJson } from "./cli-scan-logs-json.js";
32
34
  import { ARTIFACT_EXPORT_FILENAMES, exportEnvironment, resolveArtifactFormat, resolveArtifactExportOutput, resolveSavedArtifactDirectory, runArtifactExport, writeArtifactOutput as writeCliOutput, } from "./artifact-export.js";
33
35
  export { exportEnvironment } from "./artifact-export.js";
34
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
36
+ import { parse as parseToml } from "smol-toml";
35
37
  import { parse as parseYaml } from "yaml";
36
38
  import { classifyConnectionFailure, CodexSecurity, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, scanCodexHome, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
37
39
  import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, environmentEntry, readCodexHomeConfig, } from "./auth.js";
@@ -42,7 +44,9 @@ import { parseImportedFindings } from "./findings-import.js";
42
44
  import { publishScanToCustom } from "./custom-publish.js";
43
45
  import { ExternalPublicationError, prepareExternalPublication, } from "./external-findings-publish.js";
44
46
  import { prepareLocalExternalImport } from "./external-findings-import.js";
47
+ import { externalImportsDisabledMessage, externalImportsEnabled, } from "./external-imports-feature.js";
45
48
  import { listLocalExternalFindings } from "./external-findings-local.js";
49
+ import { EXTERNAL_FINDINGS_READERS } from "./external-findings-read.js";
46
50
  import { publishPatchReview, resolvePatchReviewPublisher, } from "./patch-publication.js";
47
51
  import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
48
52
  import { savedScanWorkbench } from "./saved-scan-bootstrap.js";
@@ -58,7 +62,7 @@ import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, }
58
62
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
59
63
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
60
64
  import { createBulkScanDiscoveryDependencies, createTerminalPrompt, runBulkScanWizard, } from "./bulk-scan-discovery.js";
61
- import { DEFAULT_CODEX_CONFIG, deepMerge, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
65
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
62
66
  import { formatUsd } from "./cost.js";
63
67
  import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
64
68
  import { readRegularInputFile, resolveScanPrompts } from "./prompt-files.js";
@@ -75,7 +79,7 @@ import { componentPlanSchema } from "./component-plan.js";
75
79
  import { runComponentScans, } from "./component-scan.js";
76
80
  import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScanInternal, } from "./publish.js";
77
81
  import { importScan } from "./import-scan.js";
78
- import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, sameFile, setCodexSecurityCredentialLogout, } from "./runtime.js";
82
+ import { bundledPluginRoot, cleanupSdkDirectory, createIsolatedHome, resolvePluginPath, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, environmentWithGit, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, workbenchEnvironment, sameFile, setCodexSecurityCredentialLogout, } from "./runtime.js";
79
83
  import { comparisonFindingGroups, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
80
84
  import { scanActivitiesFromEvent } from "./scan-activity.js";
81
85
  import { codexSecurityRequestContext } from "./request-metadata.js";
@@ -84,10 +88,11 @@ import { findScanSession, readSavedScanLogs, } from "./scan-logs.js";
84
88
  import { sendFeedback } from "./feedback.js";
85
89
  import { renderScanHistory, } from "./scan-history-renderer.js";
86
90
  import { ScanDashboard } from "./scan-dashboard.js";
91
+ import { ACCOUNT_LIMITS_UNAVAILABLE, formatAccountLimits, formatUsageFreshness, isChatGptAuthentication, USAGE_TIME_UNAVAILABLE, } from "./scan-usage-display.js";
87
92
  import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
88
93
  import { scanPhaseLabel as scanPhase, scanProgressCount, } from "./worker-progress.js";
89
- import { abortable, DiffTarget, enclosingGitWorktreeRoots, UNSUPPORTED_GIT_ENVIRONMENT, relativePathIsOutside as isOutsidePath, } from "./targets.js";
90
- import { resolveTrustedExecutable } from "./trusted-executable.js";
94
+ import { abortable, DiffTarget, enclosingGitWorktreeRoots, gitMarkerRoot, normalizeRepository, UNSUPPORTED_GIT_ENVIRONMENT, relativePathIsOutside as isOutsidePath, } from "./targets.js";
95
+ import { inspectTrustedExecutable, resolveTrustedExecutable, } from "./trusted-executable.js";
91
96
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
92
97
  import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
93
98
  import { resolveConfigPath } from "./config-path.js";
@@ -98,6 +103,19 @@ const PROGRESS_REFRESH_MILLISECONDS = 1_000;
98
103
  const execFile = promisify(execFileCallback);
99
104
  const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
100
105
  const WINDOWS_LOCAL_DEVICE_ROOT = /^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
106
+ const FRAMEWORK_ACTIONS = new Set([
107
+ "--llms",
108
+ "--llms-full",
109
+ "--mcp",
110
+ "--update",
111
+ "--incur-update-check",
112
+ ]);
113
+ const FRAMEWORK_VALUE_OPTIONS = new Set([
114
+ "--format",
115
+ "--filter-output",
116
+ "--token-limit",
117
+ "--token-offset",
118
+ ]);
101
119
  const OUTPUT_OPTION = /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
102
120
  const HIDE_CURSOR = "\u001B[?25l";
103
121
  const SHOW_CURSOR = "\u001B[?25h";
@@ -701,23 +719,50 @@ const DEFAULT_DEPENDENCIES = {
701
719
  runCodex: (args, output, environment, input) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment, input),
702
720
  runRepositoryCommand,
703
721
  exportFindings: runArtifactExport,
704
- runWorkbench: async (args, input, signal, pythonPath, protectedRoot) => {
705
- const environment = {
706
- ...exportEnvironment(),
707
- CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
708
- };
709
- return await runWorkbench({
710
- python: await resolvePluginPython({
711
- configuredPath: pythonPath,
712
- environment,
713
- protectedRoot,
714
- signal,
715
- }),
716
- pluginRoot: await bundledPluginRoot(),
722
+ runWorkbench: async (args, input, signal, pythonPath, protectedRoot, gitProtectedRoots = [], pluginPath) => {
723
+ const checkingTarget = args[0] === "get-scan" && args.includes("--check-target");
724
+ let environment = !checkingTarget || protectedRoot === undefined
725
+ ? {
726
+ ...exportEnvironment(),
727
+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
728
+ }
729
+ : workbenchEnvironment(process.env);
730
+ const protectedRoots = await Promise.all((protectedRoot === undefined
731
+ ? []
732
+ : typeof protectedRoot === "string"
733
+ ? [protectedRoot]
734
+ : protectedRoot).map(async (root) => (await gitMarkerRoot(root, signal, "outermost")) ?? root));
735
+ const python = await resolvePluginPython({
736
+ configuredPath: pythonPath,
717
737
  environment,
718
738
  signal,
719
- failureMessage: "Could not read Codex Security scan history",
720
- }, args, input);
739
+ protectedRoot: protectedRoot === undefined ? undefined : protectedRoots,
740
+ });
741
+ if (checkingTarget && protectedRoot !== undefined) {
742
+ const git = await inspectTrustedExecutable("git", environment, [
743
+ ...protectedRoots,
744
+ ...gitProtectedRoots,
745
+ ]);
746
+ environment = environmentWithGit(git.environment, git);
747
+ }
748
+ const workspace = pluginPath === undefined
749
+ ? undefined
750
+ : await createIsolatedHome(undefined, (path) => requireOutputOutsideRepositories([...protectedRoots, ...gitProtectedRoots], path, "runtime"));
751
+ try {
752
+ return await runWorkbench({
753
+ python,
754
+ pluginRoot: workspace === undefined
755
+ ? await bundledPluginRoot()
756
+ : await resolvePluginPath(pluginPath, workspace, signal),
757
+ environment,
758
+ signal,
759
+ failureMessage: "Could not read Codex Security scan history",
760
+ }, args, input);
761
+ }
762
+ finally {
763
+ if (workspace !== undefined)
764
+ await cleanupSdkDirectory(workspace).catch(() => undefined);
765
+ }
721
766
  },
722
767
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
723
768
  };
@@ -736,80 +781,16 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
736
781
  const ambientConfig = output.appServer === undefined
737
782
  ? {}
738
783
  : resolveCodexProfile(await readCodexHomeConfig(processEnvironment));
739
- const overrides = parseToml(stringifyToml(output.codexOverrides ?? {}));
740
- const config = deepMerge(structuredClone(ambientConfig), overrides);
741
- const provider = output.modelProvider ?? scanModelProvider(config);
742
- // Native Codex ignores configured tables for these built-in providers.
743
- const providerConfiguration = typeof provider === "string" &&
744
- !["openai", "ollama", "lmstudio"].includes(provider)
745
- ? config["model_providers"]?.[provider]
746
- : undefined;
747
- const providerEnvKey = typeof providerConfiguration?.["env_key"] === "string"
748
- ? providerConfiguration["env_key"]
749
- : undefined;
750
- const commandAuth = providerConfiguration?.["auth"] != null;
751
- const explicitChatgpt = output.auth === "chatgpt" && !isExternalModelProvider(provider);
752
- const providerBearer = typeof providerConfiguration?.["experimental_bearer_token"] ===
753
- "string";
754
- const providerKeyConfigured = providerEnvKey !== undefined || providerBearer;
755
- const requiresOpenAiAuth = !commandAuth &&
756
- (explicitChatgpt || !providerKeyConfigured) &&
757
- (provider === undefined ||
758
- provider === "openai" ||
759
- providerConfiguration?.["requires_openai_auth"] === true ||
760
- (explicitChatgpt && providerKeyConfigured));
784
+ const resolved = resolveSkillAuthentication({ ...output, auth: output.auth }, processEnvironment, ambientConfig);
785
+ const { provider, providerConfiguration, providerEnvKey, requiresOpenAiAuth, } = resolved;
786
+ authentication = resolved.authentication;
761
787
  modelProvider = output.modelProvider;
762
788
  let credentialConfig;
763
- if (providerEnvKey !== undefined && !commandAuth && !explicitChatgpt) {
764
- const key = environmentEntry(processEnvironment, providerEnvKey)?.trim();
765
- if (!key && output.auth === "api-key") {
766
- throw new AuthenticationRequiredError(`API-key authentication requires ${providerEnvKey}. Set a valid API key for the selected provider.`);
767
- }
768
- authentication = key
769
- ? { method: "api_key", source: providerEnvKey, verified: false }
770
- : { method: "stored_credentials", verified: false };
771
- }
772
- else {
773
- authentication = scanAuthentication(processEnvironment, output.auth, provider, commandAuth);
774
- }
775
- if (authentication.method === "stored_credentials" &&
776
- isExternalModelProvider(provider)) {
777
- const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
778
- throw new AuthenticationRequiredError(`Set ${providerEnvKey ?? externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
779
- }
780
- let selected = selectedScanEnvironment(processEnvironment, authentication.method === "command" ? "chatgpt" : output.auth, provider);
781
- if (explicitChatgpt &&
782
- !commandAuth &&
783
- providerConfiguration !== undefined &&
784
- providerKeyConfigured) {
785
- if (providerEnvKey !== undefined) {
786
- selected = Object.fromEntries(Object.entries(selected).filter(([name]) => process.platform === "win32"
787
- ? name.toUpperCase() !== providerEnvKey.toUpperCase()
788
- : name !== providerEnvKey));
789
- }
790
- // Native provider keys take precedence over stored authentication.
791
- // Apply explicit ChatGPT selection to the home and CLI configuration.
792
- const providerOverrides = typeof provider === "string"
793
- ? overrides["model_providers"]?.[provider]
794
- : undefined;
795
- for (const selectedConfig of [
796
- providerConfiguration,
797
- providerOverrides,
798
- ]) {
799
- if (selectedConfig === undefined)
800
- continue;
801
- delete selectedConfig["env_key"];
802
- delete selectedConfig["experimental_bearer_token"];
803
- selectedConfig["requires_openai_auth"] = true;
804
- }
805
- args = [
806
- ...args,
807
- ...modelProviderConfigOverride(overrides).flatMap((value) => [
808
- "--config",
809
- value,
810
- ]),
811
- ];
812
- }
789
+ let selected = resolved.environment;
790
+ args = [
791
+ ...args,
792
+ ...resolved.configOverrides.flatMap((value) => ["--config", value]),
793
+ ];
813
794
  if (authentication.method === "stored_credentials" &&
814
795
  requiresOpenAiAuth) {
815
796
  const directory = await realpath(output.directory ?? output.appServer?.directory ?? process.cwd());
@@ -1123,6 +1104,7 @@ async function skillDaybreakConfigOverrides(args, command, environment, director
1123
1104
  return overrides;
1124
1105
  }
1125
1106
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
1107
+ const importsEnabled = externalImportsEnabled(dependencies.environment);
1126
1108
  const remediationOperation = argv[0] === "patch"
1127
1109
  ? "patch"
1128
1110
  : argv[0] === "verify-fix"
@@ -1394,7 +1376,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1394
1376
  async run({ args, format }) {
1395
1377
  const requestedRepository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1396
1378
  const repository = await realpath(requestedRepository).catch(() => requestedRepository);
1397
- return presentHistory(await history(["list-repositories"], async (value) => {
1379
+ return presentHistory(await history(["list-repositories", "--status", "scanned"], async (value) => {
1398
1380
  const repositories = value["repositories"];
1399
1381
  let target = repositories.find((entry) => entry["targetPath"] === requestedRepository);
1400
1382
  const canonicalTarget = repositories.find((entry) => entry["targetPath"] === repository);
@@ -1422,45 +1404,50 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1422
1404
  }), "findings", format, { repository: requestedRepository });
1423
1405
  },
1424
1406
  });
1425
- findingFeedback.command("imported", {
1426
- description: "List imported vendor evidence for a local repository.",
1427
- mcp: false,
1428
- args: z.object({
1429
- repository: z
1430
- .string()
1431
- .optional()
1432
- .describe("Local repository to inspect (default: current directory)."),
1433
- }),
1434
- output: z.record(z.string(), z.unknown()).optional(),
1435
- async run({ args, format, error: incurError }) {
1436
- const controller = new AbortController();
1437
- const removeSignals = listenForAbort(dependencies, controller);
1438
- try {
1439
- const repository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1440
- const findings = await (dependencies.listLocalExternalFindings ?? listLocalExternalFindings)({ repository }, { environment: dependencies.environment, signal: controller.signal });
1441
- return { repository, findings };
1442
- }
1443
- catch (error) {
1444
- if (controller.signal.aborted) {
1445
- exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
1446
- if (argv.includes("--full-output") &&
1447
- (format === "json" || format === "jsonl")) {
1448
- structuredError = true;
1449
- return incurError({
1450
- code: "FINDINGS_READ_FAILED",
1451
- message: diagnosticValue(error),
1452
- exitCode,
1453
- });
1407
+ if (importsEnabled) {
1408
+ findingFeedback.command("imported", {
1409
+ description: "List imported vendor evidence for a local repository.",
1410
+ mcp: false,
1411
+ args: z.object({
1412
+ repository: z
1413
+ .string()
1414
+ .optional()
1415
+ .describe("Local repository to inspect (default: current directory)."),
1416
+ }),
1417
+ output: z.record(z.string(), z.unknown()).optional(),
1418
+ async run({ args, format, error: incurError }) {
1419
+ const controller = new AbortController();
1420
+ const removeSignals = listenForAbort(dependencies, controller);
1421
+ try {
1422
+ const repository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1423
+ const findings = await (dependencies.listLocalExternalFindings ?? listLocalExternalFindings)({ repository }, {
1424
+ environment: dependencies.environment,
1425
+ signal: controller.signal,
1426
+ });
1427
+ return { repository, findings };
1428
+ }
1429
+ catch (error) {
1430
+ if (controller.signal.aborted) {
1431
+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
1432
+ if (argv.includes("--full-output") &&
1433
+ (format === "json" || format === "jsonl")) {
1434
+ structuredError = true;
1435
+ return incurError({
1436
+ code: "FINDINGS_READ_FAILED",
1437
+ message: diagnosticValue(error),
1438
+ exitCode,
1439
+ });
1440
+ }
1441
+ return;
1454
1442
  }
1455
- return;
1443
+ throw error;
1456
1444
  }
1457
- throw error;
1458
- }
1459
- finally {
1460
- removeSignals();
1461
- }
1462
- },
1463
- });
1445
+ finally {
1446
+ removeSignals();
1447
+ }
1448
+ },
1449
+ });
1450
+ }
1464
1451
  const scanHistory = Cli.create("scans", {
1465
1452
  description: "Review saved scans (default: list).",
1466
1453
  })
@@ -1621,7 +1608,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1621
1608
  typeof saved["scanDir"] !== "string") {
1622
1609
  throw new CodexSecurityError("The workbench returned invalid scan resume context.");
1623
1610
  }
1624
- scanArguments = await prepareScanArgumentsFromRecipe(saved["recipe"], saved["scanId"], {
1611
+ scanArguments = await prepareScanArgumentsFromRecipe(saved["recipe"], "resume", {
1625
1612
  scanPrompt: typeof saved["userContext"] === "string"
1626
1613
  ? saved["userContext"]
1627
1614
  : undefined,
@@ -1631,7 +1618,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1631
1618
  if (scanArguments.knowledgeBasePaths.length > 0) {
1632
1619
  scanArguments.knowledgeBaseSnapshot = await restoreScanKnowledge(scanArguments.outputDir, scanArguments.repository, saved["recipe"]["scanInputs"]);
1633
1620
  }
1634
- scanArguments.parentScanId = undefined;
1635
1621
  // Resume uses the installed engine with the saved recipe and checkpoints.
1636
1622
  scanArguments.expectedPluginVersion = undefined;
1637
1623
  scanArguments.verbose = options.verbose;
@@ -1722,7 +1708,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1722
1708
  });
1723
1709
  return finishScan(outcome, format, incurError, "SCAN_IMPORT_FAILED");
1724
1710
  }
1725
- scanArguments = await prepareScanArgumentsFromRecipe(recipe, parentScanId, {
1711
+ scanArguments = await prepareScanArgumentsFromRecipe(recipe, "rerun", {
1726
1712
  scanPromptFile: options.scanPromptFile === undefined
1727
1713
  ? undefined
1728
1714
  : resolveCliPath(dependencies.currentDirectory(), options.scanPromptFile),
@@ -1732,6 +1718,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1732
1718
  }, dependencies.currentDirectory());
1733
1719
  scanArguments.verbose = options.verbose;
1734
1720
  scanArguments.showCost = options.showCost;
1721
+ scanArguments.parentScanId = parentScanId;
1735
1722
  scanArguments.rerunInputIdentity = isJsonObject(recipe)
1736
1723
  ? (recipe["scanInputs"] ?? null)
1737
1724
  : null;
@@ -1784,7 +1771,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1784
1771
  },
1785
1772
  })
1786
1773
  .command("compare", {
1787
- description: "Match and compare findings and coverage between scans.",
1774
+ description: "Match and compare findings between scans.",
1788
1775
  destructive: true,
1789
1776
  mcp: false,
1790
1777
  args: z.object({
@@ -2307,205 +2294,225 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2307
2294
  });
2308
2295
  },
2309
2296
  });
2310
- publication.command("findings", {
2311
- description: "Preview and import selected Wiz, Snyk, Semgrep Code, Endor, or GitHub findings locally or to Cloud.",
2312
- hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
2313
- destructive: true,
2314
- mcp: false,
2315
- args: z.object({
2316
- file: z
2317
- .string()
2318
- .describe("Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV."),
2319
- }),
2320
- options: z.object({
2321
- to: z.enum(["cloud", "local"]).describe("Import destination (required)."),
2322
- repository: optionValue("--repository").describe("Local repository path for --to local; authorized repository ID or URL for --to cloud."),
2323
- provider: z
2324
- .enum(["wiz", "snyk", "semgrep", "endor", "github"])
2325
- .describe("Provider that produced these findings."),
2326
- sourceRepositoryUrl: optionValue("--source-repository-url")
2327
- .optional()
2328
- .describe("Required for Semgrep: source repository URL, checked against the Cloud destination or configured local Git remotes."),
2329
- sourceKey: optionValue("--source-key").describe("Stable vendor tenant and finding namespace; not a project selection filter."),
2330
- dryRun: z
2331
- .boolean()
2332
- .default(false)
2333
- .describe("Read and preview the destination and findings without storing them."),
2334
- yes: z
2335
- .boolean()
2336
- .default(false)
2337
- .describe("Confirm publication of the previewed input without a terminal prompt."),
2338
- }),
2339
- output: z.record(z.string(), z.unknown()).optional(),
2340
- async run({ args, options, format, formatExplicit, error: incurError }) {
2341
- return await withTerminalErrorsHandled(errorOutput, async () => {
2342
- const writeDiagnostic = (message) => notify(() => errorOutput.write(message));
2343
- if (argv.includes("--full-output") &&
2344
- format !== "json" &&
2345
- format !== "jsonl") {
2346
- structuredError = true;
2347
- exitCode = 2;
2348
- return incurError({
2349
- code: "INVALID_ARGUMENTS",
2350
- message: "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",
2351
- exitCode,
2352
- });
2353
- }
2354
- const controller = new AbortController();
2355
- const removeSignals = listenForAbort(dependencies, controller);
2356
- const structured = formatExplicit && format !== "toon";
2357
- const humanSummary = format === "toon" &&
2358
- !formatExplicit &&
2359
- !argv.some((argument) => OUTPUT_OPTION.test(argument));
2360
- const confirmImport = async (preview, showPreview) => {
2361
- if (options.yes)
2362
- return true;
2363
- const prompt = dependencies.externalPublicationPrompt ??
2364
- createTerminalPrompt(errorOutput);
2365
- const local = options.to === "local";
2366
- if (!prompt.isInteractive())
2367
- throw new CodexSecurityError(`${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`);
2368
- if (structured)
2369
- showPreview();
2370
- const action = local
2371
- ? `Store these ${preview.findings.length} findings locally`
2372
- : `Publish these ${preview.findings.length} findings`;
2373
- return prompt.confirm(`${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`, false, controller.signal);
2374
- };
2375
- let lastProgress = "";
2376
- const onProgress = (event) => {
2377
- if (errorOutput.isTTY !== true)
2378
- return;
2379
- const step = event.total
2380
- ? Math.floor((event.completed * 10) / event.total)
2381
- : 0;
2382
- const key = `${event.phase}:${step}`;
2383
- if (key === lastProgress)
2384
- return;
2385
- lastProgress = key;
2386
- const labels = {
2387
- reading: "Reading selected findings",
2388
- discovering: "Checking Cloud account and repository",
2389
- preparing: "Preparing findings",
2390
- waiting: "Waiting for publication access",
2391
- uploading: "Acknowledged findings",
2392
- verifying: "Verifying source records",
2297
+ let disabledImportInvocation = false;
2298
+ function registerFindingPublication() {
2299
+ publication.command("findings", {
2300
+ description: "Preview and import selected Wiz, Snyk, Semgrep Code, OpenGrep, Endor, or GitHub findings locally or to Cloud.",
2301
+ hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For OpenGrep, supply native JSON and --source-repository-url; imports use the semgrep storage provider and preserve OpenGrep as the scanner origin. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
2302
+ destructive: true,
2303
+ mcp: false,
2304
+ args: z.object({
2305
+ file: z
2306
+ .string()
2307
+ .describe("Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; OpenGrep native JSON; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV."),
2308
+ }),
2309
+ options: z.object({
2310
+ to: z
2311
+ .enum(["cloud", "local"])
2312
+ .describe("Import destination (required)."),
2313
+ repository: optionValue("--repository").describe("Local repository path for --to local; authorized repository ID or URL for --to cloud."),
2314
+ provider: z
2315
+ .enum(EXTERNAL_FINDINGS_READERS)
2316
+ .describe("Report reader; OpenGrep uses the semgrep storage provider."),
2317
+ sourceRepositoryUrl: optionValue("--source-repository-url")
2318
+ .optional()
2319
+ .describe("Required for Semgrep and OpenGrep: source repository URL, checked against the Cloud destination or configured local Git remotes."),
2320
+ sourceKey: optionValue("--source-key").describe("Stable vendor tenant and finding namespace; not a project selection filter."),
2321
+ dryRun: z
2322
+ .boolean()
2323
+ .default(false)
2324
+ .describe("Read and preview the destination and findings without storing them."),
2325
+ yes: z
2326
+ .boolean()
2327
+ .default(false)
2328
+ .describe("Confirm publication of the previewed input without a terminal prompt."),
2329
+ }),
2330
+ output: z.record(z.string(), z.unknown()).optional(),
2331
+ async run({ args, options, format, formatExplicit, error: incurError }) {
2332
+ return await withTerminalErrorsHandled(errorOutput, async () => {
2333
+ const writeDiagnostic = (message) => notify(() => errorOutput.write(message));
2334
+ const machineFormat = format === "json" || format === "jsonl";
2335
+ if (argv.includes("--full-output") && !machineFormat) {
2336
+ structuredError = true;
2337
+ exitCode = 2;
2338
+ return incurError({
2339
+ code: "INVALID_ARGUMENTS",
2340
+ message: "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",
2341
+ exitCode,
2342
+ });
2343
+ }
2344
+ const controller = new AbortController();
2345
+ const removeSignals = listenForAbort(dependencies, controller);
2346
+ const structured = formatExplicit && format !== "toon";
2347
+ const humanSummary = format === "toon" &&
2348
+ !formatExplicit &&
2349
+ !argv.some((argument) => OUTPUT_OPTION.test(argument));
2350
+ const confirmImport = async (preview, showPreview) => {
2351
+ if (options.yes)
2352
+ return true;
2353
+ const prompt = dependencies.externalPublicationPrompt ??
2354
+ createTerminalPrompt(errorOutput);
2355
+ const local = options.to === "local";
2356
+ if (!prompt.isInteractive())
2357
+ throw new CodexSecurityError(`${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`);
2358
+ if (structured)
2359
+ showPreview();
2360
+ const action = local
2361
+ ? `Store these ${preview.findings.length} findings locally`
2362
+ : `Publish these ${preview.findings.length} findings`;
2363
+ return prompt.confirm(`${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`, false, controller.signal);
2393
2364
  };
2394
- writeDiagnostic(`${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`);
2395
- };
2396
- try {
2397
- if (options.to === "local") {
2398
- const prepared = await (dependencies.prepareLocalExternalImport ??
2399
- prepareLocalExternalImport)(resolveCliPath(dependencies.currentDirectory(), args.file), {
2400
- ...options,
2401
- repository: resolveCliPath(dependencies.currentDirectory(), options.repository),
2402
- }, {
2365
+ const showScannerReport = (preview) => {
2366
+ if (options.provider !== "opengrep")
2367
+ return;
2368
+ writeDiagnostic("Reader: OpenGrep (stored provider: semgrep)\n");
2369
+ const diagnostics = preview.report?.["errors"];
2370
+ if (Array.isArray(diagnostics) && diagnostics.length) {
2371
+ writeDiagnostic(`Scanner diagnostics: ${diagnostics.length}. Scan coverage may be incomplete.\n`);
2372
+ for (const diagnostic of diagnostics)
2373
+ writeDiagnostic(`${diagnosticValue(JSON.stringify(diagnostic))}\n`);
2374
+ }
2375
+ };
2376
+ let lastProgress = "";
2377
+ const onProgress = (event) => {
2378
+ if (errorOutput.isTTY !== true)
2379
+ return;
2380
+ const step = event.total
2381
+ ? Math.floor((event.completed * 10) / event.total)
2382
+ : 0;
2383
+ const key = `${event.phase}:${step}`;
2384
+ if (key === lastProgress)
2385
+ return;
2386
+ lastProgress = key;
2387
+ const labels = {
2388
+ reading: "Reading selected findings",
2389
+ discovering: "Checking Cloud account and repository",
2390
+ preparing: "Preparing findings",
2391
+ waiting: "Waiting for publication access",
2392
+ uploading: "Acknowledged findings",
2393
+ verifying: "Verifying source records",
2394
+ };
2395
+ writeDiagnostic(`${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`);
2396
+ };
2397
+ try {
2398
+ if (!importsEnabled)
2399
+ throw new CodexSecurityError(externalImportsDisabledMessage);
2400
+ if (options.to === "local") {
2401
+ const prepared = await (dependencies.prepareLocalExternalImport ??
2402
+ prepareLocalExternalImport)(resolveCliPath(dependencies.currentDirectory(), args.file), {
2403
+ ...options,
2404
+ repository: resolveCliPath(dependencies.currentDirectory(), options.repository),
2405
+ }, {
2406
+ environment: dependencies.environment,
2407
+ signal: controller.signal,
2408
+ });
2409
+ const { preview } = prepared;
2410
+ const showPreview = () => {
2411
+ showScannerReport(preview);
2412
+ writeDiagnostic(`Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`);
2413
+ for (const excluded of preview.excluded)
2414
+ writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`);
2415
+ for (const finding of preview.findings.slice(0, 5))
2416
+ writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2417
+ writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`);
2418
+ };
2419
+ if (!structured)
2420
+ showPreview();
2421
+ if (options.dryRun) {
2422
+ if (humanSummary)
2423
+ renderedOutput = "Dry run complete. No findings stored.\n";
2424
+ return { ...preview, dryRun: true };
2425
+ }
2426
+ if (!(await confirmImport(preview, showPreview))) {
2427
+ if (humanSummary)
2428
+ renderedOutput = "No findings stored.\n";
2429
+ return { imported: false, preview };
2430
+ }
2431
+ const result = await prepared.import();
2432
+ if (result.excluded.length > 0)
2433
+ exitCode = 1;
2434
+ const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
2435
+ if (humanSummary)
2436
+ renderedOutput = summary;
2437
+ else if (!structured)
2438
+ writeDiagnostic(summary);
2439
+ return { ...result };
2440
+ }
2441
+ const prepared = await prepareExternalPublication(resolveCliPath(dependencies.currentDirectory(), args.file), options, {
2403
2442
  environment: dependencies.environment,
2443
+ fetch: dependencies.cloudFetch,
2404
2444
  signal: controller.signal,
2445
+ onProgress,
2405
2446
  });
2406
2447
  const { preview } = prepared;
2407
2448
  const showPreview = () => {
2408
- writeDiagnostic(`Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`);
2449
+ showScannerReport(preview);
2450
+ writeDiagnostic(`Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`);
2451
+ if (preview.cloudUrl)
2452
+ writeDiagnostic(`Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`);
2409
2453
  for (const excluded of preview.excluded)
2410
2454
  writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`);
2455
+ writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`);
2456
+ const severities = new Map();
2457
+ for (const finding of preview.findings)
2458
+ severities.set(finding.evidence.severity, (severities.get(finding.evidence.severity) ?? 0) + 1);
2459
+ writeDiagnostic(`Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`);
2411
2460
  for (const finding of preview.findings.slice(0, 5))
2412
2461
  writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2413
- writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`);
2462
+ if (preview.findings.length > 5)
2463
+ writeDiagnostic(`Showing 5 of ${preview.findings.length} findings.\n`);
2464
+ writeDiagnostic("Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n");
2414
2465
  };
2415
2466
  if (!structured)
2416
2467
  showPreview();
2417
2468
  if (options.dryRun) {
2418
2469
  if (humanSummary)
2419
- renderedOutput = "Dry run complete. No findings stored.\n";
2470
+ renderedOutput = "Dry run complete. No findings uploaded.\n";
2420
2471
  return { ...preview, dryRun: true };
2421
2472
  }
2422
2473
  if (!(await confirmImport(preview, showPreview))) {
2423
2474
  if (humanSummary)
2424
- renderedOutput = "No findings stored.\n";
2425
- return { imported: false, preview };
2475
+ renderedOutput = "No findings published.\n";
2476
+ return { published: false, preview };
2426
2477
  }
2427
- const result = await prepared.import();
2428
- if (result.excluded.length > 0)
2478
+ const result = await prepared.publish();
2479
+ if (result.status === "partial")
2429
2480
  exitCode = 1;
2430
- const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
2431
2481
  if (humanSummary)
2432
- renderedOutput = summary;
2482
+ renderedOutput = renderExternalPublicationSummary(result);
2433
2483
  else if (!structured)
2434
- writeDiagnostic(summary);
2484
+ writeDiagnostic(renderExternalPublicationSummary(result));
2435
2485
  return { ...result };
2436
2486
  }
2437
- const prepared = await prepareExternalPublication(resolveCliPath(dependencies.currentDirectory(), args.file), options, {
2438
- environment: dependencies.environment,
2439
- fetch: dependencies.cloudFetch,
2440
- signal: controller.signal,
2441
- onProgress,
2442
- });
2443
- const { preview } = prepared;
2444
- const showPreview = () => {
2445
- writeDiagnostic(`Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`);
2446
- if (preview.cloudUrl)
2447
- writeDiagnostic(`Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`);
2448
- for (const excluded of preview.excluded)
2449
- writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`);
2450
- writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`);
2451
- const severities = new Map();
2452
- for (const finding of preview.findings)
2453
- severities.set(finding.evidence.severity, (severities.get(finding.evidence.severity) ?? 0) + 1);
2454
- writeDiagnostic(`Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`);
2455
- for (const finding of preview.findings.slice(0, 5))
2456
- writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2457
- if (preview.findings.length > 5)
2458
- writeDiagnostic(`Showing 5 of ${preview.findings.length} findings.\n`);
2459
- writeDiagnostic("Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n");
2460
- };
2461
- if (!structured)
2462
- showPreview();
2463
- if (options.dryRun) {
2464
- if (humanSummary)
2465
- renderedOutput = "Dry run complete. No findings uploaded.\n";
2466
- return { ...preview, dryRun: true };
2467
- }
2468
- if (!(await confirmImport(preview, showPreview))) {
2469
- if (humanSummary)
2470
- renderedOutput = "No findings published.\n";
2471
- return { published: false, preview };
2487
+ catch (error) {
2488
+ if (argv.includes("--full-output") && machineFormat)
2489
+ failedResultOutput = {
2490
+ format,
2491
+ code: "IMPORT_FAILED",
2492
+ message: diagnosticValue(error),
2493
+ };
2494
+ reportPublicationError(diagnosticValue(error), controller.signal.aborted ? controller.signal.reason : undefined);
2495
+ if (error instanceof ExternalPublicationError) {
2496
+ if (humanSummary)
2497
+ renderedOutput = renderExternalPublicationSummary(error.result);
2498
+ return { ...error.result };
2499
+ }
2500
+ const failure = { status: "failed", error: diagnosticValue(error) };
2501
+ if (machineFormat &&
2502
+ !argv.includes("--full-output") &&
2503
+ argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument)))
2504
+ filteredScanFailure = { format, data: failure };
2505
+ return structured ? failure : undefined;
2472
2506
  }
2473
- const result = await prepared.publish();
2474
- if (result.status === "partial")
2475
- exitCode = 1;
2476
- if (humanSummary)
2477
- renderedOutput = renderExternalPublicationSummary(result);
2478
- else if (!structured)
2479
- writeDiagnostic(renderExternalPublicationSummary(result));
2480
- return { ...result };
2481
- }
2482
- catch (error) {
2483
- if (argv.includes("--full-output") &&
2484
- (format === "json" || format === "jsonl"))
2485
- failedResultOutput = {
2486
- format,
2487
- code: "IMPORT_FAILED",
2488
- message: diagnosticValue(error),
2489
- };
2490
- reportPublicationError(diagnosticValue(error), controller.signal.aborted ? controller.signal.reason : undefined);
2491
- if (error instanceof ExternalPublicationError) {
2492
- if (humanSummary)
2493
- renderedOutput = renderExternalPublicationSummary(error.result);
2494
- return { ...error.result };
2507
+ finally {
2508
+ removeSignals();
2495
2509
  }
2496
- const failure = { status: "failed", error: diagnosticValue(error) };
2497
- if ((format === "json" || format === "jsonl") &&
2498
- !argv.includes("--full-output") &&
2499
- argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument)))
2500
- filteredScanFailure = { format, data: failure };
2501
- return structured ? failure : undefined;
2502
- }
2503
- finally {
2504
- removeSignals();
2505
- }
2506
- });
2507
- },
2508
- });
2510
+ });
2511
+ },
2512
+ });
2513
+ }
2514
+ if (importsEnabled)
2515
+ registerFindingPublication();
2509
2516
  publication.command("check", {
2510
2517
  description: "Check saved scan history and Linear access without creating issues.",
2511
2518
  mcp: false,
@@ -2537,10 +2544,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2537
2544
  },
2538
2545
  });
2539
2546
  const imports = Cli.create("import", {
2540
- description: "Read GitHub code scanning alerts and security advisories.",
2547
+ description: importsEnabled
2548
+ ? "Read GitHub code scanning alerts and security advisories."
2549
+ : "Read GitHub code scanning alerts.",
2541
2550
  }).command("github", {
2542
2551
  description: "Read GitHub code scanning alerts without changing GitHub.",
2543
- hint: "Save complete --format json output for publish findings --provider github. This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
2552
+ hint: `${importsEnabled ? "Save complete --format json output for publish findings --provider github. " : ""}This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.`,
2544
2553
  destructive: false,
2545
2554
  mcp: false,
2546
2555
  args: z.object({
@@ -2603,82 +2612,88 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2603
2612
  }
2604
2613
  },
2605
2614
  });
2606
- imports.command("github-advisories", {
2607
- description: "Read GitHub security advisories without changing GitHub.",
2608
- hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",
2609
- destructive: false,
2610
- mcp: false,
2611
- args: z.object({
2612
- repository: z
2613
- .string()
2614
- .min(1)
2615
- .describe("Source repository, or target context for global IDs, in OWNER/REPO form."),
2616
- }),
2617
- options: z.object({
2618
- githubAdvisory: z
2619
- .array(optionValue("--github-advisory").regex(/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu, "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form."))
2620
- .default([])
2621
- .describe("Exact GHSA ID; repeat to select a subset. Required for global advisories."),
2622
- githubAdvisorySource: z
2623
- .enum(["repository", "global"])
2624
- .default("repository")
2625
- .describe("Advisory API to read; global requires exact IDs and never lists the database."),
2626
- githubState: z
2627
- .enum(GITHUB_ADVISORY_STATES)
2628
- .default("published")
2629
- .describe("Repository advisory list state; omit when selecting exact GHSA IDs."),
2630
- }),
2631
- output: z
2632
- .array(z.object({
2633
- source: z.literal("github-security-advisory"),
2634
- selection: z.enum(["repository", "global"]),
2635
- repository: z.string(),
2636
- githubHost: z.string(),
2637
- ghsaId: z.string(),
2638
- url: z.string(),
2639
- advisory: z.record(z.string(), z.unknown()),
2640
- }))
2641
- .optional(),
2642
- async run({ args, options, error: incurError }) {
2643
- const controller = new AbortController();
2644
- const removeSignals = listenForAbort(dependencies, controller);
2645
- try {
2646
- return await (dependencies.importGitHubAdvisories ?? importGitHubAdvisories)({
2647
- repository: args.repository,
2648
- advisoryIds: options.githubAdvisory,
2649
- source: options.githubAdvisorySource,
2650
- state: options.githubState,
2651
- signal: controller.signal,
2652
- }, {
2653
- environment: dependencies.environment,
2654
- currentDirectory: dependencies.currentDirectory(),
2655
- });
2656
- }
2657
- catch (error) {
2658
- const signal = controller.signal.reason;
2659
- if (signal === "SIGINT" || signal === "SIGTERM") {
2660
- exitCode = signal === "SIGINT" ? 130 : 143;
2661
- errorOutput.write(`codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`);
2615
+ function registerGitHubAdvisories() {
2616
+ imports.command("github-advisories", {
2617
+ description: "Read GitHub security advisories without changing GitHub.",
2618
+ hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",
2619
+ destructive: false,
2620
+ mcp: false,
2621
+ args: z.object({
2622
+ repository: z
2623
+ .string()
2624
+ .min(1)
2625
+ .describe("Source repository, or target context for global IDs, in OWNER/REPO form."),
2626
+ }),
2627
+ options: z.object({
2628
+ githubAdvisory: z
2629
+ .array(optionValue("--github-advisory").regex(/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu, "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form."))
2630
+ .default([])
2631
+ .describe("Exact GHSA ID; repeat to select a subset. Required for global advisories."),
2632
+ githubAdvisorySource: z
2633
+ .enum(["repository", "global"])
2634
+ .default("repository")
2635
+ .describe("Advisory API to read; global requires exact IDs and never lists the database."),
2636
+ githubState: z
2637
+ .enum(GITHUB_ADVISORY_STATES)
2638
+ .default("published")
2639
+ .describe("Repository advisory list state; omit when selecting exact GHSA IDs."),
2640
+ }),
2641
+ output: z
2642
+ .array(z.object({
2643
+ source: z.literal("github-security-advisory"),
2644
+ selection: z.enum(["repository", "global"]),
2645
+ repository: z.string(),
2646
+ githubHost: z.string(),
2647
+ ghsaId: z.string(),
2648
+ url: z.string(),
2649
+ advisory: z.record(z.string(), z.unknown()),
2650
+ }))
2651
+ .optional(),
2652
+ async run({ args, options, error: incurError }) {
2653
+ const controller = new AbortController();
2654
+ const removeSignals = listenForAbort(dependencies, controller);
2655
+ try {
2656
+ if (!importsEnabled)
2657
+ throw new CodexSecurityError(externalImportsDisabledMessage);
2658
+ return await (dependencies.importGitHubAdvisories ?? importGitHubAdvisories)({
2659
+ repository: args.repository,
2660
+ advisoryIds: options.githubAdvisory,
2661
+ source: options.githubAdvisorySource,
2662
+ state: options.githubState,
2663
+ signal: controller.signal,
2664
+ }, {
2665
+ environment: dependencies.environment,
2666
+ currentDirectory: dependencies.currentDirectory(),
2667
+ });
2662
2668
  }
2663
- else {
2664
- exitCode = 2;
2665
- errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2669
+ catch (error) {
2670
+ const signal = controller.signal.reason;
2671
+ if (signal === "SIGINT" || signal === "SIGTERM") {
2672
+ exitCode = signal === "SIGINT" ? 130 : 143;
2673
+ errorOutput.write(`codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`);
2674
+ }
2675
+ else {
2676
+ exitCode = 2;
2677
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2678
+ }
2679
+ if (argv.includes("--full-output")) {
2680
+ structuredError = true;
2681
+ return incurError({
2682
+ code: "GITHUB_IMPORT_FAILED",
2683
+ message: diagnosticValue(error),
2684
+ exitCode,
2685
+ });
2686
+ }
2687
+ return undefined;
2666
2688
  }
2667
- if (argv.includes("--full-output")) {
2668
- structuredError = true;
2669
- return incurError({
2670
- code: "GITHUB_IMPORT_FAILED",
2671
- message: diagnosticValue(error),
2672
- exitCode,
2673
- });
2689
+ finally {
2690
+ removeSignals();
2674
2691
  }
2675
- return undefined;
2676
- }
2677
- finally {
2678
- removeSignals();
2679
- }
2680
- },
2681
- });
2692
+ },
2693
+ });
2694
+ }
2695
+ if (importsEnabled)
2696
+ registerGitHubAdvisories();
2682
2697
  const infoOutput = z.object({
2683
2698
  sdkVersion: z.string(),
2684
2699
  bundledPluginVersion: z.string(),
@@ -2692,7 +2707,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2692
2707
  nextStep: z.string(),
2693
2708
  configuration: z.record(z.string(), z.unknown()),
2694
2709
  });
2695
- const cli = Cli.create("codex-security", {
2710
+ const cliOptions = {
2696
2711
  aliases: ["cs"],
2697
2712
  description: "Find, review, and fix security issues in your code.",
2698
2713
  version: VERSION,
@@ -2701,7 +2716,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2701
2716
  tools: { discovery: "direct" },
2702
2717
  instructions: "Use info for read-only SDK metadata. Scans and other state-changing commands are CLI-only because the MCP transport cannot cancel active commands.",
2703
2718
  },
2704
- })
2719
+ };
2720
+ const cli = Cli.create("codex-security", cliOptions)
2705
2721
  .command("policy", {
2706
2722
  description: "Draft SECURITY.md for review.",
2707
2723
  destructive: true,
@@ -2925,6 +2941,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2925
2941
  .boolean()
2926
2942
  .default(false)
2927
2943
  .describe("Patch and verify confirmed findings after the scan."),
2944
+ validate: z
2945
+ .boolean()
2946
+ .default(false)
2947
+ .describe("Run standalone finding validation after the scan."),
2928
2948
  patchSeverity: z
2929
2949
  .enum(REPORTABLE_SEVERITIES)
2930
2950
  .optional()
@@ -2955,8 +2975,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2955
2975
  .refine((options) => !options.patch || !options.dryRun, {
2956
2976
  message: "--patch cannot be combined with --dry-run.",
2957
2977
  })
2958
- .refine((options) => !options.mock || (!options.dryRun && !options.patch), {
2959
- message: "--mock cannot be combined with --dry-run or --patch.",
2978
+ .refine((options) => !options.validate || !options.dryRun, {
2979
+ message: "--validate cannot be combined with --dry-run.",
2980
+ })
2981
+ .refine((options) => !options.mock ||
2982
+ (!options.dryRun && !options.patch && !options.validate), {
2983
+ message: "--mock cannot be combined with --dry-run, --patch, or --validate.",
2960
2984
  }),
2961
2985
  output: scanOutputSchema("SCAN_FAILED"),
2962
2986
  async run({ args, error: incurError, format, options }) {
@@ -2991,6 +3015,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2991
3015
  if (options.archiveExisting && settings.outputDir === undefined) {
2992
3016
  throw new CodexSecurityError("--archive-existing requires --output-dir.");
2993
3017
  }
3018
+ if (options.validate && settings.maxCostUsd !== undefined) {
3019
+ throw new CodexSecurityError("--validate cannot be combined with a scan cost limit because standalone validation is not cost-tracked.");
3020
+ }
2994
3021
  outcome = await runScan({
2995
3022
  ...settings,
2996
3023
  codexOverrides: config.codexOverrides,
@@ -3003,6 +3030,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3003
3030
  pluginPath: options.pluginPath,
3004
3031
  pythonPath: options.python,
3005
3032
  patch: options.patch,
3033
+ validate: options.validate,
3006
3034
  patchSeverity: options.patchSeverity,
3007
3035
  createPr: options.createPr,
3008
3036
  showCost: options.showCost,
@@ -3530,11 +3558,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3530
3558
  ? (event) => {
3531
3559
  const componentName = componentNames.get(event.componentId) ??
3532
3560
  event.componentId;
3533
- const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined);
3561
+ const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined, settings.auth);
3534
3562
  if (line !== null)
3535
3563
  errorOutput.write(line);
3536
3564
  }
3537
- : (event) => dashboard?.recordComponentEvent(event),
3565
+ : (event) => dashboard?.recordComponentEvent(event, settings.auth),
3538
3566
  onDeduplicationStarted: () => {
3539
3567
  if (dashboard !== null)
3540
3568
  dashboard.showComponents("Combining duplicate findings");
@@ -3754,7 +3782,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3754
3782
  errorOutput.write(`codex-security: ${scan.scanId}: Original session logs are unavailable. Preserving this attempt and starting a new one.\n`);
3755
3783
  return undefined;
3756
3784
  }
3757
- const recipe = await prepareScanArgumentsFromRecipe(saved["recipe"], scan.scanId, {
3785
+ const recipe = await prepareScanArgumentsFromRecipe(saved["recipe"], "resume", {
3758
3786
  scanPrompt: typeof saved["userContext"] === "string"
3759
3787
  ? saved["userContext"]
3760
3788
  : undefined,
@@ -4015,7 +4043,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4015
4043
  },
4016
4044
  ],
4017
4045
  output: z.record(z.string(), z.unknown()).optional(),
4018
- async run({ format, options }) {
4046
+ async run({ format, options, error: incurError }) {
4047
+ const diagnostics = captureOutput();
4048
+ let failureReported = false;
4019
4049
  try {
4020
4050
  if (options.host)
4021
4051
  throw new CodexSecurityError("Use verify-fix --host alone.");
@@ -4071,8 +4101,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4071
4101
  const response = captureOutput();
4072
4102
  const progress = new FindingProgressPresenter(errorOutput, dependencies, repository, identifiers.length);
4073
4103
  progress.startVerification();
4104
+ const verificationErrors = new NodeWritable({
4105
+ write(chunk, _encoding, callback) {
4106
+ diagnostics.stream.write(chunk);
4107
+ progress.stop();
4108
+ void writeCliOutput(errorOutput, chunk).then(() => callback(), callback);
4109
+ },
4110
+ });
4074
4111
  try {
4075
- exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options, response.stream, errorOutput, dependencies, {
4112
+ exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options, response.stream, verificationErrors, dependencies, {
4076
4113
  directory: repository,
4077
4114
  ...(selected === undefined
4078
4115
  ? {}
@@ -4084,10 +4121,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4084
4121
  onEvent: progress.observe.bind(progress),
4085
4122
  });
4086
4123
  if (exitCode !== 0) {
4087
- if (exitCode !== 130 && exitCode !== 143)
4088
- exitCode = 2;
4089
- frameworkExit = exitCode;
4090
- return undefined;
4124
+ if (exitCode === 130 || exitCode === 143) {
4125
+ frameworkExit = exitCode;
4126
+ return undefined;
4127
+ }
4128
+ failureReported = diagnostics.text().trim().length > 0;
4129
+ throw new CodexSecurityError(diagnostics.text().trim() ||
4130
+ `Codex verification failed with exit code ${exitCode}.`);
4091
4131
  }
4092
4132
  results = parseFindingVerifications(response.text(), identifiers);
4093
4133
  progress.complete(results);
@@ -4115,8 +4155,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4115
4155
  }
4116
4156
  catch (error) {
4117
4157
  exitCode = 2;
4118
- errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
4119
- throw error;
4158
+ const message = errorMessage(error);
4159
+ if (!failureReported)
4160
+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);
4161
+ return finishScan({ exitCode, error: message }, format, incurError, "VERIFICATION_FAILED");
4120
4162
  }
4121
4163
  },
4122
4164
  })
@@ -4633,7 +4675,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4633
4675
  },
4634
4676
  });
4635
4677
  const commands = Cli.toCommands.get(cli);
4636
- const valueOptions = cliValueOptions(commands);
4678
+ let valueOptions = cliValueOptions(commands);
4637
4679
  function isScanImportCommand(argv) {
4638
4680
  const commandIndex = cliCommandIndex(argv);
4639
4681
  return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";
@@ -4741,6 +4783,36 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4741
4783
  command === "publish" ||
4742
4784
  command === "import";
4743
4785
  const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;
4786
+ if (command === "import" &&
4787
+ (subcommand === "github" || subcommand === "github-advisories") &&
4788
+ frameworkFlags.rawCollector) {
4789
+ // Incur's skill-sync notice turns a saved collector array into an object.
4790
+ cliOptions.sync = false;
4791
+ }
4792
+ if (!importsEnabled &&
4793
+ ((command === "publish" && subcommand === "findings") ||
4794
+ (command === "findings" && subcommand === "imported") ||
4795
+ (command === "import" && subcommand === "github-advisories"))) {
4796
+ if (process.env["COMPLETE"] ||
4797
+ argv.some((value) => FRAMEWORK_ACTIONS.has(value))) {
4798
+ return externalImportsDisabledMessage;
4799
+ }
4800
+ if (!argv.includes("--version")) {
4801
+ if (argv.includes("--schema") ||
4802
+ (command !== "publish" &&
4803
+ (command !== "import" || !argv.includes("--full-output")))) {
4804
+ return externalImportsDisabledMessage;
4805
+ }
4806
+ disabledImportInvocation = true;
4807
+ // This route only formats a disabled command; it is not an installed skill.
4808
+ cliOptions.sync = false;
4809
+ if (command === "publish")
4810
+ registerFindingPublication();
4811
+ else
4812
+ registerGitHubAdvisories();
4813
+ valueOptions = cliValueOptions(commands);
4814
+ }
4815
+ }
4744
4816
  if (command === "info") {
4745
4817
  for (let index = 0; index < argv.length; index += 1) {
4746
4818
  const argument = argv[index];
@@ -4798,8 +4870,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4798
4870
  : 1)) {
4799
4871
  return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;
4800
4872
  }
4873
+ if (disabledImportInvocation && frameworkFlags.hideDisabledRoute)
4874
+ return externalImportsDisabledMessage;
4801
4875
  }
4802
4876
  argv = normalizeScanImportArguments(defaultListCommand(argv));
4877
+ const frameworkArgv = argv.flatMap((argument) => {
4878
+ const separator = argument.indexOf("=");
4879
+ if (separator < 0 ||
4880
+ !FRAMEWORK_VALUE_OPTIONS.has(argument.slice(0, separator)))
4881
+ return [argument];
4882
+ return [argument.slice(0, separator), argument.slice(separator + 1)];
4883
+ });
4884
+ const frameworkFlags = frameworkOutputFlags(frameworkArgv);
4803
4885
  const policyFullOutput = argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
4804
4886
  const argumentError = validateCliArguments(argv, positionals);
4805
4887
  if (argumentError !== undefined && !policyFullOutput) {
@@ -4893,12 +4975,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4893
4975
  }
4894
4976
  let notice;
4895
4977
  try {
4896
- await cli.serve(argv.flatMap((argument) => {
4897
- if (!/^--(?:format|filter-output|token-limit|token-offset)=/u.test(argument))
4898
- return [argument];
4899
- const separator = argument.indexOf("=");
4900
- return [argument.slice(0, separator), argument.slice(separator + 1)];
4901
- }), {
4978
+ await cli.serve(frameworkArgv, {
4902
4979
  stdout: frameworkCapture.stream.write,
4903
4980
  exit: (code) => {
4904
4981
  frameworkExit = code;
@@ -4946,6 +5023,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4946
5023
  catch { }
4947
5024
  }
4948
5025
  if (frameworkExit !== undefined) {
5026
+ if (disabledImportInvocation && exitCode === 0) {
5027
+ reportPublicationError(externalImportsDisabledMessage, undefined);
5028
+ return exitCode;
5029
+ }
4949
5030
  if (policyFullOutput || structuredError) {
4950
5031
  if (exitCode === 0)
4951
5032
  exitCode = 2;
@@ -5026,13 +5107,12 @@ async function runScanImport(options, errorOutput, dependencies) {
5026
5107
  removeSignals();
5027
5108
  }
5028
5109
  }
5029
- async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt, scanPromptFile, validationPromptFile, }, directory) {
5110
+ async function prepareScanArgumentsFromRecipe(recipe, operation, { scanPrompt, scanPromptFile, validationPromptFile, }, directory) {
5030
5111
  if (recipe === undefined || !isJsonObject(recipe)) {
5031
5112
  throw new CodexSecurityError("This scan does not have a saved launch recipe.");
5032
5113
  }
5033
- if (recipe["requiresScanPrompt"] === true &&
5034
- scanPrompt === undefined &&
5035
- scanPromptFile === undefined) {
5114
+ const requiresRerunPrompt = operation === "rerun" && recipe["requiresScanPrompt"] === true;
5115
+ if (requiresRerunPrompt && scanPromptFile === undefined) {
5036
5116
  throw new CodexSecurityError("This scan used additional instructions. Supply --scan-prompt-file to rerun it.");
5037
5117
  }
5038
5118
  if (recipe["validationMode"] === "custom" &&
@@ -5125,7 +5205,7 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
5125
5205
  throw new CodexSecurityError("The saved scan recipe contains invalid launch settings.");
5126
5206
  }
5127
5207
  const prompts = await resolveScanPrompts({ scanPrompt, scanPromptFile, validationPromptFile }, repository, directory);
5128
- if (recipe["requiresScanPrompt"] === true && !prompts.scanPrompt?.trim()) {
5208
+ if (requiresRerunPrompt && !prompts.scanPrompt?.trim()) {
5129
5209
  throw new CodexSecurityError("This scan used additional instructions. The --scan-prompt-file must not be empty.");
5130
5210
  }
5131
5211
  return {
@@ -5157,20 +5237,38 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
5157
5237
  maxCostUsd,
5158
5238
  maxTimeMinutes: maxTimeMinutes.data,
5159
5239
  dryRun: false,
5160
- parentScanId,
5161
5240
  ...(recipe["mock"] === true ? { mock: true } : {}),
5162
5241
  expectedPluginVersion: typeof recipe["pluginVersion"] === "string"
5163
5242
  ? recipe["pluginVersion"]
5164
5243
  : undefined,
5165
5244
  };
5166
5245
  }
5246
+ function frameworkOutputFlags(argv) {
5247
+ let hideDisabledRoute = false;
5248
+ let fullOutput = false;
5249
+ let rawCollector = false;
5250
+ for (let index = 0; index < argv.length; index++) {
5251
+ const value = argv[index];
5252
+ if (FRAMEWORK_ACTIONS.has(value) ||
5253
+ value === "--schema" ||
5254
+ value === "--help" ||
5255
+ value === "-h")
5256
+ hideDisabledRoute = true;
5257
+ if (value === "--full-output")
5258
+ fullOutput = true;
5259
+ if (value === "--json")
5260
+ rawCollector = true;
5261
+ if (FRAMEWORK_VALUE_OPTIONS.has(value)) {
5262
+ const operand = argv[++index];
5263
+ if (value === "--format")
5264
+ rawCollector =
5265
+ operand === "json" || operand === "jsonl" || operand === "yaml";
5266
+ }
5267
+ }
5268
+ return { hideDisabledRoute, rawCollector: rawCollector && !fullOutput };
5269
+ }
5167
5270
  function cliValueOptions(commands) {
5168
- const options = new Set([
5169
- "--format",
5170
- "--filter-output",
5171
- "--token-limit",
5172
- "--token-offset",
5173
- ]);
5271
+ const options = new Set(FRAMEWORK_VALUE_OPTIONS);
5174
5272
  for (const command of commands.values()) {
5175
5273
  if ("_group" in command) {
5176
5274
  for (const option of cliValueOptions(command.commands))
@@ -6500,6 +6598,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6500
6598
  let deepConsolidating = false;
6501
6599
  let runningCost = null;
6502
6600
  let runningUsage = null;
6601
+ let usageFreshness = null;
6602
+ let accountLimits = null;
6503
6603
  let maxCostUsd = arguments_.maxCostUsd;
6504
6604
  const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
6505
6605
  let phase = null;
@@ -6579,6 +6679,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6579
6679
  let providerOptions = { provider: "openai" };
6580
6680
  let auth = arguments_.auth;
6581
6681
  let patchAnalyticsOverride;
6682
+ let validation;
6683
+ let validationError;
6582
6684
  let patchServiceTier;
6583
6685
  let patchRequestMetadata;
6584
6686
  let patchOtel;
@@ -6592,6 +6694,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6592
6694
  deepScanOptions(arguments_);
6593
6695
  const directory = dependencies.currentDirectory();
6594
6696
  repository = arguments_.repository ?? directory;
6697
+ if (arguments_.validate) {
6698
+ repository = await normalizeRepository(resolve(directory, expandHome(repository)), preparationAbortController.signal);
6699
+ }
6595
6700
  const target = arguments_.target;
6596
6701
  const prompts = await resolveScanPrompts(arguments_, resolve(directory, repository), directory);
6597
6702
  const config = {
@@ -6695,6 +6800,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6695
6800
  input: scanInput,
6696
6801
  onInterrupt,
6697
6802
  });
6803
+ dashboard.setChatGptAuth(isChatGptAuthentication(selectedAuthentication, auth));
6698
6804
  }
6699
6805
  const scope = scanScope(arguments_);
6700
6806
  const runningMessage = () => {
@@ -6711,9 +6817,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6711
6817
  details.push(`Reviews: ${deepProgress.completed} completed, ${deepProgress.active} active, cap ${deepProgress.maximum}`);
6712
6818
  }
6713
6819
  else if (fileProgress !== null) {
6714
- const count = scanProgressCount(fileProgress);
6715
- if (count.total > 0)
6716
- details.push(`${count.label === "reviews" ? "Reviews" : "Files"}: ${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")}`);
6820
+ details.push(formatScanProgressCount(fileProgress, "status"));
6717
6821
  }
6718
6822
  const tokens = runningCost !== null
6719
6823
  ? formatScanCostTokens(runningCost)
@@ -6723,6 +6827,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6723
6827
  if (showCost && runningCost !== null) {
6724
6828
  details.push(`Cost: ${formatScanCost(runningCost)}`);
6725
6829
  }
6830
+ if (tokens !== null)
6831
+ details.push(usageFreshness ?? USAGE_TIME_UNAVAILABLE);
6832
+ if (accountLimits !== null)
6833
+ details.push(diagnosticValue(accountLimits));
6834
+ else if (isChatGptAuthentication(selectedAuthentication, auth))
6835
+ details.push(ACCOUNT_LIMITS_UNAVAILABLE);
6726
6836
  return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
6727
6837
  };
6728
6838
  if (dashboard === null) {
@@ -6758,6 +6868,22 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6758
6868
  archiveExisting: arguments_.archiveExisting,
6759
6869
  parentScanId: arguments_.parentScanId,
6760
6870
  expectedPluginVersion: arguments_.expectedPluginVersion,
6871
+ onUsageObservation: async (observation) => {
6872
+ if (dashboard !== null) {
6873
+ dashboard.setUsageObservation(observation);
6874
+ return;
6875
+ }
6876
+ usageFreshness = formatUsageFreshness(observation);
6877
+ accountLimits = formatAccountLimits(observation);
6878
+ const priorUsage = runningUsage;
6879
+ const priorCost = runningCost;
6880
+ // Usage and cost callbacks render the same poll. Refresh here for a receipt alone.
6881
+ await Promise.resolve();
6882
+ if (runningUsage === priorUsage && runningCost === priorCost) {
6883
+ progress?.stopTimer();
6884
+ progress?.startTimer(runningMessage());
6885
+ }
6886
+ },
6761
6887
  onUsage: async (usage) => {
6762
6888
  runningUsage = usage;
6763
6889
  if (dashboard !== null) {
@@ -6827,6 +6953,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6827
6953
  },
6828
6954
  onAuthentication: (authentication) => {
6829
6955
  selectedAuthentication = authentication;
6956
+ dashboard?.setChatGptAuth(isChatGptAuthentication(authentication, auth));
6830
6957
  const bedrock = providerOptions.provider === "amazon-bedrock" ||
6831
6958
  authentication.method === "aws_credentials";
6832
6959
  diagnostic("authentication.selected", {
@@ -6936,8 +7063,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6936
7063
  if (progress === null)
6937
7064
  return;
6938
7065
  progress.stopTimer();
6939
- const count = scanProgressCount(update);
6940
- progress.stage(`Scan phase: ${phase}${count.total === 0 ? "" : ` (${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")} ${count.label})`}.`);
7066
+ const count = formatScanProgressCount(update, "phase");
7067
+ progress.stage(`Scan phase: ${phase} (${count}).`);
6941
7068
  progress.startTimer(runningMessage());
6942
7069
  },
6943
7070
  onDeepProgress: (update) => {
@@ -7013,10 +7140,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7013
7140
  }
7014
7141
  },
7015
7142
  };
7143
+ if (((arguments_.validate && !arguments_.dryRun) ||
7144
+ arguments_.rerunInputIdentity !== undefined) &&
7145
+ options.knowledgeBasePaths?.length) {
7146
+ options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal);
7147
+ }
7016
7148
  if (arguments_.rerunInputIdentity !== undefined) {
7017
- if (options.knowledgeBasePaths?.length) {
7018
- options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal);
7019
- }
7020
7149
  const previousInputs = arguments_.rerunInputIdentity;
7021
7150
  const currentInputs = scanInputIdentity(options.scanPrompt, options.knowledgeBaseSnapshot);
7022
7151
  const changes = isJsonObject(previousInputs)
@@ -7041,6 +7170,96 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7041
7170
  result = await security.run(repository, options);
7042
7171
  scanDir = result.scanDir;
7043
7172
  repository = resolve(dependencies.currentDirectory(), repository);
7173
+ if (arguments_.validate) {
7174
+ const scanId = result.manifest.scan.id;
7175
+ const checkTarget = async () => {
7176
+ const context = await dependencies.runWorkbench(["get-scan", "--scan-id", scanId, "--check-target"], undefined, preparationAbortController.signal, config.pythonPath, repository, options.knowledgeBaseSnapshot?.protectedRoots, config.pluginPath);
7177
+ const scan = context["scan"];
7178
+ if (!isJsonObject(scan) ||
7179
+ scan["targetPath"] !== (await realpath(repository))) {
7180
+ throw new CodexSecurityError("The recorded scan target does not match the validation repository.");
7181
+ }
7182
+ };
7183
+ const findings = result.findings.findings;
7184
+ if (targetWarnings.length > 0) {
7185
+ validation = {
7186
+ status: "skipped",
7187
+ reason: "The scan target changed during execution.",
7188
+ };
7189
+ }
7190
+ else if (findings.length === 0) {
7191
+ try {
7192
+ await checkTarget();
7193
+ validation = { status: "complete", findings: 0 };
7194
+ }
7195
+ catch (error) {
7196
+ const message = errorMessage(error);
7197
+ validationError = message;
7198
+ validation = { status: "failed", findings: 0, message };
7199
+ errorOutput.write(`codex-security: Validation failed: ${diagnosticValue(message)}\n`);
7200
+ }
7201
+ }
7202
+ else {
7203
+ stopPresentation();
7204
+ try {
7205
+ progress?.stage(`Validating ${findings.length} scan findings`);
7206
+ }
7207
+ catch { }
7208
+ try {
7209
+ const scanDirectory = result.scanDir;
7210
+ let reportPath = join(scanDirectory, "validation.md");
7211
+ const report = await open(reportPath, "wx", 0o600).catch(async (error) => {
7212
+ if (error.code !== "EEXIST")
7213
+ throw error;
7214
+ reportPath = join(scanDirectory, `validation-${randomUUID()}.md`);
7215
+ return await open(reportPath, "wx", 0o600);
7216
+ });
7217
+ validation = { status: "failed", findings: 0, reportPath };
7218
+ let completed = 0;
7219
+ try {
7220
+ for (const finding of findings) {
7221
+ const assessment = await security.validate({
7222
+ repositoryPath: repository,
7223
+ scanId: result.manifest.scan.id,
7224
+ workflowId: arguments_.workflowId,
7225
+ knowledgeBasePaths: options.knowledgeBasePaths,
7226
+ knowledgeBaseSnapshot: options.knowledgeBaseSnapshot,
7227
+ finding,
7228
+ auth,
7229
+ cyberAccessProgram: arguments_.cyberAccessProgram,
7230
+ safetyIdentifier: arguments_.safetyIdentifier,
7231
+ signal: preparationAbortController.signal,
7232
+ });
7233
+ await report.writeFile(`${completed === 0 ? "" : "\n---\n\n"}## ${finding.occurrenceId}\n\nDisposition: ${assessment.disposition}\n\nEvidence: ${assessment.outputDir}\n\n${assessment.report}\n`);
7234
+ completed += 1;
7235
+ validation = { ...validation, findings: completed };
7236
+ }
7237
+ }
7238
+ finally {
7239
+ await report.close();
7240
+ }
7241
+ await checkTarget();
7242
+ validation = {
7243
+ status: "complete",
7244
+ findings: findings.length,
7245
+ reportPath,
7246
+ };
7247
+ try {
7248
+ progress?.stage(`Finding validation saved to ${reportPath}`);
7249
+ }
7250
+ catch { }
7251
+ }
7252
+ catch (error) {
7253
+ const message = errorMessage(error);
7254
+ validationError = message;
7255
+ validation = { ...validation, status: "failed", message };
7256
+ errorOutput.write(`codex-security: Validation failed: ${diagnosticValue(message)}\n`);
7257
+ if (validation["reportPath"] !== undefined) {
7258
+ errorOutput.write(`Partial validation report: ${diagnosticValue(validation["reportPath"])}\n`);
7259
+ }
7260
+ }
7261
+ }
7262
+ }
7044
7263
  }
7045
7264
  }
7046
7265
  catch (error) {
@@ -7055,7 +7274,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7055
7274
  diagnostic("runtime.cleanup.failed", {
7056
7275
  classification: classifyConnectionFailure(error),
7057
7276
  });
7058
- if (!failed) {
7277
+ if (!failed && validationError === undefined) {
7059
7278
  failed = true;
7060
7279
  failure = error;
7061
7280
  }
@@ -7066,8 +7285,11 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7066
7285
  let failureData;
7067
7286
  if (arguments_.includeFailureResults &&
7068
7287
  (failed || requestedSignal !== null)) {
7069
- if (result !== null)
7288
+ if (result !== null) {
7070
7289
  failureData = result.toJSON();
7290
+ if (validation !== undefined)
7291
+ failureData = { ...failureData, validation };
7292
+ }
7071
7293
  else if (registeredScan !== undefined) {
7072
7294
  try {
7073
7295
  const contract = await loadContract(registeredScan.scanDir, {
@@ -7090,6 +7312,19 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7090
7312
  signal: requestedSignal,
7091
7313
  partial_output: scanDir !== null,
7092
7314
  });
7315
+ if (result !== null && arguments_.validate) {
7316
+ const exitCode = requestedSignal === "SIGINT" ? 130 : 143;
7317
+ const message = `Validation interrupted. Completed scan output was kept at ${errorMessage(result.scanDir)}.`;
7318
+ errorOutput.write(`codex-security: ${message}\n`);
7319
+ return {
7320
+ exitCode,
7321
+ error: message,
7322
+ data: {
7323
+ ...result.toJSON(),
7324
+ validation: { ...validation, status: "failed", exitCode },
7325
+ },
7326
+ };
7327
+ }
7093
7328
  const exitCode = interruptedExit(requestedSignal, scanDir, errorOutput);
7094
7329
  printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
7095
7330
  return {
@@ -7176,6 +7411,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7176
7411
  let scanData = targetWarnings.length === 0
7177
7412
  ? result.toJSON()
7178
7413
  : { ...result.toJSON(), warnings: targetWarnings };
7414
+ if (validation !== undefined)
7415
+ scanData = { ...scanData, validation };
7179
7416
  let deepScanStop;
7180
7417
  if (arguments_.mode === "deep") {
7181
7418
  deepScanStop = (await readDeepScanStop(result, maxCostUsd, dependencies.runWorkbench).catch(() => undefined)) ?? {
@@ -7205,6 +7442,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
7205
7442
  ...(error === undefined ? {} : { error }),
7206
7443
  };
7207
7444
  };
7445
+ if (validationError !== undefined) {
7446
+ return finishResult(2, validationError);
7447
+ }
7208
7448
  if (targetWarnings.length > 0) {
7209
7449
  const message = "Scan target changed during execution; results do not represent the current checkout.";
7210
7450
  errorOutput.write(`codex-security: ${message}\n`);
@@ -7590,6 +7830,7 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
7590
7830
  ? ""
7591
7831
  : ` ${paint("THREAT MODEL", "1;36")} ${paint(errorMessage(threatModelPath), 4)}\n`) +
7592
7832
  `\n ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
7833
+ ` ${paint("SCOPE", 1)} ${formatCoverageScope({ mode: result.mode, ...result.manifest.scan.scope, explicitExclusions: result.review.excludedPaths.map((pattern) => ({ pattern, reason: "Excluded from review" })) })}\n` +
7593
7834
  (deepScanStop === undefined
7594
7835
  ? ""
7595
7836
  : ` ${paint("STOPPED", 1)} ${deepScanStop.reason}\n`) +
@@ -7614,11 +7855,29 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
7614
7855
  errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
7615
7856
  }
7616
7857
  }
7617
- function componentScanEventLine(componentName, event, showCost) {
7858
+ function formatScanProgressCount(progress, style) {
7859
+ const { label, completed, total } = scanProgressCount(progress);
7860
+ const totalText = total.toLocaleString("en-US");
7861
+ if (label === "files" && completed === 0) {
7862
+ return style === "phase"
7863
+ ? `${totalText} ${total === 1 ? "file" : "files"} inventoried`
7864
+ : `File inventory: ${totalText}`;
7865
+ }
7866
+ const ratio = `${completed.toLocaleString("en-US")}/${totalText}`;
7867
+ return style === "phase"
7868
+ ? `${ratio} ${label}`
7869
+ : `${label === "reviews" ? "Reviews" : "Files"}: ${ratio}`;
7870
+ }
7871
+ function componentScanEventLine(componentName, event, showCost, requestedAuth) {
7872
+ if (event.type === "authentication") {
7873
+ return isChatGptAuthentication(event.value, requestedAuth)
7874
+ ? `codex-security: ${componentName} | ${ACCOUNT_LIMITS_UNAVAILABLE}\n`
7875
+ : null;
7876
+ }
7618
7877
  if (event.type === "progress") {
7619
7878
  const progress = event.value;
7620
- const count = scanProgressCount(progress);
7621
- return `codex-security: ${componentName} ${scanPhase(progress.phase)} | ${count.label === "reviews" ? "Reviews" : "Files"}: ${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")}\n`;
7879
+ const count = formatScanProgressCount(progress, "status");
7880
+ return `codex-security: ${componentName} ${scanPhase(progress.phase)} | ${count}\n`;
7622
7881
  }
7623
7882
  if (event.type === "usage") {
7624
7883
  const tokens = formatTokenUsage(event.value);
@@ -7626,6 +7885,13 @@ function componentScanEventLine(componentName, event, showCost) {
7626
7885
  ? null
7627
7886
  : `codex-security: ${componentName} | Tokens: ${tokens}\n`;
7628
7887
  }
7888
+ if (event.type === "usage-observation") {
7889
+ const details = [
7890
+ formatUsageFreshness(event.value) ?? USAGE_TIME_UNAVAILABLE,
7891
+ formatAccountLimits(event.value),
7892
+ ].filter((detail) => detail !== null);
7893
+ return `codex-security: ${componentName} | ${diagnosticValue(details.join(" | "))}\n`;
7894
+ }
7629
7895
  if (event.type !== "cost" || !showCost)
7630
7896
  return null;
7631
7897
  return `codex-security: ${componentName} | Cost: ${formatScanCost(event.value)}\n`;