Dev.to Security 🔐 Cybersecurity 👁 0 📖 10 min read

☣️ Prototype Pollution in Node.js: Fix Your Deep Merge, Then Prove It

Plenty of Node apps have a small deep-merge helper somewhere in utils/. It takes a user's settings JSON, merges it over the defaults, and returns the result. It's ten lines long, it looks harmless, and with the right pay

☣️ Prototype Pollution in Node.js: Fix Your Deep Merge, Then Prove It

Plenty of Node apps have a small deep-merge helper somewhere in utils/. It takes a user's settings JSON, merges it over the defaults, and returns the result. It's ten lines long, it looks harmless, and with the right payload it can add a property to every object in the process.

That's prototype pollution. This post is the developer side of it: what the bug is, where it hides, how to fix it so the fix holds, and a small test suite that proves the fix instead of hoping. Everything below runs on your own machine with stand-in data. Only test systems you own or are authorized to test.

What prototype pollution is

Almost every JavaScript object inherits from Object.prototype. When you read a property an object doesn't have, the runtime walks up the prototype chain and checks there. MDN's guide to the bug puts it plainly: if an attacker can add a property to a built-in prototype such as Object.prototype, that property shows up on objects the attacker never touched.

MDN describes the attack in two phases: pollution (something adds a property to a prototype) and exploitation (normal application code later reads that property). For a developer, that becomes three places to look:

  1. The input: a JSON body or a query string parsed into nested objects. PortSwigger lists the URL, JSON input and web messages as the common sources.
  2. The write: code that assigns with keys taken from that input. Most often a recursive merge, clone or "set value at path" helper that doesn't check its keys. PortSwigger names this pattern as the typical way the bug arises.
  3. The read: code that later reads a property the object doesn't have, and so picks up the polluted value from the prototype. PortSwigger calls a property that gets abused this way a gadget.

Two keys get you from an ordinary object to Object.prototype: __proto__ (an accessor that returns the prototype) and constructor.prototype (every plain object's constructor is Object, and Object.prototype is, well, the prototype). A fix that only handles one of them isn't a fix. You'll see that in a moment.

This isn't new: Olivier Arteau's NorthSec 2018 talk and paper studied it in Node.js applications, and it's tracked as CWE-1321.

Reproduce it in your own code

Here's a merge helper of the kind that ends up in utils/. It recurses into objects and creates missing branches with key in target, a very common check:

// merge-vuln.mjs: the kind of deep-merge helper that ends up in utils/ files
export function merge(target, source) {
  for (const key in source) {
    const value = source[key];
    if (typeof value === "object" && value !== null) {
      if (!(key in target)) target[key] = {};
      merge(target[key], value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

const DEFAULTS = { theme: "light", notifications: { email: true } };

function check(label, body) {
  const settings = merge(structuredClone(DEFAULTS), JSON.parse(body));
  const fresh = {}; // an unrelated object, created afterwards
  console.log(`${label.padEnd(22)} theme=${settings.theme}  ({}).isAdmin=${fresh.isAdmin}`);
  delete Object.prototype.isAdmin; // clean up so each case starts from zero
}

if (import.meta.main) {
  check("control", '{"theme":"dark"}');
  check("__proto__ key", '{"__proto__":{"isAdmin":true}}');
  check("constructor.prototype", '{"constructor":{"prototype":{"isAdmin":true}}}');
}

The control comes first on purpose: it shows the helper works for a normal body, so whatever happens next is caused by the payload and not by a broken test. Running it on Node 24 (import.meta.main was added in Node 24.2.0 and 22.18.0; on older versions, drop the if):

control                theme=dark  ({}).isAdmin=undefined
__proto__ key          theme=light  ({}).isAdmin=true
constructor.prototype  theme=light  ({}).isAdmin=true

Read the last column. fresh is a brand-new empty object created after the merge, and it has isAdmin: true. So would every other plain object in the process, for every user, until it restarts.

Two details from building this demo are worth knowing:

  • JSON.parse isn't the problem. In JSON, __proto__ is just a key; parsing {"__proto__": {...}} gives you an object with an own property called __proto__. The damage happens later, when a helper assigns through that key. MDN notes that a shallow Object.assign only changes the target object's own prototype, and that spread syntax ({ ...input }) doesn't trigger the setter at all. I checked both on Node 24: after Object.assign({}, input) the target reads isAdmin: true, while the spread copy and a fresh {} read undefined. Deep, recursive helpers are where it reaches Object.prototype.
  • The exact shape of the helper matters. My first version created branches with typeof target[key] !== "object". That blocked the constructor path by accident, because target.constructor is a function, so the helper replaced it with an own {} instead of descending into Object. Change one condition and the second payload works. That's why you test both paths instead of reasoning about which one "should" work.

Where to look in your own codebase

You're looking for code that writes to an object using keys that came from input:

  • Recursive merge, extend, clone or "defaults" helpers, in your code or in a dependency.
  • "Set by path" helpers that take strings like a.b.c or a[b][c] from a request.
  • Query-string parsers that build nested objects from ?a[b]=c. MDN points out that libraries are often more exposed than app code, because a generic library can't allowlist keys.
  • for...in loops that copy from a request body into another object. for...in also walks inherited keys; Object.keys() doesn't.

Then look for the gadget side: checks like if (user.isAdmin) or options.debug || false, where a missing property quietly falls back to whatever the prototype says.

The fix: four layers

PortSwigger's guidance is that a key blocklist is a stopgap, not a long-term fix: sites that block __proto__ can still be polluted through constructor. So treat this as layers, each covering a different part of the chain.

1. Fix the write: merge own keys only, and never the prototype keys

// merge-safe.mjs: own keys only, no prototype keys, plain objects only
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);

function isPlainObject(v) {
  if (v === null || typeof v !== "object") return false;
  const proto = Object.getPrototypeOf(v);
  return proto === Object.prototype || proto === null;
}

export function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (BLOCKED.has(key)) continue;
    const value = source[key];
    if (isPlainObject(value)) {
      const current = Object.hasOwn(target, key) ? target[key] : undefined;
      const next = isPlainObject(current) ? current : Object.create(null);
      target[key] = safeMerge(next, value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

Three things make this hold. Object.keys() only visits own keys. The blocklist covers all three dangerous names, not just __proto__. And it only descends into what's already its own property (Object.hasOwn), so an inherited constructor can never become a path to Object. New branches are created with Object.create(null), which have no prototype to pollute. (One trade-off: those nested objects don't have methods like hasOwnProperty, so use Object.hasOwn() on them.)

Better still, if you know the shape of the settings, don't deep-merge arbitrary input at all. Validate the body against a schema first and reject unknown keys. MDN suggests a validator such as Ajv or Zod with additionalProperties: false (or the equivalent strict mode), which also lets you set defaults for missing fields.

2. Fix the read: don't trust missing properties

Pollution is only dangerous when code reads a property the object doesn't own. This little script shows the difference between a loose check and an own-property check when the prototype has been polluted:

// gadget.mjs: the read side. Pollution only matters when code reads a missing property.
Object.prototype.isAdmin = true; // simulate pollution from somewhere else

const user = { id: 42, name: "test-user" }; // no isAdmin field at all

const looseCheck = Boolean(user.isAdmin);
const ownCheck = Object.hasOwn(user, "isAdmin") && user.isAdmin === true;

console.log({ looseCheck, ownCheck });
delete Object.prototype.isAdmin;
{ looseCheck: true, ownCheck: false }

For security decisions, set every field explicitly (isAdmin: false, not "absent"), check with Object.hasOwn(), and use Map or Set for lookups built from input. map.get(key) only returns entries that were set on the map, which both OWASP and PortSwigger recommend for options objects.

3. Harden the runtime: --disable-proto, and maybe freeze

Node has a flag for this: --disable-proto=delete removes the Object.prototype.__proto__ accessor, and --disable-proto=throw makes any access throw ERR_PROTO_ACCESS. It's documented in the Node CLI docs (added in v13.12.0 and v12.17.0). Here's the vulnerable demo again with the flag:

$ node --disable-proto=delete merge-vuln.mjs
control                theme=dark  ({}).isAdmin=undefined
__proto__ key          theme=light  ({}).isAdmin=undefined
constructor.prototype  theme=light  ({}).isAdmin=true

It shut the __proto__ path and left constructor.prototype wide open. That's exactly what the OWASP cheat sheet and MDN both warn: it's defense in depth, not a fix.

Object.freeze(Object.prototype) goes further and stops new properties from being added to it at all. Run it early, after any polyfills, and test first: OWASP notes that libraries which modify built-in prototypes can break. For high-assurance code, MDN points to SES / Hardened JavaScript, which locks down all the built-ins rather than just one.

4. Keep dependencies patched

MDN notes that libraries are generally more exposed than application code, because a generic merge or query parser can't allowlist keys. Keep those dependencies updated and treat advisories in those packages as urgent, because your app is the one that supplies the source.

Prove the fix with a regression test

"I added a blocklist" is a claim. A test that fails on the old helper and passes on the new one is proof. Node's built-in test runner is enough:

// merge.test.mjs: run with `node --test`
import test from "node:test";
import assert from "node:assert/strict";
import { safeMerge } from "./merge-safe.mjs";

const PAYLOADS = [
  '{"__proto__":{"polluted":true}}',
  '{"constructor":{"prototype":{"polluted":true}}}',
  '{"a":{"__proto__":{"polluted":true}}}',
  '{"a":{"constructor":{"prototype":{"polluted":true}}}}',
];

test("control: normal settings still merge", () => {
  const out = safeMerge({ theme: "light" }, JSON.parse('{"theme":"dark","n":{"email":false}}'));
  assert.equal(out.theme, "dark");
  assert.equal(out.n.email, false);
});

for (const body of PAYLOADS) {
  test(`does not pollute: ${body}`, () => {
    safeMerge({}, JSON.parse(body));
    assert.equal({}.polluted, undefined);
    assert.equal(Object.prototype.polluted, undefined);
  });
}

test.afterEach(() => { delete Object.prototype.polluted; });

Against safeMerge:

✔ control: normal settings still merge
✔ does not pollute: {"__proto__":{"polluted":true}}
✔ does not pollute: {"constructor":{"prototype":{"polluted":true}}}
✔ does not pollute: {"a":{"__proto__":{"polluted":true}}}
✔ does not pollute: {"a":{"constructor":{"prototype":{"polluted":true}}}}
ℹ pass 5
ℹ fail 0

And the step people skip: point the same test at the old helper (swap the import for merge from merge-vuln.mjs) and make sure it fails:

✔ control: normal settings still merge
✖ does not pollute: {"__proto__":{"polluted":true}}
✖ does not pollute: {"constructor":{"prototype":{"polluted":true}}}
✖ does not pollute: {"a":{"__proto__":{"polluted":true}}}
✖ does not pollute: {"a":{"constructor":{"prototype":{"polluted":true}}}}
ℹ pass 1
ℹ fail 4

(Timings and some summary lines trimmed from both outputs.) A test that passes on the vulnerable code proves nothing, so this red run is what shows the green one means something. The control test matters too: a "fix" that refuses to merge anything would also pass the pollution tests.

I also ran the safe suite under node --disable-proto=delete, and all five still pass, so the flag and the fix work together.

Input, write and read, with the fix for each layer

Try it yourself

All of the code above runs locally with Node 24 and no dependencies. Save the four files, then run node merge-vuln.mjs, node --disable-proto=delete merge-vuln.mjs and node --test.

To practice spotting the bug in an app you're allowed to attack, PortSwigger's Web Security Academy has free labs (only test what you own or are authorized to test):

The "flawed filters" labs are worth doing after you've written your own blocklist: they show why it has to be paired with own-key checks.

Conclusion

Prototype pollution needs input, a write and a read, so fix all three: merge only own keys and never __proto__, constructor or prototype; stop security checks from trusting missing properties; and harden the runtime as a backstop. Then prove it with a test that goes red on the old code and green on the new. Until you've seen it fail, you don't know it works.

Further reading

I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.

🔐 If this was useful, follow me for more hands-on web & API security write-ups.

🔗 Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.