Skip to the solution
HardLow-Level DesignAsked in 20247 min read

Safely Merge Untrusted Input Into an Object Without a Prototype-Pollution Vulnerability

1.7k views

The problem

Problem, as an interviewer would state it: "Write a real, safe deepMerge(target, source) where source may be genuinely UNTRUSTED (e.g. real, user-submitted JSON) — explicitly block keys that could pollute the shared, global Object.prototype."

Examples:

Code
const malicious = JSON.parse('{"__proto__": {"polluted": "yes"}}');
safeMerge({}, malicious);
({}).polluted; // undefined -- genuinely NOT polluted

Clarifying questions expected:

  • What are the SPECIFIC keys that can enable this real vulnerability, and why does JSON.parse make it a genuine, live risk (versus a literal object)?
  • Should the merge recurse into nested objects, and does the same blocking need to apply at EVERY nesting level?
  • Is this purely a defensive concern, or has this been a real, documented vulnerability class in real, popular libraries?

Code / implementation expected: Yes — real, direct, LIVE demonstration: a genuine malicious payload correctly blocked by the safe version, contrasted against a naive merge shown to GENUINELY pollute the real global Object.prototype.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, live proof: a naive merge genuinely pollutes the real, global Object.prototype with a malicious payload, while the safe version leaves it untouched

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 139 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Detect a Cycle in a Linked List (Floyd's Tortoise and Hare)

Continue