@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,245 @@
1
+ /**
2
+ * claudeConfigDir: the ONE place chroxy decides where claude keeps its data
3
+ * (#8270): `projects/<slug>/<id>.jsonl` transcripts, `sessions/<pid>.json`,
4
+ * `commands/`, `agents/`, `CLAUDE.md`, per-project memory.
5
+ *
6
+ * claude honours `CLAUDE_CONFIG_DIR` from ITS environment and writes under it
7
+ * instead of `~/.claude`, so a chroxy that joins `homedir()` + `.claude`
8
+ * looks for files that were never written there.
9
+ *
10
+ * Whose env: the DAEMON's (`process.env`) by default. A caller that holds the
11
+ * exact env a child is spawned with passes it.
12
+ *
13
+ * One policy for readers and the claude child: the child env is passed through
14
+ * {@link sanitizeClaudeConfigDirEnv}, which drops a value this module would not
15
+ * accept. Both sides then use `~/.claude` for it, so chroxy never reads a tree
16
+ * claude is not writing.
17
+ *
18
+ * Accepted spelling (exactly as written, no trimming):
19
+ * - a string, no NUL byte, an absolute path
20
+ * - not the filesystem root, and not a path that RESOLVES to the filesystem
21
+ * root once symlinks are followed (the canonical value is what counts)
22
+ * Anything else (unset, empty, padded with whitespace, relative, `~/x`, root,
23
+ * a symlink alias of the root) falls back to `~/.claude`.
24
+ *
25
+ * The result is the CANONICAL path (symlinks resolved through the deepest
26
+ * existing ancestor), so it is safe to use directly as a containment root. If
27
+ * the path cannot be resolved it is treated as unusable and the default is used.
28
+ *
29
+ * This is claude's data dir only. chroxy's own `~/.chroxy` / `CHROXY_CONFIG_DIR`
30
+ * are unrelated and untouched.
31
+ */
32
+ import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs'
33
+ import { homedir, userInfo } from 'node:os'
34
+ import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
35
+ import { createLogger } from '../logger.js'
36
+
37
+ const log = createLogger('claude-config-dir')
38
+
39
+ /** The env key `os.homedir()` reads: `USERPROFILE` on Windows, `HOME` elsewhere. */
40
+ function homeEnvKey(platform) {
41
+ return platform === 'win32' ? 'USERPROFILE' : 'HOME'
42
+ }
43
+
44
+ /**
45
+ * The acceptance policy for a home value taken from an env, mirroring what Node's
46
+ * `os.homedir()` accepts: a string that is non-empty, has no NUL and is absolute.
47
+ * `/` is allowed (containers and service users run with `HOME=/`, and claude
48
+ * itself would use it); the root/canonical checks apply only to the
49
+ * `CLAUDE_CONFIG_DIR` override, where containment matters. Returns the value as
50
+ * written, or null.
51
+ * @param {unknown} raw
52
+ * @returns {string|null}
53
+ */
54
+ export function acceptClaudeHome(raw) {
55
+ return typeof raw === 'string' && raw !== '' && !raw.includes('\0') && isAbsolute(raw) ? raw : null
56
+ }
57
+
58
+ // The home a child resolves when its env carries no accepted home value: the
59
+ // account's passwd entry (win32: os.homedir(), which reads the profile API).
60
+ function accountHomeDir(platform) {
61
+ if (platform !== 'win32') {
62
+ try {
63
+ const h = userInfo().homedir
64
+ if (acceptClaudeHome(h) !== null) return h
65
+ } catch {
66
+ // no passwd entry: os.homedir() below
67
+ }
68
+ }
69
+ return homedir()
70
+ }
71
+
72
+ /**
73
+ * The home directory claude resolves for the process that runs with `env`: the
74
+ * env's `HOME` (`USERPROFILE` on Windows, never `HOME` there), the same value
75
+ * `os.homedir()` returns inside that child. When the env carries no accepted
76
+ * home, the account's passwd home (`os.userInfo().homedir`; on win32
77
+ * `os.homedir()`) is used. The child-env sanitiser removes the same unusable
78
+ * value, and a child with no HOME resolves that same passwd home (#8974).
79
+ * @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env]
80
+ * @param {NodeJS.Platform} [platform]
81
+ * @returns {string}
82
+ */
83
+ export function claudeHomeDir(env = process.env, platform = process.platform) {
84
+ return acceptClaudeHome(env?.[homeEnvKey(platform)]) ?? accountHomeDir(platform)
85
+ }
86
+
87
+ /** claude's default data dir, `<home>/.claude`. */
88
+ export function defaultClaudeConfigDir(env = process.env) {
89
+ return join(claudeHomeDir(env), '.claude')
90
+ }
91
+
92
+ function isSymlink(p) {
93
+ try {
94
+ return lstatSync(p).isSymbolicLink()
95
+ } catch {
96
+ return false
97
+ }
98
+ }
99
+
100
+ // realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a
101
+ // config dir claude has not created yet is still canonicalised.
102
+ function canonicalize(absPath) {
103
+ let current = absPath
104
+ const tail = []
105
+ for (;;) {
106
+ try {
107
+ const real = realpathSync.native(current)
108
+ return tail.length ? join(real, ...tail.reverse()) : real
109
+ } catch (err) {
110
+ if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err
111
+ // A component that IS a symlink whose target is missing (dangling) is not
112
+ // "a directory that does not exist yet": following its text could land
113
+ // anywhere. Treat the whole value as unusable instead of walking past it.
114
+ if (isSymlink(current)) throw err
115
+ const parent = dirname(current)
116
+ if (parent === current) throw err
117
+ tail.push(basename(current))
118
+ current = parent
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * The canonical config dir for an override spelling, or null when the spelling
125
+ * is not accepted (see the module comment).
126
+ * @param {unknown} raw
127
+ * @returns {string|null}
128
+ */
129
+ export function resolveClaudeConfigDirOverride(raw) {
130
+ if (typeof raw !== 'string' || raw === '' || raw.includes('\0') || !isAbsolute(raw)) return null
131
+ const normalised = resolve(raw)
132
+ if (normalised === parse(normalised).root) return null
133
+ let canonical
134
+ try {
135
+ canonical = canonicalize(normalised)
136
+ } catch {
137
+ return null
138
+ }
139
+ if (canonical === parse(canonical).root) return null
140
+ return canonical
141
+ }
142
+
143
+ /**
144
+ * @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env] - env claude runs with
145
+ * @returns {string} absolute, canonical path to claude's config dir
146
+ */
147
+ export function claudeConfigDir(env = process.env) {
148
+ return resolveClaudeConfigDirOverride(env?.CLAUDE_CONFIG_DIR) ?? defaultClaudeConfigDir(env)
149
+ }
150
+
151
+ /** `<claude config dir>/projects`. */
152
+ export function claudeProjectsDir(env = process.env) {
153
+ return join(claudeConfigDir(env), 'projects')
154
+ }
155
+
156
+ /**
157
+ * claude's global config file (OAuth account metadata, user and per-project MCP
158
+ * servers, workspace trust). claude picks ONE active file:
159
+ * 1. `<config dir>/.config.json` when it is a regular file that is non-empty,
160
+ * or empty and writable while the modern file does not exist (legacy name);
161
+ * 2. otherwise `join(CLAUDE_CONFIG_DIR || home, '.claude.json')` — directly in
162
+ * the override dir, but in the HOME directory (not `~/.claude/`) by default.
163
+ * This returns that same file, so a reader and a writer never use a different one
164
+ * than claude does (#8974). The override goes through the same acceptance policy
165
+ * as {@link claudeConfigDir}; home comes from the env (see {@link claudeHomeDir}).
166
+ * @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env] - env claude runs with
167
+ * @returns {string} absolute path
168
+ */
169
+ export function claudeGlobalConfigPath(env = process.env) {
170
+ const override = resolveClaudeConfigDirOverride(env?.CLAUDE_CONFIG_DIR)
171
+ const modern = join(override ?? claudeHomeDir(env), '.claude.json')
172
+ const legacy = join(claudeConfigDir(env), '.config.json')
173
+ try {
174
+ // Exactly claude's rule: a regular legacy file that is non-empty, or that is
175
+ // empty but writable while no modern file exists. A directory never qualifies.
176
+ const st = statSync(legacy)
177
+ if (st.isFile() && (st.size > 0 || ((st.mode & 0o222) !== 0 && !existsSync(modern)))) return legacy
178
+ } catch {
179
+ // absent / unreadable: not the active file
180
+ }
181
+ return modern
182
+ }
183
+
184
+ /**
185
+ * Parse the text of claude's global config. Empty or whitespace-only content
186
+ * (a freshly created file) is `{}`; anything else is parsed strictly and a
187
+ * malformed non-empty file still throws, so a corrupt file is never clobbered.
188
+ * @param {string} text
189
+ * @returns {any}
190
+ */
191
+ export function parseClaudeConfigText(text) {
192
+ return text.trim() === '' ? {} : JSON.parse(text)
193
+ }
194
+
195
+ const warned = new Set()
196
+
197
+ /** Is `p` a filesystem root (`/`, `C:\`)? For use sites that install a resolved dir as a containment root. */
198
+ export function isFilesystemRoot(p) {
199
+ return typeof p === 'string' && p !== '' && parse(p).root === p
200
+ }
201
+
202
+ /**
203
+ * Startup check: warn once (constant text, no path) when `CLAUDE_CONFIG_DIR` is
204
+ * set but not usable. Does not modify `env`.
205
+ * @param {Record<string, unknown>} [env]
206
+ * @returns {boolean} true when a warning was due
207
+ */
208
+ export function warnIfClaudeConfigDirUnusable(env = process.env) {
209
+ if (env?.CLAUDE_CONFIG_DIR === undefined) return false
210
+ const before = Object.hasOwn(env, 'CLAUDE_CONFIG_DIR')
211
+ const copy = sanitizeClaudeConfigDirEnv({ CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR })
212
+ return before && !Object.hasOwn(copy, 'CLAUDE_CONFIG_DIR')
213
+ }
214
+
215
+ /**
216
+ * Make a claude child env agree with {@link claudeConfigDir}: when the env
217
+ * carries a `CLAUDE_CONFIG_DIR` the resolver would reject, remove it (one
218
+ * warning per distinct value) so claude falls back to `~/.claude` as chroxy does.
219
+ * An unusable home value (HOME, or USERPROFILE on Windows) is removed the same way.
220
+ * Mutates and returns `env`.
221
+ * @param {Record<string, unknown>} env
222
+ */
223
+ export function sanitizeClaudeConfigDirEnv(env, platform = process.platform) {
224
+ if (!env) return env
225
+ // The home value the child's os.homedir() reads: an unusable one is removed so
226
+ // the child falls back to the account's passwd home, the same account the
227
+ // daemon's claudeHomeDir() fallback names (#8974).
228
+ const homeKey = homeEnvKey(platform)
229
+ if (Object.hasOwn(env, homeKey) && env[homeKey] !== undefined && acceptClaudeHome(env[homeKey]) === null) {
230
+ if (!warned.has(`home:${String(env[homeKey])}`)) {
231
+ warned.add(`home:${String(env[homeKey])}`)
232
+ log.warn('Ignoring an unusable home directory in the claude child env; the account home is used')
233
+ }
234
+ delete env[homeKey]
235
+ }
236
+ if (!Object.hasOwn(env, 'CLAUDE_CONFIG_DIR') || env.CLAUDE_CONFIG_DIR === undefined) return env
237
+ if (resolveClaudeConfigDirOverride(env.CLAUDE_CONFIG_DIR) !== null) return env
238
+ const key = String(env.CLAUDE_CONFIG_DIR)
239
+ if (!warned.has(key)) {
240
+ warned.add(key)
241
+ log.warn('Ignoring CLAUDE_CONFIG_DIR: it must be an absolute path that is not the filesystem root; using ~/.claude')
242
+ }
243
+ delete env.CLAUDE_CONFIG_DIR
244
+ return env
245
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * #8223 — the ONE spelling of the command that signs the `claude` CLI in on a
3
+ * host. The AUTH_REQUIRED messages (claude-tui's in claude-tui/pty-driver.js,
4
+ * claude-sdk's in sdk-session.js), the provider credential hints and the doctor
5
+ * row all tell an operator to run it, and four hand-typed copies were already one
6
+ * edit from disagreeing. claude 2.1.x spells it `auth login`; plain `claude login`
7
+ * is stale.
8
+ *
9
+ * A module of its own, not an export of pty-driver.js, because sdk-session.js needs
10
+ * it and pty-driver.js resolves the claude binary at import time, which the SDK
11
+ * provider must not do. The dashboard and the app read the same string from
12
+ * `@chroxy/store-core` (`CLAUDE_LOGIN_COMMAND`, next to the AUTH_REQUIRED
13
+ * presentation entry); the two packages cannot share a module, so each side keeps
14
+ * exactly one definition.
15
+ */
16
+ export const CLAUDE_LOGIN_COMMAND = 'claude auth login'
@@ -0,0 +1,81 @@
1
+ export const CLAUDE_NATIVE_FIRST_PARTY_BASE_URL = 'https://api.anthropic.com'
2
+
3
+ // Every non-OAuth selector that can move Claude Code away from the direct
4
+ // Claude.ai subscription route. CLAUDE_CODE_OAUTH_TOKEN is deliberately absent:
5
+ // it is a vendor-supported way to supply the same subscription credential that
6
+ // `claude auth status` classifies separately.
7
+ export const CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV = Object.freeze([
8
+ 'ANTHROPIC_API_HOST',
9
+ 'ANTHROPIC_API_KEY',
10
+ 'ANTHROPIC_AUTH_TOKEN',
11
+ 'ANTHROPIC_AWS_API_KEY',
12
+ 'ANTHROPIC_AWS_BASE_URL',
13
+ 'ANTHROPIC_AWS_WORKSPACE_ID',
14
+ 'ANTHROPIC_BEDROCK_BASE_URL',
15
+ 'ANTHROPIC_BEDROCK_MANTLE_BASE_URL',
16
+ 'ANTHROPIC_CUSTOM_HEADERS',
17
+ 'ANTHROPIC_FOUNDRY_API_KEY',
18
+ 'ANTHROPIC_FOUNDRY_AUTH_TOKEN',
19
+ 'ANTHROPIC_FOUNDRY_BASE_URL',
20
+ 'ANTHROPIC_FOUNDRY_RESOURCE',
21
+ 'ANTHROPIC_GOOGLE_CLOUD_BASE_URL',
22
+ 'ANTHROPIC_GOOGLE_CLOUD_LOCATION',
23
+ 'ANTHROPIC_GOOGLE_CLOUD_PROJECT',
24
+ 'ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID',
25
+ 'ANTHROPIC_PROFILE',
26
+ 'ANTHROPIC_UNIX_SOCKET',
27
+ 'ANTHROPIC_VERTEX_BASE_URL',
28
+ 'ANTHROPIC_VERTEX_PROJECT_ID',
29
+ 'CLAUDE_CODE_API_BASE_URL',
30
+ 'CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR',
31
+ 'CLAUDE_CODE_CUSTOM_OAUTH_URL',
32
+ 'CLAUDE_CODE_HOST_AUTH_ENV_VAR',
33
+ 'CLAUDE_CODE_HOST_CREDS_FILE',
34
+ 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
35
+ 'CLAUDE_CODE_SIMPLE',
36
+ 'CLAUDE_CODE_USE_ANTHROPIC_AWS',
37
+ 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
38
+ 'CLAUDE_CODE_USE_BEDROCK',
39
+ 'CLAUDE_CODE_USE_FOUNDRY',
40
+ 'CLAUDE_CODE_USE_GATEWAY',
41
+ 'CLAUDE_CODE_USE_MANTLE',
42
+ 'CLAUDE_CODE_USE_VERTEX',
43
+ '_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL',
44
+ ])
45
+
46
+ function hasValue(value) {
47
+ return typeof value === 'string' && value.trim().length > 0
48
+ }
49
+
50
+ export function buildClaudeNativeRouteEnv(baseEnv = {}) {
51
+ const env = { ...baseEnv }
52
+ for (const key of CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV) delete env[key]
53
+ env.ANTHROPIC_BASE_URL = CLAUDE_NATIVE_FIRST_PARTY_BASE_URL
54
+ return env
55
+ }
56
+
57
+ export function claudeNativeRouteSettingsEnv() {
58
+ return {
59
+ ...Object.fromEntries(CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV.map((key) => [key, ''])),
60
+ ANTHROPIC_BASE_URL: CLAUDE_NATIVE_FIRST_PARTY_BASE_URL,
61
+ }
62
+ }
63
+
64
+ export function observeClaudeNativeRoute(env = {}) {
65
+ let firstPartyEndpoint = false
66
+ try {
67
+ const url = new URL(env.ANTHROPIC_BASE_URL)
68
+ firstPartyEndpoint = url.protocol === 'https:'
69
+ && url.hostname === 'api.anthropic.com'
70
+ && (url.port === '' || url.port === '443')
71
+ && (url.pathname === '' || url.pathname === '/')
72
+ && url.search === ''
73
+ && url.hash === ''
74
+ } catch {}
75
+ const blockedKeys = CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV.filter((key) => hasValue(env[key]))
76
+ return {
77
+ firstPartyEndpoint,
78
+ blockedKeys,
79
+ safe: firstPartyEndpoint && blockedKeys.length === 0,
80
+ }
81
+ }
@@ -1,6 +1,6 @@
1
1
  import { lstatSync, readlinkSync } from 'node:fs'
2
2
  import { lstat, readlink } from 'node:fs/promises'
3
- import { dirname, isAbsolute, join, parse } from 'node:path'
3
+ import path, { dirname, join } from 'node:path'
4
4
 
5
5
  /**
6
6
  * open(2)-faithful, component-by-component path resolver — the SINGLE SOURCE for
@@ -39,22 +39,73 @@ import { dirname, isAbsolute, join, parse } from 'node:path'
39
39
  // `catch` treats as protected / rejected (fail closed).
40
40
  export const COMPONENTWISE_MAX_SYMLINKS = 40
41
41
 
42
+ // The most work one walk does: COMPONENTWISE_MAX_COMPONENTS components walked,
43
+ // those a symlink adds included, and a resolved path no longer than
44
+ // COMPONENTWISE_MAX_PATH_LENGTH characters. Past either, the walk THROWS
45
+ // `ENAMETOOLONG`, which every caller treats as a failure (fail closed). Each step
46
+ // builds and stats the full path so far, so these bound the walk's total cost.
47
+ // A real path is far below both: Linux's PATH_MAX is 4096 bytes, and even 40
48
+ // symlinks of a few dozen components each stay under the component bound.
49
+ export const COMPONENTWISE_MAX_COMPONENTS = 1024
50
+ export const COMPONENTWISE_MAX_PATH_LENGTH = 16384
51
+
42
52
  /**
43
- * #6928 — split a raw path into the components BELOW its parsed root, separating on
44
- * BOTH `/` and `\` regardless of platform. Node accepts forward slashes on Windows,
45
- * so a platform-`sep`-only split (`\` on Windows) would leave a forward-slash path
46
- * as ONE component — the walk would then break and fall back to a lexical `join()`,
47
- * reopening the exact `..`-after-symlink escape this resolver exists to close.
48
- * `root` (already parsed by the caller, which starts `resolved` there) is sliced off
49
- * first so a drive/UNC/`/` root is never walked as an ordinary component (a Windows
50
- * `C:\` would otherwise appear as a `C:` component and `join` straight back onto the
51
- * drive root).
53
+ * #6928 — split a raw path into the components BELOW its parsed root. The
54
+ * separators are the platform's own: `/` and `\` on Windows (Node accepts forward
55
+ * slashes there, so a `sep`-only split would leave a forward-slash path as ONE
56
+ * component and the walk would fall back to a lexical `join()`), but `/` ALONE on
57
+ * POSIX, where `\` is an ordinary filename character — splitting on it would walk
58
+ * a different pathname than the one a consumer opens. `root` (already parsed by the
59
+ * caller, which starts `resolved` there) is sliced off first so a drive/UNC/`/`
60
+ * root is never walked as an ordinary component (a Windows `C:\` would otherwise
61
+ * appear as a `C:` component and `join` straight back onto the drive root).
52
62
  * @param {string} p
53
63
  * @param {string} root the already-`parse`d root of `p` (`''` for a relative path)
64
+ * @param {typeof import('node:path')} [pathImpl] `path.win32` / `path.posix` to
65
+ * drive the other platform's rules (tests); defaults to the host's `path`
54
66
  * @returns {string[]}
55
67
  */
56
- export function splitPathBelowRoot(p, root) {
57
- return (root ? p.slice(root.length) : p).split(/[/\\]+/)
68
+ export function splitPathBelowRoot(p, root, pathImpl = path) {
69
+ const separators = pathImpl.sep === '\\' ? /[/\\]+/ : /\/+/
70
+ return (root ? p.slice(root.length) : p).split(separators)
71
+ }
72
+
73
+ /**
74
+ * Where a walk over the raw path `p` starts, and the components below that start.
75
+ * `current` is the real path resolved so far (the session cwd for a target, the
76
+ * link's parent for a link target).
77
+ * - a relative path starts where `current` is (`start` is `''`);
78
+ * - an absolute path starts at its own parsed root;
79
+ * - on Windows, a root-relative path (`\foo` or `/foo`, no drive) starts at the
80
+ * root of `current`'s drive (or share), exactly as `path.win32.resolve(current, p)`
81
+ * places it;
82
+ * - on Windows, a drive-relative path (`C:foo`) depends on that drive's current
83
+ * directory, which cannot be known here, so it throws EINVAL (callers fail
84
+ * closed). So does a root-relative path when `current` has no drive.
85
+ * @param {string} p
86
+ * @param {string} current the real path resolved so far
87
+ * @param {typeof import('node:path')} [pathImpl] `path.win32` / `path.posix` to
88
+ * drive the other platform's rules (tests); defaults to the host's `path`
89
+ * @returns {{ start: string, below: string[] }}
90
+ */
91
+ export function walkStart(p, current, pathImpl = path) {
92
+ const { root } = pathImpl.parse(p)
93
+ if (pathImpl.sep === '\\') {
94
+ if (/^[A-Za-z]:$/.test(root)) {
95
+ throw Object.assign(new Error('componentwise resolver: a drive-relative path depends on the drive\'s current directory'), { code: 'EINVAL' })
96
+ }
97
+ if (root === '\\' || root === '/') {
98
+ const driveRoot = pathImpl.parse(current).root
99
+ // Only a real drive or a real share (server and share, the server neither `?` nor
100
+ // `.`): the `\\?\` and `\\.\` device namespaces have no drive to anchor to.
101
+ if (!/^[A-Za-z]:[\\/]$/.test(driveRoot) && !/^[\\/]{2}[^\\/?.][^\\/]*[\\/]+[^\\/]+[\\/]?$/.test(driveRoot)) {
102
+ throw Object.assign(new Error('componentwise resolver: a root-relative path has no drive to anchor to'), { code: 'EINVAL' })
103
+ }
104
+ return { start: driveRoot, below: splitPathBelowRoot(p, root, pathImpl) }
105
+ }
106
+ }
107
+ const start = pathImpl.isAbsolute(p) ? root : ''
108
+ return { start, below: splitPathBelowRoot(p, start, pathImpl) }
58
109
  }
59
110
 
60
111
  /**
@@ -67,9 +118,9 @@ export function splitPathBelowRoot(p, root) {
67
118
  * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
68
119
  * @returns {{ resolved: string, pending: string[] }}
69
120
  */
70
- function beginWalk(realBase, target) {
71
- const targetRoot = isAbsolute(target) ? parse(target).root : ''
72
- return { resolved: targetRoot || realBase, pending: splitPathBelowRoot(target, targetRoot) }
121
+ export function beginWalk(realBase, target, pathImpl = path) {
122
+ const { start, below } = walkStart(target, realBase, pathImpl)
123
+ return { resolved: start || realBase, pending: below }
73
124
  }
74
125
 
75
126
  /**
@@ -79,24 +130,28 @@ function beginWalk(realBase, target) {
79
130
  * - `''` / `.` → skip (resolved unchanged, no stat).
80
131
  * - `..` → pop to the PARENT of the resolved-so-far real path (`dirname`),
81
132
  * i.e. apply `..` AFTER following symlinks so far — NOT lexically
82
- * on the pre-resolution path. No stat.
83
- * - tail-only → once a component was ENOENT, everything after it is a
133
+ * on the pre-resolution path. No stat. When it pops a to-be-created
134
+ * component, the tail shrinks by one; once the tail is empty the
135
+ * resolved path is a directory that exists, and the driver goes
136
+ * back to inspecting each component.
137
+ * - in a tail → once a component was ENOENT, the components after it are a
84
138
  * to-be-created tail: append by `join` with no stat.
85
139
  * - otherwise → return the `candidate` to lstat; `resolved` is left UNCHANGED
86
140
  * (it is committed only after the driver confirms `candidate` is
87
141
  * not a symlink).
88
142
  * @param {string} resolved resolved-so-far real path
89
143
  * @param {string} comp the raw component
90
- * @param {boolean} tailOnly true once a prior component was ENOENT
91
- * @returns {{ resolved: string, stat: string|null }} `stat` is the path to lstat,
92
- * or `null` when the component was fully consumed lexically (skip / `..` / tail).
144
+ * @param {number} tail how many to-be-created components follow the last
145
+ * existing directory (0 when every component so far was inspected)
146
+ * @returns {{ resolved: string, stat: string|null, tail: number }} `stat` is the
147
+ * path to lstat, or `null` when the component was fully consumed lexically.
93
148
  */
94
- function resolveComponentLexically(resolved, comp, tailOnly) {
95
- if (comp === '' || comp === '.') return { resolved, stat: null }
96
- if (comp === '..') return { resolved: dirname(resolved), stat: null }
149
+ function resolveComponentLexically(resolved, comp, tail) {
150
+ if (comp === '' || comp === '.') return { resolved, stat: null, tail }
151
+ if (comp === '..') return { resolved: dirname(resolved), stat: null, tail: tail > 0 ? tail - 1 : 0 }
97
152
  const candidate = join(resolved, comp)
98
- if (tailOnly) return { resolved: candidate, stat: null }
99
- return { resolved, stat: candidate }
153
+ if (tail > 0) return { resolved: candidate, stat: null, tail: tail + 1 }
154
+ return { resolved, stat: candidate, tail }
100
155
  }
101
156
 
102
157
  /**
@@ -112,10 +167,41 @@ function resolveComponentLexically(resolved, comp, tailOnly) {
112
167
  * @param {string} link the raw `readlink` target
113
168
  * @returns {string}
114
169
  */
115
- function spliceSymlink(pending, i, resolved, link) {
116
- const linkRoot = isAbsolute(link) ? parse(link).root : ''
117
- pending.splice(i, 0, ...splitPathBelowRoot(link, linkRoot))
118
- return linkRoot || resolved
170
+ export function spliceSymlink(pending, i, resolved, link, pathImpl = path) {
171
+ // On POSIX `\` is a name character, which the split below would read as a
172
+ // separator; a link whose target holds one is not walked (callers fail closed).
173
+ if (pathImpl.sep === '/' && link.includes('\\')) {
174
+ throw Object.assign(new Error('componentwise resolver: link target holds a backslash'), { code: 'EINVAL' })
175
+ }
176
+ const { start, below } = walkStart(link, resolved, pathImpl)
177
+ pending.splice(i, 0, ...below)
178
+ return start || resolved
179
+ }
180
+
181
+ /**
182
+ * Throw ENAMETOOLONG once a walk has consumed more than
183
+ * COMPONENTWISE_MAX_COMPONENTS components or its resolved path is longer than
184
+ * COMPONENTWISE_MAX_PATH_LENGTH characters. Called before each component and
185
+ * after the last.
186
+ * @param {number} walked components consumed so far, the current one included
187
+ * @param {string} resolved the path resolved so far
188
+ * @param {string} fnName the driver, for the message
189
+ */
190
+ function checkWalkBounds(walked, resolved, fnName) {
191
+ if (walked > COMPONENTWISE_MAX_COMPONENTS || resolved.length > COMPONENTWISE_MAX_PATH_LENGTH) {
192
+ throw Object.assign(
193
+ new Error(`${fnName}: walk exceeds ${COMPONENTWISE_MAX_COMPONENTS} components or ${COMPONENTWISE_MAX_PATH_LENGTH} characters`),
194
+ { code: 'ENAMETOOLONG' },
195
+ )
196
+ }
197
+ }
198
+
199
+ // A caller may share one walk budget across several walks (`{ left: n }`); each
200
+ // component walked spends one, and an exhausted budget fails like a long walk.
201
+ function spendWalkBudget(budget, fnName) {
202
+ if (budget !== undefined && --budget.left < 0) {
203
+ throw Object.assign(new Error(`${fnName}: the shared walk budget is spent`), { code: 'ENAMETOOLONG' })
204
+ }
119
205
  }
120
206
 
121
207
  function symlinkBudgetError(fnName) {
@@ -134,25 +220,29 @@ function symlinkBudgetError(fnName) {
134
220
  * REAL path by the same pop/append rules.
135
221
  * @param {string} realBase the session cwd, already resolved to its real path
136
222
  * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
223
+ * @param {{ left: number }} [budget] a walk budget shared with other walks
137
224
  * @returns {string} the open(2)-faithful resolved absolute real path
138
225
  */
139
- export function resolveTargetComponentwiseSync(realBase, target) {
226
+ export function resolveTargetComponentwiseSync(realBase, target, budget) {
140
227
  const { resolved: base, pending } = beginWalk(realBase, target)
141
228
  let resolved = base
142
229
  let symlinks = 0
143
- let tailOnly = false
230
+ let tail = 0
144
231
  let i = 0
145
232
  while (i < pending.length) {
146
233
  const comp = pending[i]
147
234
  i++
148
- const step = resolveComponentLexically(resolved, comp, tailOnly)
235
+ checkWalkBounds(i, resolved, 'resolveTargetComponentwiseSync')
236
+ spendWalkBudget(budget, 'resolveTargetComponentwiseSync')
237
+ const step = resolveComponentLexically(resolved, comp, tail)
149
238
  resolved = step.resolved
239
+ tail = step.tail
150
240
  if (step.stat === null) continue
151
241
  let st
152
242
  try {
153
243
  st = lstatSync(step.stat)
154
244
  } catch (err) {
155
- if (err.code === 'ENOENT') { tailOnly = true; resolved = step.stat; continue }
245
+ if (err.code === 'ENOENT') { tail = 1; resolved = step.stat; continue }
156
246
  throw err // EACCES etc. — fail closed via the caller's catch
157
247
  }
158
248
  if (st.isSymbolicLink()) {
@@ -162,6 +252,7 @@ export function resolveTargetComponentwiseSync(realBase, target) {
162
252
  resolved = step.stat
163
253
  }
164
254
  }
255
+ checkWalkBounds(i, resolved, 'resolveTargetComponentwiseSync')
165
256
  return resolved
166
257
  }
167
258
 
@@ -173,25 +264,29 @@ export function resolveTargetComponentwiseSync(realBase, target) {
173
264
  * (including `..`) by pop/append.
174
265
  * @param {string} realBase the session cwd, already resolved to its real path
175
266
  * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
267
+ * @param {{ left: number }} [budget] a walk budget shared with other walks
176
268
  * @returns {Promise<string>} the open(2)-faithful resolved absolute real path
177
269
  */
178
- export async function resolveTargetComponentwiseAsync(realBase, target) {
270
+ export async function resolveTargetComponentwiseAsync(realBase, target, budget) {
179
271
  const { resolved: base, pending } = beginWalk(realBase, target)
180
272
  let resolved = base
181
273
  let symlinks = 0
182
- let tailOnly = false
274
+ let tail = 0
183
275
  let i = 0
184
276
  while (i < pending.length) {
185
277
  const comp = pending[i]
186
278
  i++
187
- const step = resolveComponentLexically(resolved, comp, tailOnly)
279
+ checkWalkBounds(i, resolved, 'resolveTargetComponentwiseAsync')
280
+ spendWalkBudget(budget, 'resolveTargetComponentwiseAsync')
281
+ const step = resolveComponentLexically(resolved, comp, tail)
188
282
  resolved = step.resolved
283
+ tail = step.tail
189
284
  if (step.stat === null) continue
190
285
  let st
191
286
  try {
192
287
  st = await lstat(step.stat)
193
288
  } catch (err) {
194
- if (err.code === 'ENOENT') { tailOnly = true; resolved = step.stat; continue }
289
+ if (err.code === 'ENOENT') { tail = 1; resolved = step.stat; continue }
195
290
  throw err // EACCES etc. — fail closed via the caller
196
291
  }
197
292
  if (st.isSymbolicLink()) {
@@ -201,5 +296,6 @@ export async function resolveTargetComponentwiseAsync(realBase, target) {
201
296
  resolved = step.stat
202
297
  }
203
298
  }
299
+ checkWalkBounds(i, resolved, 'resolveTargetComponentwiseAsync')
204
300
  return resolved
205
301
  }