From 4ad73a17acfa20d4df36b98d2018043253650e15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Wed, 25 Nov 2026 15:04:33 +0000 Subject: [PATCH 1/4] Reject trailing input across zlib codecs [skip ci] --- README.md | 2 + .../skeleton/src/builtin/zlib.js | 67 ++++-- .../skeleton/src/builtin/zlib.rs | 218 +++++++++++++++--- examples/runtime/zlib/src/zlib.js | 79 +++++++ examples/runtime/zlib/wit/zlib.wit | 1 + tests/node_compat/config.jsonc | 2 - tests/node_compat/report.md | 15 +- tests/runtime/zlib.rs | 9 + 8 files changed, 327 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index c9782d81..df1aa7a7 100644 --- a/README.md +++ b/README.md @@ -1264,6 +1264,8 @@ throws immediately. Environment-data APIs are unavailable. - `crc32`, `constants`, `codes` - Zstandard requires the optional `zstd` feature (included in the full tiers). It uses the reference zstd codec with worker threads disabled for WASI; `normal-p3` does not include that codec. +- Decompression supports the boolean `rejectGarbageAfterEnd` option. Strict gzip/unzip rejects + input after the first member; strict zstd still accepts valid concatenated frames. diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index 44518b2c..a14fdb12 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -9,13 +9,13 @@ import { brotli_decompress_sync as _brotli_decompress_sync, crc32_compute, zlib_stream_new, - zlib_stream_push, + zlib_stream_push as _zlib_stream_push, zlib_stream_params, zlib_stream_reset, zlib_stream_close, brotli_stream_new, - brotli_stream_push, - brotli_stream_pull, + brotli_stream_push as _brotli_stream_push, + brotli_stream_pull as _brotli_stream_pull, brotli_stream_close, zstd_stream_new, zstd_stream_push, @@ -56,6 +56,19 @@ function bufferFromNativeBytes(bytes) { return bytes; } +function trailingJunkError() { + return makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', 'Trailing junk found after the end of the compressed stream'); +} + +function streamResult([bytes, trailing]) { + if (trailing) throw trailingJunkError(); + return bytes; +} + +function zlib_stream_push(...args) { return streamResult(_zlib_stream_push(...args)); } +function brotli_stream_push(...args) { return streamResult(_brotli_stream_push(...args)); } +function brotli_stream_pull(...args) { return streamResult(_brotli_stream_pull(...args)); } + function isDetachedArrayBuffer(buffer) { try { return getArrayBufferDetached(buffer); @@ -488,6 +501,15 @@ function toUint8Array(buf) { // ===== Validation for zlib options ===== +function validateRejectGarbage(opts) { + const value = opts.rejectGarbageAfterEnd; + if (value !== undefined && typeof value !== 'boolean') { + throw makeTypeError('ERR_INVALID_ARG_TYPE', + 'The "options.rejectGarbageAfterEnd" property must be of type boolean.' + invalidArgTypeHelper(value)); + } + return value === true; +} + function validateZlibOptions(opts, mode) { opts = opts || {}; const level = (opts.level !== undefined && !Number.isNaN(opts.level)) ? opts.level : Z_DEFAULT_COMPRESSION; @@ -552,7 +574,8 @@ function validateZlibOptions(opts, mode) { } } - return { level, windowBits, memLevel, strategy, chunkSize, flush, finishFlush, dictionary, info, maxOutputLength }; + const rejectGarbage = validateRejectGarbage(opts); + return { level, windowBits, memLevel, strategy, chunkSize, flush, finishFlush, dictionary, info, maxOutputLength, rejectGarbage }; } function validateBrotliOptions(opts) { @@ -586,7 +609,8 @@ function validateBrotliOptions(opts) { } } - return { flush, finishFlush, chunkSize, params, info, maxOutputLength }; + const rejectGarbage = validateRejectGarbage(opts); + return { flush, finishFlush, chunkSize, params, info, maxOutputLength, rejectGarbage }; } function validateBrotliParams(params) { @@ -900,7 +924,7 @@ class _Deflate extends ZlibBase { this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(0, this._level, this._windowBits, this._memLevel, this._strategy)); + this._setNativeHandle(zlib_stream_new(0, this._level, this._windowBits, this._memLevel, this._strategy, false)); } } @@ -912,10 +936,11 @@ class _Inflate extends ZlibBase { this._finishFlush = validated.finishFlush !== undefined ? validated.finishFlush : Z_FINISH; this._flushFlag = validated.flush !== undefined ? validated.flush : Z_NO_FLUSH; this._dictionary = validated.dictionary; + this._rejectGarbage = validated.rejectGarbage; this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(1, 0, this._windowBits, 0, 0)); + this._setNativeHandle(zlib_stream_new(1, 0, this._windowBits, 0, 0, this._rejectGarbage)); } } @@ -932,7 +957,7 @@ class _Gzip extends ZlibBase { this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(2, this._level, this._windowBits, this._memLevel, this._strategy)); + this._setNativeHandle(zlib_stream_new(2, this._level, this._windowBits, this._memLevel, this._strategy, false)); } } @@ -942,10 +967,11 @@ class _Gunzip extends ZlibBase { super(opts, GUNZIP); this._finishFlush = validated.finishFlush !== undefined ? validated.finishFlush : Z_FINISH; this._flushFlag = validated.flush !== undefined ? validated.flush : Z_NO_FLUSH; + this._rejectGarbage = validated.rejectGarbage; this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(3, 0, 15, 0, 0)); + this._setNativeHandle(zlib_stream_new(3, 0, 15, 0, 0, this._rejectGarbage)); } } @@ -963,7 +989,7 @@ class _DeflateRaw extends ZlibBase { this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(4, this._level, this._windowBits, this._memLevel, this._strategy)); + this._setNativeHandle(zlib_stream_new(4, this._level, this._windowBits, this._memLevel, this._strategy, false)); } } @@ -974,10 +1000,11 @@ class _InflateRaw extends ZlibBase { this._finishFlush = validated.finishFlush !== undefined ? validated.finishFlush : Z_FINISH; this._flushFlag = validated.flush !== undefined ? validated.flush : Z_NO_FLUSH; this._dictionary = validated.dictionary; + this._rejectGarbage = validated.rejectGarbage; this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(5, 0, 15, 0, 0)); + this._setNativeHandle(zlib_stream_new(5, 0, 15, 0, 0, this._rejectGarbage)); } } @@ -987,10 +1014,11 @@ class _Unzip extends ZlibBase { super(opts, UNZIP); this._finishFlush = validated.finishFlush !== undefined ? validated.finishFlush : Z_FINISH; this._flushFlag = validated.flush !== undefined ? validated.flush : Z_NO_FLUSH; + this._rejectGarbage = validated.rejectGarbage; this._initHandle(); } _initHandle() { - this._setNativeHandle(zlib_stream_new(6, 0, 15, 0, 0)); + this._setNativeHandle(zlib_stream_new(6, 0, 15, 0, 0, this._rejectGarbage)); } } @@ -1011,7 +1039,7 @@ class _BrotliCompress extends ZlibBase { _initHandle() { if (this._nativeHandle !== null) return; const paramsJson = brotliParamsToJson(this._brotliParams); - this._setNativeHandle(brotli_stream_new(0, paramsJson)); + this._setNativeHandle(brotli_stream_new(0, paramsJson, false)); } } @@ -1023,10 +1051,11 @@ class _BrotliDecompress extends ZlibBase { this._finishFlush = validated.finishFlush !== undefined ? validated.finishFlush : BROTLI_OPERATION_FINISH; this._flushFlag = validated.flush !== undefined ? validated.flush : BROTLI_OPERATION_PROCESS; this._brotliFlushCb = null; + this._rejectGarbage = validated.rejectGarbage; this._initHandle(); } _initHandle() { - this._setNativeHandle(brotli_stream_new(1, '{}')); + this._setNativeHandle(brotli_stream_new(1, '{}', this._rejectGarbage)); } _flush(callback) { if (this._nativeHandle === null) { @@ -1167,11 +1196,7 @@ class Zstd extends ZlibBase { throw makeTypeError('ERR_INVALID_ARG_TYPE', 'The "options.dictionary" argument must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer.' + invalidArgTypeHelper(dictionary)); } - const rejectGarbage = opts.rejectGarbageAfterEnd; - if (rejectGarbage !== undefined && typeof rejectGarbage !== 'boolean') { - throw makeTypeError('ERR_INVALID_ARG_TYPE', - 'The "options.rejectGarbageAfterEnd" property must be of type boolean.' + invalidArgTypeHelper(rejectGarbage)); - } + const rejectGarbage = validateRejectGarbage(opts); const handle = zstd_stream_new(decompress, JSON.stringify(params), toUint8Array(toBuffer(dictionary)), pledged, rejectGarbage === true); if (handle == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'Setting parameter failed'); @@ -1294,7 +1319,9 @@ function doSyncDecompress(data, opts, windowBitsOverride, mode) { uint8, wb, validated.finishFlush, + validated.rejectGarbage, ); + if (errno === -7) throw trailingJunkError(); if (errno !== 0) { throw makeZlibError(errorMessage, errno); } @@ -1368,7 +1395,9 @@ export function brotliDecompressSync(data, opts) { const [result, errorMessage, errno] = _brotli_decompress_sync( uint8, validated.finishFlush, + validated.rejectGarbage, ); + if (errno === -7) throw trailingJunkError(); if (errno !== 0) { throw typeof errorMessage === 'string' && stringStartsWith(errorMessage, 'ERR_') ? makeBrotliError(errorMessage, errno) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs index 69559e46..cae6acf7 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs @@ -57,6 +57,7 @@ fn zlib_compress_sync_impl(data: &[u8], level: i32, window_bits: i32) -> Option< enum SyncDecompressError { Buffer, + Trailing, #[cfg(feature = "brotli")] Brotli { code: String, @@ -72,6 +73,7 @@ fn gzip_decompress_multi_member( data: &[u8], finish_flush: i32, auto_detect: bool, + reject_garbage: bool, ) -> Result, SyncDecompressError> { let allow_partial = finish_flush != 4; let stop_at_block = finish_flush == 5; @@ -90,6 +92,10 @@ fn gzip_decompress_multi_member( let pos = cursor.position() as usize; let remaining = &data[pos..]; + if members_decoded > 0 && reject_garbage { + return Err(SyncDecompressError::Trailing); + } + // Node treats any suffix beginning with zero after a complete member as // gzip padding, including a zero followed by otherwise non-padding data. if members_decoded > 0 && remaining[0] == 0 { @@ -159,6 +165,7 @@ fn inflate_sync( data: &[u8], zlib_header: bool, finish_flush: i32, + reject_garbage: bool, ) -> Result, SyncDecompressError> { let allow_partial = finish_flush != 4; let flush = if allow_partial { @@ -174,6 +181,9 @@ fn inflate_sync( if !result.stream_end && !allow_partial { return Err(SyncDecompressError::Buffer); } + if result.stream_end && result.input_consumed < data.len() && reject_garbage { + return Err(SyncDecompressError::Trailing); + } output.truncate(result.output_len); Ok(output) } @@ -182,19 +192,20 @@ fn zlib_decompress_sync_impl( data: &[u8], window_bits: i32, finish_flush: i32, + reject_garbage: bool, ) -> Result, SyncDecompressError> { if window_bits >= 24 { - gzip_decompress_multi_member(data, finish_flush, false) + gzip_decompress_multi_member(data, finish_flush, false, reject_garbage) } else if window_bits == 0 { if data.len() < 2 || data.first() == Some(&0x1f) { - gzip_decompress_multi_member(data, finish_flush, true) + gzip_decompress_multi_member(data, finish_flush, true, reject_garbage) } else { - inflate_sync(data, true, finish_flush) + inflate_sync(data, true, finish_flush, reject_garbage) } } else if window_bits < 0 { - inflate_sync(data, false, finish_flush) + inflate_sync(data, false, finish_flush, reject_garbage) } else { - inflate_sync(data, true, finish_flush) + inflate_sync(data, true, finish_flush, reject_garbage) } } @@ -220,6 +231,7 @@ fn brotli_compress_sync_impl(data: &[u8], params_json: &str) -> Option> fn brotli_decompress_sync_impl( data: &[u8], finish_flush: u8, + reject_garbage: bool, ) -> Result, SyncDecompressError> { let mut state = brotli::BrotliState::new( brotli::HeapAlloc::::default(), @@ -248,7 +260,13 @@ fn brotli_decompress_sync_impl( output.extend_from_slice(&chunk[..output_offset]); match result { - brotli::BrotliResult::ResultSuccess => return Ok(output), + brotli::BrotliResult::ResultSuccess => { + return if available_in > 0 && reject_garbage { + Err(SyncDecompressError::Trailing) + } else { + Ok(output) + }; + } brotli::BrotliResult::ResultFailure => { let errno = state.error_code as i32; let decoder_error = format!("{:?}", state.error_code); @@ -309,6 +327,7 @@ fn brotli_compress_sync_impl(_data: &[u8], _params_json: &str) -> Option fn brotli_decompress_sync_impl( _data: &[u8], _finish_flush: u8, + _reject_garbage: bool, ) -> Result, SyncDecompressError> { Err(SyncDecompressError::Generic) } @@ -326,6 +345,8 @@ fn crc32_compute_impl(data: &[u8], initial: u32) -> u32 { struct ZlibStream { kind: ZlibStreamKind, bytes_written: u32, + reject_garbage: bool, + trailing: bool, } enum ZlibStreamKind { @@ -349,6 +370,7 @@ enum ZlibStreamKind { Decompress { inner: Decompress, zlib_header: bool, + finished: bool, }, GzipCompress { encoder: flate2::write::GzEncoder>, @@ -359,6 +381,7 @@ enum ZlibStreamKind { header_buf: Vec, header_parsed: bool, trailer_remaining: usize, + finished: bool, }, } @@ -470,6 +493,7 @@ fn zlib_stream_new_impl( _window_bits: i32, _mem_level: i32, _strategy: i32, + reject_garbage: bool, ) -> Option { let compression = map_compression_level(level); @@ -485,6 +509,7 @@ fn zlib_stream_new_impl( 1 => ZlibStreamKind::Decompress { inner: Decompress::new(true), zlib_header: true, + finished: false, }, // 2: gzip compress — streaming with flush support 2 => ZlibStreamKind::GzipCompress { @@ -497,6 +522,7 @@ fn zlib_stream_new_impl( header_buf: Vec::new(), header_parsed: false, trailer_remaining: 0, + finished: false, }, // 4: deflate raw compress 4 => ZlibStreamKind::RawCompress { @@ -506,6 +532,7 @@ fn zlib_stream_new_impl( 5 => ZlibStreamKind::Decompress { inner: Decompress::new(false), zlib_header: false, + finished: false, }, // 6: unzip (auto-detect gzip/zlib) — streaming decompression 6 => ZlibStreamKind::GzipDecompress { @@ -513,6 +540,7 @@ fn zlib_stream_new_impl( header_buf: Vec::new(), header_parsed: false, trailer_remaining: 0, + finished: false, }, _ => return None, }; @@ -523,6 +551,8 @@ fn zlib_stream_new_impl( ZlibStream { kind, bytes_written: 0, + reject_garbage, + trailing: false, }, ); Some(id) @@ -652,10 +682,19 @@ fn zlib_stream_push_impl(id: u32, data: &[u8], flush: i32) -> Option> { Some(Vec::new()) } } - ZlibStreamKind::Decompress { inner, .. } => { + ZlibStreamKind::Decompress { + inner, finished, .. + } => { + if *finished { + stream.trailing |= stream.reject_garbage && !data.is_empty(); + return Some(Vec::new()); + } let mut output = vec![0u8; data.len() + 1024]; let flush_mode = map_flush_decompress(flush); let result = decompress_loop(inner, data, &mut output, flush_mode)?; + *finished = result.stream_end; + stream.trailing |= + result.stream_end && result.input_consumed < data.len() && stream.reject_garbage; output.truncate(result.output_len); Some(output) } @@ -678,6 +717,7 @@ fn zlib_stream_push_impl(id: u32, data: &[u8], flush: i32) -> Option> { header_buf, header_parsed, trailer_remaining, + finished, } => { let mut all_output = Vec::new(); let mut remaining: Vec = data.to_vec(); @@ -686,6 +726,10 @@ fn zlib_stream_push_impl(id: u32, data: &[u8], flush: i32) -> Option> { if remaining.is_empty() { break; } + if *finished && stream.reject_garbage { + stream.trailing = true; + break; + } // Phase 1: Skip gzip trailer bytes (CRC32 + ISIZE = 8 bytes) if *trailer_remaining > 0 { @@ -699,6 +743,11 @@ fn zlib_stream_push_impl(id: u32, data: &[u8], flush: i32) -> Option> { // Trailer fully consumed, prepare for next member *inner = Decompress::new(false); *header_parsed = false; + *finished = true; + if stream.reject_garbage && !remaining.is_empty() { + stream.trailing = true; + break; + } if remaining.is_empty() { break; } @@ -836,9 +885,12 @@ fn zlib_stream_reset_impl(id: u32) -> bool { buffer.clear(); } ZlibStreamKind::Decompress { - inner, zlib_header, .. + inner, + zlib_header, + finished, } => { *inner = Decompress::new(*zlib_header); + *finished = false; } ZlibStreamKind::GzipCompress { encoder, level } => { *encoder = flate2::write::GzEncoder::new(Vec::new(), *level); @@ -848,14 +900,17 @@ fn zlib_stream_reset_impl(id: u32) -> bool { header_buf, header_parsed, trailer_remaining, + finished, } => { *inner = Decompress::new(false); header_buf.clear(); *header_parsed = false; *trailer_remaining = 0; + *finished = false; } } stream.bytes_written = 0; + stream.trailing = false; true } else { false @@ -945,8 +1000,17 @@ fn zlib_stream_bytes_written_impl(id: u32) -> u32 { struct BrotliStream { kind: BrotliStreamKind, bytes_written: u32, + reject_garbage: bool, + trailing: bool, } +#[cfg(feature = "brotli")] +type BrotliDecoder = brotli::BrotliState< + brotli::HeapAlloc, + brotli::HeapAlloc, + brotli::HeapAlloc, +>; + #[cfg(feature = "brotli")] enum BrotliStreamKind { Compress { @@ -957,7 +1021,10 @@ enum BrotliStreamKind { buffer: Vec, }, DecompressStreaming { - decompressor: Box>>>, + decoder: Box, + input: Vec, + offset: usize, + finished: bool, }, } @@ -966,7 +1033,7 @@ static BROTLI_STREAMS: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); #[cfg(feature = "brotli")] -fn brotli_stream_new_impl(mode: u8, params_json: &str) -> Option { +fn brotli_stream_new_impl(mode: u8, params_json: &str, reject_garbage: bool) -> Option { let kind = match mode { 0 => { let quality = parse_brotli_quality(params_json); @@ -991,6 +1058,8 @@ fn brotli_stream_new_impl(mode: u8, params_json: &str) -> Option { BrotliStream { kind, bytes_written: 0, + reject_garbage, + trailing: false, }, ); Some(id) @@ -1039,20 +1108,25 @@ fn brotli_stream_push_impl(id: u32, data: &[u8], flush: u8) -> Option> { // flush == 2 means finish (BROTLI_OPERATION_FINISH) if flush == 2 { let input = std::mem::take(buffer); - let mut decompressor = brotli::Decompressor::new(Cursor::new(input), 4096); - let chunk_size = 16 * 1024; - let mut chunk = vec![0u8; chunk_size]; - let n = decompressor.read(&mut chunk).ok()?; - chunk.truncate(n); stream.kind = BrotliStreamKind::DecompressStreaming { - decompressor: Box::new(decompressor), + decoder: Box::new(brotli::BrotliState::new( + brotli::HeapAlloc::default(), + brotli::HeapAlloc::default(), + brotli::HeapAlloc::default(), + )), + input, + offset: 0, + finished: false, }; - Some(chunk) + brotli_stream_read(stream, 16 * 1024) } else { Some(Vec::new()) } } - BrotliStreamKind::DecompressStreaming { .. } => Some(Vec::new()), + BrotliStreamKind::DecompressStreaming { .. } => { + stream.trailing |= stream.reject_garbage && !data.is_empty(); + Some(Vec::new()) + } } } @@ -1060,12 +1134,45 @@ fn brotli_stream_push_impl(id: u32, data: &[u8], flush: u8) -> Option> { fn brotli_stream_pull_impl(id: u32, max_bytes: u32) -> Option> { let mut streams = BROTLI_STREAMS.lock().unwrap(); let stream = streams.get_mut(&id)?; + brotli_stream_read(stream, max_bytes as usize) +} +#[cfg(feature = "brotli")] +fn brotli_stream_read(stream: &mut BrotliStream, max_bytes: usize) -> Option> { match &mut stream.kind { - BrotliStreamKind::DecompressStreaming { decompressor } => { - let mut chunk = vec![0u8; max_bytes as usize]; - let n = decompressor.read(&mut chunk).ok()?; - chunk.truncate(n); + BrotliStreamKind::DecompressStreaming { + decoder, + input, + offset, + finished, + } => { + if *finished { + return Some(Vec::new()); + } + let mut chunk = vec![0u8; max_bytes]; + let mut available_in = input.len() - *offset; + let mut available_out = chunk.len(); + let mut output_offset = 0; + let mut total_out = 0; + let result = brotli::BrotliDecompressStream( + &mut available_in, + offset, + input, + &mut available_out, + &mut output_offset, + &mut chunk, + &mut total_out, + decoder, + ); + match result { + brotli::BrotliResult::ResultSuccess => { + *finished = true; + stream.trailing |= stream.reject_garbage && available_in > 0; + } + brotli::BrotliResult::NeedsMoreOutput => {} + _ => return None, + } + chunk.truncate(output_offset); Some(chunk) } _ => Some(Vec::new()), @@ -1088,7 +1195,7 @@ fn brotli_stream_bytes_written_impl(id: u32) -> u32 { } #[cfg(not(feature = "brotli"))] -fn brotli_stream_new_impl(_mode: u8, _params_json: &str) -> Option { +fn brotli_stream_new_impl(_mode: u8, _params_json: &str, _reject_garbage: bool) -> Option { None } @@ -1120,6 +1227,7 @@ pub mod native_module { use rquickjs::{Ctx, TypedArray}; type DecompressOutcome<'js> = List<(Option>, Option, i32)>; + type StreamOutcome<'js> = List<(Option>, bool)>; // ===== One-shot functions ===== @@ -1143,11 +1251,13 @@ pub mod native_module { data: TypedArray<'js, u8>, window_bits: i32, finish_flush: i32, + reject_garbage: bool, ) -> rquickjs::Result> { // SAFETY: Compression consumes the rooted input synchronously without JS re-entry. let input = unsafe { data.as_bytes() }.unwrap_or_default(); - match super::zlib_decompress_sync_impl(input, window_bits, finish_flush) { + match super::zlib_decompress_sync_impl(input, window_bits, finish_flush, reject_garbage) { Ok(bytes) => Ok(List((Some(TypedArray::new(ctx, bytes)?), None, 0))), + Err(super::SyncDecompressError::Trailing) => Ok(List((None, None, -7))), Err(super::SyncDecompressError::Buffer) => { Ok(List((None, Some("unexpected end of file".to_string()), -5))) } @@ -1178,11 +1288,13 @@ pub mod native_module { ctx: Ctx<'js>, data: TypedArray<'js, u8>, finish_flush: u8, + reject_garbage: bool, ) -> rquickjs::Result> { // SAFETY: Compression consumes the rooted input synchronously without JS re-entry. let input = unsafe { data.as_bytes() }.unwrap_or_default(); - match super::brotli_decompress_sync_impl(input, finish_flush) { + match super::brotli_decompress_sync_impl(input, finish_flush, reject_garbage) { Ok(bytes) => Ok(List((Some(TypedArray::new(ctx, bytes)?), None, 0))), + Err(super::SyncDecompressError::Trailing) => Ok(List((None, None, -7))), Err(super::SyncDecompressError::Buffer) => { Ok(List((None, Some("unexpected end of file".to_string()), -5))) } @@ -1211,8 +1323,16 @@ pub mod native_module { window_bits: i32, mem_level: i32, strategy: i32, + reject_garbage: bool, ) -> Option { - super::zlib_stream_new_impl(mode, level, window_bits, mem_level, strategy) + super::zlib_stream_new_impl( + mode, + level, + window_bits, + mem_level, + strategy, + reject_garbage, + ) } #[rquickjs::function] @@ -1221,12 +1341,18 @@ pub mod native_module { id: u32, data: TypedArray<'js, u8>, flush: i32, - ) -> rquickjs::Result>> { + ) -> rquickjs::Result> { // SAFETY: Compression consumes the rooted input synchronously without JS re-entry. let input = unsafe { data.as_bytes() }.unwrap_or_default(); - super::zlib_stream_push_impl(id, input, flush) + let bytes = super::zlib_stream_push_impl(id, input, flush) .map(|bytes| TypedArray::new(ctx, bytes)) - .transpose() + .transpose()?; + let trailing = super::ZLIB_STREAMS + .lock() + .unwrap() + .get(&id) + .is_some_and(|stream| stream.trailing); + Ok(List((bytes, trailing))) } #[rquickjs::function] @@ -1252,8 +1378,8 @@ pub mod native_module { // ===== Brotli streaming functions ===== #[rquickjs::function] - pub fn brotli_stream_new(mode: u8, params_json: String) -> Option { - super::brotli_stream_new_impl(mode, ¶ms_json) + pub fn brotli_stream_new(mode: u8, params_json: String, reject_garbage: bool) -> Option { + super::brotli_stream_new_impl(mode, ¶ms_json, reject_garbage) } #[rquickjs::function] @@ -1262,12 +1388,21 @@ pub mod native_module { id: u32, data: TypedArray<'js, u8>, flush: u8, - ) -> rquickjs::Result>> { + ) -> rquickjs::Result> { // SAFETY: Compression consumes the rooted input synchronously without JS re-entry. let input = unsafe { data.as_bytes() }.unwrap_or_default(); - super::brotli_stream_push_impl(id, input, flush) + let bytes = super::brotli_stream_push_impl(id, input, flush) .map(|bytes| TypedArray::new(ctx, bytes)) - .transpose() + .transpose()?; + #[cfg(feature = "brotli")] + let trailing = super::BROTLI_STREAMS + .lock() + .unwrap() + .get(&id) + .is_some_and(|stream| stream.trailing); + #[cfg(not(feature = "brotli"))] + let trailing = false; + Ok(List((bytes, trailing))) } #[rquickjs::function] @@ -1275,10 +1410,19 @@ pub mod native_module { ctx: Ctx<'js>, id: u32, max_bytes: u32, - ) -> rquickjs::Result>> { - super::brotli_stream_pull_impl(id, max_bytes) + ) -> rquickjs::Result> { + let bytes = super::brotli_stream_pull_impl(id, max_bytes) .map(|bytes| TypedArray::new(ctx, bytes)) - .transpose() + .transpose()?; + #[cfg(feature = "brotli")] + let trailing = super::BROTLI_STREAMS + .lock() + .unwrap() + .get(&id) + .is_some_and(|stream| stream.trailing); + #[cfg(not(feature = "brotli"))] + let trailing = false; + Ok(List((bytes, trailing))) } #[rquickjs::function] diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index 714252b9..89fc8a88 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -1,6 +1,7 @@ import { Buffer } from 'node:buffer'; import assert from 'node:assert/strict'; import * as zlib from 'node:zlib'; +import { finished } from 'node:stream/promises'; import { brotliCompressSync, brotliDecompressSync, @@ -536,3 +537,81 @@ export function testZstdDisabled() { } return true; } + +export async function testTrailingInput() { + const firstText = 'first-17'; + const secondText = 'second-29'; + const trailingError = { code: 'ERR_TRAILING_JUNK_AFTER_STREAM_END', name: 'TypeError' }; + const codecs = [ + [zlib.deflateSync, zlib.inflateSync, zlib.createInflate, false], + [zlib.deflateRawSync, zlib.inflateRawSync, zlib.createInflateRaw, false], + [zlib.gzipSync, zlib.gunzipSync, zlib.createGunzip, true], + [zlib.gzipSync, zlib.unzipSync, zlib.createUnzip, true], + [zlib.brotliCompressSync, zlib.brotliDecompressSync, zlib.createBrotliDecompress, false], + [zlib.zstdCompressSync, zlib.zstdDecompressSync, zlib.createZstdDecompress, true], + ]; + async function collect(create, options, chunks) { + const stream = create(options); + const output = []; + stream.on('data', chunk => output.push(chunk)); + const done = finished(stream); + for (const chunk of chunks) stream.write(chunk); + stream.end(); + await done; + return Buffer.concat(output); + } + for (const [compress, decode, create, concatenated] of codecs) { + const first = compress(firstText); + const joined = Buffer.concat([first, compress(secondText)]); + for (const rejectGarbageAfterEnd of [false, true]) { + const options = { rejectGarbageAfterEnd }; + // Zstd accepts valid later frames even in strict mode, unlike gzip. + const rejects = rejectGarbageAfterEnd && decode !== zlib.zstdDecompressSync; + const expected = concatenated ? firstText + secondText : firstText; + if (rejects) assert.throws(() => decode(joined, options), trailingError); + else assert.equal(decode(joined, options).toString(), expected); + assert.equal(decode(first, options).toString(), firstText); + // Every boundary includes splits inside the gzip trailer and at stream end. + for (let split = 0; split <= joined.length; split++) { + const result = collect(create, options, [joined.subarray(0, split), joined.subarray(split)]); + if (rejects) await assert.rejects(result, trailingError); + else assert.equal((await result).toString(), expected); + } + const bytes = Array.from(first, byte => Buffer.from([byte])); + assert.equal((await collect(create, options, bytes)).toString(), firstText); + } + for (const value of [null, 1, 'true']) { + assert.throws(() => decode(first, { rejectGarbageAfterEnd: value }), { + code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', + }); + assert.throws(() => create({ rejectGarbageAfterEnd: value }), { + code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', + }); + } + if (decode !== zlib.brotliDecompressSync && decode !== zlib.zstdDecompressSync) { + const stream = create({ rejectGarbageAfterEnd: true }); + const output = []; + stream.on('data', chunk => output.push(chunk)); + const done = finished(stream); + await new Promise((resolve, reject) => { + stream.write(first, error => error ? reject(error) : resolve()); + }); + stream.reset(); + stream.end(compress(secondText)); + await done; + assert.equal(Buffer.concat(output).toString(), firstText + secondText); + } + } + // Brotli must retain its decoder and input offset across bounded output pulls. + const large = Buffer.alloc(100003); + for (let i = 0; i < large.length; i++) large[i] = (i * 13 + (i >>> 8)) & 255; + const compressed = zlib.brotliCompressSync(large); + for (const rejectGarbageAfterEnd of [false, true]) { + const options = { rejectGarbageAfterEnd, highWaterMark: 64 }; + assert.deepEqual(await collect(zlib.createBrotliDecompress, options, [compressed]), large); + const result = collect(zlib.createBrotliDecompress, options, [Buffer.concat([compressed, Buffer.from([42])])]); + if (rejectGarbageAfterEnd) await assert.rejects(result, trailingError); + else assert.deepEqual(await result, large); + } + return true; +} diff --git a/examples/runtime/zlib/wit/zlib.wit b/examples/runtime/zlib/wit/zlib.wit index 2e71bc86..3e27c98a 100644 --- a/examples/runtime/zlib/wit/zlib.wit +++ b/examples/runtime/zlib/wit/zlib.wit @@ -4,4 +4,5 @@ world zlib { export test-byte-transfer: func() -> bool; export test-zstd: func() -> bool; export test-zstd-disabled: func() -> bool; + export test-trailing-input: func() -> bool; } diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index 76ae3600..8c6b2697 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -16835,8 +16835,6 @@ "parallel/test-zlib-decode-strings.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, "parallel/test-zlib-negative-zero.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, "parallel/test-zlib-reject-garbage-after-end.js": { - "category": "known-gap", - "reason": "shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification", "split": true, "subtests": { "test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking": {}, diff --git a/tests/node_compat/report.md b/tests/node_compat/report.md index b3d18218..b2d9add7 100644 --- a/tests/node_compat/report.md +++ b/tests/node_compat/report.md @@ -8,21 +8,21 @@ This report is generated from `config.jsonc` and the pinned vendored Node.js sou Primary compatibility is measured over the public API surface we can provide: CI-enforced passing (`runnable`) plus `known-gap`. WASI-impossible tests, engine differences, unevaluated tests, and Node.js-internals tests are acknowledged separately and excluded from the primary percentage. -**Primary compatibility (CI-enforced):** 3190/4484 (71.1%) +**Primary compatibility (CI-enforced):** 3196/4484 (71.3%) When comparing revisions, read the runnable count and secondary full-public percentage alongside the primary percentage. Reclassifying a test into an excluded category can increase the primary percentage without increasing runnable coverage. | Classification | Count | Primary % | Public inventory % | All listed % | |----------------|-------|-----------|--------------------|--------------| -| ✅ passing (runnable) | 3190 | 71.1% | 33.2% | 29.6% | -| 🧩 known gap | 1294 | 28.9% | 13.5% | 12.0% | +| ✅ passing (runnable) | 3196 | 71.3% | 33.2% | 29.6% | +| 🧩 known gap | 1288 | 28.7% | 13.4% | 11.9% | | 🚫 WASI-impossible (excluded) | 1148 | — | 11.9% | 10.6% | | ⚙️ engine difference (excluded) | 167 | — | 1.7% | 1.5% | | ❔ unevaluated (excluded) | 3818 | — | 39.7% | 35.4% | | 🔒 Node.js internals (excluded) | 1177 | — | — | 10.9% | | **Total** | **10794** | | | **100.0%** | -Secondary full-public compatibility, including public tests that are currently excluded from primary: **3190/9617 (33.2%)**. +Secondary full-public compatibility, including public tests that are currently excluded from primary: **3196/9617 (33.2%)**. ## Inventory by Module @@ -88,7 +88,7 @@ Secondary full-public compatibility, including public tests that are currently e | webstreams | 89 | 66 | 1 | 0 | 0 | 21 | 1 | 98.5% | 75.0% | | whatwg | 319 | 43 | 32 | 0 | 0 | 56 | 188 | 57.3% | 32.8% | | worker_threads | 202 | 25 | 29 | 127 | 0 | 13 | 8 | 46.3% | 12.9% | -| zlib | 324 | 72 | 11 | 0 | 0 | 237 | 4 | 86.7% | 22.5% | +| zlib | 324 | 78 | 5 | 0 | 0 | 237 | 4 | 94.0% | 24.4% | ## Split Test Summary @@ -1040,7 +1040,7 @@ Secondary full-public compatibility, including public tests that are currently e | `test-zlib-dictionary-fail.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-failed-init.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-invalid-input.js` | 2 | 0 | 2 | 0 | 0 | 0 | 0 | -| `test-zlib-reject-garbage-after-end.js` | 6 | 0 | 6 | 0 | 0 | 0 | 0 | +| `test-zlib-reject-garbage-after-end.js` | 6 | 6 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-reset-incomplete-output.js` | 7 | 0 | 0 | 0 | 0 | 7 | 0 | | `test-zlib-truncated.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-type-error.js` | 4 | 0 | 0 | 0 | 0 | 4 | 0 | @@ -1090,7 +1090,7 @@ Secondary full-public compatibility, including public tests that are currently e ## Classified Non-Runnable Tests -### known gap (1294) +### known gap (1288) | Reason | Count | Example entries | |--------|-------|-----------------| @@ -1128,7 +1128,6 @@ Secondary full-public compatibility, including public tests that are currently e | inherited: common.canCreateSymLink shim always returns false, so symlink permission tests are skipped | 6 | `parallel/test-permission-fs-symlink-target-write.js#block_00_block_00`, `parallel/test-permission-fs-symlink-target-write.js#block_01_block_01`, `parallel/test-permission-fs-symlink.js#block_00_block_00`, ... (+3) | | inherited: perf_hooks createHistogram/monitorEventLoopDelay are not implemented | 6 | `parallel/test-perf-hooks-histogram.js#block_00_block_00`, `parallel/test-perf-hooks-histogram.js#block_01_block_01`, `parallel/test-perf-hooks-histogram.js#block_02_block_02`, ... (+3) | | same-process import.meta.resolve behavior is covered by runtime tests; remaining vendored failure requires child_process execPath emulation for --input-type/--import ESM CLI modes | 6 | `es-module/test-esm-import-meta-resolve.mjs#block_00_block_00`, `es-module/test-esm-import-meta-resolve.mjs#block_01_block_01`, `es-module/test-esm-import-meta-resolve.mjs#block_02_block_02`, ... (+3) | -| shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification | 6 | `parallel/test-zlib-reject-garbage-after-end.js#test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_01_zstd_trailing_junk_handling_is_independent_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_02_zstd_handles_incomplete_trailing_frame_identifiers_as_junk`, ... (+3) | | the test's meaningful body requires rooted symlink targets; common.canCreateSymLink skips it under the supported relative-only WASI boundary | 6 | `parallel/test-fs-options-immutable.js#block_00_block_00`, `parallel/test-fs-options-immutable.js#block_01_block_01`, `parallel/test-fs-options-immutable.js#block_02_block_02`, ... (+3) | | common-shim spawnPromisified child emulation does not support --experimental-webstorage/--localstorage-file flags | 5 | `parallel/test-webstorage.js#test_00_storage_instances_cannot_be_created_in_userland`, `parallel/test-webstorage.js#test_02_sessionstorage_is_not_persisted`, `parallel/test-webstorage.js#test_05_localstorage_is_not_persisted_if_it_is_unused`, ... (+2) | | inherited: buffer.transcode and ICU transcoding are not implemented | 5 | `parallel/test-icu-transcode.js#block_00_block_00`, `parallel/test-icu-transcode.js#block_01_block_01`, `parallel/test-icu-transcode.js#block_02_test_that_uint8array_arguments_are_okay`, ... (+2) | diff --git a/tests/runtime/zlib.rs b/tests/runtime/zlib.rs index d0cc6685..297c1efa 100644 --- a/tests/runtime/zlib.rs +++ b/tests/runtime/zlib.rs @@ -32,6 +32,15 @@ async fn zlib_zstd(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Resu Ok(()) } +#[test] +async fn zlib_trailing_input(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Result<()> { + let (result, output) = + invoke_and_capture_output(compiled.wasm_path(), None, "test-trailing-input", &[]).await; + println!("Output:\n{}", output); + assert_eq!(result?, Some(Val::Bool(true))); + Ok(()) +} + #[test] async fn zlib_zstd_disabled() -> anyhow::Result<()> { // Keep this component's Cargo output separate from the full-tier dependency. From b1b867ab1fb82619007ea57aa506f554d8e2ffe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 07:30:43 +0000 Subject: [PATCH 2/4] Preserve Brotli errors and partial output --- .../skeleton/src/builtin/zlib.js | 11 ++-- .../skeleton/src/builtin/zlib.rs | 30 +++++++++-- examples/runtime/zlib/src/zlib.js | 50 +++++++++++++++++++ 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index a14fdb12..4613e570 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -1039,7 +1039,7 @@ class _BrotliCompress extends ZlibBase { _initHandle() { if (this._nativeHandle !== null) return; const paramsJson = brotliParamsToJson(this._brotliParams); - this._setNativeHandle(brotli_stream_new(0, paramsJson, false)); + this._setNativeHandle(brotli_stream_new(0, paramsJson, false, false)); } } @@ -1055,7 +1055,9 @@ class _BrotliDecompress extends ZlibBase { this._initHandle(); } _initHandle() { - this._setNativeHandle(brotli_stream_new(1, '{}', this._rejectGarbage)); + this._setNativeHandle(brotli_stream_new( + 1, '{}', this._rejectGarbage, this._finishFlush !== BROTLI_OPERATION_FINISH, + )); } _flush(callback) { if (this._nativeHandle === null) { @@ -1086,7 +1088,8 @@ class _BrotliDecompress extends ZlibBase { try { while (this._nativeHandle !== null) { const chunk = brotli_stream_pull(this._nativeHandle, Z_DEFAULT_CHUNK); - if (!chunk || chunk.length === 0) { + if (chunk == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'zlib error'); + if (chunk.length === 0) { this._closeHandle(); callback(); return; @@ -1397,7 +1400,7 @@ export function brotliDecompressSync(data, opts) { validated.finishFlush, validated.rejectGarbage, ); - if (errno === -7) throw trailingJunkError(); + if (errno === -7 && errorMessage == null) throw trailingJunkError(); if (errno !== 0) { throw typeof errorMessage === 'string' && stringStartsWith(errorMessage, 'ERR_') ? makeBrotliError(errorMessage, errno) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs index cae6acf7..3bd32d6f 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs @@ -1001,6 +1001,7 @@ struct BrotliStream { kind: BrotliStreamKind, bytes_written: u32, reject_garbage: bool, + allow_incomplete: bool, trailing: bool, } @@ -1033,7 +1034,12 @@ static BROTLI_STREAMS: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); #[cfg(feature = "brotli")] -fn brotli_stream_new_impl(mode: u8, params_json: &str, reject_garbage: bool) -> Option { +fn brotli_stream_new_impl( + mode: u8, + params_json: &str, + reject_garbage: bool, + allow_incomplete: bool, +) -> Option { let kind = match mode { 0 => { let quality = parse_brotli_quality(params_json); @@ -1059,6 +1065,7 @@ fn brotli_stream_new_impl(mode: u8, params_json: &str, reject_garbage: bool) -> kind, bytes_written: 0, reject_garbage, + allow_incomplete, trailing: false, }, ); @@ -1170,6 +1177,11 @@ fn brotli_stream_read(stream: &mut BrotliStream, max_bytes: usize) -> Option 0; } brotli::BrotliResult::NeedsMoreOutput => {} + // Match the reader API: return decoded bytes before EOF. + brotli::BrotliResult::NeedsMoreInput if output_offset > 0 => {} + brotli::BrotliResult::NeedsMoreInput if stream.allow_incomplete => { + *finished = true; + } _ => return None, } chunk.truncate(output_offset); @@ -1195,7 +1207,12 @@ fn brotli_stream_bytes_written_impl(id: u32) -> u32 { } #[cfg(not(feature = "brotli"))] -fn brotli_stream_new_impl(_mode: u8, _params_json: &str, _reject_garbage: bool) -> Option { +fn brotli_stream_new_impl( + _mode: u8, + _params_json: &str, + _reject_garbage: bool, + _allow_incomplete: bool, +) -> Option { None } @@ -1378,8 +1395,13 @@ pub mod native_module { // ===== Brotli streaming functions ===== #[rquickjs::function] - pub fn brotli_stream_new(mode: u8, params_json: String, reject_garbage: bool) -> Option { - super::brotli_stream_new_impl(mode, ¶ms_json, reject_garbage) + pub fn brotli_stream_new( + mode: u8, + params_json: String, + reject_garbage: bool, + allow_incomplete: bool, + ) -> Option { + super::brotli_stream_new_impl(mode, ¶ms_json, reject_garbage, allow_incomplete) } #[rquickjs::function] diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index 89fc8a88..7fb68442 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -613,5 +613,55 @@ export async function testTrailingInput() { if (rejectGarbageAfterEnd) await assert.rejects(result, trailingError); else assert.deepEqual(await result, large); } + // A genuine Brotli -7 error must not alias the native trailing-junk sentinel. + const invalidHuffman = Buffer.from( + '5b330338c4da86a95e88bf5cd564a9960761816816b2508185625ad57bde1c68df7df50dc940578c58d4424cb900', + 'hex', + ); + const huffmanError = { name: 'Error', code: 'ERR__ERROR_FORMAT_HUFFMAN_SPACE', errno: -7 }; + for (const options of [undefined, { rejectGarbageAfterEnd: false }, { rejectGarbageAfterEnd: true }]) { + assert.throws(() => zlib.brotliDecompressSync(invalidHuffman, options), huffmanError); + await assert.rejects(new Promise((resolve, reject) => { + zlib.brotliDecompress(invalidHuffman, options, (error, output) => { + if (error) reject(error); + else resolve(output); + }); + }), huffmanError); + } + // A flushed 32769-byte block followed by an incomplete literal block. Keep + // every decodable byte across pulls, including the short final output chunk. + const truncatedBrotli = Buffer.from('0b00400024c2e2b14074ef000c5000086c617465206d61726b65', 'hex'); + const partialOutput = Buffer.concat([Buffer.alloc(32769, 97), Buffer.from('late marke')]); + const truncatedCases = [ + [truncatedBrotli, partialOutput], + // Same plaintext, with a small decoder window: the first pull needs more + // output space rather than more input, exercising the later-pull EOF path. + [Buffer.from('210000022011168f05a27b0760005000086c617465206d61726b65', 'hex'), partialOutput], + [Buffer.from('8f028068656c6c6f0a', 'hex'), Buffer.from('hello\n')], + [Buffer.alloc(0), Buffer.alloc(0)], + ]; + for (const [input, expected] of truncatedCases) { + for (const rejectGarbageAfterEnd of [false, true]) { + for (const finishFlush of [undefined, 0, 1, 2, 3]) { + const stream = zlib.createBrotliDecompress({ rejectGarbageAfterEnd, finishFlush }); + const chunks = []; + stream.on('data', chunk => chunks.push(chunk)); + const done = finished(stream); + stream.end(input); + // Only FINISH requires a complete stream. Permissive modes must still + // deliver every decoded byte, including the short final output chunk. + if (finishFlush === undefined || finishFlush === zlib.constants.BROTLI_OPERATION_FINISH) { + await assert.rejects(done); + } else { + await done; + } + assert.deepEqual(Buffer.concat(chunks), expected); + } + } + } + // Allowing incomplete input must not suppress actual decoder corruption. + for (const finishFlush of [0, 1, 2, 3]) { + await assert.rejects(collect(zlib.createBrotliDecompress, { finishFlush }, [invalidHuffman])); + } return true; } From 02788484a012bbc28c4ebb4023a3df5c2d987349 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 08:05:05 +0000 Subject: [PATCH 3/4] Update zlib test expectations --- examples/runtime/module-resolution/src/module-resolution.js | 6 +++--- tests/goldenfiles/generated_types_zlib_exports.d.ts | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/runtime/module-resolution/src/module-resolution.js b/examples/runtime/module-resolution/src/module-resolution.js index 3dd3892b..18e8b383 100644 --- a/examples/runtime/module-resolution/src/module-resolution.js +++ b/examples/runtime/module-resolution/src/module-resolution.js @@ -43,13 +43,13 @@ export async function testBuiltinDiscovery(testCase) { for (const id of ['node:test', 'node:sqlite']) { assert.strictEqual(get(id), require(id), id); } - // Actual package capability probes: keep absent SEA/zstd capabilities - // absent, so callers can take their ordinary-runtime/uncompressed path. + // Package probes retain the absent SEA fallback and discover the same + // supported codec APIs as the ordinary zlib module. assert.strictEqual(get('node:sea'), undefined); assert.strictEqual(get('node:sea')?.isSea() ?? false, false); const zlib = get('node:zlib'); assert.strictEqual(zlib, require('zlib')); - assert.strictEqual(zlib.zstdCompressSync, undefined); + assert.strictEqual(typeof zlib.zstdCompressSync, 'function'); assert.strictEqual(typeof zlib.gzipSync, 'function'); } else if (testCase === 1) { const originalLoad = module._load; diff --git a/tests/goldenfiles/generated_types_zlib_exports.d.ts b/tests/goldenfiles/generated_types_zlib_exports.d.ts index 9c73a551..3c2ce00c 100644 --- a/tests/goldenfiles/generated_types_zlib_exports.d.ts +++ b/tests/goldenfiles/generated_types_zlib_exports.d.ts @@ -2,4 +2,5 @@ declare module 'zlib' { export function testByteTransfer(): boolean; export function testZstd(): boolean; export function testZstdDisabled(): boolean; + export function testTrailingInput(): boolean; } From 9f3917d82d874d96009922e4173e54bfb8ce7509 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 12:43:06 +0000 Subject: [PATCH 4/4] Share trailing input error construction --- crates/wasm-rquickjs/skeleton/src/builtin/zlib.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index 6dc8013a..6013dd94 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -1262,7 +1262,7 @@ class Zstd extends ZlibBase { _processStep(data, flush, capacity) { const [bytes, message, errno, consumed, done] = zstd_stream_push(this._nativeHandle, data, flush, capacity); - if (errno === -7) throw makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', message); + if (errno === -7) throw trailingJunkError(); if (errno !== 0) { const code = errno === -5 ? 'Z_BUF_ERROR' : zstdErrorCodes[errno]; const error = makeError(code, message); @@ -1474,6 +1474,8 @@ export function brotliDecompressSync(data, opts) { validated.finishFlush, validated.rejectGarbage, ); + // Native sync trailing input uses -7 with no message; a named -7 is + // BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE, not trailing input. if (errno === -7 && errorMessage == null) throw trailingJunkError(); if (errno !== 0) { throw typeof errorMessage === 'string' && stringStartsWith(errorMessage, 'ERR_')