@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/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