@openchamber/web 1.14.1 → 1.15.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 (87) 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-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-4FWg9xMC.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DzBg8hrC.js} +123 -119
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.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 +130 -1
  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/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +246 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/network-runtime.js +14 -1
  45. package/server/lib/opencode/network-runtime.test.js +29 -9
  46. package/server/lib/opencode/proxy.js +47 -6
  47. package/server/lib/opencode/settings-helpers.js +3 -0
  48. package/server/lib/opencode/settings-helpers.test.js +11 -0
  49. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  50. package/server/lib/package-manager.js +18 -5
  51. package/server/lib/relay/DOCUMENTATION.md +78 -0
  52. package/server/lib/relay/cross-compat.test.js +135 -0
  53. package/server/lib/relay/e2ee.js +341 -0
  54. package/server/lib/relay/e2ee.test.js +124 -0
  55. package/server/lib/relay/host-client.js +389 -0
  56. package/server/lib/relay/host-client.test.js +280 -0
  57. package/server/lib/relay/identity.js +73 -0
  58. package/server/lib/relay/identity.test.js +78 -0
  59. package/server/lib/relay/service.js +247 -0
  60. package/server/lib/relay/signing-key.js +50 -0
  61. package/server/lib/relay/tunnel-codec.js +373 -0
  62. package/server/lib/relay/tunnel-codec.test.js +58 -0
  63. package/server/lib/relay/tunnel-host.js +462 -0
  64. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  65. package/server/lib/ui-auth/ui-auth.js +10 -0
  66. package/server/opencode-proxy.test.js +38 -0
  67. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  68. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  69. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  70. package/dist/assets/es-bWcuDy_2.js +0 -15
  71. package/dist/assets/fr-DzRs3OzV.js +0 -13
  72. package/dist/assets/index-KnWk9fmM.css +0 -1
  73. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  74. package/dist/assets/ja-BqUX_UD3.js +0 -15
  75. package/dist/assets/ko-BQo10SNx.js +0 -15
  76. package/dist/assets/main-BDoqLlQB.js +0 -236
  77. package/dist/assets/main-DUGyTrDt.js +0 -2
  78. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  79. package/dist/assets/mobile-DnghtOCb.js +0 -2
  80. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  81. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  82. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  83. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  84. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  85. package/dist/assets/uk-C9k8SP8q.js +0 -15
  86. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  87. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
@@ -0,0 +1,124 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+
3
+ import {
4
+ base64UrlToBytes,
5
+ bytesToBase64Url,
6
+ createFrameDecryptor,
7
+ createFrameEncryptor,
8
+ createHostHandshake,
9
+ deriveSessionKeys,
10
+ exportPublicKeyJwk,
11
+ generateEcdhKeyPair,
12
+ generateHandshakeNonce,
13
+ RELAY_PROTOCOL_VERSION,
14
+ } from './e2ee.js';
15
+
16
+ const subtle = globalThis.crypto.subtle;
17
+
18
+ // A minimal client-side initiator so the host handshake can be exercised
19
+ // end-to-end without importing the browser TS modules.
20
+ const createClientHandshake = async (hostEncPubJwk) => {
21
+ const hostPublicKey = await subtle.importKey(
22
+ 'jwk',
23
+ { kty: hostEncPubJwk.kty, crv: hostEncPubJwk.crv, x: hostEncPubJwk.x, y: hostEncPubJwk.y, ext: true },
24
+ { name: 'ECDH', namedCurve: 'P-256' },
25
+ true,
26
+ [],
27
+ );
28
+ const ephemeral = await generateEcdhKeyPair();
29
+ const nonce = generateHandshakeNonce();
30
+ const helloText = JSON.stringify({
31
+ t: 'hello',
32
+ v: RELAY_PROTOCOL_VERSION,
33
+ clientPubJwk: await exportPublicKeyJwk(ephemeral.publicKey),
34
+ nonce: bytesToBase64Url(nonce),
35
+ });
36
+ const deriveChannel = async () => {
37
+ const keys = await deriveSessionKeys(ephemeral.privateKey, hostPublicKey, nonce);
38
+ return {
39
+ encryptor: createFrameEncryptor(keys.clientToHost),
40
+ decryptor: createFrameDecryptor(keys.hostToClient),
41
+ };
42
+ };
43
+ return { helloText, deriveChannel };
44
+ };
45
+
46
+ describe('relay e2ee', () => {
47
+ it('round-trips frames in both directions after handshake', async () => {
48
+ const hostKeys = await generateEcdhKeyPair();
49
+ const hostPubJwk = await exportPublicKeyJwk(hostKeys.publicKey);
50
+ const host = createHostHandshake(hostKeys.privateKey);
51
+ const client = await createClientHandshake(hostPubJwk);
52
+
53
+ const action = await host.handleText(client.helloText);
54
+ expect(action.type).toBe('established');
55
+ const hostChannel = action.channel;
56
+ const clientChannel = await client.deriveChannel();
57
+
58
+ const c2h = new TextEncoder().encode('client-to-host payload');
59
+ const decodedAtHost = await hostChannel.decryptor.decrypt(await clientChannel.encryptor.encrypt(c2h));
60
+ expect(new TextDecoder().decode(decodedAtHost)).toBe('client-to-host payload');
61
+
62
+ const h2c = new TextEncoder().encode('host-to-client payload');
63
+ const decodedAtClient = await clientChannel.decryptor.decrypt(await hostChannel.encryptor.encrypt(h2c));
64
+ expect(new TextDecoder().decode(decodedAtClient)).toBe('host-to-client payload');
65
+ });
66
+
67
+ it('rejects tampered ciphertext', async () => {
68
+ const keyBytes = new Uint8Array(32);
69
+ globalThis.crypto.getRandomValues(keyBytes);
70
+ const key = await subtle.importKey('raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
71
+ const enc = createFrameEncryptor(key);
72
+ const dec = createFrameDecryptor(key);
73
+ const frame = await enc.encrypt(new Uint8Array([1, 2, 3]));
74
+ frame[frame.length - 1] ^= 0xff;
75
+ await expect(dec.decrypt(frame)).rejects.toThrow();
76
+ });
77
+
78
+ it('rejects counter regression / replay', async () => {
79
+ const keyBytes = new Uint8Array(32);
80
+ globalThis.crypto.getRandomValues(keyBytes);
81
+ const key = await subtle.importKey('raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
82
+ const enc = createFrameEncryptor(key);
83
+ const dec = createFrameDecryptor(key);
84
+ const first = await enc.encrypt(new Uint8Array([9]));
85
+ await dec.decrypt(first);
86
+ // Replaying the same frame (counter no longer strictly increasing) fails.
87
+ await expect(dec.decrypt(first)).rejects.toThrow('frame counter regression');
88
+ });
89
+
90
+ it('re-sends ready on identical re-hello and fails on rekey', async () => {
91
+ const hostKeys = await generateEcdhKeyPair();
92
+ const hostPubJwk = await exportPublicKeyJwk(hostKeys.publicKey);
93
+ const host = createHostHandshake(hostKeys.privateKey);
94
+ const client = await createClientHandshake(hostPubJwk);
95
+
96
+ const first = await host.handleText(client.helloText);
97
+ expect(first.type).toBe('established');
98
+
99
+ const repeat = await host.handleText(client.helloText);
100
+ expect(repeat.type).toBe('send-text');
101
+ expect(repeat.text).toBe(first.replyText);
102
+
103
+ const other = await createClientHandshake(hostPubJwk);
104
+ const rekey = await host.handleText(other.helloText);
105
+ expect(rekey.type).toBe('fail');
106
+ expect(rekey.closeCode).toBe(1008);
107
+ });
108
+
109
+ it('fails closed on plaintext after ready', async () => {
110
+ const hostKeys = await generateEcdhKeyPair();
111
+ const hostPubJwk = await exportPublicKeyJwk(hostKeys.publicKey);
112
+ const host = createHostHandshake(hostKeys.privateKey);
113
+ const client = await createClientHandshake(hostPubJwk);
114
+ await host.handleText(client.helloText);
115
+ const action = await host.handleText(JSON.stringify({ hello: 'not a handshake' }));
116
+ expect(action.type).toBe('fail');
117
+ expect(action.closeCode).toBe(1011);
118
+ });
119
+
120
+ it('base64url helpers round-trip', () => {
121
+ const bytes = new Uint8Array([0, 1, 2, 250, 251, 252, 253, 254, 255]);
122
+ expect(Array.from(base64UrlToBytes(bytesToBase64Url(bytes)))).toEqual(Array.from(bytes));
123
+ });
124
+ });
@@ -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
+ };