@dimchansky/meshpost 0.5.0 → 0.7.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 (49) 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 +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
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 { createPresenceTracker } from './presence.js';
2
+ import { createRelayEnvelope, createRelayPool, normalizeWsRelayUrl, resolveSessionPassword, resolveSessionWebSocket, validateCommonSignalingOptions, validatePositiveTimeout } from './relay-core.js';
3
+ import { 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,109 +141,41 @@ 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');
152
- if (options.password !== undefined &&
153
- (typeof options.password !== 'string' || options.password.length === 0))
154
- throw new TypeError('Invalid password');
155
- if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
156
- throw new TypeError('Invalid privateTopic option');
157
- }
158
- if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
159
- throw new TypeError('Invalid WebSocket constructor');
160
- }
149
+ validatePositiveTimeout(handshakeTimeoutMs, 'Invalid MQTT handshake timeout');
150
+ validateCommonSignalingOptions(options);
161
151
  return (discovery) => {
162
- const WsCtor = options.WebSocket ?? globalThis.WebSocket;
163
- if (typeof WsCtor !== 'function') {
164
- throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
165
- }
152
+ const WsCtor = resolveSessionWebSocket(options.WebSocket);
166
153
  const appId = options.appId ?? discovery.appId;
167
- const password = options.password ?? discovery.password;
168
154
  const privateTopic = options.privateTopic ?? false;
169
- if (privateTopic && password === undefined) {
170
- throw new TypeError('privateTopic requires a room password');
171
- }
172
- if (password !== undefined) {
173
- if (typeof password !== 'string' || password.length === 0)
174
- throw new TypeError('Invalid password');
175
- if (!globalThis.crypto?.subtle) {
176
- throw new Error('Password encryption requires a secure context (crypto.subtle)');
177
- }
178
- }
155
+ const { password } = resolveSessionPassword(options.password ?? discovery.password, privateTopic);
179
156
  const baseScope = appId + ':' + discovery.room;
180
157
  let roomTopic = privateTopic ? '' : 'meshpost/1/' + namespaceHash(baseScope);
181
158
  let inboxTopic = privateTopic ? '' : roomTopic + '/' + discovery.self;
182
159
  const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
183
- const seen = new Map();
184
- 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;
192
160
  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
- };
161
+ const envelope = createRelayEnvelope({
162
+ discovery,
163
+ password,
164
+ baseScope,
165
+ transportLabel: 'MQTT'
166
+ });
167
+ const presence = createPresenceTracker(discovery, (to) => {
168
+ void publishRaw({ type: 'present', to });
169
+ });
229
170
  const publishRaw = async (body, targetSockets, fixedMid) => {
230
- if (closed || !roomTopic)
171
+ if (pool.isClosed() || !roomTopic)
231
172
  return;
232
173
  const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
233
- const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
234
- const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
235
- let payload;
236
- try {
237
- const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
238
- payload = key ? await sealPayload(key, plain, targetTopic) : plain;
239
- }
240
- catch {
241
- return;
242
- }
243
- if (closed)
174
+ const sealed = await envelope.sealJson(body, targetTopic, fixedMid);
175
+ if (!sealed || pool.isClosed())
244
176
  return;
245
- const frame = buildPublish(targetTopic, payload);
246
- for (const ws of targetSockets ?? readySockets) {
177
+ const frame = buildPublish(targetTopic, sealed.bytes);
178
+ for (const ws of targetSockets ?? pool.readySockets) {
247
179
  if (ws.readyState === wsOpen) {
248
180
  try {
249
181
  ws.send(frame);
@@ -254,365 +186,168 @@ export function mqttSignaling(options = {}) {
254
186
  }
255
187
  }
256
188
  };
257
- const handlePayload = async (msgTopic, raw) => {
258
- if (closed)
189
+ const handlePayload = (msgTopic, raw) => {
190
+ if (pool.isClosed())
259
191
  return;
260
- let key;
261
- try {
262
- key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
263
- }
264
- catch {
192
+ if (!envelope.isEncrypted) {
193
+ const data = envelope.parsePlaintext(raw);
194
+ if (data)
195
+ presence.dispatch(data);
265
196
  return;
266
197
  }
267
- if (closed)
268
- return;
269
- let plain;
198
+ void envelope.openEncrypted(raw, msgTopic, { isClosed: pool.isClosed }).then((data) => {
199
+ if (data && !pool.isClosed())
200
+ presence.dispatch(data);
201
+ });
202
+ };
203
+ const shutdownSocket = (ws, byeFrame) => {
270
204
  try {
271
- plain = key ? await openPayload(key, raw, msgTopic) : raw;
272
- }
273
- catch {
274
- plain = null;
275
- }
276
- if (closed)
277
- return;
278
- 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
- }
205
+ if (ws.readyState === wsOpen) {
206
+ if (byeFrame)
207
+ ws.send(byeFrame);
208
+ ws.send(disconnectPkt);
285
209
  }
286
- return;
287
- }
288
- let data = null;
289
- try {
290
- data = JSON.parse(decoder.decode(plain));
210
+ ws.close();
291
211
  }
292
212
  catch {
293
- return;
213
+ // Ignore shutdown errors.
294
214
  }
295
- if (!data || !isUuid(data.from) || data.from === discovery.self)
296
- return;
297
- if (data.to !== undefined && data.to !== discovery.self)
298
- return;
299
- if (key) {
300
- const check = replayGuard.checkAuthenticated(data.from, data);
301
- 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)');
215
+ };
216
+ const pool = createRelayPool({
217
+ discovery,
218
+ urls,
219
+ handshakeTimeoutMs,
220
+ offlineReason: 'All MQTT relays disconnected',
221
+ envelope,
222
+ privateTopic,
223
+ createSocket(url) {
224
+ const ws = new WsCtor(url, ['mqtt']);
225
+ ws.binaryType = 'arraybuffer';
226
+ return ws;
227
+ },
228
+ attachSocket(ws, controls) {
229
+ let buffer = new Uint8Array(0);
230
+ let pingTimer;
231
+ let awaitingPong = false;
232
+ let subscribed = false;
233
+ const sendFrame = (frame) => {
234
+ try {
235
+ ws.send(frame);
306
236
  }
307
- return;
308
- }
309
- if (check !== 'ok')
310
- return;
311
- }
312
- else {
313
- 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))
317
- 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);
237
+ catch {
238
+ controls.abort();
339
239
  }
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
- }
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))
419
- 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)
240
+ };
241
+ ws.onopen = () => {
242
+ if (pool.isClosed()) {
243
+ controls.abort();
244
+ return;
245
+ }
246
+ const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
247
+ sendFrame(buildConnect(clientId));
248
+ };
249
+ ws.onmessage = ({ data }) => {
250
+ if (pool.isClosed() || !(data instanceof ArrayBuffer))
251
+ return;
252
+ if (buffer.length + data.byteLength > maxMqttBuffer) {
253
+ controls.abort();
254
+ return;
255
+ }
256
+ buffer = concatBytes(buffer, new Uint8Array(data));
257
+ buffer = parseMqttFrames(buffer, {
258
+ onConnAck(code) {
259
+ if (pool.isClosed())
455
260
  return;
456
- if (awaitingPong) {
457
- abortSocket();
261
+ if (code !== 0) {
262
+ controls.abort();
458
263
  return;
459
264
  }
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);
265
+ const id = nextPacketId;
266
+ nextPacketId = (nextPacketId % 65535) + 1;
267
+ sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
268
+ },
269
+ onSubAck(codes) {
270
+ if (pool.isClosed() || subscribed)
271
+ return;
272
+ if (codes.length < 2 || codes.some((c) => c === 0x80)) {
273
+ controls.abort();
274
+ return;
275
+ }
276
+ subscribed = true;
277
+ controls.markReady();
278
+ pingTimer = setInterval(() => {
279
+ if (ws.readyState !== wsOpen)
280
+ return;
281
+ if (awaitingPong) {
282
+ controls.abort();
283
+ return;
284
+ }
285
+ awaitingPong = true;
286
+ sendFrame(pingReq);
287
+ }, 20_000);
288
+ },
289
+ onPingResp() {
290
+ awaitingPong = false;
291
+ },
292
+ onPublish(msg) {
293
+ if (!subscribed)
294
+ return;
295
+ if (msg.topic === roomTopic || msg.topic === inboxTopic) {
296
+ handlePayload(msg.topic, msg.payload);
297
+ }
298
+ },
299
+ onError() {
300
+ controls.abort();
472
301
  }
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
- }
492
- }
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;
302
+ });
303
+ };
304
+ return () => {
305
+ if (pingTimer)
306
+ clearInterval(pingTimer);
307
+ };
308
+ },
309
+ onReady(ws, isInitial) {
310
+ void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
311
+ },
312
+ onPrivateKeys(keys) {
504
313
  roomTopic = 'meshpost/1/p/' + keys.privateId;
505
314
  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;
315
+ },
316
+ onSweep(now, hasReadySockets) {
317
+ presence.prune(now);
318
+ envelope.prune(now);
319
+ if (hasReadySockets)
320
+ void publishRaw({ type: 'heartbeat' });
321
+ },
322
+ sendSignal(to, signal) {
550
323
  void publishRaw({ type: 'signal', to, signal });
551
- return true;
552
324
  },
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) => {
566
- try {
567
- if (ws.readyState === wsOpen) {
568
- if (byeFrame)
569
- ws.send(byeFrame);
570
- ws.send(disconnectPkt);
571
- }
572
- ws.close();
573
- }
574
- catch {
575
- // Ignore shutdown errors.
576
- }
577
- };
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);
588
- }
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);
609
- });
610
- }
611
- else {
612
- for (const ws of socketsToClose)
325
+ onClose(allSockets, readySockets) {
326
+ const readySet = new Set(readySockets);
327
+ for (const ws of allSockets) {
328
+ if (!readySet.has(ws))
613
329
  shutdownSocket(ws);
614
330
  }
331
+ envelope.flushBye({
332
+ aad: roomTopic || undefined,
333
+ hasReadyTargets: readySockets.length > 0,
334
+ onPlain(byeJson) {
335
+ const frame = roomTopic ? buildPublish(roomTopic, encoder.encode(byeJson)) : undefined;
336
+ for (const ws of readySockets)
337
+ shutdownSocket(ws, frame);
338
+ },
339
+ onEncrypted(boxed) {
340
+ const frame = roomTopic ? buildPublish(roomTopic, boxed) : undefined;
341
+ for (const ws of readySockets)
342
+ shutdownSocket(ws, frame);
343
+ },
344
+ onDoneNoBye() {
345
+ for (const ws of readySockets)
346
+ shutdownSocket(ws);
347
+ }
348
+ });
615
349
  }
616
- };
350
+ });
351
+ return pool.session;
617
352
  };
618
353
  }