The config merge your agent wrote lets a JSON body rewrite Object.prototype: a failing test table, a safe merge and a property test in TypeScript
Agents write deepMerge and setByPath helpers that treat every key as harmless. Here's the failing Vitest table first, a fix that survives a tidy-up refactor, and a fast-check property that keeps any agent honest. About 30 minutes, no accounts needed.

A feature request lands that sounds like plumbing: let users override settings. A tenant uploads a JSON file, or a client sends a PATCH with a partial settings object, and the server layers it over the defaults. The agent writes a recursive deepMerge, maybe a setByPath("theme.colours.accent", value) for the admin screen, adds a test that merges { a: { b: 1 } } with { a: { c: 2 } }, and the demo is green.
Then somebody sends {"__proto__": {"isAdmin": true}}. The merge walks into __proto__, writes isAdmin onto the shared Object.prototype, and from that moment every plain object in the process reports isAdmin as true unless it sets its own. Nothing crashed. No error was logged. The next request that does if (user.isAdmin) on an object that never defined the field takes the admin branch.
This is prototype pollution, and merge helpers are where generated code produces it most reliably, because the obvious recursive implementation treats every key the same. This Playbook builds the fix in an order that keeps an agent honest: a failing table of hostile inputs first, a merge that refuses them, a refactor that shows why the table has to stay, and a property test that covers the inputs nobody thought to list. Examples are TypeScript with Vitest and fast-check. The method works with any coding agent that can read files and run a shell, and it ports to any language that has a similar “magic key” problem.
The first draft
Ask an agent for “a deep merge and a set-by-path helper for settings objects” and the result usually looks like this:
export function deepMerge(target: any, source: any): any {
for (const key of Object.keys(source)) {
if (typeof source[key] === "object" && source[key] !== null) {
if (typeof target[key] !== "object" || target[key] === null) target[key] = {};
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
export function setByPath(obj: any, path: string, value: unknown): void {
const parts = path.split(".");
let cur = obj;
for (const part of parts.slice(0, -1)) {
if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
cur = cur[part];
}
cur[parts[parts.length - 1]] = value;
}
It reads fine in review, which is the problem. Two details make it dangerous. First, JSON.parse turns a "__proto__" key in the text into an ordinary own property of the parsed object, so Object.keys happily returns it. Second, reading target["__proto__"] doesn’t give back an empty slot; it gives back the object’s prototype, which for a plain object is the global Object.prototype. The typeof check passes, the recursion descends into it, and the write lands on the shared object.
MDN calls __proto__ a legacy feature that “presents several security issues”, and that’s the one to remember: the key is special in a way the rest of the code doesn’t know about.
Step 1: write the table before the fix
The table is the durable part. Every row is a hostile input, and every row asserts the same outcome: Object.prototype is untouched afterwards. An afterEach deletes the probe keys so a failing row can’t poison the rows after it.
import { afterEach, describe, expect, it } from "vitest";
import { deepMerge, setByPath } from "./merge";
const probe = () => ({} as Record<string, unknown>).polluted;
afterEach(() => {
delete (Object.prototype as Record<string, unknown>).polluted;
});
describe("deepMerge", () => {
it("merges nested settings", () => {
expect(deepMerge({ a: { b: 1 } }, { a: { c: 2 } })).toEqual({ a: { b: 1, c: 2 } });
});
it.each([
["__proto__", '{"__proto__":{"polluted":"yes"}}'],
["constructor.prototype", '{"constructor":{"prototype":{"polluted":"yes"}}}'],
])("does not pollute Object.prototype via %s", (_name, json) => {
deepMerge({}, JSON.parse(json));
expect(probe()).toBeUndefined();
});
});
describe("setByPath", () => {
it("sets nested values", () => {
const o: any = {};
setByPath(o, "a.b.c", 1);
expect(o).toEqual({ a: { b: { c: 1 } } });
});
it.each(["__proto__.polluted", "constructor.prototype.polluted"])(
"does not pollute via %s",
(path) => {
setByPath({}, path, "yes");
expect(probe()).toBeUndefined();
},
);
});
Two details matter here. The inputs go through JSON.parse, because that’s how a real attacker’s payload arrives; an object literal with __proto__ in it sets the prototype instead of creating a key, so a literal would test the wrong thing. And the happy-path rows stay in the file, so a fix that blocks everything can’t pass.
Run it with npx vitest run. This is what the first draft produces:
❯ src/merge.test.ts (6 tests | 2 failed)
❯ deepMerge (3)
× does not pollute Object.prototype via __proto__
❯ setByPath (3)
× does not pollute via __proto__.polluted
FAIL src/merge.test.ts > deepMerge > does not pollute Object.prototype via __proto__
AssertionError: expected 'yes' to be undefined
Tests 2 failed | 4 passed (6)
Two rows fail, and two rows that were meant to fail pass. The constructor.prototype rows are green against the first draft, by accident. target["constructor"] is the Object function, its typeof is "function" rather than "object", so the code replaces it with a fresh {} and the write never reaches the real prototype. The defence is a side effect of a type check that was written for another reason.
Step 2: watch the accident disappear
That accidental guard is the reason the constructor rows stay in the table. A routine tidy-up, the kind an agent does when asked to “simplify setByPath”, removes it:
export function setByPath(obj: any, path: string, value: unknown): void {
const parts = path.split(".");
const last = parts.pop()!;
let cur = obj;
for (const part of parts) cur = cur[part] ??= {};
cur[last] = value;
}
It’s shorter, it passes the happy-path test, and ??= only replaces null or undefined. For constructor the existing value is the Object function, so it’s kept and walked into. Run the two pollution rows against this version:
× refactored setByPath, __proto__.polluted
× refactored setByPath, constructor.prototype.polluted
Tests 2 failed (2)
Both fail now. A code review of that diff would see a tidy loop. Only the table sees the regression, which is the argument for writing the table first and for keeping it in the repository where the agent will be told to run it.
Step 3: the fix
The rule is to decide about a key before it’s used, and to read only what an object owns. Three names are forbidden outright. Anything the code reads from an object goes through Object.hasOwn, which MDN describes as returning true only for own properties, so an inherited __proto__ or constructor can never be mistaken for data.
const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
function assertSafeKey(key: string): void {
if (FORBIDDEN.has(key)) throw new Error(`Refusing unsafe key: ${key}`);
}
type Json = { [key: string]: unknown };
const isPlain = (v: unknown): v is Json =>
typeof v === "object" && v !== null && !Array.isArray(v);
export function deepMerge(target: Json, source: Json): Json {
for (const key of Object.keys(source)) {
assertSafeKey(key);
const incoming = source[key];
if (isPlain(incoming)) {
const existing = Object.hasOwn(target, key) ? target[key] : undefined;
const next: Json = isPlain(existing) ? existing : {};
target[key] = deepMerge(next, incoming);
} else {
target[key] = incoming;
}
}
return target;
}
export function setByPath(obj: Json, path: string, value: unknown): void {
const parts = path.split(".");
parts.forEach(assertSafeKey);
let cur = obj;
for (const part of parts.slice(0, -1)) {
const existing = Object.hasOwn(cur, part) ? cur[part] : undefined;
cur = isPlain(existing) ? existing : ((cur[part] = {}) as Json);
}
cur[parts[parts.length - 1]] = value;
}
The choice to throw rather than silently skip is deliberate. A payload with __proto__ in it is never a legitimate settings file, and dropping the key quietly hides the attempt. Throwing turns it into a 400 that shows up in logs. If a product genuinely has to accept arbitrary third-party JSON and tolerate such keys, skipping is defensible, but it should be a decision somebody made.
The table now asserts the new contract. Change the pollution rows to expect a throw:
expect(() => deepMerge({}, JSON.parse(json))).toThrow(/unsafe key/);
expect(() => setByPath({}, path, "yes")).toThrow(/unsafe key/);
Asserting the throw and the untouched prototype together is stricter than either alone, because a fix that throws after polluting would still be caught by a prototype check in the same row. Add the probe() expectation to those rows as well if the function does work before the check.
Step 4: a property for the inputs nobody listed
A table covers the attacks somebody thought of. Property-based testing covers the shape of the space: generate lots of objects built from a deliberately nasty key set, merge them, and assert the invariant. fast-check is the usual library for it in TypeScript.
import fc from "fast-check";
import { expect, it } from "vitest";
import { deepMerge } from "./merge";
const keys = fc.constantFrom("a", "b", "c", "__proto__", "constructor", "prototype", "toString");
const json: fc.Arbitrary<unknown> = fc.letrec((tie) => ({
leaf: fc.oneof(fc.integer(), fc.string(), fc.boolean(), fc.constant(null)),
node: fc.dictionary(keys, tie("tree"), { maxKeys: 3 }),
tree: fc.oneof({ depthSize: "small" }, tie("leaf"), tie("node")),
})).node;
it("never changes Object.prototype", () => {
const before = Object.getOwnPropertyNames(Object.prototype).sort().join();
fc.assert(
fc.property(json, json, (a, b) => {
// Round-tripping through JSON makes "__proto__" an own key, as real input would.
const parse = (x: unknown) => JSON.parse(JSON.stringify(x));
try {
deepMerge(parse(a), parse(b));
} catch (e) {
expect(String(e)).toMatch(/unsafe key/);
}
expect(Object.getOwnPropertyNames(Object.prototype).sort().join()).toBe(before);
}),
{ numRuns: 500 },
);
});
Three details are easy to get wrong. The JSON.parse(JSON.stringify(x)) round trip matters for the same reason as in the table: fc.dictionary can produce __proto__ as a key, but only a parsed object holds it as an own property that Object.keys will return. Catching the error and asserting its message means the only acceptable failure is the intended refusal; any other exception fails the property. And the invariant compares the full list of own property names of Object.prototype, so it catches pollution under any key, not just the polluted probe.
Against the fix:
Test Files 2 passed (2)
Tests 7 passed (7)
That’s the fixed table plus the property. Point the same property at the first draft and it fails with “Property failed after” a handful of generated cases, which confirms the test has teeth. One wrinkle: once pollution has happened in a process, it stays, so the reported counterexample after the first failure can look like an empty object merged with an empty object. Treat the failure message as the signal, then rerun the table to find the actual row.
Make it yours
The same trap appears wherever code walks keys it didn’t choose. A few variations worth the same table:
- Query-string and form parsers that build nested objects from
a[b][c]=1syntax. Test with__proto__[polluted]=yesas the raw string. - Clone helpers,
Object.assignin a loop and spread-based reducers over untrusted JSON. Anything that copies keys from input into a plain object belongs in the table. - Maps instead of objects. If the data is a dictionary of arbitrary keys (tenant IDs, header names, feature flags), a
Mapor anObject.create(null)object has no prototype to pollute. OWASP’s prevention cheat sheet recommends exactly that,SetorMapover object literals, andObject.create(null)for objects that must not inherit. - C# and other stacks. The magic-key problem exists wherever a merge or binder treats a user-supplied name as a path. The method carries over: hostile-input table, then a guard at the point of use, then a property over generated inputs.
For defence in depth at the process level, Node has a flag: --disable-proto=delete removes Object.prototype.__proto__ entirely, and --disable-proto=throw makes accesses throw an error with the code ERR_PROTO_ACCESS (both documented in the Node.js CLI reference, added in v13.12.0 and v12.17.0). OWASP is explicit that this doesn’t close the hole, since pollution through constructor.prototype is still possible. Treat it as a second layer behind the key check, and run the test suite with it once to see which dependencies still touch __proto__.
What goes wrong
The forbidden-key list is a deny-list, and deny-lists are only as good as their authors. The three names cover the documented routes into Object.prototype, but code that merges into class instances, or into objects whose prototype has been customised, has other targets. Where the shape of the settings is known, validate against a schema and reject unknown keys; the merge guard is then a backstop rather than the policy.
Freezing is not a drop-in alternative. Object.freeze(Object.prototype) makes writes fail in strict mode and be ignored otherwise, which stops this class of bug at the source. OWASP notes the catch: freezing is shallow, and libraries that modify built-in prototypes may break, so test compatibility before shipping it.
The property test is slower than the table and can miss shapes the generator never produces. Keep numRuns modest in the pre-commit run and raise it in CI.
Don’t bother with the whole kit for a script that merges two files you wrote yourself. The risk scales with who controls the keys. If the input never leaves your own repository, a single row in the table is plenty.
The first 30 minutes
Search the codebase for the helpers that walk keys: deepMerge, merge(, extend(, setByPath, set( over a split string, anything with Object.keys(source) inside a loop. Pick the one that’s reachable from a request. Then give any coding agent this prompt:
Add tests/prototype-pollution.test.ts for <function>. Feed each hostile payload through JSON.parse:
{"__proto__":{"polluted":"yes"}}, {"constructor":{"prototype":{"polluted":"yes"}}}, and the same
keys nested two levels down. Assert that Object.prototype is unchanged afterwards, with an
afterEach that deletes the probe key. Keep a happy-path test. Run it with npx vitest run, show
me the failing output, and only then change <function>. Do not edit the tests to make them pass.
Check that the failure output shows the expected rows failing before you let the fix go in. Then add the fast-check property from Step 4 and put the file in the pre-commit or CI path, so the next refactor of that helper meets the same table.