Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/utils/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,15 @@ export function set(root, path, value) {
let prop = root;
let parts = split(path);
let last = parts[parts.length-1];
// Refuse to traverse or write through keys that resolve to the prototype
// chain, otherwise a path such as `__proto__.x` or `constructor.prototype.x`
// mutates `Object.prototype` instead of `root`.
for (let i=0; i<parts.length; i++) {
if (parts[i] === '__proto__' || parts[i] === 'prototype' ||
parts[i] === 'constructor') {
return;
}
}
if (parts.length > 1) {
// Loop over path parts[0..n-2] and dereference
for (let i=0; i<parts.length-1; i++) {
Expand Down
14 changes: 13 additions & 1 deletion test/unit/path.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<body>

<script type="module">
import { isAncestor, isDeep, isDescendant, root, matches, translate } from '../../lib/utils/path.js';
import { isAncestor, isDeep, isDescendant, root, matches, translate, set } from '../../lib/utils/path.js';
suite('path utilities', function() {

test('root()', function() {
Expand Down Expand Up @@ -77,5 +77,17 @@
assert.equal(matches('foo.bar','foo.baz'), false);
assert.equal(matches('foo.bar','foo.bars'), false);
});

test('set() does not pollute the prototype', function() {
assert.equal(set({}, '__proto__.polluted', true), undefined);
assert.equal(set({}, 'constructor.prototype.polluted', true), undefined);
assert.equal({}.polluted, undefined);

const obj = {a: {b: 1}};
assert.equal(set(obj, 'a.b', 2), 'a.b');
assert.equal(obj.a.b, 2);
assert.equal(set(obj, 'a', 3), 'a');
assert.equal(obj.a, 3);
});
});
</script>