@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,476 @@
1
+ import { EventEmitter } from 'node:events'
2
+ import { createLogger } from './logger.js'
3
+
4
+ const log = createLogger('ws-client-manager')
5
+
6
+ // #5563: shared immutable empty Set returned by getSessionSubscribers when a
7
+ // session has no indexed clients — avoids allocating per call on the hot path.
8
+ // `Object.freeze` does NOT stop `.add()`/`.delete()` on a Set's contents, so we
9
+ // also override the mutators to throw: an accidental write to the shared
10
+ // singleton fails loudly instead of silently leaking a phantom subscriber into
11
+ // every empty-session lookup.
12
+ const EMPTY_SET = (() => {
13
+ const s = new Set()
14
+ const fail = () => { throw new Error('getSessionSubscribers() returned the shared empty Set — it must not be mutated') }
15
+ s.add = fail
16
+ s.delete = fail
17
+ s.clear = fail
18
+ return Object.freeze(s)
19
+ })()
20
+
21
+ /**
22
+ * Manages WebSocket client connections lifecycle.
23
+ *
24
+ * Encapsulates the clients Map and all client-state queries:
25
+ * - add/remove/get client
26
+ * - connected list, pending count, authenticated count
27
+ * - active viewer detection
28
+ *
29
+ * Emits:
30
+ * - 'client_joined' ({ client, ws })
31
+ * - 'client_departed' ({ client })
32
+ */
33
+ export class WsClientManager extends EventEmitter {
34
+ /**
35
+ * @param {object} [opts]
36
+ * @param {(client: object, prev: string|null, next: string|null) => void} [opts.onActiveSessionChanged]
37
+ * Invoked AFTER a client's active session actually changes (prev !== next),
38
+ * with the index already updated. Lets the owner react to viewer-set changes
39
+ * — e.g. re-sync the live terminal mirror gate for the old + new session
40
+ * (audit P1-2) — from the single sanctioned mutation point, so every
41
+ * setActiveSession caller (switch_session, checkpoint restore, conversation
42
+ * switch, destroy re-home) inherits it instead of patching each call site.
43
+ */
44
+ constructor({ onActiveSessionChanged } = {}) {
45
+ super()
46
+ /** @type {Map<WebSocket, object>} */
47
+ this.clients = new Map()
48
+ this._onActiveSessionChanged = typeof onActiveSessionChanged === 'function' ? onActiveSessionChanged : null
49
+ // #5563: reverse index sessionId → Set<client> for O(subscribers) session
50
+ // broadcasts and O(1) subscriber counts, instead of an O(clients) scan per
51
+ // session-scoped message + a SECOND scan per buffered delta. A client is a
52
+ // member of the index for `sessionId` iff it would match
53
+ // `_broadcastToSession`'s default recipient filter: `activeSessionId ===
54
+ // sessionId` OR `subscribedSessionIds.has(sessionId)`. Both conditions
55
+ // change independently (e.g. checkpoint restore moves activeSessionId
56
+ // without subscribing; subscribe_sessions adds to the Set without touching
57
+ // activeSessionId), so the index tracks the UNION. Every mutation point for
58
+ // either condition MUST route through this class's helpers
59
+ // (subscribe / unsubscribe / setActiveSession / removeClient) so the index
60
+ // can never drift from the per-client Sets. The remaining per-member filter
61
+ // conditions (authenticated, readyState, bound checks) are still applied by
62
+ // the broadcaster per index member — the index only covers the
63
+ // active-or-subscribed predicate.
64
+ /** @type {Map<string, Set<object>>} sessionId → Set<client> */
65
+ this._sessionIndex = new Map()
66
+ // #5563: explicit primary-ownership for shared sessions. Replaces the old
67
+ // last-writer-wins `_primaryClients` map that lived on WsServer. A session's
68
+ // primary is the client currently DRIVING it; every other subscriber is an
69
+ // OBSERVER. v1 semantics:
70
+ // - First client to claim a session becomes primary.
71
+ // - The explicit `claim_primary` wire path is STICKY: a claim against an
72
+ // owned session is rejected unless `force: true` (hand-off).
73
+ // - Input that passed the input_conflict gate adopts primary with force
74
+ // (see WsServer._updatePrimary): the server can't tell "same user,
75
+ // second device" from "shared-session observer" without identity, so
76
+ // accepted input keeps today's seamless device hand-off; true
77
+ // observe-only enforcement is #5281 client-role work built on the
78
+ // sticky claim path.
79
+ // - On primary disconnect the slot is CLEARED (nobody-until-claim) so a
80
+ // backgrounded observer is never silently promoted; the next claimant
81
+ // (or first input) takes over. This matches the pre-#5563 disconnect
82
+ // behaviour (clear + broadcast null) exactly.
83
+ // Stored by clientId (not the client object) to mirror the old map's shape
84
+ // and survive a client object being replaced on reconnect-with-same-id.
85
+ /** @type {Map<string, string>} sessionId → primary clientId */
86
+ this._primaryClients = new Map()
87
+ }
88
+
89
+ /**
90
+ * The current primary clientId for `sessionId`, or undefined if unclaimed.
91
+ * @param {string} sessionId
92
+ * @returns {string|undefined}
93
+ */
94
+ getPrimary(sessionId) {
95
+ return this._primaryClients.get(sessionId)
96
+ }
97
+
98
+ /**
99
+ * True iff `clientId` is the primary for `sessionId`.
100
+ * @param {string} sessionId
101
+ * @param {string} clientId
102
+ * @returns {boolean}
103
+ */
104
+ isPrimary(sessionId, clientId) {
105
+ return this._primaryClients.get(sessionId) === clientId
106
+ }
107
+
108
+ /**
109
+ * Attempt to make `clientId` the primary for `sessionId`.
110
+ *
111
+ * Returns a result describing what happened so the caller can decide whether
112
+ * to broadcast a role change:
113
+ * - `{ changed: true, primaryClientId }` — ownership actually moved (the
114
+ * session was unclaimed, or this is a `force` hand-off to a new owner).
115
+ * - `{ changed: false, primaryClientId }` — no change: either the caller is
116
+ * already the primary (idempotent no-op) OR the claim was REJECTED
117
+ * because another client owns it and `force` is false. Inspect `rejected`
118
+ * to distinguish (set only on the rejection branch).
119
+ *
120
+ * `force` (explicit hand-off / first-input adoption) overrides an existing
121
+ * owner. Without `force`, a claim against a session another client already
122
+ * owns is rejected (returns `{ changed:false, rejected:true }`) — this is the
123
+ * observe-only guarantee.
124
+ *
125
+ * @param {string} sessionId
126
+ * @param {string} clientId
127
+ * @param {{ force?: boolean }} [opts]
128
+ * @returns {{ changed: boolean, rejected?: boolean, primaryClientId: string|undefined }}
129
+ */
130
+ claimPrimary(sessionId, clientId, { force = false } = {}) {
131
+ if (!sessionId || !clientId) return { changed: false, primaryClientId: this._primaryClients.get(sessionId) }
132
+ const current = this._primaryClients.get(sessionId)
133
+ if (current === clientId) return { changed: false, primaryClientId: current }
134
+ if (current && !force) {
135
+ // Session already owned by someone else and this is not an explicit
136
+ // hand-off / adoption — reject to preserve observe-only semantics.
137
+ return { changed: false, rejected: true, primaryClientId: current }
138
+ }
139
+ this._primaryClients.set(sessionId, clientId)
140
+ return { changed: true, primaryClientId: clientId }
141
+ }
142
+
143
+ /**
144
+ * Clear the primary slot for `sessionId`. Returns the previous owner (or
145
+ * undefined). Used on destroy_session.
146
+ * @param {string} sessionId
147
+ * @returns {string|undefined} previous primary clientId
148
+ */
149
+ clearPrimary(sessionId) {
150
+ const prev = this._primaryClients.get(sessionId)
151
+ this._primaryClients.delete(sessionId)
152
+ return prev
153
+ }
154
+
155
+ /**
156
+ * Vacate every primary slot (server shutdown / close path). No broadcast —
157
+ * the server is tearing down. Keeps the `_primaryClients` map private to this
158
+ * class so callers don't depend on its representation (#5563).
159
+ */
160
+ clearAllPrimary() {
161
+ this._primaryClients.clear()
162
+ }
163
+
164
+ /**
165
+ * Clear every session this client was primary on (disconnect path).
166
+ * @param {string} clientId
167
+ * @returns {string[]} sessionIds the client was vacated from
168
+ */
169
+ clearPrimaryForClient(clientId) {
170
+ const vacated = []
171
+ for (const [sessionId, primaryClientId] of this._primaryClients) {
172
+ if (primaryClientId === clientId) {
173
+ this._primaryClients.delete(sessionId)
174
+ vacated.push(sessionId)
175
+ }
176
+ }
177
+ return vacated
178
+ }
179
+
180
+ /**
181
+ * Add `client` to the reverse index under `sessionId`. Idempotent: a Set
182
+ * dedups, so re-subscribing or active==subscribed never double-counts.
183
+ * @param {object} client
184
+ * @param {string} sessionId
185
+ * @private
186
+ */
187
+ _indexAdd(client, sessionId) {
188
+ if (!sessionId) return
189
+ let set = this._sessionIndex.get(sessionId)
190
+ if (!set) {
191
+ set = new Set()
192
+ this._sessionIndex.set(sessionId, set)
193
+ }
194
+ set.add(client)
195
+ }
196
+
197
+ /**
198
+ * Remove `client` from the index under `sessionId` ONLY if it no longer
199
+ * matches either index condition (active or subscribed). Called after a
200
+ * condition is cleared; the other condition may still hold (e.g. a client
201
+ * unsubscribes from a session it is still actively viewing — it must stay
202
+ * in the index). Empty sets are pruned to keep the map from leaking
203
+ * sessionId keys for destroyed sessions.
204
+ * @param {object} client
205
+ * @param {string} sessionId
206
+ * @private
207
+ */
208
+ _indexRemoveIfUnreferenced(client, sessionId) {
209
+ if (!sessionId) return
210
+ if (client.activeSessionId === sessionId) return
211
+ if (client.subscribedSessionIds && client.subscribedSessionIds.has(sessionId)) return
212
+ const set = this._sessionIndex.get(sessionId)
213
+ if (!set) return
214
+ set.delete(client)
215
+ if (set.size === 0) this._sessionIndex.delete(sessionId)
216
+ }
217
+
218
+ /**
219
+ * Subscribe `client` to `sessionId`: add to its `subscribedSessionIds` Set
220
+ * AND the reverse index, atomically. The single sanctioned way to add a
221
+ * subscription — direct `client.subscribedSessionIds.add()` would drift the
222
+ * index. Idempotent.
223
+ * @param {object} client
224
+ * @param {string} sessionId
225
+ */
226
+ subscribe(client, sessionId) {
227
+ if (!sessionId) return
228
+ if (!client.subscribedSessionIds) client.subscribedSessionIds = new Set()
229
+ client.subscribedSessionIds.add(sessionId)
230
+ this._indexAdd(client, sessionId)
231
+ }
232
+
233
+ /**
234
+ * Unsubscribe `client` from `sessionId`: remove from its
235
+ * `subscribedSessionIds` Set, then drop it from the index unless it is still
236
+ * the client's active session. The single sanctioned way to remove a
237
+ * subscription.
238
+ * @param {object} client
239
+ * @param {string} sessionId
240
+ */
241
+ unsubscribe(client, sessionId) {
242
+ if (!sessionId) return
243
+ client.subscribedSessionIds?.delete(sessionId)
244
+ this._indexRemoveIfUnreferenced(client, sessionId)
245
+ }
246
+
247
+ /**
248
+ * Move `client.activeSessionId` to `sessionId` (or null), keeping the index
249
+ * in sync for BOTH the old and new active session. The single sanctioned way
250
+ * to change a client's active session — a bare `client.activeSessionId = x`
251
+ * would drift the index. The previous active session is dropped from the
252
+ * index only if the client is not also subscribed to it.
253
+ * @param {object} client
254
+ * @param {string|null} sessionId
255
+ */
256
+ setActiveSession(client, sessionId) {
257
+ const prev = client.activeSessionId
258
+ if (prev === sessionId) return
259
+ client.activeSessionId = sessionId
260
+ // Re-evaluate the old session: it leaves the index only if no longer
261
+ // referenced (i.e. the client is not subscribed to it).
262
+ if (prev) this._indexRemoveIfUnreferenced(client, prev)
263
+ // The new active session always belongs in the index.
264
+ if (sessionId) this._indexAdd(client, sessionId)
265
+ // Notify after the index + activeSessionId are settled so the listener
266
+ // observes the new viewer state. Defensive try/catch: a listener failure
267
+ // (e.g. mirror re-sync) must never corrupt the index. (audit P1-2)
268
+ if (this._onActiveSessionChanged) {
269
+ // Best-effort: index integrity comes first, but log so a failing listener
270
+ // (e.g. a future _syncTerminalMirror edge case leaving the gate unsynced)
271
+ // is triageable instead of silently swallowed.
272
+ try { this._onActiveSessionChanged(client, prev, sessionId) }
273
+ catch (err) { log.warn(`onActiveSessionChanged listener threw (index left intact): ${err?.message || err}`) }
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Return the Set of clients indexed for `sessionId` (active or subscribed).
279
+ * The returned Set is the live index Set — callers MUST NOT mutate it, and
280
+ * MUST still apply the remaining per-member filter (authenticated /
281
+ * readyState / bound). Returns an empty Set when no clients are indexed.
282
+ * @param {string} sessionId
283
+ * @returns {Set<object>}
284
+ */
285
+ getSessionSubscribers(sessionId) {
286
+ return this._sessionIndex.get(sessionId) || EMPTY_SET
287
+ }
288
+
289
+ /**
290
+ * Register a new client connection. A fresh client has `activeSessionId:
291
+ * null` and an empty `subscribedSessionIds`, so it contributes no index
292
+ * entries until it subscribes or switches via the helpers above.
293
+ *
294
+ * Centralizes the `_ws` back-reference invariant (#5563): the reverse-index
295
+ * fast path resolves each indexed client's socket via `client._ws`, so a
296
+ * client registered without it would be silently skipped by session
297
+ * broadcasts/counts. `addClient` already receives `ws`, so it backfills
298
+ * `clientInfo._ws` when missing — call sites need not remember to set it.
299
+ * @param {WebSocket} ws
300
+ * @param {object} clientInfo - Initial client state
301
+ * @returns {object} the stored client info
302
+ */
303
+ addClient(ws, clientInfo) {
304
+ if (clientInfo && clientInfo._ws == null) clientInfo._ws = ws
305
+ this.clients.set(ws, clientInfo)
306
+ return clientInfo
307
+ }
308
+
309
+ /**
310
+ * Remove a client connection. Purges the client from EVERY index Set it
311
+ * belonged to (the disconnect / terminate mutation point) so a departed
312
+ * client can never linger as a phantom broadcast recipient.
313
+ * If the client was authenticated, emits 'client_departed'.
314
+ * @param {WebSocket} ws
315
+ * @returns {object|undefined} the removed client info, or undefined
316
+ */
317
+ removeClient(ws) {
318
+ const client = this.clients.get(ws)
319
+ if (!client) return undefined
320
+ this.clients.delete(ws)
321
+ this._purgeFromIndex(client)
322
+ if (client.authenticated) {
323
+ this.emit('client_departed', { client })
324
+ }
325
+ return client
326
+ }
327
+
328
+ /**
329
+ * Drop `client` from every index Set, pruning emptied sessionId keys.
330
+ * @param {object} client
331
+ * @private
332
+ */
333
+ _purgeFromIndex(client) {
334
+ for (const [sessionId, set] of this._sessionIndex) {
335
+ if (set.delete(client) && set.size === 0) {
336
+ this._sessionIndex.delete(sessionId)
337
+ }
338
+ }
339
+ }
340
+
341
+ /**
342
+ * #5563 drift defense: assert the reverse index exactly matches a full scan
343
+ * of every client's (activeSessionId ∪ subscribedSessionIds). Cheap O(clients
344
+ * × sessions) — intended for tests and the optional `CHROXY_WS_INDEX_ASSERT`
345
+ * debug flag, NOT the hot path. Throws on any drift with a description of the
346
+ * first mismatch so the offending mutation site is obvious.
347
+ * @throws {Error} on drift
348
+ */
349
+ verifyIndexIntegrity() {
350
+ // Build the oracle: sessionId → Set<client> from per-client state.
351
+ const oracle = new Map()
352
+ const add = (sid, client) => {
353
+ if (!sid) return
354
+ let s = oracle.get(sid)
355
+ if (!s) { s = new Set(); oracle.set(sid, s) }
356
+ s.add(client)
357
+ }
358
+ for (const client of this.clients.values()) {
359
+ add(client.activeSessionId, client)
360
+ if (client.subscribedSessionIds) {
361
+ for (const sid of client.subscribedSessionIds) add(sid, client)
362
+ }
363
+ }
364
+ // Every oracle entry must be present (and identical) in the index.
365
+ for (const [sid, expected] of oracle) {
366
+ const actual = this._sessionIndex.get(sid)
367
+ if (!actual) {
368
+ throw new Error(`ws index drift: session ${sid} missing from index (oracle has ${expected.size} client(s))`)
369
+ }
370
+ for (const client of expected) {
371
+ if (!actual.has(client)) {
372
+ throw new Error(`ws index drift: client ${client.id} missing from index for session ${sid}`)
373
+ }
374
+ }
375
+ if (actual.size !== expected.size) {
376
+ throw new Error(`ws index drift: session ${sid} has ${actual.size} indexed client(s), oracle expects ${expected.size} (stale member)`)
377
+ }
378
+ }
379
+ // No index entry may exist that the oracle doesn't account for (stale keys
380
+ // / stale members on sessions with no oracle entry).
381
+ for (const [sid, actual] of this._sessionIndex) {
382
+ if (actual.size === 0) {
383
+ throw new Error(`ws index drift: session ${sid} has an empty (unpruned) Set in the index`)
384
+ }
385
+ if (!oracle.has(sid)) {
386
+ throw new Error(`ws index drift: session ${sid} present in index but no client references it`)
387
+ }
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Get client info for a WebSocket.
393
+ * @param {WebSocket} ws
394
+ * @returns {object|undefined}
395
+ */
396
+ getClient(ws) {
397
+ return this.clients.get(ws)
398
+ }
399
+
400
+ /**
401
+ * Get list of connected, authenticated clients for auth_ok payload.
402
+ * @returns {Array<{clientId, deviceName, deviceType, platform}>}
403
+ */
404
+ getConnectedList() {
405
+ const list = []
406
+ for (const [ws, client] of this.clients) {
407
+ if (client.authenticated && ws.readyState === 1) {
408
+ const info = client.deviceInfo || {}
409
+ list.push({
410
+ clientId: client.id,
411
+ deviceName: info.deviceName || null,
412
+ deviceType: info.deviceType || 'unknown',
413
+ platform: info.platform || 'unknown',
414
+ })
415
+ }
416
+ }
417
+ return list
418
+ }
419
+
420
+ /**
421
+ * Count unauthenticated connections for pre-auth limit enforcement.
422
+ * @returns {number}
423
+ */
424
+ countPending() {
425
+ let count = 0
426
+ for (const [ws, client] of this.clients) {
427
+ if (!client.authenticated && ws.readyState === 1) count++
428
+ }
429
+ return count
430
+ }
431
+
432
+ /**
433
+ * Check if any authenticated client is actively viewing the given session.
434
+ * @param {string} sessionId
435
+ * @returns {boolean}
436
+ */
437
+ hasActiveViewers(sessionId) {
438
+ for (const [ws, client] of this.clients) {
439
+ if (
440
+ client.authenticated &&
441
+ client.activeSessionId === sessionId &&
442
+ ws.readyState === 1 &&
443
+ client.visible !== false
444
+ ) return true
445
+ }
446
+ return false
447
+ }
448
+
449
+ /**
450
+ * Count of authenticated, connected clients.
451
+ * @returns {number}
452
+ */
453
+ get authenticatedCount() {
454
+ let count = 0
455
+ for (const [ws, client] of this.clients) {
456
+ if (client.authenticated && ws.readyState === 1) count++
457
+ }
458
+ return count
459
+ }
460
+
461
+ /**
462
+ * Iterate over all client entries.
463
+ * @returns {IterableIterator<[WebSocket, object]>}
464
+ */
465
+ [Symbol.iterator]() {
466
+ return this.clients[Symbol.iterator]()
467
+ }
468
+
469
+ /**
470
+ * Number of total connections (authenticated + pending).
471
+ * @returns {number}
472
+ */
473
+ get size() {
474
+ return this.clients.size
475
+ }
476
+ }
@@ -0,0 +1,115 @@
1
+ import { encrypt, DIRECTION_SERVER } from '@chroxy/store-core/crypto'
2
+ import { metrics } from './metrics.js'
3
+
4
+ /** Backpressure thresholds (bytes) */
5
+ const WARN_THRESHOLD = 64 * 1024 // 64KB — log warning
6
+ const EVICT_THRESHOLD = 1024 * 1024 // 1MB — close stale client
7
+
8
+ /** Minimum interval between backpressure warnings per client (ms) */
9
+ const WARN_THROTTLE_MS = 30_000
10
+
11
+ /**
12
+ * Factory that creates a send function for WebSocket clients.
13
+ * Handles JSON serialization, optional encryption, sequence numbering,
14
+ * post-auth queue buffering, flush-overflow buffering, and post-send
15
+ * backpressure monitoring.
16
+ *
17
+ * Post-send backpressure is intentionally distinct from the pre-send
18
+ * check in `WsBroadcaster._sendOneWithBackpressure` (#4775). The
19
+ * broadcaster only protects multi-recipient broadcast paths; single-
20
+ * recipient sends from `WsServer._send` (pong, token_rotated,
21
+ * auth_fail, rate_limited, server_status, error, etc.) bypass the
22
+ * broadcaster entirely, so this post-send path is the only thing that
23
+ * evicts a slow client on those code paths. Per #4804 both paths must
24
+ * emit `backpressure.disconnects` so alerting catches either eviction
25
+ * source — see `metrics.inc('backpressure.disconnects')` below.
26
+ *
27
+ * @param {object} log - Logger with .error() and .warn() methods
28
+ * @param {object} [opts] - Optional overrides (for testing)
29
+ * @param {number} [opts.warnThreshold] - Bytes above which to log warning
30
+ * @param {number} [opts.evictThreshold] - Bytes above which to close client
31
+ * @param {number} [opts.warnThrottleMs] - Min ms between warnings per client
32
+ * @returns {(ws: WebSocket, client: object|undefined, message: object) => boolean}
33
+ * Returns `true` when the message was handed to `ws.send` without throwing
34
+ * (or accepted into the post-auth / flush-overflow queue for later delivery),
35
+ * `false` when it could not be delivered — the client was already evicted, or
36
+ * `ws.send` threw (a torn-down / half-open socket). #5721: callers that gate
37
+ * crypto state on a frame actually reaching the wire (the eager handshake's
38
+ * `auth_ok` carrying `serverPublicKey`) MUST check this — the catch below
39
+ * swallows the throw, so there is no exception to observe otherwise.
40
+ */
41
+ export function createClientSender(log, opts = {}) {
42
+ const warnThreshold = opts.warnThreshold ?? WARN_THRESHOLD
43
+ const evictThreshold = opts.evictThreshold ?? EVICT_THRESHOLD
44
+ const warnThrottleMs = opts.warnThrottleMs ?? WARN_THROTTLE_MS
45
+
46
+ return function send(ws, client, message) {
47
+ // #4834: short-circuit if this client has already been evicted. ws.close()
48
+ // is async (CLOSING → CLOSED), so subsequent synchronous sends in the same
49
+ // chain (e.g. replayHistory / flushPostAuthQueue) would otherwise keep
50
+ // serializing + encrypting messages that will never leave the buffer.
51
+ if (client?._evicted) {
52
+ return false
53
+ }
54
+ // Queue messages while key exchange is pending
55
+ if (client?.encryptionPending && client.postAuthQueue) {
56
+ client.postAuthQueue.push(message)
57
+ return true
58
+ }
59
+ // Buffer messages while post-auth queue is still flushing
60
+ if (client?._flushing) {
61
+ client._flushOverflow = client._flushOverflow || []
62
+ client._flushOverflow.push(message)
63
+ return true
64
+ }
65
+ // Assign per-client monotonic sequence number
66
+ if (client) {
67
+ client._seq++
68
+ message = { ...message, seq: client._seq }
69
+ }
70
+ try {
71
+ // Encrypt if encryption is active for this client
72
+ if (client?.encryptionState) {
73
+ const envelope = encrypt(JSON.stringify(message), client.encryptionState.sharedKey, client.encryptionState.sendNonce, DIRECTION_SERVER)
74
+ client.encryptionState.sendNonce++
75
+ ws.send(JSON.stringify(envelope))
76
+ } else {
77
+ ws.send(JSON.stringify(message))
78
+ }
79
+
80
+ // Post-send backpressure monitoring
81
+ const buffered = ws.bufferedAmount
82
+ if (buffered > evictThreshold && client && !client._evicted) {
83
+ // #4834: sticky _evicted flag prevents log spam + metric over-counting
84
+ // while ws.close() is in flight. Without this, 10+ sends after the
85
+ // first eviction can each re-log and re-increment for a single close.
86
+ client._evicted = true
87
+ log.warn(`Backpressure: evicting client ${client.id} — bufferedAmount ${buffered} exceeds ${evictThreshold} bytes`)
88
+ // #4804: unify observability with WsBroadcaster._sendOneWithBackpressure
89
+ // so both backpressure systems feed the same metric. Without this the
90
+ // single-recipient eviction path silently bypasses alerting.
91
+ metrics.inc('backpressure.disconnects')
92
+ ws.close(4008, 'Backpressure: slow client evicted')
93
+ } else if (buffered > warnThreshold && client) {
94
+ const now = Date.now()
95
+ const lastWarn = client._lastBackpressureWarn || 0
96
+ if (now - lastWarn >= warnThrottleMs) {
97
+ client._lastBackpressureWarn = now
98
+ // Wedge instrumentation (#4678 follow-up): include the message
99
+ // type so we can correlate a warn at restore-time with which
100
+ // broadcast tipped the buffer. Without the type we cannot tell
101
+ // whether the restore session_list broadcast or a subsequent
102
+ // stream_start broadcast pushed past the threshold.
103
+ log.warn(`Backpressure: client ${client.id} bufferedAmount ${buffered} exceeds warning threshold (${warnThreshold} bytes) type=${message?.type || 'unknown'}`)
104
+ }
105
+ }
106
+ // #5721: the frame was handed to ws.send without throwing. A post-send
107
+ // backpressure eviction above (ws.close) affects FUTURE sends, not this
108
+ // one — this message already left for the socket buffer, so report success.
109
+ return true
110
+ } catch (err) {
111
+ log.error(`Send error: ${err.message}`)
112
+ return false
113
+ }
114
+ }
115
+ }