← Blog

Prototype Pollution via Deep Merge in MCP Skill Configuration Handlers — SA-SKL-PROTOTYPE8

Configuration merging is ubiquitous in MCP skill development: skill settings merged with user overrides, default audit policies merged with organization preferences, tool capability objects merged from multiple sources. When the merge function is not hardened against attacker-controlled input, a single key named __proto__ in the input object can inject arbitrary properties onto Object.prototype — the shared prototype inherited by every plain object in the Node.js process. The injected property then appears on every subsequent {} literal, every Object.create(null)-less object, and every property lookup that falls through to the prototype chain. SA-SKL-PROTOTYPE8 documents four distinct prototype pollution vectors found in real MCP skill configuration handlers: an outdated lodash version, a hand-rolled recursive merge without a prototype-chain guard, Object.assign applied to untrusted request body input, and a JSON Reviver that reconstructs nested objects from user-supplied JSON. Each is exploitable to bypass authorization checks, corrupt flag state, or in some Node.js versions enable remote code execution via prototype-polluted child_process options.

By SkillAudit  |  9 Nov 2026  |  16 min read
SA-SKL-PROTOTYPE8 findings at a glance
CRITICALPROTOTYPE8-001 — lodash _.merge(target, userInput) on a lodash version below 4.17.21 — attacker sends {"__proto__":{"isAdmin":true}}; lodash traverses the __proto__ key and assigns isAdmin: true onto Object.prototype; every subsequent obj.isAdmin check in the process returns true
CRITICALPROTOTYPE8-002 — Hand-rolled mergeDeep(target, src) without Object.hasOwn(src, key) guard — iterating over src keys picks up __proto__ and constructor; assigning target[key] = src[key] pollutes the prototype; fix: skip __proto__ / constructor / prototype keys explicitly and use Object.hasOwn
HIGHPROTOTYPE8-003 — Object.assign({}, req.body) spreads __proto__ key from the parsed body into the new plain object — when the target object subsequently propagates to a downstream authorization check that reads obj.isAdmin, the polluted prototype makes the check return true for all users
HIGHPROTOTYPE8-004 — JSON.parse(input, reviverFn) with a Reviver that reconstructs nested objects from user JSON — attacker sends {"__proto__":{"isAdmin":true}}; Reviver receives key="__proto__", value={isAdmin:true} and reconstructs it, returning an object whose __proto__ key pollutes the prototype when subsequently merged

The JavaScript prototype chain: why this works

Every JavaScript object has an internal [[Prototype]] slot pointing to its prototype. For plain objects created with {} or Object.create(null) (the latter has no prototype), the prototype is Object.prototype. Property lookup walks the prototype chain: if obj.isAdmin is not an own property of obj, the runtime looks for isAdmin on obj.__proto__ (which is Object.prototype). If that property has been injected there, it returns the injected value.

The attack is to cause a merge function to write to the prototype object rather than to the target object. In JavaScript, obj["__proto__"] is special: in most engines it is an accessor property on Object.prototype itself, so writing to it via bracket notation triggers the setter and updates the actual internal prototype of obj. But a subtler path exists: when a deep merge function recursively calls itself with the value of src["__proto__"] as the new source and target["__proto__"] as the new target, it ends up writing properties directly onto Object.prototype using regular property assignment — which does not trigger the accessor and does write to the shared prototype object.

The result: properties injected onto Object.prototype become "own"-looking properties on every plain object in the process until the Node.js instance restarts. Authorization flags, feature flags, role strings, and boolean capability checks are all vulnerable if they fall back to a prototype lookup when the own property is absent.

Severity context: In older Node.js versions (before v14 hardening of child_process options), prototype-polluted properties on Object.prototype were read by child_process.spawn()'s options object — leading to remote code execution. Newer Node.js versions have partially mitigated this specific vector, but authorization bypass and application logic corruption remain fully exploitable on all current Node.js LTS versions. SkillAudit treats PROTOTYPE8-001 and PROTOTYPE8-002 as Critical severity for the authorization bypass class alone.

PROTOTYPE8-001 — lodash _.merge() with user-controlled __proto__ key

Lodash's _.merge() function is the most common deep merge utility in the Node.js ecosystem. Versions before 4.17.21 do not filter the __proto__ key during recursive merge, making them directly vulnerable to prototype pollution. When a MCP skill configuration handler calls _.merge(internalConfig, userSuppliedOverrides) and the override object originates from an HTTP request body or any other attacker-controlled source without prior sanitization, the attacker can inject properties onto Object.prototype that persist for the lifetime of the Node.js process.

// VULNERABLE — PROTOTYPE8-001
// lodash version pinned to 4.17.4 in package.json — CVE-2019-10744 unfixed.
// User-controlled skill config override merged into internal defaults.
// Attacker sends: POST /api/skills/my-skill/config
// Body: {"__proto__":{"isAdmin":true}}

import _ from 'lodash'; // version 4.17.4

async function updateSkillConfig(skillId, userId, overrides) {
  const defaults = await getSkillDefaults(skillId);

  // VULNERABLE: _.merge() on lodash <4.17.21 does not filter __proto__ key
  // After this call, Object.prototype.isAdmin === true for the entire process
  const merged = _.merge({}, defaults, overrides);

  await saveConfig(skillId, merged);
  return merged;
}

// Downstream authorization check — reads isAdmin from prototype if own property absent
async function requireAdmin(req, res, next) {
  const user = await getUser(req.userId);
  // VULNERABLE: user.isAdmin falls through to prototype — returns true for all users
  if (!user.isAdmin) {
    return res.status(403).json({ error: 'Admin required' });
  }
  next();
}
// FIXED — PROTOTYPE8-001
// Fix 1: Upgrade lodash to 4.17.21+ (patches CVE-2019-10744 by filtering __proto__).
// Fix 2: Sanitize input before merge — strip __proto__, constructor, prototype keys.
// Fix 3: Use structuredClone() to deep-clone user input before merging (strips prototype chain).
// Fix 4: Use JSON.parse(JSON.stringify(input)) as a simpler sanitization step.

import _ from 'lodash'; // upgraded to 4.17.21+

function sanitizeForMerge(obj) {
  // FIX: serialize + deserialize strips __proto__, non-serializable keys, and prototype chain
  return JSON.parse(JSON.stringify(obj));
}

async function updateSkillConfig(skillId, userId, overrides) {
  const defaults = await getSkillDefaults(skillId);

  // FIX: sanitize user input before passing to merge (defense-in-depth even with updated lodash)
  const safeOverrides = sanitizeForMerge(overrides);
  const merged = _.merge({}, defaults, safeOverrides);

  await saveConfig(skillId, merged);
  return merged;
}

// FIX: authorization check reads own property only
async function requireAdmin(req, res, next) {
  const user = await getUser(req.userId);
  // FIX: check own property explicitly — does not fall through to prototype
  if (!Object.hasOwn(user, 'isAdmin') || !user.isAdmin) {
    return res.status(403).json({ error: 'Admin required' });
  }
  next();
}

Detection: SkillAudit's static analyzer checks package.json for lodash versions below 4.17.21 and flags any call site where user-controlled data flows into _.merge(), _.mergeWith(), or _.defaultsDeep(). It also scans for CVE-2019-10744 in the installed node_modules/lodash/package.json at audit time.

PROTOTYPE8-002 — Recursive mergeDeep() without hasOwnProperty guard

Many MCP skill codebases implement their own deep merge utility rather than depending on lodash. The typical implementation iterates over the keys of the source object and recursively merges nested objects. Without an explicit guard that skips the __proto__, constructor, and prototype keys, this function is vulnerable to prototype pollution via the same mechanism as lodash. The key insight is that for...in and Object.keys() both enumerate __proto__ when it appears as a string key in a plain object (as opposed to the implicit prototype slot), making it reachable via iteration.

// VULNERABLE — PROTOTYPE8-002
// Hand-rolled recursive merge — does not guard against prototype-chain keys.
// Attacker sends skill config body: {"__proto__":{"canDeleteAnyAudit":true}}
// After merge, Object.prototype.canDeleteAnyAudit === true for all plain objects.

function mergeDeep(target, src) {
  for (const key of Object.keys(src)) {
    // VULNERABLE: key could be "__proto__" or "constructor"
    if (src[key] && typeof src[key] === 'object' && !Array.isArray(src[key])) {
      if (!target[key]) target[key] = {};
      // VULNERABLE: recursion with target["__proto__"] = Object.prototype
      // Writes properties onto Object.prototype directly
      mergeDeep(target[key], src[key]);
    } else {
      target[key] = src[key];
    }
  }
  return target;
}

async function applySkillConfigPatch(skillId, patch) {
  const config = await loadConfig(skillId);
  mergeDeep(config, patch); // VULNERABLE: patch is from req.body
  await saveConfig(skillId, config);
}
// FIXED — PROTOTYPE8-002
// Fix 1: Explicitly skip __proto__, constructor, and prototype keys.
// Fix 2: Use Object.hasOwn(src, key) instead of for...in to skip inherited keys.
// Fix 3: Use structuredClone() on the input before merging (belt + suspenders).

const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);

function mergeDeep(target, src) {
  for (const key of Object.keys(src)) {
    // FIX 1: Skip prototype-chain attack keys
    if (FORBIDDEN_KEYS.has(key)) continue;

    // FIX 2: Only merge own properties of src
    if (!Object.hasOwn(src, key)) continue;

    if (src[key] !== null && typeof src[key] === 'object' && !Array.isArray(src[key])) {
      // FIX: create target sub-object using Object.create(null) to avoid its own prototype chain
      if (!Object.hasOwn(target, key) || typeof target[key] !== 'object') {
        target[key] = {};
      }
      mergeDeep(target[key], src[key]);
    } else {
      target[key] = src[key];
    }
  }
  return target;
}

async function applySkillConfigPatch(skillId, patch) {
  const config = await loadConfig(skillId);
  // FIX 3: Sanitize patch via structuredClone before merging
  const safePatch = structuredClone(patch);
  mergeDeep(config, safePatch);
  await saveConfig(skillId, config);
}

Why Object.keys() still exposes __proto__: When a parsed JSON object has a literal string key "__proto__", that key appears as a regular string property in the resulting object — it is an own enumerable property with the string name "__proto__". Object.keys() includes it. The bracket accessor src["__proto__"] then writes to the prototype chain setter. The fix must check the key name before accessing the value.

PROTOTYPE8-003 — Object.assign({}, req.body) spreads __proto__ key

Object.assign(target, source) copies own enumerable string-keyed properties from source to target. When the source is a request body parsed by Express's express.json() middleware, and the body contains a "__proto__" key, the assignment copies that key's value onto the target. The assignment then triggers the __proto__ setter on the target object, updating its internal prototype. This is a shallow merge — it does not recurse — but it is sufficient to pollute the prototype of the returned object if the target starts as a new plain object {} whose prototype is Object.prototype.

// VULNERABLE — PROTOTYPE8-003
// Object.assign with direct request body spread — shallow prototype pollution.
// Attacker sends: POST /api/skills/settings
// Body: {"__proto__":{"isAdmin":true},"theme":"dark"}
// Object.assign({}, body) copies __proto__ key — sets new object's prototype to {isAdmin:true}
// Downstream code reads isAdmin from the modified prototype.

app.post('/api/skills/settings', requireAuth, async (req, res) => {
  // VULNERABLE: Object.assign with untrusted req.body
  const settings = Object.assign({}, req.body);

  // settings.__proto__ is now {isAdmin:true} for THIS object
  // But if Object.prototype was mutated, ALL plain objects are affected

  // VULNERABLE: downstream check on obj.isAdmin reads polluted prototype
  if (settings.isAdmin) {
    await grantAdminAccess(req.userId);
  }

  await saveUserSettings(req.userId, settings);
  res.json({ ok: true });
});
// FIXED — PROTOTYPE8-003
// Fix 1: Validate and schema-strip the request body before any merge (use ajv or zod).
// Fix 2: Use structuredClone() to deep-clone and strip the prototype chain from req.body.
// Fix 3: Never read authorization flags from merged/spread objects — read from DB-sourced user record only.

import { z } from 'zod';

const SettingsSchema = z.object({
  theme: z.enum(['dark', 'light']).optional(),
  notifications: z.boolean().optional(),
  auditBadgePublic: z.boolean().optional(),
  // FIX: schema explicitly lists allowed keys — __proto__ never matches
}).strict(); // .strict() rejects unknown keys including __proto__

app.post('/api/skills/settings', requireAuth, async (req, res) => {
  // FIX 1: Schema validation strips unknown keys and rejects __proto__
  const result = SettingsSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: result.error.format() });
  }

  // FIX 2: Work with the validated (safe) data only
  const settings = result.data;

  // FIX 3: Authorization flag read from DB-sourced user record — never from request body
  const user = await getUser(req.userId);
  if (user.isAdmin) {
    await grantAdminAccess(req.userId);
  }

  await saveUserSettings(req.userId, settings);
  res.json({ ok: true });
});

PROTOTYPE8-004 — JSON Reviver that reconstructs nested objects from user JSON

JSON.parse's second argument is a Reviver function called for each key-value pair during parsing. Some MCP skill implementations use a Reviver to reconstruct class instances, perform type coercions, or handle special date formats from configuration JSON. When the Reviver returns a new object constructed from an attacker-supplied value, and that constructed object is subsequently merged into an application configuration, the attacker can inject {"__proto__":{"isAdmin":true}} as valid JSON input. The Reviver receives key="__proto__" and value={isAdmin:true} as separate arguments, reconstructs it, and the returned object carries the __proto__ key that later pollutes the prototype during merge.

// VULNERABLE — PROTOTYPE8-004
// JSON.parse with custom Reviver that reconstructs objects from user JSON.
// Reviver does not sanitize prototype-chain keys.
// Attacker sends skill config body: {"__proto__":{"isAdmin":true},"settings":{"timeout":30}}
// After JSON.parse + merge, Object.prototype.isAdmin === true.

function configReviver(key, value) {
  // Custom Reviver — transforms date strings, reconstructs config objects
  if (value && typeof value === 'object' && value._type === 'Date') {
    return new Date(value.iso);
  }
  // VULNERABLE: returns plain objects as-is — does not strip __proto__ key
  return value;
}

async function applyRawConfig(skillId, rawJson) {
  // VULNERABLE: Reviver reconstructs attacker-controlled objects
  const parsed = JSON.parse(rawJson, configReviver);

  // VULNERABLE: deep merge of parsed (attacker-controlled) object into config
  const config = await loadConfig(skillId);
  _.merge(config, parsed); // Even lodash 4.17.21 can be bypassed via Reviver-constructed objects
  await saveConfig(skillId, config);
}
// FIXED — PROTOTYPE8-004
// Fix 1: JSON schema validation (ajv with additionalProperties:false) BEFORE Reviver or merge.
//         Schema validation rejects unknown keys like __proto__ before they reach the Reviver.
// Fix 2: If Reviver is needed, run it only after schema validation, and add key guard inside Reviver.
// Fix 3: Use structuredClone() on parsed output before any merge.

import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });

const skillConfigSchema = {
  type: 'object',
  additionalProperties: false,  // FIX: rejects __proto__ and all unknown keys
  properties: {
    timeout: { type: 'integer', minimum: 1, maximum: 300 },
    maxRetries: { type: 'integer', minimum: 0, maximum: 10 },
    webhookUrl: { type: 'string', format: 'uri' },
    tags: { type: 'array', items: { type: 'string' }, maxItems: 20 },
  },
};

const validateConfig = ajv.compile(skillConfigSchema);

function safeConfigReviver(key, value) {
  // FIX: skip prototype-chain attack keys even inside the Reviver
  if (['__proto__', 'constructor', 'prototype'].includes(key)) return undefined;

  if (value && typeof value === 'object' && value._type === 'Date') {
    return new Date(value.iso);
  }
  return value;
}

async function applyRawConfig(skillId, rawJson) {
  // FIX 1: Parse with key guard Reviver
  let parsed;
  try {
    parsed = JSON.parse(rawJson, safeConfigReviver);
  } catch {
    throw new Error('Invalid JSON in skill configuration');
  }

  // FIX 2: Schema validation after parsing — rejects __proto__ and unknown keys
  if (!validateConfig(parsed)) {
    throw new Error('Config validation failed: ' + ajv.errorsText(validateConfig.errors));
  }

  // FIX 3: structuredClone before merge (belt + suspenders)
  const safeConfig = structuredClone(parsed);

  const config = await loadConfig(skillId);
  _.merge(config, safeConfig);
  await saveConfig(skillId, config);
}

Why lodash 4.17.21 alone is not enough for PROTOTYPE8-004: Lodash's fix for CVE-2019-10744 added a guard in _.merge() that skips keys literally named "__proto__". But a custom Reviver can reconstruct an object whose actual JavaScript [[Prototype]] chain was modified during Reviver execution — before the object reaches _.merge(). The result is an object where the prototype chain is already polluted, and lodash's key-name guard does not catch it. Schema validation with additionalProperties: false before any parsing or Reviver execution is the correct defense.

Defense-in-depth checklist for MCP skill configuration handlers

Prototype pollution is unusual among injection vulnerabilities because the payload is not in the final output — it modifies global JavaScript runtime state that persists for the lifetime of the process. Standard XSS or SQL injection defenses (output encoding, parameterized queries) do not help here. The correct defenses operate at the input processing layer, before the merge occurs:

Summary — SA-SKL-PROTOTYPE8 at a glance

PatternRoot causeFixSeverity
PROTOTYPE8-001lodash _.merge() on version <4.17.21 does not filter __proto__ key; user config merged directly; Object.prototype.isAdmin set to trueUpgrade lodash to 4.17.21+; sanitize input via JSON.parse(JSON.stringify()) before merge; use Object.hasOwn in auth checksCritical
PROTOTYPE8-002Hand-rolled mergeDeep() iterates over all source keys including __proto__; recursive call with target["__proto__"] writes to Object.prototypeSkip __proto__/constructor/prototype keys; use Object.hasOwn; apply structuredClone() before mergingCritical
PROTOTYPE8-003Object.assign({}, req.body) copies __proto__ key from parsed body; triggers prototype setter on target object; downstream auth reads polluted prototypeSchema validate with zod.strict() or ajv additionalProperties:false before any spread/assign; read auth flags from DB record onlyHigh
PROTOTYPE8-004Custom JSON Reviver reconstructs nested objects from attacker JSON; __proto__ key passed to Reviver; subsequent merge inherits polluted chain even past lodash 4.17.21 guardSchema validate before Reviver runs; add key guard inside Reviver; structuredClone() parsed output before mergeHigh
SkillAudit

Does your MCP skill's configuration merge code guard against prototype pollution?

SkillAudit scans for outdated lodash versions, unguarded deep merge functions, Object.assign with untrusted input, and custom JSON Revivers that reconstruct attacker-controlled nested objects — before the next config update poisons your process's Object.prototype.

Audit your MCP skill →