@openai/codex-security 0.8.2 → 0.8.3

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 (375) hide show
  1. package/README.md +43 -61
  2. package/_bundled_plugin/.app.json +4 -0
  3. package/_bundled_plugin/.mcp.json +1 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  6. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  14. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +46 -12
  15. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  16. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  17. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  18. package/_bundled_plugin/references/artifact-storage.md +1 -1
  19. package/_bundled_plugin/references/core-scan.md +14 -5
  20. package/_bundled_plugin/references/default-severity-rubric.md +28 -0
  21. package/_bundled_plugin/references/finding-detail-fields.md +1 -0
  22. package/_bundled_plugin/references/threat-model.md +1 -0
  23. package/_bundled_plugin/scripts/deep_scan_workbench.py +23 -112
  24. package/_bundled_plugin/scripts/finalize_scan_contract.py +167 -153
  25. package/_bundled_plugin/scripts/finding_preview.py +5 -29
  26. package/_bundled_plugin/scripts/posix_scan_local_files.py +187 -0
  27. package/_bundled_plugin/scripts/report_projection.py +87 -136
  28. package/_bundled_plugin/scripts/validate_scan_contract.py +2 -6
  29. package/_bundled_plugin/scripts/windows_scan_local_files.py +212 -55
  30. package/_bundled_plugin/scripts/workbench/retained_coverage.py +8 -24
  31. package/_bundled_plugin/scripts/workbench/saved_coverage.py +143 -231
  32. package/_bundled_plugin/scripts/workbench_cli.py +102 -13
  33. package/_bundled_plugin/scripts/workbench_constants.py +9 -0
  34. package/_bundled_plugin/scripts/workbench_db.py +186 -360
  35. package/_bundled_plugin/scripts/workbench_finding_workflows.py +86 -4
  36. package/_bundled_plugin/scripts/workbench_native_indexes.py +17 -21
  37. package/_bundled_plugin/scripts/workbench_remediation.py +495 -11
  38. package/_bundled_plugin/scripts/workbench_scan_history.py +22 -25
  39. package/_bundled_plugin/scripts/workbench_scan_start.py +1 -1
  40. package/_bundled_plugin/scripts/workbench_scan_usage.py +25 -52
  41. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  42. package/_bundled_plugin/scripts/workbench_setup.py +239 -0
  43. package/_bundled_plugin/scripts/workbench_source_scopes.py +15 -23
  44. package/_bundled_plugin/scripts/workbench_target.py +213 -20
  45. package/_bundled_plugin/scripts/workbench_validation.py +1 -9
  46. package/_bundled_plugin/shared/workbench-history-repairs.json +7 -0
  47. package/_bundled_plugin/shared/workbench-migrations.json +19 -0
  48. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +1 -1
  49. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +4 -68
  50. package/_bundled_plugin/skills/check-skills/SKILL.md +43 -0
  51. package/_bundled_plugin/skills/check-skills/agents/openai.yaml +4 -0
  52. package/_bundled_plugin/skills/cloud-findings/SKILL.md +2 -0
  53. package/_bundled_plugin/skills/fix-finding/SKILL.md +18 -1
  54. package/_bundled_plugin/skills/publish-findings/SKILL.md +64 -35
  55. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +2 -21
  56. package/_bundled_plugin/skills/threat-model-visualize/scripts/build_explorer.py +14 -8
  57. package/_bundled_plugin/skills/track-findings/SKILL.md +5 -3
  58. package/_bundled_plugin/skills/triage-finding/references/github-rest-intake.md +22 -68
  59. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -4
  60. package/dist/api.d.ts +6 -1
  61. package/dist/api.d.ts.map +1 -1
  62. package/dist/api.js +411 -160
  63. package/dist/api.js.map +1 -1
  64. package/dist/auth.js +6 -1
  65. package/dist/auth.js.map +1 -1
  66. package/dist/blackduck-findings.d.ts +8 -0
  67. package/dist/blackduck-findings.d.ts.map +1 -0
  68. package/dist/blackduck-findings.js +305 -0
  69. package/dist/blackduck-findings.js.map +1 -0
  70. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  71. package/dist/bulk-scan-discovery.js +51 -36
  72. package/dist/bulk-scan-discovery.js.map +1 -1
  73. package/dist/classify-severity-records.d.ts +5 -0
  74. package/dist/classify-severity-records.d.ts.map +1 -1
  75. package/dist/classify-severity-records.js +6 -8
  76. package/dist/classify-severity-records.js.map +1 -1
  77. package/dist/classify-severity.d.ts +4 -1
  78. package/dist/classify-severity.d.ts.map +1 -1
  79. package/dist/classify-severity.js +28 -9
  80. package/dist/classify-severity.js.map +1 -1
  81. package/dist/cli.d.ts +3 -0
  82. package/dist/cli.d.ts.map +1 -1
  83. package/dist/cli.js +608 -258
  84. package/dist/cli.js.map +1 -1
  85. package/dist/codex-prompt.d.ts +2 -0
  86. package/dist/codex-prompt.d.ts.map +1 -1
  87. package/dist/codex-prompt.js +6 -0
  88. package/dist/codex-prompt.js.map +1 -1
  89. package/dist/component-scan.d.ts.map +1 -1
  90. package/dist/component-scan.js +6 -5
  91. package/dist/component-scan.js.map +1 -1
  92. package/dist/config.d.ts +2 -1
  93. package/dist/config.d.ts.map +1 -1
  94. package/dist/config.js +162 -40
  95. package/dist/config.js.map +1 -1
  96. package/dist/continuum-findings.d.ts +7 -0
  97. package/dist/continuum-findings.d.ts.map +1 -0
  98. package/dist/continuum-findings.js +157 -0
  99. package/dist/continuum-findings.js.map +1 -0
  100. package/dist/contract-values.d.ts +28 -0
  101. package/dist/contract-values.d.ts.map +1 -0
  102. package/dist/contract-values.js +75 -0
  103. package/dist/contract-values.js.map +1 -0
  104. package/dist/contract.d.ts +2 -20
  105. package/dist/contract.d.ts.map +1 -1
  106. package/dist/contract.js +58 -669
  107. package/dist/contract.js.map +1 -1
  108. package/dist/cost-model.d.ts.map +1 -1
  109. package/dist/cost-model.js +1 -4
  110. package/dist/cost-model.js.map +1 -1
  111. package/dist/cost.d.ts +19 -1
  112. package/dist/cost.d.ts.map +1 -1
  113. package/dist/cost.js +2120 -39
  114. package/dist/cost.js.map +1 -1
  115. package/dist/custom-validation-prompt.d.ts +1 -1
  116. package/dist/custom-validation-prompt.d.ts.map +1 -1
  117. package/dist/custom-validation-prompt.js +5 -0
  118. package/dist/custom-validation-prompt.js.map +1 -1
  119. package/dist/custom-validation.d.ts +2 -0
  120. package/dist/custom-validation.d.ts.map +1 -1
  121. package/dist/custom-validation.js +4 -0
  122. package/dist/custom-validation.js.map +1 -1
  123. package/dist/deduplication/deduplication-prompts.d.ts +4 -4
  124. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  125. package/dist/deduplication/deduplication-prompts.js +2 -2
  126. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  127. package/dist/deduplication/deduplication-reviewer.d.ts +14 -11
  128. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  129. package/dist/deduplication/deduplication-reviewer.js +11 -4
  130. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  131. package/dist/deduplication/deduplication.js.map +1 -1
  132. package/dist/deduplication/finding-schema.d.ts +19 -1
  133. package/dist/deduplication/finding-schema.d.ts.map +1 -1
  134. package/dist/deduplication/finding-schema.js +25 -0
  135. package/dist/deduplication/finding-schema.js.map +1 -1
  136. package/dist/deduplication/local.d.ts.map +1 -1
  137. package/dist/deduplication/local.js +3 -8
  138. package/dist/deduplication/local.js.map +1 -1
  139. package/dist/deduplication/records.d.ts +8 -2
  140. package/dist/deduplication/records.d.ts.map +1 -1
  141. package/dist/deduplication/records.js +36 -8
  142. package/dist/deduplication/records.js.map +1 -1
  143. package/dist/deep-scan.d.ts +11 -0
  144. package/dist/deep-scan.d.ts.map +1 -1
  145. package/dist/deep-scan.js +235 -4
  146. package/dist/deep-scan.js.map +1 -1
  147. package/dist/default-severity-rubric.d.ts +1 -2
  148. package/dist/default-severity-rubric.d.ts.map +1 -1
  149. package/dist/default-severity-rubric.js +2 -66
  150. package/dist/default-severity-rubric.js.map +1 -1
  151. package/dist/endor-findings.d.ts.map +1 -1
  152. package/dist/endor-findings.js +7 -37
  153. package/dist/endor-findings.js.map +1 -1
  154. package/dist/errors.js +1 -1
  155. package/dist/errors.js.map +1 -1
  156. package/dist/external-findings-import.d.ts.map +1 -1
  157. package/dist/external-findings-import.js +5 -11
  158. package/dist/external-findings-import.js.map +1 -1
  159. package/dist/external-findings-local.d.ts +9 -0
  160. package/dist/external-findings-local.d.ts.map +1 -1
  161. package/dist/external-findings-local.js +325 -179
  162. package/dist/external-findings-local.js.map +1 -1
  163. package/dist/external-findings-publish.d.ts +12 -0
  164. package/dist/external-findings-publish.d.ts.map +1 -1
  165. package/dist/external-findings-publish.js +1202 -214
  166. package/dist/external-findings-publish.js.map +1 -1
  167. package/dist/external-findings-read.d.ts +8 -0
  168. package/dist/external-findings-read.d.ts.map +1 -1
  169. package/dist/external-findings-read.js +65 -54
  170. package/dist/external-findings-read.js.map +1 -1
  171. package/dist/external-findings.d.ts +2 -0
  172. package/dist/external-findings.d.ts.map +1 -1
  173. package/dist/external-findings.js +111 -0
  174. package/dist/external-findings.js.map +1 -1
  175. package/dist/external-import-contract.d.ts +29 -1
  176. package/dist/external-import-contract.d.ts.map +1 -1
  177. package/dist/external-import-contract.js +314 -44
  178. package/dist/external-import-contract.js.map +1 -1
  179. package/dist/external-import-models.d.ts +1 -1
  180. package/dist/external-import-models.d.ts.map +1 -1
  181. package/dist/external-import-models.js.map +1 -1
  182. package/dist/finding-normalization.d.ts +1 -1
  183. package/dist/finding-normalization.d.ts.map +1 -1
  184. package/dist/finding-normalization.js +46 -11
  185. package/dist/finding-normalization.js.map +1 -1
  186. package/dist/finding-retrieval.d.ts +3 -3
  187. package/dist/finding-retrieval.d.ts.map +1 -1
  188. package/dist/finding-retrieval.js.map +1 -1
  189. package/dist/finding-workflow.d.ts +6 -1
  190. package/dist/finding-workflow.d.ts.map +1 -1
  191. package/dist/finding-workflow.js +2 -2
  192. package/dist/finding-workflow.js.map +1 -1
  193. package/dist/git-remote.d.ts +4 -0
  194. package/dist/git-remote.d.ts.map +1 -1
  195. package/dist/git-remote.js +20 -0
  196. package/dist/git-remote.js.map +1 -1
  197. package/dist/github-advisories.d.ts +3 -12
  198. package/dist/github-advisories.d.ts.map +1 -1
  199. package/dist/github-advisories.js +9 -29
  200. package/dist/github-advisories.js.map +1 -1
  201. package/dist/github-dependabot-findings.d.ts.map +1 -1
  202. package/dist/github-dependabot-findings.js +7 -16
  203. package/dist/github-dependabot-findings.js.map +1 -1
  204. package/dist/github-findings.d.ts.map +1 -1
  205. package/dist/github-findings.js +344 -56
  206. package/dist/github-findings.js.map +1 -1
  207. package/dist/github.d.ts +17 -7
  208. package/dist/github.d.ts.map +1 -1
  209. package/dist/github.js +43 -30
  210. package/dist/github.js.map +1 -1
  211. package/dist/host-protocol.d.ts +2 -2
  212. package/dist/host-protocol.d.ts.map +1 -1
  213. package/dist/host-protocol.js.map +1 -1
  214. package/dist/host-records-protocol.d.ts +10 -11
  215. package/dist/host-records-protocol.d.ts.map +1 -1
  216. package/dist/host-records-protocol.js +69 -9
  217. package/dist/host-records-protocol.js.map +1 -1
  218. package/dist/hosted-scan.d.ts +15 -0
  219. package/dist/hosted-scan.d.ts.map +1 -1
  220. package/dist/hosted-scan.js +55 -33
  221. package/dist/hosted-scan.js.map +1 -1
  222. package/dist/index.d.ts +7 -0
  223. package/dist/index.d.ts.map +1 -1
  224. package/dist/index.js +6 -0
  225. package/dist/index.js.map +1 -1
  226. package/dist/inspector-findings.d.ts.map +1 -1
  227. package/dist/inspector-findings.js +13 -18
  228. package/dist/inspector-findings.js.map +1 -1
  229. package/dist/knowledge-base.js +18 -5
  230. package/dist/knowledge-base.js.map +1 -1
  231. package/dist/local-git-metadata.d.ts +5 -0
  232. package/dist/local-git-metadata.d.ts.map +1 -0
  233. package/dist/local-git-metadata.js +131 -0
  234. package/dist/local-git-metadata.js.map +1 -0
  235. package/dist/multiscan.d.ts.map +1 -1
  236. package/dist/multiscan.js +22 -12
  237. package/dist/multiscan.js.map +1 -1
  238. package/dist/opengrep-findings.d.ts.map +1 -1
  239. package/dist/opengrep-findings.js +34 -20
  240. package/dist/opengrep-findings.js.map +1 -1
  241. package/dist/patch-tui.d.ts.map +1 -1
  242. package/dist/patch-tui.js +90 -35
  243. package/dist/patch-tui.js.map +1 -1
  244. package/dist/private-finding-import.d.ts +246 -0
  245. package/dist/private-finding-import.d.ts.map +1 -0
  246. package/dist/private-finding-import.js +387 -0
  247. package/dist/private-finding-import.js.map +1 -0
  248. package/dist/project-config.d.ts.map +1 -1
  249. package/dist/project-config.js +2 -2
  250. package/dist/project-config.js.map +1 -1
  251. package/dist/provider-profile.d.ts +10 -2
  252. package/dist/provider-profile.d.ts.map +1 -1
  253. package/dist/provider-profile.js +72 -10
  254. package/dist/provider-profile.js.map +1 -1
  255. package/dist/publication.js +7 -1
  256. package/dist/publication.js.map +1 -1
  257. package/dist/reader-selection.d.ts +13 -0
  258. package/dist/reader-selection.d.ts.map +1 -0
  259. package/dist/reader-selection.js +81 -0
  260. package/dist/reader-selection.js.map +1 -0
  261. package/dist/record.d.ts +6 -1
  262. package/dist/record.d.ts.map +1 -1
  263. package/dist/record.js +53 -2
  264. package/dist/record.js.map +1 -1
  265. package/dist/remediation.d.ts +5 -0
  266. package/dist/remediation.d.ts.map +1 -1
  267. package/dist/remediation.js +30 -0
  268. package/dist/remediation.js.map +1 -1
  269. package/dist/result.d.ts +2 -0
  270. package/dist/result.d.ts.map +1 -1
  271. package/dist/result.js +3 -1
  272. package/dist/result.js.map +1 -1
  273. package/dist/runtime.d.ts +2 -1
  274. package/dist/runtime.d.ts.map +1 -1
  275. package/dist/runtime.js +95 -52
  276. package/dist/runtime.js.map +1 -1
  277. package/dist/scan-activity.js +40 -17
  278. package/dist/scan-activity.js.map +1 -1
  279. package/dist/scan-comparison.d.ts +1 -1
  280. package/dist/scan-comparison.d.ts.map +1 -1
  281. package/dist/scan-comparison.js +11 -13
  282. package/dist/scan-comparison.js.map +1 -1
  283. package/dist/scan-dashboard.d.ts +1 -0
  284. package/dist/scan-dashboard.d.ts.map +1 -1
  285. package/dist/scan-dashboard.js +16 -37
  286. package/dist/scan-dashboard.js.map +1 -1
  287. package/dist/scan-executor.d.ts +2 -0
  288. package/dist/scan-executor.d.ts.map +1 -1
  289. package/dist/scan-executor.js.map +1 -1
  290. package/dist/scan-history-renderer.d.ts.map +1 -1
  291. package/dist/scan-history-renderer.js +22 -9
  292. package/dist/scan-history-renderer.js.map +1 -1
  293. package/dist/scan-logs.d.ts.map +1 -1
  294. package/dist/scan-logs.js +5 -5
  295. package/dist/scan-logs.js.map +1 -1
  296. package/dist/scanner-import.d.ts +46 -6
  297. package/dist/scanner-import.d.ts.map +1 -1
  298. package/dist/scanner-import.js +208 -42
  299. package/dist/scanner-import.js.map +1 -1
  300. package/dist/scanner-repository-url.d.ts +14 -0
  301. package/dist/scanner-repository-url.d.ts.map +1 -0
  302. package/dist/scanner-repository-url.js +67 -0
  303. package/dist/scanner-repository-url.js.map +1 -0
  304. package/dist/semgrep-findings.d.ts.map +1 -1
  305. package/dist/semgrep-findings.js +20 -48
  306. package/dist/semgrep-findings.js.map +1 -1
  307. package/dist/semgrep-platform-findings.d.ts +12 -0
  308. package/dist/semgrep-platform-findings.d.ts.map +1 -0
  309. package/dist/semgrep-platform-findings.js +198 -0
  310. package/dist/semgrep-platform-findings.js.map +1 -0
  311. package/dist/severity-rubric.d.ts +20 -0
  312. package/dist/severity-rubric.d.ts.map +1 -0
  313. package/dist/severity-rubric.js +73 -0
  314. package/dist/severity-rubric.js.map +1 -0
  315. package/dist/severity-store.js +15 -5
  316. package/dist/severity-store.js.map +1 -1
  317. package/dist/snyk-findings.d.ts.map +1 -1
  318. package/dist/snyk-findings.js +21 -20
  319. package/dist/snyk-findings.js.map +1 -1
  320. package/dist/sonar-collector.d.ts +16 -0
  321. package/dist/sonar-collector.d.ts.map +1 -0
  322. package/dist/sonar-collector.js +383 -0
  323. package/dist/sonar-collector.js.map +1 -0
  324. package/dist/sonar-findings.d.ts +49 -0
  325. package/dist/sonar-findings.d.ts.map +1 -0
  326. package/dist/sonar-findings.js +288 -0
  327. package/dist/sonar-findings.js.map +1 -0
  328. package/dist/sonar-import.d.ts +111 -0
  329. package/dist/sonar-import.d.ts.map +1 -0
  330. package/dist/sonar-import.js +279 -0
  331. package/dist/sonar-import.js.map +1 -0
  332. package/dist/suggest-owners.d.ts.map +1 -1
  333. package/dist/suggest-owners.js +2 -1
  334. package/dist/suggest-owners.js.map +1 -1
  335. package/dist/targets.d.ts +3 -0
  336. package/dist/targets.d.ts.map +1 -1
  337. package/dist/targets.js +18 -12
  338. package/dist/targets.js.map +1 -1
  339. package/dist/terminal-columns.d.ts +4 -0
  340. package/dist/terminal-columns.d.ts.map +1 -0
  341. package/dist/terminal-columns.js +19 -0
  342. package/dist/terminal-columns.js.map +1 -0
  343. package/dist/validation-records.d.ts +0 -3
  344. package/dist/validation-records.d.ts.map +1 -1
  345. package/dist/validation-records.js +0 -16
  346. package/dist/validation-records.js.map +1 -1
  347. package/dist/veracode-findings.d.ts +7 -0
  348. package/dist/veracode-findings.d.ts.map +1 -0
  349. package/dist/veracode-findings.js +371 -0
  350. package/dist/veracode-findings.js.map +1 -0
  351. package/dist/windows-path.d.ts.map +1 -1
  352. package/dist/windows-path.js +1 -0
  353. package/dist/windows-path.js.map +1 -1
  354. package/dist/wiz-csv.d.ts +2 -2
  355. package/dist/wiz-csv.d.ts.map +1 -1
  356. package/dist/wiz-csv.js +1 -3
  357. package/dist/wiz-csv.js.map +1 -1
  358. package/dist/wiz-findings.d.ts +10 -2
  359. package/dist/wiz-findings.d.ts.map +1 -1
  360. package/dist/wiz-findings.js +88 -49
  361. package/dist/wiz-findings.js.map +1 -1
  362. package/docs/classify-severity-records.md +1 -1
  363. package/docs/cli.md +310 -477
  364. package/docs/dedupe-records.md +10 -0
  365. package/docs/findings-service.md +21 -8
  366. package/docs/hosted-scans.md +16 -1
  367. package/package.json +8 -9
  368. package/schemas/external-findings.schema.json +12 -1
  369. package/schemas/hosted-scan-v2.fixture.json +16 -1
  370. package/_bundled_plugin/scripts/validate_tracking_source.py +0 -82
  371. package/_bundled_plugin/scripts/workbench_local_dedupe.py +0 -136
  372. package/dist/deduplication/records-protocol.d.ts +0 -4
  373. package/dist/deduplication/records-protocol.d.ts.map +0 -1
  374. package/dist/deduplication/records-protocol.js +0 -49
  375. package/dist/deduplication/records-protocol.js.map +0 -1
package/dist/contract.js CHANGED
@@ -1,372 +1,80 @@
1
- import { isDeepStrictEqual as sameArray } from "node:util";
2
- import { createHash, hash } from "node:crypto";
3
- import { normalizePersistedFindingDetails } from "./finding-normalization.js";
4
- import { constants } from "node:fs";
5
- import { lstat, open, readFile, realpath, } from "node:fs/promises";
6
- import { isAbsolute, join, posix, resolve } from "node:path";
7
- import Ajv2020 from "ajv/dist/2020.js";
8
- import { regexes } from "zod";
9
- import { ContractValidationError, abortReason, errorMessage, } from "./errors.js";
10
- import { isRecord } from "./record.js";
11
- import { requireOutputDirectoryOwnership, requireSecureOutputAncestry, } from "./runtime.js";
12
- import { isWithin as isContained } from "./trusted-executable.js";
13
- import { isWindowsUnsafePathComponent } from "./windows-path.js";
14
- const DOCUMENTS = {
15
- "scan-manifest.json": "scan-manifest.schema.json",
16
- "findings.json": "findings.schema.json",
17
- "coverage.json": "coverage.schema.json",
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
18
8
  };
9
+ import { constants } from "node:fs";
10
+ import { lstat, open } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+ import { ContractValidationError, abortReason } from "./errors.js";
14
+ import { bundledPluginRoot } from "./runtime.js";
15
+ import { safeScopePath as sharedSafeScopePath } from "./contract-values.js";
16
+ export { DEFERRED_PATH_LOCATION, SEALED_DEFERRED_PATH_RULE, deriveFindingIdentity, hasRequiredFindingText, } from "./contract-values.js";
17
+ /** @internal */
18
+ export { sha256Text } from "./contract-values.js";
19
19
  const PRODUCER_NAME = "codex-security-plugin";
20
20
  // Hosted receipts compare reread files with the bytes that passed validation.
21
21
  export const validatedFileDigests = new WeakMap();
22
22
  export class ContractSchemaError extends ContractValidationError {
23
23
  }
24
- export const SEALED_DEFERRED_PATH_RULE = "invalidSealedDeferredPath";
25
- export const DEFERRED_PATH_LOCATION = /^\/deferred\/(\d+)\/paths\/(\d+)$/u;
26
- export async function loadContract(scanDirectory, options) {
27
- return (await loadContractWithScanDirectory(scanDirectory, options)).contract;
24
+ async function contractHelper() {
25
+ return (await import(__rewriteRelativeImportExtension(pathToFileURL(join(await bundledPluginRoot(), "mcp/helpers.mjs")).href))).default;
28
26
  }
29
- export async function loadContractWithScanDirectory(scanDirectory, options) {
30
- const validators = await loadContractValidators(options.pluginRoot, options.signal);
31
- const scanRoot = await requireScanRoot(scanDirectory, options.signal);
32
- const scanDir = scanRoot.path;
33
- const fileDigests = new Map();
34
- const payloads = {};
35
- payloads["scan-manifest.json"] = await readScanJson(scanDir, "scan-manifest.json", fileDigests, options.signal, scanRoot);
36
- const rawManifest = payloads["scan-manifest.json"];
37
- const documents = validators.filter(({ filename }) => filename !== "coverage.json" ||
38
- rawManifest.scan?.coverageRef !== undefined);
39
- for (const { filename } of documents) {
40
- if (filename === "scan-manifest.json")
41
- continue;
42
- payloads[filename] = await readScanJson(scanDir, filename, fileDigests, options.signal, scanRoot);
43
- }
44
- throwIfAborted(options.signal);
45
- for (const { filename, schemaName, validate } of documents) {
46
- let payload;
47
- let valid;
48
- try {
49
- payload = payloads[filename];
50
- const validatePayload = (payload) => {
51
- const result = validate(payload);
52
- if (typeof result !== "boolean") {
53
- throw new Error("asynchronous JSON Schema validation is unsupported");
54
- }
55
- return result;
56
- };
57
- valid = validatePayload(payload);
58
- if (!valid && filename === "findings.json") {
59
- payload = normalizePersistedFindings(payload);
60
- valid = validatePayload(payload);
61
- }
62
- }
63
- catch {
64
- throw new ContractSchemaError(`${schemaName}: invalid JSON Schema.`);
65
- }
66
- if (!valid) {
67
- throw schemaError(filename, validate.errors ?? []);
68
- }
69
- payloads[filename] = payload;
70
- throwIfAborted(options.signal);
71
- }
72
- const manifest = payloads["scan-manifest.json"];
73
- const findings = payloads["findings.json"];
74
- const coverage = payloads["coverage.json"];
75
- const mode = coverage?.mode ?? manifest.scan.mode;
76
- const review = coverage
77
- ? {
78
- excludedPaths: coverage.explicitExclusions.map((item) => item.pattern),
79
- }
80
- : manifest.scan.review;
81
- if (options.expectedScanId !== undefined &&
82
- manifest.scan.id !== options.expectedScanId) {
83
- throw new ContractValidationError(`Scan artifacts do not match selected scan ${options.expectedScanId}.`);
84
- }
85
- if (findings.scanId !== manifest.scan.id ||
86
- (coverage !== undefined && coverage.scanId !== manifest.scan.id)) {
87
- throw new ContractValidationError("Canonical contract scan IDs do not match.");
88
- }
89
- if (coverage !== undefined &&
90
- !sameArray(coverage.includePaths, manifest.scan.scope.includePaths)) {
91
- throw new ContractValidationError("Coverage include paths do not match the manifest scope.");
92
- }
93
- if (coverage !== undefined &&
94
- !sameArray(coverage.excludePaths, manifest.scan.scope.excludePaths)) {
95
- throw new ContractValidationError("Coverage exclude paths do not match the manifest scope.");
96
- }
97
- validateCanonicalContract(manifest, findings, coverage);
98
- await validateSeal(scanDir, manifest, findings, coverage, fileDigests, options.signal, scanRoot);
99
- if (options.expectation !== undefined) {
100
- validateExpectation(manifest, mode, options.expectation, options.workbenchValidated === true);
101
- }
102
- await verifyScanRoot(scanRoot, options.signal);
103
- validatedFileDigests.set(manifest, fileDigests);
104
- return {
105
- contract: { manifest, findings, review, mode },
106
- scanDirectory: scanRoot.path,
107
- };
108
- }
109
- /** Normalize optional legacy details on a copy, without changing saved artifacts. */
110
- function normalizePersistedFindings(payload) {
111
- const compatible = structuredClone(payload);
112
- if (!isRecord(compatible) || !Array.isArray(compatible["findings"])) {
113
- return compatible;
27
+ async function translateContractError(operation, signal) {
28
+ try {
29
+ return await operation();
114
30
  }
115
- for (const finding of compatible["findings"]) {
116
- if (!isRecord(finding))
117
- continue;
118
- normalizePersistedFindingDetails(finding);
31
+ catch (error) {
32
+ if (signal?.aborted)
33
+ throw abortReason(signal);
34
+ if (error instanceof ContractValidationError)
35
+ throw error;
36
+ const message = error instanceof Error ? error.message : String(error);
37
+ if (error instanceof Error && error.name === "SealedContractSchemaError")
38
+ throw new ContractSchemaError(message, { cause: error.cause });
39
+ throw new ContractValidationError(message, {
40
+ cause: error instanceof Error && error.name === "SealedContractError"
41
+ ? error.cause
42
+ : error,
43
+ });
119
44
  }
120
- return compatible;
121
45
  }
122
- /** Match the producer's Python str.strip without changing saved text. */
123
- export function hasRequiredFindingText(value) {
124
- return !/^[\p{White_Space}\u001c-\u001f]*$/u.test(value);
46
+ export async function loadContract(scanDirectory, options) {
47
+ return (await loadContractWithScanDirectory(scanDirectory, options)).contract;
125
48
  }
126
- function validateCanonicalContract(manifest, findings, coverage) {
127
- const requireText = (values) => {
128
- for (const [context, value] of Object.entries(values)) {
129
- if (value !== undefined && !hasRequiredFindingText(value))
130
- throw new ContractValidationError(`${context}: expected a non-empty string.`);
131
- }
132
- };
133
- requireText({
134
- "manifest.scan.id": manifest.scan.id,
135
- "scan.target.targetId": manifest.scan.target.targetId,
136
- "scan.target.displayName": manifest.scan.target.displayName,
137
- "scan.target.revision": manifest.scan.target.kind === "git_revision"
138
- ? manifest.scan.target.revision
139
- : undefined,
140
- "scan.target.snapshotDigest": manifest.scan.target.kind !== "git_revision"
141
- ? manifest.scan.target.snapshotDigest
142
- : undefined,
143
- "manifest.scan.producer.name": manifest.scan.producer.name,
144
- "manifest.scan.producer.version": manifest.scan.producer.version,
145
- "coverage.inventoryStrategy": coverage?.inventoryStrategy,
146
- });
147
- for (const [index, surface] of (coverage?.surfaces ?? []).entries())
148
- requireText({
149
- [`coverage.surfaces[${index}].id`]: surface.id,
150
- [`coverage.surfaces[${index}].label`]: surface.label,
151
- });
152
- const remote = manifest.scan.target.remote;
153
- if (remote !== undefined) {
154
- const authority = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]+)/.exec(remote)?.[1];
155
- if (remote.includes("\\") ||
156
- /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(remote) ||
157
- authority === undefined) {
158
- throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.");
159
- }
160
- if (authority.includes("@")) {
161
- throw new ContractValidationError("scan.target.remote: remote URL must not contain credentials, query, or fragment.");
162
- }
163
- let parsed;
164
- try {
165
- parsed = new URL(remote);
166
- }
167
- catch (error) {
168
- throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.", { cause: error });
169
- }
170
- if (parsed.protocol.length === 0 || parsed.host.length === 0) {
171
- throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.");
172
- }
173
- if (parsed.username.length > 0 ||
174
- parsed.password.length > 0 ||
175
- parsed.search.length > 0 ||
176
- parsed.hash.length > 0) {
177
- throw new ContractValidationError("scan.target.remote: remote URL must not contain credentials, query, or fragment.");
178
- }
179
- }
180
- for (const field of ["includePaths", "excludePaths"]) {
181
- for (const [index, value] of manifest.scan.scope[field].entries()) {
182
- try {
183
- safeScopePath(value);
184
- }
185
- catch (error) {
186
- throw new ContractValidationError(`manifest.scan.scope.${field}[${index}]: expected a safe repository-relative POSIX path.`, { cause: error });
187
- }
188
- }
189
- }
190
- for (const [index, deferred] of (coverage?.deferred ?? []).entries()) {
191
- for (const [pathIndex, path] of (deferred.paths ?? []).entries()) {
192
- const context = `coverage.deferred[${index}].paths[${pathIndex}]`;
193
- try {
194
- safeRelativePath(path, context, true);
195
- }
196
- catch (error) {
197
- throw new ContractValidationError(`${context}: expected a safe repository-relative POSIX path.`, { cause: error });
198
- }
199
- }
200
- }
201
- const occurrenceIds = new Set();
202
- for (const [findingIndex, finding] of findings.findings.entries()) {
203
- const context = `findings.findings[${findingIndex}]`;
204
- requireText({
205
- [`${context}.title`]: finding.title,
206
- [`${context}.summary`]: finding.summary,
207
- [`${context}.remediation`]: finding.remediation,
208
- [`${context}.confidence.rationale`]: finding.confidence.rationale,
209
- [`${context}.severity.scoringSystem`]: finding.severity.score === undefined
210
- ? undefined
211
- : (finding.severity.scoringSystem ?? ""),
212
- [`${context}.taxonomy.category`]: finding.taxonomy.category,
213
- [`${context}.provenance.source`]: finding.provenance.source,
214
- });
215
- if (occurrenceIds.has(finding.occurrenceId))
216
- throw new ContractValidationError(`${context}: duplicate finding occurrence identity; use identity.instance to split siblings.`);
217
- occurrenceIds.add(finding.occurrenceId);
218
- for (const [locationIndex, location] of finding.locations.entries()) {
219
- const locationContext = `${context}.locations[${locationIndex}]`;
220
- try {
221
- safeRelativePath(location.path, `${locationContext}.path`);
222
- }
223
- catch (error) {
224
- throw new ContractValidationError(`${locationContext}.path: expected a safe repository-relative POSIX path.`, { cause: error });
225
- }
226
- if ((location.endLine ?? location.startLine) < location.startLine) {
227
- throw new ContractValidationError(`${locationContext}.endLine: expected an integer >= startLine.`);
228
- }
229
- }
230
- for (const [evidenceIndex, evidence] of (finding.codeEvidence ?? []).entries()) {
231
- const evidenceContext = `${context}.codeEvidence[${evidenceIndex}].path`;
232
- try {
233
- safeRelativePath(evidence.path, evidenceContext);
234
- }
235
- catch (error) {
236
- throw new ContractValidationError(`${evidenceContext}: expected a safe repository-relative POSIX path.`, { cause: error });
237
- }
238
- }
239
- const { findingId, occurrenceId, fingerprints } = deriveFindingIdentity(manifest.scan.id, manifest.scan.target.targetId, finding.ruleId, finding.identity);
240
- if (finding.findingId !== findingId) {
241
- throw new ContractValidationError(`${context}.findingId: does not match derived fingerprint identity.`);
242
- }
243
- if (finding.occurrenceId !== occurrenceId) {
244
- throw new ContractValidationError(`${context}.occurrenceId: does not match scan occurrence identity.`);
245
- }
246
- if (finding.fingerprints.primary !== fingerprints.primary) {
247
- throw new ContractValidationError(`${context}.fingerprints: does not match derived fingerprint.`);
248
- }
249
- }
49
+ export async function loadContractWithScanDirectory(scanDirectory, options) {
50
+ return translateContractError(async () => {
51
+ const helper = await contractHelper();
52
+ const result = (await helper.loadSealedContract(scanDirectory, {
53
+ pluginRoot: options.pluginRoot,
54
+ expectedScanId: options.expectedScanId,
55
+ signal: options.signal,
56
+ }));
57
+ if (options.expectation !== undefined)
58
+ validateExpectation(result.contract.manifest, result.contract.mode, options.expectation, options.workbenchValidated === true);
59
+ validatedFileDigests.set(result.contract.manifest, result.fileDigests);
60
+ return {
61
+ contract: result.contract,
62
+ scanDirectory: result.scanDirectory,
63
+ };
64
+ }, options.signal);
250
65
  }
251
66
  export async function requireScanFile(scanDirectory, relativePath, context, signal) {
252
- return (await requireCheckedScanFile(scanDirectory, relativePath, context, signal)).path;
67
+ return translateContractError(async () => (await contractHelper()).requireSealedScanFile(scanDirectory, relativePath, context, signal), signal);
253
68
  }
254
69
  export async function readScanFile(scanDirectory, relativePath, context, signal) {
255
- const file = await openCheckedScanFile(scanDirectory, relativePath, context, signal);
256
- try {
257
- return await file.readFile({ signal });
258
- }
259
- finally {
260
- await file.close();
261
- }
70
+ return translateContractError(async () => (await contractHelper()).readSealedScanFile(scanDirectory, relativePath, context, signal), signal);
262
71
  }
263
- async function requireCheckedScanFile(scanDirectory, relativePath, context, signal, expectedRoot) {
264
- const checkedRoot = await requireScanRoot(scanDirectory, signal);
265
- const scanDir = checkedRoot.path;
266
- throwIfAborted(signal);
267
- const safePath = portableRelativePath(relativePath, context);
268
- const parts = safePath.split("/");
269
- let current = scanDir;
72
+ export function safeScopePath(value) {
270
73
  try {
271
- const rootMetadata = checkedRoot.metadata;
272
- if (expectedRoot !== undefined &&
273
- (scanDir !== expectedRoot.path ||
274
- rootMetadata.dev !== expectedRoot.metadata.dev ||
275
- rootMetadata.ino !== expectedRoot.metadata.ino)) {
276
- throw new Error("scan directory changed while reading");
277
- }
278
- const parents = [{ path: scanDir, metadata: rootMetadata }];
279
- throwIfAborted(signal);
280
- for (const part of parts.slice(0, -1)) {
281
- current = join(current, part);
282
- const metadata = await lstat(current, { bigint: true });
283
- throwIfAborted(signal);
284
- if (!metadata.isDirectory()) {
285
- throw new Error("unsafe parent");
286
- }
287
- parents.push({ path: current, metadata });
288
- }
289
- const path = join(scanDir, ...parts);
290
- const metadata = await lstat(path, { bigint: true });
291
- throwIfAborted(signal);
292
- if (!metadata.isFile()) {
293
- throw new ContractValidationError(`${context}: expected a regular non-symlink file.`);
294
- }
295
- const canonical = await realpath(path);
296
- throwIfAborted(signal);
297
- if (!isContained(scanDir, canonical)) {
298
- throw new Error("outside scan directory");
299
- }
300
- return { path, metadata, parents };
74
+ return sharedSafeScopePath(value);
301
75
  }
302
76
  catch (error) {
303
- throwIfAborted(signal);
304
- if (error instanceof ContractValidationError) {
305
- throw error;
306
- }
307
- throw new ContractValidationError(`${context}: expected a file inside the scan directory.`, {
308
- cause: error,
309
- });
310
- }
311
- }
312
- async function validateSeal(scanDir, manifest, findings, coverage, fileDigests, signal, expectedRoot) {
313
- const scan = manifest.scan;
314
- if (scan.sealedAt !== scan.completedAt) {
315
- throw new ContractValidationError("Manifest sealedAt must match completedAt.");
316
- }
317
- const artifactPaths = new Set();
318
- const artifactCollisionKeys = new Set();
319
- for (const [index, artifact] of scan.artifacts.entries()) {
320
- throwIfAborted(signal);
321
- const context = `manifest.scan.artifacts[${index}]`;
322
- const normalized = portableRelativePath(artifact.path, `${context}.path`);
323
- const collisionKey = normalized.toLowerCase();
324
- if (artifactCollisionKeys.has(collisionKey)) {
325
- throw new ContractValidationError(`${context}.path: duplicate artifact path.`);
326
- }
327
- artifactPaths.add(normalized);
328
- artifactCollisionKeys.add(collisionKey);
329
- const digest = fileDigests.get(normalized) ??
330
- (await sha256ScanFile(scanDir, normalized, context, signal, expectedRoot));
331
- if (digest !== artifact.sha256) {
332
- throw new ContractValidationError(`${context}: sealed artifact changed or is missing.`);
333
- }
334
- fileDigests.set(artifact.path, digest);
335
- }
336
- const requireSealedReference = (reference, context) => {
337
- throwIfAborted(signal);
338
- if (typeof reference !== "string") {
339
- throw new ContractValidationError(`${context}: expected a string.`);
340
- }
341
- const normalized = portableRelativePath(reference, context.toLowerCase());
342
- if (!normalized.startsWith("artifacts/")) {
343
- throw new ContractValidationError(`${context} must be under artifacts/: ${reference}`);
344
- }
345
- if (!artifactPaths.has(normalized)) {
346
- throw new ContractValidationError(`${context} is missing from sealed artifacts: ${reference}`);
347
- }
348
- };
349
- for (const surface of coverage?.surfaces ?? []) {
350
- for (const receipt of surface.receiptRefs) {
351
- requireSealedReference(receipt, "Coverage receipt");
352
- }
353
- }
354
- const extensions = scan["extensions"];
355
- const imported = isRecord(extensions) ? extensions["import"] : undefined;
356
- if (isRecord(imported) && "sourceRef" in imported) {
357
- requireSealedReference(imported["sourceRef"], "Import source");
358
- }
359
- for (const [index, finding] of findings.findings.entries()) {
360
- const writeup = finding.writeup;
361
- if (writeup === undefined)
362
- continue;
363
- const file = await openCheckedScanFile(scanDir, writeup.reportPath, `findings[${index}].writeup.reportPath`, signal, expectedRoot);
364
- await file.close();
365
- }
366
- const hardening = manifest.scan.hardening;
367
- if (hardening !== undefined) {
368
- const file = await openCheckedScanFile(scanDir, hardening.portfolioPath, "manifest.scan.hardening.portfolioPath", signal, expectedRoot);
369
- await file.close();
77
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), { cause: error });
370
78
  }
371
79
  }
372
80
  function validateExpectation(manifest, mode, expectation, workbenchValidated = false) {
@@ -424,269 +132,6 @@ function expectedCoverageMode(target, mode) {
424
132
  return "working_tree";
425
133
  return mode === "deep" ? "deep_repository" : "repository";
426
134
  }
427
- async function requireScanRoot(scanDirectory, signal) {
428
- throwIfAborted(signal);
429
- const absolute = resolve(scanDirectory);
430
- try {
431
- const metadata = await lstat(absolute, { bigint: true });
432
- throwIfAborted(signal);
433
- const canonical = await realpath(absolute);
434
- throwIfAborted(signal);
435
- const current = await lstat(absolute, { bigint: true });
436
- throwIfAborted(signal);
437
- const returned = await lstat(canonical, { bigint: true });
438
- throwIfAborted(signal);
439
- if (!metadata.isDirectory() ||
440
- !current.isDirectory() ||
441
- metadata.dev !== current.dev ||
442
- metadata.ino !== current.ino ||
443
- !returned.isDirectory() ||
444
- metadata.dev !== returned.dev ||
445
- metadata.ino !== returned.ino) {
446
- throw new Error("not a directory");
447
- }
448
- try {
449
- requireOutputDirectoryOwnership({ uid: Number(returned.uid) }, canonical);
450
- await requireSecureOutputAncestry(canonical);
451
- }
452
- catch (error) {
453
- throw new ContractValidationError(error instanceof Error
454
- ? error.message
455
- : "Scan directory must remain owned by the current user.", { cause: error });
456
- }
457
- return { path: canonical, metadata: returned };
458
- }
459
- catch (error) {
460
- throwIfAborted(signal);
461
- if (error instanceof ContractValidationError)
462
- throw error;
463
- throw new ContractValidationError("Scan directory must be an existing non-symlink directory.", { cause: error });
464
- }
465
- }
466
- async function verifyScanRoot(root, signal) {
467
- try {
468
- const current = await lstat(root.path, { bigint: true });
469
- throwIfAborted(signal);
470
- if (!current.isDirectory() ||
471
- current.dev !== root.metadata.dev ||
472
- current.ino !== root.metadata.ino) {
473
- throw new Error("scan directory changed while reading");
474
- }
475
- requireOutputDirectoryOwnership({ uid: Number(current.uid) }, root.path);
476
- await requireSecureOutputAncestry(root.path);
477
- }
478
- catch (error) {
479
- throwIfAborted(signal);
480
- throw new ContractValidationError("Scan directory changed while reading the canonical contract.", { cause: error });
481
- }
482
- }
483
- function safeRelativePath(value, context, allowDot = false) {
484
- const parts = value.split("/");
485
- if (value.length === 0 ||
486
- Buffer.from(value, "utf8").toString("utf8") !== value ||
487
- (!allowDot && value === ".") ||
488
- value.startsWith("/") ||
489
- /^[A-Za-z]:/.test(value) ||
490
- parts.includes("..") ||
491
- value.includes("\\") ||
492
- /[\u0000-\u001f]/u.test(value)) {
493
- throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
494
- }
495
- const normalized = posix.normalize(value).replace(/\/+$/, "");
496
- if ((!allowDot && normalized === ".") ||
497
- normalized.startsWith("../") ||
498
- isAbsolute(normalized)) {
499
- throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
500
- }
501
- return normalized;
502
- }
503
- function portableRelativePath(value, context) {
504
- const normalized = safeRelativePath(value, context);
505
- if (value.trim().length === 0 ||
506
- value.split("/").some(isWindowsUnsafePathComponent)) {
507
- throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
508
- }
509
- return normalized;
510
- }
511
- export function safeScopePath(value) {
512
- return value === "."
513
- ? value
514
- : safeRelativePath(value, "manifest scope include path");
515
- }
516
- async function readScanJson(scanDir, relativePath, fileDigests, signal, expectedRoot) {
517
- const file = await openCheckedScanFile(scanDir, relativePath, relativePath, signal, expectedRoot);
518
- try {
519
- const bytes = await file.readFile({ signal });
520
- fileDigests.set(relativePath, hash("sha256", bytes));
521
- return parseJson(join(scanDir, relativePath), bytes);
522
- }
523
- catch (error) {
524
- throwIfAborted(signal);
525
- if (error instanceof ContractValidationError)
526
- throw error;
527
- throw new ContractValidationError(`${join(scanDir, relativePath)}: unreadable JSON document.`, { cause: error });
528
- }
529
- finally {
530
- await file.close();
531
- }
532
- }
533
- async function readJson(path, signal) {
534
- try {
535
- return parseJson(path, await readFile(path, { signal }));
536
- }
537
- catch (error) {
538
- throwIfAborted(signal);
539
- if (error instanceof ContractValidationError)
540
- throw error;
541
- if (nodeErrorCode(error) === "ENOENT") {
542
- throw new ContractValidationError(`Missing required contract document: ${path}`);
543
- }
544
- throw new ContractValidationError(`${path}: unreadable JSON document.`, {
545
- cause: error,
546
- });
547
- }
548
- }
549
- function parseJson(path, bytes) {
550
- let text;
551
- try {
552
- text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
553
- }
554
- catch (error) {
555
- throw new ContractValidationError(`${path}: unreadable JSON document.`, {
556
- cause: error,
557
- });
558
- }
559
- let payload;
560
- try {
561
- payload = JSON.parse(text);
562
- }
563
- catch (error) {
564
- throw new ContractValidationError(`${path}: invalid JSON: ${String(error)}`, { cause: error });
565
- }
566
- if (!isRecord(payload)) {
567
- throw new ContractValidationError(`${path}: expected a JSON object.`);
568
- }
569
- validateParsedJson(payload, path);
570
- return payload;
571
- }
572
- function validateParsedJson(value, context) {
573
- if (typeof value === "number") {
574
- if (!Number.isFinite(value)) {
575
- throw new ContractValidationError(`${context}: non-finite JSON numbers are not supported.`);
576
- }
577
- if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
578
- throw new ContractValidationError(`${context}: unsafe integer-valued JSON numbers are not supported.`);
579
- }
580
- return;
581
- }
582
- if (typeof value === "string") {
583
- if (!value.isWellFormed()) {
584
- throw new ContractValidationError(`${context}: expected well-formed Unicode JSON strings.`);
585
- }
586
- return;
587
- }
588
- if (Array.isArray(value)) {
589
- for (const [index, item] of value.entries()) {
590
- validateParsedJson(item, `${context}[${index}]`);
591
- }
592
- return;
593
- }
594
- if (isRecord(value)) {
595
- for (const [key, item] of Object.entries(value)) {
596
- if (!key.isWellFormed()) {
597
- throw new ContractValidationError(`${context}: expected well-formed Unicode JSON keys.`);
598
- }
599
- validateParsedJson(item, `${context}[${JSON.stringify(key)}]`);
600
- }
601
- }
602
- }
603
- async function loadContractValidators(pluginRoot, signal) {
604
- // The plugin schemas are the immutable v0 contract. They are valid Draft
605
- // 2020-12 but intentionally omit redundant local `type` keywords that Ajv's
606
- // optional strict-schema linter requires.
607
- const ajv = new Ajv2020({ allErrors: false, strict: false, verbose: true });
608
- ajv.addFormat("date-time", {
609
- type: "string",
610
- validate: validRfc3339DateTime,
611
- });
612
- const validators = [];
613
- for (const [filename, schemaName] of Object.entries(DOCUMENTS)) {
614
- const schema = await readJson(join(pluginRoot, "schemas", schemaName), signal).catch((error) => {
615
- throwIfAborted(signal);
616
- throw new ContractSchemaError(errorMessage(error), { cause: error });
617
- });
618
- try {
619
- const validate = ajv.compile(schema);
620
- if ("$async" in validate && validate.$async === true) {
621
- throw new Error("asynchronous JSON Schema validation is unsupported");
622
- }
623
- validators.push({ filename, schemaName, validate });
624
- }
625
- catch {
626
- throw new ContractSchemaError(`${schemaName}: invalid JSON Schema.`);
627
- }
628
- throwIfAborted(signal);
629
- }
630
- return validators;
631
- }
632
- async function sha256ScanFile(scanDir, relativePath, context, signal, expectedRoot) {
633
- const file = await openCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot);
634
- try {
635
- throwIfAborted(signal);
636
- const digest = createHash("sha256");
637
- const buffer = Buffer.alloc(64 * 1024);
638
- while (true) {
639
- throwIfAborted(signal);
640
- const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
641
- if (bytesRead === 0)
642
- break;
643
- digest.update(buffer.subarray(0, bytesRead));
644
- }
645
- throwIfAborted(signal);
646
- return digest.digest("hex");
647
- }
648
- finally {
649
- await file.close();
650
- }
651
- }
652
- async function openCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot) {
653
- const checked = await requireCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot);
654
- let file;
655
- try {
656
- file = await open(checked.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
657
- const opened = await file.stat({ bigint: true });
658
- throwIfAborted(signal);
659
- if (!opened.isFile() ||
660
- opened.ino !== checked.metadata.ino ||
661
- !(await sameCheckedFileDevice(file, checked, opened))) {
662
- throw new ContractValidationError(`${context}: expected the checked regular file.`);
663
- }
664
- for (const parent of checked.parents) {
665
- const current = await lstat(parent.path, { bigint: true });
666
- throwIfAborted(signal);
667
- if (!current.isDirectory() ||
668
- current.dev !== parent.metadata.dev ||
669
- current.ino !== parent.metadata.ino) {
670
- throw new ContractValidationError(`${context}: checked parent changed before opening the file.`);
671
- }
672
- }
673
- const current = await lstat(checked.path, { bigint: true });
674
- throwIfAborted(signal);
675
- if (!current.isFile() ||
676
- current.dev !== checked.metadata.dev ||
677
- current.ino !== checked.metadata.ino) {
678
- throw new ContractValidationError(`${context}: checked file changed before reading.`);
679
- }
680
- return file;
681
- }
682
- catch (error) {
683
- await file?.close();
684
- throwIfAborted(signal);
685
- if (error instanceof ContractValidationError)
686
- throw error;
687
- throw new ContractValidationError(`${context}: unable to open the checked regular file.`, { cause: error });
688
- }
689
- }
690
135
  export async function sameCheckedFileDevice(file, checked, opened, platform = process.platform, openReference = open) {
691
136
  if (opened.ino !== checked.metadata.ino)
692
137
  return false;
@@ -714,60 +159,4 @@ export async function sameCheckedFileDevice(file, checked, opened, platform = pr
714
159
  await reference.close();
715
160
  }
716
161
  }
717
- function throwIfAborted(signal) {
718
- if (!signal?.aborted)
719
- return;
720
- throw abortReason(signal);
721
- }
722
- const RFC3339_DATE_TIME = new RegExp(regexes.datetime({ offset: true }).source, "i");
723
- function validRfc3339DateTime(value) {
724
- return !value.startsWith("0000") && RFC3339_DATE_TIME.test(value);
725
- }
726
- function schemaError(filename, errors) {
727
- const first = errors[0];
728
- if (filename === "coverage.json" &&
729
- first?.keyword === "oneOf" &&
730
- Array.isArray(first.schema) &&
731
- first.schema.some((rule, index) => isRecord(rule) &&
732
- rule["$comment"] === SEALED_DEFERRED_PATH_RULE &&
733
- first.params["passingSchemas"]?.includes(index))) {
734
- const match = DEFERRED_PATH_LOCATION.exec(first.instancePath);
735
- if (match)
736
- return new ContractValidationError(`coverage.deferred[${match[1]}].paths[${match[2]}]: expected a safe repository-relative POSIX path.`);
737
- }
738
- const location = first?.instancePath
739
- ? JSON.stringify(first.instancePath)
740
- : "<root>";
741
- const keyword = first?.keyword ?? "unknown";
742
- const count = errors.length;
743
- return new ContractValidationError(`${filename}:${location}: schema validation failed (${keyword}${keyword === "format" && first?.params["format"] === "date-time" ? "; date-time" : ""}; ${count} ${count === 1 ? "error" : "errors"})${first?.message ? `: ${first.message}` : ""}.`);
744
- }
745
- function nodeErrorCode(error) {
746
- return typeof error === "object" && error !== null && "code" in error
747
- ? String(error.code)
748
- : undefined;
749
- }
750
- /** @internal */
751
- export function sha256Text(value) {
752
- return hash("sha256", value);
753
- }
754
- export function deriveFindingIdentity(scanId, targetId, ruleId, identity) {
755
- const fingerprint = `codex-security/v1:sha256:${sha256Text([
756
- "codex-security/v1",
757
- targetId,
758
- ruleId,
759
- identity.anchor,
760
- identity.instance ?? "",
761
- ].join("\0"))}`;
762
- return {
763
- findingId: `csf_${sha256Text(fingerprint).slice(0, 24)}`,
764
- occurrenceId: `occ_${sha256Text([scanId, fingerprint].join("\0")).slice(0, 24)}`,
765
- ruleId,
766
- identity,
767
- fingerprints: {
768
- algorithm: "codex-security/v1",
769
- primary: fingerprint,
770
- },
771
- };
772
- }
773
162
  //# sourceMappingURL=contract.js.map