@dimchansky/meshpost 0.5.0 → 0.6.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.
Files changed (46) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +5 -24
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +2 -0
  10. package/dist/identity.js +39 -71
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +1 -1
  17. package/dist/public.js +9 -54
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +11 -1
  39. package/dist/voice.js +99 -295
  40. package/dist/ws.js +39 -142
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +10 -4
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/mqtt.js CHANGED
@@ -1,5 +1,6 @@
1
- import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, maxMidLength, openPayload, sealPayload } from './crypto.js';
2
- import { isSignal, isUuid, namespaceHash } from './signaling.js';
1
+ import { createReplayGuard, maxMidLength, openPayload, sealPayload } from './crypto.js';
2
+ import { createErrorThrottle, createPresenceTracker, createRelayPool, normalizeWsRelayUrl, validatePositiveTimeout } from './relay-core.js';
3
+ import { isUuid, namespaceHash } from './signaling.js';
3
4
  /** Built-in public MQTT-over-WebSocket relay URLs used by default. */
4
5
  export const defaultMqttRelays = Object.freeze([
5
6
  'wss://broker.emqx.io:8084/mqtt',
@@ -10,7 +11,6 @@ const wsOpen = 1;
10
11
  const encoder = new TextEncoder();
11
12
  const decoder = new TextDecoder();
12
13
  const maxMqttBuffer = 128 * 1024;
13
- const maxSeenPeers = 256;
14
14
  const defaultMqttHandshakeTimeoutMs = 10_000;
15
15
  function encodeRemainingLength(length) {
16
16
  const bytes = [];
@@ -24,54 +24,53 @@ function encodeRemainingLength(length) {
24
24
  } while (n > 0);
25
25
  return bytes;
26
26
  }
27
- function encodeMqttString(str) {
28
- const data = encoder.encode(str);
29
- const out = new Uint8Array(2 + data.length);
30
- out[0] = (data.length >>> 8) & 0xff;
31
- out[1] = data.length & 0xff;
32
- out.set(data, 2);
27
+ function encodeString(text) {
28
+ const body = encoder.encode(text);
29
+ const out = new Uint8Array(2 + body.length);
30
+ out[0] = (body.length >>> 8) & 0xff;
31
+ out[1] = body.length & 0xff;
32
+ out.set(body, 2);
33
33
  return out;
34
34
  }
35
35
  function concatBytes(...parts) {
36
36
  let total = 0;
37
- for (const p of parts)
38
- total += p.length;
37
+ for (const part of parts)
38
+ total += part.length;
39
39
  const out = new Uint8Array(total);
40
40
  let offset = 0;
41
- for (const p of parts) {
42
- out.set(p, offset);
43
- offset += p.length;
41
+ for (const part of parts) {
42
+ out.set(part, offset);
43
+ offset += part.length;
44
44
  }
45
45
  return out;
46
46
  }
47
- function mqttPacket(header, body) {
48
- const rem = encodeRemainingLength(body.length);
49
- const out = new Uint8Array(1 + rem.length + body.length);
50
- out[0] = header;
47
+ function buildPacket(typeAndFlags, ...parts) {
48
+ let bodyLength = 0;
49
+ for (const part of parts)
50
+ bodyLength += part.length;
51
+ const rem = encodeRemainingLength(bodyLength);
52
+ const out = new Uint8Array(1 + rem.length + bodyLength);
53
+ out[0] = typeAndFlags;
51
54
  out.set(rem, 1);
52
- out.set(body, 1 + rem.length);
55
+ let offset = 1 + rem.length;
56
+ for (const part of parts) {
57
+ out.set(part, offset);
58
+ offset += part.length;
59
+ }
53
60
  return out;
54
61
  }
55
62
  function buildConnect(clientId) {
56
- const proto = encodeMqttString('MQTT');
57
- const flags = new Uint8Array([
58
- 4, // Protocol level 4 (MQTT 3.1.1)
59
- 0x02, // Clean Session
60
- 0,
61
- 30 // Keep Alive = 30s
62
- ]);
63
- return mqttPacket(0x10, concatBytes(proto, flags, encodeMqttString(clientId)));
63
+ return buildPacket(0x10, encodeString('MQTT'), new Uint8Array([0x04, 0x02, 0x00, 60]), encodeString(clientId));
64
64
  }
65
65
  function buildSubscribe(packetId, topics) {
66
66
  const parts = [new Uint8Array([(packetId >>> 8) & 0xff, packetId & 0xff])];
67
- const qos = new Uint8Array([0]);
68
67
  for (const topic of topics) {
69
- parts.push(encodeMqttString(topic), qos);
68
+ parts.push(encodeString(topic), new Uint8Array([0x00]));
70
69
  }
71
- return mqttPacket(0x82, concatBytes(...parts));
70
+ return buildPacket(0x82, ...parts);
72
71
  }
73
72
  function buildPublish(topic, payload) {
74
- return mqttPacket(0x30, concatBytes(encodeMqttString(topic), payload));
73
+ return buildPacket(0x30, encodeString(topic), payload);
75
74
  }
76
75
  const pingReq = new Uint8Array([0xc0, 0x00]);
77
76
  const disconnectPkt = new Uint8Array([0xe0, 0x00]);
@@ -79,43 +78,44 @@ function parseMqttFrames(buffer, handlers) {
79
78
  let offset = 0;
80
79
  while (offset + 2 <= buffer.length) {
81
80
  const header = buffer[offset];
82
- const type = header >>> 4;
83
81
  let multiplier = 1;
84
- let remaining = 0;
82
+ let remLen = 0;
85
83
  let pos = offset + 1;
86
- let done = false;
84
+ let complete = false;
85
+ let malformed = false;
87
86
  while (pos < buffer.length) {
88
- const encoded = buffer[pos++];
89
- remaining += (encoded & 0x7f) * multiplier;
90
- if ((encoded & 0x80) === 0) {
91
- done = true;
87
+ const digit = buffer[pos++];
88
+ remLen += (digit & 0x7f) * multiplier;
89
+ if ((digit & 0x80) === 0) {
90
+ complete = true;
92
91
  break;
93
92
  }
94
93
  multiplier *= 128;
95
94
  if (multiplier > 128 * 128 * 128) {
96
- handlers.onError();
97
- return new Uint8Array(0);
95
+ malformed = true;
96
+ break;
98
97
  }
99
98
  }
100
- if (!done)
101
- break;
102
- if (remaining > maxMqttBuffer) {
99
+ if (malformed) {
103
100
  handlers.onError();
104
101
  return new Uint8Array(0);
105
102
  }
106
- if (pos + remaining > buffer.length)
103
+ if (!complete)
107
104
  break;
108
- const end = pos + remaining;
109
- if (type === 2 && remaining >= 2) {
105
+ const end = pos + remLen;
106
+ if (end > buffer.length)
107
+ break;
108
+ const type = header >>> 4;
109
+ if (type === 2 && remLen >= 2) {
110
110
  handlers.onConnAck(buffer[pos + 1]);
111
111
  }
112
- else if (type === 9 && remaining >= 3) {
112
+ else if (type === 9 && remLen >= 2) {
113
113
  handlers.onSubAck(buffer.subarray(pos + 2, end));
114
114
  }
115
115
  else if (type === 13) {
116
116
  handlers.onPingResp();
117
117
  }
118
- else if (type === 3 && remaining >= 2) {
118
+ else if (type === 3 && remLen >= 2) {
119
119
  const topicLen = (buffer[pos] << 8) | buffer[pos + 1];
120
120
  let bodyStart = pos + 2 + topicLen;
121
121
  const qos = (header >>> 1) & 0x03;
@@ -141,17 +141,16 @@ function parseMqttFrames(buffer, handlers) {
141
141
  * handshakes with AES-256-GCM (+ topic AAD and timestamp anti-replay) when `password` is provided.
142
142
  */
143
143
  export function mqttSignaling(options = {}) {
144
- const urls = [...(options.urls ?? defaultMqttRelays)];
145
- if (urls.length === 0)
144
+ const rawUrls = [...(options.urls ?? defaultMqttRelays)];
145
+ if (rawUrls.length === 0)
146
146
  throw new RangeError('At least one MQTT relay URL is required');
147
+ const urls = rawUrls.map((u) => normalizeWsRelayUrl(u, 'Invalid MQTT relay URL', 'MQTT relay URL must use ws: or wss:'));
147
148
  const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultMqttHandshakeTimeoutMs;
148
- if (!Number.isSafeInteger(handshakeTimeoutMs) ||
149
- handshakeTimeoutMs <= 0 ||
150
- handshakeTimeoutMs > 2_147_483_647)
151
- throw new RangeError('Invalid MQTT handshake timeout');
149
+ validatePositiveTimeout(handshakeTimeoutMs, 'Invalid MQTT handshake timeout');
152
150
  if (options.password !== undefined &&
153
- (typeof options.password !== 'string' || options.password.length === 0))
151
+ (typeof options.password !== 'string' || options.password.length === 0)) {
154
152
  throw new TypeError('Invalid password');
153
+ }
155
154
  if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
156
155
  throw new TypeError('Invalid privateTopic option');
157
156
  }
@@ -170,8 +169,9 @@ export function mqttSignaling(options = {}) {
170
169
  throw new TypeError('privateTopic requires a room password');
171
170
  }
172
171
  if (password !== undefined) {
173
- if (typeof password !== 'string' || password.length === 0)
172
+ if (typeof password !== 'string' || password.length === 0) {
174
173
  throw new TypeError('Invalid password');
174
+ }
175
175
  if (!globalThis.crypto?.subtle) {
176
176
  throw new Error('Password encryption requires a secure context (crypto.subtle)');
177
177
  }
@@ -180,70 +180,30 @@ export function mqttSignaling(options = {}) {
180
180
  let roomTopic = privateTopic ? '' : 'meshpost/1/' + namespaceHash(baseScope);
181
181
  let inboxTopic = privateTopic ? '' : roomTopic + '/' + discovery.self;
182
182
  const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
183
- const seen = new Map();
184
183
  const replayGuard = createReplayGuard();
185
- const readySockets = new Set();
186
- const allSockets = new Set();
187
- const reconnectTimers = new Set();
188
- let closed = false;
189
- let reportedOnline = false;
190
- let reportedOffline = false;
191
- let initialPending = urls.length;
184
+ const emitError = createErrorThrottle(discovery);
192
185
  let nextPacketId = 1;
193
- let msgSeq = 0;
194
- let lastDecryptErrorAt = -Infinity;
195
- let lastClockSkewErrorAt = -Infinity;
196
- let resolvedKey;
197
- const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
198
- const roster = () => discovery.roster([...seen.keys()]);
199
- const touch = (id) => {
200
- const known = seen.has(id);
201
- if (!known && seen.size >= maxSeenPeers) {
202
- const oldest = seen.keys().next().value;
203
- if (oldest !== undefined)
204
- seen.delete(oldest);
205
- }
206
- seen.delete(id);
207
- seen.set(id, Date.now());
208
- if (!known)
209
- roster();
210
- return known;
211
- };
212
- const updateStatus = () => {
213
- if (closed)
214
- return;
215
- const online = readySockets.size > 0;
216
- if (online && !reportedOnline) {
217
- reportedOnline = true;
218
- reportedOffline = false;
219
- discovery.status('online');
220
- }
221
- else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
222
- reportedOnline = false;
223
- reportedOffline = true;
224
- const reason = 'All MQTT relays disconnected';
225
- discovery.status('offline', reason);
226
- discovery.error?.('signaling-error', reason);
227
- }
228
- };
186
+ const presence = createPresenceTracker(discovery, (to) => {
187
+ void publishRaw({ type: 'present', to });
188
+ });
229
189
  const publishRaw = async (body, targetSockets, fixedMid) => {
230
- if (closed || !roomTopic)
190
+ if (pool.isClosed() || !roomTopic)
231
191
  return;
232
192
  const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
233
- const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
193
+ const mid = fixedMid ?? pool.nextMid();
234
194
  const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
235
195
  let payload;
236
196
  try {
237
- const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
197
+ const key = await pool.getKey();
238
198
  payload = key ? await sealPayload(key, plain, targetTopic) : plain;
239
199
  }
240
200
  catch {
241
201
  return;
242
202
  }
243
- if (closed)
203
+ if (pool.isClosed())
244
204
  return;
245
205
  const frame = buildPublish(targetTopic, payload);
246
- for (const ws of targetSockets ?? readySockets) {
206
+ for (const ws of targetSockets ?? pool.readySockets) {
247
207
  if (ws.readyState === wsOpen) {
248
208
  try {
249
209
  ws.send(frame);
@@ -255,16 +215,16 @@ export function mqttSignaling(options = {}) {
255
215
  }
256
216
  };
257
217
  const handlePayload = async (msgTopic, raw) => {
258
- if (closed)
218
+ if (pool.isClosed())
259
219
  return;
260
220
  let key;
261
221
  try {
262
- key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
222
+ key = await pool.getKey();
263
223
  }
264
224
  catch {
265
225
  return;
266
226
  }
267
- if (closed)
227
+ if (pool.isClosed())
268
228
  return;
269
229
  let plain;
270
230
  try {
@@ -273,16 +233,11 @@ export function mqttSignaling(options = {}) {
273
233
  catch {
274
234
  plain = null;
275
235
  }
276
- if (closed)
236
+ if (pool.isClosed())
277
237
  return;
278
238
  if (!plain) {
279
- if (key) {
280
- const now = Date.now();
281
- if (now - lastDecryptErrorAt >= errorCooldownMs) {
282
- lastDecryptErrorAt = now;
283
- discovery.error?.('decrypt-failed', 'Failed to decrypt MQTT signaling message');
284
- }
285
- }
239
+ if (key)
240
+ emitError('decrypt-failed', 'Failed to decrypt MQTT signaling message');
286
241
  return;
287
242
  }
288
243
  let data = null;
@@ -299,11 +254,7 @@ export function mqttSignaling(options = {}) {
299
254
  if (key) {
300
255
  const check = replayGuard.checkAuthenticated(data.from, data);
301
256
  if (check === 'clock-skew') {
302
- const now = Date.now();
303
- if (now - lastClockSkewErrorAt >= errorCooldownMs) {
304
- lastClockSkewErrorAt = now;
305
- discovery.error?.('clock-skew', 'MQTT signaling message rejected due to system clock skew (>60s)');
306
- }
257
+ emitError('clock-skew', 'MQTT signaling message rejected due to system clock skew (>60s)');
307
258
  return;
308
259
  }
309
260
  if (check !== 'ok')
@@ -311,308 +262,142 @@ export function mqttSignaling(options = {}) {
311
262
  }
312
263
  else {
313
264
  if (data.mid !== undefined &&
314
- (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength))
315
- return;
316
- if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid))
265
+ (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength)) {
317
266
  return;
318
- }
319
- switch (data.type) {
320
- case 'hello':
321
- touch(data.from);
322
- void publishRaw({ type: 'present', to: data.from });
323
- break;
324
- case 'heartbeat':
325
- if (!touch(data.from))
326
- void publishRaw({ type: 'present', to: data.from });
327
- break;
328
- case 'present':
329
- touch(data.from);
330
- break;
331
- case 'bye':
332
- if (seen.delete(data.from))
333
- roster();
334
- break;
335
- case 'signal':
336
- if (isSignal(data.signal)) {
337
- touch(data.from);
338
- discovery.receive(data.from, data.signal);
339
- }
340
- break;
341
- }
342
- };
343
- const connectBroker = (url, attempt = 0, isInitial = true) => {
344
- if (closed)
345
- return;
346
- let settledInitial = !isInitial;
347
- const settleInitial = () => {
348
- if (!settledInitial) {
349
- settledInitial = true;
350
- initialPending = Math.max(0, initialPending - 1);
351
267
  }
352
- };
353
- let ws;
354
- try {
355
- ws = new WsCtor(url, ['mqtt']);
356
- }
357
- catch {
358
- settleInitial();
359
- updateStatus();
360
- return;
361
- }
362
- ws.binaryType = 'arraybuffer';
363
- allSockets.add(ws);
364
- let buffer = new Uint8Array(0);
365
- let pingTimer;
366
- let handshakeTimer;
367
- let awaitingPong = false;
368
- let subscribed = false;
369
- const abortSocket = () => {
370
- try {
371
- ws.close();
372
- }
373
- catch {
374
- // Ignore close errors.
375
- }
376
- };
377
- const sendFrame = (frame) => {
378
- try {
379
- ws.send(frame);
380
- }
381
- catch {
382
- abortSocket();
383
- }
384
- };
385
- handshakeTimer = setTimeout(() => {
386
- if (!subscribed)
387
- abortSocket();
388
- }, handshakeTimeoutMs);
389
- const cleanup = () => {
390
- if (handshakeTimer)
391
- clearTimeout(handshakeTimer);
392
- if (pingTimer)
393
- clearInterval(pingTimer);
394
- allSockets.delete(ws);
395
- const wasReady = readySockets.delete(ws);
396
- settleInitial();
397
- if (wasReady || initialPending === 0)
398
- updateStatus();
399
- if (!closed) {
400
- const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
401
- const delay = Math.round(base * (0.75 + Math.random() * 0.5));
402
- const timer = setTimeout(() => {
403
- reconnectTimers.delete(timer);
404
- connectBroker(url, attempt + 1, false);
405
- }, delay);
406
- reconnectTimers.add(timer);
407
- }
408
- };
409
- ws.onopen = () => {
410
- if (closed) {
411
- abortSocket();
412
- return;
413
- }
414
- const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
415
- sendFrame(buildConnect(clientId));
416
- };
417
- ws.onmessage = ({ data }) => {
418
- if (closed || !(data instanceof ArrayBuffer))
268
+ if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid)) {
419
269
  return;
420
- if (buffer.length + data.byteLength > maxMqttBuffer) {
421
- abortSocket();
422
- return;
423
- }
424
- buffer = concatBytes(buffer, new Uint8Array(data));
425
- buffer = parseMqttFrames(buffer, {
426
- onConnAck(code) {
427
- if (closed)
428
- return;
429
- if (code !== 0) {
430
- abortSocket();
431
- return;
432
- }
433
- const id = nextPacketId;
434
- nextPacketId = (nextPacketId % 65535) + 1;
435
- sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
436
- },
437
- onSubAck(codes) {
438
- if (closed || subscribed)
439
- return;
440
- if (codes.length < 2 || codes.some((c) => c === 0x80)) {
441
- abortSocket();
442
- return;
443
- }
444
- subscribed = true;
445
- if (handshakeTimer)
446
- clearTimeout(handshakeTimer);
447
- handshakeTimer = undefined;
448
- attempt = 0;
449
- settleInitial();
450
- readySockets.add(ws);
451
- updateStatus();
452
- void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
453
- pingTimer = setInterval(() => {
454
- if (ws.readyState !== wsOpen)
455
- return;
456
- if (awaitingPong) {
457
- abortSocket();
458
- return;
459
- }
460
- awaitingPong = true;
461
- sendFrame(pingReq);
462
- }, 20_000);
463
- },
464
- onPingResp() {
465
- awaitingPong = false;
466
- },
467
- onPublish(msg) {
468
- if (!subscribed)
469
- return;
470
- if (msg.topic === roomTopic || msg.topic === inboxTopic) {
471
- void handlePayload(msg.topic, msg.payload);
472
- }
473
- },
474
- onError() {
475
- abortSocket();
476
- }
477
- });
478
- };
479
- ws.onerror = abortSocket;
480
- ws.onclose = cleanup;
481
- };
482
- const leaseTimer = setInterval(() => {
483
- if (closed)
484
- return;
485
- const now = Date.now();
486
- let changed = false;
487
- for (const [id, last] of seen) {
488
- if (now - last > 30_000) {
489
- seen.delete(id);
490
- changed = true;
491
270
  }
492
271
  }
493
- if (changed)
494
- roster();
495
- replayGuard.prune(now);
496
- if (readySockets.size > 0)
497
- void publishRaw({ type: 'heartbeat' });
498
- }, 5_000);
499
- if (keysPromise && privateTopic) {
500
- void keysPromise
501
- .then((keys) => {
502
- if (closed)
503
- return;
504
- roomTopic = 'meshpost/1/p/' + keys.privateId;
505
- inboxTopic = roomTopic + '/' + discovery.self;
506
- resolvedKey = keys.aeadKey;
507
- for (const url of urls)
508
- connectBroker(url);
509
- })
510
- .catch(() => {
511
- if (closed)
512
- return;
513
- initialPending = 0;
514
- updateStatus();
515
- });
516
- }
517
- else {
518
- if (keysPromise) {
519
- void keysPromise
520
- .then((keys) => {
521
- resolvedKey = keys.aeadKey;
522
- })
523
- .catch(() => {
524
- if (closed)
525
- return;
526
- initialPending = 0;
527
- for (const ws of [...allSockets]) {
528
- try {
529
- ws.close();
530
- }
531
- catch {
532
- // Ignore close errors.
533
- }
534
- }
535
- updateStatus();
536
- });
537
- }
538
- queueMicrotask(() => {
539
- if (closed)
540
- return;
541
- for (const url of urls)
542
- connectBroker(url);
543
- });
544
- }
545
- return {
546
- trickle: true,
547
- send(to, signal) {
548
- if (closed || readySockets.size === 0)
549
- return false;
550
- void publishRaw({ type: 'signal', to, signal });
551
- return true;
272
+ presence.dispatch(data);
273
+ };
274
+ const pool = createRelayPool({
275
+ discovery,
276
+ urls,
277
+ handshakeTimeoutMs,
278
+ offlineReason: 'All MQTT relays disconnected',
279
+ password,
280
+ privateTopic,
281
+ baseScope,
282
+ createSocket(url) {
283
+ const ws = new WsCtor(url, ['mqtt']);
284
+ ws.binaryType = 'arraybuffer';
285
+ return ws;
552
286
  },
553
- close() {
554
- if (closed)
555
- return;
556
- closed = true;
557
- clearInterval(leaseTimer);
558
- for (const timer of reconnectTimers)
559
- clearTimeout(timer);
560
- reconnectTimers.clear();
561
- const socketsToClose = [...allSockets];
562
- const readyToNotify = [...readySockets];
563
- allSockets.clear();
564
- readySockets.clear();
565
- const shutdownSocket = (ws, byeFrame) => {
287
+ attachSocket(ws, controls) {
288
+ let buffer = new Uint8Array(0);
289
+ let pingTimer;
290
+ let awaitingPong = false;
291
+ let subscribed = false;
292
+ const sendFrame = (frame) => {
566
293
  try {
567
- if (ws.readyState === wsOpen) {
568
- if (byeFrame)
569
- ws.send(byeFrame);
570
- ws.send(disconnectPkt);
571
- }
572
- ws.close();
294
+ ws.send(frame);
573
295
  }
574
296
  catch {
575
- // Ignore shutdown errors.
297
+ controls.abort();
576
298
  }
577
299
  };
578
- const byePlain = encoder.encode(JSON.stringify({
579
- type: 'bye',
580
- from: discovery.self,
581
- mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
582
- ts: Date.now()
583
- }));
584
- if (!keysPromise && roomTopic) {
585
- const byeFrame = buildPublish(roomTopic, byePlain);
586
- for (const ws of socketsToClose) {
587
- shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
300
+ ws.onopen = () => {
301
+ if (pool.isClosed()) {
302
+ controls.abort();
303
+ return;
588
304
  }
589
- }
590
- else if (resolvedKey && roomTopic && readyToNotify.length > 0) {
591
- const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
592
- for (const ws of nonReady)
593
- shutdownSocket(ws);
594
- const fallbackTimer = setTimeout(() => {
595
- for (const ws of readyToNotify)
596
- shutdownSocket(ws);
597
- }, 250);
598
- void sealPayload(resolvedKey, byePlain, roomTopic)
599
- .then((boxed) => {
600
- clearTimeout(fallbackTimer);
601
- const byeFrame = buildPublish(roomTopic, boxed);
602
- for (const ws of readyToNotify)
603
- shutdownSocket(ws, byeFrame);
604
- })
605
- .catch(() => {
606
- clearTimeout(fallbackTimer);
607
- for (const ws of readyToNotify)
608
- shutdownSocket(ws);
305
+ const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
306
+ sendFrame(buildConnect(clientId));
307
+ };
308
+ ws.onmessage = ({ data }) => {
309
+ if (pool.isClosed() || !(data instanceof ArrayBuffer))
310
+ return;
311
+ if (buffer.length + data.byteLength > maxMqttBuffer) {
312
+ controls.abort();
313
+ return;
314
+ }
315
+ buffer = concatBytes(buffer, new Uint8Array(data));
316
+ buffer = parseMqttFrames(buffer, {
317
+ onConnAck(code) {
318
+ if (pool.isClosed())
319
+ return;
320
+ if (code !== 0) {
321
+ controls.abort();
322
+ return;
323
+ }
324
+ const id = nextPacketId;
325
+ nextPacketId = (nextPacketId % 65535) + 1;
326
+ sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
327
+ },
328
+ onSubAck(codes) {
329
+ if (pool.isClosed() || subscribed)
330
+ return;
331
+ if (codes.length < 2 || codes.some((c) => c === 0x80)) {
332
+ controls.abort();
333
+ return;
334
+ }
335
+ subscribed = true;
336
+ controls.markReady();
337
+ pingTimer = setInterval(() => {
338
+ if (ws.readyState !== wsOpen)
339
+ return;
340
+ if (awaitingPong) {
341
+ controls.abort();
342
+ return;
343
+ }
344
+ awaitingPong = true;
345
+ sendFrame(pingReq);
346
+ }, 20_000);
347
+ },
348
+ onPingResp() {
349
+ awaitingPong = false;
350
+ },
351
+ onPublish(msg) {
352
+ if (!subscribed)
353
+ return;
354
+ if (msg.topic === roomTopic || msg.topic === inboxTopic) {
355
+ void handlePayload(msg.topic, msg.payload);
356
+ }
357
+ },
358
+ onError() {
359
+ controls.abort();
360
+ }
609
361
  });
362
+ };
363
+ return () => {
364
+ if (pingTimer)
365
+ clearInterval(pingTimer);
366
+ };
367
+ },
368
+ onReady(ws, isInitial) {
369
+ void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
370
+ },
371
+ onPrivateKeys(keys) {
372
+ roomTopic = 'meshpost/1/p/' + keys.privateId;
373
+ inboxTopic = roomTopic + '/' + discovery.self;
374
+ },
375
+ onSweep(now, hasReadySockets) {
376
+ presence.prune(now);
377
+ replayGuard.prune(now);
378
+ if (hasReadySockets)
379
+ void publishRaw({ type: 'heartbeat' });
380
+ },
381
+ sendSignal(to, signal) {
382
+ void publishRaw({ type: 'signal', to, signal });
383
+ },
384
+ buildPlainBye: (byeJson) => roomTopic ? buildPublish(roomTopic, encoder.encode(byeJson)) : undefined,
385
+ buildEncryptedBye: (boxed) => (roomTopic ? buildPublish(roomTopic, boxed) : undefined),
386
+ byeAad: () => roomTopic || undefined,
387
+ shutdownSocket(ws, byeFrame) {
388
+ try {
389
+ if (ws.readyState === wsOpen) {
390
+ if (byeFrame)
391
+ ws.send(byeFrame);
392
+ ws.send(disconnectPkt);
393
+ }
394
+ ws.close();
610
395
  }
611
- else {
612
- for (const ws of socketsToClose)
613
- shutdownSocket(ws);
396
+ catch {
397
+ // Ignore shutdown errors.
614
398
  }
615
399
  }
616
- };
400
+ });
401
+ return pool.session;
617
402
  };
618
403
  }