@dimchansky/meshpost 0.6.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.
package/dist/blob.js CHANGED
@@ -1,27 +1,31 @@
1
1
  import { createChannel } from './channel.js';
2
2
  import { bindAbort, createListeners, reportAsyncError } from './listeners.js';
3
- import { isRoomClosed, onRoomClose } from './room.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
4
4
  const opStart = 0x01;
5
5
  const opData = 0x02;
6
6
  const opAbort = 0x03;
7
7
  const startHeaderBytes = 9;
8
8
  const dataHeaderBytes = 5;
9
9
  const abortFrameBytes = 5;
10
- const maxPacketBytes = 16 * 1024;
11
10
  const maxUint32 = 0xffff_ffff;
12
11
  const defaultMaxReceiveBytes = 4 * 1024 * 1024;
13
12
  const defaultChunkSize = 15 * 1024;
14
13
  const defaultReceiveTimeoutMs = 30_000;
15
14
  const defaultMaxConcurrentPerPeer = 4;
16
- const encoder = new TextEncoder();
17
15
  /**
18
16
  * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
19
17
  * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
20
18
  */
21
19
  export function createBlobChannel(room, name, options = {}) {
20
+ if (!room ||
21
+ typeof room !== 'object' ||
22
+ typeof room.onDrain !== 'function' ||
23
+ typeof room.onPeerLeave !== 'function' ||
24
+ !Array.isArray(room.peers)) {
25
+ throw new TypeError('Invalid room');
26
+ }
22
27
  const channel = createChannel(room, name, { delivery: 'reliable' });
23
- const nameBytesLen = encoder.encode(name).length;
24
- const maxAllowedChunk = maxPacketBytes - (1 + nameBytesLen) - startHeaderBytes;
28
+ const maxAllowedChunk = channel.maxPayloadBytes - startHeaderBytes;
25
29
  const maxReceiveBytes = options.maxReceiveBytes ?? defaultMaxReceiveBytes;
26
30
  if (!Number.isSafeInteger(maxReceiveBytes) || maxReceiveBytes < 0 || maxReceiveBytes > maxUint32)
27
31
  throw new RangeError('Invalid maxReceiveBytes');
@@ -42,10 +46,19 @@ export function createBlobChannel(room, name, options = {}) {
42
46
  const progresses = createListeners();
43
47
  const incoming = new Map();
44
48
  const closeWaiters = new Set();
45
- const internalAbort = new AbortController();
46
49
  let nextTransferId = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x7fff_ffff) + 1;
47
- let closed = isRoomClosed(room);
48
- let offRoomClose;
50
+ const lifecycle = bindRoomLifecycle(room, () => {
51
+ for (const byPeer of incoming.values()) {
52
+ for (const entry of byPeer.values())
53
+ clearTimeout(entry.timer);
54
+ }
55
+ incoming.clear();
56
+ for (const wake of [...closeWaiters])
57
+ wake();
58
+ closeWaiters.clear();
59
+ blobs.clear();
60
+ progresses.clear();
61
+ });
49
62
  const dropTransfer = (peerId, transferId) => {
50
63
  const byPeer = incoming.get(peerId);
51
64
  const entry = byPeer?.get(transferId);
@@ -64,24 +77,6 @@ export function createBlobChannel(room, name, options = {}) {
64
77
  clearTimeout(entry.timer);
65
78
  incoming.delete(peerId);
66
79
  };
67
- const shutdown = () => {
68
- if (closed)
69
- return;
70
- closed = true;
71
- offRoomClose?.();
72
- offRoomClose = undefined;
73
- internalAbort.abort();
74
- for (const byPeer of incoming.values()) {
75
- for (const entry of byPeer.values())
76
- clearTimeout(entry.timer);
77
- }
78
- incoming.clear();
79
- for (const wake of [...closeWaiters])
80
- wake();
81
- closeWaiters.clear();
82
- blobs.clear();
83
- progresses.clear();
84
- };
85
80
  const sendAbort = (peerId, transferId) => {
86
81
  if (isRoomClosed(room))
87
82
  return;
@@ -97,7 +92,7 @@ export function createBlobChannel(room, name, options = {}) {
97
92
  }
98
93
  };
99
94
  const waitForDrain = (peerId, signal) => new Promise((resolve) => {
100
- if (closed || signal?.aborted) {
95
+ if (lifecycle.isClosed() || signal?.aborted) {
101
96
  resolve('abort');
102
97
  return;
103
98
  }
@@ -126,13 +121,17 @@ export function createBlobChannel(room, name, options = {}) {
126
121
  done('drain');
127
122
  }, { signal: ctrl.signal });
128
123
  room.onPeerLeave((id) => {
124
+ if (isRoomClosed(room)) {
125
+ lifecycle.close();
126
+ return;
127
+ }
129
128
  if (id === peerId)
130
129
  done('unavailable');
131
130
  }, { signal: ctrl.signal });
132
131
  });
133
132
  const sendToPeer = async (peerId, bytes, options) => {
134
133
  const { onProgress, signal } = options;
135
- if (closed || signal?.aborted)
134
+ if (lifecycle.isClosed() || signal?.aborted)
136
135
  return 'aborted';
137
136
  if (isRoomClosed(room))
138
137
  return 'unavailable';
@@ -143,7 +142,7 @@ export function createBlobChannel(room, name, options = {}) {
143
142
  let offset = 0;
144
143
  let started = false;
145
144
  while (true) {
146
- if (closed || signal?.aborted) {
145
+ if (lifecycle.isClosed() || signal?.aborted) {
147
146
  if (started)
148
147
  sendAbort(peerId, transferId);
149
148
  return 'aborted';
@@ -201,12 +200,11 @@ export function createBlobChannel(room, name, options = {}) {
201
200
  }
202
201
  }
203
202
  };
204
- if (!closed) {
205
- const internalListen = { signal: internalAbort.signal };
206
- offRoomClose = onRoomClose(room, shutdown);
203
+ if (!lifecycle.isClosed()) {
204
+ const internalListen = { signal: lifecycle.signal };
207
205
  room.onPeerLeave((peerId) => dropPeerTransfers(peerId), internalListen);
208
206
  channel.onPacket((from, bytes) => {
209
- if (closed || bytes.byteLength < abortFrameBytes)
207
+ if (lifecycle.isClosed() || bytes.byteLength < abortFrameBytes)
210
208
  return;
211
209
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
212
210
  const op = bytes[0];
@@ -289,7 +287,7 @@ export function createBlobChannel(room, name, options = {}) {
289
287
  receivedBytes: entry.receivedBytes,
290
288
  totalBytes: entry.totalBytes
291
289
  });
292
- if (closed || byPeer?.get(transferId) !== entry)
290
+ if (lifecycle.isClosed() || byPeer?.get(transferId) !== entry)
293
291
  return;
294
292
  if (entry.receivedBytes === entry.totalBytes) {
295
293
  dropTransfer(from, transferId);
@@ -304,8 +302,10 @@ export function createBlobChannel(room, name, options = {}) {
304
302
  return {
305
303
  name,
306
304
  async send(bytes, sendOptions = {}) {
307
- if (closed || isRoomClosed(room))
305
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
306
+ lifecycle.close();
308
307
  throw new Error('BlobChannel is closed');
308
+ }
309
309
  if (!(bytes instanceof Uint8Array))
310
310
  throw new TypeError('Expected a Uint8Array');
311
311
  const targets = sendOptions.to === undefined ? [...room.peers] : [sendOptions.to];
@@ -319,6 +319,6 @@ export function createBlobChannel(room, name, options = {}) {
319
319
  },
320
320
  onBlob: blobs.add,
321
321
  onProgress: progresses.add,
322
- close: shutdown
322
+ close: lifecycle.close
323
323
  };
324
324
  }
package/dist/channel.d.ts CHANGED
@@ -13,6 +13,8 @@ export interface Channel {
13
13
  readonly name: string;
14
14
  /** Delivery mode configured for this channel. */
15
15
  readonly delivery: Delivery;
16
+ /** Maximum usable payload bytes per packet on this channel (`16384 - 1 - utf8(name).length`). */
17
+ readonly maxPayloadBytes: number;
16
18
  /** Send a binary packet on this named channel synchronously. Returns a per-recipient result map. */
17
19
  send(bytes: Uint8Array, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
18
20
  /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
@@ -31,6 +33,8 @@ export interface CodecChannel<T> {
31
33
  readonly name: string;
32
34
  /** Delivery mode configured for this channel. */
33
35
  readonly delivery: Delivery;
36
+ /** Maximum usable encoded payload bytes per packet on this channel (`16384 - 1 - utf8(name).length`). */
37
+ readonly maxPayloadBytes: number;
34
38
  /** Encode and send a typed value synchronously. Returns a per-recipient result map. */
35
39
  send(value: T, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
36
40
  /** Subscribe to decoded, validated values on this channel. Malformed incoming frames are ignored. */
package/dist/channel.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createListeners } from './listeners.js';
2
+ import { maxPacketBytes } from './peer-link.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  const encoder = new TextEncoder();
4
5
  const strictDecoder = new TextDecoder('utf-8', { fatal: true });
@@ -176,10 +177,12 @@ export function createChannel(room, name, options = {}) {
176
177
  const prefix = new Uint8Array(1 + nameBytes.length);
177
178
  prefix[0] = nameBytes.length;
178
179
  prefix.set(nameBytes, 1);
180
+ const maxPayloadBytes = maxPacketBytes - prefix.length;
179
181
  const router = getRouter(room);
180
182
  return {
181
183
  name,
182
184
  delivery,
185
+ maxPayloadBytes,
183
186
  send(bytes, sendOptions = {}) {
184
187
  if (!(bytes instanceof Uint8Array))
185
188
  throw new TypeError('Expected a Uint8Array');
@@ -205,6 +208,7 @@ export function createCodecChannel(room, name, codec, options = {}) {
205
208
  return {
206
209
  name: channel.name,
207
210
  delivery: channel.delivery,
211
+ maxPayloadBytes: channel.maxPayloadBytes,
208
212
  send(value, sendOptions = {}) {
209
213
  const bytes = codec.encode(value);
210
214
  if (!(bytes instanceof Uint8Array)) {
package/dist/combine.d.ts CHANGED
@@ -1,10 +1,17 @@
1
- import type { Signaling } from './signaling.js';
1
+ import { type Signaling, type SignalingState } from './signaling.js';
2
2
  /**
3
3
  * Combine multiple signaling adapters into one composite adapter.
4
4
  * Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
5
5
  * and stays `'online'` as long as at least one child adapter is `'online'`.
6
6
  */
7
7
  export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
8
+ export interface WithLocalTabsOptions {
9
+ /**
10
+ * Optional observer invoked whenever the internal same-browser `tabSignaling()` adapter
11
+ * changes `SignalingState` (skipped when `BroadcastChannel` is unavailable or blocked).
12
+ */
13
+ onTabsState?: (state: SignalingState, reason?: string) => void;
14
+ }
8
15
  /**
9
16
  * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
10
17
  * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
@@ -15,4 +22,4 @@ export declare function combineSignaling(...adapters: readonly Signaling[]): Sig
15
22
  * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
16
23
  * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
17
24
  */
18
- export declare function withLocalTabs(primary: Signaling): Signaling;
25
+ export declare function withLocalTabs(primary: Signaling, options?: WithLocalTabsOptions): Signaling;
package/dist/combine.js CHANGED
@@ -1,8 +1,9 @@
1
+ import { createErrorThrottle } from './presence.js';
2
+ import { observeSignaling } from './signaling.js';
1
3
  import { tabSignaling } from './tabs.js';
2
4
  const maxSeenIcePeers = 256;
3
5
  const maxSeenIceAttemptsPerPeer = 4;
4
6
  const maxSeenIceKeysPerAttempt = 64;
5
- const compositeErrorCooldownMs = 15_000;
6
7
  function iceCandidateKey(item) {
7
8
  return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
8
9
  }
@@ -34,10 +35,15 @@ function createCompositeSession(discovery, list, primaryIndex) {
34
35
  let closed = false;
35
36
  let aggState = 'connecting';
36
37
  let lastReason;
37
- let lastDecryptErrorAt = -Infinity;
38
- let lastClockSkewErrorAt = -Infinity;
39
38
  let publishedRoster = new Set();
40
39
  let rosterDirty = false;
40
+ const emitThrottledError = createErrorThrottle((code, message) => {
41
+ if (initializing) {
42
+ buffered.push({ kind: 'error', code, message });
43
+ return;
44
+ }
45
+ discovery.error?.(code, message);
46
+ });
41
47
  const computeAggregateState = () => {
42
48
  if (primaryIndex !== null) {
43
49
  return children[primaryIndex].state;
@@ -188,17 +194,9 @@ function createCompositeSession(discovery, list, primaryIndex) {
188
194
  return;
189
195
  if (primaryIndex !== null && index !== primaryIndex)
190
196
  return;
191
- if (code === 'decrypt-failed') {
192
- const now = Date.now();
193
- if (now - lastDecryptErrorAt < compositeErrorCooldownMs)
194
- return;
195
- lastDecryptErrorAt = now;
196
- }
197
- else if (code === 'clock-skew') {
198
- const now = Date.now();
199
- if (now - lastClockSkewErrorAt < compositeErrorCooldownMs)
200
- return;
201
- lastClockSkewErrorAt = now;
197
+ if (code === 'decrypt-failed' || code === 'clock-skew') {
198
+ emitThrottledError(code, message);
199
+ return;
202
200
  }
203
201
  if (initializing) {
204
202
  buffered.push({ kind: 'error', code, message });
@@ -304,8 +302,28 @@ function canUseLocalTabs() {
304
302
  }
305
303
  return true;
306
304
  }
307
- /** @internal */
308
- export function withLocalTabsInternal(primary, wrapTabs) {
305
+ /**
306
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
307
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
308
+ *
309
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
310
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
311
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
312
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
313
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
314
+ */
315
+ export function withLocalTabs(primary, options) {
316
+ if (typeof primary !== 'function') {
317
+ throw new TypeError('Expected a signaling adapter function');
318
+ }
319
+ if (options !== undefined &&
320
+ (!options || typeof options !== 'object' || Array.isArray(options))) {
321
+ throw new TypeError('Invalid withLocalTabs options');
322
+ }
323
+ const onTabsState = options?.onTabsState;
324
+ if (onTabsState !== undefined && typeof onTabsState !== 'function') {
325
+ throw new TypeError('Expected onTabsState to be a function');
326
+ }
309
327
  return (discovery) => {
310
328
  if (!canUseLocalTabs())
311
329
  return primary(discovery);
@@ -319,23 +337,7 @@ export function withLocalTabsInternal(primary, wrapTabs) {
319
337
  return primary(discovery);
320
338
  }
321
339
  const baseTabs = tabSignaling();
322
- const tabs = wrapTabs ? wrapTabs(baseTabs) : baseTabs;
340
+ const tabs = onTabsState ? observeSignaling(baseTabs, onTabsState) : baseTabs;
323
341
  return createCompositeSession(discovery, [tabs, primary], 1);
324
342
  };
325
343
  }
326
- /**
327
- * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
328
- * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
329
- *
330
- * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
331
- * (avoiding a permanently `'online'` indicator when network connectivity is lost).
332
- * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
333
- * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
334
- * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
335
- */
336
- export function withLocalTabs(primary) {
337
- if (typeof primary !== 'function') {
338
- throw new TypeError('Expected a signaling adapter function');
339
- }
340
- return withLocalTabsInternal(primary);
341
- }
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export type { PeerState, PeerStateChangeReason, PeerStateOptions } from './state
11
11
  export { createBlobChannel } from './blob.js';
12
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
13
13
  export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
14
- export type { AudioInputDevice, AudioInputsChangeOptions, MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
14
+ export type { AudioInputDevice, AudioInputsChangeOptions, MicError, MicErrorCode, MicStatus, MicStopReason, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
15
15
  export { fetchTurnCredentials } from './turn.js';
16
16
  export type { FetchTurnOptions } from './turn.js';
17
17
  export { tabSignaling } from './tabs.js';
@@ -26,5 +26,6 @@ export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
26
26
  export { publicSignaling } from './public.js';
27
27
  export type { PublicSignalingOptions, PublicTransportEvent, PublicTransportKind } from './public.js';
28
28
  export { combineSignaling, withLocalTabs } from './combine.js';
29
+ export type { WithLocalTabsOptions } from './combine.js';
29
30
  export { isSignal, isUuid, observeSignaling, withLoopbackFallback } from './signaling.js';
30
31
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/mqtt.js CHANGED
@@ -1,6 +1,6 @@
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';
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';
4
4
  /** Built-in public MQTT-over-WebSocket relay URLs used by default. */
5
5
  export const defaultMqttRelays = Object.freeze([
6
6
  'wss://broker.emqx.io:8084/mqtt',
@@ -147,42 +147,23 @@ export function mqttSignaling(options = {}) {
147
147
  const urls = rawUrls.map((u) => normalizeWsRelayUrl(u, 'Invalid MQTT relay URL', 'MQTT relay URL must use ws: or wss:'));
148
148
  const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultMqttHandshakeTimeoutMs;
149
149
  validatePositiveTimeout(handshakeTimeoutMs, 'Invalid MQTT handshake timeout');
150
- if (options.password !== undefined &&
151
- (typeof options.password !== 'string' || options.password.length === 0)) {
152
- throw new TypeError('Invalid password');
153
- }
154
- if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
155
- throw new TypeError('Invalid privateTopic option');
156
- }
157
- if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
158
- throw new TypeError('Invalid WebSocket constructor');
159
- }
150
+ validateCommonSignalingOptions(options);
160
151
  return (discovery) => {
161
- const WsCtor = options.WebSocket ?? globalThis.WebSocket;
162
- if (typeof WsCtor !== 'function') {
163
- throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
164
- }
152
+ const WsCtor = resolveSessionWebSocket(options.WebSocket);
165
153
  const appId = options.appId ?? discovery.appId;
166
- const password = options.password ?? discovery.password;
167
154
  const privateTopic = options.privateTopic ?? false;
168
- if (privateTopic && password === undefined) {
169
- throw new TypeError('privateTopic requires a room password');
170
- }
171
- if (password !== undefined) {
172
- if (typeof password !== 'string' || password.length === 0) {
173
- throw new TypeError('Invalid password');
174
- }
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 replayGuard = createReplayGuard();
184
- const emitError = createErrorThrottle(discovery);
185
160
  let nextPacketId = 1;
161
+ const envelope = createRelayEnvelope({
162
+ discovery,
163
+ password,
164
+ baseScope,
165
+ transportLabel: 'MQTT'
166
+ });
186
167
  const presence = createPresenceTracker(discovery, (to) => {
187
168
  void publishRaw({ type: 'present', to });
188
169
  });
@@ -190,19 +171,10 @@ export function mqttSignaling(options = {}) {
190
171
  if (pool.isClosed() || !roomTopic)
191
172
  return;
192
173
  const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
193
- const mid = fixedMid ?? pool.nextMid();
194
- const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
195
- let payload;
196
- try {
197
- const key = await pool.getKey();
198
- payload = key ? await sealPayload(key, plain, targetTopic) : plain;
199
- }
200
- catch {
201
- return;
202
- }
203
- if (pool.isClosed())
174
+ const sealed = await envelope.sealJson(body, targetTopic, fixedMid);
175
+ if (!sealed || pool.isClosed())
204
176
  return;
205
- const frame = buildPublish(targetTopic, payload);
177
+ const frame = buildPublish(targetTopic, sealed.bytes);
206
178
  for (const ws of targetSockets ?? pool.readySockets) {
207
179
  if (ws.readyState === wsOpen) {
208
180
  try {
@@ -214,71 +186,40 @@ export function mqttSignaling(options = {}) {
214
186
  }
215
187
  }
216
188
  };
217
- const handlePayload = async (msgTopic, raw) => {
189
+ const handlePayload = (msgTopic, raw) => {
218
190
  if (pool.isClosed())
219
191
  return;
220
- let key;
221
- try {
222
- key = await pool.getKey();
223
- }
224
- catch {
192
+ if (!envelope.isEncrypted) {
193
+ const data = envelope.parsePlaintext(raw);
194
+ if (data)
195
+ presence.dispatch(data);
225
196
  return;
226
197
  }
227
- if (pool.isClosed())
228
- return;
229
- let plain;
230
- try {
231
- plain = key ? await openPayload(key, raw, msgTopic) : raw;
232
- }
233
- catch {
234
- plain = null;
235
- }
236
- if (pool.isClosed())
237
- return;
238
- if (!plain) {
239
- if (key)
240
- emitError('decrypt-failed', 'Failed to decrypt MQTT signaling message');
241
- return;
242
- }
243
- let data = null;
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) => {
244
204
  try {
245
- data = JSON.parse(decoder.decode(plain));
246
- }
247
- catch {
248
- return;
249
- }
250
- if (!data || !isUuid(data.from) || data.from === discovery.self)
251
- return;
252
- if (data.to !== undefined && data.to !== discovery.self)
253
- return;
254
- if (key) {
255
- const check = replayGuard.checkAuthenticated(data.from, data);
256
- if (check === 'clock-skew') {
257
- emitError('clock-skew', 'MQTT signaling message rejected due to system clock skew (>60s)');
258
- return;
205
+ if (ws.readyState === wsOpen) {
206
+ if (byeFrame)
207
+ ws.send(byeFrame);
208
+ ws.send(disconnectPkt);
259
209
  }
260
- if (check !== 'ok')
261
- return;
210
+ ws.close();
262
211
  }
263
- else {
264
- if (data.mid !== undefined &&
265
- (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength)) {
266
- return;
267
- }
268
- if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid)) {
269
- return;
270
- }
212
+ catch {
213
+ // Ignore shutdown errors.
271
214
  }
272
- presence.dispatch(data);
273
215
  };
274
216
  const pool = createRelayPool({
275
217
  discovery,
276
218
  urls,
277
219
  handshakeTimeoutMs,
278
220
  offlineReason: 'All MQTT relays disconnected',
279
- password,
221
+ envelope,
280
222
  privateTopic,
281
- baseScope,
282
223
  createSocket(url) {
283
224
  const ws = new WsCtor(url, ['mqtt']);
284
225
  ws.binaryType = 'arraybuffer';
@@ -352,7 +293,7 @@ export function mqttSignaling(options = {}) {
352
293
  if (!subscribed)
353
294
  return;
354
295
  if (msg.topic === roomTopic || msg.topic === inboxTopic) {
355
- void handlePayload(msg.topic, msg.payload);
296
+ handlePayload(msg.topic, msg.payload);
356
297
  }
357
298
  },
358
299
  onError() {
@@ -374,28 +315,37 @@ export function mqttSignaling(options = {}) {
374
315
  },
375
316
  onSweep(now, hasReadySockets) {
376
317
  presence.prune(now);
377
- replayGuard.prune(now);
318
+ envelope.prune(now);
378
319
  if (hasReadySockets)
379
320
  void publishRaw({ type: 'heartbeat' });
380
321
  },
381
322
  sendSignal(to, signal) {
382
323
  void publishRaw({ type: 'signal', to, signal });
383
324
  },
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();
395
- }
396
- catch {
397
- // Ignore shutdown errors.
325
+ onClose(allSockets, readySockets) {
326
+ const readySet = new Set(readySockets);
327
+ for (const ws of allSockets) {
328
+ if (!readySet.has(ws))
329
+ shutdownSocket(ws);
398
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
+ });
399
349
  }
400
350
  });
401
351
  return pool.session;