Skip to content

Commit

Permalink
Copy own __proto__ on older versions of node
Browse files Browse the repository at this point in the history
- In the __proto__ test, construct the source object with
Object.defineProperty() instead of JSON.parse()
- Use Object.getOwnPropertyDescriptor() when cloning an
own __proto__ to work around a bug in accessing __proto__ in
some environments
  • Loading branch information
mnespor committed Apr 27, 2018
1 parent 632cc9c commit 1a5c464
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
12 changes: 9 additions & 3 deletions index.js
Expand Up @@ -45,10 +45,16 @@ var setProperty = function setProperty(target, options) {
}
};

// Return a new object instead of __proto__ if '__proto__' is not an own property
// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
if (name === '__proto__' && !hasOwn.call(obj, name)) {
return undefined;
if (name === '__proto__') {
if (!hasOwn.call(obj, name)) {
return undefined;
} else if (Object.getOwnPropertyDescriptor) {
// In early versions of node, obj['__proto__'] is buggy when obj has
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
return Object.getOwnPropertyDescriptor(obj, name).value;
}
}

return obj[name];
Expand Down
16 changes: 7 additions & 9 deletions test/index.js
Expand Up @@ -628,15 +628,13 @@ test('non-object target', function (t) {
});

test('__proto__ is merged as an own property', function (t) {
var malicious = JSON.parse('{ "fred": 1, "__proto__": { "george": 1 } }');
// this test isn't valid for earlier versions of V8, which strip __proto__ during JSON.parse()
if (Object.prototype.hasOwnProperty.call(malicious, '__proto__')) {
var target = {};
extend(true, target, malicious);
t.notOk(target.george);
t.ok(Object.prototype.hasOwnProperty.call(target, '__proto__'));
t.deepEqual(target.__proto__, { george: 1 }); // eslint-disable-line no-proto
}
var malicious = { fred: 1 };
Object.defineProperty(malicious, '__proto__', { value: { george: 1 }, enumerable: true });
var target = {};
extend(true, target, malicious);
t.notOk(target.george);
t.ok(Object.prototype.hasOwnProperty.call(target, '__proto__'));
t.deepEqual(Object.getOwnPropertyDescriptor(target, '__proto__').value, { george: 1 });

t.end();
});

0 comments on commit 1a5c464

Please sign in to comment.