@dimchansky/meshpost 0.1.0 → 0.3.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 +169 -33
- package/dist/blob.d.ts +45 -0
- package/dist/blob.js +364 -0
- package/dist/channel.d.ts +2 -2
- package/dist/channel.js +11 -3
- package/dist/combine.d.ts +18 -0
- package/dist/combine.js +340 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.js +5 -0
- package/dist/mqtt.js +33 -5
- package/dist/room.d.ts +38 -7
- package/dist/room.js +656 -57
- package/dist/signaling.d.ts +25 -1
- package/dist/signaling.js +49 -1
- package/dist/tabs.js +9 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +81 -0
- package/dist/voice.js +838 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +86 -14
- package/package.json +1 -1
package/dist/ws.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Signaling } from './signaling.js';
|
|
2
|
+
export interface WsSignalingOptions {
|
|
3
|
+
/** Automatically reconnect with jittered backoff when disconnected. @default true */
|
|
4
|
+
reconnect?: boolean;
|
|
5
|
+
/** Maximum time in milliseconds to wait for WebSocket open before retrying/failing. @default 10000 */
|
|
6
|
+
handshakeTimeoutMs?: number;
|
|
7
|
+
/** Interval in milliseconds for client keepalive pings (`{ type: 'ping' }`). @default 25000 */
|
|
8
|
+
pingIntervalMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
12
|
+
* Rooms are isolated by a hash of `(appId, room, password)` so raw passwords are never sent.
|
|
13
|
+
*/
|
|
14
|
+
export declare function wsSignaling(url: string, options?: WsSignalingOptions): Signaling;
|
package/dist/ws.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
2
|
+
const maxFrameBytes = 128 * 1024;
|
|
3
|
+
const maxPeers = 256;
|
|
4
|
+
const defaultHandshakeTimeoutMs = 10_000;
|
|
5
|
+
const defaultPingIntervalMs = 25_000;
|
|
6
|
+
/**
|
|
7
|
+
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
8
|
+
* Rooms are isolated by a hash of `(appId, room, password)` so raw passwords are never sent.
|
|
9
|
+
*/
|
|
10
|
+
export function wsSignaling(url, options = {}) {
|
|
11
|
+
let parsed;
|
|
12
|
+
try {
|
|
13
|
+
parsed = new URL(url);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new TypeError('Invalid WebSocket signaling URL');
|
|
17
|
+
}
|
|
18
|
+
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
|
19
|
+
throw new TypeError('WebSocket signaling URL must use ws: or wss:');
|
|
20
|
+
}
|
|
21
|
+
const normalizedUrl = parsed.toString();
|
|
22
|
+
const shouldReconnect = options.reconnect ?? true;
|
|
23
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
|
|
24
|
+
if (!Number.isSafeInteger(handshakeTimeoutMs) ||
|
|
25
|
+
handshakeTimeoutMs <= 0 ||
|
|
26
|
+
handshakeTimeoutMs > 2_147_483_647) {
|
|
27
|
+
throw new RangeError('Invalid WebSocket handshake timeout');
|
|
28
|
+
}
|
|
29
|
+
const pingIntervalMs = options.pingIntervalMs ?? defaultPingIntervalMs;
|
|
30
|
+
if (!Number.isSafeInteger(pingIntervalMs) ||
|
|
31
|
+
pingIntervalMs <= 0 ||
|
|
32
|
+
pingIntervalMs > 2_147_483_647) {
|
|
33
|
+
throw new RangeError('Invalid WebSocket ping interval');
|
|
34
|
+
}
|
|
35
|
+
return (discovery) => {
|
|
36
|
+
const roomKey = namespaceHash(discovery.appId +
|
|
37
|
+
':' +
|
|
38
|
+
discovery.room +
|
|
39
|
+
(discovery.password !== undefined ? ':' + discovery.password : ''));
|
|
40
|
+
const knownPeers = new Set();
|
|
41
|
+
let ws;
|
|
42
|
+
let closed = false;
|
|
43
|
+
let reportedOnline = false;
|
|
44
|
+
let reportedOffline = false;
|
|
45
|
+
let awaitingPong = false;
|
|
46
|
+
let attempt = 0;
|
|
47
|
+
let handshakeTimer;
|
|
48
|
+
let pingTimer;
|
|
49
|
+
let reconnectTimer;
|
|
50
|
+
const clearTimers = () => {
|
|
51
|
+
clearTimeout(handshakeTimer);
|
|
52
|
+
handshakeTimer = undefined;
|
|
53
|
+
clearInterval(pingTimer);
|
|
54
|
+
pingTimer = undefined;
|
|
55
|
+
};
|
|
56
|
+
const sendJson = (payload) => {
|
|
57
|
+
if (closed || !ws || ws.readyState !== WebSocket.OPEN)
|
|
58
|
+
return false;
|
|
59
|
+
try {
|
|
60
|
+
ws.send(JSON.stringify(payload));
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const reportOffline = (reason) => {
|
|
68
|
+
if (closed)
|
|
69
|
+
return;
|
|
70
|
+
if (reportedOnline || !reportedOffline) {
|
|
71
|
+
reportedOnline = false;
|
|
72
|
+
reportedOffline = true;
|
|
73
|
+
discovery.status('offline', reason);
|
|
74
|
+
discovery.error?.('signaling-error', reason);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const scheduleReconnect = () => {
|
|
78
|
+
if (closed || !shouldReconnect || reconnectTimer)
|
|
79
|
+
return;
|
|
80
|
+
const base = Math.min(10_000, 500 * 2 ** Math.min(attempt++, 5));
|
|
81
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
82
|
+
reconnectTimer = setTimeout(() => {
|
|
83
|
+
reconnectTimer = undefined;
|
|
84
|
+
connect();
|
|
85
|
+
}, delay);
|
|
86
|
+
};
|
|
87
|
+
const connect = () => {
|
|
88
|
+
if (closed)
|
|
89
|
+
return;
|
|
90
|
+
clearTimers();
|
|
91
|
+
let socket;
|
|
92
|
+
try {
|
|
93
|
+
socket = new WebSocket(normalizedUrl);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
reportOffline('WebSocket signaling connection failed');
|
|
97
|
+
scheduleReconnect();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
ws = socket;
|
|
101
|
+
awaitingPong = false;
|
|
102
|
+
let settled = false;
|
|
103
|
+
handshakeTimer = setTimeout(() => {
|
|
104
|
+
if (closed || ws !== socket || settled)
|
|
105
|
+
return;
|
|
106
|
+
try {
|
|
107
|
+
socket.close();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// Ignore close errors.
|
|
111
|
+
}
|
|
112
|
+
}, handshakeTimeoutMs);
|
|
113
|
+
socket.onopen = () => {
|
|
114
|
+
if (closed || ws !== socket) {
|
|
115
|
+
try {
|
|
116
|
+
socket.close();
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Ignore close errors.
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
settled = true;
|
|
124
|
+
clearTimeout(handshakeTimer);
|
|
125
|
+
handshakeTimer = undefined;
|
|
126
|
+
attempt = 0;
|
|
127
|
+
awaitingPong = false;
|
|
128
|
+
if (!sendJson({ type: 'join', room: roomKey, id: discovery.self })) {
|
|
129
|
+
try {
|
|
130
|
+
socket.close();
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Ignore close errors.
|
|
134
|
+
}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!reportedOnline) {
|
|
138
|
+
reportedOnline = true;
|
|
139
|
+
reportedOffline = false;
|
|
140
|
+
discovery.status('online');
|
|
141
|
+
}
|
|
142
|
+
pingTimer = setInterval(() => {
|
|
143
|
+
if (closed || ws !== socket)
|
|
144
|
+
return;
|
|
145
|
+
if (awaitingPong) {
|
|
146
|
+
try {
|
|
147
|
+
socket.close();
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// Ignore close errors.
|
|
151
|
+
}
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
awaitingPong = true;
|
|
155
|
+
if (!sendJson({ type: 'ping' })) {
|
|
156
|
+
try {
|
|
157
|
+
socket.close();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// Ignore close errors.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}, pingIntervalMs);
|
|
164
|
+
};
|
|
165
|
+
socket.onmessage = ({ data }) => {
|
|
166
|
+
if (closed || ws !== socket)
|
|
167
|
+
return;
|
|
168
|
+
if (typeof data !== 'string' || data.length > maxFrameBytes)
|
|
169
|
+
return;
|
|
170
|
+
let msg;
|
|
171
|
+
try {
|
|
172
|
+
const parsedMsg = JSON.parse(data);
|
|
173
|
+
msg =
|
|
174
|
+
parsedMsg && typeof parsedMsg === 'object'
|
|
175
|
+
? parsedMsg
|
|
176
|
+
: null;
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (!msg || typeof msg.type !== 'string')
|
|
182
|
+
return;
|
|
183
|
+
awaitingPong = false;
|
|
184
|
+
if (msg.type === 'pong')
|
|
185
|
+
return;
|
|
186
|
+
if (msg.type === 'roster' && Array.isArray(msg.peers)) {
|
|
187
|
+
knownPeers.clear();
|
|
188
|
+
for (const id of msg.peers) {
|
|
189
|
+
if (isUuid(id) && id !== discovery.self) {
|
|
190
|
+
knownPeers.add(id);
|
|
191
|
+
if (knownPeers.size >= maxPeers)
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
discovery.roster([...knownPeers]);
|
|
196
|
+
}
|
|
197
|
+
else if (msg.type === 'signal' &&
|
|
198
|
+
isUuid(msg.from) &&
|
|
199
|
+
msg.from !== discovery.self &&
|
|
200
|
+
isSignal(msg.signal)) {
|
|
201
|
+
if (!knownPeers.has(msg.from)) {
|
|
202
|
+
if (knownPeers.size >= maxPeers) {
|
|
203
|
+
const oldest = knownPeers.values().next().value;
|
|
204
|
+
if (oldest !== undefined)
|
|
205
|
+
knownPeers.delete(oldest);
|
|
206
|
+
}
|
|
207
|
+
knownPeers.add(msg.from);
|
|
208
|
+
discovery.roster([...knownPeers]);
|
|
209
|
+
}
|
|
210
|
+
discovery.receive(msg.from, msg.signal);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
socket.onerror = () => {
|
|
214
|
+
if (ws !== socket)
|
|
215
|
+
return;
|
|
216
|
+
try {
|
|
217
|
+
socket.close();
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// Ignore close errors.
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
socket.onclose = () => {
|
|
224
|
+
if (ws !== socket)
|
|
225
|
+
return;
|
|
226
|
+
ws = undefined;
|
|
227
|
+
clearTimers();
|
|
228
|
+
if (closed)
|
|
229
|
+
return;
|
|
230
|
+
const reason = settled
|
|
231
|
+
? 'WebSocket signaling disconnected'
|
|
232
|
+
: 'WebSocket signaling connection failed';
|
|
233
|
+
reportOffline(reason);
|
|
234
|
+
scheduleReconnect();
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
// Defer initial connect so synchronous errors never fire before callers attach listeners.
|
|
238
|
+
queueMicrotask(connect);
|
|
239
|
+
return {
|
|
240
|
+
trickle: true,
|
|
241
|
+
send(to, signal) {
|
|
242
|
+
return sendJson({ type: 'signal', to, signal });
|
|
243
|
+
},
|
|
244
|
+
close() {
|
|
245
|
+
if (closed)
|
|
246
|
+
return;
|
|
247
|
+
closed = true;
|
|
248
|
+
clearTimers();
|
|
249
|
+
clearTimeout(reconnectTimer);
|
|
250
|
+
reconnectTimer = undefined;
|
|
251
|
+
const current = ws;
|
|
252
|
+
ws = undefined;
|
|
253
|
+
if (current) {
|
|
254
|
+
if (current.readyState === WebSocket.OPEN) {
|
|
255
|
+
try {
|
|
256
|
+
current.send(JSON.stringify({ type: 'leave' }));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// Ignore send errors during close.
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
current.close();
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
// Ignore close errors.
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
};
|
|
272
|
+
}
|
package/docs/behavior.md
CHANGED
|
@@ -18,7 +18,11 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
18
18
|
| Early-packet buffer | `64` packets or `256 KiB` per peer | Holds packets arriving before both data channels open. |
|
|
19
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
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.
|
|
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
|
+
| `createVoice` remote cap | `4` audio streams per peer | Max concurrent incoming audio streams played/metered per peer (`180` ms meter default). |
|
|
25
|
+
| `fetchTurnCredentials` caps | `5,000` ms / `64 KiB` / `16` servers | Default request timeout, max JSON response body, and max sanitized `RTCIceServer` entries. |
|
|
22
26
|
|
|
23
27
|
## Room lifecycle
|
|
24
28
|
|
|
@@ -27,7 +31,8 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
27
31
|
- `joinRoom(name, options)` generates a fresh random peer ID (UUID v4, exposed as `room.id`). A page reload creates a new peer ID.
|
|
28
32
|
- `joinRoom()` returns synchronously and starts discovery immediately.
|
|
29
33
|
- `room.peers` returns a snapshot array of remote peer IDs whose unreliable and reliable channels are both open.
|
|
30
|
-
- Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription returns an unsubscribe function.
|
|
34
|
+
- Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `blobChannel.onBlob`, `blobChannel.onProgress`, and `voice.onChange`) returns an idempotent unsubscribe function and optionally accepts `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`).
|
|
35
|
+
- 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.
|
|
31
36
|
- A room of `N` peers forms up to `N(N - 1) / 2` direct connections (bounded per peer by `maxPeers`).
|
|
32
37
|
- There is no host election, packet forwarding, or history replay. Any peer can join first.
|
|
33
38
|
|
|
@@ -48,12 +53,33 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
48
53
|
- Meshpost attempts to send `meshpost/1/leave` over the reliable channel and waits up to `750` ms before closing the `RTCPeerConnection`.
|
|
49
54
|
- Abruptly closing a tab can skip the departure notice. Other peer pairs keep working normally.
|
|
50
55
|
|
|
56
|
+
### Structured errors (`room.onError`)
|
|
57
|
+
|
|
58
|
+
`room.onError((error) => ...)` emits `RoomError` objects (`{ code, message, peerId? }`) with built-in anti-spam guarantees:
|
|
59
|
+
|
|
60
|
+
| Code | When emitted | Anti-spam rule |
|
|
61
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
|
|
62
|
+
| `'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. |
|
|
63
|
+
| `'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. |
|
|
64
|
+
| `'media-error'` | In-band WebRTC media renegotiation fails on a live link. Includes `peerId`. Healthy data channels stay open. | Emitted per failed renegotiation operation. |
|
|
65
|
+
| `'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. |
|
|
66
|
+
| `'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()`. |
|
|
67
|
+
|
|
68
|
+
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.
|
|
69
|
+
|
|
51
70
|
### Synchronous errors
|
|
52
71
|
|
|
53
72
|
- `joinRoom()` throws `TypeError` for invalid `name` (`^[a-zA-Z0-9_-]{1,64}$`), invalid `appId` (`^[a-zA-Z0-9._-]{1,64}$`), or empty `password`.
|
|
54
73
|
- `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`.
|
|
55
74
|
- `room.send()` throws `Error` after `leave()`, and `TypeError` for non-`Uint8Array` payloads or invalid `delivery`.
|
|
75
|
+
- `room.addStream()` throws `Error` after `leave()`, and `TypeError` for non-`MediaStream` arguments.
|
|
56
76
|
- `createChannel()` throws `TypeError` for an empty name or invalid `delivery`, and `RangeError` if the UTF-8 name exceeds 64 bytes.
|
|
77
|
+
- `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
|
|
78
|
+
- `wsSignaling()` throws `TypeError` for non-`ws:`/`wss:` URLs and `RangeError` for invalid `handshakeTimeoutMs` or `pingIntervalMs`.
|
|
79
|
+
- `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.
|
|
80
|
+
- `mqttSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, and `TypeError` for an empty `password`.
|
|
81
|
+
- `createVoice()` throws `TypeError` for invalid `room`, `audioConstraints`, or `to`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `voice.setVolume()` throws `RangeError` for non-finite numbers.
|
|
82
|
+
- `fetchTurnCredentials()` rejects with `TypeError` for invalid URLs, disallowed protocols, embedded URL credentials, or invalid `accessKey`, and `RangeError` for invalid `timeoutMs`.
|
|
57
83
|
|
|
58
84
|
## Sending and receiving
|
|
59
85
|
|
|
@@ -101,13 +127,14 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
101
127
|
- 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.
|
|
102
128
|
- Duplicate `answer` delivery is ignored once the first `answer` for an attempt is applied.
|
|
103
129
|
|
|
104
|
-
### ICE gathering and loopback fallback
|
|
130
|
+
### ICE gathering, opt-in Trickle ICE, and loopback fallback
|
|
105
131
|
|
|
106
|
-
-
|
|
107
|
-
-
|
|
108
|
-
- When
|
|
132
|
+
- Adapters can opt in to **Trickle ICE** by setting `trickle: true` on their returned `SignalingSession` (enabled by default in `tabSignaling()`, `wsSignaling()`, `mqttSignaling()`, `withLocalTabs(primary)` when `primary` sets `trickle: true`, and in `combineSignaling()` when every child session sets `trickle: true`).
|
|
133
|
+
- 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).
|
|
134
|
+
- 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.
|
|
135
|
+
- 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.
|
|
109
136
|
- By default, `defaultIceServers` provides public Cloudflare and Google STUN servers. Override with `rtcConfig.iceServers` or extend with `turnConfig`.
|
|
110
|
-
- 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 (unless `iceTransportPolicy` is `'relay'`).
|
|
137
|
+
- 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'`).
|
|
111
138
|
- Original candidates stay intact, and Meshpost never sends this local fallback over signaling.
|
|
112
139
|
|
|
113
140
|
### SCTP data channels
|
|
@@ -122,7 +149,11 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
122
149
|
### Framing and early packets
|
|
123
150
|
|
|
124
151
|
- Application messages on both channels are raw binary `ArrayBuffer` frames. `room.send()` adds no library header.
|
|
125
|
-
- A text message `'meshpost/1/leave'` on stream `1` signals graceful departure.
|
|
152
|
+
- A text message `'meshpost/1/leave'` on stream `1` signals graceful departure.
|
|
153
|
+
- 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.
|
|
154
|
+
- 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()`.
|
|
155
|
+
- 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`.
|
|
156
|
+
- `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()`.
|
|
126
157
|
- Incoming binary packets larger than `16,384` bytes are ignored on stream `0` and close the link on stream `1`.
|
|
127
158
|
- Packets arriving before both channels open are buffered up to `64` packets and `256 KiB` per peer.
|
|
128
159
|
- Exceeding the early buffer drops excess unreliable packets or closes the incomplete link on a reliable packet.
|
|
@@ -133,21 +164,32 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
133
164
|
- `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]`.
|
|
134
165
|
- `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).
|
|
135
166
|
|
|
167
|
+
### Chunked transfers (`createBlobChannel`)
|
|
168
|
+
|
|
169
|
+
- `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.
|
|
170
|
+
- Wire opcodes inside the logical channel:
|
|
171
|
+
- `0x01` `START`: `[0x01, transferId (u32 BE), totalBytes (u32 BE), ...chunk0]` (blobs `<= chunkSize`, including `0`-byte blobs, complete in one packet).
|
|
172
|
+
- `0x02` `DATA`: `[0x02, transferId (u32 BE), ...chunkN]` (non-empty ordered payload chunks).
|
|
173
|
+
- `0x03` `ABORT`: `[0x03, transferId (u32 BE)]` (sent best-effort on sender `AbortSignal` cancellation, `blobChannel.close()`, or mid-transfer `'too-large'`).
|
|
174
|
+
- Senders pace every recipient independently (`channel.send(frame, { to: peerId })`) using `room.onDrain` so one slow peer never stalls another during broadcast.
|
|
175
|
+
- 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()`.
|
|
176
|
+
|
|
136
177
|
## Signaling adapters
|
|
137
178
|
|
|
138
179
|
### Custom `Signaling` contract
|
|
139
180
|
|
|
140
|
-
- A `Signaling` factory receives `Discovery` (`appId`, `room`, `self`, optional `password`, `roster`, `receive`, `status`) and returns `{ send(to, signal), close() }
|
|
181
|
+
- A `Signaling` factory receives `Discovery` (`appId`, `room`, `self`, optional `password`, `roster`, `receive`, `status`, optional `error`) and returns a `SignalingSession` (`{ trickle?, canReach?(peerId), send(to, signal), close() }`).
|
|
141
182
|
- `send(to, signal)` must return `boolean` (`true` when accepted for delivery; returning `false` drops the pending link).
|
|
142
183
|
- Report `status('online')` before publishing a roster.
|
|
143
184
|
- Deliver a roster containing a sender before calling `receive(from, signal)`.
|
|
144
185
|
- Isolate rooms by `(appId, room)` (and `password` if used).
|
|
145
186
|
|
|
146
|
-
| `Signal`
|
|
147
|
-
|
|
|
148
|
-
| `{ kind: 'need', previous }`
|
|
149
|
-
| `{ kind: 'offer', attempt, sdp }`
|
|
150
|
-
| `{ kind: 'answer', attempt, sdp }`
|
|
187
|
+
| `Signal` | Purpose |
|
|
188
|
+
| -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
189
|
+
| `{ kind: 'need', previous }` | Answerer requests an offer. Matching `previous` starts a new attempt; otherwise pending offer resends. |
|
|
190
|
+
| `{ kind: 'offer', attempt, sdp }` | Offerer publishes its SDP offer (complete in non-trickle mode, immediate in trickle mode). |
|
|
191
|
+
| `{ kind: 'answer', attempt, sdp }` | Answerer replies to the named attempt. |
|
|
192
|
+
| `{ kind: 'ice', attempt, candidates }` | Batched Trickle ICE candidates (`1..32` `IceCandidatePayload` items) for the named attempt. |
|
|
151
193
|
|
|
152
194
|
### `tabSignaling()`
|
|
153
195
|
|
|
@@ -163,6 +205,34 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
163
205
|
- Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`).
|
|
164
206
|
- Transitions to `'offline'` if all brokers fail on startup or disconnect later, then reconnects with jittered backoff.
|
|
165
207
|
|
|
208
|
+
### `wsSignaling(url, options?)`
|
|
209
|
+
|
|
210
|
+
- Zero-dependency JSON-over-WebSocket signaling adapter (`ws://` or `wss://`).
|
|
211
|
+
- Isolates rooms using `roomKey = namespaceHash(appId:room[:password])`; raw passwords are never sent to the server.
|
|
212
|
+
- 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.
|
|
213
|
+
- 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.
|
|
214
|
+
- Tracks `awaitingPong`: if no `{ type: 'pong' }` (or other valid server message) arrives before the next ping interval, the socket is closed to trigger reconnect.
|
|
215
|
+
- 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.
|
|
216
|
+
|
|
217
|
+
### `combineSignaling(...adapters)`
|
|
218
|
+
|
|
219
|
+
- Composes one or more `Signaling` adapters into a single adapter (returning the single adapter directly when given one).
|
|
220
|
+
- 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).
|
|
221
|
+
- 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'`.
|
|
222
|
+
- Maintains per-child peer sets, publishes their union to `Discovery.roster`, clears unreachable entries when a child goes `'offline'`/`'closed'` (preserving already-open WebRTC links and any peers still reachable via nested `canReach`), routes `send(to, signal)` to every reachable child advertising `to`, and forwards child `error` reports.
|
|
223
|
+
- Advertises `trickle: true` only when every child session advertises `trickle === true`, and deduplicates incoming `{ kind: 'ice' }` candidates per `(from, attempt)` across child adapters.
|
|
224
|
+
|
|
225
|
+
### `withLocalTabs(primary)`
|
|
226
|
+
|
|
227
|
+
- Composes `tabSignaling()` with `primary`, publishing the union roster and deduplicating Trickle ICE across both transports while forwarding **only `primary`'s `SignalingState` and `error` events** to the room.
|
|
228
|
+
- Exposes `SignalingSession.canReach(peerId)` so same-browser tabs still negotiate and connect even while `primary` (and `room.signalingState`) is `'connecting'` or `'offline'` (including when nested inside `combineSignaling()`).
|
|
229
|
+
- Delegates directly to `primary` without error when `BroadcastChannel` is undefined, on `file:` or opaque (`origin === 'null'`) origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
|
|
230
|
+
|
|
231
|
+
### `createVoice(room, options?)` and `fetchTurnCredentials(url, options?)`
|
|
232
|
+
|
|
233
|
+
- `createVoice(room, options?)` attaches hidden `<audio autoplay>` elements for up to `4` remote audio streams per peer (hydrating any streams already active on `room` at construction), coalesces concurrent `startMic()`/`toggleMic()` calls, cancels pending `getUserMedia` via `micEpoch` 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.
|
|
234
|
+
- `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]+$`).
|
|
235
|
+
|
|
166
236
|
### `manualSignaling(outgoing)`
|
|
167
237
|
|
|
168
238
|
- Produces JSON envelopes with `{ v: 1, app, room, from, auth?, to?, signal? }`.
|
|
@@ -176,5 +246,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
176
246
|
- **Signaling integrity:** SDP contains the DTLS certificate fingerprint. An attacker who can modify signaling messages can intercept and alter the handshake (MitM).
|
|
177
247
|
- **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.
|
|
178
248
|
- **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`.
|
|
249
|
+
- **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>`).
|
|
250
|
+
- **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.
|
|
179
251
|
- **Manual signaling:** Exchange connection text only over a trusted channel with the intended peer.
|
|
180
252
|
- **Application concerns:** Durable user identity, authorization, shared state, and game rules belong in the application layer.
|