@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,639 @@
1
+ /**
2
+ * Package-tree provenance manifest (#8040).
3
+ *
4
+ * `verify-provenance.js` used to hash exactly one file: the path preflight
5
+ * resolved. For a provider whose resolved path is a script LAUNCHER — npm
6
+ * `codex`'s `bin/codex.js`, which `spawn`s a native binary from a sibling
7
+ * platform package; `gemini`'s `bundle/gemini.js`, which `require`s dozens of
8
+ * sibling chunk files — that one file is not the code that actually runs. A
9
+ * swap of the native binary or a bundle chunk left the pinned hash unchanged
10
+ * and went undetected in `block` mode.
11
+ *
12
+ * **Decided (Chris, 2026-09-28): hash the package tree.** When the resolved
13
+ * path is a launcher, the provenance hash covers a MANIFEST of the whole
14
+ * installed package — the entry, every sibling file (including nested
15
+ * `node_modules`, where npm-global codex's native binary lives), and any
16
+ * hoisted `optionalDependencies` package that installs OUTSIDE the launcher's
17
+ * own package root. A native (non-script) resolution is unaffected — it keeps
18
+ * today's single-file hash, computed by the caller exactly as before.
19
+ *
20
+ * ## Launcher detection
21
+ *
22
+ * The resolved path is realpath'd FIRST (best-effort) — before either check
23
+ * below runs — because npm's real bin symlink (`/opt/homebrew/bin/codex` ->
24
+ * `../lib/node_modules/@openai/codex/bin/codex.js`) would otherwise be
25
+ * classified by its own (extension-less) name and directory instead of the
26
+ * real script it points to.
27
+ *
28
+ * A resolved path is a launcher only when ALL of these hold, checked against
29
+ * that realpath:
30
+ * 1. It is a SCRIPT — either a `.js`/`.mjs`/`.cjs` extension, or its first
31
+ * two bytes are `#!` (a shebang). A native binary's magic bytes (ELF
32
+ * `\x7fELF`, Mach-O `\xcf\xfa\xed\xfe` / `\xca\xfe\xba\xbe`, PE `MZ`)
33
+ * never collide with `#!`, so this never misclassifies a native binary.
34
+ * 2. It has an ENCLOSING PACKAGE ROOT — prefer the root of the nearest
35
+ * containing `node_modules/<name>` or `node_modules/@scope/<name>`
36
+ * install layout, so a closer claiming package.json cannot narrow a
37
+ * valid npm package's tree (#8097). That root must have a non-empty
38
+ * `name` AND a `bin` (string or map) or `main` claiming this entry.
39
+ * If the layout root is invalid, or outside an npm layout, keep the
40
+ * nearest claiming ancestor fallback. Its `package.json` needs a
41
+ * non-empty `name` AND its `bin`
42
+ * (string or map) or `main` field actually resolves to this entry file
43
+ * (#8093 review S3). Climbing skips a name-less marker file (e.g. a bare
44
+ * `{"type":"module"}` some build tooling drops partway up a tree), a
45
+ * malformed one, and a NAMED one that doesn't claim this entry as its
46
+ * own — none of those are a real boundary for THIS entry — and keeps
47
+ * climbing past any of them. Without the bin/main check, any stray
48
+ * named `package.json` above a shebang script (an accidental `npm init
49
+ * -y` left in `$HOME`, say) would become the root for an unrelated
50
+ * script somewhere underneath it, walking the entire home directory on
51
+ * every cold turn — it still fails CLOSED (the cap, or a permission
52
+ * error, refuses it), so this isn't a bypass, just a confusing,
53
+ * avoidable denial of service.
54
+ *
55
+ * A script with no enclosing package root (e.g. a standalone shell wrapper
56
+ * with no package.json anywhere above it, or one whose only named ancestor
57
+ * doesn't claim it via bin/main) keeps the single-file hash — there is no
58
+ * "whole package" to manifest.
59
+ *
60
+ * ## Manifest shape
61
+ *
62
+ * The package root is resolved to its REALPATH first, then walked
63
+ * recursively, INCLUDING nested `node_modules`. For each entry:
64
+ * - a regular file is hashed by CONTENT (reusing the caller's injected
65
+ * hasher — in production, `sha256FileCached`, so an unchanged file is
66
+ * never re-read, only re-`stat`'d — see #8030);
67
+ * - a symlink is recorded by its link TEXT and never followed — the walk
68
+ * never `stat`s or reads through it, so a symlink swap changes the
69
+ * digest and a symlink pointing OUTSIDE the root cannot pull in
70
+ * arbitrary bytes from elsewhere on disk;
71
+ * - a directory is walked, contributing no line of its own — only the
72
+ * files/symlinks under it do;
73
+ * - anything else (a FIFO, socket, or device file — never legitimately
74
+ * present inside an npm package tree) makes the whole manifest
75
+ * UNREADABLE, the same fail-closed-in-`block`-mode status a cap breach
76
+ * or an unreadable file gets (see below) — there is no safe way to
77
+ * characterize its "content".
78
+ *
79
+ * Every (relative path, kind, hash) triple is sorted by POSIX relative path,
80
+ * then folded into one SHA-256 digest over a versioned header plus one
81
+ * `relpath\0kind\0hash\n` line per entry — changing, adding, or removing any
82
+ * file/symlink anywhere in the tree changes the digest. The header ALSO folds
83
+ * in the entry's own package-root-relative path (#8093 review C4) — without
84
+ * this, the digest covers the tree's CONTENT but not WHICH file is the one
85
+ * actually launched, so retargeting the resolved bin symlink at a DIFFERENT
86
+ * script already inside the same tree (a nested dependency's own CLI, say)
87
+ * would leave the digest unchanged, a strict regression versus the pre-#8040
88
+ * single-file pin (which DID change when the pinned path's target changed).
89
+ *
90
+ * A symlink INSIDE the tree whose target is OUTSIDE it is still only pinned
91
+ * by its link TEXT — the target's bytes are never covered, even though Node
92
+ * (and the OS) follow it at runtime if the launcher ever loads it. This is a
93
+ * known, documented limitation (see `docs/security/spawned-binary-
94
+ * provenance.md`), not a bug: covering it would mean walking arbitrary
95
+ * locations on disk that a package's own tree doesn't own.
96
+ *
97
+ * ## Hoisted optional dependencies
98
+ *
99
+ * A non-global (local / nested `node_modules`) install can HOIST a launcher's
100
+ * platform package (codex's `@openai/codex-<platform>`) OUTSIDE the
101
+ * launcher's own package root, same as any other npm dependency hoisting.
102
+ * For each name in the launcher package's `optionalDependencies`, this
103
+ * resolves the installed root the way Node itself would FROM the launcher —
104
+ * by directory, via `require.resolve.paths(name)` (#8093 review S6 — NOT
105
+ * `require.resolve('<name>/package.json')`, which throws
106
+ * `ERR_PACKAGE_PATH_NOT_EXPORTED` for a real package whose `exports` map
107
+ * omits `./package.json`, misreading it as "not installed") — since a
108
+ * missing optional dependency is normal (npm did not install it for this
109
+ * platform/arch). When that root lies OUTSIDE the main package root, its
110
+ * tree is walked too, under a manifest prefix (`\0optdep\0<name>/…`) keyed
111
+ * off a NUL byte (#8093 review N1) — a real dirent name can never contain
112
+ * `\0`, so this can never collide with an in-root relative path, unlike the
113
+ * original `+optdep/<name>` spelling, which an in-root directory literally
114
+ * named `+optdep` could reproduce byte-for-byte.
115
+ *
116
+ * A regular (non-optional) hoisted `dependencies` package is a DOCUMENTED
117
+ * LIMITATION, not covered here — see `docs/security/spawned-binary-
118
+ * provenance.md`'s "Known limitations".
119
+ *
120
+ * ## Bounds
121
+ *
122
+ * The walk is capped on total dirents visited (`maxFiles`) and total regular-
123
+ * file bytes (`maxBytes`), generous enough to clear gemini's real ~794-file
124
+ * tree comfortably. Exceeding either cap — like any other unreadable tree —
125
+ * is reported as `unreadable` so the caller fails CLOSED in `block` mode
126
+ * rather than silently hashing a truncated, incomplete manifest.
127
+ */
128
+ import {
129
+ readFileSync,
130
+ statSync,
131
+ readdirSync,
132
+ readlinkSync,
133
+ realpathSync,
134
+ existsSync,
135
+ openSync,
136
+ readSync,
137
+ closeSync,
138
+ } from 'fs'
139
+ import { createRequire } from 'module'
140
+ import { createHash } from 'crypto'
141
+ import { dirname, join, relative, extname, isAbsolute, sep } from 'path'
142
+
143
+ /** Bumped whenever the manifest's line shape or hashing rule changes. */
144
+ export const MANIFEST_FORMAT_VERSION = 'chroxy-binary-manifest-v1'
145
+
146
+ // Generous defaults: gemini's real installed tree is ~794 files / ~98 MB;
147
+ // npm-global codex's nested platform package is 10 files / ~277 MB (the
148
+ // native binary dominates). Both clear these caps comfortably. Tests override
149
+ // both to exercise the fail-closed path without building a huge fixture.
150
+ export const DEFAULT_MANIFEST_MAX_FILES = 20000
151
+ export const DEFAULT_MANIFEST_MAX_BYTES = 2 * 1024 * 1024 * 1024 // 2 GiB
152
+
153
+ const SCRIPT_EXTENSIONS = new Set(['.js', '.mjs', '.cjs'])
154
+
155
+ /**
156
+ * Does `path` begin with a `#!` shebang? Reads only the first two bytes (an
157
+ * open + one positioned read), never the whole file — the entry files this
158
+ * runs against are small, but there is no reason to read more than needed.
159
+ *
160
+ * @param {string} path
161
+ * @param {object} [seams]
162
+ * @param {typeof openSync} [seams.openSync]
163
+ * @param {typeof readSync} [seams.readSync]
164
+ * @param {typeof closeSync} [seams.closeSync]
165
+ * @returns {boolean}
166
+ */
167
+ export function hasShebang(path, { openSync: open = openSync, readSync: read = readSync, closeSync: close = closeSync } = {}) {
168
+ let fd
169
+ try {
170
+ fd = open(path, 'r')
171
+ const buf = Buffer.alloc(2)
172
+ const n = read(fd, buf, 0, 2, 0)
173
+ return n === 2 && buf[0] === 0x23 && buf[1] === 0x21
174
+ } catch {
175
+ return false
176
+ } finally {
177
+ if (fd !== undefined) {
178
+ try {
179
+ close(fd)
180
+ } catch {
181
+ // ignore — best-effort close, nothing left to clean up on failure
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Is `path` a SCRIPT — `.js`/`.mjs`/`.cjs` extension, or a `#!` shebang?
189
+ *
190
+ * @param {string} path
191
+ * @param {object} [seams] — forwarded to {@link hasShebang}
192
+ * @returns {boolean}
193
+ */
194
+ export function isScriptFile(path, seams = {}) {
195
+ const ext = extname(path).toLowerCase()
196
+ if (SCRIPT_EXTENSIONS.has(ext)) return true
197
+ return hasShebang(path, seams)
198
+ }
199
+
200
+ /**
201
+ * Does `pkg` (a parsed `package.json` at `root`) actually claim `entryPath`
202
+ * as one of its own `bin` targets (string or map) or its `main`? (#8093
203
+ * review S3.) Without this check, ANY named `package.json` anywhere above a
204
+ * shebang script becomes a "package root" — including a stray, accidental
205
+ * one in `$HOME` (an `npm init -y` left behind is common), which would then
206
+ * make a totally unrelated shebang script somewhere underneath it (a pnpm
207
+ * shim under `~/Library/pnpm`, say) resolve to a walk of the entire home
208
+ * directory. That fails closed (the cap, or a permission error, refuses it),
209
+ * so it is not a bypass — but it is a confusing, non-obvious denial of
210
+ * service on every cold turn. Requiring the entry to be a real bin/main
211
+ * target bounds the climb to packages that actually claim to own this file.
212
+ *
213
+ * @param {string} root
214
+ * @param {object} pkg
215
+ * @param {string} entryPath — already realpath'd
216
+ * @param {(p: string) => string} realpath
217
+ * @returns {boolean}
218
+ */
219
+ function packageClaimsEntry(root, pkg, entryPath, realpath) {
220
+ const candidates = []
221
+ if (typeof pkg.bin === 'string') {
222
+ candidates.push(pkg.bin)
223
+ } else if (pkg.bin && typeof pkg.bin === 'object') {
224
+ for (const v of Object.values(pkg.bin)) {
225
+ if (typeof v === 'string') candidates.push(v)
226
+ }
227
+ }
228
+ if (typeof pkg.main === 'string') candidates.push(pkg.main)
229
+ if (candidates.length === 0) return false
230
+ for (const rel of candidates) {
231
+ const abs = join(root, rel)
232
+ let resolved = abs
233
+ try {
234
+ resolved = realpath(abs)
235
+ } catch {
236
+ // the candidate might not exist as a real path (e.g. a build step
237
+ // hasn't run yet) — fall back to comparing the raw joined path.
238
+ }
239
+ if (resolved === entryPath || abs === entryPath) return true
240
+ }
241
+ return false
242
+ }
243
+
244
+ /**
245
+ * Prefer a package root in a containing node_modules layout (innermost to
246
+ * outermost),
247
+ * provided its named package.json claims the canonical entry (#8097). Use
248
+ * that root's metadata, not a closer decoy's optionalDependencies. Aliased
249
+ * installs may have a different package name than the directory spelling.
250
+ * For an invalid layout root or a non-npm path, retain the nearest claiming
251
+ * ancestor fallback (#8093 review S3 — see {@link packageClaimsEntry}).
252
+ * Skips a name-less marker file, a malformed one, and a named-but-non-
253
+ * claiming one — none of those are a real package boundary for THIS entry —
254
+ * and keeps climbing past any of them.
255
+ *
256
+ * @param {string} entryPath — already realpath'd
257
+ * @param {object} [seams]
258
+ * @param {typeof readFileSync} [seams.readFileSync]
259
+ * @param {typeof existsSync} [seams.existsSync]
260
+ * @param {typeof realpathSync} [seams.realpathSync]
261
+ * @returns {{ root: string, packageJson: object }|null}
262
+ */
263
+ export function findEnclosingPackageRoot(
264
+ entryPath,
265
+ { readFileSync: readFile = readFileSync, existsSync: exists = existsSync, realpathSync: realpath = realpathSync } = {},
266
+ ) {
267
+ function readOwner(root) {
268
+ const pkgPath = join(root, 'package.json')
269
+ if (exists(pkgPath)) {
270
+ try {
271
+ const pkg = JSON.parse(readFile(pkgPath, 'utf8'))
272
+ if (pkg && typeof pkg.name === 'string' && pkg.name.length > 0 && packageClaimsEntry(root, pkg, entryPath, realpath)) {
273
+ return { root, packageJson: pkg }
274
+ }
275
+ } catch {
276
+ // Malformed JSON is not a package boundary.
277
+ }
278
+ }
279
+ return null
280
+ }
281
+
282
+ // Use components rather than a substring. Collect EVERY containing npm
283
+ // install root (a non-claiming inner package must not hide a valid outer
284
+ // owner), then try them innermost to outermost.
285
+ const parts = dirname(entryPath).split(sep)
286
+ const npmRoots = []
287
+ for (let index = 0; index < parts.length; index += 1) {
288
+ if (parts[index] !== 'node_modules') continue
289
+ const scope = parts[index + 1]
290
+ const rootLength = index + (scope?.startsWith('@') ? 3 : 2)
291
+ // A malformed scope or the reserved unscoped package name node_modules
292
+ // does not describe a valid npm install. Keep the old fallback there.
293
+ const valid = parts.length >= rootLength
294
+ && scope !== '@' && !scope?.includes('@', 1) && scope !== 'node_modules'
295
+ if (valid) npmRoots.push(parts.slice(0, rootLength).join(sep))
296
+ // Package-name components are not install containers themselves, even
297
+ // when a scoped package's own directory is named node_modules.
298
+ index += scope?.startsWith('@') ? 2 : 1
299
+ }
300
+ const tried = new Set()
301
+ for (let i = npmRoots.length - 1; i >= 0; i -= 1) {
302
+ tried.add(npmRoots[i])
303
+ const owner = readOwner(npmRoots[i])
304
+ if (owner) return owner
305
+ }
306
+
307
+ // Keep the existing nearest-claim fallback for non-npm and invalid roots.
308
+ // The npm candidates were already read, so do not read them a second time.
309
+ let dir = dirname(entryPath)
310
+ let prev = null
311
+ while (dir !== prev) {
312
+ if (!tried.has(dir)) {
313
+ const owner = readOwner(dir)
314
+ if (owner) return owner
315
+ }
316
+ prev = dir
317
+ dir = dirname(dir)
318
+ }
319
+ return null
320
+ }
321
+
322
+ /**
323
+ * Classify a resolved binary path as a launcher (script + enclosing package)
324
+ * or native (everything else, including a script with no enclosing package).
325
+ *
326
+ * @param {string} path
327
+ * @param {object} [seams] — forwarded to {@link isScriptFile} / {@link findEnclosingPackageRoot}
328
+ * @param {typeof realpathSync} [seams.realpathSync]
329
+ * @returns {{ kind: 'native' } | { kind: 'launcher', packageRoot: string, packageJson: object, entryPath: string }}
330
+ */
331
+ export function classifyResolvedBinary(path, { realpathSync: realpath = realpathSync, ...seams } = {}) {
332
+ if (typeof path !== 'string' || path.length === 0) return { kind: 'native' }
333
+ // Resolve the realpath FIRST, before either check — best-effort; a failure
334
+ // (dangling symlink) falls back to the raw path rather than erroring,
335
+ // matching every other realpath fallback in this module. Package-root
336
+ // detection NEEDS this: it climbs ancestor DIRECTORIES of `dirname(path)`,
337
+ // a pure string operation with no syscall of its own, so a path that is
338
+ // itself a symlink (npm's real `/opt/homebrew/bin/codex` ->
339
+ // `../lib/node_modules/@openai/codex/bin/codex.js`) would climb from the
340
+ // SYMLINK's own directory (`/opt/homebrew/bin`) and never reach the real
341
+ // package tree at all. #8093 review N3: the extension half of the script
342
+ // check must also run on the REALPATH, not the original — a bin symlink
343
+ // with no extension of its own (e.g. a bare `codex` link, as opposed to
344
+ // one npm happens to name `codex.js`) would otherwise be classified by its
345
+ // own (possibly extension-less) name instead of the real script it points
346
+ // to. The shebang half doesn't strictly need this (reading FILE CONTENT
347
+ // through a symlink already resolves transparently at the OS level), but
348
+ // running both checks on the same, already-resolved path is simpler than
349
+ // splitting them.
350
+ let realPath = path
351
+ try {
352
+ realPath = realpath(path)
353
+ } catch {
354
+ // fall back to the raw path
355
+ }
356
+ if (!isScriptFile(realPath, seams)) return { kind: 'native' }
357
+ const found = findEnclosingPackageRoot(realPath, { ...seams, realpathSync: realpath })
358
+ if (!found) return { kind: 'native' }
359
+ return { kind: 'launcher', packageRoot: found.root, packageJson: found.packageJson, entryPath: realPath }
360
+ }
361
+
362
+ function isPathInside(parent, child) {
363
+ if (parent === child) return true
364
+ const rel = relative(parent, child)
365
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)
366
+ }
367
+
368
+ /**
369
+ * For each name in the launcher package's `optionalDependencies`, resolve its
370
+ * installed package root the way Node itself would resolve it FROM the
371
+ * launcher, and return only the ones that land OUTSIDE the main package
372
+ * root — i.e. hoisted. A missing optional dependency (not installed for this
373
+ * platform/arch) is normal and silently skipped.
374
+ *
375
+ * @param {{ packageRoot: string, packageJson: object, entryPath: string }} launcher
376
+ * @param {object} [seams]
377
+ * @param {(path: string) => NodeJS.Require} [seams.createRequire]
378
+ * @param {typeof realpathSync} [seams.realpathSync]
379
+ * @param {typeof existsSync} [seams.existsSync]
380
+ * @returns {{ name: string, root: string }[]}
381
+ */
382
+ export function resolveHoistedOptionalDependencyRoots(
383
+ { packageRoot, packageJson, entryPath },
384
+ { createRequire: makeRequire = createRequire, realpathSync: realpath = realpathSync, existsSync: seamsExists = existsSync } = {},
385
+ ) {
386
+ const deps = packageJson && typeof packageJson.optionalDependencies === 'object' && packageJson.optionalDependencies !== null
387
+ ? packageJson.optionalDependencies
388
+ : null
389
+ if (!deps) return []
390
+ const names = Object.keys(deps)
391
+ if (names.length === 0) return []
392
+
393
+ let req
394
+ try {
395
+ req = makeRequire(entryPath)
396
+ } catch {
397
+ return []
398
+ }
399
+
400
+ // Node's own module resolution realpath's what it resolves (unless
401
+ // `--preserve-symlinks`), so `require.resolve()` below can return a path
402
+ // through a DIFFERENT (but equivalent) prefix than `packageRoot` — e.g. on
403
+ // macOS, `/var` is itself a symlink to `/private/var`, and `os.tmpdir()`
404
+ // returns the `/var/...` spelling while `require.resolve` returns the
405
+ // realpath'd `/private/var/...` one. Canonicalize BOTH sides before the
406
+ // inside/outside check, or a purely spelling difference gets misread as
407
+ // "hoisted outside the root". A realpath failure (a dangling symlink, a
408
+ // removed dir) falls back to the raw path rather than erroring — this is
409
+ // a best-effort canonicalization, not a correctness requirement of its own.
410
+ const canon = (p) => {
411
+ try {
412
+ return realpath(p)
413
+ } catch {
414
+ return p
415
+ }
416
+ }
417
+ const canonicalPackageRoot = canon(packageRoot)
418
+
419
+ const roots = []
420
+ for (const name of names) {
421
+ const root = resolvePackageDirectory(req, name, { existsSync: seamsExists })
422
+ if (root === null) continue // not installed for this platform/arch — normal, not an error
423
+ if (!isPathInside(canonicalPackageRoot, canon(root))) {
424
+ roots.push({ name, root })
425
+ }
426
+ }
427
+ return roots
428
+ }
429
+
430
+ /**
431
+ * Locate an installed package's ROOT DIRECTORY by name, the way Node itself
432
+ * would resolve it from `req`'s module, without going through the package's
433
+ * `exports` map (#8093 review S6). `req.resolve('<name>/package.json')`
434
+ * throws `ERR_PACKAGE_PATH_NOT_EXPORTED` for a package whose `exports` map
435
+ * omits `./package.json` — real, published packages do this — which reads
436
+ * exactly like "not installed" and silently skips a hoisted dependency that
437
+ * `require(name)` would happily find. `require.resolve.paths(name)` returns
438
+ * the ordered list of `node_modules` directories Node would search for
439
+ * `name` (the same list used internally, unaffected by `exports`), so the
440
+ * first `<dir>/<name>/package.json` that actually EXISTS on disk is the
441
+ * package root, however unusual its `exports` map is.
442
+ *
443
+ * @param {NodeJS.Require} req
444
+ * @param {string} name
445
+ * @param {object} [seams]
446
+ * @param {typeof existsSync} [seams.existsSync]
447
+ * @returns {string|null} the package's root directory, or null if not found
448
+ */
449
+ function resolvePackageDirectory(req, name, { existsSync: exists = existsSync } = {}) {
450
+ let searchPaths
451
+ try {
452
+ searchPaths = req.resolve.paths(name)
453
+ } catch {
454
+ return null
455
+ }
456
+ if (!Array.isArray(searchPaths)) return null
457
+ for (const dir of searchPaths) {
458
+ const candidateRoot = join(dir, name)
459
+ if (exists(join(candidateRoot, 'package.json'))) {
460
+ return candidateRoot
461
+ }
462
+ }
463
+ return null
464
+ }
465
+
466
+ /**
467
+ * Walk `packageRoot` (plus any hoisted `extraRoots`, each under its own
468
+ * manifest prefix) and fold every regular file / symlink into one SHA-256
469
+ * digest. See the module docblock for the exact shape and the cap/unreadable
470
+ * semantics.
471
+ *
472
+ * @param {object} opts
473
+ * @param {string} opts.packageRoot
474
+ * @param {string} [opts.entryPath] — the launcher's own entry file (#8093
475
+ * review C4). When given, its package-root-relative POSIX path is folded
476
+ * into the digest header — otherwise retargeting the resolved bin symlink
477
+ * at a DIFFERENT script already inside the same tree (a nested
478
+ * dependency's own CLI, say) would leave the digest unchanged: the
479
+ * manifest covers the tree's CONTENT, not which file is the one actually
480
+ * launched. Omitted only by tests that don't care which file is "the
481
+ * entry" — every production caller (`verify-provenance.js`) always
482
+ * supplies it, since `classifyResolvedBinary` always returns one for a
483
+ * `kind: 'launcher'` result.
484
+ * @param {{ name: string, root: string }[]} [opts.extraRoots]
485
+ * @param {(path: string, opts: { platform: string }) => string} opts.hashFile — content hasher (e.g. `sha256FileCached`)
486
+ * @param {string} [opts.platform]
487
+ * @param {number} [opts.maxFiles=DEFAULT_MANIFEST_MAX_FILES]
488
+ * @param {number} [opts.maxBytes=DEFAULT_MANIFEST_MAX_BYTES]
489
+ * @param {object} [seams]
490
+ * @param {typeof statSync} [seams.statSync]
491
+ * @param {typeof readdirSync} [seams.readdirSync]
492
+ * @param {typeof readlinkSync} [seams.readlinkSync]
493
+ * @param {typeof realpathSync} [seams.realpathSync]
494
+ * @returns {{ digest: string|null, fileCount: number, totalBytes: number, capped: boolean, unreadable: boolean, error: string|null }}
495
+ */
496
+ export function buildPackageTreeManifest(
497
+ {
498
+ packageRoot,
499
+ entryPath = null,
500
+ extraRoots = [],
501
+ hashFile,
502
+ platform = process.platform,
503
+ maxFiles = DEFAULT_MANIFEST_MAX_FILES,
504
+ maxBytes = DEFAULT_MANIFEST_MAX_BYTES,
505
+ },
506
+ {
507
+ statSync: stat = statSync,
508
+ readdirSync: readdir = readdirSync,
509
+ readlinkSync: readlink = readlinkSync,
510
+ realpathSync: realpath = realpathSync,
511
+ } = {},
512
+ ) {
513
+ const lines = []
514
+ let fileCount = 0
515
+ let totalBytes = 0
516
+ let cappedReason = null
517
+ let unreadableReason = null
518
+
519
+ function walk(dirAbs, prefix) {
520
+ if (cappedReason || unreadableReason) return
521
+ let entries
522
+ try {
523
+ entries = readdir(dirAbs, { withFileTypes: true })
524
+ } catch (err) {
525
+ unreadableReason = `could not read directory ${dirAbs} (${(err && err.code) || (err && err.message) || 'error'})`
526
+ return
527
+ }
528
+ for (const entry of entries) {
529
+ if (cappedReason || unreadableReason) return
530
+ fileCount += 1
531
+ if (fileCount > maxFiles) {
532
+ cappedReason = `exceeds the file-count cap (${maxFiles})`
533
+ return
534
+ }
535
+ const fullPath = join(dirAbs, entry.name)
536
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name
537
+
538
+ if (entry.isSymbolicLink()) {
539
+ let target
540
+ try {
541
+ target = readlink(fullPath)
542
+ } catch (err) {
543
+ unreadableReason = `could not read symlink ${fullPath} (${(err && err.code) || 'error'})`
544
+ return
545
+ }
546
+ const hash = createHash('sha256').update(target).digest('hex')
547
+ lines.push(`${relPath}\0symlink\0${hash}`)
548
+ continue
549
+ }
550
+ if (entry.isDirectory()) {
551
+ walk(fullPath, relPath)
552
+ continue
553
+ }
554
+ if (entry.isFile()) {
555
+ let st
556
+ try {
557
+ st = stat(fullPath)
558
+ } catch (err) {
559
+ unreadableReason = `could not stat ${fullPath} (${(err && err.code) || 'error'})`
560
+ return
561
+ }
562
+ totalBytes += st.size
563
+ if (totalBytes > maxBytes) {
564
+ cappedReason = `exceeds the byte-size cap (${maxBytes})`
565
+ return
566
+ }
567
+ let hash
568
+ try {
569
+ hash = hashFile(fullPath, { platform })
570
+ } catch (err) {
571
+ unreadableReason = `could not hash ${fullPath} (${(err && err.code) || 'error'})`
572
+ return
573
+ }
574
+ lines.push(`${relPath}\0file\0${hash}`)
575
+ continue
576
+ }
577
+ // A FIFO, socket, or device file — never legitimately present inside an
578
+ // npm package tree, and there is no safe way to characterize it.
579
+ unreadableReason = `unsupported file type at ${fullPath}`
580
+ }
581
+ }
582
+
583
+ let canonicalRoot
584
+ try {
585
+ canonicalRoot = realpath(packageRoot)
586
+ } catch (err) {
587
+ return {
588
+ digest: null, fileCount: 0, totalBytes: 0, capped: false, unreadable: true,
589
+ error: `could not resolve package root (${(err && err.code) || 'error'})`,
590
+ }
591
+ }
592
+ walk(canonicalRoot, '')
593
+
594
+ for (const { name, root } of extraRoots) {
595
+ if (cappedReason || unreadableReason) break
596
+ let canonicalExtra
597
+ try {
598
+ canonicalExtra = realpath(root)
599
+ } catch (err) {
600
+ unreadableReason = `could not resolve optional dependency root "${name}" (${(err && err.code) || 'error'})`
601
+ break
602
+ }
603
+ // #8093 review N1: prefix with a NUL byte, not a leading `+` — a real
604
+ // dirent name can never contain `\0` (it's a hard OS-level guarantee on
605
+ // every platform this runs on), so this prefix can never collide with an
606
+ // in-root relative path no matter what an attacker names a directory.
607
+ // The old `+optdep/<name>` prefix was merely conventionally unlikely: an
608
+ // in-root directory literally named `+optdep` produced an IDENTICAL
609
+ // digest to an extra root of the same name/content.
610
+ walk(canonicalExtra, `\0optdep\0${name}`)
611
+ }
612
+
613
+ if (cappedReason) {
614
+ return { digest: null, fileCount, totalBytes, capped: true, unreadable: false, error: cappedReason }
615
+ }
616
+ if (unreadableReason) {
617
+ return { digest: null, fileCount, totalBytes, capped: false, unreadable: true, error: unreadableReason }
618
+ }
619
+
620
+ lines.sort()
621
+ // #8093 review C4: bind WHICH file is the entry into the digest, not just
622
+ // the tree's content — see the `entryPath` param doc above. `entryRelPath`
623
+ // is empty when no `entryPath` was given (test-only), which still folds a
624
+ // well-formed, deterministic (if unbound) header line.
625
+ let entryRelPath = ''
626
+ if (entryPath) {
627
+ let canonicalEntry = entryPath
628
+ try {
629
+ canonicalEntry = realpath(entryPath)
630
+ } catch {
631
+ // fall back to the raw path — still folded into the header either way
632
+ }
633
+ entryRelPath = relative(canonicalRoot, canonicalEntry).split(sep).join('/')
634
+ }
635
+ const hash = createHash('sha256')
636
+ hash.update(`${MANIFEST_FORMAT_VERSION}\0entry\0${entryRelPath}\n`)
637
+ for (const line of lines) hash.update(`${line}\n`)
638
+ return { digest: hash.digest('hex'), fileCount, totalBytes, capped: false, unreadable: false, error: null }
639
+ }