@openai/codex-security 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (484) hide show
  1. package/README.md +437 -2692
  2. package/_bundled_plugin/.app.json +5 -1
  3. package/_bundled_plugin/.codex-plugin/plugin.json +4 -0
  4. package/_bundled_plugin/.mcp.json +2 -0
  5. package/_bundled_plugin/examples/completed-scan/coverage.json +0 -1
  6. package/_bundled_plugin/examples/completed-scan/report.md +28 -26
  7. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  8. package/_bundled_plugin/mcp/helpers.mjs +1 -0
  9. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +6 -213
  11. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +556 -0
  20. package/_bundled_plugin/mcp/server.mjs +1 -0
  21. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  22. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  23. package/_bundled_plugin/preflight/capability-profiles.toml +0 -13
  24. package/_bundled_plugin/references/artifact-storage.md +2 -2
  25. package/_bundled_plugin/references/config-preflight.md +0 -4
  26. package/_bundled_plugin/references/core-scan.md +21 -9
  27. package/_bundled_plugin/references/final-report.md +11 -13
  28. package/_bundled_plugin/references/finding-detail-fields.md +90 -80
  29. package/_bundled_plugin/references/sarif-adapter.md +1 -1
  30. package/_bundled_plugin/references/scan-artifacts.md +1 -2
  31. package/_bundled_plugin/references/scan-contract.md +9 -4
  32. package/_bundled_plugin/references/scan-prologue.md +12 -0
  33. package/_bundled_plugin/references/security-guidance.md +2 -2
  34. package/_bundled_plugin/references/standalone-validation.md +11 -0
  35. package/_bundled_plugin/references/threat-model.md +1 -1
  36. package/_bundled_plugin/schemas/coverage.schema.json +43 -170
  37. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +2 -24
  38. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +49 -25
  39. package/_bundled_plugin/schemas/findings.schema.json +159 -567
  40. package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +106 -119
  41. package/_bundled_plugin/schemas/scan-manifest.schema.json +78 -220
  42. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +91 -83
  43. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +35 -64
  44. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +5 -2
  45. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +6 -55
  46. package/_bundled_plugin/schemas/tools/review-items.schema.json +2 -38
  47. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +169 -294
  48. package/_bundled_plugin/scripts/codex_profile.mjs +239 -0
  49. package/_bundled_plugin/scripts/codex_session.mjs +53 -0
  50. package/_bundled_plugin/scripts/config_preflight.py +26 -62
  51. package/_bundled_plugin/scripts/deep_scan_config.py +9 -11
  52. package/_bundled_plugin/scripts/deep_scan_workbench.py +129 -150
  53. package/_bundled_plugin/scripts/finalize_scan_contract.py +321 -237
  54. package/_bundled_plugin/scripts/finding_preview.py +39 -9
  55. package/_bundled_plugin/scripts/generate_in_scope_files.py +27 -77
  56. package/_bundled_plugin/scripts/generate_rank_input.py +115 -926
  57. package/_bundled_plugin/scripts/launch_codex_security_mcp +35 -10
  58. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +5 -5
  59. package/_bundled_plugin/scripts/rank_preview.py +42 -918
  60. package/_bundled_plugin/scripts/report_projection.py +150 -183
  61. package/_bundled_plugin/scripts/snapshot_sqlite.py +6 -1
  62. package/_bundled_plugin/scripts/threat_model_projection.py +4 -7
  63. package/_bundled_plugin/scripts/validate_scan_contract.py +4 -34
  64. package/_bundled_plugin/scripts/validate_tracking_source.py +3 -13
  65. package/_bundled_plugin/scripts/windows_scan_local_files.py +48 -3
  66. package/_bundled_plugin/scripts/workbench/handoff.py +25 -50
  67. package/_bundled_plugin/scripts/workbench/runtime_toml.py +22 -0
  68. package/_bundled_plugin/scripts/workbench/storage.py +10 -6
  69. package/_bundled_plugin/scripts/workbench_cli.py +102 -184
  70. package/_bundled_plugin/scripts/workbench_db.py +463 -464
  71. package/_bundled_plugin/scripts/workbench_feedback.py +6 -3
  72. package/_bundled_plugin/scripts/workbench_finding_index.py +19 -1
  73. package/_bundled_plugin/scripts/workbench_finding_workflows.py +18 -4
  74. package/_bundled_plugin/scripts/workbench_local_dedupe.py +136 -0
  75. package/_bundled_plugin/scripts/workbench_native_indexes.py +27 -14
  76. package/_bundled_plugin/scripts/workbench_progress.py +14 -58
  77. package/_bundled_plugin/scripts/workbench_publication.py +234 -289
  78. package/_bundled_plugin/scripts/workbench_remediation.py +12 -0
  79. package/_bundled_plugin/scripts/workbench_saved_results.py +172 -49
  80. package/_bundled_plugin/scripts/workbench_scan_history.py +57 -57
  81. package/_bundled_plugin/scripts/workbench_scan_start.py +105 -41
  82. package/_bundled_plugin/scripts/workbench_scan_usage.py +194 -42
  83. package/_bundled_plugin/scripts/workbench_schema.py +37 -1151
  84. package/_bundled_plugin/scripts/workbench_source_excerpt.py +11 -1
  85. package/_bundled_plugin/scripts/workbench_target.py +430 -142
  86. package/_bundled_plugin/scripts/workbench_validation.py +31 -28
  87. package/_bundled_plugin/shared/workbench-history-repairs.json +218 -0
  88. package/_bundled_plugin/shared/workbench-migrations.json +414 -0
  89. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +15 -4
  90. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +1 -0
  91. package/_bundled_plugin/skills/cloud-findings/SKILL.md +54 -0
  92. package/_bundled_plugin/skills/cloud-findings/agents/openai.yaml +4 -0
  93. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +3 -3
  94. package/_bundled_plugin/skills/finding-discovery/SKILL.md +3 -3
  95. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +50 -20
  96. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +8 -14
  97. package/_bundled_plugin/skills/security-scan/SKILL.md +22 -7
  98. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  99. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +15 -1
  100. package/_bundled_plugin/skills/threat-model/SKILL.md +1 -1
  101. package/_bundled_plugin/skills/track-findings/SKILL.md +48 -176
  102. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +16 -24
  103. package/_bundled_plugin/skills/track-findings/references/jira.md +15 -61
  104. package/_bundled_plugin/skills/triage-finding/SKILL.md +50 -289
  105. package/_bundled_plugin/skills/triage-finding/agents/openai.yaml +2 -2
  106. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +23 -43
  107. package/_bundled_plugin/skills/triage-finding/references/triage-result-contract.md +7 -1
  108. package/bin/codex-security.mjs +9 -2
  109. package/dist/api.d.ts +63 -10
  110. package/dist/api.d.ts.map +1 -1
  111. package/dist/api.js +1015 -383
  112. package/dist/api.js.map +1 -1
  113. package/dist/artifact-export.d.ts +1 -1
  114. package/dist/artifact-export.d.ts.map +1 -1
  115. package/dist/artifact-export.js +28 -13
  116. package/dist/artifact-export.js.map +1 -1
  117. package/dist/auth.d.ts +2 -6
  118. package/dist/auth.d.ts.map +1 -1
  119. package/dist/auth.js +19 -9
  120. package/dist/auth.js.map +1 -1
  121. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  122. package/dist/bulk-scan-discovery.js +1 -0
  123. package/dist/bulk-scan-discovery.js.map +1 -1
  124. package/dist/classify-severity.d.ts +26 -9
  125. package/dist/classify-severity.d.ts.map +1 -1
  126. package/dist/classify-severity.js +13 -30
  127. package/dist/classify-severity.js.map +1 -1
  128. package/dist/cli-help.d.ts.map +1 -1
  129. package/dist/cli-help.js +17 -13
  130. package/dist/cli-help.js.map +1 -1
  131. package/dist/cli-signals.d.ts +8 -0
  132. package/dist/cli-signals.d.ts.map +1 -0
  133. package/dist/cli-signals.js +28 -0
  134. package/dist/cli-signals.js.map +1 -0
  135. package/dist/cli.d.ts +4 -3
  136. package/dist/cli.d.ts.map +1 -1
  137. package/dist/cli.js +1102 -905
  138. package/dist/cli.js.map +1 -1
  139. package/dist/cloud-publish.d.ts.map +1 -1
  140. package/dist/cloud-publish.js +10 -9
  141. package/dist/cloud-publish.js.map +1 -1
  142. package/dist/codeowners.d.ts +19 -0
  143. package/dist/codeowners.d.ts.map +1 -0
  144. package/dist/codeowners.js +138 -0
  145. package/dist/codeowners.js.map +1 -0
  146. package/dist/codex-sdk-environment.d.ts +1 -0
  147. package/dist/codex-sdk-environment.d.ts.map +1 -1
  148. package/dist/codex-sdk-environment.js +40 -2
  149. package/dist/codex-sdk-environment.js.map +1 -1
  150. package/dist/component-plan.d.ts +2 -5
  151. package/dist/component-plan.d.ts.map +1 -1
  152. package/dist/component-plan.js +39 -31
  153. package/dist/component-plan.js.map +1 -1
  154. package/dist/component-scan.d.ts +6 -5
  155. package/dist/component-scan.d.ts.map +1 -1
  156. package/dist/component-scan.js +25 -36
  157. package/dist/component-scan.js.map +1 -1
  158. package/dist/config.d.ts.map +1 -1
  159. package/dist/config.js +64 -74
  160. package/dist/config.js.map +1 -1
  161. package/dist/contract.d.ts +16 -3
  162. package/dist/contract.d.ts.map +1 -1
  163. package/dist/contract.js +91 -255
  164. package/dist/contract.js.map +1 -1
  165. package/dist/cost-model.d.ts +13 -6
  166. package/dist/cost-model.d.ts.map +1 -1
  167. package/dist/cost-model.js +14 -4
  168. package/dist/cost-model.js.map +1 -1
  169. package/dist/cost.d.ts +10 -2
  170. package/dist/cost.d.ts.map +1 -1
  171. package/dist/cost.js +102 -104
  172. package/dist/cost.js.map +1 -1
  173. package/dist/custom-validation-prompt.d.ts.map +1 -1
  174. package/dist/custom-validation-prompt.js +6 -5
  175. package/dist/custom-validation-prompt.js.map +1 -1
  176. package/dist/custom-validation.d.ts +1 -2
  177. package/dist/custom-validation.d.ts.map +1 -1
  178. package/dist/custom-validation.js +9 -3
  179. package/dist/custom-validation.js.map +1 -1
  180. package/dist/deduplication/checkpointed-review.d.ts +4 -2
  181. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  182. package/dist/deduplication/checkpointed-review.js +23 -9
  183. package/dist/deduplication/checkpointed-review.js.map +1 -1
  184. package/dist/deduplication/codex-review.d.ts +8 -6
  185. package/dist/deduplication/codex-review.d.ts.map +1 -1
  186. package/dist/deduplication/codex-review.js +128 -19
  187. package/dist/deduplication/codex-review.js.map +1 -1
  188. package/dist/deduplication/deduplication-prompts.d.ts +5 -2
  189. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  190. package/dist/deduplication/deduplication-prompts.js +18 -4
  191. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  192. package/dist/deduplication/deduplication-reviewer.d.ts +27 -5
  193. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  194. package/dist/deduplication/deduplication-reviewer.js +58 -48
  195. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  196. package/dist/deduplication/deduplication.d.ts.map +1 -1
  197. package/dist/deduplication/deduplication.js +19 -51
  198. package/dist/deduplication/deduplication.js.map +1 -1
  199. package/dist/deduplication/diagnostics.d.ts +17 -0
  200. package/dist/deduplication/diagnostics.d.ts.map +1 -0
  201. package/dist/deduplication/diagnostics.js +5 -0
  202. package/dist/deduplication/diagnostics.js.map +1 -0
  203. package/dist/deduplication/finding-schema.d.ts.map +1 -1
  204. package/dist/deduplication/finding-schema.js +7 -1
  205. package/dist/deduplication/finding-schema.js.map +1 -1
  206. package/dist/deduplication/local.d.ts +31 -0
  207. package/dist/deduplication/local.d.ts.map +1 -0
  208. package/dist/deduplication/local.js +166 -0
  209. package/dist/deduplication/local.js.map +1 -0
  210. package/dist/deduplication/records-protocol.d.ts +3 -8
  211. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  212. package/dist/deduplication/records-protocol.js +11 -184
  213. package/dist/deduplication/records-protocol.js.map +1 -1
  214. package/dist/deduplication/records.d.ts +186 -11
  215. package/dist/deduplication/records.d.ts.map +1 -1
  216. package/dist/deduplication/records.js +10 -18
  217. package/dist/deduplication/records.js.map +1 -1
  218. package/dist/deduplication/scan.d.ts +9 -3
  219. package/dist/deduplication/scan.d.ts.map +1 -1
  220. package/dist/deduplication/scan.js +158 -39
  221. package/dist/deduplication/scan.js.map +1 -1
  222. package/dist/deep-config.d.ts +2 -1
  223. package/dist/deep-config.d.ts.map +1 -1
  224. package/dist/deep-config.js +4 -4
  225. package/dist/deep-config.js.map +1 -1
  226. package/dist/deep-progress.d.ts +17 -1
  227. package/dist/deep-progress.d.ts.map +1 -1
  228. package/dist/deep-progress.js +19 -17
  229. package/dist/deep-progress.js.map +1 -1
  230. package/dist/deep-scan.d.ts +20 -0
  231. package/dist/deep-scan.d.ts.map +1 -0
  232. package/dist/deep-scan.js +113 -0
  233. package/dist/deep-scan.js.map +1 -0
  234. package/dist/errors.d.ts +2 -0
  235. package/dist/errors.d.ts.map +1 -1
  236. package/dist/errors.js +2 -0
  237. package/dist/errors.js.map +1 -1
  238. package/dist/executable-path.d.ts +2 -0
  239. package/dist/executable-path.d.ts.map +1 -0
  240. package/dist/executable-path.js +12 -0
  241. package/dist/executable-path.js.map +1 -0
  242. package/dist/feedback.d.ts +1 -4
  243. package/dist/feedback.d.ts.map +1 -1
  244. package/dist/feedback.js +54 -22
  245. package/dist/feedback.js.map +1 -1
  246. package/dist/finding-catalogue.d.ts.map +1 -1
  247. package/dist/finding-catalogue.js +4 -8
  248. package/dist/finding-catalogue.js.map +1 -1
  249. package/dist/finding-normalization.d.ts +5 -0
  250. package/dist/finding-normalization.d.ts.map +1 -0
  251. package/dist/finding-normalization.js +120 -0
  252. package/dist/finding-normalization.js.map +1 -0
  253. package/dist/finding-retrieval.d.ts +9 -0
  254. package/dist/finding-retrieval.d.ts.map +1 -1
  255. package/dist/finding-retrieval.js.map +1 -1
  256. package/dist/finding-workflow.d.ts +13 -8
  257. package/dist/finding-workflow.d.ts.map +1 -1
  258. package/dist/finding-workflow.js +14 -6
  259. package/dist/finding-workflow.js.map +1 -1
  260. package/dist/findings-client.d.ts +2 -1
  261. package/dist/findings-client.d.ts.map +1 -1
  262. package/dist/findings-client.js +36 -9
  263. package/dist/findings-client.js.map +1 -1
  264. package/dist/findings-errors.d.ts +16 -0
  265. package/dist/findings-errors.d.ts.map +1 -0
  266. package/dist/findings-errors.js +24 -0
  267. package/dist/findings-errors.js.map +1 -0
  268. package/dist/findings-import.d.ts +1 -1
  269. package/dist/findings-import.d.ts.map +1 -1
  270. package/dist/findings-import.js +12 -30
  271. package/dist/findings-import.js.map +1 -1
  272. package/dist/github.d.ts.map +1 -1
  273. package/dist/github.js +7 -1
  274. package/dist/github.js.map +1 -1
  275. package/dist/host-protocol.d.ts +19 -0
  276. package/dist/host-protocol.d.ts.map +1 -0
  277. package/dist/host-protocol.js +270 -0
  278. package/dist/host-protocol.js.map +1 -0
  279. package/dist/hosted-scan-protocol.d.ts +4 -0
  280. package/dist/hosted-scan-protocol.d.ts.map +1 -0
  281. package/dist/hosted-scan-protocol.js +25 -0
  282. package/dist/hosted-scan-protocol.js.map +1 -0
  283. package/dist/hosted-scan.d.ts +117 -0
  284. package/dist/hosted-scan.d.ts.map +1 -0
  285. package/dist/hosted-scan.js +260 -0
  286. package/dist/hosted-scan.js.map +1 -0
  287. package/dist/import-scan.d.ts.map +1 -1
  288. package/dist/import-scan.js +48 -38
  289. package/dist/import-scan.js.map +1 -1
  290. package/dist/index.d.ts +11 -4
  291. package/dist/index.d.ts.map +1 -1
  292. package/dist/index.js +2 -1
  293. package/dist/index.js.map +1 -1
  294. package/dist/knowledge-base.d.ts +7 -1
  295. package/dist/knowledge-base.d.ts.map +1 -1
  296. package/dist/knowledge-base.js +114 -46
  297. package/dist/knowledge-base.js.map +1 -1
  298. package/dist/linear.d.ts.map +1 -1
  299. package/dist/linear.js +2 -7
  300. package/dist/linear.js.map +1 -1
  301. package/dist/mock-scan.d.ts.map +1 -1
  302. package/dist/mock-scan.js +0 -1
  303. package/dist/mock-scan.js.map +1 -1
  304. package/dist/models.d.ts +0 -2
  305. package/dist/models.d.ts.map +1 -1
  306. package/dist/models.js.map +1 -1
  307. package/dist/multiscan.d.ts +9 -3
  308. package/dist/multiscan.d.ts.map +1 -1
  309. package/dist/multiscan.js +240 -135
  310. package/dist/multiscan.js.map +1 -1
  311. package/dist/owner-evidence.d.ts +10 -2
  312. package/dist/owner-evidence.d.ts.map +1 -1
  313. package/dist/owner-evidence.js +67 -8
  314. package/dist/owner-evidence.js.map +1 -1
  315. package/dist/patch-tui.d.ts.map +1 -1
  316. package/dist/patch-tui.js +3 -2
  317. package/dist/patch-tui.js.map +1 -1
  318. package/dist/project-config.js +3 -3
  319. package/dist/project-config.js.map +1 -1
  320. package/dist/provider-profile.d.ts +21 -0
  321. package/dist/provider-profile.d.ts.map +1 -0
  322. package/dist/provider-profile.js +133 -0
  323. package/dist/provider-profile.js.map +1 -0
  324. package/dist/publication-events.d.ts +6 -8
  325. package/dist/publication-events.d.ts.map +1 -1
  326. package/dist/publication-events.js +25 -50
  327. package/dist/publication-events.js.map +1 -1
  328. package/dist/publication-store.d.ts.map +1 -1
  329. package/dist/publication-store.js +95 -109
  330. package/dist/publication-store.js.map +1 -1
  331. package/dist/publication.d.ts +1 -4
  332. package/dist/publication.d.ts.map +1 -1
  333. package/dist/publication.js +2 -13
  334. package/dist/publication.js.map +1 -1
  335. package/dist/publish.d.ts +1 -5
  336. package/dist/publish.d.ts.map +1 -1
  337. package/dist/publish.js +109 -160
  338. package/dist/publish.js.map +1 -1
  339. package/dist/request-metadata.d.ts +9 -0
  340. package/dist/request-metadata.d.ts.map +1 -0
  341. package/dist/request-metadata.js +13 -0
  342. package/dist/request-metadata.js.map +1 -0
  343. package/dist/runtime.d.ts +20 -6
  344. package/dist/runtime.d.ts.map +1 -1
  345. package/dist/runtime.js +407 -148
  346. package/dist/runtime.js.map +1 -1
  347. package/dist/saved-scan-bootstrap.d.ts +14 -0
  348. package/dist/saved-scan-bootstrap.d.ts.map +1 -0
  349. package/dist/saved-scan-bootstrap.js +261 -0
  350. package/dist/saved-scan-bootstrap.js.map +1 -0
  351. package/dist/saved-scan.d.ts +1 -1
  352. package/dist/saved-scan.d.ts.map +1 -1
  353. package/dist/saved-scan.js +6 -12
  354. package/dist/saved-scan.js.map +1 -1
  355. package/dist/scan-activity.js +11 -8
  356. package/dist/scan-activity.js.map +1 -1
  357. package/dist/scan-comparison.d.ts +28 -15
  358. package/dist/scan-comparison.d.ts.map +1 -1
  359. package/dist/scan-comparison.js +276 -281
  360. package/dist/scan-comparison.js.map +1 -1
  361. package/dist/scan-dashboard.d.ts +3 -0
  362. package/dist/scan-dashboard.d.ts.map +1 -1
  363. package/dist/scan-dashboard.js +345 -77
  364. package/dist/scan-dashboard.js.map +1 -1
  365. package/dist/scan-executor.d.ts +104 -0
  366. package/dist/scan-executor.d.ts.map +1 -0
  367. package/dist/scan-executor.js +62 -0
  368. package/dist/scan-executor.js.map +1 -0
  369. package/dist/scan-history-renderer.d.ts.map +1 -1
  370. package/dist/scan-history-renderer.js +54 -13
  371. package/dist/scan-history-renderer.js.map +1 -1
  372. package/dist/scan-inputs.d.ts +6 -0
  373. package/dist/scan-inputs.d.ts.map +1 -0
  374. package/dist/scan-inputs.js +71 -0
  375. package/dist/scan-inputs.js.map +1 -0
  376. package/dist/scan-logs.d.ts +2 -3
  377. package/dist/scan-logs.d.ts.map +1 -1
  378. package/dist/scan-logs.js +12 -6
  379. package/dist/scan-logs.js.map +1 -1
  380. package/dist/scan-sessions.d.ts +4 -0
  381. package/dist/scan-sessions.d.ts.map +1 -1
  382. package/dist/scan-sessions.js +17 -0
  383. package/dist/scan-sessions.js.map +1 -1
  384. package/dist/scan-skill-paths.d.ts +8 -0
  385. package/dist/scan-skill-paths.d.ts.map +1 -0
  386. package/dist/scan-skill-paths.js +47 -0
  387. package/dist/scan-skill-paths.js.map +1 -0
  388. package/dist/security-policy-cli.d.ts.map +1 -1
  389. package/dist/security-policy-cli.js +7 -27
  390. package/dist/security-policy-cli.js.map +1 -1
  391. package/dist/security-policy.d.ts +9 -5
  392. package/dist/security-policy.d.ts.map +1 -1
  393. package/dist/security-policy.js +33 -14
  394. package/dist/security-policy.js.map +1 -1
  395. package/dist/server/api.d.ts +0 -1
  396. package/dist/server/api.d.ts.map +1 -1
  397. package/dist/server/api.js +0 -1
  398. package/dist/server/api.js.map +1 -1
  399. package/dist/server/embeddings.d.ts +3 -1
  400. package/dist/server/embeddings.d.ts.map +1 -1
  401. package/dist/server/embeddings.js +10 -3
  402. package/dist/server/embeddings.js.map +1 -1
  403. package/dist/server/errors.d.ts +5 -2
  404. package/dist/server/errors.d.ts.map +1 -1
  405. package/dist/server/errors.js +7 -0
  406. package/dist/server/errors.js.map +1 -1
  407. package/dist/server/sqlite-store.d.ts +0 -2
  408. package/dist/server/sqlite-store.d.ts.map +1 -1
  409. package/dist/server/sqlite-store.js +54 -44
  410. package/dist/server/sqlite-store.js.map +1 -1
  411. package/dist/server/storage.d.ts +0 -2
  412. package/dist/server/storage.d.ts.map +1 -1
  413. package/dist/server/storage.js.map +1 -1
  414. package/dist/severity-store.js +19 -24
  415. package/dist/severity-store.js.map +1 -1
  416. package/dist/standalone-validation-prompt.d.ts +2 -0
  417. package/dist/standalone-validation-prompt.d.ts.map +1 -0
  418. package/dist/standalone-validation-prompt.js +10 -0
  419. package/dist/standalone-validation-prompt.js.map +1 -0
  420. package/dist/suggest-owners.d.ts +4 -2
  421. package/dist/suggest-owners.d.ts.map +1 -1
  422. package/dist/suggest-owners.js +11 -5
  423. package/dist/suggest-owners.js.map +1 -1
  424. package/dist/targets.d.ts +11 -0
  425. package/dist/targets.d.ts.map +1 -1
  426. package/dist/targets.js +123 -72
  427. package/dist/targets.js.map +1 -1
  428. package/dist/trusted-executable.d.ts +2 -2
  429. package/dist/trusted-executable.d.ts.map +1 -1
  430. package/dist/trusted-executable.js +8 -6
  431. package/dist/trusted-executable.js.map +1 -1
  432. package/dist/value.js +7 -0
  433. package/dist/value.js.map +1 -1
  434. package/dist/version.js.map +1 -1
  435. package/dist/workbench-arguments.d.ts +3 -0
  436. package/dist/workbench-arguments.d.ts.map +1 -0
  437. package/dist/workbench-arguments.js +15 -0
  438. package/dist/workbench-arguments.js.map +1 -0
  439. package/dist/worker-progress.d.ts +44 -11
  440. package/dist/worker-progress.d.ts.map +1 -1
  441. package/dist/worker-progress.js +48 -49
  442. package/dist/worker-progress.js.map +1 -1
  443. package/docs/cli.md +1788 -0
  444. package/docs/findings-service.md +402 -0
  445. package/docs/hosted-scans.md +242 -0
  446. package/package.json +23 -22
  447. package/schemas/hosted-scan-v2.fixture.json +145 -0
  448. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +0 -18
  449. package/_bundled_plugin/scripts/workbench_dashboard.py +0 -159
  450. package/_bundled_plugin/scripts/workbench_findings.py +0 -221
  451. package/_bundled_plugin/scripts/workbench_severity.py +0 -122
  452. package/_bundled_plugin/skills/assess-patch-risk/scripts/validate_patch_risk_assessment.py +0 -163
  453. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +0 -276
  454. package/dist/server/dashboard/app.css +0 -2
  455. package/dist/server/dashboard/app.js +0 -66
  456. package/dist/server/dashboard/index.html +0 -18
  457. package/dist/server/dashboard-types.d.ts +0 -48
  458. package/dist/server/dashboard-types.d.ts.map +0 -1
  459. package/dist/server/dashboard-types.js +0 -2
  460. package/dist/server/dashboard-types.js.map +0 -1
  461. package/dist/server/dashboard.d.ts +0 -6
  462. package/dist/server/dashboard.d.ts.map +0 -1
  463. package/dist/server/dashboard.js +0 -59
  464. package/dist/server/dashboard.js.map +0 -1
  465. package/dist/server/index.d.ts +0 -2
  466. package/dist/server/index.d.ts.map +0 -1
  467. package/dist/server/index.js +0 -6
  468. package/dist/server/index.js.map +0 -1
  469. package/dist/server/routes.d.ts +0 -7
  470. package/dist/server/routes.d.ts.map +0 -1
  471. package/dist/server/routes.js +0 -98
  472. package/dist/server/routes.js.map +0 -1
  473. package/dist/server/serve.d.ts +0 -2
  474. package/dist/server/serve.d.ts.map +0 -1
  475. package/dist/server/serve.js +0 -28
  476. package/dist/server/serve.js.map +0 -1
  477. package/dist/server/server.d.ts +0 -10
  478. package/dist/server/server.d.ts.map +0 -1
  479. package/dist/server/server.js +0 -16
  480. package/dist/server/server.js.map +0 -1
  481. package/dist/server/validation.d.ts +0 -17
  482. package/dist/server/validation.d.ts.map +0 -1
  483. package/dist/server/validation.js +0 -53
  484. package/dist/server/validation.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,YAAY,EACV,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,YAAY,EACV,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,kBAAkB,EAClB,YAAY,GACb,MAAM,4BAA4B,CAAC;AACpC,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,aAAa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ACtB,OAAO,EACL,UAAU,EACV,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EAClB,YAAY,GACb,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,gBAAgB,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC3E,YAAY,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { exportArtifact } from "./artifact-export.js";
2
2
  export { CodexSecurity, createSecurity } from "./api.js";
3
+ export { runHostedScan, HostedScanInputSchema, HostedScanPreparationError, } from "./hosted-scan.js";
3
4
  export { loadProjectConfig, resolveProjectConfig } from "./project-config.js";
4
5
  export { classifySeverity } from "./classify-severity.js";
5
6
  export { suggestOwners } from "./suggest-owners.js";
@@ -9,7 +10,7 @@ export { normalizeComponentPlan, planComponents } from "./component-plan.js";
9
10
  export { estimateScanCost } from "./cost.js";
10
11
  export { matchScanFindings } from "./scan-comparison.js";
11
12
  export { CodexLoginHandle } from "./auth.js";
12
- export { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, ContractValidationError, DeduplicationReviewError, IncompleteScanError, InvalidTargetError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
13
+ export { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, ContractValidationError, DeduplicationReviewError, IncompleteScanError, InvalidTargetError, LocalPluginBootstrapError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
13
14
  export { DEFAULT_CODEX_CONFIG, mergedCodexConfig, writeCodexConfig, } from "./config.js";
14
15
  export { loadContract, requireScanFile } from "./contract.js";
15
16
  export { resolveSecurityPolicyTarget, securityPolicyDiff, } from "./security-policy.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAU9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAcpD,OAAO,EACL,oBAAoB,EACpB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAKrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAQxD,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAK7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAK7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AA2BzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAG7C,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,kBAAkB,EAClB,uBAAuB,EACvB,wBAAwB,EACxB,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,4BAA4B,EAC5B,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,aAAa,CAAC;AAOrB,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAG9D,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAQ9B,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAK1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAWhE,OAAO,EACL,eAAe,EACf,wBAAwB,GACzB,MAAM,yBAAyB,CAAC;AAOjC,OAAO,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAC;AAY7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAMzC,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,0BAA0B,EAC1B,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAOtB,OAAO,EACL,UAAU,EACV,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EAClB,YAAY,GACb,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { exportArtifact } from \"./artifact-export.js\";\nexport type {\n ExportArtifactOptions,\n ArtifactExportResult,\n} from \"./artifact-export.js\";\nexport { CodexSecurity, createSecurity } from \"./api.js\";\nexport { loadProjectConfig, resolveProjectConfig } from \"./project-config.js\";\nexport type {\n ResolvedProjectConfig,\n ProjectConfigProvenance,\n} from \"./project-config.js\";\nexport type {\n ProjectConfigInput,\n ProjectScope,\n} from \"./project-config-schema.js\";\nexport type { ScanSettings } from \"./scan-settings.js\";\nexport { classifySeverity } from \"./classify-severity.js\";\nexport { suggestOwners } from \"./suggest-owners.js\";\nexport type {\n OwnerFinding,\n OwnerIdentity,\n OwnerSuggestion,\n OwnerSuggestions,\n SuggestOwnersOptions,\n} from \"./suggest-owners.js\";\nexport type {\n ClassifySeverityOptions,\n SeverityClassificationFinding,\n SeverityClassification,\n SeverityAssessment,\n} from \"./classify-severity.js\";\nexport {\n classifyScanSeverity,\n classifyScanDirectorySeverity,\n} from \"./classify-scan-severity.js\";\nexport type {\n ClassifyScanSeverityOptions,\n ScanSeverityClassification,\n} from \"./classify-scan-severity.js\";\nexport { runComponentScans } from \"./component-scan.js\";\nexport type {\n ComponentDeduplicationSummary,\n ComponentReceipt,\n ComponentScanOptions,\n ComponentScanEvent,\n ComponentScanResult,\n} from \"./component-scan.js\";\nexport { normalizeComponentPlan, planComponents } from \"./component-plan.js\";\nexport type {\n ComponentPlan,\n ComponentPlanningOptions,\n} from \"./component-plan.js\";\nexport { estimateScanCost } from \"./cost.js\";\nexport type { ScanCost, ScanSessionEvent } from \"./cost.js\";\nexport type { DeepScanProgress } from \"./deep-progress.js\";\nexport type { CustomValidationResult } from \"./custom-validation.js\";\nexport type { ScanActivity, ScanActivityStatus } from \"./scan-activity.js\";\nexport { matchScanFindings } from \"./scan-comparison.js\";\nexport type {\n ScanComparisonInput,\n ScanComparisonOptions,\n ScanComparisonProgress,\n ScanComparisonResult,\n} from \"./scan-comparison.js\";\nexport type {\n CodexSecurityMetadata,\n DeepScanOptions,\n ScanAuthMode,\n ScanAuthentication,\n ScanBudget,\n ScanOptions,\n ScanPreflight,\n ScanReconnectDetails,\n ScanTrustedAccessStatus,\n ScanWarningDetails,\n ValidationOptions,\n ValidationResult,\n} from \"./api.js\";\nexport type {\n ScanPhase,\n ScanProgress,\n ScanWorkerPhase,\n ScanWorkerStatus,\n} from \"./worker-progress.js\";\nexport { CodexLoginHandle } from \"./auth.js\";\nexport type { AccountStatus, LoginResult } from \"./auth.js\";\n\nexport {\n AuthenticationRequiredError,\n CodexSecurityError,\n ConfigurationError,\n ContractValidationError,\n DeduplicationReviewError,\n IncompleteScanError,\n InvalidTargetError,\n OutputDirectoryError,\n OutputDirectoryNotEmptyError,\n OutputInsideProtectedRootError,\n PluginBootstrapError,\n PluginPythonUnavailableError,\n SandboxUnavailableError,\n ScanCostLimitExceededError,\n ScanInterruptedError,\n} from \"./errors.js\";\nexport type {\n DeduplicationReviewFailureCategory,\n DeduplicationReviewFailureMetadata,\n DeduplicationReviewStage,\n ProtectedScanPathKind,\n} from \"./errors.js\";\nexport {\n DEFAULT_CODEX_CONFIG,\n mergedCodexConfig,\n writeCodexConfig,\n} from \"./config.js\";\nexport type { CodexSecurityConfig, JsonObject, JsonValue } from \"./config.js\";\nexport { loadContract, requireScanFile } from \"./contract.js\";\nexport type { LoadedContract, ScanExpectation } from \"./contract.js\";\nexport type * from \"./models.js\";\nexport {\n resolveSecurityPolicyTarget,\n securityPolicyDiff,\n} from \"./security-policy.js\";\nexport type {\n SecurityPolicyDraft,\n SecurityPolicyOptions,\n SecurityPolicyPreflight,\n SecurityPolicyStage,\n SecurityPolicyTarget,\n} from \"./security-policy.js\";\nexport { checkScanPublication, publishScan } from \"./publish.js\";\nexport { publishScanToCustom } from \"./custom-publish.js\";\nexport type {\n PublishScanToCustomOptions,\n CustomPublicationResult,\n} from \"./custom-publish.js\";\nexport { deduplicateRecords } from \"./deduplication/records.js\";\nexport type {\n DeduplicateRecordsInput,\n DeduplicateRecordsOptions,\n DeduplicateRecordsResult,\n} from \"./deduplication/records.js\";\nexport type {\n DeduplicationReviewRequest,\n DeduplicationReviewAttribution,\n DeduplicationReviewRunner,\n} from \"./deduplication/review.js\";\nexport {\n deduplicateScan,\n deduplicateScanDirectory,\n} from \"./deduplication/scan.js\";\nexport type {\n DeduplicateScanDirectoryOptions,\n DeduplicateScanOptions,\n DeduplicateScanResult,\n} from \"./deduplication/scan.js\";\nexport type { DeduplicationRefusal } from \"./deduplication/deduplication.js\";\nexport { importGitHubCodeScanningAlerts } from \"./github.js\";\nexport type {\n GitHubCodeScanningImportOptions,\n ImportedGitHubCodeScanningAlert,\n} from \"./github.js\";\nexport type {\n CheckScanPublicationOptions,\n CheckScanPublicationResult,\n PublishScanOptions,\n PublishScanProgress,\n PublishScanResult,\n} from \"./publish.js\";\nexport { ScanResult } from \"./result.js\";\nexport type {\n RepositoryFinding,\n ScanResultOptions,\n TurnResultMetadata,\n} from \"./result.js\";\nexport {\n bootstrapPlugin,\n bundledPluginRoot,\n cleanupSdkDirectory,\n createIsolatedHome,\n createMarketplace,\n extractPluginZip,\n importAmbientAuth,\n MARKETPLACE_NAME,\n pluginExecutionEnvironment,\n pluginMetadata,\n PLUGIN_NAME,\n prepareOutputDir,\n resolveCodexCommand,\n resolvePluginPath,\n resolvePluginPython,\n validateOutputDir,\n} from \"./runtime.js\";\nexport type {\n CodexCommand,\n PluginInstall,\n PluginPythonOptions,\n ProcessEnvironment,\n} from \"./runtime.js\";\nexport {\n DiffTarget,\n normalizeRepository,\n normalizeTarget,\n repositoryRevision,\n validateMode,\n} from \"./targets.js\";\nexport type { NormalizedTarget, ScanMode, ScanTarget } from \"./targets.js\";\nexport type { AbsolutePath } from \"./config-path.js\";\nexport { BUNDLED_PLUGIN_VERSION, VERSION } from \"./version.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EACL,aAAa,EACb,qBAAqB,EACrB,0BAA0B,GAC3B,MAAM,kBAAkB,CAAC;AAY1B,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAU9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAepD,OAAO,EACL,oBAAoB,EACpB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AAKrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAQxD,OAA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iB,EACjB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAOtB,OAAO,EACL,UAAU,EACV,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EAClB,YAAY,GACb,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { exportArtifact } from \"./artifact-export.js\";\nexport type {\n ExportArtifactOptions,\n ArtifactExportResult,\n} from \"./artifact-export.js\";\nexport { CodexSecurity, createSecurity } from \"./api.js\";\nexport {\n runHostedScan,\n HostedScanInputSchema,\n HostedScanPreparationError,\n} from \"./hosted-scan.js\";\nexport type {\n HostedScanInput,\n HostedScanOptions,\n HostedScanResult,\n} from \"./hosted-scan.js\";\nexport type {\n ScanExecutor,\n ScanExecutionRequest,\n ScanExecutionResult,\n ScanExecutionEvent,\n} from \"./scan-executor.js\";\nexport { loadProjectConfig, resolveProjectConfig } from \"./project-config.js\";\nexport type {\n ResolvedProjectConfig,\n ProjectConfigProvenance,\n} from \"./project-config.js\";\nexport type {\n ProjectConfigInput,\n ProjectScope,\n} from \"./project-config-schema.js\";\nexport type { ScanSettings } from \"./scan-settings.js\";\nexport { classifySeverity } from \"./classify-severity.js\";\nexport { suggestOwners } from \"./suggest-owners.js\";\nexport type {\n OwnerFinding,\n CodeownerIdentity,\n OwnerIdentity,\n OwnerSuggestion,\n OwnerSuggestions,\n SuggestOwnersOptions,\n} from \"./suggest-owners.js\";\nexport type {\n ClassifySeverityOptions,\n SeverityClassificationFinding,\n SeverityClassification,\n SeverityAssessment,\n} from \"./classify-severity.js\";\nexport {\n classifyScanSeverity,\n classifyScanDirectorySeverity,\n} from \"./classify-scan-severity.js\";\nexport type {\n ClassifyScanSeverityOptions,\n ScanSeverityClassification,\n} from \"./classify-scan-severity.js\";\nexport { runComponentScans } from \"./component-scan.js\";\nexport type {\n ComponentDeduplicationSummary,\n ComponentReceipt,\n ComponentScanOptions,\n ComponentScanEvent,\n ComponentScanResult,\n} from \"./component-scan.js\";\nexport { normalizeComponentPlan, planComponents } from \"./component-plan.js\";\nexport type {\n ComponentPlan,\n ComponentPlanningOptions,\n} from \"./component-plan.js\";\nexport { estimateScanCost } from \"./cost.js\";\nexport type { ScanCost, ScanSessionEvent, ScanWorkerEvent } from \"./cost.js\";\nexport type { ScanTokenUsage } from \"./cost-model.js\";\nexport type { DeepScanProgress } from \"./deep-progress.js\";\nexport type { CustomValidationResult } from \"./custom-validation.js\";\nexport type { ScanActivity, ScanActivityStatus } from \"./scan-activity.js\";\nexport { matchScanFindings } from \"./scan-comparison.js\";\nexport type {\n ScanComparisonInput,\n ScanComparisonOptions,\n ScanComparisonProgress,\n ScanComparisonResult,\n} from \"./scan-comparison.js\";\nexport type {\n CodexSecurityMetadata,\n DeepScanOptions,\n PatchOptions,\n PatchResult,\n ScanAuthMode,\n ScanAuthentication,\n ScanBudget,\n ScanOptions,\n ScanPreflight,\n ScanReconnectDetails,\n ScanTrustedAccessStatus,\n ScanWarningDetails,\n ValidationOptions,\n ValidationResult,\n} from \"./api.js\";\nexport type {\n ScanPhase,\n ScanProgress,\n ScanWorkerPhase,\n ScanWorkerStatus,\n} from \"./worker-progress.js\";\nexport { CodexLoginHandle } from \"./auth.js\";\nexport type { AccountStatus, LoginResult } from \"./auth.js\";\n\nexport {\n AuthenticationRequiredError,\n CodexSecurityError,\n ConfigurationError,\n ContractValidationError,\n DeduplicationReviewError,\n IncompleteScanError,\n InvalidTargetError,\n LocalPluginBootstrapError,\n OutputDirectoryError,\n OutputDirectoryNotEmptyError,\n OutputInsideProtectedRootError,\n PluginBootstrapError,\n PluginPythonUnavailableError,\n SandboxUnavailableError,\n ScanCostLimitExceededError,\n ScanInterruptedError,\n} from \"./errors.js\";\nexport type {\n DeduplicationReviewFailureCategory,\n DeduplicationReviewFailureMetadata,\n DeduplicationReviewStage,\n ProtectedScanPathKind,\n} from \"./errors.js\";\nexport {\n DEFAULT_CODEX_CONFIG,\n mergedCodexConfig,\n writeCodexConfig,\n} from \"./config.js\";\nexport type { CodexSecurityConfig, JsonObject, JsonValue } from \"./config.js\";\nexport { loadContract, requireScanFile } from \"./contract.js\";\nexport type { LoadedContract, ScanExpectation } from \"./contract.js\";\nexport type * from \"./models.js\";\nexport {\n resolveSecurityPolicyTarget,\n securityPolicyDiff,\n} from \"./security-policy.js\";\nexport type {\n SecurityPolicyDraft,\n SecurityPolicyOptions,\n SecurityPolicyPreflight,\n SecurityPolicyStage,\n SecurityPolicyTarget,\n} from \"./security-policy.js\";\nexport { checkScanPublication, publishScan } from \"./publish.js\";\nexport { publishScanToCustom } from \"./custom-publish.js\";\nexport type {\n PublishScanToCustomOptions,\n CustomPublicationResult,\n} from \"./custom-publish.js\";\nexport { deduplicateRecords } from \"./deduplication/records.js\";\nexport type {\n DeduplicateRecordsInput,\n DeduplicateRecordsOptions,\n DeduplicateRecordsResult,\n} from \"./deduplication/records.js\";\nexport type {\n DeduplicationReviewRequest,\n DeduplicationReviewAttribution,\n DeduplicationReviewRunner,\n} from \"./deduplication/review.js\";\nexport {\n deduplicateScan,\n deduplicateScanDirectory,\n} from \"./deduplication/scan.js\";\nexport type {\n DeduplicateScanDirectoryOptions,\n DeduplicateScanOptions,\n DeduplicateScanResult,\n} from \"./deduplication/scan.js\";\nexport type { DeduplicationRefusal } from \"./deduplication/deduplication.js\";\nexport type { FindingEmbeddingBinding } from \"./deduplication/local.js\";\nexport type {\n DeduplicationDiagnostic,\n DeduplicationDiagnosticObserver,\n} from \"./deduplication/diagnostics.js\";\nexport type { FindingEmbedder } from \"./server/embeddings.js\";\nexport { importGitHubCodeScanningAlerts } from \"./github.js\";\nexport type {\n GitHubCodeScanningImportOptions,\n ImportedGitHubCodeScanningAlert,\n} from \"./github.js\";\nexport type {\n CheckScanPublicationOptions,\n CheckScanPublicationResult,\n PublishScanOptions,\n PublishScanProgress,\n PublishScanResult,\n} from \"./publish.js\";\nexport { ScanResult } from \"./result.js\";\nexport type {\n RepositoryFinding,\n ScanResultOptions,\n TurnResultMetadata,\n} from \"./result.js\";\nexport {\n bootstrapPlugin,\n bundledPluginRoot,\n cleanupSdkDirectory,\n createIsolatedHome,\n createMarketplace,\n extractPluginZip,\n importAmbientAuth,\n MARKETPLACE_NAME,\n pluginExecutionEnvironment,\n pluginMetadata,\n PLUGIN_NAME,\n prepareOutputDir,\n resolveCodexCommand,\n resolvePluginPath,\n resolvePluginPython,\n validateOutputDir,\n} from \"./runtime.js\";\nexport type {\n CodexCommand,\n PluginInstall,\n PluginPythonOptions,\n ProcessEnvironment,\n} from \"./runtime.js\";\nexport {\n DiffTarget,\n normalizeRepository,\n normalizeTarget,\n repositoryRevision,\n validateMode,\n} from \"./targets.js\";\nexport type { NormalizedTarget, ScanMode, ScanTarget } from \"./targets.js\";\nexport type { AbsolutePath } from \"./config-path.js\";\nexport { BUNDLED_PLUGIN_VERSION, VERSION } from \"./version.js\";\n"]}
@@ -1,7 +1,13 @@
1
1
  export interface PreparedKnowledgeBase {
2
2
  path: string;
3
3
  sources: string[];
4
+ protectedRoots: string[];
4
5
  cleanup(): Promise<void>;
5
6
  }
6
- export declare function prepareKnowledgeBase(paths: readonly string[], signal?: AbortSignal, directory?: string): Promise<PreparedKnowledgeBase>;
7
+ export interface KnowledgeBaseSnapshot {
8
+ readonly sources: readonly string[];
9
+ readonly protectedRoots?: readonly string[];
10
+ readonly documents: Readonly<Record<string, string>>;
11
+ }
12
+ export declare function prepareKnowledgeBase(input: readonly string[] | KnowledgeBaseSnapshot, signal?: AbortSignal, directory?: string): Promise<PreparedKnowledgeBase>;
7
13
  //# sourceMappingURL=knowledge-base.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge-base.d.ts","sourceRoot":"","sources":["../src/knowledge-base.ts"],"names":[],"mappings":"AAuBA,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,EACpB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,qBAAqB,CAAC,CAiFhC"}
1
+ {"version":3,"file":"knowledge-base.d.ts","sourceRoot":"","sources":["../src/knowledge-base.ts"],"names":[],"mappings":"AA8BA,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACtD;AAyFD,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,qBAAqB,EAChD,MAAM,CAAC,EAAE,WAAW,EACpB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,qBAAqB,CAAC,CAyChC"}
@@ -1,9 +1,11 @@
1
1
  import { constants } from "node:fs";
2
- import { lstat, mkdtemp, readFile, readdir, realpath, rm, writeFile, } from "node:fs/promises";
2
+ import { lstat, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile, } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, extname, join, resolve } from "node:path";
5
5
  import { unzipSync } from "fflate";
6
+ import { ConfigurationError, errorMessage } from "./errors.js";
6
7
  import { expandHome } from "./runtime.js";
8
+ import { gitMarkerRoot, isGitMetadataDirectory, nullIfMissingFile, } from "./targets.js";
7
9
  const DOCUMENT_EXTENSIONS = new Set([
8
10
  ".md",
9
11
  ".markdown",
@@ -11,35 +13,36 @@ const DOCUMENT_EXTENSIONS = new Set([
11
13
  ".pdf",
12
14
  ".docx",
13
15
  ]);
14
- export async function prepareKnowledgeBase(paths, signal, directory) {
15
- const sources = new Set();
16
- const documents = new Set();
17
- for (const requested of paths) {
18
- signal?.throwIfAborted();
19
- if (!requested.trim())
20
- throw new Error("Knowledge base paths cannot be empty.");
21
- const path = resolve(expandHome(requested));
22
- const metadata = await lstat(path);
23
- if (metadata.isSymbolicLink()) {
24
- throw new Error(`Knowledge base paths cannot be symbolic links: ${path}`);
25
- }
26
- if (!metadata.isFile() && !metadata.isDirectory()) {
27
- throw new Error(`Knowledge base path is not a file or directory: ${path}`);
28
- }
29
- const source = await realpath(path);
30
- const selected = metadata.isDirectory()
31
- ? await discover(source, signal)
32
- : [source];
33
- if (selected.length === 0) {
34
- throw new Error(`Knowledge base directory contains no supported documents: ${path}`);
35
- }
36
- for (const document of selected) {
37
- documents.add(document);
38
- }
39
- sources.add(source);
40
- }
41
- const path = await mkdtemp(join(directory ?? tmpdir(), "codex-security-knowledge-"));
16
+ /** @internal Extract once so campaign identity and workers use identical inputs. */
17
+ export async function readKnowledgeBaseSnapshot(paths, signal) {
42
18
  try {
19
+ const sources = new Set();
20
+ const documents = new Set();
21
+ for (const requested of paths) {
22
+ signal?.throwIfAborted();
23
+ if (!requested.trim())
24
+ throw new Error("Knowledge base paths cannot be empty.");
25
+ const path = resolve(expandHome(requested));
26
+ const metadata = await lstat(path);
27
+ if (metadata.isSymbolicLink()) {
28
+ throw new Error(`Knowledge base paths cannot be symbolic links: ${path}`);
29
+ }
30
+ if (!metadata.isFile() && !metadata.isDirectory()) {
31
+ throw new Error(`Knowledge base path is not a file or directory: ${path}`);
32
+ }
33
+ const source = await realpath(path);
34
+ const selected = metadata.isDirectory()
35
+ ? (await discover(source, signal)).sort()
36
+ : [source];
37
+ if (selected.length === 0) {
38
+ throw new Error(`Knowledge base directory contains no supported documents: ${path}`);
39
+ }
40
+ for (const document of selected) {
41
+ documents.add(document);
42
+ }
43
+ sources.add(source);
44
+ }
45
+ const extracted = {};
43
46
  let index = 0;
44
47
  for (const document of documents) {
45
48
  signal?.throwIfAborted();
@@ -53,7 +56,7 @@ export async function prepareKnowledgeBase(paths, signal, directory) {
53
56
  });
54
57
  const extension = extname(document).toLowerCase();
55
58
  const text = extension === ".pdf"
56
- ? await extractPdf(document, bytes)
59
+ ? await extractPdf(document, bytes, signal)
57
60
  : extension === ".docx"
58
61
  ? extractDocx(document, bytes)
59
62
  : decodeText(document, bytes);
@@ -63,23 +66,63 @@ export async function prepareKnowledgeBase(paths, signal, directory) {
63
66
  const name = `${index}-${basename(document)}.txt`;
64
67
  // The prefix and suffix can exceed the filesystem's 255-byte name limit.
65
68
  const filename = Buffer.byteLength(name) > 255 ? `${index}.txt` : name;
66
- await writeFile(join(path, filename), text, {
67
- encoding: "utf8",
68
- mode: 0o600,
69
- signal,
70
- });
69
+ extracted[filename] = text;
71
70
  index++;
72
71
  }
72
+ return {
73
+ sources: [...sources],
74
+ protectedRoots: await Promise.all([...sources].map(async (source) => (await gitMarkerRoot(source, signal, "outermost")) ?? source)),
75
+ documents: extracted,
76
+ };
73
77
  }
74
78
  catch (error) {
75
- await rm(path, { recursive: true, force: true });
76
- throw error;
79
+ if (signal?.aborted || error instanceof ConfigurationError)
80
+ throw error;
81
+ throw new ConfigurationError(errorMessage(error), { cause: error });
77
82
  }
78
- return {
79
- path,
80
- sources: [...sources],
81
- cleanup: () => rm(path, { recursive: true, force: true }),
82
- };
83
+ }
84
+ export async function prepareKnowledgeBase(input, signal, directory) {
85
+ try {
86
+ const snapshot = "documents" in input
87
+ ? input
88
+ : await readKnowledgeBaseSnapshot(input, signal);
89
+ const protectedRoots = snapshot.protectedRoots === undefined
90
+ ? await Promise.all(snapshot.sources.map(async (source) => (await gitMarkerRoot(source, signal, "outermost")) ?? source))
91
+ : [...snapshot.protectedRoots];
92
+ const path = await mkdtemp(join(directory ?? tmpdir(), "codex-security-knowledge-"));
93
+ try {
94
+ for (const [filename, text] of Object.entries(snapshot.documents)) {
95
+ signal?.throwIfAborted();
96
+ await writeFile(join(path, filename), text, {
97
+ encoding: "utf8",
98
+ mode: 0o600,
99
+ signal,
100
+ });
101
+ }
102
+ }
103
+ catch (error) {
104
+ await rm(path, { recursive: true, force: true });
105
+ throw error;
106
+ }
107
+ return {
108
+ path,
109
+ sources: [...snapshot.sources],
110
+ protectedRoots,
111
+ cleanup: () => rm(path, { recursive: true, force: true }),
112
+ };
113
+ }
114
+ catch (error) {
115
+ if (signal?.aborted || error instanceof ConfigurationError)
116
+ throw error;
117
+ throw new ConfigurationError(errorMessage(error), { cause: error });
118
+ }
119
+ }
120
+ /** @internal Read the same extracted document text used by scans. */
121
+ export async function readKnowledgeBaseDocuments(paths, signal) {
122
+ const { documents } = await readKnowledgeBaseSnapshot(paths, signal);
123
+ return Object.keys(documents)
124
+ .sort()
125
+ .map((name) => documents[name]);
83
126
  }
84
127
  async function discover(directory, signal) {
85
128
  signal?.throwIfAborted();
@@ -88,9 +131,24 @@ async function discover(directory, signal) {
88
131
  signal?.throwIfAborted();
89
132
  for (const entry of entries) {
90
133
  signal?.throwIfAborted();
91
- if (entry.name.toLowerCase() === ".git")
134
+ if ((process.platform === "win32" ? entry.name.toLowerCase() : entry.name) ===
135
+ ".git")
92
136
  continue;
93
137
  const path = join(directory, entry.name);
138
+ if (entry.name.toLowerCase() === ".git") {
139
+ const marker = await stat(join(directory, ".git"), {
140
+ bigint: true,
141
+ }).catch(nullIfMissingFile);
142
+ if (marker !== null) {
143
+ const candidate = await lstat(path, { bigint: true });
144
+ if (candidate.dev === marker.dev && candidate.ino === marker.ino) {
145
+ continue;
146
+ }
147
+ }
148
+ if (entry.isDirectory() && (await isGitMetadataDirectory(path, signal))) {
149
+ continue;
150
+ }
151
+ }
94
152
  if (entry.isDirectory()) {
95
153
  for (const document of await discover(path, signal)) {
96
154
  documents.push(document);
@@ -127,7 +185,7 @@ function decodeText(path, bytes) {
127
185
  });
128
186
  }
129
187
  }
130
- async function extractPdf(path, bytes) {
188
+ async function extractPdf(path, bytes, signal) {
131
189
  try {
132
190
  const { getDocument, VerbosityLevel } = await import("pdfjs-dist/legacy/build/pdf.mjs");
133
191
  const loadingTask = getDocument({
@@ -139,7 +197,9 @@ async function extractPdf(path, bytes) {
139
197
  const document = await loadingTask.promise;
140
198
  const pages = [];
141
199
  for (let number = 1; number <= document.numPages; number++) {
200
+ signal?.throwIfAborted();
142
201
  const content = await (await document.getPage(number)).getTextContent();
202
+ signal?.throwIfAborted();
143
203
  pages.push(content.items
144
204
  .map((item) => ("str" in item ? item.str : ""))
145
205
  .join(" "));
@@ -151,6 +211,8 @@ async function extractPdf(path, bytes) {
151
211
  }
152
212
  }
153
213
  catch (error) {
214
+ if (signal?.aborted)
215
+ throw error;
154
216
  throw new Error(`Cannot extract text from knowledge base PDF: ${path}`, {
155
217
  cause: error,
156
218
  });
@@ -177,7 +239,8 @@ function extractDocx(path, bytes) {
177
239
  }
178
240
  return decodeXml(xml
179
241
  .replace(/<\/(?:\w+:)?p\s*>/gu, "\n")
180
- .replace(/<(?:\w+:)?tab\b[^>]*\/>/gu, "\t")
242
+ .replace(/<(?:\w+:)?(?:br|cr)\b[^>]*>/gu, "\n")
243
+ .replace(/<(?:\w+:)?tab\b[^>]*>/gu, "\t")
181
244
  .replace(/<[^>]+>/gu, ""));
182
245
  }
183
246
  catch (error) {
@@ -198,7 +261,12 @@ function decodeXml(value) {
198
261
  if (!name.startsWith("#"))
199
262
  return entities[name.toLowerCase()] ?? entity;
200
263
  const hexadecimal = name[1]?.toLowerCase() === "x";
201
- return String.fromCodePoint(Number.parseInt(name.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10));
264
+ const codePoint = Number.parseInt(name.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10);
265
+ if (codePoint > 0x10ffff ||
266
+ (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
267
+ return entity;
268
+ }
269
+ return String.fromCodePoint(codePoint);
202
270
  });
203
271
  }
204
272
  //# sourceMappingURL=knowledge-base.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge-base.js","sourceRoot":"","sources":["../src/knowledge-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,EAAE,EACF,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,KAAK;IACL,WAAW;IACX,MAAM;IACN,MAAM;IACN,OAAO;CACR,CAAC,CAAC;AAQH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAwB,EACxB,MAAoB,EACpB,SAAkB;IAElB,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IAEpC,KAAK,MAAM,SAAS,IAAI,KAAK,EAAE,CAAC;QAC9B,MAAM,EAAE,cAAc,EAAE,CAAC;QACzB,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC3D,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QAC5C,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,QAAQ,CAAC,cAAc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C,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CACxE,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport {\n lstat,\n mkdtemp,\n readFile,\n readdir,\n realpath,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, extname, join, resolve } from \"node:path\";\nimport { unzipSync } from \"fflate\";\nimport { expandHome } from \"./runtime.js\";\n\nconst DOCUMENT_EXTENSIONS = new Set([\n \".md\",\n \".markdown\",\n \".txt\",\n \".pdf\",\n \".docx\",\n]);\n\nexport interface PreparedKnowledgeBase {\n path: string;\n sources: string[];\n cleanup(): Promise<void>;\n}\n\nexport async function prepareKnowledgeBase(\n paths: readonly string[],\n signal?: AbortSignal,\n directory?: string,\n): Promise<PreparedKnowledgeBase> {\n const sources = new Set<string>();\n const documents = new Set<string>();\n\n for (const requested of paths) {\n signal?.throwIfAborted();\n if (!requested.trim())\n throw new Error(\"Knowledge base paths cannot be empty.\");\n const path = resolve(expandHome(requested));\n const metadata = await lstat(path);\n if (metadata.isSymbolicLink()) {\n throw new Error(`Knowledge base paths cannot be symbolic links: ${path}`);\n }\n if (!metadata.isFile() && !metadata.isDirectory()) {\n throw new Error(\n `Knowledge base path is not a file or directory: ${path}`,\n );\n }\n\n const source = await realpath(path);\n const selected = metadata.isDirectory()\n ? await discover(source, signal)\n : [source];\n if (selected.length === 0) {\n throw new Error(\n `Knowledge base directory contains no supported documents: ${path}`,\n );\n }\n for (const document of selected) {\n documents.add(document);\n }\n sources.add(source);\n }\n\n const path = await mkdtemp(\n join(directory ?? tmpdir(), \"codex-security-knowledge-\"),\n );\n try {\n let index = 0;\n for (const document of documents) {\n signal?.throwIfAborted();\n const metadata = await lstat(document);\n if (process.platform !== \"win32\" && (metadata.mode & 0o444) === 0) {\n throw new Error(`Knowledge base document is not readable: ${document}`);\n }\n const bytes = await readFile(document, {\n flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n signal,\n });\n const extension = extname(document).toLowerCase();\n const text =\n extension === \".pdf\"\n ? await extractPdf(document, bytes)\n : extension === \".docx\"\n ? extractDocx(document, bytes)\n : decodeText(document, bytes);\n if ((extension === \".pdf\" || extension === \".docx\") && !text.trim()) {\n throw new Error(\n `Knowledge base document contains no extractable text: ${document}`,\n );\n }\n const name = `${index}-${basename(document)}.txt`;\n // The prefix and suffix can exceed the filesystem's 255-byte name limit.\n const filename = Buffer.byteLength(name) > 255 ? `${index}.txt` : name;\n await writeFile(join(path, filename), text, {\n encoding: \"utf8\",\n mode: 0o600,\n signal,\n });\n index++;\n }\n } catch (error) {\n await rm(path, { recursive: true, force: true });\n throw error;\n }\n\n return {\n path,\n sources: [...sources],\n cleanup: () => rm(path, { recursive: true, force: true }),\n };\n}\n\nasync function discover(\n directory: string,\n signal?: AbortSignal,\n): Promise<string[]> {\n signal?.throwIfAborted();\n const documents: string[] = [];\n const entries = await readdir(directory, { withFileTypes: true });\n signal?.throwIfAborted();\n for (const entry of entries) {\n signal?.throwIfAborted();\n if (entry.name.toLowerCase() === \".git\") continue;\n const path = join(directory, entry.name);\n if (entry.isDirectory()) {\n for (const document of await discover(path, signal)) {\n documents.push(document);\n }\n } else if (entry.isFile()) {\n if (!DOCUMENT_EXTENSIONS.has(extname(path).toLowerCase())) {\n const bytes = await readFile(path, {\n flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n signal,\n });\n try {\n decodeText(path, bytes);\n } catch {\n continue;\n }\n }\n documents.push(path);\n }\n }\n return documents;\n}\n\nfunction decodeText(path: string, bytes: Uint8Array): string {\n if (bytes.includes(0)) {\n throw new Error(`Knowledge base document contains binary data: ${path}`);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Knowledge base document is not valid UTF-8: ${path}`, {\n cause: error,\n });\n }\n}\n\nasync function extractPdf(path: string, bytes: Uint8Array): Promise<string> {\n try {\n const { getDocument, VerbosityLevel } =\n await import(\"pdfjs-dist/legacy/build/pdf.mjs\");\n const loadingTask = getDocument({\n data: new Uint8Array(bytes),\n stopAtErrors: true,\n verbosity: VerbosityLevel.ERRORS,\n });\n try {\n const document = await loadingTask.promise;\n const pages: string[] = [];\n for (let number = 1; number <= document.numPages; number++) {\n const content = await (await document.getPage(number)).getTextContent();\n pages.push(\n content.items\n .map((item) => (\"str\" in item ? item.str : \"\"))\n .join(\" \"),\n );\n }\n return pages.join(\"\\n\");\n } finally {\n await loadingTask.destroy();\n }\n } catch (error) {\n throw new Error(`Cannot extract text from knowledge base PDF: ${path}`, {\n cause: error,\n });\n }\n}\n\nfunction extractDocx(path: string, bytes: Uint8Array): string {\n try {\n const files = unzipSync(bytes, {\n filter: (file) => {\n if (file.name !== \"word/document.xml\") return false;\n if (file.originalSize > 25 * 1024 * 1024) {\n throw new Error(\"DOCX document text exceeds 25 MB.\");\n }\n return true;\n },\n });\n const document = files[\"word/document.xml\"];\n if (document === undefined) throw new Error(\"Missing word/document.xml.\");\n const xml = decodeText(path, document);\n if (\n !/<(?:\\w+:)?document\\b[^>]*>[\\s\\S]*<\\/(?:\\w+:)?document\\s*>/u.test(xml)\n ) {\n throw new Error(\"Malformed word/document.xml.\");\n }\n return decodeXml(\n xml\n .replace(/<\\/(?:\\w+:)?p\\s*>/gu, \"\\n\")\n .replace(/<(?:\\w+:)?tab\\b[^>]*\\/>/gu, \"\\t\")\n .replace(/<[^>]+>/gu, \"\"),\n );\n } catch (error) {\n throw new Error(`Cannot extract text from knowledge base DOCX: ${path}`, {\n cause: error,\n });\n }\n}\n\nfunction decodeXml(value: string): string {\n const entities: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n };\n return value.replace(\n /&(amp|lt|gt|quot|apos|#\\d+|#x[\\da-f]+);/giu,\n (entity, name: string) => {\n if (!name.startsWith(\"#\")) return entities[name.toLowerCase()] ?? entity;\n const hexadecimal = name[1]?.toLowerCase() === \"x\";\n return String.fromCodePoint(\n Number.parseInt(name.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10),\n );\n },\n );\n}\n"]}
1
+ {"version":3,"file":"knowledge-base.js","sourceRoot":"","sources":["../src/knowledge-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,EAAE,EACF,IAAI,EACJ,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EACL,aAAa,EACb,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAEtB,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,KAAK;IACL,WAAW;IACX,MAAM;IACN,MAAM;IACN,OAAO;CACR,CAAC,CAAC;AAeH,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,KAAwB,EACxB,MAAoB;IAEpB,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;QAClC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;QAEpC,KAAK,MAAM,SAAS,IAAI,KAAK,EAAE,CAAC;YAC9B,MAAM,EAAE,cAAc,EAAE,CAAC;YACzB,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;gB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,IAAI,KAAK,CAAC,iDAAiD,IAAI,EAAE,EAAE;YACvE,KAAK,EAAE,KAAK;SACb,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,MAAM,QAAQ,GAA2B;QACvC,GAAG,EAAE,GAAG;QACR,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,IAAI,EAAE,GAAG;QACT,IAAI,EAAE,GAAG;KACV,CAAC;IACF,OAAO,KAAK,CAAC,OAAO,CAClB,4CAA4C,EAC5C,CAAC,MAAM,EAAE,IAAY,EAAE,EAAE;QACvB,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,OAAO,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,MAAM,CAAC;QACzE,MAAM,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,KAAK,GAAG,CAAC;QACnD,MAAM,SAAS,GAAG,MAAM,CAAC,QAAQ,CAC/B,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAC/B,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CACtB,CAAC;QACF,IACE,SAAS,GAAG,QAAQ;YACpB,CAAC,SAAS,IAAI,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,EAC5C,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport {\n lstat,\n mkdtemp,\n readFile,\n readdir,\n realpath,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, extname, join, resolve } from \"node:path\";\nimport { unzipSync } from \"fflate\";\nimport { ConfigurationError, errorMessage } from \"./errors.js\";\nimport { expandHome } from \"./runtime.js\";\nimport {\n gitMarkerRoot,\n isGitMetadataDirectory,\n nullIfMissingFile,\n} from \"./targets.js\";\n\nconst DOCUMENT_EXTENSIONS = new Set([\n \".md\",\n \".markdown\",\n \".txt\",\n \".pdf\",\n \".docx\",\n]);\n\nexport interface PreparedKnowledgeBase {\n path: string;\n sources: string[];\n protectedRoots: string[];\n cleanup(): Promise<void>;\n}\n\nexport interface KnowledgeBaseSnapshot {\n readonly sources: readonly string[];\n readonly protectedRoots?: readonly string[];\n readonly documents: Readonly<Record<string, string>>;\n}\n\n/** @internal Extract once so campaign identity and workers use identical inputs. */\nexport async function readKnowledgeBaseSnapshot(\n paths: readonly string[],\n signal?: AbortSignal,\n): Promise<KnowledgeBaseSnapshot> {\n try {\n const sources = new Set<string>();\n const documents = new Set<string>();\n\n for (const requested of paths) {\n signal?.throwIfAborted();\n if (!requested.trim())\n throw new Error(\"Knowledge base paths cannot be empty.\");\n const path = resolve(expandHome(requested));\n const metadata = await lstat(path);\n if (metadata.isSymbolicLink()) {\n throw new Error(\n `Knowledge base paths cannot be symbolic links: ${path}`,\n );\n }\n if (!metadata.isFile() && !metadata.isDirectory()) {\n throw new Error(\n `Knowledge base path is not a file or directory: ${path}`,\n );\n }\n\n const source = await realpath(path);\n const selected = metadata.isDirectory()\n ? (await discover(source, signal)).sort()\n : [source];\n if (selected.length === 0) {\n throw new Error(\n `Knowledge base directory contains no supported documents: ${path}`,\n );\n }\n for (const document of selected) {\n documents.add(document);\n }\n sources.add(source);\n }\n\n const extracted: Record<string, string> = {};\n let index = 0;\n for (const document of documents) {\n signal?.throwIfAborted();\n const metadata = await lstat(document);\n if (process.platform !== \"win32\" && (metadata.mode & 0o444) === 0) {\n throw new Error(`Knowledge base document is not readable: ${document}`);\n }\n const bytes = await readFile(document, {\n flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n signal,\n });\n const extension = extname(document).toLowerCase();\n const text =\n extension === \".pdf\"\n ? await extractPdf(document, bytes, signal)\n : extension === \".docx\"\n ? extractDocx(document, bytes)\n : decodeText(document, bytes);\n if ((extension === \".pdf\" || extension === \".docx\") && !text.trim()) {\n throw new Error(\n `Knowledge base document contains no extractable text: ${document}`,\n );\n }\n const name = `${index}-${basename(document)}.txt`;\n // The prefix and suffix can exceed the filesystem's 255-byte name limit.\n const filename = Buffer.byteLength(name) > 255 ? `${index}.txt` : name;\n extracted[filename] = text;\n index++;\n }\n return {\n sources: [...sources],\n protectedRoots: await Promise.all(\n [...sources].map(\n async (source) =>\n (await gitMarkerRoot(source, signal, \"outermost\")) ?? source,\n ),\n ),\n documents: extracted,\n };\n } catch (error) {\n if (signal?.aborted || error instanceof ConfigurationError) throw error;\n throw new ConfigurationError(errorMessage(error), { cause: error });\n }\n}\n\nexport async function prepareKnowledgeBase(\n input: readonly string[] | KnowledgeBaseSnapshot,\n signal?: AbortSignal,\n directory?: string,\n): Promise<PreparedKnowledgeBase> {\n try {\n const snapshot =\n \"documents\" in input\n ? input\n : await readKnowledgeBaseSnapshot(input, signal);\n const protectedRoots =\n snapshot.protectedRoots === undefined\n ? await Promise.all(\n snapshot.sources.map(\n async (source) =>\n (await gitMarkerRoot(source, signal, \"outermost\")) ?? source,\n ),\n )\n : [...snapshot.protectedRoots];\n const path = await mkdtemp(\n join(directory ?? tmpdir(), \"codex-security-knowledge-\"),\n );\n try {\n for (const [filename, text] of Object.entries(snapshot.documents)) {\n signal?.throwIfAborted();\n await writeFile(join(path, filename), text, {\n encoding: \"utf8\",\n mode: 0o600,\n signal,\n });\n }\n } catch (error) {\n await rm(path, { recursive: true, force: true });\n throw error;\n }\n return {\n path,\n sources: [...snapshot.sources],\n protectedRoots,\n cleanup: () => rm(path, { recursive: true, force: true }),\n };\n } catch (error) {\n if (signal?.aborted || error instanceof ConfigurationError) throw error;\n throw new ConfigurationError(errorMessage(error), { cause: error });\n }\n}\n\n/** @internal Read the same extracted document text used by scans. */\nexport async function readKnowledgeBaseDocuments(\n paths: readonly string[],\n signal?: AbortSignal,\n): Promise<string[]> {\n const { documents } = await readKnowledgeBaseSnapshot(paths, signal);\n return Object.keys(documents)\n .sort()\n .map((name) => documents[name]!);\n}\n\nasync function discover(\n directory: string,\n signal?: AbortSignal,\n): Promise<string[]> {\n signal?.throwIfAborted();\n const documents: string[] = [];\n const entries = await readdir(directory, { withFileTypes: true });\n signal?.throwIfAborted();\n for (const entry of entries) {\n signal?.throwIfAborted();\n if (\n (process.platform === \"win32\" ? entry.name.toLowerCase() : entry.name) ===\n \".git\"\n )\n continue;\n const path = join(directory, entry.name);\n if (entry.name.toLowerCase() === \".git\") {\n const marker = await stat(join(directory, \".git\"), {\n bigint: true,\n }).catch(nullIfMissingFile);\n if (marker !== null) {\n const candidate = await lstat(path, { bigint: true });\n if (candidate.dev === marker.dev && candidate.ino === marker.ino) {\n continue;\n }\n }\n if (entry.isDirectory() && (await isGitMetadataDirectory(path, signal))) {\n continue;\n }\n }\n if (entry.isDirectory()) {\n for (const document of await discover(path, signal)) {\n documents.push(document);\n }\n } else if (entry.isFile()) {\n if (!DOCUMENT_EXTENSIONS.has(extname(path).toLowerCase())) {\n const bytes = await readFile(path, {\n flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n signal,\n });\n try {\n decodeText(path, bytes);\n } catch {\n continue;\n }\n }\n documents.push(path);\n }\n }\n return documents;\n}\n\nfunction decodeText(path: string, bytes: Uint8Array): string {\n if (bytes.includes(0)) {\n throw new Error(`Knowledge base document contains binary data: ${path}`);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Knowledge base document is not valid UTF-8: ${path}`, {\n cause: error,\n });\n }\n}\n\nasync function extractPdf(\n path: string,\n bytes: Uint8Array,\n signal?: AbortSignal,\n): Promise<string> {\n try {\n const { getDocument, VerbosityLevel } =\n await import(\"pdfjs-dist/legacy/build/pdf.mjs\");\n const loadingTask = getDocument({\n data: new Uint8Array(bytes),\n stopAtErrors: true,\n verbosity: VerbosityLevel.ERRORS,\n });\n try {\n const document = await loadingTask.promise;\n const pages: string[] = [];\n for (let number = 1; number <= document.numPages; number++) {\n signal?.throwIfAborted();\n const content = await (await document.getPage(number)).getTextContent();\n signal?.throwIfAborted();\n pages.push(\n content.items\n .map((item) => (\"str\" in item ? item.str : \"\"))\n .join(\" \"),\n );\n }\n return pages.join(\"\\n\");\n } finally {\n await loadingTask.destroy();\n }\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new Error(`Cannot extract text from knowledge base PDF: ${path}`, {\n cause: error,\n });\n }\n}\n\nfunction extractDocx(path: string, bytes: Uint8Array): string {\n try {\n const files = unzipSync(bytes, {\n filter: (file) => {\n if (file.name !== \"word/document.xml\") return false;\n if (file.originalSize > 25 * 1024 * 1024) {\n throw new Error(\"DOCX document text exceeds 25 MB.\");\n }\n return true;\n },\n });\n const document = files[\"word/document.xml\"];\n if (document === undefined) throw new Error(\"Missing word/document.xml.\");\n const xml = decodeText(path, document);\n if (\n !/<(?:\\w+:)?document\\b[^>]*>[\\s\\S]*<\\/(?:\\w+:)?document\\s*>/u.test(xml)\n ) {\n throw new Error(\"Malformed word/document.xml.\");\n }\n return decodeXml(\n xml\n .replace(/<\\/(?:\\w+:)?p\\s*>/gu, \"\\n\")\n .replace(/<(?:\\w+:)?(?:br|cr)\\b[^>]*>/gu, \"\\n\")\n .replace(/<(?:\\w+:)?tab\\b[^>]*>/gu, \"\\t\")\n .replace(/<[^>]+>/gu, \"\"),\n );\n } catch (error) {\n throw new Error(`Cannot extract text from knowledge base DOCX: ${path}`, {\n cause: error,\n });\n }\n}\n\nfunction decodeXml(value: string): string {\n const entities: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n };\n return value.replace(\n /&(amp|lt|gt|quot|apos|#\\d+|#x[\\da-f]+);/giu,\n (entity, name: string) => {\n if (!name.startsWith(\"#\")) return entities[name.toLowerCase()] ?? entity;\n const hexadecimal = name[1]?.toLowerCase() === \"x\";\n const codePoint = Number.parseInt(\n name.slice(hexadecimal ? 2 : 1),\n hexadecimal ? 16 : 10,\n );\n if (\n codePoint > 0x10ffff ||\n (codePoint >= 0xd800 && codePoint <= 0xdfff)\n ) {\n return entity;\n }\n return String.fromCodePoint(codePoint);\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"linear.d.ts","sourceRoot":"","sources":["../src/linear.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,YAAY,EAEb,MAAM,aAAa,CAAC;AAIrB,MAAM,MAAM,mBAAmB,CAC7B,MAAM,SAAS,MAAM,YAAY,GAAG,OAAO,GAAG,UAAU,IACtD,CACF,OAAO,EAAE,qBAAqB,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,KACnD,IAAI,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;AAEhC,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,CAAC,UAAU,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,GAAG,SAAS,CAMpB;AAED,wBAAgB,kBAAkB,CAAC,MAAM,SAAS,MAAM,YAAY,EAClE,OAAO,EAAE,qBAAqB,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,EACtD,OAAO,CAAC,EAAE,mBAAmB,CAAC,MAAM,CAAC,GACpC,IAAI,CAAC,YAAY,EAAE,MAAM,CAAC,CAG5B;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,QAAQ,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd;AAED,wBAAsB,kBAAkB,CAAC,OAAO,EAAE;IAChD,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IA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AO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC,UAAU,CAAC;IAC/B,YAAY,CAAC,EAAE,mBAAmB,CAAC;CACpC,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAqG3B;AAaD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE9D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG;IACnD,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAYA"}
package/dist/linear.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { parseJson } from "./value.js";
1
2
  import { AuthenticationLinearError, ForbiddenLinearError, LinearClient, RatelimitedLinearError, } from "@linear/sdk";
2
3
  import { CodexSecurityError, errorMessage } from "./errors.js";
3
4
  export function resolveLinearApiKey(environment, explicit) {
@@ -91,13 +92,7 @@ export async function importLinearIssues(options) {
91
92
  function linearIssueFilter(input) {
92
93
  if (input === undefined)
93
94
  return {};
94
- let filter;
95
- try {
96
- filter = JSON.parse(input);
97
- }
98
- catch {
99
- filter = null;
100
- }
95
+ const filter = parseJson(() => input);
101
96
  if (typeof filter === "object" && filter !== null && !Array.isArray(filter)) {
102
97
  return filter;
103
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"linear.js","sourceRoot":"","sources":["../src/linear.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,YAAY,EACZ,sBAAsB,GACvB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQ/D,MAAM,UAAU,mBAAmB,CACjC,WAA8B,EAC9B,QAAiB;IAEjB,OAAO,CACL,QAAQ,EAAE,IAAI,EAAE;QAChB,WAAW,CAAC,+BAA+B,CAAC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Y;QAC7B,KAAK,KAAK,IAAI;QACd,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,EACnC,CAAC;QACD,MAAM,IAAI,kBAAkB,CAAC,8BAA8B,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC,CAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAE,CAAC,WAAW,EAAE,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["import {\n AuthenticationLinearError,\n ForbiddenLinearError,\n LinearClient,\n RatelimitedLinearError,\n} from \"@linear/sdk\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\n\nexport type LinearClientFactory<\n Method extends keyof LinearClient = \"issue\" | \"projects\",\n> = (\n options: ConstructorParameters<typeof LinearClient>[0],\n) => Pick<LinearClient, Method>;\n\nexport function resolveLinearApiKey(\n environment: NodeJS.ProcessEnv,\n explicit?: string,\n): string | undefined {\n return (\n explicit?.trim() ||\n environment[\"CODEX_SECURITY_LINEAR_API_KEY\"]?.trim() ||\n undefined\n );\n}\n\nexport function createLinearClient<Method extends keyof LinearClient>(\n options: ConstructorParameters<typeof LinearClient>[0],\n factory?: LinearClientFactory<Method>,\n): Pick<LinearClient, Method> {\n const configuration = { ...options, redirect: \"error\" as const };\n return factory ? factory(configuration) : new LinearClient(configuration);\n}\n\nexport interface ImportedIssue {\n source: \"linear\";\n id: string;\n url: string;\n text: string;\n}\n\nexport async function importLinearIssues(options: {\n issues: readonly string[];\n project?: string;\n filter?: string;\n apiKey?: string;\n environment: NodeJS.ProcessEnv;\n linearClient?: LinearClientFactory;\n}): Promise<ImportedIssue[]> {\n const apiKey =\n resolveLinearApiKey(options.environment, options.apiKey) ||\n options.environment[\"LINEAR_API_KEY\"]?.trim();\n const accessToken = options.environment[\"LINEAR_ACCESS_TOKEN\"]?.trim();\n const credential = apiKey || accessToken;\n if (!credential) {\n throw new CodexSecurityError(\n \"Linear access requires CODEX_SECURITY_LINEAR_API_KEY, LINEAR_API_KEY, or LINEAR_ACCESS_TOKEN.\",\n );\n }\n\n const client = createLinearClient(\n apiKey ? { apiKey } : { accessToken },\n options.linearClient,\n );\n\n try {\n const issues: Awaited<ReturnType<LinearClient[\"issue\"]>>[] = [];\n if (options.project !== undefined) {\n const suppliedFilter = linearIssueFilter(options.filter);\n const filter = Object.hasOwn(suppliedFilter, \"state\")\n ? suppliedFilter\n : {\n state: { type: { nin: [\"completed\", \"canceled\"] } },\n ...suppliedFilter,\n };\n const projects = await client.projects({\n filter: { name: { eqIgnoreCase: options.project } },\n first: 2,\n });\n if (projects.nodes.length !== 1) {\n throw new CodexSecurityError(\n `Linear project \"${options.project}\" ${projects.nodes.length === 0 ? \"was not found or is not accessible\" : \"is ambiguous\"}.`,\n );\n }\n\n const page = await projects.nodes[0]!.issues({ first: 50, filter });\n while (page.pageInfo.hasNextPage) await page.fetchNext();\n issues.push(...page.nodes);\n if (issues.length === 0) {\n throw new CodexSecurityError(\n `No open Linear issues matched project \"${options.project}\" and its filter.`,\n );\n }\n } else {\n for (const input of options.issues) {\n const { id, workspace } = linearIssueReference(input);\n const issue = await client.issue(id);\n if (!issue) {\n throw new CodexSecurityError(\n `Linear issue \"${id}\" was not found or is not accessible.`,\n );\n }\n if (\n workspace !== undefined &&\n linearIssueReference(issue.url).workspace !== workspace\n ) {\n throw new CodexSecurityError(\n \"Fetched Linear issue does not match the workspace in the selected URL.\",\n );\n }\n issues.push(issue);\n }\n }\n\n const imports: ImportedIssue[] = [];\n for (const issue of issues) {\n const comments = await issue.comments({ first: 50 });\n while (comments.pageInfo.hasNextPage) await comments.fetchNext();\n imports.push({\n source: \"linear\",\n id: issue.identifier,\n url: issue.url,\n text: [\n `Title: ${issue.title}`,\n `<description>\\n${issue.description ?? \"\"}\\n</description>`,\n ...comments.nodes.map(\n ({ url, body }) => `<comment>\\nURL: ${url}\\n\\n${body}\\n</comment>`,\n ),\n ].join(\"\\n\\n\"),\n });\n }\n return imports;\n } catch (error) {\n if (error instanceof CodexSecurityError) throw error;\n if (\n error instanceof AuthenticationLinearError ||\n error instanceof ForbiddenLinearError\n ) {\n throw new CodexSecurityError(\"Linear authentication failed.\");\n }\n if (error instanceof RatelimitedLinearError) {\n throw new CodexSecurityError(\n \"Linear request was rate limited. Wait and retry.\",\n );\n }\n throw new CodexSecurityError(\n `Linear request failed: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction linearIssueFilter(input: string | undefined): JsonObject {\n if (input === undefined) return {};\n let filter: unknown;\n try {\n filter = JSON.parse(input);\n } catch {\n filter = null;\n }\n if (typeof filter === \"object\" && filter !== null && !Array.isArray(filter)) {\n return filter as JsonObject;\n }\n throw new CodexSecurityError(\n \"--linear-filter must be a JSON Linear issue filter.\",\n );\n}\n\nexport function isLinearIssueIdentifier(input: string): boolean {\n return /^[A-Za-z][A-Za-z0-9_-]*-\\d+$/u.test(input);\n}\n\nexport function linearIssueReference(input: string): {\n id: string;\n workspace?: string;\n} {\n if (!/^https?:\\/\\//iu.test(input)) return { id: input };\n const url = new URL(input);\n const match = /^\\/([^/]+)\\/issue\\/([^/]+)(?:\\/|$)/iu.exec(url.pathname);\n if (\n url.hostname !== \"linear.app\" ||\n match === null ||\n !isLinearIssueIdentifier(match[2]!)\n ) {\n throw new CodexSecurityError(\"Linear issue URL is invalid.\");\n }\n return { id: match[2]!, workspace: match[1]!.toLowerCase() };\n}\n"]}
1
+ {"version":3,"file":"linear.js","sourceRoot":"","sources":["../src/linear.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,YAAY,EACZ,sBAAsB,GACvB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQ/D,MAAM,UAAU,mBAAmB,CACjC,WAA8B,EAC9B,QAAiB;IAEjB,O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AAC,uBAAuB,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,EACnC,CAAC;QACD,MAAM,IAAI,kBAAkB,CAAC,8BAA8B,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC,CAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAE,CAAC,WAAW,EAAE,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["import { parseJson } from \"./value.js\";\nimport {\n AuthenticationLinearError,\n ForbiddenLinearError,\n LinearClient,\n RatelimitedLinearError,\n} from \"@linear/sdk\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\n\nexport type LinearClientFactory<\n Method extends keyof LinearClient = \"issue\" | \"projects\",\n> = (\n options: ConstructorParameters<typeof LinearClient>[0],\n) => Pick<LinearClient, Method>;\n\nexport function resolveLinearApiKey(\n environment: NodeJS.ProcessEnv,\n explicit?: string,\n): string | undefined {\n return (\n explicit?.trim() ||\n environment[\"CODEX_SECURITY_LINEAR_API_KEY\"]?.trim() ||\n undefined\n );\n}\n\nexport function createLinearClient<Method extends keyof LinearClient>(\n options: ConstructorParameters<typeof LinearClient>[0],\n factory?: LinearClientFactory<Method>,\n): Pick<LinearClient, Method> {\n const configuration = { ...options, redirect: \"error\" as const };\n return factory ? factory(configuration) : new LinearClient(configuration);\n}\n\nexport interface ImportedIssue {\n source: \"linear\";\n id: string;\n url: string;\n text: string;\n}\n\nexport async function importLinearIssues(options: {\n issues: readonly string[];\n project?: string;\n filter?: string;\n apiKey?: string;\n environment: NodeJS.ProcessEnv;\n linearClient?: LinearClientFactory;\n}): Promise<ImportedIssue[]> {\n const apiKey =\n resolveLinearApiKey(options.environment, options.apiKey) ||\n options.environment[\"LINEAR_API_KEY\"]?.trim();\n const accessToken = options.environment[\"LINEAR_ACCESS_TOKEN\"]?.trim();\n const credential = apiKey || accessToken;\n if (!credential) {\n throw new CodexSecurityError(\n \"Linear access requires CODEX_SECURITY_LINEAR_API_KEY, LINEAR_API_KEY, or LINEAR_ACCESS_TOKEN.\",\n );\n }\n\n const client = createLinearClient(\n apiKey ? { apiKey } : { accessToken },\n options.linearClient,\n );\n\n try {\n const issues: Awaited<ReturnType<LinearClient[\"issue\"]>>[] = [];\n if (options.project !== undefined) {\n const suppliedFilter = linearIssueFilter(options.filter);\n const filter = Object.hasOwn(suppliedFilter, \"state\")\n ? suppliedFilter\n : {\n state: { type: { nin: [\"completed\", \"canceled\"] } },\n ...suppliedFilter,\n };\n const projects = await client.projects({\n filter: { name: { eqIgnoreCase: options.project } },\n first: 2,\n });\n if (projects.nodes.length !== 1) {\n throw new CodexSecurityError(\n `Linear project \"${options.project}\" ${projects.nodes.length === 0 ? \"was not found or is not accessible\" : \"is ambiguous\"}.`,\n );\n }\n\n const page = await projects.nodes[0]!.issues({ first: 50, filter });\n while (page.pageInfo.hasNextPage) await page.fetchNext();\n issues.push(...page.nodes);\n if (issues.length === 0) {\n throw new CodexSecurityError(\n `No open Linear issues matched project \"${options.project}\" and its filter.`,\n );\n }\n } else {\n for (const input of options.issues) {\n const { id, workspace } = linearIssueReference(input);\n const issue = await client.issue(id);\n if (!issue) {\n throw new CodexSecurityError(\n `Linear issue \"${id}\" was not found or is not accessible.`,\n );\n }\n if (\n workspace !== undefined &&\n linearIssueReference(issue.url).workspace !== workspace\n ) {\n throw new CodexSecurityError(\n \"Fetched Linear issue does not match the workspace in the selected URL.\",\n );\n }\n issues.push(issue);\n }\n }\n\n const imports: ImportedIssue[] = [];\n for (const issue of issues) {\n const comments = await issue.comments({ first: 50 });\n while (comments.pageInfo.hasNextPage) await comments.fetchNext();\n imports.push({\n source: \"linear\",\n id: issue.identifier,\n url: issue.url,\n text: [\n `Title: ${issue.title}`,\n `<description>\\n${issue.description ?? \"\"}\\n</description>`,\n ...comments.nodes.map(\n ({ url, body }) => `<comment>\\nURL: ${url}\\n\\n${body}\\n</comment>`,\n ),\n ].join(\"\\n\\n\"),\n });\n }\n return imports;\n } catch (error) {\n if (error instanceof CodexSecurityError) throw error;\n if (\n error instanceof AuthenticationLinearError ||\n error instanceof ForbiddenLinearError\n ) {\n throw new CodexSecurityError(\"Linear authentication failed.\");\n }\n if (error instanceof RatelimitedLinearError) {\n throw new CodexSecurityError(\n \"Linear request was rate limited. Wait and retry.\",\n );\n }\n throw new CodexSecurityError(\n `Linear request failed: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction linearIssueFilter(input: string | undefined): JsonObject {\n if (input === undefined) return {};\n const filter = parseJson(() => input);\n if (typeof filter === \"object\" && filter !== null && !Array.isArray(filter)) {\n return filter as JsonObject;\n }\n throw new CodexSecurityError(\n \"--linear-filter must be a JSON Linear issue filter.\",\n );\n}\n\nexport function isLinearIssueIdentifier(input: string): boolean {\n return /^[A-Za-z][A-Za-z0-9_-]*-\\d+$/u.test(input);\n}\n\nexport function linearIssueReference(input: string): {\n id: string;\n workspace?: string;\n} {\n if (!/^https?:\\/\\//iu.test(input)) return { id: input };\n const url = new URL(input);\n const match = /^\\/([^/]+)\\/issue\\/([^/]+)(?:\\/|$)/iu.exec(url.pathname);\n if (\n url.hostname !== \"linear.app\" ||\n match === null ||\n !isLinearIssueIdentifier(match[2]!)\n ) {\n throw new CodexSecurityError(\"Linear issue URL is invalid.\");\n }\n return { id: match[2]!, workspace: match[1]!.toLowerCase() };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mock-scan.d.ts","sourceRoot":"","sources":["../src/mock-scan.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAuMrD,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,gBAAgB,EACxB,YAAY,EAAE,UAAU,EACxB,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,IAAI,CAAC,CA0Df"}
1
+ {"version":3,"file":"mock-scan.d.ts","sourceRoot":"","sources":["../src/mock-scan.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AA6LrD,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,gBAAgB,EACxB,YAAY,EAAE,UAAU,EACxB,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,IAAI,CAAC,CAyDf"}
package/dist/mock-scan.js CHANGED
@@ -186,7 +186,6 @@ export async function writeMockScanDraft(scanDir, scanId, target, registration,
186
186
  },
187
187
  "findings.json": { findings: mockFindings(scanId) },
188
188
  "coverage.json": {
189
- completeness: "complete",
190
189
  inventoryStrategy: target.kind === "paths"
191
190
  ? "scoped_path"
192
191
  : target.kind === "repository"
@@ -1 +1 @@
1
- {"version":3,"file":"mock-scan.js","sourceRoot":"","sources":["../src/mock-scan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAoBjC,mFAAmF;AACnF,MAAM,QAAQ,GAA2B;IACvC;QACE,EAAE,EAAE,mBAAmB;QACvB,KAAK,EAAE,yCAAyC;QAChD,QAAQ,EAAE,UAAU;QACpB,GAAG,EAAE,QAAQ;QACb,OAAO,EACL,6IAA6I;QAC/I,IAAI,EAAE,sDAAsD;QAC5D,WAAW,EACT,yFAAyF;KAC5F;IACD;QACE,EAAE,EAAE,gBAAgB;QACpB,KAAK,EAAE,gDAAgD;QACvD,QAAQ,EAAE,MAAM;QAChB,GAAG,EAAE,QAAQ;QACb,OAAO,EACL,kLAAkL;QACpL,IAAI,EAAE,qEAAqE;QAC3E,WAA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AAW,CAAC;iBAC3B;gBACD,UAAU,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;aAC3B;SACF;QACD,eAAe,EAAE,EAAE,QAAQ,EAAE,YAAY,CAAC,MAAM,CAAC,EAAE;QACnD,eAAe,EAAE;YACf,YAAY,EAAE,UAAU;YACxB,iBAAiB,EACf,MAAM,CAAC,IAAI,KAAK,OAAO;gBACrB,CAAC,CAAC,aAAa;gBACf,CAAC,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY;oBAC5B,CAAC,CAAC,YAAY;oBACd,CAAC,CAAC,MAAM;YACd,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;gBACnC,EAAE,EAAE,QAAQ,OAAO,CAAC,EAAE,EAAE;gBACxB,KAAK,EAAE,UAAU,OAAO,CAAC,KAAK,EAAE;gBAChC,WAAW,EAAE,UAAU;gBACvB,WAAW,EAAE,EAAE;gBACf,KAAK,EAAE,WAAW;aACnB,CAAC,CAAC;YACH,kBAAkB,EAAE,EAAE;YACtB,QAAQ,EAAE,EAAE;SACb;KACF,CAAC;IACF,KAAK,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QACzD,MAAM,SAAS,CACb,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EACnB,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EACxC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,CACvB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport { createHash } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport type { JsonObject } from \"./config.js\";\nimport type { Finding, SeverityLevel } from \"./models.js\";\nimport type { NormalizedTarget } from \"./targets.js\";\n\ntype DraftFinding = Omit<\n Finding,\n \"findingId\" | \"occurrenceId\" | \"fingerprints\"\n>;\n\ninterface MockFinding {\n id: string;\n title: string;\n severity: SeverityLevel;\n cwe: string;\n summary: string;\n code: string;\n remediation: string;\n}\n\n// Entirely synthetic examples; the paths and snippets do not come from the target.\nconst EXAMPLES: readonly MockFinding[] = [\n {\n id: \"command-injection\",\n title: \"Export filename reaches a shell command\",\n severity: \"critical\",\n cwe: \"CWE-78\",\n summary:\n \"The example export route interpolates an untrusted filename into a shell command, allowing shell metacharacters to execute another command.\",\n code: \"exec(`convert ${request.body.filename} output.pdf`);\",\n remediation:\n \"Pass the filename as a separate argument to a process API that does not invoke a shell.\",\n },\n {\n id: \"path-traversal\",\n title: \"Archive entry escapes the extraction directory\",\n severity: \"high\",\n cwe: \"CWE-22\",\n summary:\n \"The example archive extractor writes a supplied entry name without checking containment, allowing a parent-directory entry to overwrite a file outside the extraction directory.\",\n code: \"await writeFile(join(outputDirectory, entry.name), entry.contents);\",\n remediation:\n \"Resolve each entry destination and reject paths outside the extraction directory before writing.\",\n },\n {\n id: \"missing-authorization\",\n title: \"Document download omits the ownership check\",\n severity: \"high\",\n cwe: \"CWE-862\",\n summary:\n \"The example download handler accepts a document ID from any signed-in account and returns the document without checking that the account owns it.\",\n code: \"response.json(await documents.findById(request.params.id));\",\n remediation:\n \"Restrict document lookup to records the authenticated account is authorized to read.\",\n },\n {\n id: \"stored-xss\",\n title: \"Comment preview renders stored HTML\",\n severity: \"medium\",\n cwe: \"CWE-79\",\n summary:\n \"The example preview inserts a stored comment directly into HTML, allowing a comment author to execute script in another viewer's browser.\",\n code: \"preview.innerHTML = comment.body;\",\n remediation:\n \"Render comments as text or sanitize intentionally supported HTML before insertion.\",\n },\n {\n id: \"verbose-errors\",\n title: \"Error response exposes an internal stack trace\",\n severity: \"low\",\n cwe: \"CWE-209\",\n summary:\n \"The example error handler returns a stack trace to a remote caller, revealing internal module names and filesystem layout.\",\n code: \"response.status(500).send(error.stack);\",\n remediation:\n \"Return a generic error identifier and retain diagnostic details in internal logs.\",\n },\n {\n id: \"version-disclosure\",\n title: \"Response header advertises the framework version\",\n severity: \"informational\",\n cwe: \"CWE-200\",\n summary:\n \"The example response header exposes the precise framework version. This helps fingerprint the service but does not establish an exploitable vulnerability.\",\n code: 'response.setHeader(\"X-Example-Version\", frameworkVersion);',\n remediation: \"Omit the framework version from public response headers.\",\n },\n {\n id: \"sql-injection\",\n title: \"Search term is concatenated into a SQL query\",\n severity: \"high\",\n cwe: \"CWE-89\",\n summary:\n \"The example search handler concatenates request text into SQL, allowing a caller to change the query and read records beyond the intended search.\",\n code: \"db.query(`SELECT * FROM items WHERE name = '${request.query.name}'`);\",\n remediation: \"Use a parameterized query for the search term.\",\n },\n {\n id: \"ssrf\",\n title: \"Image proxy fetches arbitrary destinations\",\n severity: \"medium\",\n cwe: \"CWE-918\",\n summary:\n \"The example image proxy fetches a caller-supplied URL without restricting its destination, allowing requests to internal services reachable by the proxy.\",\n code: \"return await fetch(request.query.imageUrl);\",\n remediation:\n \"Restrict fetch destinations to the intended image hosts and enforce that policy across redirects.\",\n },\n {\n id: \"open-redirect\",\n title: \"Sign-in callback accepts an external redirect\",\n severity: \"medium\",\n cwe: \"CWE-601\",\n summary:\n \"The example sign-in callback redirects to a supplied URL without checking its origin, allowing an attacker to send users from the sign-in flow to an unrelated site.\",\n code: \"response.redirect(request.query.returnTo);\",\n remediation:\n \"Accept only application-relative return paths or explicitly permitted origins.\",\n },\n {\n id: \"cookie-flags\",\n title: \"Session cookie omits HttpOnly\",\n severity: \"low\",\n cwe: \"CWE-1004\",\n summary:\n \"The example session cookie is accessible to browser scripts because HttpOnly is absent, increasing the impact of a separate script-injection vulnerability.\",\n code: 'response.cookie(\"session\", sessionId, { secure: true });',\n remediation: \"Set HttpOnly on the session cookie.\",\n },\n];\n\nfunction mockFindings(scanId: string): DraftFinding[] {\n const findings = EXAMPLES.map((example, index): DraftFinding => {\n const unique = index >= 6;\n const path = `mock/${example.id}${unique ? `-${scanId}` : \"\"}.ts`;\n return {\n ruleId: `mock.${example.id}`,\n identity: { anchor: example.id, ...(unique ? { instance: scanId } : {}) },\n title: `[Mock] ${example.title}`,\n summary: `Synthetic test finding. ${example.summary}`,\n severity: { level: example.severity },\n confidence: {\n level: \"high\",\n rationale:\n \"Deterministic fixture; not a conclusion about the scanned repository.\",\n },\n taxonomy: { category: example.id, cwe: [example.cwe] },\n locations: [{ path, startLine: 10, endLine: 10, role: \"sink\" }],\n codeEvidence: [\n {\n id: \"example-sink\",\n label: \"Synthetic vulnerable operation\",\n path,\n startLine: 10,\n language: \"typescript\",\n role: \"sink\",\n code: example.code,\n explanation:\n \"Illustrative fixture code; this file is not read from or written to the repository.\",\n },\n ],\n rootCause: { summary: example.summary, evidenceRefs: [\"example-sink\"] },\n remediation: example.remediation,\n validation: {\n status: \"mock\",\n method: \"synthetic\",\n summary: \"Fixture only; no code was analyzed or executed.\",\n },\n attackPath: {\n summary: example.summary,\n assumptions: [\n \"The fictional example exposes this operation to untrusted input.\",\n ],\n evidenceRefs: [\"example-sink\"],\n },\n remediationTests: [\n `In the example application, verify the fix: ${example.remediation}`,\n ],\n preventiveControls: [example.remediation],\n provenance: { source: \"mock\" },\n extensions: {\n mock: true,\n mockGroup: example.id,\n mockRecurrence: unique ? \"unique\" : \"shared\",\n },\n };\n });\n // Alternate reports have distinct identities but describe the same root causes.\n for (const [index, title] of [\n [0, \"Shell metacharacters in the export name execute commands\"],\n [1, \"Parent-directory archive names overwrite files outside extraction\"],\n ] as const) {\n const original = findings[index]!;\n findings.push({\n ...structuredClone(original),\n identity: { anchor: `${EXAMPLES[index]!.id}-alternate-report` },\n title: `[Mock] ${title}`,\n });\n }\n return findings;\n}\n\nexport async function writeMockScanDraft(\n scanDir: string,\n scanId: string,\n target: NormalizedTarget,\n registration: JsonObject,\n signal: AbortSignal,\n): Promise<void> {\n const contract = registration[\"contract\"] as {\n target: { allowedKinds: string[] };\n diffTarget?: {\n kind: string;\n baseRevision: string;\n headRevision: string;\n } | null;\n };\n const diff = contract.diffTarget;\n const snapshotDigest =\n diff && diff.kind !== \"working_tree\"\n ? `codex-security-snapshot/v1:sha256:${createHash(\"sha256\").update([\"codex-security-diff/v1\", diff.kind, diff.baseRevision, diff.headRevision].join(\"\\0\")).digest(\"hex\")}`\n : undefined;\n const description =\n \"Synthetic mock scan for testing. No LLM calls or security analysis were performed. Locations and code snippets describe fictional examples.\";\n const documents = {\n \"scan-manifest.json\": {\n scan: {\n target: {\n kind: contract.target.allowedKinds[0],\n ...(snapshotDigest === undefined ? {} : { snapshotDigest }),\n },\n scope: {\n summary: description,\n runtimeStatus: \"mock\",\n limitations: [description],\n },\n extensions: { mock: true },\n },\n },\n \"findings.json\": { findings: mockFindings(scanId) },\n \"coverage.json\": {\n completeness: \"complete\",\n inventoryStrategy:\n target.kind === \"paths\"\n ? \"scoped_path\"\n : target.kind === \"repository\"\n ? \"repository\"\n : \"diff\",\n surfaces: EXAMPLES.map((example) => ({\n id: `mock-${example.id}`,\n label: `[Mock] ${example.title}`,\n disposition: \"reported\",\n receiptRefs: [],\n notes: description,\n })),\n explicitExclusions: [],\n deferred: [],\n },\n };\n for (const [name, document] of Object.entries(documents)) {\n await writeFile(\n join(scanDir, name),\n `${JSON.stringify(document, null, 2)}\\n`,\n { flag: \"wx\", signal },\n );\n }\n}\n"]}
1
+ {"version":3,"file":"mock-scan.js","sourceRoot":"","sources":["../src/mock-scan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAUjC,mFAAmF;AACnF,MAAM,QAAQ,GAAG;IACf;QACE,EAAE,EAAE,mBAAmB;QACvB,KAAK,EAAE,yCAAyC;QAChD,QAAQ,EAAE,UAAU;QACpB,GAAG,EAAE,QAAQ;QACb,OAAO,EACL,6IAA6I;QAC/I,IAAI,EAAE,sDAAsD;QAC5D,WAAW,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"node:crypto\";\nimport { join } from \"node:path\";\nimport type { JsonObject } from \"./config.js\";\nimport type { Finding } from \"./models.js\";\nimport type { NormalizedTarget } from \"./targets.js\";\n\ntype DraftFinding = Omit<\n Finding,\n \"findingId\" | \"occurrenceId\" | \"fingerprints\"\n>;\n\n// Entirely synthetic examples; the paths and snippets do not come from the target.\nconst EXAMPLES = [\n {\n id: \"command-injection\",\n title: \"Export filename reaches a shell command\",\n severity: \"critical\",\n cwe: \"CWE-78\",\n summary:\n \"The example export route interpolates an untrusted filename into a shell command, allowing shell metacharacters to execute another command.\",\n code: \"exec(`convert ${request.body.filename} output.pdf`);\",\n remediation:\n \"Pass the filename as a separate argument to a process API that does not invoke a shell.\",\n },\n {\n id: \"path-traversal\",\n title: \"Archive entry escapes the extraction directory\",\n severity: \"high\",\n cwe: \"CWE-22\",\n summary:\n \"The example archive extractor writes a supplied entry name without checking containment, allowing a parent-directory entry to overwrite a file outside the extraction directory.\",\n code: \"await writeFile(join(outputDirectory, entry.name), entry.contents);\",\n remediation:\n \"Resolve each entry destination and reject paths outside the extraction directory before writing.\",\n },\n {\n id: \"missing-authorization\",\n title: \"Document download omits the ownership check\",\n severity: \"high\",\n cwe: \"CWE-862\",\n summary:\n \"The example download handler accepts a document ID from any signed-in account and returns the document without checking that the account owns it.\",\n code: \"response.json(await documents.findById(request.params.id));\",\n remediation:\n \"Restrict document lookup to records the authenticated account is authorized to read.\",\n },\n {\n id: \"stored-xss\",\n title: \"Comment preview renders stored HTML\",\n severity: \"medium\",\n cwe: \"CWE-79\",\n summary:\n \"The example preview inserts a stored comment directly into HTML, allowing a comment author to execute script in another viewer's browser.\",\n code: \"preview.innerHTML = comment.body;\",\n remediation:\n \"Render comments as text or sanitize intentionally supported HTML before insertion.\",\n },\n {\n id: \"verbose-errors\",\n title: \"Error response exposes an internal stack trace\",\n severity: \"low\",\n cwe: \"CWE-209\",\n summary:\n \"The example error handler returns a stack trace to a remote caller, revealing internal module names and filesystem layout.\",\n code: \"response.status(500).send(error.stack);\",\n remediation:\n \"Return a generic error identifier and retain diagnostic details in internal logs.\",\n },\n {\n id: \"version-disclosure\",\n title: \"Response header advertises the framework version\",\n severity: \"informational\",\n cwe: \"CWE-200\",\n summary:\n \"The example response header exposes the precise framework version. This helps fingerprint the service but does not establish an exploitable vulnerability.\",\n code: 'response.setHeader(\"X-Example-Version\", frameworkVersion);',\n remediation: \"Omit the framework version from public response headers.\",\n },\n {\n id: \"sql-injection\",\n title: \"Search term is concatenated into a SQL query\",\n severity: \"high\",\n cwe: \"CWE-89\",\n summary:\n \"The example search handler concatenates request text into SQL, allowing a caller to change the query and read records beyond the intended search.\",\n code: \"db.query(`SELECT * FROM items WHERE name = '${request.query.name}'`);\",\n remediation: \"Use a parameterized query for the search term.\",\n },\n {\n id: \"ssrf\",\n title: \"Image proxy fetches arbitrary destinations\",\n severity: \"medium\",\n cwe: \"CWE-918\",\n summary:\n \"The example image proxy fetches a caller-supplied URL without restricting its destination, allowing requests to internal services reachable by the proxy.\",\n code: \"return await fetch(request.query.imageUrl);\",\n remediation:\n \"Restrict fetch destinations to the intended image hosts and enforce that policy across redirects.\",\n },\n {\n id: \"open-redirect\",\n title: \"Sign-in callback accepts an external redirect\",\n severity: \"medium\",\n cwe: \"CWE-601\",\n summary:\n \"The example sign-in callback redirects to a supplied URL without checking its origin, allowing an attacker to send users from the sign-in flow to an unrelated site.\",\n code: \"response.redirect(request.query.returnTo);\",\n remediation:\n \"Accept only application-relative return paths or explicitly permitted origins.\",\n },\n {\n id: \"cookie-flags\",\n title: \"Session cookie omits HttpOnly\",\n severity: \"low\",\n cwe: \"CWE-1004\",\n summary:\n \"The example session cookie is accessible to browser scripts because HttpOnly is absent, increasing the impact of a separate script-injection vulnerability.\",\n code: 'response.cookie(\"session\", sessionId, { secure: true });',\n remediation: \"Set HttpOnly on the session cookie.\",\n },\n] as const;\n\nfunction mockFindings(scanId: string): DraftFinding[] {\n const findings = EXAMPLES.map((example, index): DraftFinding => {\n const unique = index >= 6;\n const path = `mock/${example.id}${unique ? `-${scanId}` : \"\"}.ts`;\n return {\n ruleId: `mock.${example.id}`,\n identity: { anchor: example.id, ...(unique ? { instance: scanId } : {}) },\n title: `[Mock] ${example.title}`,\n summary: `Synthetic test finding. ${example.summary}`,\n severity: { level: example.severity },\n confidence: {\n level: \"high\",\n rationale:\n \"Deterministic fixture; not a conclusion about the scanned repository.\",\n },\n taxonomy: { category: example.id, cwe: [example.cwe] },\n locations: [{ path, startLine: 10, endLine: 10, role: \"sink\" }],\n codeEvidence: [\n {\n id: \"example-sink\",\n label: \"Synthetic vulnerable operation\",\n path,\n startLine: 10,\n language: \"typescript\",\n role: \"sink\",\n code: example.code,\n explanation:\n \"Illustrative fixture code; this file is not read from or written to the repository.\",\n },\n ],\n rootCause: { summary: example.summary, evidenceRefs: [\"example-sink\"] },\n remediation: example.remediation,\n validation: {\n status: \"mock\",\n method: \"synthetic\",\n summary: \"Fixture only; no code was analyzed or executed.\",\n },\n attackPath: {\n summary: example.summary,\n assumptions: [\n \"The fictional example exposes this operation to untrusted input.\",\n ],\n evidenceRefs: [\"example-sink\"],\n },\n remediationTests: [\n `In the example application, verify the fix: ${example.remediation}`,\n ],\n preventiveControls: [example.remediation],\n provenance: { source: \"mock\" },\n extensions: {\n mock: true,\n mockGroup: example.id,\n mockRecurrence: unique ? \"unique\" : \"shared\",\n },\n };\n });\n // Alternate reports have distinct identities but describe the same root causes.\n for (const [index, title] of [\n [0, \"Shell metacharacters in the export name execute commands\"],\n [1, \"Parent-directory archive names overwrite files outside extraction\"],\n ] as const) {\n const original = findings[index]!;\n findings.push({\n ...structuredClone(original),\n identity: { anchor: `${EXAMPLES[index]!.id}-alternate-report` },\n title: `[Mock] ${title}`,\n });\n }\n return findings;\n}\n\nexport async function writeMockScanDraft(\n scanDir: string,\n scanId: string,\n target: NormalizedTarget,\n registration: JsonObject,\n signal: AbortSignal,\n): Promise<void> {\n const contract = registration[\"contract\"] as {\n target: { allowedKinds: string[] };\n diffTarget?: {\n kind: string;\n baseRevision: string;\n headRevision: string;\n } | null;\n };\n const diff = contract.diffTarget;\n const snapshotDigest =\n diff && diff.kind !== \"working_tree\"\n ? `codex-security-snapshot/v1:sha256:${createHash(\"sha256\").update([\"codex-security-diff/v1\", diff.kind, diff.baseRevision, diff.headRevision].join(\"\\0\")).digest(\"hex\")}`\n : undefined;\n const description =\n \"Synthetic mock scan for testing. No LLM calls or security analysis were performed. Locations and code snippets describe fictional examples.\";\n const documents = {\n \"scan-manifest.json\": {\n scan: {\n target: {\n kind: contract.target.allowedKinds[0],\n ...(snapshotDigest === undefined ? {} : { snapshotDigest }),\n },\n scope: {\n summary: description,\n runtimeStatus: \"mock\",\n limitations: [description],\n },\n extensions: { mock: true },\n },\n },\n \"findings.json\": { findings: mockFindings(scanId) },\n \"coverage.json\": {\n inventoryStrategy:\n target.kind === \"paths\"\n ? \"scoped_path\"\n : target.kind === \"repository\"\n ? \"repository\"\n : \"diff\",\n surfaces: EXAMPLES.map((example) => ({\n id: `mock-${example.id}`,\n label: `[Mock] ${example.title}`,\n disposition: \"reported\",\n receiptRefs: [],\n notes: description,\n })),\n explicitExclusions: [],\n deferred: [],\n },\n };\n for (const [name, document] of Object.entries(documents)) {\n await writeFile(\n join(scanDir, name),\n `${JSON.stringify(document, null, 2)}\\n`,\n { flag: \"wx\", signal },\n );\n }\n}\n"]}