@dimchansky/meshpost 0.4.1 → 0.5.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 +62 -67
- package/dist/blob.js +5 -44
- package/dist/channel.js +4 -2
- package/dist/combine.js +20 -15
- package/dist/identity.d.ts +43 -0
- package/dist/identity.js +192 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.js +2 -2
- package/dist/listeners.d.ts +4 -0
- package/dist/listeners.js +97 -0
- package/dist/public.d.ts +19 -1
- package/dist/public.js +71 -9
- package/dist/room.js +25 -44
- package/dist/rpc.js +7 -4
- package/dist/state.d.ts +5 -2
- package/dist/state.js +5 -50
- package/dist/voice.d.ts +34 -0
- package/dist/voice.js +177 -69
- package/dist/ws.js +22 -5
- package/docs/behavior.md +9 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -185,31 +185,23 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
|
|
|
185
185
|
| `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream, meta: PeerStreamMeta) => ...`). Returns unsubscribe. |
|
|
186
186
|
| `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
|
|
187
187
|
|
|
188
|
-
All `on*` methods (on `Room`, `Channel`, `CodecChannel`, `PeerState`, `BlobChannel`, `Voice`, plus `rpc.handle()`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
|
|
188
|
+
All `on*` methods (on `Room`, `Channel`, `CodecChannel`, `PeerState`, `BlobChannel`, `Voice`, plus `rpc.handle()`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts. Meshpost multiplexes all subscriptions sharing the same `AbortSignal` onto a single native `'abort'` listener (avoiding Node.js `MaxListenersExceededWarning`). Note that `room.leave()` automatically unsubscribes all room/module listeners and rejects pending `rpc.call()` promises with `RpcError('closed')`, so a shared `AbortSignal` is only needed for earlier teardown while the room stays open.
|
|
189
189
|
|
|
190
190
|
`room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
|
|
191
191
|
|
|
192
|
-
### Verifiable peer identity (`
|
|
192
|
+
### Verifiable peer identity (`createIdentityStore` / `createIdentity`)
|
|
193
193
|
|
|
194
194
|
Zero-dependency persistent peer identity powered by native WebCrypto `ECDSA P-256` (`SHA-256`), with **DTLS certificate fingerprint channel binding** so signatures cannot be MitM-relayed or replayed across rooms, apps, or connections (even on unencrypted signaling relays):
|
|
195
195
|
|
|
196
|
-
- `
|
|
197
|
-
- `exportIdentity(identity)
|
|
198
|
-
-
|
|
199
|
-
- `isSerializedIdentity(value): value is SerializedIdentity` — runtime type guard for untrusted storage payloads.
|
|
196
|
+
- `createIdentityStore({ key, storage? }): IdentityStore` — race-safe persistent identity manager (`load()`, `rotate()`, `clear()`) backed by `localStorage` by default (safely degrading to ephemeral in-memory caching on `SecurityError`/non-DOM runtimes, coalescing concurrent `load()` calls, self-healing corrupt storage, and preventing `load()` vs `rotate()` races via a monotonic epoch). _(Security note: `localStorage` stores an extractable JWK readable by same-origin scripts; for stronger XSS isolation, use `createIdentity({ extractable: false })` with IndexedDB.)_
|
|
197
|
+
- Low-level primitives: `createIdentity(options?: CreateIdentityOptions)`, `exportIdentity(identity)`, `importIdentity(data, options?)`, and `isSerializedIdentity(value)`.
|
|
198
|
+
- Exported identity types: `PeerIdentity`, `SerializedIdentity`, `CreateIdentityOptions`, `IdentityStorage`, `IdentityStoreOptions`, `IdentityStore`.
|
|
200
199
|
|
|
201
200
|
```ts
|
|
202
|
-
import {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
isSerializedIdentity,
|
|
207
|
-
joinRoom
|
|
208
|
-
} from '@dimchansky/meshpost'
|
|
209
|
-
|
|
210
|
-
const raw = JSON.parse(localStorage.getItem('my-id') ?? 'null')
|
|
211
|
-
const identity = isSerializedIdentity(raw) ? await importIdentity(raw) : await createIdentity()
|
|
212
|
-
localStorage.setItem('my-id', JSON.stringify(await exportIdentity(identity)))
|
|
201
|
+
import { createIdentityStore, joinRoom } from '@dimchansky/meshpost'
|
|
202
|
+
|
|
203
|
+
const identityStore = createIdentityStore({ key: 'my-app:identity' })
|
|
204
|
+
const identity = await identityStore.load()
|
|
213
205
|
|
|
214
206
|
const room = joinRoom('lobby', { signaling, identity })
|
|
215
207
|
console.log('My verified userId:', room.userId)
|
|
@@ -229,48 +221,51 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
|
|
|
229
221
|
- Tracks speaking peers (`speakingPeers`) and local mic activity (`selfSpeaking`) via a shared lazy `AudioContext` + `AnalyserNode` (routed through a `GainNode(0)` sink for WebKit/iOS Safari compatibility).
|
|
230
222
|
- Handles browser Autoplay Policy & iOS Safari quirks out of the box (lock-free `{ capture: true }` gesture unlocking on `pointerdown`/`pointerup`/`touchend`/`click`/`keydown`, iOS `'interrupted'` `AudioContext` recovery, `visibilitychange` foreground resume, and 6-path `navigator.audioSession` `'play-and-record'` save/restore).
|
|
231
223
|
|
|
232
|
-
| `VoiceOptions` field
|
|
233
|
-
|
|
|
234
|
-
| `volume`
|
|
235
|
-
| `deafened`
|
|
236
|
-
| `
|
|
237
|
-
| `
|
|
238
|
-
| `
|
|
239
|
-
| `
|
|
240
|
-
| `
|
|
241
|
-
| `
|
|
242
|
-
| `
|
|
243
|
-
| `
|
|
244
|
-
|
|
245
|
-
| `
|
|
246
|
-
|
|
247
|
-
| `
|
|
248
|
-
|
|
|
249
|
-
| `voice.
|
|
250
|
-
| `voice.
|
|
251
|
-
| `voice.
|
|
252
|
-
| `voice.
|
|
253
|
-
| `voice.
|
|
254
|
-
| `voice.
|
|
255
|
-
| `voice.
|
|
256
|
-
| `voice.
|
|
257
|
-
| `voice.
|
|
258
|
-
| `voice.
|
|
259
|
-
| `voice.
|
|
260
|
-
| `voice.
|
|
261
|
-
| `voice.
|
|
262
|
-
| `voice.
|
|
263
|
-
| `voice.
|
|
264
|
-
| `voice.
|
|
265
|
-
| `voice.
|
|
266
|
-
| `voice.
|
|
267
|
-
| `voice.
|
|
268
|
-
| `voice.
|
|
269
|
-
| `voice.
|
|
270
|
-
| `voice.
|
|
271
|
-
| `voice.
|
|
272
|
-
|
|
273
|
-
|
|
224
|
+
| `VoiceOptions` field | Type | Default | Purpose |
|
|
225
|
+
| ----------------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
226
|
+
| `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
|
|
227
|
+
| `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
|
|
228
|
+
| `deviceId` | `string \| null` | `null` | Preferred microphone `deviceId` (`null` / `''` for system default). Preserves `defaultAudioConstraints`. |
|
|
229
|
+
| `fallbackToDefaultOnNotFound` | `boolean` | `false` | On initial mic start (`toggleMic` / `startMic`), auto-retry with system default if `deviceId` fails with `'not-found'`. |
|
|
230
|
+
| `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
|
|
231
|
+
| `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
|
|
232
|
+
| `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
|
|
233
|
+
| `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
|
|
234
|
+
| `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
|
|
235
|
+
| `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
|
|
236
|
+
| `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
|
|
237
|
+
| `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
|
|
238
|
+
|
|
239
|
+
| `Voice` member | Description |
|
|
240
|
+
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
241
|
+
| `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
|
|
242
|
+
| `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
|
|
243
|
+
| `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
|
|
244
|
+
| `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
|
|
245
|
+
| `voice.deafened` | Whether incoming peer audio is muted locally. |
|
|
246
|
+
| `voice.volume` | Current master incoming playback volume (`0` to `1`). |
|
|
247
|
+
| `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
|
|
248
|
+
| `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
|
|
249
|
+
| `voice.speakingPeers` | Snapshot array of remote peer IDs whose incoming audio currently exceeds `speakingThreshold` (independent of `deafened` / `mutedPeers`; filter locally if your UI hides speaking indicators for muted peers). |
|
|
250
|
+
| `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
|
|
251
|
+
| `voice.peerVolumes` | Sparse read-only map (`Readonly<Record<string, number>>`) of overridden per-peer playback volumes (`!== 1`; omitted peers default to `1`). |
|
|
252
|
+
| `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 11 state fields above (`Voice extends VoiceSnapshot`). |
|
|
253
|
+
| `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
|
|
254
|
+
| `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
|
|
255
|
+
| `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
|
|
256
|
+
| `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
|
|
257
|
+
| `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
|
|
258
|
+
| `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
|
|
259
|
+
| `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
|
|
260
|
+
| `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
|
|
261
|
+
| `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
|
|
262
|
+
| `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
|
|
263
|
+
| `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
|
|
264
|
+
| `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
|
|
265
|
+
| `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
|
|
266
|
+
| `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
|
|
267
|
+
|
|
268
|
+
Exported voice helpers & types: `listAudioInputs()`, `onAudioInputsChange(fn, options?: ListenOptions)`, `AudioInputDevice`, `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
|
|
274
269
|
|
|
275
270
|
```ts
|
|
276
271
|
import { createVoice } from '@dimchansky/meshpost'
|
|
@@ -284,7 +279,7 @@ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
|
|
|
284
279
|
await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
|
|
285
280
|
|
|
286
281
|
voice.onChange((snap) => {
|
|
287
|
-
// snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
|
|
282
|
+
// snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers, peerVolumes }
|
|
288
283
|
if (snap.autoplayBlocked) showUnlockBanner()
|
|
289
284
|
})
|
|
290
285
|
|
|
@@ -402,7 +397,7 @@ const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
|
|
|
402
397
|
Creates a single-writer per-peer state synchronization store (zero CRDT bloat): each peer owns its own slot (`set(value)` / `clear()`), while remote peers' latest states are automatically ordered via RFC 1982 `u32` sequence numbers, **hydrated reliably on `onPeerJoin`** (even when live updates use `delivery: 'unreliable'`), cleaned up on `onPeerLeave`, and coalesced in `O(1)` memory on `room.onDrain` when send buffers are `'busy'`.
|
|
403
398
|
|
|
404
399
|
- `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
|
|
405
|
-
- Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev) => ..., options?: ListenOptions), close() }`.
|
|
400
|
+
- Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev, reason: PeerStateChangeReason) => ..., options?: ListenOptions), close() }` where `reason` is `'set' | 'clear' | 'leave'`.
|
|
406
401
|
|
|
407
402
|
```ts
|
|
408
403
|
import { createPeerState } from '@dimchansky/meshpost'
|
|
@@ -445,17 +440,17 @@ const results = await files.send(fileBytes, {
|
|
|
445
440
|
|
|
446
441
|
### Signaling exports
|
|
447
442
|
|
|
448
|
-
- `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room.
|
|
443
|
+
- `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket?, onTransportChange? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room. Pass `onTransportChange?: (event: PublicTransportEvent) => void` to observe per-transport (`'ws' | 'mqtt' | 'nostr' | 'tabs'`) lifecycle transitions (`state`, optional `url` for `'ws'`, and optional `reason`); note that per the WHATWG WebSocket spec, browsers hide HTTP `403`/TLS failure details behind opaque close code `1006`, while client-side handshake timeouts and non-`1006` close codes appear in `reason`.
|
|
449
444
|
- `mqttSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`), with optional `AES-256-GCM` E2E encryption, `privateTopic` topic hiding, and optional custom `WebSocket` constructor injection.
|
|
450
445
|
- `nostrSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Zero-server signaling over public **port-443** NIP-01 Nostr relays (`defaultNostrRelays`) using ephemeral `kind: 25050` events (never persisted by relays), pure-TS BIP-340 Schnorr signatures (0 dependencies, tree-shakeable), optional `AES-256-GCM` E2E encryption + `privateTopic` tag hiding, and optional custom `WebSocket` constructor injection.
|
|
451
446
|
- `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`, `encrypt: true`, `privateTopic: false`). Automatically appends `?room=<roomKey>` for stateless per-room sharding and E2E-encrypts signaling (`box` envelopes) when `password` is set. See [examples/ws-worker/](examples/ws-worker/README.md) for a ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) relay, or [examples/serve.mjs](examples/serve.mjs) for Node.js.
|
|
452
|
-
- `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
447
|
+
- `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` (forwarding the close/timeout `reason`) and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
453
448
|
- `withLocalTabs(primary)` — Decorates a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant same-browser `BroadcastChannel` discovery (`tabSignaling()`) while **preserving `primary`'s `SignalingState`** for `room.signalingState` / `room.onSignalingChange` (avoiding a stuck `'online'` state when internet connectivity drops, while still connecting local tabs offline). Safely falls back to `primary` on `file:` / opaque origins or when `BroadcastChannel` is unavailable.
|
|
454
449
|
- `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(wsSignaling('wss://primary.example/ws'), mqttSignaling())`).
|
|
455
450
|
- `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
|
|
456
451
|
- `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
|
|
457
452
|
- `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
|
|
458
|
-
- Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
|
|
453
|
+
- Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `PublicTransportKind`, `PublicTransportEvent`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
|
|
459
454
|
|
|
460
455
|
## Connecting through strict firewalls (TURN)
|
|
461
456
|
|
|
@@ -549,11 +544,11 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
|
|
|
549
544
|
|
|
550
545
|
All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
|
|
551
546
|
|
|
552
|
-
- [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade using `@dimchansky/meshpost/*` subpath imports to wire `joinRoom()`, `
|
|
553
|
-
- [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `
|
|
547
|
+
- [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade using `@dimchansky/meshpost/*` subpath imports to wire `joinRoom()`, `createIdentityStore()`, signaling adapters (`publicSignaling({ onTransportChange })`, `withLocalTabs`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createPeerState()` (`presence`, `cursor`), `createChannel()` (`ripple`, `draw`), `createCodecChannel()` + `jsonCodec()` (`chat`, `direct`), `createRpc()` (`ping`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()` + `listAudioInputs()` / `onAudioInputsChange()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
|
|
548
|
+
- [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `optionalWsSignaling()` with per-transport status reporting and a silent fallback to `tabSignaling()` on plain static localhost servers.
|
|
554
549
|
- [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs (`cursorCodec`, canvas strokes, file metadata envelopes) and payload type guards.
|
|
555
550
|
- [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
|
|
556
|
-
- [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons,
|
|
551
|
+
- [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, persistent pre-join/live mic selector (`listAudioInputs`, `onAudioInputsChange`, `switchDevice`, `fallbackToDefaultOnNotFound`), per-peer volume/mute controls, autoplay banner, and `KeyM` to `createVoice()`.
|
|
557
552
|
- [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
|
|
558
553
|
- [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
|
|
559
554
|
- [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
|
package/dist/blob.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createChannel } from './channel.js';
|
|
2
|
+
import { bindAbort, createListeners } from './listeners.js';
|
|
2
3
|
const opStart = 0x01;
|
|
3
4
|
const opData = 0x02;
|
|
4
5
|
const opAbort = 0x03;
|
|
@@ -12,48 +13,7 @@ const defaultChunkSize = 15 * 1024;
|
|
|
12
13
|
const defaultReceiveTimeoutMs = 30_000;
|
|
13
14
|
const defaultMaxConcurrentPerPeer = 4;
|
|
14
15
|
const encoder = new TextEncoder();
|
|
15
|
-
|
|
16
|
-
const entries = new Set();
|
|
17
|
-
let closed = false;
|
|
18
|
-
return {
|
|
19
|
-
add(fn, options) {
|
|
20
|
-
const signal = options?.signal;
|
|
21
|
-
if (closed || signal?.aborted)
|
|
22
|
-
return () => { };
|
|
23
|
-
const entry = {
|
|
24
|
-
fn,
|
|
25
|
-
once: Boolean(options?.once),
|
|
26
|
-
off() {
|
|
27
|
-
if (!entries.delete(entry))
|
|
28
|
-
return;
|
|
29
|
-
signal?.removeEventListener('abort', entry.off);
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
entries.add(entry);
|
|
33
|
-
signal?.addEventListener('abort', entry.off, { once: true });
|
|
34
|
-
return entry.off;
|
|
35
|
-
},
|
|
36
|
-
fire(...args) {
|
|
37
|
-
for (const entry of [...entries]) {
|
|
38
|
-
if (!entries.has(entry))
|
|
39
|
-
continue;
|
|
40
|
-
if (entry.once)
|
|
41
|
-
entry.off();
|
|
42
|
-
try {
|
|
43
|
-
entry.fn(...args);
|
|
44
|
-
}
|
|
45
|
-
catch (error) {
|
|
46
|
-
globalThis.reportError?.(error);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
},
|
|
50
|
-
clear() {
|
|
51
|
-
closed = true;
|
|
52
|
-
for (const entry of [...entries])
|
|
53
|
-
entry.off();
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
}
|
|
16
|
+
const listeners = createListeners;
|
|
57
17
|
/**
|
|
58
18
|
* Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
|
|
59
19
|
* Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
|
|
@@ -145,19 +105,20 @@ export function createBlobChannel(room, name, options = {}) {
|
|
|
145
105
|
}
|
|
146
106
|
const ctrl = new AbortController();
|
|
147
107
|
let settled = false;
|
|
108
|
+
let unbindAbort;
|
|
148
109
|
const done = (outcome) => {
|
|
149
110
|
if (settled)
|
|
150
111
|
return;
|
|
151
112
|
settled = true;
|
|
152
113
|
ctrl.abort();
|
|
153
114
|
closeWaiters.delete(onClose);
|
|
154
|
-
|
|
115
|
+
unbindAbort?.();
|
|
155
116
|
resolve(outcome);
|
|
156
117
|
};
|
|
157
118
|
const onClose = () => done('abort');
|
|
158
119
|
const onAbort = () => done('abort');
|
|
159
120
|
closeWaiters.add(onClose);
|
|
160
|
-
signal
|
|
121
|
+
unbindAbort = bindAbort(signal, onAbort);
|
|
161
122
|
room.onDrain((id, delivery) => {
|
|
162
123
|
if (id === peerId && delivery === 'reliable')
|
|
163
124
|
done('drain');
|
package/dist/channel.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { bindAbort } from './listeners.js';
|
|
1
2
|
import { isRoomClosed, onRoomClose } from './room.js';
|
|
2
3
|
const encoder = new TextEncoder();
|
|
3
4
|
const strictDecoder = new TextDecoder('utf-8', { fatal: true });
|
|
@@ -101,6 +102,7 @@ function getRouter(room) {
|
|
|
101
102
|
table.lengthCounts[nameLen] = (table.lengthCounts[nameLen] ?? 0) + 1;
|
|
102
103
|
}
|
|
103
104
|
let removed = false;
|
|
105
|
+
let unbindAbort;
|
|
104
106
|
const entry = {
|
|
105
107
|
fn,
|
|
106
108
|
once: Boolean(options?.once),
|
|
@@ -108,7 +110,7 @@ function getRouter(room) {
|
|
|
108
110
|
if (removed)
|
|
109
111
|
return;
|
|
110
112
|
removed = true;
|
|
111
|
-
|
|
113
|
+
unbindAbort?.();
|
|
112
114
|
const current = table.byName.get(name);
|
|
113
115
|
if (current?.delete(entry)) {
|
|
114
116
|
activeSubs = Math.max(0, activeSubs - 1);
|
|
@@ -123,7 +125,7 @@ function getRouter(room) {
|
|
|
123
125
|
};
|
|
124
126
|
subs.add(entry);
|
|
125
127
|
activeSubs++;
|
|
126
|
-
signal
|
|
128
|
+
unbindAbort = bindAbort(signal, entry.off);
|
|
127
129
|
return entry.off;
|
|
128
130
|
}
|
|
129
131
|
};
|
package/dist/combine.js
CHANGED
|
@@ -323,20 +323,8 @@ function canUseLocalTabs() {
|
|
|
323
323
|
}
|
|
324
324
|
return true;
|
|
325
325
|
}
|
|
326
|
-
/**
|
|
327
|
-
|
|
328
|
-
* same-browser `BroadcastChannel` discovery (`tabSignaling()`).
|
|
329
|
-
*
|
|
330
|
-
* - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
|
|
331
|
-
* (avoiding a permanently `'online'` indicator when network connectivity is lost).
|
|
332
|
-
* - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
|
|
333
|
-
* - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
|
|
334
|
-
* origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
|
|
335
|
-
*/
|
|
336
|
-
export function withLocalTabs(primary) {
|
|
337
|
-
if (typeof primary !== 'function') {
|
|
338
|
-
throw new TypeError('Expected a signaling adapter function');
|
|
339
|
-
}
|
|
326
|
+
/** @internal */
|
|
327
|
+
export function withLocalTabsInternal(primary, wrapTabs) {
|
|
340
328
|
return (discovery) => {
|
|
341
329
|
if (!canUseLocalTabs())
|
|
342
330
|
return primary(discovery);
|
|
@@ -349,7 +337,24 @@ export function withLocalTabs(primary) {
|
|
|
349
337
|
catch {
|
|
350
338
|
return primary(discovery);
|
|
351
339
|
}
|
|
352
|
-
const
|
|
340
|
+
const baseTabs = tabSignaling();
|
|
341
|
+
const tabs = wrapTabs ? wrapTabs(baseTabs) : baseTabs;
|
|
353
342
|
return createCompositeSession(discovery, [tabs, primary], 1);
|
|
354
343
|
};
|
|
355
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
|
|
347
|
+
* same-browser `BroadcastChannel` discovery (`tabSignaling()`).
|
|
348
|
+
*
|
|
349
|
+
* - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
|
|
350
|
+
* (avoiding a permanently `'online'` indicator when network connectivity is lost).
|
|
351
|
+
* - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
|
|
352
|
+
* - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
|
|
353
|
+
* origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
|
|
354
|
+
*/
|
|
355
|
+
export function withLocalTabs(primary) {
|
|
356
|
+
if (typeof primary !== 'function') {
|
|
357
|
+
throw new TypeError('Expected a signaling adapter function');
|
|
358
|
+
}
|
|
359
|
+
return withLocalTabsInternal(primary);
|
|
360
|
+
}
|
package/dist/identity.d.ts
CHANGED
|
@@ -27,6 +27,39 @@ export interface SerializedIdentity {
|
|
|
27
27
|
/** 32-byte canonical base64url private scalar (43 chars). */
|
|
28
28
|
readonly d: string;
|
|
29
29
|
}
|
|
30
|
+
/** Minimal synchronous `Storage`-compatible interface accepted by `createIdentityStore()`. */
|
|
31
|
+
export interface IdentityStorage {
|
|
32
|
+
getItem(key: string): string | null;
|
|
33
|
+
setItem(key: string, value: string): void;
|
|
34
|
+
removeItem(key: string): void;
|
|
35
|
+
}
|
|
36
|
+
/** Options passed to `createIdentityStore()`. */
|
|
37
|
+
export interface IdentityStoreOptions {
|
|
38
|
+
/** Required storage key isolating identities across apps on the same origin (`1..256` chars). */
|
|
39
|
+
key: string;
|
|
40
|
+
/**
|
|
41
|
+
* Storage backend (`localStorage`, `sessionStorage`, or custom `IdentityStorage`).
|
|
42
|
+
* Defaults to safely probing `globalThis.localStorage` inside `try/catch` (degrading to
|
|
43
|
+
* ephemeral in-memory caching when unavailable or throwing `SecurityError`).
|
|
44
|
+
* Pass `null` for strictly ephemeral in-memory caching without persistence.
|
|
45
|
+
*/
|
|
46
|
+
storage?: IdentityStorage | null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Race-safe persistent identity manager backed by `createIdentity()` / `importIdentity()` / `exportIdentity()`.
|
|
50
|
+
*
|
|
51
|
+
* Security note: persisting serialized keys in `localStorage` stores an extractable JWK readable by
|
|
52
|
+
* same-origin scripts (XSS). For stronger key isolation, use `createIdentity({ extractable: false })`
|
|
53
|
+
* with IndexedDB directly.
|
|
54
|
+
*/
|
|
55
|
+
export interface IdentityStore {
|
|
56
|
+
/** Load the stored identity or generate and persist a fresh one (coalesces concurrent calls; self-heals corrupt storage). */
|
|
57
|
+
load(): Promise<PeerIdentity>;
|
|
58
|
+
/** Generate a fresh identity, persist it, and supersede any in-flight `load()` or earlier `rotate()`. */
|
|
59
|
+
rotate(): Promise<PeerIdentity>;
|
|
60
|
+
/** Clear the in-memory cache, remove the stored key (best-effort), and invalidate in-flight operations. */
|
|
61
|
+
clear(): void;
|
|
62
|
+
}
|
|
30
63
|
/**
|
|
31
64
|
* Generate a fresh WebCrypto `ECDSA P-256` peer identity with a deterministic 128-bit `userId`.
|
|
32
65
|
*/
|
|
@@ -43,3 +76,13 @@ export declare function isSerializedIdentity(value: unknown): value is Serialize
|
|
|
43
76
|
* Import and cryptographically self-verify a `SerializedIdentity` (`(x, y)` verified against `d`).
|
|
44
77
|
*/
|
|
45
78
|
export declare function importIdentity(data: unknown, options?: CreateIdentityOptions): Promise<PeerIdentity>;
|
|
79
|
+
/**
|
|
80
|
+
* Create a race-safe persistent `PeerIdentity` store backed by `localStorage` (by default) or a custom `IdentityStorage`.
|
|
81
|
+
*
|
|
82
|
+
* - Coalesces concurrent `load()` calls and uses a monotonic `epoch` guard so `rotate()` or `clear()`
|
|
83
|
+
* cannot be overwritten by an earlier in-flight operation.
|
|
84
|
+
* - Caps stored JSON reads at `1,024` chars, cryptographically verifies imported keys, and silently
|
|
85
|
+
* regenerates corrupt entries (preserving stored entries untouched if `crypto.subtle` is unavailable).
|
|
86
|
+
* - Degrades cleanly to in-memory caching when `localStorage` throws `SecurityError` or is unavailable.
|
|
87
|
+
*/
|
|
88
|
+
export declare function createIdentityStore(options: IdentityStoreOptions): IdentityStore;
|