@johnhenry/wsh 0.36.0 → 0.38.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.
@@ -0,0 +1,49 @@
1
+ /** A WebSocket-like duplex: the `ws` package's, a browser's, or a Worker's. */
2
+ export interface PipeSocket {
3
+ send(data: Uint8Array | ArrayBuffer): void;
4
+ close(code?: number, reason?: string): void;
5
+ readonly readyState: number;
6
+ readonly bufferedAmount?: number;
7
+ pause?(): void;
8
+ resume?(): void;
9
+ on?(event: string, listener: (...args: any[]) => void): unknown;
10
+ addEventListener?(event: string, listener: (ev: any) => void): unknown;
11
+ }
12
+
13
+ export interface PipeRelayOptions {
14
+ /** Halves waiting for a partner, over all ids (default 1024). */
15
+ maxWaiting?: number;
16
+ /** How long a half waits for its partner (default 120000). */
17
+ rendezvousTimeoutMs?: number;
18
+ /** A pipe that carried no byte either way for this long is closed (default 300000). */
19
+ idleTimeoutMs?: number;
20
+ /** A pipe is closed this long after pairing (default 12 hours). */
21
+ maxLifetimeMs?: number;
22
+ /** Total bytes copied per pipe, both directions (default 1 GiB). */
23
+ maxBytes?: number;
24
+ /** Largest single message (default 4 MiB). */
25
+ maxMessageBytes?: number;
26
+ /** What a half may send before its partner arrives (default 64 KiB). */
27
+ earlyBytes?: number;
28
+ /** Outgoing buffer size past which the sender is paused (default 1 MiB). */
29
+ highWaterBytes?: number;
30
+ /** Optional gate before a half may wait or pair; default: anyone holding a well-formed id. */
31
+ authorize?: (who: { id: string; role: 'host' | 'operator'; remote?: object }) => boolean | Promise<boolean>;
32
+ onLog?: (line: string) => void;
33
+ }
34
+
35
+ export interface PipeRelay {
36
+ /** Hand the relay one accepted connection; resolves false when it was refused (and closed). */
37
+ accept(socket: PipeSocket, who: { id: string; role?: 'host' | 'operator'; remote?: object }): Promise<boolean>;
38
+ /** Listen for WebSocket upgrades on `<path>/<id>` (default `/r`); `?role=host` is the host side. Needs the `ws` package. */
39
+ listen(options?: { host?: string; port?: number; path?: string; tls?: object }): Promise<{ port: number; address: string; close(): Promise<void> }>;
40
+ close(): Promise<void>;
41
+ stats(): { waiting: number; pipes: number };
42
+ newRendezvousId(): string;
43
+ }
44
+
45
+ export function createPipeRelay(options?: PipeRelayOptions): PipeRelay;
46
+ /** A fresh 128-bit rendezvous id, base64url. */
47
+ export function newRendezvousId(): string;
48
+ /** The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host. */
49
+ export function pipeUrl(relayUrl: string, id: string, role?: 'host' | 'operator'): string;
@@ -0,0 +1,274 @@
1
+ /**
2
+ * A pipe relay (wsh #118): rendezvous and byte copying, nothing else.
3
+ *
4
+ * Two parties that cannot reach each other directly both dial the relay with the same unguessable rendezvous id --
5
+ * the host (`role: 'host'`) and the operator (`role: 'operator'`) -- and the relay joins them and copies WebSocket
6
+ * messages in both directions. It does not parse wsh: it holds no keys, runs nothing, reads no files, and cannot
7
+ * tell who either party is. The host serves its connection with the ordinary `createWshServer().accept(socket)` (or
8
+ * `createMemoryHost().accept`), so it runs the ordinary handshake and verifies the OPERATOR'S OWN signature; the
9
+ * operator connects with the ordinary `WshClient.connect(pipeUrl(...))` and can pin the host key. Compare relay
10
+ * mode (`createWshServer({ relay })`), where the relay authenticates the operator and tells the peer who it is.
11
+ * What a pipe relay can still do is in the README's Security model: it sees metadata and ciphertext-free traffic
12
+ * volume, can drop or delay bytes, and can offer a host or operator to whoever holds the rendezvous id.
13
+ *
14
+ * THIS MODULE IMPORTS NOTHING STATICALLY, and its only dynamic imports are `ws`, `node:http` and `node:https` (in
15
+ * `listen()`, for embedders that do not already run an HTTP server). test/pipe-relay.test.mjs asserts that the
16
+ * module graph reaches nothing that can execute code or read files. That is the point of shipping it as its own
17
+ * entry point (`@johnhenry/wsh/pipe-relay`) rather than a mode of the server.
18
+ *
19
+ * Bounds (every one has a default; 0 turns a limit off only where noted):
20
+ * maxWaiting halves waiting for a partner, over all ids (default 1024); more are refused
21
+ * rendezvousTimeoutMs how long a half waits for its partner (default 120000)
22
+ * idleTimeoutMs a pipe that carried no byte either way for this long is closed (default 300000; wsh clients ping)
23
+ * maxLifetimeMs a pipe is closed this long after pairing (default 12 h)
24
+ * maxBytes total bytes copied per pipe, both directions (default 1 GiB)
25
+ * maxMessageBytes largest single message (default 4 MiB)
26
+ * earlyBytes what a half may send before its partner arrives (default 64 KiB); more closes it
27
+ * highWaterBytes a socket whose outgoing buffer exceeds this is not fed further until it drains (default 1 MiB)
28
+ *
29
+ * Backpressure: when the receiving socket's `bufferedAmount` passes `highWaterBytes`, the sending socket is
30
+ * `pause()`d (the `ws` package's flow control, which stops reading its TCP socket) and resumed once the buffer is
31
+ * below half of it. A socket that cannot pause (a browser's, say) is closed instead of buffered without bound.
32
+ */
33
+
34
+ const OPEN = 1;
35
+ const ID_RE = /^[A-Za-z0-9_-]{22,128}$/;
36
+ const ROLES = new Set(['host', 'operator']);
37
+ const MIN_ID_LENGTH = 22; // 16 random bytes, base64url
38
+
39
+ /** A fresh rendezvous id: 128 bits from the platform CSPRNG, base64url (22 characters). */
40
+ export function newRendezvousId() {
41
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
42
+ let s = '';
43
+ for (const b of bytes) s += String.fromCharCode(b);
44
+ return btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
45
+ }
46
+
47
+ /**
48
+ * The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host (the operator is the default).
49
+ * @param {string} relayUrl - `ws://` / `wss://` (or `http(s)://`) base of the relay
50
+ * @param {string} id
51
+ * @param {'host' | 'operator'} [role='operator']
52
+ */
53
+ export function pipeUrl(relayUrl, id, role = 'operator') {
54
+ if (!ID_RE.test(id)) throw new TypeError(`pipeUrl: the rendezvous id must be ${MIN_ID_LENGTH}-128 base64url characters (use newRendezvousId())`);
55
+ if (!ROLES.has(role)) throw new TypeError("pipeUrl: role must be 'host' or 'operator'");
56
+ const u = new URL(relayUrl);
57
+ u.pathname = `${u.pathname.replace(/\/+$/, '')}/r/${id}`;
58
+ u.search = role === 'host' ? '?role=host' : '';
59
+ return u.toString();
60
+ }
61
+
62
+ const sane = (code) => (Number.isInteger(code) && code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000);
63
+
64
+ /** Adapt a `ws`-style (`on`) or browser-style (`addEventListener`) socket to message/close callbacks. */
65
+ function listenOn(socket, onMessage, onClose) {
66
+ if (typeof socket.addEventListener === 'function') {
67
+ socket.addEventListener('message', (ev) => onMessage(ev?.data));
68
+ socket.addEventListener('close', (ev) => onClose(ev?.code));
69
+ socket.addEventListener('error', () => {});
70
+ } else if (typeof socket.on === 'function') {
71
+ socket.on('message', (data, isBinary) => onMessage(data, isBinary));
72
+ socket.on('close', (code) => onClose(code));
73
+ socket.on('error', () => {});
74
+ } else {
75
+ throw new TypeError('createPipeRelay: socket must support on() or addEventListener()');
76
+ }
77
+ }
78
+
79
+ const sizeOf = (data) => (typeof data === 'string' ? -1
80
+ : Array.isArray(data) ? data.reduce((n, d) => n + d.byteLength, 0)
81
+ : data?.byteLength ?? data?.size ?? -1);
82
+
83
+ /**
84
+ * @param {object} [options]
85
+ * @param {number} [options.maxWaiting=1024]
86
+ * @param {number} [options.rendezvousTimeoutMs=120000]
87
+ * @param {number} [options.idleTimeoutMs=300000]
88
+ * @param {number} [options.maxLifetimeMs=43200000]
89
+ * @param {number} [options.maxBytes=1073741824]
90
+ * @param {number} [options.maxMessageBytes=4194304]
91
+ * @param {number} [options.earlyBytes=65536]
92
+ * @param {number} [options.highWaterBytes=1048576]
93
+ * @param {(who: { id: string, role: 'host' | 'operator', remote?: object }) => boolean | Promise<boolean>} [options.authorize]
94
+ * Optional gate, called before a half may wait or pair (rate limiting, an allow-list of ids you minted). Default:
95
+ * anyone holding a well-formed id; the id is the capability.
96
+ * @param {(line: string) => void} [options.onLog]
97
+ */
98
+ export function createPipeRelay({
99
+ maxWaiting = 1024, rendezvousTimeoutMs = 120_000, idleTimeoutMs = 300_000, maxLifetimeMs = 12 * 3600_000,
100
+ maxBytes = 1024 ** 3, maxMessageBytes = 4 * 1024 * 1024, earlyBytes = 64 * 1024, highWaterBytes = 1024 * 1024,
101
+ authorize, onLog = () => {},
102
+ } = {}) {
103
+ for (const [name, v] of Object.entries({ maxWaiting, rendezvousTimeoutMs, idleTimeoutMs, maxLifetimeMs, maxBytes, maxMessageBytes, earlyBytes, highWaterBytes })) {
104
+ if (!Number.isFinite(v) || v < 1) throw new TypeError(`createPipeRelay: ${name} must be a positive number`);
105
+ }
106
+ if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('createPipeRelay: authorize must be a function');
107
+
108
+ /** id -> the one half waiting for its partner. */
109
+ const waiting = new Map();
110
+ /** Live pipes. */
111
+ const pipes = new Set();
112
+ let closed = false;
113
+ let server = null;
114
+
115
+ const closeSocket = (socket, code = 1000, reason = '') => { try { socket.close(code, reason); } catch { /* gone */ } };
116
+
117
+ function wait(half) {
118
+ half.timer = setTimeout(() => { waiting.delete(half.id); closeSocket(half.socket, 1000, 'no partner arrived'); onLog(`pipe ${half.id.slice(0, 6)}: ${half.role} waited too long`); }, rendezvousTimeoutMs);
119
+ half.timer.unref?.();
120
+ waiting.set(half.id, half);
121
+ }
122
+
123
+ function pair(first, second) {
124
+ clearTimeout(first.timer);
125
+ waiting.delete(first.id);
126
+ const pipe = { halves: [first, second], bytes: 0, last: Date.now(), timers: [], done: false };
127
+ pipes.add(pipe);
128
+ const end = (code, reason, from) => {
129
+ if (pipe.done) return;
130
+ pipe.done = true;
131
+ pipes.delete(pipe);
132
+ for (const t of pipe.timers) { clearInterval(t); clearTimeout(t); }
133
+ for (const h of pipe.halves) { h.resume?.(); if (h !== from) closeSocket(h.socket, sane(code), reason); }
134
+ onLog(`pipe ${first.id.slice(0, 6)} closed (${reason || code}) after ${pipe.bytes} bytes`);
135
+ };
136
+ pipe.end = end;
137
+ const life = setTimeout(() => end(1000, 'maximum lifetime reached'), maxLifetimeMs);
138
+ const idle = setInterval(() => { if (Date.now() - pipe.last > idleTimeoutMs) end(1000, 'idle'); }, Math.max(1000, Math.min(idleTimeoutMs / 4, 30_000)));
139
+ for (const t of [life, idle]) t.unref?.();
140
+ pipe.timers.push(life, idle);
141
+
142
+ const [a, b] = pipe.halves;
143
+ for (const [from, to] of [[a, b], [b, a]]) {
144
+ from.forward = (data, isBinary) => {
145
+ if (pipe.done) return;
146
+ const n = sizeOf(data);
147
+ if (n < 0 || isBinary === false) return end(1003, 'binary messages only', null);
148
+ if (n > maxMessageBytes) return end(1009, 'message too large', null);
149
+ pipe.bytes += n;
150
+ pipe.last = Date.now();
151
+ if (pipe.bytes > maxBytes) return end(1008, 'byte limit reached', null);
152
+ if (to.socket.readyState !== OPEN) return;
153
+ try { to.socket.send(data); } catch { return end(1011, 'send failed', null); }
154
+ if ((to.socket.bufferedAmount ?? 0) > highWaterBytes) throttle(from, to, pipe);
155
+ };
156
+ // Whatever it said before its partner arrived.
157
+ for (const m of from.early.splice(0)) from.forward(m.data, m.isBinary);
158
+ }
159
+ }
160
+
161
+ function throttle(from, to, pipe) {
162
+ if (from.paused) return;
163
+ if (typeof from.socket.pause !== 'function' || typeof from.socket.resume !== 'function') return pipe.end(1013, 'receiver too slow', null);
164
+ from.paused = true;
165
+ from.socket.pause();
166
+ from.resume = () => { if (from.paused) { from.paused = false; try { from.socket.resume(); } catch { /* gone */ } } };
167
+ const poll = setInterval(() => {
168
+ if (pipe.done) return clearInterval(poll);
169
+ if ((to.socket.bufferedAmount ?? 0) < highWaterBytes / 2) { clearInterval(poll); from.resume(); }
170
+ }, 10);
171
+ poll.unref?.();
172
+ pipe.timers.push(poll);
173
+ }
174
+
175
+ /**
176
+ * Hand the relay one accepted connection.
177
+ * @param {object} socket - a WebSocket-like duplex (`send`, `close`, `readyState`, `on` or `addEventListener`)
178
+ * @param {{ id: string, role?: 'host' | 'operator', remote?: object }} who
179
+ * @returns {Promise<boolean>} whether the connection is now waiting or paired (false: it was refused and closed)
180
+ */
181
+ async function accept(socket, { id, role = 'operator', remote } = {}) {
182
+ if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') throw new TypeError('createPipeRelay.accept: socket must be a WebSocket-like duplex');
183
+ const refuse = (code, reason) => { closeSocket(socket, code, reason); return false; };
184
+ if (closed) return refuse(1001, 'relay is shutting down');
185
+ if (typeof id !== 'string' || !ID_RE.test(id)) return refuse(1008, 'bad rendezvous id');
186
+ if (!ROLES.has(role)) return refuse(1008, 'bad role');
187
+
188
+ // Listeners first, so nothing the peer says while we decide is lost; it is held (bounded) until it can be passed on.
189
+ const half = { id, role, socket, early: [], earlyBytes: 0, timer: null, forward: null, paused: false, resume: null };
190
+ let pipeRef = null;
191
+ listenOn(socket, (data, isBinary) => {
192
+ if (half.forward) return half.forward(data, isBinary);
193
+ const n = sizeOf(data);
194
+ half.earlyBytes += Math.max(n, 0);
195
+ if (n < 0 || isBinary === false || half.earlyBytes > earlyBytes) {
196
+ waiting.get(id) === half && (clearTimeout(half.timer), waiting.delete(id));
197
+ return closeSocket(socket, n < 0 || isBinary === false ? 1003 : 1009, 'too much before the partner arrived');
198
+ }
199
+ half.early.push({ data, isBinary });
200
+ }, (code) => {
201
+ if (waiting.get(id) === half) { clearTimeout(half.timer); waiting.delete(id); }
202
+ for (const p of pipes) if (p.halves.includes(half)) { pipeRef = p; break; }
203
+ pipeRef?.end(code, 'peer closed', half);
204
+ });
205
+
206
+ if (authorize) {
207
+ let ok = false;
208
+ try { ok = (await authorize({ id, role, remote })) === true; } catch (e) { onLog(`authorize threw: ${e.message}`); }
209
+ if (!ok) return refuse(1008, 'not permitted');
210
+ if (closed || socket.readyState !== OPEN) return false;
211
+ }
212
+
213
+ const other = waiting.get(id);
214
+ if (!other) {
215
+ if (waiting.size >= maxWaiting) return refuse(1013, 'too many waiting connections');
216
+ wait(half);
217
+ return true;
218
+ }
219
+ if (other.role === role) return refuse(1008, 'rendezvous id in use');
220
+ pair(other, half);
221
+ onLog(`pipe ${id.slice(0, 6)}: paired`);
222
+ return true;
223
+ }
224
+
225
+ /**
226
+ * Listen for WebSocket upgrades on `<path>/<id>` (default path `/r`), `?role=host` for the host side.
227
+ * Convenience for embedders without an HTTP server; needs the `ws` package. `tls` is the options of `https.createServer`.
228
+ * @returns {Promise<{ port: number, address: string, close(): Promise<void> }>}
229
+ */
230
+ async function listen({ host = '127.0.0.1', port = 0, path = '/r', tls } = {}) {
231
+ if (server) throw new Error('createPipeRelay: already listening');
232
+ const { WebSocketServer } = await import('ws');
233
+ const http = tls ? await import('node:https') : await import('node:http');
234
+ const wss = new WebSocketServer({ noServer: true, maxPayload: maxMessageBytes });
235
+ const srv = tls ? http.createServer(tls) : http.createServer();
236
+ srv.on('request', (_req, res) => { res.statusCode = 426; res.end('WebSocket only'); });
237
+ srv.on('upgrade', (req, sock, head) => {
238
+ let url;
239
+ try { url = new URL(req.url, 'http://x'); } catch { sock.destroy(); return; }
240
+ const m = url.pathname.startsWith(`${path}/`) ? url.pathname.slice(path.length + 1) : null;
241
+ const role = url.searchParams.get('role') ?? 'operator';
242
+ if (!m || !ID_RE.test(m) || !ROLES.has(role)) { sock.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); sock.destroy(); return; }
243
+ wss.handleUpgrade(req, sock, head, (ws) => { accept(ws, { id: m, role, remote: { address: req.socket.remoteAddress, headers: req.headers } }).catch(() => closeSocket(ws, 1011, 'error')); });
244
+ });
245
+ await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(port, host, () => { srv.off('error', reject); resolve(); }); });
246
+ server = { srv, wss };
247
+ const addr = srv.address();
248
+ return {
249
+ port: addr.port, address: addr.address,
250
+ close: () => close(),
251
+ };
252
+ }
253
+
254
+ async function close() {
255
+ closed = true;
256
+ for (const h of waiting.values()) { clearTimeout(h.timer); closeSocket(h.socket, 1001, 'relay is shutting down'); }
257
+ waiting.clear();
258
+ for (const p of [...pipes]) p.end(1001, 'relay is shutting down', null);
259
+ if (server) {
260
+ const { srv, wss } = server;
261
+ server = null;
262
+ for (const c of wss.clients) c.terminate();
263
+ await new Promise((r) => wss.close(r));
264
+ await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); });
265
+ }
266
+ }
267
+
268
+ return {
269
+ accept, listen, close,
270
+ /** `{ waiting, pipes }` right now. */
271
+ stats: () => ({ waiting: waiting.size, pipes: pipes.size }),
272
+ newRendezvousId,
273
+ };
274
+ }
@@ -1,4 +1,4 @@
1
- import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost } from './server/index.js';
1
+ import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost, WshClientEnv } from './server/index.js';
2
2
  import type { WshFileBackend } from './host.js';
3
3
 
4
4
  export type { WshReverseHost } from './server/index.js';
@@ -9,7 +9,7 @@ export type { WshReverseHost } from './server/index.js';
9
9
  */
10
10
  export interface WshBrowserReverseHostOptions extends Omit<WshReverseHostOptions, 'exec' | 'fs' | 'pty' | 'mcp'> {
11
11
  /** `run(command, io)` or `{ run }`: there is no shell in a browser to run `true` with. */
12
- exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
12
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
13
13
  /** `node-pty`-shaped `{ spawn }`, injected. Input arrives at `write` as a `Uint8Array`. */
14
14
  pty?: WshServerPtyOptions;
15
15
  /** An object of file operations, not a root path. */
@@ -16,9 +16,11 @@
16
16
 
17
17
  import { WshClient } from './client.mjs';
18
18
  import { exportPublicKeyRaw, fingerprint } from './auth.mjs';
19
- import { reverseAccept, reverseReject } from './messages.gen.mjs';
19
+ import { MSG, reverseAccept, reverseReject, reverseChallenge } from './messages.gen.mjs';
20
20
  import { MULTI_OPERATOR_FEATURE } from './server/relay.mjs';
21
- import { E2E_SIGN_FEATURE } from './e2e-exchange.mjs';
21
+ import { E2E_SIGN_FEATURE, E2EResponder } from './e2e-exchange.mjs';
22
+ import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyOperatorProof } from './operator-proof.mjs';
23
+ import { SealedBridge } from './bridge-seal.mjs';
22
24
  import { resolveBackends } from './host-backends.mjs';
23
25
  import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
24
26
 
@@ -30,7 +32,7 @@ const BACKOFF_MAX_MS = 30_000;
30
32
  * @param {string} options.url - The relay (`ws://` or `wss://`).
31
33
  * @param {string} options.username
32
34
  * @param {CryptoKeyPair} options.keyPair - This host's identity; its fingerprint is what operators connect to.
33
- * @param {(operator: { fingerprint: string, username: string }) => boolean | Promise<boolean>} [options.accept]
35
+ * @param {(operator: { fingerprint: string, username: string, proven?: boolean, publicKey?: Uint8Array }) => boolean | Promise<boolean>} [options.accept]
34
36
  * Who may be bridged to this host. Default: nobody.
35
37
  * @param {true | object | Function} [options.exec]
36
38
  * @param {object} [options.pty]
@@ -55,6 +57,16 @@ const BACKOFF_MAX_MS = 30_000;
55
57
  * @param {boolean} [options.reportFeatures=true] - State this host's features in `ReverseAccept.features`, so the operator's
56
58
  * feature gates follow this host rather than the relay. Turn off only for a relay (a Rust `wsh-server` older than the field)
57
59
  * that rejects a `ReverseAccept` carrying it.
60
+ * @param {boolean} [options.requireOperatorProof=false] - wsh #117. Do not take the operator's identity from the relay.
61
+ * When the relay carries `operator-proof` (its ServerHello says so) and the operator can answer, this host sends it a
62
+ * signed challenge and verifies the operator's signature over this host's fingerprint, a nonce it chose and the
63
+ * bridge's session BEFORE `accept` runs; `accept` then receives `{ fingerprint, username, proven: true, publicKey }`
64
+ * taken from the proof, not from the relay (a relay that rewrote `from_fingerprint` is refused). This option makes
65
+ * that mandatory: an operator that does not prove itself is refused, and the bridge is SEALED -- this host acts only on
66
+ * messages the operator sealed under a key exchange both sides signed, because a relay can stamp any identity on a
67
+ * plain message (it could inject an `Open`). Needs `e2e` (on by default) and `reportFeatures`. Without this option the
68
+ * proof is requested when it can be and reported as `proven`, and the bridge is sealed only if the operator asks.
69
+ * @param {number} [options.proofTimeoutMs=5000] - How long an operator has to answer the challenge.
58
70
  * @param {(line: string) => void} [options.onLog]
59
71
  */
60
72
  export function createReverseHost(options = {}) {
@@ -68,8 +80,12 @@ export function createReverseHost(options = {}) {
68
80
  * @param {ReturnType<typeof resolveBackends>} backends
69
81
  */
70
82
  export function createReverseHostWith({
71
- url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {}, onLog = () => {},
83
+ url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
84
+ requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
72
85
  } = {}, backends) {
86
+ if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
87
+ if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
88
+ if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
73
89
  if (!url) throw new TypeError('createReverseHost: url is required');
74
90
  if (!username) throw new TypeError('createReverseHost: username is required');
75
91
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -108,6 +124,7 @@ export function createReverseHostWith({
108
124
  /** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
109
125
  let endAllBridges = () => {};
110
126
  let myFingerprint = null;
127
+ let myPublicKeyRaw = null;
111
128
  let closed = false;
112
129
  let timer = null;
113
130
  let backoff = BACKOFF_START_MS;
@@ -121,6 +138,8 @@ export function createReverseHostWith({
121
138
  const operatorLimit = () => (manyOperators() ? maxOperators : 1);
122
139
  /** Operators whose `accept` is still running: they count towards the cap. */
123
140
  const reserved = new Set();
141
+ /** challenge nonce (hex) -> resolves with the operator's ReverseProof (or null on timeout) */
142
+ const proofWaiters = new Map();
124
143
  operatorsNow = bridges;
125
144
 
126
145
  const endBridge = (fp) => {
@@ -149,25 +168,116 @@ export function createReverseHostWith({
149
168
  reserved.add(from);
150
169
  let ok = false;
151
170
  try {
152
- try { ok = (await accept?.({ fingerprint: from, username: String(req.username ?? '') })) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
171
+ // Who is this operator? The relay says (`from`); with proof the operator says so itself (#117).
172
+ const canProve = c.hasFeature(OPERATOR_PROOF_FEATURE) && Array.isArray(req.features) && req.features.includes(OPERATOR_PROOF_FEATURE);
173
+ if (requireOperatorProof && !canProve) { await refuse('operator proof required'); return; }
174
+ let proven = null;
175
+ let challenge = null;
176
+ if (canProve) {
177
+ const outcome = await challengeOperator(c, from);
178
+ if (outcome.error) { await refuse(outcome.error); return; }
179
+ ({ proven, challenge } = outcome);
180
+ // The relay's claim and the operator's own must agree: a relay that rewrote from_fingerprint is caught here.
181
+ if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted'); return; }
182
+ if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted'); return; }
183
+ }
184
+ const who = { fingerprint: from, username: String(req.username ?? ''), proven: !!proven, ...(proven ? { publicKey: proven.publicKey } : {}) };
185
+ try { ok = (await accept?.(who)) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
153
186
  if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
154
187
  c.trustRelayPeer(from);
155
- const bridge = factory({
156
- // With several operators every message names its recipient; with one the relay knows.
157
- sendMessage: (m) => c.sendRelayControl(m, manyOperators() ? { to: from } : undefined),
158
- authenticated: { username: String(req.username ?? 'operator'), fingerprint: from },
159
- dataStreams: false,
160
- e2e: e2eFor(c),
161
- });
188
+ const bridge = makeBridge(c, from, String(req.username ?? 'operator'), proven, challenge);
162
189
  bridges.set(from, bridge);
163
- onLog(`[reverse] bridged to ${from.slice(0, 12)}`);
190
+ onLog(`[reverse] bridged to ${from.slice(0, 12)}${proven ? ' (operator proven)' : ''}${requireOperatorProof ? ', sealed' : ''}`);
164
191
  await answer(reverseAccept({
165
192
  targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
166
193
  supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
167
- features: reportFeatures ? bridgeFeatures(c, e2eFor(c), manyOperators()) : undefined,
194
+ features: reportFeatures ? [...bridgeFeatures(c, e2eFor(c), manyOperators()), ...(proven && e2e !== false ? [E2E_SEALED_FEATURE] : [])] : undefined,
168
195
  }));
169
196
  } finally { reserved.delete(from); }
170
197
  };
198
+
199
+ /** Send a signed challenge, wait for the operator's proof and verify it. @returns {Promise<{ error?: string, proven?: object, challenge?: object }>} */
200
+ async function challengeOperator(conn, from) {
201
+ const issued = await createReverseChallenge({ keyPair }, from);
202
+ const key = Array.from(issued.nonce, (b) => b.toString(16).padStart(2, '0')).join('');
203
+ const proofMsg = new Promise((resolve) => { proofWaiters.set(key, resolve); });
204
+ const timer = setTimeout(() => { proofWaiters.get(key)?.(null); }, proofTimeoutMs);
205
+ timer.unref?.();
206
+ try {
207
+ await conn.sendRelayControl(reverseChallenge({ targetFingerprint: from, ...issued.fields }));
208
+ const msg = await proofMsg;
209
+ if (!msg) return { error: 'operator did not answer the challenge' };
210
+ const proven = await verifyOperatorProof(msg, issued);
211
+ if (!proven) return { error: 'operator proof does not verify' };
212
+ return { proven, challenge: issued };
213
+ } catch (e) {
214
+ onLog(`[reverse] challenge failed: ${e.message}`);
215
+ return { error: 'operator proof failed' };
216
+ } finally { clearTimeout(timer); proofWaiters.delete(key); }
217
+ }
218
+ c.onReverseProof = (m) => {
219
+ if (!(m.nonce instanceof Uint8Array)) return;
220
+ const key = Array.from(m.nonce, (b) => b.toString(16).padStart(2, '0')).join('');
221
+ proofWaiters.get(key)?.(m);
222
+ };
223
+
224
+ /**
225
+ * The connection for one bridged operator. A proven operator may seal the bridge (a signed `KeyExchange` for the
226
+ * challenge's session id); with `requireOperatorProof` it must, and until it has the host hears nothing else.
227
+ */
228
+ function makeBridge(conn, from, operatorName, proven, challenge) {
229
+ const to = () => (manyOperators() ? { to: from } : undefined);
230
+ let sealed = null;
231
+ const mustSeal = requireOperatorProof;
232
+ const base = factory({
233
+ // With several operators every message names its recipient; with one the relay knows.
234
+ sendMessage: async (m) => {
235
+ if (sealed) return conn.sendRelayControl(await sealed.seal(m), to());
236
+ if (mustSeal) return undefined; // nothing may leave a bridge that is not sealed yet
237
+ return conn.sendRelayControl(m, to());
238
+ },
239
+ authenticated: { username: operatorName, fingerprint: from },
240
+ dataStreams: false,
241
+ e2e: e2eFor(conn),
242
+ });
243
+ if (!proven || e2e === false) return base;
244
+
245
+ const responder = new E2EResponder({
246
+ signKey: keyPair.privateKey, hybrid: e2e.hybrid !== false, identity: myPublicKeyRaw,
247
+ initiator: { publicKey: proven.publicKey, require: true },
248
+ });
249
+ let chain = Promise.resolve();
250
+ let giveUp = null;
251
+ const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); endBridge(from); };
252
+ if (mustSeal) {
253
+ giveUp = setTimeout(() => { if (!sealed) fail('no key exchange in time'); }, proofTimeoutMs * 2);
254
+ giveUp.unref?.();
255
+ }
256
+ return {
257
+ receiveMessage(msg) {
258
+ if (sealed) {
259
+ if (!sealed.isFrame(msg)) { onLog('[reverse] dropped a plaintext message on a sealed bridge'); return; }
260
+ chain = chain.then(async () => base.receiveMessage(await sealed.open(msg))).catch((e) => onLog(`[reverse] dropped a sealed frame: ${e.message}`));
261
+ return;
262
+ }
263
+ if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === challenge.sessionId) {
264
+ chain = chain.then(async () => {
265
+ const result = await responder.respond(msg, (reply) => conn.sendRelayControl(reply, to()));
266
+ if (result.key) {
267
+ sealed = new SealedBridge({ key: result.key, sessionId: challenge.sessionId, role: 'responder' });
268
+ clearTimeout(giveUp);
269
+ onLog(`[reverse] bridge to ${from.slice(0, 12)} sealed${result.hybrid ? ' (hybrid)' : ''}`);
270
+ }
271
+ }).catch((e) => fail(e.message));
272
+ return;
273
+ }
274
+ if (mustSeal) { onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`); return; }
275
+ base.receiveMessage(msg);
276
+ },
277
+ bindStream: (s) => base.bindStream?.(s),
278
+ close() { clearTimeout(giveUp); responder.close(); base.close(); },
279
+ };
280
+ }
171
281
  c.onClose = () => {
172
282
  endAll();
173
283
  if (operatorsNow === bridges) operatorsNow = new Map();
@@ -205,7 +315,8 @@ export function createReverseHostWith({
205
315
  async start() {
206
316
  if (client) throw new Error('createReverseHost: already started');
207
317
  closed = false;
208
- myFingerprint = await fingerprint(await exportPublicKeyRaw(keyPair.publicKey));
318
+ myPublicKeyRaw = await exportPublicKeyRaw(keyPair.publicKey);
319
+ myFingerprint = await fingerprint(myPublicKeyRaw);
209
320
  await dial();
210
321
  return { fingerprint: myFingerprint };
211
322
  },