@openchamber/web 1.14.1 → 1.16.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 (124) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
  8. package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
  9. package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
  10. package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
  12. package/dist/assets/es-r0_jT91q.js +15 -0
  13. package/dist/assets/fr-Bo8rtAJ1.js +13 -0
  14. package/dist/assets/index-8J6waVO6.js +2 -0
  15. package/dist/assets/index-DEMqM4Lz.css +1 -0
  16. package/dist/assets/ja-BPWtkG-c.js +15 -0
  17. package/dist/assets/ko-Bv0k-0E3.js +15 -0
  18. package/dist/assets/main-B-GA5Tg5.js +237 -0
  19. package/dist/assets/main-Dfm-VKZ9.js +2 -0
  20. package/dist/assets/miniChat-CfmCFFfu.js +2 -0
  21. package/dist/assets/mobile-CXJqeDlm.js +2 -0
  22. package/dist/assets/pl-CiTP50bz.js +15 -0
  23. package/dist/assets/pt-BR-DadIjX5L.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
  25. package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
  27. package/dist/assets/uk-2RpsWGoZ.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
  31. package/dist/assets/zh-TW--f_BqBpD.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +236 -2
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  41. package/server/lib/notifications/apns-runtime.js +11 -16
  42. package/server/lib/notifications/runtime.js +135 -33
  43. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  44. package/server/lib/opencode/agents.js +3 -0
  45. package/server/lib/opencode/bootstrap-runtime.js +15 -0
  46. package/server/lib/opencode/core-routes.js +321 -8
  47. package/server/lib/opencode/core-routes.test.js +329 -9
  48. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  49. package/server/lib/opencode/network-runtime.js +14 -1
  50. package/server/lib/opencode/network-runtime.test.js +29 -9
  51. package/server/lib/opencode/proxy.js +47 -6
  52. package/server/lib/opencode/settings-helpers.js +24 -0
  53. package/server/lib/opencode/settings-helpers.test.js +25 -0
  54. package/server/lib/opencode/settings-normalization-runtime.js +21 -4
  55. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  56. package/server/lib/opencode/settings-runtime.js +25 -0
  57. package/server/lib/opencode/shutdown-runtime.js +2 -0
  58. package/server/lib/opencode/tunnel-auth.js +4 -9
  59. package/server/lib/package-manager.js +18 -5
  60. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  61. package/server/lib/permission-auto-accept/runtime.js +263 -0
  62. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  63. package/server/lib/projects/project-config.js +8 -0
  64. package/server/lib/quota/DOCUMENTATION.md +5 -2
  65. package/server/lib/quota/credentials/providers.js +43 -0
  66. package/server/lib/quota/credentials/store.js +48 -0
  67. package/server/lib/quota/credentials/store.test.js +26 -0
  68. package/server/lib/quota/opencode-go-credentials.js +11 -0
  69. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  70. package/server/lib/quota/providers/codex.js +7 -4
  71. package/server/lib/quota/providers/codex.test.js +48 -0
  72. package/server/lib/quota/providers/cursor.js +28 -39
  73. package/server/lib/quota/providers/index.js +7 -0
  74. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  75. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  76. package/server/lib/quota/providers/opencode-go.js +70 -0
  77. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  78. package/server/lib/quota/routes.js +78 -7
  79. package/server/lib/quota/routes.test.js +40 -0
  80. package/server/lib/relay/DOCUMENTATION.md +98 -0
  81. package/server/lib/relay/cross-compat.test.js +135 -0
  82. package/server/lib/relay/e2ee.js +341 -0
  83. package/server/lib/relay/e2ee.test.js +124 -0
  84. package/server/lib/relay/host-client.js +389 -0
  85. package/server/lib/relay/host-client.test.js +280 -0
  86. package/server/lib/relay/host-lock.js +101 -0
  87. package/server/lib/relay/host-lock.test.js +129 -0
  88. package/server/lib/relay/identity.js +93 -0
  89. package/server/lib/relay/identity.test.js +78 -0
  90. package/server/lib/relay/service.js +334 -0
  91. package/server/lib/relay/signing-key.js +73 -0
  92. package/server/lib/relay/tunnel-codec.js +373 -0
  93. package/server/lib/relay/tunnel-codec.test.js +58 -0
  94. package/server/lib/relay/tunnel-host.js +462 -0
  95. package/server/lib/scheduled-tasks/runtime.js +104 -0
  96. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  97. package/server/lib/session-goal/objectives.js +61 -0
  98. package/server/lib/session-goal/routes.js +36 -0
  99. package/server/lib/session-goal/runtime.js +764 -0
  100. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  101. package/server/lib/ui-auth/ui-auth.js +10 -0
  102. package/server/opencode-proxy.test.js +38 -0
  103. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  104. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  105. package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
  106. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  107. package/dist/assets/es-bWcuDy_2.js +0 -15
  108. package/dist/assets/fr-DzRs3OzV.js +0 -13
  109. package/dist/assets/index-KnWk9fmM.css +0 -1
  110. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  111. package/dist/assets/ja-BqUX_UD3.js +0 -15
  112. package/dist/assets/ko-BQo10SNx.js +0 -15
  113. package/dist/assets/main-BDoqLlQB.js +0 -236
  114. package/dist/assets/main-DUGyTrDt.js +0 -2
  115. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  116. package/dist/assets/mobile-DnghtOCb.js +0 -2
  117. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  118. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  119. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  120. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  121. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  122. package/dist/assets/uk-C9k8SP8q.js +0 -15
  123. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  124. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
@@ -0,0 +1,389 @@
1
+ // Long-lived relay host client: maintains the signed `host-control` socket to
2
+ // the relay, and per connected client a signed `host-data` socket that runs the
3
+ // responder E2EE handshake and feeds decrypted frames into a tunnel-host
4
+ // dispatcher. Spec: .opencode/plans/private-relay/01-protocol-spec.md (Layer 1).
5
+
6
+ import { WebSocket } from 'ws';
7
+
8
+ import { RELAY_PROTOCOL_VERSION, RelayCloseCode, createHostHandshake } from './e2ee.js';
9
+ import { createOutboundFrameBatcher, decodeFrameBatch } from './tunnel-codec.js';
10
+ import { createTunnelHost } from './tunnel-host.js';
11
+
12
+ const BACKOFF_BASE_MS = 1000;
13
+ const BACKOFF_CAP_MS = 30000;
14
+ const DATA_SOCKET_OPEN_TIMEOUT_MS = 15000;
15
+ // Clients send a tunnel Ping at least every ~30s when idle, so a data socket
16
+ // with no inbound traffic for 3 ping intervals belongs to a client that died
17
+ // without a WebSocket close (network loss, battery kill). The relay worker may
18
+ // not notice the dead client leg for a long time, so the host must reap these
19
+ // itself — both to free resources and to keep the "N devices connected" status
20
+ // honest instead of counting ghosts.
21
+ const DATA_SOCKET_IDLE_TIMEOUT_MS = 90_000;
22
+ const DATA_SOCKET_IDLE_SWEEP_INTERVAL_MS = 30_000;
23
+ // Protocol-level keepalive for the control socket. Without it, a network path
24
+ // that dies silently (NAT timeout, relay-edge eviction without close frames)
25
+ // leaves the host believing it is registered while the relay has forgotten it —
26
+ // every client tunnel then hangs in `connecting` forever. A missed pong window
27
+ // terminates the socket, which drives the normal reconnect + re-registration.
28
+ const CONTROL_PING_INTERVAL_MS = 30_000;
29
+ const CONTROL_PONG_GRACE_MS = 10_000;
30
+ const DEFAULT_BATCH_WINDOW_MS = 150;
31
+
32
+ // Resolve the frame-batching flush window: explicit option wins, then env, then
33
+ // the 150 ms default. Only applies on directions where batching was negotiated.
34
+ const resolveBatchWindowMs = (option) => {
35
+ if (Number.isFinite(option) && option >= 0) return option;
36
+ const envValue = Number.parseInt(process.env.OPENCHAMBER_RELAY_BATCH_WINDOW_MS ?? '', 10);
37
+ if (Number.isFinite(envValue) && envValue >= 0) return envValue;
38
+ return DEFAULT_BATCH_WINDOW_MS;
39
+ };
40
+
41
+ /**
42
+ * @param {{
43
+ * relayUrl: string,
44
+ * identity: { serverId: string, hostEncPrivateKey: CryptoKey, signRelayAuth: (role: string, connectionId?: string | null) => { ts: number, sig: string, pk: string } },
45
+ * localPort?: number,
46
+ * getLocalPort?: () => number,
47
+ * onStatus?: (status: { state: string, lastError: string | null, connectedClients: number }) => void,
48
+ * logger?: Pick<Console, 'warn'>,
49
+ * }} options
50
+ */
51
+ export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, onStatus, logger = console, batchWindowMs, batch }) => {
52
+ const resolveLocalPort = typeof getLocalPort === 'function' ? getLocalPort : () => localPort;
53
+ const localBatch = batch !== false;
54
+ const resolvedBatchWindowMs = resolveBatchWindowMs(batchWindowMs);
55
+
56
+ let stopped = false;
57
+ let state = 'connecting';
58
+ let lastError = null;
59
+ let controlSocket = null;
60
+ let reconnectTimer = null;
61
+ let consecutiveFailures = 0;
62
+ /** @type {Map<string, { socket: WebSocket, tunnel: ReturnType<typeof createTunnelHost> | null, openTimer: NodeJS.Timeout | null }>} */
63
+ const dataSockets = new Map();
64
+
65
+ const emitStatus = () => {
66
+ try {
67
+ onStatus?.({ state, lastError, connectedClients: dataSockets.size });
68
+ } catch {
69
+ // status consumers must not break the transport
70
+ }
71
+ };
72
+
73
+ const setState = (nextState, error) => {
74
+ state = nextState;
75
+ if (error !== undefined) lastError = error;
76
+ emitStatus();
77
+ };
78
+
79
+ const buildSocketUrl = (role, connectionId) => {
80
+ const url = new URL(relayUrl);
81
+ url.searchParams.set('v', String(RELAY_PROTOCOL_VERSION));
82
+ url.searchParams.set('role', role);
83
+ url.searchParams.set('serverId', identity.serverId);
84
+ if (connectionId) url.searchParams.set('connectionId', connectionId);
85
+ const auth = identity.signRelayAuth(role, connectionId ?? null);
86
+ url.searchParams.set('ts', String(auth.ts));
87
+ url.searchParams.set('sig', auth.sig);
88
+ url.searchParams.set('pk', auth.pk);
89
+ return url.toString();
90
+ };
91
+
92
+ const teardownDataSocket = (connectionId, closeCode, reason) => {
93
+ const entry = dataSockets.get(connectionId);
94
+ if (!entry) return;
95
+ dataSockets.delete(connectionId);
96
+ if (entry.openTimer) clearTimeout(entry.openTimer);
97
+ entry.batcher?.dispose();
98
+ entry.tunnel?.close();
99
+ try {
100
+ if (entry.socket.readyState === WebSocket.OPEN || entry.socket.readyState === WebSocket.CONNECTING) {
101
+ if (closeCode) entry.socket.close(closeCode, reason ?? '');
102
+ else entry.socket.terminate();
103
+ }
104
+ } catch {
105
+ // socket already gone
106
+ }
107
+ emitStatus();
108
+ };
109
+
110
+ const openDataSocket = (connectionId) => {
111
+ if (stopped || dataSockets.has(connectionId)) return;
112
+
113
+ let socket;
114
+ try {
115
+ socket = new WebSocket(buildSocketUrl('host-data', connectionId));
116
+ } catch (error) {
117
+ logger.warn(`[Relay] host-data dial failed: ${error?.message ?? error}`);
118
+ return;
119
+ }
120
+
121
+ const entry = { socket, tunnel: null, openTimer: null, batcher: null, lastActivityAt: Date.now() };
122
+ dataSockets.set(connectionId, entry);
123
+ entry.openTimer = setTimeout(() => {
124
+ logger.warn('[Relay] host-data socket open timeout');
125
+ teardownDataSocket(connectionId);
126
+ }, DATA_SOCKET_OPEN_TIMEOUT_MS);
127
+
128
+ const handshake = createHostHandshake(identity.hostEncPrivateKey, { batch: localBatch });
129
+ let channel = null;
130
+ let batchNegotiated = false;
131
+ // Serialize async message handling so encrypted frame order (and the
132
+ // strictly-increasing decrypt counter) is preserved.
133
+ let processing = Promise.resolve();
134
+ // Serialize encrypt+send so the per-direction IV counter reaches the wire in
135
+ // encryption order. One encrypt() == one WS message == one counter tick,
136
+ // whether it carries a batch or a lone frame.
137
+ let sendChain = Promise.resolve();
138
+ const sendEncryptedPlaintext = (plaintext) => {
139
+ sendChain = sendChain
140
+ .then(async () => {
141
+ if (dataSockets.get(connectionId) !== entry || socket.readyState !== WebSocket.OPEN || !channel) return;
142
+ const encrypted = await channel.encryptor.encrypt(plaintext);
143
+ socket.send(encrypted, { binary: true });
144
+ })
145
+ .catch((error) => {
146
+ logger.warn(`[Relay] host-data send failed: ${error?.message ?? error}`);
147
+ });
148
+ };
149
+
150
+ const failChannel = (closeCode, reason) => {
151
+ // connectionId + reason only — never payload contents.
152
+ logger.warn(`[Relay] data channel failed connectionId=${connectionId} reason=${reason ?? 'unknown'}`);
153
+ teardownDataSocket(connectionId, closeCode, reason);
154
+ };
155
+
156
+ const handleMessage = async (data, isBinary) => {
157
+ const current = dataSockets.get(connectionId);
158
+ if (current !== entry) return;
159
+ // Any inbound message (including the client's keepalive Ping) proves the
160
+ // client is alive; the idle sweeper reaps sockets this stops updating.
161
+ entry.lastActivityAt = Date.now();
162
+
163
+ if (!isBinary) {
164
+ const action = await handshake.handleText(data.toString('utf8'));
165
+ if (action.type === 'send-text') {
166
+ socket.send(action.text);
167
+ } else if (action.type === 'established') {
168
+ channel = action.channel;
169
+ batchNegotiated = action.batch === true;
170
+ entry.batcher = batchNegotiated
171
+ ? createOutboundFrameBatcher({ windowMs: resolvedBatchWindowMs, sendBatch: sendEncryptedPlaintext })
172
+ : null;
173
+ entry.tunnel = createTunnelHost({
174
+ connectionId,
175
+ getLocalPort: resolveLocalPort,
176
+ getBufferedAmount: () => socket.bufferedAmount,
177
+ sendFrame: (plaintextFrame) => {
178
+ if (dataSockets.get(connectionId) !== entry || socket.readyState !== WebSocket.OPEN) return;
179
+ if (entry.batcher) entry.batcher.enqueue(plaintextFrame);
180
+ else sendEncryptedPlaintext(plaintextFrame);
181
+ },
182
+ });
183
+ if (action.replyText) socket.send(action.replyText);
184
+ } else if (action.type === 'fail') {
185
+ failChannel(action.closeCode, action.reason);
186
+ }
187
+ return;
188
+ }
189
+
190
+ if (!channel || !entry.tunnel) {
191
+ // Encrypted traffic before the handshake completed: fail closed.
192
+ failChannel(RelayCloseCode.ChannelFailure, 'binary frame before handshake');
193
+ return;
194
+ }
195
+ let plaintext;
196
+ try {
197
+ plaintext = await channel.decryptor.decrypt(new Uint8Array(data));
198
+ } catch {
199
+ failChannel(RelayCloseCode.ChannelFailure, 'frame decryption failed');
200
+ return;
201
+ }
202
+ try {
203
+ if (batchNegotiated) {
204
+ // One encrypted message may carry several tunnel frames; dispatch each
205
+ // in order through the same per-frame handling as legacy.
206
+ for (const frame of decodeFrameBatch(plaintext)) {
207
+ if (dataSockets.get(connectionId) !== entry) return;
208
+ await entry.tunnel.handleFrame(frame);
209
+ }
210
+ } else {
211
+ await entry.tunnel.handleFrame(plaintext);
212
+ }
213
+ } catch (error) {
214
+ logger.warn(`[Relay] tunnel frame handling failed: ${error?.message ?? error}`);
215
+ }
216
+ };
217
+
218
+ socket.on('open', () => {
219
+ if (entry.openTimer) {
220
+ clearTimeout(entry.openTimer);
221
+ entry.openTimer = null;
222
+ }
223
+ emitStatus();
224
+ });
225
+ socket.on('message', (data, isBinary) => {
226
+ processing = processing
227
+ .then(() => handleMessage(data, isBinary))
228
+ .catch((error) => {
229
+ logger.warn(`[Relay] data socket message failed: ${error?.message ?? error}`);
230
+ failChannel(RelayCloseCode.ChannelFailure, 'internal error');
231
+ });
232
+ });
233
+ socket.on('close', () => {
234
+ teardownDataSocket(connectionId);
235
+ });
236
+ socket.on('error', (error) => {
237
+ logger.warn(`[Relay] host-data socket error: ${error?.message ?? error}`);
238
+ });
239
+ };
240
+
241
+ const handleControlMessage = (raw) => {
242
+ let message;
243
+ try {
244
+ message = JSON.parse(raw);
245
+ } catch {
246
+ return;
247
+ }
248
+ if (!message || typeof message !== 'object') return;
249
+ if (message.type === 'sync' && Array.isArray(message.connectionIds)) {
250
+ const wanted = new Set(message.connectionIds.filter((id) => typeof id === 'string' && id.length > 0));
251
+ for (const connectionId of [...dataSockets.keys()]) {
252
+ if (!wanted.has(connectionId)) teardownDataSocket(connectionId);
253
+ }
254
+ for (const connectionId of wanted) {
255
+ openDataSocket(connectionId);
256
+ }
257
+ return;
258
+ }
259
+ if (message.type === 'connected' && typeof message.connectionId === 'string') {
260
+ openDataSocket(message.connectionId);
261
+ return;
262
+ }
263
+ if (message.type === 'disconnected' && typeof message.connectionId === 'string') {
264
+ teardownDataSocket(message.connectionId);
265
+ }
266
+ };
267
+
268
+ const scheduleReconnect = () => {
269
+ if (stopped || reconnectTimer) return;
270
+ const delay = Math.min(BACKOFF_BASE_MS * 2 ** consecutiveFailures, BACKOFF_CAP_MS);
271
+ consecutiveFailures += 1;
272
+ setState('reconnecting');
273
+ reconnectTimer = setTimeout(() => {
274
+ reconnectTimer = null;
275
+ connectControl();
276
+ }, delay);
277
+ };
278
+
279
+ const connectControl = () => {
280
+ if (stopped) return;
281
+ setState(consecutiveFailures === 0 ? 'connecting' : 'reconnecting');
282
+
283
+ let socket;
284
+ try {
285
+ socket = new WebSocket(buildSocketUrl('host-control'));
286
+ } catch (error) {
287
+ lastError = error?.message ?? String(error);
288
+ scheduleReconnect();
289
+ return;
290
+ }
291
+ controlSocket = socket;
292
+
293
+ // Liveness: ping on an interval; any pong (or message) proves the path.
294
+ // A quiet window beyond interval+grace means the connection silently died —
295
+ // terminate so the close handler reconnects and re-registers at the relay.
296
+ let lastAliveAt = Date.now();
297
+ const pingTimer = setInterval(() => {
298
+ if (controlSocket !== socket || socket.readyState !== WebSocket.OPEN) return;
299
+ if (Date.now() - lastAliveAt > CONTROL_PING_INTERVAL_MS + CONTROL_PONG_GRACE_MS) {
300
+ logger.warn('[Relay] control socket unresponsive (missed pong) — reconnecting');
301
+ try {
302
+ socket.terminate();
303
+ } catch {
304
+ // terminate is best-effort; the close handler still runs.
305
+ }
306
+ return;
307
+ }
308
+ try {
309
+ socket.ping();
310
+ } catch {
311
+ // Send failure surfaces via the error/close handlers.
312
+ }
313
+ }, CONTROL_PING_INTERVAL_MS);
314
+ if (typeof pingTimer.unref === 'function') pingTimer.unref();
315
+
316
+ socket.on('open', () => {
317
+ if (controlSocket !== socket) return;
318
+ consecutiveFailures = 0;
319
+ lastAliveAt = Date.now();
320
+ setState('connected', null);
321
+ });
322
+ socket.on('pong', () => {
323
+ lastAliveAt = Date.now();
324
+ });
325
+ socket.on('message', (data, isBinary) => {
326
+ if (controlSocket !== socket || isBinary) return;
327
+ lastAliveAt = Date.now();
328
+ handleControlMessage(data.toString('utf8'));
329
+ });
330
+ socket.on('error', (error) => {
331
+ if (controlSocket !== socket) return;
332
+ lastError = error?.message ?? String(error);
333
+ });
334
+ socket.on('close', (code, reasonBuffer) => {
335
+ clearInterval(pingTimer);
336
+ if (controlSocket !== socket) return;
337
+ controlSocket = null;
338
+ const reason = reasonBuffer ? reasonBuffer.toString('utf8') : '';
339
+ if (!lastError && code && code !== 1000) {
340
+ lastError = `control socket closed (${code}${reason ? `: ${reason}` : ''})`;
341
+ }
342
+ // Data sockets ride their own relay connections; the relay keeps clients
343
+ // alive through a 30 s control-reconnect grace window, so leave them up.
344
+ scheduleReconnect();
345
+ });
346
+ };
347
+
348
+ // Reap data sockets whose client went silent (no frames, no keepalive pings)
349
+ // — a dead phone leg the relay worker hasn't noticed yet.
350
+ const idleSweepTimer = setInterval(() => {
351
+ const now = Date.now();
352
+ for (const [connectionId, entry] of [...dataSockets.entries()]) {
353
+ if (now - entry.lastActivityAt <= DATA_SOCKET_IDLE_TIMEOUT_MS) continue;
354
+ logger.info(`[Relay] reaping idle data socket connectionId=${connectionId}`);
355
+ teardownDataSocket(connectionId, 1001, 'client idle timeout');
356
+ }
357
+ }, DATA_SOCKET_IDLE_SWEEP_INTERVAL_MS);
358
+ if (typeof idleSweepTimer.unref === 'function') idleSweepTimer.unref();
359
+
360
+ const stop = () => {
361
+ if (stopped) return;
362
+ stopped = true;
363
+ clearInterval(idleSweepTimer);
364
+ if (reconnectTimer) {
365
+ clearTimeout(reconnectTimer);
366
+ reconnectTimer = null;
367
+ }
368
+ for (const connectionId of [...dataSockets.keys()]) {
369
+ teardownDataSocket(connectionId, 1001, 'host stopping');
370
+ }
371
+ const socket = controlSocket;
372
+ controlSocket = null;
373
+ if (socket) {
374
+ try {
375
+ socket.close(1001, 'host stopping');
376
+ } catch {
377
+ socket.terminate();
378
+ }
379
+ }
380
+ setState('disabled');
381
+ };
382
+
383
+ connectControl();
384
+
385
+ return {
386
+ stop,
387
+ getStatus: () => ({ state, lastError, connectedClients: dataSockets.size }),
388
+ };
389
+ };
@@ -0,0 +1,280 @@
1
+ // Integration test: fake relay (minimal Layer 1) + real host-client + a scripted
2
+ // client using the JS e2ee initiator. Verifies the full handshake and a tunneled
3
+ // HTTP GET /health, and asserts only binary frames cross the relay post-handshake.
4
+
5
+ import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
6
+ import http from 'node:http';
7
+ import crypto from 'node:crypto';
8
+ import { WebSocket, WebSocketServer } from 'ws';
9
+
10
+ import { startRelayHost } from './host-client.js';
11
+ import {
12
+ bytesToBase64Url,
13
+ createFrameDecryptor,
14
+ createFrameEncryptor,
15
+ deriveSessionKeys,
16
+ exportPublicKeyJwk,
17
+ generateEcdhKeyPair,
18
+ generateHandshakeNonce,
19
+ importEcdhPrivateKey,
20
+ RELAY_PROTOCOL_VERSION,
21
+ } from './e2ee.js';
22
+ import {
23
+ TunnelFrameType,
24
+ decodeTunnelFrame,
25
+ encodeJsonPayload,
26
+ encodeTunnelFrame,
27
+ } from './tunnel-codec.js';
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Fake relay: routes host-control <-> host-data <-> client by (serverId, connectionId).
31
+ // Forwards frames verbatim, never inspects them.
32
+ // ---------------------------------------------------------------------------
33
+ const startFakeRelay = () => {
34
+ const server = http.createServer();
35
+ const wss = new WebSocketServer({ server });
36
+ const state = {
37
+ control: null,
38
+ hostData: new Map(), // connectionId -> ws
39
+ clients: new Map(), // connectionId -> ws
40
+ buffered: new Map(), // connectionId -> [[data, isBinary]] awaiting host-data
41
+ relayFrames: [], // observed forwarded frames (for plaintext assertions)
42
+ };
43
+
44
+ wss.on('connection', (ws, req) => {
45
+ const url = new URL(req.url, 'http://localhost');
46
+ const role = url.searchParams.get('role');
47
+ const connectionId = url.searchParams.get('connectionId');
48
+
49
+ if (role === 'host-control') {
50
+ state.control = ws;
51
+ // Announce any already-waiting clients.
52
+ ws.send(JSON.stringify({ type: 'sync', connectionIds: [...state.clients.keys()] }));
53
+ for (const id of state.clients.keys()) {
54
+ ws.send(JSON.stringify({ type: 'connected', connectionId: id }));
55
+ }
56
+ return;
57
+ }
58
+
59
+ if (role === 'host-data') {
60
+ state.hostData.set(connectionId, ws);
61
+ // Flush any client frames that arrived before this socket attached.
62
+ const buffered = state.buffered.get(connectionId) || [];
63
+ state.buffered.delete(connectionId);
64
+ for (const [data, isBinary] of buffered) ws.send(data, { binary: isBinary });
65
+ ws.on('message', (data, isBinary) => {
66
+ state.relayFrames.push({ from: 'host', isBinary });
67
+ const client = state.clients.get(connectionId);
68
+ if (client && client.readyState === WebSocket.OPEN) client.send(data, { binary: isBinary });
69
+ });
70
+ ws.on('close', () => state.hostData.delete(connectionId));
71
+ return;
72
+ }
73
+
74
+ if (role === 'client') {
75
+ state.clients.set(connectionId, ws);
76
+ ws.on('message', (data, isBinary) => {
77
+ state.relayFrames.push({ from: 'client', isBinary });
78
+ const host = state.hostData.get(connectionId);
79
+ if (host && host.readyState === WebSocket.OPEN) {
80
+ host.send(data, { binary: isBinary });
81
+ } else {
82
+ const queue = state.buffered.get(connectionId) || [];
83
+ queue.push([data, isBinary]);
84
+ state.buffered.set(connectionId, queue);
85
+ }
86
+ });
87
+ ws.on('close', () => state.clients.delete(connectionId));
88
+ if (state.control && state.control.readyState === WebSocket.OPEN) {
89
+ state.control.send(JSON.stringify({ type: 'connected', connectionId }));
90
+ }
91
+ }
92
+ });
93
+
94
+ return new Promise((resolve) => {
95
+ server.listen(0, '127.0.0.1', () => {
96
+ const port = server.address().port;
97
+ resolve({
98
+ wsUrl: `ws://127.0.0.1:${port}`,
99
+ state,
100
+ stop: () => new Promise((r) => {
101
+ wss.close();
102
+ server.close(() => r());
103
+ }),
104
+ });
105
+ });
106
+ });
107
+ };
108
+
109
+ // A stub loopback origin serving /health.
110
+ const startLoopbackOrigin = () =>
111
+ new Promise((resolve) => {
112
+ const server = http.createServer((req, res) => {
113
+ if (req.url === '/health') {
114
+ res.writeHead(200, { 'content-type': 'application/json' });
115
+ res.end(JSON.stringify({ ok: true, service: 'stub', relayConn: req.headers['x-openchamber-relay-connection'] || null }));
116
+ return;
117
+ }
118
+ res.writeHead(404);
119
+ res.end();
120
+ });
121
+ server.listen(0, '127.0.0.1', () => resolve({ port: server.address().port, stop: () => new Promise((r) => server.close(() => r())) }));
122
+ });
123
+
124
+ // Build the host identity around a fresh keypair (ECDH enc key + ECDSA sign key).
125
+ const buildIdentity = async () => {
126
+ const enc = await generateEcdhKeyPair();
127
+ const encPrivJwk = await globalThis.crypto.subtle.exportKey('jwk', enc.privateKey);
128
+ const { privateKey: signPriv, publicKey: signPub } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
129
+ const signPubJwk = signPub.export({ format: 'jwk' });
130
+ const canonical = JSON.stringify({ crv: signPubJwk.crv, kty: signPubJwk.kty, x: signPubJwk.x, y: signPubJwk.y });
131
+ const serverId = crypto.createHash('sha256').update(canonical).digest('base64url');
132
+ return {
133
+ serverId,
134
+ hostEncPubJwk: await exportPublicKeyJwk(enc.publicKey),
135
+ hostEncPrivateKey: await importEcdhPrivateKey(encPrivJwk),
136
+ signRelayAuth: (role, connectionId) => {
137
+ const ts = Date.now();
138
+ const sig = crypto
139
+ .sign('SHA256', Buffer.from(`${ts}.${serverId}.${role}.${connectionId ?? ''}`), { key: signPriv, dsaEncoding: 'ieee-p1363' })
140
+ .toString('base64url');
141
+ return { ts, sig, pk: Buffer.from(canonical, 'utf8').toString('base64url') };
142
+ },
143
+ };
144
+ };
145
+
146
+ // Scripted client using the JS initiator: connects, handshakes, does a GET.
147
+ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
148
+ const connectionId = 'conn-test-1';
149
+ const url = new URL(`${relayUrl}/`);
150
+ url.searchParams.set('v', String(RELAY_PROTOCOL_VERSION));
151
+ url.searchParams.set('role', 'client');
152
+ url.searchParams.set('serverId', serverId);
153
+ url.searchParams.set('connectionId', connectionId);
154
+ const ws = new WebSocket(url.toString());
155
+
156
+ const hostPub = await globalThis.crypto.subtle.importKey(
157
+ 'jwk',
158
+ { kty: hostEncPubJwk.kty, crv: hostEncPubJwk.crv, x: hostEncPubJwk.x, y: hostEncPubJwk.y, ext: true },
159
+ { name: 'ECDH', namedCurve: 'P-256' },
160
+ true,
161
+ [],
162
+ );
163
+ const ephemeral = await generateEcdhKeyPair();
164
+ const nonce = generateHandshakeNonce();
165
+
166
+ let channel = null;
167
+ const responseChunks = [];
168
+ let responseStatus = null;
169
+ let resolveDone;
170
+ const done = new Promise((resolve) => {
171
+ resolveDone = resolve;
172
+ });
173
+
174
+ ws.on('open', async () => {
175
+ ws.send(JSON.stringify({
176
+ t: 'hello',
177
+ v: RELAY_PROTOCOL_VERSION,
178
+ clientPubJwk: await exportPublicKeyJwk(ephemeral.publicKey),
179
+ nonce: bytesToBase64Url(nonce),
180
+ }));
181
+ });
182
+
183
+ // Serialize message handling: an async ws handler runs per-message tasks
184
+ // concurrently, letting StreamEnd overtake HttpBody and trip the decryptor's
185
+ // strict counter ordering (the production tunnel client chains decrypts).
186
+ let processing = Promise.resolve();
187
+ const handleMessage = async (data, isBinary) => {
188
+ if (!isBinary) {
189
+ const msg = JSON.parse(data.toString('utf8'));
190
+ if (msg.t === 'ready') {
191
+ const keys = await deriveSessionKeys(ephemeral.privateKey, hostPub, nonce);
192
+ channel = {
193
+ encryptor: createFrameEncryptor(keys.clientToHost),
194
+ decryptor: createFrameDecryptor(keys.hostToClient),
195
+ };
196
+ // Send an HTTP GET /health over stream 1.
197
+ const req = encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
198
+ method: 'GET',
199
+ path: '/health',
200
+ query: '',
201
+ headers: { accept: 'application/json' },
202
+ }));
203
+ ws.send(await channel.encryptor.encrypt(req), { binary: true });
204
+ ws.send(await channel.encryptor.encrypt(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0))), { binary: true });
205
+ }
206
+ return;
207
+ }
208
+ if (!channel) return;
209
+ const plaintext = await channel.decryptor.decrypt(new Uint8Array(data));
210
+ const frame = decodeTunnelFrame(plaintext);
211
+ if (frame.frameType === TunnelFrameType.HttpResponse) {
212
+ responseStatus = JSON.parse(new TextDecoder().decode(frame.payload)).status;
213
+ } else if (frame.frameType === TunnelFrameType.HttpBody) {
214
+ responseChunks.push(frame.payload);
215
+ } else if (frame.frameType === TunnelFrameType.StreamEnd) {
216
+ const total = responseChunks.reduce((n, c) => n + c.length, 0);
217
+ const body = new Uint8Array(total);
218
+ let off = 0;
219
+ for (const c of responseChunks) {
220
+ body.set(c, off);
221
+ off += c.length;
222
+ }
223
+ resolveDone({ status: responseStatus, body: JSON.parse(new TextDecoder().decode(body)) });
224
+ ws.close();
225
+ }
226
+ };
227
+ ws.on('message', (data, isBinary) => {
228
+ processing = processing.then(() => handleMessage(data, isBinary));
229
+ });
230
+
231
+ return done;
232
+ };
233
+
234
+ describe('relay host-client integration', () => {
235
+ let relay;
236
+ let origin;
237
+ let host;
238
+
239
+ beforeAll(async () => {
240
+ relay = await startFakeRelay();
241
+ origin = await startLoopbackOrigin();
242
+ });
243
+
244
+ afterAll(async () => {
245
+ host?.stop();
246
+ await relay?.stop();
247
+ await origin?.stop();
248
+ });
249
+
250
+ it('tunnels an HTTP GET /health with only binary frames post-handshake', async () => {
251
+ const identity = await buildIdentity();
252
+ host = startRelayHost({
253
+ relayUrl: `${relay.wsUrl}/`,
254
+ identity,
255
+ getLocalPort: () => origin.port,
256
+ onStatus: () => {},
257
+ logger: { warn: () => {} },
258
+ });
259
+
260
+ // Give the control socket a moment to connect before the client arrives.
261
+ await new Promise((r) => setTimeout(r, 200));
262
+
263
+ const result = await runScriptedClient({
264
+ relayUrl: relay.wsUrl,
265
+ serverId: identity.serverId,
266
+ hostEncPubJwk: identity.hostEncPubJwk,
267
+ });
268
+
269
+ expect(result.status).toBe(200);
270
+ expect(result.body.ok).toBe(true);
271
+ expect(result.body.relayConn).toBe('conn-test-1');
272
+
273
+ // Every forwarded frame after the two plaintext handshake frames (client
274
+ // hello, host ready) must be binary.
275
+ const forwarded = relay.state.relayFrames;
276
+ const plaintextForwarded = forwarded.filter((f) => !f.isBinary);
277
+ expect(plaintextForwarded.length).toBe(2); // hello + ready only
278
+ expect(forwarded.filter((f) => f.isBinary).length).toBeGreaterThan(0);
279
+ });
280
+ });