@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
package/src/ws-auth.js ADDED
@@ -0,0 +1,645 @@
1
+ /**
2
+ * Authentication message handling and key exchange for WsServer.
3
+ *
4
+ * Extracted from ws-server.js _handleMessage to separate auth/encryption
5
+ * concerns from message routing.
6
+ */
7
+ import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
8
+ import { AuthSchema, KeyExchangeSchema, PairSchema, PairRequestSchema } from './ws-schemas.js'
9
+ import { createLogger } from './logger.js'
10
+ import { metrics } from './metrics.js'
11
+
12
+ const log = createLogger('ws')
13
+
14
+ /** Maximum number of IP entries tracked in the auth-failure rate-limit map.
15
+ * When the cap is reached the oldest entry is evicted before inserting. */
16
+ export const MAX_AUTH_FAILURE_ENTRIES = 10_000
17
+
18
+ /** #5555.3 — cap on the number of per-session history cursors honoured from a
19
+ * single `auth` message. A client only ever replays its bound/active session
20
+ * on connect, so a handful is the realistic case; this bound keeps a
21
+ * malformed/oversized map from inflating the post-auth path. */
22
+ export const MAX_HISTORY_CURSORS = 64
23
+
24
+ /** Lenient counter for benign pairing failures (already_used / expired).
25
+ *
26
+ * These reasons are exempt from the strict brute-force `authFailures` bucket
27
+ * (#2917): legitimate users rescanning a consumed QR code must not be locked
28
+ * out. However a malicious client holding a known consumed pairing ID could
29
+ * still hammer the server during the 60s consumed-ID TTL window.
30
+ *
31
+ * This separate bucket caps that abuse without ever firing on a legitimate
32
+ * rescan loop. The threshold (50 attempts in a 60s rolling window) is many
33
+ * orders of magnitude above what a human bouncing the scanner could produce
34
+ * (a real user typically rescans 2-6 times). When breached we impose a short
35
+ * 30s temp block and respond with `pair_fail reason: rate_limited`.
36
+ *
37
+ * Critically, this counter is NEVER merged with the strict `authFailures`
38
+ * bucket — they have different thresholds and a benign breach must not
39
+ * disable real auth rate limiting for the same IP. */
40
+ export const BENIGN_PAIR_THRESHOLD = 50
41
+ export const BENIGN_PAIR_WINDOW_MS = 60_000
42
+ export const BENIGN_PAIR_BLOCK_MS = 30_000
43
+
44
+ /** Evict the oldest entry from a Map if it has reached the size cap. */
45
+ function evictOldestIfFull(map) {
46
+ if (map.size >= MAX_AUTH_FAILURE_ENTRIES) {
47
+ const oldestKey = map.keys().next().value
48
+ map.delete(oldestKey)
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Record a benign pairing attempt against the lenient bucket and return
54
+ * whether the caller should now block the client.
55
+ *
56
+ * Each entry is `{ count, windowStart, blockedUntil }`. The window is rolling
57
+ * — when the current attempt arrives more than `BENIGN_PAIR_WINDOW_MS` after
58
+ * `windowStart`, the count resets and the window slides forward. If the count
59
+ * within the live window crosses `BENIGN_PAIR_THRESHOLD`, we set
60
+ * `blockedUntil = now + BENIGN_PAIR_BLOCK_MS` and return true.
61
+ *
62
+ * On block-arm we also slide the rolling window forward (reset windowStart,
63
+ * count=0) so an attacker cannot chain back-to-back blocks. Without this, a
64
+ * breach at t=1s blocks until t=31s; the very first post-block attempt at
65
+ * t=31s would still see count=51 (>threshold) inside a window that does not
66
+ * expire until t=61s, and would immediately re-arm another 30s block. The
67
+ * reset guarantees the lockout is exactly BENIGN_PAIR_BLOCK_MS followed by a
68
+ * fresh threshold budget.
69
+ *
70
+ * @param {Map} map - benignPairAttempts map
71
+ * @param {string} key - rateLimitKey (CF-Connecting-IP or socketIp)
72
+ * @param {number} now - Date.now()
73
+ * @returns {boolean} true if the caller should now respond with rate_limited
74
+ */
75
+ export function recordBenignPairAttempt(map, key, now) {
76
+ let entry = map.get(key)
77
+ if (!entry || now - entry.windowStart > BENIGN_PAIR_WINDOW_MS) {
78
+ if (!map.has(key)) evictOldestIfFull(map)
79
+ entry = { count: 0, windowStart: now, blockedUntil: 0 }
80
+ map.set(key, entry)
81
+ }
82
+ entry.count++
83
+ if (entry.count > BENIGN_PAIR_THRESHOLD && entry.blockedUntil <= now) {
84
+ entry.blockedUntil = now + BENIGN_PAIR_BLOCK_MS
85
+ entry.windowStart = now
86
+ entry.count = 0
87
+ return true
88
+ }
89
+ return false
90
+ }
91
+
92
+ /**
93
+ * Handle an auth message from an unauthenticated client.
94
+ * Returns true if the message was consumed (caller should return).
95
+ *
96
+ * @param {object} ctx - Server context
97
+ * @param {WebSocket} ws
98
+ * @param {object} msg - The parsed message
99
+ * @returns {boolean}
100
+ */
101
+ export function handleAuthMessage(ctx, ws, msg) {
102
+ const {
103
+ clients, authRequired, isTokenValid,
104
+ authFailures, send, onAuthSuccess,
105
+ minProtocolVersion, serverProtocolVersion,
106
+ pairingManager,
107
+ } = ctx
108
+ const client = clients.get(ws)
109
+ if (!client || client.authenticated) return false
110
+ if (msg.type !== 'auth') return false
111
+
112
+ // Validate auth message shape
113
+ const authParsed = AuthSchema.safeParse(msg)
114
+ if (!authParsed.success) {
115
+ send(ws, { type: 'auth_fail', reason: 'invalid_message' })
116
+ ws.close()
117
+ return true
118
+ }
119
+ const authData = authParsed.data
120
+
121
+ // Check rate limit before processing auth.
122
+ //
123
+ // Must use client.rateLimitKey (CF-Connecting-IP when behind a Cloudflare
124
+ // tunnel, socketIp otherwise) — NOT client.socketIp. Cloudflare tunnels
125
+ // deliver every request with socketIp=127.0.0.1, so keying off socketIp
126
+ // would lump every real caller into one shared bucket and let a single
127
+ // unauthenticated attacker lock out every legitimate client by flooding
128
+ // failed-auth attempts.
129
+ //
130
+ // See 88f54dc39 for the equivalent fix in the main WS rate limiter; this
131
+ // call site was missed at the time.
132
+ const rateLimitKey = client.rateLimitKey || client.socketIp
133
+ const failure = authFailures.get(rateLimitKey)
134
+ if (failure && failure.blockedUntil > Date.now()) {
135
+ log.warn(`Auth rate-limited for ${rateLimitKey} (${failure.count} failures)`)
136
+ send(ws, { type: 'auth_fail', reason: 'rate_limited' })
137
+ ws.close()
138
+ return true
139
+ }
140
+
141
+ if (!authRequired || isTokenValid(msg.token)) {
142
+ client.authenticated = true
143
+ client.authTime = Date.now()
144
+ // #6004 — remember the exact token this connection authed with so the
145
+ // user-shell create gate can require it still be the CURRENT token (not a
146
+ // grace/previous token after a rotation). In-memory only, for the
147
+ // connection lifetime — the client already holds the E2E shared key, so
148
+ // this is comparable exposure. Undefined in --no-auth (no token), where the
149
+ // shell gate's current-token check is skipped (no TokenManager).
150
+ client.authToken = msg.token
151
+ authFailures.delete(rateLimitKey)
152
+
153
+ const hasVersion = typeof msg.protocolVersion === 'number' && Number.isInteger(msg.protocolVersion)
154
+ const clientVersion = hasVersion ? msg.protocolVersion : null
155
+
156
+ if (clientVersion !== null && clientVersion < minProtocolVersion) {
157
+ send(ws, { type: 'auth_fail', reason: `unsupported protocol version ${clientVersion} (minimum: ${minProtocolVersion})` })
158
+ ws.close()
159
+ return true
160
+ }
161
+
162
+ client.protocolVersion = clientVersion !== null
163
+ ? Math.min(clientVersion, serverProtocolVersion)
164
+ : minProtocolVersion
165
+
166
+ if (msg.deviceInfo && typeof msg.deviceInfo === 'object') {
167
+ client.deviceInfo = {
168
+ deviceId: typeof msg.deviceInfo.deviceId === 'string' ? msg.deviceInfo.deviceId : null,
169
+ deviceName: typeof msg.deviceInfo.deviceName === 'string' ? msg.deviceInfo.deviceName : null,
170
+ deviceType: ['phone', 'tablet', 'desktop', 'unknown'].includes(msg.deviceInfo.deviceType) ? msg.deviceInfo.deviceType : 'unknown',
171
+ platform: typeof msg.deviceInfo.platform === 'string' ? msg.deviceInfo.platform : 'unknown',
172
+ }
173
+ }
174
+
175
+ // If this token was issued via pairing, bind the client to the session
176
+ // that was active at pairing time (if any). This prevents a valid
177
+ // session token from being used to attach to an unrelated session.
178
+ if (pairingManager && msg.token) {
179
+ const boundSessionId = pairingManager.getSessionIdForToken(msg.token)
180
+ if (boundSessionId) {
181
+ client.boundSessionId = boundSessionId
182
+ }
183
+ }
184
+
185
+ // #5985b (epic #5982) — the WS analog of the HTTP-only
186
+ // `_validatePrimaryBearerAuth`. The WS layer previously could not tell the
187
+ // primary token from an unbound linking-mode pairing token (both have no
188
+ // `boundSessionId`), so a high-privilege capability gated only on
189
+ // "unbound" would admit a paired phone (swarm-audit finding C1). A token is
190
+ // the PRIMARY class iff it is NOT a PairingManager-issued session token
191
+ // (`isSessionTokenValid` is true for every pairing token — bound and
192
+ // unbound — and false for the static/rotated primary). In no-auth mode every
193
+ // local client is trusted as primary, matching `_validatePrimaryBearerAuth`'s
194
+ // `!authRequired` short-circuit. The `pair`-message path never sets this, so
195
+ // paired clients default to undefined (non-primary) — gates use strict
196
+ // `=== true`. Consumed by the user-shell create + terminal_* gates.
197
+ client.isPrimaryToken = !authRequired || !pairingManager?.isSessionTokenValid(msg.token)
198
+
199
+ client.clientCapabilities = new Set(authData.capabilities ?? [])
200
+
201
+ // #5555 (eager key exchange) — stash the client's ephemeral public key +
202
+ // salt if it supplied BOTH in the auth message. sendPostAuthInfo (called
203
+ // from onAuthSuccess) consumes these to derive the shared key inline and
204
+ // returns the server's public key in auth_ok, skipping the discrete
205
+ // `key_exchange` round trip. Both fields are required together; a client
206
+ // that sends only one (or empty strings) is treated as not-eager and falls
207
+ // through to the discrete handshake. The derivation is identical to the
208
+ // discrete path (deriveSharedKey → deriveConnectionKey with the same salt
209
+ // semantics) — only the transport timing changes.
210
+ if (typeof authData.eagerPublicKey === 'string' && authData.eagerPublicKey &&
211
+ typeof authData.eagerSalt === 'string' && authData.eagerSalt) {
212
+ client.eagerKeyExchange = { publicKey: authData.eagerPublicKey, salt: authData.eagerSalt }
213
+ }
214
+
215
+ // #5555.3 (lastSeq delta replay) — stash the per-session history cursor map
216
+ // so replayHistory (via sendPostAuthInfo → onAuthSuccess) can send only the
217
+ // entries newer than the client's cursor. The schema already coerced it to
218
+ // a { [sessionId]: nonNegativeInt } record; cap the honoured keys
219
+ // defensively (MAX_HISTORY_CURSORS) so an oversized map can't bloat the
220
+ // post-auth path. Absent → client.historyCursors stays undefined → full
221
+ // replay (the backward-compatible default).
222
+ if (authData.historyCursors && typeof authData.historyCursors === 'object') {
223
+ const cursors = {}
224
+ let n = 0
225
+ for (const [sid, seq] of Object.entries(authData.historyCursors)) {
226
+ if (n >= MAX_HISTORY_CURSORS) break
227
+ if (typeof seq === 'number' && Number.isFinite(seq) && seq >= 0) {
228
+ cursors[sid] = seq
229
+ n++
230
+ }
231
+ }
232
+ if (n > 0) client.historyCursors = cursors
233
+ }
234
+
235
+ onAuthSuccess(ws, client)
236
+ log.info(`Client ${client.id} authenticated`)
237
+ return true
238
+ }
239
+
240
+ // Auth failure — track for rate limiting, keyed by rateLimitKey (the
241
+ // trusted CF-Connecting-IP identity, not the TLS socket peer).
242
+ const now = Date.now()
243
+ const existing = authFailures.get(rateLimitKey) || { count: 0, firstFailure: now, blockedUntil: 0 }
244
+ if (!authFailures.has(rateLimitKey)) evictOldestIfFull(authFailures)
245
+ existing.count++
246
+ const backoff = Math.min(1000 * Math.pow(2, existing.count - 1), 60_000)
247
+ existing.blockedUntil = now + backoff
248
+ authFailures.set(rateLimitKey, existing)
249
+ metrics.inc('auth.failures')
250
+ log.warn(`Auth failure from ${rateLimitKey} (attempt ${existing.count}, blocked for ${backoff}ms)`)
251
+ send(ws, { type: 'auth_fail', reason: 'invalid_token' })
252
+ ws.close()
253
+ return true
254
+ }
255
+
256
+ /**
257
+ * Handle a pair message from an unauthenticated client.
258
+ * Validates the pairing ID and issues a session token.
259
+ * Returns true if the message was consumed (caller should return).
260
+ *
261
+ * @param {object} ctx - Server context (includes pairingManager)
262
+ * @param {WebSocket} ws
263
+ * @param {object} msg - The parsed message
264
+ * @returns {boolean}
265
+ */
266
+ export function handlePairMessage(ctx, ws, msg) {
267
+ const {
268
+ clients, pairingManager, send, onAuthSuccess,
269
+ authFailures, benignPairAttempts, minProtocolVersion, serverProtocolVersion,
270
+ activeSessionId,
271
+ } = ctx
272
+ const client = clients.get(ws)
273
+ if (!client || client.authenticated) return false
274
+ if (msg.type !== 'pair') return false
275
+ if (!pairingManager) {
276
+ send(ws, { type: 'pair_fail', reason: 'pairing_not_enabled' })
277
+ ws.close()
278
+ return true
279
+ }
280
+
281
+ // Validate pair message shape
282
+ const pairParsed = PairSchema.safeParse(msg)
283
+ if (!pairParsed.success) {
284
+ send(ws, { type: 'pair_fail', reason: 'invalid_message' })
285
+ ws.close()
286
+ return true
287
+ }
288
+ const pairData = pairParsed.data
289
+
290
+ // Check rate limit.
291
+ //
292
+ // Must use client.rateLimitKey (CF-Connecting-IP when behind a Cloudflare
293
+ // tunnel) — NOT client.socketIp. Behind cloudflared every client has
294
+ // socketIp=127.0.0.1, so keying pairing failures off socketIp lets one
295
+ // attacker lock out every legitimate pairing attempt via the shared
296
+ // bucket. Same pattern as handleAuthMessage above. 2026-04-11 audit
297
+ // blocker 7 follow-up — Copilot caught this second site on PR #2805.
298
+ const rateLimitKey = client.rateLimitKey || client.socketIp
299
+ const failure = authFailures.get(rateLimitKey)
300
+ if (failure && failure.blockedUntil > Date.now()) {
301
+ log.warn(`Pair rate-limited for ${rateLimitKey} (${failure.count} failures)`)
302
+ send(ws, { type: 'pair_fail', reason: 'rate_limited' })
303
+ ws.close()
304
+ return true
305
+ }
306
+
307
+ // Lenient rate limiter for benign already_used/expired hammering (#3019).
308
+ // Independent from the strict authFailures bucket so its breach never
309
+ // disables genuine brute-force protection for the same IP.
310
+ const benignEntry = benignPairAttempts && benignPairAttempts.get(rateLimitKey)
311
+ if (benignEntry && benignEntry.blockedUntil > Date.now()) {
312
+ log.warn(`Pair lenient-rate-limited for ${rateLimitKey} (${benignEntry.count} benign attempts)`)
313
+ send(ws, { type: 'pair_fail', reason: 'rate_limited' })
314
+ ws.close()
315
+ return true
316
+ }
317
+
318
+ // Linking-mode default (#3079): WsServer's activeSessionId getter always
319
+ // returns null, so the issued token is NOT auto-bound to a session. The QR
320
+ // shown by the dashboard is a general "link this device" code; the app can
321
+ // create or switch sessions freely on its own. Session-scoped pairings can
322
+ // still be issued via a different code path (per-client boundSessionId) —
323
+ // this signature keeps the parameter so future opt-in callers can pass a
324
+ // real sessionId. See packages/server/src/ws-server.js:510 for the full
325
+ // rationale.
326
+ const result = pairingManager.validatePairing(msg.pairingId, activeSessionId || null)
327
+ if (result.valid) {
328
+ // Check protocol version BEFORE marking authenticated
329
+ const hasVersion = typeof msg.protocolVersion === 'number' && Number.isInteger(msg.protocolVersion)
330
+ const clientVersion = hasVersion ? msg.protocolVersion : null
331
+
332
+ if (clientVersion !== null && clientVersion < minProtocolVersion) {
333
+ send(ws, { type: 'pair_fail', reason: `unsupported protocol version ${clientVersion} (minimum: ${minProtocolVersion})` })
334
+ ws.close()
335
+ return true
336
+ }
337
+
338
+ client.authenticated = true
339
+ client.authTime = Date.now()
340
+ client.pairedWith = msg.pairingId
341
+ authFailures.delete(rateLimitKey)
342
+ if (benignPairAttempts) benignPairAttempts.delete(rateLimitKey)
343
+
344
+ client.protocolVersion = clientVersion !== null
345
+ ? Math.min(clientVersion, serverProtocolVersion)
346
+ : minProtocolVersion
347
+
348
+ if (msg.deviceInfo && typeof msg.deviceInfo === 'object') {
349
+ client.deviceInfo = {
350
+ deviceId: typeof msg.deviceInfo.deviceId === 'string' ? msg.deviceInfo.deviceId : null,
351
+ deviceName: typeof msg.deviceInfo.deviceName === 'string' ? msg.deviceInfo.deviceName : null,
352
+ deviceType: ['phone', 'tablet', 'desktop', 'unknown'].includes(msg.deviceInfo.deviceType) ? msg.deviceInfo.deviceType : 'unknown',
353
+ platform: typeof msg.deviceInfo.platform === 'string' ? msg.deviceInfo.platform : 'unknown',
354
+ }
355
+ }
356
+
357
+ client.clientCapabilities = new Set(pairData.capabilities ?? [])
358
+
359
+ // Attach sessionToken so onAuthSuccess can include it in the auth_ok payload
360
+ // (client stores this for future reconnections)
361
+ client._sessionToken = result.sessionToken
362
+ onAuthSuccess(ws, client)
363
+ log.info(`Client ${client.id} paired via pairing ID`)
364
+ return true
365
+ }
366
+
367
+ // Approval-gated id (#5513, epic #5509): a Discord-delivered pairing link
368
+ // carries a flagged id that mints NO token. validatePairing consumed it
369
+ // (single-use) and reported `requires_approval`. This is NOT a failure — it
370
+ // is the intended routing: possession of the link is never sufficient; the
371
+ // device must request pairing and the host must approve it (#5510). We reply
372
+ // with a legible `pair_fail { reason: 'requires_approval' }` and close:
373
+ // - old clients surface the reason and clean up (no hang);
374
+ // - new dashboards detect the reason and transparently open the
375
+ // request-pair UX (RequestPairPanel), which issues a fresh `pair_request`
376
+ // on its own connection through the existing #5510 flow.
377
+ // It does NOT count toward either rate-limit bucket — this is a normal,
378
+ // expected redemption, not a brute-force or benign-hammer signal.
379
+ if (result.reason === 'requires_approval') {
380
+ log.info(`Gated pairing id redeemed from ${rateLimitKey} — routing to host approval (requires_approval)`)
381
+ send(ws, { type: 'pair_fail', reason: 'requires_approval' })
382
+ ws.close()
383
+ return true
384
+ }
385
+
386
+ // Pairing failure — only increment the shared rate-limiter bucket for
387
+ // genuine brute-force signals (invalid_pairing_id).
388
+ //
389
+ // `already_used` and `expired` are benign UX events: the client retried
390
+ // with a stale or consumed QR code. Counting them toward the exponential
391
+ // backoff budget locks out legitimate users who rescan a few times while
392
+ // waiting for a fresh QR. Only `invalid_pairing_id` warrants aggressive
393
+ // rate limiting because it is the only reason that indicates a fresh
394
+ // wrong code — the threat model for brute-force guessing.
395
+ //
396
+ // See #2917 for the full threat-model breakdown.
397
+ const isBruteForceSignal = result.reason === 'invalid_pairing_id'
398
+ if (isBruteForceSignal) {
399
+ const now = Date.now()
400
+ const existing = authFailures.get(rateLimitKey) || { count: 0, firstFailure: now, blockedUntil: 0 }
401
+ if (!authFailures.has(rateLimitKey)) evictOldestIfFull(authFailures)
402
+ existing.count++
403
+ const backoff = Math.min(1000 * Math.pow(2, existing.count - 1), 60_000)
404
+ existing.blockedUntil = now + backoff
405
+ authFailures.set(rateLimitKey, existing)
406
+ log.warn(`Pair failure from ${rateLimitKey}: ${result.reason} (attempt ${existing.count})`)
407
+ send(ws, { type: 'pair_fail', reason: result.reason })
408
+ ws.close()
409
+ return true
410
+ }
411
+
412
+ // Benign failure (already_used / expired). Tally on the lenient bucket so a
413
+ // single IP cannot hammer the server during the consumed-ID TTL window.
414
+ // recordBenignPairAttempt returns true the moment the threshold is breached.
415
+ if (benignPairAttempts) {
416
+ const blockedNow = recordBenignPairAttempt(benignPairAttempts, rateLimitKey, Date.now())
417
+ if (blockedNow) {
418
+ log.warn(`Pair lenient-rate-limit triggered for ${rateLimitKey} after benign hammering`)
419
+ send(ws, { type: 'pair_fail', reason: 'rate_limited' })
420
+ ws.close()
421
+ return true
422
+ }
423
+ }
424
+ log.info(`Pair failure from ${rateLimitKey}: ${result.reason} (benign — not counted toward strict rate limit)`)
425
+ send(ws, { type: 'pair_fail', reason: result.reason })
426
+ ws.close()
427
+ return true
428
+ }
429
+
430
+ /**
431
+ * Handle a `pair_request` from an UNAUTHENTICATED client (#5510, epic #5509).
432
+ *
433
+ * Same exposure class as `handlePairMessage`: pre-auth, rate-limited (the
434
+ * PairingManager queue enforces a global cap + per-request TTL + per-source rate
435
+ * limit), and the connection is kept OPEN so the requester can later receive its
436
+ * terminal `pair_result`.
437
+ *
438
+ * The verify code is generated SERVER-SIDE inside enqueuePendingRequest and only
439
+ * ever travels server→requester (display) and server→host surfaces (compare).
440
+ * The requester never echoes it back, so a mismatch is impossible by
441
+ * construction. deviceName is attacker-controlled — capped at the schema and
442
+ * relayed as plain text (never interpolated into a log format).
443
+ *
444
+ * Returns true if the message was consumed.
445
+ *
446
+ * @param {object} ctx - Server context (pairingManager, registerPairRequester,
447
+ * broadcastPairPending, send)
448
+ * @param {WebSocket} ws
449
+ * @param {object} msg
450
+ * @returns {boolean}
451
+ */
452
+ export function handlePairRequestMessage(ctx, ws, msg) {
453
+ const {
454
+ clients, pairingManager, send,
455
+ registerPairRequester, broadcastPairPending,
456
+ } = ctx
457
+ const client = clients.get(ws)
458
+ if (!client || client.authenticated) return false
459
+ if (msg.type !== 'pair_request') return false
460
+
461
+ if (!pairingManager) {
462
+ send(ws, { type: 'pair_result', requestId: typeof msg?.requestId === 'string' ? msg.requestId : '', ok: false, reason: 'pairing_not_enabled' })
463
+ ws.close()
464
+ return true
465
+ }
466
+
467
+ // Validate shape.
468
+ const parsed = PairRequestSchema.safeParse(msg)
469
+ if (!parsed.success) {
470
+ send(ws, { type: 'pair_result', requestId: typeof msg?.requestId === 'string' ? msg.requestId : '', ok: false, reason: 'invalid_message' })
471
+ ws.close()
472
+ return true
473
+ }
474
+ const data = parsed.data
475
+
476
+ // Rate-limit key: CF-Connecting-IP behind the tunnel, else socket ip (same
477
+ // rationale as handlePairMessage — keying off socketIp behind cloudflared lets
478
+ // one source lock out everyone).
479
+ const source = client.rateLimitKey || client.socketIp || ''
480
+
481
+ const result = pairingManager.enqueuePendingRequest({
482
+ requestId: data.requestId,
483
+ deviceName: data.deviceName || '',
484
+ source,
485
+ })
486
+
487
+ if (!result.ok) {
488
+ // Bounded rejection (rate_limited / queue_full / duplicate_request). Do NOT
489
+ // log deviceName (attacker-controlled). The connection closes — the
490
+ // requester can retry with backoff / a fresh requestId.
491
+ log.warn(`pair_request rejected for ${source}: ${result.reason}`)
492
+ send(ws, { type: 'pair_result', requestId: data.requestId, ok: false, reason: result.reason })
493
+ ws.close()
494
+ return true
495
+ }
496
+
497
+ // Track the requester's open connection so approve/deny/expire can reach it.
498
+ registerPairRequester(data.requestId, ws)
499
+
500
+ // Tell the requester its code to display.
501
+ send(ws, { type: 'pair_request_pending', requestId: data.requestId, verifyCode: result.verifyCode })
502
+
503
+ // Fan the request out to host-level approval surfaces. deviceName relayed
504
+ // verbatim (plain text); never logged.
505
+ broadcastPairPending({
506
+ type: 'pair_pending',
507
+ requestId: data.requestId,
508
+ deviceName: data.deviceName ? String(data.deviceName).slice(0, 64) : '',
509
+ verifyCode: result.verifyCode,
510
+ expiresAt: result.expiresAt,
511
+ })
512
+
513
+ // requestId is pre-auth attacker-controlled (the schema permits newlines /
514
+ // control chars); JSON.stringify keeps it a single well-formed log record.
515
+ log.info(`pair_request queued from ${source} (requestId ${JSON.stringify(data.requestId)})`)
516
+ return true
517
+ }
518
+
519
+ /**
520
+ * Handle key exchange for E2E encryption.
521
+ * Returns true if the message was consumed (caller should return).
522
+ *
523
+ * @param {object} ctx - Server context
524
+ * @param {WebSocket} ws
525
+ * @param {object} msg
526
+ * @returns {boolean}
527
+ */
528
+ export function handleKeyExchange(ctx, ws, msg) {
529
+ const { clients, flushPostAuthQueue, serverIdentity } = ctx
530
+ const client = clients.get(ws)
531
+
532
+ if (!client?.encryptionPending) return false
533
+
534
+ if (msg.type === 'key_exchange') {
535
+ clearTimeout(client._keyExchangeTimeout)
536
+
537
+ // Check the salt requirement BEFORE schema validation. Since
538
+ // KeyExchangeSchema now requires salt, the safeParse below would reject
539
+ // old no-salt clients with a generic INVALID_MESSAGE. Hoisting the
540
+ // salt-specific check up here lets us give clients a precise and
541
+ // actionable KEY_EXCHANGE_SALT_REQUIRED error that names the exact
542
+ // upgrade path.
543
+ //
544
+ // We still do a minimum shape check (type and a string publicKey) before
545
+ // issuing the targeted error — if the payload isn't even a key_exchange,
546
+ // fall through to the schema validator for the generic error.
547
+ if (typeof msg.publicKey === 'string' && !msg.salt) {
548
+ log.warn(`key_exchange from ${client.id} missing required 'salt' field; client likely predates 600612649 (chroxy >= v0.6.8). Rejecting to avoid nonce reuse on reconnect.`)
549
+ try {
550
+ ws.send(JSON.stringify({
551
+ type: 'error',
552
+ code: 'KEY_EXCHANGE_SALT_REQUIRED',
553
+ message: 'key_exchange requires a client-supplied salt. Please upgrade your Chroxy client to v0.6.8 or later.',
554
+ details: 'key_exchange requires a client-supplied salt for per-connection key derivation. Older clients that omit salt would fall back to the raw DH shared key with nonce=0 on reconnect, re-introducing a nonce-reuse vulnerability. Upgrade the client to a build that includes commit 600612649 (Chroxy v0.6.8 or later).',
555
+ }))
556
+ } catch (err) {
557
+ log.error(`Failed to send salt-required error: ${err.message}`)
558
+ }
559
+ ws.close(1008, 'key_exchange salt required')
560
+ return true
561
+ }
562
+
563
+ const keParsed = KeyExchangeSchema.safeParse(msg)
564
+ if (!keParsed.success) {
565
+ const details = keParsed.error.issues.map(i => i.message).join(', ')
566
+ log.warn(`Invalid key_exchange message from ${client.id}: ${details}`)
567
+ try {
568
+ ws.send(JSON.stringify({
569
+ type: 'error',
570
+ code: 'INVALID_MESSAGE',
571
+ message: 'Invalid key_exchange message.',
572
+ details,
573
+ }))
574
+ } catch (err) {
575
+ log.error(`Failed to send key_exchange error: ${err.message}`)
576
+ }
577
+ ws.close(1008, 'Invalid key_exchange message')
578
+ return true
579
+ }
580
+ const serverKp = createKeyPair()
581
+ const rawSharedKey = deriveSharedKey(msg.publicKey, serverKp.secretKey)
582
+ // Derive a per-connection sub-key so the nonce counter can safely restart
583
+ // at 0 on each reconnect without reusing (key, nonce) pairs from a prior
584
+ // session. This is the enforced path after the 2026-04-11 audit.
585
+ const encryptionKey = deriveConnectionKey(rawSharedKey, msg.salt)
586
+ client.encryptionState = { sharedKey: encryptionKey, sendNonce: 0, recvNonce: 0 }
587
+ client.encryptionPending = false
588
+ // #5536 — sign the ephemeral exchange public key with the long-lived
589
+ // identity key so a client that pinned our identity (at pairing time) can
590
+ // verify this exchange key really came from this daemon, defeating a MITM
591
+ // key swap. Absent when pinning is unavailable (no identity / signing
592
+ // error) — old clients ignore the field and the exchange stays TOFU.
593
+ let serverKeySig = null
594
+ if (serverIdentity?.secretKey) {
595
+ try {
596
+ serverKeySig = signExchangeKey(serverKp.publicKey, serverIdentity.secretKey, { domainSeparated: true })
597
+ } catch (err) {
598
+ log.warn(`Failed to sign exchange key for ${client.id}: ${err.message}`)
599
+ }
600
+ }
601
+ try {
602
+ ws.send(JSON.stringify({
603
+ type: 'key_exchange_ok',
604
+ publicKey: serverKp.publicKey,
605
+ ...(serverKeySig ? { serverKeySig } : {}),
606
+ // #5616/#5976 — identity-rotation continuity cert (discrete path). Same
607
+ // contract as the eager auth_ok path: present only alongside a live
608
+ // exchange signature and only when the daemon was rotated. Absent for
609
+ // un-rotated daemons; old clients ignore it.
610
+ ...(serverKeySig && serverIdentity?.rotationCert
611
+ ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
612
+ : {}),
613
+ }))
614
+ } catch (err) {
615
+ // #5702 (8b): the client never received the exchange key, so we must NOT
616
+ // mark E2E established or flush the post-auth queue. `encryptionState` was
617
+ // already set above, so proceeding would encrypt frames the client can't
618
+ // decrypt — a wedged session (the client waits forever for key_exchange_ok
619
+ // while the server speaks ciphertext it can't read). Roll the crypto state
620
+ // back and close so the client reconnects and retries the handshake.
621
+ log.error(`Failed to send key_exchange_ok to ${client.id}: ${String(err?.message || err)} — aborting handshake`)
622
+ client.encryptionState = null
623
+ client.encryptionPending = false
624
+ client.postAuthQueue = null
625
+ try { ws.close(1011, 'Key exchange failed') } catch { /* socket already gone */ }
626
+ return true
627
+ }
628
+ log.info(`E2E encryption established with ${client.id}`)
629
+ const queue = client.postAuthQueue
630
+ client.postAuthQueue = null
631
+ flushPostAuthQueue(ws, queue)
632
+ return true
633
+ }
634
+
635
+ // Non-key_exchange message while pending — disconnect
636
+ clearTimeout(client._keyExchangeTimeout)
637
+ log.error(`Client ${client.id} sent ${msg.type} instead of key_exchange — disconnecting (encryption required)`)
638
+ client.encryptionPending = false
639
+ client.postAuthQueue = null
640
+ try {
641
+ ws.send(JSON.stringify({ type: 'server_error', message: 'Encryption required but client did not initiate key exchange.', recoverable: false }))
642
+ } catch (_) {}
643
+ ws.close(1008, 'Key exchange required')
644
+ return true
645
+ }