@bom-pi/core 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,9 +28,22 @@
28
28
  * booleans. The envelope is the
29
29
  * entire encoded wire frame at this hop, so a base64url seam payload admits slightly less than
30
30
  * the 1 MiB data bound — a conservative consequence of §16's whole-frame limit, not a relaxation.
31
- * Cloud-initiated RPC requests are refused locally in this candidate: only the daemon's own
32
- * correlated responses are consumed (§6 subscription/relay control is later-phase work). */
31
+ * Cloud-initiated RPC requests are refused locally except the §7 pair-delivery surface
32
+ * (`onCloudDelivery`) — and, since M4 lane B3, X's `relay-close` channel notifications, which
33
+ * dispose the local relay channel state (the wired delivery handler still sees the payload).
34
+ *
35
+ * M4 lane B3 adds the CLIENT side of the relay lane: `relayOpen` probes X's advertised capability
36
+ * with an authenticated `relay-caps` RPC and fails closed on an old cloud (static error, no
37
+ * relay-open frame ever leaves, every existing lane byte-identical). A successful `relay-open`
38
+ * — claim = relation id, grant epoch, both membership refs, requester→target direction; X checks
39
+ * topology and A's central boundary authoritatively re-verifies the grant — stores the channel id
40
+ * and admits §16-bounded binary frames (1 MiB whole-frame gate, empty refused, backpressure
41
+ * bound, oversize refused locally before any write) via `relaySend`/`onRelayData`, with one
42
+ * bounded close notification on teardown (peer notification, local close, or connection loss →
43
+ * `onRelayClosed`). The channel is memory-only: it dies with the connection and nothing about it
44
+ * persists. */
33
45
  import { createPublicKey, randomBytes, verify, type KeyObject } from "node:crypto";
46
+ import { CLOUD_RECEIPT_DOMAIN } from "@bom-pi/protocol/receipt.ts";
34
47
  import {
35
48
  canonicalJson,
36
49
  MAX_CONTROL_BYTES,
@@ -39,6 +52,7 @@ import {
39
52
  type CanonicalValue,
40
53
  } from "@bom-pi/protocol/codec.ts";
41
54
  import { fingerprintPublicKey } from "@bom-pi/protocol/identity.ts";
55
+ import { encodeMuxFrame, MUX_CHANNEL_ID_HEX, parseMuxFrame } from "./relay-mux-wire.ts";
42
56
  import type { IngressClass } from "./ingress-receiver.ts";
43
57
  import {
44
58
  ConnectorStateError,
@@ -50,12 +64,15 @@ import {
50
64
  type PinnedCloud,
51
65
  type ReceiptExpectation,
52
66
  type ReceiptVerifier,
67
+ type RelayCapableTransport,
68
+ type RelayClosedNotice,
69
+ type RelayCloseReason,
70
+ type RelayOpenClaim,
53
71
  type StoredCleanupRequest,
54
72
  } from "./cloud-connector.ts";
55
73
 
56
- // Candidate duplicated literal, byte-identical to apps/bom-cloud/server/pickup-authority.ts
57
- // (packages must not import apps). Leader owns single-sourcing this constant.
58
- const CLOUD_RECEIPT_DOMAIN = "bom-pi/cloud-receipt/v1";
74
+ // REL-13: the cloud-receipt domain literal is single-sourced in
75
+ // @bom-pi/protocol/receipt.ts and imported above; this module only consumes it.
59
76
 
60
77
  const WIRE_VERSION = 1;
61
78
  const TYPE_CONTROL = "control";
@@ -66,6 +83,21 @@ const METHOD_PAIR_OFFER = "pair-offer";
66
83
  const METHOD_PAIR_REDEEM = "pair-redeem";
67
84
  /** X → daemon delivered control request (§7 prepare/provisional over the live connector). */
68
85
  const METHOD_PAIR_DELIVER = "pair-deliver";
86
+ /** M4 lane B3 relay methods: capability probe, channel open, cooperative teardown. */
87
+ const METHOD_RELAY_CAPS = "relay-caps";
88
+ const METHOD_RELAY_OPEN = "relay-open";
89
+ const METHOD_RELAY_CLOSE = "relay-close";
90
+
91
+ /** The fixed close-reason vocabulary a relay notification may carry. Duplicated literal of
92
+ * apps/bom-cloud/server/connect-wss.ts RELAY_CLOSE_REASONS (packages must not import apps). */
93
+ const RELAY_CLOSE_REASONS: ReadonlySet<string> = new Set([
94
+ "overflow",
95
+ "peer-closed",
96
+ "session-ended",
97
+ ]);
98
+
99
+ /** §11/§12 relation ids and X's relay channel ids are exactly 32 hex. */
100
+ const RELAY_ID_HEX = /^[0-9a-f]{32}$/;
69
101
 
70
102
  /** §16 candidate whole-encoded-wire-frame bounds, per ingress class. */
71
103
  const WIRE_LIMIT_BY_CLASS: Record<IngressClass, number> = {
@@ -298,12 +330,49 @@ function storedToWire(stored: StoredCleanupRequest): CanonicalValue {
298
330
  return { request: stored.request, signature: stored.signature };
299
331
  }
300
332
 
333
+ function isRelayCloseReason(value: CanonicalValue | undefined): value is RelayCloseReason {
334
+ return typeof value === "string" && RELAY_CLOSE_REASONS.has(value);
335
+ }
336
+
337
+ /** Structural validation of the §11/§12 routing claim before any wire activity: exactly the five
338
+ * schema fields, a 32-hex relation id, a positive grant epoch and the requester→target direction.
339
+ * Membership refs go through the same strict ref shape every cloud RPC uses. X re-validates the
340
+ * exact schema against the stored relation and live topology; A's central boundary authoritatively
341
+ * re-verifies the grant before anything opens. */
342
+ function relayClaimToWire(claim: RelayOpenClaim): { [key: string]: CanonicalValue } {
343
+ if (
344
+ !exactKeys(claim, [
345
+ "relationId",
346
+ "grantEpoch",
347
+ "requesterMembership",
348
+ "targetMembership",
349
+ "direction",
350
+ ]) ||
351
+ typeof claim.relationId !== "string" ||
352
+ !RELAY_ID_HEX.test(claim.relationId) ||
353
+ typeof claim.grantEpoch !== "number" ||
354
+ !Number.isSafeInteger(claim.grantEpoch) ||
355
+ claim.grantEpoch < 1 ||
356
+ claim.direction !== "requester-to-target"
357
+ ) {
358
+ throw new ConnectorStateError("Invalid relay open claim shape");
359
+ }
360
+
361
+ return {
362
+ relationId: claim.relationId,
363
+ grantEpoch: claim.grantEpoch,
364
+ requesterMembership: refToWire(claim.requesterMembership),
365
+ targetMembership: refToWire(claim.targetMembership),
366
+ direction: claim.direction,
367
+ };
368
+ }
369
+
301
370
  /**
302
371
  * The concrete pinned-cloud WSS transport: one CloudTransport + CloudEndpoint over one global
303
372
  * WebSocket connection. One instance serves exactly one open() — the connector builds a fresh
304
373
  * transport per reconcile attempt, so no state ever resurrects across connection generations.
305
374
  */
306
- export class CloudWssTransport implements CloudTransport, CloudEndpoint {
375
+ export class CloudWssTransport implements CloudTransport, CloudEndpoint, RelayCapableTransport {
307
376
  private readonly pinned: PinnedCloud;
308
377
  private readonly options: CloudWssTransportOptions;
309
378
  private readonly rpcTimeoutMs: number;
@@ -329,6 +398,29 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
329
398
  private generationValue: number | null = null;
330
399
  private refusedFrames = 0;
331
400
  private seamErrors = 0;
401
+ /** M4 lane B3: the open relay channel's id on THIS connection (memory-only, dies with the
402
+ * connection), its single data listener, and its close callbacks (cleared on teardown). */
403
+ private relayChannelIdValue: string | null = null;
404
+
405
+ /** M4 target-side channel state: X adopts A's session into a relay channel via the
406
+ * relay-open pair-delivery (A never learns the channel id — X routes raw frames), so the
407
+ * target keeps its own adoption flag rather than a requester-side channel id. */
408
+ private relayTargetActive = false;
409
+ private relayDataListener: ((payload: Uint8Array) => void) | null = null;
410
+ private relayClosedCallbacks: ((notice: RelayClosedNotice) => void)[] = [];
411
+
412
+ /* ---------------- D2 SEC-13: the multichannel (mux) relay state ---------------- */
413
+
414
+ /** Cached {mux:1} capability probe for THIS connection; undefined = not probed yet,
415
+ * null = probed and the pinned cloud does not advertise mux (fail-closed to 1 channel). */
416
+ private muxCapsValue: { maxChannels: number } | null | undefined = undefined;
417
+ /** Requester-side open mux channel ids on THIS connection (X-minted, memory-only). */
418
+ private readonly relayMuxRequesterChannels = new Set<string>();
419
+ /** Target-side adopted mux channel ids (A's per-channel demux table, memory-only). */
420
+ private readonly relayTargetChannels = new Set<string>();
421
+ /** THE inbound mux-frame listener (one per connection; a second registration refuses). */
422
+ private relayMuxDataListener:
423
+ ((frame: { channelId: string; payload: Uint8Array }) => void) | null = null;
332
424
 
333
425
  constructor(input: { pinned: PinnedCloud; options?: CloudWssTransportOptions }) {
334
426
  this.pinned = input.pinned;
@@ -365,6 +457,455 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
365
457
  return this.generationValue;
366
458
  }
367
459
 
460
+ /** The open relay channel's id on THIS connection, or null while none is open. */
461
+ relayChannelId(): string | null {
462
+ return this.relayChannelIdValue;
463
+ }
464
+
465
+ /** M4 target-side adoption (§12): the daemon accepted X's relay-open delivery, so this
466
+ * connection now carries relayed binary frames for exactly one channel. Mirrors the
467
+ * requester-side guards: a second adoption is refused, and every relay frame bound below
468
+ * (inbound/outbound/listener) accepts EITHER the requester channel or target adoption. */
469
+ adoptRelayTarget(): void {
470
+ if (this.relayChannelIdValue !== null || this.relayTargetActive) {
471
+ throw new ConnectorStateError("Relay channel already open on this transport");
472
+ }
473
+
474
+ this.relayTargetActive = true;
475
+ }
476
+
477
+ /** Target-side teardown: clears the adoption and fires the registered close callbacks
478
+ * exactly once. Safe to call when nothing is adopted. */
479
+ releaseRelayTarget(): void {
480
+ if (this.relayTargetActive) {
481
+ this.disposeRelayChannel("peer-closed");
482
+ }
483
+ }
484
+
485
+ /**
486
+ * M4 lane B3: opens the relayed application channel toward the relation target. Capability
487
+ * is probed FIRST (authenticated `relay-caps`): an old pinned cloud that does not know the
488
+ * method answers a failure, and the open fails closed with the static capability error — no
489
+ * relay-open frame ever leaves, and every existing lane is untouched. The claim is validated
490
+ * structurally before any wire activity; X then checks topology and forwards the exact claims
491
+ * to A's central boundary, which authoritatively re-verifies the grant before the channel id
492
+ * is issued (§11/§12 — this transport performs NO authorization of its own).
493
+ */
494
+ async relayOpen(claim: RelayOpenClaim): Promise<string> {
495
+ this.requireOpenSocket();
496
+
497
+ // SEC-13 mode isolation: a transport holding mux channels never falls back to the
498
+ // legacy single-channel lane (and vice versa) — refuse locally, no frame leaves.
499
+ if (
500
+ this.relayChannelIdValue !== null ||
501
+ this.relayMuxRequesterChannels.size > 0 ||
502
+ this.relayTargetChannels.size > 0
503
+ ) {
504
+ throw new ConnectorStateError("Relay channel already open on this transport");
505
+ }
506
+
507
+ const claimBody = relayClaimToWire(claim);
508
+ let caps: CanonicalValue;
509
+
510
+ try {
511
+ caps = await this.rpc(METHOD_RELAY_CAPS, {});
512
+ } catch {
513
+ // Any probe failure — unknown method on an old cloud, transient 503, deadline — fails
514
+ // the open closed with the same static error: this client never infers capability
515
+ // from wire text, so an old X and an unreachable one are indistinguishable here and
516
+ // both refuse closed (no relay-open frame ever leaves on a failed probe).
517
+ throw new ConnectorStateError("Relay capability not advertised by the cloud");
518
+ }
519
+
520
+ if (!isPlainObject(caps) || !exactKeys(caps, ["relay"]) || caps.relay !== 1) {
521
+ throw new ConnectorStateError("Relay capability not advertised by the cloud");
522
+ }
523
+
524
+ const result = await this.rpc(METHOD_RELAY_OPEN, { d: claimBody });
525
+ const channelId = isPlainObject(result) ? result.channel : undefined;
526
+
527
+ if (typeof channelId !== "string" || !RELAY_ID_HEX.test(channelId)) {
528
+ throw new ConnectorStateError("Malformed relay channel id from cloud");
529
+ }
530
+
531
+ this.relayChannelIdValue = channelId;
532
+
533
+ return channelId;
534
+ }
535
+
536
+ /** Sends one §16-bounded binary relay frame on the open channel; oversize or empty payloads
537
+ * are refused locally BEFORE any write, and the outbound backpressure bound applies exactly
538
+ * like every other send. Binary frames are only legal on this profile while a relay channel
539
+ * is open — anything else stays a refused protocol violation, byte-identical to pre-relay. */
540
+ relaySend(payload: Uint8Array): void {
541
+ const ws = this.requireOpenSocket();
542
+
543
+ if (this.relayChannelIdValue === null && !this.relayTargetActive) {
544
+ throw new ConnectorStateError("No relay channel is open");
545
+ }
546
+
547
+ const bytes = payload instanceof Uint8Array ? payload : null;
548
+
549
+ if (bytes === null || bytes.length === 0) {
550
+ throw new ConnectorStateError("Relay data frames must not be empty");
551
+ }
552
+
553
+ if (bytes.length > MAX_DATA_FRAME_BYTES) {
554
+ throw new ConnectorStateError(
555
+ `Relay data frame exceeds the ${MAX_DATA_FRAME_BYTES}-byte whole-frame wire bound; refused before send`,
556
+ );
557
+ }
558
+
559
+ if (ws.bufferedAmount + bytes.length > this.maxBufferedBytes) {
560
+ throw new EndpointError(503, "Cloud WSS outbound backpressure bound reached");
561
+ }
562
+
563
+ try {
564
+ // A fresh ArrayBuffer-backed view: WebSocket.send requires BufferSource over a plain
565
+ // ArrayBuffer, and the one bounded copy keeps the wire type honest (≤ 1 MiB).
566
+ ws.send(Uint8Array.from(bytes));
567
+ } catch {
568
+ throw new EndpointError(503, "Cloud WSS send failed");
569
+ }
570
+ }
571
+
572
+ /** Registers THE inbound relay-data listener (a second registration is refused: ambiguity
573
+ * about who consumes relayed frames is what fail-closed wiring must not allow). Frames that
574
+ * arrive with no listener registered are refused and counted, never buffered. */
575
+ onRelayData(listener: (payload: Uint8Array) => void): void {
576
+ if (this.relayChannelIdValue === null && !this.relayTargetActive) {
577
+ throw new ConnectorStateError("No relay channel is open");
578
+ }
579
+
580
+ if (this.relayDataListener !== null) {
581
+ throw new ConnectorStateError("Relay data listener already registered");
582
+ }
583
+
584
+ this.relayDataListener = listener;
585
+ }
586
+
587
+ /** Registers a relay-close callback; fires exactly once per torn-down channel (peer
588
+ * notification, local close, or connection loss). Default: refuses while no channel is
589
+ * open (the frozen §16 seam contract). `early: true` opts into connection-scoped
590
+ * registration BEFORE any mux channel opens — for wirings (RemoteChannel.open) whose
591
+ * channel may close between the relay-open reply and their listener attachment. */
592
+ onRelayClosed(
593
+ callback: (notice: RelayClosedNotice) => void,
594
+ options: { early?: boolean } = {},
595
+ ): void {
596
+ if (
597
+ options.early !== true &&
598
+ this.relayChannelIdValue === null &&
599
+ !this.relayTargetActive &&
600
+ this.relayMuxRequesterChannels.size === 0 &&
601
+ this.relayTargetChannels.size === 0
602
+ ) {
603
+ throw new ConnectorStateError("No relay channel is open");
604
+ }
605
+
606
+ this.relayClosedCallbacks.push(callback);
607
+ }
608
+
609
+ /** Cooperative teardown: the relay-close RPC is best effort (X may have already disposed the
610
+ * channel), and the local state clears either way with the one bounded close notification. */
611
+ async relayClose(): Promise<void> {
612
+ const channelId = this.relayChannelIdValue;
613
+
614
+ if (channelId === null) {
615
+ throw new ConnectorStateError("No relay channel is open");
616
+ }
617
+
618
+ try {
619
+ await this.rpc(METHOD_RELAY_CLOSE, { d: { channel: channelId } });
620
+ } catch {
621
+ // X may have already torn the channel down (peer ended, session rotated): the local
622
+ // channel is gone either way — clearing here is the fail-closed path.
623
+ }
624
+
625
+ this.disposeRelayChannel("peer-closed");
626
+ }
627
+
628
+ /* ------------- D2 SEC-13: the multichannel (mux) relay surface (additive) ------------- */
629
+
630
+ /** The per-connection mux capability: probed once with the authenticated {mux:1}
631
+ * relay-caps; an old cloud (or any probe failure) reads null and every mux open fails
632
+ * closed with a static error — exactly the legacy fail-closed pattern, no relay-open
633
+ * frame ever leaves for a cloud that did not advertise mux. */
634
+ async relayMuxCaps(): Promise<{ maxChannels: number } | null> {
635
+ if (this.muxCapsValue !== undefined) {
636
+ return this.muxCapsValue;
637
+ }
638
+
639
+ this.requireOpenSocket();
640
+
641
+ let caps: CanonicalValue;
642
+
643
+ try {
644
+ caps = await this.rpc(METHOD_RELAY_CAPS, { d: { mux: 1 } });
645
+ } catch {
646
+ this.muxCapsValue = null;
647
+
648
+ return null;
649
+ }
650
+
651
+ if (
652
+ !isPlainObject(caps) ||
653
+ !exactKeys(caps, ["relay", "mux", "maxChannels"]) ||
654
+ caps.relay !== 1 ||
655
+ caps.mux !== 1 ||
656
+ typeof caps.maxChannels !== "number" ||
657
+ !Number.isSafeInteger(caps.maxChannels) ||
658
+ caps.maxChannels < 1 ||
659
+ caps.maxChannels > 4
660
+ ) {
661
+ this.muxCapsValue = null;
662
+
663
+ return null;
664
+ }
665
+
666
+ this.muxCapsValue = { maxChannels: caps.maxChannels };
667
+
668
+ return this.muxCapsValue;
669
+ }
670
+
671
+ /** SEC-13: opens one E2EE mux channel toward the relation target. The claim is the exact
672
+ * §11/§12 routing claim; `clientHello` is this channel's opaque §21 handshake first
673
+ * message, which X forwards inside the relay-open delivery — never parsed here or at X.
674
+ * Returns X's minted (unprivileged) channel id plus the target's opaque serverHello. A
675
+ * cloud without mux, a held legacy channel on this transport, or the per-endpoint cap
676
+ * refuse closed with static errors before any frame leaves. */
677
+ async relayOpenE2ee(
678
+ claim: RelayOpenClaim,
679
+ clientHello: Uint8Array,
680
+ ): Promise<{ channelId: string; serverHello: Uint8Array }> {
681
+ this.requireOpenSocket();
682
+
683
+ if (this.relayChannelIdValue !== null || this.relayTargetActive) {
684
+ throw new ConnectorStateError("Relay channel already open on this transport");
685
+ }
686
+
687
+ const caps = await this.relayMuxCaps();
688
+
689
+ if (caps === null) {
690
+ throw new ConnectorStateError(
691
+ "Relay mux capability not advertised by the cloud (old cloud or relay lane absent)",
692
+ );
693
+ }
694
+
695
+ if (this.relayMuxRequesterChannels.size >= caps.maxChannels) {
696
+ throw new ConnectorStateError(
697
+ "Relay channel capacity reached on this transport (SEC-13 mux cap)",
698
+ );
699
+ }
700
+
701
+ const hello =
702
+ clientHello instanceof Uint8Array
703
+ ? Buffer.from(clientHello).toString("base64url")
704
+ : null;
705
+
706
+ if (hello === null || hello.length === 0 || hello.length > 12_000) {
707
+ throw new ConnectorStateError("Invalid relay handshake hello");
708
+ }
709
+
710
+ const claimBody = relayClaimToWire(claim);
711
+ const result = await this.rpc(METHOD_RELAY_OPEN, {
712
+ d: { ...claimBody, e2ee: 1, hello },
713
+ });
714
+
715
+ if (
716
+ !isPlainObject(result) ||
717
+ !exactKeys(result, ["channel", "hello"]) ||
718
+ typeof result.channel !== "string" ||
719
+ !MUX_CHANNEL_ID_HEX.test(result.channel) ||
720
+ typeof result.hello !== "string" ||
721
+ result.hello.length === 0 ||
722
+ result.hello.length > 12_000
723
+ ) {
724
+ throw new ConnectorStateError("Malformed mux relay-open result from cloud");
725
+ }
726
+
727
+ const serverHello = decodeBase64urlStrict(result.hello);
728
+
729
+ if (serverHello === null || serverHello.length === 0) {
730
+ throw new ConnectorStateError("Malformed mux relay-open result from cloud");
731
+ }
732
+
733
+ this.relayMuxRequesterChannels.add(result.channel);
734
+
735
+ return { channelId: result.channel, serverHello };
736
+ }
737
+
738
+ /** The requester-side open mux channel ids (memory-only, in open order). */
739
+ relayMuxChannelIds(): readonly string[] {
740
+ return [...this.relayMuxRequesterChannels];
741
+ }
742
+
743
+ /** Sends one §16-bounded mux-framed binary body on an open mux channel; oversize or
744
+ * empty frames are refused locally BEFORE any write (the 17-byte mux header counts
745
+ * toward the whole-frame bound), and the outbound backpressure bound applies exactly
746
+ * like every other send. */
747
+ relaySendChannel(channelId: string, payload: Uint8Array): void {
748
+ const ws = this.requireOpenSocket();
749
+
750
+ if (
751
+ !MUX_CHANNEL_ID_HEX.test(channelId) ||
752
+ (!this.relayMuxRequesterChannels.has(channelId) &&
753
+ !this.relayTargetChannels.has(channelId))
754
+ ) {
755
+ throw new ConnectorStateError("No such mux relay channel is open");
756
+ }
757
+
758
+ const bytes = payload instanceof Uint8Array ? payload : null;
759
+
760
+ if (bytes === null || bytes.length === 0) {
761
+ throw new ConnectorStateError("Relay data frames must not be empty");
762
+ }
763
+
764
+ const frame = encodeMuxFrame(channelId, bytes);
765
+
766
+ if (frame.length > MAX_DATA_FRAME_BYTES) {
767
+ throw new ConnectorStateError(
768
+ `Relay data frame exceeds the ${MAX_DATA_FRAME_BYTES}-byte whole-frame wire bound; refused before send`,
769
+ );
770
+ }
771
+
772
+ if (ws.bufferedAmount + frame.length > this.maxBufferedBytes) {
773
+ throw new EndpointError(503, "Cloud WSS outbound backpressure bound reached");
774
+ }
775
+
776
+ try {
777
+ // A fresh ArrayBuffer-backed view (same as the legacy lane): WebSocket.send
778
+ // requires a BufferSource over a plain ArrayBuffer, with the one bounded copy.
779
+ ws.send(Uint8Array.from(frame));
780
+ } catch {
781
+ throw new EndpointError(503, "Cloud WSS send failed");
782
+ }
783
+ }
784
+
785
+ /** Cooperative per-channel teardown (mux): best-effort RPC, local state clears either
786
+ * way, and the registered close callbacks fire exactly once with this channel id. */
787
+ async relayCloseChannel(channelId: string): Promise<void> {
788
+ if (!this.relayMuxRequesterChannels.has(channelId)) {
789
+ throw new ConnectorStateError("No such mux relay channel is open");
790
+ }
791
+
792
+ try {
793
+ await this.rpc(METHOD_RELAY_CLOSE, { d: { channel: channelId } });
794
+ } catch {
795
+ // X may already have disposed the channel; local teardown proceeds fail-closed.
796
+ }
797
+
798
+ this.dropMuxChannel(channelId, "peer-closed");
799
+ }
800
+
801
+ /** Target-side (A) mux adoption: X delivered a relay-open(e2ee) for this channel id, so
802
+ * this connection now demultiplexes inbound mux frames for it. A duplicate or malformed
803
+ * id refuses; adoption carries no authorization (the boundary already decided at open). */
804
+ adoptRelayTargetChannel(channelId: string): void {
805
+ if (!MUX_CHANNEL_ID_HEX.test(channelId)) {
806
+ throw new ConnectorStateError("Malformed mux channel id");
807
+ }
808
+
809
+ if (this.relayTargetChannels.has(channelId)) {
810
+ throw new ConnectorStateError("Mux relay channel already adopted");
811
+ }
812
+
813
+ this.relayTargetChannels.add(channelId);
814
+ }
815
+
816
+ /** Target-side per-channel release; safe when nothing is adopted. */
817
+ releaseRelayTargetChannel(channelId: string): void {
818
+ if (this.relayTargetChannels.has(channelId)) {
819
+ this.dropMuxChannel(channelId, "peer-closed");
820
+ }
821
+ }
822
+
823
+ /** Registers THE inbound mux-frame listener (one per connection; a second registration
824
+ * refuses — ambiguity about who consumes relayed frames is what fail-closed wiring must
825
+ * not allow). Frames arriving with no listener are refused and counted, never buffered. */
826
+ onRelayMuxData(listener: (frame: { channelId: string; payload: Uint8Array }) => void): void {
827
+ this.requireOpenSocket();
828
+
829
+ if (this.relayMuxDataListener !== null) {
830
+ throw new ConnectorStateError("Mux relay data listener already registered");
831
+ }
832
+
833
+ // Connection-scoped registration: it may happen BEFORE any mux channel opens (the
834
+ // first channel's handshake reply can race the caller's wiring); frames arriving
835
+ // with no OPEN channel stay refused by the demux, never buffered.
836
+ this.relayMuxDataListener = listener;
837
+ }
838
+
839
+ /** Clears one mux channel locally and fires the close callbacks exactly once for it. */
840
+ private dropMuxChannel(channelId: string, reason: RelayCloseReason): void {
841
+ const wasRequester = this.relayMuxRequesterChannels.delete(channelId);
842
+ const wasTarget = this.relayTargetChannels.delete(channelId);
843
+
844
+ if (!wasRequester && !wasTarget) {
845
+ return;
846
+ }
847
+
848
+ for (const callback of [...this.relayClosedCallbacks]) {
849
+ try {
850
+ callback({ channelId, reason });
851
+ } catch {
852
+ // A close listener must not break teardown; the channel is gone either way.
853
+ }
854
+ }
855
+ }
856
+
857
+ /** Tears the channel down exactly once: both listener slots cleared, every registered close
858
+ * callback fired with the static reason. A no-op when no channel is open — which includes
859
+ * the TARGET-side adoption (A never holds a channel id; X routes raw frames), so the
860
+ * guard must consider BOTH the requester channel and the target flag. Connection loss
861
+ * also disposes every open mux channel, each with its own exactly-once notification. */
862
+ private disposeRelayChannel(reason: RelayCloseReason): void {
863
+ const channelId = this.relayChannelIdValue;
864
+
865
+ if (channelId === null && !this.relayTargetActive) {
866
+ this.disposeMuxChannels(reason);
867
+
868
+ return;
869
+ }
870
+
871
+ this.relayChannelIdValue = null;
872
+ this.relayTargetActive = false;
873
+ this.relayDataListener = null;
874
+
875
+ const callbacks = this.relayClosedCallbacks.splice(0);
876
+
877
+ for (const callback of callbacks) {
878
+ try {
879
+ callback({ channelId: channelId ?? "target", reason });
880
+ } catch {
881
+ // A close listener must not break the teardown path; the channel is gone either
882
+ // way, and the connection-level onClosed path is unaffected.
883
+ }
884
+ }
885
+
886
+ this.disposeMuxChannels(reason);
887
+ }
888
+
889
+ /** Connection-loss teardown of every open mux channel (requester and target side), each
890
+ * close callback firing exactly once with its own channel id. */
891
+ private disposeMuxChannels(reason: RelayCloseReason): void {
892
+ const ids = [...this.relayMuxRequesterChannels, ...this.relayTargetChannels];
893
+
894
+ this.relayMuxRequesterChannels.clear();
895
+ this.relayTargetChannels.clear();
896
+ this.relayMuxDataListener = null;
897
+
898
+ for (const id of ids) {
899
+ for (const callback of [...this.relayClosedCallbacks]) {
900
+ try {
901
+ callback({ channelId: id, reason });
902
+ } catch {
903
+ // See disposeRelayChannel: a listener must not break teardown.
904
+ }
905
+ }
906
+ }
907
+ }
908
+
368
909
  /**
369
910
  * Registers the ONLY cloud-initiated control surface this client will answer: X's §7 pair
370
911
  * deliveries (prepare/provisional). No other X-initiated request is ever answered — anything
@@ -664,6 +1205,8 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
664
1205
 
665
1206
  this.closedByUs = true;
666
1207
  this.failPending(new EndpointError(503, "Cloud transport closed locally"));
1208
+ // An open relay channel dies with the connection it was opened on (memory-only, §16).
1209
+ this.disposeRelayChannel("session-ended");
667
1210
 
668
1211
  if (this.openWait !== null) {
669
1212
  // A close() during opening fails the pending open instead of leaving it hanging, and
@@ -944,6 +1487,10 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
944
1487
  * close settles close(), everything else is connection loss and fires onClosed exactly once. */
945
1488
  private adoptClosed(): void {
946
1489
  this.failPending(new EndpointError(503, "Cloud connection lost"));
1490
+ // The relay channel (if any) dies with the connection, before the loss callbacks fire;
1491
+ // every open mux channel dies with it (SEC-13), each with its own notification.
1492
+ this.disposeRelayChannel("session-ended");
1493
+ this.muxCapsValue = undefined;
947
1494
  this.state = "closed";
948
1495
 
949
1496
  const ws = this.ws;
@@ -1010,6 +1557,34 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
1010
1557
  if (requestShape) {
1011
1558
  const payload = envelope.d;
1012
1559
 
1560
+ // M4 B3: X's relay-close notification rides the pair-delivery path. When it matches
1561
+ // THIS connection's open channel, the local channel state is disposed here (so the
1562
+ // bounded close event fires even with no delivery handler wired); everything else —
1563
+ // stray ids, unknown types, the handler's reply semantics — stays exactly as before.
1564
+ if (
1565
+ envelope.m === METHOD_PAIR_DELIVER &&
1566
+ isPlainObject(payload) &&
1567
+ payload.type === "relay-close" &&
1568
+ isRelayCloseReason(payload.reason)
1569
+ ) {
1570
+ // The legacy single channel closes through its own dispose; a MUX channel
1571
+ // (SEC-13) closes through the same bounded notice — dropped here so the
1572
+ // per-channel close event fires even with no delivery handler wired, and
1573
+ // the connection itself stays intact for the remaining channels.
1574
+ if (
1575
+ typeof payload.channel === "string" &&
1576
+ this.relayChannelIdValue !== null &&
1577
+ payload.channel === this.relayChannelIdValue
1578
+ ) {
1579
+ this.disposeRelayChannel(payload.reason);
1580
+ } else if (
1581
+ typeof payload.channel === "string" &&
1582
+ this.relayMuxRequesterChannels.has(payload.channel)
1583
+ ) {
1584
+ this.dropMuxChannel(payload.channel, payload.reason);
1585
+ }
1586
+ }
1587
+
1013
1588
  if (
1014
1589
  envelope.m !== METHOD_PAIR_DELIVER ||
1015
1590
  !isPlainObject(payload) ||
@@ -1044,7 +1619,19 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
1044
1619
  }
1045
1620
 
1046
1621
  const successShape = exactKeys(envelope, ["v", "k", "id", "r"]);
1047
- const failureShape = exactKeys(envelope, ["v", "k", "id", "s"], ["e", "rc"]);
1622
+ const failureShape = exactKeys(envelope, ["v", "k", "id", "s"], ["e", "rc", "retryable"]);
1623
+
1624
+ // SEC-13: the one failure extra the relay may send is the retryable flag — but only
1625
+ // as canonical 1 on exactly a capped-channel-open 409; anything else is malformed.
1626
+ if (
1627
+ failureShape &&
1628
+ envelope.retryable !== undefined &&
1629
+ (envelope.s !== 409 || envelope.retryable !== 1)
1630
+ ) {
1631
+ this.refuse();
1632
+
1633
+ return;
1634
+ }
1048
1635
 
1049
1636
  if (
1050
1637
  // Exactly one response shape must match: a success carries its result, a failure its
@@ -1196,6 +1783,9 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
1196
1783
  }
1197
1784
 
1198
1785
  private attach(ws: WebSocket): void {
1786
+ // A fresh connection re-probes the mux capability (SEC-13): caps are per-connection.
1787
+ this.muxCapsValue = undefined;
1788
+
1199
1789
  ws.addEventListener("message", (event) => {
1200
1790
  if (this.ws !== ws || this.state !== "open") {
1201
1791
  return;
@@ -1204,7 +1794,77 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
1204
1794
  const data: unknown = event.data;
1205
1795
 
1206
1796
  if (typeof data !== "string") {
1207
- // Non-text frames are not part of the canonical JSON wire profile: refused.
1797
+ // M4 B3 + SEC-13: binary belongs to an OPEN relay channel only — bounded §16
1798
+ // frames go to the registered data listener; anything else (no channel,
1799
+ // oversize, empty) is refused locally exactly like the pre-relay profile:
1800
+ // counted, never forwarded. A connection holding mux channels demultiplexes
1801
+ // mux-framed bodies per channel id (unknown id or missing listener refuses).
1802
+ if (data instanceof ArrayBuffer) {
1803
+ const payload = Buffer.from(data);
1804
+
1805
+ if (
1806
+ payload.length > 0 &&
1807
+ payload.length <= MAX_DATA_FRAME_BYTES &&
1808
+ (this.relayMuxRequesterChannels.size > 0 ||
1809
+ this.relayTargetChannels.size > 0)
1810
+ ) {
1811
+ const mux = parseMuxFrame(payload);
1812
+
1813
+ if (mux !== null) {
1814
+ const known =
1815
+ this.relayMuxRequesterChannels.has(mux.channelId) ||
1816
+ this.relayTargetChannels.has(mux.channelId);
1817
+
1818
+ if (!known || this.relayMuxDataListener === null) {
1819
+ this.refuse();
1820
+
1821
+ return;
1822
+ }
1823
+
1824
+ const listener = this.relayMuxDataListener;
1825
+
1826
+ try {
1827
+ listener({ channelId: mux.channelId, payload: mux.body });
1828
+ } catch {
1829
+ // The relay consumer owns its session-fatal path; a throwing
1830
+ // listener must neither crash the event emitter nor corrupt
1831
+ // transport state. Counted.
1832
+ this.seamErrors += 1;
1833
+ }
1834
+
1835
+ return;
1836
+ }
1837
+ }
1838
+
1839
+ if (this.relayChannelIdValue !== null || this.relayTargetActive) {
1840
+ if (
1841
+ payload.length === 0 ||
1842
+ payload.length > MAX_DATA_FRAME_BYTES ||
1843
+ this.relayDataListener === null
1844
+ ) {
1845
+ this.refuse();
1846
+
1847
+ return;
1848
+ }
1849
+
1850
+ const listener = this.relayDataListener;
1851
+
1852
+ try {
1853
+ listener(payload);
1854
+ } catch {
1855
+ // The relay consumer owns its session-fatal path; a throwing listener must
1856
+ // neither crash the event emitter nor corrupt transport state. Counted.
1857
+ this.seamErrors += 1;
1858
+ }
1859
+
1860
+ return;
1861
+ }
1862
+
1863
+ this.refuse();
1864
+
1865
+ return;
1866
+ }
1867
+
1208
1868
  this.refuse();
1209
1869
 
1210
1870
  return;