@chroxy/server 0.11.0 → 0.11.10

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