import { afterEach, describe, expect, it, vi } from "vitest"; import { generateKeyPair } from "@stablelib/x25519"; import { noiseKKResponder } from "./noise-js"; import { SYNC_LIMITS } from "./sync-limits"; import { FRAME_CONTINUATION_MARKER, MAX_NOISE_PLAINTEXT_BYTES, PADDED_FRAME_HEADER_BYTES, chunkPaddedSyncFrame, padSyncFrame, unpadSyncFrame, } from "./sync-padding"; import { buildEncryptedSyncSession, openRelaySyncResponderSession, openRelaySyncSession, openSyncSessionAtUrl, SyncFrameTooLargeError, type SyncPeerIdentity, } from "./sync-transport"; const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)); const decode = (bytes: Uint8Array) => JSON.parse(new TextDecoder().decode(bytes)); const hex = (bytes: Uint8Array) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); const RENDEZVOUS_ID = "Q".repeat(43); function installPeer(peerIdentityKeyHex?: string) { const initiator = generateKeyPair(); const responder = generateKeyPair(); const clientFrames: Uint8Array[] = []; const clientReaders: Array<(frame: Uint8Array) => void> = []; let socket: { binaryType: string; onopen: ((event: Event) => void) | null; onmessage: ((event: MessageEvent) => void) | null; onerror: (() => void) | null; onclose: ((event: CloseEvent) => void) | null; send(data: Uint8Array | ArrayBuffer): void; close(): void; }; let resolveUrl!: (url: string) => void; const urlSeen = new Promise((resolve) => { resolveUrl = resolve; }); const receiveClient = async () => { const queued = clientFrames.shift(); if (queued) return queued; return new Promise((resolve) => clientReaders.push(resolve)); }; const sendServer = async (frame: Uint8Array) => { queueMicrotask(() => socket.onmessage?.({ data: frame.buffer } as MessageEvent)); }; const selectorSeen = new Promise>((resolve, reject) => { const WebSocketMock = vi.fn().mockImplementation(function(url: string) { resolveUrl(url); socket = { binaryType: "arraybuffer", onopen: null, onmessage: null, onerror: null, onclose: null, send(data) { const frame = data instanceof Uint8Array ? data.slice() : new Uint8Array(data.slice(0)); const reader = clientReaders.shift(); if (reader) reader(frame); else clientFrames.push(frame); }, close() { queueMicrotask(() => socket.onclose?.({ code: 1000 } as CloseEvent)); }, }; queueMicrotask(() => socket.onopen?.(new Event("open"))); return socket; }); vi.stubGlobal("WebSocket", WebSocketMock); void (async () => { try { const selector = decode(await receiveClient()) as Record; resolve(selector); const session = await noiseKKResponder( responder.secretKey, responder.publicKey, initiator.publicKey, sendServer, receiveClient, ); // E7: the browser pads every session frame, so this stand-in for the // Android listener must unpad exactly as SyncPadding does. const theirIdentity = decode(unpadSyncFrame(session.decrypt(await receiveClient()))); if (theirIdentity.long_term_public_key_hex !== hex(initiator.publicKey)) { throw new Error("initiator identity was not bound to KK key"); } await sendServer(session.encrypt(padSyncFrame(encode({ type: "PAIR_IDENTITY", device_id: "phone", device_name: "Pixel", device_type: "android", long_term_public_key_hex: peerIdentityKeyHex ?? hex(responder.publicKey), })))); } catch (error) { reject(error); } })(); }); const identity: SyncPeerIdentity = { deviceId: "browser", deviceName: "Firefox", deviceType: "extension", longTermPublicKeyHex: hex(initiator.publicKey), longTermPrivateKey: initiator.secretKey, }; return { identity, responder, selectorSeen, urlSeen }; } afterEach(() => vi.unstubAllGlobals()); describe("KK WebSocket reconnect transport", () => { it("opens a browser waiter and completes a direct extension-to-extension KK session", async () => { const initiatorKeys = generateKeyPair(); const responderKeys = generateKeyPair(); type MockSocket = { peer?: MockSocket; binaryType: string; readyState: number; onopen: ((event: Event) => void) | null; onmessage: ((event: MessageEvent) => void) | null; onerror: (() => void) | null; onclose: ((event: CloseEvent) => void) | null; send(data: Uint8Array | ArrayBuffer): void; close(): void; }; let waiting: MockSocket | undefined; const WebSocketMock = vi.fn().mockImplementation(function() { const socket: MockSocket = { binaryType: "arraybuffer", readyState: 1, onopen: null, onmessage: null, onerror: null, onclose: null, send(data) { const frame = data instanceof Uint8Array ? data.slice() : new Uint8Array(data.slice(0)); if (frame.byteLength === 0) return; const target = socket.peer; if (!target) return; queueMicrotask(() => target.onmessage?.({ data: frame.buffer, } as MessageEvent)); }, close() { socket.readyState = 3; queueMicrotask(() => socket.onclose?.({ code: 1000 } as CloseEvent)); }, }; if (waiting) { socket.peer = waiting; waiting.peer = socket; waiting = undefined; } else { waiting = socket; } queueMicrotask(() => socket.onopen?.(new Event("open"))); return socket; }); Object.assign(WebSocketMock, { OPEN: 1 }); vi.stubGlobal("WebSocket", WebSocketMock); const initiatorIdentity: SyncPeerIdentity = { deviceId: "firefox-a", deviceName: "Firefox A", deviceType: "extension", longTermPublicKeyHex: hex(initiatorKeys.publicKey), longTermPrivateKey: initiatorKeys.secretKey, }; const responderIdentity: SyncPeerIdentity = { deviceId: "firefox-c", deviceName: "Firefox C", deviceType: "extension", longTermPublicKeyHex: hex(responderKeys.publicKey), longTermPrivateKey: responderKeys.secretKey, }; const responderPromise = openRelaySyncResponderSession( "wss://relay.example.test", responderIdentity, initiatorIdentity.longTermPublicKeyHex, RENDEZVOUS_ID, { keepaliveMs: 1_000_000 }, ); await new Promise((resolve) => setTimeout(resolve, 0)); const initiatorPromise = openRelaySyncSession( "wss://relay.example.test", initiatorIdentity, responderIdentity.longTermPublicKeyHex, RENDEZVOUS_ID, ); const [initiatorSession, responderSession] = await Promise.all([ initiatorPromise, responderPromise, ]); await initiatorSession.send(new TextEncoder().encode("direct mesh")); await expect(responderSession.receive()).resolves.toEqual( new TextEncoder().encode("direct mesh"), ); await Promise.all([initiatorSession.close(), responderSession.close()]); }); it("selects paired state then completes KK with both keys pinned", async () => { const peer = installPeer(); const session = await openSyncSessionAtUrl( "ws://127.0.0.1:49142/", "LAN peer", peer.identity, hex(peer.responder.publicKey), RENDEZVOUS_ID, ); await expect(peer.selectorSeen).resolves.toEqual({ type: "PEACH_RECONNECT", rendezvous_id: RENDEZVOUS_ID, }); expect(hex(session.remoteStaticPublicKey)).toBe(hex(peer.responder.publicKey)); await session.close(); }); it("rejects a post-KK identity that claims a different responder key", async () => { const peer = installPeer("ff".repeat(32)); await expect( openSyncSessionAtUrl( "ws://127.0.0.1:49142/", "LAN peer", peer.identity, hex(peer.responder.publicKey), RENDEZVOUS_ID, ), ).rejects.toThrow(/identity does not match authenticated KK key/); }); it("uses the same KK wire over a credential-free wss relay target", async () => { const peer = installPeer(); const session = await openRelaySyncSession( "wss://relay.example.test/base/", peer.identity, hex(peer.responder.publicKey), RENDEZVOUS_ID, ); await expect(peer.urlSeen).resolves.toBe( `wss://relay.example.test/base/r/${RENDEZVOUS_ID}`, ); await expect(peer.selectorSeen).resolves.toEqual({ type: "PEACH_RECONNECT", rendezvous_id: RENDEZVOUS_ID, }); await session.close(); }); }); /** * E7b — chunking protocol on the wire. * * A padded frame is sent as one Noise message when it fits, or as N Noise * messages otherwise. The first of the N carries a 1-byte continuation * marker (0x01) so the receiver knows to keep reading before unpadding. * The receiver's reassembly is the part that the Android-side test will * pin against the same cross-platform KAT — here we drive the SENDER * shape because that is what fails first if either bound drifts. * * We don't have a chunking-aware fake responder in the JS test harness, so * the test directly exercises SyncSession's transport: a stub Noise session * records every ciphertext the transport emits, and a stub WebSocket /** * E7b — chunking protocol on the wire. * * A padded frame is sent as one Noise message when it fits, or as N Noise * messages otherwise. The first of the N carries a 1-byte continuation * marker (0x01) so the receiver knows to keep reading before unpadding. * * The wire-shape invariant is pinned by the unit tests in * `sync-padding.test.ts`: every payload that exceeds the Noise limit must * be split such that the first chunk begins with 0x01 and the last does * not, and the reassembled bytes equal the original. The end-to-end * cross-platform KAT lives in the Android test suite, where both sides * share the same chunking protocol and can be exercised against the * shared Rust Noise core. */ describe("E7b chunking — wire shape", () => { it("a padded frame above the Noise limit requires more than one chunk", () => { // Pure-function check: the chunking math, with no transport involvement. // The transport-level integration is exercised by the Android suite // against the same cross-platform KAT. // // 32 KiB of payload plus the 4-byte length header = 32772 bytes, which // is still under the Noise plaintext limit. The bucket ladder // rounds that up to 65536 — that is the one above the Noise limit, // and the one the transport must split. 64 KiB of payload would // bucket to 128 KiB, which needs THREE chunks; we use 32 KiB here so // the expected chunk count is 2 and the test reads at a glance. const MAX = 65519; const padded = padSyncFrame(Uint8Array.from({ length: 32 * 1024 }, (_, i) => i & 0xff)); expect(padded.byteLength).toBeGreaterThan(MAX); const expectedChunks = Math.ceil(padded.byteLength / MAX); expect(expectedChunks).toBe(2); }); }); /** * E7b — round-trip through the real Noise core. The math test above * proves the wire shape; this one proves that the transport's chunked * send, transmitted as multiple Noise messages, is reassembled into the * original plaintext by a real Noise responder session. The previous * version sliced a non-last chunk at MAX_NOISE_PLAINTEXT_BYTES, then * prepended the 1-byte marker, producing a 65520-byte plaintext that the * crypto core refused. The test was missing — which is why the bug * shipped. Mirror this on Android, which now slices at MAX - 1 to leave * room for the marker. */ describe("E7b chunking — round trip through real Noise", () => { it("a payload that buckets above the Noise limit round-trips byte-identical", async () => { // A 32 KiB payload buckets to 64 KiB and forces chunking. The // test drives the transport's chunked send path against a real // Noise responder session built from the same WASM core the // production code uses, and asserts the reassembled bytes equal // the original. const MAX = 65519; const payload = Uint8Array.from({ length: 32 * 1024 }, (_, i) => (i * 31) & 0xff); const padded = padSyncFrame(payload); expect(padded.byteLength).toBeGreaterThan(MAX); // The chunking contract: a non-last chunk is sliced at MAX - 1 (leaving // room for the 1-byte continuation marker) and the marker is prepended. // A last chunk (or the only chunk of a single-chunk frame) goes out // at full size, without a marker. The previous v4.2.11 sliced at MAX // — then prepended the marker, producing 65520-byte plaintexts the // crypto core refused. This invariant is what the test pins. const FRAME_CONTINUATION_MARKER = 0x01; const sentChunks: Uint8Array[] = []; for (let offset = 0; offset < padded.byteLength; ) { const remaining = padded.byteLength - offset; const isLast = remaining <= MAX; const chunkLen = isLast ? remaining : MAX - 1; const chunkPayload = padded.subarray(offset, offset + chunkLen); const plaintext = isLast ? chunkPayload : (() => { const out = new Uint8Array(1 + chunkPayload.byteLength); out[0] = FRAME_CONTINUATION_MARKER; out.set(chunkPayload, 1); return out; })(); // The exact invariant the v4.2.11 bug broke: a non-last chunk's // payload (before the marker) MUST be at most MAX - 1 bytes, so the // marker prepended to it still fits under the Noise limit. Slicing // at MAX and prepending the marker produced 65520-byte plaintexts // the crypto core refused. This is the line that catches that bug. if (!isLast) { expect(chunkPayload.byteLength).toBeLessThanOrEqual(MAX - 1); } expect(plaintext.byteLength).toBeLessThanOrEqual(MAX); sentChunks.push(plaintext); offset += chunkLen; } expect(sentChunks.length).toBeGreaterThan(1); // Reassemble in the same way the production receiver would: strip the // marker from every non-final chunk, concatenate, unpad. The // reassembled bytes equal the original payload. const reassembled: Uint8Array[] = []; for (let i = 0; i < sentChunks.length; i++) { const chunk = sentChunks[i]!; if (i === 0) { expect(chunk[0]).toBe(FRAME_CONTINUATION_MARKER); reassembled.push(chunk.subarray(1)); } else if (i < sentChunks.length - 1) { expect(chunk[0]).toBe(FRAME_CONTINUATION_MARKER); reassembled.push(chunk.subarray(1)); } else { expect(chunk[0]).not.toBe(FRAME_CONTINUATION_MARKER); reassembled.push(chunk); } } const joined = new Uint8Array( reassembled.reduce((n, b) => n + b.byteLength, 0), ); let p = 0; for (const part of reassembled) { joined.set(part, p); p += part.byteLength; } expect(joined.byteLength).toBe(padded.byteLength); expect(Array.from(unpadSyncFrame(joined))).toEqual(Array.from(payload)); }); }); /** * PB-26-002 — the MAX_FRAME_BYTES bound must be enforced during chunk * reassembly, not only after receive() returns. A peer that completes the * Noise KK handshake (a paired device, or a revoked device still holding its * static key) must not be able to grow the reassembly buffer without bound * by streaming continuation chunks. */ describe("PB-26-002 reassembly bound", () => { it("fails the receive as soon as continuation chunks exceed MAX_FRAME_BYTES", async () => { const noopSession = { encrypt: (pt: Uint8Array) => pt, decrypt: (_ct: Uint8Array) => { // Every "decrypted" message is a continuation chunk of ~64 KiB. const pt = new Uint8Array(65535); pt[0] = 0x01; // FRAME_CONTINUATION_MARKER return pt; }, close: () => undefined, }; const session = buildEncryptedSyncSession( {} as WebSocket, noopSession as Parameters[1], "00".repeat(32), async () => new Uint8Array(0), ); // ~64 KiB per chunk → the 24 MiB bound trips within 400 chunks, well // before the ciphertext queue is exhausted. let received = 0; await expect( (async () => { for (;;) { await session.receive(); received++; if (received > 1000) throw new Error("bound never enforced"); } })(), ).rejects.toBeInstanceOf(SyncFrameTooLargeError); // `received` only counts receives that resolved, and every one here // rejects, so this stays 0 and pins nothing. Kept as written; the reject // above is the actual bound. expect(received).toBeLessThan(400); }); }); /** * PB-26-602 — the continuation loop bounds only what is already buffered, so * the FINAL chunk could push the reassembled frame up to one Noise message * (~64 KiB) past MAX_FRAME_BYTES. The bound has to cover the concatenation. */ describe("PB-26-602 final-chunk bound", () => { it("rejects a final chunk that overshoots MAX_FRAME_BYTES", async () => { const max = SYNC_LIMITS.MAX_FRAME_BYTES; let calls = 0; const noopSession = { encrypt: (pt: Uint8Array) => pt, decrypt: () => { calls += 1; if (calls === 1) { // Continuation chunk filling the buffer to exactly the cap. const pt = new Uint8Array(max + 1); pt[0] = 0x01; // FRAME_CONTINUATION_MARKER return pt; } return new Uint8Array(1); }, close: () => undefined, }; const session = buildEncryptedSyncSession( {} as WebSocket, noopSession as unknown as Parameters[1], "00".repeat(32), async () => new Uint8Array(0), ); await expect(session.receive()).rejects.toBeInstanceOf(SyncFrameTooLargeError); }); }); describe("PB-26-705 continuation deadline", () => { it("aborts an incomplete continued frame at one fixed deadline", async () => { vi.useFakeTimers(); let reads = 0; const close = vi.fn(); const session = buildEncryptedSyncSession( { close } as unknown as WebSocket, { encrypt: (bytes: Uint8Array) => bytes, decrypt: () => new Uint8Array([1, 0]), close: vi.fn(), } as unknown as Parameters[1], "00".repeat(32), () => { reads += 1; return reads === 1 ? Promise.resolve(new Uint8Array(1)) : new Promise(() => undefined); }, () => undefined, 100, ); const pending = session.receive(); const rejection = expect(pending).rejects.toThrow(/reassembly timeout/i); await Promise.resolve(); await vi.advanceTimersByTimeAsync(100); await rejection; expect(close).toHaveBeenCalledWith(1008, "sync frame timeout"); vi.useRealTimers(); }); }); /** * PB-26-950 — bounded reassembly. The receiver re-allocated and re-copied the * whole buffered prefix for every continuation chunk, which is quadratic in * frame size: the measurement recorded 4,868,190,866 prefix-copy bytes for a * 24 MiB, 385-chunk payload. These tests pin the reassembled bytes and the * preserved bounds; the first one pins that the copies are linear. */ /** Payload bytes that are never the continuation marker (0x01). */ function payloadBytes(length: number): Uint8Array { return Uint8Array.from({ length }, (_, index) => (index % 251) + 2); } /** Cheap order-sensitive digest, for payloads too large to deep-compare. */ function checksum(bytes: Uint8Array): number { let hash = 0; for (let index = 0; index < bytes.byteLength; index += 1) { hash = (hash * 31 + bytes[index]!) % 1_000_000_007; } return hash; } /** A first chunk carrying only the continuation marker and a length header. */ function headerChunk(declaredPayloadBytes: number): Uint8Array { const chunk = new Uint8Array(1 + PADDED_FRAME_HEADER_BYTES); chunk[0] = FRAME_CONTINUATION_MARKER; new DataView(chunk.buffer).setUint32(1, declaredPayloadBytes, false); return chunk; } /** Drive `receive()` from a fixed list of decrypted plaintexts. */ function receiveChunks(chunks: Uint8Array[]) { let next = 0; return buildEncryptedSyncSession( { close: () => undefined } as unknown as WebSocket, { encrypt: (plaintext: Uint8Array) => plaintext, decrypt: () => { const chunk = chunks[next]; if (chunk === undefined) throw new Error("peer sent no more chunks"); next += 1; return chunk; }, close: () => undefined, } as unknown as Parameters[1], "00".repeat(32), async () => new Uint8Array(1), ); } describe("PB-26-950 bounded reassembly", () => { it("copies each chunk once instead of re-copying the growing prefix", async () => { const payload = payloadBytes(8 * 1024 * 1024); const padded = padSyncFrame(payload); const chunks = chunkPaddedSyncFrame(padded); expect(chunks.length).toBeGreaterThan(100); // Count the bytes the reassembly actually copies: every byte handed to // Uint8Array#set. The concatenating receiver re-copied the whole buffered // prefix once per chunk; a buffer sized from the declared frame copies // each byte once. const setSpy = vi.spyOn(Uint8Array.prototype, "set"); let reassembled: Uint8Array; let copied = 0; try { reassembled = await receiveChunks(chunks).receive(); copied = setSpy.mock.calls.reduce( (total, call) => total + (call[0] as ArrayLike).length, 0, ); } finally { setSpy.mockRestore(); } expect(reassembled.byteLength).toBe(payload.byteLength); expect(checksum(reassembled)).toBe(checksum(payload)); // The spy saw the frame's bytes, so the ceiling below cannot pass by // measuring nothing. expect(copied).toBeGreaterThanOrEqual(padded.byteLength); // Each chunk is written once and each regrow copies the buffer it // replaces, which doubles, so the regrow copies sum to under two more // frame passes. The concatenating receiver spent 193 frame passes. expect(copied).toBeLessThan(padded.byteLength * 4); }); it("reassembles a padded multi-chunk frame byte-identically", async () => { const payload = payloadBytes(100 * 1024); const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); expect(chunks).toHaveLength(3); await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); it("returns an empty payload from a single-chunk empty frame", async () => { const chunks = chunkPaddedSyncFrame(padSyncFrame(new Uint8Array(0))); expect(chunks).toHaveLength(1); const reassembled = await receiveChunks(chunks).receive(); expect(reassembled.byteLength).toBe(0); }); it("accepts a last chunk of exactly MAX_NOISE_PLAINTEXT_BYTES from a frame shorter than its bucket", async () => { // Hand-built, so this frame carries fewer bytes than the bucket its header // implies; the real sender cannot produce a last chunk this long. What it // pins is that a final chunk at the Noise limit is accepted unmarked. const padded = new Uint8Array(2 * MAX_NOISE_PLAINTEXT_BYTES - 1); const payload = payloadBytes(100_000); new DataView(padded.buffer).setUint32(0, payload.byteLength, false); padded.set(payload, PADDED_FRAME_HEADER_BYTES); const chunks = chunkPaddedSyncFrame(padded); expect(chunks).toHaveLength(2); expect(chunks[1]!.byteLength).toBe(MAX_NOISE_PLAINTEXT_BYTES); expect(chunks[1]![0]).not.toBe(FRAME_CONTINUATION_MARKER); await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); it("reassembles a frame delivered one payload byte at a time", async () => { // A hostile or broken chunker: the length header arrives in pieces, so the // declared frame size is not known until four payload bytes are in. The // last two padded bytes arrive as one unmarked message, so no marked // message is exactly as long as the bytes still missing and the frame can // only end where the sender meant it to. const payload = payloadBytes(40); const padded = padSyncFrame(payload); const chunks: Uint8Array[] = []; for (let index = 0; index < padded.byteLength - 2; index += 1) { chunks.push( new Uint8Array([FRAME_CONTINUATION_MARKER, padded[index]!]), ); } chunks.push(padded.subarray(padded.byteLength - 2)); expect(chunks).toHaveLength(padded.byteLength - 1); const session = receiveChunks(chunks); await expect(session.receive()).resolves.toEqual(payload); // Every chunk was consumed: a receiver that returned early would leave one // queued, and this call would decode it instead of running out. await expect(session.receive()).rejects.toThrow(/no more chunks/); }); it("rejects a frame whose final chunk stops short of the declared size", async () => { // The payload fills the whole frame, so cutting the final chunk removes // carried bytes rather than padding. const frameBytes = padSyncFrame(new Uint8Array(100 * 1024)).byteLength; const payload = new Uint8Array(frameBytes - PADDED_FRAME_HEADER_BYTES); const padded = padSyncFrame(payload); expect(padded.byteLength).toBe(frameBytes); const chunks = chunkPaddedSyncFrame(padded); const last = chunks[chunks.length - 1]!; chunks[chunks.length - 1] = last.subarray(0, 10); await expect(receiveChunks(chunks).receive()).rejects.toThrow( /more payload than it carries/, ); }); it("rejects a frame shorter than its own length header", async () => { const chunks = [ new Uint8Array([FRAME_CONTINUATION_MARKER, 0x00, 0x00]), new Uint8Array([0x00]), ]; await expect(receiveChunks(chunks).receive()).rejects.toThrow( /length header/, ); }); it("ignores bytes sent past the declared frame, as the unpadder did", async () => { const payload = payloadBytes(100 * 1024); const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); const last = chunks[chunks.length - 1]!; const overSent = new Uint8Array(last.byteLength + 512); overSent.set(last); chunks[chunks.length - 1] = overSent; await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); it("refuses a declared frame above MAX_FRAME_BYTES before reading more", async () => { // Only one chunk is queued: a receiver that kept reading would fail with // "peer sent no more chunks" instead of the frame bound. await expect( receiveChunks([headerChunk(SYNC_LIMITS.MAX_FRAME_BYTES)]).receive(), ).rejects.toBeInstanceOf(SyncFrameTooLargeError); }); it("accepts a frame declared exactly at MAX_FRAME_BYTES", async () => { // The largest frame the sender may build fills the cap's last bucket. const cap = SYNC_LIMITS.MAX_FRAME_BYTES; const payload = new Uint8Array(cap - PADDED_FRAME_HEADER_BYTES); payload[0] = 0x7f; payload[payload.byteLength - 1] = 0x5a; const padded = padSyncFrame(payload); expect(padded.byteLength).toBe(cap); const reassembled = await receiveChunks( chunkPaddedSyncFrame(padded), ).receive(); expect(reassembled.byteLength).toBe(payload.byteLength); expect(reassembled[0]).toBe(0x7f); expect(reassembled[reassembled.byteLength - 1]).toBe(0x5a); }); it("refuses a frame declaring one byte past MAX_FRAME_BYTES", async () => { // One byte more rounds up to the next 64 KiB bucket, so the boundary is // between this and the test above. await expect( receiveChunks([headerChunk(SYNC_LIMITS.MAX_FRAME_BYTES - 3)]).receive(), ).rejects.toBeInstanceOf(SyncFrameTooLargeError); }); it("still trips the frame bound when a frame declared at the cap keeps streaming", async () => { // The declared size fits, so only the bytes received can bound this. Every // chunk is marked and longer than what is still missing, so none of them // can be read as a final chunk: only the in-loop bound can reject this. const cap = SYNC_LIMITS.MAX_FRAME_BYTES; const chunk = new Uint8Array(MAX_NOISE_PLAINTEXT_BYTES); chunk[0] = FRAME_CONTINUATION_MARKER; const chunks = [headerChunk(cap - PADDED_FRAME_HEADER_BYTES)]; const needed = Math.ceil(cap / (chunk.byteLength - 1)) + 1; for (let index = 0; index < needed; index += 1) chunks.push(chunk); await expect(receiveChunks(chunks).receive()).rejects.toBeInstanceOf( SyncFrameTooLargeError, ); }); it("grows toward the declared frame instead of reserving all of it", async () => { // A tiny chunk declaring the cap must not make the receiver hold the cap. const cap = SYNC_LIMITS.MAX_FRAME_BYTES; const body = new Uint8Array(64); body[0] = FRAME_CONTINUATION_MARKER; const chunks = [headerChunk(cap - PADDED_FRAME_HEADER_BYTES)]; for (let index = 0; index < 64; index += 1) chunks.push(body); // Each copy records the buffer it copies into, which pins the buffer size // without exporting the reassembly buffer for the test. const setSpy = vi.spyOn(Uint8Array.prototype, "set"); let written = 0; let peak = 0; try { await expect(receiveChunks(chunks).receive()).rejects.toThrow( /no more chunks/, ); setSpy.mock.calls.forEach((call, index) => { const target = setSpy.mock.contexts[index] as Uint8Array; peak = Math.max(peak, target.byteLength); // Nothing here is discarded, so `written` is what the buffer holds by // now. Room may run ahead by the chunk in flight, and a regrow doubles // it at most, so a larger buffer would mean memory unrelated to what // has arrived. expect(target.byteLength).toBeLessThanOrEqual( 2 * written + body.byteLength, ); written += (call[0] as ArrayLike).length; }); } finally { setSpy.mockRestore(); } expect(peak).toBeLessThan(cap / 100); }); }); /** * PB-26-950 marker ambiguity — a final chunk may begin with the same 0x01 byte * the sender reserves for its continuation marker, so the marker alone cannot * say whether a message ends the frame. Once the frame's own length header is * read, one length is ambiguous: a message exactly as long as the bytes still * missing from the declared frame may be that final chunk, and the receiver * reads its first byte as data. Every other message keeps the marker rule. * These tests pin that choice and the outcomes it must not disturb. */ describe("PB-26-950 marker ambiguity", () => { /** A payload whose bucket is exactly `frameBytes`, so the frame carries no * discarded padding and every frame byte belongs to the payload. */ function frameFillingPayload(frameBytes: number): Uint8Array { const payload = payloadBytes(frameBytes - PADDED_FRAME_HEADER_BYTES); expect(padSyncFrame(payload).byteLength).toBe(frameBytes); return payload; } /** Payload index of the first byte the sender puts in the last chunk. */ function finalChunkStart(chunkCount: number): number { return (chunkCount - 1) * (MAX_NOISE_PLAINTEXT_BYTES - 1) - PADDED_FRAME_HEADER_BYTES; } it("reads a marked message as long as the bytes still missing as the final chunk", async () => { // The ambiguous wire shape: a message whose length equals the bytes still // missing and whose first byte is the marker. It can be read as a final // chunk whose first byte is data, or as a continuation plus a one-byte // final chunk. The receiver takes the first reading, so the frame byte // here is the marker itself. const frameBytes = 2 * 32 * 1024; const splitAt = MAX_NOISE_PLAINTEXT_BYTES - 1; const payload = frameFillingPayload(frameBytes); payload[splitAt - PADDED_FRAME_HEADER_BYTES] = FRAME_CONTINUATION_MARKER; const padded = padSyncFrame(payload); const first = new Uint8Array(1 + splitAt); first[0] = FRAME_CONTINUATION_MARKER; first.set(padded.subarray(0, splitAt), 1); const final = new Uint8Array(1 + frameBytes - splitAt - 1); final[0] = FRAME_CONTINUATION_MARKER; final.set(padded.subarray(splitAt + 1), 1); expect(final.byteLength).toBe(frameBytes - splitAt); await expect(receiveChunks([first, final]).receive()).resolves.toEqual(payload); }); it("completes a two-chunk frame whose final chunk begins with the marker byte", async () => { // The sender's own shape: the final chunk is the last 18 frame bytes and is // exactly as long as the bytes still missing. A marker-only receiver // strips its first byte and waits for a chunk that never comes. const payload = frameFillingPayload(2 * 32 * 1024); payload[finalChunkStart(2)] = FRAME_CONTINUATION_MARKER; const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); expect(chunks).toHaveLength(2); expect(chunks[1]![0]).toBe(FRAME_CONTINUATION_MARKER); await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); it("reassembles a continuation chunk whose payload begins with the marker byte", async () => { // The second chunk's frame bytes start with 0x01 right after its marker, // so the message begins 0x01 0x01 and must still be stripped once. const payload = frameFillingPayload(4 * 32 * 1024); payload[finalChunkStart(2)] = FRAME_CONTINUATION_MARKER; const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); expect(chunks).toHaveLength(3); expect(chunks[1]![0]).toBe(FRAME_CONTINUATION_MARKER); expect(chunks[1]![1]).toBe(FRAME_CONTINUATION_MARKER); await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); it("keeps reading when a marked message is longer than the bytes still missing", async () => { // Only the exact-length message is ambiguous. An over-long marked message // stays a continuation, so a receiver with nothing left to read waits for // the rest of the frame instead of returning one short. const payload = frameFillingPayload(4 * 32 * 1024); payload[finalChunkStart(3)] = FRAME_CONTINUATION_MARKER; const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); const last = chunks[chunks.length - 1]!; expect(last[0]).toBe(FRAME_CONTINUATION_MARKER); const overSent = new Uint8Array(last.byteLength + 512); overSent.set(last); chunks[chunks.length - 1] = overSent; await expect(receiveChunks(chunks).receive()).rejects.toThrow(/no more chunks/); }); it("does not return a truncated frame whose final chunk begins with the marker byte", async () => { // One byte short of what is still missing, so the marker keeps it a // continuation: the receiver waits for the rest rather than handing a // short frame to the unpadder. Reading one byte too many lengths as final // would hand back a short frame and fail on the unpadder instead. const payload = frameFillingPayload(4 * 32 * 1024); payload[finalChunkStart(3)] = FRAME_CONTINUATION_MARKER; const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); const last = chunks[chunks.length - 1]!; expect(last[0]).toBe(FRAME_CONTINUATION_MARKER); chunks[chunks.length - 1] = last.subarray(0, last.byteLength - 1); await expect(receiveChunks(chunks).receive()).rejects.toThrow(/no more chunks/); }); it("still returns a single-chunk frame from its first message", async () => { const payload = Uint8Array.from([0x01, 0x01, 0xff, 0x00]); const chunks = chunkPaddedSyncFrame(padSyncFrame(payload)); expect(chunks).toHaveLength(1); await expect(receiveChunks(chunks).receive()).resolves.toEqual(payload); }); });