@openai/codex-security 0.8.3 → 0.10.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 (658) hide show
  1. package/README.md +36 -746
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +7 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +16 -4
  5. package/_bundled_plugin/examples/completed-scan/report.md +11 -8
  6. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +4 -2
  7. package/_bundled_plugin/mcp/fzstd-LICENSE.txt +21 -0
  8. package/_bundled_plugin/mcp/helpers.mjs +2 -11
  9. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +3 -210
  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/package.json +1 -0
  20. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +5 -2
  21. package/_bundled_plugin/mcp/server.mjs +2 -11
  22. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  23. package/_bundled_plugin/mcp/session-decompression.mjs +712 -0
  24. package/_bundled_plugin/references/artifact-storage.md +1 -1
  25. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  26. package/_bundled_plugin/references/core-scan.md +5 -42
  27. package/_bundled_plugin/references/default-severity-rubric.md +9 -4
  28. package/_bundled_plugin/references/final-report.md +5 -3
  29. package/_bundled_plugin/references/finding-detail-fields.md +18 -18
  30. package/_bundled_plugin/references/focused-investigator.md +13 -0
  31. package/_bundled_plugin/references/sarif-adapter.md +8 -2
  32. package/_bundled_plugin/references/scan-artifacts.md +21 -12
  33. package/_bundled_plugin/references/scan-contract.md +27 -33
  34. package/_bundled_plugin/references/scan-prologue.md +2 -2
  35. package/_bundled_plugin/references/scan-runtime.md +4 -2
  36. package/_bundled_plugin/references/security-guidance.md +14 -1
  37. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  38. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +2 -2
  39. package/_bundled_plugin/scripts/check_deep_scan_target.py +97 -0
  40. package/_bundled_plugin/scripts/codex_profile.mjs +7 -1
  41. package/_bundled_plugin/scripts/deep_scan_config.py +20 -1
  42. package/_bundled_plugin/scripts/deep_scan_workbench.py +192 -352
  43. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  44. package/_bundled_plugin/scripts/filesystem_identity.py +1 -0
  45. package/_bundled_plugin/scripts/finalize_scan_contract.py +182 -230
  46. package/_bundled_plugin/scripts/finding_preview.py +20 -0
  47. package/_bundled_plugin/scripts/launch_codex_security_mcp +55 -16
  48. package/_bundled_plugin/scripts/legacy_findings.py +148 -0
  49. package/_bundled_plugin/scripts/posix_scan_local_files.py +37 -1
  50. package/_bundled_plugin/scripts/read_codex_session.mjs +21 -0
  51. package/_bundled_plugin/scripts/report_projection.py +81 -43
  52. package/_bundled_plugin/scripts/review_state.py +8 -2
  53. package/_bundled_plugin/scripts/servicenow_avit.py +20 -0
  54. package/_bundled_plugin/scripts/snapshot_sqlite.py +9 -2
  55. package/_bundled_plugin/scripts/threat_model_projection.py +22 -26
  56. package/_bundled_plugin/scripts/validate_scan_contract.py +7 -1
  57. package/_bundled_plugin/scripts/windows_scan_local_files.py +582 -20
  58. package/_bundled_plugin/scripts/workbench/__init__.py +1 -1
  59. package/_bundled_plugin/scripts/workbench/handoff.py +100 -23
  60. package/_bundled_plugin/scripts/workbench/retained_coverage.py +30 -51
  61. package/_bundled_plugin/scripts/workbench/retained_records.py +18 -30
  62. package/_bundled_plugin/scripts/workbench/runtime_toml.py +4 -1
  63. package/_bundled_plugin/scripts/workbench/saved_coverage.py +9 -17
  64. package/_bundled_plugin/scripts/workbench/saved_outputs.py +9 -0
  65. package/_bundled_plugin/scripts/workbench/saved_sources.py +47 -40
  66. package/_bundled_plugin/scripts/workbench/storage.py +91 -7
  67. package/_bundled_plugin/scripts/workbench_cli.py +54 -14
  68. package/_bundled_plugin/scripts/workbench_constants.py +12 -0
  69. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +3 -3
  70. package/_bundled_plugin/scripts/workbench_db.py +562 -303
  71. package/_bundled_plugin/scripts/workbench_feedback.py +57 -11
  72. package/_bundled_plugin/scripts/workbench_finding_index.py +1 -0
  73. package/_bundled_plugin/scripts/workbench_finding_workflows.py +4 -0
  74. package/_bundled_plugin/scripts/workbench_native_indexes.py +238 -41
  75. package/_bundled_plugin/scripts/workbench_progress.py +169 -4
  76. package/_bundled_plugin/scripts/workbench_publication.py +16 -13
  77. package/_bundled_plugin/scripts/workbench_remediation.py +155 -2
  78. package/_bundled_plugin/scripts/workbench_saved_results.py +176 -81
  79. package/_bundled_plugin/scripts/workbench_scan_history.py +398 -174
  80. package/_bundled_plugin/scripts/workbench_scan_start.py +224 -31
  81. package/_bundled_plugin/scripts/workbench_scan_usage.py +675 -73
  82. package/_bundled_plugin/scripts/workbench_schema.py +258 -63
  83. package/_bundled_plugin/scripts/workbench_setup.py +14 -2
  84. package/_bundled_plugin/scripts/workbench_source_excerpt.py +13 -0
  85. package/_bundled_plugin/scripts/workbench_source_scopes.py +18 -0
  86. package/_bundled_plugin/scripts/workbench_target.py +594 -136
  87. package/_bundled_plugin/scripts/workbench_target_state.py +1110 -21
  88. package/_bundled_plugin/scripts/workbench_validation.py +43 -3
  89. package/_bundled_plugin/shared/workbench-history-repairs.json +77 -35
  90. package/_bundled_plugin/shared/workbench-migrations.json +100 -0
  91. package/_bundled_plugin/skills/cloud-findings/SKILL.md +5 -5
  92. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +7 -50
  93. package/_bundled_plugin/skills/fix-finding/SKILL.md +2 -1
  94. package/_bundled_plugin/skills/publish-findings/SKILL.md +24 -153
  95. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  96. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +37 -0
  97. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +3 -3
  98. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +409 -0
  99. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +224 -0
  100. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  101. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  102. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  103. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  104. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  105. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  106. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  107. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  108. package/_bundled_plugin/skills/threat-model-visualize/scripts/build_explorer.py +22 -1
  109. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -2
  110. package/bin/codex-security.mjs +2 -2
  111. package/dist/api.d.ts +45 -5
  112. package/dist/api.d.ts.map +1 -1
  113. package/dist/api.js +1192 -427
  114. package/dist/api.js.map +1 -1
  115. package/dist/armorcode-findings.d.ts +9 -0
  116. package/dist/armorcode-findings.d.ts.map +1 -0
  117. package/dist/armorcode-findings.js +145 -0
  118. package/dist/armorcode-findings.js.map +1 -0
  119. package/dist/artifact-export.d.ts +2 -0
  120. package/dist/artifact-export.d.ts.map +1 -1
  121. package/dist/artifact-export.js +29 -13
  122. package/dist/artifact-export.js.map +1 -1
  123. package/dist/auth.d.ts +6 -2
  124. package/dist/auth.d.ts.map +1 -1
  125. package/dist/auth.js +37 -18
  126. package/dist/auth.js.map +1 -1
  127. package/dist/batch-cost.d.ts +18 -0
  128. package/dist/batch-cost.d.ts.map +1 -0
  129. package/dist/batch-cost.js +41 -0
  130. package/dist/batch-cost.js.map +1 -0
  131. package/dist/bedrock-oss-pricing.d.ts +6 -0
  132. package/dist/bedrock-oss-pricing.d.ts.map +1 -0
  133. package/dist/bedrock-oss-pricing.js +58 -0
  134. package/dist/bedrock-oss-pricing.js.map +1 -0
  135. package/dist/bedrock-pricing.d.ts +15 -0
  136. package/dist/bedrock-pricing.d.ts.map +1 -0
  137. package/dist/bedrock-pricing.js +117 -0
  138. package/dist/bedrock-pricing.js.map +1 -0
  139. package/dist/blackduck-findings.d.ts +1 -1
  140. package/dist/blackduck-findings.d.ts.map +1 -1
  141. package/dist/blackduck-findings.js +24 -22
  142. package/dist/blackduck-findings.js.map +1 -1
  143. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  144. package/dist/bulk-scan-discovery.js +4 -4
  145. package/dist/bulk-scan-discovery.js.map +1 -1
  146. package/dist/bundled-plugin.d.ts +4 -0
  147. package/dist/bundled-plugin.d.ts.map +1 -0
  148. package/dist/bundled-plugin.js +23 -0
  149. package/dist/bundled-plugin.js.map +1 -0
  150. package/dist/checkmarx-evidence.d.ts +19 -0
  151. package/dist/checkmarx-evidence.d.ts.map +1 -0
  152. package/dist/checkmarx-evidence.js +36 -0
  153. package/dist/checkmarx-evidence.js.map +1 -0
  154. package/dist/checkmarx-findings.d.ts +4 -0
  155. package/dist/checkmarx-findings.d.ts.map +1 -0
  156. package/dist/checkmarx-findings.js +27 -0
  157. package/dist/checkmarx-findings.js.map +1 -0
  158. package/dist/checkmarx-one.d.ts +4 -0
  159. package/dist/checkmarx-one.d.ts.map +1 -0
  160. package/dist/checkmarx-one.js +53 -0
  161. package/dist/checkmarx-one.js.map +1 -0
  162. package/dist/checkmarx-repository.d.ts +12 -0
  163. package/dist/checkmarx-repository.d.ts.map +1 -0
  164. package/dist/checkmarx-repository.js +181 -0
  165. package/dist/checkmarx-repository.js.map +1 -0
  166. package/dist/checkmarx-xml.d.ts +12 -0
  167. package/dist/checkmarx-xml.d.ts.map +1 -0
  168. package/dist/checkmarx-xml.js +196 -0
  169. package/dist/checkmarx-xml.js.map +1 -0
  170. package/dist/classify-scan-severity.d.ts +1 -1
  171. package/dist/classify-scan-severity.d.ts.map +1 -1
  172. package/dist/classify-scan-severity.js +11 -3
  173. package/dist/classify-scan-severity.js.map +1 -1
  174. package/dist/classify-severity-records.d.ts +1 -9
  175. package/dist/classify-severity-records.d.ts.map +1 -1
  176. package/dist/classify-severity-records.js +3 -13
  177. package/dist/classify-severity-records.js.map +1 -1
  178. package/dist/classify-severity.d.ts.map +1 -1
  179. package/dist/classify-severity.js +11 -10
  180. package/dist/classify-severity.js.map +1 -1
  181. package/dist/cli-argument.d.ts +4 -0
  182. package/dist/cli-argument.d.ts.map +1 -0
  183. package/dist/cli-argument.js +17 -0
  184. package/dist/cli-argument.js.map +1 -0
  185. package/dist/cli-help.d.ts +1 -1
  186. package/dist/cli-help.d.ts.map +1 -1
  187. package/dist/cli-help.js +71 -29
  188. package/dist/cli-help.js.map +1 -1
  189. package/dist/cli-hook.d.ts +3 -0
  190. package/dist/cli-hook.d.ts.map +1 -0
  191. package/dist/cli-hook.js +87 -0
  192. package/dist/cli-hook.js.map +1 -0
  193. package/dist/cli-integrations.d.ts +13 -0
  194. package/dist/cli-integrations.d.ts.map +1 -0
  195. package/dist/cli-integrations.js +333 -0
  196. package/dist/cli-integrations.js.map +1 -0
  197. package/dist/cli-mcp.d.ts +15 -0
  198. package/dist/cli-mcp.d.ts.map +1 -0
  199. package/dist/cli-mcp.js +178 -0
  200. package/dist/cli-mcp.js.map +1 -0
  201. package/dist/cli-token-view.d.ts +10 -0
  202. package/dist/cli-token-view.d.ts.map +1 -0
  203. package/dist/cli-token-view.js +41 -0
  204. package/dist/cli-token-view.js.map +1 -0
  205. package/dist/cli.d.ts +16 -8
  206. package/dist/cli.d.ts.map +1 -1
  207. package/dist/cli.js +3382 -2017
  208. package/dist/cli.js.map +1 -1
  209. package/dist/cloud-publish.d.ts.map +1 -1
  210. package/dist/cloud-publish.js +35 -33
  211. package/dist/cloud-publish.js.map +1 -1
  212. package/dist/codex-sdk-environment.d.ts +6 -0
  213. package/dist/codex-sdk-environment.d.ts.map +1 -1
  214. package/dist/codex-sdk-environment.js +19 -0
  215. package/dist/codex-sdk-environment.js.map +1 -1
  216. package/dist/command-words.d.ts +3 -0
  217. package/dist/command-words.d.ts.map +1 -0
  218. package/dist/command-words.js +46 -0
  219. package/dist/command-words.js.map +1 -0
  220. package/dist/component-scan.d.ts +19 -4
  221. package/dist/component-scan.d.ts.map +1 -1
  222. package/dist/component-scan.js +67 -9
  223. package/dist/component-scan.js.map +1 -1
  224. package/dist/config.d.ts +1 -1
  225. package/dist/config.d.ts.map +1 -1
  226. package/dist/config.js +130 -67
  227. package/dist/config.js.map +1 -1
  228. package/dist/continuum-findings.d.ts +1 -1
  229. package/dist/continuum-findings.d.ts.map +1 -1
  230. package/dist/continuum-findings.js +149 -19
  231. package/dist/continuum-findings.js.map +1 -1
  232. package/dist/contract-values.d.ts +2 -0
  233. package/dist/contract-values.d.ts.map +1 -1
  234. package/dist/contract-values.js +12 -9
  235. package/dist/contract-values.js.map +1 -1
  236. package/dist/cost-model.d.ts +13 -1
  237. package/dist/cost-model.d.ts.map +1 -1
  238. package/dist/cost-model.js +66 -112
  239. package/dist/cost-model.js.map +1 -1
  240. package/dist/cost.d.ts +42 -3
  241. package/dist/cost.d.ts.map +1 -1
  242. package/dist/cost.js +484 -149
  243. package/dist/cost.js.map +1 -1
  244. package/dist/custom-publish.d.ts +4 -0
  245. package/dist/custom-publish.d.ts.map +1 -1
  246. package/dist/custom-publish.js +40 -3
  247. package/dist/custom-publish.js.map +1 -1
  248. package/dist/custom-validation-prompt.d.ts +1 -1
  249. package/dist/custom-validation-prompt.d.ts.map +1 -1
  250. package/dist/custom-validation-prompt.js +29 -19
  251. package/dist/custom-validation-prompt.js.map +1 -1
  252. package/dist/deduplication/local.d.ts +4 -2
  253. package/dist/deduplication/local.d.ts.map +1 -1
  254. package/dist/deduplication/local.js +9 -2
  255. package/dist/deduplication/local.js.map +1 -1
  256. package/dist/deduplication/refusal.d.ts.map +1 -1
  257. package/dist/deduplication/refusal.js +26 -5
  258. package/dist/deduplication/refusal.js.map +1 -1
  259. package/dist/deduplication/scan.d.ts +5 -0
  260. package/dist/deduplication/scan.d.ts.map +1 -1
  261. package/dist/deduplication/scan.js +24 -7
  262. package/dist/deduplication/scan.js.map +1 -1
  263. package/dist/deep-config.d.ts +0 -1
  264. package/dist/deep-config.d.ts.map +1 -1
  265. package/dist/deep-config.js +22 -33
  266. package/dist/deep-config.js.map +1 -1
  267. package/dist/deep-scan-defaults.d.ts +2 -0
  268. package/dist/deep-scan-defaults.d.ts.map +1 -1
  269. package/dist/deep-scan-defaults.js +28 -1
  270. package/dist/deep-scan-defaults.js.map +1 -1
  271. package/dist/deep-scan.d.ts +2 -0
  272. package/dist/deep-scan.d.ts.map +1 -1
  273. package/dist/deep-scan.js +44 -19
  274. package/dist/deep-scan.js.map +1 -1
  275. package/dist/default-severity-rubric.d.ts +1 -1
  276. package/dist/default-severity-rubric.d.ts.map +1 -1
  277. package/dist/default-severity-rubric.js +1 -1
  278. package/dist/default-severity-rubric.js.map +1 -1
  279. package/dist/endor-findings.d.ts +3 -1
  280. package/dist/endor-findings.d.ts.map +1 -1
  281. package/dist/endor-findings.js +86 -45
  282. package/dist/endor-findings.js.map +1 -1
  283. package/dist/errors.d.ts +4 -2
  284. package/dist/errors.d.ts.map +1 -1
  285. package/dist/errors.js +15 -4
  286. package/dist/errors.js.map +1 -1
  287. package/dist/executable-path.d.ts +3 -0
  288. package/dist/executable-path.d.ts.map +1 -1
  289. package/dist/executable-path.js +26 -0
  290. package/dist/executable-path.js.map +1 -1
  291. package/dist/external-findings-import.d.ts +5 -3
  292. package/dist/external-findings-import.d.ts.map +1 -1
  293. package/dist/external-findings-import.js +19 -7
  294. package/dist/external-findings-import.js.map +1 -1
  295. package/dist/external-findings-local.d.ts +69 -5
  296. package/dist/external-findings-local.d.ts.map +1 -1
  297. package/dist/external-findings-local.js +537 -108
  298. package/dist/external-findings-local.js.map +1 -1
  299. package/dist/external-findings-publish.d.ts +13 -6
  300. package/dist/external-findings-publish.d.ts.map +1 -1
  301. package/dist/external-findings-publish.js +895 -1142
  302. package/dist/external-findings-publish.js.map +1 -1
  303. package/dist/external-findings-read.d.ts +21 -2
  304. package/dist/external-findings-read.d.ts.map +1 -1
  305. package/dist/external-findings-read.js +130 -68
  306. package/dist/external-findings-read.js.map +1 -1
  307. package/dist/external-findings.d.ts +15 -3
  308. package/dist/external-findings.d.ts.map +1 -1
  309. package/dist/external-findings.js +54 -2
  310. package/dist/external-findings.js.map +1 -1
  311. package/dist/external-import-contract.d.ts +8 -12
  312. package/dist/external-import-contract.d.ts.map +1 -1
  313. package/dist/external-import-contract.js +51 -184
  314. package/dist/external-import-contract.js.map +1 -1
  315. package/dist/external-import-models.d.ts +1 -1
  316. package/dist/external-import-models.d.ts.map +1 -1
  317. package/dist/external-import-models.js.map +1 -1
  318. package/dist/feedback.d.ts.map +1 -1
  319. package/dist/feedback.js +5 -4
  320. package/dist/feedback.js.map +1 -1
  321. package/dist/finding-prompt.d.ts +5 -0
  322. package/dist/finding-prompt.d.ts.map +1 -0
  323. package/dist/finding-prompt.js +32 -0
  324. package/dist/finding-prompt.js.map +1 -0
  325. package/dist/findings-client.d.ts +1 -0
  326. package/dist/findings-client.d.ts.map +1 -1
  327. package/dist/findings-client.js +27 -3
  328. package/dist/findings-client.js.map +1 -1
  329. package/dist/github-advisories.d.ts.map +1 -1
  330. package/dist/github-advisories.js +0 -2
  331. package/dist/github-advisories.js.map +1 -1
  332. package/dist/github-dependabot-findings.d.ts.map +1 -1
  333. package/dist/github-dependabot-findings.js +18 -8
  334. package/dist/github-dependabot-findings.js.map +1 -1
  335. package/dist/github-findings.d.ts +4 -1
  336. package/dist/github-findings.d.ts.map +1 -1
  337. package/dist/github-findings.js +73 -316
  338. package/dist/github-findings.js.map +1 -1
  339. package/dist/hosted-git-remotes.d.ts +5 -0
  340. package/dist/hosted-git-remotes.d.ts.map +1 -0
  341. package/dist/hosted-git-remotes.js +285 -0
  342. package/dist/hosted-git-remotes.js.map +1 -0
  343. package/dist/hosted-git-repository.d.ts +28 -0
  344. package/dist/hosted-git-repository.d.ts.map +1 -0
  345. package/dist/hosted-git-repository.js +222 -0
  346. package/dist/hosted-git-repository.js.map +1 -0
  347. package/dist/hosted-remediation.d.ts +1 -0
  348. package/dist/hosted-remediation.d.ts.map +1 -1
  349. package/dist/hosted-remediation.js +23 -3
  350. package/dist/hosted-remediation.js.map +1 -1
  351. package/dist/hosted-scan-protocol.js +2 -2
  352. package/dist/hosted-scan-protocol.js.map +1 -1
  353. package/dist/hosted-scan.d.ts.map +1 -1
  354. package/dist/hosted-scan.js +16 -11
  355. package/dist/hosted-scan.js.map +1 -1
  356. package/dist/hosted-scanner-http.d.ts +21 -0
  357. package/dist/hosted-scanner-http.d.ts.map +1 -0
  358. package/dist/hosted-scanner-http.js +204 -0
  359. package/dist/hosted-scanner-http.js.map +1 -0
  360. package/dist/import-scan.d.ts.map +1 -1
  361. package/dist/import-scan.js +3 -0
  362. package/dist/import-scan.js.map +1 -1
  363. package/dist/index.d.ts +21 -9
  364. package/dist/index.d.ts.map +1 -1
  365. package/dist/index.js +12 -3
  366. package/dist/index.js.map +1 -1
  367. package/dist/inspector-findings.d.ts.map +1 -1
  368. package/dist/inspector-findings.js +52 -86
  369. package/dist/inspector-findings.js.map +1 -1
  370. package/dist/knowledge-base.d.ts +1 -1
  371. package/dist/knowledge-base.d.ts.map +1 -1
  372. package/dist/knowledge-base.js +102 -32
  373. package/dist/knowledge-base.js.map +1 -1
  374. package/dist/linear.d.ts +11 -0
  375. package/dist/linear.d.ts.map +1 -1
  376. package/dist/linear.js.map +1 -1
  377. package/dist/local-git-metadata.d.ts +5 -2
  378. package/dist/local-git-metadata.d.ts.map +1 -1
  379. package/dist/local-git-metadata.js +8 -5
  380. package/dist/local-git-metadata.js.map +1 -1
  381. package/dist/multiscan.d.ts +10 -4
  382. package/dist/multiscan.d.ts.map +1 -1
  383. package/dist/multiscan.js +217 -102
  384. package/dist/multiscan.js.map +1 -1
  385. package/dist/native-json-findings.d.ts +2 -1
  386. package/dist/native-json-findings.d.ts.map +1 -1
  387. package/dist/native-json-findings.js +12 -2
  388. package/dist/native-json-findings.js.map +1 -1
  389. package/dist/opengrep-findings.d.ts +5 -2
  390. package/dist/opengrep-findings.d.ts.map +1 -1
  391. package/dist/opengrep-findings.js +54 -33
  392. package/dist/opengrep-findings.js.map +1 -1
  393. package/dist/operation-telemetry.d.ts +104 -0
  394. package/dist/operation-telemetry.d.ts.map +1 -0
  395. package/dist/operation-telemetry.js +293 -0
  396. package/dist/operation-telemetry.js.map +1 -0
  397. package/dist/plugin-python-probe.d.ts +4 -0
  398. package/dist/plugin-python-probe.d.ts.map +1 -0
  399. package/dist/plugin-python-probe.js +10 -0
  400. package/dist/plugin-python-probe.js.map +1 -0
  401. package/dist/private-finding-import.d.ts +99 -9
  402. package/dist/private-finding-import.d.ts.map +1 -1
  403. package/dist/private-finding-import.js +116 -152
  404. package/dist/private-finding-import.js.map +1 -1
  405. package/dist/project-config.d.ts.map +1 -1
  406. package/dist/project-config.js +53 -13
  407. package/dist/project-config.js.map +1 -1
  408. package/dist/prompt-files.d.ts +7 -2
  409. package/dist/prompt-files.d.ts.map +1 -1
  410. package/dist/prompt-files.js +42 -20
  411. package/dist/prompt-files.js.map +1 -1
  412. package/dist/provider-profile.d.ts +1 -1
  413. package/dist/provider-profile.d.ts.map +1 -1
  414. package/dist/provider-profile.js +12 -10
  415. package/dist/provider-profile.js.map +1 -1
  416. package/dist/publication-telemetry.d.ts +45 -0
  417. package/dist/publication-telemetry.d.ts.map +1 -0
  418. package/dist/publication-telemetry.js +50 -0
  419. package/dist/publication-telemetry.js.map +1 -0
  420. package/dist/publication.d.ts +1 -1
  421. package/dist/publication.d.ts.map +1 -1
  422. package/dist/publication.js.map +1 -1
  423. package/dist/publish.d.ts +4 -0
  424. package/dist/publish.d.ts.map +1 -1
  425. package/dist/publish.js +42 -2
  426. package/dist/publish.js.map +1 -1
  427. package/dist/record.d.ts +1 -5
  428. package/dist/record.d.ts.map +1 -1
  429. package/dist/record.js +3 -51
  430. package/dist/record.js.map +1 -1
  431. package/dist/remediation.d.ts +1 -4
  432. package/dist/remediation.d.ts.map +1 -1
  433. package/dist/remediation.js +6 -8
  434. package/dist/remediation.js.map +1 -1
  435. package/dist/request-metadata.d.ts +3 -0
  436. package/dist/request-metadata.d.ts.map +1 -1
  437. package/dist/request-metadata.js +9 -0
  438. package/dist/request-metadata.js.map +1 -1
  439. package/dist/result.d.ts +4 -0
  440. package/dist/result.d.ts.map +1 -1
  441. package/dist/result.js +1 -1
  442. package/dist/result.js.map +1 -1
  443. package/dist/retry-windows-rename.d.ts +8 -0
  444. package/dist/retry-windows-rename.d.ts.map +1 -0
  445. package/dist/retry-windows-rename.js +24 -0
  446. package/dist/retry-windows-rename.js.map +1 -0
  447. package/dist/runtime.d.ts +54 -6
  448. package/dist/runtime.d.ts.map +1 -1
  449. package/dist/runtime.js +1084 -256
  450. package/dist/runtime.js.map +1 -1
  451. package/dist/saved-scan-bootstrap.d.ts +7 -1
  452. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  453. package/dist/saved-scan-bootstrap.js +269 -114
  454. package/dist/saved-scan-bootstrap.js.map +1 -1
  455. package/dist/scan-activity.d.ts.map +1 -1
  456. package/dist/scan-activity.js +141 -56
  457. package/dist/scan-activity.js.map +1 -1
  458. package/dist/scan-archive-path.d.ts +2 -0
  459. package/dist/scan-archive-path.d.ts.map +1 -0
  460. package/dist/scan-archive-path.js +5 -0
  461. package/dist/scan-archive-path.js.map +1 -0
  462. package/dist/scan-comparison.d.ts +10 -5
  463. package/dist/scan-comparison.d.ts.map +1 -1
  464. package/dist/scan-comparison.js +66 -17
  465. package/dist/scan-comparison.js.map +1 -1
  466. package/dist/scan-dashboard.d.ts +7 -6
  467. package/dist/scan-dashboard.d.ts.map +1 -1
  468. package/dist/scan-dashboard.js +92 -43
  469. package/dist/scan-dashboard.js.map +1 -1
  470. package/dist/scan-executor.d.ts +10 -1
  471. package/dist/scan-executor.d.ts.map +1 -1
  472. package/dist/scan-executor.js +24 -2
  473. package/dist/scan-executor.js.map +1 -1
  474. package/dist/scan-history-renderer.d.ts +1 -0
  475. package/dist/scan-history-renderer.d.ts.map +1 -1
  476. package/dist/scan-history-renderer.js +34 -28
  477. package/dist/scan-history-renderer.js.map +1 -1
  478. package/dist/scan-logs.d.ts +12 -0
  479. package/dist/scan-logs.d.ts.map +1 -1
  480. package/dist/scan-logs.js +131 -78
  481. package/dist/scan-logs.js.map +1 -1
  482. package/dist/scan-measurement.d.ts +26 -0
  483. package/dist/scan-measurement.d.ts.map +1 -0
  484. package/dist/scan-measurement.js +77 -0
  485. package/dist/scan-measurement.js.map +1 -0
  486. package/dist/scan-progress.d.ts +1 -0
  487. package/dist/scan-progress.d.ts.map +1 -1
  488. package/dist/scan-progress.js +3 -0
  489. package/dist/scan-progress.js.map +1 -1
  490. package/dist/scan-sessions.d.ts.map +1 -1
  491. package/dist/scan-sessions.js +4 -1
  492. package/dist/scan-sessions.js.map +1 -1
  493. package/dist/scan-settings.d.ts +1 -1
  494. package/dist/scan-settings.d.ts.map +1 -1
  495. package/dist/scan-settings.js +1 -24
  496. package/dist/scan-settings.js.map +1 -1
  497. package/dist/scanner-import.d.ts +25 -13
  498. package/dist/scanner-import.d.ts.map +1 -1
  499. package/dist/scanner-import.js +216 -97
  500. package/dist/scanner-import.js.map +1 -1
  501. package/dist/scanner-repository-url.d.ts +4 -1
  502. package/dist/scanner-repository-url.d.ts.map +1 -1
  503. package/dist/scanner-repository-url.js +10 -6
  504. package/dist/scanner-repository-url.js.map +1 -1
  505. package/dist/security-policy.d.ts +1 -1
  506. package/dist/security-policy.d.ts.map +1 -1
  507. package/dist/security-policy.js +26 -6
  508. package/dist/security-policy.js.map +1 -1
  509. package/dist/semgrep-findings.d.ts +6 -3
  510. package/dist/semgrep-findings.d.ts.map +1 -1
  511. package/dist/semgrep-findings.js +72 -42
  512. package/dist/semgrep-findings.js.map +1 -1
  513. package/dist/semgrep-guardian-findings.d.ts +38 -0
  514. package/dist/semgrep-guardian-findings.d.ts.map +1 -0
  515. package/dist/semgrep-guardian-findings.js +165 -0
  516. package/dist/semgrep-guardian-findings.js.map +1 -0
  517. package/dist/semgrep-platform-collector.d.ts +26 -0
  518. package/dist/semgrep-platform-collector.d.ts.map +1 -0
  519. package/dist/semgrep-platform-collector.js +108 -0
  520. package/dist/semgrep-platform-collector.js.map +1 -0
  521. package/dist/semgrep-platform-findings.d.ts +157 -6
  522. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  523. package/dist/semgrep-platform-findings.js +766 -103
  524. package/dist/semgrep-platform-findings.js.map +1 -1
  525. package/dist/server/api.d.ts +1 -1
  526. package/dist/server/api.d.ts.map +1 -1
  527. package/dist/server/api.js.map +1 -1
  528. package/dist/server/embedding-tokenizer.cdx.json +33 -0
  529. package/dist/server/embedding-tokenizer.d.ts +2 -0
  530. package/dist/server/embedding-tokenizer.d.ts.map +1 -0
  531. package/dist/server/embedding-tokenizer.js +322 -0
  532. package/dist/server/embedding-tokenizer.js.map +6 -0
  533. package/dist/server/embeddings.d.ts +16 -2
  534. package/dist/server/embeddings.d.ts.map +1 -1
  535. package/dist/server/embeddings.js +35 -5
  536. package/dist/server/embeddings.js.map +1 -1
  537. package/dist/session-lines.d.ts +5 -0
  538. package/dist/session-lines.d.ts.map +1 -0
  539. package/dist/session-lines.js +60 -0
  540. package/dist/session-lines.js.map +1 -0
  541. package/dist/severity-review.d.ts +3 -1
  542. package/dist/severity-review.d.ts.map +1 -1
  543. package/dist/severity-review.js +3 -2
  544. package/dist/severity-review.js.map +1 -1
  545. package/dist/skill-authentication.d.ts +1 -0
  546. package/dist/skill-authentication.d.ts.map +1 -1
  547. package/dist/skill-authentication.js +1 -0
  548. package/dist/skill-authentication.js.map +1 -1
  549. package/dist/snyk-findings.d.ts +9 -2
  550. package/dist/snyk-findings.d.ts.map +1 -1
  551. package/dist/snyk-findings.js +90 -70
  552. package/dist/snyk-findings.js.map +1 -1
  553. package/dist/snyk-rest-findings.d.ts +59 -0
  554. package/dist/snyk-rest-findings.d.ts.map +1 -0
  555. package/dist/snyk-rest-findings.js +879 -0
  556. package/dist/snyk-rest-findings.js.map +1 -0
  557. package/dist/snyk-token-origin.d.ts +4 -0
  558. package/dist/snyk-token-origin.d.ts.map +1 -0
  559. package/dist/snyk-token-origin.js +82 -0
  560. package/dist/snyk-token-origin.js.map +1 -0
  561. package/dist/sonar-collector.d.ts.map +1 -1
  562. package/dist/sonar-collector.js +0 -3
  563. package/dist/sonar-collector.js.map +1 -1
  564. package/dist/sonar-findings.d.ts +1 -1
  565. package/dist/sonar-findings.d.ts.map +1 -1
  566. package/dist/sonar-findings.js +2 -4
  567. package/dist/sonar-findings.js.map +1 -1
  568. package/dist/sonar-import.d.ts +3 -0
  569. package/dist/sonar-import.d.ts.map +1 -1
  570. package/dist/sonar-import.js +30 -34
  571. package/dist/sonar-import.js.map +1 -1
  572. package/dist/stored-finding-projection.d.ts +6 -0
  573. package/dist/stored-finding-projection.d.ts.map +1 -0
  574. package/dist/stored-finding-projection.js +104 -0
  575. package/dist/stored-finding-projection.js.map +1 -0
  576. package/dist/stored-findings-publication.d.ts +23 -0
  577. package/dist/stored-findings-publication.d.ts.map +1 -0
  578. package/dist/stored-findings-publication.js +169 -0
  579. package/dist/stored-findings-publication.js.map +1 -0
  580. package/dist/target-drift.d.ts +9 -0
  581. package/dist/target-drift.d.ts.map +1 -0
  582. package/dist/target-drift.js +27 -0
  583. package/dist/target-drift.js.map +1 -0
  584. package/dist/targets.d.ts +8 -1
  585. package/dist/targets.d.ts.map +1 -1
  586. package/dist/targets.js +131 -42
  587. package/dist/targets.js.map +1 -1
  588. package/dist/tenable-findings.d.ts +6 -0
  589. package/dist/tenable-findings.d.ts.map +1 -0
  590. package/dist/tenable-findings.js +122 -0
  591. package/dist/tenable-findings.js.map +1 -0
  592. package/dist/terminal-stream.d.ts +13 -0
  593. package/dist/terminal-stream.d.ts.map +1 -0
  594. package/dist/terminal-stream.js +35 -0
  595. package/dist/terminal-stream.js.map +1 -0
  596. package/dist/trivy-findings.d.ts +19 -0
  597. package/dist/trivy-findings.d.ts.map +1 -0
  598. package/dist/trivy-findings.js +424 -0
  599. package/dist/trivy-findings.js.map +1 -0
  600. package/dist/trivy-import.d.ts +19 -0
  601. package/dist/trivy-import.d.ts.map +1 -0
  602. package/dist/trivy-import.js +151 -0
  603. package/dist/trivy-import.js.map +1 -0
  604. package/dist/trusted-executable.d.ts +6 -0
  605. package/dist/trusted-executable.d.ts.map +1 -1
  606. package/dist/trusted-executable.js +140 -37
  607. package/dist/trusted-executable.js.map +1 -1
  608. package/dist/validation-records.js +1 -1
  609. package/dist/validation-records.js.map +1 -1
  610. package/dist/veracode-findings.d.ts +1 -1
  611. package/dist/veracode-findings.d.ts.map +1 -1
  612. package/dist/veracode-findings.js +19 -6
  613. package/dist/veracode-findings.js.map +1 -1
  614. package/dist/version.d.ts +3 -1
  615. package/dist/version.d.ts.map +1 -1
  616. package/dist/version.js +184 -32
  617. package/dist/version.js.map +1 -1
  618. package/dist/vertex-pricing.d.ts +8 -0
  619. package/dist/vertex-pricing.d.ts.map +1 -0
  620. package/dist/vertex-pricing.js +20 -0
  621. package/dist/vertex-pricing.js.map +1 -0
  622. package/dist/windows-path.d.ts +1 -0
  623. package/dist/windows-path.d.ts.map +1 -1
  624. package/dist/windows-path.js +26 -1
  625. package/dist/windows-path.js.map +1 -1
  626. package/dist/wiz-findings.d.ts +6 -2
  627. package/dist/wiz-findings.d.ts.map +1 -1
  628. package/dist/wiz-findings.js +65 -89
  629. package/dist/wiz-findings.js.map +1 -1
  630. package/docs/classify-severity-records.md +27 -12
  631. package/docs/cli.md +853 -639
  632. package/docs/dedupe-records.md +44 -24
  633. package/docs/findings-service.md +84 -44
  634. package/docs/hosted-remediation.md +27 -11
  635. package/docs/hosted-scans.md +50 -42
  636. package/docs/sdk.md +903 -0
  637. package/docs/telemetry.md +236 -0
  638. package/docs/validate-records.md +78 -44
  639. package/package.json +23 -16
  640. package/schemas/external-findings.schema.json +4 -1
  641. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  642. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  643. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  644. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  645. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  646. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +0 -96
  647. package/dist/external-imports-feature.d.ts +0 -6
  648. package/dist/external-imports-feature.d.ts.map +0 -1
  649. package/dist/external-imports-feature.js +0 -51
  650. package/dist/external-imports-feature.js.map +0 -1
  651. package/dist/finding-normalization.d.ts +0 -5
  652. package/dist/finding-normalization.d.ts.map +0 -1
  653. package/dist/finding-normalization.js +0 -155
  654. package/dist/finding-normalization.js.map +0 -1
  655. package/dist/reader-selection.d.ts +0 -13
  656. package/dist/reader-selection.d.ts.map +0 -1
  657. package/dist/reader-selection.js +0 -81
  658. package/dist/reader-selection.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -1,27 +1,31 @@
1
- import { forwardExternalImportSetting } from "./external-imports-feature.js";
2
- import { executablePathForSpawn } from "./executable-path.js";
1
+ import { configuredExecutableValue, executablePathForSpawn, isExplicitPathWithTrailingWhitespace, isExecutableFile, } from "./executable-path.js";
2
+ import { retryWindowsRename } from "./retry-windows-rename.js";
3
3
  export { executablePathForSpawn } from "./executable-path.js";
4
+ import { bundledPluginRoot, hasPluginManifest } from "./bundled-plugin.js";
5
+ export { bundledPluginCandidates, bundledPluginRoot, } from "./bundled-plugin.js";
6
+ import { PLUGIN_PYTHON_PROBE, PLUGIN_PYTHON_PROBE_TIMEOUT_MS, PLUGIN_PYTHON_READY, } from "./plugin-python-probe.js";
4
7
  import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";
5
- import { gitProtectionRoots } from "./targets.js";
8
+ import { abortable, gitProtectionRoots, resolveTargetPath } from "./targets.js";
6
9
  import { isNonEmptyString, notify } from "./value.js";
7
10
  import { execFile as execFileCallback, spawn, } from "node:child_process";
8
- import { randomUUID } from "node:crypto";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { shortArchivePrefix } from "./scan-archive-path.js";
9
13
  import { chmodSync, close as closeCallback, constants, createWriteStream, fstat as fstatCallback, open as openCallback, read as readCallback, } from "node:fs";
10
- import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
14
+ import { access, chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
11
15
  import { homedir, tmpdir } from "node:os";
12
16
  import { createRequire } from "node:module";
13
17
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, win32, } from "node:path";
14
- import { fileURLToPath } from "node:url";
15
18
  import { promisify } from "node:util";
16
19
  import { pipeline } from "node:stream/promises";
17
20
  import { crc32 } from "node:zlib";
18
21
  import { setTimeout as delay } from "node:timers/promises";
19
22
  import { fromFdPromise } from "yauzl";
20
23
  import { parse } from "smol-toml";
21
- import { CodexSecurityError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, LocalPluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, errorMessage, abortReason, } from "./errors.js";
24
+ import { CodexSecurityError, InvalidTargetError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, LocalPluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, errorMessage, abortReason, } from "./errors.js";
25
+ import { writeCodexConfig, writePrivateConfig, } from "./config.js";
22
26
  import { isRecord } from "./record.js";
23
- import { isWithin, resolveTrustedExecutable, } from "./trusted-executable.js";
24
- import { isWindowsUnsafePathComponent, windowsUnsafePathComponent, } from "./windows-path.js";
27
+ import { campaignExecutable, inspectTrustedExecutable, isWithin, resolveTrustedExecutable, } from "./trusted-executable.js";
28
+ import { isWindowsUnsafePathComponent, sqliteFilename, windowsUnsafePathComponent, } from "./windows-path.js";
25
29
  const execFile = promisify(execFileCallback);
26
30
  export const MARKETPLACE_NAME = "codex-security-sdk";
27
31
  export const PLUGIN_NAME = "codex-security";
@@ -45,6 +49,7 @@ const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
45
49
  const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
46
50
  const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
47
51
  const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
52
+ const KEYRING_LOGIN = ".codex-security-keyring-login";
48
53
  const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
49
54
  const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
50
55
  const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
@@ -56,6 +61,7 @@ const PLUGIN_HELPER_SECRET_ENVIRONMENT_VARIABLES = new Set([
56
61
  "OPENROUTER_API_KEY",
57
62
  "FIREWORKS_API_KEY",
58
63
  "CHEAPER_INFERENCE_API_KEY",
64
+ "HF_TOKEN",
59
65
  ]);
60
66
  const PREPARE_SCAN_ARTIFACT_RESTORER_PROGRAM = `
61
67
  from pathlib import Path
@@ -97,7 +103,7 @@ function environmentValue(environment, requested, preserveWhitespace = false) {
97
103
  return preserveWhitespace ? value : value?.trim();
98
104
  }
99
105
  export function codexSecurityStateDirectory(environment = process.env) {
100
- const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR");
106
+ const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR", process.platform !== "win32");
101
107
  const path = configured !== undefined
102
108
  ? resolve(expandHome(configured, environment))
103
109
  : resolve(expandHome(environmentValue(environment, "CODEX_HOME", true) ??
@@ -281,6 +287,7 @@ const WINDOWS_PRINCIPAL_ALIASES = {
281
287
  HA: "S-1-5-32-578",
282
288
  AA: "S-1-5-32-579",
283
289
  };
290
+ const WINDOWS_ACCOUNT_SID = /^S-1-5-21-(?:\d+-){3}\d+$/u;
284
291
  const WINDOWS_SID = /^S-1-(?:\d+-)*\d+$/u;
285
292
  const WINDOWS_GUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
286
293
  const WINDOWS_SDDL_SID = "(?:S-1-(?:\\d+-)*\\d+|[A-Z]{2})";
@@ -367,7 +374,10 @@ export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options
367
374
  if (type === "A" || type === "OA" || type === "XA" || type === "ZA") {
368
375
  if (!trustedPrincipal(principal)) {
369
376
  if (options.scope !== "ancestor" ||
370
- windowsAceAllowsAncestorReplacement(rights, inheritanceFlags)) {
377
+ // OWNER RIGHTS applies to the owner already verified above. Every
378
+ // descendant is inspected with its own security descriptor.
379
+ (principal !== WINDOWS_OWNER_RIGHTS_SID &&
380
+ windowsAceAllowsAncestorReplacement(rights, inheritanceFlags))) {
371
381
  untrustedPrincipals.add(principal);
372
382
  }
373
383
  }
@@ -387,7 +397,9 @@ export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options
387
397
  }
388
398
  }
389
399
  }
390
- else {
400
+ else if (principal === currentUserSid ||
401
+ !WINDOWS_ACCOUNT_SID.test(principal) ||
402
+ (options.currentGroupSids?.has(principal) ?? true)) {
391
403
  deniedPrincipals.add(principal);
392
404
  }
393
405
  remaining = rest;
@@ -584,6 +596,7 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
584
596
  const ancestorPath = ancestors[index];
585
597
  try {
586
598
  const ancestor = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
599
+ currentGroupSids: options.currentGroupSids,
587
600
  resolvedAliases: options.resolvedAliases,
588
601
  scope: "ancestor",
589
602
  });
@@ -605,6 +618,7 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
605
618
  if (index === ancestors.length) {
606
619
  try {
607
620
  home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
621
+ currentGroupSids: options.currentGroupSids,
608
622
  resolvedAliases: options.resolvedAliases,
609
623
  });
610
624
  }
@@ -617,6 +631,7 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
617
631
  return;
618
632
  }
619
633
  const descendant = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
634
+ currentGroupSids: options.currentGroupSids,
620
635
  resolvedAliases: options.resolvedAliases,
621
636
  scope: "file",
622
637
  });
@@ -644,17 +659,45 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
644
659
  }
645
660
  throw new Error("Windows credential descendants could not be verified");
646
661
  }
662
+ /** A file server may add its own groups to the client's token. */
663
+ export async function isLocalWindowsCredentialVolume(path, readDriveType) {
664
+ const drive = /^\\\\[?.]\\([A-Z]:)\\/iu.exec(win32.toNamespacedPath(path))?.[1];
665
+ if (!drive)
666
+ return false;
667
+ // Win32_LogicalDisk reports removable, local disk, and RAM disk as 2, 3, 6.
668
+ return ["2", "3", "6"].includes((await readDriveType(drive)).trim());
669
+ }
670
+ /** Keep every token group, including groups used only for deny ACEs. */
671
+ export function parseWindowsTokenGroupSids(output) {
672
+ const groups = new Set();
673
+ for (const row of output.trim().split(/\r?\n/u)) {
674
+ const sid = /^"(?:[^"]|"")*","(?:[^"]|"")*","(S-1-(?:\d+-)*\d+)","(?:[^"]|"")*"$/u.exec(row)?.[1];
675
+ if (!sid)
676
+ throw new Error("Unable to identify Windows token group SIDs");
677
+ groups.add(sid);
678
+ }
679
+ return groups;
680
+ }
647
681
  async function secureWindowsCredentialHome(path) {
648
682
  const ancestorAclScript = windowsCredentialAncestorAclScript(path);
683
+ const treePath = win32.toNamespacedPath(path);
649
684
  const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
650
685
  const systemDirectory = join(systemRoot, "System32");
651
- const powershell = join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
686
+ const powershellDirectory = join(systemDirectory, "WindowsPowerShell", "v1.0");
687
+ const powershell = join(powershellDirectory, "powershell.exe");
688
+ const powershellArgs = [
689
+ "-NoLogo",
690
+ "-NoProfile",
691
+ "-NonInteractive",
692
+ "-Command",
693
+ ];
652
694
  const inheritedEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
653
695
  const processOptions = {
654
696
  env: {
655
697
  ...inheritedEnvironment,
656
698
  CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
657
- PSModulePath: join(systemDirectory, "WindowsPowerShell", "v1.0", "Modules"),
699
+ CODEX_SECURITY_CREDENTIAL_TREE_PATH: treePath,
700
+ PSModulePath: join(powershellDirectory, "Modules"),
658
701
  },
659
702
  encoding: "utf8",
660
703
  windowsHide: true,
@@ -672,30 +715,47 @@ async function secureWindowsCredentialHome(path) {
672
715
  const script = [
673
716
  "$ErrorActionPreference = 'Stop'",
674
717
  "$script:descriptorCount = 0",
675
- "function Write-CredentialAcl($path) { $descriptor = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
718
+ "function Write-CredentialAcl($path) {",
719
+ " $descriptors = @(Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl)",
720
+ " if ($descriptors.Count -ne @($path).Count) { throw 'Windows credential ACL could not be verified' }",
721
+ " foreach ($descriptor in $descriptors) { if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
722
+ "}",
676
723
  "function Read-CredentialDescendants($path) {",
677
724
  " try { $entries = @(Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $path -Force) } catch {",
678
725
  // A child can disappear while an existing directory is being enumerated.
679
726
  // Retry that incomplete listing before accepting a vanished descendant.
680
727
  ` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
681
- " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",
728
+ " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",
682
729
  " throw",
683
730
  " }",
684
- " foreach ($entry in $entries) {",
731
+ " $children = @(foreach ($entry in $entries) {",
685
732
  " if (($entry.Attributes -band 1024) -and ($entry.LinkType -in @('SymbolicLink', 'Junction'))) { throw 'Windows credential home contains a symbolic link or junction' }",
686
733
  " if ($entry.PSObject.TypeNames -notcontains 'System.IO.DirectoryInfo' -and $entry.PSObject.TypeNames -notcontains 'System.IO.FileInfo') { throw 'Windows credential home contains an unsafe entry' }",
687
- " try { Write-CredentialAcl $entry.FullName } catch {",
688
- // A descendant can disappear inside Get-Acl after it was enumerated.
689
- ` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetAclCommand' -or $_.FullyQualifiedErrorId -eq 'GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
690
- " if ($_.FullyQualifiedErrorId -like 'GetAcl_PathNotFound,*') { continue }",
691
- " throw",
734
+ // Keep the extended-length path when Windows PowerShell returns child names.
735
+ ' "$path\\$($entry.Name)"',
736
+ " })",
737
+ " if ($children.Count -eq 0) { return }",
738
+ " try { Write-CredentialAcl $children } catch {",
739
+ // A vanished path is the only reason to retry the batch one child at a time.
740
+ " if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw }",
741
+ " for ($i = 0; $i -lt $children.Count; $i++) {",
742
+ " try { Write-CredentialAcl $children[$i] } catch {",
743
+ " if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw }",
744
+ " $children[$i] = $null",
745
+ " }",
692
746
  " }",
693
- " if ($entry.PSIsContainer) { Read-CredentialDescendants $entry.FullName }",
747
+ " }",
748
+ " for ($i = 0; $i -lt $children.Count; $i++) {",
749
+ " if ($children[$i] -and $entries[$i].PSIsContainer) { Read-CredentialDescendants $children[$i] }",
694
750
  " }",
695
751
  "}",
696
752
  ancestorAclScript,
697
753
  "Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
698
- "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
754
+ "try { Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH } catch {",
755
+ // Either a batch or a single-child Get-Acl may report an incomplete listing.
756
+ ` if ($_.FullyQualifiedErrorId -in @('System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetAclCommand', 'GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand')) { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
757
+ " throw",
758
+ "}",
699
759
  `"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,
700
760
  ].join("\n");
701
761
  const resolvePrincipalScript = [
@@ -704,31 +764,40 @@ async function secureWindowsCredentialHome(path) {
704
764
  "Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl $descriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty RawDescriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Owner | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Value",
705
765
  ].join("; ");
706
766
  const resolvedAliases = {};
767
+ function requireNumericSid(value) {
768
+ if (!WINDOWS_SID.test(value))
769
+ throw new Error("Windows credential ACL contains an unresolvable identity");
770
+ return value;
771
+ }
707
772
  const resolvePrincipal = async (principal) => {
708
773
  if (!/^[A-Z]{2}$/u.test(principal) ||
709
774
  WINDOWS_PRINCIPAL_ALIASES[principal] !== undefined ||
710
775
  resolvedAliases[principal] !== undefined) {
711
776
  return;
712
777
  }
713
- const resolved = await execFile(powershell, [
714
- "-NoLogo",
715
- "-NoProfile",
716
- "-NonInteractive",
717
- "-Command",
718
- resolvePrincipalScript,
719
- ], {
778
+ const resolved = await execFile(powershell, [...powershellArgs, resolvePrincipalScript], {
720
779
  ...processOptions,
721
780
  env: {
722
781
  ...processOptions.env,
723
782
  CODEX_SECURITY_CREDENTIAL_PRINCIPAL: principal,
724
783
  },
725
784
  });
726
- const numeric = resolved.stdout.trim();
727
- if (!WINDOWS_SID.test(numeric)) {
728
- throw new Error("Windows credential ACL contains an unresolvable identity");
729
- }
730
- resolvedAliases[principal] = numeric;
785
+ resolvedAliases[principal] = requireNumericSid(resolved.stdout.trim());
731
786
  };
787
+ const loadLocalGroupSids = async () => {
788
+ const local = await isLocalWindowsCredentialVolume(treePath, async (drive) => {
789
+ const volume = await execFile(powershell, [
790
+ ...powershellArgs,
791
+ `$ErrorActionPreference = 'Stop'; (CimCmdlets\\Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID = '${drive}'").DriveType`,
792
+ ], processOptions);
793
+ return volume.stdout;
794
+ });
795
+ if (!local)
796
+ return null;
797
+ const groups = await execFile(join(systemDirectory, "whoami.exe"), ["/groups", "/fo", "csv", "/nh"], processOptions);
798
+ return parseWindowsTokenGroupSids(groups.stdout);
799
+ };
800
+ let currentGroupSids;
732
801
  const resolveDescriptorAliases = async (descriptor) => {
733
802
  const header = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
734
803
  if (header === null)
@@ -737,9 +806,18 @@ async function secureWindowsCredentialHome(path) {
737
806
  let remaining = header[3];
738
807
  while (remaining.startsWith("(")) {
739
808
  const { rule, rest } = windowsSecurityDescriptorRule(remaining);
740
- const principal = rule.split(";")[5];
741
- if (principal !== undefined)
809
+ const fields = rule.split(";");
810
+ const principal = fields[5];
811
+ if (principal !== undefined) {
742
812
  await resolvePrincipal(principal);
813
+ const trustee = resolvedAliases[principal] ?? principal;
814
+ if (currentGroupSids === undefined &&
815
+ ["D", "OD", "XD"].includes(fields[0]) &&
816
+ trustee !== sid &&
817
+ WINDOWS_ACCOUNT_SID.test(trustee)) {
818
+ currentGroupSids = await loadLocalGroupSids();
819
+ }
820
+ }
743
821
  remaining = rest;
744
822
  }
745
823
  };
@@ -747,25 +825,19 @@ async function secureWindowsCredentialHome(path) {
747
825
  const readAcl = async () => {
748
826
  const snapshot = await inspectWindowsCredentialAclSnapshot(path, sid, {
749
827
  command: powershell,
750
- args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
828
+ args: [...powershellArgs, script],
751
829
  environment: processOptions.env,
830
+ get currentGroupSids() {
831
+ return currentGroupSids ?? undefined;
832
+ },
752
833
  resolvedAliases,
753
834
  resolveDescriptorAliases,
754
835
  });
755
836
  descendantsArePrivate = snapshot.descendantsArePrivate;
756
837
  return snapshot.home;
757
838
  };
758
- const icacls = join(systemDirectory, "icacls.exe");
759
- const installTrustedAcl = async (target = path) => {
760
- await execFile(icacls, [
761
- target,
762
- "/inheritance:r",
763
- "/grant:r",
764
- `*${sid}:(OI)(CI)F`,
765
- `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
766
- `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
767
- ], processOptions);
768
- };
839
+ const icacls = (target, ...args) => execFile(join(systemDirectory, "icacls.exe"), [target, ...args], processOptions);
840
+ const installTrustedAcl = () => icacls(path, "/inheritance:r", "/grant:r", `*${sid}:(OI)(CI)F`, `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`, `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`);
769
841
  let existing;
770
842
  for (let attempt = 0; existing === undefined && attempt < 3; attempt += 1) {
771
843
  try {
@@ -773,7 +845,7 @@ async function secureWindowsCredentialHome(path) {
773
845
  }
774
846
  catch (error) {
775
847
  if (error instanceof RepairableWindowsCredentialOwnerError) {
776
- await execFile(icacls, [path, "/setowner", `*${sid}`], processOptions);
848
+ await icacls(path, "/setowner", `*${sid}`);
777
849
  }
778
850
  else if (error instanceof RepairableWindowsCredentialAclError) {
779
851
  await installTrustedAcl();
@@ -789,7 +861,7 @@ async function secureWindowsCredentialHome(path) {
789
861
  if (existing.grantsCurrentUserAccess &&
790
862
  existing.untrustedPrincipals.length === 0 &&
791
863
  !existing.protected) {
792
- await execFile(icacls, [path, "/inheritance:d"], processOptions);
864
+ await icacls(path, "/inheritance:d");
793
865
  existing = await readAcl();
794
866
  }
795
867
  let verified = existing;
@@ -798,17 +870,12 @@ async function secureWindowsCredentialHome(path) {
798
870
  verified.untrustedPrincipals.length !== 0) {
799
871
  await installTrustedAcl();
800
872
  verified = await readAcl();
801
- for (const principal of verified.untrustedPrincipals) {
802
- if (!WINDOWS_SID.test(principal)) {
803
- throw new Error("Windows credential ACL contains an unresolvable identity");
804
- }
805
- await execFile(icacls, [path, "/remove:g", `*${principal}`], processOptions);
806
- }
807
- for (const principal of verified.deniedPrincipals) {
808
- if (!WINDOWS_SID.test(principal)) {
809
- throw new Error("Windows credential ACL contains an unresolvable identity");
810
- }
811
- await execFile(icacls, [path, "/remove:d", `*${principal}`], processOptions);
873
+ for (const [remove, principals] of [
874
+ ["/remove:g", verified.untrustedPrincipals],
875
+ ["/remove:d", verified.deniedPrincipals],
876
+ ]) {
877
+ for (const principal of principals)
878
+ await icacls(path, remove, `*${requireNumericSid(principal)}`);
812
879
  }
813
880
  if (verified.untrustedPrincipals.length !== 0 ||
814
881
  verified.deniedPrincipals.length !== 0) {
@@ -825,13 +892,58 @@ async function secureWindowsCredentialHome(path) {
825
892
  throw new Error("Windows credential ACL grants access to another identity");
826
893
  }
827
894
  if (!descendantsArePrivate) {
828
- await execFile(icacls, [join(path, "*"), "/reset", "/t", "/q"], processOptions);
895
+ await icacls(join(treePath, "*"), "/reset", "/t", "/q");
829
896
  await readAcl();
830
897
  if (!descendantsArePrivate) {
831
898
  throw new Error("Windows credential descendants remain accessible");
832
899
  }
833
900
  }
834
901
  }
902
+ export function sqliteDatabaseOpener(access = "read-write") {
903
+ const require = createRequire(import.meta.url);
904
+ const bun = process.versions["bun"] !== undefined;
905
+ const Database = (bun ? require("bun:sqlite").Database : require("node:sqlite").DatabaseSync);
906
+ return (path) => {
907
+ const filename = sqliteFilename(path);
908
+ if (access === "read-write")
909
+ return new Database(filename);
910
+ // Apple's SQLite requires write access to initialize missing WAL sidecars.
911
+ // The history reader sets PRAGMA query_only on this existing-file connection.
912
+ return new Database(filename, bun
913
+ ? {
914
+ readonly: process.platform !== "darwin",
915
+ readwrite: process.platform === "darwin",
916
+ create: false,
917
+ }
918
+ : { readOnly: true });
919
+ };
920
+ }
921
+ function sqliteBusy(error) {
922
+ return (isRecord(error) &&
923
+ (error["errcode"] === 5 || error["code"] === "SQLITE_BUSY"));
924
+ }
925
+ export async function acquireScanExecutionLock(stateDirectory, scanDirectory) {
926
+ const directory = join(stateDirectory, "scan-locks");
927
+ await mkdir(directory, { recursive: true, mode: 0o700 });
928
+ await requirePrivateDirectory(await stat(directory), directory, "scan locks");
929
+ const identity = createHash("sha256").update(scanDirectory).digest("hex");
930
+ const path = join(directory, `${identity}.sqlite3`);
931
+ const database = sqliteDatabaseOpener()(path);
932
+ try {
933
+ if (process.platform !== "win32")
934
+ await chmod(path, 0o600);
935
+ database.exec("PRAGMA busy_timeout = 0");
936
+ database.exec("BEGIN EXCLUSIVE");
937
+ }
938
+ catch (error) {
939
+ database.close();
940
+ if (sqliteBusy(error)) {
941
+ throw new CodexSecurityError("This scan is already running in another CLI or SDK call.");
942
+ }
943
+ throw error;
944
+ }
945
+ return () => database.close();
946
+ }
835
947
  export async function withCredentialHomeLock(codexHome, operation, signal) {
836
948
  const release = await acquireCodexSecurityCredentialHomeLock(codexHome, signal);
837
949
  try {
@@ -854,17 +966,11 @@ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal,
854
966
  if (existingDatabaseMetadata !== null) {
855
967
  requireCredentialLockDatabaseFile(existingDatabaseMetadata, databasePath);
856
968
  }
857
- const require = createRequire(import.meta.url);
858
- // Both supported runtimes bundle SQLite. Keep the transaction in the process
859
- // doing the protected work, so pausing it cannot expire its lock.
860
- const Database = process.versions["bun"]
861
- ? require("bun:sqlite")
862
- .Database
863
- : require("node:sqlite").DatabaseSync;
969
+ const openDatabase = sqliteDatabaseOpener();
864
970
  // Let SQLite create a missing guard so no separate descriptor can close after
865
971
  // another connection acquires its process-owned POSIX lock. Keep the guard
866
972
  // across releases so every contender locks the same inode.
867
- const database = new Database(databasePath);
973
+ const database = openDatabase(databasePath);
868
974
  let databaseLocked = false;
869
975
  try {
870
976
  // SQLite creates new databases with the process umask. Tighten or repair
@@ -895,8 +1001,7 @@ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal,
895
1001
  database.exec("BEGIN EXCLUSIVE");
896
1002
  }
897
1003
  catch (error) {
898
- if (!isRecord(error) ||
899
- (error["errcode"] !== 5 && error["code"] !== "SQLITE_BUSY")) {
1004
+ if (!sqliteBusy(error)) {
900
1005
  throw error;
901
1006
  }
902
1007
  await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
@@ -1035,29 +1140,168 @@ async function recoverStaleCredentialHomeLock(lock) {
1035
1140
  await rm(quarantine, { recursive: true, force: true });
1036
1141
  return true;
1037
1142
  }
1143
+ function sameInode(left, right) {
1144
+ return left.dev === right.dev && left.ino === right.ino;
1145
+ }
1146
+ /** Distinguish two hard links from two paths to the same directory entry. */
1147
+ async function hasSeparateAmbientLink(localPath, ambientHome) {
1148
+ try {
1149
+ const local = await lstat(localPath, { bigint: true });
1150
+ if (!local.isFile() || local.nlink < 2n || local.ino === 0n)
1151
+ return false;
1152
+ const ambient = await lstat(join(ambientHome, "auth.json"), {
1153
+ bigint: true,
1154
+ });
1155
+ if (!ambient.isFile() || !sameInode(local, ambient))
1156
+ return false;
1157
+ const [localDir, ambientDir] = await Promise.all([
1158
+ stat(dirname(localPath), { bigint: true }),
1159
+ stat(ambientHome, { bigint: true }),
1160
+ ]);
1161
+ return (localDir.ino !== 0n &&
1162
+ ambientDir.ino !== 0n &&
1163
+ !sameInode(localDir, ambientDir));
1164
+ }
1165
+ catch {
1166
+ // Without a verified second link, leave logout to the configured native store.
1167
+ return false;
1168
+ }
1169
+ }
1170
+ /** Native Codex defaults to file storage when the managed home has no setting. */
1171
+ async function credentialStore(home) {
1172
+ const contents = await readFile(join(home, "config.toml"), "utf8").catch(nullIfMissingFileError);
1173
+ return contents === null
1174
+ ? "file"
1175
+ : (parse(contents, { integersAsBigInt: "asNeeded" })["cli_auth_credentials_store"] ?? "file");
1176
+ }
1177
+ async function hasCredentialFile(home) {
1178
+ const file = await lstat(join(home, "auth.json")).catch(nullIfMissingFileError);
1179
+ return file?.isFile() === true;
1180
+ }
1181
+ function savedKeyringHistory(home) {
1182
+ return readFile(join(home, KEYRING_LOGIN), "utf8").catch(nullIfMissingFileError);
1183
+ }
1184
+ function canUseKeyring(store) {
1185
+ return store === "auto" || store === "keyring";
1186
+ }
1187
+ function keyringHistory(saved, store, hasFile) {
1188
+ if (saved === "keyring" || saved === "pending")
1189
+ return "keyring";
1190
+ // On upgrade, a prior keyring login may exist. Auto can also move a file
1191
+ // credential into the keyring on refresh, removing auth.json.
1192
+ if ((saved === null && canUseKeyring(store)) ||
1193
+ (saved === "file" && store === "auto" && !hasFile))
1194
+ return "keyring";
1195
+ return hasFile ? "file" : "none";
1196
+ }
1197
+ async function rememberStoredFile(home) {
1198
+ if ((await savedKeyringHistory(home)) === "none") {
1199
+ await writePrivateConfig(join(home, KEYRING_LOGIN), "file");
1200
+ }
1201
+ }
1202
+ /** Arm logout before a native login can persist a keyring grant and be interrupted. */
1203
+ export async function beginCredentialLogin(home) {
1204
+ const store = await credentialStore(home);
1205
+ if (!canUseKeyring(store))
1206
+ return;
1207
+ const marker = join(home, KEYRING_LOGIN);
1208
+ const saved = await savedKeyringHistory(home);
1209
+ const present = await hasCredentialFile(home);
1210
+ const previous = keyringHistory(saved, store, present);
1211
+ // Only this login's successful file fallback can discharge a new pending marker.
1212
+ const next = previous === "keyring" ? "keyring" : "pending";
1213
+ if (next !== saved)
1214
+ await writePrivateConfig(marker, next);
1215
+ }
1216
+ /** Is the managed file the active login, or a known-empty file destination for an ambient import? */
1217
+ export async function credentialHomeUsesFileStorage(home, options = {}) {
1218
+ const store = await credentialStore(home);
1219
+ if (store !== "auto")
1220
+ return store === "file";
1221
+ const saved = await savedKeyringHistory(home);
1222
+ const hasFile = await hasCredentialFile(home);
1223
+ return hasFile
1224
+ ? saved === "file"
1225
+ : options.allowAmbientImport === true && saved === "none";
1226
+ }
1227
+ /** Preserve credential provenance before a scan or sign-in replaces the shared config. */
1228
+ export async function writeCredentialHomeConfig(home, config) {
1229
+ const old = await credentialStore(home);
1230
+ if (canUseKeyring(old) ||
1231
+ canUseKeyring(config["cli_auth_credentials_store"])) {
1232
+ const marker = join(home, KEYRING_LOGIN);
1233
+ const saved = await savedKeyringHistory(home);
1234
+ const hasFile = await hasCredentialFile(home);
1235
+ const observed = keyringHistory(saved, old, hasFile);
1236
+ if (observed !== saved)
1237
+ await writePrivateConfig(marker, observed);
1238
+ }
1239
+ await writeCodexConfig(join(home, "config.toml"), config);
1240
+ }
1241
+ /** Run under the credential-home lock so status cannot reimport the sign-in during logout. */
1242
+ export async function logoutCredentialHome(home, ambientHome, nativeLogout, onLoggedOut) {
1243
+ const localPath = join(home, "auth.json");
1244
+ const shared = await hasSeparateAmbientLink(localPath, ambientHome);
1245
+ let recorded = false;
1246
+ const recordLogout = async () => {
1247
+ if (recorded)
1248
+ return;
1249
+ await setCodexSecurityCredentialLogout(home, true);
1250
+ if (shared)
1251
+ await rm(localPath);
1252
+ onLoggedOut?.();
1253
+ recorded = true;
1254
+ };
1255
+ // Detach before native logout can revoke a shared token, even if native cleanup fails.
1256
+ if (shared)
1257
+ await recordLogout();
1258
+ const marker = join(home, KEYRING_LOGIN);
1259
+ const previous = await savedKeyringHistory(home);
1260
+ const active = await credentialStore(home);
1261
+ const hasFile = await hasCredentialFile(home);
1262
+ const keyring = keyringHistory(previous, active, hasFile || shared) === "keyring";
1263
+ if (keyring && hasFile) {
1264
+ // Native keyring logout also unlinks the file, but only revokes the token it loads.
1265
+ const status = await nativeLogout(active === "file" ? undefined : "file");
1266
+ if (status !== undefined && status !== 0)
1267
+ return status;
1268
+ // A retry must not re-import ambient credentials after the file was revoked.
1269
+ await recordLogout();
1270
+ }
1271
+ let override;
1272
+ if (keyring && !canUseKeyring(active))
1273
+ override = "keyring";
1274
+ else if (!keyring && active !== "file" && (hasFile || canUseKeyring(active)))
1275
+ override = "file";
1276
+ const status = await nativeLogout(override);
1277
+ if (status === undefined || status === 0) {
1278
+ await recordLogout();
1279
+ if (canUseKeyring(active))
1280
+ await writePrivateConfig(marker, "none");
1281
+ else
1282
+ await rm(marker, { force: true });
1283
+ }
1284
+ return status;
1285
+ }
1038
1286
  export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
1039
1287
  await requireSecureCredentialHome(codexHome);
1040
1288
  const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
1041
1289
  if (!loggedOut) {
1042
- await rm(marker, { force: true });
1043
- return;
1044
- }
1045
- const temporary = join(codexHome, `.codex-security-logout-${randomUUID()}.tmp`);
1046
- try {
1047
- const handle = await open(temporary, "wx", 0o600);
1048
- try {
1049
- await handle.chmod(0o600);
1050
- await handle.writeFile("logged out\n", "utf8");
1051
- await handle.sync();
1290
+ // Native auto removes auth.json on keyring success and leaves it on file fallback.
1291
+ const store = await credentialStore(codexHome);
1292
+ const history = join(codexHome, KEYRING_LOGIN);
1293
+ if (store === "keyring" ||
1294
+ (store === "auto" && !(await hasCredentialFile(codexHome)))) {
1295
+ await writePrivateConfig(history, "keyring");
1052
1296
  }
1053
- finally {
1054
- await handle.close();
1297
+ else if (store === "auto" &&
1298
+ (await savedKeyringHistory(codexHome)) === "pending") {
1299
+ await writePrivateConfig(history, "file");
1055
1300
  }
1056
- await rename(temporary, marker);
1057
- }
1058
- finally {
1059
- await rm(temporary, { force: true });
1301
+ await rm(marker, { force: true });
1302
+ return;
1060
1303
  }
1304
+ await writePrivateConfig(marker, "logged out\n");
1061
1305
  }
1062
1306
  export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
1063
1307
  await requireSecureCredentialHome(codexHome);
@@ -1142,7 +1386,8 @@ export async function preserveCodexSecurityPluginRegistration(codexHome, config)
1142
1386
  }
1143
1387
  export function requireOutputOutsideRepository(repository, outputDirectory, pathKind = "output") {
1144
1388
  if (isWithin(repository, outputDirectory) ||
1145
- (pathKind === "output" && isWithin(outputDirectory, repository))) {
1389
+ ((pathKind === "output" || pathKind === "state") &&
1390
+ isWithin(outputDirectory, repository))) {
1146
1391
  throw new OutputInsideProtectedRootError(outputDirectory, repository, pathKind);
1147
1392
  }
1148
1393
  }
@@ -1150,6 +1395,40 @@ export function requireOutputOutsideRepositories(repositories, outputDirectory,
1150
1395
  for (const repository of repositories)
1151
1396
  requireOutputOutsideRepository(repository, outputDirectory, pathKind);
1152
1397
  }
1398
+ /** Check where the scan will create state and default artifacts without creating them. */
1399
+ export async function checkScanStorage(stateDirectory, defaultOutputRepository) {
1400
+ try {
1401
+ let root = await canonicalConfigPath(stateDirectory);
1402
+ await requireWritableDirectoryOrParent(root);
1403
+ if (defaultOutputRepository === undefined)
1404
+ return;
1405
+ for (const name of ["scans", safePrefix(defaultOutputRepository)]) {
1406
+ root = join(root, name);
1407
+ const metadata = await lstat(root).catch(nullIfMissingFileError);
1408
+ if (metadata !== null && !metadata.isDirectory()) {
1409
+ throw new OutputDirectoryError(`Persistent scan output must use real directories: ${root}`);
1410
+ }
1411
+ }
1412
+ await requireWritableDirectoryOrParent(root);
1413
+ // New per-scan directories are created beneath this root.
1414
+ await requireSecureOutputAncestry(join(root, `codex-security-${randomUUID()}`));
1415
+ }
1416
+ catch (error) {
1417
+ throw new OutputDirectoryError(`Cannot use scan state directory ${stateDirectory}. Check CODEX_SECURITY_STATE_DIR: ${errorMessage(error)}`, { cause: error });
1418
+ }
1419
+ }
1420
+ async function requireWritableDirectoryOrParent(path) {
1421
+ const metadata = await lstat(path).catch(nullIfMissingFileError);
1422
+ if (metadata === null) {
1423
+ const parent = dirname(path);
1424
+ if (parent === path)
1425
+ throw new OutputDirectoryError(`Directory does not exist: ${path}`);
1426
+ return requireWritableDirectoryOrParent(parent);
1427
+ }
1428
+ if (!metadata.isDirectory())
1429
+ throw new OutputDirectoryError(`Expected a directory: ${path}`);
1430
+ await access(path, constants.W_OK | constants.X_OK);
1431
+ }
1153
1432
  export async function preparePersistentOutputRoot(stateDirectory, category, repositoryName) {
1154
1433
  requireModelSafeOutputDir(stateDirectory);
1155
1434
  await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
@@ -1172,20 +1451,21 @@ import runpy, sys
1172
1451
  sys.argv = sys.argv[1:]
1173
1452
  runpy.run_path(sys.argv[0], run_name="__main__")
1174
1453
  `;
1175
- const ARCHIVE_READY = "codex-security-archive-ready\n";
1176
- const ARCHIVE_REGISTRATION_PROGRAM = String.raw `
1177
- import io, json, runpy, sys
1178
- control = sys.stdin
1179
- payload = json.loads(control.readline())
1180
- sys.stdin = io.TextIOWrapper(io.BytesIO(payload.encode("utf-8")), encoding="utf-8")
1454
+ const WORKBENCH_REGISTRATION_PROGRAM = String.raw `
1455
+ import os, runpy, sys
1181
1456
  sys.argv = sys.argv[1:]
1182
- workbench = runpy.run_path(sys.argv[0])
1183
- def before_archive():
1184
- sys.stdout.buffer.write(b"codex-security-archive-ready\n")
1185
- sys.stdout.buffer.flush()
1186
- if control.readline() != "\n":
1187
- raise SystemExit("Scan registration canceled before archival.")
1188
- workbench["main"](before_archive=before_archive)
1457
+ def before_output_change():
1458
+ with os.fdopen(3, "r+b", buffering=0) as control:
1459
+ control.write(b"?")
1460
+ if control.read(1) != b"!":
1461
+ raise SystemExit("Scan registration canceled before changing the output.")
1462
+ sys._codex_security_before_output_change = before_output_change
1463
+ if "--archive-existing" in sys.argv[1:] and "--archived-scan-dir" not in sys.argv[1:]:
1464
+ # Released workbenches accept this callback before moving an existing output.
1465
+ runpy.run_path(sys.argv[0])["main"](before_archive=before_output_change)
1466
+ else:
1467
+ # A selected plugin keeps its script entrypoint, argv, stdin and stdout.
1468
+ runpy.run_path(sys.argv[0], run_name="__main__")
1189
1469
  `;
1190
1470
  export async function runWorkbench(options, args, input) {
1191
1471
  const script = join(options.pluginRoot, "scripts", "workbench_db.py");
@@ -1193,14 +1473,17 @@ export async function runWorkbench(options, args, input) {
1193
1473
  // Explicitly selected external plugins retain their own workbench protocol.
1194
1474
  const nativeLocalDedupe = args[0] === "local-dedupe" &&
1195
1475
  (await sameFile(options.pluginRoot, await bundledPluginRoot()));
1196
- const run = async (arguments_, input, archiveHandshake = false) => {
1476
+ const run = async (arguments_, input, registrationHandshake = false) => {
1197
1477
  const native = nativeLocalDedupe ||
1198
1478
  [
1199
1479
  "database-info",
1200
1480
  "store-findings",
1201
1481
  "list-stored-findings",
1202
1482
  "store-external-findings",
1203
- "list-external-findings",
1483
+ "read-external-findings",
1484
+ "list-external-imports",
1485
+ "record-external-finding-publications",
1486
+ "list-external-finding-publications",
1204
1487
  "find-potential-duplicates",
1205
1488
  "store-dedupe-groups",
1206
1489
  "list-dedupe-groups",
@@ -1244,11 +1527,21 @@ export async function runWorkbench(options, args, input) {
1244
1527
  "-B",
1245
1528
  "-c",
1246
1529
  WORKBENCH_ARGUMENTS_PROGRAM +
1247
- (archiveHandshake
1248
- ? ARCHIVE_REGISTRATION_PROGRAM
1530
+ (registrationHandshake
1531
+ ? WORKBENCH_REGISTRATION_PROGRAM
1249
1532
  : WORKBENCH_SCRIPT_PROGRAM),
1250
1533
  script,
1251
- ], pluginHelperEnvironment(node?.environment ?? options.environment),
1534
+ ], pluginHelperEnvironment({
1535
+ ...(node?.environment ?? options.environment),
1536
+ // Python's compressed-rollout reader needs the selected Node even when
1537
+ // this SDK was launched by absolute path without Node on PATH.
1538
+ ...(!native &&
1539
+ !process.versions["bun"] &&
1540
+ environmentValue(options.environment, "CODEX_MCP_NODE_PATH") ===
1541
+ undefined
1542
+ ? { CODEX_MCP_NODE_PATH: process.execPath }
1543
+ : {}),
1544
+ }),
1252
1545
  // The SDK owns configuration normalization; the helper receives its resolved location.
1253
1546
  nativeLocalDedupe
1254
1547
  ? `{"stateDirectory":${JSON.stringify(stateDirectory)},"payload":${input ?? "null"}}`
@@ -1259,11 +1552,13 @@ export async function runWorkbench(options, args, input) {
1259
1552
  stateDirectory,
1260
1553
  payload: input === undefined ? undefined : JSON.parse(input),
1261
1554
  })
1262
- : input, signal, archiveHandshake,
1263
- // Frame Python arguments on stdin to preserve NUL and long diagnostics.
1264
- native
1265
- ? undefined
1266
- : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`);
1555
+ : input, signal, {
1556
+ registrationHandshake,
1557
+ // Frame Python arguments on stdin to preserve NUL and long diagnostics.
1558
+ stdinPrefix: native
1559
+ ? undefined
1560
+ : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`,
1561
+ });
1267
1562
  if (!result.success) {
1268
1563
  throw new Error(result.stderr.trim() ||
1269
1564
  result.stdout.trim() ||
@@ -1273,11 +1568,25 @@ export async function runWorkbench(options, args, input) {
1273
1568
  };
1274
1569
  let stdout;
1275
1570
  try {
1276
- const archiveHandshake = signal !== undefined &&
1571
+ const registrationHandshake = signal !== undefined &&
1277
1572
  args[0] === "register-cli-scan" &&
1278
- args.includes("--archive-existing") &&
1279
- !args.includes("--archived-scan-dir");
1280
- stdout = await run(args, input, archiveHandshake);
1573
+ (process.platform === "win32" ||
1574
+ (args.includes("--archive-existing") &&
1575
+ !args.includes("--archived-scan-dir")));
1576
+ try {
1577
+ stdout = await run(args, input, registrationHandshake);
1578
+ }
1579
+ catch (error) {
1580
+ const focusedIndex = args.indexOf("--after-scan-id");
1581
+ if (args[0] !== "list-unmatched-scan-pairs" ||
1582
+ focusedIndex === -1 ||
1583
+ !/unrecognized arguments: --after-scan-id(?:\s+\S+)?$/u.test(processErrorDetail(error)))
1584
+ throw error;
1585
+ options.signal?.throwIfAborted();
1586
+ const legacyArgs = [...args];
1587
+ legacyArgs.splice(focusedIndex, 2);
1588
+ stdout = await run(legacyArgs, input, registrationHandshake);
1589
+ }
1281
1590
  }
1282
1591
  catch (error) {
1283
1592
  if (options.signal?.aborted)
@@ -1298,28 +1607,28 @@ export async function runWorkbench(options, args, input) {
1298
1607
  }
1299
1608
  return result;
1300
1609
  }
1301
- export function bundledPluginCandidates(moduleDirectory) {
1302
- return [
1303
- resolve(moduleDirectory, "_bundled_plugin"),
1304
- resolve(moduleDirectory, "../_bundled_plugin"),
1305
- ];
1306
- }
1307
- export async function bundledPluginRoot() {
1308
- const moduleDirectory = dirname(fileURLToPath(import.meta.url));
1309
- for (const candidate of bundledPluginCandidates(moduleDirectory)) {
1310
- if (await hasPluginManifest(candidate)) {
1311
- return await realpath(candidate);
1610
+ export async function resolveScanOutputPath(outputDirectory, validateTraversalLink) {
1611
+ try {
1612
+ const requested = resolveInputPath(outputDirectory);
1613
+ const path = await resolveParentTraversal(requested, {
1614
+ allowMissing: true,
1615
+ });
1616
+ requireModelSafeOutputDir(path);
1617
+ if (validateTraversalLink && path !== resolve(requested)) {
1618
+ await validateDirectoryLinks(requested, validateTraversalLink);
1312
1619
  }
1620
+ return path;
1621
+ }
1622
+ catch (error) {
1623
+ throw outputInspectionError(outputDirectory, error);
1313
1624
  }
1314
- throw new PluginBootstrapError("The bundled Codex Security plugin is missing.");
1315
1625
  }
1316
- export async function validateOutputDir(outputDirectory, archiveExisting = false) {
1626
+ export async function validateOutputDir(outputDirectory, archiveExisting = false, validateTraversalLink) {
1317
1627
  if (outputDirectory === undefined) {
1318
1628
  return null;
1319
1629
  }
1320
- const path = resolve(expandHome(outputDirectory));
1321
- requireModelSafeOutputDir(path);
1322
1630
  try {
1631
+ const path = await resolveScanOutputPath(outputDirectory, validateTraversalLink);
1323
1632
  const metadata = await lstat(path).catch(nullIfMissingFileError);
1324
1633
  if (metadata !== null) {
1325
1634
  if (!metadata.isDirectory()) {
@@ -1329,8 +1638,9 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1329
1638
  throw new OutputDirectoryNotEmptyError(path);
1330
1639
  }
1331
1640
  requireOutputDirectoryOwnership(metadata, path);
1332
- await requireSecureOutputAncestry(path);
1333
- const canonical = await realpath(path);
1641
+ const writableLeaf = !archiveExisting ||
1642
+ (process.platform === "win32" && (await readdir(path)).length === 0);
1643
+ const canonical = await checkedOutputPath(path, writableLeaf).catch(rethrowOutputPathValidationError);
1334
1644
  requireModelSafeOutputDir(canonical);
1335
1645
  return canonical;
1336
1646
  }
@@ -1340,7 +1650,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1340
1650
  if ((await stat(parent)).isDirectory()) {
1341
1651
  const canonical = resolve(await realpath(parent), relative(parent, path));
1342
1652
  requireModelSafeOutputDir(canonical);
1343
- await requireSecureOutputAncestry(canonical);
1653
+ await requireSecureOutputAncestry(canonical).catch(rethrowOutputPathValidationError);
1344
1654
  return canonical;
1345
1655
  }
1346
1656
  break;
@@ -1357,11 +1667,41 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1357
1667
  throw new OutputDirectoryError(`Unable to create scan output directory: ${path}`);
1358
1668
  }
1359
1669
  catch (error) {
1360
- if (error instanceof OutputDirectoryError)
1361
- throw error;
1362
- throw new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause: error });
1670
+ throw outputInspectionError(outputDirectory, error);
1671
+ }
1672
+ }
1673
+ function outputInspectionError(outputDirectory, cause) {
1674
+ return cause instanceof OutputDirectoryError
1675
+ ? cause
1676
+ : new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause });
1677
+ }
1678
+ /** Check each traversed directory link at its physical location, including linked targets. */
1679
+ export async function validateDirectoryLinks(requested, validateLocation) {
1680
+ const directories = [dirname(requested)];
1681
+ const visited = new Set();
1682
+ while (directories.length > 0) {
1683
+ let directory = directories.pop();
1684
+ while (dirname(directory) !== directory && !visited.has(directory)) {
1685
+ visited.add(directory);
1686
+ if ((await lstat(directory).catch(nullIfMissingFileError))?.isSymbolicLink()) {
1687
+ const parent = await realpath(await resolveParentTraversal(dirname(directory)));
1688
+ validateLocation(join(parent, basename(directory)));
1689
+ directories.push(resolveTargetPath(await readlink(directory), parent));
1690
+ }
1691
+ directory = dirname(directory);
1692
+ }
1363
1693
  }
1364
1694
  }
1695
+ function rethrowOutputPathValidationError(error) {
1696
+ if (process.platform !== "win32" ||
1697
+ nodeErrorCode(error) !== "ERR_DLOPEN_FAILED")
1698
+ throw error;
1699
+ const blocked = error instanceof Error &&
1700
+ /^(?:LoadLibrary failed: )?An Application Control policy has blocked this file\.(?:\s|$)/u.test(error.message);
1701
+ throw new OutputDirectoryError(blocked
1702
+ ? "Windows Application Control blocked the bundled Codex Security filesystem module (windows.node). Check the CodeIntegrity Operational log in Event Viewer."
1703
+ : "Could not load the bundled Codex Security filesystem module (windows.node) on Windows.", { cause: error });
1704
+ }
1365
1705
  export async function prepareScanArtifactRestorer(options, scanDirectory) {
1366
1706
  let helperPath;
1367
1707
  let canonicalPath;
@@ -1437,13 +1777,30 @@ export async function planOutputArchive(outputDirectory) {
1437
1777
  const entries = await readdir(outputDirectory).catch(nullIfMissingFileError);
1438
1778
  if (entries === null || entries.length === 0)
1439
1779
  return null;
1440
- return `${outputDirectory}${outputArchiveSuffix()}`;
1780
+ const id = randomUUID().slice(0, 8);
1781
+ const archive = `${outputDirectory}${outputArchiveSuffix(id)}`;
1782
+ if (process.platform === "win32" || !(await archiveNameTooLong(archive)))
1783
+ return archive;
1784
+ // The workbench reserves a sibling with an eight-character random suffix.
1785
+ const sibling = `${outputDirectory}.previous-${id}`;
1786
+ if (!(await archiveNameTooLong(sibling)))
1787
+ return sibling;
1788
+ return join(dirname(outputDirectory), shortArchivePrefix(basename(outputDirectory)) + id);
1789
+ }
1790
+ async function archiveNameTooLong(path) {
1791
+ try {
1792
+ await lstat(path);
1793
+ return false;
1794
+ }
1795
+ catch (error) {
1796
+ return nodeErrorCode(error) === "ENAMETOOLONG";
1797
+ }
1441
1798
  }
1442
- function outputArchiveSuffix() {
1799
+ function outputArchiveSuffix(id = randomUUID().slice(0, 8)) {
1443
1800
  return `.previous-${new Date()
1444
1801
  .toISOString()
1445
1802
  .replaceAll(/[-:]/g, "")
1446
- .replace(/\.\d{3}Z$/, "")}-${randomUUID().slice(0, 8)}`;
1803
+ .replace(/\.\d{3}Z$/, "")}-${id}`;
1447
1804
  }
1448
1805
  export function requireModelSafeOutputDir(path) {
1449
1806
  if (MODEL_UNSAFE_PATH.test(path)) {
@@ -1461,12 +1818,15 @@ export async function canonicalizeModelSafePath(input) {
1461
1818
  requireModelSafeOutputDir(canonical);
1462
1819
  return canonical;
1463
1820
  }
1464
- export async function canonicalConfigPath(path) {
1821
+ export async function canonicalConfigPath(path, { verifyIdentity = false } = {}) {
1465
1822
  let existing = resolve(path);
1466
1823
  const missing = [];
1467
1824
  while (true) {
1468
1825
  try {
1469
- return join(await realpath(existing), ...missing);
1826
+ const canonical = await realpath(existing);
1827
+ if (verifyIdentity && !(await sameFile(existing, canonical)))
1828
+ throw new InvalidTargetError(`Repository path changed: ${existing}`);
1829
+ return join(canonical, ...missing);
1470
1830
  }
1471
1831
  catch (error) {
1472
1832
  const parent = dirname(existing);
@@ -1486,13 +1846,12 @@ export async function prepareScanRegistrationOutput(outputDirectory, repositoryN
1486
1846
  return prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, archiveExisting ? "preserve" : "reject");
1487
1847
  }
1488
1848
  async function prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, existingOutput, onOutputArchived) {
1489
- if (outputDirectory === undefined) {
1490
- requireModelSafeOutputDir(temporaryRoot);
1491
- requireModelSafeOutputDir(await realpath(temporaryRoot));
1492
- }
1493
- const path = await validateOutputDir(outputDirectory, existingOutput !== "reject");
1494
- validateLocation?.(path ?? (await realpath(temporaryRoot)));
1849
+ const path = await validateOutputDir(outputDirectory, existingOutput !== "reject", validateLocation);
1495
1850
  if (path === null) {
1851
+ requireModelSafeOutputDir(temporaryRoot);
1852
+ const canonicalRoot = await realpath(temporaryRoot);
1853
+ requireModelSafeOutputDir(canonicalRoot);
1854
+ validateLocation?.(canonicalRoot);
1496
1855
  const prefix = `codex-security-${safePrefix(repositoryName)}`;
1497
1856
  let created;
1498
1857
  if (process.platform === "win32") {
@@ -1500,11 +1859,19 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1500
1859
  // Reserve room within NTFS's 255-unit component limit for later archival.
1501
1860
  // The SDK suffix is longer than the workbench's .previous-<tempname> suffix.
1502
1861
  const prefixLength = 255 - suffix.length - outputArchiveSuffix().length;
1503
- created = join(temporaryRoot, `${prefix.slice(0, prefixLength)}${suffix}`);
1862
+ created = join(canonicalRoot, `${prefix.slice(0, prefixLength)}${suffix}`);
1504
1863
  await createWindowsOutputDirectory(created, false);
1505
1864
  }
1506
1865
  else {
1507
- created = await mkdtemp(join(temporaryRoot, `${prefix}-`));
1866
+ try {
1867
+ created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
1868
+ }
1869
+ catch (error) {
1870
+ if (nodeErrorCode(error) !== "ENAMETOOLONG")
1871
+ throw error;
1872
+ // The repository name itself can fill a filesystem component.
1873
+ created = await mkdtemp(join(canonicalRoot, "codex-security-"));
1874
+ }
1508
1875
  }
1509
1876
  try {
1510
1877
  if ((process.umask() & 0o700) !== 0)
@@ -1516,6 +1883,7 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1516
1883
  throw error;
1517
1884
  }
1518
1885
  }
1886
+ validateLocation?.(path);
1519
1887
  let createdRoot;
1520
1888
  try {
1521
1889
  let existing = await lstat(path).catch(nullIfMissingFileError);
@@ -1535,7 +1903,11 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1535
1903
  if ((process.umask() & 0o700) !== 0)
1536
1904
  await chmod(path, 0o700);
1537
1905
  }
1538
- return await validatePreparedOutputDir(path, validateLocation, existingOutput === "preserve");
1906
+ // Registration retains a populated scan for archival. An empty Windows
1907
+ // directory must still satisfy the checks for a writable scan output.
1908
+ const preserveContents = existingOutput === "preserve" &&
1909
+ (process.platform !== "win32" || (await readdir(path)).length !== 0);
1910
+ return await validatePreparedOutputDir(path, validateLocation, preserveContents);
1539
1911
  }
1540
1912
  catch (error) {
1541
1913
  if (createdRoot !== undefined) {
@@ -1548,10 +1920,19 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1548
1920
  });
1549
1921
  }
1550
1922
  }
1923
+ async function windowsOutputBinding() {
1924
+ return createRequire(import.meta.url)(join(await bundledPluginRoot(), "mcp", "native", `win32-${process.arch}`, "windows.node"));
1925
+ }
1926
+ export async function requireWindowsOutputPath(path, writableLeaf, retainedDirectory) {
1927
+ const native = await windowsOutputBinding();
1928
+ const error = native.validateWindowsOutputPath(Buffer.from(win32.toNamespacedPath(path), "utf16le"), writableLeaf, retainedDirectory);
1929
+ if (error !== 0)
1930
+ throw new OutputDirectoryError(`Scan output directory or its parent could not be trusted (Windows error ${error}): ${path}`);
1931
+ }
1551
1932
  export async function createWindowsOutputDirectory(path, recursive) {
1552
- const native = createRequire(import.meta.url)(join(await bundledPluginRoot(), "mcp", "native", `win32-${process.arch}`, "windows.node"));
1933
+ const native = await windowsOutputBinding();
1553
1934
  const create = async (target) => {
1554
- const createOne = () => native.createPrivateWindowsDirectory(Buffer.from(win32.toNamespacedPath(target), "utf16le"));
1935
+ const createOne = () => native.createPrivateWindowsDirectory(Buffer.from(win32.toNamespacedPath(target), "utf16le"), true);
1555
1936
  let error = createOne();
1556
1937
  let firstCreated;
1557
1938
  if (recursive &&
@@ -1562,8 +1943,10 @@ export async function createWindowsOutputDirectory(path, recursive) {
1562
1943
  }
1563
1944
  if (error === 0)
1564
1945
  return firstCreated ?? target;
1565
- if (recursive && error === 183 && (await stat(target)).isDirectory())
1946
+ if (recursive && error === 183 && (await stat(target)).isDirectory()) {
1947
+ await requireWindowsOutputPath(target, target === path);
1566
1948
  return firstCreated;
1949
+ }
1567
1950
  throw new OutputDirectoryError(`Unable to create private Windows output directory (Windows error ${error}): ${target}`);
1568
1951
  };
1569
1952
  return create(path);
@@ -1573,14 +1956,42 @@ export async function validatePreparedOutputDir(path, validateLocation, allowNon
1573
1956
  if (!metadata.isDirectory()) {
1574
1957
  throw new OutputDirectoryError(`Scan output is not a directory: ${path}`);
1575
1958
  }
1576
- const canonical = await realpath(path);
1959
+ const canonical = await checkedOutputPath(path, !allowNonempty);
1577
1960
  requireModelSafeOutputDir(canonical);
1578
1961
  validateLocation?.(canonical);
1579
1962
  if (!allowNonempty && (await readdir(canonical)).length !== 0) {
1580
1963
  throw new OutputDirectoryError(`Scan output directory must be empty: ${path}`);
1581
1964
  }
1582
1965
  requireOutputDirectoryOwnership(metadata, path);
1583
- await requireSecureOutputAncestry(canonical);
1966
+ return canonical;
1967
+ }
1968
+ async function checkedOutputPath(path, writableLeaf) {
1969
+ if (process.platform === "win32") {
1970
+ // Keep the selected leaf for the no-follow check, including across an
1971
+ // in-place directory change between lstat and canonicalization.
1972
+ const directory = dirname(path);
1973
+ const parent = await realpath(directory);
1974
+ const selected = join(parent, relative(directory, path));
1975
+ await requireWindowsOutputPath(selected, writableLeaf);
1976
+ const canonical = await realpath(selected);
1977
+ if (canonical === selected)
1978
+ return selected;
1979
+ // Accept a canonical leaf spelling (case or short name) within the checked parent.
1980
+ if (dirname(canonical) === parent) {
1981
+ const [leaf, resolved] = await Promise.all([
1982
+ lstat(selected, { bigint: true }),
1983
+ lstat(canonical, { bigint: true }),
1984
+ ]);
1985
+ if (leaf.isDirectory() && leaf.ino !== 0n && sameInode(leaf, resolved)) {
1986
+ return canonical;
1987
+ }
1988
+ }
1989
+ throw new OutputDirectoryError(`Scan output directory changed during preparation: ${path}`);
1990
+ }
1991
+ await requireSecureOutputAncestry(path);
1992
+ const canonical = await realpath(path);
1993
+ if (canonical !== path)
1994
+ await requireSecureOutputAncestry(canonical);
1584
1995
  return canonical;
1585
1996
  }
1586
1997
  export function requirePrivateOutputDirectory(metadata, path, effectiveUid = process.geteuid?.()) {
@@ -1601,7 +2012,7 @@ export function requireOutputDirectoryOwnership(metadata, path, effectiveUid = p
1601
2012
  /** Reject shared parents whose owner can rename or replace scan output. */
1602
2013
  export async function requireSecureOutputAncestry(path, effectiveUid = process.geteuid?.()) {
1603
2014
  if (process.platform === "win32")
1604
- return;
2015
+ return requireWindowsOutputPath(path);
1605
2016
  let current = dirname(resolve(path));
1606
2017
  while (true) {
1607
2018
  try {
@@ -1721,6 +2132,7 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1721
2132
  throw error;
1722
2133
  }
1723
2134
  await chmod(destination, 0o600);
2135
+ await rememberStoredFile(isolatedHome);
1724
2136
  return true;
1725
2137
  }
1726
2138
  catch (error) {
@@ -1733,9 +2145,18 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1733
2145
  }
1734
2146
  }
1735
2147
  export async function extractPluginZip(archive, destination, signal) {
2148
+ return extractValidatedPluginZip(archive, destination, signal);
2149
+ }
2150
+ async function extractValidatedPluginZip(archive, destination, signal, digest) {
1736
2151
  const archivePath = resolve(expandHome(archive));
1737
- await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1738
- const staging = await realpath(await mkdtemp(join(dirname(destination), ".codex-security-plugin-")));
2152
+ const parent = dirname(destination);
2153
+ await mkdir(parent, { recursive: true, mode: 0o700 });
2154
+ // Windows mkdtemp otherwise fails at 248 UTF-16 units, including its suffix.
2155
+ const stagingParent = process.platform === "win32"
2156
+ ? win32.toNamespacedPath(await realpath(parent))
2157
+ : parent;
2158
+ const staging = await realpath(await mkdtemp(join(stagingParent, ".codex-security-plugin-")));
2159
+ let publishingOnWindows = false;
1739
2160
  try {
1740
2161
  throwIfSignalAborted(signal);
1741
2162
  let expandedSize = 0;
@@ -1774,6 +2195,7 @@ export async function extractPluginZip(archive, destination, signal) {
1774
2195
  const output = join(staging, ...path.split("/"));
1775
2196
  const entryMode = (entry.externalFileAttributes >>> 16) & 0xffff;
1776
2197
  const permissions = (entryMode || (directory ? 0o700 : 0o600)) & 0o777;
2198
+ digest?.update(JSON.stringify([path, directory, permissions]));
1777
2199
  await mkdir(directory ? output : dirname(output), {
1778
2200
  recursive: true,
1779
2201
  ...(directory ? { mode: permissions } : {}),
@@ -1794,16 +2216,34 @@ export async function extractPluginZip(archive, destination, signal) {
1794
2216
  if (crc32(bytes) !== checksum) {
1795
2217
  throw new PluginBootstrapError(`Plugin ZIP entry failed CRC-32 validation: ${path}`);
1796
2218
  }
2219
+ digest?.update(createHash("sha256").update(bytes).digest());
1797
2220
  }
1798
2221
  const pluginRoot = await discoverPluginRoot(staging);
1799
2222
  throwIfSignalAborted(signal);
1800
2223
  const relativeRoot = relative(staging, pluginRoot);
1801
- await rename(staging, destination);
2224
+ if (process.platform === "win32") {
2225
+ publishingOnWindows = true;
2226
+ await retryWindowsRename(async () => {
2227
+ throwIfSignalAborted(signal);
2228
+ if (await lstat(destination).catch(nullIfMissingFileError))
2229
+ throw new Error(`Destination already exists: ${destination}`);
2230
+ await rename(staging, destination);
2231
+ }, undefined, signal);
2232
+ publishingOnWindows = false;
2233
+ }
2234
+ else {
2235
+ await rename(staging, destination);
2236
+ }
1802
2237
  return await validatePluginRoot(join(destination, relativeRoot));
1803
2238
  }
1804
2239
  catch (error) {
1805
- await rm(staging, { recursive: true, force: true }).catch(() => undefined);
2240
+ let cleanupDiagnostic = "";
2241
+ await rm(staging, { recursive: true, force: true }).catch((cleanupError) => {
2242
+ cleanupDiagnostic = `\nCould not remove staging directory ${staging}: ${errorMessage(cleanupError)}`;
2243
+ });
1806
2244
  throwIfSignalAborted(signal);
2245
+ if (publishingOnWindows)
2246
+ throw new PluginBootstrapError(`Could not publish extracted plugin ZIP: ${errorMessage(error)}${cleanupDiagnostic}`, { cause: error });
1807
2247
  if (error instanceof PluginBootstrapError)
1808
2248
  throw error;
1809
2249
  throw new PluginBootstrapError(`Invalid plugin ZIP: ${archivePath}`, {
@@ -1882,18 +2322,28 @@ async function openPluginZip(path, signal) {
1882
2322
  }
1883
2323
  }
1884
2324
  export async function resolvePluginPath(pluginPath, workspace, signal) {
2325
+ return (await resolvePluginSource(pluginPath, workspace, signal)).root;
2326
+ }
2327
+ /** @internal */
2328
+ export async function resolvePluginSource(pluginPath, workspace, signal, pinZip = false) {
1885
2329
  try {
1886
2330
  if (pluginPath === undefined) {
1887
- return await bundledPluginRoot();
2331
+ return { root: await bundledPluginRoot() };
1888
2332
  }
1889
2333
  const path = resolve(expandHome(pluginPath));
1890
2334
  const metadata = await lstat(path).catch(() => null);
1891
2335
  if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
1892
- return await extractPluginZip(path, join(workspace, "extracted-plugin"), signal);
2336
+ const digest = pinZip ? createHash("sha256") : undefined;
2337
+ const archive = digest ? await realpath(path) : path;
2338
+ const root = await extractValidatedPluginZip(archive, join(workspace, "extracted-plugin"), signal, digest);
2339
+ return {
2340
+ root,
2341
+ ...(digest && { zip: { path: archive, digest: digest.digest("hex") } }),
2342
+ };
1893
2343
  }
1894
2344
  if (metadata?.isDirectory()) {
1895
2345
  throwIfSignalAborted(signal);
1896
- return await validatePluginRoot(path);
2346
+ return { root: await validatePluginRoot(path) };
1897
2347
  }
1898
2348
  throw new PluginBootstrapError(`Plugin path must be a directory or ZIP: ${path}`);
1899
2349
  }
@@ -1903,6 +2353,79 @@ export async function resolvePluginPath(pluginPath, workspace, signal) {
1903
2353
  throw new LocalPluginBootstrapError(errorMessage(error), { cause: error });
1904
2354
  }
1905
2355
  }
2356
+ /** @internal */
2357
+ export async function prepareWindowsScanPluginZip(source, scanDirectory, protectedDirectories, validateLocation, signal) {
2358
+ throwIfSignalAborted(signal);
2359
+ const protectedPath = (path) => protectedDirectories.some((directory) => isWithin(directory, path));
2360
+ if (protectedPath(source.path))
2361
+ return;
2362
+ const metadata = await lstat(source.path).catch(nullIfMissingFileError);
2363
+ if (metadata === null)
2364
+ return;
2365
+ const changed = "The selected plugin ZIP changed after runtime preparation.";
2366
+ if (!metadata.isFile())
2367
+ throw new LocalPluginBootstrapError(changed);
2368
+ const canonicalSource = await realpath(source.path).catch(nullIfMissingFileError);
2369
+ if (canonicalSource === null)
2370
+ return;
2371
+ if (protectedPath(canonicalSource))
2372
+ throw new LocalPluginBootstrapError(changed);
2373
+ let workspace;
2374
+ const parents = [...new Set([dirname(scanDirectory), tmpdir()])].filter((parent) => !protectedPath(parent) && !isWithin(scanDirectory, parent));
2375
+ // PowerShell may fail to launch the selected plugin's .cmd at a long path.
2376
+ // Prefer the shorter canonical parent, retaining the output parent on ties.
2377
+ const candidates = await abortable(() => Promise.allSettled(parents.map((path) => realpath(path))), signal);
2378
+ const length = (candidate) => candidate.status === "fulfilled" ? candidate.value.length : Infinity;
2379
+ for (const candidate of candidates.sort((a, b) => length(a) - length(b))) {
2380
+ throwIfSignalAborted(signal);
2381
+ try {
2382
+ if (candidate.status === "rejected")
2383
+ throw candidate.reason;
2384
+ const canonical = candidate.value;
2385
+ if (protectedPath(canonical) || isWithin(scanDirectory, canonical))
2386
+ continue;
2387
+ // Host-side plugin helpers may execute from this copy. A sibling keeps it
2388
+ // outside the writable scan, and the native creator verifies its parents.
2389
+ workspace = await prepareOutputDir(undefined, "plugin-input", canonical, validateLocation);
2390
+ break;
2391
+ }
2392
+ catch (error) {
2393
+ if (!(error instanceof OutputDirectoryError) &&
2394
+ !["EACCES", "EPERM", "ENOENT"].includes(nodeErrorCode(error) ?? ""))
2395
+ throw error;
2396
+ }
2397
+ }
2398
+ // Keep existing plugin handling where neither scan input location is usable.
2399
+ if (workspace === undefined)
2400
+ return;
2401
+ try {
2402
+ throwIfSignalAborted(signal);
2403
+ const digest = createHash("sha256");
2404
+ const root = await extractValidatedPluginZip(source.path, join(workspace, "plugin"), signal, digest);
2405
+ throwIfSignalAborted(signal);
2406
+ if (digest.digest("hex") !== source.digest) {
2407
+ throw new LocalPluginBootstrapError(changed);
2408
+ }
2409
+ return { workspace, root };
2410
+ }
2411
+ catch (error) {
2412
+ try {
2413
+ await cleanupSdkDirectory(workspace);
2414
+ }
2415
+ catch (cleanupError) {
2416
+ throwIfSignalAborted(signal);
2417
+ throw new LocalPluginBootstrapError(`${errorMessage(error)}\nCould not remove scan input directory ${workspace}: ${errorMessage(cleanupError)}`, { cause: error });
2418
+ }
2419
+ throwIfSignalAborted(signal);
2420
+ const cause = error instanceof PluginBootstrapError ? error.cause : undefined;
2421
+ if (isRecord(cause) &&
2422
+ cause["code"] === "ENOENT" &&
2423
+ cause["syscall"] === "open" &&
2424
+ cause["path"] === source.path)
2425
+ return;
2426
+ throw error;
2427
+ }
2428
+ }
1906
2429
  export async function createMarketplace(codexHome, pluginRoot, signal) {
1907
2430
  try {
1908
2431
  throwIfSignalAborted(signal);
@@ -1955,6 +2478,20 @@ async function writeMarketplaceManifest(marketplace, signal) {
1955
2478
  await rm(temporary, { force: true });
1956
2479
  }
1957
2480
  }
2481
+ // Private handoff to the staged SDK launcher and shell-invoked helpers.
2482
+ export const SDK_NODE_SEARCH_PATH = "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH";
2483
+ export async function sdkNodeSearchPath(roots) {
2484
+ let fallback = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin";
2485
+ const current = dirname(process.execPath);
2486
+ if (process.release.name === "node" &&
2487
+ !process.versions["bun"] &&
2488
+ !process.versions["electron"] &&
2489
+ basename(process.execPath) === "node" &&
2490
+ !current.includes(":"))
2491
+ fallback += `:${current}`;
2492
+ const inspected = await inspectTrustedExecutable("node", { PATH: fallback }, roots);
2493
+ return inspected.environment["PATH"] ?? "";
2494
+ }
1958
2495
  async function pluginRuntimeProjection(root, signal) {
1959
2496
  const path = join(root, ".mcp.json");
1960
2497
  // Keep the source link checks ahead of any configuration read.
@@ -1973,13 +2510,10 @@ async function pluginRuntimeProjection(root, signal) {
1973
2510
  const environment = server["env_vars"];
1974
2511
  if (environment !== undefined && !Array.isArray(environment))
1975
2512
  return;
1976
- if (!Array.isArray(environment) ||
1977
- !environment.includes("CODEX_SECURITY_PLUGIN_ROOT")) {
1978
- server["env_vars"] = [
1979
- ...(Array.isArray(environment) ? environment : []),
1980
- "CODEX_SECURITY_PLUGIN_ROOT",
1981
- ];
1982
- }
2513
+ server["env_vars"] = [
2514
+ ...(environment ?? []),
2515
+ ...["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"].filter((name) => !environment?.includes(name)),
2516
+ ];
1983
2517
  const files = new Map();
1984
2518
  server["command"] =
1985
2519
  server["command"] === "./scripts/launch_codex_security_mcp.cmd"
@@ -1990,7 +2524,7 @@ async function pluginRuntimeProjection(root, signal) {
1990
2524
  'if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ]; then\n' +
1991
2525
  ' exec "$CODEX_SECURITY_PLUGIN_ROOT/scripts/launch_codex_security_mcp" "$@"\n' +
1992
2526
  "fi\n" +
1993
- 'exec "$(dirname "$0")/launch_codex_security_mcp" "$@"\n'),
2527
+ 'exec "$(command -p dirname "$0")/launch_codex_security_mcp" "$@"\n'),
1994
2528
  mode: 0o755,
1995
2529
  });
1996
2530
  files.set("scripts/launch_codex_security_mcp_sdk.cmd", {
@@ -2007,10 +2541,10 @@ async function pluginRuntimeProjection(root, signal) {
2007
2541
  return { root, files };
2008
2542
  }
2009
2543
  export function resolveCodexCommand(environment = process.env) {
2010
- const configured = environmentValue(environment, "CODEX_CLI_PATH");
2544
+ const configured = configuredExecutableValue(environmentValue(environment, "CODEX_CLI_PATH", true), process.platform, (value) => isExecutableFile(expandHomeForLookup(value, environment)));
2011
2545
  const expanded = configured === undefined
2012
2546
  ? undefined
2013
- : expandExecutableHome(configured, environment);
2547
+ : expandHomeForLookup(configured, environment);
2014
2548
  if (expanded &&
2015
2549
  (process.platform !== "win32" || /\.(?:exe|com)$/iu.test(expanded))) {
2016
2550
  return {
@@ -2071,8 +2605,22 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2071
2605
  ? null
2072
2606
  : await pluginMetadata(join(marketplace, "plugins", PLUGIN_NAME)).catch(() => null);
2073
2607
  const stagedRoot = join(marketplace, "plugins", PLUGIN_NAME);
2074
- const stagedMatches = staged?.version === version &&
2075
- (await pluginContentsMatch(root, stagedRoot, options.signal, false, projection));
2608
+ const matchesSelected = (destination, allowExtraFiles = false, generatedDirectory) => pluginContentsMatch(root, destination, options.signal, allowExtraFiles, projection, generatedDirectory);
2609
+ const stagedMatches = staged?.version === version && (await matchesSelected(stagedRoot));
2610
+ const matchesNativeInstall = async (installedRoot, allowRuntimeFiles = false) => (await matchesSelected(stagedRoot)) &&
2611
+ // Ordinary reuse permits runtime files when all selected bytes are present.
2612
+ // The native receipt still verifies the complete generated command output.
2613
+ ((allowRuntimeFiles && (await matchesSelected(installedRoot, true))) ||
2614
+ (await matchesSelected(installedRoot, false, migratedCommands(installedRoot))));
2615
+ const nativeMigration = (installedRoot, allowRuntimeFiles = false) => verifiedCommandMigration(installedRoot, (path) => matchesNativeInstall(path, allowRuntimeFiles), options.signal);
2616
+ const matchesReceipt = async (installedRoot, migration) => {
2617
+ if (typeof migration === "string" &&
2618
+ options.runCodex === undefined &&
2619
+ (await isBundledPluginInstaller(command))) {
2620
+ return (await nativeMigration(installedRoot, true)) === migration;
2621
+ }
2622
+ return matchesSelected(installedRoot, true);
2623
+ };
2076
2624
  if (!stagedMatches) {
2077
2625
  if (existing !== null) {
2078
2626
  await rm(marketplace, { recursive: true, force: true });
@@ -2103,9 +2651,18 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2103
2651
  const previous = await readFile(installRecord, "utf8")
2104
2652
  .then((value) => JSON.parse(value))
2105
2653
  .catch((error) => {
2106
- if (nodeErrorCode(error) === "ENOENT" || error instanceof SyntaxError) {
2654
+ const code = nodeErrorCode(error);
2655
+ if (code === "ENOENT" || error instanceof SyntaxError) {
2107
2656
  return null;
2108
2657
  }
2658
+ if (process.platform === "win32" &&
2659
+ error instanceof Error &&
2660
+ (code === "EACCES" || code === "EPERM")) {
2661
+ // Keep the original system error, including its path, code and syscall.
2662
+ error.message +=
2663
+ " If the SDK created this plugin installation receipt but cannot reopen it, " +
2664
+ "check its read permissions and the permissions new files inherit from the sdk-marketplace directory.";
2665
+ }
2109
2666
  throw error;
2110
2667
  });
2111
2668
  const plugins = configuration["plugins"];
@@ -2121,7 +2678,7 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2121
2678
  isRecord(previous) &&
2122
2679
  typeof previous["installedPath"] === "string" &&
2123
2680
  previous["version"] === version &&
2124
- (await pluginContentsMatch(root, previous["installedPath"], options.signal, true, projection))) {
2681
+ (await matchesReceipt(previous["installedPath"], previous["nativeCommandMigration"]))) {
2125
2682
  return {
2126
2683
  pluginRoot: root,
2127
2684
  marketplaceRoot: marketplace,
@@ -2131,7 +2688,35 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2131
2688
  version,
2132
2689
  };
2133
2690
  }
2134
- const output = await run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2691
+ const addPlugin = () => run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2692
+ let output;
2693
+ let retried = false;
2694
+ try {
2695
+ output = await addPlugin();
2696
+ }
2697
+ catch (first) {
2698
+ if (!isRolledBackPluginActivation(first))
2699
+ throw first;
2700
+ throwIfSignalAborted(options.signal);
2701
+ if (!(await isBundledPluginInstaller(command)))
2702
+ throw first;
2703
+ // The bundled CLI restored the old cache. A short-lived Windows reader
2704
+ // of the new tree can release it before a fresh installation attempt.
2705
+ try {
2706
+ await delay(100, undefined, { signal: options.signal });
2707
+ throwIfSignalAborted(options.signal);
2708
+ if (!(await matchesSelected(stagedRoot))) {
2709
+ throw new LocalPluginBootstrapError("The selected plugin or its marketplace changed before the native installation could be retried.", { cause: first });
2710
+ }
2711
+ throwIfSignalAborted(options.signal);
2712
+ output = await addPlugin();
2713
+ retried = true;
2714
+ }
2715
+ catch (second) {
2716
+ throwIfSignalAborted(options.signal);
2717
+ throw isRolledBackPluginActivation(second) ? first : second;
2718
+ }
2719
+ }
2135
2720
  let installed;
2136
2721
  try {
2137
2722
  installed = JSON.parse(output);
@@ -2144,9 +2729,25 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2144
2729
  installed["version"] !== version) {
2145
2730
  throw new PluginBootstrapError("Codex plugin install did not return the selected plugin path and version.");
2146
2731
  }
2732
+ // The bundled installer removes stale command skills before regenerating them.
2733
+ const bundledInstaller = retried ||
2734
+ (options.runCodex === undefined &&
2735
+ (await isBundledPluginInstaller(command)));
2736
+ const hasSourceMigration = bundledInstaller &&
2737
+ (await lstat(migratedCommands(root)).catch(nullIfMissingFileError))?.isDirectory() === true;
2738
+ const nativeCommandMigration = hasSourceMigration
2739
+ ? await nativeMigration(installed["installedPath"])
2740
+ : undefined;
2741
+ if (retried &&
2742
+ !(hasSourceMigration
2743
+ ? nativeCommandMigration !== undefined
2744
+ : await matchesNativeInstall(installed["installedPath"]))) {
2745
+ throw new PluginBootstrapError("The retried Codex plugin install did not install the selected plugin contents.");
2746
+ }
2147
2747
  await writeFile(installRecord, JSON.stringify({
2148
2748
  installedPath: installed["installedPath"],
2149
2749
  version,
2750
+ ...(nativeCommandMigration ? { nativeCommandMigration } : {}),
2150
2751
  }), { mode: 0o600, signal: options.signal });
2151
2752
  return {
2152
2753
  pluginRoot: root,
@@ -2157,7 +2758,92 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2157
2758
  version,
2158
2759
  };
2159
2760
  }
2160
- async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection) {
2761
+ async function isBundledPluginInstaller(command) {
2762
+ try {
2763
+ return await sameFile(command.command, resolveBundledCodexExecutable());
2764
+ }
2765
+ catch {
2766
+ return false;
2767
+ }
2768
+ }
2769
+ function migratedCommands(plugin) {
2770
+ return join(plugin, ".codex-plugin", "migrated-command-skills");
2771
+ }
2772
+ // Bind a receipt to the generated files observed in this installation.
2773
+ // Entry names come from its directories, never from the saved digest.
2774
+ async function verifiedCommandMigration(installedRoot, matchesSelected, signal) {
2775
+ const digest = createHash("sha256");
2776
+ const record = (...fields) => digest.update(JSON.stringify(fields)).update("\n");
2777
+ async function visit(path, name) {
2778
+ throwIfSignalAborted(signal);
2779
+ const metadata = await lstat(path, { bigint: true });
2780
+ if (metadata.isSymbolicLink() ||
2781
+ relative(path, await realpath(path)) !== "")
2782
+ return false;
2783
+ if (metadata.isDirectory()) {
2784
+ record("directory", name);
2785
+ for (const entry of (await readdir(path)).sort()) {
2786
+ const child = join(path, entry);
2787
+ if (!(await visit(child, name ? `${name}/${entry}` : entry)))
2788
+ return false;
2789
+ }
2790
+ return sameInode(metadata, await lstat(path, { bigint: true }));
2791
+ }
2792
+ if (!metadata.isFile())
2793
+ return false;
2794
+ const file = await open(path, constants.O_RDONLY |
2795
+ (constants.O_NOFOLLOW ?? 0) |
2796
+ (constants.O_NONBLOCK ?? 0));
2797
+ try {
2798
+ const opened = await file.stat({ bigint: true });
2799
+ if (!opened.isFile())
2800
+ return false;
2801
+ if (!sameInode(metadata, opened)) {
2802
+ if (process.platform !== "win32")
2803
+ return false;
2804
+ // Some Windows Node versions report a different device on an open handle.
2805
+ const { sameCheckedFileDevice } = await import("./contract.js");
2806
+ if (!(await sameCheckedFileDevice(file, { path, metadata }, opened)))
2807
+ return false;
2808
+ }
2809
+ const contents = createHash("sha256")
2810
+ .update(await file.readFile({ signal }))
2811
+ .digest("hex");
2812
+ record("file", name, Number(opened.mode & 73n), contents);
2813
+ }
2814
+ finally {
2815
+ await file.close();
2816
+ }
2817
+ return true;
2818
+ }
2819
+ throwIfSignalAborted(signal);
2820
+ const installation = await lstat(installedRoot, { bigint: true }).catch(nullIfMissingFileError);
2821
+ if (!installation?.isDirectory() ||
2822
+ installation.ino === 0n ||
2823
+ !(await matchesSelected(installedRoot)))
2824
+ return;
2825
+ try {
2826
+ const directory = migratedCommands(await realpath(installedRoot));
2827
+ const parent = dirname(directory);
2828
+ if (!(await lstat(parent)).isDirectory() ||
2829
+ relative(parent, await realpath(parent)) !== "")
2830
+ return;
2831
+ const root = await lstat(directory, { bigint: true }).catch(nullIfMissingFileError);
2832
+ if (root && (!root.isDirectory() || !(await visit(directory, ""))))
2833
+ return;
2834
+ // Native activation replaces the installed directory even at the same version.
2835
+ if (!sameInode(installation, await lstat(installedRoot, { bigint: true })))
2836
+ return;
2837
+ throwIfSignalAborted(signal);
2838
+ return root ? `sha256:${digest.digest("hex")}` : "absent";
2839
+ }
2840
+ catch (error) {
2841
+ throwIfSignalAborted(signal);
2842
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EISDIR", "EACCES", "EPERM"].includes(nodeErrorCode(error) ?? ""))
2843
+ throw error;
2844
+ }
2845
+ }
2846
+ async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection, generatedDirectory) {
2161
2847
  throwIfSignalAborted(signal);
2162
2848
  const sourceMetadata = await lstat(source);
2163
2849
  const destinationMetadata = await lstat(destination).catch((error) => {
@@ -2186,15 +2872,39 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2186
2872
  if (!sourceMetadata.isDirectory() || !destinationMetadata.isDirectory()) {
2187
2873
  return false;
2188
2874
  }
2189
- const entries = await readdir(source);
2875
+ let entries = await readdir(source);
2876
+ let nativeOutputs = 0;
2877
+ if (generatedDirectory) {
2878
+ const parent = dirname(generatedDirectory);
2879
+ if (parent === destination ||
2880
+ (relative(parent, destination) === "" &&
2881
+ (await sameFile(parent, destination)))) {
2882
+ // The installer removes old command output before regenerating it. Resolve
2883
+ // its source spelling on volumes that preserve case but ignore it on lookup.
2884
+ const path = join(source, basename(generatedDirectory));
2885
+ const original = await lstat(path).catch(nullIfMissingFileError);
2886
+ if (original?.isSymbolicLink())
2887
+ return false;
2888
+ if (original) {
2889
+ const name = basename(await realpath(path));
2890
+ entries = entries.filter((entry) => entry !== name);
2891
+ }
2892
+ const installed = await lstat(generatedDirectory).catch(nullIfMissingFileError);
2893
+ if (installed) {
2894
+ if (!installed.isDirectory())
2895
+ return false;
2896
+ nativeOutputs = 1;
2897
+ }
2898
+ }
2899
+ }
2190
2900
  const projectedDirectory = projection === undefined
2191
2901
  ? undefined
2192
2902
  : relative(projection.root, source).split(sep).join("/") || ".";
2193
2903
  const generated = [...(projection?.files ?? [])].filter(([path]) => dirname(path) === projectedDirectory && !entries.includes(basename(path)));
2194
2904
  if (!allowExtraFiles &&
2195
- entries.length + generated.length !== (await readdir(destination)).length) {
2905
+ entries.length + generated.length + nativeOutputs !==
2906
+ (await readdir(destination)).length)
2196
2907
  return false;
2197
- }
2198
2908
  for (const [path, file] of generated) {
2199
2909
  const generatedPath = join(destination, basename(path));
2200
2910
  const metadata = await lstat(generatedPath).catch(nullIfMissingFileError);
@@ -2206,7 +2916,7 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2206
2916
  }
2207
2917
  }
2208
2918
  for (const entry of entries) {
2209
- if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection))) {
2919
+ if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection, generatedDirectory))) {
2210
2920
  return false;
2211
2921
  }
2212
2922
  }
@@ -2237,12 +2947,10 @@ export async function pluginMetadata(root) {
2237
2947
  }
2238
2948
  export async function resolvePluginPython(options = {}) {
2239
2949
  const environment = options.environment ?? process.env;
2240
- const requestedRoots = options.protectedRoot ?? process.cwd();
2950
+ const cwd = process.cwd();
2951
+ const requestedRoots = options.protectedRoot ?? cwd;
2241
2952
  const protectedRoot = typeof requestedRoots === "string" ? [requestedRoots] : [...requestedRoots];
2242
- const callerDirectories = [
2243
- process.cwd(),
2244
- options.currentDirectory ?? process.cwd(),
2245
- ];
2953
+ const callerDirectories = new Set([cwd, options.currentDirectory ?? cwd]);
2246
2954
  // Preserve target and enclosing-checkout protection for every interpreter.
2247
2955
  for (const directory of new Set([...callerDirectories, ...protectedRoot])) {
2248
2956
  for (const checkout of await gitProtectionRoots(directory, options.signal))
@@ -2251,22 +2959,59 @@ export async function resolvePluginPython(options = {}) {
2251
2959
  }
2252
2960
  // Named interpreters are ambient PATH discovery, even when PYTHON names one.
2253
2961
  // Explicit trusted paths and managed runtimes retain their existing precedence.
2254
- const discoveryRoots = [...protectedRoot, ...callerDirectories];
2962
+ const discoveryRoots = [
2963
+ ...protectedRoot,
2964
+ ...(options.discoveryProtectedRoots ?? []),
2965
+ ];
2966
+ for (const directory of callerDirectories) {
2967
+ const physical = directory === cwd
2968
+ ? cwd
2969
+ : await realpath(directory).catch(() => undefined);
2970
+ // A filesystem-root launch directory also contains the operator's installed tools.
2971
+ // Explicit scan roots and enclosing checkouts are already in protectedRoot.
2972
+ if (protectedRoot.length === 0 ||
2973
+ physical === undefined ||
2974
+ dirname(physical) !== physical)
2975
+ discoveryRoots.push(directory);
2976
+ }
2977
+ const missingBoundaryMessage = "Could not establish the saved checkout boundary for Python discovery. Set PYTHON to an absolute trusted interpreter.";
2255
2978
  if (options.configuredPath !== undefined) {
2979
+ if (!isPythonPathCandidate(options.configuredPath) &&
2980
+ options.allowPathLookup === false)
2981
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2256
2982
  return await requirePython(options.configuredPath, "configured plugin Python", environment, isPythonPathCandidate(options.configuredPath)
2257
2983
  ? protectedRoot
2258
2984
  : discoveryRoots, options.signal);
2259
2985
  }
2260
- const inherited = environmentValue(environment, "PYTHON");
2986
+ const inherited = environmentValue(environment, "PYTHON", true);
2261
2987
  if (inherited) {
2262
- return await requirePython(inherited, "PYTHON", environment, isPythonPathCandidate(inherited) ? protectedRoot : discoveryRoots, options.signal);
2988
+ if (!isPythonPathCandidate(inherited) && options.allowPathLookup === false)
2989
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2990
+ const roots = isPythonPathCandidate(inherited)
2991
+ ? protectedRoot
2992
+ : discoveryRoots;
2993
+ // Check an explicit literal path with the same repository protections as the launch.
2994
+ const candidate = isExplicitPathWithTrailingWhitespace(inherited, process.platform) &&
2995
+ (await resolveTrustedExecutable(expandHomeForLookup(inherited, environment), environment, roots))
2996
+ ? inherited
2997
+ : inherited.trim();
2998
+ return await requirePython(candidate, "PYTHON", environment, roots, options.signal);
2999
+ }
3000
+ let managedRoots = options.managedRuntimeRoots;
3001
+ if (managedRoots === undefined) {
3002
+ try {
3003
+ const cache = environmentValue(environment, "XDG_CACHE_HOME", true) ||
3004
+ join(options.homeDirectory ?? homedir(), ".cache");
3005
+ managedRoots = [join(cache, "codex-runtimes", "codex-primary-runtime")];
3006
+ }
3007
+ catch (error) {
3008
+ // A numeric Linux UID can lack a home for the optional managed cache.
3009
+ if (process.platform !== "linux" ||
3010
+ error.info?.code !== "ENOENT")
3011
+ throw error;
3012
+ managedRoots = [];
3013
+ }
2263
3014
  }
2264
- const home = options.homeDirectory ?? homedir();
2265
- const cacheDirectory = environmentValue(environment, "XDG_CACHE_HOME", true) ||
2266
- join(home, ".cache");
2267
- const managedRoots = options.managedRuntimeRoots ?? [
2268
- join(cacheDirectory, "codex-runtimes", "codex-primary-runtime"),
2269
- ];
2270
3015
  const relativeCandidates = process.platform === "win32"
2271
3016
  ? [
2272
3017
  join("dependencies", "python", "python.exe"),
@@ -2285,6 +3030,8 @@ export async function resolvePluginPython(options = {}) {
2285
3030
  return resolved;
2286
3031
  }
2287
3032
  }
3033
+ if (options.allowPathLookup === false)
3034
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2288
3035
  for (const candidate of process.platform === "win32"
2289
3036
  ? ["python", "python3", "py"]
2290
3037
  : ["python3", "python"]) {
@@ -2296,14 +3043,12 @@ export async function resolvePluginPython(options = {}) {
2296
3043
  "Set pythonPath, --python, or PYTHON, install the Codex managed runtime, or add python3/python (py on Windows) to PATH.");
2297
3044
  }
2298
3045
  export function pluginExecutionEnvironment(python, environment = process.env) {
2299
- const child = {
3046
+ return {
2300
3047
  ...pythonUtf8Environment(environment),
2301
3048
  PYTHON: python,
2302
3049
  CODEX_SECURITY_PYTHON_COMMAND: python,
2303
3050
  CODEX_CLI_PATH: resolveCodexCommand(environment).command,
2304
3051
  };
2305
- forwardExternalImportSetting(environment, child);
2306
- return child;
2307
3052
  }
2308
3053
  export function environmentWithGit(environment, git) {
2309
3054
  if (git === undefined)
@@ -2334,35 +3079,56 @@ function pluginHelperEnvironment(environment) {
2334
3079
  export async function cleanupSdkDirectory(path) {
2335
3080
  await rm(path, { recursive: true, force: true });
2336
3081
  }
2337
- export async function runCodexCommand(command, args, environment, input, signal, archiveHandshake = false, stdinPrefix) {
2338
- const cancellation = archiveHandshake ? new AbortController() : undefined;
3082
+ // A child can finish or reject a request before the parent finishes writing it.
3083
+ export function isDisconnectedChildStdin(error) {
3084
+ return [
3085
+ "EPIPE",
3086
+ "ECONNRESET",
3087
+ "ENOTCONN",
3088
+ "EOF",
3089
+ "ERR_STREAM_DESTROYED",
3090
+ ].includes(error.code ?? "");
3091
+ }
3092
+ export async function runCodexCommand(command, args, environment, input, launchSignal, { registrationHandshake = false, stdinPrefix, cwd, } = {}) {
3093
+ const campaign = campaignExecutable(command.command, environment);
3094
+ const selected = campaign && (await campaign);
3095
+ const executable = selected?.executable ?? command.command;
3096
+ const commandArgs = typeof args === "function" ? args(executable) : args;
3097
+ const signal = typeof launchSignal === "function" ? launchSignal() : launchSignal;
3098
+ const cancellation = registrationHandshake
3099
+ ? new AbortController()
3100
+ : undefined;
2339
3101
  const abort = () => cancellation?.abort(signal?.reason);
2340
3102
  const commandSignal = cancellation?.signal ?? signal;
2341
- let awaitingArchive = archiveHandshake;
2342
- const child = spawn(executablePathForSpawn(command.command), [...(command.args ?? []), ...args], {
2343
- env: environment,
2344
- stdio: ["pipe", "pipe", "pipe"],
3103
+ const child = spawn(executablePathForSpawn(executable), [...(command.args ?? []), ...commandArgs], {
3104
+ cwd,
3105
+ env: selected?.environment ?? environment,
3106
+ stdio: registrationHandshake
3107
+ ? ["pipe", "pipe", "pipe", "pipe"]
3108
+ : ["pipe", "pipe", "pipe"],
2345
3109
  windowsHide: true,
2346
3110
  signal: commandSignal,
2347
3111
  });
2348
3112
  let stdout = "";
2349
3113
  let stderr = "";
2350
3114
  let processError;
3115
+ const control = child.stdio[3];
3116
+ control?.once("data", () => {
3117
+ // The helper cannot change the output until the host allows the transaction.
3118
+ signal?.removeEventListener("abort", abort);
3119
+ if (signal?.aborted)
3120
+ abort();
3121
+ else
3122
+ control.end("!");
3123
+ });
3124
+ control?.on("error", (error) => {
3125
+ if (!isDisconnectedChildStdin(error))
3126
+ processError = error;
3127
+ });
2351
3128
  child.stdout.setEncoding("utf8");
2352
3129
  child.stderr.setEncoding("utf8");
2353
3130
  child.stdout.on("data", (chunk) => {
2354
3131
  stdout += chunk;
2355
- if (awaitingArchive && stdout.startsWith(ARCHIVE_READY)) {
2356
- awaitingArchive = false;
2357
- stdout = stdout.slice(ARCHIVE_READY.length);
2358
- signal?.removeEventListener("abort", abort);
2359
- // The helper cannot rename until this acknowledgement. Detach and check
2360
- // cancellation before allowing the filesystem/database transaction.
2361
- if (signal?.aborted)
2362
- abort();
2363
- else
2364
- child.stdin.end("\n");
2365
- }
2366
3132
  });
2367
3133
  child.stderr.on("data", (chunk) => {
2368
3134
  stderr += chunk;
@@ -2372,7 +3138,7 @@ export async function runCodexCommand(command, args, environment, input, signal,
2372
3138
  processError = error;
2373
3139
  });
2374
3140
  child.stdin.on("error", (error) => {
2375
- if (!["EPIPE", "ECONNRESET", "EOF", "ERR_STREAM_DESTROYED"].includes(error.code ?? ""))
3141
+ if (!isDisconnectedChildStdin(error))
2376
3142
  processError = error;
2377
3143
  });
2378
3144
  child.once("close", (exitCode) => processError === undefined
@@ -2391,12 +3157,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2391
3157
  child.stdin.destroy();
2392
3158
  child.stdout.destroy();
2393
3159
  child.stderr.destroy();
3160
+ control?.destroy();
2394
3161
  };
2395
3162
  commandSignal?.addEventListener("abort", settleCanceledChild, { once: true });
2396
3163
  child.once("exit", settleCanceledChild);
2397
3164
  if (commandSignal?.aborted)
2398
3165
  settleCanceledChild();
2399
- if (archiveHandshake) {
3166
+ if (registrationHandshake) {
2400
3167
  signal?.addEventListener("abort", abort, { once: true });
2401
3168
  if (signal?.aborted)
2402
3169
  abort();
@@ -2404,15 +3171,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2404
3171
  try {
2405
3172
  if (stdinPrefix !== undefined)
2406
3173
  child.stdin.write(stdinPrefix);
2407
- if (archiveHandshake)
2408
- child.stdin.write(`${JSON.stringify(input ?? "")}\n`);
2409
- else
2410
- child.stdin.end(input);
3174
+ child.stdin.end(input);
2411
3175
  return await completion;
2412
3176
  }
2413
3177
  finally {
2414
- if (archiveHandshake)
3178
+ if (registrationHandshake)
2415
3179
  signal?.removeEventListener("abort", abort);
3180
+ control?.destroy();
2416
3181
  clearTimeout(forceTermination);
2417
3182
  commandSignal?.removeEventListener("abort", settleCanceledChild);
2418
3183
  child.removeListener("exit", settleCanceledChild);
@@ -2423,11 +3188,24 @@ export async function probeCodexSandbox(command, environment, signal) {
2423
3188
  if (process.platform === "win32")
2424
3189
  return;
2425
3190
  // Reuse the resolved Codex executable instead of looking up a probe on PATH.
2426
- const args = ["sandbox", "--", command.command, "--version"];
2427
- const timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
3191
+ const args = (executable) => [
3192
+ "sandbox",
3193
+ "--",
3194
+ executable,
3195
+ "--version",
3196
+ ];
3197
+ signal?.throwIfAborted();
3198
+ let timeout;
2428
3199
  let detail;
2429
3200
  try {
2430
- const result = await runCodexCommand(command, args, environment, undefined, signal === undefined ? timeout : AbortSignal.any([signal, timeout]));
3201
+ const result = await runCodexCommand(command, args, environment, undefined, () => {
3202
+ // Campaign tool selection happens before the sandbox process starts.
3203
+ signal?.throwIfAborted();
3204
+ timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
3205
+ return signal === undefined
3206
+ ? timeout
3207
+ : AbortSignal.any([signal, timeout]);
3208
+ });
2431
3209
  if (result.success)
2432
3210
  return;
2433
3211
  detail =
@@ -2437,20 +3215,49 @@ export async function probeCodexSandbox(command, environment, signal) {
2437
3215
  }
2438
3216
  catch (error) {
2439
3217
  signal?.throwIfAborted();
3218
+ if (timeout?.aborted)
3219
+ throw new SandboxUnavailableError(`Codex sandbox probe timed out after ${SANDBOX_PROBE_TIMEOUT_MILLISECONDS / 1000} seconds.`, { cause: error });
2440
3220
  detail = processErrorDetail(error);
2441
3221
  }
2442
3222
  const guidance = process.platform === "linux"
2443
3223
  ? "\nOn Linux this usually means unprivileged user namespaces are restricted (kernel.apparmor_restrict_unprivileged_userns=1 on Ubuntu 24.04 and later), which Bubblewrap needs; inside the container image, use the AppArmor profile and Compose override from the SDK README."
2444
3224
  : "";
2445
- throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args.join(" ")}'.${guidance}`);
3225
+ throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args(command.command).join(" ")}'.${guidance}`);
3226
+ }
3227
+ class RolledBackPluginActivationError extends Error {
3228
+ }
3229
+ function isRolledBackPluginActivation(error) {
3230
+ return (error instanceof PluginBootstrapError &&
3231
+ error.cause instanceof RolledBackPluginActivationError);
2446
3232
  }
2447
3233
  async function runPluginCommand(command, args, environment, signal) {
2448
3234
  try {
2449
- const { success, exitCode, stdout, stderr } = await runCodexCommand(command, args, environment, undefined, signal);
3235
+ const run = (argv, cwd) => runCodexCommand(command, argv, environment, undefined, signal, { cwd });
3236
+ let result = await run(args);
3237
+ const source = args[1] === "marketplace" ? args[3] : undefined;
3238
+ if (result.exitCode === 1 &&
3239
+ source?.includes("#") &&
3240
+ result.stderr
3241
+ .split(/\r?\n/u)
3242
+ .includes("Error: --ref is only supported for git marketplace sources")) {
3243
+ // Native Codex parsed a literal hash in the local path as a Git ref.
3244
+ result = await run(["plugin", "marketplace", "add", "."], source);
3245
+ }
3246
+ const { success, exitCode, stdout, stderr } = result;
2450
3247
  if (!success) {
2451
- throw new Error(stderr.trim() ||
3248
+ const detail = stderr.trim() ||
2452
3249
  stdout.trim() ||
2453
- `Codex exited with status ${exitCode}.`);
3250
+ `Codex exited with status ${exitCode}.`;
3251
+ // This native headline is emitted only after the previous entry was
3252
+ // restored. The Windows message itself may be localized.
3253
+ if (process.platform === "win32" &&
3254
+ args[0] === "plugin" &&
3255
+ args[1] === "add" &&
3256
+ exitCode === 1 &&
3257
+ /^Error: failed to activate updated plugin cache entry: [^\r\n]+ \(os error 5\)(?:\r?\n|$)/u.test(stderr) &&
3258
+ !stderr.includes("failed to restore previous cache entry"))
3259
+ throw new RolledBackPluginActivationError(detail);
3260
+ throw new Error(detail);
2454
3261
  }
2455
3262
  return stdout;
2456
3263
  }
@@ -2476,7 +3283,7 @@ async function validatePluginRoot(root) {
2476
3283
  await pluginMetadata(root);
2477
3284
  return await realpath(root);
2478
3285
  }
2479
- async function copyPluginTree(source, destination, signal) {
3286
+ export async function copyPluginTree(source, destination, signal) {
2480
3287
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
2481
3288
  try {
2482
3289
  await cp(source, destination, {
@@ -2538,26 +3345,19 @@ async function requirePython(candidate, source, environment, protectedRoot, sign
2538
3345
  }
2539
3346
  async function usablePython(candidate, environment = process.env, protectedRoot = process.cwd(), signal) {
2540
3347
  const command = await resolveTrustedExecutable(isPythonPathCandidate(candidate)
2541
- ? expandExecutableHome(candidate, environment)
3348
+ ? expandHomeForLookup(candidate, environment)
2542
3349
  : candidate, environment, protectedRoot);
2543
3350
  if (command === null)
2544
3351
  return null;
2545
3352
  try {
2546
- const { stdout } = await execFile(command.executable, [
2547
- "-I",
2548
- "-c",
2549
- "import importlib.util,sys\nif sys.version_info < (3, 10): raise SystemExit(1)\nif sys.version_info < (3, 11) and importlib.util.find_spec('tomli') is None: raise SystemExit(1)\nprint('codex-security-python-ok')",
2550
- ], {
3353
+ const { stdout } = await execFile(command.executable, ["-I", "-c", PLUGIN_PYTHON_PROBE], {
2551
3354
  env: command.environment,
2552
3355
  encoding: "utf8",
2553
- // Cold Python startup can exceed five seconds on busy Windows hosts.
2554
- timeout: 30_000,
3356
+ timeout: PLUGIN_PYTHON_PROBE_TIMEOUT_MS,
2555
3357
  windowsHide: true,
2556
3358
  signal,
2557
3359
  });
2558
- return stdout.trim() === "codex-security-python-ok"
2559
- ? command.executable
2560
- : null;
3360
+ return stdout.trim() === PLUGIN_PYTHON_READY ? command.executable : null;
2561
3361
  }
2562
3362
  catch (error) {
2563
3363
  if (signal?.aborted)
@@ -2568,19 +3368,47 @@ async function usablePython(candidate, environment = process.env, protectedRoot
2568
3368
  export function isPythonPathCandidate(candidate) {
2569
3369
  return candidate.includes("/") || candidate.includes("\\");
2570
3370
  }
2571
- async function hasPluginManifest(root) {
2572
- return await lstat(join(root, ".codex-plugin", "plugin.json")).then((metadata) => metadata.isFile(), () => false);
2573
- }
2574
3371
  /** @internal Compare filesystem identity without depending on path spelling. */
2575
3372
  export function sameFile(left, right) {
2576
3373
  // NTFS file IDs can exceed JavaScript's safe integer range.
2577
3374
  return Promise.all([
2578
3375
  stat(left, { bigint: true }),
2579
3376
  stat(right, { bigint: true }),
2580
- ]).then(([leftMetadata, rightMetadata]) => leftMetadata.dev === rightMetadata.dev &&
2581
- leftMetadata.ino === rightMetadata.ino, () => false);
3377
+ ]).then(([leftMetadata, rightMetadata]) => sameInode(leftMetadata, rightMetadata), () => false);
2582
3378
  }
2583
- function expandExecutableHome(value, environment) {
3379
+ export function resolveInputPath(value, directory = process.cwd(), environment = process.env) {
3380
+ if (value === "~")
3381
+ value = expandHome("~", environment);
3382
+ else if (value.startsWith("~/") || value.startsWith("~\\")) {
3383
+ const home = expandHome("~", environment);
3384
+ const suffix = value.startsWith("~\\")
3385
+ ? value.slice(2).split("\\").filter(Boolean).join(sep)
3386
+ : value.slice(2);
3387
+ value = home === "" ? suffix : `${home}${sep}${suffix}`;
3388
+ }
3389
+ return resolveTargetPath(value, directory);
3390
+ }
3391
+ /** Resolve through the last parent traversal while retaining aliases in the remaining path. */
3392
+ export async function resolveParentTraversal(path, { allowMissing = false } = {}) {
3393
+ const parts = path.split(sep);
3394
+ const parent = parts.lastIndexOf("..");
3395
+ if (parent === -1)
3396
+ return path;
3397
+ const prefix = parts.slice(0, parent + 1).join(sep);
3398
+ // A new output directory can be spelled missing/../scan before its parent exists.
3399
+ if (allowMissing &&
3400
+ (await stat(prefix).catch(nullIfMissingFileError)) === null) {
3401
+ return resolve(path);
3402
+ }
3403
+ // Resolve each directory before moving to its parent. Some runtimes collapse
3404
+ // a literal ".." inside realpath before consulting the filesystem.
3405
+ const before = parts.slice(0, parent).join(sep) || (isAbsolute(path) ? sep : ".");
3406
+ const physical = dirname(await realpath(await resolveParentTraversal(before)));
3407
+ if (!(await sameFile(prefix, physical)))
3408
+ throw new InvalidTargetError(`Repository path changed: ${prefix}`);
3409
+ return join(physical, ...parts.slice(parent + 1));
3410
+ }
3411
+ export function expandHomeForLookup(value, environment = process.env) {
2584
3412
  const path = value.startsWith("~\\") ? value.replaceAll("\\", "/") : value;
2585
3413
  // Expand only the home prefix; joining the suffix would collapse symlink/.. paths.
2586
3414
  return path.startsWith("~/")
@@ -2588,17 +3416,17 @@ function expandExecutableHome(value, environment) {
2588
3416
  : expandHome(path, environment);
2589
3417
  }
2590
3418
  export function expandHome(value, environment = process.env) {
2591
- const home = (process.platform === "win32"
3419
+ const home = () => (process.platform === "win32"
2592
3420
  ? (environmentValue(environment, "USERPROFILE") ??
2593
3421
  environmentValue(environment, "HOME"))
2594
3422
  : (environmentValue(environment, "HOME") ??
2595
3423
  environmentValue(environment, "USERPROFILE"))) ?? homedir();
2596
3424
  if (value === "~")
2597
- return home;
3425
+ return home();
2598
3426
  if (value.startsWith("~/"))
2599
- return join(home, value.slice(2));
3427
+ return join(home(), value.slice(2));
2600
3428
  if (value.startsWith("~\\")) {
2601
- return join(home, ...value.slice(2).split("\\"));
3429
+ return join(home(), ...value.slice(2).split("\\"));
2602
3430
  }
2603
3431
  return value;
2604
3432
  }