@dimchansky/meshpost 0.1.0 → 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.
- package/README.md +91 -29
- 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 +7 -0
- package/dist/combine.js +249 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +3 -0
- package/dist/mqtt.js +33 -5
- package/dist/room.d.ts +32 -7
- package/dist/room.js +581 -51
- package/dist/signaling.d.ts +20 -1
- package/dist/signaling.js +49 -1
- package/dist/tabs.js +1 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +71 -14
- package/package.json +1 -1
package/dist/signaling.d.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/** Individual ICE candidate entry carried inside a Trickle ICE `'ice'` signal. */
|
|
2
|
+
export interface IceCandidatePayload {
|
|
3
|
+
/** SDP candidate attribute string (`''` signals end-of-candidates). */
|
|
4
|
+
readonly candidate: string;
|
|
5
|
+
/** Optional media stream identification tag. */
|
|
6
|
+
readonly sdpMid?: string | null;
|
|
7
|
+
/** Optional zero-based media description index. */
|
|
8
|
+
readonly sdpMLineIndex?: number | null;
|
|
9
|
+
}
|
|
1
10
|
/** Discovery supplies peer IDs. Only the two endpoints interpret the signal payload. */
|
|
2
11
|
export type Signal = {
|
|
3
12
|
kind: 'need';
|
|
@@ -6,9 +15,15 @@ export type Signal = {
|
|
|
6
15
|
kind: 'offer' | 'answer';
|
|
7
16
|
attempt: number;
|
|
8
17
|
sdp: string;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'ice';
|
|
20
|
+
attempt: number;
|
|
21
|
+
candidates: readonly IceCandidatePayload[];
|
|
9
22
|
};
|
|
10
23
|
/** Connection state reported by a signaling adapter. */
|
|
11
24
|
export type SignalingState = 'connecting' | 'online' | 'offline' | 'closed';
|
|
25
|
+
/** Structured error codes that a signaling adapter may report via `Discovery.error`. */
|
|
26
|
+
export type SignalingErrorCode = 'decrypt-failed' | 'signaling-error';
|
|
12
27
|
/** Callbacks and room metadata passed by `joinRoom()` into a `Signaling` adapter factory. */
|
|
13
28
|
export interface Discovery {
|
|
14
29
|
/** Application namespace isolating rooms across apps. */
|
|
@@ -25,9 +40,13 @@ export interface Discovery {
|
|
|
25
40
|
receive(from: string, signal: Signal): void;
|
|
26
41
|
/** Report a signaling state transition (with an optional human-readable reason). */
|
|
27
42
|
status(state: SignalingState, reason?: string): void;
|
|
43
|
+
/** Optional: report a structured signaling error (e.g. `'decrypt-failed'` or `'signaling-error'`). */
|
|
44
|
+
error?(code: SignalingErrorCode, message?: string): void;
|
|
28
45
|
}
|
|
29
46
|
/** Active signaling handle returned by a `Signaling` adapter factory. */
|
|
30
47
|
export interface SignalingSession {
|
|
48
|
+
/** Set `true` if this adapter supports incremental Trickle ICE (`{ kind: 'ice' }`) messages. */
|
|
49
|
+
readonly trickle?: boolean;
|
|
31
50
|
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
32
51
|
send(to: string, signal: Signal): boolean;
|
|
33
52
|
/** Shut down the signaling adapter and release all sockets/timers. */
|
|
@@ -43,7 +62,7 @@ export declare function isUuid(value: unknown): value is string;
|
|
|
43
62
|
export declare function randomUuid(): string;
|
|
44
63
|
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
45
64
|
export declare function namespaceHash(input: string): string;
|
|
46
|
-
/** Type guard validating a parsed signaling payload (`need`, `offer`, or `
|
|
65
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
47
66
|
export declare function isSignal(value: unknown): value is Signal;
|
|
48
67
|
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
49
68
|
* Preserve the original candidate and its priority. Never transmit this local hint.
|
package/dist/signaling.js
CHANGED
|
@@ -27,7 +27,26 @@ export function namespaceHash(input) {
|
|
|
27
27
|
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
28
28
|
return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0');
|
|
29
29
|
}
|
|
30
|
-
|
|
30
|
+
function isIceCandidatePayload(value) {
|
|
31
|
+
if (!value || typeof value !== 'object')
|
|
32
|
+
return false;
|
|
33
|
+
const c = value;
|
|
34
|
+
if (typeof c.candidate !== 'string' || c.candidate.length > 1024)
|
|
35
|
+
return false;
|
|
36
|
+
if (c.sdpMid !== undefined &&
|
|
37
|
+
c.sdpMid !== null &&
|
|
38
|
+
(typeof c.sdpMid !== 'string' || c.sdpMid.length > 64))
|
|
39
|
+
return false;
|
|
40
|
+
if (c.sdpMLineIndex !== undefined &&
|
|
41
|
+
c.sdpMLineIndex !== null &&
|
|
42
|
+
(typeof c.sdpMLineIndex !== 'number' ||
|
|
43
|
+
!Number.isSafeInteger(c.sdpMLineIndex) ||
|
|
44
|
+
c.sdpMLineIndex < 0 ||
|
|
45
|
+
c.sdpMLineIndex > 65535))
|
|
46
|
+
return false;
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
31
50
|
export function isSignal(value) {
|
|
32
51
|
if (!value || typeof value !== 'object')
|
|
33
52
|
return false;
|
|
@@ -41,6 +60,18 @@ export function isSignal(value) {
|
|
|
41
60
|
value.previous > 0 &&
|
|
42
61
|
value.previous <= maxAttemptNumber)));
|
|
43
62
|
}
|
|
63
|
+
if (value.kind === 'ice') {
|
|
64
|
+
return ('attempt' in value &&
|
|
65
|
+
typeof value.attempt === 'number' &&
|
|
66
|
+
Number.isSafeInteger(value.attempt) &&
|
|
67
|
+
value.attempt > 0 &&
|
|
68
|
+
value.attempt <= maxAttemptNumber &&
|
|
69
|
+
'candidates' in value &&
|
|
70
|
+
Array.isArray(value.candidates) &&
|
|
71
|
+
value.candidates.length > 0 &&
|
|
72
|
+
value.candidates.length <= 32 &&
|
|
73
|
+
value.candidates.every(isIceCandidatePayload));
|
|
74
|
+
}
|
|
44
75
|
return ((value.kind === 'offer' || value.kind === 'answer') &&
|
|
45
76
|
'attempt' in value &&
|
|
46
77
|
typeof value.attempt === 'number' &&
|
|
@@ -51,12 +82,29 @@ export function isSignal(value) {
|
|
|
51
82
|
typeof value.sdp === 'string' &&
|
|
52
83
|
value.sdp.length <= 64 * 1024);
|
|
53
84
|
}
|
|
85
|
+
const localMdnsCandidatePattern = /^(?:a=)?candidate:\S+ (\d+) udp \d+ [a-z0-9.-]+\.local (\d+) typ host(?: |$)/i;
|
|
54
86
|
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
55
87
|
* Preserve the original candidate and its priority. Never transmit this local hint.
|
|
56
88
|
*/
|
|
57
89
|
export function withLoopbackFallback(signal) {
|
|
58
90
|
if (signal.kind === 'need')
|
|
59
91
|
return signal;
|
|
92
|
+
if (signal.kind === 'ice') {
|
|
93
|
+
let index = 0;
|
|
94
|
+
const out = [];
|
|
95
|
+
for (const item of signal.candidates) {
|
|
96
|
+
out.push(item);
|
|
97
|
+
const match = localMdnsCandidatePattern.exec(item.candidate);
|
|
98
|
+
if (match) {
|
|
99
|
+
out.push({
|
|
100
|
+
candidate: `candidate:mp${++index} ${match[1]} udp 1 127.0.0.1 ${match[2]} typ host`,
|
|
101
|
+
...(item.sdpMid !== undefined ? { sdpMid: item.sdpMid } : {}),
|
|
102
|
+
...(item.sdpMLineIndex !== undefined ? { sdpMLineIndex: item.sdpMLineIndex } : {})
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return index ? { ...signal, candidates: out } : signal;
|
|
107
|
+
}
|
|
60
108
|
const eol = signal.sdp.includes('\r\n') ? '\r\n' : '\n';
|
|
61
109
|
let index = 0;
|
|
62
110
|
const lines = [];
|
package/dist/tabs.js
CHANGED
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,9 @@ 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. |
|
|
22
24
|
|
|
23
25
|
## Room lifecycle
|
|
24
26
|
|
|
@@ -27,7 +29,8 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
27
29
|
- `joinRoom(name, options)` generates a fresh random peer ID (UUID v4, exposed as `room.id`). A page reload creates a new peer ID.
|
|
28
30
|
- `joinRoom()` returns synchronously and starts discovery immediately.
|
|
29
31
|
- `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.
|
|
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.
|
|
31
34
|
- A room of `N` peers forms up to `N(N - 1) / 2` direct connections (bounded per peer by `maxPeers`).
|
|
32
35
|
- There is no host election, packet forwarding, or history replay. Any peer can join first.
|
|
33
36
|
|
|
@@ -48,12 +51,31 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
48
51
|
- Meshpost attempts to send `meshpost/1/leave` over the reliable channel and waits up to `750` ms before closing the `RTCPeerConnection`.
|
|
49
52
|
- Abruptly closing a tab can skip the departure notice. Other peer pairs keep working normally.
|
|
50
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
|
+
|
|
51
68
|
### Synchronous errors
|
|
52
69
|
|
|
53
70
|
- `joinRoom()` throws `TypeError` for invalid `name` (`^[a-zA-Z0-9_-]{1,64}$`), invalid `appId` (`^[a-zA-Z0-9._-]{1,64}$`), or empty `password`.
|
|
54
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`.
|
|
55
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.
|
|
56
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`.
|
|
57
79
|
|
|
58
80
|
## Sending and receiving
|
|
59
81
|
|
|
@@ -101,13 +123,14 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
|
|
|
101
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.
|
|
102
124
|
- Duplicate `answer` delivery is ignored once the first `answer` for an attempt is applied.
|
|
103
125
|
|
|
104
|
-
### ICE gathering and loopback fallback
|
|
126
|
+
### ICE gathering, opt-in Trickle ICE, and loopback fallback
|
|
105
127
|
|
|
106
|
-
-
|
|
107
|
-
-
|
|
108
|
-
- When
|
|
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.
|
|
109
132
|
- 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'`).
|
|
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'`).
|
|
111
134
|
- Original candidates stay intact, and Meshpost never sends this local fallback over signaling.
|
|
112
135
|
|
|
113
136
|
### SCTP data channels
|
|
@@ -122,7 +145,11 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
122
145
|
### Framing and early packets
|
|
123
146
|
|
|
124
147
|
- 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.
|
|
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()`.
|
|
126
153
|
- Incoming binary packets larger than `16,384` bytes are ignored on stream `0` and close the link on stream `1`.
|
|
127
154
|
- Packets arriving before both channels open are buffered up to `64` packets and `256 KiB` per peer.
|
|
128
155
|
- Exceeding the early buffer drops excess unreliable packets or closes the incomplete link on a reliable packet.
|
|
@@ -133,21 +160,32 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
133
160
|
- `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]`.
|
|
134
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).
|
|
135
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
|
+
|
|
136
173
|
## Signaling adapters
|
|
137
174
|
|
|
138
175
|
### Custom `Signaling` contract
|
|
139
176
|
|
|
140
|
-
- A `Signaling` factory receives `Discovery` (`appId`, `room`, `self`, optional `password`, `roster`, `receive`, `status`) and returns `{ send(to, signal), close() }`.
|
|
177
|
+
- A `Signaling` factory receives `Discovery` (`appId`, `room`, `self`, optional `password`, `roster`, `receive`, `status`, optional `error`) and returns `{ send(to, signal), close() }`.
|
|
141
178
|
- `send(to, signal)` must return `boolean` (`true` when accepted for delivery; returning `false` drops the pending link).
|
|
142
179
|
- Report `status('online')` before publishing a roster.
|
|
143
180
|
- Deliver a roster containing a sender before calling `receive(from, signal)`.
|
|
144
181
|
- Isolate rooms by `(appId, room)` (and `password` if used).
|
|
145
182
|
|
|
146
|
-
| `Signal`
|
|
147
|
-
|
|
|
148
|
-
| `{ kind: 'need', previous }`
|
|
149
|
-
| `{ kind: 'offer', attempt, sdp }`
|
|
150
|
-
| `{ kind: 'answer', attempt, sdp }`
|
|
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. |
|
|
151
189
|
|
|
152
190
|
### `tabSignaling()`
|
|
153
191
|
|
|
@@ -163,6 +201,23 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
163
201
|
- Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`).
|
|
164
202
|
- Transitions to `'offline'` if all brokers fail on startup or disconnect later, then reconnects with jittered backoff.
|
|
165
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
|
+
|
|
166
221
|
### `manualSignaling(outgoing)`
|
|
167
222
|
|
|
168
223
|
- Produces JSON envelopes with `{ v: 1, app, room, from, auth?, to?, signal? }`.
|
|
@@ -176,5 +231,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
176
231
|
- **Signaling integrity:** SDP contains the DTLS certificate fingerprint. An attacker who can modify signaling messages can intercept and alter the handshake (MitM).
|
|
177
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.
|
|
178
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.
|
|
179
236
|
- **Manual signaling:** Exchange connection text only over a trusted channel with the intended peer.
|
|
180
237
|
- **Application concerns:** Durable user identity, authorization, shared state, and game rules belong in the application layer.
|