`FromNapiValue for serde_json::Value` has no depth limit: a cyclic or deeply nested argument aborts the process
Summary
With the serde-json feature, converting a JS value to serde_json::Value recurses into every array and object with no depth limit and no cycle check:
An object that refers to itself, or one nested a few thousand levels deep, overflows the native stack. The Node.js process then aborts or segfaults, instead of the call throwing a JS error that could be caught.
The conversion runs in the generated glue, before the body of a #[napi] function that takes a serde_json::Value. That function has no chance to guard against it, and wrapping the call in try/catch on the JS side does not help.
Reproduction
Environment:
- napi 3.12.7, napi-derive 3.6.8 (
features = ["napi8", "serde-json"]) - The conversion code is unchanged on
main(afbe5dfc) and in napi 3.13.0. - Node.js v24.15.0, Linux x86_64, debug build
use napi_derive::napi;
#[napi]
pub fn take(value: serde_json::Value) -> bool {
value.is_object()
}const { take } = require('./repro.node');
const cyclic = {};
cyclic.self = cyclic;
take(cyclic);
// Segmentation fault (exit code 139)
let deep = {};
for (let i = 0; i < 5000; i++) deep = { a: deep };
take(deep);
// # Fatal error in , line 0
// # Check failed: isolate_->IsOnCentralStack().
// Trace/breakpoint trap (exit code 133)Nesting of 100 or 1,000 levels returns normally.
Why it matters
JSON.parse accepts far deeper input than this: 100,000 levels parse fine on Node.js v24. A server that passes request JSON to such a function can therefore be taken down with a single request.
Expected behavior
A catchable JS error (for example Status::InvalidArg), similar to JSON.stringify, which throws a TypeError for a cycle.
Suggestion
Count the nesting while converting, and fail once it passes a limit, for example 128 (serde_json's own default recursion limit). A cycle is infinitely deep, so the same limit also stops cycles and no separate cycle check is needed.
Context
We hit this in lindera. Our workaround is a newtype whose FromNapiValue walks the value the same way (array elements, Object::keys with undefined properties skipped) while counting the depth. It hands every non-container to Value::from_napi_value, so the values and error messages stay the same.
Source: napi-rs/napi-rs