fd2766f30216
bound padded-frame reassembly without prefix copies (v5.3.31)
- time
- 2026-11-22 23:43 UTC · 5 days ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-5.6-sol
- session
- remediate interim audit findings
- parent
- d3e8fc2f131b
↓ peach-browser-fd2766f3.tar.gzatlas at this save
files changed7 files
manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/shared/sync-kk-transport.test.ts+257 −1src/shared/sync-padding.test.ts+21 −0src/shared/sync-padding.ts+37 −12src/shared/sync-transport.ts+128 −37manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.30",4+ "version": "5.3.31",55 "description": "Zero-knowledge password manager",66 "browser_specific_settings": {77 "gecko": {manifest.json+1 −1
@@ -2,7 +2,7 @@22 "manifest_version": 3,33 "minimum_chrome_version": "116",44 "name": "Peach Password Manager",5- "version": "5.3.30",5+ "version": "5.3.31",66 "description": "Zero-knowledge password manager",77 "action": {88 "default_popup": "src/popup/index.html",package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "peach",3- "version": "5.3.30",3+ "version": "5.3.31",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/shared/sync-kk-transport.test.ts+257 −1
@@ -2,8 +2,15 @@22 import { generateKeyPair } from "@stablelib/x25519";33 import { noiseKKResponder } from "./noise-js";44 import { SYNC_LIMITS } from "./sync-limits";5-import { padSyncFrame, unpadSyncFrame } from "./sync-padding";65 import {6+ FRAME_CONTINUATION_MARKER,7+ MAX_NOISE_PLAINTEXT_BYTES,8+ PADDED_FRAME_HEADER_BYTES,9+ chunkPaddedSyncFrame,10+ padSyncFrame,11+ unpadSyncFrame,12+} from "./sync-padding";13+import {714 buildEncryptedSyncSession,815 openRelaySyncResponderSession,916 openRelaySyncSession,@@ -429,6 +436,9 @@429436 }430437 })(),431438 ).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.432442 expect(received).toBeLessThan(400);433443 });434444 });@@ -495,5 +505,251 @@495505 await rejection;496506 expect(close).toHaveBeenCalledWith(1008, "sync frame timeout");497507 vi.useRealTimers();508+ });509+});510+511+/**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+ */518+519+/** Payload bytes that are never the continuation marker (0x01). */520+function payloadBytes(length: number): Uint8Array {521+ return Uint8Array.from({ length }, (_, index) => (index % 251) + 2);522+}523+524+/** Cheap order-sensitive digest, for payloads too large to deep-compare. */525+function 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+}532+533+/** A first chunk carrying only the continuation marker and a length header. */534+function 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+}540+541+/** Drive `receive()` from a fixed list of decrypted plaintexts. */542+function 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+}560+561+describe("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);567+568+ // 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+ });594+595+ 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+ });601+602+ 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+ });608+609+ 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+ });623+624+ 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+ });639+640+ 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+ });654+655+ 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+ });664+665+ 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+ });674+675+ 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+ });682+683+ 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+ });698+699+ 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+ });706+707+ 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);715+716+ await expect(receiveChunks(chunks).receive()).rejects.toBeInstanceOf(717+ SyncFrameTooLargeError,718+ );719+ });720+721+ 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);728+729+ // 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);498754 });499755 });src/shared/sync-padding.test.ts+21 −0
@@ -1,6 +1,7 @@11 import { describe, expect, it } from "vitest";22 import {33 padSyncFrame,4+ declaredPaddedFrameBytes,45 syncFrameBucket,56 unpadSyncFrame,67 MAX_NOISE_PLAINTEXT_BYTES,@@ -60,6 +61,26 @@6061 6162 it("rejects a frame shorter than its length header", () => {6263 expect(() => unpadSyncFrame(new Uint8Array(3))).toThrow(/length header/);64+ });65+66+ it("declares the padded size the frame's own length header implies", () => {67+ // Every input comes from padSyncFrame, so this pins the header round-trip;68+ // the KAT above pins the buckets.69+ for (const size of [0, 251, 70_000, 1_000_000]) {70+ const payload = new Uint8Array(size);71+ const padded = padSyncFrame(payload);72+ expect(declaredPaddedFrameBytes(padded)).toBe(padded.byteLength);73+ }74+ });75+76+ it("refuses a prefix shorter than the length header", () => {77+ // The receiver reads this only once it holds all four header bytes.78+ expect(() => declaredPaddedFrameBytes(new Uint8Array(0))).toThrow(79+ /length header/,80+ );81+ expect(() => declaredPaddedFrameBytes(new Uint8Array(3))).toThrow(82+ /length header/,83+ );6384 });6485 });6586 src/shared/sync-padding.ts+37 −12
@@ -17,7 +17,9 @@1717 // identically. A mismatch is loud, not silent: the receiver reads a length1818 // that does not fit its frame and rejects it.1919 20-const HEADER_BYTES = 4;20+/** Bytes of the big-endian payload length that starts every padded frame. */21+export const PADDED_FRAME_HEADER_BYTES = 4;22+2123 /** Below this, every frame looks the same — covers HELLO/REQUEST/DONE and any2224 * other small control frame. */2325 const MIN_BUCKET = 256;@@ -40,15 +42,15 @@4042 }4143 4244 export function padSyncFrame(payload: Uint8Array): Uint8Array {43- const bucket = syncFrameBucket(HEADER_BYTES + payload.length);45+ const bucket = syncFrameBucket(PADDED_FRAME_HEADER_BYTES + payload.length);4446 const out = new Uint8Array(bucket);4547 new DataView(out.buffer).setUint32(0, payload.length, false);46- out.set(payload, HEADER_BYTES);48+ out.set(payload, PADDED_FRAME_HEADER_BYTES);4749 return out;4850 }4951 5052 export function unpadSyncFrame(padded: Uint8Array): Uint8Array {51- if (padded.length < HEADER_BYTES) {53+ if (padded.length < PADDED_FRAME_HEADER_BYTES) {5254 throw new Error("padded sync frame is shorter than its length header");5355 }5456 const length = new DataView(@@ -56,13 +58,37 @@5658 padded.byteOffset,5759 padded.byteLength,5860 ).getUint32(0, false);59- if (length > padded.length - HEADER_BYTES) {61+ if (length > padded.length - PADDED_FRAME_HEADER_BYTES) {6062 throw new Error("padded sync frame declares more payload than it carries");6163 }62- return padded.slice(HEADER_BYTES, HEADER_BYTES + length);64+ return padded.slice(65+ PADDED_FRAME_HEADER_BYTES,66+ PADDED_FRAME_HEADER_BYTES + length,67+ );6368 }6469 6570 /**71+ * Padded size a frame's own length header declares. The prefix must already72+ * hold the header; fewer bytes is a caller bug, not a frame the wire can73+ * produce. Receivers use the result to size one reassembly buffer, which74+ * bounds what is stored — the frame itself ends at the first chunk without the75+ * continuation marker.76+ */77+export function declaredPaddedFrameBytes(paddedPrefix: Uint8Array): number {78+ if (paddedPrefix.length < PADDED_FRAME_HEADER_BYTES) {79+ throw new Error(80+ "padded sync frame prefix is shorter than its length header",81+ );82+ }83+ const length = new DataView(84+ paddedPrefix.buffer,85+ paddedPrefix.byteOffset,86+ PADDED_FRAME_HEADER_BYTES,87+ ).getUint32(0, false);88+ return syncFrameBucket(PADDED_FRAME_HEADER_BYTES + length);89+}90+91+/**6692 * Maximum plaintext bytes that fit in a single Noise transport message.6793 * Noise caps a ciphertext at 65535 bytes, of which 16 are the Poly1305 auth6894 * tag (see `crypto-core/src/lib.rs`), so a 65519-byte plaintext is the limit@@ -75,12 +101,11 @@75101 export const MAX_NOISE_PLAINTEXT_BYTES = 65519;76102 77103 /**78- * The first byte of a chunked padded frame. Identifies that what follows is79- * a fragment of a larger padded frame, not a complete one — receivers must80- * keep reading until the declared bucket has been reassembled before they81- * can hand the frame to the unpadder. Single-chunk frames never carry this82- * header: a frame that fits one Noise message is sent as one message, as83- * before, and the receiver uses its length header to know when it is done.104+ * The first byte of a chunked padded frame. Every chunk carries it except the105+ * last, so a receiver keeps reading until a chunk arrives without it and only106+ * then hands the frame to the unpadder. The frame's own length header, not the107+ * number of chunks, bounds how much of those bytes it keeps. A frame that fits108+ * one Noise message is sent as one unmarked chunk, as before.84109 */85110 export const FRAME_CONTINUATION_MARKER: number = 0x01;86111 src/shared/sync-transport.ts+128 −37
@@ -32,6 +32,8 @@3232 import {3333 padSyncFrame,3434 unpadSyncFrame,35+ declaredPaddedFrameBytes,36+ PADDED_FRAME_HEADER_BYTES,3537 MAX_NOISE_PLAINTEXT_BYTES,3638 FRAME_CONTINUATION_MARKER,3739 chunkPaddedSyncFrame,@@ -480,6 +482,100 @@480482 );481483 }482484 485+/**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+ */498+class 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;506+507+ get received(): number {508+ return this.seen;509+ }510+511+ /** The frame bytes held for the unpadder. */512+ get assembled(): Uint8Array {513+ return this.bytes.subarray(0, this.filled);514+ }515+516+ 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+ }536+537+ /** 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+ }549+550+ /** 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+ }561+562+ /**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+}578+483579 // Exported for the PB-26-002 reassembly-bound regression test.484580 export function buildEncryptedSyncSession(485581 ws: WebSocket,@@ -496,10 +592,10 @@496592 // E7b: a padded frame can legitimately be up to 24 MiB, but Noise caps a497593 // single transport message at 65535 bytes (see crypto-core/src/lib.rs —498594 // 65519 plaintext, 16-byte tag). We split a too-large padded frame into499- // numbered Noise messages and tag every chunk after the first with a500- // 1-byte continuation header. The receiver reassembles by reading the501- // padded frame's 4-byte length header, computing the same bucket from502- // the same ladder, and keeping reading until the bucket is full.595+ // 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.503599 const padded = padSyncFrame(plaintext);504600 if (padded.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {505601 throw new SyncFrameTooLargeError(@@ -534,7 +630,7 @@534630 // begins with the continuation marker, the message is one of N chunks535631 // — the padded-frame length header comes inside the first chunk's536632 // payload, so we read it there to learn the total.537- let buffered: Uint8Array | null = null;633+ let reassembly: PaddedFrameReassembly | null = null;538634 let deadlineTimer: ReturnType<typeof setTimeout> | undefined;539635 let deadline: Promise<never> | undefined;540636 try {@@ -543,9 +639,14 @@543639 ? Promise.race([receiveCiphertext(), deadline])544640 : receiveCiphertext());545641 const pt = session.decrypt(ct);546- if (buffered === null && pt.byteLength > 0 && pt[0] === FRAME_CONTINUATION_MARKER) {547- // Strip the continuation byte and keep the payload.548- buffered = pt.subarray(1);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();549650 deadline = new Promise<never>((_resolve, reject) => {550651 deadlineTimer = setTimeout(() => {551652 session.close();@@ -553,41 +654,31 @@553654 reject(new SyncFrameReassemblyTimeoutError());554655 }, reassemblyTimeoutMs);555656 });556- continue;557657 }558- if (buffered !== null) {559- if (pt.byteLength > 0 && pt[0] === FRAME_CONTINUATION_MARKER) {560- const merged: Uint8Array = new Uint8Array(buffered.length + pt.byteLength - 1);561- merged.set(buffered, 0);562- merged.set(pt.subarray(1), buffered.length);563- buffered = merged;564- // PB-26-002: the frame bound must hold DURING reassembly. The565- // post-receive check in the coordinator runs only after the full566- // frame is in memory, so a peer that completes the Noise KK567- // handshake could otherwise stream continuation chunks without568- // bound inside the session window.569- if (buffered.length > SYNC_LIMITS.MAX_FRAME_BYTES) {570- throw new SyncFrameTooLargeError(571- `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,572- );573- }574- continue;575- }576- // Final chunk. PB-26-602: the continuation loop only bounds what is577- // buffered, so the last chunk could push the frame up to 64 KiB past578- // the cap. Bound the concatenation, not just the buffer.579- if (buffered.length + pt.byteLength > SYNC_LIMITS.MAX_FRAME_BYTES) {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) {580667 throw new SyncFrameTooLargeError(581668 `sync frame exceeds ${SYNC_LIMITS.MAX_FRAME_BYTES} bytes`,582669 );583670 }584- const reassembled = new Uint8Array(buffered.length + pt.byteLength);585- reassembled.set(buffered, 0);586- reassembled.set(pt, buffered.length);587- return unpadSyncFrame(reassembled);671+ continue;588672 }589- // Single-chunk frame, exactly as before.590- return unpadSyncFrame(pt);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);591682 }592683 } finally {593684 if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);