@dimchansky/meshpost 0.1.0 → 0.3.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.
@@ -0,0 +1,340 @@
1
+ import { tabSignaling } from './tabs.js';
2
+ const maxSeenIcePeers = 256;
3
+ const maxSeenIceAttemptsPerPeer = 4;
4
+ const maxSeenIceKeysPerAttempt = 64;
5
+ function iceCandidateKey(item) {
6
+ return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
7
+ }
8
+ function setsEqual(a, b) {
9
+ if (a.size !== b.size)
10
+ return false;
11
+ for (const item of a) {
12
+ if (!b.has(item))
13
+ return false;
14
+ }
15
+ return true;
16
+ }
17
+ function childCanReach(child, peerId) {
18
+ if (!child.peers.has(peerId) || !child.session)
19
+ return false;
20
+ if (typeof child.session.canReach === 'function') {
21
+ return child.session.canReach(peerId);
22
+ }
23
+ return child.state === 'online';
24
+ }
25
+ function createCompositeSession(discovery, list, primaryIndex) {
26
+ const children = list.map(() => ({
27
+ state: 'connecting',
28
+ peers: new Set()
29
+ }));
30
+ const buffered = [];
31
+ const seenIce = new Map();
32
+ let initializing = true;
33
+ let closed = false;
34
+ let aggState = 'connecting';
35
+ let lastReason;
36
+ let publishedRoster = new Set();
37
+ let rosterDirty = false;
38
+ const computeAggregateState = () => {
39
+ if (primaryIndex !== null) {
40
+ return children[primaryIndex].state;
41
+ }
42
+ let hasConnecting = false;
43
+ let hasOffline = false;
44
+ for (const child of children) {
45
+ if (child.state === 'online')
46
+ return 'online';
47
+ if (child.state === 'connecting')
48
+ hasConnecting = true;
49
+ else if (child.state === 'offline')
50
+ hasOffline = true;
51
+ }
52
+ if (hasConnecting)
53
+ return 'connecting';
54
+ if (hasOffline)
55
+ return 'offline';
56
+ return 'closed';
57
+ };
58
+ const syncState = (reason) => {
59
+ if (closed)
60
+ return;
61
+ const next = computeAggregateState();
62
+ if (next === aggState)
63
+ return;
64
+ aggState = next;
65
+ lastReason = reason;
66
+ if (!initializing)
67
+ discovery.status(next, reason);
68
+ };
69
+ const computeUnion = () => {
70
+ const union = new Set();
71
+ for (const child of children) {
72
+ for (const id of child.peers) {
73
+ if (child.session ? childCanReach(child, id) : child.state === 'online') {
74
+ union.add(id);
75
+ }
76
+ }
77
+ }
78
+ return union;
79
+ };
80
+ const syncRoster = () => {
81
+ if (closed)
82
+ return;
83
+ if (initializing) {
84
+ rosterDirty = true;
85
+ return;
86
+ }
87
+ const union = computeUnion();
88
+ if (setsEqual(union, publishedRoster))
89
+ return;
90
+ publishedRoster = union;
91
+ discovery.roster([...union]);
92
+ };
93
+ const dedupeIceSignal = (from, signal) => {
94
+ if (signal.kind !== 'ice')
95
+ return signal;
96
+ let byAttempt = seenIce.get(from);
97
+ if (!byAttempt) {
98
+ if (seenIce.size >= maxSeenIcePeers) {
99
+ const oldestPeer = seenIce.keys().next().value;
100
+ if (oldestPeer !== undefined)
101
+ seenIce.delete(oldestPeer);
102
+ }
103
+ byAttempt = new Map();
104
+ }
105
+ seenIce.delete(from);
106
+ seenIce.set(from, byAttempt);
107
+ let keys = byAttempt.get(signal.attempt);
108
+ if (!keys) {
109
+ if (byAttempt.size >= maxSeenIceAttemptsPerPeer) {
110
+ const oldestAttempt = byAttempt.keys().next().value;
111
+ if (oldestAttempt !== undefined)
112
+ byAttempt.delete(oldestAttempt);
113
+ }
114
+ keys = new Set();
115
+ }
116
+ byAttempt.delete(signal.attempt);
117
+ byAttempt.set(signal.attempt, keys);
118
+ const fresh = [];
119
+ for (const item of signal.candidates) {
120
+ const key = iceCandidateKey(item);
121
+ if (keys.has(key))
122
+ continue;
123
+ if (keys.size < maxSeenIceKeysPerAttempt)
124
+ keys.add(key);
125
+ fresh.push(item);
126
+ }
127
+ return fresh.length > 0 ? { ...signal, candidates: fresh } : null;
128
+ };
129
+ const closeAll = () => {
130
+ seenIce.clear();
131
+ for (const child of children) {
132
+ try {
133
+ child.session?.close();
134
+ }
135
+ catch {
136
+ // Ensure one failing child close does not leak sibling sessions.
137
+ }
138
+ delete child.session;
139
+ }
140
+ };
141
+ const makeChildDiscovery = (index, child) => ({
142
+ appId: discovery.appId,
143
+ room: discovery.room,
144
+ self: discovery.self,
145
+ ...(discovery.password !== undefined ? { password: discovery.password } : {}),
146
+ status(next, reason) {
147
+ if (closed || next === child.state)
148
+ return;
149
+ child.state = next;
150
+ if (next === 'closed') {
151
+ if (child.peers.size > 0) {
152
+ child.peers.clear();
153
+ syncRoster();
154
+ }
155
+ }
156
+ else if (next === 'offline') {
157
+ if (typeof child.session?.canReach === 'function') {
158
+ let removed = false;
159
+ for (const id of [...child.peers]) {
160
+ if (!child.session.canReach(id)) {
161
+ child.peers.delete(id);
162
+ removed = true;
163
+ }
164
+ }
165
+ if (removed)
166
+ syncRoster();
167
+ }
168
+ else if (child.peers.size > 0) {
169
+ child.peers.clear();
170
+ syncRoster();
171
+ }
172
+ }
173
+ else if (next === 'online' && child.peers.size > 0) {
174
+ syncRoster();
175
+ }
176
+ if (primaryIndex === null || index === primaryIndex) {
177
+ syncState(reason);
178
+ }
179
+ },
180
+ roster(ids) {
181
+ if (closed)
182
+ return;
183
+ child.peers = new Set(ids);
184
+ syncRoster();
185
+ },
186
+ receive(from, signal) {
187
+ if (closed)
188
+ return;
189
+ if (!child.peers.has(from)) {
190
+ child.peers.add(from);
191
+ syncRoster();
192
+ }
193
+ const deduped = dedupeIceSignal(from, signal);
194
+ if (!deduped)
195
+ return;
196
+ if (initializing) {
197
+ buffered.push({ kind: 'receive', from, signal: deduped });
198
+ return;
199
+ }
200
+ discovery.receive(from, deduped);
201
+ },
202
+ error(code, message) {
203
+ if (closed)
204
+ return;
205
+ if (primaryIndex !== null && index !== primaryIndex)
206
+ return;
207
+ if (initializing) {
208
+ buffered.push({ kind: 'error', code, message });
209
+ return;
210
+ }
211
+ discovery.error?.(code, message);
212
+ }
213
+ });
214
+ try {
215
+ for (let i = 0; i < list.length; i++) {
216
+ const child = children[i];
217
+ const adapter = list[i];
218
+ child.session = adapter(makeChildDiscovery(i, child));
219
+ if (child.peers.size > 0)
220
+ rosterDirty = true;
221
+ }
222
+ }
223
+ catch (error) {
224
+ closed = true;
225
+ closeAll();
226
+ throw error;
227
+ }
228
+ initializing = false;
229
+ if (!closed) {
230
+ const nextState = computeAggregateState();
231
+ aggState = nextState;
232
+ if (nextState !== 'connecting')
233
+ discovery.status(nextState, lastReason);
234
+ if (rosterDirty) {
235
+ rosterDirty = false;
236
+ const union = computeUnion();
237
+ if (union.size > 0) {
238
+ publishedRoster = union;
239
+ discovery.roster([...union]);
240
+ }
241
+ }
242
+ for (const ev of buffered) {
243
+ if (closed)
244
+ break;
245
+ if (ev.kind === 'receive')
246
+ discovery.receive(ev.from, ev.signal);
247
+ else
248
+ discovery.error?.(ev.code, ev.message);
249
+ }
250
+ buffered.length = 0;
251
+ }
252
+ const trickle = children.every((child) => child.session?.trickle === true);
253
+ return {
254
+ trickle,
255
+ canReach(peerId) {
256
+ if (closed)
257
+ return false;
258
+ for (const child of children) {
259
+ if (childCanReach(child, peerId))
260
+ return true;
261
+ }
262
+ return false;
263
+ },
264
+ send(to, signal) {
265
+ if (closed)
266
+ return false;
267
+ let accepted = false;
268
+ for (const child of children) {
269
+ if (childCanReach(child, to) && child.session) {
270
+ if (child.session.send(to, signal))
271
+ accepted = true;
272
+ }
273
+ }
274
+ return accepted;
275
+ },
276
+ close() {
277
+ if (closed)
278
+ return;
279
+ closed = true;
280
+ closeAll();
281
+ }
282
+ };
283
+ }
284
+ /**
285
+ * Combine multiple signaling adapters into one composite adapter.
286
+ * Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
287
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
288
+ */
289
+ export function combineSignaling(...adapters) {
290
+ if (adapters.length === 0)
291
+ throw new RangeError('At least one signaling adapter is required');
292
+ for (const adapter of adapters) {
293
+ if (typeof adapter !== 'function') {
294
+ throw new TypeError('All signaling adapters must be functions');
295
+ }
296
+ }
297
+ if (adapters.length === 1)
298
+ return adapters[0];
299
+ const list = [...adapters];
300
+ return (discovery) => createCompositeSession(discovery, list, null);
301
+ }
302
+ function canUseLocalTabs() {
303
+ if (typeof BroadcastChannel !== 'function')
304
+ return false;
305
+ if (typeof location !== 'undefined') {
306
+ if (location.protocol === 'file:' || location.origin === 'null')
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+ /**
312
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
313
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
314
+ *
315
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
316
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
317
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
318
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
319
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
320
+ */
321
+ export function withLocalTabs(primary) {
322
+ if (typeof primary !== 'function') {
323
+ throw new TypeError('Expected a signaling adapter function');
324
+ }
325
+ return (discovery) => {
326
+ if (!canUseLocalTabs())
327
+ return primary(discovery);
328
+ // Probe BroadcastChannel construction before starting anything so a synchronous SecurityError
329
+ // falls back cleanly to `primary(discovery)` without creating duplicate sessions.
330
+ try {
331
+ const probe = new BroadcastChannel('meshpost/probe');
332
+ probe.close();
333
+ }
334
+ catch {
335
+ return primary(discovery);
336
+ }
337
+ const tabs = tabSignaling();
338
+ return createCompositeSession(discovery, [tabs, primary], 1);
339
+ };
340
+ }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,20 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export type { Delivery, PeerRoute, PeerStats, Room, RoomOptions, SendOptions, SendResult } from './room.js';
2
+ export type { Delivery, ListenOptions, PeerRoute, PeerStats, Room, RoomError, RoomErrorCode, RoomOptions, SendOptions, SendResult } from './room.js';
3
3
  export { createChannel } from './channel.js';
4
4
  export type { Channel, ChannelOptions, ChannelSendOptions } from './channel.js';
5
+ export { createBlobChannel } from './blob.js';
6
+ export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
7
+ export { createVoice } from './voice.js';
8
+ export type { MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
9
+ export { fetchTurnCredentials } from './turn.js';
10
+ export type { FetchTurnOptions } from './turn.js';
5
11
  export { tabSignaling } from './tabs.js';
6
12
  export { manualSignaling } from './manual.js';
7
13
  export type { ManualSignaling } from './manual.js';
8
14
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
9
15
  export type { MqttSignalingOptions } from './mqtt.js';
16
+ export { wsSignaling } from './ws.js';
17
+ export type { WsSignalingOptions } from './ws.js';
18
+ export { combineSignaling, withLocalTabs } from './combine.js';
10
19
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
11
- export type { Discovery, Signal, Signaling, SignalingSession, SignalingState } from './signaling.js';
20
+ export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,6 +1,11 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
2
  export { createChannel } from './channel.js';
3
+ export { createBlobChannel } from './blob.js';
4
+ export { createVoice } from './voice.js';
5
+ export { fetchTurnCredentials } from './turn.js';
3
6
  export { tabSignaling } from './tabs.js';
4
7
  export { manualSignaling } from './manual.js';
5
8
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
9
+ export { wsSignaling } from './ws.js';
10
+ export { combineSignaling, withLocalTabs } from './combine.js';
6
11
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
package/dist/mqtt.js CHANGED
@@ -10,9 +10,11 @@ const decoder = new TextDecoder();
10
10
  const maxMqttBuffer = 128 * 1024;
11
11
  const maxSeenPeers = 256;
12
12
  const maxSeenMids = 2048;
13
+ const maxMidLength = 64;
13
14
  const replayWindowMs = 60_000;
14
15
  const midTtlMs = replayWindowMs * 2;
15
16
  const defaultMqttHandshakeTimeoutMs = 10_000;
17
+ const decryptErrorCooldownMs = 15_000;
16
18
  function encodeRemainingLength(length) {
17
19
  const bytes = [];
18
20
  let n = length;
@@ -152,7 +154,7 @@ async function sealPayload(key, plain, aad) {
152
154
  return concatBytes(iv, cipher);
153
155
  }
154
156
  async function openPayload(key, boxed, aad) {
155
- if (boxed.length <= 12)
157
+ if (boxed.length < 28)
156
158
  return null;
157
159
  try {
158
160
  const iv = Uint8Array.from(boxed.subarray(0, 12));
@@ -205,6 +207,7 @@ export function mqttSignaling(options = {}) {
205
207
  let initialPending = urls.length;
206
208
  let nextPacketId = 1;
207
209
  let msgSeq = 0;
210
+ let lastDecryptErrorAt = -Infinity;
208
211
  let resolvedKey;
209
212
  const keyPromise = password !== undefined
210
213
  ? deriveKey(password, roomTopic).then((k) => {
@@ -256,7 +259,9 @@ export function mqttSignaling(options = {}) {
256
259
  else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
257
260
  reportedOnline = false;
258
261
  reportedOffline = true;
259
- discovery.status('offline', 'All MQTT relays disconnected');
262
+ const reason = 'All MQTT relays disconnected';
263
+ discovery.status('offline', reason);
264
+ discovery.error?.('signaling-error', reason);
260
265
  }
261
266
  };
262
267
  const publishRaw = async (body, targetSockets, fixedMid) => {
@@ -291,16 +296,33 @@ export function mqttSignaling(options = {}) {
291
296
  if (closed)
292
297
  return;
293
298
  let key;
294
- let plain;
295
299
  try {
296
300
  key = resolvedKey ?? (keyPromise ? await keyPromise : undefined);
297
- plain = key ? await openPayload(key, raw, msgTopic) : raw;
298
301
  }
299
302
  catch {
300
303
  return;
301
304
  }
302
- if (!plain || closed)
305
+ if (closed)
303
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
+ }
304
326
  let data = null;
305
327
  try {
306
328
  data = JSON.parse(decoder.decode(plain));
@@ -312,7 +334,12 @@ export function mqttSignaling(options = {}) {
312
334
  return;
313
335
  if (data.to !== undefined && data.to !== discovery.self)
314
336
  return;
337
+ if (data.mid !== undefined &&
338
+ (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength))
339
+ return;
315
340
  if (key) {
341
+ if (typeof data.mid !== 'string')
342
+ return;
316
343
  if (typeof data.ts !== 'number' || Math.abs(Date.now() - data.ts) > replayWindowMs)
317
344
  return;
318
345
  }
@@ -508,6 +535,7 @@ export function mqttSignaling(options = {}) {
508
535
  connectBroker(url);
509
536
  });
510
537
  return {
538
+ trickle: true,
511
539
  send(to, signal) {
512
540
  if (closed || readySockets.size === 0)
513
541
  return false;
package/dist/room.d.ts CHANGED
@@ -1,4 +1,10 @@
1
- import { type Signaling, type SignalingState } from './signaling.js';
1
+ import { type Signaling, type SignalingErrorCode, type SignalingState } from './signaling.js';
2
+ /** @internal */
3
+ export declare function isRoomClosed(room: Room): boolean;
4
+ /** @internal */
5
+ export declare function onRoomClose(room: Room, fn: () => void): () => void;
6
+ /** @internal */
7
+ export declare function getRoomRemoteStreams(room: Room): Array<[string, MediaStream]>;
2
8
  /** Built-in Cloudflare and Google public STUN servers used by default. */
3
9
  export declare const defaultIceServers: readonly RTCIceServer[];
4
10
  /** Delivery guarantee for a packet: fast unordered (`'unreliable'`) or ordered reliable (`'reliable'`). */
@@ -16,7 +22,7 @@ export interface RoomOptions {
16
22
  turnConfig?: readonly RTCIceServer[];
17
23
  /** Max time in milliseconds per connection attempt before retrying. @default 35000 */
18
24
  handshakeTimeoutMs?: number;
19
- /** Soft cap in milliseconds for ICE candidate gathering before sending SDP. @default 2500 */
25
+ /** Soft cap in milliseconds for ICE candidate gathering on non-trickle adapters (such as `manualSignaling()`). @default 2500 */
20
26
  iceGatheringTimeoutMs?: number;
21
27
  /** Maximum simultaneous peer connections in this room. @default 32 */
22
28
  maxPeers?: number;
@@ -46,6 +52,21 @@ export interface PeerStats {
46
52
  /** Bytes currently queued in the reliable send buffer. */
47
53
  readonly bufferedReliable: number;
48
54
  }
55
+ /** Structured error codes emitted via `room.onError()`. */
56
+ export type RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | SignalingErrorCode;
57
+ /** Structured diagnostic error emitted via `room.onError()`. */
58
+ export interface RoomError {
59
+ readonly code: RoomErrorCode;
60
+ readonly message: string;
61
+ readonly peerId?: string;
62
+ }
63
+ /** Options for subscribing to room or channel events. */
64
+ export interface ListenOptions {
65
+ /** Automatically unsubscribe after the listener is invoked once. */
66
+ once?: boolean;
67
+ /** Automatically unsubscribe when the given AbortSignal aborts. */
68
+ signal?: AbortSignal;
69
+ }
49
70
  export interface Room {
50
71
  /** Local peer ID (random UUID v4). A page reload creates a new peer ID. */
51
72
  readonly id: string;
@@ -58,15 +79,25 @@ export interface Room {
58
79
  /** Read current ping, route, byte counts, and buffer sizes for a connected peer, or `null` if unavailable. */
59
80
  getStats(peerId: string): Promise<PeerStats | null>;
60
81
  /** Subscribe to incoming binary packets. Returns an unsubscribe function. */
61
- onPacket(fn: (from: string, bytes: Uint8Array, delivery: Delivery) => void): () => void;
82
+ onPacket(fn: (from: string, bytes: Uint8Array, delivery: Delivery) => void, options?: ListenOptions): () => void;
62
83
  /** Subscribe to send-buffer drain events (fires after `'busy'` clears). Returns an unsubscribe function. */
63
- onDrain(fn: (id: string, delivery: Delivery) => void): () => void;
84
+ onDrain(fn: (id: string, delivery: Delivery) => void, options?: ListenOptions): () => void;
64
85
  /** Subscribe to peer connection events. Returns an unsubscribe function. */
65
- onPeerJoin(fn: (id: string) => void): () => void;
86
+ onPeerJoin(fn: (id: string) => void, options?: ListenOptions): () => void;
66
87
  /** Subscribe to peer disconnection events. Returns an unsubscribe function. */
67
- onPeerLeave(fn: (id: string) => void): () => void;
88
+ onPeerLeave(fn: (id: string) => void, options?: ListenOptions): () => void;
68
89
  /** Subscribe to future signaling state changes. Returns an unsubscribe function. */
69
- onSignalingChange(fn: (state: SignalingState, reason?: string) => void): () => void;
90
+ onSignalingChange(fn: (state: SignalingState, reason?: string) => void, options?: ListenOptions): () => void;
91
+ /** Subscribe to structured room and signaling errors. Returns an unsubscribe function. */
92
+ onError(fn: (error: RoomError) => void, options?: ListenOptions): () => void;
93
+ /** Attach a local MediaStream to all connected/future peers (broadcast), or selectively to one peer (`to`). Broadcast and per-peer registrations are tracked independently. */
94
+ addStream(stream: MediaStream, to?: string): void;
95
+ /** Detach a previously added local MediaStream from broadcast (`to` omitted) or from one peer (`to`). Does not stop local tracks. */
96
+ removeStream(stream: MediaStream, to?: string): void;
97
+ /** Subscribe to incoming remote MediaStreams. Fires strictly after `onPeerJoin`. */
98
+ onPeerStream(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
99
+ /** Subscribe to remote MediaStream removals (explicit removal or peer disconnect). */
100
+ onPeerStreamEnd(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
70
101
  /** Leave the room, notify peers, and close all connections. Safe to call more than once. */
71
102
  leave(): void;
72
103
  }