@dimchansky/meshpost 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import type { Signaling } from './signaling.js';
2
+ /**
3
+ * Combine multiple signaling adapters into one composite adapter.
4
+ * Merges peer rosters across all children, routes signals to online children that advertise the target peer,
5
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
6
+ */
7
+ export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
@@ -0,0 +1,249 @@
1
+ const maxSeenIcePeers = 256;
2
+ const maxSeenIceAttemptsPerPeer = 4;
3
+ const maxSeenIceKeysPerAttempt = 64;
4
+ function iceCandidateKey(item) {
5
+ return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
6
+ }
7
+ function setsEqual(a, b) {
8
+ if (a.size !== b.size)
9
+ return false;
10
+ for (const item of a) {
11
+ if (!b.has(item))
12
+ return false;
13
+ }
14
+ return true;
15
+ }
16
+ /**
17
+ * Combine multiple signaling adapters into one composite adapter.
18
+ * Merges peer rosters across all children, routes signals to online children that advertise the target peer,
19
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
20
+ */
21
+ export function combineSignaling(...adapters) {
22
+ if (adapters.length === 0)
23
+ throw new RangeError('At least one signaling adapter is required');
24
+ for (const adapter of adapters) {
25
+ if (typeof adapter !== 'function') {
26
+ throw new TypeError('All signaling adapters must be functions');
27
+ }
28
+ }
29
+ if (adapters.length === 1)
30
+ return adapters[0];
31
+ const list = [...adapters];
32
+ return (discovery) => {
33
+ const children = list.map(() => ({
34
+ state: 'connecting',
35
+ peers: new Set()
36
+ }));
37
+ const buffered = [];
38
+ const seenIce = new Map();
39
+ let initializing = true;
40
+ let closed = false;
41
+ let aggState = 'connecting';
42
+ let lastReason;
43
+ let publishedRoster = new Set();
44
+ let rosterDirty = false;
45
+ const computeAggregateState = () => {
46
+ let hasConnecting = false;
47
+ let hasOffline = false;
48
+ for (const child of children) {
49
+ if (child.state === 'online')
50
+ return 'online';
51
+ if (child.state === 'connecting')
52
+ hasConnecting = true;
53
+ else if (child.state === 'offline')
54
+ hasOffline = true;
55
+ }
56
+ if (hasConnecting)
57
+ return 'connecting';
58
+ if (hasOffline)
59
+ return 'offline';
60
+ return 'closed';
61
+ };
62
+ const syncState = (reason) => {
63
+ if (closed)
64
+ return;
65
+ const next = computeAggregateState();
66
+ if (next === aggState)
67
+ return;
68
+ aggState = next;
69
+ lastReason = reason;
70
+ if (!initializing)
71
+ discovery.status(next, reason);
72
+ };
73
+ const computeUnion = () => {
74
+ const union = new Set();
75
+ for (const child of children) {
76
+ for (const id of child.peers)
77
+ union.add(id);
78
+ }
79
+ return union;
80
+ };
81
+ const syncRoster = () => {
82
+ if (closed)
83
+ return;
84
+ if (initializing) {
85
+ rosterDirty = true;
86
+ return;
87
+ }
88
+ const union = computeUnion();
89
+ if (setsEqual(union, publishedRoster))
90
+ return;
91
+ publishedRoster = union;
92
+ discovery.roster([...union]);
93
+ };
94
+ const dedupeIceSignal = (from, signal) => {
95
+ if (signal.kind !== 'ice')
96
+ return signal;
97
+ let byAttempt = seenIce.get(from);
98
+ if (!byAttempt) {
99
+ if (seenIce.size >= maxSeenIcePeers) {
100
+ const oldestPeer = seenIce.keys().next().value;
101
+ if (oldestPeer !== undefined)
102
+ seenIce.delete(oldestPeer);
103
+ }
104
+ byAttempt = new Map();
105
+ }
106
+ // Refresh peer LRU order on hit/insert.
107
+ seenIce.delete(from);
108
+ seenIce.set(from, byAttempt);
109
+ let keys = byAttempt.get(signal.attempt);
110
+ if (!keys) {
111
+ if (byAttempt.size >= maxSeenIceAttemptsPerPeer) {
112
+ const oldestAttempt = byAttempt.keys().next().value;
113
+ if (oldestAttempt !== undefined)
114
+ byAttempt.delete(oldestAttempt);
115
+ }
116
+ keys = new Set();
117
+ }
118
+ // Refresh attempt LRU order so active legitimate attempts stay hot.
119
+ byAttempt.delete(signal.attempt);
120
+ byAttempt.set(signal.attempt, keys);
121
+ const fresh = [];
122
+ for (const item of signal.candidates) {
123
+ const key = iceCandidateKey(item);
124
+ if (keys.has(key))
125
+ continue;
126
+ if (keys.size < maxSeenIceKeysPerAttempt)
127
+ keys.add(key);
128
+ fresh.push(item);
129
+ }
130
+ return fresh.length > 0 ? { ...signal, candidates: fresh } : null;
131
+ };
132
+ const closeAll = () => {
133
+ seenIce.clear();
134
+ for (const child of children) {
135
+ try {
136
+ child.session?.close();
137
+ }
138
+ catch {
139
+ // Ensure one failing child close does not leak sibling sessions.
140
+ }
141
+ delete child.session;
142
+ }
143
+ };
144
+ try {
145
+ for (let i = 0; i < list.length; i++) {
146
+ const child = children[i];
147
+ const adapter = list[i];
148
+ child.session = adapter({
149
+ appId: discovery.appId,
150
+ room: discovery.room,
151
+ self: discovery.self,
152
+ ...(discovery.password !== undefined ? { password: discovery.password } : {}),
153
+ status(next, reason) {
154
+ if (closed || next === child.state)
155
+ return;
156
+ child.state = next;
157
+ if (next === 'offline' || next === 'closed') {
158
+ if (child.peers.size > 0) {
159
+ child.peers.clear();
160
+ syncRoster();
161
+ }
162
+ }
163
+ syncState(reason);
164
+ },
165
+ roster(ids) {
166
+ if (closed)
167
+ return;
168
+ child.peers = new Set(ids);
169
+ syncRoster();
170
+ },
171
+ receive(from, signal) {
172
+ if (closed)
173
+ return;
174
+ if (!child.peers.has(from)) {
175
+ child.peers.add(from);
176
+ syncRoster();
177
+ }
178
+ const deduped = dedupeIceSignal(from, signal);
179
+ if (!deduped)
180
+ return;
181
+ if (initializing) {
182
+ buffered.push({ kind: 'receive', from, signal: deduped });
183
+ return;
184
+ }
185
+ discovery.receive(from, deduped);
186
+ },
187
+ error(code, message) {
188
+ if (closed)
189
+ return;
190
+ if (initializing) {
191
+ buffered.push({ kind: 'error', code, message });
192
+ return;
193
+ }
194
+ discovery.error?.(code, message);
195
+ }
196
+ });
197
+ }
198
+ }
199
+ catch (error) {
200
+ closed = true;
201
+ closeAll();
202
+ throw error;
203
+ }
204
+ initializing = false;
205
+ if (!closed) {
206
+ if (aggState !== 'connecting')
207
+ discovery.status(aggState, lastReason);
208
+ if (rosterDirty) {
209
+ rosterDirty = false;
210
+ const union = computeUnion();
211
+ if (union.size > 0) {
212
+ publishedRoster = union;
213
+ discovery.roster([...union]);
214
+ }
215
+ }
216
+ for (const ev of buffered) {
217
+ if (closed)
218
+ break;
219
+ if (ev.kind === 'receive')
220
+ discovery.receive(ev.from, ev.signal);
221
+ else
222
+ discovery.error?.(ev.code, ev.message);
223
+ }
224
+ buffered.length = 0;
225
+ }
226
+ const trickle = children.every((child) => child.session?.trickle === true);
227
+ return {
228
+ trickle,
229
+ send(to, signal) {
230
+ if (closed)
231
+ return false;
232
+ let accepted = false;
233
+ for (const child of children) {
234
+ if (child.state === 'online' && child.peers.has(to) && child.session) {
235
+ if (child.session.send(to, signal))
236
+ accepted = true;
237
+ }
238
+ }
239
+ return accepted;
240
+ },
241
+ close() {
242
+ if (closed)
243
+ return;
244
+ closed = true;
245
+ closeAll();
246
+ }
247
+ };
248
+ };
249
+ }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,16 @@
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';
5
7
  export { tabSignaling } from './tabs.js';
6
8
  export { manualSignaling } from './manual.js';
7
9
  export type { ManualSignaling } from './manual.js';
8
10
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
9
11
  export type { MqttSignalingOptions } from './mqtt.js';
12
+ export { wsSignaling } from './ws.js';
13
+ export type { WsSignalingOptions } from './ws.js';
14
+ export { combineSignaling } from './combine.js';
10
15
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
11
- export type { Discovery, Signal, Signaling, SignalingSession, SignalingState } from './signaling.js';
16
+ export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
2
  export { createChannel } from './channel.js';
3
+ export { createBlobChannel } from './blob.js';
3
4
  export { tabSignaling } from './tabs.js';
4
5
  export { manualSignaling } from './manual.js';
5
6
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
7
+ export { wsSignaling } from './ws.js';
8
+ export { combineSignaling } from './combine.js';
6
9
  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,4 @@
1
- import { type Signaling, type SignalingState } from './signaling.js';
1
+ import { type Signaling, type SignalingErrorCode, type SignalingState } from './signaling.js';
2
2
  /** Built-in Cloudflare and Google public STUN servers used by default. */
3
3
  export declare const defaultIceServers: readonly RTCIceServer[];
4
4
  /** Delivery guarantee for a packet: fast unordered (`'unreliable'`) or ordered reliable (`'reliable'`). */
@@ -16,7 +16,7 @@ export interface RoomOptions {
16
16
  turnConfig?: readonly RTCIceServer[];
17
17
  /** Max time in milliseconds per connection attempt before retrying. @default 35000 */
18
18
  handshakeTimeoutMs?: number;
19
- /** Soft cap in milliseconds for ICE candidate gathering before sending SDP. @default 2500 */
19
+ /** Soft cap in milliseconds for ICE candidate gathering on non-trickle adapters (such as `manualSignaling()`). @default 2500 */
20
20
  iceGatheringTimeoutMs?: number;
21
21
  /** Maximum simultaneous peer connections in this room. @default 32 */
22
22
  maxPeers?: number;
@@ -46,6 +46,21 @@ export interface PeerStats {
46
46
  /** Bytes currently queued in the reliable send buffer. */
47
47
  readonly bufferedReliable: number;
48
48
  }
49
+ /** Structured error codes emitted via `room.onError()`. */
50
+ export type RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | SignalingErrorCode;
51
+ /** Structured diagnostic error emitted via `room.onError()`. */
52
+ export interface RoomError {
53
+ readonly code: RoomErrorCode;
54
+ readonly message: string;
55
+ readonly peerId?: string;
56
+ }
57
+ /** Options for subscribing to room or channel events. */
58
+ export interface ListenOptions {
59
+ /** Automatically unsubscribe after the listener is invoked once. */
60
+ once?: boolean;
61
+ /** Automatically unsubscribe when the given AbortSignal aborts. */
62
+ signal?: AbortSignal;
63
+ }
49
64
  export interface Room {
50
65
  /** Local peer ID (random UUID v4). A page reload creates a new peer ID. */
51
66
  readonly id: string;
@@ -58,15 +73,25 @@ export interface Room {
58
73
  /** Read current ping, route, byte counts, and buffer sizes for a connected peer, or `null` if unavailable. */
59
74
  getStats(peerId: string): Promise<PeerStats | null>;
60
75
  /** Subscribe to incoming binary packets. Returns an unsubscribe function. */
61
- onPacket(fn: (from: string, bytes: Uint8Array, delivery: Delivery) => void): () => void;
76
+ onPacket(fn: (from: string, bytes: Uint8Array, delivery: Delivery) => void, options?: ListenOptions): () => void;
62
77
  /** Subscribe to send-buffer drain events (fires after `'busy'` clears). Returns an unsubscribe function. */
63
- onDrain(fn: (id: string, delivery: Delivery) => void): () => void;
78
+ onDrain(fn: (id: string, delivery: Delivery) => void, options?: ListenOptions): () => void;
64
79
  /** Subscribe to peer connection events. Returns an unsubscribe function. */
65
- onPeerJoin(fn: (id: string) => void): () => void;
80
+ onPeerJoin(fn: (id: string) => void, options?: ListenOptions): () => void;
66
81
  /** Subscribe to peer disconnection events. Returns an unsubscribe function. */
67
- onPeerLeave(fn: (id: string) => void): () => void;
82
+ onPeerLeave(fn: (id: string) => void, options?: ListenOptions): () => void;
68
83
  /** Subscribe to future signaling state changes. Returns an unsubscribe function. */
69
- onSignalingChange(fn: (state: SignalingState, reason?: string) => void): () => void;
84
+ onSignalingChange(fn: (state: SignalingState, reason?: string) => void, options?: ListenOptions): () => void;
85
+ /** Subscribe to structured room and signaling errors. Returns an unsubscribe function. */
86
+ onError(fn: (error: RoomError) => void, options?: ListenOptions): () => void;
87
+ /** Attach a local MediaStream to all connected/future peers (broadcast), or selectively to one peer (`to`). Broadcast and per-peer registrations are tracked independently. */
88
+ addStream(stream: MediaStream, to?: string): void;
89
+ /** Detach a previously added local MediaStream from broadcast (`to` omitted) or from one peer (`to`). Does not stop local tracks. */
90
+ removeStream(stream: MediaStream, to?: string): void;
91
+ /** Subscribe to incoming remote MediaStreams. Fires strictly after `onPeerJoin`. */
92
+ onPeerStream(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
93
+ /** Subscribe to remote MediaStream removals (explicit removal or peer disconnect). */
94
+ onPeerStreamEnd(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
70
95
  /** Leave the room, notify peers, and close all connections. Safe to call more than once. */
71
96
  leave(): void;
72
97
  }