@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.
Files changed (49) 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 +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
package/docs/behavior.md CHANGED
@@ -84,13 +84,13 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
84
84
  - `createCodecChannel()` throws `TypeError` for an invalid `codec`, non-`Uint8Array` `encode()` return, or non-function `onMessage` listener; `jsonCodec()` throws `TypeError` for a non-function `validate` or unserializable value (`undefined`).
85
85
  - `createRpc()` throws `TypeError` for an invalid `room`, `requestCodec`, `responseCodec`, or `handle` callback, `Error` if a second active `handle()` is registered on the same `RpcEndpoint`, and `RangeError` for out-of-range `timeoutMs`, `maxPendingCalls`, or `maxConcurrentPerPeer`. `rpc.call()` rejects with `TypeError`/`RangeError` for invalid `peerId`/`timeoutMs`, or with `RpcError`.
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
- - `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
87
+ - `createBlobChannel()` throws `TypeError` for an invalid `room`, and `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
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
- - `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.
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 or `options` / `options.onTabsState` is invalid.
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
@@ -174,7 +174,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
174
174
 
175
175
  ### Logical channels (`createChannel` & `createCodecChannel`)
176
176
 
177
- - `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]`.
177
+ - `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]` and exposes `maxPayloadBytes` (`16,384 - 1 - nameLen`) so callers and higher-level helpers do not hardcode framing overhead.
178
178
  - `nameLen` is `1–64` bytes. A lazy per-`Room` `WeakMap` router attaches a single shared `room.onPacket` listener while at least one channel subscriber is active, decodes `name` once with strict UTF-8 (`fatal: true`), dispatches in `O(1)` time to matching subscribers (isolating each callback with `try/catch` + `reportError`), and passes a zero-copy `subarray` view of the original `Uint8Array`.
179
179
  - `createCodecChannel(room, name, codec, options?)` wraps `createChannel` with synchronous `codec.encode(value)` on `send()` (preserving synchronous `ReadonlyMap<string, SendResult>`) and guarded `codec.decode(bytes)` on `onMessage` (dropping malformed frames without consuming `{ once: true }`).
180
180
 
@@ -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
  | -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
@@ -233,7 +235,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
233
235
  - Zero-dependency MQTT 3.1.1 client over WebSocket connecting to `urls` (default `defaultMqttRelays`) in parallel.
234
236
  - Waits for `CONNACK` and `SUBACK` within `handshakeTimeoutMs` (`10 s`), monitors `PINGRESP` every 20 s, and caps incoming buffers at `128 KiB`.
235
237
  - Splits traffic across two topics: `${roomTopic}` for presence (`hello`, `heartbeat`, `bye`) and `${roomTopic}/${peerId}` for targeted `present` and `signal` messages (`roomTopic` is `'meshpost/1/' + namespaceHash(appId:room)` by default, or `'meshpost/1/p/' + privateId` after key derivation when `privateTopic: true`).
236
- - Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`). Valid AEAD frames outside `±60 s` emit rate-limited `'clock-skew'` without polluting `seenMids` or the peer roster.
238
+ - Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`), caps pending async `AES-256-GCM` decrypts at `64`, and emits rate-limited `'clock-skew'` for valid AEAD frames outside `±60 s` without polluting `seenMids` or the peer roster.
237
239
  - Transitions to `'offline'` if all brokers fail on startup or disconnect later, then reconnects with jittered backoff.
238
240
 
239
241
  ### `nostrSignaling(options?)`
@@ -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.
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