sueta / client / src / lib / mesh.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**
 * Full-mesh WebRTC manager: one RTCPeerConnection per remote peer, perfect
 * negotiation, symmetric negotiated datachannels, ICE-restart recovery, and
 * E2E-encrypted transport for JSON + binary payloads. docs/PROTOCOL.md §6.
 */

import type { Bytes, Envelope, RoomCrypto } from "./crypto";
import type { PeerConnState, SignalPayload } from "./protocol";
import type { Signaling } from "./signaling";
import type { IceConfig } from "./turn";

export interface MeshEvents {
  /** Connection state / display-name change for a peer. */
  peerState(peer: string, state: PeerConnState, name: string | undefined): void;
  /** Peer is gone for good (left or unrecoverable). */
  peerGone(peer: string): void;
  /** Decrypted JSON payload from a peer's datachannel. */
  message(from: string, payload: unknown): void;
  /** Decrypted binary payload from a peer's datachannel. */
  binary(from: string, data: Uint8Array): void;
  /** A datachannel to a peer just opened (good moment to say hello). */
  channelOpen(peer: string): void;
  /** Remote media stream from a peer (fires on ontrack; re-fires after pc rebuild). */
  track(peer: string, stream: MediaStream): void;
}

const UNDECRYPTABLE_DROP_MS = 15_000;
const FAILED_REBUILD_MS = 10_000;
const BACKPRESSURE_HIGH = 1 << 20; // 1 MiB
const BACKPRESSURE_LOW = 256 << 10;

class Peer {
  pc!: RTCPeerConnection;
  dc!: RTCDataChannel;
  readonly id: string;
  readonly polite: boolean;
  name: string | undefined;
  state: PeerConnState = "connecting";

  makingOffer = false;
  ignoreOffer = false;
  settingRemoteAnswer = false;
  hadValidSignal = false;
  /** Serializes signal handling per peer — candidates must not race the offer. */
  queue: Promise<void> = Promise.resolve();
  /** Candidates that arrived before the remote description was set. */
  pendingCandidates: (RTCIceCandidateInit | null)[] = [];
  /** Declarative desired outgoing media; re-applied after pc rebuilds. */
  wantedStream: MediaStream | null = null;
  maxVideoKbps: number | undefined;
  /** Serializes attach/detach — a late applyMedia must never undo a detach. */
  mediaQueue: Promise<void> = Promise.resolve();
  dropTimer: ReturnType<typeof setTimeout> | null = null;
  rebuildTimer: ReturnType<typeof setTimeout> | null = null;

  constructor(id: string, myId: string) {
    this.id = id;
    this.polite = myId < id;
  }

  destroy() {
    if (this.dropTimer) clearTimeout(this.dropTimer);
    if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
    try {
      this.dc?.close();
    } catch {}
    try {
      this.pc?.close();
    } catch {}
  }
}

export class Mesh {
  #crypto: RoomCrypto;
  #signaling: Signaling;
  #ice: IceConfig;
  #ev: MeshEvents;
  #myName: () => string;
  #peers = new Map<string, Peer>();
  #closed = false;

  constructor(opts: {
    crypto: RoomCrypto;
    signaling: Signaling;
    ice: IceConfig;
    events: MeshEvents;
    /** Called whenever we need our current display name for signal payloads. */
    myName: () => string;
  }) {
    this.#crypto = opts.crypto;
    this.#signaling = opts.signaling;
    this.#ice = opts.ice;
    this.#ev = opts.events;
    this.#myName = opts.myName;
  }

  get myId(): string {
    return this.#crypto.peerId;
  }

  peerNames(): Map<string, string | undefined> {
    return new Map([...this.#peers.values()].map((p) => [p.id, p.name]));
  }

  /** Dev diagnostics. */
  debugState(): Record<string, unknown>[] {
    return [...this.#peers.values()].map((p) => ({
      id: p.id,
      polite: p.polite,
      pc: p.pc?.connectionState,
      ice: p.pc?.iceConnectionState,
      signaling: p.pc?.signalingState,
      dc: p.dc?.readyState,
      name: p.name,
      tx: p.pc?.getTransceivers().length ?? 0,
      sending: p.pc?.getSenders().filter((s) => s.track).length ?? 0,
    }));
  }

  /** Wire these three into the Signaling events. */
  onPeers(list: string[]): void {
    const listed = new Set(list);
    for (const id of list) {
      if (id === this.myId) continue;
      const existing = this.#peers.get(id);
      if (!existing) {
        // We are the (re)joiner: we initiate. Existing peers wait for our offer.
        void this.#createPeer(id, true);
      } else if (isDead(existing.pc) && this.myId < id) {
        void this.#rebuild(existing);
      }
    }
    // Peers we know that the server no longer lists: keep only live channels.
    for (const p of [...this.#peers.values()]) {
      if (!listed.has(p.id) && p.dc?.readyState !== "open") this.#drop(p);
    }
  }

  onPeerJoined(id: string): void {
    if (id === this.myId || this.#peers.has(id)) return;
    // Don't initiate (joiner initiates) — but track them and enforce the
    // 15s "must produce a decryptable signal" rule against server-injected peers.
    const peer = new Peer(id, this.myId);
    this.#peers.set(id, peer);
    peer.dropTimer = setTimeout(() => {
      if (!peer.hadValidSignal) this.#drop(peer);
    }, UNDECRYPTABLE_DROP_MS);
  }

  onPeerLeft(id: string): void {
    const p = this.#peers.get(id);
    if (!p) return;
    // Their signaling socket died. If the datachannel still works, keep chatting.
    if (p.dc?.readyState !== "open") this.#drop(p);
  }

  async onSignal(from: string, env: Envelope): Promise<void> {
    if (this.#closed) return;
    const payload = (await this.#crypto.openSignal(from, env)) as SignalPayload | null;
    if (!payload) return; // undecryptable ⇒ not a room member ⇒ ignore
    let peer = this.#peers.get(from);
    if (!peer) {
      peer = new Peer(from, this.myId);
      this.#peers.set(from, peer);
    }
    peer.hadValidSignal = true;
    if (peer.dropTimer) {
      clearTimeout(peer.dropTimer);
      peer.dropTimer = null;
    }
    if (payload.name && payload.name !== peer.name) {
      peer.name = payload.name;
      this.#emitState(peer);
    }
    // Serialize per peer: an ICE candidate must never race setRemoteDescription.
    peer.queue = peer.queue.then(async () => {
      if (!peer.pc) await this.#setupPC(peer);
      await this.#handleSignal(peer, payload);
    });
    await peer.queue;
  }

  /** Seal once, broadcast to every open channel. */
  async broadcast(payload: unknown): Promise<void> {
    const env = await this.#crypto.sealMsg(payload);
    const text = JSON.stringify(env);
    for (const p of this.#peers.values()) {
      if (p.dc?.readyState === "open") {
        try {
          p.dc.send(text);
        } catch {}
      }
    }
  }

  // media (calls) — one transceiver per kind per peer, forever; toggles are
  // replaceTrack (no renegotiation), full detach flips direction to inactive.

  /**
   * Declaratively set the media sent to one peer. Diffs against current
   * senders; a stream missing a kind soft-mutes it. Survives pc rebuilds.
   */
  attachMedia(peerId: string, stream: MediaStream, opts?: { maxVideoKbps?: number }): boolean {
    const peer = this.#peers.get(peerId);
    if (!peer?.pc) return false;
    peer.wantedStream = stream;
    if (opts?.maxVideoKbps !== undefined) peer.maxVideoKbps = opts.maxVideoKbps;
    peer.mediaQueue = peer.mediaQueue.then(() => this.#applyMedia(peer));
    return true;
  }

  /** Stop sending AND receiving media with this peer (dc unaffected). */
  detachMedia(peerId: string): void {
    const peer = this.#peers.get(peerId);
    if (!peer?.pc) return;
    peer.wantedStream = null;
    peer.mediaQueue = peer.mediaQueue.then(async () => {
      if (peer.wantedStream) return; // re-attached since — skip the stale detach
      for (const t of peer.pc.getTransceivers()) {
        if (t.receiver.track?.kind === undefined) continue;
        await t.sender.replaceTrack(null).catch(() => {});
        try {
          t.direction = "inactive";
        } catch {}
      }
    });
  }

  detachAllMedia(): void {
    for (const id of [...this.#peers.keys()]) this.detachMedia(id);
  }

  async #applyMedia(peer: Peer): Promise<void> {
    const pc = peer.pc;
    if (!pc || pc.connectionState === "closed") return;
    for (const kind of ["audio", "video"] as const) {
      const want = peer.wantedStream?.getTracks().find((t) => t.kind === kind) ?? null;
      const tx = pc.getTransceivers().find((t) => t.receiver.track?.kind === kind);
      try {
        if (want) {
          if (tx) {
            if (tx.sender.track !== want) await tx.sender.replaceTrack(want);
            if (tx.direction !== "sendrecv") tx.direction = "sendrecv";
          } else {
            pc.addTrack(want, peer.wantedStream!);
          }
        } else if (tx?.sender.track) {
          await tx.sender.replaceTrack(null); // soft mute — no renegotiation
        }
      } catch (err) {
        console.warn("applyMedia", kind, err);
      }
    }
    // bitrate cap on the video sender (relayed pairs get a lower cap)
    const vSender = pc.getSenders().find((s) => s.track?.kind === "video");
    if (vSender && peer.maxVideoKbps) {
      try {
        const p = vSender.getParameters();
        p.encodings = p.encodings?.length ? p.encodings : [{}];
        p.encodings[0].maxBitrate = peer.maxVideoKbps * 1000;
        await vSender.setParameters(p);
      } catch {}
    }
  }

  /** Directed send to one peer (same per-sender sealing as broadcast). */
  async sendTo(peerId: string, payload: unknown): Promise<boolean> {
    const p = this.#peers.get(peerId);
    if (p?.dc?.readyState !== "open") return false;
    const env = await this.#crypto.sealMsg(payload);
    try {
      p.dc.send(JSON.stringify(env));
      return true;
    } catch {
      return false;
    }
  }

  /** Directed binary send to one peer, with backpressure. */
  async sendBinaryTo(peerId: string, data: Bytes): Promise<void> {
    const p = this.#peers.get(peerId);
    if (p?.dc?.readyState !== "open") return;
    const sealed = await this.#crypto.sealMsgBinary(data);
    await this.#sendWithBackpressure(p, sealed);
  }

  /** Seal once, broadcast binary with per-channel backpressure. */
  async broadcastBinary(data: Bytes): Promise<void> {
    const sealed = await this.#crypto.sealMsgBinary(data);
    await Promise.all(
      [...this.#peers.values()]
        .filter((p) => p.dc?.readyState === "open")
        .map((p) => this.#sendWithBackpressure(p, sealed)),
    );
  }

  openChannelCount(): number {
    return this.openPeers().length;
  }

  /** Peer ids with an open datachannel. */
  openPeers(): string[] {
    return [...this.#peers.values()].filter((p) => p.dc?.readyState === "open").map((p) => p.id);
  }

  close(): void {
    this.#closed = true;
    for (const p of this.#peers.values()) p.destroy();
    this.#peers.clear();
  }

  // internals

  async #createPeer(id: string, _initiator: boolean): Promise<void> {
    const peer = new Peer(id, this.myId);
    this.#peers.set(id, peer);
    await this.#setupPC(peer);
    // Creating the negotiated datachannel triggers onnegotiationneeded → offer.
  }

  async #setupPC(peer: Peer): Promise<void> {
    const config = await this.#ice.get();
    if (this.#closed || peer.pc) return;
    const pc = new RTCPeerConnection(config);
    peer.pc = pc;

    // Symmetric negotiated channel: no ondatachannel race, immune to glare.
    const dc = pc.createDataChannel("chat", { negotiated: true, id: 0 });
    dc.binaryType = "arraybuffer";
    peer.dc = dc;
    dc.bufferedAmountLowThreshold = BACKPRESSURE_LOW;
    dc.onopen = () => {
      this.#refreshTransportState(peer);
      this.#ev.channelOpen(peer.id);
    };
    dc.onmessage = (e) => void this.#onChannelMessage(peer, e.data);

    pc.ontrack = (e) => {
      const stream = e.streams[0] ?? new MediaStream([e.track]);
      this.#ev.track(peer.id, stream);
    };

    pc.onnegotiationneeded = async () => {
      try {
        peer.makingOffer = true;
        await pc.setLocalDescription();
        this.#sendSignal(peer.id, { kind: "offer", sdp: pc.localDescription!.sdp, name: this.#myName() });
      } catch (err) {
        console.warn("negotiationneeded failed", err);
      } finally {
        peer.makingOffer = false;
      }
    };
    pc.onicecandidate = (e) => {
      this.#sendSignal(peer.id, { kind: "ice", candidate: e.candidate ? e.candidate.toJSON() : null, name: this.#myName() });
    };
    pc.onconnectionstatechange = () => {
      switch (pc.connectionState) {
        case "connected":
          if (peer.rebuildTimer) {
            clearTimeout(peer.rebuildTimer);
            peer.rebuildTimer = null;
          }
          this.#refreshTransportState(peer);
          break;
        case "disconnected":
          peer.state = "disconnected";
          this.#emitState(peer);
          break;
        case "failed":
          peer.state = "disconnected";
          this.#emitState(peer);
          pc.restartIce();
          peer.rebuildTimer ??= setTimeout(() => {
            peer.rebuildTimer = null;
            // Deterministic single re-initiator avoids a double rebuild.
            if (isDead(pc) && this.#signaling.connected && this.myId < peer.id) void this.#rebuild(peer);
          }, FAILED_REBUILD_MS);
          break;
        case "closed":
          break;
      }
    };

    // rebuild path: a fresh pc must get the media the app still wants
    if (peer.wantedStream) void this.#applyMedia(peer);
  }

  async #handleSignal(peer: Peer, payload: SignalPayload): Promise<void> {
    const pc = peer.pc;
    try {
      if (payload.kind === "offer" || payload.kind === "answer") {
        const description: RTCSessionDescriptionInit = { type: payload.kind, sdp: payload.sdp };
        const readyForOffer = !peer.makingOffer && (pc.signalingState === "stable" || peer.settingRemoteAnswer);
        const offerCollision = description.type === "offer" && !readyForOffer;
        peer.ignoreOffer = !peer.polite && offerCollision;
        if (peer.ignoreOffer) return;
        peer.settingRemoteAnswer = description.type === "answer";
        await pc.setRemoteDescription(description);
        peer.settingRemoteAnswer = false;
        for (const c of peer.pendingCandidates.splice(0)) await this.#addCandidate(peer, c);
        if (description.type === "offer") {
          await pc.setLocalDescription();
          this.#sendSignal(peer.id, { kind: "answer", sdp: pc.localDescription!.sdp, name: this.#myName() });
        }
      } else if (payload.kind === "ice") {
        if (!pc.remoteDescription) {
          peer.pendingCandidates.push(payload.candidate);
        } else {
          await this.#addCandidate(peer, payload.candidate);
        }
      }
    } catch (err) {
      console.warn("signal handling failed", err);
    }
  }

  async #addCandidate(peer: Peer, candidate: RTCIceCandidateInit | null): Promise<void> {
    try {
      await peer.pc.addIceCandidate(candidate ?? undefined);
    } catch (err) {
      if (!peer.ignoreOffer) console.warn("addIceCandidate failed", err);
    }
  }

  #sendSignal(to: string, payload: SignalPayload): void {
    void this.#crypto.sealSignal(to, payload).then((env) => this.#signaling.signal(to, env));
  }

  async #onChannelMessage(peer: Peer, data: string | ArrayBuffer): Promise<void> {
    if (typeof data === "string") {
      let env: Envelope;
      try {
        env = JSON.parse(data);
      } catch {
        return;
      }
      const payload = await this.#crypto.openMsg(peer.id, env);
      if (payload !== null) this.#ev.message(peer.id, payload);
    } else {
      const plain = await this.#crypto.openMsgBinary(peer.id, data);
      if (plain) this.#ev.binary(peer.id, plain);
    }
  }

  #sendWithBackpressure(peer: Peer, data: ArrayBuffer): Promise<void> {
    return new Promise((resolve) => {
      const dc = peer.dc;
      if (dc.readyState !== "open") return resolve();
      if (dc.bufferedAmount <= BACKPRESSURE_HIGH) {
        try {
          dc.send(data);
        } catch {}
        return resolve();
      }
      const onLow = () => {
        dc.removeEventListener("bufferedamountlow", onLow);
        if (dc.readyState === "open") {
          try {
            dc.send(data);
          } catch {}
        }
        resolve();
      };
      dc.addEventListener("bufferedamountlow", onLow);
    });
  }

  async #refreshTransportState(peer: Peer): Promise<void> {
    peer.state = "connecting";
    try {
      const stats = await peer.pc.getStats();
      let selected: RTCIceCandidatePairStats | undefined;
      const locals = new Map<string, { candidateType?: string }>();
      stats.forEach((s) => {
        if (s.type === "local-candidate") locals.set(s.id, s as { candidateType?: string });
        if (s.type === "candidate-pair" && (s as RTCIceCandidatePairStats).nominated && s.state === "succeeded") {
          selected = s as RTCIceCandidatePairStats;
        }
        if (s.type === "transport" && (s as { selectedCandidatePairId?: string }).selectedCandidatePairId) {
          const pair = stats.get((s as { selectedCandidatePairId: string }).selectedCandidatePairId);
          if (pair) selected = pair as RTCIceCandidatePairStats;
        }
      });
      const local = selected && locals.get(selected.localCandidateId);
      peer.state = local?.candidateType === "relay" ? "relayed" : "direct";
    } catch {
      peer.state = "direct";
    }
    this.#emitState(peer);
  }

  #emitState(peer: Peer): void {
    this.#ev.peerState(peer.id, peer.state, peer.name);
  }

  async #rebuild(peer: Peer): Promise<void> {
    const stream = peer.wantedStream;
    const kbps = peer.maxVideoKbps;
    this.#drop(peer, /* silent */ true);
    await this.#createPeer(peer.id, true);
    // the rebuilt Peer is a fresh object — carry the desired media over so
    // a mid-call rebuild resumes sending (setupPC applied it if set pre-await;
    // attachMedia here covers the created-after-await ordering)
    const fresh = this.#peers.get(peer.id);
    if (fresh && stream) {
      fresh.maxVideoKbps = kbps;
      this.attachMedia(peer.id, stream, kbps !== undefined ? { maxVideoKbps: kbps } : undefined);
    }
  }

  #drop(peer: Peer, silent = false): void {
    peer.destroy();
    this.#peers.delete(peer.id);
    if (!silent) this.#ev.peerGone(peer.id);
  }
}

function isDead(pc: RTCPeerConnection | undefined): boolean {
  return !pc || pc.connectionState === "failed" || pc.connectionState === "closed";
}