@dimchansky/meshpost 0.3.0 → 0.4.1

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,6 @@
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';
2
4
  const roomInternals = new WeakMap();
3
5
  /** @internal */
4
6
  export function isRoomClosed(room) {
@@ -148,10 +150,41 @@ const gatherTimeoutDefault = 2_500;
148
150
  const maxPeersDefault = 32;
149
151
  const disconnectGrace = 8_000;
150
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;
151
157
  const rtcControlPrefix = 'meshpost/1/rtc:';
152
158
  const maxRtcControlBytes = 64 * 1024;
153
159
  const maxRtcQueueDepth = 16;
154
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
+ }
155
188
  const trickleBatchMs = 50;
156
189
  const trickleBatchSize = 16;
157
190
  const maxTrickleCandidates = 64;
@@ -175,13 +208,22 @@ export function joinRoom(name, options) {
175
208
  const maxPeers = options.maxPeers ?? maxPeersDefault;
176
209
  if (!Number.isSafeInteger(maxPeers) || maxPeers <= 0)
177
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
+ }
178
220
  const baseIceServers = options.rtcConfig?.iceServers ?? defaultIceServers;
179
221
  const rtcConfig = {
180
222
  ...options.rtcConfig,
181
223
  iceServers: [...baseIceServers, ...(options.turnConfig ?? [])]
182
224
  };
183
225
  // Fail fast on malformed browser RTC configuration instead of retrying silently.
184
- new RTCPeerConnection(rtcConfig).close();
226
+ new PeerConnection(rtcConfig).close();
185
227
  const needsRelay = rtcConfig.iceTransportPolicy === 'relay';
186
228
  const hasTurn = rtcConfig.iceServers?.some((server) => {
187
229
  const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
@@ -190,8 +232,87 @@ export function joinRoom(name, options) {
190
232
  const self = randomUuid();
191
233
  const peers = new Map();
192
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
+ };
193
313
  const broadcastStreams = new Set();
194
314
  const peerStreams = new Map();
315
+ const localStreamTags = new Map();
195
316
  const joins = listeners();
196
317
  const leaves = listeners();
197
318
  const packets = listeners();
@@ -226,6 +347,49 @@ export function joinRoom(name, options) {
226
347
  }
227
348
  return set;
228
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));
229
393
  const sendRtcControl = (link, payload) => {
230
394
  const reliable = link.channels.reliable;
231
395
  if (reliable.readyState !== 'open')
@@ -287,7 +451,12 @@ export function joinRoom(name, options) {
287
451
  await link.pc.setLocalDescription(offer);
288
452
  if (stopped || peer.link !== link || !link.pc.localDescription)
289
453
  return;
290
- 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
+ })) {
291
460
  for (const id of link.pendingStreamEnds) {
292
461
  sendRtcControl(link, { kind: 'stream-end', id });
293
462
  }
@@ -326,15 +495,23 @@ export function joinRoom(name, options) {
326
495
  if (stopped || peer.link !== link || !link.ready)
327
496
  return;
328
497
  const stream = link.remoteStreams.get(streamId);
498
+ const meta = remoteMetaFor(link, streamId);
499
+ link.remoteStreamTags.delete(streamId);
329
500
  if (stream) {
330
501
  link.remoteStreams.delete(streamId);
331
- peerStreamEndListeners.fire(peer.id, stream);
502
+ peerStreamEndListeners.fire(peer.id, stream, meta);
332
503
  }
333
504
  });
334
505
  return;
335
506
  }
336
507
  if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
337
508
  return;
509
+ let incomingTags = null;
510
+ if (msg.tags !== undefined) {
511
+ incomingTags = parseIncomingStreamTags(msg.tags);
512
+ if (!incomingTags)
513
+ return;
514
+ }
338
515
  const kind = msg.kind;
339
516
  const sdp = msg.sdp;
340
517
  const polite = self > peer.id;
@@ -352,6 +529,8 @@ export function joinRoom(name, options) {
352
529
  await link.pc.setLocalDescription({ type: 'rollback' });
353
530
  link.renegotiateQueued = true;
354
531
  }
532
+ if (incomingTags)
533
+ mergeRemoteStreamTags(link, incomingTags);
355
534
  await link.pc.setRemoteDescription({ type: 'offer', sdp });
356
535
  if (stopped || peer.link !== link)
357
536
  return;
@@ -361,7 +540,12 @@ export function joinRoom(name, options) {
361
540
  await link.pc.setLocalDescription(answer);
362
541
  if (stopped || peer.link !== link || !link.pc.localDescription)
363
542
  return;
364
- 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
+ });
365
549
  }
366
550
  catch {
367
551
  if (!stopped && peer.link === link) {
@@ -380,6 +564,8 @@ export function joinRoom(name, options) {
380
564
  if (link.pc.signalingState !== 'have-local-offer')
381
565
  return;
382
566
  try {
567
+ if (incomingTags)
568
+ mergeRemoteStreamTags(link, incomingTags);
383
569
  await link.pc.setRemoteDescription({ type: 'answer', sdp });
384
570
  }
385
571
  catch {
@@ -451,15 +637,17 @@ export function joinRoom(name, options) {
451
637
  peers.delete(peer.id);
452
638
  if (link.ready) {
453
639
  for (const stream of [...link.remoteStreams.values()]) {
454
- peerStreamEndListeners.fire(peer.id, stream);
640
+ peerStreamEndListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
455
641
  }
456
642
  link.remoteStreams.clear();
643
+ link.remoteStreamTags.clear();
457
644
  link.senders.clear();
458
645
  link.pendingStreamEnds.clear();
459
646
  leaves.fire(peer.id);
460
647
  }
461
648
  else {
462
649
  link.remoteStreams.clear();
650
+ link.remoteStreamTags.clear();
463
651
  link.senders.clear();
464
652
  link.pendingStreamEnds.clear();
465
653
  }
@@ -469,7 +657,7 @@ export function joinRoom(name, options) {
469
657
  function createLink(peer, attempt) {
470
658
  clearTimeout(peer.retry);
471
659
  delete peer.retry;
472
- const pc = new RTCPeerConnection(rtcConfig);
660
+ const pc = new PeerConnection(rtcConfig);
473
661
  // Fixed stream IDs let both endpoints create identical channels without glare.
474
662
  let channels;
475
663
  try {
@@ -497,18 +685,28 @@ export function joinRoom(name, options) {
497
685
  pc,
498
686
  channels,
499
687
  attempt,
688
+ channelsOpen: false,
689
+ helloSent: false,
690
+ helloReceived: false,
691
+ helloVerified: false,
500
692
  ready: false,
501
693
  accepted: false,
502
694
  published: false,
503
695
  answerApplied: false,
504
696
  remoteDescApplied: false,
697
+ userId: null,
698
+ verifiedUserId: null,
699
+ reclaimCommit: null,
700
+ remoteReclaimCommit: null,
701
+ pendingReclaimMatch: null,
505
702
  pendingCandidates: [],
506
703
  rtcQueue: Promise.resolve(),
507
704
  rtcPending: 0,
508
705
  renegotiateQueued: false,
509
706
  pendingStreamEnds: new Set(),
510
707
  senders: new Map(),
511
- remoteStreams: new Map()
708
+ remoteStreams: new Map(),
709
+ remoteStreamTags: new Map()
512
710
  };
513
711
  // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
514
712
  if (self < peer.id) {
@@ -520,12 +718,15 @@ export function joinRoom(name, options) {
520
718
  pc.ontrack = (event) => {
521
719
  if (stopped || peer.link !== link)
522
720
  return;
523
- 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;
524
725
  if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
525
726
  return;
526
727
  link.remoteStreams.set(stream.id, stream);
527
728
  if (link.ready)
528
- peerStreamListeners.fire(peer.id, stream);
729
+ peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
529
730
  else
530
731
  earlyStreams.push(stream);
531
732
  };
@@ -537,6 +738,14 @@ export function joinRoom(name, options) {
537
738
  errors.fire({ code: 'ice-failed', peerId: peer.id, message });
538
739
  }
539
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
+ };
540
749
  peer.link = link;
541
750
  link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
542
751
  pc.onconnectionstatechange = () => {
@@ -557,6 +766,75 @@ export function joinRoom(name, options) {
557
766
  const early = [];
558
767
  const earlyRtc = [];
559
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
+ };
560
838
  for (const delivery of ['unreliable', 'reliable']) {
561
839
  const channel = channels[delivery];
562
840
  channel.binaryType = 'arraybuffer';
@@ -568,51 +846,62 @@ export function joinRoom(name, options) {
568
846
  channel.onclose = () => drop(peer, link);
569
847
  channel.onerror = () => drop(peer, link);
570
848
  channel.onopen = () => {
571
- if (stopped || peer.link !== link || link.ready)
849
+ if (stopped || peer.link !== link || link.channelsOpen)
572
850
  return;
573
- if (Object.values(channels).every((c) => c.readyState === 'open')) {
574
- clearTimeout(link.deadline);
575
- clearTimeout(link.iceFlush);
576
- delete link.iceFlush;
577
- link.ready = true;
578
- peer.failures = 0;
579
- peer.iceFailedReported = false;
580
- joins.fire(peer.id);
581
- for (const stream of earlyStreams) {
582
- if (peer.link !== link || stopped)
583
- break;
584
- peerStreamListeners.fire(peer.id, stream);
585
- }
586
- earlyStreams.length = 0;
587
- for (const raw of earlyRtc) {
588
- if (peer.link !== link || stopped)
589
- break;
590
- handleRtcControl(peer, link, raw);
591
- }
592
- earlyRtc.length = 0;
593
- for (const [bytes, mode] of early) {
594
- if (peer.link !== link || stopped)
595
- break;
596
- packets.fire(peer.id, bytes, mode);
597
- }
598
- early.length = 0;
599
- // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
600
- if (!stopped && peer.link === link) {
601
- const desired = desiredStreamsFor(peer.id);
602
- let needsRenegotiate = false;
603
- for (const stream of desired) {
604
- if (attachStreamToLink(link, stream))
605
- 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
+ }
606
872
  }
607
- for (const stream of [...link.senders.keys()]) {
608
- if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
609
- 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');
610
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;
611
891
  }
612
- if (needsRenegotiate)
613
- enqueueRenegotiate(peer, link);
892
+ if (channels.reliable.readyState !== 'open') {
893
+ drop(peer, link);
894
+ return;
895
+ }
896
+ channels.reliable.send(helloPrefix + JSON.stringify(payload));
897
+ link.helloSent = true;
898
+ tryPromoteReady();
614
899
  }
615
- }
900
+ catch {
901
+ if (!stopped && peer.link === link)
902
+ drop(peer, link);
903
+ }
904
+ })();
616
905
  };
617
906
  channel.onmessage = ({ data }) => {
618
907
  if (stopped || peer.link !== link)
@@ -622,6 +911,117 @@ export function joinRoom(name, options) {
622
911
  drop(peer, link);
623
912
  return;
624
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
+ }
625
1025
  if (typeof data === 'string' &&
626
1026
  delivery === 'reliable' &&
627
1027
  data.startsWith(rtcControlPrefix)) {
@@ -942,20 +1342,27 @@ export function joinRoom(name, options) {
942
1342
  }
943
1343
  },
944
1344
  error(code, message) {
945
- if (stopped || (code !== 'decrypt-failed' && code !== 'signaling-error'))
1345
+ if (stopped ||
1346
+ (code !== 'decrypt-failed' && code !== 'clock-skew' && code !== 'signaling-error'))
946
1347
  return;
947
1348
  errors.fire({
948
1349
  code,
949
1350
  message: message ??
950
1351
  (code === 'decrypt-failed'
951
1352
  ? 'Failed to decrypt signaling message'
952
- : 'Signaling adapter error')
1353
+ : code === 'clock-skew'
1354
+ ? 'Signaling message rejected due to system clock skew (>60s)'
1355
+ : 'Signaling adapter error')
953
1356
  });
954
1357
  },
955
1358
  roster(ids) {
956
1359
  if (stopped)
957
1360
  return;
958
- 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
+ }
959
1366
  for (const id of [...rejectedFull]) {
960
1367
  if (!present.has(id) || peers.has(id))
961
1368
  rejectedFull.delete(id);
@@ -994,6 +1401,10 @@ export function joinRoom(name, options) {
994
1401
  }
995
1402
  }
996
1403
  });
1404
+ if (hasWindowEvents) {
1405
+ window.addEventListener('pagehide', onPageHide);
1406
+ window.addEventListener('pageshow', onPageShow);
1407
+ }
997
1408
  useTrickle = signaling.trickle === true;
998
1409
  for (const peer of peers.values())
999
1410
  discover(peer);
@@ -1001,12 +1412,19 @@ export function joinRoom(name, options) {
1001
1412
  const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
1002
1413
  const room = {
1003
1414
  id: self,
1415
+ userId: identity?.userId ?? null,
1004
1416
  get peers() {
1005
1417
  return connected();
1006
1418
  },
1007
1419
  get signalingState() {
1008
1420
  return state;
1009
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
+ },
1010
1428
  onPacket: packets.add,
1011
1429
  onDrain: drains.add,
1012
1430
  onPeerJoin: joins.add,
@@ -1015,11 +1433,33 @@ export function joinRoom(name, options) {
1015
1433
  onError: errors.add,
1016
1434
  onPeerStream: peerStreamListeners.add,
1017
1435
  onPeerStreamEnd: peerStreamEndListeners.add,
1018
- addStream(stream, to) {
1436
+ addStream(stream, toOrOptions) {
1019
1437
  if (stopped)
1020
1438
  throw new Error('Room is closed');
1021
1439
  if (!stream || typeof stream.getTracks !== 'function')
1022
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
+ }
1023
1463
  if (to === undefined) {
1024
1464
  broadcastStreams.add(stream);
1025
1465
  for (const peer of peers.values()) {
@@ -1030,8 +1470,11 @@ export function joinRoom(name, options) {
1030
1470
  }
1031
1471
  }
1032
1472
  else {
1033
- if (to === self)
1473
+ if (to === self) {
1474
+ if (!isStreamRegistered(stream))
1475
+ localStreamTags.delete(stream);
1034
1476
  return;
1477
+ }
1035
1478
  let set = peerStreams.get(to);
1036
1479
  if (!set) {
1037
1480
  set = new Set();
@@ -1045,12 +1488,27 @@ export function joinRoom(name, options) {
1045
1488
  }
1046
1489
  }
1047
1490
  },
1048
- 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
+ }
1049
1505
  if (stopped || !stream)
1050
1506
  return;
1051
1507
  if (to === undefined) {
1052
1508
  if (!broadcastStreams.delete(stream))
1053
1509
  return;
1510
+ if (!isStreamRegistered(stream))
1511
+ localStreamTags.delete(stream);
1054
1512
  for (const peer of peers.values()) {
1055
1513
  if (peerStreams.get(peer.id)?.has(stream))
1056
1514
  continue;
@@ -1066,6 +1524,8 @@ export function joinRoom(name, options) {
1066
1524
  return;
1067
1525
  if (set.size === 0)
1068
1526
  peerStreams.delete(to);
1527
+ if (!isStreamRegistered(stream))
1528
+ localStreamTags.delete(stream);
1069
1529
  if (broadcastStreams.has(stream))
1070
1530
  return;
1071
1531
  const peer = peers.get(to);
@@ -1075,6 +1535,54 @@ export function joinRoom(name, options) {
1075
1535
  }
1076
1536
  }
1077
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
+ },
1078
1586
  async getStats(peerId) {
1079
1587
  if (stopped || peerId === self)
1080
1588
  return null;
@@ -1119,9 +1627,10 @@ export function joinRoom(name, options) {
1119
1627
  result.set(id, 'accepted');
1120
1628
  }
1121
1629
  catch (error) {
1122
- result.set(id, error instanceof DOMException && error.name === 'OperationError'
1123
- ? 'busy'
1124
- : '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');
1125
1634
  }
1126
1635
  }
1127
1636
  }
@@ -1142,6 +1651,16 @@ export function joinRoom(name, options) {
1142
1651
  globalThis.reportError?.(error);
1143
1652
  }
1144
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
+ }
1145
1664
  signaling?.close();
1146
1665
  for (const peer of peers.values()) {
1147
1666
  peer.advertised = false;
@@ -1152,8 +1671,10 @@ export function joinRoom(name, options) {
1152
1671
  }
1153
1672
  peers.clear();
1154
1673
  rejectedFull.clear();
1674
+ supersededPeers.clear();
1155
1675
  broadcastStreams.clear();
1156
1676
  peerStreams.clear();
1677
+ localStreamTags.clear();
1157
1678
  if (!wasClosed)
1158
1679
  status.fire('closed');
1159
1680
  for (const group of [
@@ -1186,10 +1707,11 @@ export function joinRoom(name, options) {
1186
1707
  if (stopped)
1187
1708
  return out;
1188
1709
  for (const peer of peers.values()) {
1189
- if (!peer.link?.ready)
1710
+ const link = peer.link;
1711
+ if (!link?.ready)
1190
1712
  continue;
1191
- for (const stream of peer.link.remoteStreams.values()) {
1192
- out.push([peer.id, stream]);
1713
+ for (const stream of link.remoteStreams.values()) {
1714
+ out.push([peer.id, stream, remoteMetaFor(link, stream.id)]);
1193
1715
  }
1194
1716
  }
1195
1717
  return out;