@dimchansky/meshpost 0.5.0 → 0.7.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 +66 -544
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +44 -45
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +19 -44
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +40 -57
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +2 -0
- package/dist/identity.js +39 -71
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +211 -476
- package/dist/nostr.js +194 -836
- package/dist/peer-link.d.ts +1 -0
- package/dist/peer-link.js +983 -0
- package/dist/presence.d.ts +1 -0
- package/dist/presence.js +74 -0
- package/dist/public.d.ts +1 -1
- package/dist/public.js +25 -77
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +399 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +115 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +245 -1218
- package/dist/rpc.js +25 -28
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +55 -0
- package/dist/state.js +23 -33
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.d.ts +1 -0
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.d.ts +1 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +19 -1
- package/dist/voice.js +95 -1036
- package/dist/ws.js +56 -197
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +219 -0
- package/docs/behavior.md +14 -8
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +6 -3
package/dist/ws.js
CHANGED
|
@@ -1,81 +1,39 @@
|
|
|
1
|
-
import { createReplayGuard, deriveSignalingKeys,
|
|
1
|
+
import { createReplayGuard, deriveSignalingKeys, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
|
|
2
|
+
import { createErrorThrottle } from './presence.js';
|
|
3
|
+
import { maxDecryptQueueDepth, normalizeWsRelayUrl, resolveSessionPassword, resolveSessionWebSocket, safeCloseSocket, startKeyDerivation, validateCommonSignalingOptions, validatePositiveTimeout } from './relay-core.js';
|
|
2
4
|
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
3
5
|
const wsOpen = 1;
|
|
4
6
|
const defaultOptionalHandshakeTimeoutMs = 4_000;
|
|
5
7
|
const maxFrameBytes = 128 * 1024;
|
|
6
8
|
const maxPeers = 256;
|
|
7
9
|
const maxEncryptQueueDepth = 128;
|
|
8
|
-
const maxDecryptQueueDepth = 64;
|
|
9
10
|
const defaultHandshakeTimeoutMs = 10_000;
|
|
10
11
|
const defaultPingIntervalMs = 25_000;
|
|
11
12
|
const insecureWsMessage = 'Password encryption requires a secure context (crypto.subtle); pass encrypt: false for plaintext LAN testing';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
parsed = new URL(url);
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
throw new TypeError('Invalid WebSocket signaling URL');
|
|
23
|
-
}
|
|
24
|
-
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
|
25
|
-
throw new TypeError('WebSocket signaling URL must use ws: or wss:');
|
|
26
|
-
}
|
|
27
|
-
const normalizedUrl = parsed.toString();
|
|
28
|
-
const shouldReconnect = options.reconnect ?? true;
|
|
29
|
-
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
|
|
30
|
-
if (!Number.isSafeInteger(handshakeTimeoutMs) ||
|
|
31
|
-
handshakeTimeoutMs <= 0 ||
|
|
32
|
-
handshakeTimeoutMs > 2_147_483_647) {
|
|
33
|
-
throw new RangeError('Invalid WebSocket handshake timeout');
|
|
34
|
-
}
|
|
13
|
+
function createWsSignaling(url, options, optional) {
|
|
14
|
+
const normalizedUrl = normalizeWsRelayUrl(url, 'Invalid WebSocket signaling URL', 'WebSocket signaling URL must use ws: or wss:');
|
|
15
|
+
const shouldReconnect = optional ? false : (options.reconnect ?? true);
|
|
16
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ??
|
|
17
|
+
(optional ? defaultOptionalHandshakeTimeoutMs : defaultHandshakeTimeoutMs);
|
|
18
|
+
validatePositiveTimeout(handshakeTimeoutMs, 'Invalid WebSocket handshake timeout');
|
|
35
19
|
const pingIntervalMs = options.pingIntervalMs ?? defaultPingIntervalMs;
|
|
36
|
-
|
|
37
|
-
pingIntervalMs <= 0 ||
|
|
38
|
-
pingIntervalMs > 2_147_483_647) {
|
|
39
|
-
throw new RangeError('Invalid WebSocket ping interval');
|
|
40
|
-
}
|
|
20
|
+
validatePositiveTimeout(pingIntervalMs, 'Invalid WebSocket ping interval');
|
|
41
21
|
if (options.encrypt !== undefined && typeof options.encrypt !== 'boolean') {
|
|
42
22
|
throw new TypeError('Invalid encrypt option');
|
|
43
23
|
}
|
|
44
|
-
|
|
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
|
-
}
|
|
24
|
+
validateCommonSignalingOptions(options);
|
|
50
25
|
return (discovery) => {
|
|
51
|
-
const WsCtor = options.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;
|
|
26
|
+
const WsCtor = resolveSessionWebSocket(options.WebSocket);
|
|
56
27
|
const encrypt = options.encrypt ?? true;
|
|
57
28
|
const privateTopic = options.privateTopic ?? false;
|
|
58
|
-
|
|
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
|
-
}
|
|
29
|
+
const { password, useEncryption } = resolveSessionPassword(discovery.password, privateTopic, encrypt, insecureWsMessage);
|
|
73
30
|
const baseScope = discovery.appId + ':' + discovery.room;
|
|
74
31
|
let roomKey = privateTopic
|
|
75
32
|
? ''
|
|
76
33
|
: namespaceHash(baseScope + (!useEncryption && password !== undefined ? ':' + password : ''));
|
|
77
34
|
const knownPeers = new Set();
|
|
78
35
|
const replayGuard = createReplayGuard();
|
|
36
|
+
const emitError = createErrorThrottle((code, message) => discovery.error?.(code, message));
|
|
79
37
|
let ws;
|
|
80
38
|
let closed = false;
|
|
81
39
|
let reportedOnline = false;
|
|
@@ -88,10 +46,8 @@ export function wsSignaling(url, options = {}) {
|
|
|
88
46
|
let pendingTotalRecvCount = 0;
|
|
89
47
|
let sendChain = Promise.resolve();
|
|
90
48
|
let recvChain = Promise.resolve();
|
|
91
|
-
let lastDecryptErrorAt = -Infinity;
|
|
92
|
-
let lastClockSkewErrorAt = -Infinity;
|
|
93
49
|
let resolvedKey;
|
|
94
|
-
const keysPromise = useEncryption
|
|
50
|
+
const keysPromise = useEncryption && password !== undefined
|
|
95
51
|
? deriveSignalingKeys(password, baseScope, insecureWsMessage)
|
|
96
52
|
: undefined;
|
|
97
53
|
let handshakeTimer;
|
|
@@ -103,20 +59,8 @@ export function wsSignaling(url, options = {}) {
|
|
|
103
59
|
clearInterval(pingTimer);
|
|
104
60
|
pingTimer = undefined;
|
|
105
61
|
};
|
|
106
|
-
const emitDecryptFailed = (message) =>
|
|
107
|
-
|
|
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
|
-
};
|
|
62
|
+
const emitDecryptFailed = (message) => emitError('decrypt-failed', message);
|
|
63
|
+
const emitClockSkew = () => emitError('clock-skew', 'WebSocket signaling message rejected due to system clock skew (>60s)');
|
|
120
64
|
const applyRoster = (peers) => {
|
|
121
65
|
knownPeers.clear();
|
|
122
66
|
for (const id of peers) {
|
|
@@ -154,6 +98,17 @@ export function wsSignaling(url, options = {}) {
|
|
|
154
98
|
const reportOffline = (reason) => {
|
|
155
99
|
if (closed)
|
|
156
100
|
return;
|
|
101
|
+
if (optional) {
|
|
102
|
+
closed = true;
|
|
103
|
+
clearTimers();
|
|
104
|
+
clearTimeout(reconnectTimer);
|
|
105
|
+
reconnectTimer = undefined;
|
|
106
|
+
const current = ws;
|
|
107
|
+
ws = undefined;
|
|
108
|
+
safeCloseSocket(current);
|
|
109
|
+
discovery.status('closed', reason);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
157
112
|
if (reportedOnline || !reportedOffline) {
|
|
158
113
|
reportedOnline = false;
|
|
159
114
|
reportedOffline = true;
|
|
@@ -196,21 +151,11 @@ export function wsSignaling(url, options = {}) {
|
|
|
196
151
|
if (closed || ws !== socket || settled)
|
|
197
152
|
return;
|
|
198
153
|
timedOut = true;
|
|
199
|
-
|
|
200
|
-
socket.close();
|
|
201
|
-
}
|
|
202
|
-
catch {
|
|
203
|
-
// Ignore close errors.
|
|
204
|
-
}
|
|
154
|
+
safeCloseSocket(socket);
|
|
205
155
|
}, handshakeTimeoutMs);
|
|
206
156
|
socket.onopen = () => {
|
|
207
157
|
if (closed || ws !== socket) {
|
|
208
|
-
|
|
209
|
-
socket.close();
|
|
210
|
-
}
|
|
211
|
-
catch {
|
|
212
|
-
// Ignore close errors.
|
|
213
|
-
}
|
|
158
|
+
safeCloseSocket(socket);
|
|
214
159
|
return;
|
|
215
160
|
}
|
|
216
161
|
settled = true;
|
|
@@ -219,12 +164,7 @@ export function wsSignaling(url, options = {}) {
|
|
|
219
164
|
attempt = 0;
|
|
220
165
|
awaitingPong = false;
|
|
221
166
|
if (!sendJson({ type: 'join', room: roomKey, id: discovery.self })) {
|
|
222
|
-
|
|
223
|
-
socket.close();
|
|
224
|
-
}
|
|
225
|
-
catch {
|
|
226
|
-
// Ignore close errors.
|
|
227
|
-
}
|
|
167
|
+
safeCloseSocket(socket);
|
|
228
168
|
return;
|
|
229
169
|
}
|
|
230
170
|
if (!reportedOnline) {
|
|
@@ -238,22 +178,12 @@ export function wsSignaling(url, options = {}) {
|
|
|
238
178
|
if (useEncryption)
|
|
239
179
|
replayGuard.prune();
|
|
240
180
|
if (awaitingPong) {
|
|
241
|
-
|
|
242
|
-
socket.close();
|
|
243
|
-
}
|
|
244
|
-
catch {
|
|
245
|
-
// Ignore close errors.
|
|
246
|
-
}
|
|
181
|
+
safeCloseSocket(socket);
|
|
247
182
|
return;
|
|
248
183
|
}
|
|
249
184
|
awaitingPong = true;
|
|
250
185
|
if (!sendJson({ type: 'ping' })) {
|
|
251
|
-
|
|
252
|
-
socket.close();
|
|
253
|
-
}
|
|
254
|
-
catch {
|
|
255
|
-
// Ignore close errors.
|
|
256
|
-
}
|
|
186
|
+
safeCloseSocket(socket);
|
|
257
187
|
}
|
|
258
188
|
}, pingIntervalMs);
|
|
259
189
|
};
|
|
@@ -365,12 +295,7 @@ export function wsSignaling(url, options = {}) {
|
|
|
365
295
|
socket.onerror = () => {
|
|
366
296
|
if (ws !== socket)
|
|
367
297
|
return;
|
|
368
|
-
|
|
369
|
-
socket.close();
|
|
370
|
-
}
|
|
371
|
-
catch {
|
|
372
|
-
// Ignore close errors.
|
|
373
|
-
}
|
|
298
|
+
safeCloseSocket(socket);
|
|
374
299
|
};
|
|
375
300
|
socket.onclose = (event) => {
|
|
376
301
|
if (ws !== socket)
|
|
@@ -401,42 +326,22 @@ export function wsSignaling(url, options = {}) {
|
|
|
401
326
|
scheduleReconnect();
|
|
402
327
|
};
|
|
403
328
|
};
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
329
|
+
startKeyDerivation({
|
|
330
|
+
keysPromise,
|
|
331
|
+
privateTopic,
|
|
332
|
+
isClosed: () => closed,
|
|
333
|
+
onResolvedKey(key) {
|
|
334
|
+
resolvedKey = key;
|
|
335
|
+
},
|
|
336
|
+
onPrivateKeys(keys) {
|
|
409
337
|
roomKey = 'p_' + keys.privateId;
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
.catch(() => {
|
|
414
|
-
if (closed)
|
|
415
|
-
return;
|
|
338
|
+
},
|
|
339
|
+
onConnect: connect,
|
|
340
|
+
onError() {
|
|
416
341
|
reportOffline('WebSocket signaling key derivation failed');
|
|
417
|
-
|
|
418
|
-
}
|
|
419
|
-
else {
|
|
420
|
-
if (keysPromise) {
|
|
421
|
-
void keysPromise
|
|
422
|
-
.then((keys) => {
|
|
423
|
-
resolvedKey = keys.aeadKey;
|
|
424
|
-
})
|
|
425
|
-
.catch(() => {
|
|
426
|
-
if (closed)
|
|
427
|
-
return;
|
|
428
|
-
reportOffline('WebSocket signaling key derivation failed');
|
|
429
|
-
try {
|
|
430
|
-
ws?.close();
|
|
431
|
-
}
|
|
432
|
-
catch {
|
|
433
|
-
// Ignore close errors.
|
|
434
|
-
}
|
|
435
|
-
});
|
|
342
|
+
safeCloseSocket(ws);
|
|
436
343
|
}
|
|
437
|
-
|
|
438
|
-
queueMicrotask(connect);
|
|
439
|
-
}
|
|
344
|
+
});
|
|
440
345
|
return {
|
|
441
346
|
trickle: true,
|
|
442
347
|
send(to, signal) {
|
|
@@ -492,17 +397,19 @@ export function wsSignaling(url, options = {}) {
|
|
|
492
397
|
// Ignore send errors during close.
|
|
493
398
|
}
|
|
494
399
|
}
|
|
495
|
-
|
|
496
|
-
current.close();
|
|
497
|
-
}
|
|
498
|
-
catch {
|
|
499
|
-
// Ignore close errors.
|
|
500
|
-
}
|
|
400
|
+
safeCloseSocket(current);
|
|
501
401
|
}
|
|
502
402
|
}
|
|
503
403
|
};
|
|
504
404
|
};
|
|
505
405
|
}
|
|
406
|
+
/**
|
|
407
|
+
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
408
|
+
* When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
|
|
409
|
+
*/
|
|
410
|
+
export function wsSignaling(url, options = {}) {
|
|
411
|
+
return createWsSignaling(url, options, false);
|
|
412
|
+
}
|
|
506
413
|
/**
|
|
507
414
|
* Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
|
|
508
415
|
* - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
|
|
@@ -511,53 +418,5 @@ export function wsSignaling(url, options = {}) {
|
|
|
511
418
|
* the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
512
419
|
*/
|
|
513
420
|
export function optionalWsSignaling(url, options = {}) {
|
|
514
|
-
|
|
515
|
-
handshakeTimeoutMs: options.handshakeTimeoutMs ?? defaultOptionalHandshakeTimeoutMs,
|
|
516
|
-
...(options.pingIntervalMs !== undefined ? { pingIntervalMs: options.pingIntervalMs } : {}),
|
|
517
|
-
...(options.encrypt !== undefined ? { encrypt: options.encrypt } : {}),
|
|
518
|
-
...(options.privateTopic !== undefined ? { privateTopic: options.privateTopic } : {}),
|
|
519
|
-
...(options.WebSocket !== undefined ? { WebSocket: options.WebSocket } : {}),
|
|
520
|
-
reconnect: false
|
|
521
|
-
});
|
|
522
|
-
return (discovery) => {
|
|
523
|
-
let abandoned = false;
|
|
524
|
-
let session;
|
|
525
|
-
session = baseWs({
|
|
526
|
-
...discovery,
|
|
527
|
-
status(state, reason) {
|
|
528
|
-
if (abandoned)
|
|
529
|
-
return;
|
|
530
|
-
if (state === 'online') {
|
|
531
|
-
discovery.status('online', reason);
|
|
532
|
-
}
|
|
533
|
-
else {
|
|
534
|
-
abandoned = true;
|
|
535
|
-
session?.close();
|
|
536
|
-
discovery.status('closed', reason);
|
|
537
|
-
}
|
|
538
|
-
},
|
|
539
|
-
error(code, message) {
|
|
540
|
-
if (abandoned)
|
|
541
|
-
return;
|
|
542
|
-
if (code === 'decrypt-failed' || code === 'clock-skew') {
|
|
543
|
-
discovery.error?.(code, message);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
});
|
|
547
|
-
if (abandoned) {
|
|
548
|
-
session.close();
|
|
549
|
-
}
|
|
550
|
-
return {
|
|
551
|
-
...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
|
|
552
|
-
send(to, signal) {
|
|
553
|
-
if (abandoned)
|
|
554
|
-
return false;
|
|
555
|
-
return session.send(to, signal);
|
|
556
|
-
},
|
|
557
|
-
close() {
|
|
558
|
-
abandoned = true;
|
|
559
|
-
session.close();
|
|
560
|
-
}
|
|
561
|
-
};
|
|
562
|
-
};
|
|
421
|
+
return createWsSignaling(url, options, true);
|
|
563
422
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# ADR-0001: Public `Channel.maxPayloadBytes` vs Internal `Room` Lifecycle Hooks
|
|
2
|
+
|
|
3
|
+
- **Status:** Accepted
|
|
4
|
+
- **Date:** 2026-12-06
|
|
5
|
+
|
|
6
|
+
## Context
|
|
7
|
+
|
|
8
|
+
Higher-level protocol modules built on top of `Room` (`src/channel.ts`, `src/state.ts`, `src/rpc.ts`, `src/blob.ts`, and `src/voice.ts`) share two cross-cutting needs:
|
|
9
|
+
|
|
10
|
+
1. **Packet budget accounting:** `Room` enforces a `16,384`-byte (16 KiB) per-packet limit, and `createChannel()` reserves `1 + utf8(name).length` bytes for its framing header. Previously, `src/peer-link.ts`, `src/state.ts`, and `src/blob.ts` each hardcoded `16 * 1024`, and `state.ts` and `blob.ts` independently re-encoded `name` to compute remaining payload bytes. Application authors writing custom binary protocols over `Channel` had no public way to query the exact usable payload budget either.
|
|
11
|
+
2. **Lifecycle and stream coordination:** Protocol helpers must clean up timers, pending promises, and listeners automatically when `room.leave()` is called—without closing prematurely when a signaling adapter transitions to `'closed'` while live WebRTC links remain open. Additionally, `createVoice()` must discover already-active remote `MediaStream`s when attached after peers have joined.
|
|
12
|
+
|
|
13
|
+
This raised an API design question: should we promote `onRoomClose` / `getRemoteStreams` onto the public `Room` interface, or keep them internal while exposing `maxPayloadBytes` on `Channel`?
|
|
14
|
+
|
|
15
|
+
## Decision
|
|
16
|
+
|
|
17
|
+
1. **Expose `readonly maxPayloadBytes: number` publicly on `Channel` and `CodecChannel<T>`.**
|
|
18
|
+
- Computed once from the single internal constant `maxPacketBytes` (`16 * 1024` in `src/peer-link.ts`) minus the channel prefix (`1 + utf8(name).length`).
|
|
19
|
+
- Internal protocol modules (`src/state.ts`, `src/blob.ts`) derive their payload/chunk caps directly from `channel.maxPayloadBytes`, eliminating duplicated `16 * 1024` constants and UTF-8 framing math.
|
|
20
|
+
- Publicly useful to downstream applications building custom framing over `createChannel()` or `createCodecChannel()`, and 100% additive/backward-compatible because consumers create channels via `createChannel()` rather than hand-implementing the `Channel` interface.
|
|
21
|
+
2. **Keep `isRoomClosed`, `onRoomClose`, `bindRoomLifecycle`, and `getRoomRemoteStreams` internal (backed by `WeakMap<Room, RoomInternals>`).**
|
|
22
|
+
- Consolidate duplicated `closed` + `AbortController` + `onRoomClose` teardown ceremony across `state.ts`, `rpc.ts`, and `blob.ts` into a single internal `bindRoomLifecycle(room, onShutdown)` helper in `src/room.ts`.
|
|
23
|
+
- Retain the fallback to `room.signalingState === 'closed'` / `room.onSignalingChange` when a caller passes a duck-typed mock `Room` in unit tests.
|
|
24
|
+
- Do **not** add new required methods to the public `Room` interface.
|
|
25
|
+
|
|
26
|
+
## Consequences
|
|
27
|
+
|
|
28
|
+
- **Zero breaking changes for downstream TypeScript consumers:** Projects that write duck-typed mock `Room` objects in their own test suites (such as `netwars` or Meshpost's own `tests/unit/helpers/mock-room.mjs`) continue to compile without implementing extra lifecycle/introspection methods, while still receiving automatic teardown on `leave()` via `bindRoomLifecycle`.
|
|
29
|
+
- **Single source of truth for framing limits:** `maxPacketBytes` lives once in `src/peer-link.ts`, `Channel.maxPayloadBytes` computes the channel overhead once in `src/channel.ts`, and `PeerState` / `BlobChannel` subtract only their own header size.
|
|
30
|
+
- **Minimal public `Room` surface:** `Room` remains focused on peer connectivity, binary packets, and media tracks, keeping the mental model small for library users.
|
|
31
|
+
- **Trade-off:** Third-party custom helpers outside Meshpost that need `room.leave()` detection still rely on `room.onSignalingChange((s) => s === 'closed')` or explicit `.close()` calls; if a strong ecosystem use case emerges in `v1.0`, a public `room.closed` or `room.signal` (`AbortSignal`) can be considered as a planned major-version enhancement.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# API Reference
|
|
2
|
+
|
|
3
|
+
`@dimchansky/meshpost` is a zero-dependency ESM package with `"sideEffects": false`. Import from granular subpaths for optimal tree-shaking, or from the root barrel `@dimchansky/meshpost` for convenience.
|
|
4
|
+
|
|
5
|
+
## Package entry points
|
|
6
|
+
|
|
7
|
+
| Subpath | Purpose |
|
|
8
|
+
| -------------------------------- | --------------------------------------------------------------------------------------------------- |
|
|
9
|
+
| `@dimchansky/meshpost` | Root barrel re-exporting all public symbols and types |
|
|
10
|
+
| `@dimchansky/meshpost/room` | `joinRoom`, `defaultIceServers`, core `Room` types |
|
|
11
|
+
| `@dimchansky/meshpost/channel` | `createChannel`, `createCodecChannel`, `binaryCodec`, `textCodec`, `jsonCodec` |
|
|
12
|
+
| `@dimchansky/meshpost/state` | `createPeerState` (replicated per-peer state with auto-hydration & drain coalescing) |
|
|
13
|
+
| `@dimchansky/meshpost/rpc` | `createRpc`, `RpcError` (typed request-response RPC) |
|
|
14
|
+
| `@dimchansky/meshpost/blob` | `createBlobChannel` (chunked reliable binary transfers >16 KiB) |
|
|
15
|
+
| `@dimchansky/meshpost/voice` | `createVoice`, `listAudioInputs`, `onAudioInputsChange` |
|
|
16
|
+
| `@dimchansky/meshpost/identity` | `createIdentity`, `createIdentityStore`, `exportIdentity`, `importIdentity`, `isSerializedIdentity` |
|
|
17
|
+
| `@dimchansky/meshpost/turn` | `fetchTurnCredentials` |
|
|
18
|
+
| `@dimchansky/meshpost/public` | `publicSignaling` (out-of-the-box WS + MQTT + Nostr + LocalTabs pool) |
|
|
19
|
+
| `@dimchansky/meshpost/ws` | `wsSignaling`, `optionalWsSignaling` |
|
|
20
|
+
| `@dimchansky/meshpost/mqtt` | `mqttSignaling`, `defaultMqttRelays` |
|
|
21
|
+
| `@dimchansky/meshpost/nostr` | `nostrSignaling`, `defaultNostrRelays` |
|
|
22
|
+
| `@dimchansky/meshpost/tabs` | `tabSignaling` |
|
|
23
|
+
| `@dimchansky/meshpost/manual` | `manualSignaling` |
|
|
24
|
+
| `@dimchansky/meshpost/combine` | `combineSignaling`, `withLocalTabs` |
|
|
25
|
+
| `@dimchansky/meshpost/signaling` | `observeSignaling`, `isUuid`, `isSignal`, `withLoopbackFallback`, adapter types |
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## `@dimchansky/meshpost/room`
|
|
30
|
+
|
|
31
|
+
- `joinRoom(name: string, options: RoomOptions): Room` — Joins a room and starts peer discovery immediately.
|
|
32
|
+
- `defaultIceServers: readonly RTCIceServer[]` — Built-in Cloudflare and Google public STUN servers.
|
|
33
|
+
|
|
34
|
+
### `RoomOptions`
|
|
35
|
+
|
|
36
|
+
| Option | Type | Default | Notes |
|
|
37
|
+
| ----------------------- | ------------------------------ | ------------------------------ | --------------------------------------------------------------------------------- |
|
|
38
|
+
| `signaling` | `Signaling` | **required** | Signaling adapter factory |
|
|
39
|
+
| `appId` | `string` | `'meshpost'` | Application namespace isolating rooms across apps |
|
|
40
|
+
| `password` | `string` | — | Optional non-empty shared password isolating & encrypting signaling |
|
|
41
|
+
| `rtcConfig` | `RTCConfiguration` | — | Custom WebRTC config; keeps `defaultIceServers` unless `iceServers` is set |
|
|
42
|
+
| `turnConfig` | `readonly RTCIceServer[]` | — | Extra TURN/STUN servers appended to `rtcConfig.iceServers` or `defaultIceServers` |
|
|
43
|
+
| `handshakeTimeoutMs` | `number` | `35000` | Max ms per connection attempt before retrying |
|
|
44
|
+
| `iceGatheringTimeoutMs` | `number` | `2500` | Soft cap ms for ICE gathering on non-trickle adapters |
|
|
45
|
+
| `maxPeers` | `number` | `32` | Maximum simultaneous peer connections (positive safe integer) |
|
|
46
|
+
| `identity` | `PeerIdentity` | — | Optional WebCrypto ECDSA P-256 identity proven over each DTLS link |
|
|
47
|
+
| `RTCPeerConnection` | `RTCPeerConnectionConstructor` | `globalThis.RTCPeerConnection` | Custom constructor for Node.js/Bun/Deno or tests |
|
|
48
|
+
|
|
49
|
+
### `Room`
|
|
50
|
+
|
|
51
|
+
- Properties: `id: string`, `userId: string | null`, `peers: readonly string[]`, `signalingState: SignalingState`.
|
|
52
|
+
- Identity: `peerUserId(peerId: string): string | null`.
|
|
53
|
+
- Data: `send(bytes: Uint8Array, options?: SendOptions): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`, `onDrain(fn, options?)`.
|
|
54
|
+
- `Delivery = 'unreliable' | 'reliable'` (default `'unreliable'`).
|
|
55
|
+
- `SendResult = 'accepted' | 'unavailable' | 'busy' | 'too-large'`.
|
|
56
|
+
- Lifecycle & diagnostics: `onPeerJoin(fn, options?)`, `onPeerLeave(fn, options?)`, `onSignalingChange(fn, options?)`, `onError(fn, options?)`, `getStats(peerId): Promise<PeerStats | null>`, `leave(): void`.
|
|
57
|
+
- `RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | 'auth-failed' | SignalingErrorCode`.
|
|
58
|
+
- `PeerStats = { rttMs: number | null, route: 'direct' | 'relay' | 'unknown', bytesSent: number, bytesReceived: number, bufferedUnreliable: number, bufferedReliable: number }`.
|
|
59
|
+
- Media streams: `addStream(stream, toOrOptions?: string | AddStreamOptions)`, `removeStream(stream, toOrOptions?: string | RemoveStreamOptions)`, `replaceStreamTrack(stream, oldTrack, newTrack): Promise<void>`, `onPeerStream(fn, options?)`, `onPeerStreamEnd(fn, options?)`.
|
|
60
|
+
- `AddStreamOptions = { to?: string, tag?: string }` (`tag`: `1..32` chars `[a-zA-Z0-9._-]`).
|
|
61
|
+
- `PeerStreamMeta = { readonly tag?: string }`.
|
|
62
|
+
- `ListenOptions = { once?: boolean, signal?: AbortSignal }` — supported on every `on*` method across the library.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## `@dimchansky/meshpost/channel`
|
|
67
|
+
|
|
68
|
+
- `createChannel(room: Room, name: string, options?: ChannelOptions): Channel`
|
|
69
|
+
- Multiplexes a named channel (`1..64` UTF-8 bytes) over the room's existing data channels in `O(1)` dispatch time.
|
|
70
|
+
- `ChannelOptions = { delivery?: Delivery }` (default `'unreliable'`).
|
|
71
|
+
- `Channel`: `name`, `delivery`, `maxPayloadBytes` (`16384 - 1 - utf8(name).length`), `send(bytes, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`.
|
|
72
|
+
- `createCodecChannel<T>(room: Room, name: string, codec: Codec<T>, options?: ChannelOptions): CodecChannel<T>`
|
|
73
|
+
- `Codec<T> = { encode(value: T): Uint8Array, decode(bytes: Uint8Array): T }`.
|
|
74
|
+
- `CodecChannel<T>`: `name`, `delivery`, `maxPayloadBytes`, `send(value, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onMessage(fn, options?)`. Malformed frames are dropped without consuming `{ once: true }`.
|
|
75
|
+
- Built-in codecs:
|
|
76
|
+
- `binaryCodec: Codec<Uint8Array>` (zero-copy identity)
|
|
77
|
+
- `textCodec: Codec<string>` (strict UTF-8)
|
|
78
|
+
- `jsonCodec<T>(validate?: ((value: unknown) => value is T) | ((value: unknown) => boolean)): Codec<T>`
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## `@dimchansky/meshpost/state`
|
|
83
|
+
|
|
84
|
+
- `createPeerState<T = unknown>(room: Room, name: string, options?: PeerStateOptions<T>): PeerState<T>`
|
|
85
|
+
- Options: `delivery?: Delivery` (default `'reliable'`), `codec?: Codec<T>` (default `jsonCodec()`), `initial?: T`, `coalesce?: boolean` (default `true`).
|
|
86
|
+
- Methods: `getSelf()`, `get(peerId)`, `getAll()`, `set(value)`, `clear()`, `onChange(fn: (peerId, next, prev, reason: PeerStateChangeReason) => void, options?)`, `close()`.
|
|
87
|
+
- `PeerStateChangeReason = 'set' | 'clear' | 'leave'`.
|
|
88
|
+
- Closes automatically on `room.leave()`.
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## `@dimchansky/meshpost/rpc`
|
|
93
|
+
|
|
94
|
+
- `createRpc<Req = unknown, Res = unknown>(room: Room, name: string, options?: RpcOptions<Req, Res>): RpcEndpoint<Req, Res>`
|
|
95
|
+
- Options: `timeoutMs` (default `10000`), `requestCodec` (default `jsonCodec()`), `responseCodec` (default `jsonCodec()`), `maxPendingCalls` (default `256`, `1..4096`), `maxConcurrentPerPeer` (default `16`, `1..256`).
|
|
96
|
+
- Methods: `call(peerId, request, options?: { timeoutMs?: number, signal?: AbortSignal }): Promise<Res>`, `handle(fn, options?: ListenOptions): () => void` (at most one active handler per endpoint), `close()`.
|
|
97
|
+
- `class RpcError extends Error` — Properties: `code: RpcErrorCode`, `peerId: string`.
|
|
98
|
+
- `RpcErrorCode = 'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed'`.
|
|
99
|
+
- Closes automatically on `room.leave()`.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## `@dimchansky/meshpost/blob`
|
|
104
|
+
|
|
105
|
+
- `createBlobChannel(room: Room, name: string, options?: BlobChannelOptions): BlobChannel`
|
|
106
|
+
- Options: `maxReceiveBytes` (default `4194304` = `4 MiB`), `chunkSize` (default `15360`), `receiveTimeoutMs` (default `30000`), `maxConcurrentPerPeer` (default `4`).
|
|
107
|
+
- Methods:
|
|
108
|
+
- `send(bytes: Uint8Array, options?: { to?: string, onProgress?: (peerId, sentBytes, totalBytes) => void, signal?: AbortSignal }): Promise<ReadonlyMap<string, BlobSendStatus>>` (`'sent' | 'aborted' | 'unavailable' | 'too-large'`).
|
|
109
|
+
- `onBlob(fn: (from, bytes) => void, options?)`
|
|
110
|
+
- `onProgress(fn: (from, progress: BlobProgress) => void, options?)`
|
|
111
|
+
- `close()` (also runs automatically on `room.leave()`).
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## `@dimchansky/meshpost/voice`
|
|
116
|
+
|
|
117
|
+
- `createVoice(room: Room, options?: VoiceOptions): Voice`
|
|
118
|
+
- Options: `volume` (`1`), `deafened` (`false`), `deviceId` (`null`), `fallbackToDefaultOnNotFound` (`false`), `audioConstraints` (`{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }`), `autoUnlock` (`true`), `speakingDetection` (`true`), `speakingThreshold` (`0.03`), `speakingIntervalMs` (`180`), `to`, `streamTag` (`'voice'`), `strictStreamTag` (`false`).
|
|
119
|
+
- Snapshot fields (also exposed directly as readonly properties on `Voice`): `micStatus: MicStatus`, `micError: MicError | null`, `micStopReason: MicStopReason | null`, `deviceId: string | null`, `autoplayBlocked: boolean`, `deafened: boolean`, `volume: number`, `selfSpeaking: boolean`, `remotePeers: readonly string[]`, `speakingPeers: readonly string[]`, `mutedPeers: readonly string[]`, `peerVolumes: Readonly<Record<string, number>>`.
|
|
120
|
+
- Methods: `getSnapshot()`, `toggleMic()`, `startMic()`, `setMuted(muted)`, `stopMic()`, `switchDevice(deviceId?)`, `setVolume(volume)`, `setPeerVolume(peerId, volume)`, `getPeerVolume(peerId)`, `setDeafened(deafened)`, `setPeerMuted(peerId, muted)`, `isPeerMuted(peerId)`, `unlockAudio()`, `onChange(fn, options?)`, `close()` (also runs automatically on `room.leave()`).
|
|
121
|
+
- `MicStatus = 'off' | 'requesting' | 'live' | 'muted' | 'error'`.
|
|
122
|
+
- `MicStopReason = 'stopped' | 'ended'` (`'stopped'` after local `stopMic()`/`close()`, `'ended'` after unexpected hardware `track.onended`, `null` before first stop or while active/errored).
|
|
123
|
+
- `MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown'`.
|
|
124
|
+
- `listAudioInputs(): Promise<readonly AudioInputDevice[]>` — Safe cross-runtime audio input enumeration (`{ deviceId, label, groupId }`).
|
|
125
|
+
- `onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: AudioInputsChangeOptions): () => void`
|
|
126
|
+
- `AudioInputsChangeOptions` extends `ListenOptions` with `immediate?: boolean` (default `false`).
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## `@dimchansky/meshpost/identity`
|
|
131
|
+
|
|
132
|
+
- `createIdentity(options?: { extractable?: boolean }): Promise<PeerIdentity>` (`extractable` defaults to `true`).
|
|
133
|
+
- `PeerIdentity = { readonly userId: string, readonly publicKey: string }`.
|
|
134
|
+
- `exportIdentity(identity: PeerIdentity): Promise<SerializedIdentity>`
|
|
135
|
+
- `importIdentity(data: unknown, options?: { extractable?: boolean }): Promise<PeerIdentity>` (cryptographically verifies `(x, y)` against `d`).
|
|
136
|
+
- `isSerializedIdentity(value: unknown): value is SerializedIdentity`
|
|
137
|
+
- `createIdentityStore(options: { key: string, storage?: IdentityStorage | null }): IdentityStore`
|
|
138
|
+
- `IdentityStore`: `readonly current: PeerIdentity | null`, `load(): Promise<PeerIdentity>`, `rotate(): Promise<PeerIdentity>`, `clear(): void`.
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## `@dimchansky/meshpost/turn`
|
|
143
|
+
|
|
144
|
+
- `fetchTurnCredentials(url: string, options?: FetchTurnOptions): Promise<RTCIceServer[]>`
|
|
145
|
+
- `FetchTurnOptions = { accessKey?: string, signal?: AbortSignal, timeoutMs?: number }` (`timeoutMs` defaults to `5000`; pass `0` to disable).
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## `@dimchansky/meshpost/public`
|
|
150
|
+
|
|
151
|
+
- `publicSignaling(options?: PublicSignalingOptions): Signaling`
|
|
152
|
+
- Options: `wsUrls?: string | readonly string[]` (0..8 unique `ws:`/`wss:` URLs), `mqtt?: boolean | readonly string[]` (`true`), `nostr?: boolean | readonly string[]` (`true`), `localTabs?: boolean` (`true`), `wsEncrypt?: boolean` (`true`), `privateTopic?: boolean` (`false`), `appId?: string`, `wsHandshakeTimeoutMs?: number` (`4000`), `handshakeTimeoutMs?: number` (`10000`), `WebSocket?: WebSocketConstructor`, `onTransportChange?: (event: PublicTransportEvent) => void`.
|
|
153
|
+
- `PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs'`.
|
|
154
|
+
- `PublicTransportEvent = { readonly transport: PublicTransportKind, readonly url?: string, readonly state: SignalingState, readonly reason?: string }`.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## `@dimchansky/meshpost/ws`
|
|
159
|
+
|
|
160
|
+
- `wsSignaling(url: string, options?: WsSignalingOptions): Signaling`
|
|
161
|
+
- Options: `reconnect` (`true`), `handshakeTimeoutMs` (`10000`), `pingIntervalMs` (`25000`), `encrypt` (`true`), `privateTopic` (`false`), `WebSocket`.
|
|
162
|
+
- `optionalWsSignaling(url: string, options?: OptionalWsSignalingOptions): Signaling`
|
|
163
|
+
- Opportunistic single-shot WS adapter (`reconnect: false`, `handshakeTimeoutMs: 4000` default, suppresses `'signaling-error'`).
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## `@dimchansky/meshpost/mqtt`
|
|
168
|
+
|
|
169
|
+
- `mqttSignaling(options?: MqttSignalingOptions): Signaling`
|
|
170
|
+
- Options: `urls` (`defaultMqttRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
|
|
171
|
+
- `defaultMqttRelays: readonly string[]`
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## `@dimchansky/meshpost/nostr`
|
|
176
|
+
|
|
177
|
+
- `nostrSignaling(options?: NostrSignalingOptions): Signaling`
|
|
178
|
+
- Options: `urls` (`defaultNostrRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
|
|
179
|
+
- `defaultNostrRelays: readonly string[]`
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## `@dimchansky/meshpost/tabs`
|
|
184
|
+
|
|
185
|
+
- `tabSignaling(): Signaling` — Same-origin `BroadcastChannel` signaling (zero network).
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
## `@dimchansky/meshpost/manual`
|
|
190
|
+
|
|
191
|
+
- `manualSignaling(outgoing: (to: string, text: string) => void): ManualSignaling`
|
|
192
|
+
- `ManualSignaling = { readonly signaling: Signaling, contact(): string, accept(text: string): void, forget(peerId: string): void }`.
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## `@dimchansky/meshpost/combine`
|
|
197
|
+
|
|
198
|
+
- `combineSignaling(...adapters: readonly Signaling[]): Signaling`
|
|
199
|
+
- `withLocalTabs(primary: Signaling, options?: WithLocalTabsOptions): Signaling`
|
|
200
|
+
- `WithLocalTabsOptions = { onTabsState?: (state: SignalingState, reason?: string) => void }`.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## `@dimchansky/meshpost/signaling`
|
|
205
|
+
|
|
206
|
+
- `observeSignaling(adapter: Signaling, onChange: (state: SignalingState, reason?: string) => void): Signaling`
|
|
207
|
+
- `isUuid(value: unknown): value is string`
|
|
208
|
+
- `isSignal(value: unknown): value is Signal`
|
|
209
|
+
- `withLoopbackFallback<T extends Signal>(signal: T): T`
|
|
210
|
+
- Types: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `WebSocketConstructor`.
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## See also
|
|
215
|
+
|
|
216
|
+
- [Guide](./guide.md) — step-by-step usage examples
|
|
217
|
+
- [Voice & Media](./voice-and-media.md) — voice and custom `MediaStream` guide
|
|
218
|
+
- [Signaling & Production](./signaling-and-production.md) — signaling recipes, TURN, edge workers, and headless peers
|
|
219
|
+
- [Behavior & Security Spec](./behavior.md) — protocol details, invariants, limits, and security model
|