@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
@@ -58,7 +58,7 @@ export declare function runArtifactHelper(args: readonly string[], options?: Hel
58
58
  export declare function writeThreatModel(directory: string, options?: HelperOptions): Promise<string>;
59
59
  /** Read the current document path without making an optional projection required. */
60
60
  export declare function readThreatModelPath(directory: string, options?: HelperOptions): Promise<string | null>;
61
- export declare function runArtifactExport(arguments_: ArtifactExportArguments, output?: ArtifactOutput): Promise<Uint8Array | undefined>;
61
+ export declare function runArtifactExport(arguments_: ArtifactExportArguments, output?: ArtifactOutput): Promise<string | undefined>;
62
62
  export declare function resolveArtifactExportOutput(arguments_: ArtifactExportArguments, currentDirectory: string): Promise<ArtifactExportArguments>;
63
63
  /** Resolve saved artifacts after the workbench validates their recorded identity. */
64
64
  export declare function resolveSavedArtifactDirectory(scanId: string, artifact: ExportArtifactKind, format: ExportFormat, workbench: (args: readonly string[]) => Promise<JsonObject>): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-export.d.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chArgs } from "./workbench-arguments.js";
1
2
  import { spawn } from "node:child_process";
2
- import { realpath } from "node:fs/promises";
3
+ import { lstat, realpath } from "node:fs/promises";
3
4
  import { basename, dirname, join, relative, resolve } from "node:path";
4
5
  import { Writable as NodeWritable } from "node:stream";
5
6
  import { pipeline } from "node:stream/promises";
@@ -34,6 +35,7 @@ export async function runArtifactHelper(args, options = {}) {
34
35
  "-I",
35
36
  "-X",
36
37
  "utf8",
38
+ "-B",
37
39
  join(plugin, "scripts", "finalize_scan_contract.py"),
38
40
  ...args,
39
41
  ], {
@@ -120,7 +122,7 @@ export async function runArtifactExport(arguments_, output) {
120
122
  });
121
123
  return (arguments_.output === "-" && output === undefined) ||
122
124
  arguments_.includeMetadata
123
- ? Buffer.from(result.stdout)
125
+ ? result.stdout
124
126
  : undefined;
125
127
  }
126
128
  export async function resolveArtifactExportOutput(arguments_, currentDirectory) {
@@ -143,10 +145,26 @@ export async function resolveArtifactExportOutput(arguments_, currentDirectory)
143
145
  }), basename(arguments_.output));
144
146
  if (arguments_.output !== "-") {
145
147
  const outputFromCurrent = relative(currentDirectory, arguments_.output);
146
- if (!isOutsidePath(outputFromCurrent)) {
148
+ if (outputFromCurrent !== "" && !isOutsidePath(outputFromCurrent)) {
149
+ let existingParent;
150
+ for (let directory = dirname(arguments_.output); relative(currentDirectory, directory) !== ""; directory = dirname(directory)) {
151
+ const metadata = await lstat(directory).catch((error) => {
152
+ if (error.code === "ENOENT")
153
+ return undefined;
154
+ throw error;
155
+ });
156
+ if (metadata?.isSymbolicLink()) {
157
+ throw new CodexSecurityError("The export output path cannot traverse a repository symlink.");
158
+ }
159
+ if (metadata !== undefined)
160
+ existingParent ??= directory;
161
+ }
147
162
  const canonicalCurrent = await realpath(currentDirectory).catch(() => currentDirectory);
148
- if (relative(resolve(canonicalCurrent, outputFromCurrent), outputPath) !==
149
- "") {
163
+ const expectedOutput = existingParent === undefined
164
+ ? resolve(canonicalCurrent, outputFromCurrent)
165
+ : resolve(await realpath(existingParent), relative(existingParent, arguments_.output));
166
+ if (isOutsidePath(relative(canonicalCurrent, outputPath)) ||
167
+ relative(expectedOutput, outputPath) !== "") {
150
168
  throw new CodexSecurityError("The export output path cannot traverse a repository symlink.");
151
169
  }
152
170
  }
@@ -157,16 +175,12 @@ export async function resolveArtifactExportOutput(arguments_, currentDirectory)
157
175
  export async function resolveSavedArtifactDirectory(scanId, artifact, format, workbench) {
158
176
  // Reuse the workbench's recorded digest and scan binding checks without
159
177
  // requiring a writable saved-scan directory for stdout or external exports.
160
- const context = await workbench([
161
- "export-findings",
162
- "--scan-id",
178
+ const context = await workbench(workbenchArgs("export-findings", {
163
179
  scanId,
164
- "--artifact",
165
180
  artifact,
166
- "--format",
167
181
  format,
168
- "--validate-only",
169
- ]);
182
+ validateOnly: true,
183
+ }));
170
184
  const scan = context["scan"];
171
185
  if (typeof scan?.["scanDir"] !== "string")
172
186
  throw new CodexSecurityError(`Artifacts for scan ${scanId} are unavailable.`);
@@ -214,7 +228,7 @@ export async function exportArtifact(options) {
214
228
  const metadata = await runArtifactExport(arguments_, options.output === "-" ? process.stdout : undefined);
215
229
  const description = metadata === undefined
216
230
  ? null
217
- : JSON.parse(Buffer.from(metadata).toString("utf8"));
231
+ : JSON.parse(metadata);
218
232
  return {
219
233
  path: arguments_.output === "-" ? null : arguments_.output,
220
234
  provenance: description?.provenance ?? null,
@@ -267,6 +281,7 @@ export function exportEnvironment(environment = process.env) {
267
281
  "TEMP",
268
282
  "TMPDIR",
269
283
  "PYTHON",
284
+ "XDG_CACHE_HOME",
270
285
  "LANG",
271
286
  "LC_ALL",
272
287
  "LC_CTYPE",
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-export.js","sourceRoot":"","sources":["../src/artifact-export.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,O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AW,CACZ,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,IAAI,MAAM,YAAY,YAAY,EAAE,CAAC;YACnC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,WAAW,GAAsB,OAAO,CAAC,GAAG;IAE5C,OAAO,qBAAqB,CAC1B,MAAM,CAAC,WAAW,CAChB;QACE,MAAM;QACN,MAAM;QACN,SAAS;QACT,YAAY;QACZ,YAAY;QACZ,QAAQ;QACR,KAAK;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,MAAM;QACN,QAAQ;QACR,UAAU;KACX;SACE,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;SAC/C,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CACzC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { realpath } from \"node:fs/promises\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { Writable as NodeWritable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type { ThreatModel } from \"./models.js\";\nimport { relativePathIsOutside as isOutsidePath } from \"./targets.js\";\nimport {\n bundledPluginRoot,\n codexSecurityStateDirectory,\n expandHome,\n pythonUtf8Environment,\n resolvePluginPython,\n runWorkbench,\n} from \"./runtime.js\";\n\nexport type ArtifactOutput = Pick<NodeJS.WriteStream, \"write\">;\n\nexport const ARTIFACT_EXPORT_FILENAMES = {\n csv: \"findings.csv\",\n json: \"findings.json\",\n sarif: \"results.sarif\",\n md: \"threatmodel.md\",\n} as const;\nexport type ExportFormat = keyof typeof ARTIFACT_EXPORT_FILENAMES;\nexport type ExportArtifactKind = \"findings\" | \"threat-model\";\n\nexport interface ArtifactExportArguments {\n scanDir: string;\n artifact?: ExportArtifactKind;\n format: ExportFormat;\n output: string;\n sourceRoot?: string;\n pythonPath?: string;\n signal?: AbortSignal;\n includeMetadata?: boolean;\n}\n\ninterface ThreatModelDescription {\n threatModel: ThreatModel | null;\n provenance: JsonObject;\n path: string | null;\n}\n\nexport type ExportArtifactOptions = {\n source:\n | { directory: string; scanId?: never }\n | { scanId: string; directory?: never };\n output: string;\n pythonPath?: string;\n signal?: AbortSignal;\n} & (\n | { artifact: \"threat-model\"; format?: \"md\"; sourceRoot?: never }\n | {\n artifact?: \"findings\";\n format?: \"csv\" | \"json\" | \"sarif\";\n sourceRoot?: string;\n }\n);\n\nexport interface ArtifactExportResult {\n path: string | null;\n provenance: JsonObject | null;\n}\n\ninterface HelperOptions {\n pythonPath?: string;\n protectedRoot?: string;\n pluginRoot?: string;\n signal?: AbortSignal;\n output?: ArtifactOutput;\n failureMessage?: string;\n}\n\nexport function resolveArtifactFormat(\n artifact: ExportArtifactKind,\n format?: ExportFormat,\n): ExportFormat {\n const selected = format ?? (artifact === \"threat-model\" ? \"md\" : \"sarif\");\n if ((artifact === \"threat-model\") !== (selected === \"md\")) {\n throw new CodexSecurityError(\n artifact === \"threat-model\"\n ? \"Threat-model exports only support --export-format md.\"\n : \"Findings exports support --export-format csv, json, or sarif.\",\n );\n }\n return selected;\n}\n\nexport async function runArtifactHelper(\n args: readonly string[],\n options: HelperOptions = {},\n): Promise<{ stdout: string; stderr: string }> {\n const environment = exportEnvironment();\n const python = await resolvePluginPython({\n configuredPath: options.pythonPath,\n environment,\n protectedRoot: options.protectedRoot,\n signal: options.signal,\n });\n const plugin = options.pluginRoot ?? (await bundledPluginRoot());\n const invocation = spawn(\n python,\n [\n \"-I\",\n \"-X\",\n \"utf8\",\n join(plugin, \"scripts\", \"finalize_scan_contract.py\"),\n ...args,\n ],\n {\n env: environment,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n signal: options.signal,\n },\n );\n let stderr = \"\";\n let stdout = \"\";\n invocation.stderr.setEncoding(\"utf8\");\n invocation.stderr.on(\"data\", (chunk: string) => {\n stderr = `${stderr}${chunk}`.slice(-64 * 1024);\n });\n const forwarded =\n options.output === undefined\n ? (async () => {\n invocation.stdout.setEncoding(\"utf8\");\n for await (const chunk of invocation.stdout) stdout += chunk;\n })()\n : writeArtifactOutput(options.output, invocation.stdout);\n let status: number;\n try {\n [status] = await Promise.all([\n new Promise<number>((resolve, reject) => {\n invocation.once(\"error\", reject);\n invocation.once(\"close\", (code, signal) =>\n resolve(signal === null ? (code ?? 1) : 1),\n );\n }),\n forwarded,\n ]);\n } catch (error) {\n invocation.stdout.destroy();\n invocation.kill();\n throw error;\n }\n if (status !== 0) {\n const detail = stderr.trim().split(\"\\n\").at(-1);\n throw new CodexSecurityError(\n detail?.replace(/^finalize_scan_contract\\.py: error: /, \"\") ||\n options.failureMessage ||\n \"Could not export Codex Security artifacts.\",\n );\n }\n return { stdout, stderr };\n}\n\nexport async function writeThreatModel(\n directory: string,\n options: HelperOptions = {},\n): Promise<string> {\n const result = await runArtifactHelper(\n [\"--scan-dir\", directory, \"--write-threat-model\"],\n options,\n );\n return result.stderr.trim().replace(/^codex-security: warning: /u, \"\");\n}\n\n/** Read the current document path without making an optional projection required. */\nexport async function readThreatModelPath(\n directory: string,\n options: HelperOptions = {},\n): Promise<string | null> {\n try {\n options.signal?.throwIfAborted();\n const result = await runArtifactHelper(\n [\"--scan-dir\", directory, \"--describe-threat-model\"],\n options,\n );\n return (JSON.parse(result.stdout) as ThreatModelDescription).path;\n } catch {\n options.signal?.throwIfAborted();\n return null;\n }\n}\n\nexport async function runArtifactExport(\n arguments_: ArtifactExportArguments,\n output?: ArtifactOutput,\n): Promise<Uint8Array | undefined> {\n const artifact = arguments_.artifact ?? \"findings\";\n resolveArtifactFormat(artifact, arguments_.format);\n const result = await runArtifactHelper(\n [\n \"--scan-dir\",\n arguments_.scanDir,\n ...(artifact === \"findings\" ? [] : [\"--export-artifact\", artifact]),\n \"--export-format\",\n arguments_.format,\n ...(arguments_.output === \"-\"\n ? []\n : [\"--export-output\", arguments_.output]),\n ...(arguments_.sourceRoot === undefined\n ? []\n : [\"--source-root\", arguments_.sourceRoot]),\n ...(arguments_.includeMetadata ? [\"--export-metadata\"] : []),\n ],\n {\n pythonPath: arguments_.pythonPath,\n signal: arguments_.signal,\n failureMessage:\n artifact === \"findings\"\n ? `Could not export Codex Security findings as ${arguments_.format.toUpperCase()}.`\n : \"Could not export the saved threat model as Markdown.\",\n ...(arguments_.output === \"-\" && output !== undefined ? { output } : {}),\n },\n );\n return (arguments_.output === \"-\" && output === undefined) ||\n arguments_.includeMetadata\n ? Buffer.from(result.stdout)\n : undefined;\n}\n\nexport async function resolveArtifactExportOutput(\n arguments_: ArtifactExportArguments,\n currentDirectory: string,\n): Promise<ArtifactExportArguments> {\n const canonicalScan = await realpath(arguments_.scanDir).catch(\n () => arguments_.scanDir,\n );\n const scanRelativeOutput = relative(arguments_.scanDir, arguments_.output);\n const scanLocalOutput = join(\n \"exports\",\n ARTIFACT_EXPORT_FILENAMES[arguments_.format],\n );\n if (\n arguments_.output !== \"-\" &&\n !isOutsidePath(scanRelativeOutput) &&\n scanRelativeOutput !== scanLocalOutput\n ) {\n throw new CodexSecurityError(\n \"The export output path cannot overwrite a scan artifact.\",\n );\n }\n const outputPath =\n arguments_.output === \"-\"\n ? \"-\"\n : !isOutsidePath(scanRelativeOutput)\n ? join(canonicalScan, scanRelativeOutput)\n : join(\n await realpath(dirname(arguments_.output)).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\")\n throw new CodexSecurityError(\n `Export output directory does not exist: ${dirname(arguments_.output)}. Create the directory and retry.`,\n );\n throw error;\n },\n ),\n basename(arguments_.output),\n );\n if (arguments_.output !== \"-\") {\n const outputFromCurrent = relative(currentDirectory, arguments_.output);\n if (!isOutsidePath(outputFromCurrent)) {\n const canonicalCurrent = await realpath(currentDirectory).catch(\n () => currentDirectory,\n );\n if (\n relative(resolve(canonicalCurrent, outputFromCurrent), outputPath) !==\n \"\"\n ) {\n throw new CodexSecurityError(\n \"The export output path cannot traverse a repository symlink.\",\n );\n }\n }\n }\n return { ...arguments_, scanDir: canonicalScan, output: outputPath };\n}\n\n/** Resolve saved artifacts after the workbench validates their recorded identity. */\nexport async function resolveSavedArtifactDirectory(\n scanId: string,\n artifact: ExportArtifactKind,\n format: ExportFormat,\n workbench: (args: readonly string[]) => Promise<JsonObject>,\n): Promise<string> {\n // Reuse the workbench's recorded digest and scan binding checks without\n // requiring a writable saved-scan directory for stdout or external exports.\n const context = await workbench([\n \"export-findings\",\n \"--scan-id\",\n scanId,\n \"--artifact\",\n artifact,\n \"--format\",\n format,\n \"--validate-only\",\n ]);\n const scan = context[\"scan\"] as JsonObject | undefined;\n if (typeof scan?.[\"scanDir\"] !== \"string\")\n throw new CodexSecurityError(\n `Artifacts for scan ${scanId} are unavailable.`,\n );\n return resolve(expandHome(scan[\"scanDir\"]));\n}\n\n/** Export saved artifacts without authenticating or starting Codex. */\nexport async function exportArtifact(\n options: ExportArtifactOptions,\n): Promise<ArtifactExportResult> {\n const artifact = options.artifact ?? \"findings\";\n const format = resolveArtifactFormat(artifact, options.format);\n const environment = {\n ...exportEnvironment(),\n CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),\n };\n let directory: string;\n if (options.source.directory !== undefined) {\n directory = resolve(expandHome(options.source.directory));\n } else {\n const python = await resolvePluginPython({\n configuredPath: options.pythonPath,\n environment,\n signal: options.signal,\n });\n const pluginRoot = await bundledPluginRoot();\n directory = await resolveSavedArtifactDirectory(\n options.source.scanId,\n artifact,\n format,\n (args) =>\n runWorkbench(\n {\n python,\n pluginRoot,\n environment,\n signal: options.signal,\n failureMessage: \"Could not export Codex Security scan artifacts\",\n },\n args,\n ),\n );\n }\n const arguments_ = await resolveArtifactExportOutput(\n {\n scanDir: directory,\n artifact,\n format,\n output:\n options.output === \"-\" ? \"-\" : resolve(expandHome(options.output)),\n pythonPath: options.pythonPath,\n signal: options.signal,\n includeMetadata: artifact === \"threat-model\" && options.output !== \"-\",\n ...(options.sourceRoot === undefined\n ? {}\n : { sourceRoot: resolve(expandHome(options.sourceRoot)) }),\n },\n process.cwd(),\n );\n const metadata = await runArtifactExport(\n arguments_,\n options.output === \"-\" ? process.stdout : undefined,\n );\n const description =\n metadata === undefined\n ? null\n : (JSON.parse(\n Buffer.from(metadata).toString(\"utf8\"),\n ) as ThreatModelDescription);\n return {\n path: arguments_.output === \"-\" ? null : arguments_.output,\n provenance: description?.provenance ?? null,\n };\n}\n\nexport async function writeArtifactOutput(\n output: ArtifactOutput,\n value: string | Uint8Array | AsyncIterable<Uint8Array>,\n): Promise<void> {\n const destination = new NodeWritable({\n write(chunk, _encoding, callback) {\n try {\n if (output instanceof NodeWritable) {\n output.write(chunk, callback);\n } else if (output.write(chunk)) {\n callback();\n } else {\n callback(\n new CodexSecurityError(\n \"The export stdout stream cannot report backpressure safely.\",\n ),\n );\n }\n } catch (error) {\n callback(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n const forwardError = (error: Error): void => {\n destination.destroy(error);\n };\n if (output instanceof NodeWritable) output.once(\"error\", forwardError);\n try {\n await pipeline(\n typeof value === \"string\" || value instanceof Uint8Array\n ? [value]\n : value,\n destination,\n );\n } finally {\n if (output instanceof NodeWritable) {\n output.removeListener(\"error\", forwardError);\n }\n }\n}\n\nexport function exportEnvironment(\n environment: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n return pythonUtf8Environment(\n Object.fromEntries(\n [\n \"PATH\",\n \"Path\",\n \"PATHEXT\",\n \"SystemRoot\",\n \"SYSTEMROOT\",\n \"WINDIR\",\n \"TMP\",\n \"TEMP\",\n \"TMPDIR\",\n \"PYTHON\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n ]\n .filter((key) => environment[key] !== undefined)\n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,cAAc,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,WAAW,GAAsB,OAAO,CAAC,GAAG;IAE5C,OAAO,qBAAqB,CAC1B,MAAM,CAAC,WAAW,CAChB;QACE,MAAM;QACN,MAAM;QACN,SAAS;QACT,YAAY;QACZ,YAAY;QACZ,QAAQ;QACR,KAAK;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,gBAAgB;QAChB,MAAM;QACN,QAAQ;QACR,UAAU;KACX;SACE,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;SAC/C,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CACzC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { workbenchArgs } from \"./workbench-arguments.js\";\nimport { spawn } from \"node:child_process\";\nimport { lstat, realpath } from \"node:fs/promises\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { Writable as NodeWritable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport { relativePathIsOutside as isOutsidePath } from \"./targets.js\";\nimport {\n bundledPluginRoot,\n codexSecurityStateDirectory,\n expandHome,\n pythonUtf8Environment,\n resolvePluginPython,\n runWorkbench,\n} from \"./runtime.js\";\n\nexport type ArtifactOutput = Pick<NodeJS.WriteStream, \"write\">;\n\nexport const ARTIFACT_EXPORT_FILENAMES = {\n csv: \"findings.csv\",\n json: \"findings.json\",\n sarif: \"results.sarif\",\n md: \"threatmodel.md\",\n} as const;\nexport type ExportFormat = keyof typeof ARTIFACT_EXPORT_FILENAMES;\nexport type ExportArtifactKind = \"findings\" | \"threat-model\";\n\nexport interface ArtifactExportArguments {\n scanDir: string;\n artifact?: ExportArtifactKind;\n format: ExportFormat;\n output: string;\n sourceRoot?: string;\n pythonPath?: string;\n signal?: AbortSignal;\n includeMetadata?: boolean;\n}\n\nexport type ExportArtifactOptions = {\n source:\n | { directory: string; scanId?: never }\n | { scanId: string; directory?: never };\n output: string;\n pythonPath?: string;\n signal?: AbortSignal;\n} & (\n | { artifact: \"threat-model\"; format?: \"md\"; sourceRoot?: never }\n | {\n artifact?: \"findings\";\n format?: \"csv\" | \"json\" | \"sarif\";\n sourceRoot?: string;\n }\n);\n\nexport interface ArtifactExportResult {\n path: string | null;\n provenance: JsonObject | null;\n}\n\ninterface HelperOptions {\n pythonPath?: string;\n protectedRoot?: string;\n pluginRoot?: string;\n signal?: AbortSignal;\n output?: ArtifactOutput;\n failureMessage?: string;\n}\n\nexport function resolveArtifactFormat(\n artifact: ExportArtifactKind,\n format?: ExportFormat,\n): ExportFormat {\n const selected = format ?? (artifact === \"threat-model\" ? \"md\" : \"sarif\");\n if ((artifact === \"threat-model\") !== (selected === \"md\")) {\n throw new CodexSecurityError(\n artifact === \"threat-model\"\n ? \"Threat-model exports only support --export-format md.\"\n : \"Findings exports support --export-format csv, json, or sarif.\",\n );\n }\n return selected;\n}\n\nexport async function runArtifactHelper(\n args: readonly string[],\n options: HelperOptions = {},\n): Promise<{ stdout: string; stderr: string }> {\n const environment = exportEnvironment();\n const python = await resolvePluginPython({\n configuredPath: options.pythonPath,\n environment,\n protectedRoot: options.protectedRoot,\n signal: options.signal,\n });\n const plugin = options.pluginRoot ?? (await bundledPluginRoot());\n const invocation = spawn(\n python,\n [\n \"-I\",\n \"-X\",\n \"utf8\",\n \"-B\",\n join(plugin, \"scripts\", \"finalize_scan_contract.py\"),\n ...args,\n ],\n {\n env: environment,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n signal: options.signal,\n },\n );\n let stderr = \"\";\n let stdout = \"\";\n invocation.stderr.setEncoding(\"utf8\");\n invocation.stderr.on(\"data\", (chunk: string) => {\n stderr = `${stderr}${chunk}`.slice(-64 * 1024);\n });\n const forwarded =\n options.output === undefined\n ? (async () => {\n invocation.stdout.setEncoding(\"utf8\");\n for await (const chunk of invocation.stdout) stdout += chunk;\n })()\n : writeArtifactOutput(options.output, invocation.stdout);\n let status: number;\n try {\n [status] = await Promise.all([\n new Promise<number>((resolve, reject) => {\n invocation.once(\"error\", reject);\n invocation.once(\"close\", (code, signal) =>\n resolve(signal === null ? (code ?? 1) : 1),\n );\n }),\n forwarded,\n ]);\n } catch (error) {\n invocation.stdout.destroy();\n invocation.kill();\n throw error;\n }\n if (status !== 0) {\n const detail = stderr.trim().split(\"\\n\").at(-1);\n throw new CodexSecurityError(\n detail?.replace(/^finalize_scan_contract\\.py: error: /, \"\") ||\n options.failureMessage ||\n \"Could not export Codex Security artifacts.\",\n );\n }\n return { stdout, stderr };\n}\n\nexport async function writeThreatModel(\n directory: string,\n options: HelperOptions = {},\n): Promise<string> {\n const result = await runArtifactHelper(\n [\"--scan-dir\", directory, \"--write-threat-model\"],\n options,\n );\n return result.stderr.trim().replace(/^codex-security: warning: /u, \"\");\n}\n\n/** Read the current document path without making an optional projection required. */\nexport async function readThreatModelPath(\n directory: string,\n options: HelperOptions = {},\n): Promise<string | null> {\n try {\n options.signal?.throwIfAborted();\n const result = await runArtifactHelper(\n [\"--scan-dir\", directory, \"--describe-threat-model\"],\n options,\n );\n return (JSON.parse(result.stdout) as ArtifactExportResult).path;\n } catch {\n options.signal?.throwIfAborted();\n return null;\n }\n}\n\nexport async function runArtifactExport(\n arguments_: ArtifactExportArguments,\n output?: ArtifactOutput,\n): Promise<string | undefined> {\n const artifact = arguments_.artifact ?? \"findings\";\n resolveArtifactFormat(artifact, arguments_.format);\n const result = await runArtifactHelper(\n [\n \"--scan-dir\",\n arguments_.scanDir,\n ...(artifact === \"findings\" ? [] : [\"--export-artifact\", artifact]),\n \"--export-format\",\n arguments_.format,\n ...(arguments_.output === \"-\"\n ? []\n : [\"--export-output\", arguments_.output]),\n ...(arguments_.sourceRoot === undefined\n ? []\n : [\"--source-root\", arguments_.sourceRoot]),\n ...(arguments_.includeMetadata ? [\"--export-metadata\"] : []),\n ],\n {\n pythonPath: arguments_.pythonPath,\n signal: arguments_.signal,\n failureMessage:\n artifact === \"findings\"\n ? `Could not export Codex Security findings as ${arguments_.format.toUpperCase()}.`\n : \"Could not export the saved threat model as Markdown.\",\n ...(arguments_.output === \"-\" && output !== undefined ? { output } : {}),\n },\n );\n return (arguments_.output === \"-\" && output === undefined) ||\n arguments_.includeMetadata\n ? result.stdout\n : undefined;\n}\n\nexport async function resolveArtifactExportOutput(\n arguments_: ArtifactExportArguments,\n currentDirectory: string,\n): Promise<ArtifactExportArguments> {\n const canonicalScan = await realpath(arguments_.scanDir).catch(\n () => arguments_.scanDir,\n );\n const scanRelativeOutput = relative(arguments_.scanDir, arguments_.output);\n const scanLocalOutput = join(\n \"exports\",\n ARTIFACT_EXPORT_FILENAMES[arguments_.format],\n );\n if (\n arguments_.output !== \"-\" &&\n !isOutsidePath(scanRelativeOutput) &&\n scanRelativeOutput !== scanLocalOutput\n ) {\n throw new CodexSecurityError(\n \"The export output path cannot overwrite a scan artifact.\",\n );\n }\n const outputPath =\n arguments_.output === \"-\"\n ? \"-\"\n : !isOutsidePath(scanRelativeOutput)\n ? join(canonicalScan, scanRelativeOutput)\n : join(\n await realpath(dirname(arguments_.output)).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\")\n throw new CodexSecurityError(\n `Export output directory does not exist: ${dirname(arguments_.output)}. Create the directory and retry.`,\n );\n throw error;\n },\n ),\n basename(arguments_.output),\n );\n if (arguments_.output !== \"-\") {\n const outputFromCurrent = relative(currentDirectory, arguments_.output);\n if (outputFromCurrent !== \"\" && !isOutsidePath(outputFromCurrent)) {\n let existingParent: string | undefined;\n for (\n let directory = dirname(arguments_.output);\n relative(currentDirectory, directory) !== \"\";\n directory = dirname(directory)\n ) {\n const metadata = await lstat(directory).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") return undefined;\n throw error;\n },\n );\n if (metadata?.isSymbolicLink()) {\n throw new CodexSecurityError(\n \"The export output path cannot traverse a repository symlink.\",\n );\n }\n if (metadata !== undefined) existingParent ??= directory;\n }\n const canonicalCurrent = await realpath(currentDirectory).catch(\n () => currentDirectory,\n );\n const expectedOutput =\n existingParent === undefined\n ? resolve(canonicalCurrent, outputFromCurrent)\n : resolve(\n await realpath(existingParent),\n relative(existingParent, arguments_.output),\n );\n if (\n isOutsidePath(relative(canonicalCurrent, outputPath)) ||\n relative(expectedOutput, outputPath) !== \"\"\n ) {\n throw new CodexSecurityError(\n \"The export output path cannot traverse a repository symlink.\",\n );\n }\n }\n }\n return { ...arguments_, scanDir: canonicalScan, output: outputPath };\n}\n\n/** Resolve saved artifacts after the workbench validates their recorded identity. */\nexport async function resolveSavedArtifactDirectory(\n scanId: string,\n artifact: ExportArtifactKind,\n format: ExportFormat,\n workbench: (args: readonly string[]) => Promise<JsonObject>,\n): Promise<string> {\n // Reuse the workbench's recorded digest and scan binding checks without\n // requiring a writable saved-scan directory for stdout or external exports.\n const context = await workbench(\n workbenchArgs(\"export-findings\", {\n scanId,\n artifact,\n format,\n validateOnly: true,\n }),\n );\n const scan = context[\"scan\"] as JsonObject | undefined;\n if (typeof scan?.[\"scanDir\"] !== \"string\")\n throw new CodexSecurityError(\n `Artifacts for scan ${scanId} are unavailable.`,\n );\n return resolve(expandHome(scan[\"scanDir\"]));\n}\n\n/** Export saved artifacts without authenticating or starting Codex. */\nexport async function exportArtifact(\n options: ExportArtifactOptions,\n): Promise<ArtifactExportResult> {\n const artifact = options.artifact ?? \"findings\";\n const format = resolveArtifactFormat(artifact, options.format);\n const environment = {\n ...exportEnvironment(),\n CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),\n };\n let directory: string;\n if (options.source.directory !== undefined) {\n directory = resolve(expandHome(options.source.directory));\n } else {\n const python = await resolvePluginPython({\n configuredPath: options.pythonPath,\n environment,\n signal: options.signal,\n });\n const pluginRoot = await bundledPluginRoot();\n directory = await resolveSavedArtifactDirectory(\n options.source.scanId,\n artifact,\n format,\n (args) =>\n runWorkbench(\n {\n python,\n pluginRoot,\n environment,\n signal: options.signal,\n failureMessage: \"Could not export Codex Security scan artifacts\",\n },\n args,\n ),\n );\n }\n const arguments_ = await resolveArtifactExportOutput(\n {\n scanDir: directory,\n artifact,\n format,\n output:\n options.output === \"-\" ? \"-\" : resolve(expandHome(options.output)),\n pythonPath: options.pythonPath,\n signal: options.signal,\n includeMetadata: artifact === \"threat-model\" && options.output !== \"-\",\n ...(options.sourceRoot === undefined\n ? {}\n : { sourceRoot: resolve(expandHome(options.sourceRoot)) }),\n },\n process.cwd(),\n );\n const metadata = await runArtifactExport(\n arguments_,\n options.output === \"-\" ? process.stdout : undefined,\n );\n const description =\n metadata === undefined\n ? null\n : (JSON.parse(metadata) as ArtifactExportResult);\n return {\n path: arguments_.output === \"-\" ? null : arguments_.output,\n provenance: description?.provenance ?? null,\n };\n}\n\nexport async function writeArtifactOutput(\n output: ArtifactOutput,\n value: string | Uint8Array | AsyncIterable<Uint8Array>,\n): Promise<void> {\n const destination = new NodeWritable({\n write(chunk, _encoding, callback) {\n try {\n if (output instanceof NodeWritable) {\n output.write(chunk, callback);\n } else if (output.write(chunk)) {\n callback();\n } else {\n callback(\n new CodexSecurityError(\n \"The export stdout stream cannot report backpressure safely.\",\n ),\n );\n }\n } catch (error) {\n callback(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n const forwardError = (error: Error): void => {\n destination.destroy(error);\n };\n if (output instanceof NodeWritable) output.once(\"error\", forwardError);\n try {\n await pipeline(\n typeof value === \"string\" || value instanceof Uint8Array\n ? [value]\n : value,\n destination,\n );\n } finally {\n if (output instanceof NodeWritable) {\n output.removeListener(\"error\", forwardError);\n }\n }\n}\n\nexport function exportEnvironment(\n environment: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n return pythonUtf8Environment(\n Object.fromEntries(\n [\n \"PATH\",\n \"Path\",\n \"PATHEXT\",\n \"SystemRoot\",\n \"SYSTEMROOT\",\n \"WINDIR\",\n \"TMP\",\n \"TEMP\",\n \"TMPDIR\",\n \"PYTHON\",\n \"XDG_CACHE_HOME\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n ]\n .filter((key) => environment[key] !== undefined)\n .map((key) => [key, environment[key]]),\n ),\n );\n}\n"]}
package/dist/auth.d.ts CHANGED
@@ -1,9 +1,5 @@
1
- import { type CodexCommand, type ProcessEnvironment } from "./runtime.js";
2
- export interface LoginResult {
3
- success: boolean;
4
- exitCode: number | null;
5
- stdout: string;
6
- stderr: string;
1
+ import { runCodexCommand, type CodexCommand, type ProcessEnvironment } from "./runtime.js";
2
+ export interface LoginResult extends Awaited<ReturnType<typeof runCodexCommand>> {
7
3
  }
8
4
  export interface AccountStatus {
9
5
  authenticated: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAQA,OAAO,EAIL,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACxB,MAAM,cAAc,CAAC;AA6DtB,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,OAAO,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,gBAAgB;;IAkB3B,YACE,OAAO,EAAE,YAAY,EACrB,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,WAAW,EAAE,kBAAkB,EAC/B,SAAS,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EA+CtC;IAED,IAAW,OAAO,IAAI,IAAI,CAEzB;IAED,IAAW,OAAO,IAAI,M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AAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EAqDtC;IAED,IAAW,OAAO,IAAI,IAAI,CAEzB;IAED,IAAW,OAAO,IAAI,MAAM,GAAG,IAAI,CAElC;IAED,IAAW,eAAe,IAAI,MAAM,GAAG,IAAI,CAE1C;IAED,IAAW,QAAQ,IAAI,MAAM,GAAG,IAAI,CAEnC;IAEY,IAAI,IAAI,OAAO,CAAC,WAAW,CAAC,CAExC;IAEY,mBAAmB,CAC9B,OAAO,GAAE;QAAE,UAAU,CAAC,EAAE,OAAO,CAAA;KAAO,GACrC,OAAO,CAAC,IAAI,CAAC,CAGf;IAEM,MAAM,IAAI,IAAI,CAoBpB;CA2CF;AAED,wBAAsB,WAAW,CAC/B,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,kBAAkB,EAC/B,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,WAAW,CAAC,CAWtB;AAED,wBAAsB,aAAa,CACjC,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,kBAAkB,EAC/B,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,aAAa,CAAC,CAgBxB;AAED,wBAAsB,MAAM,CAC1B,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,kBAAkB,EAC/B,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,IAAI,CAAC,CAaf"}
package/dist/auth.js CHANGED
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { parse } from "smol-toml";
7
- import { CodexSecurityError, PluginBootstrapError } from "./errors.js";
7
+ import { CodexSecurityError, PluginBootstrapError, errorMessage, } from "./errors.js";
8
8
  import { executablePathForSpawn, expandHome, runCodexCommand, } from "./runtime.js";
9
9
  const LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;
10
10
  /** @internal */
@@ -21,8 +21,8 @@ export function withoutOpenAiApiKeys(environment) {
21
21
  }
22
22
  /** @internal */
23
23
  export function configuredCodexHome(environment) {
24
- return resolve(expandHome(environmentEntry(environment, "CODEX_HOME")?.trim() ||
25
- join(homedir(), ".codex"), environment));
24
+ const configured = environmentEntry(environment, "CODEX_HOME");
25
+ return resolve(expandHome(configured?.trim() ? configured : join(homedir(), ".codex"), environment));
26
26
  }
27
27
  /** @internal */
28
28
  export async function readCodexHomeConfig(environment, signal) {
@@ -36,7 +36,7 @@ export async function readCodexHomeConfig(environment, signal) {
36
36
  signal?.throwIfAborted();
37
37
  if (error.code === "ENOENT")
38
38
  return {};
39
- throw new CodexSecurityError("Could not read the configured Codex provider.");
39
+ throw new CodexSecurityError(`Could not read the configured Codex provider: ${errorMessage(error)}`, { cause: error });
40
40
  }
41
41
  }
42
42
  export class CodexLoginHandle {
@@ -59,7 +59,7 @@ export class CodexLoginHandle {
59
59
  constructor(command, args, environment, onSuccess) {
60
60
  void this.#urlReady.promise.catch(() => undefined);
61
61
  void this.#deviceReady.promise.catch(() => undefined);
62
- this.#child = spawn(executablePathForSpawn(command.command), [...args], {
62
+ this.#child = spawn(executablePathForSpawn(command.command), [...(command.args ?? []), ...args], {
63
63
  env: environment,
64
64
  stdio: ["pipe", "pipe", "pipe"],
65
65
  windowsHide: true,
@@ -86,7 +86,9 @@ export class CodexLoginHandle {
86
86
  };
87
87
  this.#settleInstructionWaiters(result);
88
88
  if (result.success) {
89
- Promise.resolve(onSuccess()).then(() => resolve(result), reject);
89
+ Promise.resolve()
90
+ .then(onSuccess)
91
+ .then(() => resolve(result), reject);
90
92
  }
91
93
  else {
92
94
  resolve(result);
@@ -125,8 +127,14 @@ export class CodexLoginHandle {
125
127
  }
126
128
  cancel() {
127
129
  this.#canceled = true;
128
- if (this.#child.exitCode !== null || this.#child.signalCode !== null)
130
+ if (this.#child.exitCode !== null || this.#child.signalCode !== null) {
131
+ // Descendants can retain inherited pipes after the login process exits.
132
+ // Cancellation must release those pipes so the close event can settle.
133
+ this.#child.stdin.destroy();
134
+ this.#child.stdout.destroy();
135
+ this.#child.stderr.destroy();
129
136
  return;
137
+ }
130
138
  this.#child.kill("SIGTERM");
131
139
  if (this.#forcedTermination !== undefined)
132
140
  return;
@@ -213,8 +221,10 @@ function preferredAuthUrl(value) {
213
221
  for (const match of plainTerminalText(value).matchAll(/https?:\/\/[^\s<>"']+/g)) {
214
222
  const url = match[0].replace(/[.,;:!?)\]}]+$/, "");
215
223
  try {
216
- const hostname = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
217
- if (hostname !== "localhost" &&
224
+ const parsed = new URL(url);
225
+ const hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
226
+ if (parsed.protocol === "https:" &&
227
+ hostname !== "localhost" &&
218
228
  !hostname.endsWith(".localhost") &&
219
229
  !(isIP(hostname) === 4 && hostname.startsWith("127.")) &&
220
230
  hostname !== "0.0.0.0" &&
package/dist/auth.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,eAAe,GAGhB,MAAM,cAAc,CAAC;AAEtB,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAE/C,gBAAgB;AAChB,MAAM,UAAU,gBAAgB,CAC9B,WAA+B,EAC/B,SAAiB;IAEjB,MAAM,KAAK,GAAG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Y,CAAC;gBAClC,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAC7B,CAAC;gBACD,OAAO,GAAG,CAAC;YACb,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACvC,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,CAAC;IAC9E,OAAO,CACL,MAAM,CAAC,KAAK,CAAC,8CAA8C,CAAC,EAAE,CAAC,CAAC,CAAC;QACjE,MAAM,CAAC,KAAK,CAAC,oCAAoC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,IAAI,CACL,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAa;IACtC,OAAO,KAAK;SACT,OAAO,CAAC,wCAAwC,EAAE,EAAE,CAAC;SACrD,OAAO,CAAC,4BAA4B,EAAE,EAAE,CAAC;SACzC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, PluginBootstrapError } from \"./errors.js\";\nimport {\n executablePathForSpawn,\n expandHome,\n runCodexCommand,\n type CodexCommand,\n type ProcessEnvironment,\n} from \"./runtime.js\";\n\nconst LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;\n\n/** @internal */\nexport function environmentEntry(\n environment: ProcessEnvironment,\n requested: string,\n): string | undefined {\n const exact = environment[requested];\n if (exact !== undefined || process.platform !== \"win32\") return exact;\n const upper = requested.toUpperCase();\n return Object.entries(environment).find(\n ([name]) => name.toUpperCase() === upper,\n )?.[1];\n}\n\n/** @internal */\nexport function withoutOpenAiApiKeys<Value>(\n environment: Record<string, Value>,\n): Record<string, Value> {\n return Object.fromEntries(\n Object.entries(environment).filter(\n ([name]) =>\n ![\"OPENAI_API_KEY\", \"CODEX_API_KEY\"].includes(name.toUpperCase()),\n ),\n );\n}\n\n/** @internal */\nexport function configuredCodexHome(environment: ProcessEnvironment): string {\n return resolve(\n expandHome(\n environmentEntry(environment, \"CODEX_HOME\")?.trim() ||\n join(homedir(), \".codex\"),\n environment,\n ),\n );\n}\n\n/** @internal */\nexport async function readCodexHomeConfig(\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<JsonObject> {\n try {\n return parse(\n await readFile(join(configuredCodexHome(environment), \"config.toml\"), {\n encoding: \"utf8\",\n signal,\n }),\n ) as JsonObject;\n } catch (error) {\n signal?.throwIfAborted();\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new CodexSecurityError(\n \"Could not read the configured Codex provider.\",\n );\n }\n}\n\nexport interface LoginResult {\n success: boolean;\n exitCode: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface AccountStatus {\n authenticated: boolean;\n details: string;\n}\n\nexport class CodexLoginHandle {\n readonly #child: ChildProcessWithoutNullStreams;\n readonly #completion: Promise<LoginResult>;\n readonly #urlReady = Promise.withResolvers<void>();\n readonly #deviceReady = Promise.withResolvers<void>();\n #canceled = false;\n #forcedTermination: ReturnType<typeof setTimeout> | undefined;\n readonly #output = { stdout: \"\", stderr: \"\" };\n readonly #tails = { stdout: \"\", stderr: \"\" };\n readonly #urls: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n readonly #codes: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n\n public constructor(\n command: CodexCommand,\n args: readonly string[],\n environment: ProcessEnvironment,\n onSuccess: () => void | Promise<void>,\n ) {\n void this.#urlReady.promise.catch(() => undefined);\n void this.#deviceReady.promise.catch(() => undefined);\n this.#child = spawn(executablePathForSpawn(command.command), [...args], {\n env: environment,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n this.#child.stdin.end();\n this.#child.stdout.setEncoding(\"utf8\");\n this.#child.stderr.setEncoding(\"utf8\");\n this.#child.stdout.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stdout\", chunk);\n });\n this.#child.stderr.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stderr\", chunk);\n });\n this.#completion = new Promise((resolve, reject) => {\n this.#child.once(\"close\", (exitCode) => {\n clearTimeout(this.#forcedTermination);\n if (!this.#canceled) {\n this.#flushInstructionTails();\n }\n const result = {\n success: exitCode === 0 && !this.#canceled,\n exitCode,\n ...this.#output,\n };\n this.#settleInstructionWaiters(result);\n if (result.success) {\n Promise.resolve(onSuccess()).then(() => resolve(result), reject);\n } else {\n resolve(result);\n }\n });\n this.#child.once(\"error\", (error) => {\n clearTimeout(this.#forcedTermination);\n this.#settleInstructionWaiters({\n success: false,\n exitCode: null,\n stdout: this.#output.stdout,\n stderr: error.message,\n });\n reject(error);\n });\n });\n }\n\n public get loginId(): null {\n return null;\n }\n\n public get authUrl(): string | null {\n return this.#urls.stdout ?? this.#urls.stderr;\n }\n\n public get verificationUrl(): string | null {\n return this.authUrl;\n }\n\n public get userCode(): string | null {\n return this.#codes.stdout ?? this.#codes.stderr;\n }\n\n public async wait(): Promise<LoginResult> {\n return await this.#completion;\n }\n\n public async waitForInstructions(\n options: { deviceCode?: boolean } = {},\n ): Promise<void> {\n await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)\n .promise;\n }\n\n public cancel(): void {\n this.#canceled = true;\n if (this.#child.exitCode !== null || this.#child.signalCode !== null)\n return;\n this.#child.kill(\"SIGTERM\");\n if (this.#forcedTermination !== undefined) return;\n this.#forcedTermination = setTimeout(() => {\n if (this.#child.exitCode === null && this.#child.signalCode === null) {\n this.#child.kill(\"SIGKILL\");\n }\n this.#child.stdin.destroy();\n this.#child.stdout.destroy();\n this.#child.stderr.destroy();\n }, LOGIN_CHILD_TERMINATION_GRACE_MS);\n }\n\n #recordOutput(stream: \"stdout\" | \"stderr\", chunk: string): void {\n this.#output[stream] += chunk;\n const output = `${this.#tails[stream]}${chunk.replaceAll(\"\\r\", \"\\n\")}`;\n const lastDelimiter = output.lastIndexOf(\"\\n\");\n const completed =\n lastDelimiter === -1 ? \"\" : output.slice(0, lastDelimiter + 1);\n this.#urls[stream] ??= preferredAuthUrl(completed);\n this.#codes[stream] ??= userCodeFromOutput(completed);\n this.#tails[stream] =\n lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);\n this.#notifyInstructions();\n }\n\n #flushInstructionTails(): void {\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);\n this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);\n }\n }\n\n #notifyInstructions(): void {\n if (this.authUrl !== null) this.#urlReady.resolve();\n if (this.verificationUrl !== null && this.userCode !== null)\n this.#deviceReady.resolve();\n }\n\n #settleInstructionWaiters(result: LoginResult): void {\n this.#notifyInstructions();\n if (result.success) {\n this.#urlReady.resolve();\n this.#deviceReady.resolve();\n return;\n }\n const error = new PluginBootstrapError(\n this.#canceled\n ? \"Codex login was canceled.\"\n : `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || \"unknown error\"}`,\n );\n this.#urlReady.reject(error);\n this.#deviceReady.reject(error);\n }\n}\n\nexport async function loginApiKey(\n command: CodexCommand,\n environment: ProcessEnvironment,\n apiKey: string,\n signal?: AbortSignal,\n): Promise<LoginResult> {\n if (apiKey.trim().length === 0) {\n throw new PluginBootstrapError(\"The API key must be non-empty.\");\n }\n return await runCodexCommand(\n command,\n [\"login\", \"--with-api-key\"],\n environment,\n `${apiKey}\\n`,\n signal,\n );\n}\n\nexport async function accountStatus(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<AccountStatus> {\n const result = await runCodexCommand(\n command,\n [\"login\", \"status\"],\n environment,\n undefined,\n signal,\n );\n const details = [result.stdout.trim(), result.stderr.trim()]\n .filter(Boolean)\n .join(\"\\n\");\n return {\n authenticated:\n result.exitCode === 0 && !/not logged in|unauthenticated/i.test(details),\n details,\n };\n}\n\nexport async function logout(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<void> {\n const result = await runCodexCommand(\n command,\n [\"logout\"],\n environment,\n undefined,\n signal,\n );\n if (!result.success) {\n throw new PluginBootstrapError(\n `Codex logout failed: ${result.stderr.trim() || result.stdout.trim() || \"unknown error\"}`,\n );\n }\n}\n\n/** @internal Authentication settings shared by login and model commands. */\nexport const CODEX_AUTH_CONFIG_KEYS = [\n \"cli_auth_credentials_store\",\n \"forced_login_method\",\n \"forced_chatgpt_workspace_id\",\n] as const;\n\n/** @internal Shared login recovery guidance for model commands. */\nexport const NO_CREDENTIALS_MESSAGE =\n \"No credentials were found. Run 'codex-security login'. On a remote or headless \" +\n \"machine, use 'codex-security login --device-auth' if your workspace allows it. \" +\n \"If device auth is disabled, see 'codex-security login --help' for browser login over SSH. \" +\n \"For CI, set OPENAI_API_KEY or CODEX_API_KEY.\";\n\nfunction preferredAuthUrl(value: string): string | null {\n for (const match of plainTerminalText(value).matchAll(\n /https?:\\/\\/[^\\s<>\"']+/g,\n )) {\n const url = match[0].replace(/[.,;:!?)\\]}]+$/, \"\");\n try {\n const hostname = new URL(url).hostname.toLowerCase().replace(/\\.$/, \"\");\n if (\n hostname !== \"localhost\" &&\n !hostname.endsWith(\".localhost\") &&\n !(isIP(hostname) === 4 && hostname.startsWith(\"127.\")) &&\n hostname !== \"0.0.0.0\" &&\n hostname !== \"[::1]\" &&\n hostname !== \"[::]\" &&\n hostname !== \"[::ffff:0:0]\" &&\n !hostname.startsWith(\"[::ffff:7f\") &&\n !hostname.startsWith(\"[::7f\")\n ) {\n return url;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction userCodeFromOutput(value: string): string | null {\n const output = plainTerminalText(value).replace(/https?:\\/\\/[^\\s<>\"']+/g, \"\");\n return (\n output.match(/(?:code|user code)\\s*[:=]\\s*([A-Z0-9-]{4,})/i)?.[1] ??\n output.match(/\\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\\b/)?.[0] ??\n null\n );\n}\n\nfunction plainTerminalText(value: string): string {\n return value\n .replace(/\\u001b\\][^\\u0007]*(?:\\u0007|\\u001b\\\\)/g, \"\")\n .replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n .replace(/\\r/g, \"\");\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,eAAe,GAGhB,MAAM,cAAc,CAAC;AAEtB,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAE/C,gBAAgB;AAChB,MAAM,UAAU,gBAAgB,CAC9B,WAA+B,EAC/B,SAAiB;IAEjB,MAAM,KAAK,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;IACrC,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACtE,MAAM,KAAK,GAAG,SAAS,CAAC,WAAW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AAQ,KAAK,QAAQ;gBAC5B,QAAQ,KAAK,WAAW;gBACxB,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC;gBAChC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBACtD,QAAQ,KAAK,SAAS;gBACtB,QAAQ,KAAK,OAAO;gBACpB,QAAQ,KAAK,MAAM;gBACnB,QAAQ,KAAK,cAAc;gBAC3B,CAAC,QAAQ,CAAC,UAAU,CAAC,YAAY,CAAC;gBAClC,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAC7B,CAAC;gBACD,OAAO,GAAG,CAAC;YACb,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACvC,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,CAAC;IAC9E,OAAO,CACL,MAAM,CAAC,KAAK,CAAC,8CAA8C,CAAC,EAAE,CAAC,CAAC,CAAC;QACjE,MAAM,CAAC,KAAK,CAAC,oCAAoC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,IAAI,CACL,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAa;IACtC,OAAO,KAAK;SACT,OAAO,CAAC,wCAAwC,EAAE,EAAE,CAAC;SACrD,OAAO,CAAC,4BAA4B,EAAE,EAAE,CAAC;SACzC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport type { JsonObject } from \"./config.js\";\nimport {\n CodexSecurityError,\n PluginBootstrapError,\n errorMessage,\n} from \"./errors.js\";\nimport {\n executablePathForSpawn,\n expandHome,\n runCodexCommand,\n type CodexCommand,\n type ProcessEnvironment,\n} from \"./runtime.js\";\n\nconst LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;\n\n/** @internal */\nexport function environmentEntry(\n environment: ProcessEnvironment,\n requested: string,\n): string | undefined {\n const exact = environment[requested];\n if (exact !== undefined || process.platform !== \"win32\") return exact;\n const upper = requested.toUpperCase();\n return Object.entries(environment).find(\n ([name]) => name.toUpperCase() === upper,\n )?.[1];\n}\n\n/** @internal */\nexport function withoutOpenAiApiKeys<Value>(\n environment: Record<string, Value>,\n): Record<string, Value> {\n return Object.fromEntries(\n Object.entries(environment).filter(\n ([name]) =>\n ![\"OPENAI_API_KEY\", \"CODEX_API_KEY\"].includes(name.toUpperCase()),\n ),\n );\n}\n\n/** @internal */\nexport function configuredCodexHome(environment: ProcessEnvironment): string {\n const configured = environmentEntry(environment, \"CODEX_HOME\");\n return resolve(\n expandHome(\n configured?.trim() ? configured : join(homedir(), \".codex\"),\n environment,\n ),\n );\n}\n\n/** @internal */\nexport async function readCodexHomeConfig(\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<JsonObject> {\n try {\n return parse(\n await readFile(join(configuredCodexHome(environment), \"config.toml\"), {\n encoding: \"utf8\",\n signal,\n }),\n ) as JsonObject;\n } catch (error) {\n signal?.throwIfAborted();\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new CodexSecurityError(\n `Could not read the configured Codex provider: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n}\n\nexport interface LoginResult extends Awaited<\n ReturnType<typeof runCodexCommand>\n> {}\n\nexport interface AccountStatus {\n authenticated: boolean;\n details: string;\n}\n\nexport class CodexLoginHandle {\n readonly #child: ChildProcessWithoutNullStreams;\n readonly #completion: Promise<LoginResult>;\n readonly #urlReady = Promise.withResolvers<void>();\n readonly #deviceReady = Promise.withResolvers<void>();\n #canceled = false;\n #forcedTermination: ReturnType<typeof setTimeout> | undefined;\n readonly #output = { stdout: \"\", stderr: \"\" };\n readonly #tails = { stdout: \"\", stderr: \"\" };\n readonly #urls: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n readonly #codes: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n\n public constructor(\n command: CodexCommand,\n args: readonly string[],\n environment: ProcessEnvironment,\n onSuccess: () => void | Promise<void>,\n ) {\n void this.#urlReady.promise.catch(() => undefined);\n void this.#deviceReady.promise.catch(() => undefined);\n this.#child = spawn(\n executablePathForSpawn(command.command),\n [...(command.args ?? []), ...args],\n {\n env: environment,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n },\n );\n this.#child.stdin.end();\n this.#child.stdout.setEncoding(\"utf8\");\n this.#child.stderr.setEncoding(\"utf8\");\n this.#child.stdout.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stdout\", chunk);\n });\n this.#child.stderr.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stderr\", chunk);\n });\n this.#completion = new Promise((resolve, reject) => {\n this.#child.once(\"close\", (exitCode) => {\n clearTimeout(this.#forcedTermination);\n if (!this.#canceled) {\n this.#flushInstructionTails();\n }\n const result = {\n success: exitCode === 0 && !this.#canceled,\n exitCode,\n ...this.#output,\n };\n this.#settleInstructionWaiters(result);\n if (result.success) {\n Promise.resolve()\n .then(onSuccess)\n .then(() => resolve(result), reject);\n } else {\n resolve(result);\n }\n });\n this.#child.once(\"error\", (error) => {\n clearTimeout(this.#forcedTermination);\n this.#settleInstructionWaiters({\n success: false,\n exitCode: null,\n stdout: this.#output.stdout,\n stderr: error.message,\n });\n reject(error);\n });\n });\n }\n\n public get loginId(): null {\n return null;\n }\n\n public get authUrl(): string | null {\n return this.#urls.stdout ?? this.#urls.stderr;\n }\n\n public get verificationUrl(): string | null {\n return this.authUrl;\n }\n\n public get userCode(): string | null {\n return this.#codes.stdout ?? this.#codes.stderr;\n }\n\n public async wait(): Promise<LoginResult> {\n return await this.#completion;\n }\n\n public async waitForInstructions(\n options: { deviceCode?: boolean } = {},\n ): Promise<void> {\n await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)\n .promise;\n }\n\n public cancel(): void {\n this.#canceled = true;\n if (this.#child.exitCode !== null || this.#child.signalCode !== null) {\n // Descendants can retain inherited pipes after the login process exits.\n // Cancellation must release those pipes so the close event can settle.\n this.#child.stdin.destroy();\n this.#child.stdout.destroy();\n this.#child.stderr.destroy();\n return;\n }\n this.#child.kill(\"SIGTERM\");\n if (this.#forcedTermination !== undefined) return;\n this.#forcedTermination = setTimeout(() => {\n if (this.#child.exitCode === null && this.#child.signalCode === null) {\n this.#child.kill(\"SIGKILL\");\n }\n this.#child.stdin.destroy();\n this.#child.stdout.destroy();\n this.#child.stderr.destroy();\n }, LOGIN_CHILD_TERMINATION_GRACE_MS);\n }\n\n #recordOutput(stream: \"stdout\" | \"stderr\", chunk: string): void {\n this.#output[stream] += chunk;\n const output = `${this.#tails[stream]}${chunk.replaceAll(\"\\r\", \"\\n\")}`;\n const lastDelimiter = output.lastIndexOf(\"\\n\");\n const completed =\n lastDelimiter === -1 ? \"\" : output.slice(0, lastDelimiter + 1);\n this.#urls[stream] ??= preferredAuthUrl(completed);\n this.#codes[stream] ??= userCodeFromOutput(completed);\n this.#tails[stream] =\n lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);\n this.#notifyInstructions();\n }\n\n #flushInstructionTails(): void {\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);\n this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);\n }\n }\n\n #notifyInstructions(): void {\n if (this.authUrl !== null) this.#urlReady.resolve();\n if (this.verificationUrl !== null && this.userCode !== null)\n this.#deviceReady.resolve();\n }\n\n #settleInstructionWaiters(result: LoginResult): void {\n this.#notifyInstructions();\n if (result.success) {\n this.#urlReady.resolve();\n this.#deviceReady.resolve();\n return;\n }\n const error = new PluginBootstrapError(\n this.#canceled\n ? \"Codex login was canceled.\"\n : `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || \"unknown error\"}`,\n );\n this.#urlReady.reject(error);\n this.#deviceReady.reject(error);\n }\n}\n\nexport async function loginApiKey(\n command: CodexCommand,\n environment: ProcessEnvironment,\n apiKey: string,\n signal?: AbortSignal,\n): Promise<LoginResult> {\n if (apiKey.trim().length === 0) {\n throw new PluginBootstrapError(\"The API key must be non-empty.\");\n }\n return await runCodexCommand(\n command,\n [\"login\", \"--with-api-key\"],\n environment,\n `${apiKey}\\n`,\n signal,\n );\n}\n\nexport async function accountStatus(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<AccountStatus> {\n const result = await runCodexCommand(\n command,\n [\"login\", \"status\"],\n environment,\n undefined,\n signal,\n );\n const details = [result.stdout.trim(), result.stderr.trim()]\n .filter(Boolean)\n .join(\"\\n\");\n return {\n authenticated:\n result.exitCode === 0 && !/not logged in|unauthenticated/i.test(details),\n details,\n };\n}\n\nexport async function logout(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<void> {\n const result = await runCodexCommand(\n command,\n [\"logout\"],\n environment,\n undefined,\n signal,\n );\n if (!result.success) {\n throw new PluginBootstrapError(\n `Codex logout failed: ${result.stderr.trim() || result.stdout.trim() || \"unknown error\"}`,\n );\n }\n}\n\n/** @internal Authentication settings shared by login and model commands. */\nexport const CODEX_AUTH_CONFIG_KEYS = [\n \"cli_auth_credentials_store\",\n \"forced_login_method\",\n \"forced_chatgpt_workspace_id\",\n] as const;\n\n/** @internal Shared login recovery guidance for model commands. */\nexport const NO_CREDENTIALS_MESSAGE =\n \"No credentials were found. Run 'codex-security login'. On a remote or headless \" +\n \"machine, use 'codex-security login --device-auth' if your workspace allows it. \" +\n \"If device auth is disabled, see 'codex-security login --help' for browser login over SSH. \" +\n \"For CI, set OPENAI_API_KEY or CODEX_API_KEY.\";\n\nfunction preferredAuthUrl(value: string): string | null {\n for (const match of plainTerminalText(value).matchAll(\n /https?:\\/\\/[^\\s<>\"']+/g,\n )) {\n const url = match[0].replace(/[.,;:!?)\\]}]+$/, \"\");\n try {\n const parsed = new URL(url);\n const hostname = parsed.hostname.toLowerCase().replace(/\\.$/, \"\");\n if (\n parsed.protocol === \"https:\" &&\n hostname !== \"localhost\" &&\n !hostname.endsWith(\".localhost\") &&\n !(isIP(hostname) === 4 && hostname.startsWith(\"127.\")) &&\n hostname !== \"0.0.0.0\" &&\n hostname !== \"[::1]\" &&\n hostname !== \"[::]\" &&\n hostname !== \"[::ffff:0:0]\" &&\n !hostname.startsWith(\"[::ffff:7f\") &&\n !hostname.startsWith(\"[::7f\")\n ) {\n return url;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction userCodeFromOutput(value: string): string | null {\n const output = plainTerminalText(value).replace(/https?:\\/\\/[^\\s<>\"']+/g, \"\");\n return (\n output.match(/(?:code|user code)\\s*[:=]\\s*([A-Z0-9-]{4,})/i)?.[1] ??\n output.match(/\\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\\b/)?.[0] ??\n null\n );\n}\n\nfunction plainTerminalText(value: string): string {\n return value\n .replace(/\\u001b\\][^\\u0007]*(?:\\u0007|\\u001b\\\\)/g, \"\")\n .replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n .replace(/\\r/g, \"\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-scan-discovery.d.ts","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AA6CxC,MAAM,WAAW,cAAc;IAC7B,aAAa,IAAI,OAAO,CAAC;IACzB,KAAK,CAAC,KAAK,EAAE,MAAM,GAA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,CAAC;CAC3B;AAED,wBAAgB,mCAAmC,CAAC,OAAO,EAAE;IAC3D,MAAM,EAAE,YAAY,CAAC;IACrB,GAAG,IAAI,MAAM,CAAC;IACd,gBAAgB,IAAI,MAAM,CAAC;CAC5B,GAAG,6BAA6B,CAehC;AAED,wBAAsB,iBAAiB,CACrC,YAAY,EAAE,6BAA6B,EAC3C,MAAM,CAAC,EAAE,WAAW,EACpB,gBAAgB,SAAqB,GACpC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAmEtC;AAyID,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,cAAc,CAsEzE"}
@@ -15,6 +15,7 @@ const GITHUB_REPOSITORIES_QUERY = `
15
15
  after: $cursor
16
16
  isArchived: false
17
17
  isFork: false
18
+ ownerAffiliations: [OWNER]
18
19
  orderBy: { field: PUSHED_AT, direction: DESC }
19
20
  ) {
20
21
  nodes {
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEhF,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;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F,CAAC;YACN,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CACf,OAAO;iBACJ,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACpB,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CACxD;iBACA,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;gBACjC,IAAI,EAAE,KAAK;gBACX,KAAK;gBACL,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;aAC1C,CAAC,CAAC;SACR,EACD,OAAO,CAAC,MAAM,CAAC,CAChB;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { checkbox, confirm, input, search, Separator } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { createAuthenticatedGitHub } from \"./github.js\";\nimport { expandHome } from \"./runtime.js\";\n\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(\n question: string,\n defaultValue?: boolean,\n signal?: AbortSignal,\n ): Promise<boolean>;\n input(\n question: string,\n defaultValue?: string,\n signal?: AbortSignal,\n ): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value; short?: string }[],\n presentation?: { header?: string },\n signal?: AbortSignal,\n ): Promise<Value>;\n checkbox<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value; short?: string }[],\n presentation?: { header?: string; required?: boolean },\n signal?: AbortSignal,\n ): Promise<Value[]>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n readonly columns?: number;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: (host, signal) =>\n createAuthenticatedGitHub(host, {\n environment: process.env,\n currentDirectory: options.currentDirectory(),\n signal,\n }),\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n defaultOutputDir = \"./security-scans\",\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(\n discovered,\n prompt,\n signal,\n );\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n expandHome(\n await prompt.input(\n \"Where should scan results be saved?\",\n defaultOutputDir,\n signal,\n ),\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\", false, signal))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const [firstPage, user] = await Promise.all([\n github.request(\"GET /user/orgs\", { per_page: 100, request: { signal } }),\n github.request(\"GET /user\", { request: { signal } }),\n ]);\n const organizations = [...firstPage.data];\n let response = firstPage;\n let page = 1;\n while (response.headers.link?.includes('rel=\"next\"')) {\n signal?.throwIfAborted();\n response = await github.request(\"GET /user/orgs\", {\n per_page: 100,\n page: ++page,\n request: { signal },\n });\n organizations.push(...response.data);\n }\n const personal = user.data.login;\n const owners = [personal, ...organizations.map(({ login }) => login)].sort();\n if (owners.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n owners.map((owner) => ({ label: owner, value: owner })),\n undefined,\n signal,\n );\n }\n prompt.write(`\\nFinding repositories in ${personal}.\\n`);\n return personal;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n undefined,\n signal,\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n return `${id.slice(0, 111)}-${createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16)}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nexport function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = (signal?: AbortSignal) => {\n const stream = new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n });\n Object.defineProperty(stream, \"columns\", {\n configurable: true,\n get: () => output.columns,\n });\n return { input: stdin, output: stream, signal };\n };\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false, signal) =>\n confirm({ message, default: defaultValue }, context(signal)),\n input: (message, defaultValue, signal) =>\n input({ message, default: defaultValue }, context(signal)),\n checkbox: (message, options, presentation, signal) =>\n checkbox(\n {\n message,\n choices: [\n ...(presentation?.header === undefined\n ? []\n : [new Separator(presentation.header)]),\n ...options.map(({ label, value, short }) => ({\n name: label,\n value,\n ...(short === undefined ? {} : { short }),\n })),\n ],\n required: presentation?.required,\n },\n context(signal),\n ),\n select: (message, options, presentation, signal) =>\n search(\n {\n message,\n ...(presentation?.header === undefined\n ? {}\n : {\n theme: {\n style: {\n searchTerm: (term: string) =>\n `${term}\\n ${presentation.header}`,\n },\n },\n }),\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value, short }) => ({\n name: label,\n value,\n ...(short === undefined ? {} : { short }),\n })),\n },\n context(signal),\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEhF,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;;;CAoBjC,CAAC;AAoEF,MAAM,UAAU,mCAAmC,CAAC,OAInD;IACC,OAAO;QACL,MAAM,EAAE,oBAAoB,CAAC,OAAO,CAAC,MAAM,CAAC;QAC5C,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;QAC1C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE;YAChC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE;YAC/C,CAAC,CAAC,EAAE,CAAC;QACP,YAAY,EAAE,CAAC,IA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K,EAAE,CAAC;aAC1C,CAAC,CAAC;SACR,EACD,OAAO,CAAC,MAAM,CAAC,CAChB;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { checkbox, confirm, input, search, Separator } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { createAuthenticatedGitHub } from \"./github.js\";\nimport { expandHome } from \"./runtime.js\";\n\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n ownerAffiliations: [OWNER]\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(\n question: string,\n defaultValue?: boolean,\n signal?: AbortSignal,\n ): Promise<boolean>;\n input(\n question: string,\n defaultValue?: string,\n signal?: AbortSignal,\n ): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value; short?: string }[],\n presentation?: { header?: string },\n signal?: AbortSignal,\n ): Promise<Value>;\n checkbox<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value; short?: string }[],\n presentation?: { header?: string; required?: boolean },\n signal?: AbortSignal,\n ): Promise<Value[]>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n readonly columns?: number;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: (host, signal) =>\n createAuthenticatedGitHub(host, {\n environment: process.env,\n currentDirectory: options.currentDirectory(),\n signal,\n }),\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n defaultOutputDir = \"./security-scans\",\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(\n discovered,\n prompt,\n signal,\n );\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n expandHome(\n await prompt.input(\n \"Where should scan results be saved?\",\n defaultOutputDir,\n signal,\n ),\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\", false, signal))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const [firstPage, user] = await Promise.all([\n github.request(\"GET /user/orgs\", { per_page: 100, request: { signal } }),\n github.request(\"GET /user\", { request: { signal } }),\n ]);\n const organizations = [...firstPage.data];\n let response = firstPage;\n let page = 1;\n while (response.headers.link?.includes('rel=\"next\"')) {\n signal?.throwIfAborted();\n response = await github.request(\"GET /user/orgs\", {\n per_page: 100,\n page: ++page,\n request: { signal },\n });\n organizations.push(...response.data);\n }\n const personal = user.data.login;\n const owners = [personal, ...organizations.map(({ login }) => login)].sort();\n if (owners.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n owners.map((owner) => ({ label: owner, value: owner })),\n undefined,\n signal,\n );\n }\n prompt.write(`\\nFinding repositories in ${personal}.\\n`);\n return personal;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n undefined,\n signal,\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n return `${id.slice(0, 111)}-${createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16)}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nexport function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = (signal?: AbortSignal) => {\n const stream = new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n });\n Object.defineProperty(stream, \"columns\", {\n configurable: true,\n get: () => output.columns,\n });\n return { input: stdin, output: stream, signal };\n };\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false, signal) =>\n confirm({ message, default: defaultValue }, context(signal)),\n input: (message, defaultValue, signal) =>\n input({ message, default: defaultValue }, context(signal)),\n checkbox: (message, options, presentation, signal) =>\n checkbox(\n {\n message,\n choices: [\n ...(presentation?.header === undefined\n ? []\n : [new Separator(presentation.header)]),\n ...options.map(({ label, value, short }) => ({\n name: label,\n value,\n ...(short === undefined ? {} : { short }),\n })),\n ],\n required: presentation?.required,\n },\n context(signal),\n ),\n select: (message, options, presentation, signal) =>\n search(\n {\n message,\n ...(presentation?.header === undefined\n ? {}\n : {\n theme: {\n style: {\n searchTerm: (term: string) =>\n `${term}\\n ${presentation.header}`,\n },\n },\n }),\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value, short }) => ({\n name: label,\n value,\n ...(short === undefined ? {} : { short }),\n })),\n },\n context(signal),\n ),\n };\n}\n"]}