From db7ecabe387822f80b978971c5bb90371ecd77b4 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Wed, 11 Nov 2026 17:34:31 -0800 Subject: [PATCH 01/16] 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. The issue was introduced in 04f6dfb9 (0.9.2). --- src/qjs.c | 11 ++++++----- test/js/njs_on_exit_replace.t.js | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 test/js/njs_on_exit_replace.t.js diff --git a/src/qjs.c b/src/qjs.c index 5220486b..2ab6ed0c 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -355,7 +355,7 @@ qjs_chb_rt_free(void *rt, void *p) JSValue qjs_call_exit_hook(JSContext *ctx) { - JSValue global, obj, ret; + JSValue global, obj, hook, ret; qjs_njs_t *njs; global = JS_GetGlobalObject(ctx); @@ -367,12 +367,13 @@ qjs_call_exit_hook(JSContext *ctx) njs = JS_GetOpaque(obj, QJS_CORE_CLASS_ID_NJS); if (njs != NULL && JS_IsFunction(ctx, njs->hooks[QJS_NJS_HOOK_EXIT])) { - ret = JS_Call(ctx, njs->hooks[QJS_NJS_HOOK_EXIT], JS_UNDEFINED, - 0, NULL); - - JS_FreeValue(ctx, njs->hooks[QJS_NJS_HOOK_EXIT]); + hook = njs->hooks[QJS_NJS_HOOK_EXIT]; njs->hooks[QJS_NJS_HOOK_EXIT] = JS_UNDEFINED; + ret = JS_Call(ctx, hook, JS_UNDEFINED, 0, NULL); + + JS_FreeValue(ctx, hook); + if (JS_IsException(ret)) { JS_FreeValue(ctx, obj); JS_FreeValue(ctx, global); diff --git a/test/js/njs_on_exit_replace.t.js b/test/js/njs_on_exit_replace.t.js new file mode 100644 index 00000000..f005523a --- /dev/null +++ b/test/js/njs_on_exit_replace.t.js @@ -0,0 +1,24 @@ +/*--- +includes: [] +flags: [] +---*/ + +if (typeof njs == 'object' && typeof njs.on == 'function') { + (function() { + let o = {v: 'x'}; + + njs.on('exit', function() { + njs.on('exit', null); + + let a = []; + + for (let i = 0; i < 100; i++) { + a.push({i}); + } + + if (o.v !== 'x') { + throw Error('closure is lost'); + } + }); + })(); +} -- 2.47.3 From 549ee59ac3772ca5f3c4b824369d59c0dbfd7bca Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Wed, 11 Nov 2026 17:36:24 -0800 Subject: [PATCH 02/16] 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. --- nginx/t/js_exit.t | 20 ++++++++++++-- src/qjs.c | 68 +++++++++++++++++++++++++++++++---------------- src/qjs.h | 1 + 3 files changed, 64 insertions(+), 25 deletions(-) diff --git a/nginx/t/js_exit.t b/nginx/t/js_exit.t index c89eb090..4655a94c 100644 --- a/nginx/t/js_exit.t +++ b/nginx/t/js_exit.t @@ -51,6 +51,11 @@ http { location /test { js_content test.test; } + + location /replaced { + js_context_reuse 0; + js_content test.replaced; + } } } @@ -68,6 +73,14 @@ $t->write_file('test.js', < ngx.log(ngx.WARN, "replaced exit hook")); + + globalThis.njs = {}; + + r.return(200, 'replaced'); + } + function bytes_sent(r) { return r.variables.bytes_sent; } @@ -80,11 +93,11 @@ $t->write_file('test.js', <try_run('no njs')->plan(4); +$t->try_run('no njs')->plan(6); ############################################################################### @@ -93,6 +106,7 @@ like(http( . 'Foo: bar' . CRLF . 'Host: localhost' . CRLF . CRLF ), qr/bs: 0/, 'response'); +like(http_get('/replaced'), qr/replaced$/, 'replaced njs response'); $t->stop(); @@ -100,6 +114,8 @@ my $error_log = $t->read_file('error.log'); like($error_log, qr/\[warn\].*exit hook: bs: \d+/, 'exit hook logged'); like($error_log, qr/\[warn\].*exit hook promise/, 'exit hook promise logged'); +like($error_log, qr/\[warn\].*replaced exit hook/, + 'exit hook with replaced njs'); like($t->read_file('access.log'), qr/\[var:\d+ header:626172 url:\/test\]/, 'access log has bytes_sent'); diff --git a/src/qjs.c b/src/qjs.c index 2ab6ed0c..8de2ebe4 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -55,6 +55,7 @@ static JSValue qjs_global_atob(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); static int qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global); +static qjs_njs_t *qjs_njs(JSContext *ctx); static JSValue qjs_njs_on(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); static void qjs_njs_mark(JSRuntime *rt, JSValueConst val, @@ -159,6 +160,12 @@ static JSClassDef qjs_njs_class = { }; +static JSClassDef qjs_njs_object_class = { + "njsObject", + .finalizer = NULL, +}; + + static JSClassDef qjs_text_decoder_class = { "TextDecoder", .finalizer = qjs_text_decoder_finalizer, @@ -352,41 +359,43 @@ qjs_chb_rt_free(void *rt, void *p) } +static qjs_njs_t * +qjs_njs(JSContext *ctx) +{ + JSValue obj; + qjs_njs_t *njs; + + obj = JS_GetClassProto(ctx, QJS_CORE_CLASS_ID_NJS_OBJECT); + njs = JS_GetOpaque(obj, QJS_CORE_CLASS_ID_NJS); + JS_FreeValue(ctx, obj); + + return njs; +} + + JSValue qjs_call_exit_hook(JSContext *ctx) { - JSValue global, obj, hook, ret; + JSValue hook, ret; qjs_njs_t *njs; - global = JS_GetGlobalObject(ctx); - - obj = JS_GetPropertyStr(ctx, global, "njs"); - if (JS_IsException(obj) || JS_IsUndefined(obj)) { - goto done; + njs = qjs_njs(ctx); + if (njs == NULL || !JS_IsFunction(ctx, njs->hooks[QJS_NJS_HOOK_EXIT])) { + return JS_UNDEFINED; } - njs = JS_GetOpaque(obj, QJS_CORE_CLASS_ID_NJS); - if (njs != NULL && JS_IsFunction(ctx, njs->hooks[QJS_NJS_HOOK_EXIT])) { - hook = njs->hooks[QJS_NJS_HOOK_EXIT]; - njs->hooks[QJS_NJS_HOOK_EXIT] = JS_UNDEFINED; - - ret = JS_Call(ctx, hook, JS_UNDEFINED, 0, NULL); + hook = njs->hooks[QJS_NJS_HOOK_EXIT]; + njs->hooks[QJS_NJS_HOOK_EXIT] = JS_UNDEFINED; - JS_FreeValue(ctx, hook); + ret = JS_Call(ctx, hook, JS_UNDEFINED, 0, NULL); - if (JS_IsException(ret)) { - JS_FreeValue(ctx, obj); - JS_FreeValue(ctx, global); - return ret; - } + JS_FreeValue(ctx, hook); - JS_FreeValue(ctx, ret); + if (JS_IsException(ret)) { + return ret; } -done: - - JS_FreeValue(ctx, obj); - JS_FreeValue(ctx, global); + JS_FreeValue(ctx, ret); return JS_UNDEFINED; } @@ -404,6 +413,17 @@ qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global) return -1; } + /* + * The class is used only to keep the njs object in its prototype + * slot, so the exit hook does not depend on the "njs" global property. + */ + + if (JS_NewClass(JS_GetRuntime(cx), QJS_CORE_CLASS_ID_NJS_OBJECT, + &qjs_njs_object_class) < 0) + { + return -1; + } + proto = JS_NewObject(cx); if (JS_IsException(proto)) { return -1; @@ -429,6 +449,8 @@ qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global) JS_SetOpaque(obj, njs); + JS_SetClassProto(cx, QJS_CORE_CLASS_ID_NJS_OBJECT, JS_DupValue(cx, obj)); + if (JS_SetPropertyStr(cx, global, "njs", obj) < 0) { return -1; } diff --git a/src/qjs.h b/src/qjs.h index e6008cc7..a24c8a80 100644 --- a/src/qjs.h +++ b/src/qjs.h @@ -35,6 +35,7 @@ enum { QJS_CORE_CLASS_ID_TEXT_DECODER, QJS_CORE_CLASS_ID_TEXT_ENCODER, QJS_CORE_CLASS_ID_NJS, + QJS_CORE_CLASS_ID_NJS_OBJECT, QJS_CORE_CLASS_ID_FS_STATS, QJS_CORE_CLASS_ID_FS_DIRENT, QJS_CORE_CLASS_ID_FS_FILEHANDLE, -- 2.47.3 From 548e5179b582e4701273c68d9be00e4627b0fd6b Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Wed, 11 Nov 2026 17:37:06 -0800 Subject: [PATCH 03/16] 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. The issue was introduced in 04f6dfb9 (0.9.2). --- nginx/ngx_js.c | 1 + nginx/t/js_teardown.t | 11 +++++++++-- src/qjs.c | 18 ++++++++++++++++++ src/qjs.h | 1 + 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/nginx/ngx_js.c b/nginx/ngx_js.c index a7ec295e..d3ffd4bc 100644 --- a/nginx/ngx_js.c +++ b/nginx/ngx_js.c @@ -1406,6 +1406,7 @@ ngx_engine_qjs_destroy(ngx_engine_t *e, ngx_js_ctx_t *ctx, ngx_qjs_log_exception(e, ctx->log, "unhandled rejection"); } + qjs_clear_hooks(cx); ngx_qjs_clear_events(ctx); ngx_qjs_detach_ctx(ctx, cx); diff --git a/nginx/t/js_teardown.t b/nginx/t/js_teardown.t index f8c2f7ac..193bac31 100644 --- a/nginx/t/js_teardown.t +++ b/nginx/t/js_teardown.t @@ -87,6 +87,13 @@ $t->write_file('test.js', <<'EOF'); ngx.log(ngx.ERR, 'exit hook ' + r.uri); }); + } else if (mode === 'reinstall') { + njs.on('exit', () => { + Promise.resolve().then(() => { + njs.on('exit', late('reinstalled exit hook')); + }); + }); + } r.return(200, 'ok'); @@ -95,12 +102,12 @@ $t->write_file('test.js', <<'EOF'); export default {content}; EOF -$t->try_run('no njs available')->plan(9); +$t->try_run('no njs available')->plan(11); ############################################################################### for my $scope ('zero', 'reuse') { - for my $mode ('timer', 'fetch', 'exit') { + for my $mode ('timer', 'fetch', 'exit', 'reinstall') { like(http_get("/$scope?mode=$mode"), qr/ok$/, "$scope $mode"); } } diff --git a/src/qjs.c b/src/qjs.c index 8de2ebe4..43930657 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -401,6 +401,24 @@ qjs_call_exit_hook(JSContext *ctx) } +void +qjs_clear_hooks(JSContext *ctx) +{ + unsigned i; + qjs_njs_t *njs; + + njs = qjs_njs(ctx); + if (njs == NULL) { + return; + } + + for (i = 0; i < njs_nitems(njs->hooks); i++) { + JS_FreeValue(ctx, njs->hooks[i]); + njs->hooks[i] = JS_UNDEFINED; + } +} + + static int qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global) { diff --git a/src/qjs.h b/src/qjs.h index a24c8a80..4336455b 100644 --- a/src/qjs.h +++ b/src/qjs.h @@ -62,6 +62,7 @@ typedef struct { JSContext *qjs_new_context(JSRuntime *rt, qjs_module_t **addons); JSValue qjs_call_exit_hook(JSContext *ctx); +void qjs_clear_hooks(JSContext *ctx); void *qjs_chb_ctx_alloc(void *ctx, size_t size); void qjs_chb_ctx_free(void *ctx, void *p); void *qjs_chb_rt_alloc(void *rt, size_t size); -- 2.47.3 From 640d5ab8154e45bf5db65d16c93a3ba202c651b2 Mon Sep 17 00:00:00 2001 From: basavaraj-sm05 Date: Wed, 12 Aug 2026 20:37:30 +0530 Subject: [PATCH 04/16] 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. --- src/njs_buffer.c | 98 ++++++++++++------ src/qjs_buffer.c | 213 ++++++++++++++++++++++++--------------- src/test/njs_unit_test.c | 4 + test/buffer.t.js | 57 ++++++++++- 4 files changed, 259 insertions(+), 113 deletions(-) diff --git a/src/njs_buffer.c b/src/njs_buffer.c index 5bdab1a7..39448741 100644 --- a/src/njs_buffer.c +++ b/src/njs_buffer.c @@ -674,41 +674,36 @@ njs_value_buffer_get(njs_vm_t *vm, njs_value_t *value, njs_str_t *dst) } +static njs_int_t +njs_buffer_range_arg(njs_vm_t *vm, const njs_value_t *value, uint64_t *num) +{ + if (!njs_is_defined(value)) { + return NJS_OK; + } + + return njs_value_to_index(vm, njs_value_arg(value), num); +} + + static njs_int_t njs_buffer_array_range(njs_vm_t *vm, njs_typed_array_t *array, - const njs_value_t *start, const njs_value_t *end, const char *name, + uint64_t num_start, uint64_t num_end, const char *name, uint8_t **out_start, uint8_t **out_end) { - uint64_t num_start, num_end; - njs_int_t ret; njs_array_buffer_t *buffer; - num_start = 0; - if (njs_slow_path(njs_is_detached_buffer(array->buffer))) { njs_type_error(vm, "detached buffer"); return NJS_ERROR; } - if (njs_is_defined(start)) { - ret = njs_value_to_index(vm, njs_value_arg(start), &num_start); - if (njs_slow_path(ret != NJS_OK)) { - return ret; - } - } - if (num_start > array->byte_length) { njs_range_error(vm, "\"%sStart\" is out of range: %L", name, num_start); return NJS_ERROR; } - num_end = array->byte_length; - - if (njs_is_defined(end)) { - ret = njs_value_to_index(vm, njs_value_arg(end), &num_end); - if (njs_slow_path(ret != NJS_OK)) { - return ret; - } + if (num_end == UINT64_MAX) { + num_end = array->byte_length; } if (num_end > array->byte_length) { @@ -736,6 +731,8 @@ njs_buffer_compare_array(njs_vm_t *vm, njs_value_t *val1, njs_value_t *val2, { size_t size, src_size, trg_size; uint8_t *src, *src_end, *trg, *trg_end; + uint64_t num_target_start, num_target_end, num_source_start, + num_source_end; njs_int_t ret; njs_typed_array_t *source, *target; @@ -749,14 +746,39 @@ njs_buffer_compare_array(njs_vm_t *vm, njs_value_t *val1, njs_value_t *val2, return NJS_ERROR; } - ret = njs_buffer_array_range(vm, target, target_start, target_end, "target", - &trg, &trg_end); + num_target_start = 0; + num_target_end = UINT64_MAX; + num_source_start = 0; + num_source_end = UINT64_MAX; + + ret = njs_buffer_range_arg(vm, target_start, &num_target_start); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_range_arg(vm, target_end, &num_target_end); if (njs_slow_path(ret != NJS_OK)) { return ret; } - ret = njs_buffer_array_range(vm, source, source_start, source_end, "source", - &src, &src_end); + ret = njs_buffer_range_arg(vm, source_start, &num_source_start); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_range_arg(vm, source_end, &num_source_end); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_array_range(vm, target, num_target_start, num_target_end, + "target", &trg, &trg_end); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_array_range(vm, source, num_source_start, num_source_end, + "source", &src, &src_end); if (njs_slow_path(ret != NJS_OK)) { return ret; } @@ -2022,6 +2044,7 @@ njs_buffer_prototype_copy(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, { size_t size; uint8_t *src, *src_end, *trg, *trg_end; + uint64_t num_target_start, num_source_start, num_source_end; njs_int_t ret; njs_value_t *val1, *val2; njs_typed_array_t *source, *target; @@ -2040,16 +2063,21 @@ njs_buffer_prototype_copy(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, return NJS_ERROR; } - ret = njs_buffer_array_range(vm, target, njs_arg(args, nargs, 2), - &njs_value_undefined, "target", &trg, - &trg_end); + num_target_start = 0; + num_source_start = 0; + num_source_end = UINT64_MAX; + + ret = njs_buffer_range_arg(vm, njs_arg(args, nargs, 2), &num_target_start); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_range_arg(vm, njs_arg(args, nargs, 3), &num_source_start); if (njs_slow_path(ret != NJS_OK)) { return ret; } - ret = njs_buffer_array_range(vm, source, njs_arg(args, nargs, 3), - njs_arg(args, nargs, 4), "source", &src, - &src_end); + ret = njs_buffer_range_arg(vm, njs_arg(args, nargs, 4), &num_source_end); if (njs_slow_path(ret != NJS_OK)) { return ret; } @@ -2059,6 +2087,18 @@ njs_buffer_prototype_copy(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, return NJS_ERROR; } + ret = njs_buffer_array_range(vm, target, num_target_start, UINT64_MAX, + "target", &trg, &trg_end); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + + ret = njs_buffer_array_range(vm, source, num_source_start, num_source_end, + "source", &src, &src_end); + if (njs_slow_path(ret != NJS_OK)) { + return ret; + } + size = njs_min(trg_end - trg, src_end - src); if (!njs_memory_overlaps(trg, size, src, size)) { diff --git a/src/qjs_buffer.c b/src/qjs_buffer.c index c21e835b..79175e40 100644 --- a/src/qjs_buffer.c +++ b/src/qjs_buffer.c @@ -731,31 +731,28 @@ qjs_buffer_is_encoding(JSContext *ctx, JSValueConst this_val, } -static JSValue -qjs_buffer_array_range(JSContext *ctx, njs_str_t *array, JSValueConst start, - JSValueConst end, const char *name) +static int +qjs_buffer_range_arg(JSContext *ctx, JSValueConst value, int64_t *num) { - int64_t num_start, num_end; + if (JS_IsUndefined(value)) { + return 0; + } - num_start = 0; + return JS_ToInt64(ctx, num, value); +} - if (!JS_IsUndefined(start)) { - if (JS_ToInt64(ctx, &num_start, start)) { - return JS_EXCEPTION; - } - } +static JSValue +qjs_buffer_array_range(JSContext *ctx, njs_str_t *array, int64_t num_start, + int64_t num_end, const char *name) +{ if (num_start < 0 || (size_t) num_start > array->length) { return JS_ThrowRangeError(ctx, "\"%sStart\" is out of range: %" PRId64, name, num_start); } - num_end = array->length; - - if (!JS_IsUndefined(end)) { - if (JS_ToInt64(ctx, &num_end, end)) { - return JS_EXCEPTION; - } + if (num_end == INT64_MAX) { + num_end = array->length; } if (num_end < 0 || (size_t) num_end > array->length) { @@ -782,8 +779,31 @@ qjs_buffer_compare_array(JSContext *ctx, JSValue val1, JSValue val2, int rc; size_t size; JSValue ret; + int64_t num_source_start, num_source_end, num_target_start, + num_target_end; njs_str_t src, target; + num_source_start = 0; + num_source_end = INT64_MAX; + num_target_start = 0; + num_target_end = INT64_MAX; + + if (qjs_buffer_range_arg(ctx, source_start, &num_source_start)) { + return JS_EXCEPTION; + } + + if (qjs_buffer_range_arg(ctx, source_end, &num_source_end)) { + return JS_EXCEPTION; + } + + if (qjs_buffer_range_arg(ctx, target_start, &num_target_start)) { + return JS_EXCEPTION; + } + + if (qjs_buffer_range_arg(ctx, target_end, &num_target_end)) { + return JS_EXCEPTION; + } + ret = qjs_typed_array_data(ctx, val1, &src); if (JS_IsException(ret)) { return ret; @@ -794,13 +814,14 @@ qjs_buffer_compare_array(JSContext *ctx, JSValue val1, JSValue val2, return ret; } - ret = qjs_buffer_array_range(ctx, &src, source_start, source_end, "source"); + ret = qjs_buffer_array_range(ctx, &src, num_source_start, num_source_end, + "source"); if (JS_IsException(ret)) { return ret; } - ret = qjs_buffer_array_range(ctx, &target, target_start, target_end, - "target"); + ret = qjs_buffer_array_range(ctx, &target, num_target_start, + num_target_end, "target"); if (JS_IsException(ret)) { return ret; } @@ -839,8 +860,25 @@ qjs_buffer_prototype_copy(JSContext *ctx, JSValueConst this_val, int argc, { size_t size; JSValue ret; + int64_t num_target_start, num_source_start, num_source_end; njs_str_t src, target; + num_target_start = 0; + num_source_start = 0; + num_source_end = INT64_MAX; + + if (qjs_buffer_range_arg(ctx, argv[1], &num_target_start)) { + return JS_EXCEPTION; + } + + if (qjs_buffer_range_arg(ctx, argv[2], &num_source_start)) { + return JS_EXCEPTION; + } + + if (qjs_buffer_range_arg(ctx, argv[3], &num_source_end)) { + return JS_EXCEPTION; + } + ret = qjs_typed_array_data(ctx, this_val, &src); if (JS_IsException(ret)) { return ret; @@ -851,12 +889,14 @@ qjs_buffer_prototype_copy(JSContext *ctx, JSValueConst this_val, int argc, return ret; } - ret = qjs_buffer_array_range(ctx, &target, argv[1], JS_UNDEFINED, "target"); + ret = qjs_buffer_array_range(ctx, &target, num_target_start, INT64_MAX, + "target"); if (JS_IsException(ret)) { return ret; } - ret = qjs_buffer_array_range(ctx, &src, argv[2], argv[3], "source"); + ret = qjs_buffer_array_range(ctx, &src, num_source_start, num_source_end, + "source"); if (JS_IsException(ret)) { return ret; } @@ -965,9 +1005,27 @@ qjs_buffer_prototype_index_of(JSContext *ctx, JSValueConst this_val, int argc, JSValue ret, buffer, encode, value; int64_t from, to, increment, length, i; uint32_t byte; + njs_bool_t has_from; njs_str_t self, str; const qjs_buffer_encoding_t *encoding; + from = 0; + has_from = 0; + encode = argv[2]; + + if (!JS_IsUndefined(argv[1])) { + if (JS_IsString(argv[0]) && JS_IsString(argv[1])) { + encode = argv[1]; + + } else { + if (JS_ToInt64(ctx, &from, argv[1])) { + return JS_EXCEPTION; + } + + has_from = 1; + } + } + ret = qjs_typed_array_data(ctx, this_val, &self); if (JS_IsException(ret)) { return ret; @@ -976,34 +1034,22 @@ qjs_buffer_prototype_index_of(JSContext *ctx, JSValueConst this_val, int argc, length = self.length; if (last) { - from = length - 1; to = -1; increment = -1; } else { - from = 0; to = length; increment = 1; } - encode = argv[2]; - - if (!JS_IsUndefined(argv[1])) { - if (JS_IsString(argv[0]) && JS_IsString(argv[1])) { - encode = argv[1]; - goto encoding; - } + if (!has_from) { + from = last ? length - 1 : 0; - if (JS_ToInt64(ctx, &from, argv[1])) { - return JS_EXCEPTION; - } - - if (from >= 0) { - from = njs_min(from, length); + } else if (from >= 0) { + from = njs_min(from, length); - } else { - from = njs_max(0, length + from); - } + } else { + from = njs_max(0, length + from); } if (JS_IsNumber(argv[0])) { @@ -1024,8 +1070,6 @@ qjs_buffer_prototype_index_of(JSContext *ctx, JSValueConst this_val, int argc, return JS_NewInt32(ctx, -1); } -encoding: - buffer = JS_UNDEFINED; value = argv[0]; @@ -1097,15 +1141,15 @@ qjs_buffer_prototype_read_float(JSContext *ctx, JSValueConst this_val, njs_conv_f32_t conv_f32; njs_conv_f64_t conv_f64; + if (JS_ToIndex(ctx, &index, argv[0])) { + return JS_EXCEPTION; + } + ret = qjs_typed_array_data(ctx, this_val, &self); if (JS_IsException(ret)) { return ret; } - if (JS_ToIndex(ctx, &index, argv[0])) { - return JS_EXCEPTION; - } - size = magic >> 2; if (size + index > self.length) { @@ -1159,11 +1203,6 @@ qjs_buffer_prototype_read_int(JSContext *ctx, JSValueConst this_val, njs_str_t self; njs_bool_t little, swap, sign; - ret = qjs_typed_array_data(ctx, this_val, &self); - if (JS_IsException(ret)) { - return ret; - } - if (JS_ToIndex(ctx, &index, argv[0])) { return JS_EXCEPTION; } @@ -1185,6 +1224,11 @@ qjs_buffer_prototype_read_int(JSContext *ctx, JSValueConst this_val, } } + ret = qjs_typed_array_data(ctx, this_val, &self); + if (JS_IsException(ret)) { + return ret; + } + if (size + index > self.length) { return JS_ThrowRangeError(ctx, "index %" PRIu64 " is outside the bound" " of the buffer", index); @@ -1357,7 +1401,9 @@ qjs_buffer_prototype_to_json(JSContext *ctx, JSValueConst this_val, int argc, } for (i = 0; i < src.length; i++) { - rc = JS_SetPropertyUint32(ctx, data, i, JS_NewInt32(ctx, src.start[i])); + rc = JS_DefinePropertyValueUint32(ctx, data, i, + JS_NewInt32(ctx, src.start[i]), + JS_PROP_C_W_E); if (rc == -1) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; @@ -1426,31 +1472,30 @@ qjs_buffer_prototype_to_string(JSContext *ctx, JSValueConst this_val, njs_str_t src, data; const qjs_buffer_encoding_t *encoding; - ret = qjs_typed_array_data(ctx, this_val, &src); - if (JS_IsException(ret)) { - return JS_ThrowTypeError(ctx, "method toString() called on incompatible" - " object"); - } - start = 0; - end = src.length; + end = UINT64_MAX; if (!JS_IsUndefined(argv[1])) { if (JS_ToIndex(ctx, &start, argv[1])) { return JS_EXCEPTION; } - - start = njs_min(start, src.length); } if (!JS_IsUndefined(argv[2])) { if (JS_ToIndex(ctx, &end, argv[2])) { return JS_EXCEPTION; } + } - end = njs_min(end, src.length); + ret = qjs_typed_array_data(ctx, this_val, &src); + if (JS_IsException(ret)) { + return JS_ThrowTypeError(ctx, "method toString() called on incompatible" + " object"); } + start = njs_min(start, src.length); + end = njs_min(end, src.length); + if (start >= end) { src.length = 0; @@ -1503,13 +1548,8 @@ qjs_buffer_prototype_write(JSContext *ctx, JSValueConst this_val, const uint8_t *p, *end, *prev; const qjs_buffer_encoding_t *encoding; - ret = qjs_typed_array_data(ctx, this_val, &self); - if (JS_IsException(ret)) { - return ret; - } - offset = 0; - max_length = self.length; + max_length = UINT64_MAX; encode = argv[3]; if (!JS_IsUndefined(argv[1])) { @@ -1521,8 +1561,6 @@ qjs_buffer_prototype_write(JSContext *ctx, JSValueConst this_val, if (JS_ToIndex(ctx, &offset, argv[1])) { return JS_EXCEPTION; } - - max_length = self.length - offset; } if (!JS_IsUndefined(argv[2])) { @@ -1538,6 +1576,11 @@ qjs_buffer_prototype_write(JSContext *ctx, JSValueConst this_val, write: + ret = qjs_typed_array_data(ctx, this_val, &self); + if (JS_IsException(ret)) { + return ret; + } + encoding = qjs_buffer_encoding(ctx, encode, 1); if (encoding == NULL) { return JS_EXCEPTION; @@ -1555,6 +1598,10 @@ write: return JS_ThrowRangeError(ctx, "\"offset\" is out of range"); } + if (max_length == UINT64_MAX) { + max_length = self.length - offset; + } + if (src.length == 0) { JS_FreeValue(ctx, buffer); return JS_NewInt32(ctx, 0); @@ -1601,11 +1648,6 @@ qjs_buffer_prototype_write_int(JSContext *ctx, JSValueConst this_val, njs_str_t self; njs_bool_t little, swap, sign; - ret = qjs_typed_array_data(ctx, this_val, &self); - if (JS_IsException(ret)) { - return ret; - } - if (JS_ToIndex(ctx, &index, argv[1])) { return JS_EXCEPTION; } @@ -1623,6 +1665,15 @@ qjs_buffer_prototype_write_int(JSContext *ctx, JSValueConst this_val, } } + if (JS_ToInt64(ctx, &i64, argv[0])) { + return JS_EXCEPTION; + } + + ret = qjs_typed_array_data(ctx, this_val, &self); + if (JS_IsException(ret)) { + return ret; + } + if (size + index > self.length) { return JS_ThrowRangeError(ctx, "index %" PRIu64 " is outside the bound" " of the buffer", index); @@ -1636,10 +1687,6 @@ qjs_buffer_prototype_write_int(JSContext *ctx, JSValueConst this_val, swap = !swap; #endif - if (JS_ToInt64(ctx, &i64, argv[0])) { - return JS_EXCEPTION; - } - switch (size) { case 1: if (sign) { @@ -1814,11 +1861,6 @@ qjs_buffer_prototype_write_float(JSContext *ctx, JSValueConst this_val, njs_conv_f32_t conv_f32; njs_conv_f64_t conv_f64; - ret = qjs_typed_array_data(ctx, this_val, &self); - if (JS_IsException(ret)) { - return ret; - } - if (JS_ToFloat64(ctx, &v, argv[0])) { return JS_EXCEPTION; } @@ -1827,6 +1869,11 @@ qjs_buffer_prototype_write_float(JSContext *ctx, JSValueConst this_val, return JS_EXCEPTION; } + ret = qjs_typed_array_data(ctx, this_val, &self); + if (JS_IsException(ret)) { + return ret; + } + size = magic >> 2; if (size + index > self.length) { diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index e70beff9..88c71ceb 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -22130,6 +22130,10 @@ static njs_unit_test_t njs_externals_test[] = { njs_str("new Uint8Array($r.buffer.sort().slice(0,3))"), njs_str("129,144,145") }, + { njs_str("var b = $r.buffer; " + "[Buffer.from('@#').copy(b, 4), $r.buffer[4], b[4]]"), + njs_str("2,208,64") }, + { njs_str("var b = $r.buffer; " "var v = new DataView(b.buffer, b.byteOffset);" "v.setUint8(0, '@'.codePointAt(0));" diff --git a/test/buffer.t.js b/test/buffer.t.js index 21fdedfd..6e957d45 100644 --- a/test/buffer.t.js +++ b/test/buffer.t.js @@ -211,6 +211,44 @@ let concatRevalidate_tsuite = { }; +let detachCoercion_tsuite = { + name: "Buffer detach during argument coercion tests", + skip: () => (!has_buffer() || !is_detach_available()), + T: async (params) => { + let b = Buffer.alloc(16); + let o = Buffer.alloc(16); + let d = (buf, v) => ({ valueOf() { detach(buf.buffer); return v; } }); + + try { + params.run(b, o, d); + + } catch (e) { + if (e instanceof TypeError) { + return 'SUCCESS'; + } + + throw e; + } + + throw Error('detached buffer was not detected'); + }, + + tests: [ + { run: (b, o, d) => b.readUInt32LE(d(b, 0)) }, + { run: (b, o, d) => b.readFloatLE(d(b, 0)) }, + { run: (b, o, d) => b.writeUInt32LE(d(b, 1), 0) }, + { run: (b, o, d) => b.writeFloatLE(1, d(b, 0)) }, + { run: (b, o, d) => b.write('a', d(b, 0)) }, + { run: (b, o, d) => b.toString('utf8', d(b, 0)) }, + { run: (b, o, d) => b.indexOf(1, d(b, 0)) }, + { run: (b, o, d) => b.compare(o, d(b, 0)) }, + { run: (b, o, d) => b.compare(o, 0, 16, d(o, 0)) }, + { run: (b, o, d) => b.copy(o, d(b, 0)) }, + { run: (b, o, d) => b.copy(o, 0, d(o, 0)) }, + ], +}; + + let compare_tsuite = { name: "Buffer.compare() tests", skip: () => (!has_buffer()), @@ -990,7 +1028,21 @@ let toJSON_tsuite = { name: "Buffer.toJSON() tests", skip: () => (!has_buffer()), T: async (params) => { - let r = Buffer.from(params.value).toJSON(); + let b = Buffer.from(params.value); + + if (params.detach) { + Object.defineProperty(Array.prototype, '0', { configurable: true, + set() { detach(b.buffer); } }); + } + + let r; + + try { + r = b.toJSON(); + + } finally { + delete Array.prototype[0]; + } if (!compare_object(r, params.expected)) { throw Error(`unexpected output "${JSON.stringify(r)}" != "${JSON.stringify(params.expected)}"`); @@ -1003,6 +1055,8 @@ let toJSON_tsuite = { { value: '', expected: { type: 'Buffer', data: [] } }, { value: 'αβγ', expected: { type: 'Buffer', data: [0xCE, 0xB1, 0xCE, 0xB2, 0xCE, 0xB3] } }, { value: new Uint8Array([0xff, 0xde, 0xba]), expected: { type: 'Buffer', data: [0xFF, 0xDE, 0xBA] } }, + { value: 'ab', detach: true, skip: () => !is_detach_available(), + expected: { type: 'Buffer', data: [0x61, 0x62] } }, ], }; @@ -1188,6 +1242,7 @@ run([ byteLength_tsuite, concat_tsuite, concatRevalidate_tsuite, + detachCoercion_tsuite, compare_tsuite, comparePrototype_tsuite, copy_tsuite, -- 2.47.3 From 418184c28e11c6e72171969cc417b94a60647466 Mon Sep 17 00:00:00 2001 From: basavaraj-sm05 Date: Tue, 22 Sep 2026 19:40:16 +0530 Subject: [PATCH 05/16] 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. --- nginx/ngx_http_js_module.c | 15 +++++++++++++-- nginx/ngx_js_fetch.c | 4 ++-- nginx/ngx_js_http.c | 2 +- nginx/ngx_js_http.h | 2 +- nginx/ngx_qjs_fetch.c | 4 ++-- nginx/t/js_internal_redirect.t | 7 ++++++- nginx/t/js_subrequests.t | 28 ++++++++++++++++++++++++++-- 7 files changed, 51 insertions(+), 11 deletions(-) diff --git a/nginx/ngx_http_js_module.c b/nginx/ngx_http_js_module.c index ad9649ff..4f9ac9b2 100644 --- a/nginx/ngx_http_js_module.c +++ b/nginx/ngx_http_js_module.c @@ -1853,6 +1853,12 @@ ngx_http_js_internal_redirect(ngx_http_request_t *r, ngx_http_js_ctx_t *ctx) return NGX_HTTP_INTERNAL_SERVER_ERROR; } + if (ngx_js_check_no_space_or_ctrl_chars(args.data, args.len) != NGX_OK) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "unsafe URI arguments were detected"); + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + return ngx_http_internal_redirect(r, &ctx->redirect_uri, &args); } @@ -7902,7 +7908,9 @@ ngx_http_qjs_ext_subrequest(JSContext *cx, JSValueConst this_val, flags = NGX_HTTP_LOG_UNSAFE; - if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK) { + if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK + || ngx_js_check_no_space_or_ctrl_chars(args.data, args.len) != NGX_OK) + { return JS_ThrowTypeError(cx, "unsafe uri"); } @@ -10421,7 +10429,10 @@ ngx_http_js_parse_unsafe_uri(ngx_http_request_t *r, njs_str_t *uri, args_arg.data = args->start; args_arg.len = args->length; - if (ngx_http_parse_unsafe_uri(r, &uri_arg, &args_arg, &flags) != NGX_OK) { + if (ngx_http_parse_unsafe_uri(r, &uri_arg, &args_arg, &flags) != NGX_OK + || ngx_js_check_no_space_or_ctrl_chars(args_arg.data, args_arg.len) + != NGX_OK) + { return NGX_ERROR; } diff --git a/nginx/ngx_js_fetch.c b/nginx/ngx_js_fetch.c index 91ad5d5f..ad786d4a 100644 --- a/nginx/ngx_js_fetch.c +++ b/nginx/ngx_js_fetch.c @@ -642,7 +642,7 @@ ngx_js_ext_fetch(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, resolve_host = &u.host; } - if (ngx_js_check_request_line_component(u.uri.data, u.uri.len) != NGX_OK) { + if (ngx_js_check_no_space_or_ctrl_chars(u.uri.data, u.uri.len) != NGX_OK) { njs_vm_type_error(vm, "invalid url"); goto fail; } @@ -923,7 +923,7 @@ ngx_js_method_process(njs_vm_t *vm, ngx_js_request_t *request) str.length = request->method.len; if (request->method.len == 0 - || ngx_js_check_request_line_component(request->method.data, + || ngx_js_check_no_space_or_ctrl_chars(request->method.data, request->method.len) != NGX_OK) { diff --git a/nginx/ngx_js_http.c b/nginx/ngx_js_http.c index 7fc02993..b6a2de09 100644 --- a/nginx/ngx_js_http.c +++ b/nginx/ngx_js_http.c @@ -1883,7 +1883,7 @@ ngx_js_check_header_name(u_char *name, size_t len) ngx_int_t -ngx_js_check_request_line_component(u_char *value, size_t len) +ngx_js_check_no_space_or_ctrl_chars(u_char *value, size_t len) { u_char *p, *end; diff --git a/nginx/ngx_js_http.h b/nginx/ngx_js_http.h index 939c5ed4..564bbfd9 100644 --- a/nginx/ngx_js_http.h +++ b/nginx/ngx_js_http.h @@ -191,7 +191,7 @@ void ngx_js_http_trim(u_char **value, size_t *len, int trim_c0_control_or_space); void ngx_js_http_trim_ows(u_char **value, size_t *len); ngx_int_t ngx_js_check_header_name(u_char *name, size_t len); -ngx_int_t ngx_js_check_request_line_component(u_char *value, size_t len); +ngx_int_t ngx_js_check_no_space_or_ctrl_chars(u_char *value, size_t len); ngx_int_t ngx_js_check_header_value(u_char *value, size_t len); const char *ngx_js_headers_error(ngx_js_headers_rc_t rc); ngx_js_headers_rc_t ngx_js_headers_modify(ngx_pool_t *pool, diff --git a/nginx/ngx_qjs_fetch.c b/nginx/ngx_qjs_fetch.c index ef3a9274..84fee7f2 100644 --- a/nginx/ngx_qjs_fetch.c +++ b/nginx/ngx_qjs_fetch.c @@ -422,7 +422,7 @@ ngx_qjs_ext_fetch(JSContext *cx, JSValueConst this_val, int argc, resolve_host = &u.host; } - if (ngx_js_check_request_line_component(u.uri.data, u.uri.len) != NGX_OK) { + if (ngx_js_check_no_space_or_ctrl_chars(u.uri.data, u.uri.len) != NGX_OK) { JS_ThrowTypeError(cx, "invalid url"); goto fail; } @@ -1383,7 +1383,7 @@ ngx_qjs_method_process(JSContext *cx, ngx_js_request_t *request) }; if (request->method.len == 0 - || ngx_js_check_request_line_component(request->method.data, + || ngx_js_check_no_space_or_ctrl_chars(request->method.data, request->method.len) != NGX_OK) { diff --git a/nginx/t/js_internal_redirect.t b/nginx/t/js_internal_redirect.t index 721113bb..277babdc 100644 --- a/nginx/t/js_internal_redirect.t +++ b/nginx/t/js_internal_redirect.t @@ -82,6 +82,9 @@ $t->write_file('test.js', <try_run('no njs available')->plan(5); +$t->try_run('no njs available')->plan(6); ############################################################################### @@ -117,6 +120,8 @@ like(http_get('/test?unsafe=1'), qr/500 Internal Server/s, 'unsafe redirect'); like(http_get('/test?quoted=1'), qr/200 .*redirect/s, 'quoted redirect'); +like(http_get('/test?decoded=A%0d%0aInjected:%201'), qr/500 Internal Server/s, + 'unsafe redirect args'); get('/destroyed_ctx', 'If-Match: tt'); ############################################################################### diff --git a/nginx/t/js_subrequests.t b/nginx/t/js_subrequests.t index eaabf7cd..208210c2 100644 --- a/nginx/t/js_subrequests.t +++ b/nginx/t/js_subrequests.t @@ -161,6 +161,14 @@ http { js_content test.sr_unsafe; } + location /sr_unsafe_args { + js_content test.sr_unsafe_args; + } + + location /sr_unsafe_uri_args { + js_content test.sr_unsafe_uri_args; + } + location /sr_broken { js_content test.sr_broken; } @@ -422,6 +430,16 @@ $t->write_file('test.js', < { r.return(200, JSON.stringify({code:reply.status})); @@ -545,13 +563,14 @@ $t->write_file('test.js', <write_file('t', '["SEE-THIS"]'); -$t->try_run('no njs available')->plan(35); +$t->try_run('no njs available')->plan(37); $t->run_daemon(\&http_daemon); ############################################################################### @@ -615,6 +634,11 @@ like(http_get('/sr_unsafe'), qr/500/s, 'unsafe subrequest uri'); } +like(http_get('/sr_unsafe_args?a=x%0d%0aInjected:%201'), qr/500/s, + 'unsafe subrequest args'); +like(http_get('/sr_unsafe_uri_args?a=x%0d%0aInjected:%201'), qr/500/s, + 'unsafe subrequest uri args'); + TODO: { local $TODO = 'not yet' unless has_version('0.8.5'); -- 2.47.3 From 91ecb9f01510861e77d982d89afcb7daa3e59345 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Fri, 13 Nov 2026 18:32:10 -0800 Subject: [PATCH 06/16] 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. The issue was introduced in 29271d0a (0.4.3). --- src/njs_utf16.c | 12 ++++++----- src/njs_utf16.h | 1 + src/test/unicode_unit_test.c | 39 +++++++++++++++++++++++++++++++++++- 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/njs_utf16.c b/src/njs_utf16.c index b47fbf50..a3085e52 100644 --- a/src/njs_utf16.c +++ b/src/njs_utf16.c @@ -54,9 +54,9 @@ njs_utf16_decode(njs_unicode_decode_t *ctx, const u_char **start, uint32_t unit; unsigned lead; - if (ctx->upper != 0x00) { - lead = ctx->upper - 0x01; - ctx->upper = 0x00; + if (ctx->need != 0x00) { + lead = ctx->upper; + ctx->need = 0x00; goto lead_state; } @@ -66,7 +66,8 @@ pair_state: lead = *(*start)++; if (*start >= end) { - ctx->upper = lead + 0x01; + ctx->upper = lead; + ctx->need = 0x01; return NJS_UNICODE_CONTINUE; } @@ -89,7 +90,8 @@ lead_state: (*start)--; - ctx->upper = lead + 0x01; + ctx->upper = lead; + ctx->need = 0x01; ctx->codepoint = 0x00; return NJS_UNICODE_ERROR; diff --git a/src/njs_utf16.h b/src/njs_utf16.h index b5675586..d05a8175 100644 --- a/src/njs_utf16.h +++ b/src/njs_utf16.h @@ -17,6 +17,7 @@ NJS_EXPORT uint32_t njs_utf16_decode(njs_unicode_decode_t *ctx, njs_inline void njs_utf16_decode_init(njs_unicode_decode_t *ctx) { + ctx->need = 0x00; ctx->upper = 0x00; ctx->codepoint = 0x00; } diff --git a/src/test/unicode_unit_test.c b/src/test/unicode_unit_test.c index 35416ea1..6d8540ec 100644 --- a/src/test/unicode_unit_test.c +++ b/src/test/unicode_unit_test.c @@ -211,7 +211,7 @@ utf16_unit_test() { int8_t length, length_to; u_char *start, *end, *end_to; - uint32_t cp, i; + uint32_t cp, i, j; njs_unicode_decode_t ctx; u_char buf[8], to[4]; @@ -263,6 +263,43 @@ utf16_unit_test() njs_printf("utf16 test decode-encode failed\n"); return NJS_ERROR; } + + njs_utf16_decode_init(&ctx); + start = buf; + + for (j = 0; j < (uint32_t) length; j++) { + cp = njs_utf16_decode(&ctx, (const u_char **) &start, start + 1); + + if (cp != (j + 1 == (uint32_t) length ? i : NJS_UNICODE_CONTINUE)) { + njs_printf("utf16 test byte decoding failed for %05uXD\n", i); + return NJS_ERROR; + } + } + + start = to; + (void) njs_utf16_encode(0xD800, &start, end_to); + + njs_utf16_decode_init(&ctx); + start = to; + + cp = njs_utf16_decode(&ctx, (const u_char **) &start, to + 2); + if (cp != NJS_UNICODE_CONTINUE) { + njs_printf("utf16 test pending surrogate failed\n"); + return NJS_ERROR; + } + + start = buf; + cp = njs_utf16_decode(&ctx, (const u_char **) &start, buf + length); + if (cp != NJS_UNICODE_ERROR || start != buf + 1) { + njs_printf("utf16 test unpaired surrogate failed for %05uXD\n", i); + return NJS_ERROR; + } + + cp = njs_utf16_decode(&ctx, (const u_char **) &start, buf + length); + if (cp != i || start != buf + length) { + njs_printf("utf16 test rereading code point failed for %05uXD\n", i); + return NJS_ERROR; + } } /* Surrogate pair. */ -- 2.47.3 From aeb779b531822b917984f5b741c918d4cc4d338a Mon Sep 17 00:00:00 2001 From: basavaraj-sm05 Date: Thu, 1 Oct 2026 21:28:25 +0000 Subject: [PATCH 07/16] 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. The issue was introduced in 98c26163 (0.4.3). Co-authored-by: Dmitry Volyntsev --- src/njs_string.c | 44 +++++++++++++++++++++++++--------------- src/test/njs_unit_test.c | 30 +++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 16 deletions(-) diff --git a/src/njs_string.c b/src/njs_string.c index 9a601e26..d25a4684 100644 --- a/src/njs_string.c +++ b/src/njs_string.c @@ -1469,7 +1469,7 @@ njs_string_from_char_code(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, njs_index_t is_point, njs_value_t *retval) { double num; - u_char *p, *start, *end; + u_char *p, *start, *end, *last; ssize_t len; int32_t code; uint32_t cp; @@ -1515,18 +1515,25 @@ njs_string_from_char_code(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, len = njs_utf16_encode(code, &start, end); start = buf; - cp = njs_utf16_decode(&ctx, (const u_char **) &start, start + len); + last = buf + len; - if (cp > NJS_UNICODE_MAX_CODEPOINT) { - if (cp == NJS_UNICODE_CONTINUE) { - continue; + /* An unpaired leading surrogate leaves a unit to be reread. */ + + do { + cp = njs_utf16_decode(&ctx, (const u_char **) &start, last); + + if (cp > NJS_UNICODE_MAX_CODEPOINT) { + if (cp == NJS_UNICODE_CONTINUE) { + break; + } + + cp = NJS_UNICODE_REPLACEMENT; } - cp = NJS_UNICODE_REPLACEMENT; - } + size += njs_utf8_size(cp); + length++; - size += njs_utf8_size(cp); - length++; + } while (start < last); } if (cp == NJS_UNICODE_CONTINUE) { @@ -1553,17 +1560,22 @@ njs_string_from_char_code(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, len = njs_utf16_encode(code, &start, end); start = buf; - cp = njs_utf16_decode(&ctx, (const u_char **) &start, start + len); + last = buf + len; - if (cp > NJS_UNICODE_MAX_CODEPOINT) { - if (cp == NJS_UNICODE_CONTINUE && i + 1 != nargs) { - continue; + do { + cp = njs_utf16_decode(&ctx, (const u_char **) &start, last); + + if (cp > NJS_UNICODE_MAX_CODEPOINT) { + if (cp == NJS_UNICODE_CONTINUE && i + 1 != nargs) { + break; + } + + cp = NJS_UNICODE_REPLACEMENT; } - cp = NJS_UNICODE_REPLACEMENT; - } + p = njs_utf8_encode(p, cp); - p = njs_utf8_encode(p, cp); + } while (start < last); } return NJS_OK; diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index 88c71ceb..acbcfb6e 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -9366,6 +9366,24 @@ static njs_unit_test_t njs_test[] = { njs_str("String.fromCharCode(0xD83D) + String.fromCharCode(0xDCA9)"), njs_str("��") }, + { njs_str("String.fromCharCode(0xD83D, 0x41)"), + njs_str("�A") }, + + { njs_str("String.fromCharCode(0xD83D, 0x41, 0x42)"), + njs_str("�AB") }, + + { njs_str("String.fromCharCode(0xD83D, 0x41, 0x42).length"), + njs_str("3") }, + + { njs_str("String.fromCharCode(0xD83D, 0x41, 0xD83D)"), + njs_str("�A�") }, + + { njs_str("String.fromCharCode(0xD83D, 0xD83D)"), + njs_str("��") }, + + { njs_str("String.fromCharCode(0xD83D, 0xD83D, 0xDCA9)"), + njs_str("�💩") }, + { njs_str("String.fromCodePoint(65 + 65536)"), njs_str("𐁁") }, @@ -9381,6 +9399,18 @@ static njs_unit_test_t njs_test[] = { njs_str("String.fromCodePoint(0xD83D).length"), njs_str("1") }, + { njs_str("String.fromCodePoint(0xD83D, 0x41, 0x42)"), + njs_str("�AB") }, + + { njs_str("String.fromCodePoint(0xD83D, 0x1F4A9)"), + njs_str("�💩") }, + + { njs_str("String.fromCodePoint(0xD83D, 0x1F4A9, 0x42)"), + njs_str("�💩B") }, + + { njs_str("String.fromCodePoint(0xD83D, 0x1F4A9, 0xD83D)"), + njs_str("�💩�") }, + { njs_str("String.fromCharCode(2**53 + 10)"), njs_str("\n") }, -- 2.47.3 From 2786bd98a5363849f5641b624469251800e677f0 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Fri, 13 Nov 2026 18:37:35 -0800 Subject: [PATCH 08/16] 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). --- external/njs_query_string_module.c | 14 ++++++++++---- external/qjs_query_string_module.c | 14 ++++++++++---- nginx/ngx_http_js_module.c | 14 ++++++++++---- nginx/t/js_args.t | 14 +++++++++++++- src/njs_utf8.h | 10 ++++++++-- test/querystring.t.mjs | 13 +++++++++++++ 6 files changed, 64 insertions(+), 15 deletions(-) diff --git a/external/njs_query_string_module.c b/external/njs_query_string_module.c index c5b4d58a..94267317 100644 --- a/external/njs_query_string_module.c +++ b/external/njs_query_string_module.c @@ -127,6 +127,7 @@ njs_query_string_decode(njs_vm_t *vm, njs_value_t *value, const u_char *start, u_char *dst; uint32_t cp; njs_int_t ret; + njs_bool_t consumed; njs_chb_t chain; const u_char *p, *end; njs_unicode_decode_t ctx; @@ -162,13 +163,18 @@ njs_query_string_decode(njs_vm_t *vm, njs_value_t *value, const u_char *start, while (p < end) { if (*p == '%' && end - p > 2 && hex[p[1]] >= 0 && hex[p[2]] >= 0) { - cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]]); - p += 3; + cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]], + &consumed); + if (consumed) { + p += 3; + } } else { if (*p == '+') { - cp = ' '; - p++; + cp = njs_utf8_consume(&ctx, ' ', &consumed); + if (consumed) { + p++; + } } else { cp = njs_utf8_decode(&ctx, &p, end); diff --git a/external/qjs_query_string_module.c b/external/qjs_query_string_module.c index 128a17cd..b3b429b2 100644 --- a/external/qjs_query_string_module.c +++ b/external/qjs_query_string_module.c @@ -172,6 +172,7 @@ qjs_query_string_decode(JSContext *cx, const u_char *start, size_t size) { u_char *dst; uint32_t cp; + njs_bool_t consumed; njs_chb_t chain; const u_char *p, *end; njs_unicode_decode_t ctx; @@ -207,13 +208,18 @@ qjs_query_string_decode(JSContext *cx, const u_char *start, size_t size) while (p < end) { if (*p == '%' && end - p > 2 && hex[p[1]] >= 0 && hex[p[2]] >= 0) { - cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]]); - p += 3; + cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]], + &consumed); + if (consumed) { + p += 3; + } } else { if (*p == '+') { - cp = ' '; - p++; + cp = njs_utf8_consume(&ctx, ' ', &consumed); + if (consumed) { + p++; + } } else { cp = njs_utf8_decode(&ctx, &p, end); diff --git a/nginx/ngx_http_js_module.c b/nginx/ngx_http_js_module.c index 4f9ac9b2..2b7109ed 100644 --- a/nginx/ngx_http_js_module.c +++ b/nginx/ngx_http_js_module.c @@ -6120,6 +6120,7 @@ ngx_http_qjs_query_string_decode(njs_chb_t *chain, const u_char *start, { u_char *dst; uint32_t cp; + njs_bool_t consumed; const u_char *p, *end; njs_unicode_decode_t ctx; @@ -6153,13 +6154,18 @@ ngx_http_qjs_query_string_decode(njs_chb_t *chain, const u_char *start, while (p < end) { if (*p == '%' && end - p > 2 && hex[p[1]] >= 0 && hex[p[2]] >= 0) { - cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]]); - p += 3; + cp = njs_utf8_consume(&ctx, (hex[p[1]] << 4) | hex[p[2]], + &consumed); + if (consumed) { + p += 3; + } } else { if (*p == '+') { - cp = ' '; - p++; + cp = njs_utf8_consume(&ctx, ' ', &consumed); + if (consumed) { + p++; + } } else { cp = njs_utf8_decode(&ctx, &p, end); diff --git a/nginx/t/js_args.t b/nginx/t/js_args.t index bb5cf4ff..0adfddd8 100644 --- a/nginx/t/js_args.t +++ b/nginx/t/js_args.t @@ -94,7 +94,7 @@ $t->write_file('test.js', <try_run('no njs')->plan(15); +$t->try_run('no njs')->plan(20); ############################################################################### @@ -145,6 +145,18 @@ is(get_json('/object?a=%6&b=%&c=%%&d=%zz'), '{"a":"%6","b":"%","c":"%%","d":"%zz"}', 'values percent-encoded broken object'); +is(get_json('/object?%D8%41%42=%E2%82%41%42'), + qq/{"\x{fffd}AB":"\x{fffd}AB"}/, + 'percent-encoded units after invalid UTF-8'); +is(get_json('/object?a=%D8+%41'), qq/{"a":"\x{fffd} A"}/, + 'plus after invalid UTF-8'); +is(get_json('/object?a=%E2%82+'), qq/{"a":"\x{fffd} "}/, + 'final plus after invalid UTF-8'); +is(get_json('/object?a=%D8%C2%A2'), qq/{"a":"\x{fffd}\x{a2}"}/, + 'valid UTF-8 after invalid UTF-8'); +is(get_json('/object?a=%ED%A0%80'), qq/{"a":"\x{fffd}\x{fffd}\x{fffd}"}/, + 'UTF-8 encoded surrogate'); + ############################################################################### sub has_version { diff --git a/src/njs_utf8.h b/src/njs_utf8.h index 5f2f81e2..7386b4b7 100644 --- a/src/njs_utf8.h +++ b/src/njs_utf8.h @@ -27,13 +27,19 @@ NJS_EXPORT njs_bool_t njs_utf8_is_valid(const u_char *p, size_t len); njs_inline uint32_t -njs_utf8_consume(njs_unicode_decode_t *ctx, u_char byte) +njs_utf8_consume(njs_unicode_decode_t *ctx, u_char byte, njs_bool_t *consumed) { + uint32_t cp; const u_char *p; p = &byte; - return njs_utf8_decode(ctx, &p, p + 1); + cp = njs_utf8_decode(ctx, &p, p + 1); + + /* An error may leave the byte to be decoded again. */ + *consumed = (p != &byte); + + return cp; } diff --git a/test/querystring.t.mjs b/test/querystring.t.mjs index 8ea14050..d9ebc0a3 100644 --- a/test/querystring.t.mjs +++ b/test/querystring.t.mjs @@ -117,6 +117,13 @@ let parse_tsuite = { { value: 'baz=%F', expected: { baz:'%F' } }, { value: 'baz=%', expected: { baz:'%' } }, { value: 'ba+z=f+uz', expected: { 'ba z':'f uz' } }, + { value: '%D8%41%42=%E2%82%41%42', + expected: { '�AB':'�AB' } }, + { value: 'baz=%D8+%41', expected: { baz:'� A' } }, + { value: 'baz=%E2%82+', expected: { baz:'� ' } }, + { value: 'baz=%D8%C2%A2', expected: { baz:'�¢' } }, + { value: 'baz=%D8%F0%9F%92%A9', expected: { baz:'�💩' } }, + { value: 'baz=%ED%A0%80', expected: { baz:'���' } }, { value: 'X=' + 'α'.repeat(33), expected: { X:'α'.repeat(33) } }, { value: 'X=' + 'α1'.repeat(33), expected: { X:'α1'.repeat(33) } }, @@ -214,6 +221,12 @@ let unescape_tsuite = { { value: '', expected: '' }, { value: 'baz%3Dfuz', expected: 'baz=fuz' }, { value: 'abc%CE%B1def', expected: 'abcαdef' }, + { value: '%D8%41%42', expected: '�AB' }, + { value: '%E2%41%42', expected: '�AB' }, + { value: '%E2%82%41%42', expected: '�AB' }, + { value: '%D8%C2%A2', expected: '�¢' }, + { value: '%D8%F0%9F%92%A9', expected: '�💩' }, + { value: '%ED%A0%80', expected: '���' }, ]}; run([ -- 2.47.3 From 8edb36aa0979c54e57d033cd73dc10dab6f98713 Mon Sep 17 00:00:00 2001 From: Dean Chen <862469039@qq.com> Date: Sun, 15 Nov 2026 06:19:24 +0500 Subject: [PATCH 09/16] 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. This closes #1158 issue on GitHub. --- src/njs_parser.c | 2 +- src/test/njs_unit_test.c | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/njs_parser.c b/src/njs_parser.c index 0fd63bbb..53c132d4 100644 --- a/src/njs_parser.c +++ b/src/njs_parser.c @@ -8878,7 +8878,7 @@ njs_parser_escape_string_calc_length(njs_parser_t *parser, src++; hex_length = 0; - hex_end = end; + hex_end = (end - src > 7) ? src + 7 : end; goto hex; diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index acbcfb6e..be382b3e 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -8696,6 +8696,12 @@ static njs_unit_test_t njs_test[] = { njs_str("'\\u{a00000}'"), njs_str("SyntaxError: Invalid Unicode code point \"\\u{a00000}\"") }, + { njs_str("'\\u{11111111111111110}'"), + njs_str("SyntaxError: Invalid Unicode code point \"\\u{11111111111111110}\"") }, + + { njs_str("`\\u{11111111111111110`"), + njs_str("SyntaxError: Invalid Unicode code point \"\\u{11111111111111110\"") }, + { njs_str("'\\x61'"), njs_str("a") }, -- 2.47.3 From c1fc7f03160ca0a710066a2054c983a7732f2db3 Mon Sep 17 00:00:00 2001 From: basavaraj-sm05 Date: Sun, 15 Nov 2026 20:02:00 +0530 Subject: [PATCH 10/16] 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). --- src/njs_encoding.c | 31 +++++++++++++------ src/njs_utf8.h | 27 +++++++++++++---- src/qjs.c | 36 +++++++++++++++------- test/text_decoder.t.js | 68 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 25 deletions(-) diff --git a/src/njs_encoding.c b/src/njs_encoding.c index 6cd298ea..5135d02d 100644 --- a/src/njs_encoding.c +++ b/src/njs_encoding.c @@ -17,6 +17,8 @@ typedef struct { njs_encoding_t encoding; njs_bool_t fatal; njs_bool_t ignore_bom; + njs_bool_t bom_seen; + njs_bool_t stream; njs_unicode_decode_t ctx; } njs_encoding_decode_t; @@ -332,6 +334,8 @@ njs_text_decoder_constructor(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } njs_utf8_decode_init(&data->ctx); + data->bom_seen = 0; + data->stream = 0; njs_set_data(&decoder->value, data, NJS_DATA_TAG_TEXT_DECODER); njs_set_object_value(retval, decoder); @@ -491,10 +495,10 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, size_t size; ssize_t length; njs_int_t ret; - njs_bool_t stream; + njs_bool_t stream, bom_seen; njs_value_t *this, *value, *options; const u_char *start, *end; - njs_unicode_decode_t ctx; + njs_unicode_decode_t ctx, next; njs_encoding_decode_t *data; const njs_typed_array_t *array; const njs_array_buffer_t *buffer; @@ -560,17 +564,27 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, data = njs_object_data(this); + if (!data->stream) { + njs_utf8_decode_init(&data->ctx); + data->bom_seen = 0; + } + + data->stream = stream; ctx = data->ctx; + bom_seen = data->bom_seen; /* Looking for BOM. */ - if (start != NULL && !data->ignore_bom) { - start += njs_utf8_bom(start, end); + if (!data->ignore_bom && !bom_seen) { + bom_seen = njs_utf8_bom(&ctx, &start, end); } - length = njs_utf8_stream_length(&ctx, start, end - start, !stream, + next = ctx; + + length = njs_utf8_stream_length(&next, start, end - start, !stream, data->fatal, &size); if (length == -1) { + data->ctx = next; njs_type_error(vm, "The encoded data was not valid"); return NJS_ERROR; } @@ -580,11 +594,10 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, return NJS_ERROR; } - (void) njs_utf8_stream_encode(&data->ctx, start, end, dst, !stream, 0); + (void) njs_utf8_stream_encode(&ctx, start, end, dst, !stream, 0); - if (!stream) { - njs_utf8_decode_init(&data->ctx); - } + data->ctx = ctx; + data->bom_seen = bom_seen; return NJS_OK; } diff --git a/src/njs_utf8.h b/src/njs_utf8.h index 7386b4b7..87908bbf 100644 --- a/src/njs_utf8.h +++ b/src/njs_utf8.h @@ -149,18 +149,33 @@ njs_utf8_length(const u_char *p, size_t len) } -njs_inline size_t -njs_utf8_bom(const u_char *start, const u_char *end) +njs_inline njs_bool_t +njs_utf8_bom(njs_unicode_decode_t *ctx, const u_char **start, + const u_char *end) { - if (start + 3 > end) { + uint32_t cp; + const u_char *p; + njs_unicode_decode_t next; + + if (*start == end) { + return 0; + } + + next = *ctx; + p = *start; + + cp = njs_utf8_decode(&next, &p, end); + + if (cp == NJS_UNICODE_CONTINUE) { return 0; } - if (start[0] == 0xEF && start[1] == 0xBB && start[2] == 0xBF) { - return 3; + if (cp == NJS_UNICODE_BOM) { + *ctx = next; + *start = p; } - return 0; + return 1; } diff --git a/src/qjs.c b/src/qjs.c index 43930657..ccbf8865 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -34,6 +34,8 @@ typedef struct { qjs_encoding_t encoding; int fatal; int ignore_bom; + int bom_seen; + int stream; njs_unicode_decode_t ctx; } qjs_text_decoder_t; @@ -891,7 +893,7 @@ static JSValue qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, JSValueConst *argv) { - int stream; + int stream, bom_seen; size_t size; u_char *dst; JSValue ret; @@ -899,7 +901,7 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, njs_str_t data; const u_char *end; qjs_text_decoder_t *td; - njs_unicode_decode_t ctx; + njs_unicode_decode_t ctx, next; td = JS_GetOpaque(this_val, QJS_CORE_CLASS_ID_TEXT_DECODER); if (td == NULL) { @@ -923,17 +925,28 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, JS_FreeValue(cx, ret); } - ctx = td->ctx; end = data.start + data.length; - if (data.start != NULL && !td->ignore_bom) { - data.start += njs_utf8_bom(data.start, end); + if (!td->stream) { + njs_utf8_decode_init(&td->ctx); + td->bom_seen = 0; + } + + td->stream = stream; + ctx = td->ctx; + bom_seen = td->bom_seen; + + if (!td->ignore_bom && !bom_seen) { + bom_seen = njs_utf8_bom(&ctx, (const u_char **) &data.start, end); } - length = njs_utf8_stream_length(&ctx, data.start, end - data.start, !stream, - td->fatal, &size); + next = ctx; + + length = njs_utf8_stream_length(&next, data.start, end - data.start, + !stream, td->fatal, &size); if (length == -1) { + td->ctx = next; return JS_ThrowTypeError(cx, "The encoded data was not valid"); } @@ -943,15 +956,18 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, return JS_EXCEPTION; } - (void) njs_utf8_stream_encode(&td->ctx, data.start, end, dst, !stream, 0); + (void) njs_utf8_stream_encode(&ctx, data.start, end, dst, !stream, 0); ret = JS_NewStringLen(cx, (const char *) dst, size); js_free(cx, dst); - if (!stream) { - njs_utf8_decode_init(&td->ctx); + if (JS_IsException(ret)) { + return ret; } + td->ctx = ctx; + td->bom_seen = bom_seen; + return ret; } diff --git a/test/text_decoder.t.js b/test/text_decoder.t.js index eaf7e191..737adadc 100644 --- a/test/text_decoder.t.js +++ b/test/text_decoder.t.js @@ -58,6 +58,20 @@ let stream_tsuite = { expected: ['', '', '𠮷'] }, { chunks: [new Uint8Array([0xF0, 0xA0]), new Uint8Array([])], expected: ['', '�'] }, + // BOM is ignored only at the start of the stream + { chunks: [new Uint8Array([0x41]), + new Uint8Array([0xEF, 0xBB, 0xBF, 0x42])], + expected: ['A', '\uFEFFB'] }, + { chunks: [new Uint8Array([0xEF, 0xBB, 0xBF]), + new Uint8Array([0xEF, 0xBB, 0xBF, 0x42])], + expected: ['', '\uFEFFB'] }, + { chunks: [new Uint8Array([0xEF]), new Uint8Array([0xBB, 0xBF, 0x43])], + expected: ['', 'C'] }, + { chunks: [new Uint8Array([0xEF, 0xBB]), new Uint8Array([0xBF]), + new Uint8Array([0x44])], + expected: ['', '', 'D'] }, + { chunks: [new Uint8Array([0xEF, 0xBB]), new Uint8Array([0x45])], + expected: ['', '�E'] }, { chunks: [''], exception: 'TypeError: TypeError: not a TypedArray' }, ], @@ -105,6 +119,59 @@ let fatal_tsuite = { ], }; +let reuse_tsuite = { + name: "TextDecoder() reuse tests", + T: async (params) => { + let td = new TextDecoder('utf-8', params.opts || {fatal: true}); + let chunks = []; + + for (let i = 0; i < params.chunks.length; i++) { + try { + chunks.push(td.decode(new Uint8Array(params.chunks[i]), + {stream: params.stream[i]})); + } catch (e) { + if (!e.toString().startsWith('TypeError:')) { + throw e; + } + + chunks.push(null); + } + } + + if (!compareArray(chunks, params.expected)) { + throw Error(`unexpected output ${JSON.stringify(chunks)}`); + } + + return 'SUCCESS'; + }, + + tests: [ + { chunks: [[0xFF], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [false, false], expected: [null, 'A'] }, + { chunks: [[0xFF], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [true, false], expected: [null, 'A'] }, + { chunks: [[0x41, 0xFF], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [true, false], expected: [null, 'A'] }, + { chunks: [[0xEF, 0xBB, 0xBF, 0xFF], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [true, false], expected: [null, 'A'] }, + { chunks: [[0xEF], [0xBB, 0xBF, 0xFF], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [true, true, false], expected: ['', null, 'A'] }, + { chunks: [[0x41], [0xFF], [0xEF, 0xBB, 0xBF, 0x42]], + stream: [true, false, false], expected: ['A', null, 'B'] }, + { chunks: [[0x41], [0xFF], [0xEF, 0xBB, 0xBF, 0x42]], + stream: [true, true, false], expected: ['A', null, '\uFEFFB'] }, + { chunks: [[0xEF, 0xBB], [], [0xEF, 0xBB, 0xBF, 0x41]], + stream: [true, false, false], expected: ['', null, 'A'] }, + { chunks: [[0xEF, 0xBB, 0xBF, 0x41], [0xEF, 0xBB, 0xBF, 0x42]], + stream: [false, false], expected: ['A', 'B'] }, + { chunks: [[], [0xEF], [], [0xBB], [0xBF], []], + stream: [true, true, true, true, true, false], + expected: ['', '', '', '', '', ''] }, + { chunks: [[0xEF], [0xBB], [0xBF]], opts: {ignoreBOM: true}, + stream: [true, true, false], expected: ['', '', '\uFEFF'] }, + ], +}; + let ignoreBOM_tsuite = { name: "TextDecoder() ignoreBOM tests", T: async (params) => { @@ -166,6 +233,7 @@ let detached_tsuite = { run([ stream_tsuite, fatal_tsuite, + reuse_tsuite, ignoreBOM_tsuite, detached_tsuite, ]) -- 2.47.3 From 6e2028d12a6385b70945ca8714f2fdd8a2620798 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Sun, 15 Nov 2026 17:37:21 -0800 Subject: [PATCH 11/16] 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). --- src/njs_encoding.c | 34 +++++++++++++++++----------------- src/qjs.c | 10 +++++----- test/text_decoder.t.js | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/njs_encoding.c b/src/njs_encoding.c index 5135d02d..26dd816f 100644 --- a/src/njs_encoding.c +++ b/src/njs_encoding.c @@ -515,6 +515,23 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, return NJS_ERROR; } + if (nargs > 2) { + options = njs_argument(args, 2); + + if (njs_slow_path(!njs_is_object(options))) { + njs_type_error(vm, "The \"options\" argument must be " + "of type object"); + return NJS_ERROR; + } + + ret = njs_value_property(vm, options, NJS_ATOM_STRING_stream, retval); + if (njs_slow_path(ret == NJS_ERROR)) { + return ret; + } + + stream = njs_bool(retval); + } + if (njs_fast_path(nargs > 1)) { value = njs_argument(args, 1); @@ -545,23 +562,6 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } } - if (nargs > 2) { - options = njs_argument(args, 2); - - if (njs_slow_path(!njs_is_object(options))) { - njs_type_error(vm, "The \"options\" argument must be " - "of type object"); - return NJS_ERROR; - } - - ret = njs_value_property(vm, options, NJS_ATOM_STRING_stream, retval); - if (njs_slow_path(ret == NJS_ERROR)) { - return ret; - } - - stream = njs_bool(retval); - } - data = njs_object_data(this); if (!data->stream) { diff --git a/src/qjs.c b/src/qjs.c index ccbf8865..7d70d13b 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -908,11 +908,6 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, return JS_ThrowTypeError(cx, "'this' is not a TextDecoder"); } - ret = qjs_typed_array_data(cx, argv[0], &data); - if (JS_IsException(ret)) { - return ret; - } - stream = 0; if (argc > 1) { @@ -925,6 +920,11 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, JS_FreeValue(cx, ret); } + ret = qjs_typed_array_data(cx, argv[0], &data); + if (JS_IsException(ret)) { + return ret; + } + end = data.start + data.length; if (!td->stream) { diff --git a/test/text_decoder.t.js b/test/text_decoder.t.js index 737adadc..b4ac551c 100644 --- a/test/text_decoder.t.js +++ b/test/text_decoder.t.js @@ -229,6 +229,41 @@ let detached_tsuite = { ], }; +let detached_options_tsuite = { + name: "TextDecoder() detach in options test", + skip: () => !is_detach_available(), + + T: async (params) => { + let td = new TextDecoder('utf-8'); + let uint8 = new Uint8Array(4096); + let input = params.buffer ? uint8.buffer : uint8; + let options = { + get stream() { + detach(uint8.buffer); + return false; + } + }; + + try { + td.decode(input, options); + + } catch (e) { + if (e.toString().startsWith('TypeError:')) { + return 'SUCCESS'; + } + + throw e; + } + + throw Error('Expected TypeError not thrown'); + }, + + tests: [ + { buffer: false }, + { buffer: true }, + ], +}; + run([ stream_tsuite, @@ -236,5 +271,6 @@ run([ reuse_tsuite, ignoreBOM_tsuite, detached_tsuite, + detached_options_tsuite, ]) .then($DONE, $DONE); -- 2.47.3 From a574881b8bac41e1ac137de4bafe6d05452ce792 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Sun, 15 Nov 2026 17:39:43 -0800 Subject: [PATCH 12/16] 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). --- src/njs_encoding.c | 8 ++++---- src/qjs.c | 13 +++++++++---- test/text_decoder.t.js | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/njs_encoding.c b/src/njs_encoding.c index 26dd816f..1be139a5 100644 --- a/src/njs_encoding.c +++ b/src/njs_encoding.c @@ -515,9 +515,9 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, return NJS_ERROR; } - if (nargs > 2) { - options = njs_argument(args, 2); + options = njs_arg(args, nargs, 2); + if (!njs_is_null_or_undefined(options)) { if (njs_slow_path(!njs_is_object(options))) { njs_type_error(vm, "The \"options\" argument must be " "of type object"); @@ -532,9 +532,9 @@ njs_text_decoder_decode(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, stream = njs_bool(retval); } - if (njs_fast_path(nargs > 1)) { - value = njs_argument(args, 1); + value = njs_arg(args, nargs, 1); + if (njs_fast_path(!njs_is_undefined(value))) { if (njs_is_typed_array(value)) { array = njs_typed_array(value); if (njs_slow_path(njs_is_detached_buffer(array->buffer))) { diff --git a/src/qjs.c b/src/qjs.c index 7d70d13b..3f64aedd 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -910,7 +910,7 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, stream = 0; - if (argc > 1) { + if (argc > 1 && !JS_IsNullOrUndefined(argv[1])) { ret = JS_GetPropertyStr(cx, argv[1], "stream"); if (JS_IsException(ret)) { return JS_EXCEPTION; @@ -920,9 +920,14 @@ qjs_text_decoder_decode(JSContext *cx, JSValueConst this_val, int argc, JS_FreeValue(cx, ret); } - ret = qjs_typed_array_data(cx, argv[0], &data); - if (JS_IsException(ret)) { - return ret; + data.start = NULL; + data.length = 0; + + if (!JS_IsUndefined(argv[0])) { + ret = qjs_typed_array_data(cx, argv[0], &data); + if (JS_IsException(ret)) { + return ret; + } } end = data.start + data.length; diff --git a/test/text_decoder.t.js b/test/text_decoder.t.js index b4ac551c..9b152e2d 100644 --- a/test/text_decoder.t.js +++ b/test/text_decoder.t.js @@ -172,6 +172,37 @@ let reuse_tsuite = { ], }; +let args_tsuite = { + name: "TextDecoder() optional arguments tests", + T: async (params) => { + let td = new TextDecoder('utf-8'); + let r = params.prefix ? td.decode(params.prefix, {stream: true}) : ''; + + r += td.decode.apply(td, params.args); + + if (params.exception) { + return `expected ${params.exception} not thrown`; + } + + if (r !== params.expected) { + throw Error(`unexpected output "${r}" != "${params.expected}"`); + } + + return 'SUCCESS'; + }, + + tests: [ + { args: [], expected: '' }, + { args: [undefined], expected: '' }, + { args: [new Uint8Array([0x41]), undefined], expected: 'A' }, + { args: [new Uint8Array([0x41]), null], expected: 'A' }, + { prefix: new Uint8Array([0xE2, 0x82]), args: [], expected: '\uFFFD' }, + { prefix: new Uint8Array([0xE2]), + args: [undefined, {stream: true}], expected: '' }, + { args: [null], exception: 'TypeError' }, + ], +}; + let ignoreBOM_tsuite = { name: "TextDecoder() ignoreBOM tests", T: async (params) => { @@ -269,6 +300,7 @@ run([ stream_tsuite, fatal_tsuite, reuse_tsuite, + args_tsuite, ignoreBOM_tsuite, detached_tsuite, detached_options_tsuite, -- 2.47.3 From 0852c7113209fe65a22904affab2b407cc7b2a96 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Fri, 13 Nov 2026 15:20:47 -0800 Subject: [PATCH 13/16] 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. --- .github/scripts/nginx-ci.sh | 2 +- .github/workflows/cli.yml | 2 +- external/njs_crypto_module.c | 14 +++++------ external/njs_fs_module.c | 10 ++++---- external/njs_shell.c | 14 +++++------ external/njs_webcrypto_module.c | 2 +- external/njs_xml_module.c | 18 +++++++-------- external/njs_zlib_module.c | 16 ++++++------- external/qjs_crypto_module.c | 22 +++++++++--------- external/qjs_fs_module.c | 6 ++--- external/qjs_webcrypto_module.c | 2 +- external/qjs_xml_module.c | 18 +++++++-------- external/qjs_zlib_module.c | 18 +++++++-------- nginx/ngx_http_js_module.c | 36 ++++++++++++++--------------- nginx/ngx_js.c | 14 +++++------ nginx/ngx_js_fetch.c | 8 +++---- nginx/ngx_js_shared_dict.c | 2 +- nginx/ngx_qjs_fetch.c | 6 ++--- nginx/ngx_stream_js_module.c | 6 ++--- src/qjs.c | 41 ++++++++++++++++++++++++++++++++- src/qjs.h | 1 + test/fs/readdir.t.mjs | 2 +- test/zlib.t.mjs | 2 +- 23 files changed, 151 insertions(+), 111 deletions(-) diff --git a/.github/scripts/nginx-ci.sh b/.github/scripts/nginx-ci.sh index 52722bc4..3f6c1b06 100644 --- a/.github/scripts/nginx-ci.sh +++ b/.github/scripts/nginx-ci.sh @@ -27,7 +27,7 @@ prepare() { make -C quickjs -j"$(nproc)" libquickjs.a ;; quickjs-ng) - git clone --branch v0.16.2 --depth=1 \ + git clone --branch v0.18.0 --depth=1 \ https://github.com/quickjs-ng/quickjs quickjs-ng CFLAGS="$cc_opt -fPIC" LDFLAGS="$ld_opt" \ meson setup quickjs-ng/build quickjs-ng \ diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index bd2ff9fe..3eff693a 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -79,7 +79,7 @@ jobs: - name: Build QuickJS-NG if: matrix.engine == 'quickjs-ng' run: | - git clone --branch v0.16.2 --depth=1 \ + git clone --branch v0.18.0 --depth=1 \ https://github.com/quickjs-ng/quickjs quickjs-ng CFLAGS="$(dpkg-buildflags --get CFLAGS) -fPIC" \ LDFLAGS="$(dpkg-buildflags --get LDFLAGS)" \ diff --git a/external/njs_crypto_module.c b/external/njs_crypto_module.c index aff99b5a..deeed5a3 100644 --- a/external/njs_crypto_module.c +++ b/external/njs_crypto_module.c @@ -262,7 +262,7 @@ njs_crypto_create_hash(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, cln->data = dgst; if (EVP_DigestInit_ex(dgst->ctx, md, NULL) <= 0) { - njs_vm_internal_error(vm, "EVP_DigestInit_ex() failed"); + njs_vm_error(vm, "EVP_DigestInit_ex() failed"); return NJS_ERROR; } @@ -343,13 +343,13 @@ njs_hash_prototype_update(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, if (!hmac) { if (EVP_DigestUpdate(dgst->ctx, data.start, data.length) <= 0) { - njs_vm_internal_error(vm, "EVP_DigestUpdate() failed"); + njs_vm_error(vm, "EVP_DigestUpdate() failed"); return NJS_ERROR; } } else { if (HMAC_Update(ctx->ctx, data.start, data.length) <= 0) { - njs_vm_internal_error(vm, "HMAC_Update() failed"); + njs_vm_error(vm, "HMAC_Update() failed"); return NJS_ERROR; } } @@ -408,7 +408,7 @@ njs_hash_prototype_digest(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, if (!hmac) { if (EVP_DigestFinal_ex(dgst->ctx, digest, &len) <= 0) { - njs_vm_internal_error(vm, "EVP_DigestFinal_ex() failed"); + njs_vm_error(vm, "EVP_DigestFinal_ex() failed"); return NJS_ERROR; } @@ -417,7 +417,7 @@ njs_hash_prototype_digest(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } else { if (HMAC_Final(ctx->ctx, digest, &len) <= 0) { - njs_vm_internal_error(vm, "HMAC_Final() failed"); + njs_vm_error(vm, "HMAC_Final() failed"); return NJS_ERROR; } @@ -479,7 +479,7 @@ njs_hash_prototype_copy(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, cln->data = copy; if (EVP_MD_CTX_copy_ex(copy->ctx, dgst->ctx) <= 0) { - njs_vm_internal_error(vm, "EVP_MD_CTX_copy_ex() failed"); + njs_vm_error(vm, "EVP_MD_CTX_copy_ex() failed"); return NJS_ERROR; } @@ -556,7 +556,7 @@ njs_crypto_create_hmac(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, cln->data = ctx; if (HMAC_Init_ex(ctx->ctx, key.start, (int) key.length, md, NULL) <= 0) { - njs_vm_internal_error(vm, "HMAC_Init_ex() failed"); + njs_vm_error(vm, "HMAC_Init_ex() failed"); return NJS_ERROR; } diff --git a/external/njs_fs_module.c b/external/njs_fs_module.c index 2876c84f..2fe8e414 100644 --- a/external/njs_fs_module.c +++ b/external/njs_fs_module.c @@ -2941,7 +2941,7 @@ njs_fs_make_path(njs_vm_t *vm, char *path, mode_t md, njs_bool_t recursive, } if (njs_slow_path((p - path) > NJS_MAX_PATH)) { - njs_vm_internal_error(vm, "too large path"); + njs_vm_error(vm, "too large path"); return NJS_ERROR; } @@ -3234,8 +3234,8 @@ njs_fs_path(njs_vm_t *vm, char storage[NJS_MAX_PATH + 1], njs_value_t *src, } if (njs_slow_path(str.length > NJS_MAX_PATH - 1)) { - njs_vm_internal_error(vm, "\"%s\" is too long >= %d", prop_name, - NJS_MAX_PATH); + njs_vm_range_error(vm, "\"%s\" is too long >= %d", prop_name, + NJS_MAX_PATH); return NULL; } @@ -3520,8 +3520,8 @@ njs_fs_dirent_test(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, if (njs_slow_path(njs_value_is_number(type) && (njs_value_number(type) == NJS_DT_INVALID))) { - njs_vm_internal_error(vm, "dentry type is not supported on this " - "platform"); + njs_vm_error(vm, "dentry type is not supported on this " + "platform"); return NJS_ERROR; } diff --git a/external/njs_shell.c b/external/njs_shell.c index 044762e1..2f484040 100644 --- a/external/njs_shell.c +++ b/external/njs_shell.c @@ -1288,7 +1288,7 @@ njs_module_loader(njs_vm_t *vm, njs_external_ptr_t external, njs_str_t *name) (void) close(info.fd); if (njs_slow_path(ret != NJS_OK)) { - njs_vm_internal_error(vm, "while reading \"%V\" module", &info.file); + njs_vm_error(vm, "while reading \"%V\" module", &info.file); return NULL; } @@ -1296,8 +1296,8 @@ njs_module_loader(njs_vm_t *vm, njs_external_ptr_t external, njs_str_t *name) ret = njs_console_set_cwd(console, &info.file); if (njs_slow_path(ret != NJS_OK)) { - njs_vm_internal_error(vm, "while setting cwd for \"%V\" module", - &info.file); + njs_vm_error(vm, "while setting cwd for \"%V\" module", + &info.file); return NULL; } @@ -2688,8 +2688,8 @@ njs_qjs_module_loader(JSContext *ctx, const char *module_name, void *opaque) (void) close(info.fd); if (njs_slow_path(ret != NJS_OK)) { - JS_ThrowInternalError(ctx, "while reading \"%.*s\" module", - (int) info.file.length, info.file.start); + qjs_throw_error(ctx, "while reading \"%.*s\" module", + (int) info.file.length, info.file.start); return NULL; } @@ -2697,8 +2697,8 @@ njs_qjs_module_loader(JSContext *ctx, const char *module_name, void *opaque) ret = njs_console_set_cwd(console, &info.file); if (njs_slow_path(ret != NJS_OK)) { - JS_ThrowInternalError(ctx, "while setting cwd for \"%.*s\" module", - (int) info.file.length, info.file.start); + qjs_throw_error(ctx, "while setting cwd for \"%.*s\" module", + (int) info.file.length, info.file.start); return NULL; } diff --git a/external/njs_webcrypto_module.c b/external/njs_webcrypto_module.c index c14d9288..61b3e6c9 100644 --- a/external/njs_webcrypto_module.c +++ b/external/njs_webcrypto_module.c @@ -6034,7 +6034,7 @@ njs_webcrypto_result(njs_vm_t *vm, njs_opaque_value_t *result, njs_int_t rc, error: - njs_vm_internal_error(vm, "cannot make webcrypto result"); + njs_vm_error(vm, "cannot make webcrypto result"); return NJS_ERROR; } diff --git a/external/njs_xml_module.c b/external/njs_xml_module.c index 26c3cd1c..cacbd091 100644 --- a/external/njs_xml_module.c +++ b/external/njs_xml_module.c @@ -465,7 +465,7 @@ njs_xml_ext_parse(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, ctx = xmlNewParserCtxt(); if (njs_slow_path(ctx == NULL)) { - njs_vm_internal_error(vm, "xmlNewParserCtxt() failed"); + njs_vm_error(vm, "xmlNewParserCtxt() failed"); return NJS_ERROR; } @@ -778,7 +778,7 @@ njs_xml_node_ext_add_child(njs_vm_t *vm, njs_value_t *args, node = xmlDocCopyNode(node, current->doc, 1); if (njs_slow_path(node == NULL)) { - njs_vm_internal_error(vm, "xmlDocCopyNode() failed"); + njs_vm_error(vm, "xmlDocCopyNode() failed"); return NJS_ERROR; } @@ -812,7 +812,7 @@ njs_xml_node_ext_get_attribute_ns(njs_vm_t *vm, njs_value_t *args, text = xmlNodeGetContent((xmlNode *) attr); if (njs_slow_path(text == NULL)) { - njs_vm_internal_error(vm, "xmlNodeGetContent() failed"); + njs_vm_error(vm, "xmlNodeGetContent() failed"); return NJS_ERROR; } @@ -1127,7 +1127,7 @@ njs_xml_node_ext_text(njs_vm_t *vm, njs_object_prop_t *unused, uint32_t unused1, if (retval != NULL && setval != NULL) { text = xmlNewDocTextLen(current->doc, content.start, content.length); if (njs_slow_path(text == NULL)) { - njs_vm_internal_error(vm, "xmlNewDocTextLen() failed"); + njs_vm_error(vm, "xmlNewDocTextLen() failed"); return NJS_ERROR; } } @@ -1234,7 +1234,7 @@ njs_xml_node_attr_handler(njs_vm_t *vm, xmlNode *current, njs_str_t *name, attr = xmlSetProp(current, name_c, value); if (njs_slow_path(attr == NULL)) { - njs_vm_internal_error(vm, "xmlSetProp() failed"); + njs_vm_error(vm, "xmlSetProp() failed"); return NJS_ERROR; } @@ -1252,7 +1252,7 @@ njs_xml_attr_value(njs_vm_t *vm, xmlAttr *attr, njs_value_t *retval) text = xmlNodeGetContent((xmlNode *) attr); if (njs_slow_path(text == NULL)) { - njs_vm_internal_error(vm, "xmlNodeGetContent() failed"); + njs_vm_error(vm, "xmlNodeGetContent() failed"); return NJS_ERROR; } @@ -1452,7 +1452,7 @@ njs_xml_node_tags_handler(njs_vm_t *vm, njs_value_t *value, njs_str_t *name, node = xmlDocCopyNode(node, current->doc, 1); if (njs_slow_path(node == NULL)) { - njs_vm_internal_error(vm, "xmlDocCopyNode() failed"); + njs_vm_error(vm, "xmlDocCopyNode() failed"); goto error; } @@ -2045,7 +2045,7 @@ njs_xml_ext_canonicalization(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, buf = xmlOutputBufferCreateIO(njs_xml_buf_write_cb, NULL, &chain, NULL); if (njs_slow_path(buf == NULL)) { - njs_vm_internal_error(vm, "xmlOutputBufferCreateIO() failed"); + njs_vm_error(vm, "xmlOutputBufferCreateIO() failed"); return NJS_ERROR; } @@ -2054,7 +2054,7 @@ njs_xml_ext_canonicalization(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, prefix_list, comments, buf); if (njs_slow_path(ret < 0)) { - njs_vm_internal_error(vm, "xmlC14NExecute() failed"); + njs_vm_error(vm, "xmlC14NExecute() failed"); ret = NJS_ERROR; goto error; } diff --git a/external/njs_zlib_module.c b/external/njs_zlib_module.c index a7c0b769..4f0e072c 100644 --- a/external/njs_zlib_module.c +++ b/external/njs_zlib_module.c @@ -310,14 +310,14 @@ njs_zlib_ext_deflate(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, rc = deflateInit2(&stream, level, Z_DEFLATED, window_bits, mem_level, strategy); if (njs_slow_path(rc != Z_OK)) { - njs_vm_internal_error(vm, "deflateInit2() failed"); + njs_vm_error(vm, "deflateInit2() failed"); return NJS_ERROR; } if (dictionary.start != NULL) { rc = deflateSetDictionary(&stream, dictionary.start, dictionary.length); if (njs_slow_path(rc != Z_OK)) { - njs_vm_internal_error(vm, "deflateSetDictionary() failed"); + njs_vm_error(vm, "deflateSetDictionary() failed"); return NJS_ERROR; } } @@ -335,8 +335,8 @@ njs_zlib_ext_deflate(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, rc = deflate(&stream, Z_FINISH); if (njs_slow_path(rc < 0)) { - njs_vm_internal_error(vm, "failed to deflate the data: %s", - stream.msg); + njs_vm_error(vm, "failed to deflate the data: %s", + stream.msg); goto fail; } @@ -451,14 +451,14 @@ njs_zlib_ext_inflate(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, rc = inflateInit2(&stream, window_bits); if (njs_slow_path(rc != Z_OK)) { - njs_vm_internal_error(vm, "inflateInit2() failed"); + njs_vm_error(vm, "inflateInit2() failed"); return NJS_ERROR; } if (dictionary.start != NULL) { rc = inflateSetDictionary(&stream, dictionary.start, dictionary.length); if (njs_slow_path(rc != Z_OK)) { - njs_vm_internal_error(vm, "deflateSetDictionary() failed"); + njs_vm_error(vm, "deflateSetDictionary() failed"); return NJS_ERROR; } } @@ -476,8 +476,8 @@ njs_zlib_ext_inflate(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, rc = inflate(&stream, Z_NO_FLUSH); if (njs_slow_path(rc < 0)) { - njs_vm_internal_error(vm, "failed to inflate the compressed " - "data: %s", stream.msg); + njs_vm_error(vm, "failed to inflate the compressed " + "data: %s", stream.msg); goto fail; } diff --git a/external/qjs_crypto_module.c b/external/qjs_crypto_module.c index d1e942ac..51534d2a 100644 --- a/external/qjs_crypto_module.c +++ b/external/qjs_crypto_module.c @@ -143,7 +143,7 @@ qjs_crypto_create_hash(JSContext *cx, JSValueConst this_val, int argc, if (EVP_DigestInit_ex(dgst->ctx, md, NULL) <= 0) { njs_evp_md_ctx_free(dgst->ctx); js_free(cx, dgst); - JS_ThrowInternalError(cx, "EVP_DigestInit_ex() failed"); + qjs_throw_error(cx, "EVP_DigestInit_ex() failed"); return JS_EXCEPTION; } @@ -227,7 +227,7 @@ qjs_hash_prototype_update(JSContext *cx, JSValueConst this_val, int argc, <= 0) { js_free(cx, content.start); - JS_ThrowInternalError(cx, "EVP_DigestUpdate() failed"); + qjs_throw_error(cx, "EVP_DigestUpdate() failed"); return JS_EXCEPTION; } @@ -235,7 +235,7 @@ qjs_hash_prototype_update(JSContext *cx, JSValueConst this_val, int argc, if (HMAC_Update(hctx->ctx, content.start, content.length) <= 0) { js_free(cx, content.start); - JS_ThrowInternalError(cx, "HMAC_Update() failed"); + qjs_throw_error(cx, "HMAC_Update() failed"); return JS_EXCEPTION; } } @@ -246,14 +246,14 @@ qjs_hash_prototype_update(JSContext *cx, JSValueConst this_val, int argc, if (!hmac) { if (EVP_DigestUpdate(dgst->ctx, str.start, str.length) <= 0) { JS_FreeCString(cx, (const char *) str.start); - JS_ThrowInternalError(cx, "EVP_DigestUpdate() failed"); + qjs_throw_error(cx, "EVP_DigestUpdate() failed"); return JS_EXCEPTION; } } else { if (HMAC_Update(hctx->ctx, str.start, str.length) <= 0) { JS_FreeCString(cx, (const char *) str.start); - JS_ThrowInternalError(cx, "HMAC_Update() failed"); + qjs_throw_error(cx, "HMAC_Update() failed"); return JS_EXCEPTION; } } @@ -268,13 +268,13 @@ qjs_hash_prototype_update(JSContext *cx, JSValueConst this_val, int argc, if (!hmac) { if (EVP_DigestUpdate(dgst->ctx, bytes.start, bytes.length) <= 0) { - JS_ThrowInternalError(cx, "EVP_DigestUpdate() failed"); + qjs_throw_error(cx, "EVP_DigestUpdate() failed"); return JS_EXCEPTION; } } else { if (HMAC_Update(hctx->ctx, bytes.start, bytes.length) <= 0) { - JS_ThrowInternalError(cx, "HMAC_Update() failed"); + qjs_throw_error(cx, "HMAC_Update() failed"); return JS_EXCEPTION; } } @@ -310,7 +310,7 @@ qjs_hash_prototype_digest(JSContext *cx, JSValueConst this_val, int argc, } if (EVP_DigestFinal_ex(dgst->ctx, digest, &len) <= 0) { - JS_ThrowInternalError(cx, "EVP_DigestFinal_ex() failed"); + qjs_throw_error(cx, "EVP_DigestFinal_ex() failed"); return JS_EXCEPTION; } @@ -328,7 +328,7 @@ qjs_hash_prototype_digest(JSContext *cx, JSValueConst this_val, int argc, } if (HMAC_Final(hctx->ctx, digest, &len) <= 0) { - JS_ThrowInternalError(cx, "HMAC_Final() failed"); + qjs_throw_error(cx, "HMAC_Final() failed"); return JS_EXCEPTION; } @@ -382,7 +382,7 @@ qjs_hash_prototype_copy(JSContext *cx, JSValueConst this_val, int argc, if (EVP_MD_CTX_copy_ex(copy->ctx, dgst->ctx) <= 0) { njs_evp_md_ctx_free(copy->ctx); js_free(cx, copy); - JS_ThrowInternalError(cx, "EVP_MD_CTX_copy_ex() failed"); + qjs_throw_error(cx, "EVP_MD_CTX_copy_ex() failed"); return JS_EXCEPTION; } @@ -461,7 +461,7 @@ qjs_crypto_create_hmac(JSContext *cx, JSValueConst this_val, int argc, JS_FreeCString(cx, (const char *) key.start); } - JS_ThrowInternalError(cx, "HMAC_Init_ex() failed"); + qjs_throw_error(cx, "HMAC_Init_ex() failed"); return JS_EXCEPTION; } diff --git a/external/qjs_fs_module.c b/external/qjs_fs_module.c index 05271924..cad376cd 100644 --- a/external/qjs_fs_module.c +++ b/external/qjs_fs_module.c @@ -507,7 +507,7 @@ qjs_fs_make_path(JSContext *cx, char *path, mode_t md, int recursive) } if ((p - path) > NJS_MAX_PATH) { - JS_ThrowInternalError(cx, "too large path"); + qjs_throw_error(cx, "too large path"); return JS_EXCEPTION; } @@ -2646,8 +2646,8 @@ qjs_fs_dirent_test(JSContext *cx, JSValueConst this_val, int argc, JS_FreeValue(cx, type); if (value == QJS_DT_INVALID) { - JS_ThrowInternalError(cx, "dentry type is not supported on this " - "platform"); + qjs_throw_error(cx, "dentry type is not supported on this " + "platform"); return JS_EXCEPTION; } diff --git a/external/qjs_webcrypto_module.c b/external/qjs_webcrypto_module.c index 8adcf407..e1626cb0 100644 --- a/external/qjs_webcrypto_module.c +++ b/external/qjs_webcrypto_module.c @@ -1447,7 +1447,7 @@ qjs_export_base64url_bignum(JSContext *cx, const BIGNUM *v, size_t size) } if (njs_bn_bn2binpad(v, &buf[0], size) <= 0) { - JS_ThrowInternalError(cx, "njs_bn_bn2binpad() failed"); + qjs_throw_error(cx, "njs_bn_bn2binpad() failed"); return JS_EXCEPTION; } diff --git a/external/qjs_xml_module.c b/external/qjs_xml_module.c index bbd24760..d5621924 100644 --- a/external/qjs_xml_module.c +++ b/external/qjs_xml_module.c @@ -240,7 +240,7 @@ qjs_xml_parse(JSContext *cx, JSValueConst this_val, int argc, ctx = xmlNewParserCtxt(); if (ctx == NULL) { qjs_bytes_free(cx, &data); - JS_ThrowInternalError(cx, "xmlNewParserCtxt() failed"); + qjs_throw_error(cx, "xmlNewParserCtxt() failed"); qjs_xml_doc_free(JS_GetRuntime(cx), tree); return JS_EXCEPTION; } @@ -371,7 +371,7 @@ qjs_xml_canonicalization(JSContext *cx, JSValueConst this_val, int argc, buf = xmlOutputBufferCreateIO(qjs_xml_buf_write_cb, NULL, &chain, NULL); if (buf == NULL) { - JS_ThrowInternalError(cx, "xmlOutputBufferCreateIO() failed"); + qjs_throw_error(cx, "xmlOutputBufferCreateIO() failed"); goto fail; } @@ -382,7 +382,7 @@ qjs_xml_canonicalization(JSContext *cx, JSValueConst this_val, int argc, if (size < 0) { njs_chb_destroy(&chain); (void) xmlOutputBufferClose(buf); - JS_ThrowInternalError(cx, "xmlC14NExecute() failed"); + qjs_throw_error(cx, "xmlC14NExecute() failed"); goto fail; } @@ -723,7 +723,7 @@ qjs_xml_attr_value(JSContext *cx, xmlAttr *attr) text = xmlNodeGetContent((xmlNode *) attr); if (text == NULL) { - JS_ThrowInternalError(cx, "xmlNodeGetContent() failed"); + qjs_throw_error(cx, "xmlNodeGetContent() failed"); return JS_EXCEPTION; } @@ -780,7 +780,7 @@ qjs_xml_node_attr_modify(JSContext *cx, JSValue current, const u_char *name, attr = xmlSetProp(node->node, name, value); JS_FreeCString(cx, (char *) value); if (attr == NULL) { - JS_ThrowInternalError(cx, "xmlSetProp() failed"); + qjs_throw_error(cx, "xmlSetProp() failed"); return -1; } @@ -912,7 +912,7 @@ qjs_xml_node_tags_modify(JSContext *cx, JSValue obj, njs_str_t *name, node = xmlDocCopyNode(node, current->doc->doc, 1); JS_FreeValue(cx, v); if (node == NULL) { - JS_ThrowInternalError(cx, "xmlDocCopyNode() failed"); + qjs_throw_error(cx, "xmlDocCopyNode() failed"); goto error; } @@ -1001,7 +1001,7 @@ qjs_xml_node_text_handler(JSContext *cx, JSValue current, JSValue setval) text = xmlNewDocTextLen(node->doc->doc, content.start, content.length); JS_FreeCString(cx, (char *) content.start); if (text == NULL) { - JS_ThrowInternalError(cx, "xmlNewDocTextLen() failed"); + qjs_throw_error(cx, "xmlNewDocTextLen() failed"); return -1; } } @@ -1535,7 +1535,7 @@ qjs_xml_node_get_attribute_ns(JSContext *cx, JSValueConst this_val, text = xmlNodeGetContent((xmlNode *) attr); if (text == NULL) { - value = JS_ThrowInternalError(cx, "xmlNodeGetContent() failed"); + value = qjs_throw_error(cx, "xmlNodeGetContent() failed"); break; } @@ -1611,7 +1611,7 @@ qjs_xml_node_add_child(JSContext *cx, JSValueConst this_val, node = xmlDocCopyNode(node, current->doc->doc, 1); if (node == NULL) { - JS_ThrowInternalError(cx, "xmlDocCopyNode() failed"); + qjs_throw_error(cx, "xmlDocCopyNode() failed"); return JS_EXCEPTION; } diff --git a/external/qjs_zlib_module.c b/external/qjs_zlib_module.c index adbe3dc7..8af08c89 100644 --- a/external/qjs_zlib_module.c +++ b/external/qjs_zlib_module.c @@ -246,14 +246,14 @@ qjs_zlib_ext_deflate(JSContext *ctx, JSValueConst this_val, int argc, rc = deflateInit2(&stream, level, Z_DEFLATED, window_bits, mem_level, strategy); if (njs_slow_path(rc != Z_OK)) { - JS_ThrowInternalError(ctx, "deflateInit2() failed"); + qjs_throw_error(ctx, "deflateInit2() failed"); goto fail; } if (dictionary_copy != NULL) { rc = deflateSetDictionary(&stream, dictionary_copy, dictionary_length); if (rc != Z_OK) { - JS_ThrowInternalError(ctx, "deflateSetDictionary() failed"); + qjs_throw_error(ctx, "deflateSetDictionary() failed"); goto fail; } } @@ -269,8 +269,8 @@ qjs_zlib_ext_deflate(JSContext *ctx, JSValueConst this_val, int argc, rc = deflate(&stream, Z_FINISH); if (njs_slow_path(rc < 0)) { - JS_ThrowInternalError(ctx, "failed to deflate the data: %s", - stream.msg); + qjs_throw_error(ctx, "failed to deflate the data: %s", + stream.msg); goto fail; } @@ -422,14 +422,14 @@ qjs_zlib_ext_inflate(JSContext *ctx, JSValueConst this_val, int argc, rc = inflateInit2(&stream, window_bits); if (njs_slow_path(rc != Z_OK)) { - JS_ThrowInternalError(ctx, "inflateInit2() failed"); + qjs_throw_error(ctx, "inflateInit2() failed"); goto fail; } if (dictionary_copy != NULL) { rc = inflateSetDictionary(&stream, dictionary_copy, dictionary_length); if (rc != Z_OK) { - JS_ThrowInternalError(ctx, "inflateSetDictionary() failed"); + qjs_throw_error(ctx, "inflateSetDictionary() failed"); goto fail; } } @@ -445,8 +445,8 @@ qjs_zlib_ext_inflate(JSContext *ctx, JSValueConst this_val, int argc, rc = inflate(&stream, Z_NO_FLUSH); if (njs_slow_path(rc < 0)) { - JS_ThrowInternalError(ctx, "failed to inflate the data: %s", - stream.msg); + qjs_throw_error(ctx, "failed to inflate the data: %s", + stream.msg); goto fail; } @@ -460,7 +460,7 @@ qjs_zlib_ext_inflate(JSContext *ctx, JSValueConst this_val, int argc, rc = inflateEnd(&stream); if (njs_slow_path(rc != Z_OK)) { - JS_ThrowInternalError(ctx, "inflateEnd() failed"); + qjs_throw_error(ctx, "inflateEnd() failed"); goto fail; } diff --git a/nginx/ngx_http_js_module.c b/nginx/ngx_http_js_module.c index 2b7109ed..7e96ad5b 100644 --- a/nginx/ngx_http_js_module.c +++ b/nginx/ngx_http_js_module.c @@ -3021,14 +3021,14 @@ ngx_http_js_ext_send_header(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } if (ngx_http_set_content_type(r) != NGX_OK) { - njs_vm_internal_error(vm, "failed to set content type"); + njs_vm_error(vm, "failed to set content type"); return NJS_ERROR; } r->disable_not_modified = 1; if (ngx_http_send_header(r) == NGX_ERROR) { - njs_vm_internal_error(vm, "failed to send header"); + njs_vm_error(vm, "failed to send header"); return NJS_ERROR; } @@ -3102,7 +3102,7 @@ ngx_http_js_ext_send(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, *ll = NULL; if (ngx_http_output_filter(r, out) == NGX_ERROR) { - njs_vm_internal_error(vm, "failed to send response"); + njs_vm_error(vm, "failed to send response"); return NJS_ERROR; } @@ -3272,7 +3272,7 @@ ngx_http_js_ext_finish(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } if (ngx_http_send_special(r, NGX_HTTP_LAST) == NGX_ERROR) { - njs_vm_internal_error(vm, "failed to send response"); + njs_vm_error(vm, "failed to send response"); return NJS_ERROR; } @@ -3340,7 +3340,7 @@ ngx_http_js_ext_return(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, ctx->status = ngx_http_send_response(r, status, NULL, &cv); if (ctx->status == NGX_ERROR) { - njs_vm_internal_error(vm, "failed to send response"); + njs_vm_error(vm, "failed to send response"); return NJS_ERROR; } @@ -3585,7 +3585,7 @@ ngx_http_js_ext_get_request_body(njs_vm_t *vm, njs_object_prop_t *prop, } if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - njs_vm_internal_error(vm, "failed to read request body"); + njs_vm_error(vm, "failed to read request body"); return NJS_ERROR; } @@ -4006,7 +4006,7 @@ ngx_http_js_ext_read_request_body(njs_vm_t *vm, njs_value_t *args, resolve: if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - njs_vm_internal_error(vm, "failed to read request body"); + njs_vm_error(vm, "failed to read request body"); return NJS_ERROR; } @@ -4125,7 +4125,7 @@ ngx_http_js_ext_read_request_form(njs_vm_t *vm, njs_value_t *args, resolve: if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - njs_vm_internal_error(vm, "failed to read request body"); + njs_vm_error(vm, "failed to read request body"); return NJS_ERROR; } @@ -4995,7 +4995,7 @@ ngx_http_js_ext_subrequest(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, if (ngx_http_subrequest(r, &uri, rargs.len ? &rargs : NULL, &sr, ps, flags) != NGX_OK) { - njs_vm_internal_error(vm, "subrequest creation failed"); + njs_vm_error(vm, "subrequest creation failed"); return NJS_ERROR; } @@ -6403,7 +6403,7 @@ ngx_http_qjs_ext_finish(JSContext *cx, JSValueConst this_val, } if (ngx_http_send_special(r, NGX_HTTP_LAST) == NGX_ERROR) { - return JS_ThrowInternalError(cx, "failed to send response"); + return qjs_throw_error(cx, "failed to send response"); } ctx = ngx_http_get_module_ctx(r, ngx_http_js_module); @@ -6696,7 +6696,7 @@ ngx_http_qjs_ext_request_body(JSContext *cx, JSValueConst this_val, int type) ctx = ngx_http_get_module_ctx(r, ngx_http_js_module); if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - return JS_ThrowInternalError(cx, "failed to read request body"); + return qjs_throw_error(cx, "failed to read request body"); } body = ngx_qjs_prop(cx, buffer_type, ctx->body_read_data, @@ -6856,7 +6856,7 @@ ngx_http_qjs_ext_read_request_body(JSContext *cx, JSValueConst this_val, resolve: if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - return JS_ThrowInternalError(cx, "failed to read request body"); + return qjs_throw_error(cx, "failed to read request body"); } return ngx_http_qjs_body_to_value(cx, ctx, (ngx_uint_t) magic); @@ -7017,7 +7017,7 @@ ngx_http_qjs_ext_read_request_form(JSContext *cx, JSValueConst this_val, resolve: if (ngx_http_js_collect_body(r, ctx) != NGX_OK) { - return JS_ThrowInternalError(cx, "failed to read request body"); + return qjs_throw_error(cx, "failed to read request body"); } return ngx_http_qjs_form_to_value(cx, r, ctx, max_keys, this_val); @@ -7312,7 +7312,7 @@ ngx_http_qjs_ext_return(JSContext *cx, JSValueConst this_val, ctx->status = ngx_http_send_response(r, status, NULL, &cv); if (ctx->status == NGX_ERROR) { - return JS_ThrowInternalError(cx, "failed to send response"); + return qjs_throw_error(cx, "failed to send response"); } } else { @@ -7456,7 +7456,7 @@ ngx_http_qjs_ext_send(JSContext *cx, JSValueConst this_val, *ll = NULL; if (ngx_http_output_filter(r, out) == NGX_ERROR) { - return JS_ThrowInternalError(cx, "failed to send response"); + return qjs_throw_error(cx, "failed to send response"); } return JS_UNDEFINED; @@ -7626,13 +7626,13 @@ ngx_http_qjs_ext_send_header(JSContext *cx, JSValueConst this_val, } if (ngx_http_set_content_type(r) != NGX_OK) { - return JS_ThrowInternalError(cx, "failed to set content type"); + return qjs_throw_error(cx, "failed to set content type"); } r->disable_not_modified = 1; if (ngx_http_send_header(r) == NGX_ERROR) { - return JS_ThrowInternalError(cx, "failed to send header"); + return qjs_throw_error(cx, "failed to send header"); } return JS_UNDEFINED; @@ -7997,7 +7997,7 @@ ngx_http_qjs_ext_subrequest(JSContext *cx, JSValueConst this_val, } JS_FreeValue(cx, retval); - return JS_ThrowInternalError(cx, "subrequest creation failed"); + return qjs_throw_error(cx, "subrequest creation failed"); } if (event != NULL) { diff --git a/nginx/ngx_js.c b/nginx/ngx_js.c index d3ffd4bc..21bada94 100644 --- a/nginx/ngx_js.c +++ b/nginx/ngx_js.c @@ -1509,7 +1509,7 @@ ngx_qjs_value(JSContext *cx, const ngx_str_t *path) key = JS_NewAtomLen(cx, (char *) start, size); if (key == JS_ATOM_NULL) { JS_FreeValue(cx, value); - return JS_ThrowInternalError(cx, "could not create atom"); + return qjs_throw_error(cx, "could not create atom"); } rv = JS_GetProperty(cx, value, key); @@ -2507,8 +2507,8 @@ ngx_qjs_module_loader(JSContext *cx, const char *module_name, void *opaque) (void) close(info.fd); if (ret != NJS_OK) { - JS_ThrowInternalError(cx, "while reading \"%.*s\" module", - (int) info.file.length, info.file.start); + qjs_throw_error(cx, "while reading \"%.*s\" module", + (int) info.file.length, info.file.start); return NULL; } @@ -2542,7 +2542,7 @@ ngx_qjs_module_loader(JSContext *cx, const char *module_name, void *opaque) JS_WRITE_OBJ_BYTECODE); if (pc->code == NULL) { JS_FreeValue(cx, func_val); - JS_ThrowInternalError(cx, "could not write module bytecode"); + qjs_throw_error(cx, "could not write module bytecode"); return NULL; } @@ -4622,7 +4622,7 @@ ngx_js_module_loader(njs_vm_t *vm, njs_external_ptr_t external, njs_str_t *name) (void) close(info.fd); if (ret != NJS_OK) { - njs_vm_internal_error(vm, "while reading \"%V\" module", &info.file); + njs_vm_error(vm, "while reading \"%V\" module", &info.file); return NULL; } @@ -4630,8 +4630,8 @@ ngx_js_module_loader(njs_vm_t *vm, njs_external_ptr_t external, njs_str_t *name) ret = ngx_js_set_cwd(njs_vm_memory_pool(vm), conf, &info.file); if (ret != NJS_OK) { - njs_vm_internal_error(vm, "while setting cwd for \"%V\" module", - &info.file); + njs_vm_error(vm, "while setting cwd for \"%V\" module", + &info.file); return NULL; } diff --git a/nginx/ngx_js_fetch.c b/nginx/ngx_js_fetch.c index ad786d4a..17083f5e 100644 --- a/nginx/ngx_js_fetch.c +++ b/nginx/ngx_js_fetch.c @@ -623,7 +623,7 @@ ngx_js_ext_fetch(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, &http->proxy.url, &http->proxy.auth) != NGX_OK) { - njs_vm_internal_error(vm, "failed to evaluate proxy URL"); + njs_vm_error(vm, "failed to evaluate proxy URL"); goto fail; } @@ -664,7 +664,7 @@ ngx_js_ext_fetch(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } if (ctx == NGX_NO_RESOLVER) { - njs_vm_internal_error(vm, "no resolver defined"); + njs_vm_error(vm, "no resolver defined"); goto fail; } @@ -1163,7 +1163,7 @@ ngx_js_fetch_alloc(njs_vm_t *vm, ngx_pool_t *pool, ngx_log_t *log, failed: - njs_vm_internal_error(vm, "internal error"); + njs_vm_error(vm, "internal error"); return NULL; } @@ -1240,7 +1240,7 @@ ngx_js_fetch_promissified_result(njs_vm_t *vm, njs_value_t *result, error: - njs_vm_internal_error(vm, "internal error"); + njs_vm_error(vm, "internal error"); return NJS_ERROR; } diff --git a/nginx/ngx_js_shared_dict.c b/nginx/ngx_js_shared_dict.c index 355f4e51..ddb8617a 100644 --- a/nginx/ngx_js_shared_dict.c +++ b/nginx/ngx_js_shared_dict.c @@ -551,7 +551,7 @@ njs_js_ext_global_shared_prop(njs_vm_t *vm, njs_object_prop_t *prop, ngx_js_shared_dict_proto_id, shm_zone, 0); if (ret != NJS_OK) { - njs_vm_internal_error(vm, "sharedDict creation failed"); + njs_vm_error(vm, "sharedDict creation failed"); return NJS_ERROR; } diff --git a/nginx/ngx_qjs_fetch.c b/nginx/ngx_qjs_fetch.c index 84fee7f2..ebc46ad9 100644 --- a/nginx/ngx_qjs_fetch.c +++ b/nginx/ngx_qjs_fetch.c @@ -403,7 +403,7 @@ ngx_qjs_ext_fetch(JSContext *cx, JSValueConst this_val, int argc, &http->proxy.url, &http->proxy.auth) != NGX_OK) { - JS_ThrowInternalError(cx, "failed to evaluate proxy URL"); + qjs_throw_error(cx, "failed to evaluate proxy URL"); goto fail; } @@ -444,7 +444,7 @@ ngx_qjs_ext_fetch(JSContext *cx, JSValueConst this_val, int argc, } if (rs == NGX_NO_RESOLVER) { - JS_ThrowInternalError(cx, "no resolver defined"); + qjs_throw_error(cx, "no resolver defined"); goto fail; } @@ -1661,7 +1661,7 @@ fail: JS_FreeValue(cx, fetch->promise_callbacks[0]); JS_FreeValue(cx, fetch->promise_callbacks[1]); - JS_ThrowInternalError(cx, "internal error"); + qjs_throw_error(cx, "internal error"); return NULL; } diff --git a/nginx/ngx_stream_js_module.c b/nginx/ngx_stream_js_module.c index 9c97bfc5..ae91e039 100644 --- a/nginx/ngx_stream_js_module.c +++ b/nginx/ngx_stream_js_module.c @@ -1747,7 +1747,7 @@ ngx_stream_js_ext_send(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, } else { if (ngx_stream_js_next_filter(s, ctx, cl, from_upstream) == NGX_ERROR) { - njs_vm_internal_error(vm, "ngx_stream_js_next_filter() failed"); + njs_vm_error(vm, "ngx_stream_js_next_filter() failed"); return NJS_ERROR; } } @@ -2569,8 +2569,8 @@ string: JS_FreeCString(cx, str); } - return JS_ThrowInternalError(cx, "ngx_stream_js_next_filter() " - "failed"); + return qjs_throw_error(cx, "ngx_stream_js_next_filter() " + "failed"); } } diff --git a/src/qjs.c b/src/qjs.c index 3f64aedd..f2ac6dde 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -1398,6 +1398,45 @@ qjs_array_buffer_adopt(JSContext *cx, uint8_t *src, size_t len) } +/* + * Library and host failures are reported as Error, since QuickJS-NG makes + * InternalError uncatchable by JavaScript code. + */ + +JSValue +qjs_throw_error(JSContext *cx, const char *fmt, ...) +{ + char buf[256]; + JSValue error, message; + va_list args; + + va_start(args, fmt); + vsnprintf(buf, sizeof(buf), fmt, args); + va_end(args); + + error = qjs_new_error(cx); + if (JS_IsException(error)) { + return JS_EXCEPTION; + } + + message = JS_NewString(cx, buf); + if (JS_IsException(message)) { + JS_FreeValue(cx, error); + return JS_EXCEPTION; + } + + if (JS_DefinePropertyValueStr(cx, error, "message", message, + JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE) + < 0) + { + JS_FreeValue(cx, error); + return JS_EXCEPTION; + } + + return JS_Throw(cx, error); +} + + JSValue qjs_string_create_chb(JSContext *cx, njs_chb_t *chain) { @@ -1412,7 +1451,7 @@ qjs_string_create_chb(JSContext *cx, njs_chb_t *chain) val = JS_ThrowRangeError(cx, "invalid string length"); } else { - val = JS_ThrowInternalError(cx, "failed to create string"); + val = qjs_throw_error(cx, "failed to create string"); } njs_chb_destroy(chain); diff --git a/src/qjs.h b/src/qjs.h index 4336455b..8c1e33d0 100644 --- a/src/qjs.h +++ b/src/qjs.h @@ -71,6 +71,7 @@ void qjs_chb_rt_free(void *rt, void *p); JSValue qjs_new_uint8_array(JSContext *ctx, int argc, JSValueConst *argv); JSValue qjs_array_buffer_adopt(JSContext *cx, uint8_t *src, size_t len); +JSValue qjs_throw_error(JSContext *cx, const char *fmt, ...); JSValue qjs_buffer_alloc(JSContext *ctx, uint64_t size); JSValue qjs_buffer_copy(JSContext *ctx, u_char *start, size_t size); JSValue qjs_buffer_chb_copy(JSContext *ctx, njs_chb_t *chain); diff --git a/test/fs/readdir.t.mjs b/test/fs/readdir.t.mjs index 02b12a3a..b9a58800 100644 --- a/test/fs/readdir.t.mjs +++ b/test/fs/readdir.t.mjs @@ -26,7 +26,7 @@ var match = (entry) => { return false; } } catch (e) { - if (e instanceof InternalError) { + if (e.message.startsWith('dentry type is not supported')) { return true; } diff --git a/test/zlib.t.mjs b/test/zlib.t.mjs index 69352ec1..7b9c6a28 100644 --- a/test/zlib.t.mjs +++ b/test/zlib.t.mjs @@ -100,7 +100,7 @@ let inflateSync_tsuite = { exception: 'RangeError: windowBits must be in the range -15..-8' }, { value: zlib.deflateRawSync('WAKA', {dictionary: Buffer.from('WAKA')}), - exception: 'InternalError: failed to inflate the compressed data: invalid distance too far back' }, + exception: 'Error: failed to inflate the compressed data: invalid distance too far back' }, { value: zlib.deflateSync('WAKA WAKA WAKA', {dictionary: Buffer.from('WAKA')}), raw: false, -- 2.47.3 From 60a1831564cf58aebc28d6950742ca52a5a34498 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 16:48:45 -0800 Subject: [PATCH 14/16] 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. The issue was introduced in 1b69415d (0.9.1). --- external/qjs_webcrypto_module.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/external/qjs_webcrypto_module.c b/external/qjs_webcrypto_module.c index e1626cb0..adfe3535 100644 --- a/external/qjs_webcrypto_module.c +++ b/external/qjs_webcrypto_module.c @@ -1956,7 +1956,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key, u_char *k; size_t olen; int64_t length; - JSValue ret, result, value, dobject; + JSValue ret, result, value, dobject, public_value; unsigned usage; EVP_PKEY *priv_pkey, *pub_pkey; EVP_PKEY_CTX *pctx; @@ -1964,6 +1964,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key, qjs_webcrypto_algorithm_t *dalg; result = JS_UNDEFINED; + public_value = JS_UNDEFINED; dobject = argv[2]; if (derive_key) { @@ -2029,8 +2030,9 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key, goto fail; } - pkey = JS_GetOpaque(value, QJS_CORE_CLASS_ID_WEBCRYPTO_KEY); - JS_FreeValue(cx, value); + public_value = value; + + pkey = JS_GetOpaque(public_value, QJS_CORE_CLASS_ID_WEBCRYPTO_KEY); if (pkey == NULL) { JS_ThrowTypeError(cx, "algorithm.public is not a CryptoKey object"); goto fail; @@ -2108,6 +2110,9 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key, EVP_PKEY_CTX_free(pctx); + JS_FreeValue(cx, public_value); + public_value = JS_UNDEFINED; + if (derive_key) { if (dalg->type == QJS_ALGORITHM_HMAC) { ret = qjs_algorithm_hash(cx, dobject, &dkey->hash); @@ -2129,6 +2134,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key, return qjs_promise_result(cx, result); fail: + JS_FreeValue(cx, public_value); JS_FreeValue(cx, result); return qjs_promise_result(cx, JS_EXCEPTION); -- 2.47.3 From 0a315376890db185566bb40b34cfb655ea143893 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 18:25:11 -0800 Subject: [PATCH 15/16] 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. --- external/qjs_crypto_module.c | 2 +- external/qjs_fs_module.c | 6 +++--- external/qjs_webcrypto_module.c | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/external/qjs_crypto_module.c b/external/qjs_crypto_module.c index 51534d2a..d65b14ab 100644 --- a/external/qjs_crypto_module.c +++ b/external/qjs_crypto_module.c @@ -208,7 +208,7 @@ qjs_hash_prototype_update(JSContext *cx, JSValueConst this_val, int argc, if (enc->decode_length != NULL) { content.length = enc->decode_length(cx, &str); - content.start = js_malloc(cx, content.length); + content.start = js_malloc(cx, njs_max(content.length, 1)); if (content.start == NULL) { JS_FreeCString(cx, (const char *) str.start); return JS_ThrowOutOfMemory(cx); diff --git a/external/qjs_fs_module.c b/external/qjs_fs_module.c index cad376cd..39ea873b 100644 --- a/external/qjs_fs_module.c +++ b/external/qjs_fs_module.c @@ -2002,7 +2002,7 @@ qjs_fs_write(JSContext *cx, JSValueConst this_val, int argc, if (encoding->decode_length != NULL) { content.length = encoding->decode_length(cx, &str); - content.start = js_malloc(cx, content.length); + content.start = js_malloc(cx, njs_max(content.length, 1)); if (content.start == NULL) { JS_FreeCString(cx, (const char *) str.start); JS_ThrowOutOfMemory(cx); @@ -2237,7 +2237,7 @@ decode: if (encoding->decode_length != NULL) { content.length = encoding->decode_length(cx, &str); - content.start = js_malloc(cx, content.length); + content.start = js_malloc(cx, njs_max(content.length, 1)); if (content.start == NULL) { JS_FreeCString(cx, (const char *) str.start); JS_ThrowOutOfMemory(cx); @@ -2871,7 +2871,7 @@ qjs_fs_encode(JSContext *cx, const qjs_buffer_encoding_t *encoding, } else if (encoding->encode_length != NULL) { data.length = encoding->encode_length(cx, str); - data.start = js_malloc(cx, data.length); + data.start = js_malloc(cx, njs_max(data.length, 1)); if (data.start == NULL) { JS_ThrowOutOfMemory(cx); return JS_EXCEPTION; diff --git a/external/qjs_webcrypto_module.c b/external/qjs_webcrypto_module.c index adfe3535..5defe8c9 100644 --- a/external/qjs_webcrypto_module.c +++ b/external/qjs_webcrypto_module.c @@ -2270,7 +2270,7 @@ qjs_webcrypto_derive(JSContext *cx, JSValueConst this_val, int argc, dkey = JS_GetOpaque(dkey_value, QJS_CORE_CLASS_ID_WEBCRYPTO_KEY); } - k = js_malloc(cx, length); + k = js_malloc(cx, njs_max(length, 1)); if (k == NULL) { JS_ThrowOutOfMemory(cx); return JS_EXCEPTION; @@ -3786,7 +3786,7 @@ qjs_import_jwk_oct(JSContext *cx, JSValue jwk, qjs_webcrypto_key_t *key) size = qjs_base64url_decode_length(cx, &b64); key->u.s.raw.length = size; - key->u.s.raw.start = js_malloc(cx, size); + key->u.s.raw.start = js_malloc(cx, njs_max(size, 1)); if (key->u.s.raw.start == NULL) { JS_FreeCString(cx, (char *) b64.start); JS_ThrowOutOfMemory(cx); @@ -4271,7 +4271,7 @@ qjs_webcrypto_import_key_internal(JSContext *cx, qjs_webcrypto_key_format_t fmt, goto fail; } - wkey->u.s.raw.start = js_malloc(cx, kd.length); + wkey->u.s.raw.start = js_malloc(cx, njs_max(kd.length, 1)); if (wkey->u.s.raw.start == NULL) { JS_ThrowOutOfMemory(cx); goto fail; @@ -4327,7 +4327,7 @@ qjs_webcrypto_import_key_internal(JSContext *cx, qjs_webcrypto_key_format_t fmt, case QJS_ALGORITHM_PBKDF2: case QJS_ALGORITHM_HKDF: default: - wkey->u.s.raw.start = js_malloc(cx, kd.length); + wkey->u.s.raw.start = js_malloc(cx, njs_max(kd.length, 1)); if (wkey->u.s.raw.start == NULL) { JS_ThrowOutOfMemory(cx); goto fail; -- 2.47.3 From 14f8ae4dd8bede83f4e4fc9f7fd532ab5e2c05b8 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 18:26:58 -0800 Subject: [PATCH 16/16] 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). --- external/njs_webcrypto_module.c | 5 +++++ external/qjs_webcrypto_module.c | 5 +++++ test/webcrypto/import.t.mjs | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/external/njs_webcrypto_module.c b/external/njs_webcrypto_module.c index 61b3e6c9..f12244ea 100644 --- a/external/njs_webcrypto_module.c +++ b/external/njs_webcrypto_module.c @@ -4298,6 +4298,11 @@ njs_webcrypto_import_key_internal(njs_vm_t *vm, njs_webcrypto_key_format_t fmt, } } + if (key->u.s.raw.length == 0) { + njs_vm_type_error(vm, "HMAC key cannot be empty"); + goto fail; + } + break; case NJS_ALGORITHM_AES_GCM: diff --git a/external/qjs_webcrypto_module.c b/external/qjs_webcrypto_module.c index 5defe8c9..f4b22b69 100644 --- a/external/qjs_webcrypto_module.c +++ b/external/qjs_webcrypto_module.c @@ -4294,6 +4294,11 @@ qjs_webcrypto_import_key_internal(JSContext *cx, qjs_webcrypto_key_format_t fmt, } } + if (wkey->u.s.raw.length == 0) { + JS_ThrowTypeError(cx, "HMAC key cannot be empty"); + goto fail; + } + break; case QJS_ALGORITHM_AES_GCM: diff --git a/test/webcrypto/import.t.mjs b/test/webcrypto/import.t.mjs index 9972d68d..0160d7c4 100644 --- a/test/webcrypto/import.t.mjs +++ b/test/webcrypto/import.t.mjs @@ -424,6 +424,12 @@ let hmac_tsuite = { extractable: true, usage: [ "sign", "verify" ] }, exception: "TypeError: unknown hash name: \"SHA-385\"" }, + { key: { fmt: "raw", + key: "", + alg: { name: "HMAC", hash: "SHA-256" }, + extractable: true, + usage: [ "sign", "verify" ] }, + exception: "TypeError: HMAC key cannot be empty" }, { key: { fmt: "spki", key: "ec.spki", alg: { name: "HMAC" }, @@ -489,6 +495,12 @@ let hmac_tsuite = { extractable: true, usage: [ "sign" ]}, exception: "TypeError: Invalid JWK oct key" }, + { key: { fmt: "jwk", + key: { alg: 'HS256', ext: true, k: '', kty: 'oct' }, + alg: { name: "HMAC", hash: "SHA-256" }, + extractable: true, + usage: [ "sign" ]}, + exception: "TypeError: HMAC key cannot be empty" }, { key: { fmt: "jwk", key: { alg: 'HS256', k: 'AA', key_ops: [ 'sign' ], kty: 'oct' }, alg: { name: "HMAC", hash: "SHA-256" }, -- 2.47.3