@johnhenry/wsh 0.45.0 → 0.46.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,381 @@
1
+ /**
2
+ * `@johnhenry/wsh/page` -- a web page (or any window-shaped realm) as a wsh host behind a pipe relay it chose (#190).
3
+ *
4
+ * ```js
5
+ * import { captureWebMcp, createPageHost } from '@johnhenry/wsh/page';
6
+ * captureWebMcp(window); // first, before the application registers its tools
7
+ * // ... the application calls document.modelContext.registerTool({ name, description, inputSchema, execute }) ...
8
+ * const host = await createPageHost({
9
+ * window, // the only realm this touches; passing it exposes nothing by itself
10
+ * relay: 'wss://relay.example/pipe', // a page cannot listen: it dials a relay, and prints host.operatorUrl for the operator
11
+ * name: 'shop-tab',
12
+ * authorizedKeys: [operatorPublicKeyLine], // required: key login only, no password, no anonymous mode
13
+ * mcp: { allow: ['search_products', 'add_to_cart'], approve: 'consequential' },
14
+ * });
15
+ * ```
16
+ *
17
+ * What a remote session can do is exactly: open the `mcp` rpc channel and list and call the tools named in `mcp.allow` (narrowed
18
+ * further by the key's `capabilities="mcp:TOOL"`), and, if `expose` is written, open the `wsh-objects` channel and read, call and set the
19
+ * paths its allow-lists name on the roots it names (`rpc:wsh-objects` is the capability for that channel). Nothing is exposed by default,
20
+ * and passing `window` is not exposing it. There is no exec, no file access, no gateway. The session must be SEALED (the pipe
21
+ * relay then sees ciphertext only), a visible indicator with a Stop control is in the page while anyone is connected, and a
22
+ * consequential tool waits for the person at the page to allow it. What this cannot make safe is in the README's Security model.
23
+ *
24
+ * Browser-safe, and it reads nothing but the `window` it is given: no `globalThis`, no `document`, no `navigator`
25
+ * (`test/page-host.test.mjs` greps this file for them).
26
+ */
27
+
28
+ import { createMemoryHost } from './memory-host.mjs';
29
+ import { resolveHostKey } from './host-backends.mjs';
30
+ import { generateKeyPair } from './auth.mjs';
31
+ import { pipeUrl } from './pipe-relay.mjs';
32
+ import { webmcpTools, captureWebMcp, createDomPrompt, timersOf, WEBMCP_DEFAULT_LIMITS } from './webmcp.mjs';
33
+ import { exposeObjects } from './objects.mjs';
34
+ import { OBJECTS_PROTOCOL } from './objects-core.mjs';
35
+
36
+ export { webmcpTools, captureWebMcp, createDomPrompt, WEBMCP_DEFAULT_LIMITS, exposeObjects };
37
+
38
+ const RECONNECT_START_MS = 1000;
39
+ const RECONNECT_MAX_MS = 30_000;
40
+ const WATCH_MS = 1000;
41
+
42
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
43
+
44
+ const BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
45
+ /** A rendezvous id as the pipe relay wants it (16 random bytes, base64url: 22 characters), from the window's own CSPRNG rather than a global. */
46
+ function randomRendezvousId(cryptoImpl) {
47
+ if (typeof cryptoImpl?.getRandomValues !== 'function') throw new TypeError('createPageHost: this window has no crypto.getRandomValues for a rendezvous id: give relay: { url, id }');
48
+ let out = '';
49
+ let acc = 0;
50
+ let bits = 0;
51
+ for (const b of cryptoImpl.getRandomValues(new Uint8Array(16))) {
52
+ acc = (acc << 8) | b; bits += 8;
53
+ while (bits >= 6) { bits -= 6; out += BASE64URL[(acc >> bits) & 63]; }
54
+ }
55
+ if (bits > 0) out += BASE64URL[(acc << (6 - bits)) & 63];
56
+ return out;
57
+ }
58
+
59
+ function readOrigin(window) {
60
+ try { const o = window.location?.origin; return typeof o === 'string' ? o : null; } catch { return null; }
61
+ }
62
+
63
+ /**
64
+ * `expose: { window: { mode: 'values', allow: { get: ['document.title'], call: ['app.**'] } } }` as the roots, allow-lists (qualified with the root's
65
+ * name: the paths in `expose` are relative to their root) and the rest `exposeObjects` takes. A root named `window` is the window that was passed;
66
+ * any other root names its object. Nothing else is reachable.
67
+ */
68
+ function exposedRoots(window, expose) {
69
+ const names = Object.keys(expose);
70
+ if (names.length === 0) throw new TypeError('createPageHost: expose names no root');
71
+ const roots = {};
72
+ const allow = { get: [], call: [], set: [] };
73
+ const authorizers = new Map();
74
+ let limits;
75
+ for (const name of names) {
76
+ const cfg = expose[name];
77
+ if (!isObj(cfg)) throw new TypeError(`createPageHost: expose.${name} must be { mode, allow }`);
78
+ if (cfg.mode === 'handles') throw new TypeError("createPageHost: expose mode 'handles' is not built: only 'values' exists (handles, events and callbacks are a later step of #190)");
79
+ if (cfg.mode !== undefined && cfg.mode !== 'values') throw new TypeError("createPageHost: expose mode must be 'values'");
80
+ if (typeof cfg.allow === 'string') throw new TypeError('createPageHost: expose allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
81
+ const object = cfg.object ?? (name === 'window' ? window : undefined);
82
+ if (object === undefined) throw new TypeError(`createPageHost: expose.${name}: only a root named "window" is the window; give { object } for another root`);
83
+ roots[name] = object;
84
+ for (const [op, list] of Object.entries(cfg.allow ?? {})) {
85
+ if (!(op in allow)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} is not an operation (get, call, set)`);
86
+ if (!Array.isArray(list)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} must be an array of path patterns`);
87
+ for (const entry of list) {
88
+ if (typeof entry !== 'string' || entry === '') throw new TypeError(`createPageHost: expose.${name}.allow.${op} entries must be non-empty strings (paths relative to ${name})`);
89
+ allow[op].push(`${name}.${entry}`);
90
+ }
91
+ }
92
+ if (cfg.authorize !== undefined) { if (typeof cfg.authorize !== 'function') throw new TypeError(`createPageHost: expose.${name}.authorize must be a function`); authorizers.set(name, cfg.authorize); }
93
+ if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
94
+ }
95
+ const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
96
+ return { roots, allow, authorize, limits };
97
+ }
98
+
99
+ /** The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. */
100
+ function createDomIndicator(window, { name }) {
101
+ const doc = window.document;
102
+ const make = (tag, props = {}, text) => {
103
+ const el = doc.createElement(tag);
104
+ for (const [k, v] of Object.entries(props)) el.setAttribute(k, v);
105
+ if (text !== undefined) el.textContent = text;
106
+ return el;
107
+ };
108
+ let root = null;
109
+ const rows = new Map();
110
+ const attach = () => {
111
+ if (!root) {
112
+ root = make('div', { 'data-wsh-page': 'indicator', role: 'status', 'aria-live': 'polite',
113
+ style: 'position:fixed;right:12px;bottom:12px;z-index:2147483645;box-sizing:border-box;max-width:min(32em,92vw);background:#7a1f1f;color:#fff;border:2px solid #fff;border-radius:8px;padding:8px 12px;font:13px/1.4 system-ui,sans-serif;box-shadow:0 2px 8px rgba(0,0,0,.4)' });
114
+ }
115
+ const parent = doc.body ?? doc.documentElement;
116
+ if (root.parentNode !== parent) parent.appendChild(root);
117
+ };
118
+ return {
119
+ show(who, stop) {
120
+ const row = make('div', { 'data-wsh-page': 'session', 'data-fingerprint': who.fingerprint ?? '', style: 'display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:2px 0' });
121
+ row.appendChild(make('span', {}, `Remote session connected to "${name}" (key`));
122
+ row.appendChild(make('code', { 'data-wsh-page': 'fingerprint', style: 'word-break:break-all' }, who.fingerprint ?? 'unknown'));
123
+ row.appendChild(make('span', {}, ')'));
124
+ const button = make('button', { type: 'button', 'data-wsh-page': 'stop', 'aria-label': `Stop the remote session of key ${who.fingerprint ?? 'unknown'}` }, 'Stop');
125
+ button.addEventListener('click', () => { void stop(); });
126
+ row.appendChild(button);
127
+ rows.set(who.fingerprint, row);
128
+ attach();
129
+ root.appendChild(row);
130
+ },
131
+ hide(who) {
132
+ const row = rows.get(who.fingerprint);
133
+ rows.delete(who.fingerprint);
134
+ try { row?.remove(); } catch { /* gone */ }
135
+ if (rows.size === 0 && root) { try { root.remove(); } catch { /* gone */ } }
136
+ },
137
+ /** Put the indicator back if something in the page took it out while a session is connected. */
138
+ ensure() { if (rows.size && root && !root.isConnected) attach(); },
139
+ destroy() { rows.clear(); try { root?.remove(); } catch { /* gone */ } root = null; },
140
+ };
141
+ }
142
+
143
+ /**
144
+ * @param {object} options
145
+ * @param {object} options.window - REQUIRED: the realm to serve (a page's `window`, an iframe's `contentWindow`, a popup, a worker's
146
+ * `self`, a fake one in a test). It says where tools are read from, where the indicator is drawn, which `WebSocket` dials the relay,
147
+ * and whose origin is reported. Passing it exposes nothing by itself.
148
+ * @param {string | { url: string, id?: string }} options.relay - a pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, and
149
+ * optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
150
+ * @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
151
+ * object access, off unless written: named roots (`window` is the window passed; another name needs `object`), each with its allow-lists by
152
+ * operation (paths relative to the root: `'document.title'`, `'app.**'`; nothing allowed by default). `mode: 'handles'` is refused: not built.
153
+ * See `@johnhenry/wsh/objects` for what `values` mode promises.
154
+ * @param {string} options.name - what this tab is called (shown in the indicator, the `serverInfo` of the MCP server)
155
+ * @param {string | Uint8Array | Array<string | Uint8Array>} options.authorizedKeys - who may log in, as `authorized_keys` lines (with their
156
+ * options, e.g. `capabilities="mcp:search_products"`) or raw keys. Required and non-empty.
157
+ * @param {{ allow?: string[], approve?: 'never' | 'consequential' | 'always', tools?: object[], prompt?: Function, limits?: object, onCall?: Function, server?: object }} [options.mcp]
158
+ * the page's WebMCP tools as MCP, see `webmcpTools`. `allow` names the tools; nothing is allowed by default.
159
+ * @param {true | false | { connected(who, control: { stop(): Promise<void> }): void, disconnected(who): void }} [options.indicator=true]
160
+ * what shows that a remote session is connected. `true`: the badge in `window.document`. Callbacks: for a context with no document
161
+ * (a worker) or an embedder with its own UI. `false` is refused unless `unattended: true`.
162
+ * @param {boolean} [options.unattended=false] - nobody is in front of this window: `indicator: false` and a window with no document become
163
+ * allowed, and a call that needs approval is denied unless `mcp.prompt` answers it.
164
+ * @param {CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey] - this host's identity. Without one a fresh
165
+ * non-extractable key is generated: it lives and dies with the page load, so an operator can pin it only for that load (compare
166
+ * `host.fingerprint`, which the page can show), and a `known_hosts` entry from an earlier load will not match.
167
+ * @param {{ load(): Promise<CryptoKeyPair | undefined | null> | CryptoKeyPair | undefined | null, save(pair: CryptoKeyPair): Promise<void> | void }} [options.hostKeyStore]
168
+ * persist the generated key through a store you inject (an IndexedDB wrapper: a non-extractable `CryptoKeyPair` can be stored there), so
169
+ * the page keeps one identity across loads and an operator's TOFU pin holds. Ignored when `hostKey` is given.
170
+ * @param {(who: { username: string, fingerprint: string }) => boolean | void | Promise<boolean | void>} [options.onSession] - a key logged in; return
171
+ * `false` to refuse it (ask the person first)
172
+ * @param {(who: { username: string, fingerprint: string }) => void} [options.onSessionEnd]
173
+ * @param {(refusal: { reason: string, who: object, detail: string }) => void} [options.onRefused] - as for every host (`REFUSAL_REASONS`)
174
+ * @param {(closed: { reason: string }) => void} [options.onClose] - the host closed itself (the window navigated away or closed) or was closed
175
+ * @param {object} [options.timers] - `{ setTimeout, clearTimeout, setInterval, clearInterval }` of the realm that runs this code, when it is not
176
+ * the window's own (an opener serving a popup, a parent serving an iframe: the window's timers die with its document)
177
+ * @param {boolean} [options.reconnect=true] - dial the relay again after a session or a failed attempt, so another operator can arrive
178
+ * @param {(line: string) => void} [options.onLog]
179
+ */
180
+ export async function createPageHost(options = {}) {
181
+ const { window, relay, name, authorizedKeys, mcp, expose, indicator = true, unattended = false, hostKey, hostKeyStore, onSession, onSessionEnd, onRefused, onClose, reconnect = true, onLog = () => {} } = options;
182
+ if (!window || (typeof window !== 'object' && typeof window !== 'function')) {
183
+ throw new TypeError('createPageHost: window is required: it is the realm served and the only thing this reads (pass `window`, an iframe\'s contentWindow, or a worker\'s self)');
184
+ }
185
+ if (typeof name !== 'string' || !name) throw new TypeError('createPageHost: name is required (what this tab is called)');
186
+ if (typeof unattended !== 'boolean') throw new TypeError('createPageHost: unattended must be true or false');
187
+ if (authorizedKeys === undefined || authorizedKeys === null || (Array.isArray(authorizedKeys) && authorizedKeys.length === 0) || authorizedKeys === '') {
188
+ throw new TypeError('createPageHost: authorizedKeys is required: a page host has no anonymous mode and no password login');
189
+ }
190
+ if (mcp !== undefined && !isObj(mcp)) throw new TypeError('createPageHost: mcp must be an object { allow: [...tool names] }');
191
+ if (expose !== undefined && !isObj(expose)) throw new TypeError('createPageHost: expose must be an object of named roots: { window: { mode: \'values\', allow: { get: [...] } } }');
192
+ if (mcp === undefined && expose === undefined) throw new TypeError('createPageHost: nothing to serve: pass mcp: { allow: [...tool names] } and/or expose: { window: { allow } }');
193
+ const exposed = expose === undefined ? null : exposedRoots(window, expose);
194
+ const doc = window.document ?? null;
195
+ const callbacks = isObj(indicator) ? indicator : null;
196
+ if (callbacks && (typeof callbacks.connected !== 'function' || typeof callbacks.disconnected !== 'function')) throw new TypeError('createPageHost: indicator callbacks need connected(who, control) and disconnected(who)');
197
+ if (indicator !== true && indicator !== false && !callbacks) throw new TypeError('createPageHost: indicator must be true, false or { connected, disconnected }');
198
+ if (indicator === false && !unattended) throw new TypeError('createPageHost: indicator: false is refused unless unattended: true (a remote session must be visible to the person at the page)');
199
+ if (indicator === true && !doc) {
200
+ if (!unattended) throw new TypeError('createPageHost: this window has no document to draw the indicator in: supply indicator callbacks, or say unattended: true');
201
+ }
202
+ if (!doc && !unattended && !callbacks) throw new TypeError('createPageHost: this window has no document: supply indicator callbacks, or say unattended: true');
203
+ if (mcp && (mcp.approve ?? 'consequential') !== 'never' && !doc && !mcp.prompt && !unattended) {
204
+ throw new TypeError("createPageHost: this window has no document to ask the person in: supply mcp.prompt, mcp.approve: 'never', or unattended: true");
205
+ }
206
+ if (typeof window.WebSocket !== 'function') throw new TypeError('createPageHost: window.WebSocket is needed to dial the relay');
207
+ for (const [k, fn] of Object.entries({ onSession, onSessionEnd, onRefused, onClose })) if (fn !== undefined && typeof fn !== 'function') throw new TypeError(`createPageHost: ${k} must be a function`);
208
+ if (hostKeyStore !== undefined && (typeof hostKeyStore?.load !== 'function' || typeof hostKeyStore?.save !== 'function')) throw new TypeError('createPageHost: hostKeyStore needs load() and save(keyPair)');
209
+
210
+ const relayOptions = typeof relay === 'string' ? { url: relay } : relay;
211
+ if (!isObj(relayOptions) || typeof relayOptions.url !== 'string') throw new TypeError('createPageHost: relay is required: the ws:// or wss:// URL of a pipe relay (or { url, id })');
212
+ const rendezvousId = relayOptions.id ?? randomRendezvousId(window.crypto);
213
+ const hostUrl = pipeUrl(relayOptions.url, rendezvousId, 'host');
214
+ const operatorUrl = pipeUrl(relayOptions.url, rendezvousId, 'operator');
215
+
216
+ const timers = timersOf(window, options.timers);
217
+ const origin = readOrigin(window);
218
+ if (origin === null) throw new TypeError('createPageHost: cannot read window.location.origin: the host closes when the window leaves its origin, so it needs to know it');
219
+
220
+ // The host's identity.
221
+ let keyOption = hostKey;
222
+ if (keyOption === undefined) {
223
+ let pair = hostKeyStore ? await hostKeyStore.load() : undefined;
224
+ if (!pair) {
225
+ pair = await generateKeyPair(false);
226
+ if (hostKeyStore) await hostKeyStore.save(pair);
227
+ }
228
+ keyOption = pair;
229
+ }
230
+ const hostFingerprint = (await resolveHostKey(keyOption, 'createPageHost: hostKey')).fingerprint;
231
+
232
+ const callbacksUi = callbacks ?? (indicator === true && doc ? createDomIndicator(window, { name }) : null);
233
+ const control = (who) => ({ stop: () => host.revoke(who.fingerprint) });
234
+
235
+ /** @type {{ who: object, since: number, socket: object } | null} */
236
+ let current = null;
237
+ let halfSocket = null;
238
+ const revoked = new Set();
239
+ let closed = false;
240
+ let closedReason = null;
241
+ let backoff = RECONNECT_START_MS;
242
+ let redialTimer = null;
243
+ let watch = null;
244
+ let unlisten = null;
245
+
246
+ const mcpHandler = mcp ? webmcpTools({
247
+ ...mcp, window, timers: options.timers, server: { name, ...(mcp.server ?? {}) },
248
+ // Nobody is in front of an unattended window: without a prompt of the embedder's, what needs approval is denied.
249
+ prompt: mcp.prompt ?? (unattended ? () => false : undefined),
250
+ guard: () => gone() ?? mcp.guard?.() ?? null,
251
+ }) : null;
252
+ const objectsHandler = exposed ? exposeObjects({
253
+ roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, timers,
254
+ guard: () => gone(),
255
+ }) : null;
256
+ /** What each handler tells and ends: the sessions of a key, or all of them. */
257
+ const closeSessions = async (reason, fingerprint) => {
258
+ const counts = await Promise.all([mcpHandler, objectsHandler].filter(Boolean).map((h) => h.closeSessions(reason, fingerprint).catch(() => 0)));
259
+ return Math.max(0, ...counts);
260
+ };
261
+
262
+ const memory = createMemoryHost({
263
+ auth: {
264
+ authorizedKeys,
265
+ async authorize(who) {
266
+ if (closed || revoked.has(who.fingerprint) || !halfSocket) return false;
267
+ try { if (onSession && (await onSession({ username: who.username, fingerprint: who.fingerprint })) === false) return false; } catch (e) { onLog(`onSession threw: ${e?.message ?? e}`); return false; }
268
+ if (closed || revoked.has(who.fingerprint)) return false;
269
+ begin(who);
270
+ return true;
271
+ },
272
+ },
273
+ hostKey: keyOption,
274
+ dataStreams: false,
275
+ sealSession: 'require',
276
+ rpc: { ...(mcpHandler ? { mcp: mcpHandler } : {}), ...(objectsHandler ? { [OBJECTS_PROTOCOL]: objectsHandler } : {}) },
277
+ onRefused,
278
+ onLog,
279
+ });
280
+
281
+ function begin(who) {
282
+ const w = { username: who.username, fingerprint: who.fingerprint };
283
+ current = { who: w, since: Date.now(), socket: halfSocket };
284
+ backoff = RECONNECT_START_MS;
285
+ try { callbacksUi?.show?.(w, control(w).stop); callbacksUi?.connected?.(w, control(w)); } catch (e) { onLog(`indicator threw: ${e?.message ?? e}`); }
286
+ }
287
+ function end() {
288
+ if (!current) return;
289
+ const { who } = current;
290
+ current = null;
291
+ try { callbacksUi?.hide?.(who); callbacksUi?.disconnected?.(who); } catch (e) { onLog(`indicator threw: ${e?.message ?? e}`); }
292
+ try { onSessionEnd?.(who); } catch (e) { onLog(`onSessionEnd threw: ${e?.message ?? e}`); }
293
+ }
294
+
295
+ /** Why this window can no longer be served, or null. */
296
+ function gone() {
297
+ if (closedReason) return closedReason;
298
+ try { if (window.closed === true) return 'the window was closed'; } catch { return 'the window was closed'; }
299
+ if (readOrigin(window) !== origin) return 'the window navigated to another origin';
300
+ return null;
301
+ }
302
+
303
+ function dial() {
304
+ if (closed) return;
305
+ let socket;
306
+ try { socket = new window.WebSocket(hostUrl); } catch (e) { onLog(`dialing the relay failed: ${e?.message ?? e}`); schedule(false); return; }
307
+ halfSocket = socket;
308
+ onLog('dialed the relay, waiting for an operator');
309
+ let served = false;
310
+ void memory.accept(socket, { remote: { address: 'relay' } }).catch((e) => onLog(`accept failed: ${e?.message ?? e}`));
311
+ const onEnd = () => {
312
+ if (halfSocket === socket) halfSocket = null;
313
+ served = current?.socket === socket;
314
+ if (served) end();
315
+ schedule(served);
316
+ };
317
+ socket.addEventListener('close', onEnd);
318
+ }
319
+ function schedule(afterSession) {
320
+ if (closed || !reconnect || redialTimer !== null) return;
321
+ const delay = afterSession ? 0 : backoff;
322
+ if (!afterSession) backoff = Math.min(backoff * 2, RECONNECT_MAX_MS);
323
+ redialTimer = timers.setTimeout(() => { redialTimer = null; dial(); }, delay);
324
+ }
325
+
326
+ async function shutdown(reason, { tell = true } = {}) {
327
+ if (closed) return;
328
+ closedReason = reason;
329
+ if (tell) await closeSessions(reason).catch(() => {});
330
+ closed = true;
331
+ timers.clearTimeout(redialTimer);
332
+ if (watch !== null) timers.clearInterval(watch);
333
+ try { unlisten?.(); } catch { /* the window is gone */ }
334
+ try { halfSocket?.close(1000); } catch { /* already closed */ }
335
+ end();
336
+ callbacksUi?.destroy?.();
337
+ await memory.close();
338
+ try { onClose?.({ reason }); } catch (e) { onLog(`onClose threw: ${e?.message ?? e}`); }
339
+ }
340
+
341
+ const host = {
342
+ /** The URL an operator dials (its rendezvous id is the secret that pairs it with this page). */
343
+ operatorUrl,
344
+ rendezvousId,
345
+ /** What the page serves: its name and the origin it was started in. */
346
+ name,
347
+ origin,
348
+ /** This host's key: compare it with what the operator sees (`client.hostKey.fingerprint`) to pin it. New on every page load unless a key or a `hostKeyStore` was given. */
349
+ fingerprint: hostFingerprint,
350
+ /** Who is connected now: `[{ username, fingerprint, since }]`. */
351
+ get sessions() { return current ? [{ ...current.who, since: current.since }] : []; },
352
+ get closed() { return closed; },
353
+ /** Why the host closed itself, or null. */
354
+ get closedReason() { return closedReason; },
355
+ /**
356
+ * End the session of a key and refuse that key until this host is closed (a Stop that lets the same operator straight back in is
357
+ * not a Stop). The operator is told why before the channel ends. Resolves true if a session was ended.
358
+ */
359
+ async revoke(fingerprint) {
360
+ revoked.add(fingerprint);
361
+ const n = await closeSessions('the person at the page stopped this session', fingerprint);
362
+ if (current?.who.fingerprint === fingerprint) { try { current.socket.close(1000); } catch { /* gone */ } }
363
+ return n > 0 || current?.who.fingerprint === fingerprint;
364
+ },
365
+ /** End every session, close the relay connection and stop serving. */
366
+ close: () => shutdown('the page host was closed'),
367
+ };
368
+
369
+ // The window going away: a navigation, a close, a different origin. Events where the window sends them, and a check every second
370
+ // and before every call, for the cases it cannot (an iframe that navigated cross-origin, a popup that closed).
371
+ const leave = () => { void shutdown(gone() ?? 'the window was unloaded'); };
372
+ try { window.addEventListener?.('pagehide', leave); unlisten = () => window.removeEventListener?.('pagehide', leave); } catch { /* a window that takes no listeners: the check below covers it */ }
373
+ watch = timers.setInterval(() => {
374
+ const why = gone();
375
+ if (why) void shutdown(why);
376
+ else callbacksUi?.ensure?.();
377
+ }, WATCH_MS);
378
+
379
+ dial();
380
+ return host;
381
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The Node-only half of the pipe relay: an HTTP(S) server that accepts WebSocket upgrades on `<path>/<id>` and hands each to
3
+ * `relay.accept()`. `createPipeRelay().listen()` loads this module on demand; the relay itself (`./pipe-relay.mjs`) is
4
+ * browser-safe and imports nothing. Needs the optional `ws` package. Its only imports are `ws`, `node:http` and `node:https`,
5
+ * all dynamic, so it reaches nothing that can execute code or read files (test/pipe-relay.test.mjs walks its graph too).
6
+ */
7
+
8
+ const ID_RE = /^[A-Za-z0-9_-]{22,128}$/;
9
+ const ROLES = new Set(['host', 'operator']);
10
+
11
+ /**
12
+ * @param {{ accept: Function, maxMessageBytes: number, onClose: (fn: () => Promise<void> | void) => void, close: () => Promise<void> }} relay
13
+ * @param {{ host?: string, port?: number, path?: string, tls?: object }} [options]
14
+ * @returns {Promise<{ port: number, address: string, close(): Promise<void> }>}
15
+ */
16
+ export async function listenPipeRelay(relay, { host = '127.0.0.1', port = 0, path = '/r', tls } = {}) {
17
+ const { WebSocketServer } = await import('ws');
18
+ const http = tls ? await import('node:https') : await import('node:http');
19
+ const wss = new WebSocketServer({ noServer: true, maxPayload: relay.maxMessageBytes });
20
+ const srv = tls ? http.createServer(tls) : http.createServer();
21
+ srv.on('request', (_req, res) => { res.statusCode = 426; res.end('WebSocket only'); });
22
+ srv.on('upgrade', (req, sock, head) => {
23
+ let url;
24
+ try { url = new URL(req.url, 'http://x'); } catch { sock.destroy(); return; }
25
+ const m = url.pathname.startsWith(`${path}/`) ? url.pathname.slice(path.length + 1) : null;
26
+ const role = url.searchParams.get('role') ?? 'operator';
27
+ 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; }
28
+ // `paired=1` is the host asking to be told when its partner arrives; an operator that sends it is not a host, so it is ignored.
29
+ const notifyPaired = role === 'host' && url.searchParams.get('paired') === '1';
30
+ wss.handleUpgrade(req, sock, head, (ws) => {
31
+ relay.accept(ws, { id: m, role, notifyPaired, remote: { address: req.socket.remoteAddress, headers: req.headers } })
32
+ .catch(() => { try { ws.close(1011, 'error'); } catch { /* gone */ } });
33
+ });
34
+ });
35
+ await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(port, host, () => { srv.off('error', reject); resolve(); }); });
36
+ relay.onClose(async () => {
37
+ for (const c of wss.clients) c.terminate();
38
+ await new Promise((r) => wss.close(r));
39
+ await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); });
40
+ });
41
+ const addr = srv.address();
42
+ return { port: addr.port, address: addr.address, close: () => relay.close() };
43
+ }
@@ -34,8 +34,12 @@ export interface PipeRelayOptions {
34
34
 
35
35
  export interface PipeRelay {
36
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. */
37
+ accept(socket: PipeSocket, who: { id: string; role?: 'host' | 'operator'; remote?: object; notifyPaired?: boolean }): Promise<boolean>;
38
+ /**
39
+ * Listen for WebSocket upgrades on `<path>/<id>` (default `/r`); `?role=host` is the host side, `&paired=1` asks to be told when the
40
+ * operator arrives. Node only, and needs the `ws` package: the code that does it is loaded when this is called, so the rest of this
41
+ * module bundles for a browser.
42
+ */
39
43
  listen(options?: { host?: string; port?: number; path?: string; tls?: object }): Promise<{ port: number; address: string; close(): Promise<void> }>;
40
44
  close(): Promise<void>;
41
45
  stats(): { waiting: number; pipes: number };
@@ -45,5 +49,16 @@ export interface PipeRelay {
45
49
  export function createPipeRelay(options?: PipeRelayOptions): PipeRelay;
46
50
  /** A fresh 128-bit rendezvous id, base64url. */
47
51
  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;
52
+ /**
53
+ * The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host. `notifyPaired` (host only) adds `&paired=1`: ask the relay to
54
+ * send `PAIRED_FRAME` when the operator arrives; a relay that predates it ignores the parameter.
55
+ */
56
+ export function pipeUrl(relayUrl: string, id: string, role?: 'host' | 'operator', options?: { notifyPaired?: boolean }): string;
57
+ /** The one text frame a relay sends a host that asked, when its partner arrives, before anything the partner said. */
58
+ export const PAIRED_FRAME: 'wsh-pipe/1 paired';
59
+ /**
60
+ * Host side of the paired signal: wrap the socket the host dialled (with `notifyPaired`) before anything is attached, pass `socket` on to
61
+ * `accept()`, await `paired`. It resolves when the operator arrives and rejects if the socket closes first; the signal frame is kept out
62
+ * of what the wsh host reads. Against a relay that does not know the flag it never resolves and the connection works as before.
63
+ */
64
+ export function watchPairing<S extends object>(socket: S): { socket: S; paired: Promise<void> };