cautpartener / client / src / lib / net.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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/**
 * libp2p transport for the sueta p2p stack (v2). Replaces signaling.ts and the
 * datachannel half of mesh.ts: one libp2p node per session with an ephemeral
 * Ed25519 identity, a websocket connection to a circuit-relay-v2 node, peer
 * discovery over the relay's shared pubsub topic, and direct browser-to-browser
 * WebRTC upgrades. See docs/PROTOCOL.md v2.
 *
 * Membership model: a discovered peer is only surfaced to the app after it
 * proves room membership with a presence beacon that decrypts under the room's
 * keys (the v1 "undecryptable peers get dropped" rule, §3). The relay and
 * unrelated peers on it see only an opaque topic string and sealed envelopes;
 * room traffic itself never touches the relay — gossipsub rides the direct
 * member-to-member connections.
 */

import { gossipsub } from "@chainsafe/libp2p-gossipsub";
import { noise } from "@chainsafe/libp2p-noise";
import { yamux } from "@chainsafe/libp2p-yamux";
import { bootstrap } from "@libp2p/bootstrap";
import { circuitRelayTransport } from "@libp2p/circuit-relay-v2";
import { generateKeyPair } from "@libp2p/crypto/keys";
import { identify } from "@libp2p/identify";
import { peerIdFromPrivateKey } from "@libp2p/peer-id";
import { ping } from "@libp2p/ping";
import { pubsubPeerDiscovery } from "@libp2p/pubsub-peer-discovery";
import { webRTC } from "@libp2p/webrtc";
import { webSockets } from "@libp2p/websockets";
import { multiaddr } from "@multiformats/multiaddr";
import { createLibp2p, type Libp2p } from "libp2p";
import type { PingService } from "@libp2p/ping";
import * as lp from "it-length-prefixed";
import { pushable, type Pushable } from "it-pushable";
import { pipe } from "it-pipe";
import type { PrivateKey, Stream, Connection, PeerId, PubSub } from "@libp2p/interface";
import type { GossipsubEvents } from "@chainsafe/libp2p-gossipsub";
import type { Envelope, RoomCrypto, Bytes } from "./crypto";
import type { PeerConnState } from "./protocol";
import type { IceConfig } from "./turn";

const MSG_PROTOCOL = "/sueta/2/msg/1.0";
const BEACON_MS = 10_000; // presence heartbeat
const STALE_MS = 30_000; // no decryptable beacon for this long ⇒ gone
const STRANGER_DROP_MS = 20_000; // connected but never proved membership ⇒ hang up
const PING_MS = 25_000; // relay liveness probe (mobile TCP half-open)
const MAX_FRAME = 256 * 1024; // matches v1 relay cap; images are chunked below this

/** Fresh network identity for this session; the relay can't link page loads. */
export async function newSessionKey(): Promise<{ privateKey: PrivateKey; peerId: string }> {
  const privateKey = await generateKeyPair("Ed25519");
  return { privateKey, peerId: peerIdFromPrivateKey(privateKey).toString() };
}

export interface NetEvents {
  /** Membership-verified peer appeared or its transport state changed. */
  peerState(peer: string, state: PeerConnState, name: string | undefined): void;
  peerGone(peer: string): void;
  /** Decrypted broadcast or directed JSON payload. */
  message(from: string, payload: unknown): void;
  /** Decrypted directed binary payload. */
  binary(from: string, data: Uint8Array): void;
  /** Peer is connected + membership-verified; safe to sendTo (v1 channelOpen). */
  peerReady(peer: string): void;
  /** Relay connectivity, for the signaling dot in the UI. */
  status(up: boolean): void;
}

interface PresenceBeacon {
  kind: "presence";
  op: "beacon" | "bye";
  name: string;
  ts: number;
}

interface OutChannel {
  push: Pushable<Uint8Array>;
  stream: Stream;
}

interface PeerRec {
  state: PeerConnState;
  name?: string;
  lastBeacon: number; // 0 = never verified
  firstSeen: number;
  lastDialAt: number; // dial throttle (upgrade attempts ride the beacon cadence)
  beaconedAt: number; // directed-beacon throttle (pre-upgrade membership proof)
  ready: boolean;
  out: Map<string, OutChannel>; // per stream protocol
}

type SuetaNode = Libp2p<{ identify: unknown; ping: PingService; pubsub: PubSub<GossipsubEvents> }>;

export class Net {
  readonly libp2p: SuetaNode;
  #crypto: RoomCrypto;
  #events: NetEvents;
  #myName: () => string;
  #relayAddr: string;
  #relayPeer: string;
  #peers = new Map<string, PeerRec>();
  #timers: ReturnType<typeof setInterval>[] = [];
  #redialTimer: ReturnType<typeof setTimeout> | null = null;
  #redialAttempt = 0;
  #windowListeners: [string, () => unknown][] = [];
  #relayUp = false;
  #closed = false;

  private constructor(
    node: SuetaNode,
    crypto: RoomCrypto,
    events: NetEvents,
    myName: () => string,
    relayAddr: string,
  ) {
    this.libp2p = node;
    this.#crypto = crypto;
    this.#events = events;
    this.#myName = myName;
    this.#relayAddr = relayAddr;
    this.#relayPeer = relayAddr.split("/p2p/").pop() ?? "";
  }

  get myId(): string {
    return this.libp2p.peerId.toString();
  }

  static async create(opts: {
    privateKey: PrivateKey;
    crypto: RoomCrypto;
    ice: IceConfig;
    relayMultiaddr: string;
    discoveryTopic: string;
    myName: () => string;
    events: NetEvents;
  }): Promise<Net> {
    const node = await createLibp2p({
      privateKey: opts.privateKey,
      addresses: { listen: ["/p2p-circuit", "/webrtc"] },
      transports: [
        webSockets(),
        webRTC({ rtcConfiguration: () => opts.ice.get() }),
        circuitRelayTransport(),
      ],
      connectionEncrypters: [noise()],
      streamMuxers: [yamux()],
      peerDiscovery: [
        bootstrap({ list: [opts.relayMultiaddr] }),
        pubsubPeerDiscovery({ interval: 5000, topics: [opts.discoveryTopic] }),
      ],
      services: {
        identify: identify(),
        ping: ping(),
        // gossipsub deliberately does NOT run on limited (circuit) connections:
        // its streams must only ever bind to direct webrtc connections, so an
        // established mesh keeps flowing when the relay dies. Pre-upgrade
        // membership proof rides DIRECTED beacons on the msg stream instead
        // (handleFrames/sendFrame run on limited connections).
        pubsub: gossipsub({ allowPublishToZeroTopicPeers: true, emitSelf: false }),
      },
      connectionManager: { maxConnections: 32 },
    });

    const net = new Net(node, opts.crypto, opts.events, opts.myName, opts.relayMultiaddr);
    await net.#start();
    return net;
  }

  #pubsub(): PubSub<GossipsubEvents> {
    return this.libp2p.services.pubsub;
  }

  async #start(): Promise<void> {
    const node = this.libp2p;

    await this.handleFrames(MSG_PROTOCOL, (from, frame) => void this.#onMsgFrame(from, frame));

    node.addEventListener("peer:discovery", (e) => {
      const id = e.detail.id.toString();
      if (id === this.#relayPeer || id === this.myId) return;
      void this.#dialPeer(e.detail.id);
    });

    node.addEventListener("connection:open", (e) => this.#onConnChange(e.detail));
    node.addEventListener("connection:close", (e) => this.#onConnChange(e.detail));

    const ps = this.#pubsub();
    ps.subscribe(this.#crypto.roomTopic);
    ps.addEventListener("message", (e) => {
      if (e.detail.topic !== this.#crypto.roomTopic) return;
      const from = (e.detail as { from?: PeerId }).from?.toString();
      if (!from || from === this.myId) return;
      void this.#onTopicMessage(from, e.detail.data);
    });

    // presence heartbeat + stale sweep
    this.#timers.push(setInterval(() => void this.#beacon("beacon"), BEACON_MS));
    this.#timers.push(setInterval(() => this.#sweep(), 5000));
    // relay liveness: ping; two consecutive failures force a redial
    let pingFails = 0;
    this.#timers.push(
      setInterval(() => {
        if (!this.#relayUp || this.#closed) return;
        const relay = this.#relayPeerId();
        if (!relay) return;
        this.libp2p.services.ping
          .ping(relay, { signal: AbortSignal.timeout(10_000) })
          .then(() => (pingFails = 0))
          .catch(async () => {
            if (++pingFails >= 2) {
              pingFails = 0;
              await this.libp2p.hangUp(relay).catch(() => {});
            }
          });
      }, PING_MS),
    );

    // mobile wake: check the relay connection immediately and re-announce.
    // Handlers are kept so close() can remove them — a consumer that creates
    // and closes Nets without a page reload must not leak them (each closure
    // retains the whole node).
    const kick = () => {
      if (this.#closed) return;
      this.#redialAttempt = 0;
      this.#ensureRelay();
      void this.#beacon("beacon");
    };
    this.#windowListeners = [
      ["visibilitychange", () => document.visibilityState === "visible" && kick()],
      ["pageshow", kick],
      ["online", kick],
      ["pagehide", () => void this.#beacon("bye")],
    ];
    for (const [evt, fn] of this.#windowListeners) window.addEventListener(evt, fn);

    this.#ensureRelay();
    void this.#beacon("beacon");
  }

  #relayPeerId(): PeerId | null {
    for (const c of this.libp2p.getConnections()) {
      if (c.remotePeer.toString() === this.#relayPeer) return c.remotePeer;
    }
    return null;
  }

  // ---- relay connection management -----------------------------------------

  #ensureRelay(): void {
    if (this.#closed) return;
    const connected = this.libp2p
      .getConnections()
      .some((c) => c.remotePeer.toString() === this.#relayPeer && c.status === "open");
    if (connected) {
      this.#setRelayUp(true);
      return;
    }
    this.#setRelayUp(false);
    void this.libp2p
      .dial(multiaddr(this.#relayAddr), { signal: AbortSignal.timeout(15_000) })
      .then(() => {
        this.#redialAttempt = 0;
        this.#setRelayUp(true);
      })
      .catch(() => this.#scheduleRedial());
  }

  #scheduleRedial(): void {
    if (this.#redialTimer || this.#closed) return;
    // jittered exponential backoff, same shape as v1 signaling.ts
    const base = Math.min(15_000, 500 * 2 ** this.#redialAttempt++);
    const delay = base * (0.5 + Math.random());
    this.#redialTimer = setTimeout(() => {
      this.#redialTimer = null;
      this.#ensureRelay();
    }, delay);
  }

  #setRelayUp(up: boolean): void {
    if (this.#relayUp !== up) {
      this.#relayUp = up;
      this.#events.status(up);
    }
  }

  // ---- peer lifecycle ------------------------------------------------------

  /**
   * Two-stage dialing (quota + privacy): a DISCOVERED peer is dialed over the
   * bare relay circuit only — cheap, no ICE, no TURN allocation, and the peer
   * never sees any of our candidates. Only once it PROVES membership (§4b:
   * something it sent decrypted) do we dial the WebRTC upgrade, which gathers
   * ICE and — under `&relay` — consumes a coturn allocation. Strangers from
   * the shared discovery topic therefore cost nothing and learn nothing;
   * without this, ~7 stranger dials could exhaust user-quota=16 and starve
   * the call media pcs (seen live as "486 TURN allocate error").
   */
  async #dialPeer(id: PeerId | string): Promise<void> {
    if (this.#closed) return;
    const idStr = id.toString();
    const rec = this.#recFor(idStr); // starts the stranger-drop clock
    const verified = rec.lastBeacon > 0;
    const conns = this.libp2p.getConnections().filter((c) => c.remotePeer.toString() === idStr && c.status === "open");
    const upgraded = conns.some((c) => c.remoteAddr.toString().includes("/webrtc"));
    if (verified ? upgraded : conns.length > 0) return;
    if (Date.now() - rec.lastDialAt < 15_000) return; // an attempt is in flight
    rec.lastDialAt = Date.now();
    const ma = multiaddr(
      verified
        ? `${this.#relayAddr}/p2p-circuit/webrtc/p2p/${idStr}` // member: upgrade to direct
        : `${this.#relayAddr}/p2p-circuit/p2p/${idStr}`, // unknown: circuit probe only
    );
    await this.libp2p.dial(ma, { signal: AbortSignal.timeout(30_000) }).catch(() => {
      /* the other side may dial us instead */
    });
  }

  #recFor(id: string): PeerRec {
    let rec = this.#peers.get(id);
    if (!rec) {
      rec = {
        state: "connecting",
        lastBeacon: 0,
        firstSeen: Date.now(),
        lastDialAt: 0,
        beaconedAt: 0,
        ready: false,
        out: new Map(),
      };
      this.#peers.set(id, rec);
    }
    return rec;
  }

  #onConnChange(conn: Connection): void {
    const id = conn.remotePeer.toString();
    if (id === this.#relayPeer) {
      const stillUp = this.libp2p
        .getConnections()
        .some((c) => c.remotePeer.toString() === this.#relayPeer && c.status === "open");
      this.#setRelayUp(stillUp);
      if (!stillUp) this.#scheduleRedial();
      return;
    }
    const rec = this.#peers.get(id);
    if (!rec) return;
    this.#refreshState(id, rec, true);
    this.#maybeReady(id, rec);
    // fresh contact over a bare circuit: hand them our membership proof
    // (gossipsub can't — it only runs on direct connections)
    if (conn.status === "open" && !rec.ready) this.#beaconTo(id);
  }

  #refreshState(id: string, rec: PeerRec, emit: boolean): void {
    const conns = this.libp2p
      .getConnections()
      .filter((c) => c.remotePeer.toString() === id && c.status === "open");
    let state: PeerConnState;
    if (conns.length === 0) {
      state = rec.lastBeacon ? "disconnected" : "connecting";
      rec.ready = false;
      this.#endChannels(rec);
    } else if (conns.some((c) => c.remoteAddr.toString().includes("/webrtc"))) {
      state = "direct";
    } else {
      state = "relayed"; // circuit only — privacy unaffected (sealed e2e), just slower
    }
    if (state !== rec.state) {
      rec.state = state;
      if (emit && rec.lastBeacon) this.#events.peerState(id, state, rec.name);
    }
  }

  /** peerReady = live connection + proven membership, fired once per session. */
  #maybeReady(id: string, rec: PeerRec): void {
    const hasConn = this.libp2p
      .getConnections()
      .some((c) => c.remotePeer.toString() === id && c.status === "open");
    if (!rec.ready && hasConn && rec.lastBeacon) {
      rec.ready = true;
      this.#events.peerReady(id);
    }
  }

  #sweep(): void {
    const now = Date.now();
    for (const [id, rec] of this.#peers) {
      if (rec.lastBeacon) {
        if (now - rec.lastBeacon > STALE_MS) {
          this.#dropPeer(id, rec);
        }
      } else if (now - rec.firstSeen > STRANGER_DROP_MS) {
        // connected (or discovered) but never sent a decryptable beacon:
        // not a member of this room — disconnect quietly (v1 §3 rule)
        this.#peers.delete(id);
        this.#hangUpStr(id);
      }
    }
  }

  #endChannels(rec: PeerRec): void {
    for (const chan of rec.out.values()) chan.push.end();
    rec.out.clear();
  }

  #dropPeer(id: string, rec: PeerRec): void {
    this.#endChannels(rec);
    this.#peers.delete(id);
    this.#hangUpStr(id);
    if (rec.lastBeacon) this.#events.peerGone(id);
  }

  #hangUpStr(id: string): void {
    const conn = this.libp2p.getConnections().find((c) => c.remotePeer.toString() === id);
    if (conn) void this.libp2p.hangUp(conn.remotePeer).catch(() => {});
  }

  // ---- room topic (broadcast + presence) -----------------------------------

  #lastBeaconAt = 0;

  async #beacon(op: "beacon" | "bye"): Promise<void> {
    if (this.#closed) return;
    if (op === "beacon") this.#lastBeaconAt = Date.now();
    const b: PresenceBeacon = { kind: "presence", op, name: this.#myName(), ts: Date.now() };
    await this.broadcast(b).catch(() => {});
  }

  /**
   * Any payload that decrypts under the room keys IS proof of membership
   * (v1 §3: decryptability is the trust boundary). Called for every decrypted
   * inbound payload so directed messages from a peer whose beacon hasn't
   * arrived yet still verify it — e.g. a hist-req right after joining.
   */
  #verified(from: string): PeerRec {
    const rec = this.#recFor(from);
    const first = rec.lastBeacon === 0;
    rec.lastBeacon = Date.now();
    this.#refreshState(from, rec, !first);
    if (first) {
      this.#events.peerState(from, rec.state, rec.name);
      this.#maybeReady(from, rec);
      // fast hello: answer with our own beacon so the new member verifies us
      // without waiting out the 10s cadence (throttled against beacon loops);
      // the directed copy reaches them even while we're still circuit-only
      if (Date.now() - this.#lastBeaconAt > 2000) void this.#beacon("beacon");
      this.#beaconTo(from);
      // membership proven — NOW spend the WebRTC upgrade on this peer
      rec.lastDialAt = 0;
      void this.#dialPeer(from);
    }
    return rec;
  }

  async #onTopicMessage(from: string, data: Uint8Array): Promise<void> {
    let env: Envelope;
    try {
      env = JSON.parse(new TextDecoder().decode(data)) as Envelope;
    } catch {
      return;
    }
    const payload = await this.#crypto.openMsg(from, env);
    if (payload === null) return; // not a member (or tampered) — drop silently
    const p = payload as Partial<PresenceBeacon>;
    if (p.kind === "presence") {
      this.#onPresence(from, p);
      return;
    }
    this.#verified(from);
    this.#events.message(from, payload);
  }

  /** Presence handling, shared by the room topic and the directed msg stream. */
  #onPresence(from: string, p: Partial<PresenceBeacon>): void {
    if (p.op === "bye") {
      const known = this.#peers.get(from);
      if (known?.lastBeacon) this.#dropPeer(from, known);
      return;
    }
    const prev = this.#peers.get(from);
    const wasKnown = (prev?.lastBeacon ?? 0) > 0;
    const prevName = prev?.name;
    if (typeof p.name === "string") this.#recFor(from).name = p.name;
    const rec = this.#verified(from);
    if (wasKnown && rec.name !== prevName) this.#events.peerState(from, rec.state, rec.name);
    // keep verified members converging on a direct connection: #dialPeer
    // no-ops when already upgraded and self-throttles between attempts
    void this.#dialPeer(from);
  }

  /**
   * Directed sealed beacon: the pre-upgrade membership proof. Gossipsub only
   * runs on direct connections, so a peer we just met over a bare circuit
   * would never see our topic beacons — this hands them one over the msg
   * stream (which does run on limited connections). Decrypting it proves OUR
   * membership; their directed reply proves theirs; then both sides upgrade.
   */
  #beaconTo(peer: string): void {
    const rec = this.#recFor(peer);
    if (Date.now() - rec.beaconedAt < 5000) return;
    rec.beaconedAt = Date.now();
    void this.sendTo(peer, { kind: "presence", op: "beacon", name: this.#myName(), ts: Date.now() })
  }

  /** Seal once, deliver to every connected member via the room topic. */
  async broadcast(payload: unknown): Promise<void> {
    const env = await this.#crypto.sealMsg(payload);
    const bytes = new TextEncoder().encode(JSON.stringify(env));
    await this.#pubsub()
      .publish(this.#crypto.roomTopic, bytes)
      .catch(() => {}); // alone in the room is fine
  }

  // ---- directed streams (generic per-protocol frame channels) --------------

  /**
   * Register a length-prefixed frame handler for a stream protocol. Frames are
   * raw bytes — the caller does its own sealing/opening (lib/media.ts uses
   * kSig-sealed signaling envelopes on /sueta/2/call-sig/1.0).
   */
  async handleFrames(protocol: string, onFrame: (from: string, frame: Uint8Array) => void): Promise<void> {
    await this.libp2p.handle(
      protocol,
      ({ stream, connection }) => {
        const from = connection.remotePeer.toString();
        void pipe(stream, (s) => lp.decode(s, { maxDataLength: MAX_FRAME }), async (frames) => {
          for await (const frame of frames) onFrame(from, frame.subarray());
        }).catch(() => {}); // stream reset — sender reopens on next send
      },
      // sealed frames must work over bare relay circuits (pre-upgrade members,
      // the "relayed" fallback) — the crypto layer, not the transport, gates trust
      { runOnLimitedConnection: true },
    );
  }

  /** Send one frame on a per-(peer, protocol) persistent outbound stream. */
  async sendFrame(protocol: string, peer: string, frame: Uint8Array): Promise<boolean> {
    // transport-level: no membership gate here — replies to decrypted directed
    // messages may target peers whose beacon hasn't arrived yet
    const rec = this.#recFor(peer);
    const existing = rec.out.get(protocol);
    if (existing && existing.stream.status === "open") {
      existing.push.push(frame);
      return true;
    }
    const pid = this.libp2p.getPeers().find((x) => x.toString() === peer);
    const target = pid ?? multiaddr(`${this.#relayAddr}/p2p-circuit/webrtc/p2p/${peer}`);
    try {
      const stream = await this.libp2p.dialProtocol(target as never, protocol, {
        signal: AbortSignal.timeout(15_000),
        runOnLimitedConnection: true,
      });
      const push = pushable<Uint8Array>();
      const chan: OutChannel = { push, stream };
      rec.out.set(protocol, chan);
      void pipe(push, (s) => lp.encode(s), stream).catch(() => {
        if (rec.out.get(protocol) === chan) rec.out.delete(protocol);
      });
      push.push(frame);
      return true;
    } catch {
      return false;
    }
  }

  async #onMsgFrame(from: string, buf: Uint8Array): Promise<void> {
    if (buf.length < 2) return;
    const kind = buf[0];
    const body = buf.subarray(1);
    if (kind === 0x00) {
      let env: Envelope;
      try {
        env = JSON.parse(new TextDecoder().decode(body)) as Envelope;
      } catch {
        return;
      }
      const payload = await this.#crypto.openMsg(from, env);
      if (payload !== null) {
        // directed presence = the pre-upgrade membership handshake — handle
        // like topic presence, don't surface it to the app
        if ((payload as Partial<PresenceBeacon>).kind === "presence") {
          this.#onPresence(from, payload as Partial<PresenceBeacon>);
          return;
        }
        this.#verified(from);
        this.#events.message(from, payload);
      }
    } else if (kind === 0x01) {
      const ab = new ArrayBuffer(body.length);
      new Uint8Array(ab).set(body);
      const data = await this.#crypto.openMsgBinary(from, ab);
      if (data !== null) {
        this.#verified(from);
        this.#events.binary(from, data);
      }
    }
  }

  #frame(kind: number, body: Uint8Array): Uint8Array {
    const out = new Uint8Array(1 + body.length);
    out[0] = kind;
    out.set(body, 1);
    return out;
  }

  /** Directed JSON payload; resolves false if the peer is unreachable. */
  async sendTo(peer: string, payload: unknown): Promise<boolean> {
    const env = await this.#crypto.sealMsg(payload);
    return this.sendFrame(MSG_PROTOCOL, peer, this.#frame(0x00, new TextEncoder().encode(JSON.stringify(env))));
  }

  async sendBinaryTo(peer: string, data: Bytes): Promise<void> {
    const sealed = await this.#crypto.sealMsgBinary(data);
    await this.sendFrame(MSG_PROTOCOL, peer, this.#frame(0x01, new Uint8Array(sealed)));
  }

  /** Binary fan-out to every ready peer. Seals once. */
  async broadcastBinary(data: Bytes): Promise<void> {
    const sealed = new Uint8Array(await this.#crypto.sealMsgBinary(data));
    const frame = this.#frame(0x01, sealed);
    await Promise.all(this.openPeers().map((id) => this.sendFrame(MSG_PROTOCOL, id, frame)));
  }

  // ---- app-facing helpers --------------------------------------------------

  openPeers(): string[] {
    return [...this.#peers.entries()].filter(([, r]) => r.ready).map(([id]) => id);
  }

  debugState(): Record<string, unknown>[] {
    return [...this.#peers.entries()].map(([id, r]) => ({
      id,
      state: r.state,
      name: r.name,
      ready: r.ready,
      verified: r.lastBeacon > 0,
      conns: this.libp2p
        .getConnections()
        .filter((c) => c.remotePeer.toString() === id)
        .map((c) => c.remoteAddr.toString()),
    }));
  }

  get relayUp(): boolean {
    return this.#relayUp;
  }

  async close(): Promise<void> {
    this.#closed = true;
    await this.#beacon("bye").catch(() => {});
    for (const [evt, fn] of this.#windowListeners) window.removeEventListener(evt, fn);
    this.#windowListeners = [];
    for (const t of this.#timers) clearInterval(t);
    if (this.#redialTimer) clearTimeout(this.#redialTimer);
    for (const [, rec] of this.#peers) this.#endChannels(rec);
    await Promise.resolve(this.libp2p.stop()).catch(() => {});
  }
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git