@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,2866 @@
1
+ import { createServer } from 'http'
2
+ import { randomBytes, randomUUID } from 'crypto'
3
+ import { execFileSync } from 'child_process'
4
+ import { WebSocketServer } from 'ws'
5
+ import { readFileSync } from 'fs'
6
+ import { fileURLToPath } from 'url'
7
+ import { dirname, join } from 'path'
8
+ import { homedir } from 'os'
9
+ import { PagesStore } from './pages-store.js'
10
+ import { ShellApprovalStore } from './shell-approval-store.js'
11
+ import { finalizeShellCreate } from './handlers/session-handlers.js'
12
+ import { decrypt, DIRECTION_CLIENT } from '@chroxy/store-core/crypto'
13
+ import { safeTokenCompare } from './token-compare.js'
14
+ import { createClientSender } from './ws-client-sender.js'
15
+ import { ClientMessageSchema, EncryptedEnvelopeSchema } from './ws-schemas.js'
16
+ import { EventNormalizer } from './event-normalizer.js'
17
+ import { createFileOps } from './ws-file-ops/index.js'
18
+ import { createPermissionHandler } from './ws-permissions.js'
19
+ import { setupForwarding } from './ws-forwarding.js'
20
+ import { handleSessionMessage, handleCliMessage } from './ws-message-handlers.js'
21
+ import { handleAuthMessage, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
22
+ import { postPairLinkToDiscord } from './discord-pair-delivery.js'
23
+ import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo } from './ws-history.js'
24
+ import { createDevicePreferences } from './device-preferences.js'
25
+ import { isUserShellEnabled, isIdeFeatureEnabled } from './config.js'
26
+ import { createHttpHandler } from './http-routes.js'
27
+ import { CheckpointManager } from './checkpoint-manager.js'
28
+ import { DevPreviewManager } from './dev-preview.js'
29
+ import { WebTaskManager } from './web-task-manager.js'
30
+ import { RateLimiter, getClientIp, getRateLimitKey, LOOPBACK_ADDRESSES } from './rate-limiter.js'
31
+ import { isUserShellApprovalRequired } from './config.js'
32
+ import { writeShellApprovalInfo, removeShellApprovalInfo } from './shell-approval-info.js'
33
+ import { createLogger, addLogListener, removeLogListener } from './logger.js'
34
+ import { PermissionAuditLog } from './permission-audit.js'
35
+ import { WsBroadcaster } from './ws-broadcaster.js'
36
+ import { WsClientManager } from './ws-client-manager.js'
37
+ import { terminalMirrorRecipient } from './handler-utils.js'
38
+ import { getProviderDataDirs } from './providers.js'
39
+ import { assertCtxShape } from './ws-handler-context.js'
40
+ import { isLoopbackHost } from './bind-host.js'
41
+ import { isLocalOrLanPeer } from './connection-locality.js'
42
+
43
+ const __filename = fileURLToPath(import.meta.url)
44
+ const __dirname = dirname(__filename)
45
+ const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
46
+
47
+ export function sanitizeErrorMessage(err) {
48
+ const safeMessages = {
49
+ INVALID_MESSAGE: 'Message validation failed',
50
+ SESSION_NOT_FOUND: 'Session not found',
51
+ PERMISSION_DENIED: 'Permission denied',
52
+ }
53
+ if (err && err.code && safeMessages[err.code]) {
54
+ return safeMessages[err.code]
55
+ }
56
+ return 'An internal error occurred'
57
+ }
58
+
59
+ /**
60
+ * Resolve the per-IP rate-limit config for GET /diagnostics (#3737).
61
+ *
62
+ * Override precedence:
63
+ * 1. Constructor opt `diagnosticsRateLimit` — full RateLimiter options
64
+ * object `{ windowMs, maxMessages, burst }`. Used by tests.
65
+ * 2. `CHROXY_DIAGNOSTICS_RATE_LIMIT` env var — a single positive integer
66
+ * sets `maxMessages`; burst defaults to `Math.max(1, Math.floor(N/3))`.
67
+ * 3. Defaults — 12 req/min + 4 burst (half of /permission since the cost
68
+ * is comparable but legitimate use is diagnostic, not interactive).
69
+ *
70
+ * Invalid env values (NaN, non-integer, < 1) silently fall through to
71
+ * defaults. Sub-integer values like `0.5` are rejected outright rather
72
+ * than truncated, because Math.trunc(0.5) = 0 and RateLimiter treats
73
+ * `maxMessages: 0` as "use default" via `||`, which would *raise* the
74
+ * limit instead of restoring it.
75
+ *
76
+ * @param {object|null} overrideOpts
77
+ * @returns {{ windowMs: number, maxMessages: number, burst: number }}
78
+ */
79
+ export function resolveDiagnosticsRateLimit(overrideOpts) {
80
+ if (overrideOpts && typeof overrideOpts === 'object') return overrideOpts
81
+ const raw = process.env.CHROXY_DIAGNOSTICS_RATE_LIMIT
82
+ if (raw != null && raw !== '') {
83
+ const n = Number(raw)
84
+ if (Number.isInteger(n) && n >= 1) {
85
+ return {
86
+ windowMs: 60_000,
87
+ maxMessages: n,
88
+ burst: Math.max(1, Math.floor(n / 3)),
89
+ }
90
+ }
91
+ }
92
+ return { windowMs: 60_000, maxMessages: 12, burst: 4 }
93
+ }
94
+
95
+ /**
96
+ * Parse a duration value coming from a `CHROXY_DEVICE_PREFS_*_MS` env var.
97
+ * Accepts:
98
+ * - a non-negative numeric string → that many milliseconds (fractional
99
+ * values are floored, e.g. `"1.9"` → 1)
100
+ * - `"0"` → 0 (the literal zero; callers decide what 0 means — the
101
+ * device-preferences `prune()` treats `maxAgeMs === 0` as "no age
102
+ * cap", so setting `CHROXY_DEVICE_PREFS_MAX_AGE_MS=0` disables the
103
+ * hard age cap rather than evicting every entry)
104
+ * - empty / null / non-numeric → fall back to `defaultMs`
105
+ *
106
+ * Negative numbers are silently coerced to the default so a typo can't
107
+ * disable the prune by making `now - updatedAt > -1` always true.
108
+ *
109
+ * @param {string|undefined|null} raw
110
+ * @param {number} defaultMs
111
+ * @returns {number}
112
+ */
113
+ export function parseDevicePrefsDuration(raw, defaultMs) {
114
+ if (raw == null || raw === '') return defaultMs
115
+ const n = Number(raw)
116
+ if (!Number.isFinite(n) || n < 0) return defaultMs
117
+ return Math.floor(n)
118
+ }
119
+
120
+ const SERVER_VERSION = packageJson.version
121
+ const log = createLogger('ws')
122
+
123
+ /**
124
+ * Protocol version — controls client/server compatibility negotiation.
125
+ *
126
+ * BUMP POLICY (Option B — breaking changes only):
127
+ *
128
+ * - DO NOT bump for additive changes (new message types, new optional fields).
129
+ * Clients already ignore unknown message types with a console.warn when
130
+ * serverProtocolVersion > clientProtocolVersion.
131
+ *
132
+ * - DO bump (increment by 1) for breaking changes:
133
+ * * Removing or renaming an existing message type
134
+ * * Changing the shape of an existing message (renaming/removing fields,
135
+ * changing field types, making optional fields required)
136
+ * * Changing auth handshake semantics
137
+ *
138
+ * - When bumping, update PROTOCOL_CHANGELOG below and coordinate with
139
+ * CLIENT_PROTOCOL_VERSION in:
140
+ * * packages/app/src/store/message-handler.ts
141
+ * * packages/dashboard/src/store/message-handler.ts
142
+ *
143
+ * - If a bump would break old clients, consider whether MIN_PROTOCOL_VERSION
144
+ * should also increase (rejecting clients that cannot speak the new protocol).
145
+ *
146
+ * See also: #1058 (enforce MIN_PROTOCOL_VERSION during auth)
147
+ */
148
+ export const SERVER_PROTOCOL_VERSION = 2
149
+ /** Minimum protocol version this server can speak */
150
+ export const MIN_PROTOCOL_VERSION = 1
151
+ /**
152
+ * Minimum protocol version for structured tunnel-warming/ready status
153
+ * broadcasts (#2849). v1 clients don't know how to render the `phase`
154
+ * field and would mis-render it as a chat message — they are simply
155
+ * excluded from these broadcasts rather than served a phase-less
156
+ * fallback (which would reintroduce the mis-render).
157
+ */
158
+ export const TUNNEL_STATUS_MIN_PROTOCOL_VERSION = 2
159
+
160
+ /**
161
+ * PROTOCOL_CHANGELOG
162
+ *
163
+ * v1 (initial) — baseline message set: auth, auth_ok, message, assistant,
164
+ * result, raw_output, model_changed, permission_request, tool_use, etc.
165
+ * All subsequent additive message types (e.g. plan_started, plan_ready,
166
+ * models_updated, client_focus_changed, message_queued, message_dequeued)
167
+ * do NOT bump the version per the breaking-changes-only policy above.
168
+ *
169
+ * v2 (#2849) — `server_status` gained a structured `phase` field
170
+ * ('tunnel_warming' | 'ready') that v1 dashboards don't know how to
171
+ * render (they only read `msg.message` and push the payload as a
172
+ * chat system message). The structured broadcasts are gated to
173
+ * clients that advertised v2+ at auth time; v1 clients no longer
174
+ * receive tunnel warming / ready status at all. Gating happens at
175
+ * the broadcast site in server-cli.js via
176
+ * WsServer.broadcastMinProtocolVersion (see
177
+ * TUNNEL_STATUS_MIN_PROTOCOL_VERSION).
178
+ */
179
+
180
+ /** Cached latest version from npm registry (null if unavailable) */
181
+ let _latestVersionCache = { version: null, checkedAt: 0 }
182
+ const VERSION_CHECK_TTL = 3600_000 // 1 hour
183
+
184
+ // #5555.6 — keepalive sweep cadence. Previously 30s, which (with the
185
+ // two-phase mark-then-terminate cycle) held a zombie client up to ~60s — ~6×
186
+ // longer than a client holds a zombie server (15s ping + 5s pong timeout =
187
+ // 20s). We now (1) treat ANY inbound frame as proof of life (the client's own
188
+ // 15s heartbeat ping suffices — see ws.on('message')), and (2) drop the sweep
189
+ // to 15s so a client that goes truly silent is detected in 15–30s, ~2× the
190
+ // client cadence. The server's own ws.ping() still fires each sweep to hold
191
+ // Cloudflare / mobile-OS idle timeouts open for clients that don't initiate.
192
+ export const KEEPALIVE_SWEEP_MS = 15_000
193
+
194
+ async function checkLatestVersion(packageName) {
195
+ const now = Date.now()
196
+ if (_latestVersionCache.checkedAt > 0 && (now - _latestVersionCache.checkedAt) < VERSION_CHECK_TTL) {
197
+ return _latestVersionCache.version
198
+ }
199
+ try {
200
+ const controller = new AbortController()
201
+ const timeout = setTimeout(() => controller.abort(), 5000)
202
+ try {
203
+ const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`, {
204
+ signal: controller.signal,
205
+ headers: { 'Accept': 'application/json' },
206
+ })
207
+ clearTimeout(timeout)
208
+ if (res.ok) {
209
+ const data = await res.json()
210
+ if (data.version) {
211
+ _latestVersionCache = { version: data.version, checkedAt: now }
212
+ return data.version
213
+ }
214
+ }
215
+ } finally {
216
+ clearTimeout(timeout)
217
+ }
218
+ } catch {
219
+ // npm registry unreachable or package not published — expected
220
+ }
221
+ _latestVersionCache = { version: null, checkedAt: now }
222
+ return null
223
+ }
224
+
225
+ function getGitInfo() {
226
+ try {
227
+ const commit = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { stdio: ['pipe', 'pipe', 'pipe'] }).toString().trim()
228
+ const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { stdio: ['pipe', 'pipe', 'pipe'] }).toString().trim()
229
+ return { commit, branch }
230
+ } catch {
231
+ return { commit: 'unknown', branch: 'unknown' }
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Determine if request is served over HTTPS (tunnel or reverse proxy).
237
+ */
238
+ function _isSecureRequest(req) {
239
+ const proto = req.headers['x-forwarded-proto']
240
+ return proto === 'https'
241
+ }
242
+
243
+ /**
244
+ * WebSocket server that bridges the phone client to the backend.
245
+ *
246
+ * Supports two modes:
247
+ * - Multi-session (sessionManager): multiple concurrent CliSession instances
248
+ * - Single CLI (cliSession): headless `claude -p` with structured JSON (legacy)
249
+ *
250
+ * Protocol (JSON messages over WebSocket):
251
+ *
252
+ * Client -> Server:
253
+ * { type: 'auth', token: '...', deviceInfo? } — authenticate (deviceInfo: { deviceId, deviceName, deviceType, platform })
254
+ * { type: 'input', data: '...' } — send text to active session
255
+ * { type: 'interrupt' } — interrupt active session (also cancels the WHOLE outgoing queue)
256
+ * { type: 'cancel_queued', clientMessageId, sessionId? } — cancel ONE queued send-while-busy follow-up (#5943); server emits message_dequeued(reason: 'cancelled')
257
+ * { type: 'set_model', model: '...' } — change model on active session
258
+ * { type: 'set_permission_mode', mode: '...', confirmed? } — change permission mode (confirmed: true required for 'auto')
259
+ * { type: 'permission_response', requestId, decision } — respond to permission prompt
260
+ * { type: 'list_sessions' } — request session list
261
+ * { type: 'switch_session', sessionId } — switch to a different session
262
+ * { type: 'create_session', name?, cwd?, provider?, agentCommId? } — create a new session
263
+ * { type: 'destroy_session', sessionId } — destroy a session
264
+ * { type: 'rename_session', sessionId, name } — rename a session
265
+ * { type: 'register_push_token', token } — register push token for notifications
266
+ * { type: 'user_question_response', answer } — respond to AskUserQuestion prompt
267
+ * { type: 'list_directory', path? } — request directory listing for file browser
268
+ * { type: 'browse_files', path? } — request file/directory listing for file browser
269
+ * { type: 'read_file', path } — request file content for file viewer
270
+ * { type: 'write_file', path, content } — write file content (path validated, 5MB limit)
271
+ * { type: 'list_slash_commands' } — request available slash commands
272
+ * { type: 'list_agents' } — request available custom agents
273
+ * { type: 'request_full_history', sessionId? } — request full JSONL history for a session
274
+ * { type: 'key_exchange', publicKey } — client's ephemeral X25519 public key (E2E encryption)
275
+ * { type: 'create_checkpoint', name?, description? } — create a checkpoint for active session
276
+ * { type: 'list_checkpoints' } — request checkpoint list for active session
277
+ * { type: 'restore_checkpoint', checkpointId } — rewind to a checkpoint (creates new session)
278
+ * { type: 'delete_checkpoint', checkpointId } — delete a checkpoint
279
+ * { type: 'close_dev_preview', port, sessionId? } — close a dev server preview tunnel
280
+ * { type: 'launch_web_task', prompt, cwd? } — launch a Claude Code Web cloud task
281
+ * { type: 'list_web_tasks' } — request list of web tasks
282
+ * { type: 'teleport_web_task', taskId } — pull cloud task into local session
283
+ * { type: 'ping' } — client heartbeat (server responds with pong)
284
+ * { type: 'add_repo', path } — add a repository path to workspace
285
+ * { type: 'cli', command } — send raw CLI command to active session
286
+ * { type: 'get_diff', path? } — request git diff for working directory
287
+ * { type: 'git_branches' } — request git branch list
288
+ * { type: 'git_commit', message, files? } — commit staged/specified files
289
+ * { type: 'git_stage', files } — stage files for commit
290
+ * { type: 'git_status' } — request git status
291
+ * { type: 'git_unstage', files } — unstage files
292
+ * { type: 'list_conversations' } — request saved conversation list
293
+ * { type: 'list_files', path? } — request file listing for a path
294
+ * { type: 'list_symbols', path? } — request workspace symbol table (#6471, opt-in IDE — features.ide)
295
+ * { type: 'resolve_symbol', symbol, file? } — resolve a symbol name to its definition (#6475, opt-in IDE — features.ide)
296
+ * { type: 'search_content', query, path? } — find-in-project content grep (#6474, opt-in IDE — features.ide)
297
+ * { type: 'find_references', symbol, file? } — find-all-references word-boundary grep (#6477, opt-in IDE — features.ide)
298
+ * { type: 'list_providers' } — request available provider list
299
+ * { type: 'list_repos' } — request workspace repository list
300
+ * { type: 'list_skills' } — request active skills list
301
+ * { type: 'pair', pairingCode } — pair with another device via pairing code
302
+ * { type: 'query_permission_audit', last? } — query permission audit log
303
+ * { type: 'remove_repo', path } — remove a repository path from workspace
304
+ * { type: 'request_cost_summary' } — request cost summary for current session
305
+ * { type: 'request_session_context', sessionId? } — request session context (cwd, conversation, etc.)
306
+ * { type: 'resume_budget' } — resume after budget exceeded
307
+ * { type: 'resume_conversation', conversationId } — resume a saved conversation
308
+ * { type: 'search_conversations', query } — search saved conversations
309
+ * { type: 'subscribe_sessions' } — subscribe to session discovery events
310
+ * { type: 'unsubscribe_sessions' } — unsubscribe from session discovery
311
+ * { type: 'terminal_subscribe', sessionId } — #5835 opt IN to a session's live PTY mirror (terminal_output); only opted-in clients receive raw bytes
312
+ * { type: 'terminal_unsubscribe', sessionId } — #5835 opt OUT of a session's live PTY mirror
313
+ * { type: 'terminal_resize', sessionId, cols, rows } — #5835 Phase 2 request to resize the live claude-tui PTY; applied only for the session's primary owner (or an unclaimed session), then broadcast back as terminal_size
314
+ * { type: 'terminal_input', sessionId, data } — #5835 Phase 3 raw keystrokes → live claude-tui PTY (true remote control); authority mirrors `input` (bound-session check + single-driver primary gate; an observer's keystroke is rejected with input_conflict)
315
+ * { type: 'set_thinking_level', level } — set thinking budget level ('default'|'high'|'max')
316
+ * { type: 'set_permission_rules', rules, sessionId } — set per-session auto-approval rules
317
+ * { type: 'set_prompt_evaluator', value: boolean, sessionId? } — toggle the per-session promptEvaluator (#3185)
318
+ * { type: 'set_prompt_evaluator_skip_pattern', value: string|null, sessionId? } — set the per-session evaluator skip-pattern source (#3639)
319
+ * { type: 'set_chroxy_context_hint', value: boolean, sessionId? } — toggle the per-session Chroxy context hint (#3805)
320
+ * { type: 'set_session_preamble', value: string, sessionId? } — set the per-session user-authored preamble (#4660)
321
+ * { type: 'skill_activate', skillName, sessionId? } — activate a manual skill at runtime (#3209)
322
+ * { type: 'skill_deactivate', skillName, sessionId? } — deactivate a manual skill at runtime (#3209)
323
+ * { type: 'skill_trust_accept', skillName, sessionId?, requestId? } — re-trust a skill after a content-hash mismatch (#3235)
324
+ * { type: 'skill_trust_grant', skillName, author, scope?, sessionId?, requestId? } — grant community-skill trust (#3297)
325
+ * { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
326
+ * { type: 'create_environment', name, cwd, image?, ... } — create persistent container environment
327
+ * { type: 'list_environments' } — list all persistent environments
328
+ * { type: 'destroy_environment', environmentId } — destroy an environment and its container
329
+ * { type: 'get_environment', environmentId } — get single environment details
330
+ *
331
+ * Server -> Client:
332
+ * All session-scoped messages include a `sessionId` field for background sync.
333
+ * { type: 'auth_ok', clientId, serverMode, serverVersion, latestVersion, serverCommit, cwd, defaultCwd, connectedClients, encryption, resultTimeoutMs, hardTimeoutMs, streamStallTimeoutMs } — auth succeeded (encryption: 'required'|'disabled'; resultTimeoutMs = soft-warning window in ms, hardTimeoutMs = hard-kill window in ms, streamStallTimeoutMs = stream-stall recovery window in ms (0 = disabled) — #3760, #3905, #4477)
334
+ * { type: 'key_exchange_ok', publicKey } — server's ephemeral X25519 public key (E2E encryption)
335
+ * { type: 'auth_bootstrap', providers, slashCommands, agents, sessionId?, tunnelUrl? } — #5555: connect-time burst folding the provider/slash-command/agent lists so a new client skips its 3-request list_* round trip; tunnelUrl re-advertises the live public URL (sub-item 7)
336
+ * { type: 'tunnel_url_changed', url, previousUrl? } — #5555 (sub-item 7): quick-tunnel recovery rotated the public URL; clients repoint their stored endpoint. Best-effort for tunnel-connected clients (their socket rode the now-dead old tunnel); durable recovery is auth_bootstrap.tunnelUrl on reconnect
337
+ * { type: 'auth_fail', reason: '...' } — auth failed
338
+ * { type: 'server_mode', mode: 'cli' } — which backend mode is active
339
+ * { type: 'message', ... } — parsed chat message
340
+ * { type: 'stream_start', messageId: '...' } — beginning of streaming response
341
+ * { type: 'stream_delta', messageId, delta } — token-by-token text
342
+ * { type: 'stream_end', messageId: '...' } — streaming response complete
343
+ * { type: 'terminal_output', sessionId, data } — #5835 live claude-tui PTY mirror (raw, ANSI-intact, coalesced ~50ms); emitted from ws-forwarding.js to clients that opted in via terminal_subscribe; the remote-viewer / authenticity surface
344
+ * { type: 'terminal_size', sessionId, cols, rows } — #5835 Phase 2 authoritative live-PTY grid size; sent to a client on terminal_subscribe and broadcast to all terminal subscribers on a primary-driven terminal_resize so observers re-letterbox to the same grid
345
+ * { type: 'tool_start', messageId, toolUseId, tool, input, serverName? } — tool invocation (serverName present for MCP tools)
346
+ * { type: 'tool_input_delta', messageId, toolUseId, partialJson } — #4080/#4081: incremental partial JSON for the streaming tool_use `input`; concatenate per-toolUseId for the live bubble preview
347
+ * { type: 'tool_result', toolUseId, result, truncated, images? } — tool result (images: [{mediaType, data}])
348
+ * { type: 'mcp_servers', servers: [{ name, status }] } — connected MCP servers
349
+ * { type: 'result', ... } — query stats
350
+ * { type: 'status', connected: true } — connection status
351
+ * { type: 'claude_ready' } — Claude Code ready for input
352
+ * { type: 'model_changed', model: '...' } — active model updated
353
+ * { type: 'available_models', models: [...], provider?, defaultModel? } — models the active provider accepts
354
+ * { type: 'permission_input', requestId, found, tool?, input?, error? } — #6543 (IDE P3 feature B) reply to a `get_permission_input` pull: the FULL secret-redacted tool input for a pending permission (the `permission_request` broadcast truncates `input` at ~10K), so a client can build a per-hunk pre-write diff. `found:false` (+ `error`) when the request is unknown / already resolved / owned by another session — the handler is session-bound (a client only gets input for a permission its session owns).
355
+ * { type: 'permission_request', requestId, tool, description, input, remainingMs } — permission prompt
356
+ * { type: 'confirm_permission_mode', mode, warning } — server challenges auto mode (client must re-send with confirmed: true)
357
+ * { type: 'permission_mode_changed', mode: '...' } — permission mode updated
358
+ * { type: 'available_permission_modes', modes: [...] } — permission modes
359
+ * { type: 'session_list', sessions: [...] } — all sessions
360
+ * { type: 'session_switched', sessionId, name, cwd, conversationId?, sessionPreset? } — switched active session. On a fresh create-confirm `sessionPreset` (#5553) discloses the resolved per-repo preset (length-only preamble — the text is already folded into the prompt server-side — plus the seed staged editable into the composer + trust metadata); omitted when the session has no preset.
361
+ * { type: 'session_created', sessionId, name } — new session created
362
+ * { type: 'session_destroyed', sessionId } — session removed
363
+ * { type: 'session_stopped', sessionId?, code? } — user-initiated Stop confirmation (#4756); CliSession emitted `stopped` after a clean SIGINT exit; pairs with the louder `session_error` crash toast
364
+ * { type: 'session_restore_failed', sessionId, name, provider, cwd?, model?, permissionMode?, errorCode, errorMessage, originalHistoryPreserved, historyLength? }
365
+ * — session in persisted state could not be restored (e.g. missing env var); history kept on disk for retry
366
+ * { type: 'session_persist_failed', sessionId, name|null }
367
+ * — a session-list mutation (create/rename/destroy) could not be flushed to disk and will be lost on restart (#5714).
368
+ * `name` is null on the destroy path where the entry was already removed before the flush.
369
+ * { type: 'session_error', message, category?, sessionId?, recoverable? } — session operation error
370
+ * { type: 'history_replay_start', sessionId, fullHistory?, truncated? } — beginning of history replay
371
+ * { type: 'history_replay_end', sessionId } — end of history replay
372
+ * { type: 'conversation_id', sessionId, conversationId } — SDK conversation ID for session portability
373
+ * { type: 'user_question', toolUseId, questions } — AskUserQuestion prompt from Claude
374
+ * { type: 'agent_busy' } — agent started processing (per-session)
375
+ * { type: 'agent_idle' } — agent finished processing (per-session)
376
+ * { type: 'plan_started' } — Claude entered plan mode (transient)
377
+ * { type: 'plan_ready', allowedPrompts } — plan complete, awaiting approval (transient)
378
+ * { type: 'inactivity_warning', messageId, idleMs, prefab } — soft check-in prompt, session stays alive (#3899)
379
+ * { type: 'multi_question_intervention', toolUseId, questionCount, reason, timestamp } — chroxy permission-hook denied a multi-question AskUserQuestion (#4653)
380
+ * { type: 'server_shutdown', reason, restartEtaMs } — server shutting down (reason: 'restart'|'shutdown')
381
+ * { type: 'server_status', message } — non-error status update (e.g., recovery)
382
+ * { type: 'server_error', category, message, recoverable, sessionId? } — server-side error forwarded to app
383
+ * { type: 'directory_listing', path, parentPath, entries, error } — directory listing response for file browser
384
+ * { type: 'file_listing', path, parentPath, entries, error } — file browser listing response
385
+ * { type: 'file_content', path, content, language, size, truncated, error } — file content response
386
+ * { type: 'symbols_snapshot', path, symbols: [{ name, kind, file, line, exported }], truncated, error } — #6471 workspace symbol table (opt-in IDE, features.ide; dashboard-only v1)
387
+ * { type: 'symbol_location', symbol, file, line, error } — #6475 go-to-definition result (opt-in IDE, features.ide; dashboard-only v1)
388
+ * { type: 'code_search_results', query, results: [{ file, line, column, text }], truncated, error } — #6474 find-in-project results (opt-in IDE, features.ide; dashboard-only v1)
389
+ * { type: 'references_result', symbol, results: [{ file, line, column, text }], truncated, error } — #6477 find-all-references results (opt-in IDE, features.ide; dashboard-only v1)
390
+ * { type: 'slash_commands', commands: [{ name, description, source }] } — available slash commands
391
+ * { type: 'agent_list', agents: [{ name, description, source }] } — available custom agents
392
+ * { type: 'client_joined', client: { clientId, deviceName, deviceType, platform } } — new client connected
393
+ * { type: 'client_left', clientId } — client disconnected
394
+ * { type: 'client_focus_changed', clientId, sessionId, timestamp } — another client changed session focus
395
+ * { type: 'checkpoint_created', sessionId, checkpoint } — checkpoint created (auto or manual)
396
+ * { type: 'checkpoint_list', sessionId, checkpoints } — list of checkpoints
397
+ * { type: 'checkpoint_restored', checkpointId, newSessionId, name } — checkpoint restored (new session created)
398
+ * { type: 'primary_changed', sessionId, clientId } — last-writer-wins primary changed (null on disconnect)
399
+ * { type: 'session_role', sessionId, primaryClientId } — #5589/#5281: explicit primary-ownership; client derives its role (primary iff primaryClientId === own clientId, observer if another holds it, null = unclaimed)
400
+ * { type: 'pong' } — heartbeat response
401
+ * { type: 'permission_expired', requestId, sessionId, message } — permission response could not be routed (expired/handled)
402
+ * { type: 'token_rotated', token?, expiresAt, reason? } — API token changed. Scheduled rotation carries the new `token` to encrypted clients (transparent re-key, sessions survive). A `reason: 'revoke'` (#6006) carries NO token: the operator revoked, so the server severed user-shell sessions and cleared this connection's auth — the client must re-authenticate with the current token (obtained out-of-band).
403
+ * { type: 'session_warning', sessionId, name, reason, message, remainingMs } — session about to timeout
404
+ * { type: 'session_timeout', sessionId, name, idleMs } — session destroyed due to idle timeout
405
+ * { type: 'dev_preview', port, url, sessionId } — dev server preview tunnel opened
406
+ * { type: 'dev_preview_stopped', port, sessionId } — dev server preview tunnel closed
407
+ * { type: 'web_task_created', task } — cloud task launched
408
+ * { type: 'web_task_updated', task } — cloud task status changed
409
+ * { type: 'web_task_error', taskId?, message, code?, boundSessionId?, boundSessionName? } — cloud task error
410
+ * (code may carry SESSION_TOKEN_MISMATCH or other web-task codes
411
+ * e.g. WEB_TASK_PROMPT_TOO_LARGE; boundSessionId/boundSessionName
412
+ * are populated on SESSION_TOKEN_MISMATCH only;
413
+ * see docs/error-taxonomy.md)
414
+ * { type: 'web_task_list', tasks } — response to list_web_tasks
415
+ * { type: 'diff_result', diff, error? } — git diff result
416
+ * { type: 'error', message } — general error message
417
+ * { type: 'file_list', path, files, error? } — file listing response
418
+ * { type: 'git_branches_result', branches, current, error? } — git branches result
419
+ * { type: 'git_commit_result', success, hash?, error? } — git commit result
420
+ * { type: 'git_stage_result', success, error? } — git stage result
421
+ * { type: 'git_status_result', status, error? } — git status result
422
+ * { type: 'git_unstage_result', success, error? } — git unstage result
423
+ * { type: 'write_file_result', success, error? } — write file result
424
+ * { type: 'log_entry', level, message, timestamp } — server log entry for dashboard
425
+ * { type: 'session_activity', sessionId, isBusy, lastCost } — session busy/idle state change
426
+ * { type: 'session_context', sessionId, cwd, conversationId?, ... } — session context data
427
+ * { type: 'session_updated', sessionId, name } — session metadata updated
428
+ * { type: 'discovered_sessions', sessions } — discovered local Claude sessions
429
+ * { type: 'pair_fail', reason } — pairing failed
430
+ * { type: 'pairing_refreshed' } — pairing ID consumed; clients should re-fetch /qr (#2916)
431
+ * { type: 'pair_request_pending', requestId, verifyCode } — pairing-approval primitive (#5510, epic #5509): ack to the camera-less requester carrying the 6-digit code to DISPLAY. Sent only over the requester's own pre-auth connection; the code travels server→requester only and is never echoed back.
432
+ * { type: 'pair_pending', requestId, deviceName, verifyCode, expiresAt } — pairing-approval fan-out (#5510) to HOST-LEVEL (unbound) surfaces only; carries the verify code to COMPARE and the attacker-controlled (schema-capped, plain-text) deviceName. Bound/session-scoped clients never receive it.
433
+ * { type: 'pair_result', requestId, ok, token?, reason? } — pairing-approval terminal result (#5510) to the requester over its still-open connection. On approve `ok: true` + the unbound (host-authority) session token, delivered exactly once and never logged; on deny/expire/disconnect `ok: false` + reason.
434
+ * { type: 'pair_resolved', requestId, reason } — pairing-approval retraction (#5510) to host-level surfaces so every banner drops a request that was approved/denied/expired/disconnected elsewhere.
435
+ * { type: 'rate_limited', message } — client rate-limited
436
+ * { type: 'agent_spawned', sessionId, agentId, parentToolId, model } — background agent spawned
437
+ * { type: 'agent_completed', sessionId, agentId, parentToolId } — background agent completed
438
+ * { type: 'agent_event', sessionId, parentToolUseId, eventType, payload } — Task subagent intermediate wire event re-emit (#5016, transient; eventType is one of `tool_start` / `tool_input_delta` / `tool_result` / `stream_delta`)
439
+ * { type: 'background_work_changed', sessionId, pending } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`)
440
+ * { type: 'shell_pending_approval', approvalId, hint? } — #6277 host-local user-shell approval: a requested user-shell spawn is HELD pending the host operator's out-of-band approval (`chroxy shell approve <id>`). Informational; dashboard-only banner for v1. The normal `session_switched` confirms on approval, a `session_error` (SHELL_APPROVAL_DENIED) on deny.
441
+ * { type: 'activity_snapshot', sessionId, schemaVersion, entries } — Control Room full activity tree for a session, on subscribe/resync (#5161 schema; emitter #5160; `entries: [{ id, kind, label, status, startedAt, endedAt?, parentId?, outputRef? }, …]`)
442
+ * { type: 'activity_delta', sessionId, schemaVersion, op, entry } — Control Room incremental activity-entry change (#5161 schema; emitter #5160; `op` is one of `started` / `updated` / `ended`; `entry` is the full node)
443
+ * { type: 'message_queued', sessionId, clientMessageId?, text, queueLength } — a send-while-busy follow-up entered the server's outgoing-message queue (#5936/#5937, transient; mirrors `_outgoingQueue`)
444
+ * { type: 'message_dequeued', sessionId, clientMessageId?, queueLength, reason } — a queued follow-up left the queue (#5936/#5937/#5943, transient; `reason` is `flush` (auto-sent on turn-complete), `interrupted` (whole queue cancelled by a Stop), or `cancelled` (one item cancelled via `cancel_queued`))
445
+ * { type: 'host_status_snapshot', requestId?, generatedAt, root, summary, repos, error? } — Control Room Host/Repo Status survey reply (#5171 schema; emitter #5174); reply to a `host_status_request`. Always carries the full snapshot shape (so it is protocol-schema-valid); on failure `repos` is empty, `summary` is zeroed, and an additive `error: { code, message }` annotation is present for the consumer to branch on. `requestId` echoes the request when provided.
446
+ * { type: 'runner_status_snapshot', requestId?, generatedAt, root, summary, repos, error? } — Control Room self-hosted runner survey reply (#5253 schema + emitter); reply to a `runner_status_request`. Same degraded-snapshot-with-`error` posture as `host_status_snapshot`: always the full shape; on failure `repos` is empty, `summary` is zeroed, and an additive `error: { code, message }` is present. `requestId` echoes the request when provided.
447
+ * { type: 'containers_status_snapshot', requestId?, generatedAt, summary, containers, dockerStatsNote?, error? } — Control Room containers & environments survey reply (#6133 schema + emitter, epic #5530); reply to a `containers_status_request`. Flat `containers` array of chroxy-managed environments (id, name, cwd, image, status, backend, sessionCount, uptimeMs, best-effort `docker stats`); `dockerStatsNote` is set when the stats enrichment was unavailable (every entry's `stats` then null). Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
448
+ * { type: 'repo_runtime_config_snapshot', requestId?, generatedAt, backend, backendSource, isolation, allowlist, repos, summary, error? } — Control Room per-repo runtime config survey reply (#6139, epic #5530); reply to a `repo_runtime_config_request`. Read-only. Host-level defaults (effective `backend` + its `backendSource`, `isolation` order, effective image `allowlist`) plus a per-repo array (devcontainer/compose presence, the image it would run + the allowlist verdict). Same degraded-snapshot-with-`error` posture as the host/runner/containers surveys. `requestId` echoes the request when provided.
449
+ * { type: 'byok_pool_status_snapshot', requestId?, generatedAt, enabled, note, limits, stats, error? } — Control Room BYOK container-pool stats survey reply (#6135, epic #5530); reply to a `byok_pool_status_request`. Read-only. `enabled:false` (with `note`, null limits/stats) is a first-class state — the pool is off by default. When enabled: `limits` (idle TTL / per-key / total / max-age caps) + `stats` (hits/misses/releases/evictions-by-reason + per-key warm buckets + a recent-evictions tail). Same degraded-snapshot-with-`error` posture as the sibling surveys. `requestId` echoes the request when provided.
450
+ * { type: 'host_prune_status_snapshot', requestId?, generatedAt, dockerAvailable, note, containers, images, summary, error? } — Control Room host prune guardrails survey reply (#6140, epic #5530); reply to a `host_prune_status_request`. Read-only. Reclaimable, chroxy-scoped, ORPHAN-ONLY docker pressure: stopped `chroxy-env-*` containers + chroxy snapshot images (`chroxy-env`/`chroxy-byok-snap`) NOT tracked by a live env, with per-resource sizes + a `summary` (counts + estimated reclaimableBytes). `dockerAvailable:false` (with `note`, empty lists) is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
451
+ * { type: 'host_prune_action_ack', kind, requestId?, dockerAvailable, removedContainers, removedImages, reclaimedBytes, failures } — Control Room host prune action ack (#6140, epic #5530); reply to a successful `host_prune_action` (kind containers/images/all). The server re-surveys the chroxy-scoped orphan set and removes only those ids; the ack carries removed counts, estimated `reclaimedBytes`, and a `failures` list (resources whose `docker rm`/`rmi` failed). Failures to start surface as a HOST_PRUNE_ACTION_FAILED `session_error` echoing `kind`/`requestId`.
452
+ * { type: 'simulator_status_snapshot', requestId?, generatedAt, available, note, devices, readyForMaestro, error? } — Control Room iOS simulator survey reply (#6136, epic #5530); reply to a `simulator_status_request`. Read-only. `devices` is the `xcrun simctl list devices` inventory (udid/name/state/runtime/deviceType); `readyForMaestro` is the composite verdict (booted sim + Metro :8081 + mock-server :9876 reachable, with `reasons[]`). `available:false` (with `note`, empty devices) off macOS / no xcrun is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
453
+ * { type: 'emulator_status_snapshot', requestId?, generatedAt, available, note, devices, readyForMaestro, error? } — Control Room Android emulator survey reply (#6137, epic #5530); reply to an `emulator_status_request`. Read-only. `devices` joins `emulator -list-avds` with `adb devices` (avd/serial/state: running|stopped); `readyForMaestro` is the composite verdict (running emulator + Metro :8081 + mock-server :9876 reachable, with `reasons[]`). `available:false` (with `note`, empty devices) with no Android SDK is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
454
+ * { type: 'emulator_action_ack', action, avd?, serial?, requestId?, status } — Control Room Android emulator action ack (#6137, epic #5530); reply to a successful `emulator_action` (boot/kill). The server re-surveys, validates the target (boot → a stopped `avd`, kill → a running `serial`) + state-gates it, runs `emulator -avd` (detached) / `adb emu kill`, and echoes `action` + the relevant `avd`/`serial` (+ `requestId`) plus the resulting `status` ("starting"/"killed"). Failures surface as an EMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
455
+ * { type: 'wsl_status_snapshot', requestId?, generatedAt, available, note, defaultDistro, distros, error? } — Control Room WSL2 distro survey reply (#6138, epic #5530); reply to a `wsl_status_request`. Read-only (Windows hosts). `distros` is the `wsl.exe -l -v` inventory (name/state/version/isDefault); `defaultDistro` names the `*`-marked default. `available:false` (with `note`, empty distros) off Windows / no wsl.exe is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
456
+ * { type: 'wsl_action_ack', action, distro, requestId?, status } — Control Room WSL2 action ack (#6138, epic #5530); reply to a successful `wsl_action` (start/terminate). The server re-surveys `wsl.exe -l -v`, validates the `distro` is enumerated + state-gated (start a non-running distro, terminate a running one), runs `wsl.exe -d <distro> -e true` / `wsl.exe --terminate <distro>`, and echoes `action`/`distro` (+ `requestId`) plus the resulting `status` ("running"/"stopped"). Failures surface as a WSL_ACTION_FAILED `session_error` echoing the same correlation fields.
457
+ * { type: 'integration_status_snapshot', requestId?, generatedAt, root, summary, repos, repoMemoryCli?, error? } — Control Room Integrations survey reply (#5499 schema + emitter, epic #5498); reply to an `integration_status_request`. Per-repo repo-memory status (config, cache stats, telemetry report); `repoMemoryCli` notes the once-per-snapshot binary probe. Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
458
+ * { type: 'containers_action_ack', action, environmentId, requestId?, status? } — Control Room container lifecycle action ack (#6134, epic #5530); reply to a successful `containers_action` (stop/restart/destroy). Echoes `action`/`environmentId` (+ `requestId` when provided) and carries the resulting `status` (stopped/running/destroyed). Failures surface as a CONTAINER_ACTION_FAILED `session_error` echoing the same correlation fields.
459
+ * { type: 'byok_pool_action_ack', action, requestId?, key?, drained?, evicted?, limits?, configured? } — Control Room BYOK pool mutating action ack (#6135 slice 2, epic #5530); reply to a successful `byok_pool_action` (drain/recycle/resize). Echoes `action` (+ `requestId`/`key` when provided) and carries the result: `drained` (containers evicted by drain/recycle), `evicted` (containers evicted to honor a tightened resize), `limits` (new effective caps after resize), `configured` (the operator-configured cap ceiling resize clamps to). Failures surface as a BYOK_POOL_ACTION_FAILED `session_error` echoing the same correlation fields.
460
+ * { type: 'simulator_action_ack', action, udid, requestId?, status } — Control Room iOS simulator action ack (#6136 slice 2, epic #5530); reply to a successful `simulator_action` (boot/shutdown). The server re-surveys `xcrun simctl list devices`, validates the `udid` is enumerated + state-gated (boot a non-booted device, shutdown a booted one), runs `simctl <action> <udid>`, and echoes `action`/`udid` (+ `requestId` when provided) plus the resulting `status` ("Booted"/"Shutdown"). Failures surface as a SIMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
461
+ * { type: 'integration_action_ack', action, repoPath, requestId?, counts } — Control Room Integrations action ack (#5500, epic #5498); reply to a successful `integration_action` (currently `repo_memory_reindex`). Echoes `action`/`repoPath` (+ `requestId` when provided) cloning the cancel_activity_ack correlation contract; `counts` carries the parsed scanned/summarized/fresh/skipped index result, or null when the CLI output was unparseable. Failures surface as an INTEGRATION_ACTION_FAILED `session_error` echoing the same correlation fields.
462
+ * { type: 'skills_inventory_snapshot', requestId?, generatedAt, root, global, globalError?, repos, error? } — Control Room Skills inventory survey reply (#5554 schema + emitter, epic #5159); reply to a `skills_inventory_request`. `global` is the `~/.chroxy/skills/` tier and `repos` the per-repo `.chroxy/skills/` overlays, each entry carrying name/description/activation/trust/hash/installed + usage (lastUsed/count/repos). Skill BODIES never leave the server. Same degraded-snapshot-with-`error` posture as the host/runner/integration surveys; `globalError` / per-repo `error` degrade a single tier without blanking the snapshot. `requestId` echoes the request when provided.
463
+ * { type: 'mailbox_status_snapshot', requestId?, generatedAt, registrations, recentEvents, error? } — Control Room "Mailbox" tab survey reply (#5914 follow-up); reply to a `mailbox_status_request`. `registrations` is the live agentCommId→session map (each with sessionName/isBusy/isTui) and `recentEvents` a bounded newest-first ring buffer of recent live-interrupt deliveries (to/from/unreadCount/outcome). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
464
+ * { type: 'external_sessions_snapshot', requestId?, generatedAt, sessions, error? } — Control Room mission-control external-session survey reply (#5969, epic #5422 phase 4); reply to an `external_sessions_request`. `sessions` lists the LIVE external Claude Code sessions the daemon learned about over `POST /api/events` (#5413) — sessions it did NOT launch — each carrying source/sessionId/name/project/cwd, a read-only `status` ('running'|'idle'), active `subagents`, and `lastActivityTs`. Read-only (no PTY/control handle exists for these). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
465
+ * { type: 'repo_events_delta', generatedAt, event } — Control Room repo-events LIVE delta (#6536, PR-2 of #5966); server-INITIATED (no request) push of a single newly-buffered repo-event when a GitHub webhook delivery lands, so the pane updates without a Refresh. Host-level: broadcast ONLY to unbound (host-authority) clients — a session-bound (share-a-session) token never receives host repo activity. A client that hasn't run the survey ignores it; a client with a snapshot appends the event (bounded). No `error`/`requestId` — degraded surveys still flow through the pull `repo_events_snapshot`.
466
+ * { type: 'repo_events_snapshot', requestId?, generatedAt, events, error? } — Control Room repo-events survey reply (#5966, epic #5422 phase 5); reply to a `repo_events_request`. `events` is the tail (most-recent-last) of the daemon's bounded RepoEventStore — GitHub-webhook activity (push/pull_request/issues/ping) ingested HMAC-verified over `POST /api/github/webhook` (#6468) — each carrying kind/repo/actor/at plus kind-specific branch/action/number/title/url and a pre-rendered `summary`. Read-only; no delta stream (a full snapshot per pull, like the host/mailbox/external surveys). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
467
+ * { type: 'summarize_session_result', sessionId, summary, truncated?, requestId? } — reply to a `summarize_session` (#5547); the model-written continuation brief built from the session's persisted history, seeded editable into the dashboard's create-session composer. `truncated` flags a windowed history. Failures surface as a SUMMARIZE_FAILED `session_error` echoing `sessionId`/`requestId` (curated message — no token/key material).
468
+ * { type: 'session_preset_snapshot', cwd, preset: { source, active, trustState, enabled, preamble, seed, preambleLength, seedLength, capped, repoPath } | null, requestId? } — Control Room per-repo session-preset reply (#5553, epic #5159); reply to a host-authority `session_preset_get` / `session_preset_set` / `session_preset_approve` / `session_preset_revoke`. `preset` is null when the repo has no preset. Full preamble + seed text reaches HOST-level clients only (the four requests are rejected for session-bound pairing clients). `requestId` echoes the request when provided.
469
+ * { type: 'provider_list', providers } — available providers
470
+ * { type: 'byok_credentials_status', requestId?, status, source, masked?, reason? } — BYOK credentials state for the dashboard (#4052)
471
+ * { type: 'credentials_status', requestId?, credentials: [{ key, provider, label, kind, status, source, masked?, oauth }], fileExists?, fileError? } — generalized provider-credential status for the dashboard (#3855); masked, value-free; sent to requester + broadcast after set/delete
472
+ * { type: 'credential_test_result', requestId?, key, ok, error?, model?, latencyMs? } — result of a test_credential ping (#3855)
473
+ * { type: 'notification_prefs', requestId?, prefs: { categories, devices, quietHours } } — current notification preferences snapshot (#4541/#4542); echoed back on `notification_prefs_get` and broadcast after every `notification_prefs_set`
474
+ * { type: 'skills_list', skills } — active skills (name, description, activation, active per entry)
475
+ * { type: 'skill_changed', skillName, sessionId, oldHashPrefix, newHashPrefix, mode } — skill content-hash mismatch (#3234, transient)
476
+ * { type: 'skill_activated', sessionId, skillName } — manual skill toggled on at runtime (#3209)
477
+ * { type: 'skill_deactivated', sessionId, skillName } — manual skill toggled off at runtime (#3209)
478
+ * { type: 'skill_trust_accepted', sessionId, skillName } — operator re-trusted a skill after hash mismatch (#3235)
479
+ * { type: 'skill_trust_request', skillName, author, source, description, path, sessionId } — community skill awaiting first-activation grant (#3297, transient)
480
+ * { type: 'skill_trust_granted', sessionId, skillName, author } — community skill trust granted (#3297)
481
+ * { type: 'skill_trust_grant_ok', requestId, sessionId, skillName, author } — ack for skill_trust_grant handler (#3297)
482
+ * { type: 'push_token_error', message } — push token registration error
483
+ * { type: 'cost_update', sessionId, sessionCost, totalCost, budget } — session cost update (budget-oriented; sessionId injected by _broadcastToSession)
484
+ * { type: 'session_usage', sessionId, cumulativeUsage } — per-session cumulative tokens + cost; cumulativeUsage = { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd, turnsBilled } (#4072)
485
+ * { type: 'session_cost_threshold_crossed', sessionId, costUsd, thresholdUsd } — soft "you've spent $X" warning; fires ONCE per session when cumulativeUsage.costUsd >= threshold (#4075)
486
+ * { type: 'budget_warning', sessionId, message, ... } — budget approaching limit
487
+ * { type: 'budget_exceeded', sessionId, message, ... } — budget exceeded
488
+ * { type: 'monthly_budget', month, spentUsd, budgetUsd, percent, warning, exceeded, ... } — machine-wide monthly programmatic-credit meter (#5665); broadcast to ALL clients after each programmatic-credit turn + sent once on connect
489
+ * { type: 'web_feature_status', features } — web feature availability
490
+ * { type: 'permission_rules_updated', rules } — per-session auto-approval rules changed
491
+ * { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
492
+ * { type: 'environment_created', environmentId, name, status } — environment created
493
+ * { type: 'environment_list', environments: [...] } — list of all environments
494
+ * { type: 'environment_destroyed', environmentId } — environment destroyed
495
+ * { type: 'environment_info', environment: {...} } — single environment details
496
+ * { type: 'environment_error', error, environmentId? } — environment operation error
497
+ * { type: 'evaluate_draft_result', requestId, verdict?, rewritten?, clarification?, reasoning?, error? } — prompt evaluator response (#3068)
498
+ * { type: 'prompt_evaluator_changed', sessionId, value: boolean } — per-session promptEvaluator toggle changed (#3185)
499
+ * { type: 'prompt_evaluator_skip_pattern_changed', sessionId, value: string|null } — per-session evaluator skip pattern changed (#3639)
500
+ * { type: 'chroxy_context_hint_changed', sessionId, value: boolean } — per-session Chroxy context hint toggle changed (#3805)
501
+ * { type: 'session_preamble_changed', sessionId, value: string } — per-session preamble changed (#4660)
502
+ * { type: 'evaluator_rewrite', sessionId, originalDraft, rewritten, reasoning, evaluatorIterationId } — auto-evaluator rewrite verdict broadcast (#3208 schema, #3186 emit, #3188 dashboard handler)
503
+ * { type: 'evaluator_clarify', sessionId, originalDraft, clarification, reasoning, evaluatorIterationId, evaluatorIteration } — auto-evaluator clarify verdict broadcast (#3208 schema, #3186 emit, #3188 dashboard handler)
504
+ * { type: 'stdin_dropped_totals', sessionId, bytes, count, reason, escalated } — cumulative SidecarProcess pre-dial-cap drop totals (#3544, transient)
505
+ *
506
+ * Encrypted envelope (bidirectional, wraps any message above after key exchange):
507
+ * { type: 'encrypted', d: '<base64 ciphertext>', n: <nonce counter> }
508
+ *
509
+ * ─────────────────────────────────────────────────────────────────────────────
510
+ * Error response taxonomy (see docs/error-taxonomy.md for the full contract)
511
+ * ─────────────────────────────────────────────────────────────────────────────
512
+ * The server emits three distinct error message types. Clients must handle all
513
+ * three, and handlers must pick the type that best matches the failure class.
514
+ * Do NOT rename or remove these types — existing clients depend on them.
515
+ *
516
+ * 1. { type: 'error', code, message, requestId?, correlationId?, details? }
517
+ * Transport / protocol / validation errors. Client-caused.
518
+ * Emitted for: invalid JSON, schema validation failures, auth failures.
519
+ * Sent by: ws-auth.js, ws-server._handleMessage (schema path), handler-utils.sendError.
520
+ * Client behavior: surface message, do not retry automatically.
521
+ *
522
+ * 2. { type: 'server_error', message, recoverable, correlationId?, category?, sessionId? }
523
+ * Server-side handler failure or unhandled exception. Not the client's fault.
524
+ * Emitted for: unhandled errors in _handleMessage, ws-broadcaster failures,
525
+ * repo listing failures, encryption key-exchange timeouts.
526
+ * `recoverable: true` — client may retry the request.
527
+ * `recoverable: false` — client should reconnect (fatal connection state).
528
+ * Sent by: ws-server._handleMessage (catch path), ws-history.js, ws-auth.js,
529
+ * ws-broadcaster.js, repo-handlers.js.
530
+ *
531
+ * 3. { type: 'session_error', message, sessionId?, code?, category?, recoverable? }
532
+ * Session-scoped operation error. Tied to a specific session or to the
533
+ * client's active session context (may be null when no session exists).
534
+ * Emitted for: session not found, session-token mismatch, input while paused,
535
+ * provider does not support feature, invalid session operation arguments,
536
+ * checkpoint/conversation/environment operation failures.
537
+ * Sent by: handlers/*-handlers.js via ctx.send.
538
+ * Client behavior: surface message, clear loading state for the session.
539
+ *
540
+ * Rule of thumb for handler authors:
541
+ * - The WS message was malformed or failed schema validation → `error`
542
+ * - The handler threw an unexpected exception → `server_error` (handled by outer catch)
543
+ * - A session operation failed in an expected, user-facing way → `session_error`
544
+ */
545
+ export class WsServer {
546
+ constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter } = {}) {
547
+ this.port = port
548
+ this.apiToken = apiToken
549
+ this._tokenManager = tokenManager || null
550
+ this._pairingManager = pairingManager || null
551
+ // #5536 — long-lived Ed25519 identity keypair. Its secret half signs each
552
+ // connection's ephemeral exchange public key (eager + discrete paths) so a
553
+ // pinned client can verify the exchange key came from this daemon. Null when
554
+ // pinning is unavailable — in that case the server signs nothing and the
555
+ // exchange stays TOFU (backward compatible: old clients never look for a sig).
556
+ this._serverIdentity = serverIdentity || null
557
+ // Runtime config object — exposed to handler dispatch so validators
558
+ // can read settings (e.g. workspaceRoots for cwd allowlist) at
559
+ // message time. May be null in tests that don't pass it through.
560
+ this.config = config || null
561
+ this._maxPayload = maxPayload || 10 * 1024 * 1024 // default 10MB (supports image/doc attachments)
562
+ this.authRequired = authRequired
563
+ this._encryptionEnabled = !noEncrypt
564
+ this._keyExchangeTimeoutMs = keyExchangeTimeoutMs ?? 10_000
565
+ this._localhostBypass = localhostBypass ?? true
566
+ this._maxPendingConnections = maxPendingConnections ?? 20
567
+ // #5356 (visibility layer): exposure snapshot surfaced in auth_ok so the
568
+ // dashboard can warn about non-loopback binds / public quick tunnels.
569
+ // _boundHost is set in start(); _quickTunnelActive by server-cli when a
570
+ // quick (trycloudflare) tunnel is configured.
571
+ this._boundHost = undefined
572
+ this._quickTunnelActive = false
573
+ // #5555 (sub-item 7): the server's current public tunnel URL as a `wss://`
574
+ // endpoint, set by server-cli once the tunnel is up and updated on a
575
+ // quick-tunnel URL rotation. Surfaced in the auth_bootstrap burst so a
576
+ // reconnecting client always re-learns the live URL. `null` for LAN /
577
+ // no-tunnel deployments.
578
+ this._tunnelUrl = null
579
+ this._backpressureThreshold = backpressureThreshold ?? 1024 * 1024 // 1MB default
580
+ this._backpressureMaxDrops = 10 // close connection after this many consecutive drops
581
+ // #3996: name each limiter so eviction logs and /diagnostics
582
+ // rateLimiters[].name can identify which one is shedding entries.
583
+ this._rateLimiter = new RateLimiter({ name: 'ws' })
584
+ // Separate, relaxed limiter for permission/question responses (60 per minute, no burst)
585
+ this._permissionRateLimiter = new RateLimiter({ name: 'permission', windowMs: 60_000, maxMessages: 60, burst: 0 })
586
+ // #6551: dedicated limiter for get_permission_input (the pre-write-diff pull).
587
+ // Each pull can return up to 512K, so it's TIGHTER than the general limiter
588
+ // (30/min + 10 burst vs 100 + 20) to bound cost/egress amplification — a
589
+ // legit diff-review UI pulls at most once per permission prompt, so 40
590
+ // effective/min is generous while capping a self-DoS from one client hammering
591
+ // one requestId.
592
+ this._permissionInputRateLimiter = new RateLimiter({ name: 'permission-input', windowMs: 60_000, maxMessages: 30, burst: 10 })
593
+ // #3737: per-IP limiter for GET /diagnostics. Default 12 req/min + 4 burst
594
+ // — half of /permission since the cost (FS read + session iteration) is
595
+ // comparable but legitimate use is diagnostic, not interactive. Override
596
+ // via constructor opt (tests) or `CHROXY_DIAGNOSTICS_RATE_LIMIT` (deploy:
597
+ // a single integer sets maxMessages, with a 1/3 burst).
598
+ this._diagnosticsRateLimiter = new RateLimiter(
599
+ { name: 'diagnostics', ...resolveDiagnosticsRateLimit(diagnosticsRateLimit) }
600
+ )
601
+ // #5683 — Chroxy Pages. Per-IP limiter for the public `/p/<slug>` route
602
+ // (assets + refreshes are more frequent than diagnostics, hence higher
603
+ // than /diagnostics but still bounded to blunt slug-scanning). The store is
604
+ // injectable for tests; the default is rooted at $CHROXY_CONFIG_DIR /
605
+ // ~/.chroxy/pages and only READS on construct (no sandbox write).
606
+ // Injectable so tests/deployments can override or DISABLE it (pass null).
607
+ // `!== undefined` (not ||/??) so an explicit null genuinely disables the
608
+ // limiter rather than falling back to the default.
609
+ this._pagesRateLimiter = pagesRateLimiter !== undefined
610
+ ? pagesRateLimiter
611
+ : new RateLimiter({ name: 'pages', windowMs: 60_000, maxMessages: 120, burst: 30 })
612
+ this.pagesStore = pagesStore || new PagesStore({
613
+ pagesDir: join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'pages'),
614
+ })
615
+ // #6277: host-local user-shell approval store. The create gate holds a spawn
616
+ // here when userShell.requireApproval is on; the host operator approves it
617
+ // out-of-band via the loopback /api/shell routes (or `chroxy shell approve`).
618
+ this._shellApprovalStore = new ShellApprovalStore()
619
+ this._clientSend = createClientSender(log)
620
+ // audit P1-2: when a client's active session changes, re-sync the live
621
+ // terminal mirror gate for BOTH the session it left and the one it joined.
622
+ // Without this a client opted into session A's terminal that switches to B
623
+ // would fall out of A's delivery filter while A's coalescer kept running to
624
+ // nobody (the waste #5837/#5844 set out to kill). _syncTerminalMirror
625
+ // no-ops on a null id, so passing prev=null is safe.
626
+ this._clientManager = new WsClientManager({
627
+ onActiveSessionChanged: (_client, prev, next) => {
628
+ this._syncTerminalMirror(prev)
629
+ this._syncTerminalMirror(next)
630
+ },
631
+ })
632
+ this.clients = this._clientManager.clients // back-compat: expose the raw Map for context objects
633
+ // #4835: per-device active-session memory. Caller can inject a custom
634
+ // store (tests do this with a tmp file path); otherwise we construct
635
+ // the default disk-backed store rooted at $CHROXY_CONFIG_DIR /
636
+ // ~/.chroxy. The store is consumed by ws-history.sendPostAuthInfo on
637
+ // reconnect and updated by session-handlers.handleSwitchSession after
638
+ // every explicit switch.
639
+ this._devicePreferences = devicePreferences || createDevicePreferences()
640
+ // #5821: provider for the current billing-canary snapshot, wired by
641
+ // server-cli after the monitor is constructed (the monitor depends on this
642
+ // WsServer's broadcast, so it's created after — set the provider here once
643
+ // it exists). null = no seed (older boot / tests); the ctx getter folds this in.
644
+ this._billingCanaryProvider = null
645
+ // #4849: lazy startup prune. server-cli calls sessionManager.restoreState()
646
+ // before constructing the WsServer, so any device-pref entry whose
647
+ // activeSessionId is missing here is genuinely orphaned (a session
648
+ // destroyed in a previous run, or one rotated out by the user). The
649
+ // grace window guards against the rare path where restoreState
650
+ // intentionally skipped a session (e.g. corrupted state). prune is a
651
+ // no-op when the device list is empty, so the disk-I/O cost is zero
652
+ // for first-run installs and for users who never connected from
653
+ // ephemeral devices. Threshold env vars:
654
+ // - CHROXY_DEVICE_PREFS_MAX_AGE_MS — hard age cap (default 90d)
655
+ // - CHROXY_DEVICE_PREFS_STALE_GRACE_MS — stale-session grace (default 30d)
656
+ // Both can be set to 0 to disable. See #4849.
657
+ if (sessionManager && typeof this._devicePreferences.prune === 'function') {
658
+ try {
659
+ const maxAgeMs = parseDevicePrefsDuration(
660
+ process.env.CHROXY_DEVICE_PREFS_MAX_AGE_MS,
661
+ 90 * 24 * 60 * 60 * 1000,
662
+ )
663
+ const staleGraceMs = parseDevicePrefsDuration(
664
+ process.env.CHROXY_DEVICE_PREFS_STALE_GRACE_MS,
665
+ 30 * 24 * 60 * 60 * 1000,
666
+ )
667
+ // Only enable stale-session pruning when SessionManager actually
668
+ // exposes getSession. With optional chaining, `getSession?.(id)`
669
+ // silently returns undefined when the method is missing — every
670
+ // session would look "stale" and the prune would evict everything
671
+ // past the grace window. Belt-and-braces: when the predicate is
672
+ // omitted, prune() skips the stale-session arm and only the
673
+ // age-based cap (if any) applies.
674
+ const pruneOpts = {
675
+ maxAgeMs,
676
+ staleSessionGraceMs: staleGraceMs,
677
+ }
678
+ if (typeof sessionManager.getSession === 'function') {
679
+ pruneOpts.sessionExists = (id) => !!sessionManager.getSession(id)
680
+ }
681
+ this._devicePreferences.prune(pruneOpts)
682
+ } catch (err) {
683
+ // A prune failure must never block server startup — the next mutation
684
+ // will reload the file anyway, and the worst case is a slightly
685
+ // larger preferences file.
686
+ log.warn(`device-preferences startup prune failed: ${err.message}`)
687
+ }
688
+ }
689
+ this.httpServer = null
690
+ this.wss = null
691
+ this._pingInterval = null
692
+ this._pendingPermissions = new Map() // requestId -> { resolve, timer }
693
+ // #3637: per-session auto-evaluator iteration counter for the clarify
694
+ // loop cap (#3186). Lives on the WsServer (not per-message-ctx)
695
+ // because handler ctx is spread fresh on every dispatch — without a
696
+ // stable home the counter would reset on every message and the cap
697
+ // would never fire in production. Cleaned up by `_sessionDestroyedHandler`
698
+ // so a long-running server doesn't leak entries for destroyed sessions.
699
+ this._evaluatorIterations = new Map() // sessionId -> iteration count
700
+ this._permissionSessionMap = new Map() // requestId -> sessionId (for routing responses to correct session)
701
+ // #5704: refcount of permission-INDUCED session subscriptions, per client.
702
+ // clientId -> Map<sessionId, refcount>. _registerPermissionRoute increments
703
+ // it for a new route's auto-subscribe UNLESS that subscription is explicitly
704
+ // owned (the client holds it with refcount 0) — so a permission can never
705
+ // "steal ownership" of an explicit subscription, while a second concurrent
706
+ // permission on an already permission-owned session does count up;
707
+ // _unregisterPermissionRoute (wired to every resolve/expire/cleanup site)
708
+ // decrements it and tears the auto-subscription back down when the count
709
+ // hits zero AND the client is neither active on nor explicitly subscribed to
710
+ // the session. An explicit switch_session/subscribe_sessions ADOPTS the
711
+ // subscription by zeroing this refcount (see _adoptPermissionSubscription),
712
+ // so permission teardown never unsubscribes a client that asked to watch.
713
+ this._permissionSubs = new Map() // clientId -> Map<sessionId, refcount>
714
+ this._hookSecrets = new Set() // per-session hook secrets registered by active CliSessions
715
+ this._sessionHookSecrets = new Map() // sessionId -> hookSecret (for cleanup on session_destroyed)
716
+ this._questionSessionMap = new Map() // toolUseId -> sessionId (for routing question responses)
717
+ // #5563: primary-ownership now lives on the WsClientManager (sessionId →
718
+ // primary clientId) with explicit claim/observe/hand-off semantics, not a
719
+ // last-writer-wins map. `primaryClients` is no longer a server-owned Map;
720
+ // handlers query it through ctx.transport.getPrimary / isPrimary / claim /
721
+ // clear helpers below.
722
+ // #5510: pairing-approval primitive — requestId → requester ws. The
723
+ // requester's WS stays open (pre-auth) after pair_request; on approve/deny/
724
+ // expire/disconnect we look it up here to deliver `pair_result`. Bounded by
725
+ // the PairingManager queue cap; cleaned up on resolution and on disconnect.
726
+ this._pairRequesters = new Map() // requestId -> ws
727
+ // Late-binding wrappers: allows tests to monkey-patch _send/_broadcast
728
+ const self = this
729
+ const sendFn = (ws, msg) => self._send(ws, msg)
730
+ this._broadcaster = new WsBroadcaster({
731
+ clients: this.clients,
732
+ // #5563: share the reverse index owner so session broadcasts + subscriber
733
+ // counts iterate the sessionId→clients index instead of scanning all clients.
734
+ clientManager: this._clientManager,
735
+ sendFn,
736
+ backpressureThreshold: this._backpressureThreshold,
737
+ backpressureMaxDrops: this._backpressureMaxDrops,
738
+ })
739
+ const broadcastFn = (msg, filter) => self._broadcast(msg, filter)
740
+ // Pass explicit workspace root so file ops resolve paths against the
741
+ // session manager's default cwd instead of falling back to homedir.
742
+ const workspaceRoot = sessionManager?.defaultCwd || process.cwd()
743
+ this._fileOps = createFileOps(sendFn, workspaceRoot)
744
+ this._permissions = createPermissionHandler({
745
+ sendFn,
746
+ broadcastFn,
747
+ validateBearerAuth: (req, res) => self._validateBearerAuth(req, res),
748
+ validateHookAuth: (req, res) => self._validateHookAuth(req, res),
749
+ pushManager,
750
+ pendingPermissions: this._pendingPermissions,
751
+ permissionSessionMap: this._permissionSessionMap,
752
+ // #4798: same auto-subscribe helper used by ws-forwarding's dispatch
753
+ // path. Hook-originated HTTP permission requests also need to seed
754
+ // subscribedSessionIds on connected viewers so the settings-handler
755
+ // subscription guard accepts the legitimate response.
756
+ registerPermissionRoute: (requestId, sessionId) => self._registerPermissionRoute(requestId, sessionId),
757
+ // #5704: tear down the permission-induced subscription refcount in lockstep
758
+ // with the map entry on every resolve / expire / cleanup / drain / destroy.
759
+ unregisterPermissionRoute: (requestId) => self._unregisterPermissionRoute(requestId),
760
+ getSessionManager: () => self.sessionManager,
761
+ // Pass pairingManager so the HTTP /permission-response fallback can
762
+ // enforce session binding — see 2026-04-11 audit blocker 5.
763
+ pairingManager: this._pairingManager,
764
+ // #2831: let the permission handler tell a CliSession that a hook
765
+ // permission belonging to it is outstanding so the session's
766
+ // 5-min inactivity timer can pause until the user responds.
767
+ findSessionByHookSecret: (secret) => self._findSessionByHookSecret(secret),
768
+ // #3059: audit HTTP user-initiated permission responses. Late-bound
769
+ // via getter because _permissionAudit is constructed after this call.
770
+ getPermissionAudit: () => self._permissionAudit,
771
+ })
772
+ // Handler context (#5558): role-scoped namespaces, not a flat god-context.
773
+ // Each bucket declares what a handler couples to — transport (send/
774
+ // broadcast/subscribe), sessions (the session managers), permissions
775
+ // (audit + routing maps), services (managers + config + fileOps), runtime
776
+ // (drain flag, provider dirs, evaluator counters). Late-bound via getters
777
+ // for test compat (tests may reassign the underlying server properties).
778
+ // The single source of truth for the shape is ws-handler-context.js.
779
+ this._handlerCtx = {
780
+ transport: {
781
+ send: sendFn,
782
+ broadcast: broadcastFn,
783
+ broadcastToSession: (sid, msg, filter) => self._broadcastToSession(sid, msg, filter),
784
+ broadcastSessionList: () => {
785
+ const allSessions = self.sessionManager.listSessions()
786
+ for (const [ws, c] of self.clients) {
787
+ if (c.authenticated && ws.readyState === 1) {
788
+ const sessions = c.boundSessionId
789
+ ? allSessions.filter(s => s.sessionId === c.boundSessionId)
790
+ : allSessions
791
+ sendFn(ws, { type: 'session_list', sessions })
792
+ }
793
+ }
794
+ },
795
+ // #5563: index-maintaining mutators for client subscription / active
796
+ // session. Handlers MUST route subscription + active-session changes
797
+ // through these (NOT bare `client.subscribedSessionIds.add()` /
798
+ // `client.activeSessionId = x`) so the sessionId→clients reverse index
799
+ // can never drift from the per-client Sets.
800
+ subscribeClient: (client, sid) => {
801
+ // #5704: an EXPLICIT subscribe (switch_session / subscribe_sessions /
802
+ // session-create auto-sub all route through here) adopts the
803
+ // subscription — zero any permission-induced refcount so permission
804
+ // teardown can never tear down a subscription the client asked for.
805
+ self._adoptPermissionSubscription(client.id, sid)
806
+ self._clientManager.subscribe(client, sid)
807
+ },
808
+ unsubscribeClient: (client, sid) => {
809
+ // #5704: an explicit unsubscribe also drops any permission refcount —
810
+ // the client chose to stop watching; a later permission teardown must
811
+ // not be a no-op-that-leaks the bookkeeping entry.
812
+ self._adoptPermissionSubscription(client.id, sid)
813
+ self._clientManager.unsubscribe(client, sid)
814
+ },
815
+ setActiveSession: (client, sid) => self._clientManager.setActiveSession(client, sid),
816
+ // #5563: explicit primary-ownership surface. `updatePrimary` is the
817
+ // first-input adoption path (claims if unclaimed, no-op if already
818
+ // primary, REJECTED-without-side-effects if another client owns it).
819
+ // `claimPrimary` is the explicit claim/hand-off path (force=true for an
820
+ // operator-driven hand-off). `getPrimary`/`isPrimary` are reads used by
821
+ // the input_conflict gate. `clearPrimary` is the destroy/cleanup path.
822
+ updatePrimary: (sid, cid) => self._updatePrimary(sid, cid),
823
+ claimPrimary: (sid, cid, opts) => self._claimPrimary(sid, cid, opts),
824
+ getPrimary: (sid) => self._clientManager.getPrimary(sid),
825
+ isPrimary: (sid, cid) => self._clientManager.isPrimary(sid, cid),
826
+ clearPrimary: (sid) => self._clearPrimary(sid),
827
+ // #5837: re-evaluate the terminal-mirror coalescer gate for a session
828
+ // after its subscriber set changes (handlers call this on subscribe/
829
+ // unsubscribe; departure is handled server-side in _handleClientDeparture).
830
+ syncTerminalMirror: (sid) => self._syncTerminalMirror(sid),
831
+ sendSessionInfo: (ws, sid) => self._sendSessionInfo(ws, sid),
832
+ replayHistory: (ws, sid, opts) => self._replayHistory(ws, sid, opts),
833
+ get clients() { return self.clients },
834
+ },
835
+ sessions: {
836
+ get sessionManager() { return self.sessionManager },
837
+ get cliSession() { return self.cliSession },
838
+ },
839
+ permissions: {
840
+ permissions: this._permissions,
841
+ get permissionAudit() { return self._permissionAudit },
842
+ pendingPermissions: this._pendingPermissions,
843
+ permissionSessionMap: this._permissionSessionMap,
844
+ // #5704: the resolver in settings-handlers (WS permission_response) must
845
+ // route its map delete through this so the permission-induced
846
+ // subscription refcount is decremented in lockstep — same hook the HTTP
847
+ // resolver uses via createPermissionHandler.
848
+ unregisterPermissionRoute: (requestId) => self._unregisterPermissionRoute(requestId),
849
+ questionSessionMap: this._questionSessionMap,
850
+ },
851
+ services: {
852
+ get pushManager() { return self.pushManager },
853
+ // #5510: pairing-approval primitive — host-level approve/deny handlers.
854
+ get pairingManager() { return self._pairingManager },
855
+ get checkpointManager() { return self._checkpointManager },
856
+ // #6006: the token lifecycle manager — exposed so the primary-gated
857
+ // `revoke_token` handler can fire the operator panic button
858
+ // (TokenManager.revoke()). Null when auth is disabled (--no-auth).
859
+ get tokenManager() { return self._tokenManager },
860
+ get devPreview() { return self._devPreview },
861
+ get webTaskManager() { return self._webTaskManager },
862
+ get environmentManager() { return self.environmentManager },
863
+ // #4835: per-device active-session memory. handleSwitchSession writes
864
+ // here after every successful switch so the next reconnect can
865
+ // restore the same session.
866
+ get devicePreferences() { return self._devicePreferences },
867
+ fileOps: this._fileOps,
868
+ // Runtime config exposed to handlers so validators (e.g.
869
+ // validateCwdAllowed) can consult workspaceRoots, feature flags,
870
+ // etc. Late-bound so test harnesses that mutate this.config after
871
+ // construction still see the updated value.
872
+ get config() { return self.config },
873
+ // #5554: the per-skill usage recorder lives on the SessionManager (it
874
+ // records activations at session creation); the Skills inventory handler
875
+ // reads its aggregates to join lastUsed / count / repos onto the snapshot.
876
+ get skillsUsageRecorder() { return self.sessionManager?.skillsUsageRecorder ?? null },
877
+ resolvePairRequester: (requestId, result) => self._resolvePairRequester(requestId, result),
878
+ broadcastPairResolved: (requestId, reason) => self._broadcastPairResolved(requestId, reason),
879
+ // #6277: the create gate reads this to HOLD a user-shell spawn pending
880
+ // host approval. Late-bound so it tracks the server instance.
881
+ get shellApprovalStore() { return self._shellApprovalStore },
882
+ // #5966: the bounded RepoEventStore the GitHub-webhook receiver fills
883
+ // (github-webhook.js) and the Control Room repo-events survey drains.
884
+ // Lazily created on the first webhook delivery, so null until then —
885
+ // the survey handler treats a null store as an empty (schema-valid) feed.
886
+ get repoEventStore() { return self._repoEventStore ?? null },
887
+ },
888
+ runtime: {
889
+ get draining() { return self._draining },
890
+ // Multi-provider data dirs (#2965): computed fresh each access so new
891
+ // provider registrations are reflected without restarting the server.
892
+ get projectsDirs() { return getProviderDataDirs().map(d => join(d, 'projects')) },
893
+ get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
894
+ // #3637: stable per-session auto-evaluator iteration counter (#3186).
895
+ // See WsServer constructor for the lifecycle rationale.
896
+ evaluatorIterations: this._evaluatorIterations,
897
+ },
898
+ }
899
+ // Fail loudly if the production ctx ever drifts from the declared shape.
900
+ // #5579: deep assert so a CTX_NAMESPACES field forgotten on _handlerCtx
901
+ // fails at construction, not as a silent `undefined` read in prod. The
902
+ // deep check uses `key in bucket`, which does NOT invoke getters — so the
903
+ // late-bound getter fields (config, skillsUsageRecorder, projectsDirs, …)
904
+ // are verified present without triggering their side effects. One-time
905
+ // cost at startup is acceptable.
906
+ assertCtxShape(this._handlerCtx, { deep: true })
907
+
908
+ // Context objects for extracted modules (ws-auth.js, ws-history.js)
909
+ this._historyCtx = {
910
+ get clients() { return self.clients },
911
+ // #5563: index-maintaining active-session mutator for the post-auth
912
+ // restore path (ws-history.js sets activeSessionId once per connect).
913
+ setActiveSession: (client, sid) => self._clientManager.setActiveSession(client, sid),
914
+ // #5731 T5 / #5623 / #5613: current primary owner for a session, so
915
+ // sendSessionInfo can re-sync `session_role` on reconnect/tab-switch
916
+ // (otherwise the presence badge goes stale — the role is only ever
917
+ // broadcast on an actual primary change via _announcePrimary).
918
+ getPrimary: (sid) => self._clientManager.getPrimary(sid),
919
+ get sessionManager() { return self.sessionManager },
920
+ get cliSession() { return self.cliSession },
921
+ get defaultSessionId() { return self.defaultSessionId },
922
+ get serverMode() { return self.serverMode },
923
+ serverVersion: SERVER_VERSION,
924
+ get latestVersion() { return self._latestVersion },
925
+ get gitInfo() { return self._gitInfo },
926
+ get encryptionEnabled() { return self._encryptionEnabled },
927
+ // #5536 — identity keypair for signing the eager exchange public key.
928
+ get serverIdentity() { return self._serverIdentity },
929
+ get localhostBypass() { return self._localhostBypass },
930
+ // #6564 — a POSITIVE "an edge could be in front" signal. Any of: a running
931
+ // Quick/named tunnel (_quickTunnelActive / _tunnelUrl), OR an operator-supplied
932
+ // external URL (config.externalUrl — SKIP_TUNNEL mode, where the operator runs
933
+ // their own reverse proxy in front, exactly the unknown-edge case). When true,
934
+ // the localhost plaintext bypass is gated off (see ws-history).
935
+ get tunnelActive() { return self._quickTunnelActive || self._tunnelUrl != null || Boolean(self.config?.externalUrl) },
936
+ get keyExchangeTimeoutMs() { return self._keyExchangeTimeoutMs },
937
+ protocolVersion: SERVER_PROTOCOL_VERSION,
938
+ minProtocolVersion: MIN_PROTOCOL_VERSION,
939
+ get webTaskManager() { return self._webTaskManager },
940
+ send: sendFn,
941
+ broadcast: broadcastFn,
942
+ getConnectedClientList: () => self._getConnectedClientList(),
943
+ get permissions() { return self._permissions },
944
+ // #3760: effective inactivity timeout, surfaced in auth_ok so clients
945
+ // render their ActivityIndicator timeout warning against the real
946
+ // configured value. Late-bound so test harnesses mutating this.config
947
+ // after construction are reflected. #3905 adds the parallel hard-cap.
948
+ get resultTimeoutMs() { return self.config?.resultTimeoutMs ?? null },
949
+ get hardTimeoutMs() { return self.config?.hardTimeoutMs ?? null },
950
+ // #4477: effective stream-stall recovery window in ms. null = use
951
+ // BaseSession's DEFAULT_STREAM_STALL_TIMEOUT_MS (5min); 0 = operator
952
+ // explicitly disabled stall recovery (preserved as-is on the wire so
953
+ // the dashboard chip can hide instead of rendering against a
954
+ // disabled timer).
955
+ get streamStallTimeoutMs() { return self.config?.streamStallTimeoutMs ?? null },
956
+ // #5986 (epic #5982): whether the embedded user-shell terminal is enabled
957
+ // (userShell.enabled). Surfaced in auth_ok's capability map so the
958
+ // dashboard can show/hide the "New shell" affordance fail-closed (the
959
+ // user-shell provider is hidden from listProviders, so the picker can't
960
+ // advertise it). Late-bound getter so a test mutating self.config is seen.
961
+ get userShellEnabled() { return isUserShellEnabled(self.config) },
962
+ // #6481 (epic #6469): whether the opt-in IDE feature surface is enabled on
963
+ // this server (config.features.ide / CHROXY_ENABLE_IDE). Surfaced as the
964
+ // `ide` capability so clients gate IDE UI. Late-bound getter so a test
965
+ // mutating self.config is seen.
966
+ get ideEnabled() { return isIdeFeatureEnabled(self.config) },
967
+ // #6006: whether the operator panic button (revoke_token) can fire — true
968
+ // iff a usable rotating TokenManager exists (i.e. auth is on). Mirrors the
969
+ // token-handlers availability check (`typeof revoke === 'function'`) so the
970
+ // capability never advertises a button that would only get REVOKE_UNAVAILABLE.
971
+ // Surfaced as the `tokenRevoke` capability, further gated to primary-token
972
+ // clients in ws-history so a paired device never sees the affordance.
973
+ get tokenRevocable() { return self._tokenManager != null && typeof self._tokenManager.revoke === 'function' },
974
+ // #4835: per-device active-session memory consulted during reconnect.
975
+ // sendPostAuthInfo treats this as optional, but production wiring
976
+ // always supplies the default disk-backed store from the WsServer
977
+ // constructor.
978
+ get devicePreferences() { return self._devicePreferences },
979
+ // #5356: exposure snapshot (non-loopback bind / public quick tunnel)
980
+ // surfaced in auth_ok so the dashboard can render a warning banner.
981
+ // null until start() has bound a socket.
982
+ get exposure() { return self.exposure },
983
+ // #5821: current billing-canary snapshot, seeded into auth_ok so a
984
+ // freshly-connected client renders the billing banner immediately. null
985
+ // until a provider is wired (server-cli sets it post-construct) — live
986
+ // changes still arrive via the `billing_canary` broadcast.
987
+ get billingCanary() {
988
+ try { return self._billingCanaryProvider ? self._billingCanaryProvider() : null }
989
+ catch { return null }
990
+ },
991
+ // #5555 (auth_bootstrap): file ops + provider agent dirs so the
992
+ // connect-time bootstrap burst can compute the slash-command / agent
993
+ // lists inline (same payloads the list_* request handlers produce),
994
+ // letting the client skip its 3-request connect-time round trip.
995
+ get fileOps() { return self._fileOps },
996
+ get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
997
+ // #5555 (sub-item 7): the current public tunnel URL (wss://), folded into
998
+ // the auth_bootstrap burst so a reconnecting client always re-learns the
999
+ // live URL — the durable recovery path when a quick-tunnel rotation
1000
+ // happened while the client was offline. null for LAN / no-tunnel.
1001
+ get tunnelUrl() { return self._tunnelUrl },
1002
+ }
1003
+ this._authCtx = {
1004
+ get clients() { return self.clients },
1005
+ get authRequired() { return self.authRequired },
1006
+ isTokenValid: (token) => self._isTokenValid(token),
1007
+ get authFailures() { return self._authFailures },
1008
+ get benignPairAttempts() { return self._benignPairAttempts },
1009
+ get pairingManager() { return self._pairingManager },
1010
+ // #5536 — identity keypair for signing the discrete exchange public key.
1011
+ get serverIdentity() { return self._serverIdentity },
1012
+ get activeSessionId() {
1013
+ // Linking-mode default: return null so paired tokens are NOT auto-bound
1014
+ // to a specific session. The QR shown by the dashboard is intended as a
1015
+ // general "link this device" code that lets the app create/switch
1016
+ // sessions freely. Auto-binding to defaultSessionId/firstSessionId
1017
+ // (the prior behavior) silently produced session-locked tokens, so
1018
+ // every newly-paired phone hit "Device paired to one session" the
1019
+ // moment it tried to open another tab.
1020
+ //
1021
+ // Session-bound pairings are still possible via the per-client
1022
+ // boundSessionId path; a future "Share this session" UI can opt in by
1023
+ // creating a session-scoped pairing through a different code path.
1024
+ return null
1025
+ },
1026
+ send: sendFn,
1027
+ onAuthSuccess: (ws, client) => {
1028
+ // If paired, include sessionToken in auth_ok response
1029
+ if (client._sessionToken) {
1030
+ self._sendPostAuthInfo(ws, { sessionToken: client._sessionToken })
1031
+ delete client._sessionToken
1032
+ } else {
1033
+ self._sendPostAuthInfo(ws)
1034
+ }
1035
+ self._broadcastClientJoined(client, ws)
1036
+ },
1037
+ minProtocolVersion: MIN_PROTOCOL_VERSION,
1038
+ serverProtocolVersion: SERVER_PROTOCOL_VERSION,
1039
+ flushPostAuthQueue: (ws, queue) => self._flushPostAuthQueue(ws, queue),
1040
+ // #5510: register the requester's still-open ws so a later approve/deny
1041
+ // can reach it, and fan `pair_pending` out to host-level surfaces.
1042
+ registerPairRequester: (requestId, ws) => self._pairRequesters.set(requestId, ws),
1043
+ broadcastPairPending: (msg) => self._broadcastPairPending(msg),
1044
+ }
1045
+
1046
+ this.pushManager = pushManager
1047
+
1048
+ // Permission audit trail
1049
+ this._permissionAudit = new PermissionAuditLog()
1050
+
1051
+ // Auth rate limiting: track failed attempts per IP
1052
+ this._authFailures = new Map() // ip -> { count, firstFailure, blockedUntil }
1053
+ // Lenient pairing rate limiter (#3019) — caps already_used/expired hammering
1054
+ // without locking out users who legitimately rescan a stale QR a few times.
1055
+ // Strictly separate from _authFailures: a benign breach must NOT disable
1056
+ // genuine brute-force protection for the same IP.
1057
+ this._benignPairAttempts = new Map() // ip -> { count, windowStart, blockedUntil }
1058
+ this._authCleanupInterval = null
1059
+
1060
+ // Multi-session support: prefer sessionManager, fall back to single cliSession
1061
+ this.sessionManager = sessionManager || null
1062
+ this.environmentManager = environmentManager || null
1063
+ this.defaultSessionId = defaultSessionId || null
1064
+ this._checkpointManager = new CheckpointManager()
1065
+
1066
+ // Register/unregister per-session hook secrets and clean up checkpoints on lifecycle events.
1067
+ // Handlers are stored on `this` so close() can remove them — without this, a long-lived
1068
+ // SessionManager keeps every retired WsServer pinned in memory and replays events to
1069
+ // closed instances. Symmetric with _pairingRefreshedHandler / _tokenRotatedHandler.
1070
+ if (sessionManager && typeof sessionManager.on === 'function') {
1071
+ this._sessionCreatedHandler = ({ sessionId }) => {
1072
+ const entry = sessionManager.getSession(sessionId)
1073
+ this._registerSessionHookSecretIfMissing(sessionId, entry)
1074
+ }
1075
+ this._sessionDestroyedHandler = ({ sessionId }) => {
1076
+ // Look up the stored secret — the session is already removed from the map
1077
+ const secret = this._sessionHookSecrets.get(sessionId)
1078
+ if (secret) {
1079
+ this.unregisterHookSecret(secret)
1080
+ this._sessionHookSecrets.delete(sessionId)
1081
+ log.debug(`Unregistered hook secret for session ${sessionId}`)
1082
+ }
1083
+ try {
1084
+ this._checkpointManager.clearCheckpoints(sessionId)
1085
+ } catch (err) {
1086
+ log.warn(`Failed to clear checkpoints for destroyed session ${sessionId}: ${err.message}`)
1087
+ }
1088
+ // #5731 T7: auto-deny any pending HTTP-hook permission for this session
1089
+ // BEFORE we drop its map entries below. Otherwise the hook's parked
1090
+ // POST /permission blocks the tool call for the full 5-min timeout,
1091
+ // then fires on a destroyed session, leaking the held response until
1092
+ // then. drainSessionPermissions() resolves each as 'deny' (its shared
1093
+ // cleanup also removes the requestId from _permissionSessionMap); the
1094
+ // loop below then only mops up any orphaned mapping with no live
1095
+ // pending entry.
1096
+ try {
1097
+ this._permissions?.drainSessionPermissions?.(sessionId)
1098
+ } catch (err) {
1099
+ log.warn(`Failed to drain pending permissions for destroyed session ${sessionId}: ${err.message}`)
1100
+ }
1101
+ // #5704: route the orphan sweep through _unregisterPermissionRoute so a
1102
+ // destroyed session's permission-induced subscriptions are torn down,
1103
+ // not just the map entry. Collect keys first to avoid mutating the map
1104
+ // mid-iteration (_unregisterPermissionRoute deletes the entry).
1105
+ for (const key of [...this._permissionSessionMap.keys()]) {
1106
+ if (this._permissionSessionMap.get(key) === sessionId) this._unregisterPermissionRoute(key)
1107
+ }
1108
+ for (const [key, sid] of this._questionSessionMap) {
1109
+ if (sid === sessionId) this._questionSessionMap.delete(key)
1110
+ }
1111
+ // #3637: drop the auto-evaluator iteration counter entry for the
1112
+ // destroyed session. The Map would otherwise grow unboundedly
1113
+ // over the server's lifetime — small leak (one int per session)
1114
+ // but a long-running server with many session destroys would
1115
+ // accumulate dead entries.
1116
+ this._evaluatorIterations.delete(sessionId)
1117
+ }
1118
+ // #3057: audit auto-deny resolution paths (timeout / aborted / cleared).
1119
+ // The WS inline response path in settings-handlers.js audits user
1120
+ // resolutions with the responding client's id. Auto-deny paths have no
1121
+ // client — record them here with clientId null so forensic queries see
1122
+ // the full lifecycle of every permission request, not just the ones a
1123
+ // user touched. (HTTP user resolutions still aren't audited — pre-existing
1124
+ // gap tracked in #3059.)
1125
+ this._sessionEventAuditHandler = ({ sessionId, event, data }) => {
1126
+ if (event !== 'permission_resolved') return
1127
+ if (!data || data.reason === 'user') return
1128
+ // #3061: defensive — if the SdkSession requestId gate is ever widened
1129
+ // (e.g. to propagate AskUserQuestion lifecycle events), don't silently
1130
+ // write audit entries with requestId: undefined. Today this branch is
1131
+ // unreachable because sdk-session.js gates the re-emit on data.requestId.
1132
+ if (!data.requestId) return
1133
+ this._permissionAudit.logDecision({
1134
+ clientId: null,
1135
+ sessionId,
1136
+ requestId: data.requestId,
1137
+ decision: data.decision,
1138
+ reason: data.reason,
1139
+ })
1140
+ }
1141
+ sessionManager.on('session_created', this._sessionCreatedHandler)
1142
+ sessionManager.on('session_destroyed', this._sessionDestroyedHandler)
1143
+ sessionManager.on('session_event', this._sessionEventAuditHandler)
1144
+
1145
+ // Retroactively register hook secrets for sessions that already exist
1146
+ // on this SessionManager. server-cli.js calls sessionManager.restoreState()
1147
+ // BEFORE constructing the WsServer, so the session_created events fire
1148
+ // before _sessionCreatedHandler is attached and restored sessions never
1149
+ // get their _hookSecret registered. Result: every POST /permission from
1150
+ // a restored session's hook script fails _validateHookAuth with 403,
1151
+ // the curl response has no `decision` field, and the script returns
1152
+ // "ask" — surfacing as "Hook PreToolUse:Bash asked for confirmation"
1153
+ // with no dashboard prompt ever appearing (#3716).
1154
+ // Guard: many tests pass a stub sessionManager without _sessions.
1155
+ // Resolve each entry through getSession() so we skip sessions marked
1156
+ // _destroying — matches what _sessionCreatedHandler above does and
1157
+ // mirrors clearAllPendingPermissions() at line 1443.
1158
+ if (sessionManager._sessions instanceof Map && typeof sessionManager.getSession === 'function') {
1159
+ for (const [sessionId, entry] of sessionManager._sessions) {
1160
+ if (entry?._destroying) continue
1161
+ this._registerSessionHookSecretIfMissing(sessionId, sessionManager.getSession(sessionId))
1162
+ }
1163
+ }
1164
+ }
1165
+
1166
+ // Dev server preview tunneling
1167
+ this._devPreview = new DevPreviewManager()
1168
+
1169
+ // Web task manager (Claude Code Web cloud delegation)
1170
+ this._webTaskManager = new WebTaskManager({ cwd: sessionManager?.defaultCwd || process.cwd() })
1171
+
1172
+ // Legacy single-session mode: wrap cliSession in a minimal shim
1173
+ if (!sessionManager && cliSession) {
1174
+ this.cliSession = cliSession
1175
+ // Register the hook secret immediately — no session_created event fires in legacy mode
1176
+ if (cliSession._hookSecret) {
1177
+ this.registerHookSecret(cliSession._hookSecret)
1178
+ }
1179
+ } else {
1180
+ this.cliSession = null
1181
+ }
1182
+
1183
+ this.serverMode = 'cli'
1184
+ // #5516/#5562: hand the normalizer a subscriber-count resolver so it can
1185
+ // tighten the fixed delta micro-batch window (16→8ms) when a session has a
1186
+ // single subscriber — the common phone-on-LAN / single-dashboard case.
1187
+ // Multi-client sessions keep the 16ms window (fan-out amortization). These
1188
+ // are fixed micro-batch windows, not an adaptive throttle — the adaptive
1189
+ // part is the client-side store-core EWMA (resolveDeltaFlushMs); #5562
1190
+ // shrank the server window from 25/50ms so it no longer stacks on top of
1191
+ // that EWMA. Legacy single-session mode (sessionId === null) reports null
1192
+ // (unknown), which the normalizer treats as "keep the default window".
1193
+ // #5578: also hand it a deflate-subscriber predicate so the window can
1194
+ // widen (8/16 → 16/25ms) when any subscriber is on a deflate-negotiated
1195
+ // (tunnel/cellular) socket, where each sub-1024B stream_delta ships
1196
+ // uncompressed and the per-frame small-packet cost dominates. O(subscribers)
1197
+ // via the #5575 reverse index — never an O(all-clients) scan on the
1198
+ // per-token hot path. Legacy single-session mode (sessionId === null) can't
1199
+ // resolve subscribers, so it reports false → keeps the LAN window.
1200
+ this._normalizer = new EventNormalizer({
1201
+ getSubscriberCount: (sessionId) =>
1202
+ sessionId == null ? null : this._broadcaster._countSessionSubscribers(sessionId),
1203
+ getHasDeflateSubscriber: (sessionId) =>
1204
+ sessionId == null ? false : this._broadcaster._hasDeflateSubscriber(sessionId),
1205
+ })
1206
+ this._gitInfo = getGitInfo()
1207
+ this._startedAt = Date.now()
1208
+ this._draining = false
1209
+ this._latestVersion = null
1210
+
1211
+ // Background version check (non-blocking, skipped in test/CI)
1212
+ if (process.env.NODE_ENV !== 'test') {
1213
+ checkLatestVersion(packageJson.name).then((v) => { this._latestVersion = v }).catch((err) => {
1214
+ log.warn(`Failed to check latest npm version: ${err.message} (non-critical, update check skipped)`)
1215
+ })
1216
+ }
1217
+
1218
+ // Wire PairingManager refresh events — broadcast pairing_refreshed to all
1219
+ // authenticated dashboard clients so they can auto-refresh the QR code (#2916).
1220
+ this._pairingRefreshedHandler = null
1221
+ this._pendingRequestExpiredHandler = null
1222
+ if (this._pairingManager) {
1223
+ this._pairingRefreshedHandler = () => {
1224
+ this._broadcast({ type: 'pairing_refreshed' })
1225
+ log.debug('Broadcasted pairing_refreshed to all clients')
1226
+ }
1227
+ this._pairingManager.on('pairing_refreshed', this._pairingRefreshedHandler)
1228
+
1229
+ // #5510: a pending pair request hit its TTL while still unresolved. Tell
1230
+ // the requester (its connection may still be open) and retract the banner
1231
+ // on every host surface.
1232
+ this._pendingRequestExpiredHandler = ({ requestId }) => {
1233
+ this._resolvePairRequester(requestId, { ok: false, reason: 'expired' })
1234
+ this._broadcastPairResolved(requestId, 'expired')
1235
+ }
1236
+ this._pairingManager.on('pending_request_expired', this._pendingRequestExpiredHandler)
1237
+ }
1238
+
1239
+ // Wire TokenManager rotation events — broadcast new token to all clients
1240
+ this._tokenRotatedHandler = null
1241
+ if (this._tokenManager) {
1242
+ this._tokenRotatedHandler = ({ newToken, expiresAt, reason }) => {
1243
+ // Update our reference so subsequent auth checks use the new token
1244
+ this.apiToken = newToken
1245
+
1246
+ if (reason === 'revoke') {
1247
+ // #6006 panic button. The old token is compromised and we cannot tell
1248
+ // an attacker's connection from a legitimate one — every connection
1249
+ // authenticated with the same now-suspect token. So:
1250
+ // (a) sever every privileged user-shell session, and
1251
+ // (b) force EVERY connection to re-authenticate: clear
1252
+ // `authenticated` + `isPrimaryToken` so the dispatch gate
1253
+ // (_handleMessage) rejects all privileged ops — including a
1254
+ // re-create of the shell — until the connection re-auths with
1255
+ // the current token, obtained out-of-band (re-pair / re-scan).
1256
+ // We deliberately do NOT push the new token to any client, even
1257
+ // encrypted ones: handing it down a possibly-compromised connection
1258
+ // would defeat the revoke. The token-less `token_rotated` already
1259
+ // drives clients onto their "must re-authenticate" path.
1260
+ let severed = 0
1261
+ try {
1262
+ severed = this.sessionManager?.destroyAllUserShellSessions('revoked') ?? 0
1263
+ } catch (err) {
1264
+ log.error(`Failed to sever user-shell sessions on revoke: ${err.message}`)
1265
+ }
1266
+ let forced = 0
1267
+ for (const [ws, client] of this.clients) {
1268
+ // Skip connections still mid-handshake (not yet authenticated): they
1269
+ // hold no authority to strip and will fail their pending auth step
1270
+ // against the now-current token on their own.
1271
+ if (!client.authenticated || ws.readyState !== 1) continue
1272
+ client.authenticated = false
1273
+ client.isPrimaryToken = false
1274
+ this._send(ws, { type: 'token_rotated', expiresAt, reason: 'revoke' })
1275
+ forced++
1276
+ }
1277
+ log.warn(`Token REVOKED — severed ${severed} user-shell session(s), forced re-auth on ${forced} connection(s)`)
1278
+ return
1279
+ }
1280
+
1281
+ // Scheduled/periodic rotation — graceful re-key, live sessions survive.
1282
+ // Send the new token to encrypted clients (they need it for reconnection).
1283
+ // Unencrypted clients (e.g. localhost dashboard) get the event without the
1284
+ // raw token to avoid leaking credentials over plaintext connections.
1285
+ let encrypted = 0, unencrypted = 0
1286
+ for (const [ws, client] of this.clients) {
1287
+ if (!client.authenticated || ws.readyState !== 1) continue
1288
+ // Carry `reason: 'scheduled'` so the wire is self-describing and
1289
+ // matches the documented contract + TokenManager's event payload.
1290
+ if (client.encryptionState) {
1291
+ this._send(ws, { type: 'token_rotated', token: newToken, expiresAt, reason: 'scheduled' })
1292
+ // #6012: this connection just received the new token, so refresh the
1293
+ // token recorded at auth — an honest, still-connected encrypted
1294
+ // primary can then open a NEW user-shell (#6004 gate) without a
1295
+ // reconnect. Only on a SCHEDULED push: revoke never pushes the token
1296
+ // and de-auths instead, so a compromised connection can't gain
1297
+ // currency this way. Unencrypted clients get no token, so theirs
1298
+ // stays stale (they must reconnect) — handled by the else branch.
1299
+ client.authToken = newToken
1300
+ encrypted++
1301
+ } else {
1302
+ this._send(ws, { type: 'token_rotated', expiresAt, reason: 'scheduled' })
1303
+ unencrypted++
1304
+ }
1305
+ }
1306
+ log.info(`Broadcasted token_rotated to ${encrypted} encrypted + ${unencrypted} unencrypted clients`)
1307
+ }
1308
+ this._tokenManager.on('token_rotated', this._tokenRotatedHandler)
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * Check whether a token is valid. Delegates to TokenManager (supports
1314
+ * rotated + grace-period tokens) when available, otherwise falls back
1315
+ * to constant-time comparison against the static apiToken.
1316
+ */
1317
+ _isTokenValid(token) {
1318
+ if (!token) return false
1319
+ // Check session tokens issued via pairing
1320
+ if (this._pairingManager && this._pairingManager.isSessionTokenValid(token)) return true
1321
+ if (this._tokenManager) return this._tokenManager.validate(token)
1322
+ return safeTokenCompare(token, this.apiToken)
1323
+ }
1324
+
1325
+ /**
1326
+ * Authenticate a dashboard HTTP request using cookie, bearer, or query token.
1327
+ * Returns true if auth passes (or auth is disabled). On failure or redirect,
1328
+ * writes the response and returns false (caller should stop processing).
1329
+ */
1330
+ _authenticateDashboardRequest(req, res, dashUrl, securityHeaders) {
1331
+ if (!this.authRequired) return true
1332
+ const bearerToken = (req.headers['authorization'] || '').startsWith('Bearer ')
1333
+ ? req.headers['authorization'].slice(7) : null
1334
+ const cookieToken = (req.headers['cookie'] || '').match(/(?:^|;\s*)chroxy_auth=([^;]*)/)
1335
+ let cookieVal = null
1336
+ if (cookieToken) {
1337
+ try { cookieVal = decodeURIComponent(cookieToken[1]) } catch { cookieVal = null }
1338
+ }
1339
+ const queryToken = dashUrl.searchParams.get('token')
1340
+ const token = queryToken || bearerToken || cookieVal
1341
+ if (!token || !this._isTokenValid(token)) {
1342
+ res.writeHead(403, { 'Content-Type': 'text/html', ...securityHeaders })
1343
+ res.end('<h1>403 Forbidden</h1><p>Invalid or missing token.</p>')
1344
+ return false
1345
+ }
1346
+ if (queryToken) {
1347
+ const encoded = encodeURIComponent(queryToken)
1348
+ // Set cookie for future requests, but DON'T redirect — serve content
1349
+ // directly. Tauri's WKWebView doesn't reliably send cookies on 302
1350
+ // redirects to 127.0.0.1 with SameSite=Strict.
1351
+ const securePart = _isSecureRequest(req) ? '; Secure' : ''
1352
+ res.setHeader('Set-Cookie', `chroxy_auth=${encoded}; Path=/dashboard; SameSite=Strict; HttpOnly${securePart}; Max-Age=86400`)
1353
+ }
1354
+ return true
1355
+ }
1356
+
1357
+ /**
1358
+ * Validate Bearer token on an HTTP request. Returns true if auth passes
1359
+ * (or auth is disabled). On failure, writes a 403 response and returns false.
1360
+ */
1361
+ _validateBearerAuth(req, res) {
1362
+ if (!this.authRequired) return true
1363
+ const authHeader = req.headers['authorization'] || ''
1364
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
1365
+ if (!token || !this._isTokenValid(token)) {
1366
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1367
+ res.end(JSON.stringify({ error: 'unauthorized' }))
1368
+ return false
1369
+ }
1370
+ return true
1371
+ }
1372
+
1373
+ /**
1374
+ * Validate that an HTTP request carries the PRIMARY token class — i.e. the
1375
+ * static apiToken (or an active rotation/grace token), NOT a pairing-bound
1376
+ * session token. Used by host-authority endpoints that a scoped, paired
1377
+ * device must not be able to invoke (#5533): e.g. POST /pair-discord, which
1378
+ * posts a fresh pairing link to a shared channel. Per
1379
+ * docs/security/bearer-token-authority.md, pairing-bound tokens are scoped to
1380
+ * one session and must never carry host-level authority.
1381
+ *
1382
+ * A token is primary iff it validates but is NOT a PairingManager-issued
1383
+ * session token. Returns true on pass; writes a 403 and returns false
1384
+ * otherwise.
1385
+ */
1386
+ _validatePrimaryBearerAuth(req, res) {
1387
+ if (!this.authRequired) return true
1388
+ const authHeader = req.headers['authorization'] || ''
1389
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
1390
+ if (!token || !this._isTokenValid(token)) {
1391
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1392
+ res.end(JSON.stringify({ error: 'unauthorized' }))
1393
+ return false
1394
+ }
1395
+ // Reject pairing-bound (and any other PairingManager-issued) session tokens:
1396
+ // they are valid, but scoped — not the host-authority primary token.
1397
+ if (this._pairingManager && this._pairingManager.isSessionTokenValid(token)) {
1398
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1399
+ res.end(JSON.stringify({ error: 'primary_token_required' }))
1400
+ return false
1401
+ }
1402
+ return true
1403
+ }
1404
+
1405
+ /**
1406
+ * #6277 — complete a host-approved user-shell spawn. Resolves the requesting
1407
+ * socket from the client map (it may be GONE if the requester disconnected
1408
+ * during the approval window — that's tolerated: the session is still created
1409
+ * + audited + broadcast to other clients, only the requester notify is
1410
+ * skipped) and replays finalizeShellCreate with the audit identity captured at
1411
+ * request time. Returns the created sessionId; throws on a create failure
1412
+ * (the caller maps it to an HTTP 500).
1413
+ *
1414
+ * @param {object} entry - the resolved pending-approval entry from the store
1415
+ * @returns {string} sessionId
1416
+ */
1417
+ completeShellApproval(entry) {
1418
+ let ws = null
1419
+ let client = null
1420
+ for (const [sock, c] of this.clients) {
1421
+ if (c?.id === entry.clientId) { ws = sock; client = c; break }
1422
+ }
1423
+ return finalizeShellCreate(ws, client, entry.createSessionOptions, this._handlerCtx, {
1424
+ isUserShell: true,
1425
+ tokenClass: entry.tokenClass || 'primary',
1426
+ deviceName: entry.deviceName,
1427
+ clientId: entry.clientId,
1428
+ })
1429
+ }
1430
+
1431
+ /**
1432
+ * #6277 — tell the requester their shell was declined by the host operator.
1433
+ * No-op if the requesting socket is already gone.
1434
+ * @param {object} entry - the resolved pending-approval entry
1435
+ */
1436
+ notifyShellDenied(entry) {
1437
+ for (const [sock, c] of this.clients) {
1438
+ if (c?.id === entry.clientId) {
1439
+ this._handlerCtx.transport.send(sock, {
1440
+ type: 'session_error',
1441
+ code: 'SHELL_APPROVAL_DENIED',
1442
+ message: 'The host operator declined this shell.',
1443
+ })
1444
+ break
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ /**
1450
+ * #6277 — start the host-local user-shell approval listener.
1451
+ *
1452
+ * A SEPARATE HTTP server bound to 127.0.0.1 ONLY, on an ephemeral port the
1453
+ * Cloudflare tunnel never forwards (cloudflared only proxies the main port).
1454
+ * This separation is the load-bearing security property: a loopback check on
1455
+ * the MAIN port would be defeated because cloudflared makes tunnel traffic
1456
+ * arrive as 127.0.0.1, so a leaked-token attacker over the tunnel could
1457
+ * approve their own held shell. Only the host can reach this listener; the
1458
+ * primary-token check then narrows it to the operator. The port is published
1459
+ * to a 0600 file for the `chroxy shell approve` CLI.
1460
+ */
1461
+ _startApprovalListener() {
1462
+ this._approvalServer = createServer((req, res) => this._handleApprovalRequest(req, res))
1463
+ this._approvalServer.on('error', (err) => {
1464
+ log.error(`[shell-approval] listener error: ${err.message}`)
1465
+ })
1466
+ this._approvalServer.listen(0, '127.0.0.1', () => {
1467
+ const port = this._approvalServer.address()?.port
1468
+ this._shellApprovalPort = port
1469
+ try {
1470
+ writeShellApprovalInfo({ port, pid: process.pid })
1471
+ log.info(`[shell-approval] host-local approval listener on 127.0.0.1:${port} — user-shell spawns require \`chroxy shell approve\``)
1472
+ } catch (err) {
1473
+ log.error(`[shell-approval] failed to publish approval port: ${err.message}`)
1474
+ }
1475
+ })
1476
+ }
1477
+
1478
+ /**
1479
+ * #6277 — request handler for the host-local approval listener. Serves only
1480
+ * POST /api/shell/approve, POST /api/shell/deny, GET /api/shell/pending. The
1481
+ * listener is already 127.0.0.1-bound, but the kernel socket-IP is re-checked
1482
+ * (defense-in-depth against a future bind mistake) and every route requires
1483
+ * the primary token.
1484
+ */
1485
+ _handleApprovalRequest(req, res) {
1486
+ const json = (code, body) => {
1487
+ res.writeHead(code, { 'Content-Type': 'application/json' })
1488
+ res.end(JSON.stringify(body))
1489
+ }
1490
+ // Defense-in-depth: bound to 127.0.0.1, but re-verify the kernel-supplied
1491
+ // socket IP so a future 0.0.0.0 bind mistake can't quietly expose this.
1492
+ const socketIp = req.socket?.remoteAddress || ''
1493
+ if (!LOOPBACK_ADDRESSES.has(socketIp)) return json(403, { error: 'loopback_only' })
1494
+ // Host-OPERATOR authority: rejects pairing-bound tokens (writes its own 403).
1495
+ // Under --no-auth (no token configured) this passes through, consistent with
1496
+ // chroxy's local-trust model — the listener is still loopback-only (not
1497
+ // tunnel-reachable) and the create-side gate is equally token-free there.
1498
+ if (!this._validatePrimaryBearerAuth(req, res)) return
1499
+ const path = (req.url || '').split('?')[0]
1500
+ const store = this._shellApprovalStore
1501
+ if (req.method === 'GET' && path === '/api/shell/pending') {
1502
+ return json(200, { pending: store.list() })
1503
+ }
1504
+ if (req.method === 'POST' && (path === '/api/shell/approve' || path === '/api/shell/deny')) {
1505
+ let id = null
1506
+ try { id = new URL(req.url, 'http://localhost').searchParams.get('id') } catch { /* malformed url */ }
1507
+ if (!id) return json(400, { error: 'missing_id' })
1508
+ const isApprove = path === '/api/shell/approve'
1509
+ const result = isApprove ? store.approve(id) : store.deny(id)
1510
+ if (!result.ok) return json(result.reason === 'not_found' ? 404 : 403, { error: result.reason })
1511
+ if (isApprove) {
1512
+ try {
1513
+ return json(200, { ok: true, sessionId: this.completeShellApproval(result.entry) })
1514
+ } catch (err) {
1515
+ log.warn(`[shell-approval] approve ${id}: create failed: ${err.message}`)
1516
+ return json(500, { error: 'create_failed', message: err.message })
1517
+ }
1518
+ }
1519
+ try { this.notifyShellDenied(result.entry) } catch { /* requester socket gone */ }
1520
+ return json(200, { ok: true })
1521
+ }
1522
+ return json(404, { error: 'not_found' })
1523
+ }
1524
+
1525
+ /**
1526
+ * Post an approval-gated pairing link to the configured Discord webhook
1527
+ * (#5513). Thin seam around discord-pair-delivery.postPairLinkToDiscord so
1528
+ * http-routes can call it and tests can stub it. Never logs / returns the
1529
+ * webhook URL.
1530
+ */
1531
+ async _postPairLinkToDiscord(link) {
1532
+ return postPairLinkToDiscord(link)
1533
+ }
1534
+
1535
+ /**
1536
+ * Validate the per-session hook secret on a POST /permission request.
1537
+ * Only accepts secrets registered by active CliSessions — never the primary
1538
+ * API token. Falls back to bearer auth when no hook secrets are registered
1539
+ * (e.g. single-session legacy mode without hook secret support).
1540
+ */
1541
+ _validateHookAuth(req, res) {
1542
+ if (!this.authRequired) return true
1543
+ const authHeader = req.headers['authorization'] || ''
1544
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
1545
+ if (!token) {
1546
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1547
+ res.end(JSON.stringify({ error: 'unauthorized' }))
1548
+ return false
1549
+ }
1550
+ if (this._hookSecrets.size > 0) {
1551
+ let valid = false
1552
+ for (const secret of this._hookSecrets) {
1553
+ if (safeTokenCompare(token, secret)) { valid = true; break }
1554
+ }
1555
+ if (!valid) {
1556
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1557
+ res.end(JSON.stringify({ error: 'unauthorized' }))
1558
+ return false
1559
+ }
1560
+ return true
1561
+ }
1562
+ // No hook secrets registered — fall back to main token validation
1563
+ // (handles legacy single-session setups and tests that don't register secrets)
1564
+ if (!this._isTokenValid(token)) {
1565
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1566
+ res.end(JSON.stringify({ error: 'unauthorized' }))
1567
+ return false
1568
+ }
1569
+ return true
1570
+ }
1571
+
1572
+ /**
1573
+ * Register a session's hook secret on this WsServer if not already tracked.
1574
+ * Shared by the `session_created` handler and the constructor's retroactive
1575
+ * scan over `sessionManager._sessions` (#3716, #3717). Caller is responsible
1576
+ * for the outer `instanceof Map` check and any `_destroying` skip on the raw
1577
+ * map entry; this helper handles the missing-secret and dedupe guards.
1578
+ */
1579
+ _registerSessionHookSecretIfMissing(sessionId, entry) {
1580
+ const secret = entry?.session?._hookSecret
1581
+ if (!secret) return
1582
+ if (this._sessionHookSecrets.has(sessionId)) return
1583
+ this.registerHookSecret(secret)
1584
+ this._sessionHookSecrets.set(sessionId, secret)
1585
+ log.debug(`Registered hook secret for session ${sessionId}`)
1586
+ }
1587
+
1588
+ /**
1589
+ * Register a per-session hook secret so POST /permission accepts it.
1590
+ * Called by session-manager when a CliSession is created.
1591
+ */
1592
+ registerHookSecret(secret) {
1593
+ if (secret) this._hookSecrets.add(secret)
1594
+ }
1595
+
1596
+ /**
1597
+ * Find the CliSession whose hookSecret matches `secret`. Returns
1598
+ * `{ session, sessionId }` (sessionId is the chroxy-managed key, not
1599
+ * the upstream Claude conversation id) or `null` if no match.
1600
+ *
1601
+ * The sessionId is needed by the permission handler so it can populate
1602
+ * `permissionSessionMap[requestId]` for legacy hook-based permissions
1603
+ * (#2832). Without that mapping, a paired client whose token is bound
1604
+ * to the same session can never approve hook permissions — the
1605
+ * binding check at `permission_response` time finds no entry and
1606
+ * rejects with SESSION_TOKEN_MISMATCH.
1607
+ */
1608
+ _findSessionByHookSecret(secret) {
1609
+ if (!secret) return null
1610
+ // Scan _sessionHookSecrets — Map<sessionId, secret>
1611
+ for (const [sessionId, storedSecret] of this._sessionHookSecrets) {
1612
+ if (storedSecret === secret) {
1613
+ const entry = this.sessionManager?.getSession(sessionId)
1614
+ return entry?.session ? { session: entry.session, sessionId } : null
1615
+ }
1616
+ }
1617
+ // Legacy single-session mode — no chroxy sessionId surface, so
1618
+ // callers can still notify the session but must skip mapping.
1619
+ if (this.cliSession && this.cliSession._hookSecret === secret) {
1620
+ return { session: this.cliSession, sessionId: null }
1621
+ }
1622
+ return null
1623
+ }
1624
+
1625
+ /**
1626
+ * Remove a per-session hook secret when the session is destroyed.
1627
+ * Called by session-manager when a CliSession is destroyed.
1628
+ */
1629
+ unregisterHookSecret(secret) {
1630
+ if (secret) this._hookSecrets.delete(secret)
1631
+ }
1632
+
1633
+ /**
1634
+ * #5356: record whether the configured tunnel is a public quick
1635
+ * (trycloudflare) tunnel. Called by server-cli before tunnel startup so the
1636
+ * exposure snapshot in auth_ok reflects the public URL.
1637
+ * @param {boolean} active
1638
+ */
1639
+ setQuickTunnelActive(active) {
1640
+ this._quickTunnelActive = !!active
1641
+ }
1642
+
1643
+ /**
1644
+ * #5555 (sub-item 7): record the server's current public tunnel URL as a
1645
+ * `wss://` endpoint. Called by server-cli once the tunnel is up (and on a
1646
+ * URL rotation via broadcastTunnelUrlChanged). Surfaced in the
1647
+ * auth_bootstrap burst so a reconnecting client always re-learns the live
1648
+ * URL — the durable recovery path when a rotation happened while the client
1649
+ * was offline. Pass `null` to clear (no tunnel).
1650
+ * @param {string|null} wsUrl
1651
+ */
1652
+ setTunnelUrl(wsUrl) {
1653
+ this._tunnelUrl = wsUrl || null
1654
+ }
1655
+
1656
+ /** #5555 (sub-item 7): the current `wss://` tunnel URL, or null. */
1657
+ get tunnelUrl() {
1658
+ return this._tunnelUrl
1659
+ }
1660
+
1661
+ /**
1662
+ * #5555 (sub-item 7): a quick-tunnel recovery rotated the public URL. Record
1663
+ * the new URL (so reconnecting clients get it via auth_bootstrap) and push a
1664
+ * `tunnel_url_changed` frame to every authenticated client so they can
1665
+ * update the stored endpoint their reconnect path dials.
1666
+ *
1667
+ * BEST-EFFORT for tunnel-connected clients: they reach the server THROUGH
1668
+ * the old tunnel, which has just died, so the push usually will not arrive —
1669
+ * their durable recovery is the auth_bootstrap `tunnelUrl` on next connect.
1670
+ * LAN-connected clients (localhost dashboard, LAN clients) keep their socket
1671
+ * across the rotation and get the new URL immediately.
1672
+ *
1673
+ * SECURITY: the tunnel URL is connection metadata, not a secret (the QR code
1674
+ * shares it), so it goes to ALL authenticated clients including
1675
+ * pairing-bound ones — see docs/security/bearer-token-authority.md.
1676
+ *
1677
+ * @param {string} newWsUrl the new `wss://` endpoint
1678
+ * @param {string|null} [previousWsUrl] the prior `wss://` endpoint, if known
1679
+ */
1680
+ broadcastTunnelUrlChanged(newWsUrl, previousWsUrl = null) {
1681
+ if (!newWsUrl) return
1682
+ this.setTunnelUrl(newWsUrl)
1683
+ this._broadcast({
1684
+ type: 'tunnel_url_changed',
1685
+ url: newWsUrl,
1686
+ ...(previousWsUrl ? { previousUrl: previousWsUrl } : {}),
1687
+ })
1688
+ }
1689
+
1690
+ /**
1691
+ * #5356: exposure snapshot included in auth_ok (see sendPostAuthInfo).
1692
+ * `null` until start() has bound a socket — test harnesses that never call
1693
+ * start() simply omit the field from auth_ok.
1694
+ * @returns {{ lanBind: boolean, bindHost: string, quickTunnel: boolean }|null}
1695
+ */
1696
+ get exposure() {
1697
+ if (this._boundHost === undefined) return null
1698
+ return {
1699
+ lanBind: !isLoopbackHost(this._boundHost),
1700
+ bindHost: this._boundHost,
1701
+ quickTunnel: this._quickTunnelActive,
1702
+ }
1703
+ }
1704
+
1705
+ start(host) {
1706
+ // #5356: remember what we bound. `undefined` means the default
1707
+ // all-interfaces bind — record it as 0.0.0.0 so exposure reads true.
1708
+ this._boundHost = host ?? '0.0.0.0'
1709
+ // Create HTTP server — route handling extracted to http-routes.js
1710
+ this.httpServer = createServer(createHttpHandler(this))
1711
+
1712
+ // WebSocket server in noServer mode — we handle the upgrade manually
1713
+ this.wss = new WebSocketServer({
1714
+ noServer: true,
1715
+ maxPayload: this._maxPayload,
1716
+ // #5516 (epic #5514): permessage-deflate is enabled here for ALL
1717
+ // connections (tunnel bandwidth saving). It is then SKIPPED per-connection
1718
+ // for local/LAN peers in the 'upgrade' handler below (strip the client's
1719
+ // Sec-WebSocket-Extensions header before handleUpgrade) — local links
1720
+ // aren't bandwidth-bound, so compressing every frame just adds CPU
1721
+ // latency. Choosing skip-on-local over a blanket higher threshold keeps
1722
+ // tunnel behavior byte-for-byte unchanged.
1723
+ perMessageDeflate: {
1724
+ zlibDeflateOptions: { level: 6 },
1725
+ zlibInflateOptions: { chunkSize: 16 * 1024 },
1726
+ threshold: 1024,
1727
+ concurrencyLimit: 10,
1728
+ },
1729
+ })
1730
+
1731
+ this.httpServer.on('upgrade', (req, socket, head) => {
1732
+ // Enforce pre-auth connection limit to prevent FD exhaustion
1733
+ const pendingCount = this._countPendingConnections()
1734
+ if (pendingCount >= this._maxPendingConnections) {
1735
+ log.warn(`Pre-auth connection limit reached (${pendingCount}/${this._maxPendingConnections}), rejecting upgrade`)
1736
+ socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
1737
+ return
1738
+ }
1739
+ // #5516 (epic #5514): skip permessage-deflate for local/LAN peers. On a
1740
+ // fast local link compressing every message buys nothing (the link isn't
1741
+ // the bottleneck) and just adds CPU latency on the dev machine. Tunnel
1742
+ // connections KEEP deflate — that's where the WAN bandwidth saving is
1743
+ // real. `ws` negotiates permessage-deflate from the client's
1744
+ // Sec-WebSocket-Extensions request header, so deleting it for a local
1745
+ // peer makes `handleUpgrade` complete WITHOUT compression for THIS socket
1746
+ // only — the server-level config still applies to tunnel connections.
1747
+ // Security: isLocalOrLanPeer keys off the unspoofable socket peer; a
1748
+ // forged proxy header can only KEEP deflate (the safe default), never
1749
+ // remove it. See connection-locality.js.
1750
+ // #5578: stash the locality decision on `req` so the 'connection' handler
1751
+ // can stamp a per-client `usesDeflate` flag without re-classifying. A
1752
+ // LAN/loopback peer had its extension header stripped (no deflate); any
1753
+ // other peer keeps the server-level permessage-deflate. The flag drives
1754
+ // the deflate-aware delta-coalescing window (see EventNormalizer /
1755
+ // ws-broadcaster `_hasDeflateSubscriber`). Keyed off the unspoofable
1756
+ // socket peer, identical to the strip decision — they can never diverge.
1757
+ const localPeer = isLocalOrLanPeer(req)
1758
+ req._chroxyUsesDeflate = !localPeer
1759
+ // #6562: carry the same upgrade-time locality CLASSIFICATION (unspoofable
1760
+ // socket peer + proxy-header ABSENCE) to the encryption decision.
1761
+ // isLocalOrLanPeer is false when proxy headers are present, so a
1762
+ // cloudflared-tunneled connection (which arrives at socketIp 127.0.0.1 but
1763
+ // carries cf-connecting-ip) is NOT classified local — the loopback
1764
+ // encryption bypass (ws-history.js) must consult this so tunneled clients
1765
+ // still do the key_exchange instead of a plaintext downgrade. Header absence
1766
+ // is a weak positive signal (see #6564), but the security-relevant direction
1767
+ // is safe: an attacker can't strip cloudflared's edge-stamped header to gain
1768
+ // the bypass.
1769
+ req._chroxyLocalPeer = localPeer
1770
+ if (localPeer) {
1771
+ delete req.headers['sec-websocket-extensions']
1772
+ }
1773
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
1774
+ this.wss.emit('connection', ws, req)
1775
+ })
1776
+ })
1777
+
1778
+ this.wss.on('connection', (ws, req) => {
1779
+ const clientId = randomUUID().slice(0, 8)
1780
+ // Best-effort client IP for logging — prefers CF-Connecting-IP / X-Forwarded-For.
1781
+ const ip = getClientIp(req)
1782
+ // SECURITY: For localhost bypass decisions (e.g. skipping encryption),
1783
+ // use ONLY the raw TCP socket address. Proxy headers like x-forwarded-for
1784
+ // and cf-connecting-ip can be spoofed by an attacker to fake a localhost
1785
+ // origin and bypass encryption. req.socket.remoteAddress is set by the
1786
+ // kernel and cannot be forged over the network.
1787
+ const socketIp = req.socket.remoteAddress || 'unknown'
1788
+ // Rate-limit key: trusts proxy headers only when the TCP peer is loopback
1789
+ // (cloudflared or local proxy). Direct connections use socketIp to prevent
1790
+ // header spoofing that could exhaust another IP's rate-limit bucket.
1791
+ const rateLimitKey = getRateLimitKey(socketIp, req)
1792
+ this._clientManager.addClient(ws, {
1793
+ id: clientId,
1794
+ // #5563: stable back-reference to this client's socket so the
1795
+ // sessionId→clients reverse index (which stores `client`) can resolve
1796
+ // the `ws` for readyState + backpressure without a per-send Map lookup.
1797
+ _ws: ws,
1798
+ authenticated: false,
1799
+ // #5985b: a fresh client is never the primary token class until
1800
+ // handleAuthMessage proves it. Initialized false (not left undefined) so
1801
+ // the strict `=== true` user-shell gates fail closed even if a future
1802
+ // code path reads the field before auth completes.
1803
+ isPrimaryToken: false,
1804
+ mode: 'chat', // default to chat view
1805
+ activeSessionId: null,
1806
+ subscribedSessionIds: new Set(),
1807
+ // #5835 Phase 1: sessions this client opted into LIVE TERMINAL output for
1808
+ // (terminal_subscribe). Kept separate from subscribedSessionIds so a
1809
+ // Chat-tab client subscribed to a session doesn't receive its raw PTY
1810
+ // mirror bytes — only clients actually viewing the terminal do.
1811
+ terminalSessionIds: new Set(),
1812
+ isAlive: true,
1813
+ deviceInfo: null,
1814
+ ip,
1815
+ socketIp,
1816
+ rateLimitKey,
1817
+ // #5578: true for a non-LAN peer (tunnel / remote) that kept the
1818
+ // server-level permessage-deflate; false for LAN/loopback peers whose
1819
+ // extension header was stripped at upgrade. This is the upgrade-time
1820
+ // LOCALITY decision, not the actual negotiated extension — a remote
1821
+ // client that declines deflate in its handshake still reads true, which
1822
+ // is the intended (and safe) direction: those links pay the same WAN
1823
+ // per-frame cost. Drives the deflate-aware delta-coalescing window
1824
+ // — see EventNormalizer._resolveFlushIntervalMs. Set from the
1825
+ // unspoofable upgrade-time locality decision (req._chroxyUsesDeflate).
1826
+ usesDeflate: req._chroxyUsesDeflate === true,
1827
+ // #6562: true only for a genuine loopback/LAN peer with NO proxy headers
1828
+ // — i.e. NOT a cloudflared-tunneled connection. Gates the loopback
1829
+ // encryption bypass so a tunneled (proxied) connection to socketIp
1830
+ // 127.0.0.1 is not treated as trusted-local and still requires E2E.
1831
+ localPeer: req._chroxyLocalPeer === true,
1832
+ // #3404: visible defaults to true; mobile flips to false on backgrounding
1833
+ // so completion push notifications fire instead of being suppressed by
1834
+ // a still-alive but invisible WS connection.
1835
+ visible: true,
1836
+ _seq: 0, // monotonic sequence number for outbound messages
1837
+ encryptionState: null, // { sharedKey, sendNonce, recvNonce } when active
1838
+ encryptionPending: false, // true while waiting for key_exchange
1839
+ postAuthQueue: null, // queued messages during key exchange
1840
+ _flushing: false, // gates _send during setImmediate gaps in post-auth flush
1841
+ _flushOverflow: null, // messages that arrived during flush
1842
+ })
1843
+
1844
+ // Track pong responses for keepalive detection
1845
+ ws.on('pong', () => {
1846
+ const client = this.clients.get(ws)
1847
+ if (client) client.isAlive = true
1848
+ })
1849
+
1850
+ log.info(`Client ${clientId} connected (awaiting auth)`)
1851
+
1852
+ // When auth is disabled, auto-authenticate immediately
1853
+ if (!this.authRequired) {
1854
+ const client = this.clients.get(ws)
1855
+ client.authenticated = true
1856
+ client.authTime = Date.now()
1857
+ // --no-auth is dev-only and trusts itself — pin to the server's own
1858
+ // protocol version so version-gated broadcasts (e.g. #2849 tunnel
1859
+ // warming / ready via broadcastMinProtocolVersion) reach dev clients
1860
+ // instead of being silently filtered out.
1861
+ //
1862
+ // Assumption: a client connecting to a --no-auth dev server is built
1863
+ // from the same checkout as the server and therefore speaks
1864
+ // SERVER_PROTOCOL_VERSION (loopback bind enforces this in practice).
1865
+ // Stale-build clients on a newer --no-auth server may receive v2-shape
1866
+ // messages they can't parse — acceptable for dev, revisit if --no-auth
1867
+ // ever broadens beyond loopback. See packages/server/CONFIG.md#--no-auth-trust-model.
1868
+ client.protocolVersion = SERVER_PROTOCOL_VERSION
1869
+ this._sendPostAuthInfo(ws)
1870
+ this._broadcastClientJoined(client, ws)
1871
+ log.info(`Client ${clientId} auto-authenticated (--no-auth)`)
1872
+ }
1873
+
1874
+ // Auto-disconnect if not authenticated within 10s (skip when auth is disabled)
1875
+ const authTimeout = this.authRequired
1876
+ ? setTimeout(() => {
1877
+ const client = this.clients.get(ws)
1878
+ if (client && !client.authenticated) {
1879
+ this._send(ws, { type: 'auth_fail', reason: 'timeout' })
1880
+ ws.close()
1881
+ }
1882
+ }, 10_000)
1883
+ : null
1884
+
1885
+ ws.on('message', (raw) => {
1886
+ let msg
1887
+ try {
1888
+ msg = JSON.parse(raw.toString())
1889
+ } catch {
1890
+ return // ignore non-JSON
1891
+ }
1892
+ // Reject non-object top-level JSON up front. JSON.parse accepts
1893
+ // JSON "value" grammar, so `null`, `"string"`, `42`, `[]`, `true`
1894
+ // are all valid parses but none carry a `.type` field. Without
1895
+ // this guard, the downgrade check below would throw TypeError on
1896
+ // `null.type` and (worse) could be bypassed by a client sending
1897
+ // JSON `null` as a post-handshake plaintext frame — the
1898
+ // type-check would throw, control would escape to the outer
1899
+ // error handler, and _handleMessage would be called on the null.
1900
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
1901
+ return // ignore non-object payloads
1902
+ }
1903
+ // Decrypt incoming encrypted messages, and enforce encryption once
1904
+ // a key exchange has established it. Without this post-handshake
1905
+ // rejection, a buggy or malicious client could unilaterally downgrade
1906
+ // to plaintext after a successful key_exchange — the server would
1907
+ // happily process the plaintext frame as a normal message. Discovered
1908
+ // in the 2026-04-11 production readiness audit.
1909
+ //
1910
+ // On a downgrade attempt, we log server-side (diagnostics for the
1911
+ // operator) and close silently with 1008 + a policy-violation reason
1912
+ // in the WebSocket close frame. We deliberately do NOT send a
1913
+ // plaintext error envelope back — doing so would itself leak a
1914
+ // plaintext frame after a successful handshake, contradicting the
1915
+ // very invariant this check exists to enforce. The WebSocket close
1916
+ // reason string ('encryption required') is diagnostic enough for a
1917
+ // legitimate misconfigured client.
1918
+ const client = this.clients.get(ws)
1919
+ // #5555.6 — any inbound frame is proof of life. The client's 15s
1920
+ // heartbeat ping is the dominant signal, but ANY decoded frame (input,
1921
+ // subscribe, pong-as-message, …) resets the liveness flag so the 15s
1922
+ // keepalive sweep never terminates a client that is actively talking.
1923
+ // This is the "client ping IS liveness" half of #5555.6; the protocol
1924
+ // `pong` listener on the socket covers the server-initiated ping.
1925
+ if (client) client.isAlive = true
1926
+ if (client?.encryptionState) {
1927
+ if (msg.type !== 'encrypted') {
1928
+ log.error(`Plaintext frame from ${client.id} after encryption established (type=${msg?.type}); closing connection`)
1929
+ ws.close(1008, 'encryption required')
1930
+ return
1931
+ }
1932
+ const envParsed = EncryptedEnvelopeSchema.safeParse(msg)
1933
+ if (!envParsed.success) {
1934
+ log.error(`Invalid encrypted message envelope from ${client.id}`)
1935
+ ws.close()
1936
+ return
1937
+ }
1938
+ try {
1939
+ msg = decrypt(msg, client.encryptionState.sharedKey, client.encryptionState.recvNonce, DIRECTION_CLIENT)
1940
+ client.encryptionState.recvNonce++
1941
+ } catch (err) {
1942
+ log.error(`Decryption failed from ${client.id}: ${err.message}`)
1943
+ ws.close()
1944
+ return
1945
+ }
1946
+ }
1947
+ this._handleMessage(ws, msg).catch((err) => {
1948
+ log.error(`Unhandled error in message handler: ${err.message}`)
1949
+ if (err.stack) log.error(err.stack)
1950
+ try {
1951
+ this._send(ws, { type: 'server_error', message: sanitizeErrorMessage(err), recoverable: true })
1952
+ } catch {
1953
+ // Best-effort — client may already be disconnected
1954
+ }
1955
+ })
1956
+ })
1957
+
1958
+ ws.on('close', () => {
1959
+ clearTimeout(authTimeout)
1960
+ const client = this._clientManager.getClient(ws)
1961
+ if (client?._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
1962
+ log.info(`Client ${client?.id} disconnected`)
1963
+ if (client?.authenticated) {
1964
+ this._handleClientDeparture(client)
1965
+ }
1966
+ // #5510: if a pair requester (unauthenticated, connection-pending) drops
1967
+ // before resolution, deny + drop its queue entry and retract the host
1968
+ // banner so an abandoned request can't sit on a queue slot for its TTL.
1969
+ this._cleanupPairRequesterOnDisconnect(ws)
1970
+ // Do not remove rate limiter entries on disconnect — the limiter keys by IP,
1971
+ // so removing on disconnect would reset the shared bucket for all connections
1972
+ // from the same real IP. The sliding window's natural expiry cleans up entries.
1973
+ this._clientManager.removeClient(ws)
1974
+ })
1975
+
1976
+ ws.on('error', (err) => {
1977
+ log.error(`Client error: ${err.message}`)
1978
+ })
1979
+ })
1980
+
1981
+ this.wss.on('error', (err) => {
1982
+ log.error(`WebSocket server error: ${err.message}`)
1983
+ })
1984
+
1985
+ this.httpServer.on('error', (err) => {
1986
+ if (err.code === 'EADDRINUSE') {
1987
+ log.error(`Port ${this.port} is already in use — is another Chroxy instance running?`)
1988
+ process.exit(1)
1989
+ }
1990
+ log.error(`HTTP server error: ${err.message}`)
1991
+ })
1992
+
1993
+ this.httpServer.listen(this.port, host)
1994
+
1995
+ // #6277 — host-local user-shell approval listener. Started only when approval
1996
+ // is enabled at boot (off by default → the WsServer test harness is
1997
+ // untouched). See _startApprovalListener for why it's a separate
1998
+ // 127.0.0.1-only server rather than a main-port route.
1999
+ if (isUserShellApprovalRequired(this.config)) {
2000
+ this._startApprovalListener()
2001
+ }
2002
+
2003
+ // Detect Claude Code Web features (non-blocking)
2004
+ this._webTaskManager.detectFeatures().then(({ remote, teleport }) => {
2005
+ if (remote || teleport) {
2006
+ log.info(`Claude Code Web features detected: remote=${remote}, teleport=${teleport}`)
2007
+ }
2008
+ }).catch((err) => {
2009
+ log.warn(`Failed to detect Claude Code Web features: ${err.message} (non-critical, web features disabled)`)
2010
+ })
2011
+
2012
+ // Forward web task events to all authenticated clients
2013
+ this._webTaskManager.on('task_created', (task) => this._broadcast({ type: 'web_task_created', task }))
2014
+ this._webTaskManager.on('task_updated', (task) => this._broadcast({ type: 'web_task_updated', task }))
2015
+ this._webTaskManager.on('task_error', ({ taskId, message }) => this._broadcast({ type: 'web_task_error', taskId, message }))
2016
+
2017
+ // Broadcast structured log entries to dashboard clients.
2018
+ // Re-entrancy guard prevents infinite recursion when _broadcast() itself
2019
+ // logs (e.g. backpressure debug messages) and log level is set to debug.
2020
+ //
2021
+ // #4787 (P0 security): unscoped log entries (no entry.sessionId) MUST NOT
2022
+ // fan out to bound clients (mobile pairings into a single per-task
2023
+ // session) — pre-fix, server-side logs that lacked withSession() context
2024
+ // leaked PTY hex dumps, toolUseIds, prompt sizes and attachment names from
2025
+ // every session to every authenticated WS client. Most server logs are
2026
+ // unscoped today (only a handful of call sites use withSession()), so the
2027
+ // fall-through covered almost the entire log stream. Restrict unscoped
2028
+ // entries to unbound clients (operator dashboards have boundSessionId ==
2029
+ // null and legitimately want to see everything). The durable fix — a
2030
+ // loggerForSession factory + lint to force per-call-site scoping — is
2031
+ // tracked as a follow-up (#4792).
2032
+ let inLogBroadcast = false
2033
+ this._logListener = (entry) => {
2034
+ if (inLogBroadcast) return
2035
+ inLogBroadcast = true
2036
+ try {
2037
+ if (entry.sessionId) {
2038
+ this._broadcastToSession(entry.sessionId, { type: 'log_entry', ...entry })
2039
+ } else {
2040
+ // Use loose-equality null check so any non-null/undefined
2041
+ // boundSessionId (including the unlikely empty string) is treated
2042
+ // as bound — matches the comment above and the intent of #4787.
2043
+ this._broadcast(
2044
+ { type: 'log_entry', ...entry },
2045
+ (client) => client.boundSessionId == null
2046
+ )
2047
+ }
2048
+ } finally {
2049
+ inLogBroadcast = false
2050
+ }
2051
+ }
2052
+ addLogListener(this._logListener)
2053
+
2054
+ // Wire up unified event forwarding via EventNormalizer
2055
+ setupForwarding({
2056
+ normalizer: this._normalizer,
2057
+ sessionManager: this.sessionManager,
2058
+ cliSession: this.cliSession,
2059
+ devPreview: this._devPreview,
2060
+ checkpointManager: this._checkpointManager,
2061
+ pushManager: this.pushManager,
2062
+ permissionSessionMap: this._permissionSessionMap,
2063
+ questionSessionMap: this._questionSessionMap,
2064
+ // #4788 Wave 2: hand the question-route registration through a helper so
2065
+ // dispatch and routing-guard stay symmetric. When a question is
2066
+ // registered for session S, every currently-connected client that's
2067
+ // permitted to see broadcasts for S gets auto-subscribed to S — this
2068
+ // mirrors _broadcastToSession's recipient filter so the new
2069
+ // input-handlers guard naturally passes for legitimate viewers without
2070
+ // re-opening the cross-session hijack vector (unconnected / future
2071
+ // clients are still unable to answer).
2072
+ registerQuestionRoute: (toolUseId, sessionId) => this._registerQuestionRoute(toolUseId, sessionId),
2073
+ // #4798: symmetry with registerQuestionRoute — auto-subscribe eligible
2074
+ // clients to the permission's session at dispatch time so the
2075
+ // settings-handlers subscription guard naturally passes for legitimate
2076
+ // viewers (including the "view A → switch to B → respond" flow).
2077
+ registerPermissionRoute: (requestId, sessionId) => this._registerPermissionRoute(requestId, sessionId),
2078
+ broadcast: (msg, filter) => this._broadcast(msg, filter),
2079
+ broadcastToSession: (sid, msg, filter) => this._broadcastToSession(sid, msg, filter),
2080
+ broadcastSessionList: () => this._handlerCtx.transport.broadcastSessionList(),
2081
+ })
2082
+
2083
+ // #5555.6 — sweep authenticated clients every KEEPALIVE_SWEEP_MS. See
2084
+ // _keepaliveSweep for the liveness/eviction contract.
2085
+ this._pingInterval = setInterval(() => this._keepaliveSweep(), KEEPALIVE_SWEEP_MS)
2086
+
2087
+ // Prune stale auth failure entries every 60s
2088
+ this._authCleanupInterval = setInterval(() => {
2089
+ const now = Date.now()
2090
+ const cutoff = now - 5 * 60 * 1000
2091
+ for (const [ip, entry] of this._authFailures) {
2092
+ if (entry.firstFailure < cutoff) {
2093
+ this._authFailures.delete(ip)
2094
+ }
2095
+ }
2096
+ // Lenient bucket entries are short-lived (60s window + 30s block); drop
2097
+ // any whose window is fully expired and that aren't currently blocked.
2098
+ for (const [ip, entry] of this._benignPairAttempts) {
2099
+ const windowExpired = now - entry.windowStart > BENIGN_PAIR_WINDOW_MS
2100
+ const notBlocked = entry.blockedUntil <= now
2101
+ if (windowExpired && notBlocked) {
2102
+ this._benignPairAttempts.delete(ip)
2103
+ }
2104
+ }
2105
+ }, 60_000)
2106
+
2107
+ log.info(`Server listening on ${host || '0.0.0.0'}:${this.port} (${this.serverMode} mode)`)
2108
+ }
2109
+
2110
+ /**
2111
+ * #5821: wire the billing-canary snapshot provider. server-cli calls this
2112
+ * after constructing the monitor (which depends on this server's broadcast).
2113
+ * The provider is read by the `_historyCtx.billingCanary` getter to seed
2114
+ * `auth_ok`. `fn` returns the current snapshot or null.
2115
+ */
2116
+ setBillingCanaryProvider(fn) {
2117
+ this._billingCanaryProvider = typeof fn === 'function' ? fn : null
2118
+ }
2119
+
2120
+ /** Delegates to ws-history.js */
2121
+ _sendPostAuthInfo(ws, extra) { sendPostAuthInfo(this._historyCtx, ws, extra) }
2122
+ _replayHistory(ws, sessionId, opts) { replayHistory(this._historyCtx, ws, sessionId, opts) }
2123
+ _flushPostAuthQueue(ws, queue) { flushPostAuthQueue(this._historyCtx, ws, queue) }
2124
+ _sendSessionInfo(ws, sessionId) { sendSessionInfo(this._historyCtx, ws, sessionId) }
2125
+
2126
+ /** Route incoming client messages */
2127
+ async _handleMessage(ws, msg) {
2128
+ const client = this.clients.get(ws)
2129
+ if (!client) return
2130
+
2131
+ // Generate a correlation ID for tracing this message through the pipeline
2132
+ const correlationId = randomBytes(4).toString('hex')
2133
+
2134
+ // Auth handling (delegates to ws-auth.js)
2135
+ if (!client.authenticated) {
2136
+ if (msg.type === 'pair') {
2137
+ handlePairMessage(this._authCtx, ws, msg)
2138
+ } else if (msg.type === 'pair_request') {
2139
+ // #5510: camera-less device requests pairing. Same exposure class as
2140
+ // `pair` (unauthenticated, rate-limited, queue-capped). The connection
2141
+ // stays OPEN — the requester waits for `pair_result`.
2142
+ handlePairRequestMessage(this._authCtx, ws, msg)
2143
+ } else {
2144
+ handleAuthMessage(this._authCtx, ws, msg)
2145
+ }
2146
+ return
2147
+ }
2148
+ if (msg.type === 'auth') return
2149
+
2150
+ // Key exchange for E2E encryption (delegates to ws-auth.js)
2151
+ if (handleKeyExchange(this._authCtx, ws, msg)) return
2152
+
2153
+ // Respond to client-side heartbeat pings immediately (even during drain)
2154
+ if (msg.type === 'ping') {
2155
+ // #5515 (epic #5514): stamp a wall-clock (ms epoch) serverTs so clients
2156
+ // can split the ping/pong RTT into uplink (ping send → serverTs) and
2157
+ // downlink (serverTs → pong recv) halves. Wall-clock — not the monotonic
2158
+ // clock used by the #5414 watchdogs — because it crosses machines; the
2159
+ // client treats it as skew-prone and derives one-way numbers from the
2160
+ // RTT split, never from raw clock subtraction.
2161
+ this._send(ws, { type: 'pong', serverTs: Date.now() })
2162
+ return
2163
+ }
2164
+
2165
+ // Rate limiting — permission/question responses use a relaxed separate limiter (60/min).
2166
+ // client.rateLimitKey is the trusted rate-limit identity: CF-Connecting-IP when the
2167
+ // connection arrived via the loopback (cloudflared), otherwise the raw socket address.
2168
+ if (msg.type === 'permission_response' || msg.type === 'user_question_response') {
2169
+ const { allowed, retryAfterMs } = this._permissionRateLimiter.check(client.rateLimitKey)
2170
+ if (!allowed) {
2171
+ const label = msg.type === 'user_question_response' ? 'question responses' : 'permission responses'
2172
+ this._send(ws, { type: 'rate_limited', retryAfterMs, message: `Too many ${label}. Please slow down.` })
2173
+ return
2174
+ }
2175
+ } else if (msg.type === 'get_permission_input') {
2176
+ // #6551: the pre-write-diff pull has its own tight limiter (each call can
2177
+ // return up to 512K), so it can't burn the general budget or self-DoS.
2178
+ const { allowed, retryAfterMs } = this._permissionInputRateLimiter.check(client.rateLimitKey)
2179
+ if (!allowed) {
2180
+ this._send(ws, { type: 'rate_limited', retryAfterMs, message: 'Too many permission-input pulls. Please slow down.' })
2181
+ return
2182
+ }
2183
+ } else {
2184
+ const { allowed, retryAfterMs } = this._rateLimiter.check(client.rateLimitKey)
2185
+ if (!allowed) {
2186
+ this._send(ws, { type: 'rate_limited', retryAfterMs, message: 'Too many messages. Please slow down.' })
2187
+ return
2188
+ }
2189
+ }
2190
+
2191
+ // During drain, only allow permission_response and user_question_response
2192
+ if (this._draining && msg.type !== 'permission_response' && msg.type !== 'user_question_response') {
2193
+ if (msg.type === 'input') {
2194
+ this._send(ws, { type: 'server_status', message: 'Server is restarting, please wait...' })
2195
+ }
2196
+ return
2197
+ }
2198
+
2199
+ // Validate message schema before routing
2200
+ const parsed = ClientMessageSchema.safeParse(msg)
2201
+ if (!parsed.success) {
2202
+ const details = parsed.error.issues.map(i => i.message).join(', ')
2203
+ log.warn(`[${correlationId}] Invalid message from ${client.id}: ${details}`)
2204
+ this._send(ws, { type: 'error', code: 'INVALID_MESSAGE', correlationId, details })
2205
+ return
2206
+ }
2207
+ const validatedMsg = parsed.data
2208
+
2209
+ log.debug(`[${correlationId}] Handling ${validatedMsg.type} from ${client.id}`)
2210
+
2211
+ // Route based on server mode — pass correlationId in context
2212
+ const ctx = { ...this._handlerCtx, correlationId }
2213
+ try {
2214
+ if (this.sessionManager) {
2215
+ await handleSessionMessage(ws, client, validatedMsg, ctx)
2216
+ } else if (this.cliSession) {
2217
+ await handleCliMessage(ws, client, validatedMsg, ctx)
2218
+ }
2219
+ } catch (err) {
2220
+ log.error(`[${correlationId}] Handler error for ${validatedMsg.type}: ${err.message}`)
2221
+ this._send(ws, { type: 'server_error', correlationId, message: err.message, recoverable: true })
2222
+ }
2223
+ }
2224
+
2225
+ /** Delegate: re-send pending permissions (test compat) */
2226
+ _resendPendingPermissions(ws) {
2227
+ const client = this.clients.get(ws)
2228
+ this._permissions.resendPendingPermissions(ws, client)
2229
+ }
2230
+
2231
+ /** Public broadcast: send a message to all authenticated clients */
2232
+ broadcast(message) {
2233
+ this._broadcaster.broadcast(message)
2234
+ }
2235
+
2236
+ /**
2237
+ * Broadcast a message only to authenticated clients that advertised at
2238
+ * least `minProtocolVersion` during auth. See WsBroadcaster for details.
2239
+ */
2240
+ broadcastMinProtocolVersion(minProtocolVersion, message) {
2241
+ this._broadcaster.broadcastMinProtocolVersion(minProtocolVersion, message)
2242
+ }
2243
+
2244
+ /** Broadcast a message to all authenticated clients matching a filter */
2245
+ _broadcast(message, filter) {
2246
+ this._broadcaster._broadcast(message, filter)
2247
+ }
2248
+
2249
+ /**
2250
+ * Broadcast a session-scoped message to clients viewing that session.
2251
+ * Tags the message with `sessionId` so clients can route it to the correct
2252
+ * session state. By default only delivers to clients whose activeSessionId
2253
+ * matches — prevents cross-session info leakage and bandwidth waste.
2254
+ * Pass a custom filter to override the default recipient selection when needed.
2255
+ */
2256
+ _broadcastToSession(sessionId, message, filter) {
2257
+ this._broadcaster._broadcastToSession(sessionId, message, filter)
2258
+ }
2259
+
2260
+ /**
2261
+ * #5510: fan a `pair_pending` (or any pairing-approval surface event) out to
2262
+ * HOST-LEVEL clients only — authenticated clients with no `boundSessionId`.
2263
+ * A session-bound (share-a-session) token must NOT see host-wide pair
2264
+ * requests, mirroring the `host_status_request` authority gate. The verify
2265
+ * code in `msg` is server-generated; deviceName is attacker-controlled and is
2266
+ * relayed verbatim as plain text (surfaces escape on render).
2267
+ */
2268
+ _broadcastPairPending(message) {
2269
+ this._broadcast(message, (client) => !client.boundSessionId)
2270
+ }
2271
+
2272
+ /** #5510: retract a resolved pending request from every host surface. */
2273
+ _broadcastPairResolved(requestId, reason) {
2274
+ this._broadcastPairPending({ type: 'pair_resolved', requestId, reason })
2275
+ }
2276
+
2277
+ /**
2278
+ * #6536 (PR-2 of #5966): fan a live repo-events delta out to HOST-LEVEL
2279
+ * clients only — authenticated clients with no `boundSessionId` — mirroring
2280
+ * the `repo_events_request` survey's host-authority gate. Called by the
2281
+ * GitHub-webhook receiver after a normalized event is pushed onto the store,
2282
+ * so a connected Control Room pane updates without a Refresh. A session-bound
2283
+ * (share-a-session) token must NOT see host repo activity. The event is the
2284
+ * same normalized shape the survey serves; `generatedAt` is the broadcast time.
2285
+ */
2286
+ _broadcastRepoEvent(event) {
2287
+ if (!event) return
2288
+ this._broadcast(
2289
+ { type: 'repo_events_delta', generatedAt: new Date().toISOString(), event },
2290
+ (client) => !client.boundSessionId,
2291
+ )
2292
+ }
2293
+
2294
+ /**
2295
+ * #5510: deliver a terminal `pair_result` to the requester's still-open
2296
+ * connection (if present) and drop the tracking entry. On approve the result
2297
+ * carries the issued token; on deny/expire/disconnect it carries a reason.
2298
+ * If the requester's connection is gone, the entry is just dropped.
2299
+ */
2300
+ _resolvePairRequester(requestId, result) {
2301
+ const ws = this._pairRequesters.get(requestId)
2302
+ this._pairRequesters.delete(requestId)
2303
+ if (!ws || ws.readyState !== 1) return
2304
+ this._send(ws, { type: 'pair_result', requestId, ...result })
2305
+ }
2306
+
2307
+ /**
2308
+ * #5510: a requester's connection closed. If it had an outstanding pending
2309
+ * request, remove it from the queue (freeing the slot) and retract the host
2310
+ * banner. No `pair_result` is sent (the socket is gone).
2311
+ */
2312
+ _cleanupPairRequesterOnDisconnect(ws) {
2313
+ if (this._pairRequesters.size === 0) return
2314
+ for (const [requestId, reqWs] of this._pairRequesters) {
2315
+ if (reqWs !== ws) continue
2316
+ this._pairRequesters.delete(requestId)
2317
+ if (this._pairingManager) this._pairingManager.denyPendingRequest(requestId)
2318
+ this._broadcastPairResolved(requestId, 'disconnected')
2319
+ }
2320
+ }
2321
+
2322
+ /**
2323
+ * #4788 Wave 2: register an AskUserQuestion route for `toolUseId` against
2324
+ * `sessionId` AND auto-subscribe every currently-eligible authenticated
2325
+ * client to `sessionId`. This keeps the input-handler's subscription guard
2326
+ * (handlers/input-handlers.js — the "unbound client must be subscribed or
2327
+ * active on the question's session" check) symmetric with
2328
+ * `_broadcastToSession`'s default recipient filter: any client that was
2329
+ * eligible to RECEIVE the question is now eligible to ANSWER it, even after
2330
+ * a `switch_session` flips their `activeSessionId` away.
2331
+ *
2332
+ * Wave 1 closed a cross-session answer-hijack vector (#4788) by requiring
2333
+ * unbound clients to be subscribed before routing a `user_question_response`.
2334
+ * That broke the legitimate "view A → get question for A → switch to B →
2335
+ * answer" flow because `switch_session` only adds the *new* target to
2336
+ * `subscribedSessionIds`; the originating session A was in neither set.
2337
+ * Auto-subscribing at dispatch time means the client that legitimately
2338
+ * received the question keeps the membership it needs to answer it.
2339
+ *
2340
+ * Bound clients are filtered out so a client paired to session X can never
2341
+ * be quietly subscribed to session Y. Unbound clients always get added —
2342
+ * matching `_broadcastToSession`'s default filter (which only requires
2343
+ * `activeSessionId === sessionId || subscribedSessionIds.has(sessionId)`,
2344
+ * but auto-subscribe seeds the latter so the filter passes for everyone
2345
+ * currently connected). Clients that connect AFTER dispatch are still
2346
+ * unable to answer; that's the desired hijack-prevention property.
2347
+ */
2348
+ _registerQuestionRoute(toolUseId, sessionId) {
2349
+ this._questionSessionMap.set(toolUseId, sessionId)
2350
+ if (!sessionId) return
2351
+ for (const [, client] of this.clients) {
2352
+ if (!client.authenticated) continue
2353
+ // Don't auto-subscribe a client bound to a *different* session — the
2354
+ // bound binding is the security contract for that client.
2355
+ if (client.boundSessionId && client.boundSessionId !== sessionId) continue
2356
+ if (!client.subscribedSessionIds) continue
2357
+ // #5563: route through the index-maintaining helper.
2358
+ this._clientManager.subscribe(client, sessionId)
2359
+ }
2360
+ }
2361
+
2362
+ /**
2363
+ * #4798 (P0 symmetry with #4788): register a permission route for
2364
+ * `requestId` against `sessionId` AND auto-subscribe every currently-eligible
2365
+ * authenticated client to `sessionId`. Mirrors `_registerQuestionRoute` — the
2366
+ * settings-handler's permission_response subscription guard (the "unbound
2367
+ * client must be subscribed or active on the permission's session" check)
2368
+ * stays symmetric with `_broadcastToSession`'s default recipient filter:
2369
+ * any client that was eligible to RECEIVE the permission request is now
2370
+ * eligible to RESPOND to it, even after a `switch_session` flips their
2371
+ * `activeSessionId` away.
2372
+ *
2373
+ * Without the auto-subscribe at dispatch, the Wave 1 guard would silently
2374
+ * drop the legitimate "view A → get permission for A → switch to B →
2375
+ * respond" flow because `switch_session` only adds the new target to
2376
+ * `subscribedSessionIds`; the originating session A would be in neither
2377
+ * set after the switch.
2378
+ *
2379
+ * Same bound-client filter as the question variant: clients paired to a
2380
+ * different session never get quietly subscribed elsewhere. Clients that
2381
+ * connect AFTER dispatch are still unable to respond — that's the desired
2382
+ * hijack-prevention property.
2383
+ */
2384
+ _registerPermissionRoute(requestId, sessionId) {
2385
+ // #5704: a route may be re-registered for the same requestId (e.g. the
2386
+ // resend-on-reconnect path re-runs the dispatch). Don't double-count the
2387
+ // refcount — only the FIRST registration of a requestId seeds the per-client
2388
+ // permission-induced subscriptions. Subsequent re-registrations just re-seed
2389
+ // subscribedSessionIds (idempotent) without re-incrementing.
2390
+ const isNewRoute = !this._permissionSessionMap.has(requestId)
2391
+ this._permissionSessionMap.set(requestId, sessionId)
2392
+ if (!sessionId) return
2393
+ for (const [, client] of this.clients) {
2394
+ if (!client.authenticated) continue
2395
+ if (client.boundSessionId && client.boundSessionId !== sessionId) continue
2396
+ if (!client.subscribedSessionIds) continue
2397
+ // #5704: decide whether THIS route's auto-subscribe is permission-induced
2398
+ // (refcounted + torn-down) or rides on an existing EXPLICIT subscription
2399
+ // (left untouched). A subscription is EXPLICIT iff the client is subscribed
2400
+ // with NO permission refcount — an explicit switch_session/subscribe_sessions
2401
+ // ADOPTS by zeroing the refcount. The ACTIVE session is deliberately NOT
2402
+ // treated as ownership here: a client active on A at dispatch is exactly the
2403
+ // #4798 "view A → switch to B → respond" case — it WILL switch away, and we
2404
+ // must hold a refcount so the subscription is torn down after resolve. The
2405
+ // teardown's own active-session guard still protects a client that stays
2406
+ // active on the session. So:
2407
+ // - subscribed && refcount === 0 -> explicit ownership: don't count.
2408
+ // - refcount > 0 -> already permission-owned: count up
2409
+ // (a second concurrent permission).
2410
+ // - otherwise -> permission-induced subscribe: count.
2411
+ const existingRefcount = this._permissionSubs.get(client.id)?.get(sessionId) || 0
2412
+ const explicitlyOwned = client.subscribedSessionIds.has(sessionId) && existingRefcount === 0
2413
+ // #5563: route through the index-maintaining helper.
2414
+ this._clientManager.subscribe(client, sessionId)
2415
+ if (isNewRoute && !explicitlyOwned) {
2416
+ this._incPermissionSub(client.id, sessionId)
2417
+ }
2418
+ }
2419
+ }
2420
+
2421
+ /**
2422
+ * #5704: tear down a permission route registered by `_registerPermissionRoute`.
2423
+ * Called at EVERY resolve / expire / cleanup site (the WS + HTTP resolver, the
2424
+ * HTTP-hook cleanup()/destroy(), the session-destroy sweep) so a permission-
2425
+ * induced subscription never outlives its permission. Idempotent: deleting an
2426
+ * already-gone requestId is a no-op (returns without touching refcounts).
2427
+ *
2428
+ * Decrements every connected client's permission-induced refcount for the
2429
+ * route's session and, when a client's count reaches zero, removes the
2430
+ * auto-subscription UNLESS the client is the active session or still
2431
+ * explicitly subscribed (adoption — see _adoptPermissionSubscription). The
2432
+ * #4798 cross-tab flow stays intact because teardown only fires AFTER the
2433
+ * permission is resolved/expired; while it is live the refcount is > 0.
2434
+ * @param {string} requestId
2435
+ */
2436
+ _unregisterPermissionRoute(requestId) {
2437
+ if (!this._permissionSessionMap.has(requestId)) return
2438
+ const sessionId = this._permissionSessionMap.get(requestId)
2439
+ this._permissionSessionMap.delete(requestId)
2440
+ if (!sessionId) return
2441
+ // Decrement for every connected client that holds a permission-induced
2442
+ // refcount on this session. We iterate this.clients (connected clients); a
2443
+ // client that already disconnected had its refcount entry purged by
2444
+ // _handleClientDeparture, so it's absent here and never double-decremented,
2445
+ // and _decPermissionSub is a no-op for a client with no entry for sessionId.
2446
+ for (const [, client] of this.clients) {
2447
+ this._decPermissionSub(client, sessionId)
2448
+ }
2449
+ }
2450
+
2451
+ /**
2452
+ * #5704: increment the permission-induced subscription refcount for
2453
+ * (clientId, sessionId). Lazily creates the per-client Map.
2454
+ * @private
2455
+ */
2456
+ _incPermissionSub(clientId, sessionId) {
2457
+ let perSession = this._permissionSubs.get(clientId)
2458
+ if (!perSession) {
2459
+ perSession = new Map()
2460
+ this._permissionSubs.set(clientId, perSession)
2461
+ }
2462
+ perSession.set(sessionId, (perSession.get(sessionId) || 0) + 1)
2463
+ }
2464
+
2465
+ /**
2466
+ * #5704: decrement the permission-induced subscription refcount for `client`
2467
+ * on `sessionId`. When it hits zero, drop the bookkeeping entry and unsubscribe
2468
+ * the client from the session — but ONLY if the client neither has it as its
2469
+ * active session NOR is explicitly subscribed (adoption zeroes the refcount, so
2470
+ * a still-counted entry here means no explicit subscribe happened). Never
2471
+ * drives the count negative: a client with no counted entry is a no-op.
2472
+ * @private
2473
+ */
2474
+ _decPermissionSub(client, sessionId) {
2475
+ const perSession = this._permissionSubs.get(client.id)
2476
+ if (!perSession) return
2477
+ const count = perSession.get(sessionId)
2478
+ if (!count) return
2479
+ if (count > 1) {
2480
+ perSession.set(sessionId, count - 1)
2481
+ return
2482
+ }
2483
+ // Last permission-induced reference for this (client, session) is gone.
2484
+ perSession.delete(sessionId)
2485
+ if (perSession.size === 0) this._permissionSubs.delete(client.id)
2486
+ // Don't tear down a subscription the client still actively views. An
2487
+ // EXPLICIT subscribe would have adopted/zeroed the refcount, so reaching
2488
+ // here (count was > 0) already means no explicit subscribe happened — only
2489
+ // the transient active-session case still needs guarding before unsubscribe.
2490
+ if (client.activeSessionId === sessionId) return
2491
+ this._clientManager.unsubscribe(client, sessionId)
2492
+ }
2493
+
2494
+ /**
2495
+ * #5704: an explicit subscribe (switch_session / subscribe_sessions /
2496
+ * session-create auto-subscribe) ADOPTS the subscription for (client,
2497
+ * sessionId): it zeroes any permission-induced refcount so a later permission
2498
+ * teardown can never unsubscribe a client that asked to watch the session.
2499
+ * Wired into transport.subscribeClient so every explicit subscribe path runs
2500
+ * it; the permission auto-subscribe goes straight through _clientManager and
2501
+ * therefore does NOT trigger adoption of its own refcount.
2502
+ * @private
2503
+ */
2504
+ _adoptPermissionSubscription(clientId, sessionId) {
2505
+ const perSession = this._permissionSubs.get(clientId)
2506
+ if (!perSession) return
2507
+ if (perSession.delete(sessionId) && perSession.size === 0) {
2508
+ this._permissionSubs.delete(clientId)
2509
+ }
2510
+ }
2511
+
2512
+ /** Count unauthenticated connections for pre-auth limit enforcement */
2513
+ _countPendingConnections() {
2514
+ return this._clientManager.countPending()
2515
+ }
2516
+
2517
+ /** Get list of connected clients for auth_ok payload */
2518
+ _getConnectedClientList() {
2519
+ return this._clientManager.getConnectedList()
2520
+ }
2521
+
2522
+ /** Broadcast client_joined to all OTHER authenticated clients */
2523
+ _broadcastClientJoined(newClient, excludeWs) {
2524
+ this._broadcaster._broadcastClientJoined(newClient, excludeWs)
2525
+ }
2526
+
2527
+ /** Broadcast client_left to all OTHER authenticated clients */
2528
+ _broadcastClientLeft(departingClient) {
2529
+ this._broadcaster._broadcastClientLeft(departingClient)
2530
+ }
2531
+
2532
+ /**
2533
+ * #5555.6 — one keepalive sweep over all authenticated clients.
2534
+ *
2535
+ * Liveness contract: `client.isAlive` is set true by ANY inbound frame
2536
+ * (ws.on('message')) and by the protocol-level `pong` handler, so a client
2537
+ * running its 15s heartbeat ping always reads alive at the 15s sweep. Each
2538
+ * sweep clears the flag on live clients and pings them (to hold Cloudflare /
2539
+ * mobile-OS idle timeouts open for peers that don't initiate). A client that
2540
+ * goes truly silent fails the `!isAlive` check on the sweep AFTER the one that
2541
+ * cleared its flag — detection in 15–30s, ~2× the client cadence (was up to
2542
+ * ~60s with the old 30s sweep).
2543
+ *
2544
+ * Eviction goes through the sanctioned departure path so the
2545
+ * sessionId→clients reverse index (WsClientManager) and any primary-client
2546
+ * claim (#5589) are released atomically — the index lint rejects raw
2547
+ * mutations. `_handleClientDeparture` runs first (it reads client state),
2548
+ * then `removeClient` updates the index, then we terminate the socket.
2549
+ */
2550
+ _keepaliveSweep() {
2551
+ for (const [ws, client] of this.clients) {
2552
+ if (!client.authenticated) continue
2553
+ if (ws.readyState !== 1) continue
2554
+ if (!client.isAlive) {
2555
+ log.info(`Client ${client.id} unresponsive, terminating`)
2556
+ this._handleClientDeparture(client)
2557
+ this._clientManager.removeClient(ws)
2558
+ try { ws.terminate() } catch {}
2559
+ continue
2560
+ }
2561
+ client.isAlive = false
2562
+ try { ws.ping() } catch {}
2563
+ }
2564
+ }
2565
+
2566
+ /** Handle cleanup when an authenticated client disconnects or is terminated */
2567
+ _handleClientDeparture(departingClient) {
2568
+ // #5563: vacate primary for every session this client owned. Promotion
2569
+ // policy is NOBODY-UNTIL-CLAIM — we clear the slot (broadcast null) rather
2570
+ // than auto-promote an observer, so a backgrounded viewer is never silently
2571
+ // handed the session; the next claim_primary (or first input) takes over.
2572
+ // This matches the pre-#5563 disconnect behaviour exactly.
2573
+ for (const sessionId of this._clientManager.clearPrimaryForClient(departingClient.id)) {
2574
+ this._announcePrimary(sessionId, null)
2575
+ }
2576
+
2577
+ // #5837: this client's terminal subscriptions are gone. Clear them first (the
2578
+ // client is still in `this.clients` until removeClient runs after departure),
2579
+ // then re-sync each watched session's mirror so the coalescer stops when this
2580
+ // was the last viewer.
2581
+ if (departingClient.terminalSessionIds && departingClient.terminalSessionIds.size > 0) {
2582
+ const watched = [...departingClient.terminalSessionIds]
2583
+ departingClient.terminalSessionIds.clear()
2584
+ for (const sessionId of watched) this._syncTerminalMirror(sessionId)
2585
+ }
2586
+
2587
+ // Release this client's ownership of any push tokens it registered.
2588
+ // Uses ref-counted release so a token registered by multiple
2589
+ // concurrent connections (multi-device or reconnect-race) isn't
2590
+ // stripped from the registry until the last owner goes away.
2591
+ //
2592
+ // Prevents the long-lived-token-hijack pattern documented in the
2593
+ // 2026-04-11 audit (blocker 6): an attacker who authenticates,
2594
+ // registers their own ExponentPushToken, and disconnects would
2595
+ // otherwise keep receiving future permission prompts indefinitely.
2596
+ // Tokens are preserved across disconnect only if the client re-
2597
+ // registers them on reconnect, or if another active client still
2598
+ // owns them.
2599
+ if (departingClient._ownedPushTokens && this.pushManager) {
2600
+ for (const token of departingClient._ownedPushTokens) {
2601
+ this.pushManager.releaseTokenOwner(token, departingClient.id)
2602
+ }
2603
+ departingClient._ownedPushTokens.clear()
2604
+ }
2605
+
2606
+ // #5704: drop this client's permission-induced subscription bookkeeping so
2607
+ // a disconnected client never leaks a per-client Map entry (and can never be
2608
+ // double-decremented by a later _unregisterPermissionRoute — the entry is
2609
+ // gone). The reverse-index membership is purged separately by removeClient.
2610
+ this._permissionSubs.delete(departingClient.id)
2611
+
2612
+ // Broadcast client_left to remaining authenticated clients
2613
+ this._broadcastClientLeft(departingClient)
2614
+ }
2615
+
2616
+ /**
2617
+ * Input adoption path (#5563). Called only for input that already PASSED the
2618
+ * input_conflict gate — i.e. the session was idle, or the sender is already
2619
+ * primary. Accepted input adopts primary (`force: true`): the server cannot
2620
+ * distinguish "same user, second device" from "shared-session observer"
2621
+ * without identity, and blocking adoption here strands a solo user's second
2622
+ * device behind input_conflict for the rest of the run it just started. The
2623
+ * mid-run steal is still prevented by the conflict gate itself; true
2624
+ * observe-only enforcement is client-role work (#5281) built on the explicit
2625
+ * `claim_primary` path below, which IS sticky (rejects without `force`).
2626
+ * Broadcasts `primary_changed` (legacy) + `session_role` (new) only on an
2627
+ * actual change.
2628
+ */
2629
+ _updatePrimary(sessionId, clientId) {
2630
+ if (!sessionId) return
2631
+ const res = this._clientManager.claimPrimary(sessionId, clientId, { force: true })
2632
+ if (res.changed) this._announcePrimary(sessionId, clientId)
2633
+ }
2634
+
2635
+ /**
2636
+ * Explicit claim / hand-off path (#5563). Returns the claim result so the
2637
+ * handler can tell the requester whether it succeeded or was rejected
2638
+ * (observe-only: another client already owns the session and no hand-off was
2639
+ * authorised). `force` overrides an existing owner for an operator-driven
2640
+ * hand-off. Broadcasts on an actual change.
2641
+ * @returns {{ changed: boolean, rejected?: boolean, primaryClientId: string|undefined }}
2642
+ */
2643
+ _claimPrimary(sessionId, clientId, opts = {}) {
2644
+ if (!sessionId) return { changed: false, primaryClientId: undefined }
2645
+ const res = this._clientManager.claimPrimary(sessionId, clientId, opts)
2646
+ if (res.changed) this._announcePrimary(sessionId, clientId)
2647
+ return res
2648
+ }
2649
+
2650
+ /** Clear the primary slot for a session and announce the vacancy (#5563). */
2651
+ _clearPrimary(sessionId) {
2652
+ if (!sessionId) return
2653
+ const prev = this._clientManager.clearPrimary(sessionId)
2654
+ if (prev !== undefined) this._announcePrimary(sessionId, null)
2655
+ }
2656
+
2657
+ /**
2658
+ * #5837: recompute whether ANY connected client is subscribed to a session's
2659
+ * live terminal mirror, and toggle the session's coalescer accordingly. Called
2660
+ * after every terminal-subscription change (subscribe / unsubscribe / client
2661
+ * departure) so the mirror runs only while at least one viewer is watching.
2662
+ * Only claude-tui sessions expose setTerminalMirrorActive; others have no PTY.
2663
+ */
2664
+ _syncTerminalMirror(sessionId) {
2665
+ if (!sessionId) return
2666
+ const entry = this.sessionManager.getSession?.(sessionId)
2667
+ if (typeof entry?.session?.setTerminalMirrorActive !== 'function') return
2668
+ let active = false
2669
+ for (const client of this.clients.values()) {
2670
+ // Count a client only if it would actually RECEIVE terminal_output — the
2671
+ // SAME predicate ws-forwarding's terminalSubscriberFilter delivers on, so
2672
+ // the coalescer gate and the delivery audience can never diverge (#5844
2673
+ // review). Shared via terminalMirrorRecipient (audit P1-2).
2674
+ if (terminalMirrorRecipient(client, sessionId)) {
2675
+ active = true
2676
+ break
2677
+ }
2678
+ }
2679
+ entry.session.setTerminalMirrorActive(active)
2680
+ }
2681
+
2682
+ /**
2683
+ * Announce the current primary for a session to every subscriber (#5563).
2684
+ * Emits BOTH the legacy `primary_changed` envelope (so existing clients keep
2685
+ * working unchanged) AND the new `session_role` envelope that names the
2686
+ * primary and lets a client compute its own role (primary iff
2687
+ * primaryClientId === its own clientId, else observer; null === unclaimed).
2688
+ * @param {string} sessionId
2689
+ * @param {string|null} clientId - the new primary, or null when vacated
2690
+ */
2691
+ _announcePrimary(sessionId, clientId) {
2692
+ this._broadcastToSession(sessionId, {
2693
+ type: 'primary_changed',
2694
+ sessionId,
2695
+ clientId,
2696
+ })
2697
+ this._broadcastToSession(sessionId, {
2698
+ type: 'session_role',
2699
+ sessionId,
2700
+ primaryClientId: clientId,
2701
+ })
2702
+ }
2703
+
2704
+ /**
2705
+ * Broadcast a server-side error to all authenticated clients.
2706
+ * @param {'tunnel'|'session'|'permission'|'general'} category
2707
+ * @param {string} message - Human-readable error description
2708
+ * @param {boolean} recoverable - true for warnings, false for fatal errors
2709
+ * @param {string|null} [sessionId] - Optional session ID for scoped errors
2710
+ */
2711
+ broadcastError(category, message, recoverable = true, sessionId = null) {
2712
+ this._broadcaster.broadcastError(category, message, recoverable, sessionId)
2713
+ }
2714
+
2715
+ /**
2716
+ * Broadcast a server status update to all authenticated clients.
2717
+ * Used for non-error status updates like recovery notifications.
2718
+ * @param {string} message - Human-readable status message
2719
+ */
2720
+ broadcastStatus(message) {
2721
+ this._broadcaster.broadcastStatus(message)
2722
+ }
2723
+
2724
+ /**
2725
+ * Broadcast a shutdown notification to all authenticated clients.
2726
+ * Sent before the server goes down so the app can show reason + ETA.
2727
+ *
2728
+ * Note: This is a global broadcast (not per-session), so server_shutdown
2729
+ * is intentionally not listed in TRANSIENT_EVENTS in session-manager.js.
2730
+ *
2731
+ * @param {'restart'|'shutdown'|'crash'} reason - Why the server is going down
2732
+ * @param {number} restartEtaMs - Estimated ms until server is back (0 = not coming back)
2733
+ */
2734
+ broadcastShutdown(reason, restartEtaMs) {
2735
+ this._broadcaster.broadcastShutdown(reason, restartEtaMs)
2736
+ }
2737
+
2738
+ /** Set the draining state. When draining, new input is rejected. */
2739
+ setDraining(draining) {
2740
+ this._draining = !!draining
2741
+ }
2742
+
2743
+ /** Count of authenticated, connected clients */
2744
+ get authenticatedClientCount() {
2745
+ return this._clientManager.authenticatedCount
2746
+ }
2747
+
2748
+ /** Check if any authenticated client is actively viewing the given session */
2749
+ hasActiveViewersForSession(sessionId) {
2750
+ return this._clientManager.hasActiveViewers(sessionId)
2751
+ }
2752
+
2753
+ /** Send JSON to a single client (delegates to extracted ws-client-sender) */
2754
+ _send(ws, message) {
2755
+ const client = this.clients.get(ws)
2756
+ // #5721: propagate the delivery boolean so callers gating crypto state on a
2757
+ // frame reaching the wire (the eager handshake's auth_ok) can observe a
2758
+ // swallowed send failure. Other callers ignore the return, unchanged.
2759
+ return this._clientSend(ws, client, message)
2760
+ }
2761
+
2762
+ /**
2763
+ * Clear all pending permission requests across both subsystems.
2764
+ *
2765
+ * Covers:
2766
+ * - Legacy HTTP hook permissions held in this._pendingPermissions (via ws-permissions.js)
2767
+ * - SDK in-process permissions held by each session's PermissionManager
2768
+ *
2769
+ * Called by close() automatically. Exposed as a public method so callers can
2770
+ * drain permissions independently (e.g. before a controlled restart).
2771
+ */
2772
+ clearAllPendingPermissions() {
2773
+ // Legacy HTTP hook permissions: auto-deny and clear
2774
+ this._permissions.destroy()
2775
+
2776
+ // SDK in-process permissions: auto-deny via each session's PermissionManager
2777
+ if (this.sessionManager?._sessions instanceof Map) {
2778
+ for (const [, entry] of this.sessionManager._sessions) {
2779
+ try {
2780
+ entry.session?._permissions?.clearAll()
2781
+ } catch {}
2782
+ }
2783
+ }
2784
+ }
2785
+
2786
+ /** Graceful shutdown */
2787
+ close() {
2788
+ // Remove PairingManager listeners to prevent post-shutdown broadcasts
2789
+ if (this._pairingManager && this._pairingRefreshedHandler) {
2790
+ this._pairingManager.off('pairing_refreshed', this._pairingRefreshedHandler)
2791
+ this._pairingRefreshedHandler = null
2792
+ }
2793
+ if (this._pairingManager && this._pendingRequestExpiredHandler) {
2794
+ this._pairingManager.off('pending_request_expired', this._pendingRequestExpiredHandler)
2795
+ this._pendingRequestExpiredHandler = null
2796
+ }
2797
+ this._pairRequesters.clear()
2798
+
2799
+ // Remove TokenManager listener to prevent post-shutdown broadcasts
2800
+ if (this._tokenManager && this._tokenRotatedHandler) {
2801
+ this._tokenManager.off('token_rotated', this._tokenRotatedHandler)
2802
+ this._tokenRotatedHandler = null
2803
+ }
2804
+
2805
+ // Remove SessionManager listeners to prevent the closed WsServer from
2806
+ // being kept alive by a long-lived SessionManager. Without this, a server
2807
+ // recreated against the same SessionManager would receive duplicated
2808
+ // events on every old + new instance (#3060).
2809
+ if (this.sessionManager && typeof this.sessionManager.off === 'function') {
2810
+ if (this._sessionCreatedHandler) {
2811
+ this.sessionManager.off('session_created', this._sessionCreatedHandler)
2812
+ this._sessionCreatedHandler = null
2813
+ }
2814
+ if (this._sessionDestroyedHandler) {
2815
+ this.sessionManager.off('session_destroyed', this._sessionDestroyedHandler)
2816
+ this._sessionDestroyedHandler = null
2817
+ }
2818
+ if (this._sessionEventAuditHandler) {
2819
+ this.sessionManager.off('session_event', this._sessionEventAuditHandler)
2820
+ this._sessionEventAuditHandler = null
2821
+ }
2822
+ }
2823
+
2824
+ if (this._pingInterval) {
2825
+ clearInterval(this._pingInterval)
2826
+ this._pingInterval = null
2827
+ }
2828
+ if (this._authCleanupInterval) {
2829
+ clearInterval(this._authCleanupInterval)
2830
+ this._authCleanupInterval = null
2831
+ }
2832
+
2833
+ // Auto-deny all pending permission requests (both subsystems)
2834
+ this.clearAllPendingPermissions()
2835
+ this._questionSessionMap.clear()
2836
+ // #5563: primary-ownership lives on the client manager now; clear it via
2837
+ // its public API rather than reaching into the private `_primaryClients`.
2838
+ this._clientManager.clearAllPrimary()
2839
+ this._normalizer.destroy()
2840
+
2841
+ // Clean up all dev preview tunnels (fire-and-forget; close() is synchronous
2842
+ // by contract, and tunnel process cleanup is best-effort before exit)
2843
+ void this._devPreview.closeAll()
2844
+
2845
+ // Clean up web task manager
2846
+ this._webTaskManager.destroy()
2847
+
2848
+ // Remove this instance's log listener to prevent post-shutdown broadcasts and GC leak
2849
+ if (this._logListener) {
2850
+ removeLogListener(this._logListener)
2851
+ this._logListener = null
2852
+ }
2853
+
2854
+ for (const [ws] of this.clients) {
2855
+ ws.close()
2856
+ }
2857
+ if (this.wss) this.wss.close()
2858
+ if (this.httpServer) this.httpServer.close()
2859
+ // #6277 — tear down the host-local approval listener + its port file.
2860
+ if (this._approvalServer) {
2861
+ try { this._approvalServer.close() } catch { /* already closing */ }
2862
+ this._approvalServer = null
2863
+ removeShellApprovalInfo()
2864
+ }
2865
+ }
2866
+ }