@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,104 @@
1
+ // #8860: the shared, bounded page reader for a PRESERVED history array. Two
2
+ // callers read a saved history without a live session behind it — a parked
3
+ // failed restore (`SessionManager.getFailedRestoreHistory`) and the provider-
4
+ // neutral session archive (`SessionArchive.getHistoryPage`) — and both must
5
+ // serve exactly the same bounded, replay-safe shape. One implementation, so a
6
+ // bound tightened for one cannot stay loose on the other.
7
+
8
+ // Page bounds. Mirrors the protocol's `get_failed_restore_history` /
9
+ // `get_archived_session_history` limit (1..100); the clamp is repeated here
10
+ // because this is the enforcement point for any caller, not just the handler.
11
+ export const HISTORY_PAGE_DEFAULT_LIMIT = 50
12
+ export const HISTORY_PAGE_MAX_LIMIT = 100
13
+ // A page is also bounded by its serialized size. It goes out as ONE WebSocket
14
+ // frame, and ws-client-sender evicts a client whose post-send bufferedAmount
15
+ // passes 1 MiB; with permessage-deflate the buffered size has been measured at
16
+ // ~1.34x the JSON. 256 KiB of JSON keeps a page well under that. An entry that
17
+ // is alone bigger than the per-entry cap has its large fields shortened for
18
+ // display, so a single entry can never blow the page either.
19
+ export const HISTORY_PAGE_BYTES = 256 * 1024
20
+ export const HISTORY_ENTRY_BYTES = 64 * 1024
21
+ export const HISTORY_FIELD_CHARS = 16 * 1024
22
+
23
+ /**
24
+ * #8860: one preserved-history entry as the history-page replies send it.
25
+ *
26
+ * - The same `truncateEntry` the persistence boundary uses (it also drops
27
+ * `_seq`), and the same server-only fields normal history replay strips
28
+ * (`sourceToolUseId`, `answered`; see ws-history.js), so this read path shows
29
+ * no more than replay would.
30
+ * - An entry still bigger than HISTORY_ENTRY_BYTES (a long
31
+ * message, a large tool input or result) has `content` / `result` / `input`
32
+ * shortened for display, and if that is still not enough it is reduced to a
33
+ * bounded type, a numeric timestamp and `isError`, marked `_truncated` (the
34
+ * panel shows it as too large to show). Nothing on disk changes.
35
+ * - A non-object slot (a hand-edited state file) becomes `{ type: 'unknown' }`
36
+ * rather than being dropped, so page offsets keep matching history indexes.
37
+ *
38
+ * @param {unknown} raw
39
+ * @param {{ truncateEntry: (entry: object) => object }} history
40
+ * @returns {object}
41
+ */
42
+ export function historyWireEntry(raw, history) {
43
+ if (!raw || typeof raw !== 'object') return { type: 'unknown' }
44
+ const { sourceToolUseId: _sourceToolUseId, answered: _answered, ...entry } = history.truncateEntry(raw)
45
+ if (Buffer.byteLength(JSON.stringify(entry)) <= HISTORY_ENTRY_BYTES) return entry
46
+ const max = HISTORY_FIELD_CHARS
47
+ const shorten = (text) => (text.length > max ? `${text.slice(0, max)}[truncated]` : text)
48
+ for (const key of ['content', 'result', 'input']) {
49
+ const value = entry[key]
50
+ if (typeof value === 'string') {
51
+ entry[key] = shorten(value)
52
+ } else if (value && typeof value === 'object') {
53
+ let serialized
54
+ try { serialized = JSON.stringify(value) } catch { serialized = '[unserializable]' }
55
+ if (typeof serialized === 'string' && serialized.length > max) {
56
+ entry[key] = { _truncated: true, summary: shorten(serialized) }
57
+ }
58
+ }
59
+ }
60
+ if (Buffer.byteLength(JSON.stringify(entry)) <= HISTORY_ENTRY_BYTES) return entry
61
+ // Last resort (escape-heavy text, or abnormal fields of a hand-edited file):
62
+ // keep only small, typed metadata so this can never itself be large.
63
+ return {
64
+ type: typeof entry.type === 'string' && entry.type.length <= 64 ? entry.type : 'unknown',
65
+ ...(Number.isFinite(entry.timestamp) ? { timestamp: entry.timestamp } : {}),
66
+ ...(typeof entry.isError === 'boolean' ? { isError: entry.isError } : {}),
67
+ _truncated: true,
68
+ }
69
+ }
70
+
71
+ /**
72
+ * One bounded page of a preserved history, oldest first.
73
+ *
74
+ * Each entry is shaped by `historyWireEntry`, and the page stops early once its
75
+ * serialized size would pass HISTORY_PAGE_BYTES, so `entries` can be shorter
76
+ * than `limit`. `limit` is clamped to 1..MAX (default 50) and `offset` to >= 0,
77
+ * whatever the caller sent; a non-numeric value takes the default rather than
78
+ * propagating NaN into `slice`.
79
+ *
80
+ * @param {unknown} history the saved history (anything but an array reads as empty)
81
+ * @param {{ offset?: number, limit?: number }} [opts]
82
+ * @param {{ truncateEntry: (entry: object) => object }} historyHelper
83
+ * @returns {{ total: number, offset: number, entries: object[] }}
84
+ */
85
+ export function pageHistory(history, { offset, limit } = {}, historyHelper) {
86
+ const list = Array.isArray(history) ? history : []
87
+ const pageSize = Number.isFinite(limit)
88
+ ? Math.min(HISTORY_PAGE_MAX_LIMIT, Math.max(1, Math.trunc(limit)))
89
+ : HISTORY_PAGE_DEFAULT_LIMIT
90
+ const start = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0
91
+ const entries = []
92
+ let bytes = 0
93
+ for (const raw of list.slice(start, start + pageSize)) {
94
+ const entry = historyWireEntry(raw, historyHelper)
95
+ const size = Buffer.byteLength(JSON.stringify(entry))
96
+ // Always at least one entry, so paging (the next offset is
97
+ // `offset + entries.length`) can never stall. The per-entry cap already
98
+ // keeps any one entry under the page budget; this holds it if they drift.
99
+ if (entries.length > 0 && bytes + size > HISTORY_PAGE_BYTES) break
100
+ entries.push(entry)
101
+ bytes += size
102
+ }
103
+ return { total: list.length, offset: start, entries }
104
+ }
@@ -1,20 +1,30 @@
1
1
  import { readFileSync, existsSync, statSync } from 'fs'
2
+ import { captureBearer, bearerStillValid } from './bearer-recheck.js'
2
3
  import { join, resolve, dirname, relative, sep, isAbsolute } from 'path'
3
4
  import { fileURLToPath } from 'url'
4
5
  import QRCode from 'qrcode'
6
+ import { DeclaredStatusInputSchema } from '@chroxy/protocol'
7
+ import { buildSessionTokenMismatchPayload } from './handler-utils.js'
5
8
  import { readConnectionInfo } from './connection-info.js'
9
+ import { isLoopbackPeer } from './connection-locality.js'
10
+ import { computeDaemonIdleState } from './daemon-idle-state.js'
11
+ import { DAEMON_COMMIT } from './daemon-commit.js'
6
12
  import { createLogger } from './logger.js'
7
13
  import { metrics } from './metrics.js'
8
14
  import { buildDiagnosticsSnapshot } from './diagnostics.js'
9
15
  import { getRateLimitKey } from './rate-limiter.js'
10
16
  import { listSnapshots, deleteSnapshot } from './snapshots-store.js'
11
17
  import { handleEventIngest } from './event-ingest.js'
18
+ import { listContinuations } from './continuations.js'
12
19
  import { handleGithubWebhook } from './github-webhook.js'
13
20
  import { handleMailboxPing, handleMailboxRegister } from './mailbox-route.js'
14
21
  import { isPoolEnabled } from './docker-byok-pool.js'
15
22
  import { getSharedPoolStats } from './docker-byok-pool-stats.js'
16
23
  import { isValidSlug, mimeForPath } from './pages-store.js'
17
24
  import { sendOversizeResponse } from './http-oversize.js'
25
+ import { resolveDashboardDist, dashboardBuildIdOf } from './dashboard-build.js'
26
+ import { resolveOAuthCallback, MCP_OAUTH_CALLBACK_PATH } from './byok-mcp-oauth.js'
27
+ import { challengeFromUrl, computeHealthProof } from './health-proof.js'
18
28
 
19
29
  /**
20
30
  * #5683 — read + JSON-parse a request body with a byte cap. Resolves to the
@@ -96,6 +106,13 @@ const PAGE_SECURITY_HEADERS = {
96
106
 
97
107
  const log = createLogger('ws')
98
108
 
109
+ /** Minimal HTML-escape for interpolating an untrusted value into a page body. */
110
+ function escapeHtml(s) {
111
+ return String(s).replace(/[&<>"']/g, (c) => (
112
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
113
+ ))
114
+ }
115
+
99
116
  const __filename = fileURLToPath(import.meta.url)
100
117
  const __dirname = dirname(__filename)
101
118
  const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
@@ -247,7 +264,7 @@ function matchAllowedOrigin(origin) {
247
264
  * @param {object} server - WsServer instance (accessed at request time for current state)
248
265
  * @returns {(req: import('http').IncomingMessage, res: import('http').ServerResponse) => void}
249
266
  */
250
- export function createHttpHandler(server) {
267
+ export function createHttpHandler(server, { dashboardDist } = {}) {
251
268
  // #5312 (WP-1.2) — the actual routing logic, wrapped below in a top-level
252
269
  // try/catch so an unguarded throw from any route (e.g. buildDiagnosticsSnapshot,
253
270
  // readConnectionInfo, or readFileSync(index)) returns 500 instead of rejecting
@@ -275,7 +292,7 @@ export function createHttpHandler(server) {
275
292
  }
276
293
 
277
294
  // Health check — Cloudflare and app verify connectivity via GET / and GET /health
278
- if (req.method === 'GET' && (req.url === '/' || req.url === '/health')) {
295
+ if (req.method === 'GET' && (req.url === '/' || (req.url ?? '').split('?')[0] === '/health')) {
279
296
  const accept = req.headers['accept'] || ''
280
297
  if (req.url === '/' && accept.includes('text/html') && server.apiToken) {
281
298
  res.writeHead(302, {
@@ -291,7 +308,17 @@ export function createHttpHandler(server) {
291
308
  'Vary': 'Accept',
292
309
  'Access-Control-Allow-Origin': '*',
293
310
  })
294
- res.end(JSON.stringify({ status: 'ok', mode: server.serverMode, version: SERVER_VERSION }))
311
+ const body = { status: 'ok', mode: server.serverMode, version: SERVER_VERSION }
312
+ // A valid challenge adds a proof keyed by the primary API token and bound
313
+ // to the port this server listens on. Any other value is ignored. Only a
314
+ // loopback peer that carries no tunnel or proxy header gets one: a tunnel
315
+ // client connects from loopback too, but adds those headers.
316
+ const challenge = isLoopbackPeer(req) ? challengeFromUrl(req.url) : null
317
+ if (challenge && typeof server.apiToken === 'string' && server.apiToken) {
318
+ const port = server.httpServer?.address?.()?.port ?? server.port
319
+ body.proof = computeHealthProof(server.apiToken, port, challenge)
320
+ }
321
+ res.end(JSON.stringify(body))
295
322
  return
296
323
  }
297
324
 
@@ -394,6 +421,116 @@ export function createHttpHandler(server) {
394
421
  return
395
422
  }
396
423
 
424
+ // Idle probe for the idle-only auto-deploy (#8324). `scripts/deploy-daemon.mjs`
425
+ // asks this before restarting the daemon, which would kill every live
426
+ // session. Two gates, LOCALITY FIRST: a request that did not arrive directly
427
+ // over loopback (a LAN peer, or anything through the tunnel — cloudflared
428
+ // connects from 127.0.0.1, so the socket address alone proves nothing and
429
+ // the proxy headers must be absent too) gets a bare 403 that says nothing
430
+ // about whether the token was right. Then the PRIMARY token: the answer
431
+ // enumerates session names, so a pairing-bound token must not reach it.
432
+ // Fail safe: any inability to compute is `idle: false`, never `true`.
433
+ if (req.method === 'GET' && (req.url ?? '').split('?')[0] === '/api/daemon/idle') {
434
+ if (!isLoopbackPeer(req)) {
435
+ res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
436
+ res.end(JSON.stringify({ error: 'forbidden' }))
437
+ return
438
+ }
439
+ if (!server._validatePrimaryBearerAuth(req, res)) return
440
+ let state
441
+ try {
442
+ state = computeDaemonIdleState({
443
+ sessionManager: server.sessionManager,
444
+ getHookPendingPermissionCount: () => server.getHookPendingPermissionCount(),
445
+ })
446
+ } catch (err) {
447
+ state = {
448
+ idle: false,
449
+ reasons: [`idle state unavailable: ${err?.message || String(err)}`],
450
+ sessions: [],
451
+ hookPendingPermissions: 0,
452
+ }
453
+ }
454
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
455
+ res.end(JSON.stringify({
456
+ ...state,
457
+ version: SERVER_VERSION,
458
+ // The commit this process started from (null when it cannot say). The
459
+ // auto-deploy certifies a restart only by reading this back (#8324).
460
+ commit: DAEMON_COMMIT,
461
+ pid: process.pid,
462
+ startedAt: Number.isFinite(server._startedAt) ? new Date(server._startedAt).toISOString() : null,
463
+ }))
464
+ return
465
+ }
466
+
467
+ // #6822 — MCP OAuth redirect callback. The browser that completed consent
468
+ // (on the user's own device) is redirected here with `?code=...&state=...`.
469
+ // This route is intentionally UNAUTHENTICATED: the redirect carries no bearer
470
+ // token, and the high-entropy `state` value (bound server-side to a specific
471
+ // pending authorization) IS the capability. We hand the code to the matching
472
+ // pending client, which redeems it + persists tokens. When the daemon isn't
473
+ // reachable from the user's browser (remote/tunneled) this page never loads —
474
+ // the user copy-pastes the code back over the wire instead (the universal
475
+ // fallback). Never logs the code.
476
+ const oauthCbPath = (req.url ?? '').split('?')[0]
477
+ if (req.method === 'GET' && oauthCbPath === MCP_OAUTH_CALLBACK_PATH) {
478
+ let code = null
479
+ let state = null
480
+ let oauthError = null
481
+ try {
482
+ const parsed = new URL(req.url, 'http://localhost')
483
+ code = parsed.searchParams.get('code')
484
+ state = parsed.searchParams.get('state')
485
+ oauthError = parsed.searchParams.get('error')
486
+ } catch { /* malformed url — handled as missing params below */ }
487
+
488
+ const page = (title, body) =>
489
+ `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">` +
490
+ `<title>${title}</title><style>body{font-family:system-ui,-apple-system,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#1a2332;line-height:1.5}` +
491
+ `code{background:#eef1f6;padding:.15rem .35rem;border-radius:.25rem;word-break:break-all}h1{font-size:1.25rem}</style></head><body>${body}</body></html>`
492
+
493
+ const sendPage = (status, title, body) => {
494
+ res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', ...PAGE_SECURITY_HEADERS })
495
+ res.end(page(title, body))
496
+ }
497
+
498
+ if (oauthError) {
499
+ sendPage(400, 'Authorization failed',
500
+ `<h1>Authorization was not completed</h1><p>The authorization server reported an error. You can close this tab and try authorizing again from Chroxy.</p>`)
501
+ return
502
+ }
503
+ if (!code || !state) {
504
+ sendPage(400, 'Authorization callback',
505
+ `<h1>Missing authorization details</h1><p>This page expects a <code>code</code> and <code>state</code> from the authorization server. If you reached it manually, return to Chroxy and use the paste-code option.</p>`)
506
+ return
507
+ }
508
+
509
+ resolveOAuthCallback(state, code)
510
+ .then((outcome) => {
511
+ if (outcome.found && outcome.ok) {
512
+ sendPage(200, 'Authorized',
513
+ `<h1>MCP server authorized</h1><p>You can close this tab and return to Chroxy — the server is reconnecting now.</p>`)
514
+ } else if (outcome.found) {
515
+ // The daemon received the callback but redemption failed. Surface the
516
+ // code so the user can retry via paste (value shown only to the user
517
+ // whose browser holds the redirect; never logged server-side).
518
+ sendPage(200, 'Finish in Chroxy',
519
+ `<h1>Almost there</h1><p>Automatic completion didn't succeed. Copy this authorization code and paste it into Chroxy:</p><p><code>${escapeHtml(code)}</code></p>`)
520
+ } else {
521
+ // No pending authorization matched this state (expired, wrong daemon,
522
+ // or already completed). Offer the paste-code fallback.
523
+ sendPage(200, 'Finish in Chroxy',
524
+ `<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
525
+ }
526
+ })
527
+ .catch(() => {
528
+ sendPage(200, 'Finish in Chroxy',
529
+ `<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
530
+ })
531
+ return
532
+ }
533
+
397
534
  // Metrics endpoint — operational counters for monitoring
398
535
  if (req.method === 'GET' && req.url === '/metrics') {
399
536
  if (!server._validateBearerAuth(req, res)) return
@@ -430,6 +567,43 @@ export function createHttpHandler(server) {
430
567
  // on its SnapshotsPanel.
431
568
  const snapPath = (req.url ?? '').split('?')[0]
432
569
 
570
+ // Bounded session intent writes share the existing bearer classes.
571
+ const statusMatch = /^\/api\/sessions\/([^/]+)\/status$/.exec(snapPath)
572
+ if (req.method === 'POST' && statusMatch) {
573
+ if (!server._validateBearerAuth(req, res, { allowScoped: true })) return
574
+ const sessionId = statusMatch[1]
575
+ const token = (req.headers.authorization || '').slice(7)
576
+ const pairing = server._pairingManager
577
+ const bearer = captureBearer(server, req)
578
+ const isPairing = pairing?.isSessionTokenValid(token) === true
579
+ const bound = isPairing ? pairing.getSessionIdForToken(token) : null
580
+ // Only primary or a token explicitly bound to THIS session may write.
581
+ if (isPairing && bound !== sessionId) {
582
+ res.writeHead(403, { 'Content-Type': 'application/json' })
583
+ const mismatch = buildSessionTokenMismatchPayload({ sessionManager: server.sessionManager, boundSessionId: bound })
584
+ res.end(JSON.stringify({ error: mismatch.message, ...mismatch }))
585
+ return
586
+ }
587
+ const body = await readJsonBodyCapped(req, res, 4096)
588
+ if (body === null) return
589
+ // A bearer is checked again once the body has arrived (bearer-recheck.js).
590
+ if (!bearerStillValid(server, bearer)) {
591
+ res.writeHead(403, { 'Content-Type': 'application/json' })
592
+ res.end(JSON.stringify({ error: 'unauthorized' }))
593
+ return
594
+ }
595
+ const parsed = DeclaredStatusInputSchema.safeParse(body)
596
+ if (!parsed.success) {
597
+ res.writeHead(400, { 'Content-Type': 'application/json' })
598
+ res.end(JSON.stringify({ error: 'invalid status' }))
599
+ return
600
+ }
601
+ const status = server.sessionManager?.setDeclaredStatus(sessionId, parsed.data, 'api')
602
+ res.writeHead(status ? 200 : 404, { 'Content-Type': 'application/json' })
603
+ res.end(JSON.stringify(status ? { ok: true, declaredStatus: status } : { error: 'session not found' }))
604
+ return
605
+ }
606
+
433
607
  // External event ingest (#5413 Phase 3). Accepts ONLY the daemon-level
434
608
  // ingest secret (never the primary token — see
435
609
  // docs/security/bearer-token-authority.md §6); auth, body cap, schema
@@ -441,6 +615,15 @@ export function createHttpHandler(server) {
441
615
  return
442
616
  }
443
617
 
618
+ // Path metadata is a global host surface: primary bearer only, never the
619
+ // ingest credential that can announce it or a session-bound pairing token.
620
+ if (req.method === 'GET' && snapPath === '/api/continuations') {
621
+ if (!server._validatePrimaryBearerAuth(req, res)) return
622
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
623
+ res.end(JSON.stringify({ continuations: await listContinuations(server) }))
624
+ return
625
+ }
626
+
444
627
  // Control Room repo-events feed (#5966): GitHub webhook deliveries. Auth is
445
628
  // the X-Hub-Signature-256 HMAC (NOT the ingest secret) — the handler verifies
446
629
  // it over the RAW body before parsing, and stays inert (503) until a secret
@@ -521,6 +704,80 @@ export function createHttpHandler(server) {
521
704
  return
522
705
  }
523
706
 
707
+ // Paired-devices roster + live revoke (#6678, part of epic #6597). The
708
+ // dashboard "Paired devices" panel lists the RUNNING daemon's paired
709
+ // session tokens (wire-safe ids, bound session, age — never token material)
710
+ // and revokes them live: unlike `chroxy tokens revoke` (which edits the
711
+ // persisted store and needs a daemon restart), these hit PairingManager's
712
+ // in-memory map so the device's next auth fails immediately.
713
+ //
714
+ // PRIMARY-token only on ALL THREE. The roster is host-level pairing state —
715
+ // a scoped/paired device must neither enumerate its siblings (information
716
+ // disclosure) nor revoke them (a host-level mutation beyond one session's
717
+ // scope). Mirrors the DELETE /api/snapshots gate; see
718
+ // docs/security/bearer-token-authority.md §9.
719
+ if (req.method === 'GET' && snapPath === '/api/paired-devices') {
720
+ if (!server._validatePrimaryBearerAuth(req, res)) return
721
+ const pm = server._pairingManager
722
+ const devices = pm && typeof pm.listSessionTokens === 'function' ? pm.listSessionTokens() : []
723
+ res.writeHead(200, { 'Content-Type': 'application/json' })
724
+ res.end(JSON.stringify({ devices }))
725
+ return
726
+ }
727
+
728
+ // Revoke ALL paired devices — the panic button. Exact-path match (no id), so
729
+ // it never collides with the per-device DELETE below.
730
+ if (req.method === 'DELETE' && snapPath === '/api/paired-devices') {
731
+ if (!server._validatePrimaryBearerAuth(req, res)) return
732
+ const pm = server._pairingManager
733
+ const result = pm && typeof pm.revokeAllSessionTokens === 'function' ? pm.revokeAllSessionTokens() : { revoked: 0 }
734
+ // #6902: a failed durable write leaves every token valid on disk — report
735
+ // failure rather than a false `ok:true` so the operator re-tries instead of
736
+ // trusting a revoke a crash would undo.
737
+ if (result.persistFailed) {
738
+ res.writeHead(500, { 'Content-Type': 'application/json' })
739
+ res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
740
+ return
741
+ }
742
+ res.writeHead(200, { 'Content-Type': 'application/json' })
743
+ res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
744
+ return
745
+ }
746
+
747
+ // Revoke ONE paired device by its wire id (from GET /api/paired-devices).
748
+ if (req.method === 'DELETE' && snapPath.startsWith('/api/paired-devices/')) {
749
+ if (!server._validatePrimaryBearerAuth(req, res)) return
750
+ const rawId = snapPath.slice('/api/paired-devices/'.length)
751
+ let id
752
+ try {
753
+ id = decodeURIComponent(rawId)
754
+ } catch {
755
+ res.writeHead(400, { 'Content-Type': 'application/json' })
756
+ res.end(JSON.stringify({ error: 'invalid id encoding' }))
757
+ return
758
+ }
759
+ const pm = server._pairingManager
760
+ const result = pm && typeof pm.revokeSessionTokenById === 'function' ? pm.revokeSessionTokenById(id) : { revoked: 0 }
761
+ // #6902: the device exists but its removal could not be durably persisted —
762
+ // distinct from "no such device". Report failure (500) rather than a false
763
+ // success so the still-valid token isn't reported as revoked.
764
+ if (result.persistFailed) {
765
+ res.writeHead(500, { 'Content-Type': 'application/json' })
766
+ res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
767
+ return
768
+ }
769
+ if (result.revoked === 0) {
770
+ // The device is already gone (revoked elsewhere, expired, or a stale id
771
+ // from a device that re-paired). 404 so the UI can reconcile its list.
772
+ res.writeHead(404, { 'Content-Type': 'application/json' })
773
+ res.end(JSON.stringify({ error: 'no such paired device', revoked: 0 }))
774
+ return
775
+ }
776
+ res.writeHead(200, { 'Content-Type': 'application/json' })
777
+ res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
778
+ return
779
+ }
780
+
524
781
  // docker-byok pool stats endpoint (#5053). Returns a rolling
525
782
  // observability snapshot — hit/miss counters, hit rate,
526
783
  // eviction-by-reason, the recent-evictions tail, and the live per-key
@@ -542,11 +799,18 @@ export function createHttpHandler(server) {
542
799
  // matching the other host-write routes — see bearer-token-authority.md §4).
543
800
  if (req.method === 'POST' && snapPath === '/api/pages' && server.pagesStore) {
544
801
  if (!server._validatePrimaryBearerAuth(req, res)) return
802
+ const bearer = captureBearer(server, req)
545
803
  // Body cap a little above the per-page byte cap to allow JSON overhead.
546
804
  const maxBody = server.pagesStore.maxPageBytes + 1024 * 1024
547
805
  readJsonBodyCapped(req, res, maxBody)
548
806
  .then((parsed) => {
549
807
  if (parsed === null) return // 413/400 already sent
808
+ // A bearer is checked again once the body has arrived (bearer-recheck.js).
809
+ if (!bearerStillValid(server, bearer)) {
810
+ res.writeHead(403, { 'Content-Type': 'application/json' })
811
+ res.end(JSON.stringify({ error: 'unauthorized' }))
812
+ return
813
+ }
550
814
  const title = typeof parsed.title === 'string' ? parsed.title : 'Untitled'
551
815
  // Accept either { html } (single self-contained page) or
552
816
  // { files: [{ path, content }] } (multi-file). `html` is shorthand.
@@ -712,6 +976,16 @@ export function createHttpHandler(server) {
712
976
  return
713
977
  }
714
978
 
979
+ // #7004 — protected-path / secret-read FLOOR probe for the permission hook.
980
+ // The hook decides auto/acceptEdits in shell, so it asks here whether the
981
+ // target is floored before short-circuiting; a floored target is routed to a
982
+ // real prompt via POST /permission. Same per-session hook-secret auth as
983
+ // /permission; read-only (no pending request, no broadcast, no push).
984
+ if (req.method === 'POST' && req.url === '/permission-floor') {
985
+ server._permissions.handlePermissionFloorCheck(req, res)
986
+ return
987
+ }
988
+
715
989
  // Permission response endpoint (HTTP fallback)
716
990
  if (req.method === 'POST' && req.url === '/permission-response') {
717
991
  server._permissions.handlePermissionResponseHttp(req, res)
@@ -1063,9 +1337,8 @@ export function createHttpHandler(server) {
1063
1337
 
1064
1338
  // Workspace layout: packages/dashboard/dist (dev)
1065
1339
  // Tauri bundle layout: server/src/dashboard-next/dist (bundled)
1066
- const workspaceDist = join(__dirname, '..', '..', 'dashboard', 'dist')
1067
- const bundleDist = join(__dirname, 'dashboard-next', 'dist')
1068
- const distDir = existsSync(workspaceDist) ? workspaceDist : bundleDist
1340
+ // `dashboardDist` is a test seam; production never passes it.
1341
+ const distDir = dashboardDist ?? resolveDashboardDist()
1069
1342
  if (!existsSync(distDir) && !createHttpHandler._distMissWarned) {
1070
1343
  createHttpHandler._distMissWarned = true
1071
1344
  log.warn(`Dashboard dist directory not found: ${distDir} — run "npm run build -w @chroxy/dashboard"`)
@@ -1112,9 +1385,14 @@ export function createHttpHandler(server) {
1112
1385
  const indexPath = join(distDir, 'index.html')
1113
1386
  if (existsSync(indexPath)) {
1114
1387
  let html = readFileSync(indexPath, 'utf-8')
1115
- const escaped = JSON.stringify({port: server.port, noEncrypt: !server._encryptionEnabled}).replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
1388
+ const escaped = JSON.stringify({port: server.port, noEncrypt: !server._encryptionEnabled, authRequired: server.authRequired !== false}).replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
1116
1389
  const configMeta = `<meta name="chroxy-config" content='${escaped}'>`
1117
- html = html.replace('</head>', `${configMeta}\n</head>`)
1390
+ // #8268 — the id of the bundle THIS page loaded, hashed from the pristine
1391
+ // file (before the per-request config above is spliced in). The client
1392
+ // compares it with `auth_ok.dashboardBuildId`, which is the id of the file
1393
+ // on disk at connect time, so a page that outlives a daemon update can tell.
1394
+ const buildMeta = `<meta name="chroxy-build" content="${dashboardBuildIdOf(html)}">`
1395
+ html = html.replace('</head>', `${configMeta}\n${buildMeta}\n</head>`)
1118
1396
  res.writeHead(200, {
1119
1397
  'Content-Type': 'text/html; charset=utf-8',
1120
1398
  'Cache-Control': 'no-store',
package/src/ide/search.js CHANGED
@@ -14,8 +14,11 @@
14
14
  * attacker-reachable WS surface's boundary; the regression tests
15
15
  * (ide-search.test.js) assert the symlink-escape cases on both.
16
16
  */
17
- import { readdir, readFile, stat, realpath, lstat } from 'fs/promises'
17
+ import { readdir, stat, realpath, lstat } from 'fs/promises'
18
18
  import { join, resolve, relative, extname, sep } from 'path'
19
+ import { isPathWithin } from '../utils/path-containment.js'
20
+ import { makeConfigDirFilter } from '../ws-file-ops/common.js'
21
+ import { readContainedTextFile } from '../utils/regular-file.js'
19
22
 
20
23
  // Directories never worth walking (mirrors symbols.js IGNORED_DIRS).
21
24
  const IGNORED_DIRS = new Set([
@@ -95,7 +98,12 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
95
98
  return { results: [], truncated: false }
96
99
  }
97
100
  const rel = relative(root, realTarget)
98
- if (rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget) {
101
+ // #7273 — this was `rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget`.
102
+ // Correct for same-root escapes, blind to a target on a DIFFERENT Windows root:
103
+ // `path.win32.relative('C:\\ws', 'D:\\x')` returns `'D:\\x'`, which is neither `'..'`
104
+ // nor `'..' + sep`, and the round-trip clause is a tautology for exactly that input
105
+ // (`resolve(root, 'D:\\x') === 'D:\\x'`). `isPathWithin` is root-aware.
106
+ if (!isPathWithin(realTarget, root)) {
99
107
  return { results: [], truncated: false }
100
108
  }
101
109
  if (rel.split(sep).some((s) => IGNORED_DIRS.has(s) || s.startsWith('.'))) {
@@ -104,6 +112,10 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
104
112
  target = realTarget
105
113
  }
106
114
 
115
+ // The config root is resolved once per walk; every path this walk yields is real
116
+ // (a real root, descended only through real directories, symlinks never followed).
117
+ const isDaemonState = await makeConfigDirFilter()
118
+
107
119
  const results = []
108
120
  let filesRead = 0
109
121
  let truncated = false
@@ -126,11 +138,17 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
126
138
  } catch { return }
127
139
  if (!st.isFile()) return
128
140
  if (st.size > maxFileSize) return
141
+ // Files directly in the daemon's config directory are daemon-managed state, so
142
+ // search treats them the way the file viewer does: they contribute nothing. This
143
+ // matters when the session cwd is the config directory or an ancestor of a
144
+ // relocated, non-hidden one (the walk skips hidden directories). Checked after
145
+ // the cheap filters above and before the read, so a skipped file costs no read
146
+ // and does not count against the file cap.
147
+ if (isDaemonState(absPath)) return
129
148
  filesRead++
130
- let content
131
- try {
132
- content = await readFile(absPath, 'utf-8')
133
- } catch { return }
149
+ // One checked, pinned open: see readContainedTextFile.
150
+ const content = await readContainedTextFile(absPath, root, maxFileSize)
151
+ if (content === null) return
134
152
  // Skip a file that looks binary (a NUL in the first chunk) despite its ext.
135
153
  if (content.indexOf(String.fromCharCode(0)) !== -1) return
136
154
  const rel = relative(root, absPath).split(sep).join('/')
@@ -27,8 +27,11 @@
27
27
  * @property {number} line 1-indexed line of the declaration.
28
28
  * @property {boolean} exported Whether the declaration is exported / public.
29
29
  */
30
- import { readdir, readFile, stat, realpath, lstat } from 'fs/promises'
30
+ import { readdir, stat, realpath, lstat } from 'fs/promises'
31
31
  import { join, resolve, relative, extname, sep } from 'path'
32
+ import { isPathWithin } from '../utils/path-containment.js'
33
+ import { makeConfigDirFilter } from '../ws-file-ops/common.js'
34
+ import { readContainedTextFile } from '../utils/regular-file.js'
32
35
 
33
36
  // Directories never worth walking — build output, vendored deps, VCS metadata,
34
37
  // language caches. Keeps the scan bounded and the symbol table signal-rich.
@@ -214,7 +217,12 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
214
217
  return { symbols: [], truncated: false }
215
218
  }
216
219
  const rel = relative(root, realTarget)
217
- if (rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget) {
220
+ // #7273 — this was `rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget`.
221
+ // Correct for same-root escapes, blind to a target on a DIFFERENT Windows root:
222
+ // `path.win32.relative('C:\\ws', 'D:\\x')` returns `'D:\\x'`, which is neither `'..'`
223
+ // nor `'..' + sep`, and the round-trip clause is a tautology for exactly that input
224
+ // (`resolve(root, 'D:\\x') === 'D:\\x'`). `isPathWithin` is root-aware.
225
+ if (!isPathWithin(realTarget, root)) {
218
226
  // The REAL path escapes the workspace (e.g. via a symlink) — refuse.
219
227
  return { symbols: [], truncated: false }
220
228
  }
@@ -227,6 +235,10 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
227
235
  target = realTarget
228
236
  }
229
237
 
238
+ // The config root is resolved once per walk; every path this walk yields is real
239
+ // (a real root, descended only through real directories, symlinks never followed).
240
+ const isDaemonState = await makeConfigDirFilter()
241
+
230
242
  const symbols = []
231
243
  let filesRead = 0
232
244
  let truncated = false
@@ -244,11 +256,13 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
244
256
  if (!st.isFile()) return
245
257
  if (st.size > maxFileSize) return
246
258
  if (!(extname(absPath).toLowerCase() in EXT_LANG)) return
259
+ // Daemon-managed state (the config directory and files directly in it) is not
260
+ // part of the symbol table, same as the file viewer; see ide/search.js.
261
+ if (isDaemonState(absPath)) return
247
262
  filesRead++
248
- let content
249
- try {
250
- content = await readFile(absPath, 'utf-8')
251
- } catch { return }
263
+ // One checked, pinned open: see readContainedTextFile.
264
+ const content = await readContainedTextFile(absPath, root, maxFileSize)
265
+ if (content === null) return
252
266
  const rel = relative(root, absPath).split(sep).join('/')
253
267
  for (const s of parseSymbols(content, rel)) {
254
268
  if (symbols.length >= maxSymbols) { truncated = true; return }