sync-transport.ts

26.2 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  /** The frame bytes held for the unpadder. */512  get assembled(): Uint8Array {513    return this.bytes.subarray(0, this.filled);514  }515516  write(payload: Uint8Array): void {517    this.seen += payload.byteLength;518    let offset = this.stageHeader(payload);519    while (offset < payload.byteLength) {520      if (this.filled === this.declared) {521        // Past the declared frame is padding, which the unpadder ignores.522        return;523      }524      if (this.filled === this.bytes.byteLength) {525        this.grow(payload.byteLength - offset);526      }527      const take = Math.min(528        this.bytes.byteLength - this.filled,529        payload.byteLength - offset,530      );531      this.bytes.set(payload.subarray(offset, offset + take), this.filled);532      this.filled += take;533      offset += take;534    }535  }536537  /** Fill the 4-byte stage, reading the declared size once it is complete. */538  private stageHeader(payload: Uint8Array): number {539    if (this.filled >= PADDED_FRAME_HEADER_BYTES) return 0;540    const take = Math.min(541      PADDED_FRAME_HEADER_BYTES - this.filled,542      payload.byteLength,543    );544    this.bytes.set(payload.subarray(0, take), this.filled);545    this.filled += take;546    if (this.filled === PADDED_FRAME_HEADER_BYTES) this.readDeclaredSize();547    return take;548  }549550  /** Read the frame's own padded size once its length header has arrived. */551  private readDeclaredSize(): void {552    const declared = declaredPaddedFrameBytes(this.bytes);553    if (declared > SYNC_LIMITS.MAX_FRAME_BYTES) {554      // Refused before growing: a frame this large can never be accepted.555      throw new SyncFrameTooLargeError(556        `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,557      );558    }559    this.declared = declared;560  }561562  /**563   * Grow toward the declared frame by doubling or by what the pending chunk564   * needs, whichever is larger, so copies stay linear and a tiny chunk cannot565   * reserve the whole declared frame up front.566   */567  private grow(needed: number): void {568    const grown = new Uint8Array(569      Math.min(570        this.declared,571        Math.max(2 * this.bytes.byteLength, this.filled + needed),572      ),573    );574    grown.set(this.bytes);575    this.bytes = grown;576  }577}578579// Exported for the PB-26-002 reassembly-bound regression test.580export function buildEncryptedSyncSession(581  ws: WebSocket,582  session: NoiseNKSession,583  expectedRemotePubkeyHex: string,584  receiveCiphertext: () => Promise<Uint8Array>,585  beforeClose: () => void = () => undefined,586  reassemblyTimeoutMs = SYNC_REASSEMBLY_TIMEOUT_MS,587): SyncSession {588  return {589    async send(plaintext: Uint8Array) {590      // E7: bucket the size before encrypting, so the relay sees frame shapes591      // that no longer distinguish one operation (or vault size) from another.592      // E7b: a padded frame can legitimately be up to 24 MiB, but Noise caps a593      // single transport message at 65535 bytes (see crypto-core/src/lib.rs —594      // 65519 plaintext, 16-byte tag). We split a too-large padded frame into595      // Noise-sized messages, tagging every chunk but the last with a 1-byte596      // continuation marker. The receiver keeps reading until a chunk arrives597      // without the marker, and uses the padded frame's 4-byte length header to598      // bound how much of those bytes it stores.599      const padded = padSyncFrame(plaintext);600      if (padded.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {601        throw new SyncFrameTooLargeError(602          `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,603        );604      }605      // A single-chunk frame goes out as one Noise message, exactly as before606      // — no continuation byte, no per-chunk overhead, so the common small607      // case is unchanged on the wire.608      if (padded.byteLength <= MAX_NOISE_PLAINTEXT_BYTES) {609        const ct = session.encrypt(padded);610        ws.send(ct as Uint8Array<ArrayBuffer>);611        return;612      }613      for (const plaintext of chunkPaddedSyncFrame(padded)) {614        if (plaintext.byteLength > MAX_NOISE_PLAINTEXT_BYTES) {615          throw new Error(616            `chunk exceeds Noise limit after continuation byte: ${plaintext.byteLength}`,617          );618        }619        const ct = session.encrypt(plaintext);620        if (ct.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {621          throw new SyncFrameTooLargeError(622            `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,623          );624        }625        ws.send(ct as Uint8Array<ArrayBuffer>);626      }627    },628    async receive() {629      // The first Noise message of a frame is the first one we read. If it630      // begins with the continuation marker, the message is one of N chunks631      // — the padded-frame length header comes inside the first chunk's632      // payload, so we read it there to learn the total.633      let reassembly: PaddedFrameReassembly | null = null;634      let deadlineTimer: ReturnType<typeof setTimeout> | undefined;635      let deadline: Promise<never> | undefined;636      try {637        while (true) {638          const ct = await (deadline639            ? Promise.race([receiveCiphertext(), deadline])640            : receiveCiphertext());641          const pt = session.decrypt(ct);642          const continued =643            pt.byteLength > 0 && pt[0] === FRAME_CONTINUATION_MARKER;644          if (reassembly === null && !continued) {645            // Single-chunk frame, exactly as before.646            return unpadSyncFrame(pt);647          }648          if (reassembly === null) {649            reassembly = new PaddedFrameReassembly();650            deadline = new Promise<never>((_resolve, reject) => {651              deadlineTimer = setTimeout(() => {652                session.close();653                try { ws.close(1008, "sync frame timeout"); } catch { /* ignore */ }654                reject(new SyncFrameReassemblyTimeoutError());655              }, reassemblyTimeoutMs);656            });657          }658          // A continuation chunk spends its first byte on the marker.659          reassembly.write(continued ? pt.subarray(1) : pt);660          if (continued) {661            // PB-26-002: the frame bound must hold DURING reassembly. The662            // post-receive check in the coordinator runs only after the full663            // frame is in memory, so a peer that completes the Noise KK664            // handshake could otherwise stream continuation chunks without665            // bound inside the session window.666            if (reassembly.received > SYNC_LIMITS.MAX_FRAME_BYTES) {667              throw new SyncFrameTooLargeError(668                `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,669              );670            }671            continue;672          }673          // Final chunk. PB-26-602: the continuation loop only bounds what is674          // buffered, so the last chunk could push the frame up to 64 KiB past675          // the cap. Bound the concatenation, not just the buffer.676          if (reassembly.received > SYNC_LIMITS.MAX_FRAME_BYTES) {677            throw new SyncFrameTooLargeError(678              `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,679            );680          }681          return unpadSyncFrame(reassembly.assembled);682        }683      } finally {684        if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);685      }686    },687    async close() {688      beforeClose();689      try { ws.close(); } catch { /* ignore */ }690      session.close();691    },692    remoteStaticPublicKey: hexToPubkey(expectedRemotePubkeyHex),693  };694}695696function equalAscii(left: string, right: string): boolean {697  const a = new TextEncoder().encode(left);698  const b = new TextEncoder().encode(right);699  if (a.length !== b.length) return false;700  let diff = 0;701  for (let i = 0; i < a.length; i += 1) diff |= a[i] ^ b[i];702  return diff === 0;703}704705function connectWebSocketUrl(706  url: string,707  targetLabel: string,708  timeoutMs: number,709): Promise<WebSocket> {710  return new Promise((resolve, reject) => {711    let ws: WebSocket;712    try {713      ws = new WebSocket(url);714    } catch (err) {715      reject(err as Error);716      return;717    }718    const t = setTimeout(() => {719      try { ws.close(); } catch { /* ignore */ }720      reject(new Error(`${targetLabel} WebSocket connect timed out`));721    }, timeoutMs);722    ws.onopen = () => {723      clearTimeout(t);724      resolve(ws);725    };726    ws.onerror = () => {727      clearTimeout(t);728      reject(new Error(`${targetLabel} WebSocket connect errored`));729    };730  });731}