sync-transport.ts

27.4 KB · raw

1// WebSocket reconnect transport — Noise KK with both paired static keys.2// First pairing remains Noise NK; reconnect never negotiates or falls back.3//4// The lower long-term public key is the WebSocket/Noise initiator; the higher5// key holds the relay room as responder. Device type does not affect the role,6// so two extensions can sync directly without a native hub. Each binary7// WebSocket message carries one Noise frame (large padded application frames8// are split across multiple Noise messages below).9//10// On connect:11//   1. Open wss://<relay>/<rendezvous-id>/12//   2. Send PEACH_RECONNECT with an opaque rotating rendezvous capability so13//      the listener can select paired local state without exposing identities.14//   3. Run standard Noise KK using both locally-known static keys.15//   4. Exchange PAIR_IDENTITY frames over the encrypted channel (same frame16//      Android's SyncReconnectListener expects before it will treat the17//      connection as sync traffic rather than an unknown caller). Our18//      identity is bound to the static key authenticated by KK.19//   5. Hand the caller a `SyncSession` for the SyncMessage protocol.20//21// Subnet probe falls back to scanning the /24 returned by `getLocalSubnet`22// when the cached last-known IP fails. We use a short connection timeout23// (~500ms per IP) and parallel batches of 16 to keep the worst-case scan24// under ~10 seconds.2526import {27  noiseKKInitiator,28  noiseKKResponder,29  type NoiseNKSession,30} from "./noise-js";31import { SYNC_LIMITS } from "./sync-limits";32import {33  padSyncFrame,34  unpadSyncFrame,35  declaredPaddedFrameBytes,36  PADDED_FRAME_HEADER_BYTES,37  MAX_NOISE_PLAINTEXT_BYTES,38  FRAME_CONTINUATION_MARKER,39  chunkPaddedSyncFrame,40} from "./sync-padding";41import { hexToPubkey } from "./sync-identity";42import { buildRendezvousUrl } from "./rendezvous";43import type { DeviceType } from "./sync-types";4445// E6 (session rekeying) is deliberately NOT wired, and this is a reality check46// against the spec rather than an omission. E6 targets "long-lived sync47// sessions"; the browser has none. Sessions opened here are one-shot — roughly48// ten frames each way, a 30s coordinator timeout (SESSION_TIMEOUT_MS), then49// sync-runner closes them — and every reconnect runs a fresh Noise KK handshake50// with fresh ephemerals. (Android's listener does park a connection open after51// a round so it can act as a relay hub for another native peer, but the browser52// drives the lifetime of every session it opens, and closes it.) That already53// gives stronger post-compromise security than intra-session Rekey() would,54// because no two sessions share key material at all (pinned by the E6 test in55// noise-kk.test.ts).56//57// Wiring Rekey() anyway would mean both ends rekeying at the identical frame58// index with no wire signal to resynchronise on. One frame of drift between59// browser and Android breaks all sync — the exact failure class this protocol60// has already been burned by twice. The primitives are exposed on NoiseSession61// (rekeyOutgoing/rekeyIncoming) if a genuinely long-lived session ever appears;62// until then the cost is real and the benefit is zero.63const DEFAULT_CONNECT_TIMEOUT_MS = 4_000;64const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;65export const RELAY_WAITER_KEEPALIVE_MS = 20_000;66export const SYNC_REASSEMBLY_TIMEOUT_MS = 30_000;6768export interface SyncSession {69  send(plaintext: Uint8Array): void;70  receive(): Promise<Uint8Array>;71  close(): Promise<void>;72  remoteStaticPublicKey: Uint8Array;73}7475/** Our identity, repeated in the post-handshake PAIR_IDENTITY frame and bound76 *  to the local static key already authenticated by KK. */77export interface SyncPeerIdentity {78  deviceId: string;79  deviceName: string;80  deviceType: DeviceType;81  longTermPublicKeyHex: string;82  /** Local-only key material for the KK reconnect handshake; never encoded. */83  longTermPrivateKey: Uint8Array;84  signingPublicKeyHex?: string;85}8687export class SyncFrameTooLargeError extends Error {88  constructor(message = "sync frame too large (WebSocket close 1009)") {89    super(message);90    this.name = "SyncFrameTooLargeError";91  }92}9394export class SyncTransportResourceLimitError extends Error {95  constructor() {96    super("sync transport resource limit exceeded");97    this.name = "SyncTransportResourceLimitError";98  }99}100101export class SyncFrameReassemblyTimeoutError extends Error {102  constructor() {103    super("sync frame reassembly timeout");104    this.name = "SyncFrameReassemblyTimeoutError";105  }106}107108export interface SyncSessionOptions {109  connectTimeoutMs?: number;110  handshakeTimeoutMs?: number;111  signal?: AbortSignal;112}113114function encodePairIdentity(id: SyncPeerIdentity): Uint8Array {115  return new TextEncoder().encode(JSON.stringify({116    type: "PAIR_IDENTITY",117    device_id: id.deviceId,118    device_name: id.deviceName,119    device_type: id.deviceType,120    long_term_public_key_hex: id.longTermPublicKeyHex,121    signing_public_key_hex: id.signingPublicKeyHex,122  }));123}124125/**126 * Relay reconnect preserves the existing Noise KK wire protocol. The URL127 * builder enforces credential-free `wss://`.128 */129export async function openRelaySyncSession(130  relayUrl: string,131  ourIdentity: SyncPeerIdentity,132  expectedRemotePubkeyHex: string,133  rendezvousId: string,134  options: SyncSessionOptions = {},135): Promise<SyncSession> {136  return openSyncSessionAtUrl(137    buildRendezvousUrl(relayUrl, rendezvousId),138    "relay",139    ourIdentity,140    expectedRemotePubkeyHex,141    rendezvousId,142    options,143  );144}145146/**147 * Hold one relay room as the deterministic responder, then run Noise KK and148 * the bound PAIR_IDENTITY exchange. The zero-length liveness frame keeps a149 * Chrome 116+ MV3 service worker alive while the room is empty; the Peach150 * relay consumes that frame locally and never forwards it to the peer.151 */152export async function openRelaySyncResponderSession(153  relayUrl: string,154  ourIdentity: SyncPeerIdentity,155  expectedRemotePubkeyHex: string,156  rendezvousId: string,157  options: SyncSessionOptions & { keepaliveMs?: number } = {},158): Promise<SyncSession> {159  if (!/^[A-Za-z0-9_-]{22,128}$/.test(rendezvousId)) {160    throw new Error("reconnect requires a valid rotating rendezvous id");161  }162  if (ourIdentity.longTermPrivateKey.length !== 32) {163    throw new Error("local reconnect private key must be exactly 32 bytes");164  }165  const ws = await connectWebSocketUrl(166    buildRendezvousUrl(relayUrl, rendezvousId),167    "relay",168    options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,169  );170  const inbox: Uint8Array[] = [];171  let inboxBytes = 0;172  const readers: Array<(b: Uint8Array) => void> = [];173  let closed = false;174  let closeError: Error = new Error("WebSocket closed");175  const keepaliveMs = options.keepaliveMs ?? RELAY_WAITER_KEEPALIVE_MS;176  const abortWaiter = () => {177    try { ws.close(1000, "relay waiter replaced"); } catch { /* ignore */ }178  };179  const keepalive = setInterval(() => {180    if (ws.readyState !== WebSocket.OPEN) return;181    try { ws.send(new Uint8Array(0)); } catch { /* onclose owns cleanup */ }182  }, keepaliveMs);183184  ws.binaryType = "arraybuffer";185  ws.onmessage = (event: MessageEvent) => {186    if (closed) return;187    if (!(event.data instanceof ArrayBuffer)) return;188    if (event.data.byteLength === 0) return;189    if (event.data.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {190      closeError = new SyncFrameTooLargeError(191        `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,192      );193      try { ws.close(1009, "sync frame too large"); } catch { /* ignore */ }194      return;195    }196    const bytes = new Uint8Array(event.data);197    const reader = readers.shift();198    if (reader) reader(bytes);199    else if (200      inbox.length >= SYNC_LIMITS.MAX_INBOX_MESSAGES ||201      inboxBytes + bytes.byteLength > SYNC_LIMITS.MAX_INBOX_BYTES202    ) {203      closeError = new SyncTransportResourceLimitError();204      closed = true;205      inbox.length = 0;206      inboxBytes = 0;207      try { ws.close(1009, "sync inbox limit"); } catch { /* ignore */ }208    } else {209      inbox.push(bytes);210      inboxBytes += bytes.byteLength;211    }212  };213  ws.onerror = () => {214    try { ws.close(); } catch { /* ignore */ }215  };216  ws.onclose = (event: CloseEvent) => {217    clearInterval(keepalive);218    options.signal?.removeEventListener("abort", abortWaiter);219    closed = true;220    inbox.length = 0;221    inboxBytes = 0;222    if (event.code === 1009 && !(closeError instanceof SyncTransportResourceLimitError)) {223      closeError = new SyncFrameTooLargeError();224    }225    while (readers.length > 0) readers.shift()!(new Uint8Array(0));226  };227  // Install close handling before honoring an already-aborted signal so a228  // synchronous/mock close cannot strand the first receive() forever.229  options.signal?.addEventListener("abort", abortWaiter, { once: true });230  if (options.signal?.aborted) abortWaiter();231232  const send = async (bytes: Uint8Array): Promise<void> => {233    if (bytes.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {234      throw new SyncFrameTooLargeError(235        `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,236      );237    }238    ws.send(bytes as Uint8Array<ArrayBuffer>);239  };240  const receive = (): Promise<Uint8Array> => {241    if (closed) return Promise.reject(closeError);242    const buffered = inbox.shift();243    if (buffered) {244      inboxBytes -= buffered.byteLength;245      return Promise.resolve(buffered);246    }247    return new Promise<Uint8Array>((resolve, reject) => {248      readers.push((bytes) => {249        if (bytes.length === 0 && closed) reject(closeError);250        else resolve(bytes);251      });252    });253  };254255  let noiseSession: NoiseNKSession | undefined;256  try {257    const selectorBytes = await receive();258    const selector = JSON.parse(new TextDecoder().decode(selectorBytes));259    if (260      selector?.type !== "PEACH_RECONNECT" ||261      typeof selector.rendezvous_id !== "string" ||262      !equalAscii(selector.rendezvous_id, rendezvousId)263    ) {264      throw new Error("reconnect capability does not match relay room");265    }266    const handshakeTimer = setTimeout(() => {267      closeError = new Error("sync_handshake_timeout");268      try { ws.close(1000, "sync handshake timeout"); } catch { /* ignore */ }269    }, options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);270    try {271      const ourPublicKey = hexToPubkey(ourIdentity.longTermPublicKeyHex);272      noiseSession = await noiseKKResponder(273        ourIdentity.longTermPrivateKey,274        ourPublicKey,275        hexToPubkey(expectedRemotePubkeyHex),276        send,277        receive,278      );279      const theirFrame = JSON.parse(280        new TextDecoder().decode(281          unpadSyncFrame(noiseSession.decrypt(await receive())),282        ),283      );284      if (theirFrame?.type !== "PAIR_IDENTITY") {285        throw new Error(`expected PAIR_IDENTITY, got ${theirFrame?.type as string}`);286      }287      if (theirFrame.long_term_public_key_hex !== expectedRemotePubkeyHex) {288        throw new Error("peer identity does not match authenticated KK key");289      }290      await send(noiseSession.encrypt(padSyncFrame(encodePairIdentity(ourIdentity))));291    } finally {292      clearTimeout(handshakeTimer);293    }294  } catch (error) {295    clearInterval(keepalive);296    options.signal?.removeEventListener("abort", abortWaiter);297    noiseSession?.close();298    try { ws.close(); } catch { /* ignore */ }299    throw error;300  }301302  return buildEncryptedSyncSession(303    ws,304    noiseSession,305    expectedRemotePubkeyHex,306    receive,307    () => {308      clearInterval(keepalive);309      options.signal?.removeEventListener("abort", abortWaiter);310    },311  );312}313314export async function openSyncSessionAtUrl(315  url: string,316  targetLabel: string,317  ourIdentity: SyncPeerIdentity,318  expectedRemotePubkeyHex: string,319  rendezvousId: string,320  options: SyncSessionOptions = {},321): Promise<SyncSession> {322  if (!/^[A-Za-z0-9_-]{22,128}$/.test(rendezvousId)) {323    throw new Error("reconnect requires a valid rotating rendezvous id");324  }325  const ws = await connectWebSocketUrl(326    url,327    targetLabel,328    options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,329  );330  const inbox: Uint8Array[] = [];331  let inboxBytes = 0;332  const readers: Array<(b: Uint8Array) => void> = [];333  let closed = false;334  let closeError: Error = new Error("WebSocket closed");335336  ws.binaryType = "arraybuffer";337  ws.onmessage = (ev: MessageEvent) => {338    if (closed) return;339    const data = ev.data;340    if (data instanceof ArrayBuffer) {341      // MV-3: refuse oversized frames before they are buffered or decrypted.342      // A peer that sends one is misbehaving — tear the session down rather343      // than letting the inbox grow toward OOM.344      if (data.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {345        // MV-3: oversized frame — tear the session down. close() routes through346        // onclose, which rejects any parked receive(), so no error array is347        // needed (PCH-01-026 #9).348        console.warn(349          `[Peach] sync frame exceeds max size (${SYNC_LIMITS.MAX_FRAME_BYTES} bytes); closing`,350        );351        closeError = new SyncFrameTooLargeError(352          `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,353        );354        try { ws.close(1009, "sync frame too large"); } catch { /* ignore */ }355        return;356      }357      const bytes = new Uint8Array(data);358      const r = readers.shift();359      if (r) r(bytes);360      else if (361        inbox.length >= SYNC_LIMITS.MAX_INBOX_MESSAGES ||362        inboxBytes + bytes.byteLength > SYNC_LIMITS.MAX_INBOX_BYTES363      ) {364        closeError = new SyncTransportResourceLimitError();365        closed = true;366        inbox.length = 0;367        inboxBytes = 0;368        try { ws.close(1009, "sync inbox limit"); } catch { /* ignore */ }369      } else {370        inbox.push(bytes);371        inboxBytes += bytes.byteLength;372      }373    }374  };375  ws.onerror = () => {376    // PCH-01-026 #9: surface the error and unblock any parked receive() by377    // closing. Browsers usually follow error with close, but not always; an378    // explicit close guarantees the handshake fails fast instead of hanging.379    console.warn("[Peach] sync WebSocket error; closing transport");380    try { ws.close(); } catch { /* ignore */ }381  };382  ws.onclose = (event: CloseEvent) => {383    closed = true;384    inbox.length = 0;385    inboxBytes = 0;386    if (event.code === 1009 && !(closeError instanceof SyncTransportResourceLimitError)) {387      closeError = new SyncFrameTooLargeError();388    }389    while (readers.length > 0) {390      const r = readers.shift()!;391      r(new Uint8Array(0));392    }393  };394395  function send(bytes: Uint8Array): Promise<void> {396    return new Promise((resolve, reject) => {397      if (bytes.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {398        reject(399          new SyncFrameTooLargeError(400            `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,401          ),402        );403        return;404      }405      try {406        ws.send(bytes as Uint8Array<ArrayBuffer>);407        resolve();408      } catch (err) {409        reject(err as Error);410      }411    });412  }413  function receive(): Promise<Uint8Array> {414    if (closed) return Promise.reject(closeError);415    const v = inbox.shift();416    if (v) {417      inboxBytes -= v.byteLength;418      return Promise.resolve(v);419    }420    return new Promise<Uint8Array>((resolve, reject) => {421      readers.push((b) => {422        if (b.length === 0 && closed) reject(closeError);423        else resolve(b);424      });425    });426  }427428  const handshakeTimer = setTimeout(() => {429    closeError = new Error("sync_handshake_timeout");430    try { ws.close(1000, "sync handshake timeout"); } catch { /* ignore */ }431  }, options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);432  let session: NoiseNKSession;433  try {434    const ourPublicKey = hexToPubkey(ourIdentity.longTermPublicKeyHex);435    if (ourIdentity.longTermPrivateKey.length !== 32) {436      throw new Error("local reconnect private key must be exactly 32 bytes");437    }438    // This opaque rotating capability lets Android select paired local state439    // without exposing either public key to a relay. It grants no identity440    // trust; KK still proves both private keys immediately afterwards.441    await send(new TextEncoder().encode(JSON.stringify({442      type: "PEACH_RECONNECT",443      rendezvous_id: rendezvousId,444    })));445    session = await noiseKKInitiator(446      ourIdentity.longTermPrivateKey,447      ourPublicKey,448      hexToPubkey(expectedRemotePubkeyHex),449      send,450      receive,451    );452  } catch (err) {453    clearTimeout(handshakeTimer);454    try { ws.close(); } catch { /* ignore */ }455    throw err;456  }457458  try {459    await send(session.encrypt(padSyncFrame(encodePairIdentity(ourIdentity))));460    const theirFrame = JSON.parse(461      new TextDecoder().decode(unpadSyncFrame(session.decrypt(await receive()))),462    );463    if (theirFrame?.type !== "PAIR_IDENTITY") {464      throw new Error(`expected PAIR_IDENTITY, got ${theirFrame?.type as string}`);465    }466    if (theirFrame.long_term_public_key_hex !== expectedRemotePubkeyHex) {467      throw new Error("peer identity does not match authenticated KK key");468    }469    clearTimeout(handshakeTimer);470  } catch (err) {471    clearTimeout(handshakeTimer);472    session.close();473    try { ws.close(); } catch { /* ignore */ }474    throw err;475  }476477  return buildEncryptedSyncSession(478    ws,479    session,480    expectedRemotePubkeyHex,481    receive,482  );483}484485/**486 * Bounded reassembly of one split padded frame (PB-26-950).487 *488 * Only the frame's own 4-byte length header may arrive before the padded size489 * is known, so a 4-byte stage holds the header. Once it is complete the buffer490 * grows geometrically toward the declared size, doubling or taking what the491 * pending chunk needs, so every byte is copied a bounded number of times while492 * memory follows the bytes actually received. It never grows past the declared493 * frame, and bytes beyond that frame are padding the unpadder discards.494 *495 * `received` counts every payload byte, including those past the declared496 * frame, so the frame bound keeps firing at the same chunk it did before.497 */498class PaddedFrameReassembly {499  private bytes = new Uint8Array(PADDED_FRAME_HEADER_BYTES);500  /** The frame's own declaration once its header has been read. Until then the501   *  staging size stands in, which discards nothing: no frame is shorter than502   *  its header. */503  private declared = PADDED_FRAME_HEADER_BYTES;504  private filled = 0;505  private seen = 0;506507  get received(): number {508    return this.seen;509  }510511  /** Frame bytes still needed to complete the declared frame. Undefined until512   *  the length header has been read; before that only the marker can show513   *  that a frame is split. */514  get missing(): number | undefined {515    return this.filled < PADDED_FRAME_HEADER_BYTES516      ? undefined517      : this.declared - this.filled;518  }519520  /** The frame bytes held for the unpadder. */521  get assembled(): Uint8Array {522    return this.bytes.subarray(0, this.filled);523  }524525  write(payload: Uint8Array): void {526    this.seen += payload.byteLength;527    let offset = this.stageHeader(payload);528    while (offset < payload.byteLength) {529      if (this.filled === this.declared) {530        // Past the declared frame is padding, which the unpadder ignores.531        return;532      }533      if (this.filled === this.bytes.byteLength) {534        this.grow(payload.byteLength - offset);535      }536      const take = Math.min(537        this.bytes.byteLength - this.filled,538        payload.byteLength - offset,539      );540      this.bytes.set(payload.subarray(offset, offset + take), this.filled);541      this.filled += take;542      offset += take;543    }544  }545546  /** Fill the 4-byte stage, reading the declared size once it is complete. */547  private stageHeader(payload: Uint8Array): number {548    if (this.filled >= PADDED_FRAME_HEADER_BYTES) return 0;549    const take = Math.min(550      PADDED_FRAME_HEADER_BYTES - this.filled,551      payload.byteLength,552    );553    this.bytes.set(payload.subarray(0, take), this.filled);554    this.filled += take;555    if (this.filled === PADDED_FRAME_HEADER_BYTES) this.readDeclaredSize();556    return take;557  }558559  /** Read the frame's own padded size once its length header has arrived. */560  private readDeclaredSize(): void {561    const declared = declaredPaddedFrameBytes(this.bytes);562    if (declared > SYNC_LIMITS.MAX_FRAME_BYTES) {563      // Refused before growing: a frame this large can never be accepted.564      throw new SyncFrameTooLargeError(565        `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,566      );567    }568    this.declared = declared;569  }570571  /**572   * Grow toward the declared frame by doubling or by what the pending chunk573   * needs, whichever is larger, so copies stay linear and a tiny chunk cannot574   * reserve the whole declared frame up front.575   */576  private grow(needed: number): void {577    const grown = new Uint8Array(578      Math.min(579        this.declared,580        Math.max(2 * this.bytes.byteLength, this.filled + needed),581      ),582    );583    grown.set(this.bytes);584    this.bytes = grown;585  }586}587588// Exported for the PB-26-002 reassembly-bound regression test.589export function buildEncryptedSyncSession(590  ws: WebSocket,591  session: NoiseNKSession,592  expectedRemotePubkeyHex: string,593  receiveCiphertext: () => Promise<Uint8Array>,594  beforeClose: () => void = () => undefined,595  reassemblyTimeoutMs = SYNC_REASSEMBLY_TIMEOUT_MS,596): SyncSession {597  return {598    async send(plaintext: Uint8Array) {599      // E7: bucket the size before encrypting, so the relay sees frame shapes600      // that no longer distinguish one operation (or vault size) from another.601      // E7b: a padded frame can legitimately be up to 24 MiB, but Noise caps a602      // single transport message at 65535 bytes (see crypto-core/src/lib.rs —603      // 65519 plaintext, 16-byte tag). We split a too-large padded frame into604      // Noise-sized messages, tagging every chunk but the last with a 1-byte605      // continuation marker. Once the receiver has the padded frame's 4-byte606      // length header it compares how many frame bytes are still missing with607      // the message length, so the one final chunk that would otherwise look608      // like another continuation is still read as data.609      const padded = padSyncFrame(plaintext);610      if (padded.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {611        throw new SyncFrameTooLargeError(612          `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,613        );614      }615      // A single-chunk frame goes out as one Noise message, exactly as before616      // — no continuation byte, no per-chunk overhead, so the common small617      // case is unchanged on the wire.618      if (padded.byteLength <= MAX_NOISE_PLAINTEXT_BYTES) {619        const ct = session.encrypt(padded);620        ws.send(ct as Uint8Array<ArrayBuffer>);621        return;622      }623      for (const plaintext of chunkPaddedSyncFrame(padded)) {624        if (plaintext.byteLength > MAX_NOISE_PLAINTEXT_BYTES) {625          throw new Error(626            `chunk exceeds Noise limit after continuation byte: ${plaintext.byteLength}`,627          );628        }629        const ct = session.encrypt(plaintext);630        if (ct.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {631          throw new SyncFrameTooLargeError(632            `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,633          );634        }635        ws.send(ct as Uint8Array<ArrayBuffer>);636      }637    },638    async receive() {639      // The first Noise message of a frame is the first one we read. If it640      // begins with the continuation marker, the message is one of N chunks641      // — the padded-frame length header comes inside the first chunk's642      // payload, so we read it there to learn the total.643      let reassembly: PaddedFrameReassembly | null = null;644      let deadlineTimer: ReturnType<typeof setTimeout> | undefined;645      let deadline: Promise<never> | undefined;646      try {647        while (true) {648          const ct = await (deadline649            ? Promise.race([receiveCiphertext(), deadline])650            : receiveCiphertext());651          const pt = session.decrypt(ct);652          if (reassembly === null) {653            // The length header lives inside the first chunk's payload, so654            // only the marker can say whether this frame is split.655            if (pt.byteLength === 0 || pt[0] !== FRAME_CONTINUATION_MARKER) {656              // Single-chunk frame, exactly as before.657              return unpadSyncFrame(pt);658            }659            reassembly = new PaddedFrameReassembly();660            deadline = new Promise<never>((_resolve, reject) => {661              deadlineTimer = setTimeout(() => {662                session.close();663                try { ws.close(1008, "sync frame timeout"); } catch { /* ignore */ }664                reject(new SyncFrameReassemblyTimeoutError());665              }, reassemblyTimeoutMs);666            });667          }668          // PB-26-950 marker ambiguity: a final chunk may itself begin with669          // the marker byte, so the marker alone cannot say whether a message670          // ends the frame. Once the declared size is known, exactly one671          // length is ambiguous: a message as long as the bytes still missing672          // may be that final chunk, whose first byte is data, or a673          // continuation plus a one-byte final chunk. The receiver reads it as674          // the final chunk. Every other marked message keeps the marker rule675          // — longer than the bytes missing stays a continuation, which is676          // also what a peer gets for marking a message after the frame is677          // already full. Bytes past the declared frame are padding.678          const missing = reassembly.missing;679          const completesFrame =680            missing !== undefined && pt.byteLength === missing;681          const continued =682            pt.byteLength > 0 &&683            pt[0] === FRAME_CONTINUATION_MARKER &&684            !completesFrame;685          // A continuation chunk spends its first byte on the marker.686          reassembly.write(continued ? pt.subarray(1) : pt);687          // PB-26-002 / PB-26-602: the frame bound must hold DURING688          // reassembly, and must cover the final chunk too. The post-receive689          // check in the coordinator runs only after the full frame is in690          // memory, so a peer that completes the Noise KK handshake could691          // otherwise stream past the cap inside the session window, or push692          // the concatenation one chunk past it with the last message.693          if (reassembly.received > SYNC_LIMITS.MAX_FRAME_BYTES) {694            throw new SyncFrameTooLargeError(695              `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,696            );697          }698          if (continued) continue;699          return unpadSyncFrame(reassembly.assembled);700        }701      } finally {702        if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);703      }704    },705    async close() {706      beforeClose();707      try { ws.close(); } catch { /* ignore */ }708      session.close();709    },710    remoteStaticPublicKey: hexToPubkey(expectedRemotePubkeyHex),711  };712}713714function equalAscii(left: string, right: string): boolean {715  const a = new TextEncoder().encode(left);716  const b = new TextEncoder().encode(right);717  if (a.length !== b.length) return false;718  let diff = 0;719  for (let i = 0; i < a.length; i += 1) diff |= a[i] ^ b[i];720  return diff === 0;721}722723function connectWebSocketUrl(724  url: string,725  targetLabel: string,726  timeoutMs: number,727): Promise<WebSocket> {728  return new Promise((resolve, reject) => {729    let ws: WebSocket;730    try {731      ws = new WebSocket(url);732    } catch (err) {733      reject(err as Error);734      return;735    }736    const t = setTimeout(() => {737      try { ws.close(); } catch { /* ignore */ }738      reject(new Error(`${targetLabel} WebSocket connect timed out`));739    }, timeoutMs);740    ws.onopen = () => {741      clearTimeout(t);742      resolve(ws);743    };744    ws.onerror = () => {745      clearTimeout(t);746      reject(new Error(`${targetLabel} WebSocket connect errored`));747    };748  });749}