@dimchansky/meshpost 0.3.0 → 0.4.1
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 +274 -109
- package/dist/channel.d.ts +37 -2
- package/dist/channel.js +226 -12
- package/dist/combine.js +15 -0
- package/dist/crypto.d.ts +34 -0
- package/dist/crypto.js +158 -0
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +264 -0
- package/dist/index.d.ts +16 -6
- package/dist/index.js +7 -2
- package/dist/mqtt.d.ts +9 -1
- package/dist/mqtt.js +95 -87
- package/dist/nostr.d.ts +27 -0
- package/dist/nostr.js +1008 -0
- package/dist/public.d.ts +52 -0
- package/dist/public.js +133 -0
- package/dist/room.d.ts +37 -13
- package/dist/room.js +584 -62
- package/dist/rpc.d.ts +48 -0
- package/dist/rpc.js +382 -0
- package/dist/signaling.d.ts +4 -8
- package/dist/signaling.js +10 -2
- package/dist/state.d.ts +56 -0
- package/dist/state.js +305 -0
- package/dist/voice.d.ts +28 -1
- package/dist/voice.js +349 -27
- package/dist/ws.d.ts +46 -2
- package/dist/ws.js +307 -33
- package/docs/behavior.md +102 -56
- package/package.json +71 -2
package/dist/ws.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
|
+
import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
|
|
1
2
|
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
3
|
+
const wsOpen = 1;
|
|
4
|
+
const defaultOptionalHandshakeTimeoutMs = 4_000;
|
|
2
5
|
const maxFrameBytes = 128 * 1024;
|
|
3
6
|
const maxPeers = 256;
|
|
7
|
+
const maxEncryptQueueDepth = 128;
|
|
8
|
+
const maxDecryptQueueDepth = 64;
|
|
4
9
|
const defaultHandshakeTimeoutMs = 10_000;
|
|
5
10
|
const defaultPingIntervalMs = 25_000;
|
|
11
|
+
const insecureWsMessage = 'Password encryption requires a secure context (crypto.subtle); pass encrypt: false for plaintext LAN testing';
|
|
6
12
|
/**
|
|
7
13
|
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
8
|
-
*
|
|
14
|
+
* When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
|
|
9
15
|
*/
|
|
10
16
|
export function wsSignaling(url, options = {}) {
|
|
11
17
|
let parsed;
|
|
@@ -32,18 +38,62 @@ export function wsSignaling(url, options = {}) {
|
|
|
32
38
|
pingIntervalMs > 2_147_483_647) {
|
|
33
39
|
throw new RangeError('Invalid WebSocket ping interval');
|
|
34
40
|
}
|
|
41
|
+
if (options.encrypt !== undefined && typeof options.encrypt !== 'boolean') {
|
|
42
|
+
throw new TypeError('Invalid encrypt option');
|
|
43
|
+
}
|
|
44
|
+
if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
|
|
45
|
+
throw new TypeError('Invalid privateTopic option');
|
|
46
|
+
}
|
|
47
|
+
if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
|
|
48
|
+
throw new TypeError('Invalid WebSocket constructor');
|
|
49
|
+
}
|
|
35
50
|
return (discovery) => {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
51
|
+
const WsCtor = options.WebSocket ?? globalThis.WebSocket;
|
|
52
|
+
if (typeof WsCtor !== 'function') {
|
|
53
|
+
throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
|
|
54
|
+
}
|
|
55
|
+
const password = discovery.password;
|
|
56
|
+
const encrypt = options.encrypt ?? true;
|
|
57
|
+
const privateTopic = options.privateTopic ?? false;
|
|
58
|
+
if (privateTopic && password === undefined) {
|
|
59
|
+
throw new TypeError('privateTopic requires a room password');
|
|
60
|
+
}
|
|
61
|
+
if (privateTopic && !encrypt) {
|
|
62
|
+
throw new Error('privateTopic requires encrypt: true');
|
|
63
|
+
}
|
|
64
|
+
const useEncryption = password !== undefined && encrypt;
|
|
65
|
+
if (password !== undefined) {
|
|
66
|
+
if (typeof password !== 'string' || password.length === 0) {
|
|
67
|
+
throw new TypeError('Invalid password');
|
|
68
|
+
}
|
|
69
|
+
if (useEncryption && !globalThis.crypto?.subtle) {
|
|
70
|
+
throw new Error(insecureWsMessage);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const baseScope = discovery.appId + ':' + discovery.room;
|
|
74
|
+
let roomKey = privateTopic
|
|
75
|
+
? ''
|
|
76
|
+
: namespaceHash(baseScope + (!useEncryption && password !== undefined ? ':' + password : ''));
|
|
40
77
|
const knownPeers = new Set();
|
|
78
|
+
const replayGuard = createReplayGuard();
|
|
41
79
|
let ws;
|
|
42
80
|
let closed = false;
|
|
43
81
|
let reportedOnline = false;
|
|
44
82
|
let reportedOffline = false;
|
|
45
83
|
let awaitingPong = false;
|
|
46
84
|
let attempt = 0;
|
|
85
|
+
let msgSeq = 0;
|
|
86
|
+
let pendingSendCount = 0;
|
|
87
|
+
let pendingSignalRecvCount = 0;
|
|
88
|
+
let pendingTotalRecvCount = 0;
|
|
89
|
+
let sendChain = Promise.resolve();
|
|
90
|
+
let recvChain = Promise.resolve();
|
|
91
|
+
let lastDecryptErrorAt = -Infinity;
|
|
92
|
+
let lastClockSkewErrorAt = -Infinity;
|
|
93
|
+
let resolvedKey;
|
|
94
|
+
const keysPromise = useEncryption
|
|
95
|
+
? deriveSignalingKeys(password, baseScope, insecureWsMessage)
|
|
96
|
+
: undefined;
|
|
47
97
|
let handshakeTimer;
|
|
48
98
|
let pingTimer;
|
|
49
99
|
let reconnectTimer;
|
|
@@ -53,8 +103,45 @@ export function wsSignaling(url, options = {}) {
|
|
|
53
103
|
clearInterval(pingTimer);
|
|
54
104
|
pingTimer = undefined;
|
|
55
105
|
};
|
|
106
|
+
const emitDecryptFailed = (message) => {
|
|
107
|
+
const now = Date.now();
|
|
108
|
+
if (now - lastDecryptErrorAt >= errorCooldownMs) {
|
|
109
|
+
lastDecryptErrorAt = now;
|
|
110
|
+
discovery.error?.('decrypt-failed', message);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const emitClockSkew = () => {
|
|
114
|
+
const now = Date.now();
|
|
115
|
+
if (now - lastClockSkewErrorAt >= errorCooldownMs) {
|
|
116
|
+
lastClockSkewErrorAt = now;
|
|
117
|
+
discovery.error?.('clock-skew', 'WebSocket signaling message rejected due to system clock skew (>60s)');
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const applyRoster = (peers) => {
|
|
121
|
+
knownPeers.clear();
|
|
122
|
+
for (const id of peers) {
|
|
123
|
+
if (isUuid(id) && id !== discovery.self) {
|
|
124
|
+
knownPeers.add(id);
|
|
125
|
+
if (knownPeers.size >= maxPeers)
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
discovery.roster([...knownPeers]);
|
|
130
|
+
};
|
|
131
|
+
const deliverSignal = (from, signal) => {
|
|
132
|
+
if (!knownPeers.has(from)) {
|
|
133
|
+
if (knownPeers.size >= maxPeers) {
|
|
134
|
+
const oldest = knownPeers.values().next().value;
|
|
135
|
+
if (oldest !== undefined)
|
|
136
|
+
knownPeers.delete(oldest);
|
|
137
|
+
}
|
|
138
|
+
knownPeers.add(from);
|
|
139
|
+
discovery.roster([...knownPeers]);
|
|
140
|
+
}
|
|
141
|
+
discovery.receive(from, signal);
|
|
142
|
+
};
|
|
56
143
|
const sendJson = (payload) => {
|
|
57
|
-
if (closed || !ws || ws.readyState !==
|
|
144
|
+
if (closed || !ws || ws.readyState !== wsOpen)
|
|
58
145
|
return false;
|
|
59
146
|
try {
|
|
60
147
|
ws.send(JSON.stringify(payload));
|
|
@@ -85,12 +172,16 @@ export function wsSignaling(url, options = {}) {
|
|
|
85
172
|
}, delay);
|
|
86
173
|
};
|
|
87
174
|
const connect = () => {
|
|
88
|
-
if (closed)
|
|
175
|
+
if (closed || !roomKey)
|
|
89
176
|
return;
|
|
90
177
|
clearTimers();
|
|
91
178
|
let socket;
|
|
92
179
|
try {
|
|
93
|
-
|
|
180
|
+
const targetUrl = new URL(normalizedUrl);
|
|
181
|
+
if (!targetUrl.searchParams.has('room')) {
|
|
182
|
+
targetUrl.searchParams.set('room', roomKey);
|
|
183
|
+
}
|
|
184
|
+
socket = new WsCtor(targetUrl.toString());
|
|
94
185
|
}
|
|
95
186
|
catch {
|
|
96
187
|
reportOffline('WebSocket signaling connection failed');
|
|
@@ -142,6 +233,8 @@ export function wsSignaling(url, options = {}) {
|
|
|
142
233
|
pingTimer = setInterval(() => {
|
|
143
234
|
if (closed || ws !== socket)
|
|
144
235
|
return;
|
|
236
|
+
if (useEncryption)
|
|
237
|
+
replayGuard.prune();
|
|
145
238
|
if (awaitingPong) {
|
|
146
239
|
try {
|
|
147
240
|
socket.close();
|
|
@@ -183,31 +276,88 @@ export function wsSignaling(url, options = {}) {
|
|
|
183
276
|
awaitingPong = false;
|
|
184
277
|
if (msg.type === 'pong')
|
|
185
278
|
return;
|
|
186
|
-
if (
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
279
|
+
if (!useEncryption) {
|
|
280
|
+
if (msg.type === 'roster' && Array.isArray(msg.peers)) {
|
|
281
|
+
applyRoster(msg.peers);
|
|
282
|
+
}
|
|
283
|
+
else if (msg.type === 'signal' &&
|
|
284
|
+
isUuid(msg.from) &&
|
|
285
|
+
msg.from !== discovery.self &&
|
|
286
|
+
isSignal(msg.signal)) {
|
|
287
|
+
deliverSignal(msg.from, msg.signal);
|
|
194
288
|
}
|
|
195
|
-
|
|
289
|
+
return;
|
|
196
290
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
291
|
+
if (msg.type === 'roster' && Array.isArray(msg.peers)) {
|
|
292
|
+
if (pendingTotalRecvCount >= maxDecryptQueueDepth + 8)
|
|
293
|
+
return;
|
|
294
|
+
const peersSnapshot = [...msg.peers];
|
|
295
|
+
const targetSocket = socket;
|
|
296
|
+
pendingTotalRecvCount++;
|
|
297
|
+
recvChain = recvChain
|
|
298
|
+
.then(() => {
|
|
299
|
+
if (closed || ws !== targetSocket)
|
|
300
|
+
return;
|
|
301
|
+
applyRoster(peersSnapshot);
|
|
302
|
+
})
|
|
303
|
+
.catch(() => {
|
|
304
|
+
// Keep receive chain alive across errors.
|
|
305
|
+
})
|
|
306
|
+
.finally(() => {
|
|
307
|
+
pendingTotalRecvCount--;
|
|
308
|
+
});
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (msg.type === 'signal' && isUuid(msg.from) && msg.from !== discovery.self) {
|
|
312
|
+
if (msg.box === undefined) {
|
|
313
|
+
if (msg.signal !== undefined) {
|
|
314
|
+
emitDecryptFailed('Received unencrypted WebSocket signaling message in password-protected room');
|
|
206
315
|
}
|
|
207
|
-
|
|
208
|
-
discovery.roster([...knownPeers]);
|
|
316
|
+
return;
|
|
209
317
|
}
|
|
210
|
-
|
|
318
|
+
if (msg.signal !== undefined)
|
|
319
|
+
return;
|
|
320
|
+
const boxed = fromBase64Url(msg.box);
|
|
321
|
+
if (!boxed)
|
|
322
|
+
return;
|
|
323
|
+
if (pendingSignalRecvCount >= maxDecryptQueueDepth)
|
|
324
|
+
return;
|
|
325
|
+
const from = msg.from;
|
|
326
|
+
const targetSocket = socket;
|
|
327
|
+
pendingSignalRecvCount++;
|
|
328
|
+
pendingTotalRecvCount++;
|
|
329
|
+
recvChain = recvChain
|
|
330
|
+
.then(async () => {
|
|
331
|
+
if (closed || ws !== targetSocket)
|
|
332
|
+
return;
|
|
333
|
+
const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
|
|
334
|
+
if (!key || closed || ws !== targetSocket)
|
|
335
|
+
return;
|
|
336
|
+
const env = await openEnvelope(key, boxed, 'meshpost/1/ws:' + roomKey + ':' + from + ':' + discovery.self);
|
|
337
|
+
if (closed || ws !== targetSocket)
|
|
338
|
+
return;
|
|
339
|
+
if (!env) {
|
|
340
|
+
emitDecryptFailed('Failed to decrypt WebSocket signaling message');
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const check = replayGuard.checkAuthenticated(from, env);
|
|
344
|
+
if (check === 'clock-skew') {
|
|
345
|
+
emitClockSkew();
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (check !== 'ok')
|
|
349
|
+
return;
|
|
350
|
+
if (!isSignal(env.signal))
|
|
351
|
+
return;
|
|
352
|
+
deliverSignal(from, env.signal);
|
|
353
|
+
})
|
|
354
|
+
.catch(() => {
|
|
355
|
+
// Keep receive chain alive across errors.
|
|
356
|
+
})
|
|
357
|
+
.finally(() => {
|
|
358
|
+
pendingSignalRecvCount--;
|
|
359
|
+
pendingTotalRecvCount--;
|
|
360
|
+
});
|
|
211
361
|
}
|
|
212
362
|
};
|
|
213
363
|
socket.onerror = () => {
|
|
@@ -234,12 +384,78 @@ export function wsSignaling(url, options = {}) {
|
|
|
234
384
|
scheduleReconnect();
|
|
235
385
|
};
|
|
236
386
|
};
|
|
237
|
-
|
|
238
|
-
|
|
387
|
+
if (keysPromise && privateTopic) {
|
|
388
|
+
void keysPromise
|
|
389
|
+
.then((keys) => {
|
|
390
|
+
if (closed)
|
|
391
|
+
return;
|
|
392
|
+
roomKey = 'p_' + keys.privateId;
|
|
393
|
+
resolvedKey = keys.aeadKey;
|
|
394
|
+
connect();
|
|
395
|
+
})
|
|
396
|
+
.catch(() => {
|
|
397
|
+
if (closed)
|
|
398
|
+
return;
|
|
399
|
+
reportOffline('WebSocket signaling key derivation failed');
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
if (keysPromise) {
|
|
404
|
+
void keysPromise
|
|
405
|
+
.then((keys) => {
|
|
406
|
+
resolvedKey = keys.aeadKey;
|
|
407
|
+
})
|
|
408
|
+
.catch(() => {
|
|
409
|
+
if (closed)
|
|
410
|
+
return;
|
|
411
|
+
reportOffline('WebSocket signaling key derivation failed');
|
|
412
|
+
try {
|
|
413
|
+
ws?.close();
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
// Ignore close errors.
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
// Defer initial connect so synchronous errors never fire before callers attach listeners.
|
|
421
|
+
queueMicrotask(connect);
|
|
422
|
+
}
|
|
239
423
|
return {
|
|
240
424
|
trickle: true,
|
|
241
425
|
send(to, signal) {
|
|
242
|
-
|
|
426
|
+
if (!useEncryption)
|
|
427
|
+
return sendJson({ type: 'signal', to, signal });
|
|
428
|
+
if (closed || !ws || ws.readyState !== wsOpen || pendingSendCount >= maxEncryptQueueDepth) {
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
const targetSocket = ws;
|
|
432
|
+
const mid = discovery.self.slice(0, 8) + ':' + ++msgSeq;
|
|
433
|
+
const ts = Date.now();
|
|
434
|
+
pendingSendCount++;
|
|
435
|
+
sendChain = sendChain
|
|
436
|
+
.then(async () => {
|
|
437
|
+
if (closed || ws !== targetSocket || targetSocket.readyState !== wsOpen)
|
|
438
|
+
return;
|
|
439
|
+
const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
|
|
440
|
+
if (!key || closed || ws !== targetSocket || targetSocket.readyState !== wsOpen)
|
|
441
|
+
return;
|
|
442
|
+
const boxed = await sealEnvelope(key, { mid, ts, signal }, 'meshpost/1/ws:' + roomKey + ':' + discovery.self + ':' + to);
|
|
443
|
+
if (closed || ws !== targetSocket || targetSocket.readyState !== wsOpen)
|
|
444
|
+
return;
|
|
445
|
+
try {
|
|
446
|
+
targetSocket.send(JSON.stringify({ type: 'signal', to, box: toBase64Url(boxed) }));
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
// Socket closing; reconnect loop handles recovery.
|
|
450
|
+
}
|
|
451
|
+
})
|
|
452
|
+
.catch(() => {
|
|
453
|
+
// Keep send chain alive across errors.
|
|
454
|
+
})
|
|
455
|
+
.finally(() => {
|
|
456
|
+
pendingSendCount--;
|
|
457
|
+
});
|
|
458
|
+
return true;
|
|
243
459
|
},
|
|
244
460
|
close() {
|
|
245
461
|
if (closed)
|
|
@@ -251,7 +467,7 @@ export function wsSignaling(url, options = {}) {
|
|
|
251
467
|
const current = ws;
|
|
252
468
|
ws = undefined;
|
|
253
469
|
if (current) {
|
|
254
|
-
if (current.readyState ===
|
|
470
|
+
if (current.readyState === wsOpen) {
|
|
255
471
|
try {
|
|
256
472
|
current.send(JSON.stringify({ type: 'leave' }));
|
|
257
473
|
}
|
|
@@ -270,3 +486,61 @@ export function wsSignaling(url, options = {}) {
|
|
|
270
486
|
};
|
|
271
487
|
};
|
|
272
488
|
}
|
|
489
|
+
/**
|
|
490
|
+
* Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
|
|
491
|
+
* - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
|
|
492
|
+
* transitions cleanly to `'closed'` without reconnect storms.
|
|
493
|
+
* - Suppresses `'signaling-error'` so sibling relays (`tabSignaling`, `mqttSignaling`, `nostrSignaling`) carry
|
|
494
|
+
* the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
495
|
+
*/
|
|
496
|
+
export function optionalWsSignaling(url, options = {}) {
|
|
497
|
+
const baseWs = wsSignaling(url, {
|
|
498
|
+
handshakeTimeoutMs: options.handshakeTimeoutMs ?? defaultOptionalHandshakeTimeoutMs,
|
|
499
|
+
...(options.pingIntervalMs !== undefined ? { pingIntervalMs: options.pingIntervalMs } : {}),
|
|
500
|
+
...(options.encrypt !== undefined ? { encrypt: options.encrypt } : {}),
|
|
501
|
+
...(options.privateTopic !== undefined ? { privateTopic: options.privateTopic } : {}),
|
|
502
|
+
...(options.WebSocket !== undefined ? { WebSocket: options.WebSocket } : {}),
|
|
503
|
+
reconnect: false
|
|
504
|
+
});
|
|
505
|
+
return (discovery) => {
|
|
506
|
+
let abandoned = false;
|
|
507
|
+
let session;
|
|
508
|
+
session = baseWs({
|
|
509
|
+
...discovery,
|
|
510
|
+
status(state, reason) {
|
|
511
|
+
if (abandoned)
|
|
512
|
+
return;
|
|
513
|
+
if (state === 'online') {
|
|
514
|
+
discovery.status('online', reason);
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
abandoned = true;
|
|
518
|
+
session?.close();
|
|
519
|
+
discovery.status('closed');
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
error(code, message) {
|
|
523
|
+
if (abandoned)
|
|
524
|
+
return;
|
|
525
|
+
if (code === 'decrypt-failed' || code === 'clock-skew') {
|
|
526
|
+
discovery.error?.(code, message);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
if (abandoned) {
|
|
531
|
+
session.close();
|
|
532
|
+
}
|
|
533
|
+
return {
|
|
534
|
+
...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
|
|
535
|
+
send(to, signal) {
|
|
536
|
+
if (abandoned)
|
|
537
|
+
return false;
|
|
538
|
+
return session.send(to, signal);
|
|
539
|
+
},
|
|
540
|
+
close() {
|
|
541
|
+
abandoned = true;
|
|
542
|
+
session.close();
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
};
|
|
546
|
+
}
|