@johnhenry/browsermesh-transport 0.5.0 → 0.6.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/README.md +181 -2
- package/package.json +13 -4
- package/src/channel-relay.mjs +2 -2
- package/src/cross-origin.mjs +3 -3
- package/src/gateway.mjs +3 -3
- package/src/identity-binding.mjs +181 -0
- package/src/index.mjs +8 -0
- package/src/relay.mjs +2 -2
- package/src/silent-catch.mjs +38 -9
- package/src/streams.mjs +3 -3
- package/src/transport.mjs +48 -6
- package/src/webrtc.mjs +236 -25
- package/src/websocket.mjs +35 -18
- package/src/webtransport.mjs +5 -5
- package/src/wisp-client.mjs +5 -5
- package/src/wisp.mjs +4 -4
- package/src/wsh-bridge.mjs +9 -14
- package/src/wsh-frames.mjs +180 -0
- package/src/wsh-in-process.mjs +82 -0
- package/src/wsh-links.mjs +1005 -0
- package/src/wsh-pod-transport.mjs +159 -0
|
@@ -0,0 +1,1005 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wsh-links.mjs -- mesh peer links carried on wsh sessions.
|
|
3
|
+
*
|
|
4
|
+
* A link between pod A and pod B is ONE wsh session that is key-authenticated
|
|
5
|
+
* in both directions and sealed end to end, carrying ONE named endpoint
|
|
6
|
+
* (`mesh`) whose duplex byte stream holds the mesh's frames (`wsh-frames.mjs`).
|
|
7
|
+
* Between two browsers neither side can listen, so a pod that wants to be
|
|
8
|
+
* reached is a wsh host dialled in through a pipe relay (`@johnhenry/wsh/
|
|
9
|
+
* pipe-relay`) that vouches for nothing, and a pod that wants to reach it is a
|
|
10
|
+
* wsh client. Design and threat model: `docs/design/wsh-peer-link.md`.
|
|
11
|
+
*
|
|
12
|
+
* What this file enforces, and does not leave to the caller:
|
|
13
|
+
* - the pod id a peer claims is the hash of the key wsh authenticated
|
|
14
|
+
* (login username = pod id; the host refuses a mismatch);
|
|
15
|
+
* - the dialler pins the host key to the pod id it meant to reach;
|
|
16
|
+
* - the session is sealed (there is no setting that makes it plain) and the
|
|
17
|
+
* dialler checks `client.sessionSealed` after login;
|
|
18
|
+
* - a peer is allowed only if the `authorize` callback says so (default:
|
|
19
|
+
* nobody), and the key is given nothing but the `endpoint:mesh` capability;
|
|
20
|
+
* - frames are length-prefixed with a maximum enforced on the header.
|
|
21
|
+
*
|
|
22
|
+
* `@johnhenry/wsh` is an optional peer dependency, imported lazily on first
|
|
23
|
+
* `listen()` / `connect()`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
|
|
27
|
+
import { encodeFrame, FrameDecoder, WshFrameError, DEFAULT_MAX_FRAME_BYTES } from './wsh-frames.mjs';
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Errors
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Every failure of a wsh link is one of these, with a stable `code`:
|
|
35
|
+
* `WSH_HOSTKEY_MISMATCH`, `WSH_REFUSED` (`reason` says why), `WSH_IDENTITY_MISMATCH`,
|
|
36
|
+
* `WSH_NOT_SEALED`, `WSH_UNREACHABLE`, `WSH_SEAL_FAILED`, `WSH_FRAME_TOO_LARGE`,
|
|
37
|
+
* `WSH_BAD_FRAME`, `WSH_BACKPRESSURE`, `WSH_CLOSED`, `WSH_UNAVAILABLE`.
|
|
38
|
+
*/
|
|
39
|
+
export class WshLinkError extends Error {
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} code
|
|
42
|
+
* @param {string} message
|
|
43
|
+
* @param {{ reason?: string, cause?: unknown, podId?: string }} [extra]
|
|
44
|
+
*/
|
|
45
|
+
constructor(code, message, { reason, cause, podId } = {}) {
|
|
46
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
47
|
+
this.name = 'WshLinkError';
|
|
48
|
+
this.code = code;
|
|
49
|
+
if (reason !== undefined) this.reason = reason;
|
|
50
|
+
if (podId !== undefined) this.podId = podId;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Failures that do not get better by trying again. */
|
|
55
|
+
const FATAL = new Set(['WSH_HOSTKEY_MISMATCH', 'WSH_REFUSED', 'WSH_NOT_SEALED', 'WSH_UNAVAILABLE']);
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// Identity
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
const POD_ID_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
62
|
+
const HEX_FP_RE = /^[0-9a-fA-F]{64}$/;
|
|
63
|
+
|
|
64
|
+
const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
65
|
+
const fromHex = (hex) => Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16));
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* pod id (base64url of SHA-256 of the raw key) to the wsh fingerprint (the
|
|
69
|
+
* same hash, hex).
|
|
70
|
+
* @param {string} podId
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function podIdToFingerprint(podId) {
|
|
74
|
+
if (typeof podId !== 'string' || !POD_ID_RE.test(podId)) throw new TypeError('podIdToFingerprint: expected a 43 character base64url pod id');
|
|
75
|
+
const bytes = decodeBase64url(podId);
|
|
76
|
+
if (bytes.length !== 32) throw new TypeError('podIdToFingerprint: a pod id is 32 bytes');
|
|
77
|
+
return toHex(bytes);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* wsh fingerprint (hex SHA-256 of the raw key) to a pod id.
|
|
82
|
+
* @param {string} fingerprint
|
|
83
|
+
* @returns {string}
|
|
84
|
+
*/
|
|
85
|
+
export function fingerprintToPodId(fingerprint) {
|
|
86
|
+
if (typeof fingerprint !== 'string' || !HEX_FP_RE.test(fingerprint)) throw new TypeError('fingerprintToPodId: expected a 64 character hex fingerprint');
|
|
87
|
+
return encodeBase64url(fromHex(fingerprint.toLowerCase()));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The pod id of a raw 32-byte Ed25519 public key.
|
|
92
|
+
* @param {Uint8Array} raw
|
|
93
|
+
* @returns {Promise<string>}
|
|
94
|
+
*/
|
|
95
|
+
export async function podIdFromRawKey(raw) {
|
|
96
|
+
return encodeBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', raw)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const RENDEZVOUS_LABEL = 'browsermesh-wsh-link/1:';
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The pipe relay rendezvous id a pod listens at: base64url(SHA-256(label ||
|
|
103
|
+
* pod id)), 43 characters. Derived from a public value; nothing relies on it
|
|
104
|
+
* being secret.
|
|
105
|
+
* @param {string} podId
|
|
106
|
+
* @returns {Promise<string>}
|
|
107
|
+
*/
|
|
108
|
+
export async function rendezvousId(podId) {
|
|
109
|
+
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(RENDEZVOUS_LABEL + podId));
|
|
110
|
+
return encodeBase64url(new Uint8Array(hash));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Simultaneous dial tie-break. Of two links between the same pair, the one
|
|
115
|
+
* whose INITIATOR has the smaller pod id survives. Both sides evaluate the same
|
|
116
|
+
* two initiators and so agree without a message.
|
|
117
|
+
* @param {string} initiatorPodId
|
|
118
|
+
* @param {string} otherInitiatorPodId
|
|
119
|
+
* @returns {boolean} true when `initiatorPodId` wins
|
|
120
|
+
*/
|
|
121
|
+
export function initiatorWins(initiatorPodId, otherInitiatorPodId) {
|
|
122
|
+
return initiatorPodId < otherInitiatorPodId;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Turn what a caller gives (a `PodIdentity`, or `{ podId, signer }` for a key
|
|
127
|
+
* held elsewhere) into what wsh takes, and check that the pod id is the hash of
|
|
128
|
+
* the key.
|
|
129
|
+
* @param {{ podId?: string, keyPair?: CryptoKeyPair, signer?: { publicKey: Uint8Array | CryptoKey, sign: (data: Uint8Array) => Uint8Array | Promise<Uint8Array> } }} identity
|
|
130
|
+
* @returns {Promise<{ podId: string, publicKeyRaw: Uint8Array, keyPair?: CryptoKeyPair, signer?: object }>}
|
|
131
|
+
*/
|
|
132
|
+
export async function resolveCredential(identity) {
|
|
133
|
+
if (!identity || typeof identity !== 'object') throw new TypeError('identity is required (a PodIdentity, or { podId, signer })');
|
|
134
|
+
const { keyPair, signer } = identity;
|
|
135
|
+
if (!keyPair && !signer) throw new TypeError('identity needs a keyPair or a signer');
|
|
136
|
+
if (keyPair && signer) throw new TypeError('identity takes a keyPair or a signer, not both');
|
|
137
|
+
let key = keyPair ? keyPair.publicKey : signer.publicKey;
|
|
138
|
+
if (key && typeof key === 'object' && 'type' in key && key.type === 'public') key = new Uint8Array(await crypto.subtle.exportKey('raw', key));
|
|
139
|
+
if (!(key instanceof Uint8Array) || key.length !== 32) throw new TypeError('identity public key must be a 32 byte Ed25519 key');
|
|
140
|
+
const podId = await podIdFromRawKey(key);
|
|
141
|
+
if (identity.podId !== undefined && identity.podId !== podId) throw new Error('identity pod id is not the hash of its public key');
|
|
142
|
+
return keyPair ? { podId, publicKeyRaw: key, keyPair } : { podId, publicKeyRaw: key, signer: { publicKey: key, sign: signer.sign.bind(signer) } };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
// Lazy wsh
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
let clientModule = null;
|
|
150
|
+
let hostModule = null;
|
|
151
|
+
|
|
152
|
+
// Literal specifiers on purpose: a bundler can only split (and a browser can only
|
|
153
|
+
// resolve) an import() whose specifier it can read.
|
|
154
|
+
async function loadWsh(load) {
|
|
155
|
+
try {
|
|
156
|
+
return await load();
|
|
157
|
+
} catch (cause) {
|
|
158
|
+
throw new WshLinkError('WSH_UNAVAILABLE', `the wsh transport needs @johnhenry/wsh: install it (npm install @johnhenry/wsh). ${cause?.message ?? ''}`.trim(), { cause });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const loadClient = () => (clientModule ??= loadWsh(() => import('@johnhenry/wsh')));
|
|
162
|
+
const loadHost = () => (hostModule ??= loadWsh(() => import('@johnhenry/wsh/memory')));
|
|
163
|
+
|
|
164
|
+
function pipeUrl(relay, id, role) {
|
|
165
|
+
const u = new URL(relay);
|
|
166
|
+
u.pathname = `${u.pathname.replace(/\/+$/, '')}/r/${id}`;
|
|
167
|
+
u.search = role === 'host' ? '?role=host' : '';
|
|
168
|
+
return u.toString();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const ENDPOINT = 'mesh';
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* wsh logins take a user name that starts with a letter or an underscore, and a
|
|
175
|
+
* base64url pod id may start with a digit or a dash, so the user name a pod logs
|
|
176
|
+
* in with is the pod id behind this prefix.
|
|
177
|
+
*/
|
|
178
|
+
export const LINK_USERNAME_PREFIX = 'pod_';
|
|
179
|
+
|
|
180
|
+
/** The login user name that claims `podId`. */
|
|
181
|
+
export const usernameForPodId = (podId) => `${LINK_USERNAME_PREFIX}${podId}`;
|
|
182
|
+
|
|
183
|
+
/** Map what wsh throws on a dial to a `WshLinkError`. */
|
|
184
|
+
function mapDialError(err, podId) {
|
|
185
|
+
if (err instanceof WshLinkError) return err;
|
|
186
|
+
const msg = String(err?.message ?? err);
|
|
187
|
+
if (err?.name === 'HostKeyError' || /^HOST_KEY_/.test(err?.code ?? '')) {
|
|
188
|
+
return new WshLinkError('WSH_HOSTKEY_MISMATCH', `the host reached for ${podId} did not prove that pod's key (${msg})`, { cause: err, podId, reason: 'host-key' });
|
|
189
|
+
}
|
|
190
|
+
if (/^Authentication failed/i.test(msg)) {
|
|
191
|
+
return new WshLinkError('WSH_REFUSED', `${podId} refused this pod: ${msg}`, { cause: err, podId, reason: 'unauthorized' });
|
|
192
|
+
}
|
|
193
|
+
if (/sealed session/i.test(msg)) {
|
|
194
|
+
return new WshLinkError('WSH_NOT_SEALED', `no sealed session with ${podId}: ${msg}`, { cause: err, podId, reason: 'not-sealed' });
|
|
195
|
+
}
|
|
196
|
+
return new WshLinkError('WSH_UNREACHABLE', `could not reach ${podId}: ${msg}`, { cause: err, podId });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
// WshPeerLinks
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
const DEFAULT_RECONNECT = { baseMs: 250, maxMs: 10_000, maxAttempts: Infinity };
|
|
204
|
+
const EVENTS = ['peer-up', 'peer-down', 'message', 'refused', 'error', 'dropped'];
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The hub for one pod's wsh links: it listens (as a wsh host at the pod's own
|
|
208
|
+
* rendezvous id on each relay), dials (as a wsh client at the peer's), applies
|
|
209
|
+
* the tie-break when both happen at once, and hands the mesh whole frames
|
|
210
|
+
* tagged with the authenticated sender.
|
|
211
|
+
*
|
|
212
|
+
* Events: `peer-up` `{ podId, initiator: 'local'|'remote' }`, `peer-down`
|
|
213
|
+
* `{ podId, reason, error? }`, `message` `{ from, data }` (a handler may return
|
|
214
|
+
* a promise: the next frame is not read until it settles), `refused`
|
|
215
|
+
* `{ reason, who, detail }`, `error` `{ error }`, `dropped` `{ from, reason }`.
|
|
216
|
+
*/
|
|
217
|
+
export class WshPeerLinks {
|
|
218
|
+
#identity;
|
|
219
|
+
#cred = null;
|
|
220
|
+
#credReady;
|
|
221
|
+
#relays;
|
|
222
|
+
#WebSocketCtor;
|
|
223
|
+
#socketFactory;
|
|
224
|
+
#authorize;
|
|
225
|
+
#beforeDial;
|
|
226
|
+
#maxFrame;
|
|
227
|
+
#maxQueued;
|
|
228
|
+
#slotsWanted;
|
|
229
|
+
#connectTimeoutMs;
|
|
230
|
+
#reconnect;
|
|
231
|
+
#keepAlive;
|
|
232
|
+
#supersedeGraceMs;
|
|
233
|
+
#userOnRefused;
|
|
234
|
+
#onLog;
|
|
235
|
+
#bindTimeoutMs;
|
|
236
|
+
|
|
237
|
+
#listeners = new Map();
|
|
238
|
+
/** @type {Map<string, { active: object|null, all: Set<object> }>} */
|
|
239
|
+
#peers = new Map();
|
|
240
|
+
/** @type {Map<string, Promise<void>>} */
|
|
241
|
+
#dials = new Map();
|
|
242
|
+
/** @type {Map<string, { attempts: number, timer: any }>} */
|
|
243
|
+
#wanted = new Map();
|
|
244
|
+
#host = null;
|
|
245
|
+
#listening = false;
|
|
246
|
+
#closed = false;
|
|
247
|
+
/** @type {Map<string, Set<object>>} relay -> waiting host halves */
|
|
248
|
+
#slots = new Map();
|
|
249
|
+
/** @type {Map<string, any>} relay -> pending retry timer */
|
|
250
|
+
#slotRetry = new Map();
|
|
251
|
+
/** @type {Map<string, number>} relay -> consecutive failed registrations */
|
|
252
|
+
#slotAttempts = new Map();
|
|
253
|
+
#ownRid = null;
|
|
254
|
+
#pendingReasons = new Map();
|
|
255
|
+
#stats = { linksEstablished: 0, superseded: 0, messagesIn: 0, messagesOut: 0, bytesIn: 0, bytesOut: 0, refused: 0, dropped: 0 };
|
|
256
|
+
#nextConnId = 1;
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* @param {object} opts
|
|
260
|
+
* @param {object} opts.identity - a `PodIdentity`, or `{ podId, signer }`
|
|
261
|
+
* @param {string|string[]} [opts.relays] - pipe relay base URL(s), `wss://relay.example/`
|
|
262
|
+
* @param {Function} [opts.WebSocket] - WebSocket constructor (default `globalThis.WebSocket`)
|
|
263
|
+
* @param {(url: string, info: { role: 'host'|'operator', id: string, relay: string }) => object} [opts.socketFactory]
|
|
264
|
+
* Opens the WebSocket-like socket for a pipe; the seam for a test relay, a direct URL or a pipe carried some other way.
|
|
265
|
+
* @param {(peer: { podId: string, fingerprint: string, publicKey: Uint8Array }) => boolean | { expires?: string|Date|number } | Promise<boolean | { expires?: string|Date|number }>} [opts.authorize]
|
|
266
|
+
* Who may link to this pod. Asked after the key's signature verified and before any mesh frame. Default: nobody.
|
|
267
|
+
* @param {(info: { podId: string }) => void | Promise<void>} [opts.beforeDial] - Called before each outbound dial; throw to veto.
|
|
268
|
+
* @param {number} [opts.maxFrameBytes=1048576]
|
|
269
|
+
* @param {number} [opts.maxQueuedBytes=4194304] - Bytes a link may queue behind the endpoint's credit window.
|
|
270
|
+
* @param {number} [opts.listenSlots=2] - Host halves kept waiting per relay.
|
|
271
|
+
* @param {number} [opts.connectTimeoutMs=15000]
|
|
272
|
+
* @param {{ baseMs?: number, maxMs?: number, maxAttempts?: number }} [opts.reconnect]
|
|
273
|
+
* @param {{ pingIntervalMs?: number, pongTimeoutMs?: number }} [opts.keepAlive] - wsh client keepalive for links this pod dials.
|
|
274
|
+
* @param {number} [opts.supersedeGraceMs=2000] - How long a superseded link may drain.
|
|
275
|
+
* @param {(refusal: { reason: string, who: object, detail: string }) => void} [opts.onRefused]
|
|
276
|
+
* @param {(line: string) => void} [opts.onLog]
|
|
277
|
+
*/
|
|
278
|
+
constructor(opts = {}) {
|
|
279
|
+
if (!opts.identity) throw new TypeError('WshPeerLinks requires { identity }');
|
|
280
|
+
this.#identity = opts.identity;
|
|
281
|
+
this.#credReady = resolveCredential(opts.identity).then((c) => { this.#cred = c; return c; });
|
|
282
|
+
this.#credReady.catch(() => {});
|
|
283
|
+
const relays = opts.relays === undefined ? [] : Array.isArray(opts.relays) ? opts.relays : [opts.relays];
|
|
284
|
+
for (const r of relays) {
|
|
285
|
+
let u;
|
|
286
|
+
try { u = new URL(r); } catch { throw new TypeError(`relay is not a URL: ${r}`); }
|
|
287
|
+
if (!/^(wss?|https?):$/.test(u.protocol)) throw new TypeError(`relay must be a ws(s) or http(s) URL: ${r}`);
|
|
288
|
+
}
|
|
289
|
+
this.#relays = relays;
|
|
290
|
+
this.#WebSocketCtor = opts.WebSocket ?? globalThis.WebSocket ?? null;
|
|
291
|
+
this.#socketFactory = opts.socketFactory ?? null;
|
|
292
|
+
this.#authorize = typeof opts.authorize === 'function' ? opts.authorize : () => false;
|
|
293
|
+
this.#beforeDial = opts.beforeDial ?? null;
|
|
294
|
+
this.#maxFrame = opts.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
295
|
+
new FrameDecoder({ maxFrameBytes: this.#maxFrame }); // validates
|
|
296
|
+
this.#maxQueued = opts.maxQueuedBytes ?? 4 * 1024 * 1024;
|
|
297
|
+
if (!Number.isSafeInteger(this.#maxQueued) || this.#maxQueued < 1) throw new TypeError('maxQueuedBytes must be a positive integer');
|
|
298
|
+
this.#slotsWanted = opts.listenSlots ?? 2;
|
|
299
|
+
if (!Number.isSafeInteger(this.#slotsWanted) || this.#slotsWanted < 1) throw new TypeError('listenSlots must be a positive integer');
|
|
300
|
+
this.#connectTimeoutMs = opts.connectTimeoutMs ?? 15_000;
|
|
301
|
+
this.#reconnect = { ...DEFAULT_RECONNECT, ...opts.reconnect };
|
|
302
|
+
this.#keepAlive = opts.keepAlive ?? {};
|
|
303
|
+
this.#supersedeGraceMs = opts.supersedeGraceMs ?? 2000;
|
|
304
|
+
this.#userOnRefused = typeof opts.onRefused === 'function' ? opts.onRefused : null;
|
|
305
|
+
this.#onLog = opts.onLog ?? (() => {});
|
|
306
|
+
this.#bindTimeoutMs = opts.bindTimeoutMs;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// -- Public ---------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
/** This pod's id (the hash of the key it authenticates with). */
|
|
312
|
+
get podId() { return this.#cred?.podId ?? this.#identity.podId ?? null; }
|
|
313
|
+
|
|
314
|
+
/** Resolves once the identity is checked; `podId` is reliable after it. */
|
|
315
|
+
async ready() { await this.#credReady; return this.#cred.podId; }
|
|
316
|
+
|
|
317
|
+
/** Pod ids with a live link. */
|
|
318
|
+
peers() {
|
|
319
|
+
return [...this.#peers].filter(([, e]) => e.active).map(([id]) => id);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
isConnected(podId) { return !!this.#peers.get(podId)?.active; }
|
|
323
|
+
|
|
324
|
+
/** Live links (including a superseded one still draining) to a peer. */
|
|
325
|
+
linkCount(podId) {
|
|
326
|
+
const e = this.#peers.get(podId);
|
|
327
|
+
return e ? [...e.all].filter((c) => !c.ended).length : 0;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
linkInfo(podId) {
|
|
331
|
+
const c = this.#peers.get(podId)?.active;
|
|
332
|
+
return c ? { podId, initiatorPodId: c.initiatorPodId, role: c.role, sealed: true, fingerprint: podIdToFingerprint(podId) } : null;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
getStats() { return { ...this.#stats }; }
|
|
336
|
+
|
|
337
|
+
on(event, cb) {
|
|
338
|
+
if (!EVENTS.includes(event)) throw new Error(`Unknown event: ${event}`);
|
|
339
|
+
if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());
|
|
340
|
+
this.#listeners.get(event).add(cb);
|
|
341
|
+
return () => this.off(event, cb);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
off(event, cb) { this.#listeners.get(event)?.delete(cb); }
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* A transport object for one peer, shaped like the other mesh transports
|
|
348
|
+
* (`send`, `onMessage`, `onClose`, `onError`, `connect`, `close`). It dials on
|
|
349
|
+
* `connect()`.
|
|
350
|
+
* @param {string} podId
|
|
351
|
+
*/
|
|
352
|
+
link(podId) { return new WshLink(this, podId); }
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Become reachable: keep `listenSlots` host halves waiting at this pod's
|
|
356
|
+
* rendezvous id on every relay. Resolves once they are registered.
|
|
357
|
+
*/
|
|
358
|
+
async listen() {
|
|
359
|
+
if (this.#closed) throw new WshLinkError('WSH_CLOSED', 'the links are closed');
|
|
360
|
+
if (this.#listening) return;
|
|
361
|
+
this.#listening = true;
|
|
362
|
+
const cred = await this.#credReady;
|
|
363
|
+
this.#ownRid = await rendezvousId(cred.podId);
|
|
364
|
+
const { createMemoryHost } = await loadHost();
|
|
365
|
+
if (this.#closed) return;
|
|
366
|
+
this.#host = createMemoryHost({
|
|
367
|
+
hostKey: cred.keyPair ?? cred.signer,
|
|
368
|
+
dataStreams: false,
|
|
369
|
+
sealSession: 'require',
|
|
370
|
+
requireChannelBinding: true,
|
|
371
|
+
auth: (who) => this.#authorizePeer(who),
|
|
372
|
+
endpoints: { [ENDPOINT]: (duplex, who) => this.#serve(duplex, who) },
|
|
373
|
+
onRefused: (r) => this.#onWshRefused(r),
|
|
374
|
+
onLog: (line) => this.#onLog(line),
|
|
375
|
+
...(this.#bindTimeoutMs ? { bindTimeoutMs: this.#bindTimeoutMs } : {}),
|
|
376
|
+
});
|
|
377
|
+
await Promise.all(this.#relays.map((relay) => this.#fillSlots(relay)));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Link to a peer: dial its rendezvous id on the configured relays, pin its
|
|
382
|
+
* key to `podId`, log in with this pod's key, seal, open the mesh endpoint.
|
|
383
|
+
* Resolves when a link to the peer is up (this one, or the one the tie-break
|
|
384
|
+
* kept). With `keep` (default) the peer is redialled after an unplanned loss.
|
|
385
|
+
* @param {string} podId
|
|
386
|
+
* @param {{ keep?: boolean }} [opts]
|
|
387
|
+
*/
|
|
388
|
+
async connect(podId, { keep = true } = {}) {
|
|
389
|
+
if (this.#closed) throw new WshLinkError('WSH_CLOSED', 'the links are closed', { podId });
|
|
390
|
+
const cred = await this.#credReady;
|
|
391
|
+
podIdToFingerprint(podId);
|
|
392
|
+
if (podId === cred.podId) throw new WshLinkError('WSH_REFUSED', 'a pod cannot link to itself', { podId });
|
|
393
|
+
if (keep) this.#want(podId);
|
|
394
|
+
if (this.isConnected(podId)) return this.linkInfo(podId);
|
|
395
|
+
try {
|
|
396
|
+
await this.#dial(podId);
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (FATAL.has(err.code)) this.#unwant(podId);
|
|
399
|
+
else if (keep) this.#scheduleRedial(podId);
|
|
400
|
+
throw err;
|
|
401
|
+
}
|
|
402
|
+
return this.linkInfo(podId) ?? { podId };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Send one frame to a peer. The promise resolves when the endpoint's stream
|
|
407
|
+
* accepted it (after credit), and rejects with `WSH_BACKPRESSURE` when the
|
|
408
|
+
* queue is full, `WSH_FRAME_TOO_LARGE`, or `WSH_CLOSED`.
|
|
409
|
+
* @param {string} podId
|
|
410
|
+
* @param {*} data
|
|
411
|
+
* @returns {Promise<void>}
|
|
412
|
+
*/
|
|
413
|
+
send(podId, data) {
|
|
414
|
+
const conn = this.#peers.get(podId)?.active;
|
|
415
|
+
if (!conn) return Promise.reject(new WshLinkError('WSH_CLOSED', `no link to ${podId}`, { podId }));
|
|
416
|
+
let frame;
|
|
417
|
+
try {
|
|
418
|
+
frame = encodeFrame(data, { maxFrameBytes: this.#maxFrame });
|
|
419
|
+
} catch (err) {
|
|
420
|
+
return Promise.reject(err instanceof WshFrameError ? new WshLinkError(err.code, err.message, { podId, cause: err }) : err);
|
|
421
|
+
}
|
|
422
|
+
return this.#enqueue(conn, frame);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Stop reading from a peer (its sender will stall once credit runs out). */
|
|
426
|
+
pause(podId) {
|
|
427
|
+
for (const c of this.#peers.get(podId)?.all ?? []) {
|
|
428
|
+
if (!c.pause) { c.pause = {}; c.pause.promise = new Promise((r) => { c.pause.resolve = r; }); }
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
resume(podId) {
|
|
433
|
+
for (const c of this.#peers.get(podId)?.all ?? []) {
|
|
434
|
+
if (c.pause) { c.pause.resolve(); c.pause = null; }
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Close the link to a peer and stop redialling it. */
|
|
439
|
+
disconnect(podId) {
|
|
440
|
+
this.#unwant(podId);
|
|
441
|
+
const e = this.#peers.get(podId);
|
|
442
|
+
if (!e) return;
|
|
443
|
+
for (const c of [...e.all]) this.#end(c, 'local-close');
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async close() {
|
|
447
|
+
if (this.#closed) return;
|
|
448
|
+
this.#closed = true;
|
|
449
|
+
for (const w of this.#wanted.values()) clearTimeout(w.timer);
|
|
450
|
+
this.#wanted.clear();
|
|
451
|
+
for (const t of this.#slotRetry.values()) clearTimeout(t);
|
|
452
|
+
this.#slotRetry.clear();
|
|
453
|
+
this.#slotAttempts.clear();
|
|
454
|
+
for (const e of [...this.#peers.values()]) for (const c of [...e.all]) this.#end(c, 'local-close');
|
|
455
|
+
for (const set of this.#slots.values()) for (const s of set) { try { s.ws?.close(); } catch { /* already closed */ } }
|
|
456
|
+
this.#slots.clear();
|
|
457
|
+
await this.#host?.close();
|
|
458
|
+
this.#listeners.clear();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// -- Events ---------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
#emit(event, payload) {
|
|
464
|
+
const results = [];
|
|
465
|
+
for (const cb of [...(this.#listeners.get(event) ?? [])]) {
|
|
466
|
+
try { results.push(cb(payload)); } catch (e) { this.#onLog(`listener for ${event} threw: ${e?.message ?? e}`); }
|
|
467
|
+
}
|
|
468
|
+
return results;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
#fail(error, extra = {}) { this.#emit('error', { error, ...extra }); }
|
|
472
|
+
|
|
473
|
+
// -- Authorization (the listening side) -------------------------------------
|
|
474
|
+
|
|
475
|
+
async #authorizePeer(who) {
|
|
476
|
+
let podId;
|
|
477
|
+
try { podId = fingerprintToPodId(who.fingerprint); } catch { return false; }
|
|
478
|
+
if (who.username !== usernameForPodId(podId)) {
|
|
479
|
+
this.#pendingReasons.set(who.fingerprint, 'identity-mismatch');
|
|
480
|
+
return false;
|
|
481
|
+
}
|
|
482
|
+
if (podId === this.#cred.podId) return false;
|
|
483
|
+
let verdict;
|
|
484
|
+
try {
|
|
485
|
+
verdict = await this.#authorize({ podId, fingerprint: who.fingerprint, publicKey: who.publicKey });
|
|
486
|
+
} catch (e) {
|
|
487
|
+
this.#onLog(`authorize threw: ${e?.message ?? e}`);
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
490
|
+
if (!verdict) return false;
|
|
491
|
+
const grant = { capabilities: `endpoint:${ENDPOINT}` };
|
|
492
|
+
if (typeof verdict === 'object' && verdict.expires !== undefined) grant.expires = verdict.expires;
|
|
493
|
+
return grant;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
#onWshRefused({ reason, who, detail }) {
|
|
497
|
+
const own = who?.fingerprint ? this.#pendingReasons.get(who.fingerprint) : undefined;
|
|
498
|
+
if (own) this.#pendingReasons.delete(who.fingerprint);
|
|
499
|
+
const final = own ?? reason;
|
|
500
|
+
this.#stats.refused++;
|
|
501
|
+
// A sealed session whose frame did not open names the link that died.
|
|
502
|
+
if (reason === 'seal-failed' && who?.fingerprint) {
|
|
503
|
+
try {
|
|
504
|
+
const conn = this.#peers.get(fingerprintToPodId(who.fingerprint))?.active;
|
|
505
|
+
if (conn) conn.endReason = 'seal-failed';
|
|
506
|
+
} catch { /* not a pod fingerprint */ }
|
|
507
|
+
}
|
|
508
|
+
const refusal = { reason: final, who: who ?? {}, detail };
|
|
509
|
+
this.#emit('refused', refusal);
|
|
510
|
+
if (this.#userOnRefused) {
|
|
511
|
+
try { this.#userOnRefused(refusal); } catch (e) { this.#onLog(`onRefused threw: ${e?.message ?? e}`); }
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// -- Listening: waiting host halves -------------------------------------------
|
|
516
|
+
|
|
517
|
+
#openSocket(role, id, relay) {
|
|
518
|
+
const url = pipeUrl(relay, id, role);
|
|
519
|
+
if (this.#socketFactory) return this.#socketFactory(url, { role, id, relay });
|
|
520
|
+
if (!this.#WebSocketCtor) throw new WshLinkError('WSH_UNAVAILABLE', 'no WebSocket constructor: pass { WebSocket } or run where one is global');
|
|
521
|
+
return new this.#WebSocketCtor(url);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async #fillSlots(relay) {
|
|
525
|
+
if (this.#closed || !this.#listening) return;
|
|
526
|
+
let set = this.#slots.get(relay);
|
|
527
|
+
if (!set) this.#slots.set(relay, (set = new Set()));
|
|
528
|
+
const opening = [];
|
|
529
|
+
while (set.size < this.#slotsWanted) opening.push(this.#openSlot(relay, set));
|
|
530
|
+
await Promise.all(opening);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async #openSlot(relay, set) {
|
|
534
|
+
const slot = { ws: null, paired: false };
|
|
535
|
+
set.add(slot);
|
|
536
|
+
let opened = false;
|
|
537
|
+
try {
|
|
538
|
+
const ws = this.#openSocket('host', this.#ownRid, relay);
|
|
539
|
+
slot.ws = ws;
|
|
540
|
+
try { ws.binaryType = 'arraybuffer'; } catch { /* read-only on some sockets */ }
|
|
541
|
+
opened = await new Promise((resolve) => {
|
|
542
|
+
if (ws.readyState === 1) return resolve(true);
|
|
543
|
+
ws.addEventListener('open', () => resolve(true), { once: true });
|
|
544
|
+
ws.addEventListener('error', () => resolve(false), { once: true });
|
|
545
|
+
ws.addEventListener('close', () => resolve(false), { once: true });
|
|
546
|
+
});
|
|
547
|
+
if (opened) {
|
|
548
|
+
ws.addEventListener('message', () => {
|
|
549
|
+
if (slot.paired) return;
|
|
550
|
+
slot.paired = true;
|
|
551
|
+
set.delete(slot);
|
|
552
|
+
this.#slotAttempts.delete(relay);
|
|
553
|
+
void this.#fillSlots(relay);
|
|
554
|
+
});
|
|
555
|
+
ws.addEventListener('close', () => {
|
|
556
|
+
if (slot.paired) return;
|
|
557
|
+
set.delete(slot);
|
|
558
|
+
this.#retrySlots(relay);
|
|
559
|
+
});
|
|
560
|
+
void this.#host.accept(ws).catch((e) => this.#onLog(`accept failed: ${e?.message ?? e}`));
|
|
561
|
+
}
|
|
562
|
+
} catch (e) {
|
|
563
|
+
this.#onLog(`could not open a host half at ${relay}: ${e?.message ?? e}`);
|
|
564
|
+
}
|
|
565
|
+
if (!opened) {
|
|
566
|
+
set.delete(slot);
|
|
567
|
+
this.#retrySlots(relay);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
#retrySlots(relay) {
|
|
572
|
+
if (this.#closed || this.#slotRetry.has(relay)) return;
|
|
573
|
+
const prev = this.#slotAttempts.get(relay) ?? 0;
|
|
574
|
+
const delay = Math.min(this.#reconnect.baseMs * 2 ** prev, this.#reconnect.maxMs);
|
|
575
|
+
this.#slotAttempts.set(relay, prev + 1);
|
|
576
|
+
const t = setTimeout(() => {
|
|
577
|
+
this.#slotRetry.delete(relay);
|
|
578
|
+
void this.#fillSlots(relay);
|
|
579
|
+
}, delay);
|
|
580
|
+
t.unref?.();
|
|
581
|
+
this.#slotRetry.set(relay, t);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// -- Serving (the listening side's link) --------------------------------------
|
|
585
|
+
|
|
586
|
+
async #serve(duplex, who) {
|
|
587
|
+
let podId;
|
|
588
|
+
try { podId = fingerprintToPodId(who.fingerprint); } catch { duplex.destroy?.('bad identity'); return; }
|
|
589
|
+
if (who.username !== usernameForPodId(podId)) { duplex.destroy?.('identity mismatch'); return; }
|
|
590
|
+
const conn = this.#newConn({ role: 'host', podId, initiatorPodId: podId, duplex });
|
|
591
|
+
const done = new Promise((resolve) => { conn.onEnd = resolve; });
|
|
592
|
+
this.#register(conn);
|
|
593
|
+
await done;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// -- Dialling (the reaching side's link) --------------------------------------
|
|
597
|
+
|
|
598
|
+
#dial(podId) {
|
|
599
|
+
const existing = this.#dials.get(podId);
|
|
600
|
+
if (existing) return existing;
|
|
601
|
+
const p = this.#doDial(podId).finally(() => { if (this.#dials.get(podId) === p) this.#dials.delete(podId); });
|
|
602
|
+
this.#dials.set(podId, p);
|
|
603
|
+
return p;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
async #doDial(podId) {
|
|
607
|
+
if (this.#beforeDial) await this.#beforeDial({ podId });
|
|
608
|
+
if (!this.#relays.length) throw new WshLinkError('WSH_UNREACHABLE', 'no relay configured', { podId });
|
|
609
|
+
let last = null;
|
|
610
|
+
for (const relay of this.#relays) {
|
|
611
|
+
try {
|
|
612
|
+
const conn = await this.#dialRelay(relay, podId);
|
|
613
|
+
this.#register(conn);
|
|
614
|
+
return;
|
|
615
|
+
} catch (err) {
|
|
616
|
+
last = err;
|
|
617
|
+
if (FATAL.has(err.code)) throw err;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
throw last;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async #dialRelay(relay, podId) {
|
|
624
|
+
const cred = await this.#credReady;
|
|
625
|
+
const rid = await rendezvousId(podId);
|
|
626
|
+
const { WshClient, WebSocketTransport } = await loadClient();
|
|
627
|
+
const hub = this;
|
|
628
|
+
let socket = null;
|
|
629
|
+
class PipeSocket {
|
|
630
|
+
constructor() {
|
|
631
|
+
socket = hub.#openSocket('operator', rid, relay);
|
|
632
|
+
return socket;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const client = new WshClient({
|
|
636
|
+
transportFactories: {
|
|
637
|
+
ws: () => new WebSocketTransport({ WebSocket: PipeSocket }),
|
|
638
|
+
wt: () => { throw new Error('WebTransport is not used for mesh links'); },
|
|
639
|
+
},
|
|
640
|
+
...this.#keepAlive,
|
|
641
|
+
});
|
|
642
|
+
const conn = this.#newConn({ role: 'operator', podId, initiatorPodId: cred.podId, client });
|
|
643
|
+
client.onError = (err) => {
|
|
644
|
+
if (/seal|did not open|decrypt/i.test(String(err?.message ?? err))) conn.endReason = 'seal-failed';
|
|
645
|
+
conn.lastError = err;
|
|
646
|
+
};
|
|
647
|
+
client.onClose = () => this.#end(conn, conn.endReason ?? 'transport');
|
|
648
|
+
|
|
649
|
+
const attempt = (async () => {
|
|
650
|
+
await client.connect(pipeUrl(relay, rid, 'operator'), {
|
|
651
|
+
username: usernameForPodId(cred.podId),
|
|
652
|
+
...(cred.keyPair ? { keyPair: cred.keyPair } : { signer: cred.signer }),
|
|
653
|
+
transport: 'ws',
|
|
654
|
+
expectHostKey: podIdToFingerprint(podId),
|
|
655
|
+
sealSession: true,
|
|
656
|
+
requireChannelBinding: true,
|
|
657
|
+
timeout: this.#connectTimeoutMs,
|
|
658
|
+
});
|
|
659
|
+
if (!client.sessionSealed) throw new WshLinkError('WSH_NOT_SEALED', `the session with ${podId} is not sealed`, { podId, reason: 'not-sealed' });
|
|
660
|
+
conn.duplex = await client.openEndpoint(ENDPOINT);
|
|
661
|
+
})();
|
|
662
|
+
let timer;
|
|
663
|
+
const timeout = new Promise((_, reject) => {
|
|
664
|
+
timer = setTimeout(() => reject(new WshLinkError('WSH_UNREACHABLE', `${podId} did not answer within ${this.#connectTimeoutMs} ms`, { podId })), this.#connectTimeoutMs);
|
|
665
|
+
});
|
|
666
|
+
try {
|
|
667
|
+
await Promise.race([attempt, timeout]);
|
|
668
|
+
} catch (err) {
|
|
669
|
+
attempt.catch(() => {});
|
|
670
|
+
client.onClose = null;
|
|
671
|
+
conn.ended = true;
|
|
672
|
+
client.disconnect().catch(() => {});
|
|
673
|
+
try { socket?.close(); } catch { /* already closed */ }
|
|
674
|
+
throw mapDialError(err, podId);
|
|
675
|
+
} finally {
|
|
676
|
+
clearTimeout(timer);
|
|
677
|
+
}
|
|
678
|
+
return conn;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// -- Connections ----------------------------------------------------------------
|
|
682
|
+
|
|
683
|
+
#newConn({ role, podId, initiatorPodId, duplex = null, client = null }) {
|
|
684
|
+
return {
|
|
685
|
+
id: this.#nextConnId++, role, podId, initiatorPodId, duplex, client, writer: null, reader: null,
|
|
686
|
+
queue: [], queued: 0, pumping: false, idle: [], ended: false, superseded: false, pause: null, endReason: null, onEnd: null, lastError: null,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** Make a freshly authenticated connection the peer's link, or the loser of the tie-break. */
|
|
691
|
+
#register(conn) {
|
|
692
|
+
let entry = this.#peers.get(conn.podId);
|
|
693
|
+
if (!entry) this.#peers.set(conn.podId, (entry = { active: null, all: new Set() }));
|
|
694
|
+
conn.writer = conn.duplex.writable.getWriter();
|
|
695
|
+
conn.reader = conn.duplex.readable.getReader();
|
|
696
|
+
entry.all.add(conn);
|
|
697
|
+
this.#stats.linksEstablished++;
|
|
698
|
+
const current = entry.active;
|
|
699
|
+
if (!current) {
|
|
700
|
+
entry.active = conn;
|
|
701
|
+
const w = this.#wanted.get(conn.podId);
|
|
702
|
+
if (w) w.attempts = 0;
|
|
703
|
+
this.#emit('peer-up', { podId: conn.podId, initiator: conn.role === 'operator' ? 'local' : 'remote' });
|
|
704
|
+
} else {
|
|
705
|
+
let winner;
|
|
706
|
+
if (conn.initiatorPodId === current.initiatorPodId) winner = conn; // a redial racing a link not yet noticed as dead
|
|
707
|
+
else winner = initiatorWins(conn.initiatorPodId, current.initiatorPodId) ? conn : current;
|
|
708
|
+
const loser = winner === conn ? current : conn;
|
|
709
|
+
entry.active = winner;
|
|
710
|
+
void this.#supersede(loser);
|
|
711
|
+
}
|
|
712
|
+
void this.#readLoop(conn);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async #supersede(conn) {
|
|
716
|
+
if (conn.superseded || conn.ended) return;
|
|
717
|
+
conn.superseded = true;
|
|
718
|
+
this.#stats.superseded++;
|
|
719
|
+
const grace = setTimeout(() => this.#end(conn, 'superseded'), this.#supersedeGraceMs);
|
|
720
|
+
grace.unref?.();
|
|
721
|
+
conn.graceTimer = grace;
|
|
722
|
+
try {
|
|
723
|
+
// Let what is already queued go out, then half close: the peer sees the end and finishes.
|
|
724
|
+
await new Promise((resolve) => {
|
|
725
|
+
if (!conn.queue.length && !conn.pumping) resolve();
|
|
726
|
+
else conn.idle.push(resolve);
|
|
727
|
+
});
|
|
728
|
+
if (!conn.ended) await conn.writer.close();
|
|
729
|
+
} catch { /* the link may already be gone */ }
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
async #readLoop(conn) {
|
|
733
|
+
const decoder = new FrameDecoder({ maxFrameBytes: this.#maxFrame });
|
|
734
|
+
let reason = conn.endReason ?? 'closed';
|
|
735
|
+
let error = null;
|
|
736
|
+
try {
|
|
737
|
+
for (;;) {
|
|
738
|
+
if (conn.pause) await conn.pause.promise;
|
|
739
|
+
if (conn.ended) return;
|
|
740
|
+
const { value, done } = await conn.reader.read();
|
|
741
|
+
if (done) break;
|
|
742
|
+
for (const frame of decoder.push(value)) {
|
|
743
|
+
if (conn.pause) await conn.pause.promise; // paused while this read was in flight: hold the frame
|
|
744
|
+
if (conn.ended) return;
|
|
745
|
+
this.#stats.messagesIn++;
|
|
746
|
+
this.#stats.bytesIn += typeof frame === 'string' ? frame.length : frame.length;
|
|
747
|
+
const handlers = this.#emit('message', { from: conn.podId, data: frame });
|
|
748
|
+
const pending = handlers.filter((h) => h && typeof h.then === 'function');
|
|
749
|
+
if (pending.length) await Promise.allSettled(pending);
|
|
750
|
+
if (conn.ended) return;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
decoder.end();
|
|
754
|
+
} catch (err) {
|
|
755
|
+
if (err instanceof WshFrameError) {
|
|
756
|
+
reason = err.code === 'WSH_FRAME_TOO_LARGE' ? 'frame-too-large' : 'bad-frame';
|
|
757
|
+
error = new WshLinkError(err.code, err.message, { podId: conn.podId, cause: err });
|
|
758
|
+
this.#stats.dropped++;
|
|
759
|
+
this.#emit('dropped', { from: conn.podId, reason });
|
|
760
|
+
this.#fail(error, { podId: conn.podId });
|
|
761
|
+
} else {
|
|
762
|
+
reason = conn.endReason ?? 'transport';
|
|
763
|
+
error = err;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
this.#end(conn, conn.endReason ?? reason, error);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
#enqueue(conn, frame) {
|
|
770
|
+
if (conn.ended) return Promise.reject(new WshLinkError('WSH_CLOSED', `the link to ${conn.podId} is closed`, { podId: conn.podId }));
|
|
771
|
+
if (conn.queued + frame.length > this.#maxQueued) {
|
|
772
|
+
return Promise.reject(new WshLinkError('WSH_BACKPRESSURE', `the send queue to ${conn.podId} is full (${this.#maxQueued} bytes); the peer is not reading`, { podId: conn.podId }));
|
|
773
|
+
}
|
|
774
|
+
return new Promise((resolve, reject) => {
|
|
775
|
+
conn.queue.push({ frame, resolve, reject });
|
|
776
|
+
conn.queued += frame.length;
|
|
777
|
+
this.#pump(conn);
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
#pump(conn) {
|
|
782
|
+
if (conn.pumping) return;
|
|
783
|
+
conn.pumping = true;
|
|
784
|
+
(async () => {
|
|
785
|
+
try {
|
|
786
|
+
while (conn.queue.length && !conn.ended) {
|
|
787
|
+
const item = conn.queue[0];
|
|
788
|
+
await conn.writer.write(item.frame);
|
|
789
|
+
conn.queue.shift();
|
|
790
|
+
conn.queued -= item.frame.length;
|
|
791
|
+
this.#stats.messagesOut++;
|
|
792
|
+
this.#stats.bytesOut += item.frame.length;
|
|
793
|
+
item.resolve();
|
|
794
|
+
}
|
|
795
|
+
} catch (err) {
|
|
796
|
+
this.#end(conn, conn.endReason ?? 'transport', err);
|
|
797
|
+
} finally {
|
|
798
|
+
conn.pumping = false;
|
|
799
|
+
for (const resolve of conn.idle.splice(0)) resolve();
|
|
800
|
+
}
|
|
801
|
+
})();
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** A connection is over. */
|
|
805
|
+
#end(conn, reason, error = null) {
|
|
806
|
+
if (conn.ended) return;
|
|
807
|
+
conn.ended = true;
|
|
808
|
+
clearTimeout(conn.graceTimer);
|
|
809
|
+
if (reason === 'seal-failed' && !(error instanceof WshLinkError)) {
|
|
810
|
+
error = new WshLinkError('WSH_SEAL_FAILED', `a sealed frame from ${conn.podId} did not open; the link was ended`, { podId: conn.podId, cause: error ?? undefined });
|
|
811
|
+
if (!conn.superseded) this.#fail(error, { podId: conn.podId });
|
|
812
|
+
}
|
|
813
|
+
const closed = new WshLinkError('WSH_CLOSED', `the link to ${conn.podId} closed (${reason})`, { podId: conn.podId });
|
|
814
|
+
for (const item of conn.queue) item.reject(closed);
|
|
815
|
+
conn.queue = [];
|
|
816
|
+
conn.queued = 0;
|
|
817
|
+
if (conn.pause) { conn.pause.resolve(); conn.pause = null; }
|
|
818
|
+
try { conn.reader?.cancel().catch(() => {}); } catch { /* ignore */ }
|
|
819
|
+
try { conn.duplex?.destroy?.(reason); } catch { /* ignore */ }
|
|
820
|
+
if (conn.client) { conn.client.onClose = null; conn.client.disconnect().catch(() => {}); }
|
|
821
|
+
conn.onEnd?.();
|
|
822
|
+
const entry = this.#peers.get(conn.podId);
|
|
823
|
+
if (!entry) return;
|
|
824
|
+
entry.all.delete(conn);
|
|
825
|
+
if (conn.superseded || entry.active !== conn) {
|
|
826
|
+
if (!entry.all.size && !entry.active) this.#peers.delete(conn.podId);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
void this.#afterActiveEnded(conn, entry, reason, error);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async #afterActiveEnded(conn, entry, reason, error) {
|
|
833
|
+
const alt = [...entry.all].find((c) => !c.ended && !c.superseded);
|
|
834
|
+
if (alt) { entry.active = alt; return; }
|
|
835
|
+
entry.active = null;
|
|
836
|
+
const dial = this.#dials.get(conn.podId);
|
|
837
|
+
if (dial) {
|
|
838
|
+
// A dial is in flight: if it lands, this was a hand over, not a departure.
|
|
839
|
+
await dial.catch(() => {});
|
|
840
|
+
if (entry.active) return;
|
|
841
|
+
}
|
|
842
|
+
if (this.#peers.get(conn.podId) === entry && !entry.all.size) this.#peers.delete(conn.podId);
|
|
843
|
+
const detail = { podId: conn.podId, reason };
|
|
844
|
+
if (error) detail.error = error;
|
|
845
|
+
this.#emit('peer-down', detail);
|
|
846
|
+
if (reason !== 'local-close' && !this.#closed) this.#scheduleRedial(conn.podId);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// -- Redial -----------------------------------------------------------------------
|
|
850
|
+
|
|
851
|
+
#want(podId) { if (!this.#wanted.has(podId)) this.#wanted.set(podId, { attempts: 0, timer: null }); }
|
|
852
|
+
|
|
853
|
+
#unwant(podId) {
|
|
854
|
+
const w = this.#wanted.get(podId);
|
|
855
|
+
if (w) { clearTimeout(w.timer); this.#wanted.delete(podId); }
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
#scheduleRedial(podId) {
|
|
859
|
+
const w = this.#wanted.get(podId);
|
|
860
|
+
if (!w || w.timer || this.#closed) return;
|
|
861
|
+
if (w.attempts >= this.#reconnect.maxAttempts) return;
|
|
862
|
+
const delay = Math.min(this.#reconnect.baseMs * 2 ** w.attempts, this.#reconnect.maxMs);
|
|
863
|
+
w.attempts++;
|
|
864
|
+
w.timer = setTimeout(async () => {
|
|
865
|
+
w.timer = null;
|
|
866
|
+
if (this.#closed || !this.#wanted.has(podId) || this.isConnected(podId)) return;
|
|
867
|
+
try {
|
|
868
|
+
await this.#dial(podId);
|
|
869
|
+
} catch (err) {
|
|
870
|
+
if (FATAL.has(err.code)) { this.#unwant(podId); this.#fail(err, { podId }); } else this.#scheduleRedial(podId);
|
|
871
|
+
}
|
|
872
|
+
}, delay);
|
|
873
|
+
w.timer.unref?.();
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// ---------------------------------------------------------------------------
|
|
878
|
+
// WshLink: a transport object for one peer
|
|
879
|
+
// ---------------------------------------------------------------------------
|
|
880
|
+
|
|
881
|
+
const LINK_EVENTS = ['open', 'message', 'close', 'error'];
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* One peer's link shaped like the other mesh transports: `type`, `state`,
|
|
885
|
+
* `connected`, `connect()`, `send()`, `close()`, `on(event, cb)`, plus
|
|
886
|
+
* `onMessage` / `onClose` / `onError` for `PeerNode`. It is a view of the hub's
|
|
887
|
+
* link to that peer, so a redial or a tie-break switch is invisible to it.
|
|
888
|
+
*/
|
|
889
|
+
export class WshLink {
|
|
890
|
+
#hub;
|
|
891
|
+
#peer;
|
|
892
|
+
#cbs = { open: [], message: [], close: [], error: [] };
|
|
893
|
+
#unsubs = [];
|
|
894
|
+
#closed = false;
|
|
895
|
+
#connecting = false;
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* @param {WshPeerLinks} hub
|
|
899
|
+
* @param {string} peerPodId
|
|
900
|
+
*/
|
|
901
|
+
constructor(hub, peerPodId) {
|
|
902
|
+
if (!(hub instanceof WshPeerLinks)) throw new TypeError('WshLink needs the WshPeerLinks it belongs to');
|
|
903
|
+
podIdToFingerprint(peerPodId);
|
|
904
|
+
this.#hub = hub;
|
|
905
|
+
this.#peer = peerPodId;
|
|
906
|
+
this.#unsubs.push(
|
|
907
|
+
hub.on('message', ({ from, data }) => {
|
|
908
|
+
if (from !== this.#peer) return undefined;
|
|
909
|
+
const out = this.#fire('message', data);
|
|
910
|
+
const pending = out.filter((r) => r && typeof r.then === 'function');
|
|
911
|
+
return pending.length ? Promise.allSettled(pending) : undefined;
|
|
912
|
+
}),
|
|
913
|
+
hub.on('peer-up', ({ podId }) => { if (podId === this.#peer) this.#fire('open'); }),
|
|
914
|
+
hub.on('peer-down', ({ podId, reason, error }) => { if (podId === this.#peer) this.#fire('close', { reason, error }); }),
|
|
915
|
+
hub.on('error', ({ error, podId }) => { if (podId === this.#peer) this.#fire('error', error); }),
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
get type() { return 'wsh'; }
|
|
920
|
+
get peerPodId() { return this.#peer; }
|
|
921
|
+
get sealed() { return true; }
|
|
922
|
+
get fingerprint() { return podIdToFingerprint(this.#peer); }
|
|
923
|
+
get latency() { return 0; }
|
|
924
|
+
get connected() { return !this.#closed && this.#hub.isConnected(this.#peer); }
|
|
925
|
+
get state() {
|
|
926
|
+
if (this.#closed) return 'closed';
|
|
927
|
+
if (this.#hub.isConnected(this.#peer)) return 'connected';
|
|
928
|
+
return this.#connecting ? 'connecting' : 'disconnected';
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
async connect() {
|
|
932
|
+
if (this.#closed) throw new WshLinkError('WSH_CLOSED', 'this link is closed', { podId: this.#peer });
|
|
933
|
+
this.#connecting = true;
|
|
934
|
+
try { await this.#hub.connect(this.#peer); } finally { this.#connecting = false; }
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/** @returns {Promise<void>} resolves when the endpoint accepted the frame */
|
|
938
|
+
send(data) {
|
|
939
|
+
if (this.#closed) return Promise.reject(new WshLinkError('WSH_CLOSED', 'this link is closed', { podId: this.#peer }));
|
|
940
|
+
return this.#hub.send(this.#peer, data);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
async close() {
|
|
944
|
+
if (this.#closed) return;
|
|
945
|
+
this.#closed = true;
|
|
946
|
+
this.#hub.disconnect(this.#peer);
|
|
947
|
+
for (const off of this.#unsubs) off();
|
|
948
|
+
this.#unsubs = [];
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** Stop listening to the hub without closing the peer's link. */
|
|
952
|
+
dispose() {
|
|
953
|
+
for (const off of this.#unsubs) off();
|
|
954
|
+
this.#unsubs = [];
|
|
955
|
+
this.#closed = true;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
on(event, cb) {
|
|
959
|
+
if (!LINK_EVENTS.includes(event)) throw new Error(`Unknown event: ${event}`);
|
|
960
|
+
this.#cbs[event].push(cb);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
onMessage(cb) { this.on('message', cb); }
|
|
964
|
+
onClose(cb) { this.on('close', cb); }
|
|
965
|
+
onError(cb) { this.on('error', cb); }
|
|
966
|
+
|
|
967
|
+
getStats() { return this.#hub.getStats(); }
|
|
968
|
+
|
|
969
|
+
toJSON() {
|
|
970
|
+
return { type: 'wsh', state: this.state, peerPodId: this.#peer, sealed: true };
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
#fire(event, data) {
|
|
974
|
+
const out = [];
|
|
975
|
+
for (const cb of [...this.#cbs[event]]) {
|
|
976
|
+
try { out.push(cb(data)); } catch { /* listener errors do not propagate */ }
|
|
977
|
+
}
|
|
978
|
+
return out;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* A `MeshTransportNegotiator` adapter factory for `'wsh'`:
|
|
984
|
+
* `negotiator.registerAdapter('wsh', createWshTransportFactory(links))`.
|
|
985
|
+
* By the convention `createWebRTCTransportFactory` uses, the endpoint is the
|
|
986
|
+
* remote peer's pod id. Wsh is never tried unless the negotiator is told to:
|
|
987
|
+
* put `'wsh'` in its `preferenceOrder` or pass `require: 'wsh'`.
|
|
988
|
+
*
|
|
989
|
+
* @param {WshPeerLinks} links
|
|
990
|
+
* @returns {(endpoint: string, auth?: object) => Promise<WshLink>}
|
|
991
|
+
*/
|
|
992
|
+
export function createWshTransportFactory(links) {
|
|
993
|
+
if (!(links instanceof WshPeerLinks)) throw new TypeError('createWshTransportFactory needs a WshPeerLinks');
|
|
994
|
+
return async (endpoint) => {
|
|
995
|
+
const podId = typeof endpoint === 'string' ? endpoint : endpoint?.podId;
|
|
996
|
+
const link = new WshLink(links, podId);
|
|
997
|
+
try {
|
|
998
|
+
await link.connect();
|
|
999
|
+
} catch (err) {
|
|
1000
|
+
link.dispose();
|
|
1001
|
+
throw err;
|
|
1002
|
+
}
|
|
1003
|
+
return link;
|
|
1004
|
+
};
|
|
1005
|
+
}
|