@dimchansky/meshpost 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.
Files changed (46) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +5 -24
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +2 -0
  10. package/dist/identity.js +39 -71
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +1 -1
  17. package/dist/public.js +9 -54
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +11 -1
  39. package/dist/voice.js +99 -295
  40. package/dist/ws.js +39 -142
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +10 -4
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/ws.js CHANGED
@@ -1,4 +1,5 @@
1
- import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
1
+ import { createReplayGuard, deriveSignalingKeys, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
2
+ import { createErrorThrottle, normalizeWsRelayUrl, safeCloseSocket, validatePositiveTimeout } from './relay-core.js';
2
3
  import { isSignal, isUuid, namespaceHash } from './signaling.js';
3
4
  const wsOpen = 1;
4
5
  const defaultOptionalHandshakeTimeoutMs = 4_000;
@@ -9,35 +10,14 @@ 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
- * Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
14
- * When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
15
- */
16
- export function wsSignaling(url, options = {}) {
17
- let parsed;
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
- if (!Number.isSafeInteger(pingIntervalMs) ||
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
  }
@@ -76,6 +56,7 @@ export function wsSignaling(url, options = {}) {
76
56
  : namespaceHash(baseScope + (!useEncryption && password !== undefined ? ':' + password : ''));
77
57
  const knownPeers = new Set();
78
58
  const replayGuard = createReplayGuard();
59
+ const emitError = createErrorThrottle(discovery);
79
60
  let ws;
80
61
  let closed = false;
81
62
  let reportedOnline = false;
@@ -88,8 +69,6 @@ export function wsSignaling(url, options = {}) {
88
69
  let pendingTotalRecvCount = 0;
89
70
  let sendChain = Promise.resolve();
90
71
  let recvChain = Promise.resolve();
91
- let lastDecryptErrorAt = -Infinity;
92
- let lastClockSkewErrorAt = -Infinity;
93
72
  let resolvedKey;
94
73
  const keysPromise = useEncryption
95
74
  ? deriveSignalingKeys(password, baseScope, insecureWsMessage)
@@ -103,20 +82,8 @@ export function wsSignaling(url, options = {}) {
103
82
  clearInterval(pingTimer);
104
83
  pingTimer = undefined;
105
84
  };
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
- };
85
+ const emitDecryptFailed = (message) => emitError('decrypt-failed', message);
86
+ const emitClockSkew = () => emitError('clock-skew', 'WebSocket signaling message rejected due to system clock skew (>60s)');
120
87
  const applyRoster = (peers) => {
121
88
  knownPeers.clear();
122
89
  for (const id of peers) {
@@ -154,6 +121,17 @@ export function wsSignaling(url, options = {}) {
154
121
  const reportOffline = (reason) => {
155
122
  if (closed)
156
123
  return;
124
+ if (optional) {
125
+ closed = true;
126
+ clearTimers();
127
+ clearTimeout(reconnectTimer);
128
+ reconnectTimer = undefined;
129
+ const current = ws;
130
+ ws = undefined;
131
+ safeCloseSocket(current);
132
+ discovery.status('closed', reason);
133
+ return;
134
+ }
157
135
  if (reportedOnline || !reportedOffline) {
158
136
  reportedOnline = false;
159
137
  reportedOffline = true;
@@ -196,21 +174,11 @@ export function wsSignaling(url, options = {}) {
196
174
  if (closed || ws !== socket || settled)
197
175
  return;
198
176
  timedOut = true;
199
- try {
200
- socket.close();
201
- }
202
- catch {
203
- // Ignore close errors.
204
- }
177
+ safeCloseSocket(socket);
205
178
  }, handshakeTimeoutMs);
206
179
  socket.onopen = () => {
207
180
  if (closed || ws !== socket) {
208
- try {
209
- socket.close();
210
- }
211
- catch {
212
- // Ignore close errors.
213
- }
181
+ safeCloseSocket(socket);
214
182
  return;
215
183
  }
216
184
  settled = true;
@@ -219,12 +187,7 @@ export function wsSignaling(url, options = {}) {
219
187
  attempt = 0;
220
188
  awaitingPong = false;
221
189
  if (!sendJson({ type: 'join', room: roomKey, id: discovery.self })) {
222
- try {
223
- socket.close();
224
- }
225
- catch {
226
- // Ignore close errors.
227
- }
190
+ safeCloseSocket(socket);
228
191
  return;
229
192
  }
230
193
  if (!reportedOnline) {
@@ -238,22 +201,12 @@ export function wsSignaling(url, options = {}) {
238
201
  if (useEncryption)
239
202
  replayGuard.prune();
240
203
  if (awaitingPong) {
241
- try {
242
- socket.close();
243
- }
244
- catch {
245
- // Ignore close errors.
246
- }
204
+ safeCloseSocket(socket);
247
205
  return;
248
206
  }
249
207
  awaitingPong = true;
250
208
  if (!sendJson({ type: 'ping' })) {
251
- try {
252
- socket.close();
253
- }
254
- catch {
255
- // Ignore close errors.
256
- }
209
+ safeCloseSocket(socket);
257
210
  }
258
211
  }, pingIntervalMs);
259
212
  };
@@ -365,12 +318,7 @@ export function wsSignaling(url, options = {}) {
365
318
  socket.onerror = () => {
366
319
  if (ws !== socket)
367
320
  return;
368
- try {
369
- socket.close();
370
- }
371
- catch {
372
- // Ignore close errors.
373
- }
321
+ safeCloseSocket(socket);
374
322
  };
375
323
  socket.onclose = (event) => {
376
324
  if (ws !== socket)
@@ -426,12 +374,7 @@ export function wsSignaling(url, options = {}) {
426
374
  if (closed)
427
375
  return;
428
376
  reportOffline('WebSocket signaling key derivation failed');
429
- try {
430
- ws?.close();
431
- }
432
- catch {
433
- // Ignore close errors.
434
- }
377
+ safeCloseSocket(ws);
435
378
  });
436
379
  }
437
380
  // Defer initial connect so synchronous errors never fire before callers attach listeners.
@@ -492,17 +435,19 @@ export function wsSignaling(url, options = {}) {
492
435
  // Ignore send errors during close.
493
436
  }
494
437
  }
495
- try {
496
- current.close();
497
- }
498
- catch {
499
- // Ignore close errors.
500
- }
438
+ safeCloseSocket(current);
501
439
  }
502
440
  }
503
441
  };
504
442
  };
505
443
  }
444
+ /**
445
+ * Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
446
+ * When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
447
+ */
448
+ export function wsSignaling(url, options = {}) {
449
+ return createWsSignaling(url, options, false);
450
+ }
506
451
  /**
507
452
  * Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
508
453
  * - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
@@ -511,53 +456,5 @@ export function wsSignaling(url, options = {}) {
511
456
  * the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
512
457
  */
513
458
  export function optionalWsSignaling(url, options = {}) {
514
- const baseWs = wsSignaling(url, {
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
- };
459
+ return createWsSignaling(url, options, true);
563
460
  }
package/docs/api.md ADDED
@@ -0,0 +1,217 @@
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`, `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`, `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`, `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
+ - `MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown'`.
123
+ - `listAudioInputs(): Promise<readonly AudioInputDevice[]>` — Safe cross-runtime audio input enumeration (`{ deviceId, label, groupId }`).
124
+ - `onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: AudioInputsChangeOptions): () => void`
125
+ - `AudioInputsChangeOptions` extends `ListenOptions` with `immediate?: boolean` (default `false`).
126
+
127
+ ---
128
+
129
+ ## `@dimchansky/meshpost/identity`
130
+
131
+ - `createIdentity(options?: { extractable?: boolean }): Promise<PeerIdentity>` (`extractable` defaults to `true`).
132
+ - `PeerIdentity = { readonly userId: string, readonly publicKey: string }`.
133
+ - `exportIdentity(identity: PeerIdentity): Promise<SerializedIdentity>`
134
+ - `importIdentity(data: unknown, options?: { extractable?: boolean }): Promise<PeerIdentity>` (cryptographically verifies `(x, y)` against `d`).
135
+ - `isSerializedIdentity(value: unknown): value is SerializedIdentity`
136
+ - `createIdentityStore(options: { key: string, storage?: IdentityStorage | null }): IdentityStore`
137
+ - `IdentityStore`: `readonly current: PeerIdentity | null`, `load(): Promise<PeerIdentity>`, `rotate(): Promise<PeerIdentity>`, `clear(): void`.
138
+
139
+ ---
140
+
141
+ ## `@dimchansky/meshpost/turn`
142
+
143
+ - `fetchTurnCredentials(url: string, options?: FetchTurnOptions): Promise<RTCIceServer[]>`
144
+ - `FetchTurnOptions = { accessKey?: string, signal?: AbortSignal, timeoutMs?: number }` (`timeoutMs` defaults to `5000`; pass `0` to disable).
145
+
146
+ ---
147
+
148
+ ## `@dimchansky/meshpost/public`
149
+
150
+ - `publicSignaling(options?: PublicSignalingOptions): Signaling`
151
+ - 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`.
152
+ - `PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs'`.
153
+ - `PublicTransportEvent = { readonly transport: PublicTransportKind, readonly url?: string, readonly state: SignalingState, readonly reason?: string }`.
154
+
155
+ ---
156
+
157
+ ## `@dimchansky/meshpost/ws`
158
+
159
+ - `wsSignaling(url: string, options?: WsSignalingOptions): Signaling`
160
+ - Options: `reconnect` (`true`), `handshakeTimeoutMs` (`10000`), `pingIntervalMs` (`25000`), `encrypt` (`true`), `privateTopic` (`false`), `WebSocket`.
161
+ - `optionalWsSignaling(url: string, options?: OptionalWsSignalingOptions): Signaling`
162
+ - Opportunistic single-shot WS adapter (`reconnect: false`, `handshakeTimeoutMs: 4000` default, suppresses `'signaling-error'`).
163
+
164
+ ---
165
+
166
+ ## `@dimchansky/meshpost/mqtt`
167
+
168
+ - `mqttSignaling(options?: MqttSignalingOptions): Signaling`
169
+ - Options: `urls` (`defaultMqttRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
170
+ - `defaultMqttRelays: readonly string[]`
171
+
172
+ ---
173
+
174
+ ## `@dimchansky/meshpost/nostr`
175
+
176
+ - `nostrSignaling(options?: NostrSignalingOptions): Signaling`
177
+ - Options: `urls` (`defaultNostrRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
178
+ - `defaultNostrRelays: readonly string[]`
179
+
180
+ ---
181
+
182
+ ## `@dimchansky/meshpost/tabs`
183
+
184
+ - `tabSignaling(): Signaling` — Same-origin `BroadcastChannel` signaling (zero network).
185
+
186
+ ---
187
+
188
+ ## `@dimchansky/meshpost/manual`
189
+
190
+ - `manualSignaling(outgoing: (to: string, text: string) => void): ManualSignaling`
191
+ - `ManualSignaling = { readonly signaling: Signaling, contact(): string, accept(text: string): void, forget(peerId: string): void }`.
192
+
193
+ ---
194
+
195
+ ## `@dimchansky/meshpost/combine`
196
+
197
+ - `combineSignaling(...adapters: readonly Signaling[]): Signaling`
198
+ - `withLocalTabs(primary: Signaling): Signaling`
199
+
200
+ ---
201
+
202
+ ## `@dimchansky/meshpost/signaling`
203
+
204
+ - `observeSignaling(adapter: Signaling, onChange: (state: SignalingState, reason?: string) => void): Signaling`
205
+ - `isUuid(value: unknown): value is string`
206
+ - `isSignal(value: unknown): value is Signal`
207
+ - `withLoopbackFallback<T extends Signal>(signal: T): T`
208
+ - Types: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `WebSocketConstructor`.
209
+
210
+ ---
211
+
212
+ ## See also
213
+
214
+ - [Guide](./guide.md) — step-by-step usage examples
215
+ - [Voice & Media](./voice-and-media.md) — voice and custom `MediaStream` guide
216
+ - [Signaling & Production](./signaling-and-production.md) — signaling recipes, TURN, edge workers, and headless peers
217
+ - [Behavior & Security Spec](./behavior.md) — protocol details, invariants, limits, and security model
package/docs/behavior.md CHANGED
@@ -90,7 +90,7 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
90
90
  - `combineSignaling()` throws `RangeError` when given 0 adapters and `TypeError` if any argument is not a function; `withLocalTabs()` throws `TypeError` if `primary` is not a function.
91
91
  - `mqttSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for an empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
92
92
  - `nostrSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for non-`ws:`/`wss:` `urls`, invalid `appId`, empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
93
- - `createVoice()` throws `TypeError` for invalid `room`, `deviceId`, `fallbackToDefaultOnNotFound`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `onAudioInputsChange()` throws `TypeError` for a non-function listener. `voice.setVolume()` and `voice.setPeerVolume()` throw `RangeError` for non-finite numbers; `voice.setPeerVolume()` and `voice.setPeerMuted()` throw `TypeError` for invalid `peerId` strings (`1..128` chars); `voice.switchDevice()` rejects with `TypeError` for whitespace-only/non-string `deviceId` values.
93
+ - `createVoice()` throws `TypeError` for invalid `room`, `deviceId`, `fallbackToDefaultOnNotFound`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `onAudioInputsChange()` throws `TypeError` for a non-function listener or a non-boolean `immediate` option. `voice.setVolume()` and `voice.setPeerVolume()` throw `RangeError` for non-finite numbers; `voice.setPeerVolume()` and `voice.setPeerMuted()` throw `TypeError` for invalid `peerId` strings (`1..128` chars); `voice.switchDevice()` rejects with `TypeError` for whitespace-only/non-string `deviceId` values.
94
94
  - `fetchTurnCredentials()` rejects with `TypeError` for invalid URLs, disallowed protocols, embedded URL credentials, or invalid `accessKey`, and `RangeError` for invalid `timeoutMs`.
95
95
 
96
96
  ## Sending and receiving
@@ -204,6 +204,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
204
204
  - `0x03` `ABORT`: `[0x03, transferId (u32 BE)]` (sent best-effort on sender `AbortSignal` cancellation, `blobChannel.close()`, or mid-transfer `'too-large'`).
205
205
  - Senders pace every recipient independently (`channel.send(frame, { to: peerId })`) using `room.onDrain` so one slow peer never stalls another during broadcast.
206
206
  - Receivers reject `START` frames exceeding `maxReceiveBytes` (`4 MiB` default) or `maxConcurrentPerPeer` (`4` default) without allocating, accumulate incoming bytes into a growable `Uint8Array` clamped to `totalBytes` (preventing upfront memory-amplification DoS while avoiding per-chunk object overhead), and enforce a per-transfer frame cap (`Math.ceil(totalBytes / 256) + 64`) against 1-byte chunk floods. `receiveTimeoutMs` (`30 s` default) is an inactivity timeout reset on each `DATA` chunk; incomplete transfers are also discarded on `ABORT`, `onPeerLeave`, or `close()`.
207
+ - Automatically closes on `room.leave()` via the internal room-close hook (never closing prematurely when a signaling adapter reports `'closed'` while active WebRTC links stay open; falls back to `onSignalingChange('closed')` only for duck-typed mock `Room` objects).
207
208
 
208
209
  ## Signaling adapters
209
210
 
@@ -214,6 +215,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
214
215
  - Report `status('online')` before publishing a roster.
215
216
  - Deliver a roster containing a sender before calling `receive(from, signal)`.
216
217
  - Isolate rooms by `(appId, room)` (and `password` if used).
218
+ - `observeSignaling(adapter, onChange)` decorates any `Signaling` adapter to observe per-session `SignalingState` transitions without modifying `Room` or `Discovery`, deduplicating consecutive identical states, isolating callback exceptions via `reportError`, and preserving `trickle` and `canReach` on the wrapped `SignalingSession`.
217
219
 
218
220
  | `Signal` | Purpose |
219
221
  | -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
@@ -277,8 +279,12 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
277
279
 
278
280
  ### `createVoice(room, options?)` and `fetchTurnCredentials(url, options?)`
279
281
 
280
- - `createVoice(room, options?)` tags outgoing mic streams with `streamTag` (`'voice'` default) and attaches hidden `<audio autoplay>` elements for up to `4` matching remote audio streams per peer (`meta.tag === streamTag`, plus untagged streams when `strictStreamTag` is `false`; hydrating any streams already active on `room` at construction), supports optional initial `deviceId` with `fallbackToDefaultOnNotFound` (silent single-epoch fallback to system default only on initial mic acquisition, never on live `switchDevice`), per-peer volume (`setPeerVolume`, scaled by master `volume`, exposed as immutable sparse `peerVolumes`, `128`-peer cap) and per-peer mute (`setPeerMuted`, independent of `deafened`, `128`-peer cap), hot-swaps microphone input devices via serialized `switchDevice(deviceId?)` + `room.replaceStreamTrack()` with zero SDP renegotiation, coalesces concurrent `startMic()`/`toggleMic()` calls, cancels pending `getUserMedia` via `micEpoch`/`switchEpoch` on `stopMic()`/`close()`, saves/restores `navigator.audioSession.type` (`'play-and-record'`) across all exit paths, routes `AnalyserNode` through a zero-gain `GainNode` to `destination` for WebKit pull-graph compatibility, unlocks blocked audio via lock-free `{ capture: true }` gestures + `visibilitychange`, and closes automatically on `room.leave()` without redundant `removeStream()` renegotiation. Separate tree-shakeable `listAudioInputs()` and `onAudioInputsChange(cb, options?)` helpers enumerate and watch audio inputs (filtering out raw `'default'` / `'communications'` aliases when hardware devices exist).
281
- - `fetchTurnCredentials(url, options?)` validates `https://` (or `http://localhost` / `127.0.0.1` / `[::1]`) without embedded credentials, sends `POST` with `redirect: 'error'`, `credentials: 'omit'`, `cache: 'no-store'`, enforces `timeoutMs` (`5,000` ms default) and a `64 KiB` streaming body limit, and returns `1..16` sanitized `RTCIceServer` entries (`^(stuns?|turns?):[^\s]+$`).
282
+ - **Stream tagging & playback:** `createVoice(room, options?)` tags outgoing mic streams with `streamTag` (`'voice'` default) and attaches hidden `<audio autoplay>` elements for up to `4` matching remote audio streams per peer (`meta.tag === streamTag`, plus untagged streams when `strictStreamTag` is `false`; hydrating any streams already active on `room` at construction).
283
+ - **Microphone lifecycle & hot-swap:** Coalesces concurrent `startMic()`/`toggleMic()` calls, cancels pending `getUserMedia` via `micEpoch`/`switchEpoch` on `stopMic()`/`close()`, supports optional initial `deviceId` with `fallbackToDefaultOnNotFound` (silent single-epoch fallback to system default only on initial mic acquisition, never on live `switchDevice`), and hot-swaps input devices via serialized `switchDevice(deviceId?)` + `room.replaceStreamTrack()` with zero SDP renegotiation.
284
+ - **Per-peer mixer:** Supports per-peer volume (`setPeerVolume`, scaled by master `volume`, exposed as immutable sparse `peerVolumes`, `128`-peer LRU cap) and per-peer mute (`setPeerMuted`, independent of `deafened`, `128`-peer LRU cap).
285
+ - **Browser audio compatibility:** Saves/restores `navigator.audioSession.type` (`'play-and-record'`) across all exit paths, routes `AnalyserNode` through a zero-gain `GainNode` to `destination` for WebKit pull-graph compatibility, unlocks blocked audio via lock-free `{ capture: true }` gestures + `visibilitychange`, and closes automatically on `room.leave()` without redundant `removeStream()` renegotiation.
286
+ - **Device discovery helpers:** Separate tree-shakeable `listAudioInputs()` and `onAudioInputsChange(cb, options?)` enumerate and watch `audioinput` devices with non-empty `deviceId` (deduplicated by `deviceId`, labels trimmed, returning an empty frozen array if unavailable or rejected). `AudioInputsChangeOptions` extends `ListenOptions` with `immediate?: boolean` to deliver the initial device list through the same monotonic epoch guard as `'devicechange'` events.
287
+ - **`fetchTurnCredentials(url, options?)`:** Validates `https://` (or `http://localhost` / `127.0.0.1` / `[::1]`) without embedded credentials, sends `POST` with `redirect: 'error'`, `credentials: 'omit'`, `cache: 'no-store'`, enforces `timeoutMs` (`5,000` ms default) and a `64 KiB` streaming body limit, and returns `1..16` sanitized `RTCIceServer` entries (`^(stuns?|turns?):[^\s]+$`).
282
288
 
283
289
  ### `manualSignaling(outgoing)`
284
290
 
@@ -293,7 +299,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
293
299
  - **Signaling integrity:** SDP contains the DTLS certificate fingerprint. An attacker who can modify signaling messages can intercept and alter the handshake (MitM).
294
300
  - **Public MQTT / Nostr without `password`:** Anyone on a public relay can observe room topics/tags or tamper with unencrypted SDP. Use `password` or a trusted signaling server whenever confidentiality or authenticity matters.
295
301
  - **Password-encrypted signaling (`mqttSignaling`, `nostrSignaling`, & `wsSignaling`):** When `password` is set, `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (unless `encrypt: false` is explicitly set for plain HTTP LAN testing) derive a 256-bit master secret via a single `PBKDF2-HMAC-SHA256` pass (`100,000` iterations, salt `'meshpost/1/' + namespaceHash(appId:room)`) and expand it via RFC 5869 `HKDF-SHA256` into an `AES-256-GCM` key (`info: 'meshpost/1/aead'`) and a 128-bit `privateId` (`info: 'meshpost/1/topic'`). _(Note: adding HKDF domain separation updates the password wire derivation from v0.2/v0.3 `mqttSignaling`.)_ Every message is authenticated with transport/room/recipient AAD, rejects timestamps outside `±60 s` (emitting `'clock-skew'`), and tracks seen `mid`s for `120 s`. Setting `privateTopic: true` derives the MQTT topic, Nostr `#t` tag, or WS room key from `privateId` so outsiders on shared relays cannot correlate activity to `(appId, room)`. Browser Web Crypto (`crypto.subtle`) requires `https://` or `http://localhost`.
296
- - **Verifiable peer identity & `F5` session reclaim (`createIdentity` & `'meshpost/1/hello:'`):** Optional `PeerIdentity` proves ownership of a 128-bit `userId` (`SHA-256("meshpost/1/userid:" || rawUncompressedP256PubKey)[0..16]`) via a WebCrypto `ECDSA P-256` (`SHA-256`) signature bound to `(appId, room, signerId, verifierId, signerDtlsFp, verifierDtlsFp)` — rejecting weak hashes and multi-fingerprint SDP injections (RFC 8122 §5) so even an active MitM on unencrypted signaling cannot relay or replay `id.sig`. Same-tab `F5` ghost-session eviction requires presenting the 128-bit preimage matching the prior link's `SHA-256` commitment (`reclaimCommit`, saved to `sessionStorage` only on `pagehide`), preventing third-party peers from spoof-dropping live connections.
302
+ - **Verifiable peer identity & `F5` session reclaim (`createIdentity`, `createIdentityStore`, & `'meshpost/1/hello:'`):** Optional `PeerIdentity` proves ownership of a 128-bit `userId` (`SHA-256("meshpost/1/userid:" || rawUncompressedP256PubKey)[0..16]`) via a WebCrypto `ECDSA P-256` (`SHA-256`) signature bound to `(appId, room, signerId, verifierId, signerDtlsFp, verifierDtlsFp)` — rejecting weak hashes and multi-fingerprint SDP injections (RFC 8122 §5) so even an active MitM on unencrypted signaling cannot relay or replay `id.sig`. `createIdentityStore({ key, storage? })` manages race-safe persistence (`load()`, `rotate()`, `clear()`, and synchronous `current` getter) with a `1,024`-char read cap, cryptographic self-verification on import, corrupt-entry self-healing, and `SecurityError` in-memory fallback. Same-tab `F5` ghost-session eviction requires presenting the 128-bit preimage matching the prior link's `SHA-256` commitment (`reclaimCommit`, saved to `sessionStorage` only on `pagehide`), preventing third-party peers from spoof-dropping live connections.
297
303
  - **Chunked transfers (`createBlobChannel`):** Default worst-case receive memory is `maxConcurrentPerPeer × maxReceiveBytes` (`16 MiB/peer`, up to `512 MiB` across `32` peers), and `receiveTimeoutMs` resets on each `DATA` chunk. Apps facing untrusted peers should tune these bounds accordingly.
298
304
  - **Manual signaling:** Exchange connection text only over a trusted channel with the intended peer.
299
305
  - **Application concerns:** Authorization, shared state semantics, and game rules belong in the application layer.