@dimchansky/meshpost 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +355 -2
- package/dist/blob.d.ts +45 -0
- package/dist/blob.js +364 -0
- package/dist/channel.d.ts +26 -0
- package/dist/channel.js +51 -0
- package/dist/combine.d.ts +7 -0
- package/dist/combine.js +249 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +9 -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 +610 -0
- package/dist/room.d.ts +99 -0
- package/dist/room.js +1130 -0
- package/dist/signaling.d.ts +70 -0
- package/dist/signaling.js +118 -0
- package/dist/tabs.d.ts +3 -0
- package/dist/tabs.js +94 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +237 -0
- package/package.json +65 -4
package/dist/mqtt.js
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
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 maxMidLength = 64;
|
|
14
|
+
const replayWindowMs = 60_000;
|
|
15
|
+
const midTtlMs = replayWindowMs * 2;
|
|
16
|
+
const defaultMqttHandshakeTimeoutMs = 10_000;
|
|
17
|
+
const decryptErrorCooldownMs = 15_000;
|
|
18
|
+
function encodeRemainingLength(length) {
|
|
19
|
+
const bytes = [];
|
|
20
|
+
let n = length;
|
|
21
|
+
do {
|
|
22
|
+
let digit = n & 0x7f;
|
|
23
|
+
n >>>= 7;
|
|
24
|
+
if (n > 0)
|
|
25
|
+
digit |= 0x80;
|
|
26
|
+
bytes.push(digit);
|
|
27
|
+
} while (n > 0);
|
|
28
|
+
return bytes;
|
|
29
|
+
}
|
|
30
|
+
function encodeMqttString(str) {
|
|
31
|
+
const data = encoder.encode(str);
|
|
32
|
+
const out = new Uint8Array(2 + data.length);
|
|
33
|
+
out[0] = (data.length >>> 8) & 0xff;
|
|
34
|
+
out[1] = data.length & 0xff;
|
|
35
|
+
out.set(data, 2);
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
function concatBytes(...parts) {
|
|
39
|
+
let total = 0;
|
|
40
|
+
for (const p of parts)
|
|
41
|
+
total += p.length;
|
|
42
|
+
const out = new Uint8Array(total);
|
|
43
|
+
let offset = 0;
|
|
44
|
+
for (const p of parts) {
|
|
45
|
+
out.set(p, offset);
|
|
46
|
+
offset += p.length;
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function mqttPacket(header, body) {
|
|
51
|
+
const rem = encodeRemainingLength(body.length);
|
|
52
|
+
const out = new Uint8Array(1 + rem.length + body.length);
|
|
53
|
+
out[0] = header;
|
|
54
|
+
out.set(rem, 1);
|
|
55
|
+
out.set(body, 1 + rem.length);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
function buildConnect(clientId) {
|
|
59
|
+
const proto = encodeMqttString('MQTT');
|
|
60
|
+
const flags = new Uint8Array([
|
|
61
|
+
4, // Protocol level 4 (MQTT 3.1.1)
|
|
62
|
+
0x02, // Clean Session
|
|
63
|
+
0,
|
|
64
|
+
30 // Keep Alive = 30s
|
|
65
|
+
]);
|
|
66
|
+
return mqttPacket(0x10, concatBytes(proto, flags, encodeMqttString(clientId)));
|
|
67
|
+
}
|
|
68
|
+
function buildSubscribe(packetId, topics) {
|
|
69
|
+
const parts = [new Uint8Array([(packetId >>> 8) & 0xff, packetId & 0xff])];
|
|
70
|
+
const qos = new Uint8Array([0]);
|
|
71
|
+
for (const topic of topics) {
|
|
72
|
+
parts.push(encodeMqttString(topic), qos);
|
|
73
|
+
}
|
|
74
|
+
return mqttPacket(0x82, concatBytes(...parts));
|
|
75
|
+
}
|
|
76
|
+
function buildPublish(topic, payload) {
|
|
77
|
+
return mqttPacket(0x30, concatBytes(encodeMqttString(topic), payload));
|
|
78
|
+
}
|
|
79
|
+
const pingReq = new Uint8Array([0xc0, 0x00]);
|
|
80
|
+
const disconnectPkt = new Uint8Array([0xe0, 0x00]);
|
|
81
|
+
function parseMqttFrames(buffer, handlers) {
|
|
82
|
+
let offset = 0;
|
|
83
|
+
while (offset + 2 <= buffer.length) {
|
|
84
|
+
const header = buffer[offset];
|
|
85
|
+
const type = header >>> 4;
|
|
86
|
+
let multiplier = 1;
|
|
87
|
+
let remaining = 0;
|
|
88
|
+
let pos = offset + 1;
|
|
89
|
+
let done = false;
|
|
90
|
+
while (pos < buffer.length) {
|
|
91
|
+
const encoded = buffer[pos++];
|
|
92
|
+
remaining += (encoded & 0x7f) * multiplier;
|
|
93
|
+
if ((encoded & 0x80) === 0) {
|
|
94
|
+
done = true;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
multiplier *= 128;
|
|
98
|
+
if (multiplier > 128 * 128 * 128) {
|
|
99
|
+
handlers.onError();
|
|
100
|
+
return new Uint8Array(0);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!done)
|
|
104
|
+
break;
|
|
105
|
+
if (remaining > maxMqttBuffer) {
|
|
106
|
+
handlers.onError();
|
|
107
|
+
return new Uint8Array(0);
|
|
108
|
+
}
|
|
109
|
+
if (pos + remaining > buffer.length)
|
|
110
|
+
break;
|
|
111
|
+
const end = pos + remaining;
|
|
112
|
+
if (type === 2 && remaining >= 2) {
|
|
113
|
+
handlers.onConnAck(buffer[pos + 1]);
|
|
114
|
+
}
|
|
115
|
+
else if (type === 9 && remaining >= 3) {
|
|
116
|
+
handlers.onSubAck(buffer.subarray(pos + 2, end));
|
|
117
|
+
}
|
|
118
|
+
else if (type === 13) {
|
|
119
|
+
handlers.onPingResp();
|
|
120
|
+
}
|
|
121
|
+
else if (type === 3 && remaining >= 2) {
|
|
122
|
+
const topicLen = (buffer[pos] << 8) | buffer[pos + 1];
|
|
123
|
+
let bodyStart = pos + 2 + topicLen;
|
|
124
|
+
const qos = (header >>> 1) & 0x03;
|
|
125
|
+
if (qos > 0)
|
|
126
|
+
bodyStart += 2;
|
|
127
|
+
if (bodyStart <= end) {
|
|
128
|
+
const topic = decoder.decode(buffer.subarray(pos + 2, pos + 2 + topicLen));
|
|
129
|
+
handlers.onPublish({ topic, payload: buffer.subarray(bodyStart, end) });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
offset = end;
|
|
133
|
+
}
|
|
134
|
+
return offset === 0
|
|
135
|
+
? buffer
|
|
136
|
+
: offset === buffer.length
|
|
137
|
+
? new Uint8Array(0)
|
|
138
|
+
: buffer.subarray(offset);
|
|
139
|
+
}
|
|
140
|
+
async function deriveKey(password, salt) {
|
|
141
|
+
const subtle = globalThis.crypto?.subtle;
|
|
142
|
+
if (!subtle)
|
|
143
|
+
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
144
|
+
const base = await subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, [
|
|
145
|
+
'deriveKey'
|
|
146
|
+
]);
|
|
147
|
+
return subtle.deriveKey({ name: 'PBKDF2', salt: encoder.encode(salt), iterations: 100_000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
148
|
+
}
|
|
149
|
+
async function sealPayload(key, plain, aad) {
|
|
150
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
151
|
+
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, plain.buffer instanceof ArrayBuffer
|
|
152
|
+
? new Uint8Array(plain.buffer, plain.byteOffset, plain.byteLength)
|
|
153
|
+
: Uint8Array.from(plain)));
|
|
154
|
+
return concatBytes(iv, cipher);
|
|
155
|
+
}
|
|
156
|
+
async function openPayload(key, boxed, aad) {
|
|
157
|
+
if (boxed.length < 28)
|
|
158
|
+
return null;
|
|
159
|
+
try {
|
|
160
|
+
const iv = Uint8Array.from(boxed.subarray(0, 12));
|
|
161
|
+
const cipher = Uint8Array.from(boxed.subarray(12));
|
|
162
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, cipher));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Zero-backend signaling over public (or custom) MQTT-over-WebSocket brokers.
|
|
170
|
+
* Connects to multiple brokers in parallel for redundancy, splits presence and unicast topics,
|
|
171
|
+
* deduplicates multi-broker traffic, works even from `file://`, and optionally encrypts
|
|
172
|
+
* handshakes with AES-256-GCM (+ topic AAD and timestamp anti-replay) when `password` is provided.
|
|
173
|
+
*/
|
|
174
|
+
export function mqttSignaling(options = {}) {
|
|
175
|
+
const urls = [...(options.urls ?? defaultMqttRelays)];
|
|
176
|
+
if (urls.length === 0)
|
|
177
|
+
throw new RangeError('At least one MQTT relay URL is required');
|
|
178
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultMqttHandshakeTimeoutMs;
|
|
179
|
+
if (!Number.isSafeInteger(handshakeTimeoutMs) ||
|
|
180
|
+
handshakeTimeoutMs <= 0 ||
|
|
181
|
+
handshakeTimeoutMs > 2_147_483_647)
|
|
182
|
+
throw new RangeError('Invalid MQTT handshake timeout');
|
|
183
|
+
if (options.password !== undefined &&
|
|
184
|
+
(typeof options.password !== 'string' || options.password.length === 0))
|
|
185
|
+
throw new TypeError('Invalid password');
|
|
186
|
+
return (discovery) => {
|
|
187
|
+
const appId = options.appId ?? discovery.appId;
|
|
188
|
+
const password = options.password ?? discovery.password;
|
|
189
|
+
if (password !== undefined) {
|
|
190
|
+
if (typeof password !== 'string' || password.length === 0)
|
|
191
|
+
throw new TypeError('Invalid password');
|
|
192
|
+
if (!globalThis.crypto?.subtle) {
|
|
193
|
+
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const roomTopic = 'meshpost/1/' + namespaceHash(appId + ':' + discovery.room);
|
|
197
|
+
const inboxTopic = roomTopic + '/' + discovery.self;
|
|
198
|
+
const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
|
|
199
|
+
const seen = new Map();
|
|
200
|
+
const seenMids = new Map();
|
|
201
|
+
const readySockets = new Set();
|
|
202
|
+
const allSockets = new Set();
|
|
203
|
+
const reconnectTimers = new Set();
|
|
204
|
+
let closed = false;
|
|
205
|
+
let reportedOnline = false;
|
|
206
|
+
let reportedOffline = false;
|
|
207
|
+
let initialPending = urls.length;
|
|
208
|
+
let nextPacketId = 1;
|
|
209
|
+
let msgSeq = 0;
|
|
210
|
+
let lastDecryptErrorAt = -Infinity;
|
|
211
|
+
let resolvedKey;
|
|
212
|
+
const keyPromise = password !== undefined
|
|
213
|
+
? deriveKey(password, roomTopic).then((k) => {
|
|
214
|
+
resolvedKey = k;
|
|
215
|
+
return k;
|
|
216
|
+
})
|
|
217
|
+
: undefined;
|
|
218
|
+
const roster = () => discovery.roster([...seen.keys()]);
|
|
219
|
+
const touch = (id) => {
|
|
220
|
+
const known = seen.has(id);
|
|
221
|
+
if (!known && seen.size >= maxSeenPeers) {
|
|
222
|
+
const oldest = seen.keys().next().value;
|
|
223
|
+
if (oldest !== undefined)
|
|
224
|
+
seen.delete(oldest);
|
|
225
|
+
}
|
|
226
|
+
seen.delete(id);
|
|
227
|
+
seen.set(id, Date.now());
|
|
228
|
+
if (!known)
|
|
229
|
+
roster();
|
|
230
|
+
return known;
|
|
231
|
+
};
|
|
232
|
+
const recordMid = (mid) => {
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
const prev = seenMids.get(mid);
|
|
235
|
+
if (prev !== undefined && now - prev < midTtlMs)
|
|
236
|
+
return false;
|
|
237
|
+
if (seenMids.size >= maxSeenMids) {
|
|
238
|
+
for (const [key, at] of seenMids) {
|
|
239
|
+
if (now - at >= midTtlMs || seenMids.size >= maxSeenMids) {
|
|
240
|
+
seenMids.delete(key);
|
|
241
|
+
if (seenMids.size < maxSeenMids)
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
seenMids.delete(mid);
|
|
247
|
+
seenMids.set(mid, now);
|
|
248
|
+
return true;
|
|
249
|
+
};
|
|
250
|
+
const updateStatus = () => {
|
|
251
|
+
if (closed)
|
|
252
|
+
return;
|
|
253
|
+
const online = readySockets.size > 0;
|
|
254
|
+
if (online && !reportedOnline) {
|
|
255
|
+
reportedOnline = true;
|
|
256
|
+
reportedOffline = false;
|
|
257
|
+
discovery.status('online');
|
|
258
|
+
}
|
|
259
|
+
else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
|
|
260
|
+
reportedOnline = false;
|
|
261
|
+
reportedOffline = true;
|
|
262
|
+
const reason = 'All MQTT relays disconnected';
|
|
263
|
+
discovery.status('offline', reason);
|
|
264
|
+
discovery.error?.('signaling-error', reason);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
const publishRaw = async (body, targetSockets, fixedMid) => {
|
|
268
|
+
if (closed)
|
|
269
|
+
return;
|
|
270
|
+
const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
|
|
271
|
+
const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
|
|
272
|
+
const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
|
|
273
|
+
let payload;
|
|
274
|
+
try {
|
|
275
|
+
const key = resolvedKey ?? (keyPromise ? await keyPromise : undefined);
|
|
276
|
+
payload = key ? await sealPayload(key, plain, targetTopic) : plain;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (closed)
|
|
282
|
+
return;
|
|
283
|
+
const frame = buildPublish(targetTopic, payload);
|
|
284
|
+
for (const ws of targetSockets ?? readySockets) {
|
|
285
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
286
|
+
try {
|
|
287
|
+
ws.send(frame);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
// Socket closing; reconnect loop handles recovery.
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
const handlePayload = async (msgTopic, raw) => {
|
|
296
|
+
if (closed)
|
|
297
|
+
return;
|
|
298
|
+
let key;
|
|
299
|
+
try {
|
|
300
|
+
key = resolvedKey ?? (keyPromise ? await keyPromise : undefined);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (closed)
|
|
306
|
+
return;
|
|
307
|
+
let plain;
|
|
308
|
+
try {
|
|
309
|
+
plain = key ? await openPayload(key, raw, msgTopic) : raw;
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
plain = null;
|
|
313
|
+
}
|
|
314
|
+
if (closed)
|
|
315
|
+
return;
|
|
316
|
+
if (!plain) {
|
|
317
|
+
if (key) {
|
|
318
|
+
const now = Date.now();
|
|
319
|
+
if (now - lastDecryptErrorAt >= decryptErrorCooldownMs) {
|
|
320
|
+
lastDecryptErrorAt = now;
|
|
321
|
+
discovery.error?.('decrypt-failed', 'Failed to decrypt MQTT signaling message');
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
let data = null;
|
|
327
|
+
try {
|
|
328
|
+
data = JSON.parse(decoder.decode(plain));
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (!data || !isUuid(data.from) || data.from === discovery.self)
|
|
334
|
+
return;
|
|
335
|
+
if (data.to !== undefined && data.to !== discovery.self)
|
|
336
|
+
return;
|
|
337
|
+
if (data.mid !== undefined &&
|
|
338
|
+
(typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength))
|
|
339
|
+
return;
|
|
340
|
+
if (key) {
|
|
341
|
+
if (typeof data.mid !== 'string')
|
|
342
|
+
return;
|
|
343
|
+
if (typeof data.ts !== 'number' || Math.abs(Date.now() - data.ts) > replayWindowMs)
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (typeof data.mid === 'string' && !recordMid(data.from + ':' + data.mid))
|
|
347
|
+
return;
|
|
348
|
+
switch (data.type) {
|
|
349
|
+
case 'hello':
|
|
350
|
+
touch(data.from);
|
|
351
|
+
void publishRaw({ type: 'present', to: data.from });
|
|
352
|
+
break;
|
|
353
|
+
case 'heartbeat':
|
|
354
|
+
if (!touch(data.from))
|
|
355
|
+
void publishRaw({ type: 'present', to: data.from });
|
|
356
|
+
break;
|
|
357
|
+
case 'present':
|
|
358
|
+
touch(data.from);
|
|
359
|
+
break;
|
|
360
|
+
case 'bye':
|
|
361
|
+
if (seen.delete(data.from))
|
|
362
|
+
roster();
|
|
363
|
+
break;
|
|
364
|
+
case 'signal':
|
|
365
|
+
if (isSignal(data.signal)) {
|
|
366
|
+
touch(data.from);
|
|
367
|
+
discovery.receive(data.from, data.signal);
|
|
368
|
+
}
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
const connectBroker = (url, attempt = 0, isInitial = true) => {
|
|
373
|
+
if (closed)
|
|
374
|
+
return;
|
|
375
|
+
let settledInitial = !isInitial;
|
|
376
|
+
const settleInitial = () => {
|
|
377
|
+
if (!settledInitial) {
|
|
378
|
+
settledInitial = true;
|
|
379
|
+
initialPending = Math.max(0, initialPending - 1);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
let ws;
|
|
383
|
+
try {
|
|
384
|
+
ws = new WebSocket(url, ['mqtt']);
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
settleInitial();
|
|
388
|
+
updateStatus();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
ws.binaryType = 'arraybuffer';
|
|
392
|
+
allSockets.add(ws);
|
|
393
|
+
let buffer = new Uint8Array(0);
|
|
394
|
+
let pingTimer;
|
|
395
|
+
let handshakeTimer;
|
|
396
|
+
let awaitingPong = false;
|
|
397
|
+
let subscribed = false;
|
|
398
|
+
const abortSocket = () => {
|
|
399
|
+
try {
|
|
400
|
+
ws.close();
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
// Ignore close errors.
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
const sendFrame = (frame) => {
|
|
407
|
+
try {
|
|
408
|
+
ws.send(frame);
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
abortSocket();
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
handshakeTimer = setTimeout(() => {
|
|
415
|
+
if (!subscribed)
|
|
416
|
+
abortSocket();
|
|
417
|
+
}, handshakeTimeoutMs);
|
|
418
|
+
const cleanup = () => {
|
|
419
|
+
if (handshakeTimer)
|
|
420
|
+
clearTimeout(handshakeTimer);
|
|
421
|
+
if (pingTimer)
|
|
422
|
+
clearInterval(pingTimer);
|
|
423
|
+
allSockets.delete(ws);
|
|
424
|
+
const wasReady = readySockets.delete(ws);
|
|
425
|
+
settleInitial();
|
|
426
|
+
if (wasReady || initialPending === 0)
|
|
427
|
+
updateStatus();
|
|
428
|
+
if (!closed) {
|
|
429
|
+
const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
|
|
430
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
431
|
+
const timer = setTimeout(() => {
|
|
432
|
+
reconnectTimers.delete(timer);
|
|
433
|
+
connectBroker(url, attempt + 1, false);
|
|
434
|
+
}, delay);
|
|
435
|
+
reconnectTimers.add(timer);
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
ws.onopen = () => {
|
|
439
|
+
if (closed) {
|
|
440
|
+
abortSocket();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
|
|
444
|
+
sendFrame(buildConnect(clientId));
|
|
445
|
+
};
|
|
446
|
+
ws.onmessage = ({ data }) => {
|
|
447
|
+
if (closed || !(data instanceof ArrayBuffer))
|
|
448
|
+
return;
|
|
449
|
+
if (buffer.length + data.byteLength > maxMqttBuffer) {
|
|
450
|
+
abortSocket();
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
buffer = concatBytes(buffer, new Uint8Array(data));
|
|
454
|
+
buffer = parseMqttFrames(buffer, {
|
|
455
|
+
onConnAck(code) {
|
|
456
|
+
if (closed)
|
|
457
|
+
return;
|
|
458
|
+
if (code !== 0) {
|
|
459
|
+
abortSocket();
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const id = nextPacketId;
|
|
463
|
+
nextPacketId = (nextPacketId % 65535) + 1;
|
|
464
|
+
sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
|
|
465
|
+
},
|
|
466
|
+
onSubAck(codes) {
|
|
467
|
+
if (closed || subscribed)
|
|
468
|
+
return;
|
|
469
|
+
if (codes.length < 2 || codes.some((c) => c === 0x80)) {
|
|
470
|
+
abortSocket();
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
subscribed = true;
|
|
474
|
+
if (handshakeTimer)
|
|
475
|
+
clearTimeout(handshakeTimer);
|
|
476
|
+
handshakeTimer = undefined;
|
|
477
|
+
attempt = 0;
|
|
478
|
+
settleInitial();
|
|
479
|
+
readySockets.add(ws);
|
|
480
|
+
updateStatus();
|
|
481
|
+
void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
482
|
+
pingTimer = setInterval(() => {
|
|
483
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
484
|
+
return;
|
|
485
|
+
if (awaitingPong) {
|
|
486
|
+
abortSocket();
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
awaitingPong = true;
|
|
490
|
+
sendFrame(pingReq);
|
|
491
|
+
}, 20_000);
|
|
492
|
+
},
|
|
493
|
+
onPingResp() {
|
|
494
|
+
awaitingPong = false;
|
|
495
|
+
},
|
|
496
|
+
onPublish(msg) {
|
|
497
|
+
if (!subscribed)
|
|
498
|
+
return;
|
|
499
|
+
if (msg.topic === roomTopic || msg.topic === inboxTopic) {
|
|
500
|
+
void handlePayload(msg.topic, msg.payload);
|
|
501
|
+
}
|
|
502
|
+
},
|
|
503
|
+
onError() {
|
|
504
|
+
abortSocket();
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
};
|
|
508
|
+
ws.onerror = abortSocket;
|
|
509
|
+
ws.onclose = cleanup;
|
|
510
|
+
};
|
|
511
|
+
const leaseTimer = setInterval(() => {
|
|
512
|
+
if (closed)
|
|
513
|
+
return;
|
|
514
|
+
const now = Date.now();
|
|
515
|
+
let changed = false;
|
|
516
|
+
for (const [id, last] of seen) {
|
|
517
|
+
if (now - last > 30_000) {
|
|
518
|
+
seen.delete(id);
|
|
519
|
+
changed = true;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (changed)
|
|
523
|
+
roster();
|
|
524
|
+
for (const [mid, at] of seenMids) {
|
|
525
|
+
if (now - at >= midTtlMs)
|
|
526
|
+
seenMids.delete(mid);
|
|
527
|
+
}
|
|
528
|
+
if (readySockets.size > 0)
|
|
529
|
+
void publishRaw({ type: 'heartbeat' });
|
|
530
|
+
}, 5_000);
|
|
531
|
+
queueMicrotask(() => {
|
|
532
|
+
if (closed)
|
|
533
|
+
return;
|
|
534
|
+
for (const url of urls)
|
|
535
|
+
connectBroker(url);
|
|
536
|
+
});
|
|
537
|
+
return {
|
|
538
|
+
trickle: true,
|
|
539
|
+
send(to, signal) {
|
|
540
|
+
if (closed || readySockets.size === 0)
|
|
541
|
+
return false;
|
|
542
|
+
void publishRaw({ type: 'signal', to, signal });
|
|
543
|
+
return true;
|
|
544
|
+
},
|
|
545
|
+
close() {
|
|
546
|
+
if (closed)
|
|
547
|
+
return;
|
|
548
|
+
closed = true;
|
|
549
|
+
clearInterval(leaseTimer);
|
|
550
|
+
for (const timer of reconnectTimers)
|
|
551
|
+
clearTimeout(timer);
|
|
552
|
+
reconnectTimers.clear();
|
|
553
|
+
const socketsToClose = [...allSockets];
|
|
554
|
+
const readyToNotify = [...readySockets];
|
|
555
|
+
allSockets.clear();
|
|
556
|
+
readySockets.clear();
|
|
557
|
+
const shutdownSocket = (ws, byeFrame) => {
|
|
558
|
+
try {
|
|
559
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
560
|
+
if (byeFrame)
|
|
561
|
+
ws.send(byeFrame);
|
|
562
|
+
ws.send(disconnectPkt);
|
|
563
|
+
}
|
|
564
|
+
ws.close();
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
// Ignore shutdown errors.
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
const byePlain = encoder.encode(JSON.stringify({
|
|
571
|
+
type: 'bye',
|
|
572
|
+
from: discovery.self,
|
|
573
|
+
mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
|
|
574
|
+
ts: Date.now()
|
|
575
|
+
}));
|
|
576
|
+
if (!keyPromise) {
|
|
577
|
+
const byeFrame = buildPublish(roomTopic, byePlain);
|
|
578
|
+
for (const ws of socketsToClose) {
|
|
579
|
+
shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
else if (resolvedKey && readyToNotify.length > 0) {
|
|
583
|
+
const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
|
|
584
|
+
for (const ws of nonReady)
|
|
585
|
+
shutdownSocket(ws);
|
|
586
|
+
const fallbackTimer = setTimeout(() => {
|
|
587
|
+
for (const ws of readyToNotify)
|
|
588
|
+
shutdownSocket(ws);
|
|
589
|
+
}, 250);
|
|
590
|
+
void sealPayload(resolvedKey, byePlain, roomTopic)
|
|
591
|
+
.then((boxed) => {
|
|
592
|
+
clearTimeout(fallbackTimer);
|
|
593
|
+
const byeFrame = buildPublish(roomTopic, boxed);
|
|
594
|
+
for (const ws of readyToNotify)
|
|
595
|
+
shutdownSocket(ws, byeFrame);
|
|
596
|
+
})
|
|
597
|
+
.catch(() => {
|
|
598
|
+
clearTimeout(fallbackTimer);
|
|
599
|
+
for (const ws of readyToNotify)
|
|
600
|
+
shutdownSocket(ws);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
else {
|
|
604
|
+
for (const ws of socketsToClose)
|
|
605
|
+
shutdownSocket(ws);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
};
|
|
610
|
+
}
|