@openai/codex-security 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +52 -9
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  5. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  6. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +60 -9
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/references/core-scan.md +2 -0
  10. package/_bundled_plugin/references/final-report.md +5 -1
  11. package/_bundled_plugin/references/investigation-time-budget.md +11 -0
  12. package/_bundled_plugin/references/sarif-adapter.md +1 -0
  13. package/_bundled_plugin/references/scan-prologue.md +2 -6
  14. package/_bundled_plugin/references/scan-runtime.md +15 -0
  15. package/_bundled_plugin/references/threat-model.md +2 -0
  16. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +6 -2
  17. package/_bundled_plugin/scripts/deep_scan_workbench.py +7 -0
  18. package/_bundled_plugin/scripts/finalize_scan_contract.py +92 -44
  19. package/_bundled_plugin/scripts/finding_preview.py +5 -3
  20. package/_bundled_plugin/scripts/generate_in_scope_files.py +6 -6
  21. package/_bundled_plugin/scripts/generate_rank_input.py +13 -6
  22. package/_bundled_plugin/scripts/launch_codex_security_mcp +39 -4
  23. package/_bundled_plugin/scripts/report_projection.py +2 -1
  24. package/_bundled_plugin/scripts/snapshot_sqlite.py +7 -0
  25. package/_bundled_plugin/scripts/threat_model_projection.py +1 -3
  26. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -1
  27. package/_bundled_plugin/scripts/workbench/saved_coverage.py +234 -0
  28. package/_bundled_plugin/scripts/workbench_cli.py +5 -10
  29. package/_bundled_plugin/scripts/workbench_constants.py +4 -0
  30. package/_bundled_plugin/scripts/workbench_db.py +68 -39
  31. package/_bundled_plugin/scripts/workbench_native_indexes.py +10 -7
  32. package/_bundled_plugin/scripts/workbench_progress.py +0 -50
  33. package/_bundled_plugin/scripts/workbench_publication.py +4 -3
  34. package/_bundled_plugin/scripts/workbench_remediation.py +5 -1
  35. package/_bundled_plugin/scripts/workbench_saved_results.py +542 -148
  36. package/_bundled_plugin/scripts/workbench_scan_history.py +82 -80
  37. package/_bundled_plugin/scripts/workbench_scan_start.py +12 -4
  38. package/_bundled_plugin/scripts/workbench_scan_usage.py +246 -38
  39. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  40. package/_bundled_plugin/scripts/workbench_source_excerpt.py +74 -51
  41. package/_bundled_plugin/scripts/workbench_source_scopes.py +388 -0
  42. package/_bundled_plugin/scripts/workbench_target.py +28 -12
  43. package/_bundled_plugin/scripts/workbench_validation.py +52 -13
  44. package/_bundled_plugin/shared/workbench-history-repairs.json +19 -0
  45. package/_bundled_plugin/shared/workbench-migrations.json +15 -0
  46. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +1 -1
  47. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +4 -2
  48. package/_bundled_plugin/skills/security-scan/SKILL.md +3 -1
  49. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  50. package/dist/api.d.ts +4 -3
  51. package/dist/api.d.ts.map +1 -1
  52. package/dist/api.js +215 -93
  53. package/dist/api.js.map +1 -1
  54. package/dist/artifact-export.d.ts +2 -1
  55. package/dist/artifact-export.d.ts.map +1 -1
  56. package/dist/artifact-export.js +38 -23
  57. package/dist/artifact-export.js.map +1 -1
  58. package/dist/classify-scan-severity.d.ts.map +1 -1
  59. package/dist/classify-scan-severity.js +16 -18
  60. package/dist/classify-scan-severity.js.map +1 -1
  61. package/dist/classify-severity-records.d.ts +76 -0
  62. package/dist/classify-severity-records.d.ts.map +1 -0
  63. package/dist/classify-severity-records.js +141 -0
  64. package/dist/classify-severity-records.js.map +1 -0
  65. package/dist/classify-severity.d.ts +1 -23
  66. package/dist/classify-severity.d.ts.map +1 -1
  67. package/dist/classify-severity.js +3 -24
  68. package/dist/classify-severity.js.map +1 -1
  69. package/dist/cli-daybreak.d.ts +5 -0
  70. package/dist/cli-daybreak.d.ts.map +1 -0
  71. package/dist/cli-daybreak.js +89 -0
  72. package/dist/cli-daybreak.js.map +1 -0
  73. package/dist/cli-help.d.ts.map +1 -1
  74. package/dist/cli-help.js +2 -0
  75. package/dist/cli-help.js.map +1 -1
  76. package/dist/cli.d.ts +9 -3
  77. package/dist/cli.d.ts.map +1 -1
  78. package/dist/cli.js +957 -738
  79. package/dist/cli.js.map +1 -1
  80. package/dist/cloud-publish.js +1 -1
  81. package/dist/cloud-publish.js.map +1 -1
  82. package/dist/codeowners.js +2 -2
  83. package/dist/codeowners.js.map +1 -1
  84. package/dist/codex-sdk-environment.js +1 -1
  85. package/dist/codex-sdk-environment.js.map +1 -1
  86. package/dist/component-plan.d.ts.map +1 -1
  87. package/dist/component-plan.js +3 -2
  88. package/dist/component-plan.js.map +1 -1
  89. package/dist/component-scan.js +2 -2
  90. package/dist/component-scan.js.map +1 -1
  91. package/dist/config.d.ts +12 -0
  92. package/dist/config.d.ts.map +1 -1
  93. package/dist/config.js +15 -5
  94. package/dist/config.js.map +1 -1
  95. package/dist/contract.d.ts +5 -0
  96. package/dist/contract.d.ts.map +1 -1
  97. package/dist/contract.js +65 -17
  98. package/dist/contract.js.map +1 -1
  99. package/dist/cost-model.d.ts.map +1 -1
  100. package/dist/cost-model.js +7 -2
  101. package/dist/cost-model.js.map +1 -1
  102. package/dist/cost.d.ts +2 -1
  103. package/dist/cost.d.ts.map +1 -1
  104. package/dist/cost.js +17 -8
  105. package/dist/cost.js.map +1 -1
  106. package/dist/custom-validation-prompt.js +3 -3
  107. package/dist/custom-validation-prompt.js.map +1 -1
  108. package/dist/custom-validation.d.ts.map +1 -1
  109. package/dist/custom-validation.js +2 -5
  110. package/dist/custom-validation.js.map +1 -1
  111. package/dist/deduplication/codex-review.d.ts.map +1 -1
  112. package/dist/deduplication/codex-review.js +8 -6
  113. package/dist/deduplication/codex-review.js.map +1 -1
  114. package/dist/deduplication/deduplication-prompts.d.ts +1 -1
  115. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  116. package/dist/deduplication/deduplication-prompts.js +2 -2
  117. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  118. package/dist/deduplication/local.d.ts.map +1 -1
  119. package/dist/deduplication/local.js +5 -2
  120. package/dist/deduplication/local.js.map +1 -1
  121. package/dist/deduplication/records.js +1 -1
  122. package/dist/deduplication/records.js.map +1 -1
  123. package/dist/deduplication/retry.d.ts.map +1 -1
  124. package/dist/deduplication/retry.js +5 -0
  125. package/dist/deduplication/retry.js.map +1 -1
  126. package/dist/deduplication/scan.d.ts.map +1 -1
  127. package/dist/deduplication/scan.js +15 -10
  128. package/dist/deduplication/scan.js.map +1 -1
  129. package/dist/deep-config.d.ts +4 -1
  130. package/dist/deep-config.d.ts.map +1 -1
  131. package/dist/deep-config.js +21 -1
  132. package/dist/deep-config.js.map +1 -1
  133. package/dist/deep-scan.d.ts +6 -0
  134. package/dist/deep-scan.d.ts.map +1 -1
  135. package/dist/deep-scan.js +8 -6
  136. package/dist/deep-scan.js.map +1 -1
  137. package/dist/findings-import.d.ts +1 -1
  138. package/dist/findings-import.d.ts.map +1 -1
  139. package/dist/findings-import.js +26 -6
  140. package/dist/findings-import.js.map +1 -1
  141. package/dist/git-remote.d.ts +10 -0
  142. package/dist/git-remote.d.ts.map +1 -0
  143. package/dist/git-remote.js +24 -0
  144. package/dist/git-remote.js.map +1 -0
  145. package/dist/github.d.ts.map +1 -1
  146. package/dist/github.js +5 -7
  147. package/dist/github.js.map +1 -1
  148. package/dist/host-protocol.d.ts +1 -0
  149. package/dist/host-protocol.d.ts.map +1 -1
  150. package/dist/host-protocol.js +2 -2
  151. package/dist/host-protocol.js.map +1 -1
  152. package/dist/host-records-protocol.d.ts +15 -0
  153. package/dist/host-records-protocol.d.ts.map +1 -0
  154. package/dist/host-records-protocol.js +15 -0
  155. package/dist/host-records-protocol.js.map +1 -0
  156. package/dist/hosted-remediation-protocol.d.ts +5 -0
  157. package/dist/hosted-remediation-protocol.d.ts.map +1 -0
  158. package/dist/hosted-remediation-protocol.js +26 -0
  159. package/dist/hosted-remediation-protocol.js.map +1 -0
  160. package/dist/hosted-remediation.d.ts +89 -0
  161. package/dist/hosted-remediation.d.ts.map +1 -0
  162. package/dist/hosted-remediation.js +122 -0
  163. package/dist/hosted-remediation.js.map +1 -0
  164. package/dist/hosted-scan.d.ts +1 -6
  165. package/dist/hosted-scan.d.ts.map +1 -1
  166. package/dist/hosted-scan.js +2 -2
  167. package/dist/hosted-scan.js.map +1 -1
  168. package/dist/import-scan.d.ts +1 -0
  169. package/dist/import-scan.d.ts.map +1 -1
  170. package/dist/import-scan.js +5 -1
  171. package/dist/import-scan.js.map +1 -1
  172. package/dist/index.d.ts +9 -1
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +4 -0
  175. package/dist/index.js.map +1 -1
  176. package/dist/knowledge-base.d.ts.map +1 -1
  177. package/dist/knowledge-base.js +87 -7
  178. package/dist/knowledge-base.js.map +1 -1
  179. package/dist/multiscan.d.ts.map +1 -1
  180. package/dist/multiscan.js +65 -29
  181. package/dist/multiscan.js.map +1 -1
  182. package/dist/patch-publication.d.ts +26 -0
  183. package/dist/patch-publication.d.ts.map +1 -0
  184. package/dist/patch-publication.js +105 -0
  185. package/dist/patch-publication.js.map +1 -0
  186. package/dist/patch-tui.d.ts.map +1 -1
  187. package/dist/patch-tui.js +4 -1
  188. package/dist/patch-tui.js.map +1 -1
  189. package/dist/project-config-schema.d.ts +2 -0
  190. package/dist/project-config-schema.d.ts.map +1 -1
  191. package/dist/project-config-schema.js +1 -0
  192. package/dist/project-config-schema.js.map +1 -1
  193. package/dist/project-config.d.ts +1 -0
  194. package/dist/project-config.d.ts.map +1 -1
  195. package/dist/project-config.js +29 -15
  196. package/dist/project-config.js.map +1 -1
  197. package/dist/publication.d.ts.map +1 -1
  198. package/dist/publication.js +135 -19
  199. package/dist/publication.js.map +1 -1
  200. package/dist/publish.d.ts +2 -0
  201. package/dist/publish.d.ts.map +1 -1
  202. package/dist/publish.js +48 -25
  203. package/dist/publish.js.map +1 -1
  204. package/dist/remediation.d.ts +63 -0
  205. package/dist/remediation.d.ts.map +1 -0
  206. package/dist/remediation.js +110 -0
  207. package/dist/remediation.js.map +1 -0
  208. package/dist/request-metadata.d.ts +17 -7
  209. package/dist/request-metadata.d.ts.map +1 -1
  210. package/dist/request-metadata.js +43 -8
  211. package/dist/request-metadata.js.map +1 -1
  212. package/dist/runtime.d.ts.map +1 -1
  213. package/dist/runtime.js +104 -36
  214. package/dist/runtime.js.map +1 -1
  215. package/dist/saved-scan-bootstrap.d.ts +1 -0
  216. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  217. package/dist/saved-scan-bootstrap.js +16 -4
  218. package/dist/saved-scan-bootstrap.js.map +1 -1
  219. package/dist/scan-activity.js +8 -8
  220. package/dist/scan-activity.js.map +1 -1
  221. package/dist/scan-comparison.d.ts.map +1 -1
  222. package/dist/scan-comparison.js +15 -9
  223. package/dist/scan-comparison.js.map +1 -1
  224. package/dist/scan-dashboard.d.ts.map +1 -1
  225. package/dist/scan-dashboard.js +12 -6
  226. package/dist/scan-dashboard.js.map +1 -1
  227. package/dist/scan-executor.d.ts +5 -1
  228. package/dist/scan-executor.d.ts.map +1 -1
  229. package/dist/scan-executor.js +9 -8
  230. package/dist/scan-executor.js.map +1 -1
  231. package/dist/{deep-progress.d.ts → scan-progress.d.ts} +15 -7
  232. package/dist/scan-progress.d.ts.map +1 -0
  233. package/dist/scan-progress.js +138 -0
  234. package/dist/scan-progress.js.map +1 -0
  235. package/dist/scan-settings.d.ts +1 -0
  236. package/dist/scan-settings.d.ts.map +1 -1
  237. package/dist/scan-settings.js +7 -1
  238. package/dist/scan-settings.js.map +1 -1
  239. package/dist/scan-time-budget.d.ts +9 -0
  240. package/dist/scan-time-budget.d.ts.map +1 -0
  241. package/dist/scan-time-budget.js +16 -0
  242. package/dist/scan-time-budget.js.map +1 -0
  243. package/dist/security-policy.js +1 -1
  244. package/dist/security-policy.js.map +1 -1
  245. package/dist/server/embeddings.d.ts.map +1 -1
  246. package/dist/server/embeddings.js +4 -0
  247. package/dist/server/embeddings.js.map +1 -1
  248. package/dist/server/sqlite-store.d.ts.map +1 -1
  249. package/dist/server/sqlite-store.js +14 -2
  250. package/dist/server/sqlite-store.js.map +1 -1
  251. package/dist/severity-review.d.ts +29 -0
  252. package/dist/severity-review.d.ts.map +1 -0
  253. package/dist/severity-review.js +47 -0
  254. package/dist/severity-review.js.map +1 -0
  255. package/dist/severity-store.js +4 -1
  256. package/dist/severity-store.js.map +1 -1
  257. package/dist/timestamps.d.ts +3 -0
  258. package/dist/timestamps.d.ts.map +1 -0
  259. package/dist/timestamps.js +14 -0
  260. package/dist/timestamps.js.map +1 -0
  261. package/dist/validation-records.d.ts +38 -0
  262. package/dist/validation-records.d.ts.map +1 -0
  263. package/dist/validation-records.js +76 -0
  264. package/dist/validation-records.js.map +1 -0
  265. package/dist/version.d.ts +1 -1
  266. package/dist/version.d.ts.map +1 -1
  267. package/dist/version.js +17 -4
  268. package/dist/version.js.map +1 -1
  269. package/dist/workbench-arguments.d.ts.map +1 -1
  270. package/dist/workbench-arguments.js +9 -3
  271. package/dist/workbench-arguments.js.map +1 -1
  272. package/dist/worker-progress.d.ts +13 -7
  273. package/dist/worker-progress.d.ts.map +1 -1
  274. package/dist/worker-progress.js +12 -44
  275. package/dist/worker-progress.js.map +1 -1
  276. package/docs/classify-severity-records.md +89 -0
  277. package/docs/cli.md +352 -45
  278. package/docs/findings-service.md +7 -2
  279. package/docs/hosted-remediation.md +117 -0
  280. package/docs/hosted-scans.md +8 -3
  281. package/docs/validate-records.md +69 -0
  282. package/package.json +13 -10
  283. package/schemas/project-config.schema.json +7 -1
  284. package/_bundled_plugin/preflight/capability-profiles.toml +0 -76
  285. package/_bundled_plugin/references/config-preflight.md +0 -93
  286. package/_bundled_plugin/references/desktop-config-preflight.md +0 -11
  287. package/_bundled_plugin/scripts/config_preflight.py +0 -911
  288. package/dist/deep-progress.d.ts.map +0 -1
  289. package/dist/deep-progress.js +0 -92
  290. package/dist/deep-progress.js.map +0 -1
@@ -9,6 +9,7 @@ import csv
9
9
  import errno
10
10
  import hashlib
11
11
  import io
12
+ import ipaddress
12
13
  import json
13
14
  import math
14
15
  import os
@@ -67,6 +68,7 @@ RFC3339_RE = re.compile(
67
68
  re.ASCII,
68
69
  )
69
70
  REMOTE_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]")
71
+ REMOTE_UNSAFE_HOST_RE = re.compile(r"[\s<>^|]")
70
72
  GITHUB_HASH_BLOCK_SIZE = 100
71
73
  GITHUB_HASH_MOD = 37
72
74
  GITHUB_HASH_MASK = (1 << 64) - 1
@@ -845,16 +847,20 @@ def write_scan_local_bytes(
845
847
  os.replace(temp_name, parts[-1], src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
846
848
  temp_name = None
847
849
  finally:
848
- if temp_name is not None and parent_fd is not None:
850
+ try:
851
+ if temp_name is not None and parent_fd is not None:
852
+ try:
853
+ os.unlink(temp_name, dir_fd=parent_fd)
854
+ except FileNotFoundError:
855
+ # The temporary file is already gone, so cleanup is complete.
856
+ pass
857
+ finally:
849
858
  try:
850
- os.unlink(temp_name, dir_fd=parent_fd)
851
- except FileNotFoundError:
852
- # The temporary file is already gone, so cleanup is complete.
853
- pass
854
- if parent_fd is not None:
855
- os.close(parent_fd)
856
- if root_fd is not None:
857
- os.close(root_fd)
859
+ if parent_fd is not None:
860
+ os.close(parent_fd)
861
+ finally:
862
+ if root_fd is not None:
863
+ os.close(root_fd)
858
864
 
859
865
 
860
866
  def _remove_scan_local_file_if_exists(scan_dir: Path, relative_path: str) -> None:
@@ -895,13 +901,35 @@ def _write_scan_local_json(scan_dir: Path, relative_path: str, payload: Any) ->
895
901
  def _validate_remote(remote: str, context: str) -> None:
896
902
  if REMOTE_CONTROL_RE.search(remote):
897
903
  raise ContractError(f"{context}: expected a sanitized canonical absolute URL")
898
- parsed = urlsplit(remote)
904
+ try:
905
+ parsed = urlsplit(remote)
906
+ except ValueError as exc:
907
+ # urlsplit rejects authorities with unbalanced brackets.
908
+ raise ContractError(f"{context}: expected a sanitized canonical absolute URL") from exc
899
909
  if "\\" in remote or not parsed.scheme or not parsed.netloc:
900
910
  raise ContractError(f"{context}: expected a sanitized canonical absolute URL")
901
- if parsed.username or parsed.password or parsed.query or parsed.fragment:
911
+ if "@" in parsed.netloc or parsed.query or parsed.fragment:
902
912
  raise ContractError(
903
913
  f"{context}: remote URL must not contain credentials, query, or fragment"
904
914
  )
915
+ # Mirrors the authority rules of the WHATWG URL parser the SDK reader applies.
916
+ authority = parsed.netloc
917
+ if authority.startswith("["):
918
+ try:
919
+ ipaddress.IPv6Address(authority.partition("]")[0][1:])
920
+ except ValueError as exc:
921
+ raise ContractError(f"{context}: expected a sanitized canonical absolute URL") from exc
922
+ authority = authority.partition("]")[2]
923
+ if authority and not authority.startswith(":"):
924
+ raise ContractError(f"{context}: expected a sanitized canonical absolute URL")
925
+ port = authority.partition(":")[2]
926
+ hostname = parsed.hostname
927
+ if (
928
+ not hostname
929
+ or REMOTE_UNSAFE_HOST_RE.search(hostname)
930
+ or (port and (not port.isascii() or not port.isdigit() or int(port) > 65535))
931
+ ):
932
+ raise ContractError(f"{context}: expected a sanitized canonical absolute URL")
905
933
 
906
934
 
907
935
  def parse_timestamp(value: str) -> datetime:
@@ -1228,6 +1256,7 @@ def _recover_unsealed_coverage(
1228
1256
  warnings.append("Recovered malformed Deep Scan inventory strategy.")
1229
1257
 
1230
1258
  surface_ids: set[str] = set()
1259
+ receipt_paths: dict[str, str] = {}
1231
1260
  for field, label in (
1232
1261
  ("surfaces", "coverage surface"),
1233
1262
  ("explicitExclusions", "coverage exclusion"),
@@ -1248,6 +1277,7 @@ def _recover_unsealed_coverage(
1248
1277
  if not isinstance(item, dict):
1249
1278
  raise ContractError(f"{context}: expected an object")
1250
1279
  if field == "surfaces":
1280
+ surface_receipt_paths = dict(receipt_paths)
1251
1281
  surface_id = _require_str(item, "id", context)
1252
1282
  if surface_id in surface_ids:
1253
1283
  raise ContractError(f"{context}.id: duplicate surface id")
@@ -1282,6 +1312,11 @@ def _recover_unsealed_coverage(
1282
1312
  f"{ref_context}: expected a file under artifacts/"
1283
1313
  )
1284
1314
  _require_scan_local_file(scan_dir, normalized_ref, ref_context)
1315
+ key = normalized_ref.lower()
1316
+ previous = surface_receipt_paths.get(key)
1317
+ if previous is not None and previous != normalized_ref:
1318
+ raise ContractError(f"{ref_context}: duplicate artifact path")
1319
+ surface_receipt_paths[key] = normalized_ref
1285
1320
  except ContractError as exc:
1286
1321
  warnings.append(
1287
1322
  f"Skipped malformed coverage receipt "
@@ -1304,6 +1339,7 @@ def _recover_unsealed_coverage(
1304
1339
 
1305
1340
  if field == "surfaces":
1306
1341
  surface_ids.add(surface_id)
1342
+ receipt_paths = surface_receipt_paths
1307
1343
  recovered.append(item)
1308
1344
 
1309
1345
  coverage[field] = recovered
@@ -1401,19 +1437,53 @@ def _populate_unsealed_manifest_envelope(
1401
1437
  allowed_kinds = completion_binding["allowedTargetKinds"]
1402
1438
  if len(allowed_kinds) == 1:
1403
1439
  target.setdefault("kind", allowed_kinds[0])
1404
- _populate_unsealed_target_binding(target, completion_binding["target"])
1440
+ _populate_unsealed_target_binding(target, completion_binding["target"], allowed_kinds)
1405
1441
 
1406
1442
  scope = scan.setdefault("scope", {})
1407
1443
  if isinstance(scope, dict):
1408
1444
  scope.update(copy.deepcopy(completion_binding["scope"]))
1409
1445
 
1410
1446
 
1447
+ def _populate_unsealed_target_kind(
1448
+ target: dict[str, Any],
1449
+ target_binding: dict[str, Any],
1450
+ allowed_kinds: Any,
1451
+ ) -> None:
1452
+ """Adopt the registered target kind when the binding owns every coordinate it needs.
1453
+
1454
+ The workbench, not the draft, knows how the target was registered: a scan agent
1455
+ that infers the kind from the checkout (a clean worktree registered as
1456
+ git_revision is the common case) used to discard the whole completed scan at the
1457
+ seal step. The kind carries no draft-owned information when the registration
1458
+ allows a single value, so take that value instead of failing.
1459
+
1460
+ Rewriting the kind also reinterprets the coordinates that kind requires, and a
1461
+ coordinate the binding does not own survives the replacement below with whatever
1462
+ the draft computed under its own reading of the target. Adopting git_diff without
1463
+ a bound snapshotDigest, for example, would seal a whole-worktree digest as the
1464
+ diff digest. Leave the kind alone whenever the binding cannot restate every
1465
+ coordinate the registered kind requires, and let the binding check reject the
1466
+ draft instead.
1467
+ """
1468
+
1469
+ if not isinstance(allowed_kinds, list) or len(allowed_kinds) != 1:
1470
+ return
1471
+ registered_kind = allowed_kinds[0]
1472
+ if not isinstance(registered_kind, str) or target.get("kind") == registered_kind:
1473
+ return
1474
+ if not TARGET_REQUIRED_COORDINATE_FIELDS.get(registered_kind, set()) <= target_binding.keys():
1475
+ return
1476
+ target["kind"] = registered_kind
1477
+
1478
+
1411
1479
  def _populate_unsealed_target_binding(
1412
1480
  target: dict[str, Any],
1413
1481
  target_binding: dict[str, Any],
1482
+ allowed_kinds: Any = None,
1414
1483
  ) -> None:
1415
1484
  """Replace workbench-owned target coordinates without retaining incompatible drafts."""
1416
1485
 
1486
+ _populate_unsealed_target_kind(target, target_binding, allowed_kinds)
1417
1487
  target_kind = target.get("kind")
1418
1488
  required_coordinates = (
1419
1489
  TARGET_REQUIRED_COORDINATE_FIELDS.get(target_kind, set())
@@ -2197,8 +2267,8 @@ def _sarif_rule(rule_id: str, findings: list[dict[str, Any]]) -> dict[str, Any]:
2197
2267
  tags = {"security", *categories}
2198
2268
  for cwe in cwes:
2199
2269
  match = re.fullmatch(r"CWE-([0-9]+)", cwe, re.IGNORECASE)
2200
- if match and int(match[1]) > 0:
2201
- tags.add(f"external/cwe/cwe-{int(match[1]):03d}")
2270
+ if match and (digits := match[1].lstrip("0")):
2271
+ tags.add(f"external/cwe/cwe-{digits.zfill(3)}")
2202
2272
  description = f"{name}. Categories: {', '.join(map(_sarif_label, categories))}."
2203
2273
  if cwes:
2204
2274
  description += f" Weaknesses: {', '.join(cwes)}."
@@ -2443,31 +2513,6 @@ def _sarif_locations(finding: dict[str, Any]) -> list[dict[str, Any]]:
2443
2513
  return list(unique.values())
2444
2514
 
2445
2515
 
2446
- def _github_primary_location_line_hash(
2447
- finding: dict[str, Any],
2448
- source_root: Path | None,
2449
- line_hash_cache: dict[tuple[Path, int], str | None] | None = None,
2450
- ) -> str | None:
2451
- if source_root is None:
2452
- return None
2453
- primary_location = _sarif_primary_location(finding)
2454
- try:
2455
- source_root = source_root.resolve(strict=True)
2456
- except (OSError, RuntimeError):
2457
- return None
2458
- relative_path = _require_safe_relative_path(primary_location["path"], "SARIF source location")
2459
- source_path = source_root / relative_path
2460
- start_line = primary_location["startLine"]
2461
- cache_key = (source_path, start_line)
2462
- if line_hash_cache is not None and cache_key in line_hash_cache:
2463
- return line_hash_cache[cache_key]
2464
- line_hashes = _github_line_hashes_for_source(source_root, relative_path, {start_line})
2465
- line_hash = None if line_hashes is None else line_hashes.get(start_line)
2466
- if line_hash_cache is not None:
2467
- line_hash_cache[cache_key] = line_hash
2468
- return line_hash
2469
-
2470
-
2471
2516
  def _github_line_hash_cache(
2472
2517
  findings: list[dict[str, Any]], source_root: Path | None
2473
2518
  ) -> dict[tuple[Path, int], str | None]:
@@ -2487,7 +2532,7 @@ def _github_line_hash_cache(
2487
2532
  line_hash_cache: dict[tuple[Path, int], str | None] = {}
2488
2533
  for relative_path, requested_lines in requested_lines_by_path.items():
2489
2534
  line_hashes = _github_line_hashes_for_source(source_root, relative_path, requested_lines)
2490
- source_path = source_root / relative_path
2535
+ source_path = Path(relative_path)
2491
2536
  for line_number in requested_lines:
2492
2537
  line_hash_cache[(source_path, line_number)] = (
2493
2538
  None if line_hashes is None else line_hashes.get(line_number)
@@ -2515,7 +2560,6 @@ def _sarif_location(location: dict[str, Any]) -> dict[str, Any]:
2515
2560
  def _sarif_result(
2516
2561
  finding: dict[str, Any],
2517
2562
  rule_index: int,
2518
- source_root: Path | None = None,
2519
2563
  line_hash_cache: dict[tuple[Path, int], str | None] | None = None,
2520
2564
  ) -> dict[str, Any]:
2521
2565
  properties = {
@@ -2532,7 +2576,8 @@ def _sarif_result(
2532
2576
  partial_fingerprints = {
2533
2577
  "codexSecurity/v1": finding["fingerprints"]["primary"],
2534
2578
  }
2535
- line_hash = _github_primary_location_line_hash(finding, source_root, line_hash_cache)
2579
+ primary = _sarif_primary_location(finding)
2580
+ line_hash = (line_hash_cache or {}).get((Path(primary["path"]), primary["startLine"]))
2536
2581
  if line_hash is not None:
2537
2582
  partial_fingerprints["primaryLocationLineHash"] = line_hash
2538
2583
  return {
@@ -2570,7 +2615,7 @@ def build_sarif(
2570
2615
  },
2571
2616
  "automationDetails": {"id": scan["id"]},
2572
2617
  "results": [
2573
- _sarif_result(finding, rule_index[finding["ruleId"]], source_root, line_hash_cache)
2618
+ _sarif_result(finding, rule_index[finding["ruleId"]], line_hash_cache)
2574
2619
  for finding in ordered_findings
2575
2620
  ],
2576
2621
  "properties": {
@@ -2750,7 +2795,10 @@ def write_sarif_projection(
2750
2795
  scan_dir: Path, source_root: Path | None = None, schema_dir: Path | None = None
2751
2796
  ) -> None:
2752
2797
  sarif = build_sarif_projection(scan_dir, source_root, schema_dir)
2753
- _write_scan_local_json(scan_dir, "exports/results.sarif", sarif)
2798
+ relative_path = EXPORT_PATHS["sarif"]
2799
+ write_export_output(
2800
+ scan_dir, scan_dir / relative_path, "sarif", _contract_json_bytes(relative_path, sarif)
2801
+ )
2754
2802
 
2755
2803
 
2756
2804
  def csv_cell(value: Any) -> Any:
@@ -7,7 +7,7 @@ import json
7
7
  import re
8
8
  import sys
9
9
  from bisect import bisect_right
10
- from itertools import chain
10
+ from itertools import chain, islice
11
11
  from pathlib import Path
12
12
  from typing import Any
13
13
 
@@ -390,7 +390,7 @@ def bounded_json_value(
390
390
  if not consume_json_budget(budget, 2):
391
391
  return {}
392
392
  result = {}
393
- for key, item in list(value.items())[:20]:
393
+ for key, item in islice(value.items(), 20):
394
394
  if budget[0] <= 0 or not isinstance(key, str):
395
395
  break
396
396
  remaining = budget[0]
@@ -447,7 +447,9 @@ def consume_json_budget(budget: list[int], size: int) -> bool:
447
447
 
448
448
 
449
449
  def bounded_json_text(value: str, maximum_bytes: int) -> tuple[str, int]:
450
- length = bisect_right(range(len(value) + 1), maximum_bytes, key=lambda n: json_size(value[:n]))
450
+ length = bisect_right(
451
+ range(min(len(value), maximum_bytes) + 1), maximum_bytes, key=lambda n: json_size(value[:n])
452
+ )
451
453
  selected = value[: max(0, length - 1)]
452
454
  return selected, json_size(selected)
453
455
 
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
 
13
13
  # Some plugin hosts launch Python with safe-path isolation enabled.
14
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
15
- from workbench_target import git_blob_samples, git_command
15
+ from workbench_target import SOURCE_METADATA_DIRECTORIES, git_blob_samples, git_command
16
16
 
17
17
 
18
18
  class InventoryError(ValueError):
@@ -94,11 +94,11 @@ def generate_in_scope_files(repository: Path, scope: str, output: Path) -> int:
94
94
  "--hidden",
95
95
  "--path-separator",
96
96
  "/",
97
- # Prune Git metadata and its contents even when the scope starts inside .git.
97
+ # Prune metadata and its contents even when the scope starts inside it.
98
98
  "--glob",
99
- "!**/.git",
99
+ "!**/{.git,.svn}",
100
100
  "--glob",
101
- "!**/.git/**",
101
+ "!**/{.git,.svn}/**",
102
102
  "--",
103
103
  scope,
104
104
  ]
@@ -121,7 +121,7 @@ def generate_in_scope_files(repository: Path, scope: str, output: Path) -> int:
121
121
  message = f"{message}: {detail}"
122
122
  raise InventoryError(message)
123
123
 
124
- if (repository / ".git").exists():
124
+ if any((parent / ".git").exists() for parent in (repository, *repository.parents)):
125
125
  try:
126
126
  tracked = git_command(
127
127
  repository,
@@ -146,7 +146,7 @@ def generate_in_scope_files(repository: Path, scope: str, output: Path) -> int:
146
146
  inventory.seek(0)
147
147
  rows: list[bytes] = []
148
148
  for path in inventory.read().split(b"\0"):
149
- if not path:
149
+ if not path or not SOURCE_METADATA_DIRECTORIES.isdisjoint(os.fsdecode(path).split("/")):
150
150
  continue
151
151
  if b"\n" in path or b"\r" in path:
152
152
  raise InventoryError(
@@ -31,7 +31,12 @@ from rank_preview import (
31
31
  preview_for,
32
32
  preview_for_bytes,
33
33
  )
34
- from workbench_target import git_blob_samples, git_command, git_directory_snapshot_paths
34
+ from workbench_target import (
35
+ SOURCE_METADATA_DIRECTORIES,
36
+ git_blob_samples,
37
+ git_command,
38
+ git_directory_snapshot_paths,
39
+ )
35
40
 
36
41
  JsonRow = dict[str, object]
37
42
 
@@ -155,11 +160,11 @@ def scope_candidates(repo: Path, scope_path: Path) -> Iterable[Path]:
155
160
  "--hidden",
156
161
  "--no-require-git",
157
162
  "--null",
158
- # Also exclude descendants when the scope starts inside .git.
163
+ # Also exclude descendants when the scope starts inside metadata.
159
164
  "--glob",
160
- "!**/.git",
165
+ "!**/{.git,.svn}",
161
166
  "--glob",
162
- "!**/.git/**",
167
+ "!**/{.git,.svn}/**",
163
168
  "--",
164
169
  str(scope_path.relative_to(repo)),
165
170
  ]
@@ -207,7 +212,7 @@ def make_repo_scope_input(args: argparse.Namespace) -> None:
207
212
  relative = path.resolve(strict=True).relative_to(repo)
208
213
  except (OSError, ValueError):
209
214
  continue
210
- if ".git" in relative.parts:
215
+ if not SOURCE_METADATA_DIRECTORIES.isdisjoint(relative.parts):
211
216
  continue
212
217
  rows_by_path.setdefault(relative.as_posix(), {"path": relative.as_posix()})
213
218
 
@@ -227,6 +232,7 @@ def run_git_changed_paths(repo: Path, diff_args: list[str]) -> list[tuple[Path,
227
232
  "-z",
228
233
  "--diff-filter=ACMRDT",
229
234
  *diff_args,
235
+ "--",
230
236
  text=False,
231
237
  )
232
238
  result.check_returncode()
@@ -275,7 +281,8 @@ def git_changed_paths(repo: Path, base: str, head: str, mode: str) -> list[tuple
275
281
  return sorted(
276
282
  (path, status)
277
283
  for path, status in combined.items()
278
- if status == "D" or (not path.is_symlink() and path.is_file())
284
+ if SOURCE_METADATA_DIRECTORIES.isdisjoint(path.relative_to(repo).parts)
285
+ and (status == "D" or (not path.is_symlink() and path.is_file()))
279
286
  )
280
287
  raise SystemExit(f"Unknown diff mode: {mode}")
281
288
 
@@ -47,20 +47,55 @@ case "${CODEX_CLI_PATH:-}" in
47
47
  */*) codex_resources=${CODEX_CLI_PATH%/*} ;;
48
48
  esac
49
49
 
50
+ # An explicitly selected runtime remains authoritative.
51
+ if [ -n "${CODEX_MCP_NODE_PATH:-}" ] && [ -x "$CODEX_MCP_NODE_PATH" ]; then
52
+ launch_node "$CODEX_MCP_NODE_PATH" "$@"
53
+ fi
54
+
55
+ first_node=
56
+ can_load_native() {
57
+ if [ -z "$first_node" ]; then
58
+ first_node=$1
59
+ fi
60
+ # Some managed macOS runtimes enforce library validation and cannot load the
61
+ # plugin's addon. Check before starting a server or helper with side effects.
62
+ # Capture output without opening a writable file for read-only callers.
63
+ _native_probe_output=$("$1" -e '
64
+ if (process.platform === "darwin") {
65
+ require("node:sqlite");
66
+ require(require("node:path").join(process.argv[1], "native",
67
+ `${process.platform}-${process.arch}`, "unix.node"));
68
+ }
69
+ ' "$launcher_dir/../mcp" </dev/null 2>&1)
70
+ }
71
+
50
72
  for candidate in \
51
- "${CODEX_MCP_NODE_PATH:-}" \
52
73
  "${CODEX_BROWSER_USE_NODE_PATH:-}" \
53
74
  "${CODEX_ELECTRON_RESOURCES_PATH:-}/cua_node/bin/node" \
54
75
  "$codex_resources/cua_node/bin/node" \
55
76
  "$cache_root/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node"
56
77
  do
57
- if [ -n "$candidate" ] && [ -x "$candidate" ]; then
78
+ if [ -n "$candidate" ] && [ -x "$candidate" ] && can_load_native "$candidate"; then
58
79
  launch_node "$candidate" "$@"
59
80
  fi
60
81
  done
61
82
 
62
- if node_path=$(command -v node); then
63
- launch_node "$node_path" "$@"
83
+ remaining_path=$PATH
84
+ while :; do
85
+ path_entry=${remaining_path%%:*}
86
+ node_path=${path_entry:-.}/node
87
+ if [ -x "$node_path" ] && can_load_native "$node_path"; then
88
+ launch_node "$node_path" "$@"
89
+ fi
90
+ case "$remaining_path" in
91
+ *:*) remaining_path=${remaining_path#*:} ;;
92
+ *) break ;;
93
+ esac
94
+ done
95
+
96
+ if [ -n "$first_node" ]; then
97
+ # Helpers that do not use the addon can still run with the original default.
98
+ launch_node "$first_node" "$@"
64
99
  fi
65
100
 
66
101
  printf '%s\n' 'Codex Security could not find a Node runtime. Reinstall or update Codex, or set CODEX_MCP_NODE_PATH to an executable Node runtime.' >&2
@@ -47,7 +47,8 @@ def _strings(value: Any) -> list[str]:
47
47
 
48
48
  def _path_label(value: str) -> str:
49
49
  if "," in value or value != " ".join(value.split()) or any(ord(c) < 32 for c in value):
50
- return json.dumps(value)
50
+ quoted = json.dumps(value, ensure_ascii=False)
51
+ return "".join(c if c.isprintable() else json.dumps(c)[1:-1] for c in quoted)
51
52
  return value
52
53
 
53
54
 
@@ -22,6 +22,13 @@ def main() -> None:
22
22
  destination.parent.mkdir(parents=True, exist_ok=True)
23
23
  source_uri = f"file:{quote(str(source), safe='')}?mode=ro"
24
24
  with sqlite3.connect(source_uri, uri=True) as source_connection:
25
+ creation_destination = destination.resolve()
26
+ try:
27
+ creation_destination.touch(mode=0o600, exist_ok=False)
28
+ except FileExistsError:
29
+ pass
30
+ else:
31
+ creation_destination.chmod(0o600)
25
32
  with sqlite3.connect(destination) as destination_connection:
26
33
  source_connection.backup(destination_connection)
27
34
  destination.chmod(0o600)
@@ -129,9 +129,7 @@ def render_threat_model(model: dict[str, Any], provenance: dict[str, Any] | None
129
129
  ):
130
130
  if provenance.get(key):
131
131
  footer.append(f"- {label}: {text(str(provenance[key]), 'not recorded')}")
132
- footer.append(
133
- f"- Model origin: {text(str(model.get('origin', 'not recorded')), 'not recorded')}"
134
- )
132
+ footer.append(f"- Model origin: {text(model.get('origin'), 'not recorded')}")
135
133
  footer.extend(_scope_lines(model.get("scope"), "Model scope", text))
136
134
  scan_scope = provenance.get("scanScope")
137
135
  if isinstance(scan_scope, dict):
@@ -23,13 +23,13 @@ from __future__ import annotations
23
23
  import argparse
24
24
  import contextlib
25
25
  import ctypes
26
+ import ctypes.wintypes as wintypes
26
27
  import errno
27
28
  import importlib
28
29
  import ntpath
29
30
  import os
30
31
  import secrets
31
32
  from collections.abc import Iterator
32
- from ctypes import wintypes
33
33
  from pathlib import Path, PurePosixPath
34
34
  from typing import BinaryIO
35
35
 
@@ -71,7 +71,9 @@ _ERROR_ACCESS_DENIED = 5
71
71
  _ERROR_SHARING_VIOLATION = 32
72
72
  _ERROR_LOCK_VIOLATION = 33
73
73
  _ERROR_FILE_EXISTS = 80
74
+ _ERROR_INSUFFICIENT_BUFFER = 122
74
75
  _ERROR_ALREADY_EXISTS = 183
76
+ _DACL_SECURITY_INFORMATION = 0x00000004
75
77
  _MISSING_ERRORS = {_ERROR_FILE_NOT_FOUND, _ERROR_PATH_NOT_FOUND}
76
78
  _COLLISION_ERRORS = {_ERROR_FILE_EXISTS, _ERROR_ALREADY_EXISTS}
77
79
  _INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
@@ -100,6 +102,14 @@ class _FileAttributeTagInfo(ctypes.Structure):
100
102
  ]
101
103
 
102
104
 
105
+ class _SecurityAttributes(ctypes.Structure):
106
+ _fields_ = [
107
+ ("nLength", wintypes.DWORD),
108
+ ("lpSecurityDescriptor", wintypes.LPVOID),
109
+ ("bInheritHandle", wintypes.BOOL),
110
+ ]
111
+
112
+
103
113
  class _FileDispositionInfo(ctypes.Structure):
104
114
  _fields_ = [("DeleteFile", wintypes.BOOLEAN)]
105
115
 
@@ -143,6 +153,17 @@ class _OwnedHandle:
143
153
 
144
154
  if os.name == "nt":
145
155
  _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
156
+ _advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
157
+
158
+ _GetFileSecurityW = _advapi32.GetFileSecurityW
159
+ _GetFileSecurityW.argtypes = [
160
+ wintypes.LPCWSTR,
161
+ wintypes.DWORD,
162
+ wintypes.LPVOID,
163
+ wintypes.DWORD,
164
+ ctypes.POINTER(wintypes.DWORD),
165
+ ]
166
+ _GetFileSecurityW.restype = wintypes.BOOL
146
167
 
147
168
  _CreateFileW = _kernel32.CreateFileW
148
169
  _CreateFileW.argtypes = [
@@ -441,6 +462,27 @@ def _create_directory(path: Path) -> None:
441
462
  _raise_last_error("CreateDirectoryW", path)
442
463
 
443
464
 
465
+ def create_directory_with_same_dacl(path: Path, source: Path) -> None:
466
+ """Create an archive replacement with the original directory's DACL."""
467
+ _require_windows()
468
+ source_path = _extended_path(source)
469
+ size = wintypes.DWORD()
470
+ _GetFileSecurityW(source_path, _DACL_SECURITY_INFORMATION, None, 0, ctypes.byref(size))
471
+ if ctypes.get_last_error() != _ERROR_INSUFFICIENT_BUFFER:
472
+ _raise_last_error("GetFileSecurityW", source)
473
+ descriptor = ctypes.create_string_buffer(size.value)
474
+ if not _GetFileSecurityW(
475
+ source_path, _DACL_SECURITY_INFORMATION, descriptor, size.value, ctypes.byref(size)
476
+ ):
477
+ _raise_last_error("GetFileSecurityW", source)
478
+ attributes = _SecurityAttributes(
479
+ ctypes.sizeof(_SecurityAttributes), ctypes.cast(descriptor, wintypes.LPVOID), False
480
+ )
481
+ # Supply the descriptor at creation, without an inherited-access window.
482
+ if not _CreateDirectoryW(_extended_path(path), ctypes.byref(attributes)):
483
+ _raise_last_error("CreateDirectoryW", path)
484
+
485
+
444
486
  @contextlib.contextmanager
445
487
  def _locked_parent(
446
488
  scan_dir: Path,