@dimchansky/meshpost 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +293 -2
- package/dist/channel.d.ts +26 -0
- package/dist/channel.js +43 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +6 -0
- package/dist/manual.d.ts +13 -0
- package/dist/manual.js +109 -0
- package/dist/mqtt.d.ts +20 -0
- package/dist/mqtt.js +582 -0
- package/dist/room.d.ts +74 -0
- package/dist/room.js +600 -0
- package/dist/signaling.d.ts +51 -0
- package/dist/signaling.js +70 -0
- package/dist/tabs.d.ts +3 -0
- package/dist/tabs.js +93 -0
- package/docs/behavior.md +180 -0
- package/package.json +65 -4
package/dist/mqtt.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
2
|
+
/** Built-in public MQTT-over-WebSocket relay URLs used by default. */
|
|
3
|
+
export const defaultMqttRelays = Object.freeze([
|
|
4
|
+
'wss://broker.emqx.io:8084/mqtt',
|
|
5
|
+
'wss://broker.hivemq.com:8884/mqtt',
|
|
6
|
+
'wss://test.mosquitto.org:8081/mqtt'
|
|
7
|
+
]);
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
const decoder = new TextDecoder();
|
|
10
|
+
const maxMqttBuffer = 128 * 1024;
|
|
11
|
+
const maxSeenPeers = 256;
|
|
12
|
+
const maxSeenMids = 2048;
|
|
13
|
+
const replayWindowMs = 60_000;
|
|
14
|
+
const midTtlMs = replayWindowMs * 2;
|
|
15
|
+
const defaultMqttHandshakeTimeoutMs = 10_000;
|
|
16
|
+
function encodeRemainingLength(length) {
|
|
17
|
+
const bytes = [];
|
|
18
|
+
let n = length;
|
|
19
|
+
do {
|
|
20
|
+
let digit = n & 0x7f;
|
|
21
|
+
n >>>= 7;
|
|
22
|
+
if (n > 0)
|
|
23
|
+
digit |= 0x80;
|
|
24
|
+
bytes.push(digit);
|
|
25
|
+
} while (n > 0);
|
|
26
|
+
return bytes;
|
|
27
|
+
}
|
|
28
|
+
function encodeMqttString(str) {
|
|
29
|
+
const data = encoder.encode(str);
|
|
30
|
+
const out = new Uint8Array(2 + data.length);
|
|
31
|
+
out[0] = (data.length >>> 8) & 0xff;
|
|
32
|
+
out[1] = data.length & 0xff;
|
|
33
|
+
out.set(data, 2);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
function concatBytes(...parts) {
|
|
37
|
+
let total = 0;
|
|
38
|
+
for (const p of parts)
|
|
39
|
+
total += p.length;
|
|
40
|
+
const out = new Uint8Array(total);
|
|
41
|
+
let offset = 0;
|
|
42
|
+
for (const p of parts) {
|
|
43
|
+
out.set(p, offset);
|
|
44
|
+
offset += p.length;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function mqttPacket(header, body) {
|
|
49
|
+
const rem = encodeRemainingLength(body.length);
|
|
50
|
+
const out = new Uint8Array(1 + rem.length + body.length);
|
|
51
|
+
out[0] = header;
|
|
52
|
+
out.set(rem, 1);
|
|
53
|
+
out.set(body, 1 + rem.length);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
function buildConnect(clientId) {
|
|
57
|
+
const proto = encodeMqttString('MQTT');
|
|
58
|
+
const flags = new Uint8Array([
|
|
59
|
+
4, // Protocol level 4 (MQTT 3.1.1)
|
|
60
|
+
0x02, // Clean Session
|
|
61
|
+
0,
|
|
62
|
+
30 // Keep Alive = 30s
|
|
63
|
+
]);
|
|
64
|
+
return mqttPacket(0x10, concatBytes(proto, flags, encodeMqttString(clientId)));
|
|
65
|
+
}
|
|
66
|
+
function buildSubscribe(packetId, topics) {
|
|
67
|
+
const parts = [new Uint8Array([(packetId >>> 8) & 0xff, packetId & 0xff])];
|
|
68
|
+
const qos = new Uint8Array([0]);
|
|
69
|
+
for (const topic of topics) {
|
|
70
|
+
parts.push(encodeMqttString(topic), qos);
|
|
71
|
+
}
|
|
72
|
+
return mqttPacket(0x82, concatBytes(...parts));
|
|
73
|
+
}
|
|
74
|
+
function buildPublish(topic, payload) {
|
|
75
|
+
return mqttPacket(0x30, concatBytes(encodeMqttString(topic), payload));
|
|
76
|
+
}
|
|
77
|
+
const pingReq = new Uint8Array([0xc0, 0x00]);
|
|
78
|
+
const disconnectPkt = new Uint8Array([0xe0, 0x00]);
|
|
79
|
+
function parseMqttFrames(buffer, handlers) {
|
|
80
|
+
let offset = 0;
|
|
81
|
+
while (offset + 2 <= buffer.length) {
|
|
82
|
+
const header = buffer[offset];
|
|
83
|
+
const type = header >>> 4;
|
|
84
|
+
let multiplier = 1;
|
|
85
|
+
let remaining = 0;
|
|
86
|
+
let pos = offset + 1;
|
|
87
|
+
let done = false;
|
|
88
|
+
while (pos < buffer.length) {
|
|
89
|
+
const encoded = buffer[pos++];
|
|
90
|
+
remaining += (encoded & 0x7f) * multiplier;
|
|
91
|
+
if ((encoded & 0x80) === 0) {
|
|
92
|
+
done = true;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
multiplier *= 128;
|
|
96
|
+
if (multiplier > 128 * 128 * 128) {
|
|
97
|
+
handlers.onError();
|
|
98
|
+
return new Uint8Array(0);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!done)
|
|
102
|
+
break;
|
|
103
|
+
if (remaining > maxMqttBuffer) {
|
|
104
|
+
handlers.onError();
|
|
105
|
+
return new Uint8Array(0);
|
|
106
|
+
}
|
|
107
|
+
if (pos + remaining > buffer.length)
|
|
108
|
+
break;
|
|
109
|
+
const end = pos + remaining;
|
|
110
|
+
if (type === 2 && remaining >= 2) {
|
|
111
|
+
handlers.onConnAck(buffer[pos + 1]);
|
|
112
|
+
}
|
|
113
|
+
else if (type === 9 && remaining >= 3) {
|
|
114
|
+
handlers.onSubAck(buffer.subarray(pos + 2, end));
|
|
115
|
+
}
|
|
116
|
+
else if (type === 13) {
|
|
117
|
+
handlers.onPingResp();
|
|
118
|
+
}
|
|
119
|
+
else if (type === 3 && remaining >= 2) {
|
|
120
|
+
const topicLen = (buffer[pos] << 8) | buffer[pos + 1];
|
|
121
|
+
let bodyStart = pos + 2 + topicLen;
|
|
122
|
+
const qos = (header >>> 1) & 0x03;
|
|
123
|
+
if (qos > 0)
|
|
124
|
+
bodyStart += 2;
|
|
125
|
+
if (bodyStart <= end) {
|
|
126
|
+
const topic = decoder.decode(buffer.subarray(pos + 2, pos + 2 + topicLen));
|
|
127
|
+
handlers.onPublish({ topic, payload: buffer.subarray(bodyStart, end) });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
offset = end;
|
|
131
|
+
}
|
|
132
|
+
return offset === 0
|
|
133
|
+
? buffer
|
|
134
|
+
: offset === buffer.length
|
|
135
|
+
? new Uint8Array(0)
|
|
136
|
+
: buffer.subarray(offset);
|
|
137
|
+
}
|
|
138
|
+
async function deriveKey(password, salt) {
|
|
139
|
+
const subtle = globalThis.crypto?.subtle;
|
|
140
|
+
if (!subtle)
|
|
141
|
+
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
142
|
+
const base = await subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, [
|
|
143
|
+
'deriveKey'
|
|
144
|
+
]);
|
|
145
|
+
return subtle.deriveKey({ name: 'PBKDF2', salt: encoder.encode(salt), iterations: 100_000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
146
|
+
}
|
|
147
|
+
async function sealPayload(key, plain, aad) {
|
|
148
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
149
|
+
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, plain.buffer instanceof ArrayBuffer
|
|
150
|
+
? new Uint8Array(plain.buffer, plain.byteOffset, plain.byteLength)
|
|
151
|
+
: Uint8Array.from(plain)));
|
|
152
|
+
return concatBytes(iv, cipher);
|
|
153
|
+
}
|
|
154
|
+
async function openPayload(key, boxed, aad) {
|
|
155
|
+
if (boxed.length <= 12)
|
|
156
|
+
return null;
|
|
157
|
+
try {
|
|
158
|
+
const iv = Uint8Array.from(boxed.subarray(0, 12));
|
|
159
|
+
const cipher = Uint8Array.from(boxed.subarray(12));
|
|
160
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, cipher));
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Zero-backend signaling over public (or custom) MQTT-over-WebSocket brokers.
|
|
168
|
+
* Connects to multiple brokers in parallel for redundancy, splits presence and unicast topics,
|
|
169
|
+
* deduplicates multi-broker traffic, works even from `file://`, and optionally encrypts
|
|
170
|
+
* handshakes with AES-256-GCM (+ topic AAD and timestamp anti-replay) when `password` is provided.
|
|
171
|
+
*/
|
|
172
|
+
export function mqttSignaling(options = {}) {
|
|
173
|
+
const urls = [...(options.urls ?? defaultMqttRelays)];
|
|
174
|
+
if (urls.length === 0)
|
|
175
|
+
throw new RangeError('At least one MQTT relay URL is required');
|
|
176
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultMqttHandshakeTimeoutMs;
|
|
177
|
+
if (!Number.isSafeInteger(handshakeTimeoutMs) ||
|
|
178
|
+
handshakeTimeoutMs <= 0 ||
|
|
179
|
+
handshakeTimeoutMs > 2_147_483_647)
|
|
180
|
+
throw new RangeError('Invalid MQTT handshake timeout');
|
|
181
|
+
if (options.password !== undefined &&
|
|
182
|
+
(typeof options.password !== 'string' || options.password.length === 0))
|
|
183
|
+
throw new TypeError('Invalid password');
|
|
184
|
+
return (discovery) => {
|
|
185
|
+
const appId = options.appId ?? discovery.appId;
|
|
186
|
+
const password = options.password ?? discovery.password;
|
|
187
|
+
if (password !== undefined) {
|
|
188
|
+
if (typeof password !== 'string' || password.length === 0)
|
|
189
|
+
throw new TypeError('Invalid password');
|
|
190
|
+
if (!globalThis.crypto?.subtle) {
|
|
191
|
+
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const roomTopic = 'meshpost/1/' + namespaceHash(appId + ':' + discovery.room);
|
|
195
|
+
const inboxTopic = roomTopic + '/' + discovery.self;
|
|
196
|
+
const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
|
|
197
|
+
const seen = new Map();
|
|
198
|
+
const seenMids = new Map();
|
|
199
|
+
const readySockets = new Set();
|
|
200
|
+
const allSockets = new Set();
|
|
201
|
+
const reconnectTimers = new Set();
|
|
202
|
+
let closed = false;
|
|
203
|
+
let reportedOnline = false;
|
|
204
|
+
let reportedOffline = false;
|
|
205
|
+
let initialPending = urls.length;
|
|
206
|
+
let nextPacketId = 1;
|
|
207
|
+
let msgSeq = 0;
|
|
208
|
+
let resolvedKey;
|
|
209
|
+
const keyPromise = password !== undefined
|
|
210
|
+
? deriveKey(password, roomTopic).then((k) => {
|
|
211
|
+
resolvedKey = k;
|
|
212
|
+
return k;
|
|
213
|
+
})
|
|
214
|
+
: undefined;
|
|
215
|
+
const roster = () => discovery.roster([...seen.keys()]);
|
|
216
|
+
const touch = (id) => {
|
|
217
|
+
const known = seen.has(id);
|
|
218
|
+
if (!known && seen.size >= maxSeenPeers) {
|
|
219
|
+
const oldest = seen.keys().next().value;
|
|
220
|
+
if (oldest !== undefined)
|
|
221
|
+
seen.delete(oldest);
|
|
222
|
+
}
|
|
223
|
+
seen.delete(id);
|
|
224
|
+
seen.set(id, Date.now());
|
|
225
|
+
if (!known)
|
|
226
|
+
roster();
|
|
227
|
+
return known;
|
|
228
|
+
};
|
|
229
|
+
const recordMid = (mid) => {
|
|
230
|
+
const now = Date.now();
|
|
231
|
+
const prev = seenMids.get(mid);
|
|
232
|
+
if (prev !== undefined && now - prev < midTtlMs)
|
|
233
|
+
return false;
|
|
234
|
+
if (seenMids.size >= maxSeenMids) {
|
|
235
|
+
for (const [key, at] of seenMids) {
|
|
236
|
+
if (now - at >= midTtlMs || seenMids.size >= maxSeenMids) {
|
|
237
|
+
seenMids.delete(key);
|
|
238
|
+
if (seenMids.size < maxSeenMids)
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
seenMids.delete(mid);
|
|
244
|
+
seenMids.set(mid, now);
|
|
245
|
+
return true;
|
|
246
|
+
};
|
|
247
|
+
const updateStatus = () => {
|
|
248
|
+
if (closed)
|
|
249
|
+
return;
|
|
250
|
+
const online = readySockets.size > 0;
|
|
251
|
+
if (online && !reportedOnline) {
|
|
252
|
+
reportedOnline = true;
|
|
253
|
+
reportedOffline = false;
|
|
254
|
+
discovery.status('online');
|
|
255
|
+
}
|
|
256
|
+
else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
|
|
257
|
+
reportedOnline = false;
|
|
258
|
+
reportedOffline = true;
|
|
259
|
+
discovery.status('offline', 'All MQTT relays disconnected');
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
const publishRaw = async (body, targetSockets, fixedMid) => {
|
|
263
|
+
if (closed)
|
|
264
|
+
return;
|
|
265
|
+
const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
|
|
266
|
+
const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
|
|
267
|
+
const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
|
|
268
|
+
let payload;
|
|
269
|
+
try {
|
|
270
|
+
const key = resolvedKey ?? (keyPromise ? await keyPromise : undefined);
|
|
271
|
+
payload = key ? await sealPayload(key, plain, targetTopic) : plain;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (closed)
|
|
277
|
+
return;
|
|
278
|
+
const frame = buildPublish(targetTopic, payload);
|
|
279
|
+
for (const ws of targetSockets ?? readySockets) {
|
|
280
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
281
|
+
try {
|
|
282
|
+
ws.send(frame);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// Socket closing; reconnect loop handles recovery.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
const handlePayload = async (msgTopic, raw) => {
|
|
291
|
+
if (closed)
|
|
292
|
+
return;
|
|
293
|
+
let key;
|
|
294
|
+
let plain;
|
|
295
|
+
try {
|
|
296
|
+
key = resolvedKey ?? (keyPromise ? await keyPromise : undefined);
|
|
297
|
+
plain = key ? await openPayload(key, raw, msgTopic) : raw;
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (!plain || closed)
|
|
303
|
+
return;
|
|
304
|
+
let data = null;
|
|
305
|
+
try {
|
|
306
|
+
data = JSON.parse(decoder.decode(plain));
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (!data || !isUuid(data.from) || data.from === discovery.self)
|
|
312
|
+
return;
|
|
313
|
+
if (data.to !== undefined && data.to !== discovery.self)
|
|
314
|
+
return;
|
|
315
|
+
if (key) {
|
|
316
|
+
if (typeof data.ts !== 'number' || Math.abs(Date.now() - data.ts) > replayWindowMs)
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (typeof data.mid === 'string' && !recordMid(data.from + ':' + data.mid))
|
|
320
|
+
return;
|
|
321
|
+
switch (data.type) {
|
|
322
|
+
case 'hello':
|
|
323
|
+
touch(data.from);
|
|
324
|
+
void publishRaw({ type: 'present', to: data.from });
|
|
325
|
+
break;
|
|
326
|
+
case 'heartbeat':
|
|
327
|
+
if (!touch(data.from))
|
|
328
|
+
void publishRaw({ type: 'present', to: data.from });
|
|
329
|
+
break;
|
|
330
|
+
case 'present':
|
|
331
|
+
touch(data.from);
|
|
332
|
+
break;
|
|
333
|
+
case 'bye':
|
|
334
|
+
if (seen.delete(data.from))
|
|
335
|
+
roster();
|
|
336
|
+
break;
|
|
337
|
+
case 'signal':
|
|
338
|
+
if (isSignal(data.signal)) {
|
|
339
|
+
touch(data.from);
|
|
340
|
+
discovery.receive(data.from, data.signal);
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
const connectBroker = (url, attempt = 0, isInitial = true) => {
|
|
346
|
+
if (closed)
|
|
347
|
+
return;
|
|
348
|
+
let settledInitial = !isInitial;
|
|
349
|
+
const settleInitial = () => {
|
|
350
|
+
if (!settledInitial) {
|
|
351
|
+
settledInitial = true;
|
|
352
|
+
initialPending = Math.max(0, initialPending - 1);
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
let ws;
|
|
356
|
+
try {
|
|
357
|
+
ws = new WebSocket(url, ['mqtt']);
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
settleInitial();
|
|
361
|
+
updateStatus();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
ws.binaryType = 'arraybuffer';
|
|
365
|
+
allSockets.add(ws);
|
|
366
|
+
let buffer = new Uint8Array(0);
|
|
367
|
+
let pingTimer;
|
|
368
|
+
let handshakeTimer;
|
|
369
|
+
let awaitingPong = false;
|
|
370
|
+
let subscribed = false;
|
|
371
|
+
const abortSocket = () => {
|
|
372
|
+
try {
|
|
373
|
+
ws.close();
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
// Ignore close errors.
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
const sendFrame = (frame) => {
|
|
380
|
+
try {
|
|
381
|
+
ws.send(frame);
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
abortSocket();
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
handshakeTimer = setTimeout(() => {
|
|
388
|
+
if (!subscribed)
|
|
389
|
+
abortSocket();
|
|
390
|
+
}, handshakeTimeoutMs);
|
|
391
|
+
const cleanup = () => {
|
|
392
|
+
if (handshakeTimer)
|
|
393
|
+
clearTimeout(handshakeTimer);
|
|
394
|
+
if (pingTimer)
|
|
395
|
+
clearInterval(pingTimer);
|
|
396
|
+
allSockets.delete(ws);
|
|
397
|
+
const wasReady = readySockets.delete(ws);
|
|
398
|
+
settleInitial();
|
|
399
|
+
if (wasReady || initialPending === 0)
|
|
400
|
+
updateStatus();
|
|
401
|
+
if (!closed) {
|
|
402
|
+
const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
|
|
403
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
404
|
+
const timer = setTimeout(() => {
|
|
405
|
+
reconnectTimers.delete(timer);
|
|
406
|
+
connectBroker(url, attempt + 1, false);
|
|
407
|
+
}, delay);
|
|
408
|
+
reconnectTimers.add(timer);
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
ws.onopen = () => {
|
|
412
|
+
if (closed) {
|
|
413
|
+
abortSocket();
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
|
|
417
|
+
sendFrame(buildConnect(clientId));
|
|
418
|
+
};
|
|
419
|
+
ws.onmessage = ({ data }) => {
|
|
420
|
+
if (closed || !(data instanceof ArrayBuffer))
|
|
421
|
+
return;
|
|
422
|
+
if (buffer.length + data.byteLength > maxMqttBuffer) {
|
|
423
|
+
abortSocket();
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
buffer = concatBytes(buffer, new Uint8Array(data));
|
|
427
|
+
buffer = parseMqttFrames(buffer, {
|
|
428
|
+
onConnAck(code) {
|
|
429
|
+
if (closed)
|
|
430
|
+
return;
|
|
431
|
+
if (code !== 0) {
|
|
432
|
+
abortSocket();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const id = nextPacketId;
|
|
436
|
+
nextPacketId = (nextPacketId % 65535) + 1;
|
|
437
|
+
sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
|
|
438
|
+
},
|
|
439
|
+
onSubAck(codes) {
|
|
440
|
+
if (closed || subscribed)
|
|
441
|
+
return;
|
|
442
|
+
if (codes.length < 2 || codes.some((c) => c === 0x80)) {
|
|
443
|
+
abortSocket();
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
subscribed = true;
|
|
447
|
+
if (handshakeTimer)
|
|
448
|
+
clearTimeout(handshakeTimer);
|
|
449
|
+
handshakeTimer = undefined;
|
|
450
|
+
attempt = 0;
|
|
451
|
+
settleInitial();
|
|
452
|
+
readySockets.add(ws);
|
|
453
|
+
updateStatus();
|
|
454
|
+
void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
455
|
+
pingTimer = setInterval(() => {
|
|
456
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
457
|
+
return;
|
|
458
|
+
if (awaitingPong) {
|
|
459
|
+
abortSocket();
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
awaitingPong = true;
|
|
463
|
+
sendFrame(pingReq);
|
|
464
|
+
}, 20_000);
|
|
465
|
+
},
|
|
466
|
+
onPingResp() {
|
|
467
|
+
awaitingPong = false;
|
|
468
|
+
},
|
|
469
|
+
onPublish(msg) {
|
|
470
|
+
if (!subscribed)
|
|
471
|
+
return;
|
|
472
|
+
if (msg.topic === roomTopic || msg.topic === inboxTopic) {
|
|
473
|
+
void handlePayload(msg.topic, msg.payload);
|
|
474
|
+
}
|
|
475
|
+
},
|
|
476
|
+
onError() {
|
|
477
|
+
abortSocket();
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
};
|
|
481
|
+
ws.onerror = abortSocket;
|
|
482
|
+
ws.onclose = cleanup;
|
|
483
|
+
};
|
|
484
|
+
const leaseTimer = setInterval(() => {
|
|
485
|
+
if (closed)
|
|
486
|
+
return;
|
|
487
|
+
const now = Date.now();
|
|
488
|
+
let changed = false;
|
|
489
|
+
for (const [id, last] of seen) {
|
|
490
|
+
if (now - last > 30_000) {
|
|
491
|
+
seen.delete(id);
|
|
492
|
+
changed = true;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (changed)
|
|
496
|
+
roster();
|
|
497
|
+
for (const [mid, at] of seenMids) {
|
|
498
|
+
if (now - at >= midTtlMs)
|
|
499
|
+
seenMids.delete(mid);
|
|
500
|
+
}
|
|
501
|
+
if (readySockets.size > 0)
|
|
502
|
+
void publishRaw({ type: 'heartbeat' });
|
|
503
|
+
}, 5_000);
|
|
504
|
+
queueMicrotask(() => {
|
|
505
|
+
if (closed)
|
|
506
|
+
return;
|
|
507
|
+
for (const url of urls)
|
|
508
|
+
connectBroker(url);
|
|
509
|
+
});
|
|
510
|
+
return {
|
|
511
|
+
send(to, signal) {
|
|
512
|
+
if (closed || readySockets.size === 0)
|
|
513
|
+
return false;
|
|
514
|
+
void publishRaw({ type: 'signal', to, signal });
|
|
515
|
+
return true;
|
|
516
|
+
},
|
|
517
|
+
close() {
|
|
518
|
+
if (closed)
|
|
519
|
+
return;
|
|
520
|
+
closed = true;
|
|
521
|
+
clearInterval(leaseTimer);
|
|
522
|
+
for (const timer of reconnectTimers)
|
|
523
|
+
clearTimeout(timer);
|
|
524
|
+
reconnectTimers.clear();
|
|
525
|
+
const socketsToClose = [...allSockets];
|
|
526
|
+
const readyToNotify = [...readySockets];
|
|
527
|
+
allSockets.clear();
|
|
528
|
+
readySockets.clear();
|
|
529
|
+
const shutdownSocket = (ws, byeFrame) => {
|
|
530
|
+
try {
|
|
531
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
532
|
+
if (byeFrame)
|
|
533
|
+
ws.send(byeFrame);
|
|
534
|
+
ws.send(disconnectPkt);
|
|
535
|
+
}
|
|
536
|
+
ws.close();
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
// Ignore shutdown errors.
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
const byePlain = encoder.encode(JSON.stringify({
|
|
543
|
+
type: 'bye',
|
|
544
|
+
from: discovery.self,
|
|
545
|
+
mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
|
|
546
|
+
ts: Date.now()
|
|
547
|
+
}));
|
|
548
|
+
if (!keyPromise) {
|
|
549
|
+
const byeFrame = buildPublish(roomTopic, byePlain);
|
|
550
|
+
for (const ws of socketsToClose) {
|
|
551
|
+
shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
else if (resolvedKey && readyToNotify.length > 0) {
|
|
555
|
+
const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
|
|
556
|
+
for (const ws of nonReady)
|
|
557
|
+
shutdownSocket(ws);
|
|
558
|
+
const fallbackTimer = setTimeout(() => {
|
|
559
|
+
for (const ws of readyToNotify)
|
|
560
|
+
shutdownSocket(ws);
|
|
561
|
+
}, 250);
|
|
562
|
+
void sealPayload(resolvedKey, byePlain, roomTopic)
|
|
563
|
+
.then((boxed) => {
|
|
564
|
+
clearTimeout(fallbackTimer);
|
|
565
|
+
const byeFrame = buildPublish(roomTopic, boxed);
|
|
566
|
+
for (const ws of readyToNotify)
|
|
567
|
+
shutdownSocket(ws, byeFrame);
|
|
568
|
+
})
|
|
569
|
+
.catch(() => {
|
|
570
|
+
clearTimeout(fallbackTimer);
|
|
571
|
+
for (const ws of readyToNotify)
|
|
572
|
+
shutdownSocket(ws);
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
for (const ws of socketsToClose)
|
|
577
|
+
shutdownSocket(ws);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
};
|
|
582
|
+
}
|
package/dist/room.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type Signaling, type SignalingState } from './signaling.js';
|
|
2
|
+
/** Built-in Cloudflare and Google public STUN servers used by default. */
|
|
3
|
+
export declare const defaultIceServers: readonly RTCIceServer[];
|
|
4
|
+
/** Delivery guarantee for a packet: fast unordered (`'unreliable'`) or ordered reliable (`'reliable'`). */
|
|
5
|
+
export type Delivery = 'unreliable' | 'reliable';
|
|
6
|
+
export interface RoomOptions {
|
|
7
|
+
/** Signaling adapter used to discover peers and exchange WebRTC setup messages. */
|
|
8
|
+
signaling: Signaling;
|
|
9
|
+
/** Application namespace isolating rooms across different apps. @default 'meshpost' */
|
|
10
|
+
appId?: string;
|
|
11
|
+
/** Optional non-empty shared password isolating (and on MQTT, encrypting) room signaling. */
|
|
12
|
+
password?: string;
|
|
13
|
+
/** Custom WebRTC configuration. Keeps `defaultIceServers` unless `iceServers` is specified. */
|
|
14
|
+
rtcConfig?: RTCConfiguration;
|
|
15
|
+
/** Additional TURN (or STUN) servers appended to `rtcConfig.iceServers` or `defaultIceServers`. */
|
|
16
|
+
turnConfig?: readonly RTCIceServer[];
|
|
17
|
+
/** Max time in milliseconds per connection attempt before retrying. @default 35000 */
|
|
18
|
+
handshakeTimeoutMs?: number;
|
|
19
|
+
/** Soft cap in milliseconds for ICE candidate gathering before sending SDP. @default 2500 */
|
|
20
|
+
iceGatheringTimeoutMs?: number;
|
|
21
|
+
/** Maximum simultaneous peer connections in this room. @default 32 */
|
|
22
|
+
maxPeers?: number;
|
|
23
|
+
}
|
|
24
|
+
export interface SendOptions {
|
|
25
|
+
/** Optional target peer ID. Omit to broadcast to all connected peers. */
|
|
26
|
+
to?: string;
|
|
27
|
+
/** Delivery mode for this packet. @default 'unreliable' */
|
|
28
|
+
delivery?: Delivery;
|
|
29
|
+
}
|
|
30
|
+
/** Immediate per-recipient outcome returned by `room.send()` and `channel.send()`. */
|
|
31
|
+
export type SendResult = 'accepted' | 'unavailable' | 'busy' | 'too-large';
|
|
32
|
+
/** Network path used by an active peer connection. */
|
|
33
|
+
export type PeerRoute = 'direct' | 'relay' | 'unknown';
|
|
34
|
+
/** Read-only connection statistics snapshot returned by `room.getStats()`. */
|
|
35
|
+
export interface PeerStats {
|
|
36
|
+
/** Current round-trip ping in whole milliseconds, or `null` if not measured yet. */
|
|
37
|
+
readonly rttMs: number | null;
|
|
38
|
+
/** `'direct'` for peer-to-peer, `'relay'` through a TURN server, or `'unknown'`. */
|
|
39
|
+
readonly route: PeerRoute;
|
|
40
|
+
/** Total app payload bytes sent on this connection across both delivery modes. */
|
|
41
|
+
readonly bytesSent: number;
|
|
42
|
+
/** Total app payload bytes received on this connection across both delivery modes. */
|
|
43
|
+
readonly bytesReceived: number;
|
|
44
|
+
/** Bytes currently queued in the unreliable send buffer. */
|
|
45
|
+
readonly bufferedUnreliable: number;
|
|
46
|
+
/** Bytes currently queued in the reliable send buffer. */
|
|
47
|
+
readonly bufferedReliable: number;
|
|
48
|
+
}
|
|
49
|
+
export interface Room {
|
|
50
|
+
/** Local peer ID (random UUID v4). A page reload creates a new peer ID. */
|
|
51
|
+
readonly id: string;
|
|
52
|
+
/** Snapshot array of currently connected remote peer IDs. */
|
|
53
|
+
readonly peers: readonly string[];
|
|
54
|
+
/** Current state of the signaling adapter. */
|
|
55
|
+
readonly signalingState: SignalingState;
|
|
56
|
+
/** Send a binary packet (max 16 KiB) synchronously. Returns a per-recipient result map. */
|
|
57
|
+
send(bytes: Uint8Array, options?: SendOptions): ReadonlyMap<string, SendResult>;
|
|
58
|
+
/** Read current ping, route, byte counts, and buffer sizes for a connected peer, or `null` if unavailable. */
|
|
59
|
+
getStats(peerId: string): Promise<PeerStats | null>;
|
|
60
|
+
/** Subscribe to incoming binary packets. Returns an unsubscribe function. */
|
|
61
|
+
onPacket(fn: (from: string, bytes: Uint8Array, delivery: Delivery) => void): () => void;
|
|
62
|
+
/** Subscribe to send-buffer drain events (fires after `'busy'` clears). Returns an unsubscribe function. */
|
|
63
|
+
onDrain(fn: (id: string, delivery: Delivery) => void): () => void;
|
|
64
|
+
/** Subscribe to peer connection events. Returns an unsubscribe function. */
|
|
65
|
+
onPeerJoin(fn: (id: string) => void): () => void;
|
|
66
|
+
/** Subscribe to peer disconnection events. Returns an unsubscribe function. */
|
|
67
|
+
onPeerLeave(fn: (id: string) => void): () => void;
|
|
68
|
+
/** Subscribe to future signaling state changes. Returns an unsubscribe function. */
|
|
69
|
+
onSignalingChange(fn: (state: SignalingState, reason?: string) => void): () => void;
|
|
70
|
+
/** Leave the room, notify peers, and close all connections. Safe to call more than once. */
|
|
71
|
+
leave(): void;
|
|
72
|
+
}
|
|
73
|
+
/** Start discovery immediately. Membership becomes observable as peer links open. */
|
|
74
|
+
export declare function joinRoom(name: string, options: RoomOptions): Room;
|