Dmitry Volyntsev [Fri, 13 Nov 2026 00:49:01 +0000 (16:49 -0800)]
WebCrypto: fix use after free of BufferSource arguments
Previously, the QuickJS WebCrypto methods took borrowed pointers to
the bytes of BufferSource arguments and algorithm members, and then
read further algorithm members. Getters and valueOf() of those
members could detach or resize the underlying ArrayBuffer, or drop the
last reference to a temporary buffer, so OpenSSL read freed memory.
This affected encrypt(), decrypt(), sign(), verify(), deriveBits(),
deriveKey(), importKey(), wrapKey() and unwrapKey().
Now all algorithm members are read before the bytes of the data
argument are taken, and no JavaScript code runs while the bytes are
in use, avoiding copies of inputs of up to 2 GiB. BufferSource
algorithm members (iv, counter, additionalData, salt, info) are
copied when read, and members are read in lexicographic order, as
WebIDL dictionary conversion does. Detached buffers are rejected
with TypeError, matching other njs modules.
QuickJS: remove qjs_to_bytes() and qjs_is_typed_array()
Previously, qjs_to_bytes() fell back to JS_ToString() and
JS_ToCStringLen() when the input was neither a string nor a buffer,
and then fell through to a second JS_ToCStringLen() call, invoking
toString() twice and leaking the first CString. The fallback also
treated detached buffers as non-buffers and converted them to strings
instead of propagating TypeError, and qjs_is_typed_array() left a
TypeError pending in the context when returning false.
Replace qjs_to_bytes() and qjs_is_typed_array() callers with explicit
JS_IsString() and qjs_typed_array_data() checks without implicit
ToString() coercion, and remove both helpers.
Modules: use qjs_typed_array_data() for QuickJS buffer arguments
Previously, ngx_qjs_dump_obj(), ngx_qjs_string(),
ngx_qjs_value_bytes_copy(), ngx_qjs_fetch_response_ctor(),
ngx_http_qjs_ext_send_buffer() and ngx_stream_qjs_ext_send() called
JS_GetTypedArrayBuffer() directly and trusted the returned byte_length
without clamping it to the backing ArrayBuffer size. On QuickJS prior
to 56d38b8 (2026-11-09) and QuickJS-NG prior to 947ffe4 (2026-11-13),
passing a length-tracking TypedArray whose resizable ArrayBuffer had
been shrunk caused heap out-of-bounds reads, including sending heap
memory to clients in r.sendBuffer() and s.send(). Falling back to
JS_ToCStringLen() also left a pending TypeError in the context, and
ngx_stream_qjs_ext_send() leaked the backing buffer reference when
ngx_stream_js_next_filter() failed.
Use qjs_typed_array_data() instead, and clear the pending exception
before falling back to string conversion.
QuickJS: clamp typed array length to backing ArrayBuffer size
Previously, qjs_typed_array_data(), Buffer.byteLength() and
Buffer.from() trusted byte_length returned by JS_GetTypedArrayBuffer().
In QuickJS prior to 56d38b8 (2026-11-09) and QuickJS-NG prior to 947ffe4 (2026-11-13), JS_GetTypedArrayBuffer() returned the initial
byte length for a length-tracking TypedArray after its resizable
ArrayBuffer had been shrunk with resize(), so callers read past the
shrunk buffer. In addition, when falling back after a failed
JS_GetTypedArrayBuffer() or JS_GetArrayBuffer() call, the pending
TypeError was left in the context.
Clamp byte_length to the remaining backing ArrayBuffer size rounded
down to the element size in qjs_typed_array_data() and
qjs_buffer_from_typed_array(), use qjs_typed_array_data() in
qjs_buffer_byte_length(), and clear pending exceptions after failed
buffer probes.
The issues were introduced in bb3dcf21 (0.8.5) and 1a482317 (0.8.10).
Previously, njs_fs_read_file() and qjs_fs_read_file() called
open(path, flags) without a mode argument. When the flag option
included O_CREAT, such as "a+" or "w+", open() read an uninitialized
mode or aborted under _FORTIFY_SOURCE.
Pass 0666 as the default mode, as in Node.js.
The issues were introduced in 35377fb2 (0.1.15) and 1f8f9992 (0.8.9).
Previously, option reads in external/qjs_fs_module.c used the pattern
if (!JS_IsUndefined(v) && !JS_IsException(v)), treating an exception
thrown by an option getter as an absent option and leaving the
exception pending in the context. In addition, qjs_fs_stat() rejected
any defined bigint option, including {bigint: false}.
Check JS_IsException() after each JS_GetPropertyStr() on options, and
allow {bigint: false} in qjs_fs_stat() as in njs_fs_stat().
XML: ignore DTD attribute declarations in removeAttribute()
Previously, njs_xml_node_attr_handler() and qjs_xml_node_attr_handler()
passed the result of xmlHasProp() directly to xmlRemoveProp(). Because
xmlHasProp() can return an XML_ATTRIBUTE_DECL node from the DTD when
the element does not have an own attribute of that name, xmlRemoveProp()
read past the end of the declaration structure.
Only call xmlRemoveProp() when xmlHasProp() returns an
XML_ATTRIBUTE_NODE.
The issues were introduced in 7d656627 (0.7.11) and cec9a165 (0.8.10).
HTTP: clear cached QuickJS request body value after freeing it
Previously, ngx_http_qjs_ext_request_body() released the cached
req->request_body value before constructing the alternate body
representation without resetting the field to JS_UNDEFINED. If the
subsequent body collection or conversion failed, req->request_body
retained a dangling reference to the freed value, which could be read
again on a later access or in ngx_http_qjs_request_finalizer().
Reset req->request_body to JS_UNDEFINED after freeing it, matching
ngx_http_qjs_ext_response_body().
FS: fetch buffer data after argument coercion in read() and write()
Previously, qjs_fs_read() and qjs_fs_write() obtained the buffer pointer
and length before converting the offset, length, and position
arguments. Because converting those arguments can invoke user code,
such as valueOf(), which can detach or transfer the underlying
ArrayBuffer, the subsequent bounds checks and system calls could access
freed memory.
The njs counterparts, njs_fs_read() and njs_fs_write(), had the same
ordering. The njs engine does not free the storage of a detached
ArrayBuffer, so there it resulted in using a detached buffer rather
than in a memory safety issue.
Now, all the arguments are converted before the buffer data is fetched,
as in 640d5ab8.
The QuickJS issue was introduced in 1f8f9992 (0.8.9).
Previously, the flag and mode options were converted with ToString()
and ToInteger(), so objects with toString() or valueOf() invoked user
code, and mode strings were parsed as decimal numbers: {mode: "644"}
created a file with permissions 0204, whereas Node.js treats the string
as octal. In addition, the converted mode value was truncated to
mode_t without a range check, and mode -1 collided with the error
marker, so the call failed without a pending exception.
Now, as in Node.js, flag must be a string, null or undefined, and mode
must be an integer in the range 0..4294967295, an octal string, null or
undefined. Other values throw TypeError or RangeError. Similarly,
mkdir() accepts an octal string as its second argument. Numeric flags
are not supported yet.
Changed behaviour:
- Mode strings are parsed as octal, as in Node.js. {mode: "644"} used
to mean 0o1204.
- Mode values that are not integers in the range 0..4294967295 throw
RangeError.
- Objects passed as mode or flag throw TypeError instead of invoking
valueOf() or toString().
- mkdir() accepts the mode as an octal string in its second argument.
Previously, the values of the flag, mode, recursive, withFileTypes,
bigint and throwIfNoEntry options obtained with JS_GetPropertyStr()
were not freed after conversion. Reference-counted values, such as
objects and non-atom strings, leaked; an object leak also made QuickJS
assert on runtime destruction.
Previously, when entry encoding or array population failed in
qjs_fs_readdir(), the error path freed the result array without
setting result to JS_EXCEPTION, so qjs_fs_result() later read the
freed value. In addition, JS_NewArray() failure returned before
closing the opened directory, and njs_fs_readdir() left ret as NJS_OK
when njs_vm_array_push() failed.
Set result to JS_EXCEPTION after freeing it, close the directory on
JS_NewArray() failure, and set ret to NJS_ERROR when array growth
fails in njs_fs_readdir().
The QuickJS issue was introduced in 1f8f9992 (0.8.9).
FS: copy directory entry names for Buffer results in njs
Previously, njs_fs_readdir() wrapped entry->d_name in a Buffer with
njs_buffer_set() without copying the bytes and then called closedir(),
leaving the returned Buffers pointing into freed DIR storage.
Use njs_buffer_new() so that each returned Buffer owns a copy of the
directory entry name.
TextEncoder: check Uint8Array before reading buffer in QuickJS
Previously, qjs_text_encoder_encode_into() extracted the destination
buffer pointer and length with qjs_typed_array_data() before calling
qjs_is_uint8_array(). Because qjs_is_uint8_array() looks up
globalThis.Uint8Array and calls JS_IsInstanceOf(), a getter or a
Symbol.hasInstance handler could detach or transfer the underlying
ArrayBuffer, so the subsequent UTF-8 encoding loop wrote through a
stale pointer. In addition, an exception thrown during the check was
ignored: encodeInto() returned a result with the exception left
pending.
Perform the Uint8Array check and propagate its exceptions before
extracting the destination buffer pointer and length.
Zlib: keep QuickJS dictionary value alive until copied
Previously, qjs_zlib_ext_deflate() and qjs_zlib_ext_inflate() released
the dictionary JSValue right after qjs_to_bytes() returned a borrowed
pointer into its backing store. When the dictionary option was a
getter returning a temporary buffer with no other references, releasing
the value freed the buffer before memcpy() copied the dictionary bytes.
Release the dictionary value only after the dictionary bytes have been
copied.
Previously, njs_vm_query_string_parse() and qjs_vm_query_string_parse()
stopped parsing r.args after 1000 segments, empty ones included,
although r.args is documented without a key limit and the query string
size is already bounded by large_client_header_buffers.
Parse r.args without a key limit.
The issue was introduced in 83a47d7c (0.7.6) and, for QuickJS, in adbb9280.
Changed behaviour:
- r.args contains all query string arguments. It used to stop after
the first 1000 segments.
Previously, njs_query_string_parse() threw TypeError for maxKeys values
that are not finite numbers, such as Infinity, or are not numbers at
all, and qjs_query_string_parse() treated maxKeys: 0 as a limit of zero
keys, returning an empty object.
Now, as in Node.js, numeric values of 0 and below, NaN and values
above 2^32 - 1, including Infinity, remove the limit in both engines,
and values that are not numbers are ignored, keeping the default
limit of 1000. Fractional values are truncated.
The issues were introduced in 8b9b297d (0.8.0) and f289dcb9 (0.8.10).
Changed behaviour:
- querystring.parse() treats a numeric maxKeys of 0 and below, NaN and
values above 2^32 - 1, including Infinity, as no limit. The njs
engine used to throw TypeError for non-finite values, and the
QuickJS engine used to return an empty object for maxKeys: 0.
- A maxKeys that is not a number is ignored, and its valueOf() is not
called. The njs engine used to throw TypeError, and the QuickJS
engine used to convert it to a number.
basavaraj-sm05 [Fri, 20 Nov 2026 12:20:44 +0000 (17:50 +0530)]
FS: fix symlink race in recursive rmdir
Recursive rmdir checked directory entries and then opened and removed
entries by full path. A concurrent change could redirect the walk and
cause it to remove entries outside the requested tree.
Look up, open and remove entries relative to the already opened parent
directory with fstatat(), openat() and unlinkat(). Open each directory
without following symlinks and use the opened descriptor to check
filesystem boundaries and cycles. Strip trailing slashes and reject "."
and ".." before starting the walk.
Jakub Jirutka [Tue, 1 Dec 2026 15:44:28 +0000 (16:44 +0100)]
Tests: tolerate rounding differences in Math.tanh()
On Alpine Linux/i686, Math.tanh(0.5) differs from the reference
expression (Math.E - 1)/(Math.E + 1) by one ULP (about 5.55e-17).
The exact comparison fails with both SSE and x87 builds.
Allow an absolute difference of Number.EPSILON, as in the tests
for Math.atanh() and Math.acosh().
Previously, ngx_qjs_ext_shared_dict_incr() converted delta and init
with JS_ToFloat64() without checking their type, so strings and null
were coerced to numbers instead of being rejected.
Require number arguments for delta and init, matching the njs engine
and ngx_qjs_ext_shared_dict_set().
Native timeout conversion cast a double to ngx_msec_t before checking
it, invoking undefined behavior for non-finite and out-of-range values.
QuickJS instead reduced the timeout modulo 2^32, so negative and wide
values could produce unintended entry lifetimes.
Use one conversion helper to check finite values and truncate fractional
milliseconds before casting, and report invalid arguments as TypeError
on both engines. Accept converted timeouts up to the signed timer
difference limit on the platform, matching the range ngx_parse_time()
allows for the timeout= parameter.
Treat an explicit undefined timeout as omitted in QuickJS incr(), and
use ngx_msec_t so a configured default is not narrowed to uint32_t.
The native cast was introduced in d8fbff1b (0.8.5), with the QuickJS
implementation following in 352c2e59 (0.8.8).
Modules: compare shared dictionary expiration times as timers
Previously, shared dictionary expiration checks compared ngx_msec_t
values directly. On 32-bit platforms the millisecond clock wraps every
49.7 days, so near a wrap an entry whose expiration time had wrapped was
treated as expired immediately. After a wrap, entries that had expired
but were not yet removed could become visible again.
Compare the signed difference, as nginx timers do. This also matches
the expire tree, which is already ordered by
ngx_rbtree_insert_timer_value(). On 64-bit platforms the clock does not
wrap, so the behavior is unchanged.
Modules: preserve shared dictionary numbers in state files
Previously, the shared dictionary state writer formatted numbers with
six fractional digits in a fixed-size buffer. Small values rounded to
zero, ordinary fractions lost precision, large values were truncated,
and non-finite values produced invalid JSON that prevented a subsequent
startup.
Use the engine-independent dtoa formatter to write a round-trip decimal
representation, with a buffer sized by the formatter. Quote non-finite
values as "NaN", "Infinity", and "-Infinity" in JSON state files and
parse them back on load, while preserving the sign of zero and the
existing JSON state schema.
Dmitry Volyntsev [Fri, 20 Nov 2026 02:41:52 +0000 (18:41 -0800)]
WebCrypto: reject out-of-range PBKDF2 iterations
Previously, PBKDF2 converted the iteration count to int64_t and passed
it to PKCS5_PBKDF2_HMAC(), which takes int. Counts such as 2^32 + 1
were silently narrowed to one iteration, producing a weaker derivation
than requested. The same conversion could turn negative counts into
valid positive counts, and JS_ToInt64() in QuickJS also wrapped counts
modulo 2^64.
Convert QuickJS iteration counts with saturation and check that the
converted count is in 1..INT_MAX before the OpenSSL call. Reject
unsupported counts explicitly instead of narrowing them. The int limit
is imposed by the OpenSSL interface; WebCrypto defines iterations as an
unsigned long and rejects zero (section 34.4.1).
The issue was introduced in 7b2b7612 (0.7.0) and inherited by the
QuickJS implementation in 75ca26f8 (0.8.10).
Dmitry Volyntsev [Fri, 20 Nov 2026 02:41:25 +0000 (18:41 -0800)]
WebCrypto: validate PBKDF2, HKDF, and ECDH bit lengths
Previously, deriveBits() and HMAC deriveKey() divided the requested
bit length by 8 without checking its range or alignment. Sub-byte
lengths could produce empty output, unaligned lengths were silently
truncated, and omitted or null deriveBits() lengths were converted to
zero. In QuickJS, JS_ToInt64() also reduced large lengths modulo 2^64
before the range check.
Require an explicit deriveBits() length, convert QuickJS integers with
saturation like njs, and check the bit length before division and
output allocation across PBKDF2, HKDF, ECDH, and X25519. Keep the
existing derived-key validation and zero-length behavior.
The issue was introduced in 7b2b7612 (0.7.0) and inherited by ECDH in 1b69415d (0.9.1) and the QuickJS implementation in 75ca26f8 (0.8.10).
Since e503f572 in njs and bb3dcf21 in QuickJS, inflateSync() has
tried to set a supplied dictionary before reading the zlib header.
Zlib rejects this for wrapped streams, even if no dictionary is
needed.
For wrapped streams, wait for Z_NEED_DICT before setting the
dictionary. Raw inflate still needs the dictionary up front.
Zlib: guard QuickJS stream cleanup after initialization
The QuickJS wrappers introduced in bb3dcf21 use stream.opaque to
check whether the stream needs cleanup. It is set before *Init2(),
so if zlib fails to allocate its state, the wrapper calls *End()
with an uninitialized stream.state.
Only end streams that were successfully initialized and have not
already been passed to *End().
basavaraj-sm05 [Thu, 26 Nov 2026 10:36:45 +0000 (16:06 +0530)]
Zlib: release temporary allocations in njs
Like nginx, njs normally reclaims allocations when it destroys the
pool. Without a GC, it cannot generally tell when JS objects are no
longer reachable.
Zlib's working buffers can be large and never escape the call.
Since the module was added in e503f572, repeated calls have kept
these buffers until VM destruction. Release them when the stream
ends, and clean up temporary output on error.
basavaraj-sm05 [Sat, 21 Nov 2026 12:31:38 +0000 (18:01 +0530)]
Modules: skip the proxy CONNECT tunnel when no proxy is selected
ngx_js_http_connect() and the write handler chose between a forward
proxy CONNECT tunnel and a direct TLS handshake from
ngx_js_conf_proxy(), which only reports that js_fetch_proxy is
configured for the location.
When the proxy URL comes from a variable it is evaluated per request
and an empty value selects a direct connection. An "https" fetch in
such a location then connected to the origin while still being
treated as proxied: the cleartext CONNECT request was written to the
origin and the TLS handshake was never started.
Use ngx_js_http_proxy(), the per-request state the rest of the fetch
code already uses, in the connect and write paths. A static
js_fetch_proxy is unaffected because both predicates agree there.
The AES-CTR counter length from algorithm.length was read as a signed
integer and only rejected when it was zero or above 128, so a negative
value passed the check. It was then handed to njs_bn_counter128(),
whose bits parameter is njs_uint_t (uintptr_t on 64-bit builds), so a
negative length turned into a very large unsigned count. The derived
byte count then drove a memcpy() into a 16-byte stack buffer with an
attacker-influenced size, overflowing it and reading past the counter
block. The value reaches here directly from crypto.subtle.encrypt()
and decrypt() calls on both engines.
Reject any length below 1 as well, matching the 1 to 128 range the
error message already states and the WebCrypto specification requires.
Dmitry Volyntsev [Thu, 19 Nov 2026 01:26:29 +0000 (17:26 -0800)]
Tests: remove ssl_preread from stream HTTPS fetch tests
The stream access checks proxy TLS to the HTTP backend without
using any ssl_preread variables. On builds without the preread
module, its directive prevents nginx from starting and the whole
test reports a misleading "no njs.fetch" skip.
Remove the unused directives so these checks do not depend on the
preread module.
Dmitry Volyntsev [Sat, 24 Oct 2026 05:51:50 +0000 (22:51 -0700)]
CI: split test262 runs into independent PR checks
Previously, normal, UBSan and ASan runs shared one test262 job, so the
PR checks page did not distinguish their results. A failure in an
earlier run also prevented the remaining configurations from running.
Use a named matrix with fail-fast disabled, following the CLI workflow.
Each configuration builds from a fresh checkout and retains its
configure flags, sanitizer options, suite revision, failure baseline
and test timeouts.
Dmitry Volyntsev [Sat, 24 Oct 2026 05:45:29 +0000 (22:45 -0700)]
Tests: distinguish WebCrypto absence from probe failures
The capability guards introduced in 4ea1356a skipped whenever the HTTP
response did not contain "true". A startup error, HTTP 500 or malformed
response could therefore hide a regression. Referencing an absent
crypto global also raised ReferenceError instead of returning false.
Use typeof to check the global and accept only a successful response
with an exact boolean body. Probe WebCrypto through stream in the
stream test, independently of HTTP engine selection. Treat startup
and malformed probe responses as failures.
Require WebCrypto when the existing CI_SSL setting is yes. Keep a
capability skip for a valid false response outside SSL-enabled CI,
so local builds without crypto remain supported.
Dmitry Volyntsev [Sat, 24 Oct 2026 05:45:29 +0000 (22:45 -0700)]
Tests: fail debug context tests on invalid responses
Previously, missing engine IDs were treated as evidence of a non-debug
build. An endpoint failure could therefore skip a debug test, while
merge tests could pass after ignoring invalid responses from some
locations or servers. The response-based guards were introduced in c4389399.
Check --with-debug independently before starting nginx. Require a
successful HTTP response and a complete numeric engine ID from every
endpoint, or a complete numeric stream response, before comparing
contexts. Let startup and response failures fail the tests instead
of reporting unsupported functionality.
Dmitry Volyntsev [Sat, 24 Oct 2026 05:36:02 +0000 (22:36 -0700)]
CI: enable stream HTTPS fetch test coverage
The standalone nginx CI setup added in 88285bc5 does not install
IO::Socket::SSL. Consequently, stream_js_fetch_https.t skips even
when nginx is built with SSL support.
Install libio-socket-ssl-perl, as nginx CI already does, so the existing
Perl test exercises HTTPS fetch and TLS stream access checks. Keep
the dependency guard for environments without the module.
Dmitry Volyntsev [Sat, 24 Oct 2026 05:22:14 +0000 (22:22 -0700)]
Tests: fix engine-specific nginx regression test skips
The engine-specific regression tests use try_run(), which reports
any nginx startup failure as a skip. In js_clone_failure.t, the
explicit js_engine njs directive also conflicts with an engine
injected into the http block. The QuickJS lifetime tests already
inherit the engine, but their probes can mistake a failed response
for a compatible engine.
Start the regression configuration once with run() and skip only
when the probe returns a known, incompatible engine. Check both
HTTP and stream for the wrapper GC test. Keep the clone-failure
module out of the engine probe's location so its intentional
exception does not interfere with the probe.
Dmitry Volyntsev [Thu, 19 Nov 2026 06:09:54 +0000 (22:09 -0800)]
Tests: size lifetime test zones for 64K pages
The lifetime tests added in aaaf5712 configure 32k shared dict zones,
but nginx requires at least eight pages per zone. On systems with
64 KiB pages, nginx rejects both test configurations at startup.
Use 512k for the two scopes zones. They only exchange test results
and do not exercise dictionary capacity or eviction.
Dmitry Volyntsev [Wed, 18 Nov 2026 01:16:32 +0000 (17:16 -0800)]
HTTP: split QuickJS request arguments before decoding
Previously, percent decoding the whole query string made encoded
ampersands and equals signs act as separators. Use the QuickJS
querystring parser to split the raw query before decoding each field.
Match the njs engine by accepting empty names and limiting the parse
to the first 1000 segments.
Previously, deriveKey() divided the requested length by 8 before
checking it, so AES lengths such as 129 were accepted as 128. HMAC
lengths below 8 bits produced an empty key, which importKey() rejects.
ECDH and X25519 did not check AES lengths at all, and njs reported an
unsupported HKDF or PBKDF2 derived key type as InternalError.
Now both deriveKey() paths check the length in bits before converting
it to bytes, reject HMAC keys shorter than one byte, and report invalid
derived key parameters as TypeError.
The AES length issue was introduced in 7b2b7612 (0.7.0) and inherited
by ECDH in 1b69415d (0.9.1).
Dmitry Volyntsev [Wed, 18 Nov 2026 01:17:09 +0000 (17:17 -0800)]
WebCrypto: release invalid oct JWK key values in QuickJS
Reading the k property acquires a reference even when the value is
not a string. Release it on rejection. If the property access throws,
propagate its exception rather than replacing it with a TypeError.
Dmitry Volyntsev [Wed, 18 Nov 2026 01:16:59 +0000 (17:16 -0800)]
WebCrypto: validate the export format when wrapping a key
wrapKey() uses the same serializer as exportKey(), but it bypasses
its format check. This can route a key to a serializer that expects
a different native key representation. Check the format in the
shared export path before dispatching to a serializer.
Dmitry Volyntsev [Wed, 18 Nov 2026 01:16:50 +0000 (17:16 -0800)]
WebCrypto: reject asymmetric ECDH and X25519 derived keys
Previously, ECDH and X25519 deriveKey() accepted any recognized
derived key algorithm, but the result always stores raw bytes.
With an asymmetric algorithm such as ECDSA, later operations treated
these bytes as an asymmetric key.
Reject derived key algorithms whose keys are not raw. HMAC, AES,
HKDF, and PBKDF2 remain supported.
The issue was introduced for ECDH in 1b69415d (0.9.1) and inherited
by X25519 in 744039e2 (0.9.7).
Dmitry Volyntsev [Thu, 19 Nov 2026 01:05:40 +0000 (17:05 -0800)]
WebCrypto: remove empty hash from HKDF and PBKDF2 keys in njs
Previously, HKDF and PBKDF2 keys went through the HMAC branch and
key.algorithm exposed an empty hash member. These keys have no hash;
their KeyAlgorithm contains only the name.
Dmitry Volyntsev [Thu, 19 Nov 2026 01:05:29 +0000 (17:05 -0800)]
WebCrypto: fix HKDF and PBKDF2 key algorithm in QuickJS
Previously, reading key.algorithm on an HKDF or PBKDF2 key passed a
NULL hash name to JS_NewString() and crashed the process. These keys
went through the HMAC branch, although they have no hash. Report only
the algorithm name for them.
basavaraj-sm05 [Tue, 17 Nov 2026 20:06:15 +0000 (01:36 +0530)]
Fix surrogate pairs after an unpaired surrogate escape
Previously, when a leading surrogate escape was followed by another
leading surrogate escape, JSON.parse() and the string literal parser
consumed both and replaced each of them with U+FFFD. A trailing
surrogate escape right after them then had no leading half to pair
with and was replaced as well, so a valid pair that followed an
unpaired leading surrogate was lost. For example,
JSON.parse('"\\uD83D\\uD83D\\uDE00"') and "\u{D83D}\u{D83D}\u{DE00}"
produced three U+FFFD characters instead of U+FFFD followed by
U+1F600.
Now only the unpaired leading surrogate is replaced, and the escape
after it is decoded on its own, so it can start a new pair. The
result matches String.fromCharCode() for the same code units.
Dmitry Volyntsev [Tue, 17 Nov 2026 21:23:52 +0000 (13:23 -0800)]
WebCrypto: preserve pending exceptions in QuickJS
Previously, failed string conversions were reported as out of memory,
although toString() can throw or the input can be a Symbol. A Symbol
in keyUsages therefore raised a false, uncatchable OOM in QuickJS-NG.
RSA and EC JWK import also replaced existing conversion, validation
and native exceptions with a generic "Invalid JWK ... key" error
from shared cleanup.
Keep the exception set by the failed operation. Throw the generic
JWK error only for invalid key members, not from shared cleanup.
Dmitry Volyntsev [Tue, 17 Nov 2026 20:38:50 +0000 (12:38 -0800)]
WebCrypto: free QuickJS algorithm parameters on conversion errors
Previously, when converting an algorithm parameter failed, the value
read from the algorithm object was not freed: AES-GCM iv, tagLength
and additionalData, AES-CTR counter and length, AES-CBC iv, the
derived key length and PBKDF2 iterations. For example, encrypt()
with an additionalData that is not a BufferSource leaked it; with
debug QuickJS this triggered the gc_obj_list assertion in
JS_FreeRuntime().
Dmitry Volyntsev [Tue, 17 Nov 2026 20:35:56 +0000 (12:35 -0800)]
WebCrypto: free RSA modulus when exponent import fails in njs
Previously, importing an RSA JWK key leaked the already decoded
modulus when decoding the exponent failed, for example when "e" was
longer than 512 bytes.
Previously, sign() and verify() for RSA and ECDSA freed the digest
and key contexts at verify_done without resetting the pointers. If
creating the resulting ArrayBuffer then failed, the error path freed
both contexts again.
Reset the pointers after freeing, as the QuickJS implementation does.
Dmitry Volyntsev [Tue, 17 Nov 2026 02:52:24 +0000 (18:52 -0800)]
WebCrypto: set exceptions on key conversion failures
Previously, several key import, export and signature conversion
helpers returned failure without setting an exception when an OpenSSL
call failed: BN_bin2bn(), BN_new(), EVP_PKEY_new(), EVP_PKEY_set1_RSA(),
d2i_ECDSA_SIG() and the bignum padding. The resulting Promise was
rejected with undefined in njs and with an internal uninitialized
value in QuickJS. In addition, njs_convert_der_to_p1363() returned
NJS_OK on these failures, so sign() resolved with an empty
signature.
The QuickJS OKP JWK import also used the result of JS_ToCStringLen()
for "x" and "d" without checking for NULL.
Dmitry Volyntsev [Tue, 17 Nov 2026 21:23:22 +0000 (13:23 -0800)]
WebCrypto: always return a Promise from QuickJS SubtleCrypto
Previously, QuickJS digest() returned an ArrayBuffer directly, while
other SubtleCrypto methods returned Promises but threw many early
validation errors synchronously. await hid the differences, but
then() chains and Promise.all() did not receive rejected Promises.
Dispatch all methods through one wrapper that converts the result or
pending exception with qjs_promise_result(), as required by Web
Cryptography API section 14.3. The implementations return a value
or JS_EXCEPTION; no early return can bypass the wrapper. Check the
direct return value in the digest and method-wide tests.
Dmitry Volyntsev [Tue, 17 Nov 2026 02:31:16 +0000 (18:31 -0800)]
WebCrypto: reject unsupported generateKey() algorithms in njs
Previously, generateKey() with an algorithm that has no key
generation, such as HKDF, threw InternalError synchronously instead
of returning a rejected Promise, unlike every other generateKey()
error.
Route the error through the common result path, as required by Web
Cryptography API section 14.3.6.
Dmitry Volyntsev [Tue, 17 Nov 2026 01:12:26 +0000 (17:12 -0800)]
WebCrypto: free QuickJS values on allocation failures
Previously, qjs_webcrypto_key_make() returned without freeing the new
CryptoKey object when allocating its native data failed, deriveKey()
did not free the derived CryptoKey when allocating the output failed,
and the CryptoKey.algorithm getter did not free the hash name when
allocating the hash object failed. The values leaked; with debug
QuickJS the first two also triggered the gc_obj_list assertion in
JS_FreeRuntime().
Dmitry Volyntsev [Tue, 17 Nov 2026 01:10:02 +0000 (17:10 -0800)]
QuickJS: fix rejection reason leak in qjs_promise_result()
Previously, when JS_EnqueueJob() failed, the cleanup freed the
original result argument instead of the job arguments. For a
rejected result, that argument is JS_EXCEPTION, while the reason
taken with JS_GetException() leaked.
Free the job arguments, which own the callback and the reason or
result value in both cases.
Dmitry Volyntsev [Tue, 17 Nov 2026 01:09:28 +0000 (17:09 -0800)]
WebCrypto: reject HKDF output length mismatch
Previously, when EVP_PKEY_derive() succeeded but returned fewer bytes
than requested, HKDF deriveBits() and deriveKey() set an exception but
the shared cleanup only checked the positive OpenSSL return value.
The operation then resolved with partially initialized output.
Mark the result as failed before jumping to the cleanup.
The issue was introduced in 7b2b7612 (0.7.0) and copied to QuickJS
in 75ca26f8 (0.8.10).
Dmitry Volyntsev [Tue, 17 Nov 2026 01:08:43 +0000 (17:08 -0800)]
WebCrypto: check string creation status in njs
Previously, several CryptoKey getters and JWK export helpers ignored
the result of njs_vm_value_string_create(). Since b28e50b1 (0.9.0)
even short strings are allocated, so an allocation failure left the
value uninitialized. Reading key.algorithm then crashed in
njs_vm_object_alloc(), and key.type returned success with a pending
exception.
Propagate the error like the other string creation calls in the
module do.
Dmitry Volyntsev [Tue, 17 Nov 2026 01:07:04 +0000 (17:07 -0800)]
WebCrypto: reject unknown key formats in QuickJS
Previously, exportKey(), wrapKey() and unwrapKey() ignored the
QJS_KEY_FORMAT_UNKNOWN result of qjs_key_format() and kept the
pending exception. exportKey() and unwrapKey() then replaced it with
'unsupported key fmt "(null)"', while wrapKey() fell back to the raw
format and resolved, so wrapKey('JWK', ...) silently wrapped raw key
bytes.
Check the format like importKey() and the njs implementation do.
The issue was introduced in 75ca26f8 (0.8.10) for exportKey() and in f42b2683 (0.9.7) for wrapKey() and unwrapKey().
Dmitry Volyntsev [Mon, 16 Nov 2026 23:47:03 +0000 (15:47 -0800)]
WebCrypto: free output after ArrayBuffer construction failure
Previously, failure to construct a WebCrypto result ArrayBuffer left
its native output allocation unowned. The adoption helper transfers
ownership only on success, so callers must release storage on failure.
Add cleanup at the affected call sites without changing successful
ownership transfer or the common helper contract.
Most paths were introduced in 75ca26f8 (0.8.10), ECDH in 1b69415d
(0.9.1), and AES-KW in f42b2683 (0.9.7).
Previously, HMAC verification assigned its stack digest buffer to
dst. If HMAC() failed or returned an unexpected digest length, the
common error handler passed that stack pointer to js_free().
Keep dst reserved for allocated output and use the stack buffer
directly for verification. The issue was introduced in 75ca26f8
(0.8.10).
Dmitry Volyntsev [Mon, 16 Nov 2026 23:35:46 +0000 (15:35 -0800)]
WebCrypto: avoid freeing RSA JWK values twice
Previously, RSA JWK import released its parameter values before
creating the EVP_PKEY. A failure in EVP_PKEY_new() or
EVP_PKEY_set1_RSA() then released the same values in error cleanup.
Reset released values so the error handler no longer owns them.
The issue was introduced in 75ca26f8 (0.8.10).
Dmitry Volyntsev [Mon, 16 Nov 2026 23:33:44 +0000 (15:33 -0800)]
WebCrypto: transfer imported key ownership
Previously, failure to allocate the external CryptoKey object freed
an imported EVP_PKEY in the local error handler, then freed it again
when the VM memory pool ran the key cleanup.
Clear the local pointer when ownership passes to the key cleanup.
The issue was introduced in 50e7c9b2 (0.7.10).
Dmitry Volyntsev [Mon, 16 Nov 2026 23:32:07 +0000 (15:32 -0800)]
WebCrypto: free AES-GCM context on errors
Previously, additionalData conversion and output allocation failures
returned without freeing the OpenSSL cipher context. Repeated failed
operations leaked contexts and their associated allocations.
Route these failures through the existing cleanup. The issue was
introduced in 7b2b7612 (0.7.0).
Dmitry Volyntsev [Tue, 17 Nov 2026 00:19:41 +0000 (16:19 -0800)]
QueryString: use null prototypes for parsed arguments
Previously, querystring.parse() and r.args consulted inherited
properties when collecting duplicate parameters. Keys such as
"toString" included inherited functions in their values, and
"__proto__" replaced the prototype of the result with an array.
Now both engines create results with a null prototype, matching
Node.js and treating all parsed names as data. Object.prototype
methods, including hasOwnProperty(), are no longer inherited.
The njs regression was introduced in 8b9b297d (0.8.0). The QuickJS
r.args implementation introduced the same issue in 201b1276
(0.8.6), followed by querystring.parse() in f289dcb9 (0.8.10).
The issue was found by Basavaraj S m (basavaraj-sm05) in PR #1147:
https://github.com/nginx/njs/pull/1147
Dmitry Volyntsev [Fri, 13 Nov 2026 02:26:58 +0000 (18:26 -0800)]
WebCrypto: reject empty HMAC keys in importKey()
Previously, importKey() accepted an empty raw or JWK HMAC key. The
HMAC import key operation requires a DataError when the key data
length is zero. It is reported as TypeError, as other invalid key
data in njs.
The issue was introduced in 7b2b7612 (0.7.0) and the QuickJS
counterpart in 75ca26f8 (0.8.10).
Dmitry Volyntsev [Fri, 13 Nov 2026 02:25:11 +0000 (18:25 -0800)]
QuickJS: fix zero-length allocations with QuickJS-NG
QuickJS-NG js_malloc() returns NULL and throws "out of memory" for a
zero size, while QuickJS returns a valid pointer. Empty inputs to hash
update() and fs write and read functions with a string encoding, empty
raw and JWK secret keys in WebCrypto importKey() and zero-length
deriveBits() failed with an out of memory error. Since QuickJS-NG
0.18.0 (90aa2c4) that error is uncatchable, so such a call terminates
the script.
Now at least one byte is allocated, as QuickJS-NG itself does for
possibly empty allocations.
Dmitry Volyntsev [Fri, 13 Nov 2026 00:48:45 +0000 (16:48 -0800)]
WebCrypto: fix ECDH public key use after free
Previously, the QuickJS deriveBits() and deriveKey() implementation
for ECDH released the "public" algorithm member right after taking
the key from it. When the member was returned by a getter and no
other reference was held, the CryptoKey and its EVP_PKEY were freed
before EVP_PKEY_derive() used them.
Now the member value is kept until the derivation is done.
Dmitry Volyntsev [Fri, 13 Nov 2026 23:20:47 +0000 (15:20 -0800)]
Modules: report library and host failures as Error
Since QuickJS-NG 0.18.0 (db0fe52, "Make InternalErrors uncatchable by
JS code") an InternalError cannot be caught by JavaScript code. njs
used InternalError for failures of OpenSSL, zlib, libxml and nginx,
such as inflating corrupted data or failing to send a response. With
QuickJS-NG 0.18.0 such an error terminated the script, and in nginx
the handler, instead of reaching a try/catch block.
Now such failures are reported as Error in both engines, as Node.js
does. The QuickJS engine uses the new qjs_throw_error() function,
which works with both QuickJS and QuickJS-NG. InternalError is kept
for impossible internal states and unsupported features.
The "path is too long" error of fs in the njs engine is now RangeError,
as in the QuickJS engine.
CI now uses QuickJS-NG 0.18.0, where the zlib test failed because of
the uncaught InternalError.
Dmitry Volyntsev [Mon, 16 Nov 2026 01:39:43 +0000 (17:39 -0800)]
TextDecoder: allow omitted arguments in decode()
Previously, decode() rejected an undefined input or options argument,
although both are optional. The njs engine threw a TypeError for
decode(undefined) and for null or undefined options, and QuickJS also
rejected decode() without arguments. This prevented flushing a
stream with decode() or decode(undefined, {stream: true}).
Now an undefined input is treated as empty, and null or undefined
options are treated as default options, as the Web IDL conversion of
the TextDecoder.decode() arguments requires.
The issue was introduced in 0570392f (0.4.3) and copied into QuickJS
in 447d66d4 (0.8.10).
Dmitry Volyntsev [Mon, 16 Nov 2026 01:37:21 +0000 (17:37 -0800)]
TextDecoder: fix use-after-free on detach in decode() options
Previously, decode() fetched the input data pointer before reading the
"stream" option. The option getter can run user code that detaches
the buffer, for example with ArrayBuffer.prototype.transfer() in
QuickJS. QuickJS then read the freed memory, and njs decoded the
contents of the detached buffer.
Now the options are read before the input is fetched and checked, so
a detach in the getter is reported as a TypeError, the same way as a
buffer detached before the call.
The issue was introduced in 0570392f (0.4.3) and copied into QuickJS
in 447d66d4 (0.8.10).
basavaraj-sm05 [Sun, 15 Nov 2026 14:32:00 +0000 (20:02 +0530)]
TextDecoder: skip BOM only at the start of a stream
Previously, decode() checked for a UTF-8 BOM at the start of every
input chunk. This dropped U+FEFF within a stream and preserved a
leading BOM split between chunks. This affected both engines.
Now BOM handling follows the first decoded code point of the stream,
as required by Encoding Standard sections 7.1 and 7.2. Empty chunks
and incomplete UTF-8 sequences do not mark the BOM as seen.
The decoder state is reset at the start of a new stream, including
after a failed final decode(). The BOM seen flag is updated only
when decoded output is returned, while the UTF-8 context advances
up to the error in fatal mode.
The issue dates back to 0570392f (0.4.3) and was copied into QuickJS
in 447d66d4 (0.8.10).
Dean Chen [Sun, 15 Nov 2026 01:19:24 +0000 (06:19 +0500)]
Parser: fix overlong code point escape conversion
Previously, when computing the length of an escaped string, all hex
digits of a "\u{...}" escape were accumulated into a double and
converted to uint64_t before the existing six-digit limit was checked.
For overlong escapes, the parsed value could be outside the range of
uint64_t, including due to rounding with 16 digits. The conversion is
undefined behavior and aborts builds with UBSan enabled.
Now at most seven digits are parsed, which still rejects longer escapes
with the same SyntaxError while keeping the value in range.
The issue was introduced in 7cff11dc ("Fixed large non-decimal literals."),
which changed njs_number_hex_parse() to return a double.
Dmitry Volyntsev [Sat, 14 Nov 2026 02:37:35 +0000 (18:37 -0800)]
Querystring: fix decoding after invalid UTF-8
Previously, percent-decoding advanced past each encoded byte even when
the UTF-8 decoder left it unconsumed after reporting an invalid pending
sequence. For example, "%D8%41%42" decoded to "\ufffdB" instead of
"\ufffdAB". This affected querystring.parse() and unescape() in both
engines, and r.args in nginx.
Now njs_utf8_consume() reports whether the byte was consumed, so callers
can reread it before advancing the input, as the WHATWG UTF-8 decoder
requires. Plus signs are also passed through the decoder as spaces,
so they flush invalid pending sequences without losing or reordering
the replacement character.
The issue was introduced in 50ea0dbc (0.4.3), copied into QuickJS
r.args in 201b1276 (0.8.6) and into its querystring module in f289dcb9
(0.8.10).
basavaraj-sm05 [Thu, 1 Oct 2026 21:28:25 +0000 (21:28 +0000)]
String: fix decoding of code units after an unpaired surrogate
Previously, String.fromCharCode() and String.fromCodePoint() decoded
each argument only once. When a pending leading surrogate was not
followed by a trailing one, the UTF-16 decoder reported the unpaired
surrogate and left the current unit to be reread. The buffer was then
overwritten by the next argument, losing or corrupting subsequent
characters. For example, String.fromCharCode(0xD83D, 0x41, 0x42)
returned "\ufffd\u4241" instead of "\ufffdAB" on little-endian systems.
Now both the size calculation and the encoding pass drain each buffer
before proceeding to the next argument. Unpaired surrogates are still
replaced with U+FFFD, preserving the existing string representation.
Dmitry Volyntsev [Sat, 14 Nov 2026 02:32:10 +0000 (18:32 -0800)]
Core: fix buffering of 0xFF in the UTF-16 decoder
Previously, the UTF-16 decoder stored a buffered byte plus one in the
eight-bit ctx->upper field, using zero to mean no buffered byte. A
byte of 0xFF overflowed to zero and was lost. This corrupted code
units split across buffers and units reread after an unpaired leading
surrogate.
Now ctx->need indicates whether a byte is buffered, and ctx->upper
stores the byte unchanged. All byte values can be preserved without
changing the decode context layout or its streaming contract.
HTTP: fix missing validation of subrequest and redirect arguments
Previously, the target of r.subrequest() and r.internalRedirect() was
checked by ngx_http_parse_unsafe_uri(), which inspects only the path.
The arguments, both the part after "?" and the args argument of
r.subrequest(), were stored in r->args as is. Values of r.args are
percent-decoded, so "q=" + r.args.q could carry CR and LF into
r->args, and the proxy module copies it into the upstream request line
byte for byte. The upstream saw injected headers or a second request.
Now the arguments are rejected if they contain a C0 control character,
space, or DEL, as ngx.fetch() does for its request target.
r.subrequest() throws a TypeError and r.internalRedirect() fails the
request with 500. Percent-encoded values are left unchanged.
ngx_js_check_request_line_component() is renamed to
ngx_js_check_no_space_or_ctrl_chars(), because it validates a method
and arguments as well as a request target.
basavaraj-sm05 [Wed, 12 Aug 2026 15:07:30 +0000 (20:37 +0530)]
Buffer: fix use-after-free on detach during argument coercion
Several Buffer.prototype methods fetched the data pointer of the
underlying ArrayBuffer before converting their offset, length or value
arguments. The conversion may call user code (valueOf) which can
detach the buffer, for example with ArrayBuffer.prototype.transfer().
The bounds check and the memory access then used the stale pointer.
In QuickJS this affected readInt/readFloat, writeInt/writeFloat,
write(), toString(), indexOf(), compare() and copy(). In njs it
affected the range helper behind compare() and copy().
Now all arguments are converted first, and the buffer is fetched and
checked right before it is used, so a detach during the conversion is
reported as an ordinary "detached buffer" error. The order in which
the arguments are converted is preserved.
In njs, copy() now makes the target writable before computing the
target range. A target sharing external data is copied on write, so
pointers computed earlier pointed to the old data and the copy was
lost.
Similarly, toJSON() in QuickJS stored the bytes with
JS_SetPropertyUint32(), which may call a setter inherited from
Array.prototype and detach the buffer during the loop. The elements
are now defined directly on the new array.
Dmitry Volyntsev [Thu, 12 Nov 2026 01:37:06 +0000 (17:37 -0800)]
Modules: clear QuickJS hooks before a context is reused
Previously, an exit hook installed during context teardown, for example
by a promise job queued by the exit hook, was kept in the context. When
the context was reused, the hook was called during the teardown of a
later request.
Now hooks are cleared together with the pending events, after the last
user code of the request has run.
Dmitry Volyntsev [Thu, 12 Nov 2026 01:36:24 +0000 (17:36 -0800)]
QuickJS: find the exit hook without the "njs" global property
Previously, the exit hook was found through the "njs" global property.
If a script replaced or deleted globalThis.njs, the hook installed with
njs.on() was not called, unlike with the njs engine, where hooks are
kept in the VM. A getter on the property was also run as user code
during context teardown.
Now the njs object is kept in a class prototype slot of the context,
the same way as the Uint8Array constructor in the Buffer module, and
the exit hook is found there.
Dmitry Volyntsev [Thu, 12 Nov 2026 01:34:31 +0000 (17:34 -0800)]
QuickJS: fix njs.on() replacing the exit hook during its call
Previously, the exit hook was released after the call while the caller
kept no reference to it. If the hook replaced or reset itself with
njs.on(), the function was freed while it was still running, which
resulted in use-after-free.
Now the hook is detached from the njs object before the call, and the
call owns the reference.
Dmitry Volyntsev [Thu, 12 Nov 2026 01:33:52 +0000 (17:33 -0800)]
QuickJS: fix njs.on() with a foreign receiver
Previously, njs.on() allocated the hooks state lazily and attached it to
its receiver with JS_SetOpaque() if the receiver was not an njs object.
Called with another receiver, for example njs.on.call(f, ...), it
overwrote the internal opaque pointer of an arbitrary object, which
resulted in memory corruption.
Now the hooks state is allocated with the njs object, and njs.on()
called with another receiver throws TypeError.
Dmitry Volyntsev [Wed, 11 Nov 2026 22:24:35 +0000 (14:24 -0800)]
Stream: check optional arguments in QuickJS direct send methods
sendUpstream() and sendDownstream() have a declared length of one,
but their shared handler accessed the second argument unconditionally.
QuickJS pads missing arguments only up to the declared length, so calls
without options could read beyond the argument array and crash.
Check the argument count before accessing the optional options object,
without changing the methods length. The issue was introduced in 201b1276 (Modules: introduced QuickJS engine).
Dmitry Volyntsev [Wed, 11 Nov 2026 04:04:32 +0000 (20:04 -0800)]
Stream: do not use the filter output chain after the filter returns
Asynchronous s.send() without a direction appended to the output chain
of the stream filter call, which was a local variable. The pointer to
it was kept in the context after the filter returned. Only calls that
passed an options object were rejected, so a plain s.send(data) from a
timer or a promise wrote to a returned stack frame with both engines.
Reset the pointer when the filter returns and reject asynchronous sends
that have no direction regardless of the options argument.
Changed behaviour:
- Asynchronous s.send(data, options) without a direction in the options
throws TypeError, as s.send(data) already did for the options-less
call, instead of writing to a returned stack frame.
Dmitry Volyntsev [Wed, 11 Nov 2026 01:56:57 +0000 (17:56 -0800)]
Modules: release work started while logging unhandled rejections
Context teardown cleared pending events before logging an unhandled
rejection. Converting the rejection reason to a string runs user code,
which could start a timer or a fetch() after the cleanup. The timer or
connection then outlived the request pool, resulting in use-after-free
with both engines.
Dmitry Volyntsev [Wed, 11 Nov 2026 01:46:20 +0000 (17:46 -0800)]
Modules: initialize the JS context of a completed subrequest
When a subrequest completed, its JS context was allocated by the
subrequest completion handler without ngx_js_ctx_init(), so the log and
the waiting events tree were not initialized. If the subrequest had no
JS context of its own, a reply received by the parent could then use
it:
- readRequest*() on the reply inserted a caller event into the
uninitialized tree;
- reading a js_set variable through reply.variables created an engine
for the uninitialized context.
Both crashed with both engines. The waiting events tree is missing
since 9de30135 (0.8.3), the log since 9b674412 (0.8.6).
Now the context is initialized as in ngx_http_js_init_vm(). Also,
deferred body reads are allowed only for the executing request, because
the body read state of a reply belongs to the subrequest.
Changed behaviour:
- readRequestText() and the other readRequest*() methods called on a
subrequest reply throw TypeError. They used to resolve with the body
of the parent request, or to crash when the body had to be read.
Dmitry Volyntsev [Thu, 12 Nov 2026 04:04:23 +0000 (20:04 -0800)]
VM: fix call stack sharing in cloned VMs
Previously, njs_vm_clone() copied the call stack pointers of the VM
being cloned. A VM created with the "init" option keeps its initial
frame, so every clone allocated frames in the spare space of that
frame instead of its own memory. When two clones of the same VM ran at
the same time, they overwrote each other's frames. In nginx, this
happened when a parent handler evaluated a js_set variable of a
subrequest: the subrequest clone overwrote the frames of the running
parent clone, which crashed after returning from the native call.
Now a cloned VM starts with an empty call stack and allocates its own
initial frame.
Dmitry Volyntsev [Wed, 11 Nov 2026 01:44:27 +0000 (17:44 -0800)]
Modules: keep HTTP request JS state in its host context
A subrequest handler could receive the parent request JS object from
another context. Changing that object used foreign QuickJS shapes, and
setting a return value through a reply or parent stored a value from one
context in another context result slot.
Expose r.parent only on a reply whose parent is the executing request,
which matches the documented API. Allow setReturnValue() only for the
executing request. Check both engines so mixed njs and QuickJS
locations never interpret each other values.
Changed behaviour:
- r.parent is undefined in a subrequest handler, as the API reference
says. It used to be the parent request object of another context.
- setReturnValue() called through a reply or a parent throws TypeError
instead of storing the value in another request.
Dmitry Volyntsev [Thu, 12 Nov 2026 02:21:53 +0000 (18:21 -0800)]
Fix String.prototype.match() returning an empty array on no match
Previously, global matching replaced the initial null result with an
array even when no matches were collected. This differs from the
ECMA-262 RegExp.prototype [ @@match ] algorithm, which returns null
when the first execution finds no match.
The issue was introduced in 83645861 (0.3.2), which moved
array allocation outside the matching loop.
Return the array only when it contains matches. Empty-string matches
still count as matches, and lastIndex continues to be reset to zero.
Dmitry Volyntsev [Thu, 12 Nov 2026 02:20:38 +0000 (18:20 -0800)]
Fix initialization checks for identifier expression statements
Previously, a bare identifier statement emitted its initialization
check before the preceding statements. An initialized let or const
binding could therefore throw ReferenceError, and side effects before
a real TDZ error could be skipped.
The issue was introduced in 158f54e6 (0.6.0), which added let.
Defer identifier resolution and its initialization check until the
preceding statements have been generated. This preserves the existing
unused-value optimization and runtime checks for captured bindings,
while evaluating statements in source order as required by ECMA-262.
Dmitry Volyntsev [Thu, 12 Nov 2026 02:19:22 +0000 (18:19 -0800)]
Fix Array.prototype.toString() forwarding arguments to join()
Previously, arguments passed to toString() were forwarded to join(),
changing the separator and the arguments seen by a custom join method.
The same issue affected typed arrays using the shared implementation.
This behavior dates back to the initial import in bffbe5e4 (0.1.0).
Call join() with only the receiver, as required by ECMA-262 section
23.1.3.36. Extra arguments must neither reach join() nor be converted
to strings.
Dmitry Volyntsev [Wed, 11 Nov 2026 00:48:58 +0000 (16:48 -0800)]
Tests: honor injected engines in QuickJS lifetime tests
Hardcoded QuickJS directives run these tests in the default njs pass
and conflict with CI engine injection. Probe the selected engine and
skip the QuickJS-specific checks when njs is active.
Check both HTTP and stream engines for the GC test. Use an isolated
probe module for the redirect test so probing does not change the
source and destination visit counters.
Dmitry Volyntsev [Tue, 10 Nov 2026 20:17:46 +0000 (12:17 -0800)]
Modules: bind QuickJS native views to their context lifetime
HTTP and stream views can outlive their request or connection pool
in a reused runtime. Detaching only the root object leaves variables,
headers, forms and replies with dangling native pointers. Direct
session accessors and cold body getters can dereference detached roots,
while populated request caches hide their expiry.
Share a runtime-owned revocable token across each binding and its
views. Reject expired access before native dereferences, including
cache access, without retaining pools or copying native data.
Keep reply tokens tied to the originating subrequest operation so
completed replies remain usable until the parent binding is detached.
The header and variable lifetime gap dates back to 201b1276, which
introduces QuickJS integration. RequestForm uses the same unguarded
model since 0ffc96df. Extracted JS values and stream callback flags
remain independent; RequestForm remains a guarded request-bound view.
Dmitry Volyntsev [Tue, 10 Nov 2026 02:47:44 +0000 (18:47 -0800)]
Modules: embed the common opaque prefix in QuickJS wrappers
Context detach accesses the native pointer through a shared opaque
layout. Embed that layout explicitly in HTTP and stream wrappers
instead of relying on unrelated first pointer fields.
This prepares shared lifetime invalidation without changing behavior.
QuickJS: make Fetch storage independent of request pools
Fetch objects could remain reachable in a reused runtime after their
native request-pool data was freed. Headers views also pointed into
parent records, and unread Response bodies had no object owner.
Give Headers, Request, and Response runtime-owned storage. Keep
associated Headers and Request body snapshots alive through marked
JSValue references.
Header getters reuse the associated object; independent construction
copies mutable header lists without borrowing another object's data.
The Fetch operation holds its Request and Headers during transport and
moves runtime-allocated body chains into the published Response. Only
transient metadata need copying at publication. Finalizers and failure
paths release owned data, including unread bodies; consumed chains are
reset so finalization cannot free their nodes twice.
The njs engine retains its pool-backed implementation.
Dmitry Volyntsev [Tue, 10 Nov 2026 01:45:32 +0000 (17:45 -0800)]
QuickJS: distinguish buffer copies and storage ownership
The creation helpers do not express whether they copy bytes or take
responsibility for an existing allocation. Use copy names for Buffer
snapshots and adopt for owned ArrayBuffer storage.
Create the external SharedArrayBuffer directly in the sole shell
caller instead of exposing a non-owning wrapper as a common helper.
Preserve the existing ownership and allocation-failure contracts.
Dmitry Volyntsev [Tue, 10 Nov 2026 01:42:56 +0000 (17:42 -0800)]
QuickJS: add runtime-owned byte storage helpers
Fetch ownership needs native copies and chain allocations that do not
depend on request pools or a surviving JSContext. Provide common
helpers for these operations while preserving nginx value conversion
semantics.
Fetch: separate header storage from request and response records
Headers are embedded in Request and Response records, so a Headers view
cannot retain its storage independently of the parent record.
Use explicit header-storage pointers while keeping the existing pool
allocation and lifetime policy in both engines. This prepares the
shared transport for independently owned QuickJS Headers without adding
allocator modes to the header helpers.
Modules: guard debug engine id access during initialization
The request engine is not published while global code runs. Reading
ngx.engine_id at that point dereferenced NULL instead of reporting that
the debug property is unavailable.
Reject the access in both engines without publishing a partial clone.
Modules: reject asynchronous work during module initialization
Global code is intended for synchronous initialization, but Fetch and
timers could start request-bound work before clone publication. QuickJS
Fetch dereferenced the unpublished engine, and module-level timers could
escape initialization.
Reject Fetch, setTimeout(), and setImmediate() before argument conversion
or resource allocation in both engines. This does not prohibit ordinary
promise jobs or synchronous module initialization.
Modules: decouple QuickJS dump buffers from the request engine pool
Module-level logging dereferenced ctx->engine before clone publication.
Formatting only needs the current JSContext, not a published request
engine. Pool-backed js_set results also coupled nginx variable storage
to the engine's lifetime.
Return temporary runtime-owned dump buffers and release them immediately
after logging. Copy js_set results to the request or session pool and
release the temporary buffer, including on allocation failure. Keep the
njs conversion path unchanged.
Modules: use the caller context for QuickJS string conversion
String conversion recovered the context through ctx->engine even though
both the JSContext and destination pool were already supplied. During
module evaluation the engine is not published yet, so synchronous
Request and Headers construction could dereference NULL.
Use the supplied context without changing allocation or copy behavior.
The dependency was introduced in 201b1276.