← 中文资源

简体中文版本

JSON.parse 自有 __proto__,赋值触发 setter

JSON.parse 把 __proto__ 当普通自有属性,原型不受影响;但 Object.assign 或手写合并走 [[Set]] 赋值,撞上 __proto__ setter 会改写目标对象原型,合并配置前必须拒绝这几个键。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

own property: true
prototype untouched: true
payload readable: true
target prototype hijacked: true
Object.prototype still clean: true
guarded merge keeps prototype: true

实现说明

真正干活的是函数 safeMerge,其余都是接线。 文件的主干是一个循环——for (const key of Object.keys(patch))。

使用要点

  • 守卫 key === '__proto__' || key === 'constructor' || key === '… 成立时借助提前的 continue 直接离开。
  • 演示输出是带标签的(own property:、prototype untouched:、payload readable:),每个操作都会留下自己的一行标注。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 safeMerge。

入口签名:function safeMerge(target, patch)

核心语句

if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
const parsed = JSON.parse('{"__proto__": {"admin": true}}');
Object.assign(target, parsed);

代码示例

// JSON.parse defines '__proto__' as an ordinary own property: the object's
// prototype stays Object.prototype and the payload reads back verbatim.
const parsed = JSON.parse('{"__proto__": {"admin": true}}');

console.log('own property:', Object.hasOwn(parsed, '__proto__'));
console.log('prototype untouched:', Object.getPrototypeOf(parsed) === Object.prototype);
console.log('payload readable:', parsed.__proto__.admin === true);

// Object.assign copies with [[Set]], so '__proto__' hits the setter and
// hijacks the TARGET's prototype instead of creating a property.
const target = {};
Object.assign(target, parsed);
console.log('target prototype hijacked:', Object.getPrototypeOf(target).admin === true);
console.log('Object.prototype still clean:', ({}).admin === undefined);

// Hand-rolled merges have the same hazard; reject the dangerous keys.
function safeMerge(target, patch) {
  for (const key of Object.keys(patch)) {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
    target[key] = patch[key];
  }
  return target;
}

const guarded = {};
safeMerge(guarded, parsed);
console.log('guarded merge keeps prototype:', Object.getPrototypeOf(guarded) === Object.prototype);