@openchamber/web 1.14.0 → 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.
- package/bin/cli.test.js +8 -0
- package/bin/lib/DOCUMENTATION.md +3 -0
- package/bin/lib/cli-args.js +10 -0
- package/bin/lib/commands-connect-url.js +169 -22
- package/dist/assets/{DiagramView-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
- package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
- package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
- package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
- package/dist/assets/{TerminalView-DF7-jlam.js → TerminalView-D_9BAjtv.js} +3 -3
- package/dist/assets/es-cjUissX4.js +15 -0
- package/dist/assets/fr-DqbXnTdK.js +13 -0
- package/dist/assets/index-Dg0nmvQU.css +1 -0
- package/dist/assets/index-ltrmNGAf.js +2 -0
- package/dist/assets/ja-Cetyq6Eg.js +15 -0
- package/dist/assets/ko-DtunWisP.js +15 -0
- package/dist/assets/main-BC0m8s1v.js +236 -0
- package/dist/assets/main-DzNa8r0N.js +2 -0
- package/dist/assets/miniChat-BRYDE-Se.js +2 -0
- package/dist/assets/mobile-C3QJVA97.js +2 -0
- package/dist/assets/pl-DctGLgve.js +15 -0
- package/dist/assets/pt-BR-CXPhf78S.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
- package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
- package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
- package/dist/assets/uk-Bdrc-kqF.js +15 -0
- package/dist/assets/{useAppFontEffects-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
- package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
- package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
- package/dist/assets/zh-TW-CoqiQING.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +157 -6
- package/server/lib/client-auth/pairing.js +308 -0
- package/server/lib/client-auth/pairing.test.js +142 -0
- package/server/lib/client-auth/remote-clients.js +65 -3
- package/server/lib/notifications/apns-runtime.js +9 -16
- package/server/lib/opencode/bootstrap-runtime.js +10 -0
- package/server/lib/opencode/core-routes.js +247 -6
- package/server/lib/opencode/core-routes.test.js +248 -9
- package/server/lib/opencode/feature-routes-runtime.js +10 -0
- package/server/lib/opencode/models-metadata.js +61 -0
- package/server/lib/opencode/network-runtime.js +14 -1
- package/server/lib/opencode/network-runtime.test.js +29 -9
- package/server/lib/opencode/openchamber-routes.js +7 -40
- package/server/lib/opencode/proxy.js +47 -6
- package/server/lib/opencode/settings-helpers.js +16 -0
- package/server/lib/opencode/settings-helpers.test.js +11 -0
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/package-manager.js +18 -5
- package/server/lib/relay/DOCUMENTATION.md +78 -0
- package/server/lib/relay/cross-compat.test.js +135 -0
- package/server/lib/relay/e2ee.js +341 -0
- package/server/lib/relay/e2ee.test.js +124 -0
- package/server/lib/relay/host-client.js +389 -0
- package/server/lib/relay/host-client.test.js +280 -0
- package/server/lib/relay/identity.js +73 -0
- package/server/lib/relay/identity.test.js +78 -0
- package/server/lib/relay/service.js +247 -0
- package/server/lib/relay/signing-key.js +50 -0
- package/server/lib/relay/tunnel-codec.js +373 -0
- package/server/lib/relay/tunnel-codec.test.js +58 -0
- package/server/lib/relay/tunnel-host.js +462 -0
- package/server/lib/session-assist/DOCUMENTATION.md +66 -0
- package/server/lib/session-assist/runtime.js +394 -0
- package/server/lib/small-model/DOCUMENTATION.md +78 -0
- package/server/lib/small-model/call.js +380 -0
- package/server/lib/small-model/catalog.js +13 -0
- package/server/lib/small-model/index.js +167 -0
- package/server/lib/small-model/resolve.js +131 -0
- package/server/lib/small-model/resolve.test.js +197 -0
- package/server/lib/small-model/routes.js +44 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
- package/server/lib/ui-auth/ui-auth.js +10 -0
- package/server/opencode-proxy.test.js +38 -0
- package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
- package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
- package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
- package/dist/assets/es-DQIFCjC2.js +0 -15
- package/dist/assets/fr-CJRav0LS.js +0 -13
- package/dist/assets/index-5eUDDB6w.js +0 -2
- package/dist/assets/index-CgpE7F8T.css +0 -1
- package/dist/assets/ja-CjAaqvHO.js +0 -15
- package/dist/assets/ko-BEbFxvrd.js +0 -15
- package/dist/assets/main-C2put7uQ.js +0 -2
- package/dist/assets/main-DuQEoz31.js +0 -214
- package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
- package/dist/assets/mobile-X0421aWz.js +0 -2
- package/dist/assets/pl-D4kzai5T.js +0 -15
- package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
- package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
- package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
- package/dist/assets/uk-DW_dTfoO.js +0 -15
- package/dist/assets/zh-CN-r2_euV7U.js +0 -15
- package/dist/assets/zh-TW-BdPx3NWh.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
|
+
});
|