@dimchansky/meshpost 0.0.0-stage → 0.2.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.
@@ -0,0 +1,237 @@
1
+ # Room behavior and wire protocol
2
+
3
+ This document specifies limits, lifecycle rules, wire formats, and security boundaries for Meshpost v1.
4
+
5
+ ## Limits and timeouts
6
+
7
+ | Parameter | Default / Limit | Notes |
8
+ | ---------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------- |
9
+ | Max packet size | `16,384` bytes (16 KiB) | Or the smaller peer SCTP `maxMessageSize`. |
10
+ | `createChannel` payload max | `16,384 - (1 + nameBytes.length)` bytes | `name` must be `1–64` UTF-8 bytes. |
11
+ | Send buffer limit | `64 KiB` unreliable / `256 KiB` reliable | Per peer and per data channel. Exceeding returns `'busy'`. |
12
+ | `onDrain` threshold | `32 KiB` unreliable / `128 KiB` reliable | Fires when `bufferedAmount` drops to half the data channel limit. |
13
+ | `maxPeers` | `32` | Simultaneous peer connections per room. |
14
+ | `handshakeTimeoutMs` | `35,000` ms (`180,000` ms manual demo) | Deadline per connection attempt before retry. |
15
+ | `iceGatheringTimeoutMs` | `2,500` ms (up to `10,000` ms with TURN) | Max wait for ICE candidates before publishing SDP (default capped at `handshakeTimeoutMs / 2`). |
16
+ | Disconnect grace period | `8,000` ms | Wait time for transient `disconnected` state before dropping. |
17
+ | Leave flush grace | `750` ms | Max wait for `meshpost/1/leave` to flush on `room.leave()`. |
18
+ | Early-packet buffer | `64` packets or `256 KiB` per peer | Holds packets arriving before both data channels open. |
19
+ | Discovery lease | `30,000` ms (`5,000` ms heartbeat) | Peers send a heartbeat every 5,000 ms and expire from the roster after 30,000 ms of silence. |
20
+ | MQTT handshake timeout | `10,000` ms | Deadline for `CONNECT -> CONNACK -> SUBACK` per broker. |
21
+ | MQTT replay window / MID TTL | `±60,000` ms / `120,000` ms | Anti-replay window for password-encrypted MQTT signaling (`mid` required, max `64` chars). |
22
+ | WS handshake / ping timeout | `10,000` ms / `25,000` ms | `wsSignaling()` open deadline and keepalive ping interval (`awaitingPong` dead-socket check). |
23
+ | In-band `rtc:` queue / cap | `16` pending / `32` remote streams | Max queued incoming `'meshpost/1/rtc:'` frames and max tracked remote `MediaStream`s per peer. |
24
+
25
+ ## Room lifecycle
26
+
27
+ ### Identity and membership
28
+
29
+ - `joinRoom(name, options)` generates a fresh random peer ID (UUID v4, exposed as `room.id`). A page reload creates a new peer ID.
30
+ - `joinRoom()` returns synchronously and starts discovery immediately.
31
+ - `room.peers` returns a snapshot array of remote peer IDs whose unreliable and reliable channels are both open.
32
+ - Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `blobChannel.onBlob`, and `blobChannel.onProgress`) returns an idempotent unsubscribe function and optionally accepts `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`).
33
+ - 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.
34
+ - A room of `N` peers forms up to `N(N - 1) / 2` direct connections (bounded per peer by `maxPeers`).
35
+ - There is no host election, packet forwarding, or history replay. Any peer can join first.
36
+
37
+ ### Roster and retries
38
+
39
+ - Meshpost uses the signaling roster only to start new connections. Removing a peer ID stops future retries, but does not close an already-open link.
40
+ - Meshpost retries missing connections with increasing random delays (`350 ms` to `8 s` base delay with `±25%` jitter) while the peer remains in the roster and signaling is `'online'`.
41
+ - When `signalingState` transitions back to `'online'`, Meshpost automatically resumes discovery for all advertised peers without an active link.
42
+
43
+ ### Disconnects and `leave()`
44
+
45
+ - A `failed` or `closed` connection drops immediately.
46
+ - A transient `disconnected` state waits `8,000` ms before dropping.
47
+ - Calling `room.leave()` more than once has no extra effect.
48
+ - Local `room.send()` throws immediately after `leave()` starts. `room.getStats()` returns `Promise<null>` instead of throwing.
49
+ - `room.signalingState` changes to `'closed'` before `onPeerLeave` callbacks run.
50
+ - `onSignalingChange` emits `'closed'` at most once.
51
+ - Meshpost attempts to send `meshpost/1/leave` over the reliable channel and waits up to `750` ms before closing the `RTCPeerConnection`.
52
+ - Abruptly closing a tab can skip the departure notice. Other peer pairs keep working normally.
53
+
54
+ ### Structured errors (`room.onError`)
55
+
56
+ `room.onError((error) => ...)` emits `RoomError` objects (`{ code, message, peerId? }`) with built-in anti-spam guarantees:
57
+
58
+ | Code | When emitted | Anti-spam rule |
59
+ | ------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
60
+ | `'room-full'` | An advertised remote peer cannot be tracked because `peers.size >= maxPeers`. Includes `peerId`. | Emitted at most once per peer ID while that peer stays in the roster. |
61
+ | `'ice-failed'` | A non-ready link fails (`connectionState === 'failed'`) or hits `handshakeTimeoutMs`. Includes `peerId`. | Emitted at most once per peer until it connects (`ready`) or leaves the roster. |
62
+ | `'media-error'` | In-band WebRTC media renegotiation fails on a live link. Includes `peerId`. Healthy data channels stay open. | Emitted per failed renegotiation operation. |
63
+ | `'decrypt-failed'` | A password-protected signaling adapter fails to decrypt an incoming frame (e.g. wrong password on MQTT). | Rate-limited to at most once every `15,000` ms per MQTT session. |
64
+ | `'signaling-error'` | A signaling adapter reports a transport-level failure (e.g. all MQTT relays or WS disconnected/failed). | Emitted once per offline transition in `mqttSignaling()` and `wsSignaling()`. |
65
+
66
+ Note: on public MQTT topics, `roomTopic` hashes `(appId, room)` without `password`, so a password-enabled peer detects wrong-password traffic as `'decrypt-failed'`, whereas a passwordless peer silently ignores non-JSON encrypted frames.
67
+
68
+ ### Synchronous errors
69
+
70
+ - `joinRoom()` throws `TypeError` for invalid `name` (`^[a-zA-Z0-9_-]{1,64}$`), invalid `appId` (`^[a-zA-Z0-9._-]{1,64}$`), or empty `password`.
71
+ - `joinRoom()` throws `RangeError` for invalid timeouts or `maxPeers`, throws browser errors immediately if `rtcConfig` is malformed, and throws `Error` if `mqttSignaling()` is used with `password` without `crypto.subtle`.
72
+ - `room.send()` throws `Error` after `leave()`, and `TypeError` for non-`Uint8Array` payloads or invalid `delivery`.
73
+ - `room.addStream()` throws `Error` after `leave()`, and `TypeError` for non-`MediaStream` arguments.
74
+ - `createChannel()` throws `TypeError` for an empty name or invalid `delivery`, and `RangeError` if the UTF-8 name exceeds 64 bytes.
75
+ - `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
76
+ - `wsSignaling()` throws `TypeError` for non-`ws:`/`wss:` URLs and `RangeError` for invalid `handshakeTimeoutMs` or `pingIntervalMs`.
77
+ - `combineSignaling()` throws `RangeError` when given 0 adapters and `TypeError` if any argument is not a function.
78
+ - `mqttSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, and `TypeError` for an empty `password`.
79
+
80
+ ## Sending and receiving
81
+
82
+ `room.send(bytes, { to?, delivery? })` takes a `Uint8Array` and defaults to `delivery: 'unreliable'`.
83
+
84
+ - Without `to`, Meshpost snapshots `room.peers` and attempts one independent send per peer.
85
+ - No local echo occurs. An empty room returns an empty map.
86
+ - Unicast to yourself or an unknown peer ID returns `'unavailable'`.
87
+
88
+ | `SendResult` | Meaning |
89
+ | ------------- | ---------------------------------------------------------------------------------- |
90
+ | `accepted` | The browser accepted the packet into the channel send buffer. |
91
+ | `busy` | Adding the packet would exceed the channel budget, or the browser buffer is full. |
92
+ | `unavailable` | No open channel exists for this peer, or the channel closed during send. |
93
+ | `too-large` | The packet exceeds `16,384` bytes or the smaller negotiated SCTP `maxMessageSize`. |
94
+
95
+ ### Delivery guarantees and backpressure
96
+
97
+ - Both channels preserve message boundaries. Empty (`0`-byte) packets are valid.
98
+ - Meshpost keeps no internal send queue. Check the returned `SendResult` map.
99
+ - Subscribe to `room.onDrain(peerId, delivery)` to resume sending after `'busy'`.
100
+ - Reliable delivery preserves order only within one live channel. A disconnect can drop unacknowledged packets.
101
+ - Broadcast sends one independent packet to each peer. A send can succeed for one peer and fail for another, and peers can receive packets in different orders.
102
+ - A return value of `'accepted'` never proves that the remote app processed the packet.
103
+
104
+ ### Connection stats (`room.getStats(peerId)`)
105
+
106
+ - Returns `Promise<PeerStats | null>` for a connected remote peer, or `null` if the peer is unknown, not ready, disconnected while awaiting stats, or the room is closed.
107
+ - `rttMs` is the active ICE candidate pair's `currentRoundTripTime` rounded to whole milliseconds (`>= 0`), or `null` if unavailable.
108
+ - `route` is `'relay'` if either the local or remote active candidate is a TURN `'relay'`, `'direct'` if both candidate types are known and neither is `'relay'`, and `'unknown'` otherwise.
109
+ - `bytesSent` and `bytesReceived` sum WebRTC `data-channel` application payload counters across stream `0` and stream `1` (for the current connection; monotonic across ICE path switches, reset on reconnect).
110
+ - `bufferedUnreliable` and `bufferedReliable` report each channel's `bufferedAmount` read after `pc.getStats()` resolves.
111
+
112
+ ### Application patterns
113
+
114
+ - **State snapshots (unreliable):** Include a per-sender sequence number and discard stale packets. Reset state on `onPeerLeave`.
115
+ - **Critical commands (reliable):** Add application message IDs, acknowledgements, and retries if commands must survive reconnects.
116
+
117
+ ## Wire protocol (v1)
118
+
119
+ ### Negotiation (avoiding simultaneous offers / glare)
120
+
121
+ - When two peers discover each other at the same time, only the peer with the lexicographically smaller UUID creates the SDP offer.
122
+ - The offerer assigns strictly increasing `attempt` numbers starting from a random 28-bit positive integer (valid range `1..2^31 - 1`).
123
+ - Stale offers, stale answers, invalid SDPs, extreme attempt jumps (`> 1024` above a known baseline), and callbacks from replaced links cannot poison `previous` or close a newer link.
124
+ - Duplicate `answer` delivery is ignored once the first `answer` for an attempt is applied.
125
+
126
+ ### ICE gathering, opt-in Trickle ICE, and loopback fallback
127
+
128
+ - Adapters can opt in to **Trickle ICE** by setting `trickle: true` on their returned `SignalingSession` (enabled by default in `tabSignaling()`, `wsSignaling()`, and `mqttSignaling()`, and in `combineSignaling()` when every child session sets `trickle: true`).
129
+ - When `trickle` is `true`, Meshpost publishes `offer` and `answer` immediately after `setLocalDescription()` without waiting for `iceGatheringTimeoutMs`, batches outgoing ICE candidates over a `50 ms` window (up to `16` per batch, capped at `64` per link), and buffers incoming candidates that arrive before `setRemoteDescription()` resolves (including early candidates arriving before the `offer` on the answerer).
130
+ - When `trickle` is omitted or `false` (such as `manualSignaling()` or simple custom adapters), each side waits to publish one complete SDP (no trickle ICE required). Publication occurs when `iceGatheringState` reaches `'complete'` or when `iceGatheringTimeoutMs` elapses, whichever comes first.
131
+ - In non-trickle mode, when you configure TURN servers (or `iceTransportPolicy: 'relay'`) and omit `iceGatheringTimeoutMs`, Meshpost waits up to `min(10,000 ms, handshakeTimeoutMs / 2)` for the first `relay` or public (`srflx`) candidate.
132
+ - By default, `defaultIceServers` provides public Cloudflare and Google STUN servers. Override with `rtcConfig.iceServers` or extend with `turnConfig`.
133
+ - To help two browsers on the same machine connect when mDNS `.local` names fail to resolve, Meshpost adds a low-priority (priority `1`) `127.0.0.1` candidate for each remote UDP `.local` candidate in both SDP (`offer`/`answer`) and Trickle ICE (`ice`) signals (unless `iceTransportPolicy` is `'relay'`).
134
+ - Original candidates stay intact, and Meshpost never sends this local fallback over signaling.
135
+
136
+ ### SCTP data channels
137
+
138
+ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set to `appId`:
139
+
140
+ | Stream ID | Label | Configuration |
141
+ | --------: | ----------------------- | ----------------------------------- |
142
+ | 0 | `meshpost/1/unreliable` | `ordered: false, maxRetransmits: 0` |
143
+ | 1 | `meshpost/1/reliable` | `ordered: true` (full reliability) |
144
+
145
+ ### Framing and early packets
146
+
147
+ - Application messages on both channels are raw binary `ArrayBuffer` frames. `room.send()` adds no library header.
148
+ - A text message `'meshpost/1/leave'` on stream `1` signals graceful departure.
149
+ - Text messages prefixed with `'meshpost/1/rtc:'` (max `64 KiB`, max `16` pending incoming frames per link) on stream `1` carry in-band JSON control frames for media renegotiation (`{ kind: 'offer' | 'answer', sdp }` and `{ kind: 'stream-end', id }`). Other text messages are ignored.
150
+ - Mid-session `addStream()` / `removeStream()` renegotiation runs entirely in-band over stream `1` using Perfect Negotiation (deterministic polite role `self > peerId`, serialized per link alongside `stream-end`), reusing the existing BUNDLE ICE/DTLS transport without exchanging new Trickle ICE candidates. Voice/media works even when the signaling server is offline or with `manualSignaling()`.
151
+ - Active local streams on the initial offerer (`self < peerId`) are attached before initial `createOffer()` for 0-RTT media setup; remote streams received before `link.ready` are buffered and fire via `onPeerStream` strictly after `onPeerJoin` (once per `stream.id`, capped at `32` remote streams per peer). On disconnect, `onPeerStreamEnd` fires for active remote streams before `onPeerLeave`.
152
+ - `addStream()` ignores streams with 0 tracks and does not observe tracks added to a `MediaStream` after `addStream()`; `removeStream()` detaches senders from peer connections without calling `track.stop()`.
153
+ - Incoming binary packets larger than `16,384` bytes are ignored on stream `0` and close the link on stream `1`.
154
+ - Packets arriving before both channels open are buffered up to `64` packets and `256 KiB` per peer.
155
+ - Exceeding the early buffer drops excess unreliable packets or closes the incomplete link on a reliable packet.
156
+ - Buffered packets fire strictly after `onPeerJoin`.
157
+
158
+ ### Logical channels (`createChannel`)
159
+
160
+ - `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]`.
161
+ - `nameLen` is `1–64` bytes. Meshpost filters incoming frames by delivery mode and exact name prefix, then passes a `subarray` view of the original `Uint8Array` (no copy).
162
+
163
+ ### Chunked transfers (`createBlobChannel`)
164
+
165
+ - `createBlobChannel(room, name, options?)` layers chunked transfers strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain` without changing core `Room` packet limits.
166
+ - Wire opcodes inside the logical channel:
167
+ - `0x01` `START`: `[0x01, transferId (u32 BE), totalBytes (u32 BE), ...chunk0]` (blobs `<= chunkSize`, including `0`-byte blobs, complete in one packet).
168
+ - `0x02` `DATA`: `[0x02, transferId (u32 BE), ...chunkN]` (non-empty ordered payload chunks).
169
+ - `0x03` `ABORT`: `[0x03, transferId (u32 BE)]` (sent best-effort on sender `AbortSignal` cancellation, `blobChannel.close()`, or mid-transfer `'too-large'`).
170
+ - Senders pace every recipient independently (`channel.send(frame, { to: peerId })`) using `room.onDrain` so one slow peer never stalls another during broadcast.
171
+ - 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()`.
172
+
173
+ ## Signaling adapters
174
+
175
+ ### Custom `Signaling` contract
176
+
177
+ - A `Signaling` factory receives `Discovery` (`appId`, `room`, `self`, optional `password`, `roster`, `receive`, `status`, optional `error`) and returns `{ send(to, signal), close() }`.
178
+ - `send(to, signal)` must return `boolean` (`true` when accepted for delivery; returning `false` drops the pending link).
179
+ - Report `status('online')` before publishing a roster.
180
+ - Deliver a roster containing a sender before calling `receive(from, signal)`.
181
+ - Isolate rooms by `(appId, room)` (and `password` if used).
182
+
183
+ | `Signal` | Purpose |
184
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
185
+ | `{ kind: 'need', previous }` | Answerer requests an offer. Matching `previous` starts a new attempt; otherwise pending offer resends. |
186
+ | `{ kind: 'offer', attempt, sdp }` | Offerer publishes its SDP offer (complete in non-trickle mode, immediate in trickle mode). |
187
+ | `{ kind: 'answer', attempt, sdp }` | Answerer replies to the named attempt. |
188
+ | `{ kind: 'ice', attempt, candidates }` | Batched Trickle ICE candidates (`1..32` `IceCandidatePayload` items) for the named attempt. |
189
+
190
+ ### `tabSignaling()`
191
+
192
+ - Uses a `BroadcastChannel` scoped to `namespaceHash(appId:room[:password])`.
193
+ - Sends `hello` on join, `heartbeat` every 5 s (`O(N)` steady-state traffic), and expires peers after 30 s.
194
+ - Validates sender UUIDs and caps tracked peers at `256`.
195
+
196
+ ### `mqttSignaling(options?)`
197
+
198
+ - Zero-dependency MQTT 3.1.1 client over WebSocket connecting to `urls` (default `defaultMqttRelays`) in parallel.
199
+ - Waits for `CONNACK` and `SUBACK` within `handshakeTimeoutMs` (`10 s`), monitors `PINGRESP` every 20 s, and caps incoming buffers at `128 KiB`.
200
+ - Splits traffic across two topics: `${roomTopic}` for presence (`hello`, `heartbeat`, `bye`) and `${roomTopic}/${peerId}` for targeted `present` and `signal` messages.
201
+ - Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`).
202
+ - Transitions to `'offline'` if all brokers fail on startup or disconnect later, then reconnects with jittered backoff.
203
+
204
+ ### `wsSignaling(url, options?)`
205
+
206
+ - Zero-dependency JSON-over-WebSocket signaling adapter (`ws://` or `wss://`).
207
+ - Isolates rooms using `roomKey = namespaceHash(appId:room[:password])`; raw passwords are never sent to the server.
208
+ - Client sends `{ type: 'join', room, id }` on open (within `handshakeTimeoutMs`, `10,000` ms default), `{ type: 'signal', to, signal }` for peer signaling, `{ type: 'ping' }` every `pingIntervalMs` (`25,000` ms default), and `{ type: 'leave' }` on close.
209
+ - Server sends `{ type: 'roster', peers: string[] }` (validated UUIDs, capped at `256`), `{ type: 'signal', from, signal }`, and `{ type: 'pong' }`. Incoming frames larger than `128 KiB` are ignored.
210
+ - Tracks `awaitingPong`: if no `{ type: 'pong' }` (or other valid server message) arrives before the next ping interval, the socket is closed to trigger reconnect.
211
+ - 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.
212
+
213
+ ### `combineSignaling(...adapters)`
214
+
215
+ - Composes one or more `Signaling` adapters into a single adapter (returning the single adapter directly when given one).
216
+ - Pre-initializes all child states as `'connecting'` and buffers synchronous startup callbacks until every child factory returns without throwing (closing already-started children if any factory throws).
217
+ - Aggregate `SignalingState` is `'online'` if any child is `'online'`, `'connecting'` if none is `'online'` and any is `'connecting'`, `'offline'` if none is `'online'`/`'connecting'` and any is `'offline'`, and `'closed'` when all children are `'closed'`.
218
+ - Maintains per-child peer sets, publishes their union to `Discovery.roster`, clears a child's entries when that child goes `'offline'`/`'closed'` (preserving already-open WebRTC links), routes `send(to, signal)` to every online child advertising `to`, and forwards child `error` reports.
219
+ - Advertises `trickle: true` only when every child session advertises `trickle === true`, and deduplicates incoming `{ kind: 'ice' }` candidates per `(from, attempt)` across child adapters.
220
+
221
+ ### `manualSignaling(outgoing)`
222
+
223
+ - Produces JSON envelopes with `{ v: 1, app, room, from, auth?, to?, signal? }`.
224
+ - `auth` is a hash tag derived from `(appId, room, password)` when `password` is set; the raw password is never included.
225
+ - Does not emit a `need` signal when you accept an `offer` directly, and ignores duplicate `need` retries.
226
+ - Provides `contact()`, `accept(text)` (max `128 KiB`), and `forget(peerId)`.
227
+
228
+ ## Security model
229
+
230
+ - **In-transit data:** WebRTC DTLS encrypts all data channel traffic end-to-end between connected peers.
231
+ - **Signaling integrity:** SDP contains the DTLS certificate fingerprint. An attacker who can modify signaling messages can intercept and alter the handshake (MitM).
232
+ - **Public MQTT without `password`:** Anyone on a public broker can observe room topics or tamper with unencrypted SDP. Use `password` or a trusted signaling server whenever confidentiality or authenticity matters.
233
+ - **Public MQTT with `password`:** Meshpost encrypts and authenticates MQTT signaling payloads with AES-256-GCM (key derived via PBKDF2-SHA256, 100,000 iterations) and binds each message to its MQTT topic as additional authenticated data (AAD). To block replays, it rejects timestamps outside `±60 s` and tracks seen message IDs (`mid`) for `120 s`. Browser encryption (`crypto.subtle`) requires HTTPS or `localhost`.
234
+ - **WebSocket signaling (`wsSignaling`):** Relies on `wss://` TLS transport and a trusted signaling server—unlike password-protected `mqttSignaling()`, `wsSignaling()` does **not** end-to-end encrypt SDP/ICE payloads, so the WS server observes signaling in plaintext (and plain `ws://` provides neither TLS nor E2E). `namespaceHash` is a non-cryptographic 64-bit hash for room isolation, not password protection against offline brute-force. Because it does not require `crypto.subtle`, `wsSignaling()` supports `password` even on non-secure origins (e.g. `http://<lan-ip>`).
235
+ - **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.
236
+ - **Manual signaling:** Exchange connection text only over a trusted channel with the intended peer.
237
+ - **Application concerns:** Durable user identity, authorization, shared state, and game rules belong in the application layer.
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@dimchansky/meshpost",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "author": "Dmitrij Koniajev",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "description": "Zero-dependency TypeScript library for hostless browser-to-browser WebRTC mesh rooms.",
9
+ "keywords": [
10
+ "webrtc",
11
+ "p2p",
12
+ "peer-to-peer",
13
+ "mesh",
14
+ "datachannel",
15
+ "serverless",
16
+ "mqtt",
17
+ "typescript",
18
+ "esm"
19
+ ],
20
+ "homepage": "https://github.com/dimchansky/meshpost#readme",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/dimchansky/meshpost.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/dimchansky/meshpost/issues"
27
+ },
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "main": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "import": "./dist/index.js"
40
+ }
41
+ },
42
+ "files": [
43
+ "dist/*.js",
44
+ "dist/*.d.ts",
45
+ "README.md",
46
+ "LICENSE",
47
+ "docs"
48
+ ],
49
+ "scripts": {
50
+ "clean": "node -e \"import('node:fs').then(fs => fs.rmSync('dist', { recursive: true, force: true }))\"",
51
+ "build": "tsc -p tsconfig.json",
52
+ "check:pkg": "publint",
53
+ "demo": "npm run build && node examples/build.mjs",
54
+ "test": "npm run demo && playwright test",
55
+ "demo:tabs": "npm run demo && node examples/serve.mjs",
56
+ "prepack": "npm run clean && npm run build",
57
+ "format": "prettier --write .",
58
+ "format:check": "prettier --check ."
59
+ },
60
+ "devDependencies": {
61
+ "@playwright/test": "1.56.1",
62
+ "esbuild": "0.25.12",
63
+ "prettier": "3.6.2",
64
+ "publint": "0.3.25",
65
+ "typescript": "5.9.3"
66
+ }
67
+ }