@dimchansky/meshpost 0.4.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -550
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +15 -16
- package/dist/channel.js +15 -44
- package/dist/combine.js +25 -39
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +188 -28
- package/dist/index.d.ts +6 -6
- package/dist/index.js +3 -3
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +193 -408
- package/dist/nostr.js +163 -745
- package/dist/public.d.ts +19 -1
- package/dist/public.js +26 -9
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +323 -0
- package/dist/room-hello.d.ts +1 -0
- package/dist/room-hello.js +129 -0
- package/dist/room-ice.d.ts +1 -0
- package/dist/room-ice.js +115 -0
- package/dist/room-media.d.ts +1 -0
- package/dist/room-media.js +477 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +111 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +109 -919
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +64 -0
- package/dist/state.js +1 -2
- package/dist/voice-helpers.d.ts +1 -0
- package/dist/voice-helpers.js +100 -0
- package/dist/voice-meter.d.ts +1 -0
- package/dist/voice-meter.js +79 -0
- package/dist/voice.d.ts +41 -0
- package/dist/voice.js +205 -273
- package/dist/ws.js +60 -146
- package/docs/api.md +217 -0
- package/docs/behavior.md +16 -9
- 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 +3 -2
package/docs/behavior.md
CHANGED
|
@@ -35,7 +35,7 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
35
35
|
- In browser tabs with `crypto.subtle`, `joinRoom()` automatically commits a 128-bit one-time Lamport preimage (`SHA-256("meshpost/1/reclaim:" + self + ":" + secret)`) in its WebRTC `hello` frame and writes `{ id, secret, ts }` to `sessionStorage` **only on `pagehide`** (so duplicating a live tab never clones the secret), alongside a best-effort `meshpost/1/leave` notice when `!event.persisted`. When a reloaded tab (`F5`) reconnects within `60 s`, remote peers verify the preimage, drop the superseded ghost connection (`onPeerLeave(oldId)` fires strictly before `onPeerJoin(newId)`), and ignore `oldId` in future roster snapshots (`128`-entry FIFO cap) without waiting `8,000 ms` `disconnectGrace`.
|
|
36
36
|
- `joinRoom()` returns synchronously and starts discovery immediately.
|
|
37
37
|
- `room.peers` returns a snapshot array of remote peer IDs whose unreliable and reliable channels have opened and completed the `'meshpost/1/hello:'` handshake.
|
|
38
|
-
- Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `codecChannel.onMessage`, `peerState.onChange`, `rpc.handle`, `blobChannel.onBlob`, `blobChannel.onProgress`,
|
|
38
|
+
- Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `codecChannel.onMessage`, `peerState.onChange`, `rpc.handle`, `blobChannel.onBlob`, `blobChannel.onProgress`, `voice.onChange`, and `onAudioInputsChange`) returns an idempotent unsubscribe function and optionally accepts `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`).
|
|
39
39
|
- Subscribing with an already-aborted `signal` (or after `room.leave()`) is a no-op. Unsubscribing, firing a `once` listener, or calling `room.leave()` detaches any registered `'abort'` listener from `signal`. On `channel.onPacket`, `once` unsubscribes only after a packet matches both delivery mode and channel name; on `codecChannel.onMessage` and `rpc.handle`, `once` unsubscribes only after `codec.decode` succeeds.
|
|
40
40
|
- A room of `N` peers forms up to `N(N - 1) / 2` direct connections (bounded per peer by `maxPeers`).
|
|
41
41
|
- There is no host election, packet forwarding, or history replay. Any peer can join first.
|
|
@@ -76,7 +76,7 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
|
|
|
76
76
|
### Synchronous errors
|
|
77
77
|
|
|
78
78
|
- `joinRoom()` throws `TypeError` for invalid `name` (`^[a-zA-Z0-9_-]{1,64}$`), invalid `appId` (`^[a-zA-Z0-9._-]{1,64}$`), empty `password`, an invalid/forged `identity` (`PeerIdentity`), or a non-function `RTCPeerConnection` option, and throws `Error` if `RTCPeerConnection` is unavailable on `globalThis` and not provided via `options.RTCPeerConnection`.
|
|
79
|
-
- `createIdentity()`, `exportIdentity()`, and `importIdentity()` reject with `Error` when `crypto.subtle` is unavailable, `exportIdentity()` rejects with `Error` when `extractable: false`, `importIdentity()` rejects with `TypeError` on invalid shape (`!isSerializedIdentity`) or `Error` if `(x, y)` fails a challenge signature check against `d`.
|
|
79
|
+
- `createIdentity()`, `exportIdentity()`, and `importIdentity()` reject with `Error` when `crypto.subtle` is unavailable, `exportIdentity()` rejects with `Error` when `extractable: false`, `importIdentity()` rejects with `TypeError` on invalid shape (`!isSerializedIdentity`) or `Error` if `(x, y)` fails a challenge signature check against `d`. `createIdentityStore()` throws `TypeError` for an invalid `key` (`1..256` chars) or `storage` backend; `load()` / `rotate()` reject with `Error` when `crypto.subtle` is unavailable (without removing any stored entry).
|
|
80
80
|
- `joinRoom()` throws `RangeError` for invalid timeouts or `maxPeers`, throws browser errors immediately if `rtcConfig` is malformed, and throws `Error` if `mqttSignaling()`, `nostrSignaling()`, or default `wsSignaling()` (`encrypt: true`) is used with `password` without `crypto.subtle`.
|
|
81
81
|
- `room.send()` throws `Error` after `leave()`, and `TypeError` for non-`Uint8Array` payloads or invalid `delivery`.
|
|
82
82
|
- `room.addStream()` throws `Error` after `leave()`, and `TypeError` for non-`MediaStream` arguments, invalid `AddStreamOptions`, or invalid `tag` (`^[a-zA-Z0-9._-]{1,32}$`). `room.replaceStreamTrack()` rejects with `Error` if the room is closed or the stream is not attached, and `TypeError` for invalid or mismatched-`kind` tracks.
|
|
@@ -86,11 +86,11 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
|
|
|
86
86
|
- `createPeerState()` throws `TypeError` for an invalid `room`, `delivery`, `coalesce`, `codec`, `undefined` state value, or non-function `onChange` listener; `RangeError` if `initial` or `set(value)` encodes past the 16 KiB packet limit; and `Error` when calling `set()` or `clear()` after `close()` or `room.leave()`.
|
|
87
87
|
- `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
|
|
88
88
|
- `wsSignaling()` and `optionalWsSignaling()` throw `TypeError` for non-`ws:`/`wss:` URLs, non-boolean `encrypt`/`privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option; `Error` if `privateTopic: true` is combined with `encrypt: false` or if `WebSocket` is unavailable at session startup; and `RangeError` for invalid `handshakeTimeoutMs` or `pingIntervalMs`.
|
|
89
|
-
- `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, or a non-function `
|
|
89
|
+
- `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, a non-function `WebSocket` option, or a non-function `onTransportChange` callback; and `RangeError` when both `mqtt: false` and `nostr: false`, when `mqtt`/`nostr` is an empty array, when `wsUrls` exceeds `8` unique (`64` raw) entries, or when `wsHandshakeTimeoutMs` / `handshakeTimeoutMs` is out of range.
|
|
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`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `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
|
| -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
@@ -251,13 +253,14 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
251
253
|
- Client sends `{ type: 'join', room, id }` on open (within `handshakeTimeoutMs`, `10,000` ms default), `{ type: 'signal', to, signal | box }` for peer signaling, `{ type: 'ping' }` every `pingIntervalMs` (`25,000` ms default), and `{ type: 'leave' }` on close.
|
|
252
254
|
- Server sends `{ type: 'roster', peers: string[] }` (validated UUIDs, capped at `256`), `{ type: 'signal', from, signal | box }`, and `{ type: 'pong' }`. Incoming frames larger than `128 KiB` are ignored.
|
|
253
255
|
- Tracks `awaitingPong`: if no `{ type: 'pong' }` (or other valid server message) arrives before the next ping interval, the socket is closed to trigger reconnect.
|
|
254
|
-
- Reconnects with jittered exponential backoff (`500 ms` to `10 s`, `±25%` jitter) when `reconnect` is `true` (default), emitting `'offline'` and `'signaling-error'` once per offline transition.
|
|
255
|
-
- `optionalWsSignaling(url, options?)` wraps `wsSignaling` with `reconnect: false` and a `4,000 ms` default `handshakeTimeoutMs`, forwarding `'online'` while healthy and transitioning cleanly to `'closed'` (closing the underlying session and suppressing `'signaling-error'`) on any non-`'online'` transition while still forwarding `'decrypt-failed'` and `'clock-skew'`.
|
|
256
|
+
- Reconnects with jittered exponential backoff (`500 ms` to `10 s`, `±25%` jitter) when `reconnect` is `true` (default), emitting `'offline'` and `'signaling-error'` once per offline transition. Distinguishes client-side handshake timeouts (`'WebSocket signaling handshake timed out'`) and non-standard numeric WebSocket close codes (`code !== 1000 && code !== 1005 && code !== 1006`) in `reason` without interpolating untrusted remote `CloseEvent.reason` strings.
|
|
257
|
+
- `optionalWsSignaling(url, options?)` wraps `wsSignaling` with `reconnect: false` and a `4,000 ms` default `handshakeTimeoutMs`, forwarding `'online'` while healthy and transitioning cleanly to `'closed'` (forwarding `reason`, closing the underlying session, and suppressing `'signaling-error'`) on any non-`'online'` transition while still forwarding `'decrypt-failed'` and `'clock-skew'`.
|
|
256
258
|
|
|
257
259
|
### `publicSignaling(options?)`
|
|
258
260
|
|
|
259
261
|
- Flattens zero or more `optionalWsSignaling(url, ...)` children (`wsUrls?: string | readonly string[]`, validated `ws:`/`wss:`, deduplicated, capped at `8` unique URLs and `64` raw entries) together with `mqttSignaling()` (`mqtt: true` default) and `nostrSignaling()` (`nostr: true` default) into a single `combineSignaling(...)` instance, wrapped in `withLocalTabs(...)` when `localTabs` is `true` (default).
|
|
260
262
|
- Treats enabled transports as a single redundant pool: suppresses per-transport `'signaling-error'` while any sibling transport is `'online'` or `'connecting'` (e.g. when corporate Wi-Fi blocks MQTT ports while port-443 Nostr or `wsUrls` succeeds) and emits `'signaling-error'` once per aggregate `'offline'` transition, while forwarding `'decrypt-failed'` and `'clock-skew'`.
|
|
263
|
+
- Optional `onTransportChange?: (event: PublicTransportEvent) => void` observes per-transport (`'ws' | 'mqtt' | 'nostr' | 'tabs'`) state transitions with frozen events (`{ transport, url?, state, reason? }`), deduplicating repeated states, isolating callback errors via `reportError`, preserving child `trickle` and `canReach` capabilities, and omitting `'tabs'` events when `BroadcastChannel` is unavailable. Note: per the WHATWG WebSocket specification, browsers hide HTTP status codes (`403`, etc.) and TLS errors behind close code `1006`; client-side handshake timeouts and non-`1006` close codes appear in `reason`.
|
|
261
264
|
- Requires at least one persistent public relay transport (`mqtt !== false || nostr !== false`).
|
|
262
265
|
|
|
263
266
|
### `combineSignaling(...adapters)`
|
|
@@ -276,8 +279,12 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
276
279
|
|
|
277
280
|
### `createVoice(room, options?)` and `fetchTurnCredentials(url, options?)`
|
|
278
281
|
|
|
279
|
-
- `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)
|
|
280
|
-
- `
|
|
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]+$`).
|
|
281
288
|
|
|
282
289
|
### `manualSignaling(outgoing)`
|
|
283
290
|
|
|
@@ -292,7 +299,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
292
299
|
- **Signaling integrity:** SDP contains the DTLS certificate fingerprint. An attacker who can modify signaling messages can intercept and alter the handshake (MitM).
|
|
293
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.
|
|
294
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`.
|
|
295
|
-
- **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.
|
|
296
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.
|
|
297
304
|
- **Manual signaling:** Exchange connection text only over a trusted channel with the intended peer.
|
|
298
305
|
- **Application concerns:** Authorization, shared state semantics, and game rules belong in the application layer.
|
package/docs/guide.md
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# Meshpost Guide
|
|
2
|
+
|
|
3
|
+
A progressive walkthrough of `@dimchansky/meshpost`, from a 15-line peer-to-peer chat to replicated state, RPC, large file transfers, verifiable identities, and production teardown.
|
|
4
|
+
|
|
5
|
+
- Looking for microphone / audio streams? See [Voice & Media](./voice-and-media.md).
|
|
6
|
+
- Looking for signaling transports, TURN, edge workers, or Node/Bun/Deno? See [Signaling & Production](./signaling-and-production.md).
|
|
7
|
+
- Looking for exact types and option defaults? See [API Reference](./api.md) and [Behavior & Security Spec](./behavior.md).
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. Minimal P2P chat (15 lines)
|
|
12
|
+
|
|
13
|
+
`joinRoom()` creates a hostless WebRTC mesh room and starts discovering peers immediately. Multiplexed channels (`createCodecChannel`) let you send typed messages without opening extra `RTCDataChannel`s.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { joinRoom } from '@dimchansky/meshpost/room'
|
|
17
|
+
import { publicSignaling } from '@dimchansky/meshpost/public'
|
|
18
|
+
import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
|
|
19
|
+
|
|
20
|
+
const room = joinRoom('team-standup', {
|
|
21
|
+
password: 'shared-room-secret',
|
|
22
|
+
signaling: publicSignaling()
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
|
|
26
|
+
|
|
27
|
+
room.onPeerJoin((peerId) => console.log('joined:', peerId))
|
|
28
|
+
room.onPeerLeave((peerId) => console.log('left:', peerId))
|
|
29
|
+
chat.onMessage((from, text) => console.log(from, text))
|
|
30
|
+
|
|
31
|
+
// Broadcast to everyone, or pass { to: peerId } for a direct message
|
|
32
|
+
chat.send('Hello mesh!')
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
What happens under the hood:
|
|
36
|
+
|
|
37
|
+
- `publicSignaling()` connects to public MQTT + port-443 Nostr relays **and** wraps them with `withLocalTabs()` for instant same-browser tab discovery.
|
|
38
|
+
- Setting `password` encrypts SDP/ICE signaling end-to-end with `AES-256-GCM` before it touches any relay; once connected, all WebRTC traffic is DTLS-encrypted directly between peers.
|
|
39
|
+
- Every browser tab gets a random `room.id` (UUID v4). A page reload gets a fresh `room.id` and automatically reclaims its previous ghost session.
|
|
40
|
+
|
|
41
|
+
For a zero-build single HTML file you can open directly, see [examples/minimal-chat.html](../examples/minimal-chat.html).
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 2. Typed codecs, binary `DataView`, and `ListenOptions`
|
|
46
|
+
|
|
47
|
+
### Validated JSON messages
|
|
48
|
+
|
|
49
|
+
Pass a TypeScript type guard to `jsonCodec()` to validate untrusted remote packets at runtime and infer `Codec<T>` automatically. Malformed frames are silently dropped without throwing or consuming `{ once: true }` listeners.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { createCodecChannel, jsonCodec } from '@dimchansky/meshpost/channel'
|
|
53
|
+
|
|
54
|
+
interface ChatMessage {
|
|
55
|
+
text: string
|
|
56
|
+
sentAt: number
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const isChatMessage = (v: unknown): v is ChatMessage =>
|
|
60
|
+
typeof v === 'object' &&
|
|
61
|
+
v !== null &&
|
|
62
|
+
typeof (v as ChatMessage).text === 'string' &&
|
|
63
|
+
typeof (v as ChatMessage).sentAt === 'number'
|
|
64
|
+
|
|
65
|
+
const chat = createCodecChannel(room, 'chat', jsonCodec(isChatMessage), {
|
|
66
|
+
delivery: 'reliable'
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
chat.onMessage((from, msg) => {
|
|
70
|
+
// msg is typed as ChatMessage
|
|
71
|
+
console.log(from, msg.text, new Date(msg.sentAt))
|
|
72
|
+
})
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Custom binary `Codec<T>`
|
|
76
|
+
|
|
77
|
+
For high-frequency game ticks or cursors, implement `Codec<T>` with a `DataView` to avoid JSON overhead:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { createCodecChannel, type Codec } from '@dimchansky/meshpost/channel'
|
|
81
|
+
|
|
82
|
+
interface Cursor {
|
|
83
|
+
x: number
|
|
84
|
+
y: number
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const cursorCodec: Codec<Cursor> = {
|
|
88
|
+
encode({ x, y }) {
|
|
89
|
+
const buf = new ArrayBuffer(8)
|
|
90
|
+
const view = new DataView(buf)
|
|
91
|
+
view.setFloat32(0, x, true)
|
|
92
|
+
view.setFloat32(4, y, true)
|
|
93
|
+
return new Uint8Array(buf)
|
|
94
|
+
},
|
|
95
|
+
decode(bytes) {
|
|
96
|
+
if (bytes.byteLength !== 8) throw new Error('Invalid cursor')
|
|
97
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
98
|
+
const x = view.getFloat32(0, true)
|
|
99
|
+
const y = view.getFloat32(4, true)
|
|
100
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('Non-finite cursor')
|
|
101
|
+
return { x, y }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const cursors = createCodecChannel(room, 'cursor', cursorCodec, {
|
|
106
|
+
delivery: 'unreliable'
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Cancelling subscriptions with `AbortController`
|
|
111
|
+
|
|
112
|
+
Every event subscription (`room.on*`, `channel.on*`, `state.onChange`, `rpc.handle`, `blobs.on*`, `voice.onChange`, `onAudioInputsChange`) accepts `ListenOptions`: `{ once?: boolean, signal?: AbortSignal }`. Tie all UI/session listeners to one `AbortController`:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const ac = new AbortController()
|
|
116
|
+
const { signal } = ac
|
|
117
|
+
|
|
118
|
+
room.onPeerJoin((id) => console.log('joined', id), { signal })
|
|
119
|
+
chat.onMessage((from, msg) => console.log(from, msg), { signal })
|
|
120
|
+
room.onPeerJoin((id) => console.log('first peer:', id), { once: true, signal })
|
|
121
|
+
|
|
122
|
+
// One call unsubscribes everything
|
|
123
|
+
ac.abort()
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 3. Raw binary channels, delivery modes, and backpressure
|
|
129
|
+
|
|
130
|
+
Each peer link maintains two native `RTCDataChannel`s:
|
|
131
|
+
|
|
132
|
+
- `'unreliable'` (default) — unordered, zero retransmits (`maxRetransmits: 0`). Ideal for cursors, positions, and telemetry where the newest snapshot replaces older ones.
|
|
133
|
+
- `'reliable'` — ordered, guaranteed delivery. Ideal for chat, commands, RPC, and state hydration.
|
|
134
|
+
|
|
135
|
+
Both `room.send()` and `channel.send()` are **synchronous** and return `ReadonlyMap<string, SendResult>` (`'accepted' | 'unavailable' | 'busy' | 'too-large'`). The hard per-packet cap is `16 KiB` (`16,384` bytes, including channel header).
|
|
136
|
+
|
|
137
|
+
When a peer's WebRTC send buffer reaches its high-water mark, `send()` returns `'busy'` for that peer without blocking other peers. Resume when `room.onDrain` fires:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { createChannel } from '@dimchansky/meshpost/channel'
|
|
141
|
+
|
|
142
|
+
const frames = createChannel(room, 'frames', { delivery: 'reliable' })
|
|
143
|
+
const pending = new Map<string, Uint8Array[]>()
|
|
144
|
+
|
|
145
|
+
function enqueue(peerId: string, bytes: Uint8Array) {
|
|
146
|
+
const queue = pending.get(peerId) ?? []
|
|
147
|
+
if (queue.length === 0) {
|
|
148
|
+
const status = frames.send(bytes, { to: peerId }).get(peerId)
|
|
149
|
+
if (status === 'accepted') return
|
|
150
|
+
if (status !== 'busy') return // 'unavailable' or 'too-large'
|
|
151
|
+
}
|
|
152
|
+
queue.push(bytes)
|
|
153
|
+
pending.set(peerId, queue)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
room.onDrain((peerId, delivery) => {
|
|
157
|
+
if (delivery !== 'reliable') return
|
|
158
|
+
const queue = pending.get(peerId)
|
|
159
|
+
while (queue && queue.length > 0) {
|
|
160
|
+
const status = frames.send(queue[0], { to: peerId }).get(peerId)
|
|
161
|
+
if (status === 'busy') return
|
|
162
|
+
queue.shift()
|
|
163
|
+
}
|
|
164
|
+
pending.delete(peerId)
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
room.onPeerLeave((peerId) => pending.delete(peerId))
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## 4. Replicated per-peer state (`createPeerState`)
|
|
173
|
+
|
|
174
|
+
`createPeerState()` synchronizes one value per peer (display names, ready flags, player loadouts, live cursors). It automatically:
|
|
175
|
+
|
|
176
|
+
- Hydrates your latest state reliably to every late joiner on `onPeerJoin`.
|
|
177
|
+
- Drops out-of-order packets using RFC 1982 `u32` sequence numbers (safe for `'unreliable'` delivery).
|
|
178
|
+
- Coalesces `'busy'` updates and retries the latest value on `room.onDrain` (`coalesce: true` by default).
|
|
179
|
+
- Removes disconnected peers automatically on `onPeerLeave`.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { createPeerState } from '@dimchansky/meshpost/state'
|
|
183
|
+
import { jsonCodec } from '@dimchansky/meshpost/channel'
|
|
184
|
+
|
|
185
|
+
interface Presence {
|
|
186
|
+
name: string
|
|
187
|
+
ready: boolean
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const isPresence = (v: unknown): v is Presence =>
|
|
191
|
+
typeof v === 'object' &&
|
|
192
|
+
v !== null &&
|
|
193
|
+
typeof (v as Presence).name === 'string' &&
|
|
194
|
+
typeof (v as Presence).ready === 'boolean'
|
|
195
|
+
|
|
196
|
+
// Important: register your own room.onPeerLeave BEFORE createPeerState()
|
|
197
|
+
// if you want to read presence.get(peerId) before createPeerState deletes it.
|
|
198
|
+
let presence: ReturnType<typeof createPeerState<Presence>>
|
|
199
|
+
|
|
200
|
+
room.onPeerLeave((peerId) => {
|
|
201
|
+
const departed = presence.get(peerId)
|
|
202
|
+
console.log(`${departed?.name ?? peerId} left`)
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
presence = createPeerState<Presence>(room, 'presence', {
|
|
206
|
+
delivery: 'reliable',
|
|
207
|
+
codec: jsonCodec(isPresence),
|
|
208
|
+
initial: { name: 'Alice', ready: false }
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
presence.onChange((peerId, next, prev, reason) => {
|
|
212
|
+
// reason distinguishes 'set' | 'clear' | 'leave'
|
|
213
|
+
if (reason === 'set' && next) {
|
|
214
|
+
console.log(peerId, 'updated:', prev, '->', next)
|
|
215
|
+
} else if (reason === 'clear') {
|
|
216
|
+
console.log(peerId, 'cleared presence')
|
|
217
|
+
}
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
// Later: update or clear your own state
|
|
221
|
+
presence.set({ name: 'Alice', ready: true })
|
|
222
|
+
presence.clear()
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## 5. Request-response RPC (`createRpc`)
|
|
228
|
+
|
|
229
|
+
Each `createRpc(room, name)` creates a dedicated typed request-response endpoint over a reliable channel, with automatic correlation IDs, per-peer anti-spoofing, timeouts, `AbortSignal`, disconnect cancellation, and structured `RpcError` codes (`'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed'`).
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
import { createRpc, RpcError } from '@dimchansky/meshpost/rpc'
|
|
233
|
+
|
|
234
|
+
interface PingReq {
|
|
235
|
+
sentAt: number
|
|
236
|
+
}
|
|
237
|
+
interface PingRes {
|
|
238
|
+
echoedAt: number
|
|
239
|
+
serverNow: number
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const ping = createRpc<PingReq, PingRes>(room, 'ping', { timeoutMs: 5_000 })
|
|
243
|
+
|
|
244
|
+
// Register the handler (at most one active handler per endpoint)
|
|
245
|
+
ping.handle((_from, req) => ({
|
|
246
|
+
echoedAt: req.sentAt,
|
|
247
|
+
serverNow: Date.now()
|
|
248
|
+
}))
|
|
249
|
+
|
|
250
|
+
// Call a remote peer with optional AbortSignal & timeout override
|
|
251
|
+
const ac = new AbortController()
|
|
252
|
+
try {
|
|
253
|
+
const res = await ping.call(
|
|
254
|
+
peerId,
|
|
255
|
+
{ sentAt: Date.now() },
|
|
256
|
+
{ timeoutMs: 3_000, signal: ac.signal }
|
|
257
|
+
)
|
|
258
|
+
console.log('RTT ms:', Date.now() - res.echoedAt)
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (err instanceof RpcError) {
|
|
261
|
+
console.warn(`RPC failed (${err.code}) for ${err.peerId}: ${err.message}`)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
---
|
|
267
|
+
|
|
268
|
+
## 6. Large files & binary blobs (`createBlobChannel`)
|
|
269
|
+
|
|
270
|
+
For payloads larger than the `16 KiB` packet cap (images, canvas snapshots, saved files), `createBlobChannel()` chunks data over a reliable channel with `onDrain` backpressure, progress callbacks, `AbortSignal`, and bounded receive memory.
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import { createBlobChannel } from '@dimchansky/meshpost/blob'
|
|
274
|
+
|
|
275
|
+
const files = createBlobChannel(room, 'files', {
|
|
276
|
+
maxReceiveBytes: 10 * 1024 * 1024, // 10 MiB per incoming transfer (default: 4 MiB)
|
|
277
|
+
maxConcurrentPerPeer: 2 // default: 4
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
files.onProgress((from, { receivedBytes, totalBytes }) => {
|
|
281
|
+
const pct = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 100
|
|
282
|
+
console.log(`Receiving from ${from}: ${pct}%`)
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
files.onBlob((from, bytes) => {
|
|
286
|
+
const blob = new Blob([bytes])
|
|
287
|
+
console.log(`Received ${blob.size} bytes from ${from}`)
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
async function sendFile(file: File, targetPeerId?: string, signal?: AbortSignal) {
|
|
291
|
+
const bytes = new Uint8Array(await file.arrayBuffer())
|
|
292
|
+
const results = await files.send(bytes, {
|
|
293
|
+
...(targetPeerId ? { to: targetPeerId } : {}),
|
|
294
|
+
...(signal ? { signal } : {}),
|
|
295
|
+
onProgress(peerId, sentBytes, totalBytes) {
|
|
296
|
+
console.log(`To ${peerId}: ${sentBytes}/${totalBytes}`)
|
|
297
|
+
}
|
|
298
|
+
})
|
|
299
|
+
// Each peer resolves to 'sent' | 'aborted' | 'unavailable' | 'too-large'
|
|
300
|
+
return results
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
> **Memory sizing note:** Worst-case receive RAM is `maxPeers × maxConcurrentPerPeer × maxReceiveBytes`. Tune these bounds if your room accepts untrusted peers.
|
|
305
|
+
|
|
306
|
+
---
|
|
307
|
+
|
|
308
|
+
## 7. Verifiable peer identity (`createIdentityStore` & `peerUserId`)
|
|
309
|
+
|
|
310
|
+
By default, peers are anonymous (`room.userId === null`). Pass a WebCrypto `ECDSA P-256` `PeerIdentity` to `joinRoom()` to prove ownership of a stable 22-character `userId` over each WebRTC DTLS link — bound cryptographically to both peers' DTLS certificate fingerprints so even an active MitM on unencrypted signaling cannot relay or spoof identities.
|
|
311
|
+
|
|
312
|
+
### Persistent identity with `createIdentityStore`
|
|
313
|
+
|
|
314
|
+
`createIdentityStore()` handles `localStorage` persistence, concurrent `load()` coalescing, race-safe `rotate()` / `clear()`, corrupt-entry self-healing, and graceful fallback when `localStorage` throws `SecurityError`.
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { createIdentityStore } from '@dimchansky/meshpost/identity'
|
|
318
|
+
import { joinRoom } from '@dimchansky/meshpost/room'
|
|
319
|
+
import { publicSignaling } from '@dimchansky/meshpost/public'
|
|
320
|
+
|
|
321
|
+
const identityStore = createIdentityStore({ key: 'myapp:identity:v1' })
|
|
322
|
+
const identity = await identityStore.load()
|
|
323
|
+
|
|
324
|
+
// Synchronously read the cached identity anywhere later (null before load() or after clear())
|
|
325
|
+
console.log('My verified userId:', identityStore.current?.userId)
|
|
326
|
+
|
|
327
|
+
const room = joinRoom('guild-chat', {
|
|
328
|
+
password: 'guild-secret',
|
|
329
|
+
identity,
|
|
330
|
+
signaling: publicSignaling()
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
const allowedHosts = new Set(['<known-22-char-userId>'])
|
|
334
|
+
|
|
335
|
+
room.onPeerJoin((peerId) => {
|
|
336
|
+
const userId = room.peerUserId(peerId)
|
|
337
|
+
if (!userId) {
|
|
338
|
+
console.log(peerId, 'is anonymous')
|
|
339
|
+
} else if (allowedHosts.has(userId)) {
|
|
340
|
+
console.log(peerId, 'verified as host:', userId)
|
|
341
|
+
}
|
|
342
|
+
})
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
### Stronger XSS isolation (non-extractable keys)
|
|
346
|
+
|
|
347
|
+
`createIdentityStore()` stores an extractable JWK in `localStorage` (readable by same-origin scripts if your app suffers an XSS vulnerability). If you need keys that cannot be exported by JavaScript, generate a non-extractable key with `createIdentity({ extractable: false })` — note that `PeerIdentity` holds the private `CryptoKey` internally, so for cross-reload non-extractable persistence you can keep the identity in memory for the session or store a non-extractable key pair directly in IndexedDB (or use `createIdentity({ extractable: false })` in Node/Bun/Deno, as shown in [examples/headless-bot.mjs](../examples/headless-bot.mjs)).
|
|
348
|
+
|
|
349
|
+
---
|
|
350
|
+
|
|
351
|
+
## 8. Diagnostics, stats, and clean teardown
|
|
352
|
+
|
|
353
|
+
### Monitoring errors and signaling state
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
room.onSignalingChange((state, reason) => {
|
|
357
|
+
console.log('Signaling:', state, reason ?? '')
|
|
358
|
+
})
|
|
359
|
+
|
|
360
|
+
room.onError((err) => {
|
|
361
|
+
// err.code: 'room-full' | 'ice-failed' | 'media-error' | 'auth-failed'
|
|
362
|
+
// | 'decrypt-failed' | 'clock-skew' | 'signaling-error'
|
|
363
|
+
console.warn(`[${err.code}]`, err.message, err.peerId ?? '')
|
|
364
|
+
})
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Inspecting live connection stats
|
|
368
|
+
|
|
369
|
+
```ts
|
|
370
|
+
for (const peerId of room.peers) {
|
|
371
|
+
const stats = await room.getStats(peerId)
|
|
372
|
+
if (stats) {
|
|
373
|
+
// route: 'direct' | 'relay' | 'unknown'
|
|
374
|
+
console.log(
|
|
375
|
+
peerId,
|
|
376
|
+
stats.route,
|
|
377
|
+
`${stats.rttMs ?? '?'}ms`,
|
|
378
|
+
stats.bytesSent,
|
|
379
|
+
stats.bytesReceived
|
|
380
|
+
)
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
### Clean teardown
|
|
386
|
+
|
|
387
|
+
Calling `room.leave()` automatically closes every `createPeerState`, `createRpc`, `createBlobChannel`, and `createVoice` attached to that room, sends a best-effort goodbye frame, shuts down signaling, and releases all peer connections.
|
|
388
|
+
|
|
389
|
+
```ts
|
|
390
|
+
// Leaving explicitly (e.g. "Leave room" button):
|
|
391
|
+
ac.abort() // detaches your app's event listeners
|
|
392
|
+
room.leave() // closes room + all attached state/rpc/blob/voice helpers
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
> **Do not call `room.leave()` inside a `pagehide` listener.** `joinRoom()` already registers its own `pagehide` handler to notify peers and persist a one-time `F5` ghost-session reclaim token to `sessionStorage`. Calling `room.leave()` on `pagehide` clears that token and disables instant reload reclaim.
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
## Next steps
|
|
400
|
+
|
|
401
|
+
- [Voice & Media](./voice-and-media.md) — microphone capture, hot-swapping devices, per-peer mixer, and screen sharing
|
|
402
|
+
- [Signaling & Production](./signaling-and-production.md) — `publicSignaling`, custom WS/SSE relays, TURN, edge workers, importmaps, and headless peers
|
|
403
|
+
- [API Reference](./api.md) — every export across all 17 subpaths
|
|
404
|
+
- [Interactive Playground](../examples/playground/README.md) — full working app using every feature above
|