@dimchansky/meshpost 0.2.0 → 0.4.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/room.js CHANGED
@@ -1,4 +1,26 @@
1
- import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
1
+ import { toBase64Url } from './crypto.js';
2
+ import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, isValidPeerIdentity, sha256Base64Url, signIdentityProof, verifyIdentityProof } from './identity.js';
3
+ import { isSignal, isUuid, randomUuid, withLoopbackFallback } from './signaling.js';
4
+ const roomInternals = new WeakMap();
5
+ /** @internal */
6
+ export function isRoomClosed(room) {
7
+ const internal = roomInternals.get(room);
8
+ return internal ? internal.isClosed() : room.signalingState === 'closed';
9
+ }
10
+ /** @internal */
11
+ export function onRoomClose(room, fn) {
12
+ const internal = roomInternals.get(room);
13
+ if (!internal) {
14
+ if (room.signalingState === 'closed')
15
+ fn();
16
+ return () => { };
17
+ }
18
+ return internal.onClose(fn);
19
+ }
20
+ /** @internal */
21
+ export function getRoomRemoteStreams(room) {
22
+ return roomInternals.get(room)?.getRemoteStreams() ?? [];
23
+ }
2
24
  /** Built-in Cloudflare and Google public STUN servers used by default. */
3
25
  export const defaultIceServers = Object.freeze([
4
26
  Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
@@ -128,10 +150,41 @@ const gatherTimeoutDefault = 2_500;
128
150
  const maxPeersDefault = 32;
129
151
  const disconnectGrace = 8_000;
130
152
  const leaveNotice = 'meshpost/1/leave';
153
+ const helloPrefix = 'meshpost/1/hello:';
154
+ const maxHelloBytes = 4096;
155
+ const reclaimTtlMs = 60_000;
156
+ const maxSupersededPeers = 128;
131
157
  const rtcControlPrefix = 'meshpost/1/rtc:';
132
158
  const maxRtcControlBytes = 64 * 1024;
133
159
  const maxRtcQueueDepth = 16;
134
160
  const maxRemoteStreamsPerPeer = 32;
161
+ const maxRemoteStreamTags = 64;
162
+ const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
163
+ const emptyStreamMeta = Object.freeze({});
164
+ function buildStreamMeta(tag) {
165
+ return tag !== undefined ? Object.freeze({ tag }) : emptyStreamMeta;
166
+ }
167
+ function parseIncomingStreamTags(raw) {
168
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
169
+ return null;
170
+ const entries = Object.entries(raw);
171
+ if (entries.length > maxRemoteStreamsPerPeer)
172
+ return null;
173
+ const out = [];
174
+ for (const [id, tag] of entries) {
175
+ if (id.length === 0 ||
176
+ id.length > 128 ||
177
+ id === '__proto__' ||
178
+ id === 'constructor' ||
179
+ id === 'prototype' ||
180
+ typeof tag !== 'string' ||
181
+ !streamTagPattern.test(tag)) {
182
+ return null;
183
+ }
184
+ out.push([id, tag]);
185
+ }
186
+ return out;
187
+ }
135
188
  const trickleBatchMs = 50;
136
189
  const trickleBatchSize = 16;
137
190
  const maxTrickleCandidates = 64;
@@ -155,13 +208,22 @@ export function joinRoom(name, options) {
155
208
  const maxPeers = options.maxPeers ?? maxPeersDefault;
156
209
  if (!Number.isSafeInteger(maxPeers) || maxPeers <= 0)
157
210
  throw new RangeError('Invalid maxPeers limit');
211
+ const identity = options.identity;
212
+ if (identity !== undefined && !isValidPeerIdentity(identity))
213
+ throw new TypeError('Expected a valid PeerIdentity');
214
+ if (options.RTCPeerConnection !== undefined && typeof options.RTCPeerConnection !== 'function')
215
+ throw new TypeError('Invalid RTCPeerConnection constructor');
216
+ const PeerConnection = options.RTCPeerConnection ?? globalThis.RTCPeerConnection;
217
+ if (typeof PeerConnection !== 'function') {
218
+ throw new Error('RTCPeerConnection is not available in this runtime; pass options.RTCPeerConnection');
219
+ }
158
220
  const baseIceServers = options.rtcConfig?.iceServers ?? defaultIceServers;
159
221
  const rtcConfig = {
160
222
  ...options.rtcConfig,
161
223
  iceServers: [...baseIceServers, ...(options.turnConfig ?? [])]
162
224
  };
163
225
  // Fail fast on malformed browser RTC configuration instead of retrying silently.
164
- new RTCPeerConnection(rtcConfig).close();
226
+ new PeerConnection(rtcConfig).close();
165
227
  const needsRelay = rtcConfig.iceTransportPolicy === 'relay';
166
228
  const hasTurn = rtcConfig.iceServers?.some((server) => {
167
229
  const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
@@ -170,8 +232,87 @@ export function joinRoom(name, options) {
170
232
  const self = randomUuid();
171
233
  const peers = new Map();
172
234
  const rejectedFull = new Set();
235
+ const supersededPeers = new Set();
236
+ const markSuperseded = (id) => {
237
+ supersededPeers.delete(id);
238
+ supersededPeers.add(id);
239
+ if (supersededPeers.size > maxSupersededPeers) {
240
+ const oldest = supersededPeers.values().next().value;
241
+ if (oldest !== undefined)
242
+ supersededPeers.delete(oldest);
243
+ }
244
+ };
245
+ const reclaimStorageKey = `meshpost/1/reclaim:${appId}:${name}`;
246
+ let pendingReclaim = null;
247
+ try {
248
+ const raw = globalThis.sessionStorage?.getItem(reclaimStorageKey);
249
+ if (raw) {
250
+ globalThis.sessionStorage?.removeItem(reclaimStorageKey);
251
+ const parsed = JSON.parse(raw);
252
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
253
+ const rec = parsed;
254
+ if (typeof rec.id === 'string' &&
255
+ isUuid(rec.id) &&
256
+ rec.id !== self &&
257
+ decodeCanonicalBase64Url(rec.secret, 22, 16) !== null &&
258
+ typeof rec.ts === 'number' &&
259
+ Number.isFinite(rec.ts) &&
260
+ Math.abs(Date.now() - rec.ts) <= reclaimTtlMs) {
261
+ pendingReclaim = { id: rec.id, secret: rec.secret, ts: rec.ts };
262
+ }
263
+ }
264
+ }
265
+ }
266
+ catch {
267
+ // Ignore storage restrictions on opaque origins or non-browser runtimes.
268
+ }
269
+ const localReclaimSecret = globalThis.crypto?.subtle
270
+ ? toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
271
+ : null;
272
+ const localReclaimCommitPromise = localReclaimSecret
273
+ ? sha256Base64Url(`meshpost/1/reclaim:${self}:${localReclaimSecret}`)
274
+ : Promise.resolve(null);
275
+ const hasWindowEvents = typeof window !== 'undefined' &&
276
+ typeof window.addEventListener === 'function' &&
277
+ typeof window.removeEventListener === 'function';
278
+ const onPageHide = (event) => {
279
+ if (stopped)
280
+ return;
281
+ if (!event.persisted) {
282
+ for (const peer of peers.values()) {
283
+ const reliable = peer.link?.channels.reliable;
284
+ if (reliable?.readyState === 'open') {
285
+ try {
286
+ reliable.send(leaveNotice);
287
+ }
288
+ catch {
289
+ // Best-effort unload departure hint.
290
+ }
291
+ }
292
+ }
293
+ }
294
+ if (localReclaimSecret) {
295
+ try {
296
+ globalThis.sessionStorage?.setItem(reclaimStorageKey, JSON.stringify({ id: self, secret: localReclaimSecret, ts: Date.now() }));
297
+ }
298
+ catch {
299
+ // Ignore storage quota or security errors.
300
+ }
301
+ }
302
+ };
303
+ const onPageShow = () => {
304
+ if (stopped)
305
+ return;
306
+ try {
307
+ globalThis.sessionStorage?.removeItem(reclaimStorageKey);
308
+ }
309
+ catch {
310
+ // Ignore storage errors.
311
+ }
312
+ };
173
313
  const broadcastStreams = new Set();
174
314
  const peerStreams = new Map();
315
+ const localStreamTags = new Map();
175
316
  const joins = listeners();
176
317
  const leaves = listeners();
177
318
  const packets = listeners();
@@ -206,6 +347,49 @@ export function joinRoom(name, options) {
206
347
  }
207
348
  return set;
208
349
  };
350
+ const isStreamRegistered = (stream) => {
351
+ if (broadcastStreams.has(stream))
352
+ return true;
353
+ for (const set of peerStreams.values()) {
354
+ if (set.has(stream))
355
+ return true;
356
+ }
357
+ return false;
358
+ };
359
+ const collectLinkStreamTags = (link) => {
360
+ let out;
361
+ for (const stream of link.senders.keys()) {
362
+ const tag = localStreamTags.get(stream);
363
+ if (tag !== undefined) {
364
+ out ??= {};
365
+ out[stream.id] = tag;
366
+ }
367
+ }
368
+ return out;
369
+ };
370
+ const mergeRemoteStreamTags = (link, entries) => {
371
+ for (const [id, tag] of entries) {
372
+ if (link.remoteStreamTags.has(id)) {
373
+ link.remoteStreamTags.delete(id);
374
+ link.remoteStreamTags.set(id, tag);
375
+ continue;
376
+ }
377
+ if (link.remoteStreamTags.size >= maxRemoteStreamTags) {
378
+ let evicted = false;
379
+ for (const existingId of link.remoteStreamTags.keys()) {
380
+ if (!link.remoteStreams.has(existingId)) {
381
+ link.remoteStreamTags.delete(existingId);
382
+ evicted = true;
383
+ break;
384
+ }
385
+ }
386
+ if (!evicted)
387
+ continue;
388
+ }
389
+ link.remoteStreamTags.set(id, tag);
390
+ }
391
+ };
392
+ const remoteMetaFor = (link, streamId) => buildStreamMeta(link.remoteStreamTags.get(streamId));
209
393
  const sendRtcControl = (link, payload) => {
210
394
  const reliable = link.channels.reliable;
211
395
  if (reliable.readyState !== 'open')
@@ -267,7 +451,12 @@ export function joinRoom(name, options) {
267
451
  await link.pc.setLocalDescription(offer);
268
452
  if (stopped || peer.link !== link || !link.pc.localDescription)
269
453
  return;
270
- if (sendRtcControl(link, { kind: 'offer', sdp: link.pc.localDescription.sdp })) {
454
+ const tags = collectLinkStreamTags(link);
455
+ if (sendRtcControl(link, {
456
+ kind: 'offer',
457
+ sdp: link.pc.localDescription.sdp,
458
+ ...(tags ? { tags } : {})
459
+ })) {
271
460
  for (const id of link.pendingStreamEnds) {
272
461
  sendRtcControl(link, { kind: 'stream-end', id });
273
462
  }
@@ -306,15 +495,23 @@ export function joinRoom(name, options) {
306
495
  if (stopped || peer.link !== link || !link.ready)
307
496
  return;
308
497
  const stream = link.remoteStreams.get(streamId);
498
+ const meta = remoteMetaFor(link, streamId);
499
+ link.remoteStreamTags.delete(streamId);
309
500
  if (stream) {
310
501
  link.remoteStreams.delete(streamId);
311
- peerStreamEndListeners.fire(peer.id, stream);
502
+ peerStreamEndListeners.fire(peer.id, stream, meta);
312
503
  }
313
504
  });
314
505
  return;
315
506
  }
316
507
  if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
317
508
  return;
509
+ let incomingTags = null;
510
+ if (msg.tags !== undefined) {
511
+ incomingTags = parseIncomingStreamTags(msg.tags);
512
+ if (!incomingTags)
513
+ return;
514
+ }
318
515
  const kind = msg.kind;
319
516
  const sdp = msg.sdp;
320
517
  const polite = self > peer.id;
@@ -332,6 +529,8 @@ export function joinRoom(name, options) {
332
529
  await link.pc.setLocalDescription({ type: 'rollback' });
333
530
  link.renegotiateQueued = true;
334
531
  }
532
+ if (incomingTags)
533
+ mergeRemoteStreamTags(link, incomingTags);
335
534
  await link.pc.setRemoteDescription({ type: 'offer', sdp });
336
535
  if (stopped || peer.link !== link)
337
536
  return;
@@ -341,7 +540,12 @@ export function joinRoom(name, options) {
341
540
  await link.pc.setLocalDescription(answer);
342
541
  if (stopped || peer.link !== link || !link.pc.localDescription)
343
542
  return;
344
- sendRtcControl(link, { kind: 'answer', sdp: link.pc.localDescription.sdp });
543
+ const answerTags = collectLinkStreamTags(link);
544
+ sendRtcControl(link, {
545
+ kind: 'answer',
546
+ sdp: link.pc.localDescription.sdp,
547
+ ...(answerTags ? { tags: answerTags } : {})
548
+ });
345
549
  }
346
550
  catch {
347
551
  if (!stopped && peer.link === link) {
@@ -360,6 +564,8 @@ export function joinRoom(name, options) {
360
564
  if (link.pc.signalingState !== 'have-local-offer')
361
565
  return;
362
566
  try {
567
+ if (incomingTags)
568
+ mergeRemoteStreamTags(link, incomingTags);
363
569
  await link.pc.setRemoteDescription({ type: 'answer', sdp });
364
570
  }
365
571
  catch {
@@ -381,8 +587,13 @@ export function joinRoom(name, options) {
381
587
  }
382
588
  });
383
589
  };
590
+ const canReachPeer = (id) => {
591
+ if (!signaling)
592
+ return false;
593
+ return typeof signaling.canReach === 'function' ? signaling.canReach(id) : state === 'online';
594
+ };
384
595
  function retry(peer) {
385
- if (stopped || state !== 'online' || !peer.advertised || peer.retry || peer.link)
596
+ if (stopped || !canReachPeer(peer.id) || !peer.advertised || peer.retry || peer.link)
386
597
  return;
387
598
  const base = Math.min(8000, 350 * 2 ** Math.min(peer.failures++, 5));
388
599
  const delay = Math.round(base * (0.75 + Math.random() * 0.5));
@@ -426,15 +637,17 @@ export function joinRoom(name, options) {
426
637
  peers.delete(peer.id);
427
638
  if (link.ready) {
428
639
  for (const stream of [...link.remoteStreams.values()]) {
429
- peerStreamEndListeners.fire(peer.id, stream);
640
+ peerStreamEndListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
430
641
  }
431
642
  link.remoteStreams.clear();
643
+ link.remoteStreamTags.clear();
432
644
  link.senders.clear();
433
645
  link.pendingStreamEnds.clear();
434
646
  leaves.fire(peer.id);
435
647
  }
436
648
  else {
437
649
  link.remoteStreams.clear();
650
+ link.remoteStreamTags.clear();
438
651
  link.senders.clear();
439
652
  link.pendingStreamEnds.clear();
440
653
  }
@@ -444,7 +657,7 @@ export function joinRoom(name, options) {
444
657
  function createLink(peer, attempt) {
445
658
  clearTimeout(peer.retry);
446
659
  delete peer.retry;
447
- const pc = new RTCPeerConnection(rtcConfig);
660
+ const pc = new PeerConnection(rtcConfig);
448
661
  // Fixed stream IDs let both endpoints create identical channels without glare.
449
662
  let channels;
450
663
  try {
@@ -472,18 +685,28 @@ export function joinRoom(name, options) {
472
685
  pc,
473
686
  channels,
474
687
  attempt,
688
+ channelsOpen: false,
689
+ helloSent: false,
690
+ helloReceived: false,
691
+ helloVerified: false,
475
692
  ready: false,
476
693
  accepted: false,
477
694
  published: false,
478
695
  answerApplied: false,
479
696
  remoteDescApplied: false,
697
+ userId: null,
698
+ verifiedUserId: null,
699
+ reclaimCommit: null,
700
+ remoteReclaimCommit: null,
701
+ pendingReclaimMatch: null,
480
702
  pendingCandidates: [],
481
703
  rtcQueue: Promise.resolve(),
482
704
  rtcPending: 0,
483
705
  renegotiateQueued: false,
484
706
  pendingStreamEnds: new Set(),
485
707
  senders: new Map(),
486
- remoteStreams: new Map()
708
+ remoteStreams: new Map(),
709
+ remoteStreamTags: new Map()
487
710
  };
488
711
  // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
489
712
  if (self < peer.id) {
@@ -495,12 +718,15 @@ export function joinRoom(name, options) {
495
718
  pc.ontrack = (event) => {
496
719
  if (stopped || peer.link !== link)
497
720
  return;
498
- const stream = event.streams[0] ?? new MediaStream([event.track]);
721
+ const stream = event.streams[0] ??
722
+ (typeof MediaStream === 'function' ? new MediaStream([event.track]) : undefined);
723
+ if (!stream)
724
+ return;
499
725
  if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
500
726
  return;
501
727
  link.remoteStreams.set(stream.id, stream);
502
728
  if (link.ready)
503
- peerStreamListeners.fire(peer.id, stream);
729
+ peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
504
730
  else
505
731
  earlyStreams.push(stream);
506
732
  };
@@ -512,6 +738,14 @@ export function joinRoom(name, options) {
512
738
  errors.fire({ code: 'ice-failed', peerId: peer.id, message });
513
739
  }
514
740
  };
741
+ const reportAuthFailed = (message) => {
742
+ const wasReady = link.ready;
743
+ drop(peer, link);
744
+ if (!stopped && !wasReady && !peer.authFailedReported) {
745
+ peer.authFailedReported = true;
746
+ errors.fire({ code: 'auth-failed', peerId: peer.id, message });
747
+ }
748
+ };
515
749
  peer.link = link;
516
750
  link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
517
751
  pc.onconnectionstatechange = () => {
@@ -532,6 +766,75 @@ export function joinRoom(name, options) {
532
766
  const early = [];
533
767
  const earlyRtc = [];
534
768
  let earlyBytes = 0;
769
+ const tryPromoteReady = () => {
770
+ if (stopped ||
771
+ peer.link !== link ||
772
+ link.ready ||
773
+ !link.channelsOpen ||
774
+ !link.helloSent ||
775
+ !link.helloVerified) {
776
+ return;
777
+ }
778
+ const reclaimMatch = link.pendingReclaimMatch;
779
+ link.pendingReclaimMatch = null;
780
+ if (reclaimMatch) {
781
+ const oldPeer = peers.get(reclaimMatch.id);
782
+ const oldLink = oldPeer?.link;
783
+ if (oldPeer && oldLink?.reclaimCommit && oldLink.reclaimCommit === reclaimMatch.commit) {
784
+ markSuperseded(oldPeer.id);
785
+ oldPeer.advertised = false;
786
+ clearTimeout(oldPeer.retry);
787
+ delete oldPeer.retry;
788
+ drop(oldPeer, oldLink, false, false);
789
+ if (stopped || peer.link !== link)
790
+ return;
791
+ }
792
+ }
793
+ clearTimeout(link.deadline);
794
+ clearTimeout(link.iceFlush);
795
+ delete link.iceFlush;
796
+ link.reclaimCommit = link.remoteReclaimCommit;
797
+ link.userId = link.verifiedUserId;
798
+ link.ready = true;
799
+ peer.failures = 0;
800
+ peer.iceFailedReported = false;
801
+ peer.authFailedReported = false;
802
+ joins.fire(peer.id);
803
+ for (const stream of earlyStreams) {
804
+ if (peer.link !== link || stopped)
805
+ break;
806
+ peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
807
+ }
808
+ earlyStreams.length = 0;
809
+ for (const raw of earlyRtc) {
810
+ if (peer.link !== link || stopped)
811
+ break;
812
+ handleRtcControl(peer, link, raw);
813
+ }
814
+ earlyRtc.length = 0;
815
+ for (const [bytes, mode] of early) {
816
+ if (peer.link !== link || stopped)
817
+ break;
818
+ packets.fire(peer.id, bytes, mode);
819
+ }
820
+ early.length = 0;
821
+ // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
822
+ if (!stopped && peer.link === link) {
823
+ const desired = desiredStreamsFor(peer.id);
824
+ let needsRenegotiate = false;
825
+ for (const stream of desired) {
826
+ if (attachStreamToLink(link, stream))
827
+ needsRenegotiate = true;
828
+ }
829
+ for (const stream of [...link.senders.keys()]) {
830
+ if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
831
+ needsRenegotiate = true;
832
+ }
833
+ }
834
+ if (needsRenegotiate)
835
+ enqueueRenegotiate(peer, link);
836
+ }
837
+ };
535
838
  for (const delivery of ['unreliable', 'reliable']) {
536
839
  const channel = channels[delivery];
537
840
  channel.binaryType = 'arraybuffer';
@@ -543,51 +846,62 @@ export function joinRoom(name, options) {
543
846
  channel.onclose = () => drop(peer, link);
544
847
  channel.onerror = () => drop(peer, link);
545
848
  channel.onopen = () => {
546
- if (stopped || peer.link !== link || link.ready)
849
+ if (stopped || peer.link !== link || link.channelsOpen)
547
850
  return;
548
- if (Object.values(channels).every((c) => c.readyState === 'open')) {
549
- clearTimeout(link.deadline);
550
- clearTimeout(link.iceFlush);
551
- delete link.iceFlush;
552
- link.ready = true;
553
- peer.failures = 0;
554
- peer.iceFailedReported = false;
555
- joins.fire(peer.id);
556
- for (const stream of earlyStreams) {
557
- if (peer.link !== link || stopped)
558
- break;
559
- peerStreamListeners.fire(peer.id, stream);
560
- }
561
- earlyStreams.length = 0;
562
- for (const raw of earlyRtc) {
563
- if (peer.link !== link || stopped)
564
- break;
565
- handleRtcControl(peer, link, raw);
566
- }
567
- earlyRtc.length = 0;
568
- for (const [bytes, mode] of early) {
569
- if (peer.link !== link || stopped)
570
- break;
571
- packets.fire(peer.id, bytes, mode);
572
- }
573
- early.length = 0;
574
- // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
575
- if (!stopped && peer.link === link) {
576
- const desired = desiredStreamsFor(peer.id);
577
- let needsRenegotiate = false;
578
- for (const stream of desired) {
579
- if (attachStreamToLink(link, stream))
580
- needsRenegotiate = true;
851
+ if (!Object.values(channels).every((c) => c.readyState === 'open'))
852
+ return;
853
+ link.channelsOpen = true;
854
+ void (async () => {
855
+ try {
856
+ const rc = await localReclaimCommitPromise;
857
+ if (stopped || peer.link !== link)
858
+ return;
859
+ const payload = { v: 1 };
860
+ if (rc)
861
+ payload.rc = rc;
862
+ const initialTags = collectLinkStreamTags(link);
863
+ if (initialTags)
864
+ payload.st = initialTags;
865
+ if (pendingReclaim) {
866
+ if (Math.abs(Date.now() - pendingReclaim.ts) <= reclaimTtlMs) {
867
+ payload.reclaim = { id: pendingReclaim.id, secret: pendingReclaim.secret };
868
+ }
869
+ else {
870
+ pendingReclaim = null;
871
+ }
581
872
  }
582
- for (const stream of [...link.senders.keys()]) {
583
- if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
584
- needsRenegotiate = true;
873
+ if (identity) {
874
+ const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
875
+ const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
876
+ const localFp = extractUniqueDtlsFingerprint(localSdp);
877
+ const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
878
+ if (!localFp || !remoteFp) {
879
+ throw new Error('Missing unique DTLS fingerprint for identity binding');
585
880
  }
881
+ payload.id = await signIdentityProof(identity, {
882
+ appId,
883
+ room: name,
884
+ signerId: self,
885
+ verifierId: peer.id,
886
+ signerFp: localFp,
887
+ verifierFp: remoteFp
888
+ });
889
+ if (stopped || peer.link !== link)
890
+ return;
891
+ }
892
+ if (channels.reliable.readyState !== 'open') {
893
+ drop(peer, link);
894
+ return;
586
895
  }
587
- if (needsRenegotiate)
588
- enqueueRenegotiate(peer, link);
896
+ channels.reliable.send(helloPrefix + JSON.stringify(payload));
897
+ link.helloSent = true;
898
+ tryPromoteReady();
589
899
  }
590
- }
900
+ catch {
901
+ if (!stopped && peer.link === link)
902
+ drop(peer, link);
903
+ }
904
+ })();
591
905
  };
592
906
  channel.onmessage = ({ data }) => {
593
907
  if (stopped || peer.link !== link)
@@ -597,6 +911,117 @@ export function joinRoom(name, options) {
597
911
  drop(peer, link);
598
912
  return;
599
913
  }
914
+ if (typeof data === 'string' && delivery === 'reliable' && data.startsWith(helloPrefix)) {
915
+ if (link.helloReceived) {
916
+ drop(peer, link);
917
+ return;
918
+ }
919
+ link.helloReceived = true;
920
+ if (data.length > maxHelloBytes) {
921
+ reportAuthFailed('Peer handshake frame exceeded size limit');
922
+ return;
923
+ }
924
+ let parsed = null;
925
+ try {
926
+ const raw = JSON.parse(data.slice(helloPrefix.length));
927
+ parsed =
928
+ raw && typeof raw === 'object' && !Array.isArray(raw)
929
+ ? raw
930
+ : null;
931
+ }
932
+ catch {
933
+ parsed = null;
934
+ }
935
+ if (!parsed || parsed.v !== 1) {
936
+ reportAuthFailed('Invalid peer handshake frame');
937
+ return;
938
+ }
939
+ let rc = null;
940
+ if (parsed.rc !== undefined) {
941
+ if (decodeCanonicalBase64Url(parsed.rc, 43, 32) === null) {
942
+ reportAuthFailed('Invalid peer handshake commitment');
943
+ return;
944
+ }
945
+ rc = parsed.rc;
946
+ }
947
+ let reclaimCandidate = null;
948
+ if (parsed.reclaim !== undefined) {
949
+ const rec = parsed.reclaim && typeof parsed.reclaim === 'object' && !Array.isArray(parsed.reclaim)
950
+ ? parsed.reclaim
951
+ : null;
952
+ if (!rec ||
953
+ typeof rec.id !== 'string' ||
954
+ !isUuid(rec.id) ||
955
+ rec.id === self ||
956
+ rec.id === peer.id ||
957
+ decodeCanonicalBase64Url(rec.secret, 22, 16) === null) {
958
+ reportAuthFailed('Invalid peer session reclaim proof');
959
+ return;
960
+ }
961
+ reclaimCandidate = { id: rec.id, secret: rec.secret };
962
+ }
963
+ let initialStreamTags = null;
964
+ if (parsed.st !== undefined) {
965
+ initialStreamTags = parseIncomingStreamTags(parsed.st);
966
+ if (!initialStreamTags) {
967
+ reportAuthFailed('Invalid peer stream metadata');
968
+ return;
969
+ }
970
+ }
971
+ let idProof = null;
972
+ if (parsed.id !== undefined) {
973
+ if (!parsed.id || typeof parsed.id !== 'object' || Array.isArray(parsed.id)) {
974
+ reportAuthFailed('Invalid peer identity proof');
975
+ return;
976
+ }
977
+ idProof = parsed.id;
978
+ }
979
+ void (async () => {
980
+ let verifiedUserId = null;
981
+ if (idProof) {
982
+ const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
983
+ const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
984
+ const localFp = extractUniqueDtlsFingerprint(localSdp);
985
+ const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
986
+ if (!localFp || !remoteFp) {
987
+ if (!stopped && peer.link === link) {
988
+ reportAuthFailed('Missing unique DTLS fingerprint for identity verification');
989
+ }
990
+ return;
991
+ }
992
+ verifiedUserId = await verifyIdentityProof(idProof, {
993
+ appId,
994
+ room: name,
995
+ signerId: peer.id,
996
+ verifierId: self,
997
+ signerFp: remoteFp,
998
+ verifierFp: localFp
999
+ });
1000
+ if (stopped || peer.link !== link)
1001
+ return;
1002
+ if (!verifiedUserId) {
1003
+ reportAuthFailed('Peer identity verification failed');
1004
+ return;
1005
+ }
1006
+ }
1007
+ let reclaimMatch = null;
1008
+ if (reclaimCandidate) {
1009
+ const commit = await sha256Base64Url(`meshpost/1/reclaim:${reclaimCandidate.id}:${reclaimCandidate.secret}`);
1010
+ if (stopped || peer.link !== link)
1011
+ return;
1012
+ if (commit)
1013
+ reclaimMatch = { id: reclaimCandidate.id, commit };
1014
+ }
1015
+ if (initialStreamTags)
1016
+ mergeRemoteStreamTags(link, initialStreamTags);
1017
+ link.verifiedUserId = verifiedUserId;
1018
+ link.remoteReclaimCommit = rc;
1019
+ link.pendingReclaimMatch = reclaimMatch;
1020
+ link.helloVerified = true;
1021
+ tryPromoteReady();
1022
+ })();
1023
+ return;
1024
+ }
600
1025
  if (typeof data === 'string' &&
601
1026
  delivery === 'reliable' &&
602
1027
  data.startsWith(rtcControlPrefix)) {
@@ -776,7 +1201,12 @@ export function joinRoom(name, options) {
776
1201
  }
777
1202
  }
778
1203
  function discover(peer) {
779
- if (stopped || !signaling || !peer.advertised || state !== 'online' || peer.link || peer.retry)
1204
+ if (stopped ||
1205
+ !signaling ||
1206
+ !peer.advertised ||
1207
+ !canReachPeer(peer.id) ||
1208
+ peer.link ||
1209
+ peer.retry)
780
1210
  return;
781
1211
  if (self < peer.id)
782
1212
  void negotiate(peer, ++nextAttempt);
@@ -895,14 +1325,16 @@ export function joinRoom(name, options) {
895
1325
  state = next;
896
1326
  if (next !== 'online') {
897
1327
  for (const peer of peers.values()) {
898
- clearTimeout(peer.retry);
899
- delete peer.retry;
1328
+ if (!canReachPeer(peer.id)) {
1329
+ clearTimeout(peer.retry);
1330
+ delete peer.retry;
1331
+ }
900
1332
  }
901
1333
  }
902
1334
  status.fire(next, reason);
903
1335
  if (!stopped && state === 'online') {
904
1336
  for (const peer of peers.values()) {
905
- if (peer.advertised && !peer.link) {
1337
+ if (peer.advertised && !peer.link && !peer.retry) {
906
1338
  peer.failures = 0;
907
1339
  discover(peer);
908
1340
  }
@@ -910,20 +1342,27 @@ export function joinRoom(name, options) {
910
1342
  }
911
1343
  },
912
1344
  error(code, message) {
913
- if (stopped || (code !== 'decrypt-failed' && code !== 'signaling-error'))
1345
+ if (stopped ||
1346
+ (code !== 'decrypt-failed' && code !== 'clock-skew' && code !== 'signaling-error'))
914
1347
  return;
915
1348
  errors.fire({
916
1349
  code,
917
1350
  message: message ??
918
1351
  (code === 'decrypt-failed'
919
1352
  ? 'Failed to decrypt signaling message'
920
- : 'Signaling adapter error')
1353
+ : code === 'clock-skew'
1354
+ ? 'Signaling message rejected due to system clock skew (>60s)'
1355
+ : 'Signaling adapter error')
921
1356
  });
922
1357
  },
923
1358
  roster(ids) {
924
1359
  if (stopped)
925
1360
  return;
926
- const present = new Set(ids);
1361
+ const present = new Set();
1362
+ for (const id of ids) {
1363
+ if (!supersededPeers.has(id))
1364
+ present.add(id);
1365
+ }
927
1366
  for (const id of [...rejectedFull]) {
928
1367
  if (!present.has(id) || peers.has(id))
929
1368
  rejectedFull.delete(id);
@@ -962,18 +1401,30 @@ export function joinRoom(name, options) {
962
1401
  }
963
1402
  }
964
1403
  });
1404
+ if (hasWindowEvents) {
1405
+ window.addEventListener('pagehide', onPageHide);
1406
+ window.addEventListener('pageshow', onPageShow);
1407
+ }
965
1408
  useTrickle = signaling.trickle === true;
966
1409
  for (const peer of peers.values())
967
1410
  discover(peer);
1411
+ const closeHooks = new Set();
968
1412
  const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
969
- return {
1413
+ const room = {
970
1414
  id: self,
1415
+ userId: identity?.userId ?? null,
971
1416
  get peers() {
972
1417
  return connected();
973
1418
  },
974
1419
  get signalingState() {
975
1420
  return state;
976
1421
  },
1422
+ peerUserId(peerId) {
1423
+ if (stopped || peerId === self)
1424
+ return null;
1425
+ const link = peers.get(peerId)?.link;
1426
+ return link?.ready ? link.userId : null;
1427
+ },
977
1428
  onPacket: packets.add,
978
1429
  onDrain: drains.add,
979
1430
  onPeerJoin: joins.add,
@@ -982,11 +1433,33 @@ export function joinRoom(name, options) {
982
1433
  onError: errors.add,
983
1434
  onPeerStream: peerStreamListeners.add,
984
1435
  onPeerStreamEnd: peerStreamEndListeners.add,
985
- addStream(stream, to) {
1436
+ addStream(stream, toOrOptions) {
986
1437
  if (stopped)
987
1438
  throw new Error('Room is closed');
988
1439
  if (!stream || typeof stream.getTracks !== 'function')
989
1440
  throw new TypeError('Expected a MediaStream');
1441
+ let to;
1442
+ let tag;
1443
+ if (typeof toOrOptions === 'string') {
1444
+ to = toOrOptions;
1445
+ }
1446
+ else if (toOrOptions !== undefined) {
1447
+ if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
1448
+ throw new TypeError('Invalid addStream options');
1449
+ }
1450
+ if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
1451
+ throw new TypeError('Invalid target peer ID');
1452
+ }
1453
+ if (toOrOptions.tag !== undefined &&
1454
+ (typeof toOrOptions.tag !== 'string' || !streamTagPattern.test(toOrOptions.tag))) {
1455
+ throw new TypeError('Invalid stream tag');
1456
+ }
1457
+ to = toOrOptions.to;
1458
+ tag = toOrOptions.tag;
1459
+ }
1460
+ if (tag !== undefined) {
1461
+ localStreamTags.set(stream, tag);
1462
+ }
990
1463
  if (to === undefined) {
991
1464
  broadcastStreams.add(stream);
992
1465
  for (const peer of peers.values()) {
@@ -997,8 +1470,11 @@ export function joinRoom(name, options) {
997
1470
  }
998
1471
  }
999
1472
  else {
1000
- if (to === self)
1473
+ if (to === self) {
1474
+ if (!isStreamRegistered(stream))
1475
+ localStreamTags.delete(stream);
1001
1476
  return;
1477
+ }
1002
1478
  let set = peerStreams.get(to);
1003
1479
  if (!set) {
1004
1480
  set = new Set();
@@ -1012,12 +1488,27 @@ export function joinRoom(name, options) {
1012
1488
  }
1013
1489
  }
1014
1490
  },
1015
- removeStream(stream, to) {
1491
+ removeStream(stream, toOrOptions) {
1492
+ let to;
1493
+ if (typeof toOrOptions === 'string') {
1494
+ to = toOrOptions;
1495
+ }
1496
+ else if (toOrOptions !== undefined) {
1497
+ if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
1498
+ throw new TypeError('Invalid removeStream options');
1499
+ }
1500
+ if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
1501
+ throw new TypeError('Invalid target peer ID');
1502
+ }
1503
+ to = toOrOptions.to;
1504
+ }
1016
1505
  if (stopped || !stream)
1017
1506
  return;
1018
1507
  if (to === undefined) {
1019
1508
  if (!broadcastStreams.delete(stream))
1020
1509
  return;
1510
+ if (!isStreamRegistered(stream))
1511
+ localStreamTags.delete(stream);
1021
1512
  for (const peer of peers.values()) {
1022
1513
  if (peerStreams.get(peer.id)?.has(stream))
1023
1514
  continue;
@@ -1033,6 +1524,8 @@ export function joinRoom(name, options) {
1033
1524
  return;
1034
1525
  if (set.size === 0)
1035
1526
  peerStreams.delete(to);
1527
+ if (!isStreamRegistered(stream))
1528
+ localStreamTags.delete(stream);
1036
1529
  if (broadcastStreams.has(stream))
1037
1530
  return;
1038
1531
  const peer = peers.get(to);
@@ -1042,6 +1535,54 @@ export function joinRoom(name, options) {
1042
1535
  }
1043
1536
  }
1044
1537
  },
1538
+ async replaceStreamTrack(stream, oldTrack, newTrack) {
1539
+ if (stopped)
1540
+ throw new Error('Room is closed');
1541
+ if (!stream || typeof stream.getTracks !== 'function')
1542
+ throw new TypeError('Expected a MediaStream');
1543
+ if (!oldTrack ||
1544
+ typeof oldTrack.kind !== 'string' ||
1545
+ !newTrack ||
1546
+ typeof newTrack.kind !== 'string' ||
1547
+ oldTrack.kind !== newTrack.kind) {
1548
+ throw new TypeError('Expected matching-kind MediaStreamTrack instances');
1549
+ }
1550
+ if (!isStreamRegistered(stream)) {
1551
+ throw new Error('Stream is not attached to this room');
1552
+ }
1553
+ if (oldTrack === newTrack)
1554
+ return;
1555
+ if (stream.getTracks().includes(oldTrack))
1556
+ stream.removeTrack(oldTrack);
1557
+ if (!stream.getTracks().includes(newTrack))
1558
+ stream.addTrack(newTrack);
1559
+ const ops = [];
1560
+ for (const peer of peers.values()) {
1561
+ const link = peer.link;
1562
+ const senderList = link?.senders.get(stream);
1563
+ if (!peer || !link || !senderList)
1564
+ continue;
1565
+ let targetSender = senderList.find((s) => s.track === oldTrack);
1566
+ if (!targetSender) {
1567
+ const sameKind = senderList.filter((s) => s.track?.kind === newTrack.kind);
1568
+ if (sameKind.length === 1)
1569
+ targetSender = sameKind[0];
1570
+ }
1571
+ if (!targetSender)
1572
+ continue;
1573
+ ops.push(targetSender.replaceTrack(newTrack).catch(() => {
1574
+ if (!stopped && peer.link === link && link.ready) {
1575
+ errors.fire({
1576
+ code: 'media-error',
1577
+ peerId: peer.id,
1578
+ message: 'Failed to replace media track'
1579
+ });
1580
+ }
1581
+ }));
1582
+ }
1583
+ if (ops.length > 0)
1584
+ await Promise.all(ops);
1585
+ },
1045
1586
  async getStats(peerId) {
1046
1587
  if (stopped || peerId === self)
1047
1588
  return null;
@@ -1086,9 +1627,10 @@ export function joinRoom(name, options) {
1086
1627
  result.set(id, 'accepted');
1087
1628
  }
1088
1629
  catch (error) {
1089
- result.set(id, error instanceof DOMException && error.name === 'OperationError'
1090
- ? 'busy'
1091
- : 'unavailable');
1630
+ const isOpError = ((typeof DOMException === 'function' && error instanceof DOMException) ||
1631
+ error instanceof Error) &&
1632
+ error.name === 'OperationError';
1633
+ result.set(id, isOpError ? 'busy' : 'unavailable');
1092
1634
  }
1093
1635
  }
1094
1636
  }
@@ -1100,6 +1642,25 @@ export function joinRoom(name, options) {
1100
1642
  stopped = true;
1101
1643
  const wasClosed = state === 'closed';
1102
1644
  state = 'closed';
1645
+ for (const fn of [...closeHooks]) {
1646
+ closeHooks.delete(fn);
1647
+ try {
1648
+ fn();
1649
+ }
1650
+ catch (error) {
1651
+ globalThis.reportError?.(error);
1652
+ }
1653
+ }
1654
+ if (hasWindowEvents) {
1655
+ window.removeEventListener('pagehide', onPageHide);
1656
+ window.removeEventListener('pageshow', onPageShow);
1657
+ }
1658
+ try {
1659
+ globalThis.sessionStorage?.removeItem(reclaimStorageKey);
1660
+ }
1661
+ catch {
1662
+ // Ignore storage errors.
1663
+ }
1103
1664
  signaling?.close();
1104
1665
  for (const peer of peers.values()) {
1105
1666
  peer.advertised = false;
@@ -1110,8 +1671,10 @@ export function joinRoom(name, options) {
1110
1671
  }
1111
1672
  peers.clear();
1112
1673
  rejectedFull.clear();
1674
+ supersededPeers.clear();
1113
1675
  broadcastStreams.clear();
1114
1676
  peerStreams.clear();
1677
+ localStreamTags.clear();
1115
1678
  if (!wasClosed)
1116
1679
  status.fire('closed');
1117
1680
  for (const group of [
@@ -1127,4 +1690,32 @@ export function joinRoom(name, options) {
1127
1690
  group.clear();
1128
1691
  }
1129
1692
  };
1693
+ roomInternals.set(room, {
1694
+ isClosed: () => stopped,
1695
+ onClose(fn) {
1696
+ if (stopped) {
1697
+ fn();
1698
+ return () => { };
1699
+ }
1700
+ closeHooks.add(fn);
1701
+ return () => {
1702
+ closeHooks.delete(fn);
1703
+ };
1704
+ },
1705
+ getRemoteStreams() {
1706
+ const out = [];
1707
+ if (stopped)
1708
+ return out;
1709
+ for (const peer of peers.values()) {
1710
+ const link = peer.link;
1711
+ if (!link?.ready)
1712
+ continue;
1713
+ for (const stream of link.remoteStreams.values()) {
1714
+ out.push([peer.id, stream, remoteMetaFor(link, stream.id)]);
1715
+ }
1716
+ }
1717
+ return out;
1718
+ }
1719
+ });
1720
+ return room;
1130
1721
  }