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