See how npm compares to other vendors in security performance
A flaw was found in npm-serialize-javascript. The vulnerability occurs because the serialize-javascript module does not properly sanitize certain inputs, such as regex or other JavaScript object types, allowing an attacker to inject malicious code. This code could be executed when deserialized by a web browser, causing Cross-site scripting (XSS) attacks. This issue is critical in environments where serialized data is sent to web clients, potentially compromising the security of the website or web application using this package.
Description
The path filters pick, ignore, filter, and replace — the library's headline "surgical extraction" feature — recompute the full path string from the nesting stack on every checkable token. Because the stack length equals the current nesting depth, and a checkable token is emitted at every level, processing a document of depth D costs O(D²), not O(D).
This is triggered by document structure (nesting depth), not byte volume, so a tiny payload achieves outsized CPU cost, and it is the ordinary "traverse until the filter matches" path — including the exact README flagship example pick({filter: 'data'}). Any service that uses these filters to extract a field from an untrusted (or larger-than-memory) JSON body — the primary documented use case — can be made to block its event loop.
Affected code (v3.4.0)
src/core/filters/filter-base.js:
js // L26-32 — string filter: rejoins the ENTIRE stack on every call const stringFilter = (string, separator) => { const stringWithSeparator = string + separator; return stack => { const path = stack.join(separator); // O(depth) — every call return path === string || path.startsWith(stringWithSeparator); }; };
// L34-39 — regexp filter: same const regExpFilter = (regExp, separator) => { return stack => { regExp.lastIndex = 0; return regExp.test(stack.join(separator)); // O(depth) — every call }; };
js // L194 — filter(stack, chunk) is invoked for EVERY checkable token while in the 'check' state const action = checkableTokens[chunk.name] !== 1 ? nonCheckableAction : filter(stack, chunk) ? specialAction : defaultAction;
stack is pushed/popped on startObject/startArray/end (L239-250), so stack.length === depth. For a depth-D document that hasn't matched yet, filter() runs once per level and each call is O(depth) ⇒ O(D²) total.
Not affected: the streamArray/streamObject/streamValues streamers use asm.depth (an O(1) getter), so they don't exhibit this. The issue is specific to filter-base.js recomputing the path string.
Proof of concept
npm i stream-json@3.4.0 node poc-quadratic-dos.mjs
js import parserStream from 'stream-json'; import { pick } from 'stream-json/filters/pick.js'; import chain from 'stream-chain';
function run(D) { const doc = '{"meta":'.repeat(D) + '1' + '}'.repeat(D); // depth D, never matches "data" return new Promise((resolve) => { const t0 = process.hrtime.bigint(); const pipeline = chain([parserStream(), pick({ filter: 'data' })]); pipeline.on('data', () => {}); pipeline.on('end', () => resolve({ D, bytes: doc.length, ms: Number(process.hrtime.bigint() - t0) / 1e6 })); pipeline.write(doc); pipeline.end(); }); } for (const D of [5000, 10000, 20000, 40000]) { const r = await run(D); console.log(D=${r.D} bytes=${r.bytes} ms=${Math.round(r.ms)}); }
Measured (Node v24, single core, clean npm i stream-json@3.4.0):
D=5000 bytes= 45001 ms= 160 D=10000 bytes= 90001 ms= 603 (3.8x for 2x input -> quadratic) D=20000 bytes=180001 ms= 2511 (4.2x) D=40000 bytes=360001 ms=11823 (4.7x)
A ~360 KB body (pure nesting, no data) blocks the event loop for ~12 seconds; extrapolating O(D²), ~1–2 MB reaches single-digit minutes of CPU on one request.
Impact
Remote, unauthenticated denial of service against any application that runs untrusted JSON through pick/ignore/filter/replace with a string or RegExp filter — the documented primary use of the library. A small request pins a CPU core / blocks the Node event loop, degrading or halting the service.
Suggested fix
Maintain the joined path incrementally instead of rejoining the whole stack per token: - On startObject/startArray push: append separator + key to a cached path string (and remember the pre-push length). - On end/pop: truncate the cached path back to the remembered length. - Filters test/startsWith against the cached string — O(1) amortized per token, making the whole traversal O(D).
Alternatively expose/enforce a maximum nesting depth for the filter path check.
Resolution
Fixed in 3.5.0. The path filters now cap JSON nesting depth at 1024 by default and throw a RangeError beyond it; upgrading is enough. Opt out with maxDepth: Infinity.
Summary
qs.stringify throws a TypeError when it serializes an object whose own constructor property has a truthy, non-callable isBuffer member. utils.isBuffer duck-types buffers by calling obj.constructor.isBuffer(obj) after checking only that the property is truthy, so a value such as { constructor: { isBuffer: "x" } } makes the call throw TypeError: obj.constructor.isBuffer is not a function.
Details
lib/stringify.js:127 calls utils.isBuffer on every non-primitive value it serializes. utils.isBuffer (lib/utils.js:332) reads obj.constructor.isBuffer and invokes it without verifying that it is a function. constructor and isBuffer are ordinary property names, so any object carrying them as own properties reaches the unchecked call.
Such an object can be built from untrusted input. qs.parse("x[constructor][isBuffer]=y", { plainObjects: true }) or { allowPrototypes: true } keeps the constructor key as an own property (the default parse options drop it), and JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}") produces the same shape with no qs option involved. Express 4 with its default query parser setting and body-parser with extended: true both call qs.parse with allowPrototypes: true, so on those stacks req.query and req.body can carry the shape directly.
PoC
js
var qs = require("qs");
qs.stringify(qs.parse("x[constructor][isBuffer]=y", { plainObjects: true }));
qs.stringify(JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}"));
// TypeError: obj.constructor.isBuffer is not a function
// at Object.isBuffer (lib/utils.js:332:78)
// at stringify (lib/stringify.js:127:45)
Fix
lib/utils.js, applied in e83d321 on main and released as v6.16.0:
diff
- return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
+ return !!(obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj));
Real Buffer, safer-buffer, and browserify buffer polyfill instances serialize exactly as before; only the throw is removed.
Affected versions
>=2.2.5 <6.16.0, fixed in v6.16.0.
The unguarded duck-type was introduced in 3768a75 and first shipped in v2.2.5 (September 2014). v2.2.4 and earlier used Buffer.isBuffer and are not affected. Every release from v2.2.5 through v6.15.3 contains the unguarded call.
Impact
An unauthenticated request can make any code path that re-serializes attacker-influenced data with qs.stringify (for example, rebuilding a query string from req.query for a redirect or an upstream request, or serializing a parsed JSON body) throw synchronously. In a typical Node.js HTTP framework the throw is caught by the framework error boundary and the affected request returns a 500; the process survives and other requests are unaffected. Where the call runs outside an error boundary, such as an async Express 4 handler (where the throw becomes an unhandled promise rejection) or a background job, the process exits, so the impact in that case depends on the application error handling rather than on qs.
Summary brace-expansion's expand() exhibits exponential-time - O(2ⁿ) - behavior in the number of consecutive non-expanding {} groups. A short, all-ASCII input (~90 bytes/30 groups) blocks the calling thread for minutes; a slightly longer input hangs it effectively indefinitely. Because the dominant consumers run on Node's single-threaded event loop, one small input can fully stall a worker/process.
In expand, post is computed unconditionally at the top of the function, before the early-return branches that don't use it: js const post = m.post.length ? expand(m.post, max, false) : ['']; // always recurses ... if (!isSequence && !isOptions) { if (m.post.match(/,(?!,).\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str, max, true); // restart — post discarded } return [str]; }
For input like a{},{},…, the first {} is non-expanding, so control reaches the {a},b} rewrite branch - but expand has already recursed into post over the entire remaining tail, only to throw the result away. Each level therefore spawns two recursive expansions over essentially the same remaining work: T(n) = 2·T(n−1) ⇒ O(2ⁿ).
The max option does not mitigate this: max only bounds the output-building loops; neither the post recursion nor the rewrite recursion consults it. Measured on 5.0.6:
| groups (n) | input bytes | time | |---|---|---| | 20 | 60 | 130 ms | | 24 | 72 | 1.9 s | | 26 | 78 | 7.8 s | | 30 (PoC) | 90 | ~2 min |
Proof of concept js const { expand } = require('brace-expansion'); // 30 non-expanding groups, ~90 bytes — blocks for minutes: expand('a{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}');
Impact
Any application that passes attacker-influenced strings to brace-expansion.expand() - directly or transitively via minimatch/glob brace patterns - can be driven into a multi-minute-to-indefinite CPU hang by a tiny request, denying service on that thread/process.
Remediation
Upgrade to a patched release. The fix: 1. Defers computing post until after the early-return branches (and computes it locally in the $-suffix branch), so post is only expanded when a brace set actually expands and the value is used. This alone removes the exponential. 1. Converts the {a},b} rewrite from recursion to an in-function loop, so a long run of rewrites cannot grow the call stack.
Verified: the PoC drops from ~2 min to 0.55 ms, 5,000 groups complete in ~344 ms, and output is identical to 5.0.6 across a behavioral-equivalence suite (sequences, padding, $-prefix, a{},b}c, {},a}b, x{{a,b}}y, etc.). Post-fix complexity is ~O(n²) on this input class - acceptable for the security fix; a linear rewrite can be a non-urgent follow-up.
If immediate upgrade isn't possible, avoid passing untrusted input to expand() / glob brace patterns, or run such expansion under a timeout/worker.
Summary
expand() bounds the number of results it produces (the max option, 100000 by default) but not their length. By chaining many brace groups, an attacker keeps the result count under max while making every result grow with the number of groups. Building max long results — plus the intermediate arrays combined at each brace group — exhausts memory and crashes the Node process with an uncatchable out-of-memory error. try/catch around expand() does not help: the fatal error terminates the process.
A ~7.5 KB input ('{a,b}'.repeat(1500)) is enough to crash a default Node process.
Details
For N chained brace groups such as '{a,b}'.repeat(N):
- the result count is 2^N, immediately capped at max (100000), so the max protection appears to hold, but - each result is N characters long, so the total output size is max × N characters, which grows without bound in N.
expand combines each brace set with the fully-expanded tail:
js const post = m.post.length ? expand(m.post, max, false) : [''] ... for (let j = 0; j < N.length; j++) { for (let k = 0; k < post.length && expansions.length < max; k++) { const expansion = pre + N[j] + post[k] // grows one group longer per level ... expansions.push(expansion) } }
The loop guard expansions.length < max limits how many strings are built, but nothing limits how long they get. Each recursion level materializes another array of up to max strings, one character longer than the level below, and — because V8 represents pre + N[j] + post[k] as a cons-string (rope) that references post[k] — those intermediate strings stay reachable through the whole chain. Memory therefore scales with max × N.
Measured on 5.0.7 ('{a,b}'.repeat(N), default max):
| groups (N) | input bytes | result count | peak RSS | |---|---|---|---| | 20 | 100 | 100,000 | ~80 MB | | 50 | 250 | 100,000 | ~214 MB | | 100 | 500 | 100,000 | ~409 MB | | 300 | 1,500 | 100,000 | ~1,148 MB | | 1500 | 7,500 | — | OOM crash |
Proof of concept
js const { expand } = require('brace-expansion')
// ~7.5 KB input — crashes the process with a fatal, uncatchable OOM: // FATAL ERROR: ... JavaScript heap out of memory try { expand('{a,b}'.repeat(1500)) } catch (e) { // never reached — the process is already dead }
Impact
Any application that passes attacker-influenced strings to brace-expansion.expand() — directly, or transitively via minimatch / glob brace patterns — can be crashed by a small request. Because the failure is a fatal V8 out-of-memory error rather than a thrown exception, it cannot be caught and it takes down the whole worker/process, denying service.
Remediation
Upgrade to a patched release. The fix bounds the total number of characters a single expand() call may accumulate (EXPANSIONMAXLENGTH, default 4000000, configurable via a new maxLength option), applied inside the output-building loops so intermediate arrays are bounded too. Once the limit is reached, output is truncated — consistent with how max already truncates — instead of growing without bound. The limit sits well above any realistic expansion (100,000 results hitting max measure ~1M characters), so legitimate input is unaffected.
After the fix, '{a,b}'.repeat(1500) returns a bounded, truncated result in ~0.7 s using ~340 MB and never crashes, including under a constrained 512 MB heap.
The fix bounds memory but the algorithm still rebuilds intermediate arrays at each level (roughly O(N × maxLength) work on this input class). A streaming rewrite that produces output in O(total output size) can be a non-urgent follow-up.
If immediate upgrade isn't possible, avoid passing untrusted input to expand() / glob brace patterns, or pass a small explicit max and maxLength.
Summary
Address4 accepts an octet written with a leading zero and decodes it as decimal, while the WHATWG URL host parser, inetaton, and getaddrinfo all decode a leading zero as octal. The library and the network stack therefore disagree about which host a string names. new Address4('012.0.0.1') reports correctForm() of 12.0.0.1 and isPrivate() of false, but fetch('http://012.0.0.1/') connects to 10.0.0.1.
An application that builds a network trust-boundary decision on these checks (for example a filter intended to block Server-Side Request Forgery, or SSRF) will classify an internal target as external and allow the request. SSRF is an attack in which a user-supplied address coaxes the server into making a request to an internal destination the user could not otherwise reach, such as a loopback service or a cloud metadata endpoint.
Details
Address4.parse gates untrusted input on READDRESS (src/v4/constants.ts:5), whose per-octet alternative is:
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
The [01]?[0-9][0-9]? branch matches a leading zero, so 012 passes validation. Every downstream decode then reads the octet with parseInt(part, 10) (src/common.ts:87), yielding 12. A resolver reading the same string treats the leading 0 as base 8 and yields 10.
The defect is in the parse gate rather than in any one classifier, so every consumer of Address4 inherits it: isPrivate(), isLoopback(), isLinkLocal(), isCGNAT(), isInSubnet(), isHostInSubnet(), and correctForm() are all computed from the mis-decoded octets.
Address6 already rejects this notation on its IPv4-in-IPv6 path, throwing "IPv4 addresses can't have leading zeroes." (src/ipv6.ts:751-762), so Address4 is the outlier within the library.
Affected versions
<= 10.3.0. Unlike GHSA-22jq-vg5j-6vgg and GHSA-4xrf-jv44-h6hh, which were bounded below by the is classification API introduced in 10.1.1, this defect is in parse and reaches every release: a guard built on isInSubnet() against the RFC 1918 ranges is affected in versions predating that API.
Impact
The disagreement runs in both directions. Under-blocking is the security-relevant case; over-blocking is a correctness and availability problem.
| Input | correctForm() | Classified as | Resolver reaches | Effect | |---|---|---|---|---| | 012.0.0.1 | 12.0.0.1 | public | 10.0.0.1 | internal target allowed | | 012.012.012.012 | 12.12.12.12 | public | 10.10.10.10 | internal target allowed | | 010.0.0.1 | 10.0.0.1 | private | 8.0.0.1 | public target blocked |
Reachable targets are those whose leading octet is expressible as a three-character octal literal, which covers the whole of 10.0.0.0/8 and 0.0.0.0/8. A four-character octet such as 0177 for 127 is rejected by the regex, so loopback is not reachable through this path; see the note on rejection below for why rejection is not the same as safety.
Reachability
A leading-zero address is a legal URL host, so this is reachable through the ordinary URL path with no unusual application shape required:
js new URL('http://012.0.0.1/').hostname // '10.0.0.1'
This distinguishes it from GHSA-4xrf-jv44-h6hh, where the /0 CIDR suffix could not survive URL parsing and exploitation therefore required an application that accepted a bare suffix-bearing string. Here the attack rides the same code path a normal user-supplied URL takes.
Proof of concept
npm i ip-address@10.3.0, then:
js const { Address4 } = require('ip-address');
// A guard of the shape the library documents. function isBlocked(host) { return Address4.isValid(host) && new Address4(host).isPrivate(); }
for (const h of ['10.0.0.1', '012.0.0.1', '012.012.012.012']) { console.log(isBlocked(h) ? 'BLOCK' : 'ALLOW', h, '-> resolver reaches', new URL('http://' + h + '/').hostname); }
On affected versions:
BLOCK 10.0.0.1 -> resolver reaches 10.0.0.1 ALLOW 012.0.0.1 -> resolver reaches 10.0.0.1 ALLOW 012.012.012.012 -> resolver reaches 10.10.10.10
The literal RFC 1918 address is blocked as expected; the octal-ambiguous spellings of the same destinations are allowed through.
Remediation
Upgrade to the patched release. In the fix, Address4.parse rejects any octet with a leading zero followed by further digits, mirroring the check Address6 already applies at src/ipv6.ts:751, and READDRESS is tightened so those forms no longer appear in the valid corpus. After upgrading, Address4.isValid('012.0.0.1') returns false and the constructor throws AddressError.
This rejects input that previous releases accepted. An application that deliberately feeds zero-padded addresses such as 010.010.010.010 from a legacy system must strip the padding before parsing.
If you cannot upgrade immediately, reject any host whose octets carry a leading zero before you parse it:
js if (host.split('.').some((octet) => /^0\d/.test(octet))) throw new Error('ambiguous address');
A note on SSRF defense
These methods are address classifiers, not a complete SSRF defense. Regardless of this fix, a robust SSRF guard must resolve the hostname and validate the resolved IP against the socket it connects to, and account for DNS rebinding and redirects. Treat these checks as one layer, not the only one.
One specific pitfall is worth naming, because the fix above does not remove it. Address4.isValid() returning false means "this is not a dotted-quad IPv4 literal"; it does not mean "this is not an address that will reach an internal host". Every one of the following is rejected by isValid() and still resolves to loopback:
0177.0.0.1 0x7f.0.0.1 0x7f000001 2130706433 127.1 127.0.1 127.0.0.1. 127.0.0.1
A guard shaped if (Address4.isValid(h)) { check() } else { treatAsHostname() } therefore routes all of them past the IP check. Rejecting these is correct behavior for an IPv4 parser and is not changed by this advisory, but a guard must treat "not a valid literal" as a case to resolve and re-check, never as a case to allow.
Impact
body-parser 2.2.0 is vulnerable to denial of service due to inefficient handling of URL-encoded bodies with very large numbers of parameters. An attacker can send payloads containing thousands of parameters within the default 100KB request size limit, causing elevated CPU and memory usage. This can lead to service slowdown or partial outages under sustained malicious traffic.
Patches
This issue is addressed in version 2.2.1.
npm parcel 2.0.0-alpha and before has an Origin Validation Error vulnerability. Malicious websites can send XMLHTTPRequests to the application's development server and read the response to steal source code when developers visit them.
npm package expr-eval is vulnerable to Prototype Pollution. An attacker with access to express eval interface can use JavaScript prototype-based inheritance model to achieve arbitrary code execution. The npm expr-eval-fork package resolves this issue.
Malicious versions of the nx package, as well as some supporting plugin packages, were published to npm, containing code that scans the file system, collects credentials, and posts them to GitHub as a repo under user's accounts.
The ip (aka node-ip) package through 2.0.1 (in NPM) might allow SSRF because the IP address value 0 is improperly categorized as globally routable via isPublic. NOTE: this issue exists because of an incomplete fix for CVE-2024-29415. NOTE: in current versions of several applications, connection attempts to the IP address 0 (interpreted as 0.0.0.0) are blocked with error messages such as net::ERRADDRESSINVALID. However, in some situations that depend on both application version and operating system, connection attempts to 0 and 0.0.0.0 are considered connection attempts to 127.0.0.1 (and, for this reason, a false value of isPublic would be preferable).
The ip (aka node-ip) package through 2.0.1 (in NPM) might allow SSRF because the IP address value 017700000001 is improperly categorized as globally routable via isPublic. NOTE: this issue exists because of an incomplete fix for CVE-2024-29415.