@openai/codex-security 0.9.1 → 0.10.1

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 (444) hide show
  1. package/README.md +37 -788
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +3 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  5. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  6. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  14. package/_bundled_plugin/references/access-advisory.md +1 -1
  15. package/_bundled_plugin/references/artifact-storage.md +1 -1
  16. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  17. package/_bundled_plugin/references/core-scan.md +5 -42
  18. package/_bundled_plugin/references/final-report.md +1 -1
  19. package/_bundled_plugin/references/focused-investigator.md +13 -0
  20. package/_bundled_plugin/references/scan-prologue.md +2 -2
  21. package/_bundled_plugin/references/scan-runtime.md +4 -2
  22. package/_bundled_plugin/references/security-guidance.md +14 -1
  23. package/_bundled_plugin/references/threat-model.md +1 -0
  24. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +30 -12
  26. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  27. package/_bundled_plugin/scripts/finalize_scan_contract.py +47 -9
  28. package/_bundled_plugin/scripts/launch_codex_security_mcp +54 -16
  29. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +2 -0
  30. package/_bundled_plugin/scripts/posix_scan_local_files.py +26 -1
  31. package/_bundled_plugin/scripts/snapshot_sqlite.py +8 -2
  32. package/_bundled_plugin/scripts/windows_scan_local_files.py +216 -25
  33. package/_bundled_plugin/scripts/workbench/handoff.py +55 -25
  34. package/_bundled_plugin/scripts/workbench/storage.py +25 -5
  35. package/_bundled_plugin/scripts/workbench_cli.py +24 -2
  36. package/_bundled_plugin/scripts/workbench_constants.py +2 -0
  37. package/_bundled_plugin/scripts/workbench_db.py +257 -268
  38. package/_bundled_plugin/scripts/workbench_feedback.py +49 -4
  39. package/_bundled_plugin/scripts/workbench_native_indexes.py +226 -29
  40. package/_bundled_plugin/scripts/workbench_progress.py +159 -3
  41. package/_bundled_plugin/scripts/workbench_publication.py +2 -3
  42. package/_bundled_plugin/scripts/workbench_remediation.py +142 -2
  43. package/_bundled_plugin/scripts/workbench_saved_results.py +48 -8
  44. package/_bundled_plugin/scripts/workbench_scan_history.py +291 -134
  45. package/_bundled_plugin/scripts/workbench_scan_start.py +208 -11
  46. package/_bundled_plugin/scripts/workbench_scan_usage.py +36 -10
  47. package/_bundled_plugin/scripts/workbench_schema.py +220 -14
  48. package/_bundled_plugin/scripts/workbench_setup.py +1 -1
  49. package/_bundled_plugin/scripts/workbench_source_scopes.py +8 -0
  50. package/_bundled_plugin/scripts/workbench_target.py +486 -85
  51. package/_bundled_plugin/scripts/workbench_target_state.py +1108 -22
  52. package/_bundled_plugin/shared/workbench-history-repairs.json +64 -14
  53. package/_bundled_plugin/shared/workbench-migrations.json +66 -0
  54. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -2
  55. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +2 -2
  56. package/_bundled_plugin/skills/fix-finding/SKILL.md +1 -0
  57. package/_bundled_plugin/skills/publish-findings/SKILL.md +26 -160
  58. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  59. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +2 -2
  60. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +3 -58
  61. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  62. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  63. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  64. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  65. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  66. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  67. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  68. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  69. package/bin/codex-security.mjs +2 -2
  70. package/dist/api.d.ts +7 -1
  71. package/dist/api.d.ts.map +1 -1
  72. package/dist/api.js +459 -157
  73. package/dist/api.js.map +1 -1
  74. package/dist/armorcode-findings.d.ts +9 -0
  75. package/dist/armorcode-findings.d.ts.map +1 -0
  76. package/dist/armorcode-findings.js +145 -0
  77. package/dist/armorcode-findings.js.map +1 -0
  78. package/dist/artifact-export.d.ts +2 -0
  79. package/dist/artifact-export.d.ts.map +1 -1
  80. package/dist/artifact-export.js +29 -13
  81. package/dist/artifact-export.js.map +1 -1
  82. package/dist/auth.d.ts +6 -2
  83. package/dist/auth.d.ts.map +1 -1
  84. package/dist/auth.js +33 -12
  85. package/dist/auth.js.map +1 -1
  86. package/dist/batch-cost.d.ts +18 -0
  87. package/dist/batch-cost.d.ts.map +1 -0
  88. package/dist/batch-cost.js +41 -0
  89. package/dist/batch-cost.js.map +1 -0
  90. package/dist/blackduck-findings.d.ts +1 -1
  91. package/dist/blackduck-findings.d.ts.map +1 -1
  92. package/dist/blackduck-findings.js +5 -18
  93. package/dist/blackduck-findings.js.map +1 -1
  94. package/dist/bundled-plugin.d.ts +4 -0
  95. package/dist/bundled-plugin.d.ts.map +1 -0
  96. package/dist/bundled-plugin.js +23 -0
  97. package/dist/bundled-plugin.js.map +1 -0
  98. package/dist/classify-scan-severity.d.ts +1 -1
  99. package/dist/classify-scan-severity.d.ts.map +1 -1
  100. package/dist/classify-scan-severity.js +11 -3
  101. package/dist/classify-scan-severity.js.map +1 -1
  102. package/dist/classify-severity-diagnostics.d.ts +10 -0
  103. package/dist/classify-severity-diagnostics.d.ts.map +1 -0
  104. package/dist/classify-severity-diagnostics.js +57 -0
  105. package/dist/classify-severity-diagnostics.js.map +1 -0
  106. package/dist/classify-severity-records.d.ts +4 -0
  107. package/dist/classify-severity-records.d.ts.map +1 -1
  108. package/dist/classify-severity-records.js +35 -8
  109. package/dist/classify-severity-records.js.map +1 -1
  110. package/dist/classify-severity.d.ts.map +1 -1
  111. package/dist/classify-severity.js +9 -6
  112. package/dist/classify-severity.js.map +1 -1
  113. package/dist/cli-argument.d.ts +4 -0
  114. package/dist/cli-argument.d.ts.map +1 -0
  115. package/dist/cli-argument.js +17 -0
  116. package/dist/cli-argument.js.map +1 -0
  117. package/dist/cli-help.d.ts +1 -1
  118. package/dist/cli-help.d.ts.map +1 -1
  119. package/dist/cli-help.js +71 -29
  120. package/dist/cli-help.js.map +1 -1
  121. package/dist/cli-hook.d.ts +3 -0
  122. package/dist/cli-hook.d.ts.map +1 -0
  123. package/dist/cli-hook.js +87 -0
  124. package/dist/cli-hook.js.map +1 -0
  125. package/dist/cli-integrations.d.ts +13 -0
  126. package/dist/cli-integrations.d.ts.map +1 -0
  127. package/dist/cli-integrations.js +333 -0
  128. package/dist/cli-integrations.js.map +1 -0
  129. package/dist/cli-mcp.d.ts +15 -0
  130. package/dist/cli-mcp.d.ts.map +1 -0
  131. package/dist/cli-mcp.js +178 -0
  132. package/dist/cli-mcp.js.map +1 -0
  133. package/dist/cli-token-view.d.ts +10 -0
  134. package/dist/cli-token-view.d.ts.map +1 -0
  135. package/dist/cli-token-view.js +41 -0
  136. package/dist/cli-token-view.js.map +1 -0
  137. package/dist/cli.d.ts +8 -3
  138. package/dist/cli.d.ts.map +1 -1
  139. package/dist/cli.js +1860 -903
  140. package/dist/cli.js.map +1 -1
  141. package/dist/cloud-publish.d.ts.map +1 -1
  142. package/dist/cloud-publish.js +33 -31
  143. package/dist/cloud-publish.js.map +1 -1
  144. package/dist/codex-sdk-environment.d.ts +6 -0
  145. package/dist/codex-sdk-environment.d.ts.map +1 -1
  146. package/dist/codex-sdk-environment.js +19 -0
  147. package/dist/codex-sdk-environment.js.map +1 -1
  148. package/dist/command-words.d.ts +3 -0
  149. package/dist/command-words.d.ts.map +1 -0
  150. package/dist/command-words.js +46 -0
  151. package/dist/command-words.js.map +1 -0
  152. package/dist/component-plan.d.ts.map +1 -1
  153. package/dist/component-plan.js +3 -3
  154. package/dist/component-plan.js.map +1 -1
  155. package/dist/component-scan.d.ts +3 -1
  156. package/dist/component-scan.d.ts.map +1 -1
  157. package/dist/component-scan.js +40 -7
  158. package/dist/component-scan.js.map +1 -1
  159. package/dist/config.d.ts +1 -1
  160. package/dist/config.d.ts.map +1 -1
  161. package/dist/config.js +30 -1
  162. package/dist/config.js.map +1 -1
  163. package/dist/continuum-aws.d.ts +6 -0
  164. package/dist/continuum-aws.d.ts.map +1 -0
  165. package/dist/continuum-aws.js +202 -0
  166. package/dist/continuum-aws.js.map +1 -0
  167. package/dist/continuum-collector.d.ts +44 -0
  168. package/dist/continuum-collector.d.ts.map +1 -0
  169. package/dist/continuum-collector.js +266 -0
  170. package/dist/continuum-collector.js.map +1 -0
  171. package/dist/continuum-findings.d.ts +31 -2
  172. package/dist/continuum-findings.d.ts.map +1 -1
  173. package/dist/continuum-findings.js +497 -59
  174. package/dist/continuum-findings.js.map +1 -1
  175. package/dist/contract.d.ts +1 -0
  176. package/dist/contract.d.ts.map +1 -1
  177. package/dist/contract.js +3 -0
  178. package/dist/contract.js.map +1 -1
  179. package/dist/cost.d.ts.map +1 -1
  180. package/dist/cost.js +1 -45
  181. package/dist/cost.js.map +1 -1
  182. package/dist/crowdstrike-findings.d.ts +7 -0
  183. package/dist/crowdstrike-findings.d.ts.map +1 -0
  184. package/dist/crowdstrike-findings.js +210 -0
  185. package/dist/crowdstrike-findings.js.map +1 -0
  186. package/dist/custom-validation-prompt.d.ts +1 -1
  187. package/dist/custom-validation-prompt.d.ts.map +1 -1
  188. package/dist/custom-validation-prompt.js +29 -19
  189. package/dist/custom-validation-prompt.js.map +1 -1
  190. package/dist/deduplication/local.d.ts +3 -1
  191. package/dist/deduplication/local.d.ts.map +1 -1
  192. package/dist/deduplication/local.js +8 -1
  193. package/dist/deduplication/local.js.map +1 -1
  194. package/dist/deduplication/refusal.d.ts.map +1 -1
  195. package/dist/deduplication/refusal.js +2 -1
  196. package/dist/deduplication/refusal.js.map +1 -1
  197. package/dist/deduplication/scan.d.ts +2 -0
  198. package/dist/deduplication/scan.d.ts.map +1 -1
  199. package/dist/deduplication/scan.js +24 -7
  200. package/dist/deduplication/scan.js.map +1 -1
  201. package/dist/deep-scan.d.ts.map +1 -1
  202. package/dist/deep-scan.js +16 -15
  203. package/dist/deep-scan.js.map +1 -1
  204. package/dist/endor-findings.d.ts +2 -2
  205. package/dist/endor-findings.d.ts.map +1 -1
  206. package/dist/endor-findings.js +6 -23
  207. package/dist/endor-findings.js.map +1 -1
  208. package/dist/errors.d.ts +3 -1
  209. package/dist/errors.d.ts.map +1 -1
  210. package/dist/errors.js +7 -3
  211. package/dist/errors.js.map +1 -1
  212. package/dist/executable-path.d.ts +3 -0
  213. package/dist/executable-path.d.ts.map +1 -1
  214. package/dist/executable-path.js +26 -0
  215. package/dist/executable-path.js.map +1 -1
  216. package/dist/external-findings-import.d.ts.map +1 -1
  217. package/dist/external-findings-import.js +12 -1
  218. package/dist/external-findings-import.js.map +1 -1
  219. package/dist/external-findings-local.d.ts +66 -4
  220. package/dist/external-findings-local.d.ts.map +1 -1
  221. package/dist/external-findings-local.js +258 -59
  222. package/dist/external-findings-local.js.map +1 -1
  223. package/dist/external-findings-publish.d.ts +6 -1
  224. package/dist/external-findings-publish.d.ts.map +1 -1
  225. package/dist/external-findings-publish.js +330 -1633
  226. package/dist/external-findings-publish.js.map +1 -1
  227. package/dist/external-findings-read.d.ts +11 -2
  228. package/dist/external-findings-read.d.ts.map +1 -1
  229. package/dist/external-findings-read.js +56 -53
  230. package/dist/external-findings-read.js.map +1 -1
  231. package/dist/external-findings.d.ts +1 -1
  232. package/dist/external-findings.d.ts.map +1 -1
  233. package/dist/external-findings.js +12 -1
  234. package/dist/external-findings.js.map +1 -1
  235. package/dist/external-import-contract.d.ts +6 -11
  236. package/dist/external-import-contract.d.ts.map +1 -1
  237. package/dist/external-import-contract.js +35 -177
  238. package/dist/external-import-contract.js.map +1 -1
  239. package/dist/external-import-models.d.ts +1 -1
  240. package/dist/external-import-models.d.ts.map +1 -1
  241. package/dist/external-import-models.js.map +1 -1
  242. package/dist/finding-prompt.d.ts.map +1 -1
  243. package/dist/finding-prompt.js +2 -2
  244. package/dist/finding-prompt.js.map +1 -1
  245. package/dist/github-dependabot-findings.d.ts.map +1 -1
  246. package/dist/github-dependabot-findings.js +3 -4
  247. package/dist/github-dependabot-findings.js.map +1 -1
  248. package/dist/github-findings.d.ts.map +1 -1
  249. package/dist/github-findings.js +19 -287
  250. package/dist/github-findings.js.map +1 -1
  251. package/dist/host-protocol.d.ts +6 -0
  252. package/dist/host-protocol.d.ts.map +1 -1
  253. package/dist/host-protocol.js +11 -1
  254. package/dist/host-protocol.js.map +1 -1
  255. package/dist/host-records-protocol.d.ts +2 -0
  256. package/dist/host-records-protocol.d.ts.map +1 -1
  257. package/dist/host-records-protocol.js +4 -0
  258. package/dist/host-records-protocol.js.map +1 -1
  259. package/dist/hosted-remediation.d.ts +1 -0
  260. package/dist/hosted-remediation.d.ts.map +1 -1
  261. package/dist/hosted-remediation.js +23 -3
  262. package/dist/hosted-remediation.js.map +1 -1
  263. package/dist/index.d.ts +5 -3
  264. package/dist/index.d.ts.map +1 -1
  265. package/dist/index.js +3 -1
  266. package/dist/index.js.map +1 -1
  267. package/dist/inspector-findings.d.ts.map +1 -1
  268. package/dist/inspector-findings.js +19 -35
  269. package/dist/inspector-findings.js.map +1 -1
  270. package/dist/knowledge-base.d.ts +1 -1
  271. package/dist/knowledge-base.d.ts.map +1 -1
  272. package/dist/knowledge-base.js +34 -27
  273. package/dist/knowledge-base.js.map +1 -1
  274. package/dist/linear.d.ts +11 -0
  275. package/dist/linear.d.ts.map +1 -1
  276. package/dist/linear.js.map +1 -1
  277. package/dist/local-git-metadata.d.ts +5 -2
  278. package/dist/local-git-metadata.d.ts.map +1 -1
  279. package/dist/local-git-metadata.js +8 -4
  280. package/dist/local-git-metadata.js.map +1 -1
  281. package/dist/multiscan.d.ts +4 -0
  282. package/dist/multiscan.d.ts.map +1 -1
  283. package/dist/multiscan.js +83 -39
  284. package/dist/multiscan.js.map +1 -1
  285. package/dist/opengrep-findings.d.ts +4 -2
  286. package/dist/opengrep-findings.d.ts.map +1 -1
  287. package/dist/opengrep-findings.js +39 -22
  288. package/dist/opengrep-findings.js.map +1 -1
  289. package/dist/private-finding-import.d.ts +8 -13
  290. package/dist/private-finding-import.d.ts.map +1 -1
  291. package/dist/private-finding-import.js +69 -129
  292. package/dist/private-finding-import.js.map +1 -1
  293. package/dist/project-config-schema.d.ts +2 -0
  294. package/dist/project-config-schema.d.ts.map +1 -1
  295. package/dist/project-config-schema.js +1 -0
  296. package/dist/project-config-schema.js.map +1 -1
  297. package/dist/project-config.d.ts +1 -0
  298. package/dist/project-config.d.ts.map +1 -1
  299. package/dist/project-config.js +56 -13
  300. package/dist/project-config.js.map +1 -1
  301. package/dist/prompt-files.d.ts +7 -2
  302. package/dist/prompt-files.d.ts.map +1 -1
  303. package/dist/prompt-files.js +42 -20
  304. package/dist/prompt-files.js.map +1 -1
  305. package/dist/provider-profile.d.ts.map +1 -1
  306. package/dist/provider-profile.js +4 -9
  307. package/dist/provider-profile.js.map +1 -1
  308. package/dist/publication.d.ts +1 -1
  309. package/dist/publication.d.ts.map +1 -1
  310. package/dist/publication.js.map +1 -1
  311. package/dist/record.d.ts +1 -5
  312. package/dist/record.d.ts.map +1 -1
  313. package/dist/record.js +3 -51
  314. package/dist/record.js.map +1 -1
  315. package/dist/remediation.d.ts.map +1 -1
  316. package/dist/remediation.js +3 -1
  317. package/dist/remediation.js.map +1 -1
  318. package/dist/runtime.d.ts +35 -7
  319. package/dist/runtime.d.ts.map +1 -1
  320. package/dist/runtime.js +782 -153
  321. package/dist/runtime.js.map +1 -1
  322. package/dist/saved-scan-bootstrap.d.ts +6 -1
  323. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  324. package/dist/saved-scan-bootstrap.js +267 -115
  325. package/dist/saved-scan-bootstrap.js.map +1 -1
  326. package/dist/scan-archive-path.d.ts +2 -0
  327. package/dist/scan-archive-path.d.ts.map +1 -0
  328. package/dist/scan-archive-path.js +5 -0
  329. package/dist/scan-archive-path.js.map +1 -0
  330. package/dist/scan-comparison.d.ts +20 -2
  331. package/dist/scan-comparison.d.ts.map +1 -1
  332. package/dist/scan-comparison.js +26 -5
  333. package/dist/scan-comparison.js.map +1 -1
  334. package/dist/scan-dashboard.d.ts +1 -0
  335. package/dist/scan-dashboard.d.ts.map +1 -1
  336. package/dist/scan-dashboard.js +18 -2
  337. package/dist/scan-dashboard.js.map +1 -1
  338. package/dist/scan-executor.d.ts.map +1 -1
  339. package/dist/scan-executor.js +4 -2
  340. package/dist/scan-executor.js.map +1 -1
  341. package/dist/scan-history-renderer.d.ts +1 -0
  342. package/dist/scan-history-renderer.d.ts.map +1 -1
  343. package/dist/scan-history-renderer.js +25 -9
  344. package/dist/scan-history-renderer.js.map +1 -1
  345. package/dist/scan-logs.d.ts.map +1 -1
  346. package/dist/scan-logs.js +28 -4
  347. package/dist/scan-logs.js.map +1 -1
  348. package/dist/scan-settings.d.ts +1 -0
  349. package/dist/scan-settings.d.ts.map +1 -1
  350. package/dist/scan-settings.js +1 -0
  351. package/dist/scan-settings.js.map +1 -1
  352. package/dist/scanner-import.d.ts +5 -11
  353. package/dist/scanner-import.d.ts.map +1 -1
  354. package/dist/scanner-import.js +16 -89
  355. package/dist/scanner-import.js.map +1 -1
  356. package/dist/security-policy.d.ts.map +1 -1
  357. package/dist/security-policy.js +26 -6
  358. package/dist/security-policy.js.map +1 -1
  359. package/dist/semgrep-findings.d.ts.map +1 -1
  360. package/dist/semgrep-findings.js +14 -48
  361. package/dist/semgrep-findings.js.map +1 -1
  362. package/dist/semgrep-platform-findings.d.ts +20 -70
  363. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  364. package/dist/semgrep-platform-findings.js +116 -333
  365. package/dist/semgrep-platform-findings.js.map +1 -1
  366. package/dist/severity-review.d.ts.map +1 -1
  367. package/dist/severity-review.js +1 -0
  368. package/dist/severity-review.js.map +1 -1
  369. package/dist/snyk-findings.d.ts +2 -0
  370. package/dist/snyk-findings.d.ts.map +1 -1
  371. package/dist/snyk-findings.js +5 -8
  372. package/dist/snyk-findings.js.map +1 -1
  373. package/dist/snyk-rest-findings.d.ts +3 -20
  374. package/dist/snyk-rest-findings.d.ts.map +1 -1
  375. package/dist/snyk-rest-findings.js +45 -217
  376. package/dist/snyk-rest-findings.js.map +1 -1
  377. package/dist/sonar-findings.d.ts +1 -1
  378. package/dist/sonar-findings.d.ts.map +1 -1
  379. package/dist/sonar-findings.js +2 -4
  380. package/dist/sonar-findings.js.map +1 -1
  381. package/dist/sonar-import.d.ts +3 -0
  382. package/dist/sonar-import.d.ts.map +1 -1
  383. package/dist/sonar-import.js +28 -30
  384. package/dist/sonar-import.js.map +1 -1
  385. package/dist/stored-finding-projection.d.ts +6 -0
  386. package/dist/stored-finding-projection.d.ts.map +1 -0
  387. package/dist/stored-finding-projection.js +129 -0
  388. package/dist/stored-finding-projection.js.map +1 -0
  389. package/dist/stored-findings-publication.d.ts +23 -0
  390. package/dist/stored-findings-publication.d.ts.map +1 -0
  391. package/dist/stored-findings-publication.js +169 -0
  392. package/dist/stored-findings-publication.js.map +1 -0
  393. package/dist/targets.d.ts +8 -1
  394. package/dist/targets.d.ts.map +1 -1
  395. package/dist/targets.js +103 -23
  396. package/dist/targets.js.map +1 -1
  397. package/dist/tenable-findings.d.ts +1 -4
  398. package/dist/tenable-findings.d.ts.map +1 -1
  399. package/dist/tenable-findings.js.map +1 -1
  400. package/dist/trivy-findings.d.ts.map +1 -1
  401. package/dist/trivy-findings.js +0 -11
  402. package/dist/trivy-findings.js.map +1 -1
  403. package/dist/trusted-executable.d.ts +7 -0
  404. package/dist/trusted-executable.d.ts.map +1 -1
  405. package/dist/trusted-executable.js +148 -37
  406. package/dist/trusted-executable.js.map +1 -1
  407. package/dist/value.js +3 -1
  408. package/dist/value.js.map +1 -1
  409. package/dist/veracode-findings.d.ts +1 -3
  410. package/dist/veracode-findings.d.ts.map +1 -1
  411. package/dist/veracode-findings.js +13 -38
  412. package/dist/veracode-findings.js.map +1 -1
  413. package/dist/version.d.ts +3 -1
  414. package/dist/version.d.ts.map +1 -1
  415. package/dist/version.js +184 -32
  416. package/dist/version.js.map +1 -1
  417. package/dist/wiz-findings.d.ts +2 -2
  418. package/dist/wiz-findings.d.ts.map +1 -1
  419. package/dist/wiz-findings.js +14 -92
  420. package/dist/wiz-findings.js.map +1 -1
  421. package/docs/classify-severity-records.md +30 -0
  422. package/docs/cli.md +537 -124
  423. package/docs/findings-service.md +22 -9
  424. package/docs/hosted-remediation.md +13 -4
  425. package/docs/sdk.md +918 -0
  426. package/package.json +15 -6
  427. package/schemas/external-findings.schema.json +2 -1
  428. package/schemas/project-config.schema.json +5 -0
  429. package/dist/hosted-scanner-v1.d.ts +0 -6
  430. package/dist/hosted-scanner-v1.d.ts.map +0 -1
  431. package/dist/hosted-scanner-v1.js +0 -60
  432. package/dist/hosted-scanner-v1.js.map +0 -1
  433. package/dist/reader-selection.d.ts +0 -15
  434. package/dist/reader-selection.d.ts.map +0 -1
  435. package/dist/reader-selection.js +0 -89
  436. package/dist/reader-selection.js.map +0 -1
  437. package/dist/semgrep-platform-v1.d.ts +0 -6
  438. package/dist/semgrep-platform-v1.d.ts.map +0 -1
  439. package/dist/semgrep-platform-v1.js +0 -83
  440. package/dist/semgrep-platform-v1.js.map +0 -1
  441. package/dist/snyk-rest-v1.d.ts +0 -28
  442. package/dist/snyk-rest-v1.d.ts.map +0 -1
  443. package/dist/snyk-rest-v1.js +0 -132
  444. package/dist/snyk-rest-v1.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ import type { ExternalFindings, ExternalSourceRepository } from "./external-findings.js";
2
+ export declare const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";
3
+ /** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */
4
+ export declare function crowdstrikeCheckout(input: ExternalFindings, declared: string | undefined, references: readonly ExternalSourceRepository[], repository: string): Promise<ExternalSourceRepository | undefined>;
5
+ /** Read a saved FCS CLI 4.x IaC JSON report. */
6
+ export declare function readCrowdStrikeFindings(path: string, sourceRepositoryUrl?: string): Promise<ExternalFindings>;
7
+ //# sourceMappingURL=crowdstrike-findings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crowdstrike-findings.d.ts","sourceRoot":"","sources":["../src/crowdstrike-findings.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gBAAgB,EAChB,wBAAwB,EACzB,MAAM,wBAAwB,CAAC;AAsBhC,eAAO,MAAM,uBAAuB,2BAA2B,CAAC;AAgFhE,6GAA6G;AAC7G,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,UAAU,EAAE,SAAS,wBAAwB,EAAE,EAC/C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAmF/C;AAED,gDAAgD;AAChD,wBAAsB,uBAAuB,CAC3C,IAAI,EAAE,MAAM,EACZ,mBAAmB,CAAC,EAAE,MAAM,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAuG3B"}
@@ -0,0 +1,210 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { CodexSecurityError } from "./errors.js";
5
+ import { repositoryUrlKey, validateExternalEvidence, } from "./external-import-contract.js";
6
+ import { isGitHubCloudHost } from "./git-remote.js";
7
+ import { array, normalizeRecords, readScannerJson, record, repositoryFilePath, requiredText, scannerSeverity, stableId, text, } from "./scanner-import.js";
8
+ import { declaredScannerRepositoryUrl, validScannerRepositoryUrl, } from "./scanner-repository-url.js";
9
+ export const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";
10
+ function joined(...values) {
11
+ return values.filter((value) => value !== null).join("\n\n") || null;
12
+ }
13
+ function positive(value) {
14
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0
15
+ ? value
16
+ : null;
17
+ }
18
+ // A git:: scan path without its ?ref= query. When the scanned URL has a user
19
+ // name, FCS writes each detection path after this prefix.
20
+ function gitScan(path) {
21
+ const value = text(path);
22
+ return value?.startsWith("git::") ? value.split("?", 1)[0] : undefined;
23
+ }
24
+ // The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts
25
+ // fetch over HTTPS or SSH, which do not match an http:// URL.
26
+ function gitScanRepository(scan) {
27
+ const source = scan.slice("git::".length);
28
+ const scheme = /^https:\/\//iu.exec(source)?.[0];
29
+ if (!scheme)
30
+ return undefined;
31
+ const subdirectory = source.indexOf("//", scheme.length);
32
+ const url = subdirectory === -1 ? source : source.slice(0, subdirectory);
33
+ return validScannerRepositoryUrl(url, "local") ? url : undefined;
34
+ }
35
+ // FCS writes paths relative to its working directory. A git:: scan writes them
36
+ // from the scan root, after a slash or after the scan path.
37
+ function detectionPath(detection, scan) {
38
+ const raw = text(detection["file"]);
39
+ const relative = scan === undefined || !raw
40
+ ? raw
41
+ : raw.startsWith(`${scan}/`)
42
+ ? raw.slice(scan.length + 1)
43
+ : raw.replace(/^\//u, "");
44
+ const path = repositoryFilePath(relative);
45
+ if (!path)
46
+ throw new CodexSecurityError("CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.");
47
+ return path;
48
+ }
49
+ // A detection in a registry or Git module names the calling file, but its line
50
+ // is inside the module. FCS states the call line only in module_remediation.
51
+ // FCS writes the file, module source and calling file in one form, so compare them as written.
52
+ function detectionLine(detection) {
53
+ const line = positive(detection["line"]);
54
+ const file = text(detection["file"]);
55
+ const source = text(detection["module_source"]);
56
+ if (detection["is_from_module"] !== true ||
57
+ !file ||
58
+ !source ||
59
+ file.startsWith(`${source}/`))
60
+ return line;
61
+ // Search for this file's exact phrase; the remediation text comes from the report.
62
+ const remediation = text(detection["module_remediation"]) ?? "";
63
+ const marker = `called by ${file} at line `;
64
+ const start = remediation.indexOf(marker);
65
+ const call = start === -1
66
+ ? null
67
+ : /^\d+\b/u.exec(remediation.slice(start + marker.length));
68
+ return call ? positive(Number(call[0])) : null;
69
+ }
70
+ /** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */
71
+ export async function crowdstrikeCheckout(input, declared, references, repository) {
72
+ if (input.report?.["format"] !== crowdstrikeReportFormat)
73
+ throw new CodexSecurityError("CrowdStrike imports require a report from the crowdstrike reader.");
74
+ // Only a declared URL binds the checkout to its fetch remotes. A git:: report's
75
+ // own repository is recorded and must agree with it.
76
+ const declarations = [
77
+ declared,
78
+ input.report["repositoryUrl"],
79
+ ...references.map(({ url }) => url),
80
+ ];
81
+ const reportScan = gitScan(input.report["git_scan"]);
82
+ const claims = [...declarations, reportScan && gitScanRepository(reportScan)];
83
+ const files = new Map();
84
+ for (const { evidence } of input.findings) {
85
+ validateExternalEvidence(evidence, "local");
86
+ const data = evidence.source_data;
87
+ if (data?.["format"] !== crowdstrikeReportFormat)
88
+ throw new CodexSecurityError("CrowdStrike findings must retain their native detection.");
89
+ const scan = gitScan(data["git_scan"]);
90
+ claims.push(data["repository_url"], evidence.details?.repository?.url, scan && gitScanRepository(scan));
91
+ // Check the retained detection's file, and that the shown location is the same.
92
+ const detection = record(data["detection"], "CrowdStrike detection");
93
+ const file = detectionPath(detection, scan);
94
+ const [location, ...others] = evidence.locations ?? [];
95
+ if (!location ||
96
+ others.length > 0 ||
97
+ location.path !== file ||
98
+ (location.line ?? null) !== detectionLine(detection))
99
+ throw new CodexSecurityError("CrowdStrike finding locations must match the native detection file and line.");
100
+ files.set(file, (files.get(file) ?? new Set()).add(detection["file_sha256"]));
101
+ }
102
+ const urls = claims
103
+ .filter((claim) => claim != null)
104
+ .map((claim) => declaredScannerRepositoryUrl(claim, "CrowdStrike", "local"));
105
+ if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)
106
+ throw new CodexSecurityError("CrowdStrike findings name a different repository than --source-repository-url.");
107
+ // Paths are relative to where FCS ran, so a missing file means a different root or checkout.
108
+ // FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.
109
+ for (const [file, hashes] of files) {
110
+ const path = join(repository, ...file.split("/"));
111
+ if (!(await stat(path).catch(() => null))?.isFile())
112
+ throw new CodexSecurityError(`${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`);
113
+ const hash = createHash("sha256")
114
+ .update(await readFile(path))
115
+ .digest("hex");
116
+ if ([...hashes].some((expected) => expected !== hash))
117
+ throw new CodexSecurityError(`${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`);
118
+ }
119
+ const url = urls[0];
120
+ if (url === undefined || declarations.every((claim) => claim == null))
121
+ return undefined;
122
+ const { hostname } = new URL(url);
123
+ return {
124
+ url,
125
+ platform: isGitHubCloudHost(hostname)
126
+ ? "github"
127
+ : hostname === "gitlab.com"
128
+ ? "gitlab"
129
+ : undefined,
130
+ };
131
+ }
132
+ /** Read a saved FCS CLI 4.x IaC JSON report. */
133
+ export async function readCrowdStrikeFindings(path, sourceRepositoryUrl) {
134
+ const document = record(await readScannerJson(path), "CrowdStrike report");
135
+ if (!Array.isArray(document["rule_detections"]))
136
+ throw new CodexSecurityError("Expected an FCS CLI 4.x IaC JSON report with rule_detections.");
137
+ const version = text(document["fcs_version"]);
138
+ const scan = gitScan(document["path"]);
139
+ const declared = sourceRepositoryUrl === undefined
140
+ ? undefined
141
+ : declaredScannerRepositoryUrl(sourceRepositoryUrl, "CrowdStrike", "local");
142
+ // A git:: report names the repository that FCS cloned.
143
+ const repositoryUrl = declared ?? (scan && gitScanRepository(scan));
144
+ const entries = array(document["rule_detections"], "CrowdStrike rule_detections").flatMap((value) => {
145
+ const { detections, ...rule } = record(value, "CrowdStrike rule");
146
+ return array(detections ?? [], "CrowdStrike detections").map((detection) => ({
147
+ rule,
148
+ detection: record(detection, "CrowdStrike detection"),
149
+ }));
150
+ });
151
+ return normalizeRecords(entries, ({ rule, detection }) => {
152
+ const kind = rule["rule_category"] === "Secret Management" ? "secret" : "iac";
153
+ const reason = text(detection["reason"]);
154
+ const recommendation = text(detection["recommendation"]);
155
+ const file = detectionPath(detection, scan);
156
+ return validateExternalEvidence({
157
+ title: requiredText(rule["rule_name"], "CrowdStrike rule_name"),
158
+ severity: scannerSeverity(text(rule["severity"])?.toLowerCase()),
159
+ description: joined(text(rule["description"]), reason),
160
+ locations: [{ path: file, line: detectionLine(detection) }],
161
+ source_scan_id: text(document["scan_uuid"]),
162
+ // Typed IaC and secret details must name their source repository.
163
+ details: repositoryUrl && {
164
+ kind,
165
+ repository: { url: repositoryUrl },
166
+ rule: {
167
+ id: text(rule["rule_uuid"]),
168
+ name: text(rule["rule_name"]),
169
+ },
170
+ configuration: kind === "iac"
171
+ ? {
172
+ platform: text(rule["platform"]),
173
+ cloud_platform: text(rule["cloud_provider"]),
174
+ expected: recommendation,
175
+ actual: reason,
176
+ }
177
+ : null,
178
+ remediation_instructions: joined(recommendation, text(detection["module_remediation"])),
179
+ scanner_origin: version
180
+ ? `CrowdStrike FCS CLI ${version}`
181
+ : "CrowdStrike FCS CLI",
182
+ },
183
+ source_data: structuredClone({
184
+ format: crowdstrikeReportFormat,
185
+ fcs_version: version,
186
+ ...(repositoryUrl && { repository_url: repositoryUrl }),
187
+ ...(scan !== undefined && { git_scan: scan }),
188
+ rule,
189
+ detection,
190
+ }),
191
+ }, "local");
192
+ }, ({ rule, detection }) => stableId("crowdstrike", [
193
+ requiredText(rule["rule_uuid"], "CrowdStrike rule_uuid"),
194
+ detectionPath(detection, scan),
195
+ positive(detection["line"]),
196
+ detection["resource_type"] ?? null,
197
+ detection["resource_name"] ?? null,
198
+ detection["reason"] ?? null,
199
+ detection["module_path"] ?? null,
200
+ ]), "local", {
201
+ report: {
202
+ format: crowdstrikeReportFormat,
203
+ ...(declared && { repositoryUrl: declared }),
204
+ ...(scan !== undefined && { git_scan: scan }),
205
+ fcs_version: version,
206
+ scan_uuid: text(document["scan_uuid"]),
207
+ },
208
+ });
209
+ }
210
+ //# sourceMappingURL=crowdstrike-findings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crowdstrike-findings.js","sourceRoot":"","sources":["../src/crowdstrike-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKjD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,eAAe,EACf,MAAM,EACN,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,QAAQ,EACR,IAAI,GACL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AAErC,MAAM,CAAC,MAAM,uBAAuB,GAAG,wBAAwB,CAAC;AAShE,SAAS,MAAM,CAAC,GAAG,MAAyB;IAC1C,OAAO,MAAM,CAAC,M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ClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI;QAC3B,SAAS,CAAC,aAAa,CAAC,IAAI,IAAI;KACjC,CAAC,EACJ,OAAO,EACP;QACE,MAAM,EAAE;YACN,MAAM,EAAE,uBAAuB;YAC/B,GAAG,CAAC,QAAQ,IAAI,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;YAC5C,GAAG,CAAC,IAAI,KAAK,SAAS,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;YAC7C,WAAW,EAAE,OAAO;YACpB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;SACvC;KACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type {\n ExternalFindings,\n ExternalSourceRepository,\n} from \"./external-findings.js\";\nimport {\n repositoryUrlKey,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport { isGitHubCloudHost } from \"./git-remote.js\";\nimport {\n array,\n normalizeRecords,\n readScannerJson,\n record,\n repositoryFilePath,\n requiredText,\n scannerSeverity,\n stableId,\n text,\n} from \"./scanner-import.js\";\nimport {\n declaredScannerRepositoryUrl,\n validScannerRepositoryUrl,\n} from \"./scanner-repository-url.js\";\n\nexport const crowdstrikeReportFormat = \"crowdstrike-fcs-iac/v1\";\n\ntype NativeRecord = Record<string, unknown>;\n\ninterface Entry {\n rule: NativeRecord;\n detection: NativeRecord;\n}\n\nfunction joined(...values: (string | null)[]): string | null {\n return values.filter((value) => value !== null).join(\"\\n\\n\") || null;\n}\n\nfunction positive(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0\n ? value\n : null;\n}\n\n// A git:: scan path without its ?ref= query. When the scanned URL has a user\n// name, FCS writes each detection path after this prefix.\nfunction gitScan(path: unknown): string | undefined {\n const value = text(path);\n return value?.startsWith(\"git::\") ? value.split(\"?\", 1)[0] : undefined;\n}\n\n// The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts\n// fetch over HTTPS or SSH, which do not match an http:// URL.\nfunction gitScanRepository(scan: string): string | undefined {\n const source = scan.slice(\"git::\".length);\n const scheme = /^https:\\/\\//iu.exec(source)?.[0];\n if (!scheme) return undefined;\n const subdirectory = source.indexOf(\"//\", scheme.length);\n const url = subdirectory === -1 ? source : source.slice(0, subdirectory);\n return validScannerRepositoryUrl(url, \"local\") ? url : undefined;\n}\n\n// FCS writes paths relative to its working directory. A git:: scan writes them\n// from the scan root, after a slash or after the scan path.\nfunction detectionPath(detection: NativeRecord, scan: string | undefined) {\n const raw = text(detection[\"file\"]);\n const relative =\n scan === undefined || !raw\n ? raw\n : raw.startsWith(`${scan}/`)\n ? raw.slice(scan.length + 1)\n : raw.replace(/^\\//u, \"\");\n const path = repositoryFilePath(relative);\n if (!path)\n throw new CodexSecurityError(\n \"CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.\",\n );\n return path;\n}\n\n// A detection in a registry or Git module names the calling file, but its line\n// is inside the module. FCS states the call line only in module_remediation.\n// FCS writes the file, module source and calling file in one form, so compare them as written.\nfunction detectionLine(detection: NativeRecord): number | null {\n const line = positive(detection[\"line\"]);\n const file = text(detection[\"file\"]);\n const source = text(detection[\"module_source\"]);\n if (\n detection[\"is_from_module\"] !== true ||\n !file ||\n !source ||\n file.startsWith(`${source}/`)\n )\n return line;\n // Search for this file's exact phrase; the remediation text comes from the report.\n const remediation = text(detection[\"module_remediation\"]) ?? \"\";\n const marker = `called by ${file} at line `;\n const start = remediation.indexOf(marker);\n const call =\n start === -1\n ? null\n : /^\\d+\\b/u.exec(remediation.slice(start + marker.length));\n return call ? positive(Number(call[0])) : null;\n}\n\n/** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */\nexport async function crowdstrikeCheckout(\n input: ExternalFindings,\n declared: string | undefined,\n references: readonly ExternalSourceRepository[],\n repository: string,\n): Promise<ExternalSourceRepository | undefined> {\n if (input.report?.[\"format\"] !== crowdstrikeReportFormat)\n throw new CodexSecurityError(\n \"CrowdStrike imports require a report from the crowdstrike reader.\",\n );\n // Only a declared URL binds the checkout to its fetch remotes. A git:: report's\n // own repository is recorded and must agree with it.\n const declarations: unknown[] = [\n declared,\n input.report[\"repositoryUrl\"],\n ...references.map(({ url }) => url),\n ];\n const reportScan = gitScan(input.report[\"git_scan\"]);\n const claims = [...declarations, reportScan && gitScanRepository(reportScan)];\n const files = new Map<string, Set<unknown>>();\n for (const { evidence } of input.findings) {\n validateExternalEvidence(evidence, \"local\");\n const data = evidence.source_data;\n if (data?.[\"format\"] !== crowdstrikeReportFormat)\n throw new CodexSecurityError(\n \"CrowdStrike findings must retain their native detection.\",\n );\n const scan = gitScan(data[\"git_scan\"]);\n claims.push(\n data[\"repository_url\"],\n evidence.details?.repository?.url,\n scan && gitScanRepository(scan),\n );\n // Check the retained detection's file, and that the shown location is the same.\n const detection = record(data[\"detection\"], \"CrowdStrike detection\");\n const file = detectionPath(detection, scan);\n const [location, ...others] = evidence.locations ?? [];\n if (\n !location ||\n others.length > 0 ||\n location.path !== file ||\n (location.line ?? null) !== detectionLine(detection)\n )\n throw new CodexSecurityError(\n \"CrowdStrike finding locations must match the native detection file and line.\",\n );\n files.set(\n file,\n (files.get(file) ?? new Set()).add(detection[\"file_sha256\"]),\n );\n }\n const urls = claims\n .filter((claim) => claim != null)\n .map((claim) =>\n declaredScannerRepositoryUrl(claim, \"CrowdStrike\", \"local\"),\n );\n if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)\n throw new CodexSecurityError(\n \"CrowdStrike findings name a different repository than --source-repository-url.\",\n );\n // Paths are relative to where FCS ran, so a missing file means a different root or checkout.\n // FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.\n for (const [file, hashes] of files) {\n const path = join(repository, ...file.split(\"/\"));\n if (!(await stat(path).catch(() => null))?.isFile())\n throw new CodexSecurityError(\n `${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`,\n );\n const hash = createHash(\"sha256\")\n .update(await readFile(path))\n .digest(\"hex\");\n if ([...hashes].some((expected) => expected !== hash))\n throw new CodexSecurityError(\n `${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`,\n );\n }\n const url = urls[0];\n if (url === undefined || declarations.every((claim) => claim == null))\n return undefined;\n const { hostname } = new URL(url);\n return {\n url,\n platform: isGitHubCloudHost(hostname)\n ? \"github\"\n : hostname === \"gitlab.com\"\n ? \"gitlab\"\n : undefined,\n };\n}\n\n/** Read a saved FCS CLI 4.x IaC JSON report. */\nexport async function readCrowdStrikeFindings(\n path: string,\n sourceRepositoryUrl?: string,\n): Promise<ExternalFindings> {\n const document = record(await readScannerJson(path), \"CrowdStrike report\");\n if (!Array.isArray(document[\"rule_detections\"]))\n throw new CodexSecurityError(\n \"Expected an FCS CLI 4.x IaC JSON report with rule_detections.\",\n );\n const version = text(document[\"fcs_version\"]);\n const scan = gitScan(document[\"path\"]);\n const declared =\n sourceRepositoryUrl === undefined\n ? undefined\n : declaredScannerRepositoryUrl(\n sourceRepositoryUrl,\n \"CrowdStrike\",\n \"local\",\n );\n // A git:: report names the repository that FCS cloned.\n const repositoryUrl = declared ?? (scan && gitScanRepository(scan));\n const entries: Entry[] = array(\n document[\"rule_detections\"],\n \"CrowdStrike rule_detections\",\n ).flatMap((value) => {\n const { detections, ...rule } = record(value, \"CrowdStrike rule\");\n return array(detections ?? [], \"CrowdStrike detections\").map(\n (detection) => ({\n rule,\n detection: record(detection, \"CrowdStrike detection\"),\n }),\n );\n });\n return normalizeRecords(\n entries,\n ({ rule, detection }) => {\n const kind =\n rule[\"rule_category\"] === \"Secret Management\" ? \"secret\" : \"iac\";\n const reason = text(detection[\"reason\"]);\n const recommendation = text(detection[\"recommendation\"]);\n const file = detectionPath(detection, scan);\n return validateExternalEvidence(\n {\n title: requiredText(rule[\"rule_name\"], \"CrowdStrike rule_name\"),\n severity: scannerSeverity(text(rule[\"severity\"])?.toLowerCase()),\n description: joined(text(rule[\"description\"]), reason),\n locations: [{ path: file, line: detectionLine(detection) }],\n source_scan_id: text(document[\"scan_uuid\"]),\n // Typed IaC and secret details must name their source repository.\n details: repositoryUrl && {\n kind,\n repository: { url: repositoryUrl },\n rule: {\n id: text(rule[\"rule_uuid\"]),\n name: text(rule[\"rule_name\"]),\n },\n configuration:\n kind === \"iac\"\n ? {\n platform: text(rule[\"platform\"]),\n cloud_platform: text(rule[\"cloud_provider\"]),\n expected: recommendation,\n actual: reason,\n }\n : null,\n remediation_instructions: joined(\n recommendation,\n text(detection[\"module_remediation\"]),\n ),\n scanner_origin: version\n ? `CrowdStrike FCS CLI ${version}`\n : \"CrowdStrike FCS CLI\",\n },\n source_data: structuredClone({\n format: crowdstrikeReportFormat,\n fcs_version: version,\n ...(repositoryUrl && { repository_url: repositoryUrl }),\n ...(scan !== undefined && { git_scan: scan }),\n rule,\n detection,\n }),\n },\n \"local\",\n );\n },\n ({ rule, detection }) =>\n stableId(\"crowdstrike\", [\n requiredText(rule[\"rule_uuid\"], \"CrowdStrike rule_uuid\"),\n detectionPath(detection, scan),\n positive(detection[\"line\"]),\n detection[\"resource_type\"] ?? null,\n detection[\"resource_name\"] ?? null,\n detection[\"reason\"] ?? null,\n detection[\"module_path\"] ?? null,\n ]),\n \"local\",\n {\n report: {\n format: crowdstrikeReportFormat,\n ...(declared && { repositoryUrl: declared }),\n ...(scan !== undefined && { git_scan: scan }),\n fcs_version: version,\n scan_uuid: text(document[\"scan_uuid\"]),\n },\n },\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
1
  import { type JsonObject } from "./config.js";
2
- export declare function customDiscoveryPrompt(pluginRoot: string, skillName: string): Promise<string>;
2
+ export declare function customDiscoveryPrompt(pluginRoot: string, skillName: string, standardHandoff: boolean): Promise<string>;
3
3
  export declare function customValidationConfig(config: JsonObject, pluginRoot: string): Promise<JsonObject>;
4
4
  //# sourceMappingURL=custom-validation-prompt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-validation-prompt.d.ts","sourceRoot":"","sources":["../src/custom-validation-prompt.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAoDnE,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,MAAM,CAAC,CAmDjB;AAED,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,UAAU,EAClB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,UAAU,CAAC,CA+BrB"}
1
+ {"version":3,"file":"custom-validation-prompt.d.ts","sourceRoot":"","sources":["../src/custom-validation-prompt.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAsFnE,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACvB,OAAO,CAAC,MAAM,CAAC,CA4BjB;AAED,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,UAAU,EAClB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,UAAU,CAAC,CA+BrB"}
@@ -8,6 +8,7 @@ import { PLUGIN_NAME } from "./runtime.js";
8
8
  // the ordinary validation sequence with a custom-validation request.
9
9
  const SOURCES = {
10
10
  "references/core-scan.md": [
11
+ "07abac7382a66338bfbe3def9a0e89e715a89561332c88ccb4477f97b6e84fe5",
11
12
  "0e301a70d9f20acbb797f5eafcac84c09dd0513991714812d5c4f7b1f64a4a89",
12
13
  "7690b6c854de07ff15984f6d2c25ddfa1f6ae65f65876cadf2f904054b4f0679",
13
14
  "83bafdc4089803e631eaaa86ec57167c7da3f51794514d0dcdb62c5afdced8a7",
@@ -41,27 +42,36 @@ async function source(pluginRoot, name) {
41
42
  function step(text, number) {
42
43
  return text.match(new RegExp(`^${number}\\. (.+)$`, "m"))[1];
43
44
  }
44
- export async function customDiscoveryPrompt(pluginRoot, skillName) {
45
+ async function legacyDiscoveryPrompt(pluginRoot) {
46
+ const [skill, core] = await Promise.all([
47
+ source(pluginRoot, "skills/security-scan/SKILL.md"),
48
+ source(pluginRoot, "references/core-scan.md"),
49
+ ]);
50
+ const discovery = core
51
+ .replace(/^7\. .+$/m, "7. Retain the combined source-backed candidates and their existing evidence. The SDK will run independent final validation in a separate turn.")
52
+ .replace(/^Keep discovery, validation, and attack-path reasoning.+$/m, "Keep source-evidence and counterevidence checks within discovery. Do not run an independent final validation pass or invoke separate phase skills.")
53
+ .replace("reconcile their evidence and submit the result;", "reconcile their evidence and preserve provisional candidates through the SDK-owned discovery handoff;");
54
+ return [
55
+ skill.slice(skill.indexOf("## Host And Setup"), skill.indexOf("## Workflow")),
56
+ "## Discovery workflow",
57
+ `1. ${step(skill, 1)}`,
58
+ "2. Perform the embedded core discovery workflow below. Do not reload the ordinary core-scan.md or top-level security-scan skill.",
59
+ `3. ${step(skill, 3).slice(step(skill, 3).indexOf("For an SDK-owned scan with a bound semantic draft tool,"))}`,
60
+ `4. ${HANDOFF}`,
61
+ "## Embedded core discovery workflow",
62
+ discovery,
63
+ ].join("\n\n");
64
+ }
65
+ export async function customDiscoveryPrompt(pluginRoot, skillName, standardHandoff) {
45
66
  let workflow;
46
67
  if (skillName === "security-scan") {
47
- const [skill, core] = await Promise.all([
48
- source(pluginRoot, "skills/security-scan/SKILL.md"),
49
- source(pluginRoot, "references/core-scan.md"),
50
- ]);
51
- const discovery = core
52
- .replace(/^7\. .+$/m, "7. Retain the combined source-backed candidates and their existing evidence. The SDK will run independent final validation in a separate turn.")
53
- .replace(/^Keep discovery, validation, and attack-path reasoning.+$/m, "Keep source-evidence and counterevidence checks within discovery. Do not run an independent final validation pass or invoke separate phase skills.")
54
- .replace("reconcile their evidence and submit the result;", "reconcile their evidence and preserve provisional candidates through the SDK-owned discovery handoff;");
55
- workflow = [
56
- skill.slice(skill.indexOf("## Host And Setup"), skill.indexOf("## Workflow")),
57
- "## Discovery workflow",
58
- `1. ${step(skill, 1)}`,
59
- "2. Perform the embedded core discovery workflow below. Do not reload the ordinary core-scan.md or top-level security-scan skill.",
60
- `3. ${step(skill, 3).slice(step(skill, 3).indexOf("For an SDK-owned scan with a bound semantic draft tool,"))}`,
61
- `4. ${HANDOFF}`,
62
- "## Embedded core discovery workflow",
63
- discovery,
64
- ].join("\n\n");
68
+ workflow = standardHandoff
69
+ ? [
70
+ "Use <plugin_dir>/references/core-scan.md for source discovery. This caller supplies the validation handoff: the SDK runs independent final validation in a separate turn. Check source evidence and counterevidence now, but do not run the default validation pass.",
71
+ "Keep any supplied investigation time allowance unchanged. Only for an explicit time request with no existing allowance, render <plugin_dir>/references/investigation-time-budget.md once before source review.",
72
+ HANDOFF,
73
+ ].join("\n\n")
74
+ : await legacyDiscoveryPrompt(pluginRoot);
65
75
  }
66
76
  else if (skillName === "security-diff-scan") {
67
77
  const skill = await source(pluginRoot, "skills/security-diff-scan/SKILL.md");
@@ -1 +1 @@
1
- {"version":3,"file":"custom-validation-prompt.js","sourceRoot":"","sources":["../src/custom-validation-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAmB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,4EAA4E;AAC5E,qEAAqE;AACrE,MAAM,OAAO,GAAG;IACd,yBAAyB,EAAE;QACzB,kEAAkE;QAClE,kEAAkE;QAClE,kEAAkE;QAClE,kEAAkE;KACnE;IACD,+BAA+B,EAAE;QAC/B,kEAAkE;Q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AU,sBAAsB,CAC1C,MAAkB,EAClB,UAAkB;IAElB,MAAM,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CACzB,MAAM,QAAQ,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CACtD,CAAC;IACF,MAAM,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAe,CAAC;IAC5D,MAAM,UAAU,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,CAAe,CAAC;IAC9D,yEAAyE;IACzE,0EAA0E;IAC1E,OAAO;QACL,GAAG,MAAM;QACT,WAAW,EAAE;YACX,GAAG,OAAO;YACV,CAAC,WAAW,CAAC,EAAE;gBACb,GAAG,MAAM;gBACT,GAAG,UAAU;gBACb,GAAG,EAAE,OAAO,CACV,UAAU,EACT,UAAU,CAAC,KAAK,CAAwB,IAAI,MAAM,CAAC,GAAG,IAAI,GAAG,CAC/D;gBACD,cAAc,EAAE;oBACd,GAAG,IAAI,GAAG,CAAC;wBACT,GAAG,CAAC,MAAM,CAAC,cAAc,IAAI,EAAE,CAAC;wBAChC,GAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAc;wBACrD,GAAG,cAAc;qBAClB,CAAC;iBACH;aACF;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { resolveCodexProfile, type JsonObject } from \"./config.js\";\nimport { IncompleteScanError } from \"./errors.js\";\nimport { PLUGIN_NAME } from \"./runtime.js\";\n\n// Review this adapter when the bundled workflows change. Never silently run\n// the ordinary validation sequence with a custom-validation request.\nconst SOURCES = {\n \"references/core-scan.md\": [\n \"0e301a70d9f20acbb797f5eafcac84c09dd0513991714812d5c4f7b1f64a4a89\",\n \"7690b6c854de07ff15984f6d2c25ddfa1f6ae65f65876cadf2f904054b4f0679\",\n \"83bafdc4089803e631eaaa86ec57167c7da3f51794514d0dcdb62c5afdced8a7\",\n \"848eb40d42b0bf9cf21748b9927d031b0461a4443f63e3954139f9801f41c3f6\",\n ],\n \"skills/security-scan/SKILL.md\": [\n \"b6a69658d48fff6979d6690e95d2096da236bb7e51b96ebb4f92102a9863d66c\",\n \"99cfcbbaa9d5b0450881ec752a116888b05b7fe21ea7af28fd22d088882dcd46\",\n ],\n \"skills/security-diff-scan/SKILL.md\": [\n \"09232fd5d96cfed2a5bdccd176c09b7e9ca53ebd7ac136d283bec884fde94b0d\",\n ],\n};\n\nconst DISABLED_TOOLS = [\n \"start_codex_security_standard_scan\",\n \"start_codex_security_prompt_only_scan\",\n \"start_codex_security_deep_scan\",\n \"complete_codex_security_scan\",\n \"record_codex_security_candidate_validations\",\n \"record_candidate_attack_paths\",\n];\n\nconst HANDOFF =\n \"Preserve every surviving source-backed candidate as a provisional finding, including its identity, source locations, evidence, counterevidence, and preliminary assessments. Assemble unsealed scan-manifest.json and findings.json using <plugin_dir>/examples/completed-scan/ and <plugin_dir>/schemas/ as shape references. Put candidate dispositions and pending work in scan.reviewState. Set scan.scope.validationMode to custom_pending and put each finding's matching review-state surface IDs in extensions.customValidationSurfaceIds. Every reported review-state surface must have a candidate. When source discovery finishes and a bound semantic draft tool is available, submit an accepted final source-discovery draft with complete: true, preserving the provisional findings, reviewState, threat model, and custom_pending validation mode. This marks source discovery finished; it does not claim custom validation has occurred or seal the scan. Keep complete: false when requested source review remains unfinished. Verify both files exist, then return control to the SDK without invoking validation or attack-path skills, running application code, sealing files, generating a report, or calling a scan completion tool or helper.\";\n\nasync function source(pluginRoot: string, name: keyof typeof SOURCES) {\n const text = (await readFile(join(pluginRoot, name), \"utf8\")).replaceAll(\n \"\\r\\n\",\n \"\\n\",\n );\n const digest = createHash(\"sha256\").update(text).digest(\"hex\");\n if (!SOURCES[name].includes(digest)) {\n throw new IncompleteScanError(\n `Custom validation is incompatible with the installed plugin workflow (${name}). Update the SDK and plugin together. Default validation was not started.`,\n );\n }\n return text;\n}\n\nfunction step(text: string, number: number): string {\n return text.match(new RegExp(`^${number}\\\\. (.+)$`, \"m\"))![1]!;\n}\n\nexport async function customDiscoveryPrompt(\n pluginRoot: string,\n skillName: string,\n): Promise<string> {\n let workflow: string;\n if (skillName === \"security-scan\") {\n const [skill, core] = await Promise.all([\n source(pluginRoot, \"skills/security-scan/SKILL.md\"),\n source(pluginRoot, \"references/core-scan.md\"),\n ]);\n const discovery = core\n .replace(\n /^7\\. .+$/m,\n \"7. Retain the combined source-backed candidates and their existing evidence. The SDK will run independent final validation in a separate turn.\",\n )\n .replace(\n /^Keep discovery, validation, and attack-path reasoning.+$/m,\n \"Keep source-evidence and counterevidence checks within discovery. Do not run an independent final validation pass or invoke separate phase skills.\",\n )\n .replace(\n \"reconcile their evidence and submit the result;\",\n \"reconcile their evidence and preserve provisional candidates through the SDK-owned discovery handoff;\",\n );\n workflow = [\n skill.slice(\n skill.indexOf(\"## Host And Setup\"),\n skill.indexOf(\"## Workflow\"),\n ),\n \"## Discovery workflow\",\n `1. ${step(skill, 1)}`,\n \"2. Perform the embedded core discovery workflow below. Do not reload the ordinary core-scan.md or top-level security-scan skill.\",\n `3. ${step(skill, 3).slice(step(skill, 3).indexOf(\"For an SDK-owned scan with a bound semantic draft tool,\"))}`,\n `4. ${HANDOFF}`,\n \"## Embedded core discovery workflow\",\n discovery,\n ].join(\"\\n\\n\");\n } else if (skillName === \"security-diff-scan\") {\n const skill = await source(\n pluginRoot,\n \"skills/security-diff-scan/SKILL.md\",\n );\n workflow = [\n skill.slice(skill.indexOf(\"## Setup\"), skill.indexOf(\"\\n4. \")),\n `4. ${HANDOFF} Use diff for scan.mode.`,\n ].join(\"\\n\\n\");\n } else {\n throw new IncompleteScanError(\n \"Custom validation is not supported for this scan workflow.\",\n );\n }\n return [\n \"Follow this SDK-owned discovery workflow, derived from the installed plugin. It replaces the ordinary top-level scan skill for this turn. The SDK owns the separate custom validation pass and all completion. <plugin_dir> is CODEX_SECURITY_PLUGIN_ROOT; other bare reference filenames are relative to its references directory.\",\n workflow.replaceAll(\"../../references/\", \"<plugin_dir>/references/\"),\n ].join(\"\\n\\n\");\n}\n\nexport async function customValidationConfig(\n config: JsonObject,\n pluginRoot: string,\n): Promise<JsonObject> {\n config = resolveCodexProfile(config);\n const manifest = JSON.parse(\n await readFile(join(pluginRoot, \".mcp.json\"), \"utf8\"),\n );\n const server = manifest.mcpServers[PLUGIN_NAME];\n const servers = (config[\"mcp_servers\"] ?? {}) as JsonObject;\n const configured = (servers[PLUGIN_NAME] ?? {}) as JsonObject;\n // The pinned Codex applies this per-invocation server entry ahead of the\n // installed plugin. Plugin-specific command-line policy overrides do not.\n return {\n ...config,\n mcp_servers: {\n ...servers,\n [PLUGIN_NAME]: {\n ...server,\n ...configured,\n cwd: resolve(\n pluginRoot,\n (configured[\"cwd\"] as string | undefined) ?? server.cwd ?? \".\",\n ),\n disabled_tools: [\n ...new Set([\n ...(server.disabled_tools ?? []),\n ...((configured[\"disabled_tools\"] ?? []) as string[]),\n ...DISABLED_TOOLS,\n ]),\n ],\n },\n },\n };\n}\n"]}
1
+ {"version":3,"file":"custom-validation-prompt.js","sourceRoot":"","sources":["../src/custom-validation-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAmB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,4EAA4E;AAC5E,q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,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAc;wBACrD,GAAG,cAAc;qBAClB,CAAC;iBACH;aACF;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { resolveCodexProfile, type JsonObject } from \"./config.js\";\nimport { IncompleteScanError } from \"./errors.js\";\nimport { PLUGIN_NAME } from \"./runtime.js\";\n\n// Review this adapter when the bundled workflows change. Never silently run\n// the ordinary validation sequence with a custom-validation request.\nconst SOURCES = {\n \"references/core-scan.md\": [\n \"07abac7382a66338bfbe3def9a0e89e715a89561332c88ccb4477f97b6e84fe5\",\n \"0e301a70d9f20acbb797f5eafcac84c09dd0513991714812d5c4f7b1f64a4a89\",\n \"7690b6c854de07ff15984f6d2c25ddfa1f6ae65f65876cadf2f904054b4f0679\",\n \"83bafdc4089803e631eaaa86ec57167c7da3f51794514d0dcdb62c5afdced8a7\",\n \"848eb40d42b0bf9cf21748b9927d031b0461a4443f63e3954139f9801f41c3f6\",\n ],\n \"skills/security-scan/SKILL.md\": [\n \"b6a69658d48fff6979d6690e95d2096da236bb7e51b96ebb4f92102a9863d66c\",\n \"99cfcbbaa9d5b0450881ec752a116888b05b7fe21ea7af28fd22d088882dcd46\",\n ],\n \"skills/security-diff-scan/SKILL.md\": [\n \"09232fd5d96cfed2a5bdccd176c09b7e9ca53ebd7ac136d283bec884fde94b0d\",\n ],\n};\n\nconst DISABLED_TOOLS = [\n \"start_codex_security_standard_scan\",\n \"start_codex_security_prompt_only_scan\",\n \"start_codex_security_deep_scan\",\n \"complete_codex_security_scan\",\n \"record_codex_security_candidate_validations\",\n \"record_candidate_attack_paths\",\n];\n\nconst HANDOFF =\n \"Preserve every surviving source-backed candidate as a provisional finding, including its identity, source locations, evidence, counterevidence, and preliminary assessments. Assemble unsealed scan-manifest.json and findings.json using <plugin_dir>/examples/completed-scan/ and <plugin_dir>/schemas/ as shape references. Put candidate dispositions and pending work in scan.reviewState. Set scan.scope.validationMode to custom_pending and put each finding's matching review-state surface IDs in extensions.customValidationSurfaceIds. Every reported review-state surface must have a candidate. When source discovery finishes and a bound semantic draft tool is available, submit an accepted final source-discovery draft with complete: true, preserving the provisional findings, reviewState, threat model, and custom_pending validation mode. This marks source discovery finished; it does not claim custom validation has occurred or seal the scan. Keep complete: false when requested source review remains unfinished. Verify both files exist, then return control to the SDK without invoking validation or attack-path skills, running application code, sealing files, generating a report, or calling a scan completion tool or helper.\";\n\nasync function source(pluginRoot: string, name: keyof typeof SOURCES) {\n const text = (await readFile(join(pluginRoot, name), \"utf8\")).replaceAll(\n \"\\r\\n\",\n \"\\n\",\n );\n const digest = createHash(\"sha256\").update(text).digest(\"hex\");\n if (!SOURCES[name].includes(digest)) {\n throw new IncompleteScanError(\n `Custom validation is incompatible with the installed plugin workflow (${name}). Update the SDK and plugin together. Default validation was not started.`,\n );\n }\n return text;\n}\n\nfunction step(text: string, number: number): string {\n return text.match(new RegExp(`^${number}\\\\. (.+)$`, \"m\"))![1]!;\n}\n\nasync function legacyDiscoveryPrompt(pluginRoot: string) {\n const [skill, core] = await Promise.all([\n source(pluginRoot, \"skills/security-scan/SKILL.md\"),\n source(pluginRoot, \"references/core-scan.md\"),\n ]);\n const discovery = core\n .replace(\n /^7\\. .+$/m,\n \"7. Retain the combined source-backed candidates and their existing evidence. The SDK will run independent final validation in a separate turn.\",\n )\n .replace(\n /^Keep discovery, validation, and attack-path reasoning.+$/m,\n \"Keep source-evidence and counterevidence checks within discovery. Do not run an independent final validation pass or invoke separate phase skills.\",\n )\n .replace(\n \"reconcile their evidence and submit the result;\",\n \"reconcile their evidence and preserve provisional candidates through the SDK-owned discovery handoff;\",\n );\n return [\n skill.slice(\n skill.indexOf(\"## Host And Setup\"),\n skill.indexOf(\"## Workflow\"),\n ),\n \"## Discovery workflow\",\n `1. ${step(skill, 1)}`,\n \"2. Perform the embedded core discovery workflow below. Do not reload the ordinary core-scan.md or top-level security-scan skill.\",\n `3. ${step(skill, 3).slice(step(skill, 3).indexOf(\"For an SDK-owned scan with a bound semantic draft tool,\"))}`,\n `4. ${HANDOFF}`,\n \"## Embedded core discovery workflow\",\n discovery,\n ].join(\"\\n\\n\");\n}\n\nexport async function customDiscoveryPrompt(\n pluginRoot: string,\n skillName: string,\n standardHandoff: boolean,\n): Promise<string> {\n let workflow: string;\n if (skillName === \"security-scan\") {\n workflow = standardHandoff\n ? [\n \"Use <plugin_dir>/references/core-scan.md for source discovery. This caller supplies the validation handoff: the SDK runs independent final validation in a separate turn. Check source evidence and counterevidence now, but do not run the default validation pass.\",\n \"Keep any supplied investigation time allowance unchanged. Only for an explicit time request with no existing allowance, render <plugin_dir>/references/investigation-time-budget.md once before source review.\",\n HANDOFF,\n ].join(\"\\n\\n\")\n : await legacyDiscoveryPrompt(pluginRoot);\n } else if (skillName === \"security-diff-scan\") {\n const skill = await source(\n pluginRoot,\n \"skills/security-diff-scan/SKILL.md\",\n );\n workflow = [\n skill.slice(skill.indexOf(\"## Setup\"), skill.indexOf(\"\\n4. \")),\n `4. ${HANDOFF} Use diff for scan.mode.`,\n ].join(\"\\n\\n\");\n } else {\n throw new IncompleteScanError(\n \"Custom validation is not supported for this scan workflow.\",\n );\n }\n return [\n \"Follow this SDK-owned discovery workflow, derived from the installed plugin. It replaces the ordinary top-level scan skill for this turn. The SDK owns the separate custom validation pass and all completion. <plugin_dir> is CODEX_SECURITY_PLUGIN_ROOT; other bare reference filenames are relative to its references directory.\",\n workflow.replaceAll(\"../../references/\", \"<plugin_dir>/references/\"),\n ].join(\"\\n\\n\");\n}\n\nexport async function customValidationConfig(\n config: JsonObject,\n pluginRoot: string,\n): Promise<JsonObject> {\n config = resolveCodexProfile(config);\n const manifest = JSON.parse(\n await readFile(join(pluginRoot, \".mcp.json\"), \"utf8\"),\n );\n const server = manifest.mcpServers[PLUGIN_NAME];\n const servers = (config[\"mcp_servers\"] ?? {}) as JsonObject;\n const configured = (servers[PLUGIN_NAME] ?? {}) as JsonObject;\n // The pinned Codex applies this per-invocation server entry ahead of the\n // installed plugin. Plugin-specific command-line policy overrides do not.\n return {\n ...config,\n mcp_servers: {\n ...servers,\n [PLUGIN_NAME]: {\n ...server,\n ...configured,\n cwd: resolve(\n pluginRoot,\n (configured[\"cwd\"] as string | undefined) ?? server.cwd ?? \".\",\n ),\n disabled_tools: [\n ...new Set([\n ...(server.disabled_tools ?? []),\n ...((configured[\"disabled_tools\"] ?? []) as string[]),\n ...DISABLED_TOOLS,\n ]),\n ],\n },\n },\n };\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { Finding } from "../models.js";
2
2
  import type { FindingNeighborhood, FindingSearchScope } from "../finding-retrieval.js";
3
+ import type { SavedToolDiscovery } from "../saved-scan-bootstrap.js";
3
4
  import { runWorkbench } from "../runtime.js";
4
5
  import { type FindingEmbedder, type EmbeddingUsageObserver } from "../server/embeddings.js";
5
6
  /** One vector space and the adapter that produces its embeddings. */
@@ -17,11 +18,12 @@ export declare class LocalDeduplication {
17
18
  private readonly repositoryPath;
18
19
  private readonly signal?;
19
20
  private readonly workbench;
21
+ private readonly nodeDiscovery?;
20
22
  private options?;
21
23
  private cacheKeys;
22
24
  private readonly space;
23
25
  private readonly embedding;
24
- constructor(environment: NodeJS.ProcessEnv, scope: FindingSearchScope, repositoryPath: string, signal?: AbortSignal | undefined, workbench?: typeof runWorkbench, embedding?: FindingEmbeddingBinding, onEmbeddingUsage?: EmbeddingUsageObserver);
26
+ constructor(environment: NodeJS.ProcessEnv, scope: FindingSearchScope, repositoryPath: string, signal?: AbortSignal | undefined, workbench?: typeof runWorkbench, embedding?: FindingEmbeddingBinding, onEmbeddingUsage?: EmbeddingUsageObserver, nodeDiscovery?: SavedToolDiscovery | undefined);
25
27
  get inputDigest(): string;
26
28
  prepare(findings: readonly Finding[], repositoryId: string): Promise<void>;
27
29
  potentialDuplicates(findingId: string): Promise<FindingNeighborhood>;
@@ -1 +1 @@
1
- {"version":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AmD;IACnE,OAAO,CAAC,SAAS,CAA8B;IAC/C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0B;IAEpD,YACmB,WAAW,EAAE,MAAM,CAAC,UAAU,EAC9B,KAAK,EAAE,kBAAkB,EACzB,cAAc,EAAE,MAAM,EACtB,MAAM,CAAC,EAAE,WAAW,YAAA,EACpB,SAAS,GAAE,OAAO,YAA2B,EAC9D,SAAS,CAAC,EAAE,uBAAuB,EACnC,gBAAgB,CAAC,EAAE,sBAAsB,EACxB,aAAa,CAAC,EAAE,kBAAkB,YAAA,EA2BpD;IAED,IAAI,WAAW,IAAI,MAAM,CAExB;IAEK,OAAO,CACX,QAAQ,EAAE,SAAS,OAAO,EAAE,EAC5B,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAqCf;IAEK,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAMzE;IAEK,iBAAiB,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAElE;YAEa,OAAO;CA6DtB"}
@@ -14,16 +14,18 @@ export class LocalDeduplication {
14
14
  repositoryPath;
15
15
  signal;
16
16
  workbench;
17
+ nodeDiscovery;
17
18
  options;
18
19
  cacheKeys = {};
19
20
  space;
20
21
  embedding;
21
- constructor(environment, scope, repositoryPath, signal, workbench = runWorkbench, embedding, onEmbeddingUsage) {
22
+ constructor(environment, scope, repositoryPath, signal, workbench = runWorkbench, embedding, onEmbeddingUsage, nodeDiscovery) {
22
23
  this.environment = environment;
23
24
  this.scope = scope;
24
25
  this.repositoryPath = repositoryPath;
25
26
  this.signal = signal;
26
27
  this.workbench = workbench;
28
+ this.nodeDiscovery = nodeDiscovery;
27
29
  const endpoint = environmentEntry(environment, "CODEX_SECURITY_EMBEDDINGS_URL") ||
28
30
  EMBEDDINGS_URL;
29
31
  this.embedding = embedding ?? {
@@ -88,6 +90,10 @@ export class LocalDeduplication {
88
90
  async command(payload) {
89
91
  this.signal?.throwIfAborted();
90
92
  this.options ??= (async () => {
93
+ // Bun finds Node on PATH. Native Node helpers use the running process executable.
94
+ if (process.versions["bun"] &&
95
+ this.nodeDiscovery?.allowPathLookup === false)
96
+ throw new CodexSecurityError("Could not establish the saved checkout boundary for Node.js discovery. Run local deduplication with Node.js.");
91
97
  const environment = workbenchEnvironment(this.environment);
92
98
  return {
93
99
  pluginRoot: await bundledPluginRoot(),
@@ -95,6 +101,7 @@ export class LocalDeduplication {
95
101
  environment,
96
102
  signal: this.signal,
97
103
  protectedRoot: [
104
+ ...(this.nodeDiscovery?.protectedRoots ?? []),
98
105
  this.repositoryPath,
99
106
  ...(await gitProtectionRoots(this.repositoryPath, this.signal)),
100
107
  ...(await gitProtectionRoots(process.cwd(), this.signal)),
@@ -1 +1 @@
1
- {"version":3,"file":"local.js","sourceRoot":"","sources":["../../src/deduplication/local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAM9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,YAAY,GAEb,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,oBAAoB,EACpB,cAAc,GAGf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEtD,8FAA8F;AAC9F,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAWhC,2EAA2E;AAC3E,MAAM,OAAO,kBAAkB;IAOV,WAAW;IACX,KAAK;IACL,cAAc;IACd,MAAM;IACN,SAAS;IA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,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACxC,IACE,OAAO,KAAK,CAAC;gBACb,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;gBAEzD,OAAO,QAAQ,CAAC;YAClB,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;YACvD,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;gBACxB,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;gBACnC,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;oBACtC,CAAC,CAAC,OAAO,GAAG,IAAI;oBAChB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;gBACxC,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;oBAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACjE,CAAC;YACD,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;YAC9B,IAAI,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,SAAS,CAAC;gBAAE,MAAM,KAAK,CAAC;QAClE,CAAC;QACD,MAAM,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,IAAI,SAAS,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { environmentEntry } from \"../auth.js\";\nimport { abortable, gitProtectionRoots } from \"../targets.js\";\nimport type { Finding } from \"../models.js\";\nimport type {\n FindingNeighborhood,\n FindingSearchScope,\n} from \"../finding-retrieval.js\";\nimport { CodexSecurityError } from \"../errors.js\";\nimport { workflowDigest } from \"../finding-workflow.js\";\nimport {\n bundledPluginRoot,\n workbenchEnvironment,\n runWorkbench,\n type WorkbenchCommandOptions,\n} from \"../runtime.js\";\nimport {\n OpenAiFindingEmbedder,\n EMBEDDING_MODEL,\n EMBEDDING_DIMENSIONS,\n EMBEDDINGS_URL,\n type FindingEmbedder,\n type EmbeddingUsageObserver,\n} from \"../server/embeddings.js\";\nimport { retryDelay, waitForRetry } from \"./retry.js\";\n\n// Checkpoint bounded batches so a retry keeps completed work without one process per finding.\nconst EMBEDDING_BATCH_SIZE = 64;\n\n/** One vector space and the adapter that produces its embeddings. */\nexport interface FindingEmbeddingBinding {\n readonly embedder: FindingEmbedder;\n readonly model: string;\n readonly dimensions: number;\n /** Identifies the provider/vector space and preprocessing version; exclude credentials. */\n readonly cacheNamespace: string;\n}\n\n/** Direct workbench adapter. Importing it starts no HTTP or MCP server. */\nexport class LocalDeduplication {\n private options?: Promise<Omit<WorkbenchCommandOptions, \"python\">>;\n private cacheKeys: Record<string, string> = {};\n private readonly space: string;\n private readonly embedding: FindingEmbeddingBinding;\n\n constructor(\n private readonly environment: NodeJS.ProcessEnv,\n private readonly scope: FindingSearchScope,\n private readonly repositoryPath: string,\n private readonly signal?: AbortSignal,\n private readonly workbench: typeof runWorkbench = runWorkbench,\n embedding?: FindingEmbeddingBinding,\n onEmbeddingUsage?: EmbeddingUsageObserver,\n ) {\n const endpoint =\n environmentEntry(environment, \"CODEX_SECURITY_EMBEDDINGS_URL\") ||\n EMBEDDINGS_URL;\n this.embedding = embedding ?? {\n model: EMBEDDING_MODEL,\n dimensions: EMBEDDING_DIMENSIONS,\n cacheNamespace: endpoint,\n embedder: new OpenAiFindingEmbedder(\n [\n environmentEntry(environment, \"OPENAI_API_KEY\"),\n environmentEntry(environment, \"CODEX_API_KEY\"),\n ].find((value) => value?.trim()),\n embeddingRequest,\n endpoint,\n signal,\n onEmbeddingUsage,\n ),\n };\n // The digest keeps endpoint/namespace details out of persisted cache keys.\n this.space = workflowDigest({\n version: 1,\n model: this.embedding.model,\n dimensions: this.embedding.dimensions,\n namespace: this.embedding.cacheNamespace,\n });\n }\n\n get inputDigest(): string {\n return workflowDigest(this.cacheKeys);\n }\n\n async prepare(\n findings: readonly Finding[],\n repositoryId: string,\n ): Promise<void> {\n const result = await this.command({\n action: \"prepare\",\n findings,\n anchorRepositoryId: repositoryId,\n repositoryPath: this.repositoryPath,\n });\n this.cacheKeys = result[\"cacheKeys\"] as Record<string, string>;\n const findingsToEmbed = result[\"findingsToEmbed\"] as unknown as Finding[];\n for (\n let offset = 0;\n offset < findingsToEmbed.length;\n offset += EMBEDDING_BATCH_SIZE\n ) {\n this.signal?.throwIfAborted();\n const batch = findingsToEmbed.slice(\n offset,\n offset + EMBEDDING_BATCH_SIZE,\n );\n const embeddings = await abortable(() => {\n this.signal?.throwIfAborted();\n return this.embedding.embedder.embed(batch);\n }, this.signal);\n this.signal?.throwIfAborted();\n if (embeddings.length !== batch.length)\n throw new CodexSecurityError(\n \"Embedding provider returned an invalid number of vectors.\",\n );\n await this.command({\n action: \"embed\",\n entries: batch.map((finding, index) => ({\n findingId: finding.findingId,\n cacheKey: this.cacheKeys[finding.findingId],\n embedding: embeddings[index],\n })),\n });\n }\n }\n\n async potentialDuplicates(findingId: string): Promise<FindingNeighborhood> {\n return (await this.command({\n action: \"neighbors\",\n findingId,\n cacheKeys: this.cacheKeys,\n })) as unknown as FindingNeighborhood;\n }\n\n async storeDedupeGroups(groups: readonly string[][]): Promise<void> {\n await this.command({ action: \"commit\", groups, cacheKeys: this.cacheKeys });\n }\n\n private async command(payload: { action: string; [key: string]: unknown }) {\n this.signal?.throwIfAborted();\n this.options ??= (async () => {\n const environment = workbenchEnvironment(this.environment);\n return {\n pluginRoot: await bundledPluginRoot(),\n stateDirectory: environment.CODEX_SECURITY_STATE_DIR,\n environment,\n signal: this.signal,\n protectedRoot: [\n this.repositoryPath,\n ...(await gitProtectionRoots(this.repositoryPath, this.signal)),\n ...(await gitProtectionRoots(process.cwd(), this.signal)),\n ],\n failureMessage: \"Could not access local deduplication state\",\n };\n })();\n const result = await this.workbench(\n await this.options,\n [\n payload.action === \"neighbors\"\n ? \"find-potential-duplicates\"\n : payload.action === \"commit\"\n ? \"store-dedupe-groups\"\n : \"local-dedupe\",\n ],\n JSON.stringify({\n ...payload,\n scope: this.scope,\n space: this.space,\n model: this.embedding.model,\n dimensions: this.embedding.dimensions,\n ...(this.scope.allRepositories\n ? {}\n : { repositoryId: this.scope.repositoryId }),\n }),\n );\n this.signal?.throwIfAborted();\n const code = result[\"error\"];\n if (code !== undefined) {\n const message =\n code === \"finding_changed\"\n ? \"Findings changed during local deduplication. Retry with a new workflow ID if resuming.\"\n : code === \"target_mismatch\"\n ? \"The scan target does not match the approved local checkout. Use its original checkout or an explicitly configured findings service.\"\n : code === \"finding_not_indexed\"\n ? \"A local finding has no complete document. Reimport its scan before deduplicating.\"\n : `Local deduplication failed: ${String(code)}.`;\n throw new CodexSecurityError(message);\n }\n return result;\n }\n}\n\nasync function embeddingRequest(\n url: string,\n init: RequestInit,\n): Promise<Response> {\n for (let attempt = 1; ; attempt++) {\n init.signal?.throwIfAborted();\n let delay = retryDelay(attempt);\n try {\n const response = await fetch(url, init);\n if (\n attempt === 3 ||\n ![408, 429, 500, 502, 503, 504].includes(response.status)\n )\n return response;\n const retryAfter = response.headers.get(\"Retry-After\");\n if (retryAfter !== null) {\n const seconds = Number(retryAfter);\n const retryAt = Number.isFinite(seconds)\n ? seconds * 1000\n : Date.parse(retryAfter) - Date.now();\n if (Number.isFinite(retryAt)) delay = Math.max(delay, retryAt);\n }\n await response.body?.cancel().catch(() => undefined);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (attempt === 3 || !(error instanceof TypeError)) throw error;\n }\n await waitForRetry(delay, init.signal ?? undefined);\n }\n}\n"]}
1
+ {"version":3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Aa,CAAC,CAAC;YACvD,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;gBACxB,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;gBACnC,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;oBACtC,CAAC,CAAC,OAAO,GAAG,IAAI;oBAChB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;gBACxC,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;oBAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACjE,CAAC;YACD,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;YAC9B,IAAI,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,SAAS,CAAC;gBAAE,MAAM,KAAK,CAAC;QAClE,CAAC;QACD,MAAM,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,IAAI,SAAS,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { environmentEntry } from \"../auth.js\";\nimport { abortable, gitProtectionRoots } from \"../targets.js\";\nimport type { Finding } from \"../models.js\";\nimport type {\n FindingNeighborhood,\n FindingSearchScope,\n} from \"../finding-retrieval.js\";\nimport { CodexSecurityError } from \"../errors.js\";\nimport type { SavedToolDiscovery } from \"../saved-scan-bootstrap.js\";\nimport { workflowDigest } from \"../finding-workflow.js\";\nimport {\n bundledPluginRoot,\n workbenchEnvironment,\n runWorkbench,\n type WorkbenchCommandOptions,\n} from \"../runtime.js\";\nimport {\n OpenAiFindingEmbedder,\n EMBEDDING_MODEL,\n EMBEDDING_DIMENSIONS,\n EMBEDDINGS_URL,\n type FindingEmbedder,\n type EmbeddingUsageObserver,\n} from \"../server/embeddings.js\";\nimport { retryDelay, waitForRetry } from \"./retry.js\";\n\n// Checkpoint bounded batches so a retry keeps completed work without one process per finding.\nconst EMBEDDING_BATCH_SIZE = 64;\n\n/** One vector space and the adapter that produces its embeddings. */\nexport interface FindingEmbeddingBinding {\n readonly embedder: FindingEmbedder;\n readonly model: string;\n readonly dimensions: number;\n /** Identifies the provider/vector space and preprocessing version; exclude credentials. */\n readonly cacheNamespace: string;\n}\n\n/** Direct workbench adapter. Importing it starts no HTTP or MCP server. */\nexport class LocalDeduplication {\n private options?: Promise<Omit<WorkbenchCommandOptions, \"python\">>;\n private cacheKeys: Record<string, string> = {};\n private readonly space: string;\n private readonly embedding: FindingEmbeddingBinding;\n\n constructor(\n private readonly environment: NodeJS.ProcessEnv,\n private readonly scope: FindingSearchScope,\n private readonly repositoryPath: string,\n private readonly signal?: AbortSignal,\n private readonly workbench: typeof runWorkbench = runWorkbench,\n embedding?: FindingEmbeddingBinding,\n onEmbeddingUsage?: EmbeddingUsageObserver,\n private readonly nodeDiscovery?: SavedToolDiscovery,\n ) {\n const endpoint =\n environmentEntry(environment, \"CODEX_SECURITY_EMBEDDINGS_URL\") ||\n EMBEDDINGS_URL;\n this.embedding = embedding ?? {\n model: EMBEDDING_MODEL,\n dimensions: EMBEDDING_DIMENSIONS,\n cacheNamespace: endpoint,\n embedder: new OpenAiFindingEmbedder(\n [\n environmentEntry(environment, \"OPENAI_API_KEY\"),\n environmentEntry(environment, \"CODEX_API_KEY\"),\n ].find((value) => value?.trim()),\n embeddingRequest,\n endpoint,\n signal,\n onEmbeddingUsage,\n ),\n };\n // The digest keeps endpoint/namespace details out of persisted cache keys.\n this.space = workflowDigest({\n version: 1,\n model: this.embedding.model,\n dimensions: this.embedding.dimensions,\n namespace: this.embedding.cacheNamespace,\n });\n }\n\n get inputDigest(): string {\n return workflowDigest(this.cacheKeys);\n }\n\n async prepare(\n findings: readonly Finding[],\n repositoryId: string,\n ): Promise<void> {\n const result = await this.command({\n action: \"prepare\",\n findings,\n anchorRepositoryId: repositoryId,\n repositoryPath: this.repositoryPath,\n });\n this.cacheKeys = result[\"cacheKeys\"] as Record<string, string>;\n const findingsToEmbed = result[\"findingsToEmbed\"] as unknown as Finding[];\n for (\n let offset = 0;\n offset < findingsToEmbed.length;\n offset += EMBEDDING_BATCH_SIZE\n ) {\n this.signal?.throwIfAborted();\n const batch = findingsToEmbed.slice(\n offset,\n offset + EMBEDDING_BATCH_SIZE,\n );\n const embeddings = await abortable(() => {\n this.signal?.throwIfAborted();\n return this.embedding.embedder.embed(batch);\n }, this.signal);\n this.signal?.throwIfAborted();\n if (embeddings.length !== batch.length)\n throw new CodexSecurityError(\n \"Embedding provider returned an invalid number of vectors.\",\n );\n await this.command({\n action: \"embed\",\n entries: batch.map((finding, index) => ({\n findingId: finding.findingId,\n cacheKey: this.cacheKeys[finding.findingId],\n embedding: embeddings[index],\n })),\n });\n }\n }\n\n async potentialDuplicates(findingId: string): Promise<FindingNeighborhood> {\n return (await this.command({\n action: \"neighbors\",\n findingId,\n cacheKeys: this.cacheKeys,\n })) as unknown as FindingNeighborhood;\n }\n\n async storeDedupeGroups(groups: readonly string[][]): Promise<void> {\n await this.command({ action: \"commit\", groups, cacheKeys: this.cacheKeys });\n }\n\n private async command(payload: { action: string; [key: string]: unknown }) {\n this.signal?.throwIfAborted();\n this.options ??= (async () => {\n // Bun finds Node on PATH. Native Node helpers use the running process executable.\n if (\n process.versions[\"bun\"] &&\n this.nodeDiscovery?.allowPathLookup === false\n )\n throw new CodexSecurityError(\n \"Could not establish the saved checkout boundary for Node.js discovery. Run local deduplication with Node.js.\",\n );\n const environment = workbenchEnvironment(this.environment);\n return {\n pluginRoot: await bundledPluginRoot(),\n stateDirectory: environment.CODEX_SECURITY_STATE_DIR,\n environment,\n signal: this.signal,\n protectedRoot: [\n ...(this.nodeDiscovery?.protectedRoots ?? []),\n this.repositoryPath,\n ...(await gitProtectionRoots(this.repositoryPath, this.signal)),\n ...(await gitProtectionRoots(process.cwd(), this.signal)),\n ],\n failureMessage: \"Could not access local deduplication state\",\n };\n })();\n const result = await this.workbench(\n await this.options,\n [\n payload.action === \"neighbors\"\n ? \"find-potential-duplicates\"\n : payload.action === \"commit\"\n ? \"store-dedupe-groups\"\n : \"local-dedupe\",\n ],\n JSON.stringify({\n ...payload,\n scope: this.scope,\n space: this.space,\n model: this.embedding.model,\n dimensions: this.embedding.dimensions,\n ...(this.scope.allRepositories\n ? {}\n : { repositoryId: this.scope.repositoryId }),\n }),\n );\n this.signal?.throwIfAborted();\n const code = result[\"error\"];\n if (code !== undefined) {\n const message =\n code === \"finding_changed\"\n ? \"Findings changed during local deduplication. Retry with a new workflow ID if resuming.\"\n : code === \"target_mismatch\"\n ? \"The scan target does not match the approved local checkout. Use its original checkout or an explicitly configured findings service.\"\n : code === \"finding_not_indexed\"\n ? \"A local finding has no complete document. Reimport its scan before deduplicating.\"\n : `Local deduplication failed: ${String(code)}.`;\n throw new CodexSecurityError(message);\n }\n return result;\n }\n}\n\nasync function embeddingRequest(\n url: string,\n init: RequestInit,\n): Promise<Response> {\n for (let attempt = 1; ; attempt++) {\n init.signal?.throwIfAborted();\n let delay = retryDelay(attempt);\n try {\n const response = await fetch(url, init);\n if (\n attempt === 3 ||\n ![408, 429, 500, 502, 503, 504].includes(response.status)\n )\n return response;\n const retryAfter = response.headers.get(\"Retry-After\");\n if (retryAfter !== null) {\n const seconds = Number(retryAfter);\n const retryAt = Number.isFinite(seconds)\n ? seconds * 1000\n : Date.parse(retryAfter) - Date.now();\n if (Number.isFinite(retryAt)) delay = Math.max(delay, retryAt);\n }\n await response.body?.cancel().catch(() => undefined);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (attempt === 3 || !(error instanceof TypeError)) throw error;\n }\n await waitForRetry(delay, init.signal ?? undefined);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"refusal.d.ts","sourceRoot":"","sources":["../../src/deduplication/refusal.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,cAAc,CAAC,EAAE,OAAO,GACvB,OAAO,CA0CT"}
1
+ {"version":3,"file":"refusal.d.ts","sourceRoot":"","sources":["../../src/deduplication/refusal.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,cAAc,CAAC,EAAE,OAAO,GACvB,OAAO,CA2CT"}
@@ -25,10 +25,11 @@ export function isReviewRefusal(message, codexErrorInfo) {
25
25
  /\bflagged for potentially high-risk cyber activity\b/iu,
26
26
  /\bcyber[_\s-]?policy\b/iu,
27
27
  /\b(?:cybersecurity|cyber)[ _-]*policy[ _-]*(?:violation|refusal|refused)\b/iu,
28
+ /^(?:content|safety) policy (?:violation|refusal)[.!]?$/iu,
28
29
  /(?:^(?:refusal|refused)|\b(?:request|review)\s+(?:refusal|(?:(?:is|was|has been)\s+)?(?:refused|blocked)))\s+(?:under|by|due to|because of|because (?:it|this request) violates|for violating|in accordance with)\s+(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy\b/iu,
29
30
  /^(?:(?:this|the|your)\s+)?(?:request|review)(?:\s+(?:is|was|has been))?\s+(?:refusal|refused|blocked)\s*:\s*(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy(?:[.!](?:\s+(?:I can offer|Please ask)\b[^\n]*)?)?$/iu,
30
- /^(?:cybersecurity|cyber|content|safety)[ _-]*policy\s*:\s*(?:(?:(?:this|the|your)\s+)?request\s+)?(?:(?:is|was|has been)\s+)?(?:violation|refusal|refused|blocked)[.!]?$/iu,
31
31
  /\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\s+requires\s+(?:a\s+)?refusal\s+of\s+(?:(?:this|the|your)\s+)?(?:request|review)\b/iu,
32
+ /^(?:cybersecurity|cyber|content|safety)[ _-]*policy\s*:\s*(?:(?:(?:this|the|your)\s+)?(?:request|review)\s+)?(?:(?:is|was|has been)\s+)?(?:violation|refusal|refused|blocked)(?:[.!](?:\s+(?:I can offer|Please ask)\b[^\n]*)?)?$/iu,
32
33
  /\bunder\s+(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy[, :]\s*(?:this|the|your) request (?:is|was|has been) (?:refused|blocked)\b/iu,
33
34
  /^(?:I(?:['’]m| am) sorry[,.:]?\s*(?:but\s+)?|Sorry[,.:]?\s*)?I(?:\s+(?:cannot|can['’]t|won['’]t|am (?:unable|not able) to)|['’]m (?:unable|not able) to)\s+(?:help|assist|comply)\b/iu,
34
35
  ].some((pattern) => pattern.test(text));
@@ -1 +1 @@
1
- {"version":3,"file":"refusal.js","sourceRoot":"","sources":["../../src/deduplication/refusal.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,MAAM,UAAU,eAAe,CAC7B,OAAe,EACf,cAAwB;IAExB,IACE,cAAc,KAAK,aAAa;QAChC,cAAc,KAAK,6BAA6B;QAEhD,OAAO,IAAI,CAAC;IACd,+EAA+E;IAC/E,IACE,cAAc,KAAK,IAAI;QACvB,OAAO,cAAc,KAAK,QAAQ;QAClC;YACE,sBAAsB;YACtB,gCAAgC;YAChC,4BAA4B;YAC5B,+BAA+B;SAChC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAE3D,OAAO,KAAK,CAAC;IACf,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5B,MAAM,aAAa,GACjB,uKAAuK,CAAC,IAAI,CAC1K,IAAI,CACL,CAAC;IACJ,IAAI,aAAa,EAAE,CAAC;QAClB,wFAAwF;QACxF,yEAAyE;QACzE,OAAO,CAAC,+QAA+Q,CAAC,IAAI,CAC1R,aAAa,CAAC,CAAC,CAAC,IAAI,EAAE,CACvB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,+CAA+C;QAC/C,wDAAwD;QACxD,0BAA0B;QAC1B,8EAA8E;QAC9E,6RAA6R;QAC7R,uOAAuO;QACvO,4KAA4K;QAC5K,2IAA2I;QAC3I,4JAA4J;QAC5J,uLAAuL;KACxL,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/** Recognize policy blocks and explicit refusal responses, not ordinary review failures. */\nexport function isReviewRefusal(\n message: string,\n codexErrorInfo?: unknown,\n): boolean {\n if (\n codexErrorInfo === \"cyberPolicy\" ||\n codexErrorInfo === \"misalignmentPolicyViolation\"\n )\n return true;\n // Structured transport failures take precedence over fallback refusal wording.\n if (\n codexErrorInfo !== null &&\n typeof codexErrorInfo === \"object\" &&\n [\n \"httpConnectionFailed\",\n \"responseStreamConnectionFailed\",\n \"responseStreamDisconnected\",\n \"responseTooManyFailedAttempts\",\n ].some((variant) => Object.hasOwn(codexErrorInfo, variant))\n )\n return false;\n const text = message.trim();\n const policyRefusal =\n /\\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s*:\\s*(?:(?:this|the|your)\\s+)?(?:request|review)\\s+(?:(?:is|was|has been)\\s+)?(?:refused|blocked)\\b([\\s\\S]*)$/iu.exec(\n text,\n );\n if (policyRefusal) {\n // The explicit refusal predicate decides; its explanation has no controlled vocabulary.\n // A leading service-outage cause still describes an operational failure.\n return !/^\\s*(?:(?:(?:because|as|due to)\\s+|[.!:]\\s*)(?:the\\s+)?(?:upstream\\s+)?service\\s+(?:is\\s+)?(?:unavailable|unavailability|timed? out|timeout)\\b|by\\s+upstream\\s+with\\s+[45]\\d{2}\\b|(?:because|as)\\s+(?:the\\s+)?upstream(?:\\s+service)?\\s+returned\\s+(?:HTTP\\s+)?[45]\\d{2}\\b)/iu.test(\n policyRefusal[1] ?? \"\",\n );\n }\n return [\n /\\bflagged for possible cybersecurity risk\\b/iu,\n /\\bflagged for potentially high-risk cyber activity\\b/iu,\n /\\bcyber[_\\s-]?policy\\b/iu,\n /\\b(?:cybersecurity|cyber)[ _-]*policy[ _-]*(?:violation|refusal|refused)\\b/iu,\n /(?:^(?:refusal|refused)|\\b(?:request|review)\\s+(?:refusal|(?:(?:is|was|has been)\\s+)?(?:refused|blocked)))\\s+(?:under|by|due to|because of|because (?:it|this request) violates|for violating|in accordance with)\\s+(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy\\b/iu,\n /^(?:(?:this|the|your)\\s+)?(?:request|review)(?:\\s+(?:is|was|has been))?\\s+(?:refusal|refused|blocked)\\s*:\\s*(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy(?:[.!](?:\\s+(?:I can offer|Please ask)\\b[^\\n]*)?)?$/iu,\n /^(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s*:\\s*(?:(?:(?:this|the|your)\\s+)?request\\s+)?(?:(?:is|was|has been)\\s+)?(?:violation|refusal|refused|blocked)[.!]?$/iu,\n /\\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s+requires\\s+(?:a\\s+)?refusal\\s+of\\s+(?:(?:this|the|your)\\s+)?(?:request|review)\\b/iu,\n /\\bunder\\s+(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy[, :]\\s*(?:this|the|your) request (?:is|was|has been) (?:refused|blocked)\\b/iu,\n /^(?:I(?:['’]m| am) sorry[,.:]?\\s*(?:but\\s+)?|Sorry[,.:]?\\s*)?I(?:\\s+(?:cannot|can['’]t|won['’]t|am (?:unable|not able) to)|['’]m (?:unable|not able) to)\\s+(?:help|assist|comply)\\b/iu,\n ].some((pattern) => pattern.test(text));\n}\n"]}
1
+ {"version":3,"file":"refusal.js","sourceRoot":"","sources":["../../src/deduplication/refusal.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,MAAM,UAAU,eAAe,CAC7B,OAAe,EACf,cAAwB;IAExB,IACE,cAAc,KAAK,aAAa;QAChC,cAAc,KAAK,6BAA6B;QAEhD,OAAO,IAAI,CAAC;IACd,+EAA+E;IAC/E,IACE,cAAc,KAAK,IAAI;QACvB,OAAO,cAAc,KAAK,QAAQ;QAClC;YACE,sBAAsB;YACtB,gCAAgC;YAChC,4BAA4B;YAC5B,+BAA+B;SAChC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAE3D,OAAO,KAAK,CAAC;IACf,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5B,MAAM,aAAa,GACjB,uKAAuK,CAAC,IAAI,CAC1K,IAAI,CACL,CAAC;IACJ,IAAI,aAAa,EAAE,CAAC;QAClB,wFAAwF;QACxF,yEAAyE;QACzE,OAAO,CAAC,+QAA+Q,CAAC,IAAI,CAC1R,aAAa,CAAC,CAAC,CAAC,IAAI,EAAE,CACvB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,+CAA+C;QAC/C,wDAAwD;QACxD,0BAA0B;QAC1B,8EAA8E;QAC9E,0DAA0D;QAC1D,6RAA6R;QAC7R,uOAAuO;QACvO,2IAA2I;QAC3I,qOAAqO;QACrO,4JAA4J;QAC5J,uLAAuL;KACxL,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/** Recognize policy blocks and explicit refusal responses, not ordinary review failures. */\nexport function isReviewRefusal(\n message: string,\n codexErrorInfo?: unknown,\n): boolean {\n if (\n codexErrorInfo === \"cyberPolicy\" ||\n codexErrorInfo === \"misalignmentPolicyViolation\"\n )\n return true;\n // Structured transport failures take precedence over fallback refusal wording.\n if (\n codexErrorInfo !== null &&\n typeof codexErrorInfo === \"object\" &&\n [\n \"httpConnectionFailed\",\n \"responseStreamConnectionFailed\",\n \"responseStreamDisconnected\",\n \"responseTooManyFailedAttempts\",\n ].some((variant) => Object.hasOwn(codexErrorInfo, variant))\n )\n return false;\n const text = message.trim();\n const policyRefusal =\n /\\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s*:\\s*(?:(?:this|the|your)\\s+)?(?:request|review)\\s+(?:(?:is|was|has been)\\s+)?(?:refused|blocked)\\b([\\s\\S]*)$/iu.exec(\n text,\n );\n if (policyRefusal) {\n // The explicit refusal predicate decides; its explanation has no controlled vocabulary.\n // A leading service-outage cause still describes an operational failure.\n return !/^\\s*(?:(?:(?:because|as|due to)\\s+|[.!:]\\s*)(?:the\\s+)?(?:upstream\\s+)?service\\s+(?:is\\s+)?(?:unavailable|unavailability|timed? out|timeout)\\b|by\\s+upstream\\s+with\\s+[45]\\d{2}\\b|(?:because|as)\\s+(?:the\\s+)?upstream(?:\\s+service)?\\s+returned\\s+(?:HTTP\\s+)?[45]\\d{2}\\b)/iu.test(\n policyRefusal[1] ?? \"\",\n );\n }\n return [\n /\\bflagged for possible cybersecurity risk\\b/iu,\n /\\bflagged for potentially high-risk cyber activity\\b/iu,\n /\\bcyber[_\\s-]?policy\\b/iu,\n /\\b(?:cybersecurity|cyber)[ _-]*policy[ _-]*(?:violation|refusal|refused)\\b/iu,\n /^(?:content|safety) policy (?:violation|refusal)[.!]?$/iu,\n /(?:^(?:refusal|refused)|\\b(?:request|review)\\s+(?:refusal|(?:(?:is|was|has been)\\s+)?(?:refused|blocked)))\\s+(?:under|by|due to|because of|because (?:it|this request) violates|for violating|in accordance with)\\s+(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy\\b/iu,\n /^(?:(?:this|the|your)\\s+)?(?:request|review)(?:\\s+(?:is|was|has been))?\\s+(?:refusal|refused|blocked)\\s*:\\s*(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy(?:[.!](?:\\s+(?:I can offer|Please ask)\\b[^\\n]*)?)?$/iu,\n /\\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s+requires\\s+(?:a\\s+)?refusal\\s+of\\s+(?:(?:this|the|your)\\s+)?(?:request|review)\\b/iu,\n /^(?:cybersecurity|cyber|content|safety)[ _-]*policy\\s*:\\s*(?:(?:(?:this|the|your)\\s+)?(?:request|review)\\s+)?(?:(?:is|was|has been)\\s+)?(?:violation|refusal|refused|blocked)(?:[.!](?:\\s+(?:I can offer|Please ask)\\b[^\\n]*)?)?$/iu,\n /\\bunder\\s+(?:(?:the|a)\\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy[, :]\\s*(?:this|the|your) request (?:is|was|has been) (?:refused|blocked)\\b/iu,\n /^(?:I(?:['’]m| am) sorry[,.:]?\\s*(?:but\\s+)?|Sorry[,.:]?\\s*)?I(?:\\s+(?:cannot|can['’]t|won['’]t|am (?:unable|not able) to)|['’]m (?:unable|not able) to)\\s+(?:help|assist|comply)\\b/iu,\n ].some((pattern) => pattern.test(text));\n}\n"]}
@@ -27,6 +27,8 @@ export interface DeduplicateScanDirectoryOptions extends DeduplicateScanOptions
27
27
  }
28
28
  export interface DeduplicateScanResult extends DeduplicationResult {
29
29
  scanId: string;
30
+ /** One finding from this scan for each entry in uniqueFindingIds, in the same order. */
31
+ scanRepresentativeFindingIds: string[];
30
32
  }
31
33
  /** Review a saved scan against embedding candidates and persist accepted duplicate groups. */
32
34
  export declare function deduplicateScan(scanId: string, options: DeduplicateScanOptions): Promise<DeduplicateScanResult>;