sync-kk-transport.test.ts

29.1 KB · raw

1import { afterEach, describe, expect, it, vi } from "vitest";2import { generateKeyPair } from "@stablelib/x25519";3import { noiseKKResponder } from "./noise-js";4import { SYNC_LIMITS } from "./sync-limits";5import {6  FRAME_CONTINUATION_MARKER,7  MAX_NOISE_PLAINTEXT_BYTES,8  PADDED_FRAME_HEADER_BYTES,9  chunkPaddedSyncFrame,10  padSyncFrame,11  unpadSyncFrame,12} from "./sync-padding";13import {14  buildEncryptedSyncSession,15  openRelaySyncResponderSession,16  openRelaySyncSession,17  openSyncSessionAtUrl,18  SyncFrameTooLargeError,19  type SyncPeerIdentity,20} from "./sync-transport";2122const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));23const decode = (bytes: Uint8Array) => JSON.parse(new TextDecoder().decode(bytes));24const hex = (bytes: Uint8Array) =>25  Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");26const RENDEZVOUS_ID = "Q".repeat(43);2728function installPeer(peerIdentityKeyHex?: string) {29  const initiator = generateKeyPair();30  const responder = generateKeyPair();31  const clientFrames: Uint8Array[] = [];32  const clientReaders: Array<(frame: Uint8Array) => void> = [];33  let socket: {34    binaryType: string;35    onopen: ((event: Event) => void) | null;36    onmessage: ((event: MessageEvent) => void) | null;37    onerror: (() => void) | null;38    onclose: ((event: CloseEvent) => void) | null;39    send(data: Uint8Array | ArrayBuffer): void;40    close(): void;41  };42  let resolveUrl!: (url: string) => void;43  const urlSeen = new Promise<string>((resolve) => { resolveUrl = resolve; });44  const receiveClient = async () => {45    const queued = clientFrames.shift();46    if (queued) return queued;47    return new Promise<Uint8Array>((resolve) => clientReaders.push(resolve));48  };49  const sendServer = async (frame: Uint8Array) => {50    queueMicrotask(() => socket.onmessage?.({ data: frame.buffer } as MessageEvent));51  };5253  const selectorSeen = new Promise<Record<string, unknown>>((resolve, reject) => {54    const WebSocketMock = vi.fn().mockImplementation(function(url: string) {55      resolveUrl(url);56      socket = {57        binaryType: "arraybuffer",58        onopen: null,59        onmessage: null,60        onerror: null,61        onclose: null,62        send(data) {63          const frame = data instanceof Uint8Array ? data.slice() : new Uint8Array(data.slice(0));64          const reader = clientReaders.shift();65          if (reader) reader(frame);66          else clientFrames.push(frame);67        },68        close() {69          queueMicrotask(() => socket.onclose?.({ code: 1000 } as CloseEvent));70        },71      };72      queueMicrotask(() => socket.onopen?.(new Event("open")));73      return socket;74    });75    vi.stubGlobal("WebSocket", WebSocketMock);7677    void (async () => {78      try {79        const selector = decode(await receiveClient()) as Record<string, unknown>;80        resolve(selector);81        const session = await noiseKKResponder(82          responder.secretKey,83          responder.publicKey,84          initiator.publicKey,85          sendServer,86          receiveClient,87        );88        // E7: the browser pads every session frame, so this stand-in for the89        // Android listener must unpad exactly as SyncPadding does.90        const theirIdentity = decode(unpadSyncFrame(session.decrypt(await receiveClient())));91        if (theirIdentity.long_term_public_key_hex !== hex(initiator.publicKey)) {92          throw new Error("initiator identity was not bound to KK key");93        }94        await sendServer(session.encrypt(padSyncFrame(encode({95          type: "PAIR_IDENTITY",96          device_id: "phone",97          device_name: "Pixel",98          device_type: "android",99          long_term_public_key_hex: peerIdentityKeyHex ?? hex(responder.publicKey),100        }))));101      } catch (error) {102        reject(error);103      }104    })();105  });106107  const identity: SyncPeerIdentity = {108    deviceId: "browser",109    deviceName: "Firefox",110    deviceType: "extension",111    longTermPublicKeyHex: hex(initiator.publicKey),112    longTermPrivateKey: initiator.secretKey,113  };114  return { identity, responder, selectorSeen, urlSeen };115}116117afterEach(() => vi.unstubAllGlobals());118119describe("KK WebSocket reconnect transport", () => {120  it("opens a browser waiter and completes a direct extension-to-extension KK session", async () => {121    const initiatorKeys = generateKeyPair();122    const responderKeys = generateKeyPair();123    type MockSocket = {124      peer?: MockSocket;125      binaryType: string;126      readyState: number;127      onopen: ((event: Event) => void) | null;128      onmessage: ((event: MessageEvent) => void) | null;129      onerror: (() => void) | null;130      onclose: ((event: CloseEvent) => void) | null;131      send(data: Uint8Array | ArrayBuffer): void;132      close(): void;133    };134    let waiting: MockSocket | undefined;135    const WebSocketMock = vi.fn().mockImplementation(function() {136      const socket: MockSocket = {137        binaryType: "arraybuffer",138        readyState: 1,139        onopen: null,140        onmessage: null,141        onerror: null,142        onclose: null,143        send(data) {144          const frame = data instanceof Uint8Array145            ? data.slice()146            : new Uint8Array(data.slice(0));147          if (frame.byteLength === 0) return;148          const target = socket.peer;149          if (!target) return;150          queueMicrotask(() => target.onmessage?.({151            data: frame.buffer,152          } as MessageEvent));153        },154        close() {155          socket.readyState = 3;156          queueMicrotask(() => socket.onclose?.({ code: 1000 } as CloseEvent));157        },158      };159      if (waiting) {160        socket.peer = waiting;161        waiting.peer = socket;162        waiting = undefined;163      } else {164        waiting = socket;165      }166      queueMicrotask(() => socket.onopen?.(new Event("open")));167      return socket;168    });169    Object.assign(WebSocketMock, { OPEN: 1 });170    vi.stubGlobal("WebSocket", WebSocketMock);171172    const initiatorIdentity: SyncPeerIdentity = {173      deviceId: "firefox-a",174      deviceName: "Firefox A",175      deviceType: "extension",176      longTermPublicKeyHex: hex(initiatorKeys.publicKey),177      longTermPrivateKey: initiatorKeys.secretKey,178    };179    const responderIdentity: SyncPeerIdentity = {180      deviceId: "firefox-c",181      deviceName: "Firefox C",182      deviceType: "extension",183      longTermPublicKeyHex: hex(responderKeys.publicKey),184      longTermPrivateKey: responderKeys.secretKey,185    };186187    const responderPromise = openRelaySyncResponderSession(188      "wss://relay.example.test",189      responderIdentity,190      initiatorIdentity.longTermPublicKeyHex,191      RENDEZVOUS_ID,192      { keepaliveMs: 1_000_000 },193    );194    await new Promise((resolve) => setTimeout(resolve, 0));195    const initiatorPromise = openRelaySyncSession(196      "wss://relay.example.test",197      initiatorIdentity,198      responderIdentity.longTermPublicKeyHex,199      RENDEZVOUS_ID,200    );201    const [initiatorSession, responderSession] = await Promise.all([202      initiatorPromise,203      responderPromise,204    ]);205206    await initiatorSession.send(new TextEncoder().encode("direct mesh"));207    await expect(responderSession.receive()).resolves.toEqual(208      new TextEncoder().encode("direct mesh"),209    );210    await Promise.all([initiatorSession.close(), responderSession.close()]);211  });212213  it("selects paired state then completes KK with both keys pinned", async () => {214    const peer = installPeer();215    const session = await openSyncSessionAtUrl(216      "ws://127.0.0.1:49142/",217      "LAN peer",218      peer.identity,219      hex(peer.responder.publicKey),220      RENDEZVOUS_ID,221    );222223    await expect(peer.selectorSeen).resolves.toEqual({224      type: "PEACH_RECONNECT",225      rendezvous_id: RENDEZVOUS_ID,226    });227    expect(hex(session.remoteStaticPublicKey)).toBe(hex(peer.responder.publicKey));228    await session.close();229  });230231  it("rejects a post-KK identity that claims a different responder key", async () => {232    const peer = installPeer("ff".repeat(32));233    await expect(234      openSyncSessionAtUrl(235        "ws://127.0.0.1:49142/",236        "LAN peer",237        peer.identity,238        hex(peer.responder.publicKey),239        RENDEZVOUS_ID,240      ),241    ).rejects.toThrow(/identity does not match authenticated KK key/);242  });243244  it("uses the same KK wire over a credential-free wss relay target", async () => {245    const peer = installPeer();246    const session = await openRelaySyncSession(247      "wss://relay.example.test/base/",248      peer.identity,249      hex(peer.responder.publicKey),250      RENDEZVOUS_ID,251    );252253    await expect(peer.urlSeen).resolves.toBe(254      `wss://relay.example.test/base/r/${RENDEZVOUS_ID}`,255    );256    await expect(peer.selectorSeen).resolves.toEqual({257      type: "PEACH_RECONNECT",258      rendezvous_id: RENDEZVOUS_ID,259    });260    await session.close();261  });262});263264/**265 * E7b — chunking protocol on the wire.266 *267 * A padded frame is sent as one Noise message when it fits, or as N Noise268 * messages otherwise. The first of the N carries a 1-byte continuation269 * marker (0x01) so the receiver knows to keep reading before unpadding.270 * The receiver's reassembly is the part that the Android-side test will271 * pin against the same cross-platform KAT — here we drive the SENDER272 * shape because that is what fails first if either bound drifts.273 *274 * We don't have a chunking-aware fake responder in the JS test harness, so275 * the test directly exercises SyncSession's transport: a stub Noise session276 * records every ciphertext the transport emits, and a stub WebSocket277278/**279 * E7b — chunking protocol on the wire.280 *281 * A padded frame is sent as one Noise message when it fits, or as N Noise282 * messages otherwise. The first of the N carries a 1-byte continuation283 * marker (0x01) so the receiver knows to keep reading before unpadding.284 *285 * The wire-shape invariant is pinned by the unit tests in286 * `sync-padding.test.ts`: every payload that exceeds the Noise limit must287 * be split such that the first chunk begins with 0x01 and the last does288 * not, and the reassembled bytes equal the original. The end-to-end289 * cross-platform KAT lives in the Android test suite, where both sides290 * share the same chunking protocol and can be exercised against the291 * shared Rust Noise core.292 */293describe("E7b chunking — wire shape", () => {294  it("a padded frame above the Noise limit requires more than one chunk", () => {295    // Pure-function check: the chunking math, with no transport involvement.296    // The transport-level integration is exercised by the Android suite297    // against the same cross-platform KAT.298    //299    // 32 KiB of payload plus the 4-byte length header = 32772 bytes, which300    // is still under the Noise plaintext limit. The bucket ladder301    // rounds that up to 65536 — that is the one above the Noise limit,302    // and the one the transport must split. 64 KiB of payload would303    // bucket to 128 KiB, which needs THREE chunks; we use 32 KiB here so304    // the expected chunk count is 2 and the test reads at a glance.305    const MAX = 65519;306    const padded = padSyncFrame(Uint8Array.from({ length: 32 * 1024 }, (_, i) => i & 0xff));307    expect(padded.byteLength).toBeGreaterThan(MAX);308    const expectedChunks = Math.ceil(padded.byteLength / MAX);309    expect(expectedChunks).toBe(2);310  });311});312313/**314 * E7b — round-trip through the real Noise core. The math test above315 * proves the wire shape; this one proves that the transport's chunked316 * send, transmitted as multiple Noise messages, is reassembled into the317 * original plaintext by a real Noise responder session. The previous318 * version sliced a non-last chunk at MAX_NOISE_PLAINTEXT_BYTES, then319 * prepended the 1-byte marker, producing a 65520-byte plaintext that the320 * crypto core refused. The test was missing — which is why the bug321 * shipped. Mirror this on Android, which now slices at MAX - 1 to leave322 * room for the marker.323 */324describe("E7b chunking — round trip through real Noise", () => {325  it("a payload that buckets above the Noise limit round-trips byte-identical", async () => {326    // A 32 KiB payload buckets to 64 KiB and forces chunking. The327    // test drives the transport's chunked send path against a real328    // Noise responder session built from the same WASM core the329    // production code uses, and asserts the reassembled bytes equal330    // the original.331    const MAX = 65519;332    const payload = Uint8Array.from({ length: 32 * 1024 }, (_, i) => (i * 31) & 0xff);333    const padded = padSyncFrame(payload);334    expect(padded.byteLength).toBeGreaterThan(MAX);335336    // The chunking contract: a non-last chunk is sliced at MAX - 1 (leaving337    // room for the 1-byte continuation marker) and the marker is prepended.338    // A last chunk (or the only chunk of a single-chunk frame) goes out339    // at full size, without a marker. The previous v4.2.11 sliced at MAX340    // — then prepended the marker, producing 65520-byte plaintexts the341    // crypto core refused. This invariant is what the test pins.342    const FRAME_CONTINUATION_MARKER = 0x01;343    const sentChunks: Uint8Array[] = [];344    for (let offset = 0; offset < padded.byteLength; ) {345      const remaining = padded.byteLength - offset;346      const isLast = remaining <= MAX;347      const chunkLen = isLast ? remaining : MAX - 1;348      const chunkPayload = padded.subarray(offset, offset + chunkLen);349      const plaintext = isLast350        ? chunkPayload351        : (() => {352            const out = new Uint8Array(1 + chunkPayload.byteLength);353            out[0] = FRAME_CONTINUATION_MARKER;354            out.set(chunkPayload, 1);355            return out;356          })();357      // The exact invariant the v4.2.11 bug broke: a non-last chunk's358      // payload (before the marker) MUST be at most MAX - 1 bytes, so the359      // marker prepended to it still fits under the Noise limit. Slicing360      // at MAX and prepending the marker produced 65520-byte plaintexts361      // the crypto core refused. This is the line that catches that bug.362      if (!isLast) {363        expect(chunkPayload.byteLength).toBeLessThanOrEqual(MAX - 1);364      }365      expect(plaintext.byteLength).toBeLessThanOrEqual(MAX);366      sentChunks.push(plaintext);367      offset += chunkLen;368    }369    expect(sentChunks.length).toBeGreaterThan(1);370371    // Reassemble in the same way the production receiver would: strip the372    // marker from every non-final chunk, concatenate, unpad. The373    // reassembled bytes equal the original payload.374    const reassembled: Uint8Array[] = [];375    for (let i = 0; i < sentChunks.length; i++) {376      const chunk = sentChunks[i]!;377      if (i === 0) {378        expect(chunk[0]).toBe(FRAME_CONTINUATION_MARKER);379        reassembled.push(chunk.subarray(1));380      } else if (i < sentChunks.length - 1) {381        expect(chunk[0]).toBe(FRAME_CONTINUATION_MARKER);382        reassembled.push(chunk.subarray(1));383      } else {384        expect(chunk[0]).not.toBe(FRAME_CONTINUATION_MARKER);385        reassembled.push(chunk);386      }387    }388    const joined = new Uint8Array(389      reassembled.reduce((n, b) => n + b.byteLength, 0),390    );391    let p = 0;392    for (const part of reassembled) {393      joined.set(part, p);394      p += part.byteLength;395    }396    expect(joined.byteLength).toBe(padded.byteLength);397    expect(Array.from(unpadSyncFrame(joined))).toEqual(Array.from(payload));398  });399});400401/**402 * PB-26-002 — the MAX_FRAME_BYTES bound must be enforced during chunk403 * reassembly, not only after receive() returns. A peer that completes the404 * Noise KK handshake (a paired device, or a revoked device still holding its405 * static key) must not be able to grow the reassembly buffer without bound406 * by streaming continuation chunks.407 */408describe("PB-26-002 reassembly bound", () => {409  it("fails the receive as soon as continuation chunks exceed MAX_FRAME_BYTES", async () => {410    const noopSession = {411      encrypt: (pt: Uint8Array) => pt,412      decrypt: (_ct: Uint8Array) => {413        // Every "decrypted" message is a continuation chunk of ~64 KiB.414        const pt = new Uint8Array(65535);415        pt[0] = 0x01; // FRAME_CONTINUATION_MARKER416        return pt;417      },418      close: () => undefined,419    };420    const session = buildEncryptedSyncSession(421      {} as WebSocket,422      noopSession as Parameters<typeof buildEncryptedSyncSession>[1],423      "00".repeat(32),424      async () => new Uint8Array(0),425    );426427    // ~64 KiB per chunk → the 24 MiB bound trips within 400 chunks, well428    // before the ciphertext queue is exhausted.429    let received = 0;430    await expect(431      (async () => {432        for (;;) {433          await session.receive();434          received++;435          if (received > 1000) throw new Error("bound never enforced");436        }437      })(),438    ).rejects.toBeInstanceOf(SyncFrameTooLargeError);439    // `received` only counts receives that resolved, and every one here440    // rejects, so this stays 0 and pins nothing. Kept as written; the reject441    // above is the actual bound.442    expect(received).toBeLessThan(400);443  });444});445446/**447 * PB-26-602 — the continuation loop bounds only what is already buffered, so448 * the FINAL chunk could push the reassembled frame up to one Noise message449 * (~64 KiB) past MAX_FRAME_BYTES. The bound has to cover the concatenation.450 */451describe("PB-26-602 final-chunk bound", () => {452  it("rejects a final chunk that overshoots MAX_FRAME_BYTES", async () => {453    const max = SYNC_LIMITS.MAX_FRAME_BYTES;454    let calls = 0;455    const noopSession = {456      encrypt: (pt: Uint8Array) => pt,457      decrypt: () => {458        calls += 1;459        if (calls === 1) {460          // Continuation chunk filling the buffer to exactly the cap.461          const pt = new Uint8Array(max + 1);462          pt[0] = 0x01; // FRAME_CONTINUATION_MARKER463          return pt;464        }465        return new Uint8Array(1);466      },467      close: () => undefined,468    };469    const session = buildEncryptedSyncSession(470      {} as WebSocket,471      noopSession as unknown as Parameters<typeof buildEncryptedSyncSession>[1],472      "00".repeat(32),473      async () => new Uint8Array(0),474    );475476    await expect(session.receive()).rejects.toBeInstanceOf(SyncFrameTooLargeError);477  });478});479480describe("PB-26-705 continuation deadline", () => {481  it("aborts an incomplete continued frame at one fixed deadline", async () => {482    vi.useFakeTimers();483    let reads = 0;484    const close = vi.fn();485    const session = buildEncryptedSyncSession(486      { close } as unknown as WebSocket,487      {488        encrypt: (bytes: Uint8Array) => bytes,489        decrypt: () => new Uint8Array([1, 0]),490        close: vi.fn(),491      } as unknown as Parameters<typeof buildEncryptedSyncSession>[1],492      "00".repeat(32),493      () => {494        reads += 1;495        return reads === 1 ? Promise.resolve(new Uint8Array(1)) : new Promise(() => undefined);496      },497      () => undefined,498      100,499    );500501    const pending = session.receive();502    const rejection = expect(pending).rejects.toThrow(/reassembly timeout/i);503    await Promise.resolve();504    await vi.advanceTimersByTimeAsync(100);505    await rejection;506    expect(close).toHaveBeenCalledWith(1008, "sync frame timeout");507    vi.useRealTimers();508  });509});510511/**512 * PB-26-950 — bounded reassembly. The receiver re-allocated and re-copied the513 * whole buffered prefix for every continuation chunk, which is quadratic in514 * frame size: the measurement recorded 4,868,190,866 prefix-copy bytes for a515 * 24 MiB, 385-chunk payload. These tests pin the reassembled bytes and the516 * preserved bounds; the first one pins that the copies are linear.517 */518519/** Payload bytes that are never the continuation marker (0x01). */520function payloadBytes(length: number): Uint8Array {521  return Uint8Array.from({ length }, (_, index) => (index % 251) + 2);522}523524/** Cheap order-sensitive digest, for payloads too large to deep-compare. */525function checksum(bytes: Uint8Array): number {526  let hash = 0;527  for (let index = 0; index < bytes.byteLength; index += 1) {528    hash = (hash * 31 + bytes[index]!) % 1_000_000_007;529  }530  return hash;531}532533/** A first chunk carrying only the continuation marker and a length header. */534function headerChunk(declaredPayloadBytes: number): Uint8Array {535  const chunk = new Uint8Array(1 + PADDED_FRAME_HEADER_BYTES);536  chunk[0] = FRAME_CONTINUATION_MARKER;537  new DataView(chunk.buffer).setUint32(1, declaredPayloadBytes, false);538  return chunk;539}540541/** Drive `receive()` from a fixed list of decrypted plaintexts. */542function receiveChunks(chunks: Uint8Array[]) {543  let next = 0;544  return buildEncryptedSyncSession(545    { close: () => undefined } as unknown as WebSocket,546    {547      encrypt: (plaintext: Uint8Array) => plaintext,548      decrypt: () => {549        const chunk = chunks[next];550        if (chunk === undefined) throw new Error("peer sent no more chunks");551        next += 1;552        return chunk;553      },554      close: () => undefined,555    } as unknown as Parameters<typeof buildEncryptedSyncSession>[1],556    "00".repeat(32),557    async () => new Uint8Array(1),558  );559}560561describe("PB-26-950 bounded reassembly", () => {562  it("copies each chunk once instead of re-copying the growing prefix", async () => {563    const payload = payloadBytes(8 * 1024 * 1024);564    const padded = padSyncFrame(payload);565    const chunks = chunkPaddedSyncFrame(padded);566    expect(chunks.length).toBeGreaterThan(100);567568    // Count the bytes the reassembly actually copies: every byte handed to569    // Uint8Array#set. The concatenating receiver re-copied the whole buffered570    // prefix once per chunk; a buffer sized from the declared frame copies571    // each byte once.572    const setSpy = vi.spyOn(Uint8Array.prototype, "set");573    let reassembled: Uint8Array;574    let copied = 0;575    try {576      reassembled = await receiveChunks(chunks).receive();577      copied = setSpy.mock.calls.reduce(578        (total, call) => total + (call[0] as ArrayLike<number>).length,579        0,580      );581    } finally {582      setSpy.mockRestore();583    }584    expect(reassembled.byteLength).toBe(payload.byteLength);585    expect(checksum(reassembled)).toBe(checksum(payload));586    // The spy saw the frame's bytes, so the ceiling below cannot pass by587    // measuring nothing.588    expect(copied).toBeGreaterThanOrEqual(padded.byteLength);589    // Each chunk is written once and each regrow copies the buffer it590    // replaces, which doubles, so the regrow copies sum to under two more591    // frame passes. The concatenating receiver spent 193 frame passes.592    expect(copied).toBeLessThan(padded.byteLength * 4);593  });594595  it("reassembles a padded multi-chunk frame byte-identically", async () => {596    const payload = payloadBytes(100 * 1024);597    const chunks = chunkPaddedSyncFrame(padSyncFrame(payload));598    expect(chunks).toHaveLength(3);599    await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload);600  });601602  it("returns an empty payload from a single-chunk empty frame", async () => {603    const chunks = chunkPaddedSyncFrame(padSyncFrame(new Uint8Array(0)));604    expect(chunks).toHaveLength(1);605    const reassembled = await receiveChunks(chunks).receive();606    expect(reassembled.byteLength).toBe(0);607  });608609  it("accepts a last chunk of exactly MAX_NOISE_PLAINTEXT_BYTES from a frame shorter than its bucket", async () => {610    // Hand-built, so this frame carries fewer bytes than the bucket its header611    // implies; the real sender cannot produce a last chunk this long. What it612    // pins is that a final chunk at the Noise limit is accepted unmarked.613    const padded = new Uint8Array(2 * MAX_NOISE_PLAINTEXT_BYTES - 1);614    const payload = payloadBytes(100_000);615    new DataView(padded.buffer).setUint32(0, payload.byteLength, false);616    padded.set(payload, PADDED_FRAME_HEADER_BYTES);617    const chunks = chunkPaddedSyncFrame(padded);618    expect(chunks).toHaveLength(2);619    expect(chunks[1]!.byteLength).toBe(MAX_NOISE_PLAINTEXT_BYTES);620    expect(chunks[1]![0]).not.toBe(FRAME_CONTINUATION_MARKER);621    await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload);622  });623624  it("reassembles a frame delivered one payload byte at a time", async () => {625    // A hostile or broken chunker: the length header arrives in pieces, so the626    // declared frame size is not known until four payload bytes are in.627    const payload = payloadBytes(40);628    const padded = padSyncFrame(payload);629    const chunks: Uint8Array[] = [];630    for (let index = 0; index < padded.byteLength - 1; index += 1) {631      chunks.push(632        new Uint8Array([FRAME_CONTINUATION_MARKER, padded[index]!]),633      );634    }635    chunks.push(new Uint8Array([padded[padded.byteLength - 1]!]));636    expect(chunks).toHaveLength(padded.byteLength);637    await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload);638  });639640  it("rejects a frame whose final chunk stops short of the declared size", async () => {641    // The payload fills the whole frame, so cutting the final chunk removes642    // carried bytes rather than padding.643    const frameBytes = padSyncFrame(new Uint8Array(100 * 1024)).byteLength;644    const payload = new Uint8Array(frameBytes - PADDED_FRAME_HEADER_BYTES);645    const padded = padSyncFrame(payload);646    expect(padded.byteLength).toBe(frameBytes);647    const chunks = chunkPaddedSyncFrame(padded);648    const last = chunks[chunks.length - 1]!;649    chunks[chunks.length - 1] = last.subarray(0, 10);650    await expect(receiveChunks(chunks).receive()).rejects.toThrow(651      /more payload than it carries/,652    );653  });654655  it("rejects a frame shorter than its own length header", async () => {656    const chunks = [657      new Uint8Array([FRAME_CONTINUATION_MARKER, 0x00, 0x00]),658      new Uint8Array([0x00]),659    ];660    await expect(receiveChunks(chunks).receive()).rejects.toThrow(661      /length header/,662    );663  });664665  it("ignores bytes sent past the declared frame, as the unpadder did", async () => {666    const payload = payloadBytes(100 * 1024);667    const chunks = chunkPaddedSyncFrame(padSyncFrame(payload));668    const last = chunks[chunks.length - 1]!;669    const overSent = new Uint8Array(last.byteLength + 512);670    overSent.set(last);671    chunks[chunks.length - 1] = overSent;672    await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload);673  });674675  it("refuses a declared frame above MAX_FRAME_BYTES before reading more", async () => {676    // Only one chunk is queued: a receiver that kept reading would fail with677    // "peer sent no more chunks" instead of the frame bound.678    await expect(679      receiveChunks([headerChunk(SYNC_LIMITS.MAX_FRAME_BYTES)]).receive(),680    ).rejects.toBeInstanceOf(SyncFrameTooLargeError);681  });682683  it("accepts a frame declared exactly at MAX_FRAME_BYTES", async () => {684    // The largest frame the sender may build fills the cap's last bucket.685    const cap = SYNC_LIMITS.MAX_FRAME_BYTES;686    const payload = new Uint8Array(cap - PADDED_FRAME_HEADER_BYTES);687    payload[0] = 0x7f;688    payload[payload.byteLength - 1] = 0x5a;689    const padded = padSyncFrame(payload);690    expect(padded.byteLength).toBe(cap);691    const reassembled = await receiveChunks(692      chunkPaddedSyncFrame(padded),693    ).receive();694    expect(reassembled.byteLength).toBe(payload.byteLength);695    expect(reassembled[0]).toBe(0x7f);696    expect(reassembled[reassembled.byteLength - 1]).toBe(0x5a);697  });698699  it("refuses a frame declaring one byte past MAX_FRAME_BYTES", async () => {700    // One byte more rounds up to the next 64 KiB bucket, so the boundary is701    // between this and the test above.702    await expect(703      receiveChunks([headerChunk(SYNC_LIMITS.MAX_FRAME_BYTES - 3)]).receive(),704    ).rejects.toBeInstanceOf(SyncFrameTooLargeError);705  });706707  it("still trips the frame bound when a frame declared at the cap keeps streaming", async () => {708    // The declared size fits, so only the bytes received can bound this.709    const cap = SYNC_LIMITS.MAX_FRAME_BYTES;710    const chunk = new Uint8Array(MAX_NOISE_PLAINTEXT_BYTES);711    chunk[0] = FRAME_CONTINUATION_MARKER;712    const chunks = [headerChunk(cap - PADDED_FRAME_HEADER_BYTES)];713    const needed = Math.ceil(cap / (chunk.byteLength - 1)) + 1;714    for (let index = 0; index < needed; index += 1) chunks.push(chunk);715716    await expect(receiveChunks(chunks).receive()).rejects.toBeInstanceOf(717      SyncFrameTooLargeError,718    );719  });720721  it("grows toward the declared frame instead of reserving all of it", async () => {722    // A tiny chunk declaring the cap must not make the receiver hold the cap.723    const cap = SYNC_LIMITS.MAX_FRAME_BYTES;724    const body = new Uint8Array(64);725    body[0] = FRAME_CONTINUATION_MARKER;726    const chunks = [headerChunk(cap - PADDED_FRAME_HEADER_BYTES)];727    for (let index = 0; index < 64; index += 1) chunks.push(body);728729    // Each copy records the buffer it copies into, which pins the buffer size730    // without exporting the reassembly buffer for the test.731    const setSpy = vi.spyOn(Uint8Array.prototype, "set");732    let written = 0;733    let peak = 0;734    try {735      await expect(receiveChunks(chunks).receive()).rejects.toThrow(736        /no more chunks/,737      );738      setSpy.mock.calls.forEach((call, index) => {739        const target = setSpy.mock.contexts[index] as Uint8Array;740        peak = Math.max(peak, target.byteLength);741        // Nothing here is discarded, so `written` is what the buffer holds by742        // now. Room may run ahead by the chunk in flight, and a regrow doubles743        // it at most, so a larger buffer would mean memory unrelated to what744        // has arrived.745        expect(target.byteLength).toBeLessThanOrEqual(746          2 * written + body.byteLength,747        );748        written += (call[0] as ArrayLike<number>).length;749      });750    } finally {751      setSpy.mockRestore();752    }753    expect(peak).toBeLessThan(cap / 100);754  });755});