From 9c5cf19713d41cd887f7b5494d8e0f4bd7908f5f Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:21:42 -0600 Subject: [PATCH 1/3] cold-store-reaper(worker): bound zstd decompression by the manifest expected size (#6590) decompressFrame was a bare fzstd decompress(): the whole expansion was allocated before the sha256 check, so a small frame could expand past the Worker memory limit and kill the isolate (and every joined fetch on the single-flight Durable Object) instead of producing the designed clean 502. The decoder now streams the frame in slices and counts output as it is produced: past the limit the output is dropped and ExpansionLimitError is thrown, so peak memory tracks the expected size. rehydrate finally reads the job size the entry point already selects (o.size): a missing or non-numeric size fails closed with a 502 before any fetch, and an over-expansion maps to the existing 502 HttpError shape. dist/worker.js rebuilt. Tests: new test/bounded-decompress.test.mjs (wired into npm test) -- a 4 MiB-of-zeros frame (a few KiB compressed) is refused at a 1 MiB expected size at both decoder and rehydrate level, served at exactly its size with a matching sha, refused one byte under; missing/non-numeric job size fails closed; unusable decoder limits are TypeErrors. run-local-proof now passes the exact sample size, and the range-ignored job helper carries size like a real manifest row; the whole npm test suite passes. --- pkgs/cold-store-reaper/worker/dist/worker.js | 178 ++++++++++++++---- pkgs/cold-store-reaper/worker/package.json | 2 +- pkgs/cold-store-reaper/worker/src/decoder.js | 73 ++++++- pkgs/cold-store-reaper/worker/src/index.js | 25 ++- .../worker/test/bounded-decompress.test.mjs | 158 ++++++++++++++++ .../worker/test/range-ignored.test.mjs | 1 + .../worker/test/run-local-proof.mjs | 2 +- 7 files changed, 392 insertions(+), 47 deletions(-) create mode 100644 pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs diff --git a/pkgs/cold-store-reaper/worker/dist/worker.js b/pkgs/cold-store-reaper/worker/dist/worker.js index 926f2c032a..48ad3ab675 100644 --- a/pkgs/cold-store-reaper/worker/dist/worker.js +++ b/pkgs/cold-store-reaper/worker/dist/worker.js @@ -1,4 +1,4 @@ -// ../../../../../code/pkgs/cold-store-reaper/worker/node_modules/fzstd/esm/index.mjs +// node_modules/fzstd/esm/index.mjs var ab = ArrayBuffer; var u8 = Uint8Array; var u16 = Uint16Array; @@ -582,46 +582,139 @@ var cct = function(bufs, ol) { } return buf; }; -function decompress(dat, buf) { - var bufs = [], nb = +!buf; - var bt = 0, ol = 0; - for (; dat.length; ) { - var st = rzfh(dat, nb || buf); - if (typeof st == "object") { - if (nb) { - buf = null; - if (st.w.length == st.u) { - bufs.push(buf = st.w); - ol += st.u; +var Decompress = /* @__PURE__ */ (function() { + function Decompress2(ondata) { + this.ondata = ondata; + this.c = []; + this.l = 0; + this.z = 0; + } + Decompress2.prototype.push = function(chunk, final) { + if (typeof this.s == "number") { + var sub = Math.min(chunk.length, this.s); + chunk = chunk.subarray(sub); + this.s -= sub; + } + var sl = chunk.length; + var ncs = sl + this.l; + if (!this.s) { + if (final) { + if (!ncs) { + this.ondata(new u8(0), true); + return; } - } else { - bufs.push(buf); - st.e = 0; + if (ncs < 5) + err(5); + } else if (ncs < 18) { + this.c.push(chunk); + this.l = ncs; + return; + } + if (this.l) { + this.c.push(chunk); + chunk = cct(this.c, ncs); + this.c = []; + this.l = 0; + } + if (typeof (this.s = rzfh(chunk)) == "number") + return this.push(chunk, final); + } + if (typeof this.s != "number") { + if (ncs < (this.z || 3)) { + if (final) + err(5); + this.c.push(chunk); + this.l = ncs; + return; + } + if (this.l) { + this.c.push(chunk); + chunk = cct(this.c, ncs); + this.c = []; + this.l = 0; } - for (; !st.l; ) { - var blk = rzb(dat, st, buf); - if (!blk) + if (!this.z && ncs < (this.z = chunk[this.s.b] & 2 ? 4 : 3 + (chunk[this.s.b] >> 3 | chunk[this.s.b + 1] << 5 | chunk[this.s.b + 2] << 13))) { + if (final) err(5); - if (buf) - st.e = st.y; - else { - bufs.push(blk); - ol += blk.length; - cpw(st.w, 0, blk.length); - st.w.set(blk, st.w.length - blk.length); + this.c.push(chunk); + this.l = ncs; + return; + } else + this.z = 0; + for (; ; ) { + var blk = rzb(chunk, this.s); + if (!blk) { + if (final) + err(5); + var adc = chunk.subarray(this.s.b); + this.s.b = 0; + this.c.push(adc), this.l += adc.length; + return; + } else { + this.ondata(blk, false); + cpw(this.s.w, 0, blk.length); + this.s.w.set(blk, this.s.w.length - blk.length); + } + if (this.s.l) { + var rest = chunk.subarray(this.s.b); + this.s = this.s.c * 4; + this.push(rest, final); + return; } } - bt = st.b + st.c * 4; - } else - bt = st; - dat = dat.subarray(bt); - } - return cct(bufs, ol); -} + } else if (final) + err(5); + }; + return Decompress2; +})(); // src/decoder.js -function decompressFrame(frameBytes) { - return decompress(frameBytes); +var ExpansionLimitError = class extends Error { + constructor(limit, produced) { + super( + `zstd frame expands past the expected size: limit ${limit} bytes, already produced ${produced} bytes` + ); + this.name = "ExpansionLimitError"; + this.limit = limit; + } +}; +var INPUT_SLICE_BYTES = 16 * 1024; +function decompressFrame(frameBytes, maxPlainBytes) { + if (!Number.isSafeInteger(maxPlainBytes) || maxPlainBytes < 0) { + throw new TypeError( + `decompressFrame requires a non-negative integer byte limit, got ${maxPlainBytes}` + ); + } + const chunks = []; + let total = 0; + let exceeded = false; + const stream = new Decompress((data) => { + if (exceeded) return; + total += data.length; + if (total > maxPlainBytes) { + exceeded = true; + chunks.length = 0; + return; + } + chunks.push(data); + }); + if (frameBytes.length === 0) { + stream.push(new Uint8Array(0), true); + } + for (let off = 0; off < frameBytes.length && !exceeded; off += INPUT_SLICE_BYTES) { + const end = Math.min(frameBytes.length, off + INPUT_SLICE_BYTES); + stream.push(frameBytes.subarray(off, end), end === frameBytes.length); + } + if (exceeded) { + throw new ExpansionLimitError(maxPlainBytes, total); + } + const out = new Uint8Array(total); + let pos = 0; + for (const chunk of chunks) { + out.set(chunk, pos); + pos += chunk.length; + } + return out; } // src/index.js @@ -749,6 +842,13 @@ var BundleFlight = class { } async rehydrate(job) { const { drive_file_id, offset, frame_length, sha256, bundle_id } = job; + const expectedSize = typeof job.size === "string" && job.size.trim() !== "" ? Number(job.size) : job.size; + if (!Number.isSafeInteger(expectedSize) || expectedSize < 0) { + throw new HttpError( + 502, + "manifest entry has no usable expected size \u2014 refusing unbounded decompression" + ); + } const token = await this.accessToken(); const range = `bytes=${offset}-${offset + frame_length - 1}`; const resp = await fetch(`${DRIVE_FILES_URL}/${drive_file_id}?alt=media`, { @@ -771,8 +871,14 @@ var BundleFlight = class { } let plain; try { - plain = decompressFrame(frame); - } catch { + plain = decompressFrame(frame, expectedSize); + } catch (err2) { + if (err2 instanceof ExpansionLimitError) { + throw new HttpError( + 502, + `zstd frame expands past the expected ${expectedSize} bytes \u2014 refusing to return unverified bytes` + ); + } throw new HttpError(502, "zstd frame decompression failed"); } const digest = await sha256Hex(plain); diff --git a/pkgs/cold-store-reaper/worker/package.json b/pkgs/cold-store-reaper/worker/package.json index 1e32a38700..48adef4cc8 100644 --- a/pkgs/cold-store-reaper/worker/package.json +++ b/pkgs/cold-store-reaper/worker/package.json @@ -10,7 +10,7 @@ "private": true, "scripts": { "build": "esbuild src/index.js --bundle --format=esm --platform=neutral --target=es2022 --outfile=dist/worker.js", - "test": "node test/run-local-proof.mjs && node test/range-ignored.test.mjs" + "test": "node test/run-local-proof.mjs && node test/range-ignored.test.mjs && node test/bounded-decompress.test.mjs" }, "type": "module", "version": "1.0.0" diff --git a/pkgs/cold-store-reaper/worker/src/decoder.js b/pkgs/cold-store-reaper/worker/src/decoder.js index 4646f285c0..55f7bbfde4 100644 --- a/pkgs/cold-store-reaper/worker/src/decoder.js +++ b/pkgs/cold-store-reaper/worker/src/decoder.js @@ -1,13 +1,74 @@ -import { decompress } from "fzstd"; +import { Decompress } from "fzstd"; -// Decompress exactly one zstd frame. The reaper stores every object as its -// own self-contained zstd frame inside a bundle file, so a frame pulled out -// by byte range decompresses on its own — no bundle context needed. +// Decompress exactly one zstd frame, bounded by the expected plaintext +// size. The reaper stores every object as its own self-contained zstd +// frame inside a bundle file, so a frame pulled out by byte range +// decompresses on its own — no bundle context needed. +// +// The bound is the point (#6590): the unbounded decompress() this +// module used before allocates the whole expansion, so a small frame +// could expand past the Worker's memory limit and kill the isolate +// instead of producing the designed clean 502. Here the frame is fed +// to a streaming decompressor in slices and the output is counted as +// it is produced; the moment it exceeds maxPlainBytes the output is +// dropped and ExpansionLimitError is thrown, so peak memory tracks +// the expected size (plus one output block of slack), never the +// frame's declared or actual expansion. // // This module is the single decoder implementation for the whole package: // the Worker bundles it (esbuild -> dist/worker.js) and the local proof // test (test/run-local-proof.mjs) imports it directly, so the code that is // tested locally is byte-for-byte the code that ships. -export function decompressFrame(frameBytes) { - return decompress(frameBytes); + +export class ExpansionLimitError extends Error { + constructor(limit, produced) { + super( + `zstd frame expands past the expected size: limit ${limit} bytes, ` + + `already produced ${produced} bytes`, + ); + this.name = "ExpansionLimitError"; + this.limit = limit; + } +} + +const INPUT_SLICE_BYTES = 16 * 1024; + +export function decompressFrame(frameBytes, maxPlainBytes) { + if (!Number.isSafeInteger(maxPlainBytes) || maxPlainBytes < 0) { + throw new TypeError( + `decompressFrame requires a non-negative integer byte limit, got ${maxPlainBytes}`, + ); + } + const chunks = []; + let total = 0; + let exceeded = false; + const stream = new Decompress((data) => { + if (exceeded) return; // drop late output; the throw happens below + total += data.length; + if (total > maxPlainBytes) { + exceeded = true; + chunks.length = 0; + return; + } + chunks.push(data); + }); + if (frameBytes.length === 0) { + // Keep the old behaviour for an empty frame: fzstd rejects it as + // invalid data instead of our returning an empty plaintext. + stream.push(new Uint8Array(0), true); + } + for (let off = 0; off < frameBytes.length && !exceeded; off += INPUT_SLICE_BYTES) { + const end = Math.min(frameBytes.length, off + INPUT_SLICE_BYTES); + stream.push(frameBytes.subarray(off, end), end === frameBytes.length); + } + if (exceeded) { + throw new ExpansionLimitError(maxPlainBytes, total); + } + const out = new Uint8Array(total); + let pos = 0; + for (const chunk of chunks) { + out.set(chunk, pos); + pos += chunk.length; + } + return out; } diff --git a/pkgs/cold-store-reaper/worker/src/index.js b/pkgs/cold-store-reaper/worker/src/index.js index 00f0fe5b95..95fd995f0c 100644 --- a/pkgs/cold-store-reaper/worker/src/index.js +++ b/pkgs/cold-store-reaper/worker/src/index.js @@ -16,7 +16,7 @@ // Secrets (set by the operator, never committed): REHYDRATOR_API_KEY, // GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN. -import { decompressFrame } from "./decoder.js"; +import { decompressFrame, ExpansionLimitError } from "./decoder.js"; const TOKEN_URL = "https://oauth2.googleapis.com/token"; const DRIVE_FILES_URL = "https://www.googleapis.com/drive/v3/files"; @@ -167,6 +167,18 @@ export class BundleFlight { async rehydrate(job) { const { drive_file_id, offset, frame_length, sha256, bundle_id } = job; + // The manifest's expected plaintext size (selected as o.size by the + // entry point) bounds decompression (#6590). A job without a usable + // size fails closed here, before any fetch: falling back to an + // unbounded decompress is exactly the failure being fixed. + const expectedSize = + typeof job.size === "string" && job.size.trim() !== "" ? Number(job.size) : job.size; + if (!Number.isSafeInteger(expectedSize) || expectedSize < 0) { + throw new HttpError( + 502, + "manifest entry has no usable expected size — refusing unbounded decompression", + ); + } const token = await this.accessToken(); const range = `bytes=${offset}-${offset + frame_length - 1}`; const resp = await fetch(`${DRIVE_FILES_URL}/${drive_file_id}?alt=media`, { @@ -193,8 +205,15 @@ export class BundleFlight { } let plain; try { - plain = decompressFrame(frame); - } catch { + plain = decompressFrame(frame, expectedSize); + } catch (err) { + if (err instanceof ExpansionLimitError) { + throw new HttpError( + 502, + `zstd frame expands past the expected ${expectedSize} bytes — ` + + "refusing to return unverified bytes", + ); + } throw new HttpError(502, "zstd frame decompression failed"); } const digest = await sha256Hex(plain); diff --git a/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs new file mode 100644 index 0000000000..7f25027838 --- /dev/null +++ b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs @@ -0,0 +1,158 @@ +// Regression test for issue #6590: zstd decompression in the +// rehydration path is bounded by the manifest's expected plaintext +// size (the job's `size`, selected as o.size by the entry point). +// +// Before the fix, decompressFrame was a bare fzstd decompress(): a +// small frame expanded without limit before the sha256 check, so a +// corrupt or hostile bundle member could expand past the Worker's +// memory limit and kill the isolate instead of producing the +// designed clean 502. The job's size field was selected and posted +// to the Durable Object but never read. +// +// Run: node test/bounded-decompress.test.mjs (also wired into `npm test`) + +import { createHash } from "node:crypto"; +import { zstdCompressSync } from "node:zlib"; + +import { decompressFrame, ExpansionLimitError } from "../src/decoder.js"; +import { BundleFlight } from "../src/index.js"; + +let failures = 0; +function check(name, cond, detail = "") { + if (cond) { + console.log(`ok: ${name}`); + } else { + failures += 1; + console.error(`FAIL: ${name} ${detail}`); + } +} + +const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex"); + +// A high-expansion frame: 4 MiB of zeros compresses to a few KiB. +const bombPlain = new Uint8Array(4 * 1024 * 1024); +const bombFrame = new Uint8Array(zstdCompressSync(bombPlain)); +const bombSha = sha256(bombPlain); +check("bomb frame is small relative to its expansion", + bombFrame.length < bombPlain.length / 100, + `frame=${bombFrame.length} plain=${bombPlain.length}`); + +// --- decoder level ------------------------------------------------- + +{ + let err = null; + try { + decompressFrame(bombFrame, 1024 * 1024); + } catch (e) { + err = e; + } + check("decoder throws ExpansionLimitError past the expected size", + err instanceof ExpansionLimitError, `got ${err}`); +} + +{ + const plain = decompressFrame(bombFrame, bombPlain.length); + check("decoder serves a frame expanding to exactly the expected size", + plain.length === bombPlain.length && sha256(plain) === bombSha); +} + +{ + let err = null; + try { + decompressFrame(bombFrame, bombPlain.length - 1); + } catch (e) { + err = e; + } + check("decoder throws when the expansion is one byte over the expected size", + err instanceof ExpansionLimitError, `got ${err}`); +} + +{ + const small = new TextEncoder().encode("a short, legitimate object"); + const smallFrame = new Uint8Array(zstdCompressSync(small)); + const plain = decompressFrame(smallFrame, small.length); + check("decoder is unaffected for a short frame at its exact size", + Buffer.from(plain).equals(Buffer.from(small))); +} + +for (const badLimit of [undefined, -1, 1.5, "100", null]) { + let err = null; + try { + decompressFrame(bombFrame, badLimit); + } catch (e) { + err = e; + } + check(`decoder refuses an unusable byte limit (${String(badLimit)})`, + err instanceof TypeError, `got ${err}`); +} + +// --- rehydrate level (the range-ignored.test.mjs harness shape) --- + +function makeFlight(frame) { + const flight = new BundleFlight( + { storage: { async get() { return null; }, async put() {} } }, + { GOOGLE_CLIENT_ID: "id", GOOGLE_CLIENT_SECRET: "secret", GOOGLE_REFRESH_TOKEN: "rt" }, + ); + const realFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + if (String(url).startsWith("https://oauth2.googleapis.com/token")) { + return new Response(JSON.stringify({ access_token: "tok", expires_in: 3600 }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(frame, { status: 206 }); + }; + return { flight, restore: () => { globalThis.fetch = realFetch; } }; +} + +const bombJob = (overrides = {}) => ({ + drive_file_id: "file-1", + offset: 0, + frame_length: bombFrame.length, + sha256: bombSha, + bundle_id: "bundle-1", + size: bombPlain.length, + ...overrides, +}); + +async function expect502(name, job, messagePart) { + const { flight, restore } = makeFlight(bombFrame); + let err = null; + try { + await flight.rehydrate(job); + } catch (e) { + err = e; + } + restore(); + check(name, + err !== null && err.status === 502 && String(err.message).includes(messagePart), + `got ${err && `${err.status} ${err.message}`}`); +} + +// The sha would match and the frame is well-formed: only the bound +// can refuse this run, and it must do so with the 502 shape. +await expect502("rehydrate refuses a frame expanding past the job size with a 502", + bombJob({ size: 1024 * 1024 }), "expands past the expected"); + +// A job whose size never arrived (or is not numeric) fails closed +// instead of falling back to unbounded decompression. +await expect502("rehydrate fails closed when the job has no size", + bombJob({ size: undefined }), "no usable expected size"); +await expect502("rehydrate fails closed when the job size is not numeric", + bombJob({ size: "not-a-size" }), "no usable expected size"); + +// Control: exact expected size + matching sha is served as before. +{ + const { flight, restore } = makeFlight(bombFrame); + const result = await flight.rehydrate(bombJob()); + restore(); + check("rehydrate serves an exact-size frame whose sha256 matches", + result.bytes.length === bombPlain.length && result.sha256 === bombSha); +} + +if (failures > 0) { + console.error(`FAIL: ${failures} check(s) failed`); + process.exit(1); +} +console.log("PASS: bounded decompression (issue #6590)"); diff --git a/pkgs/cold-store-reaper/worker/test/range-ignored.test.mjs b/pkgs/cold-store-reaper/worker/test/range-ignored.test.mjs index 6709291ebd..d031606cfb 100644 --- a/pkgs/cold-store-reaper/worker/test/range-ignored.test.mjs +++ b/pkgs/cold-store-reaper/worker/test/range-ignored.test.mjs @@ -85,6 +85,7 @@ const job = (offset, shaOverride = sha) => ({ frame_length: frame.length, sha256: shaOverride, bundle_id: "bundle-1", + size: plaintext.length, }); // 1. Range ignored (200, large streaming bundle): correct plaintext, diff --git a/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs b/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs index 4ea2f02320..b985fc0131 100644 --- a/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs +++ b/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs @@ -65,7 +65,7 @@ const info = JSON.parse(out.trim().split("\n").pop()); const bundle = readFileSync(info.bundle_path); const frame = bundle.subarray(info.offset, info.offset + info.length); -const plain = Buffer.from(decompressFrame(new Uint8Array(frame))); +const plain = Buffer.from(decompressFrame(new Uint8Array(frame), sample.length)); const digest = createHash("sha256").update(plain).digest("hex"); if (digest !== info.hash) { From d0ec6a1e16e38d455b3297958c1b715de1e359cd Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:30:04 -0600 Subject: [PATCH 2/3] cold-store-reaper(worker): refuse oversized declared window/content size up front (Codex P1 x2 on PR #6726) Finding 1: fzstd Decompress allocates the frame header's declared window on the first push, before the output bound can fire -- a header could declare a 512 MiB window over a tiny payload. The decoder now parses the frame header (skippable frames included) and refuses up front when the declared content size exceeds the limit, or the declared window exceeds max(limit, 8 MiB) -- the allowance covers legitimate encoders (the reaper packer runs zstd -3, window <= 2 MiB). Unparseable headers fall through to the streaming decoder exactly as before. Finding 2: property coverage per the testing doctrine -- 92 generated cases (fixed-seed mulberry32; zero/random/periodic/text plaintexts, lengths 0..65536) with named oracles (round-trip: the plaintext itself; bound: a sub-length limit must throw ExpansionLimitError), plus hand-built raw-block frames pinning the window and declared-content-size refusals. dist/worker.js rebuilt. --- pkgs/cold-store-reaper/worker/dist/worker.js | 81 +++++++++- pkgs/cold-store-reaper/worker/src/decoder.js | 100 ++++++++++++- pkgs/cold-store-reaper/worker/src/index.js | 8 +- .../worker/test/bounded-decompress.test.mjs | 139 +++++++++++++++++- 4 files changed, 313 insertions(+), 15 deletions(-) diff --git a/pkgs/cold-store-reaper/worker/dist/worker.js b/pkgs/cold-store-reaper/worker/dist/worker.js index 48ad3ab675..249bb6bdcf 100644 --- a/pkgs/cold-store-reaper/worker/dist/worker.js +++ b/pkgs/cold-store-reaper/worker/dist/worker.js @@ -670,21 +670,93 @@ var Decompress = /* @__PURE__ */ (function() { // src/decoder.js var ExpansionLimitError = class extends Error { - constructor(limit, produced) { + constructor(limit, produced, message) { super( - `zstd frame expands past the expected size: limit ${limit} bytes, already produced ${produced} bytes` + message ?? `zstd frame expands past the expected size: limit ${limit} bytes, already produced ${produced} bytes \u2014 refusing to return unverified bytes` ); this.name = "ExpansionLimitError"; this.limit = limit; } }; var INPUT_SLICE_BYTES = 16 * 1024; +var MIN_WINDOW_ALLOWANCE_BYTES = 8 * 1024 * 1024; +var ZSTD_MAGIC = 4247762216; +var SKIPPABLE_MAGIC_MIN = 407710288; +var SKIPPABLE_MAGIC_MAX = 407710303; +function parseZstdFrameHeader(bytes) { + let off = 0; + for (; ; ) { + if (bytes.length - off < 5) return null; + const view2 = new DataView(bytes.buffer, bytes.byteOffset + off); + const magic = view2.getUint32(0, true); + if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) { + if (bytes.length - off < 8) return null; + off += 8 + view2.getUint32(4, true); + continue; + } + if (magic !== ZSTD_MAGIC) return null; + break; + } + const head = off + 4; + const descriptor = bytes[head]; + const fcsCode = descriptor >> 6; + const singleSegment = (descriptor & 32) !== 0; + const dictIdCode = descriptor & 3; + const dictIdBytes = [0, 1, 2, 4][dictIdCode]; + const fcsBytes = singleSegment ? [1, 2, 4, 8][fcsCode] : [0, 2, 4, 8][fcsCode]; + const headerLength = 1 + (singleSegment ? 0 : 1) + dictIdBytes + fcsBytes; + if (bytes.length - head < headerLength) return null; + const view = new DataView(bytes.buffer, bytes.byteOffset + head); + let pos = 1; + let windowSize; + if (singleSegment) { + windowSize = null; + } else { + const wd = view.getUint8(pos); + pos += 1; + const windowLog = 10 + (wd >> 3); + const windowBase = 2 ** windowLog; + windowSize = windowBase + windowBase / 8 * (wd & 7); + } + pos += dictIdBytes; + let contentSize = null; + if (fcsBytes > 0) { + if (fcsBytes === 8) { + const v = view.getBigUint64(pos, true); + contentSize = v > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(v); + } else { + let v = 0; + for (let i = fcsBytes - 1; i >= 0; i--) v = v * 256 + view.getUint8(pos + i); + contentSize = fcsBytes === 2 ? v + 256 : v; + } + } + if (singleSegment) windowSize = contentSize; + return { contentSize, windowSize }; +} function decompressFrame(frameBytes, maxPlainBytes) { if (!Number.isSafeInteger(maxPlainBytes) || maxPlainBytes < 0) { throw new TypeError( `decompressFrame requires a non-negative integer byte limit, got ${maxPlainBytes}` ); } + const header = parseZstdFrameHeader(frameBytes); + if (header !== null) { + if (header.contentSize !== null && header.contentSize > maxPlainBytes) { + throw new ExpansionLimitError( + maxPlainBytes, + header.contentSize, + `zstd frame declares a content size of ${header.contentSize} bytes, past the expected size (limit ${maxPlainBytes} bytes) \u2014 refusing to return unverified bytes` + ); + } + const windowCap = Math.max(maxPlainBytes, MIN_WINDOW_ALLOWANCE_BYTES); + if (header.windowSize !== null && header.windowSize > windowCap) { + throw new ExpansionLimitError( + maxPlainBytes, + header.windowSize, + `zstd frame declares a ${header.windowSize}-byte window, over the ${windowCap}-byte bound for an expected size of ${maxPlainBytes} bytes \u2014 refusing to return unverified bytes` + ); + } + } const chunks = []; let total = 0; let exceeded = false; @@ -874,10 +946,7 @@ var BundleFlight = class { plain = decompressFrame(frame, expectedSize); } catch (err2) { if (err2 instanceof ExpansionLimitError) { - throw new HttpError( - 502, - `zstd frame expands past the expected ${expectedSize} bytes \u2014 refusing to return unverified bytes` - ); + throw new HttpError(502, err2.message); } throw new HttpError(502, "zstd frame decompression failed"); } diff --git a/pkgs/cold-store-reaper/worker/src/decoder.js b/pkgs/cold-store-reaper/worker/src/decoder.js index 55f7bbfde4..55db58463e 100644 --- a/pkgs/cold-store-reaper/worker/src/decoder.js +++ b/pkgs/cold-store-reaper/worker/src/decoder.js @@ -15,16 +15,27 @@ import { Decompress } from "fzstd"; // the expected size (plus one output block of slack), never the // frame's declared or actual expansion. // +// The output bound alone is not enough: fzstd's Decompress allocates +// the frame header's declared window on the first push, before any +// output flows (Codex P1 on PR #6726), and a header can declare a +// huge window — or a huge content size — over a tiny payload. The +// header is therefore parsed and refused up front when its declared +// content size exceeds the limit, or when its window exceeds the +// larger of the limit and MIN_WINDOW_ALLOWANCE_BYTES (encoders +// legitimately use windows up to a few MiB even for small objects: +// the reaper's own packer runs zstd -3, whose window caps at 2 MiB). +// // This module is the single decoder implementation for the whole package: // the Worker bundles it (esbuild -> dist/worker.js) and the local proof // test (test/run-local-proof.mjs) imports it directly, so the code that is // tested locally is byte-for-byte the code that ships. export class ExpansionLimitError extends Error { - constructor(limit, produced) { + constructor(limit, produced, message) { super( - `zstd frame expands past the expected size: limit ${limit} bytes, ` + - `already produced ${produced} bytes`, + message ?? + `zstd frame expands past the expected size: limit ${limit} bytes, ` + + `already produced ${produced} bytes — refusing to return unverified bytes`, ); this.name = "ExpansionLimitError"; this.limit = limit; @@ -32,6 +43,69 @@ export class ExpansionLimitError extends Error { } const INPUT_SLICE_BYTES = 16 * 1024; +const MIN_WINDOW_ALLOWANCE_BYTES = 8 * 1024 * 1024; + +const ZSTD_MAGIC = 0xfd2fb528; +const SKIPPABLE_MAGIC_MIN = 0x184d2a50; +const SKIPPABLE_MAGIC_MAX = 0x184d2a5f; + +/** Parse the first real frame's header. Returns + * { contentSize: number | null, windowSize: number }, or null when + * the header cannot be positively parsed (too short, bad magic, + * truncated) — in which case the streaming decoder is left to + * succeed or fail exactly as it would without the pre-check. Only a + * positively parsed violation is refused up front. */ +function parseZstdFrameHeader(bytes) { + let off = 0; + for (;;) { + if (bytes.length - off < 5) return null; + const view = new DataView(bytes.buffer, bytes.byteOffset + off); + const magic = view.getUint32(0, true); + if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) { + if (bytes.length - off < 8) return null; + off += 8 + view.getUint32(4, true); + continue; + } + if (magic !== ZSTD_MAGIC) return null; + break; + } + const head = off + 4; + const descriptor = bytes[head]; + const fcsCode = descriptor >> 6; + const singleSegment = (descriptor & 0x20) !== 0; + const dictIdCode = descriptor & 0x03; + const dictIdBytes = [0, 1, 2, 4][dictIdCode]; + const fcsBytes = singleSegment ? [1, 2, 4, 8][fcsCode] : [0, 2, 4, 8][fcsCode]; + const headerLength = 1 + (singleSegment ? 0 : 1) + dictIdBytes + fcsBytes; + if (bytes.length - head < headerLength) return null; + + const view = new DataView(bytes.buffer, bytes.byteOffset + head); + let pos = 1; + let windowSize; + if (singleSegment) { + windowSize = null; // set from the content size below + } else { + const wd = view.getUint8(pos); + pos += 1; + const windowLog = 10 + (wd >> 3); + const windowBase = 2 ** windowLog; + windowSize = windowBase + (windowBase / 8) * (wd & 0x07); + } + pos += dictIdBytes; + let contentSize = null; + if (fcsBytes > 0) { + if (fcsBytes === 8) { + const v = view.getBigUint64(pos, true); + contentSize = v > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(v); + } else { + let v = 0; + for (let i = fcsBytes - 1; i >= 0; i--) v = v * 256 + view.getUint8(pos + i); + contentSize = fcsBytes === 2 ? v + 256 : v; + } + } + if (singleSegment) windowSize = contentSize; + return { contentSize, windowSize }; +} export function decompressFrame(frameBytes, maxPlainBytes) { if (!Number.isSafeInteger(maxPlainBytes) || maxPlainBytes < 0) { @@ -39,6 +113,26 @@ export function decompressFrame(frameBytes, maxPlainBytes) { `decompressFrame requires a non-negative integer byte limit, got ${maxPlainBytes}`, ); } + const header = parseZstdFrameHeader(frameBytes); + if (header !== null) { + if (header.contentSize !== null && header.contentSize > maxPlainBytes) { + throw new ExpansionLimitError( + maxPlainBytes, + header.contentSize, + `zstd frame declares a content size of ${header.contentSize} bytes, past the ` + + `expected size (limit ${maxPlainBytes} bytes) — refusing to return unverified bytes`, + ); + } + const windowCap = Math.max(maxPlainBytes, MIN_WINDOW_ALLOWANCE_BYTES); + if (header.windowSize !== null && header.windowSize > windowCap) { + throw new ExpansionLimitError( + maxPlainBytes, + header.windowSize, + `zstd frame declares a ${header.windowSize}-byte window, over the ${windowCap}-byte ` + + `bound for an expected size of ${maxPlainBytes} bytes — refusing to return unverified bytes`, + ); + } + } const chunks = []; let total = 0; let exceeded = false; diff --git a/pkgs/cold-store-reaper/worker/src/index.js b/pkgs/cold-store-reaper/worker/src/index.js index 95fd995f0c..39194028c5 100644 --- a/pkgs/cold-store-reaper/worker/src/index.js +++ b/pkgs/cold-store-reaper/worker/src/index.js @@ -208,11 +208,9 @@ export class BundleFlight { plain = decompressFrame(frame, expectedSize); } catch (err) { if (err instanceof ExpansionLimitError) { - throw new HttpError( - 502, - `zstd frame expands past the expected ${expectedSize} bytes — ` + - "refusing to return unverified bytes", - ); + // The decoder's message names the exact bound that fired + // (declared content size, declared window, produced output). + throw new HttpError(502, err.message); } throw new HttpError(502, "zstd frame decompression failed"); } diff --git a/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs index 7f25027838..0f3300fcd6 100644 --- a/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs +++ b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs @@ -133,7 +133,7 @@ async function expect502(name, job, messagePart) { // The sha would match and the frame is well-formed: only the bound // can refuse this run, and it must do so with the 502 shape. await expect502("rehydrate refuses a frame expanding past the job size with a 502", - bombJob({ size: 1024 * 1024 }), "expands past the expected"); + bombJob({ size: 1024 * 1024 }), "past the expected size"); // A job whose size never arrived (or is not numeric) fails closed // instead of falling back to unbounded decompression. @@ -151,6 +151,143 @@ await expect502("rehydrate fails closed when the job size is not numeric", result.bytes.length === bombPlain.length && result.sha256 === bombSha); } +// --- frame-header pre-check (Codex P1 on PR #6726) ----------------- +// +// fzstd's Decompress allocates the header's declared window on the +// first push, before any output flows, so the output bound alone +// cannot stop a header-driven allocation. These hand-built frames +// carry a small raw-block payload under an inflated header; the +// pre-check must refuse them before the streaming decoder runs. + +function rawBlockFrame(content, windowLog) { + // Non-single-segment frame, no FCS, no checksum, no dictID, one + // raw (stored) block: the payload needs no compression machinery, + // so the header bytes are exactly what this test says they are. + const wd = (windowLog - 10) << 3; // mantissa 0 -> window = 2**windowLog + const blockHeader = (content.length << 3) | 1; // last block, raw type + return new Uint8Array([ + 0x28, 0xb5, 0x2f, 0xfd, // zstd magic, little-endian + 0x00, // frame header descriptor + wd, + blockHeader & 0xff, (blockHeader >> 8) & 0xff, (blockHeader >> 16) & 0xff, + ...content, + ]); +} + +const smallContent = new TextEncoder().encode("w".repeat(256)); + +{ + // A 512 MiB declared window over a 256-byte payload: refused even + // though the payload would fit the limit exactly. + let err = null; + try { + decompressFrame(rawBlockFrame(smallContent, 29), smallContent.length); + } catch (e) { + err = e; + } + check("decoder refuses a 512 MiB declared window over a small payload up front", + err instanceof ExpansionLimitError && String(err.message).includes("window"), + `got ${err}`); +} + +{ + // An 8 MiB declared window is within the allowance (encoders use + // windows of a few MiB for small objects): the frame decodes. + const plain = decompressFrame(rawBlockFrame(smallContent, 23), smallContent.length); + check("decoder accepts a declared window within the allowance and decodes the payload", + Buffer.from(plain).equals(Buffer.from(smallContent))); +} + +{ + // A 16 MiB window is over the allowance for a small object but + // under a 32 MiB expected size: the cap scales with the limit. + const plain = decompressFrame(rawBlockFrame(smallContent, 24), 32 * 1024 * 1024); + check("decoder accepts a declared window under a larger expected-size cap", + Buffer.from(plain).equals(Buffer.from(smallContent))); +} + +{ + // Declared content size (4-byte FCS) of 1,000,000 over a 10-byte + // raw payload, limit 100: refused on the header, before decoding. + const blockHeader = (10 << 3) | 1; + const frame = new Uint8Array([ + 0x28, 0xb5, 0x2f, 0xfd, + 0x80, // FCS field size code 2 -> 4-byte frame content size + 0x00, // window descriptor: 1 KiB window + 0x40, 0x42, 0x0f, 0x00, // FCS = 1,000,000 little-endian + blockHeader & 0xff, (blockHeader >> 8) & 0xff, (blockHeader >> 16) & 0xff, + ...new TextEncoder().encode("0123456789"), + ]); + let err = null; + try { + decompressFrame(frame, 100); + } catch (e) { + err = e; + } + check("decoder refuses a declared content size past the expected size up front", + err instanceof ExpansionLimitError && String(err.message).includes("content size"), + `got ${err}`); +} + +// --- property coverage (Codex P1 on PR #6726; testing doctrine) ---- +// +// ORACLES (named): (1) round-trip -- the generated plaintext itself: +// a limit at or above its length must reproduce it byte-for-byte; +// (2) bound -- a limit below its length must throw +// ExpansionLimitError, never return truncated or over-limit bytes. +// The generator is a fixed-seed mulberry32, so the cases are a +// deterministic regression pin, not a fuzz run. + +function mulberry32(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +{ + const rnd = mulberry32(0x6590); + const shapes = [ + (n) => new Uint8Array(n), // zeros: maximum expansion ratio + (n) => Uint8Array.from({ length: n }, () => Math.floor(rnd() * 256)), // incompressible + (n) => Uint8Array.from({ length: n }, (_, i) => (i * 7 + 3) % 251), // periodic + (n) => new TextEncoder().encode(("cold store property line\n").repeat(Math.ceil(n / 25)).slice(0, n)), + ]; + let cases = 0; + let propFailures = 0; + for (const shape of shapes) { + for (const n of [0, 1, 2, 17, 100, 1000, 4097, 65536]) { + const plain = shape(n); + const frame = new Uint8Array(zstdCompressSync(plain)); + for (const limit of [plain.length, plain.length + 1000]) { + cases += 1; + try { + const out = decompressFrame(frame, limit); + if (!Buffer.from(out).equals(Buffer.from(plain))) propFailures += 1; + } catch { + propFailures += 1; + } + } + if (plain.length > 0) { + cases += 1; + let err = null; + try { + decompressFrame(frame, plain.length - 1); + } catch (e) { + err = e; + } + if (!(err instanceof ExpansionLimitError)) propFailures += 1; + } + } + } + check(`property: round-trip and bound hold across ${cases} generated cases`, + propFailures === 0, `${propFailures} violated cases`); +} + if (failures > 0) { console.error(`FAIL: ${failures} check(s) failed`); process.exit(1); From e8a41d265d14d964a32a7af0a34c66e27df9b53f Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:35:46 -0600 Subject: [PATCH 3/3] cold-store-reaper(worker): reject concatenated frames up front (Codex P1, round 2, PR #6726) The header pre-check covered only the first frame, but fzstd's streaming decoder walks concatenated frames on its own, allocating each later frame's declared window unchecked. The decoder's contract is exactly one frame per object (the reaper stores one self-contained frame per object), so the first frame's block chain is now walked to its exact end (raw/compressed blocks by size, RLE by one byte, plus the optional content checksum) and any trailing bytes are rejected before fzstd runs. Leading skippable frames still decode, since the header parser already skipped them. Tests pin the reported bypass shape (small frame + 512 MiB-window frame), two well-formed frames, and the skippable-prefix control. dist/worker.js rebuilt. --- pkgs/cold-store-reaper/worker/dist/worker.js | 26 ++++++++- pkgs/cold-store-reaper/worker/src/decoder.js | 54 ++++++++++++++++--- .../worker/test/bounded-decompress.test.mjs | 51 ++++++++++++++++++ 3 files changed, 124 insertions(+), 7 deletions(-) diff --git a/pkgs/cold-store-reaper/worker/dist/worker.js b/pkgs/cold-store-reaper/worker/dist/worker.js index 249bb6bdcf..7ffbcb34ff 100644 --- a/pkgs/cold-store-reaper/worker/dist/worker.js +++ b/pkgs/cold-store-reaper/worker/dist/worker.js @@ -701,6 +701,7 @@ function parseZstdFrameHeader(bytes) { const descriptor = bytes[head]; const fcsCode = descriptor >> 6; const singleSegment = (descriptor & 32) !== 0; + const checksum = (descriptor & 4) !== 0; const dictIdCode = descriptor & 3; const dictIdBytes = [0, 1, 2, 4][dictIdCode]; const fcsBytes = singleSegment ? [1, 2, 4, 8][fcsCode] : [0, 2, 4, 8][fcsCode]; @@ -731,7 +732,24 @@ function parseZstdFrameHeader(bytes) { } } if (singleSegment) windowSize = contentSize; - return { contentSize, windowSize }; + return { contentSize, windowSize, frameStart: off, headerLength, checksum }; +} +function zstdFrameEnd(bytes, info) { + let pos = info.frameStart + 4 + info.headerLength; + for (; ; ) { + if (pos + 3 > bytes.length) return null; + const bh = bytes[pos] | bytes[pos + 1] << 8 | bytes[pos + 2] << 16; + pos += 3; + const last = (bh & 1) !== 0; + const type = bh >> 1 & 3; + const size = bh >> 3; + if (type === 3) return null; + pos += type === 1 ? 1 : size; + if (pos > bytes.length) return null; + if (last) break; + } + if (info.checksum) pos += 4; + return pos <= bytes.length ? pos : null; } function decompressFrame(frameBytes, maxPlainBytes) { if (!Number.isSafeInteger(maxPlainBytes) || maxPlainBytes < 0) { @@ -756,6 +774,12 @@ function decompressFrame(frameBytes, maxPlainBytes) { `zstd frame declares a ${header.windowSize}-byte window, over the ${windowCap}-byte bound for an expected size of ${maxPlainBytes} bytes \u2014 refusing to return unverified bytes` ); } + const end = zstdFrameEnd(frameBytes, header); + if (end !== null && end < frameBytes.length) { + throw new Error( + `expected exactly one zstd frame, but ${frameBytes.length - end} trailing byte(s) follow it \u2014 refusing to decode concatenated frames` + ); + } } const chunks = []; let total = 0; diff --git a/pkgs/cold-store-reaper/worker/src/decoder.js b/pkgs/cold-store-reaper/worker/src/decoder.js index 55db58463e..4f13fe4000 100644 --- a/pkgs/cold-store-reaper/worker/src/decoder.js +++ b/pkgs/cold-store-reaper/worker/src/decoder.js @@ -24,6 +24,13 @@ import { Decompress } from "fzstd"; // larger of the limit and MIN_WINDOW_ALLOWANCE_BYTES (encoders // legitimately use windows up to a few MiB even for small objects: // the reaper's own packer runs zstd -3, whose window caps at 2 MiB). +// The same bypass would otherwise reopen through a SECOND frame: +// fzstd's streaming decoder walks concatenated frames on its own, +// allocating each frame's declared window as it reaches it (Codex +// P1, second round). This decoder's contract has always been +// exactly one frame — the reaper stores one frame per object — so +// the first frame's block chain is walked to its exact end and any +// trailing bytes are rejected before fzstd runs at all. // // This module is the single decoder implementation for the whole package: // the Worker bundles it (esbuild -> dist/worker.js) and the local proof @@ -50,11 +57,11 @@ const SKIPPABLE_MAGIC_MIN = 0x184d2a50; const SKIPPABLE_MAGIC_MAX = 0x184d2a5f; /** Parse the first real frame's header. Returns - * { contentSize: number | null, windowSize: number }, or null when - * the header cannot be positively parsed (too short, bad magic, - * truncated) — in which case the streaming decoder is left to - * succeed or fail exactly as it would without the pre-check. Only a - * positively parsed violation is refused up front. */ + * { contentSize, windowSize, frameStart, headerLength, checksum }, + * or null when the header cannot be positively parsed (too short, + * bad magic, truncated) — in which case the streaming decoder is + * left to succeed or fail exactly as it would without the + * pre-check. Only a positively parsed violation is refused. */ function parseZstdFrameHeader(bytes) { let off = 0; for (;;) { @@ -73,6 +80,7 @@ function parseZstdFrameHeader(bytes) { const descriptor = bytes[head]; const fcsCode = descriptor >> 6; const singleSegment = (descriptor & 0x20) !== 0; + const checksum = (descriptor & 0x04) !== 0; const dictIdCode = descriptor & 0x03; const dictIdBytes = [0, 1, 2, 4][dictIdCode]; const fcsBytes = singleSegment ? [1, 2, 4, 8][fcsCode] : [0, 2, 4, 8][fcsCode]; @@ -104,7 +112,31 @@ function parseZstdFrameHeader(bytes) { } } if (singleSegment) windowSize = contentSize; - return { contentSize, windowSize }; + return { contentSize, windowSize, frameStart: off, headerLength, checksum }; +} + +/** The exact end offset of the frame whose header `info` describes, + * found by walking its block chain (raw and compressed blocks carry + * their size; an RLE block carries one byte), plus the optional + * content checksum. Returns null when the chain cannot be walked + * positively (truncated, reserved block type, overrun) — the + * streaming decoder is then left to fail as it would anyway. */ +function zstdFrameEnd(bytes, info) { + let pos = info.frameStart + 4 + info.headerLength; + for (;;) { + if (pos + 3 > bytes.length) return null; + const bh = bytes[pos] | (bytes[pos + 1] << 8) | (bytes[pos + 2] << 16); + pos += 3; + const last = (bh & 1) !== 0; + const type = (bh >> 1) & 3; + const size = bh >> 3; + if (type === 3) return null; + pos += type === 1 ? 1 : size; + if (pos > bytes.length) return null; + if (last) break; + } + if (info.checksum) pos += 4; + return pos <= bytes.length ? pos : null; } export function decompressFrame(frameBytes, maxPlainBytes) { @@ -132,6 +164,16 @@ export function decompressFrame(frameBytes, maxPlainBytes) { `bound for an expected size of ${maxPlainBytes} bytes — refusing to return unverified bytes`, ); } + const end = zstdFrameEnd(frameBytes, header); + if (end !== null && end < frameBytes.length) { + // Exactly one frame per object is the storage contract; a + // second frame would be decoded by the streaming decoder on + // its own, allocating its declared window unchecked. + throw new Error( + `expected exactly one zstd frame, but ${frameBytes.length - end} trailing ` + + "byte(s) follow it — refusing to decode concatenated frames", + ); + } } const chunks = []; let total = 0; diff --git a/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs index 0f3300fcd6..59626bc406 100644 --- a/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs +++ b/pkgs/cold-store-reaper/worker/test/bounded-decompress.test.mjs @@ -288,6 +288,57 @@ function mulberry32(seed) { propFailures === 0, `${propFailures} violated cases`); } +// --- exactly one frame (Codex P1, second round, PR #6726) ---------- +// +// The streaming decoder walks concatenated frames on its own and +// would allocate a second frame's declared window unchecked, so +// trailing data after the first frame is rejected up front. + +{ + // The reported bypass shape: a small valid frame, then a frame + // declaring a 512 MiB window over a 256-byte payload, limit 256. + const first = new Uint8Array(zstdCompressSync(smallContent)); + const concat = new Uint8Array([...first, ...rawBlockFrame(smallContent, 29)]); + let err = null; + try { + decompressFrame(concat, smallContent.length); + } catch (e) { + err = e; + } + check("decoder rejects a concatenated second frame before decoding it", + err !== null && String(err.message).includes("exactly one zstd frame"), + `got ${err}`); +} + +{ + // Even two well-formed frames are refused: one object is one frame. + const one = new Uint8Array(zstdCompressSync(smallContent)); + const concat = new Uint8Array([...one, ...one]); + let err = null; + try { + decompressFrame(concat, smallContent.length * 2); + } catch (e) { + err = e; + } + check("decoder rejects two concatenated well-formed frames", + err !== null && String(err.message).includes("exactly one zstd frame"), + `got ${err}`); +} + +{ + // A leading skippable frame before the one real frame is fine: + // skippable frames carry no payload and allocate no window. + const skippable = new Uint8Array([ + 0x50, 0x2a, 0x4d, 0x18, // skippable magic 0x184d2a50, little-endian + 0x03, 0x00, 0x00, 0x00, // payload size 3 + 0xaa, 0xbb, 0xcc, + ]); + const real = new Uint8Array(zstdCompressSync(smallContent)); + const plain = decompressFrame(new Uint8Array([...skippable, ...real]), smallContent.length); + check("decoder still decodes a single frame preceded by a skippable frame", + Buffer.from(plain).equals(Buffer.from(smallContent))); +} + if (failures > 0) { console.error(`FAIL: ${failures} check(s) failed`); process.exit(1);