Skip to content

Commit

Permalink
Prevent setting/getting some problematic path components
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Oct 23, 2019
1 parent e0f8abf commit 3039c8c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
'use strict';
const isObj = require('is-obj');

const disallowedKeys = [
'__proto__',
'prototype',
'constructor'
];

const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.includes(segment));

function getPathSegments(path) {
const pathArray = path.split('.');
const parts = [];
Expand All @@ -16,6 +24,10 @@ function getPathSegments(path) {
parts.push(p);
}

if (!isValidPath(parts)) {
return [];
}

return parts;
}

Expand All @@ -26,6 +38,9 @@ module.exports = {
}

const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return;
}

for (let i = 0; i < pathArray.length; i++) {
if (!Object.prototype.propertyIsEnumerable.call(object, pathArray[i])) {
Expand Down Expand Up @@ -105,6 +120,9 @@ module.exports = {
}

const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return false;
}

for (let i = 0; i < pathArray.length; i++) {
if (isObj(object)) {
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ Path of the property in the object, using `.` to separate each nested key.

Use `\\.` if you have a `.` in the key.

The following path components are invalid and results in `undefined` being returned: `__proto__`, `prototype`, `constructor`.

#### value

Type: `unknown`
Expand Down
7 changes: 7 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,10 @@ test('has', t => {
t.is(dotProp.has({'foo.baz': {bar: true}}, 'foo\\.baz.bar'), true);
t.is(dotProp.has({'fo.ob.az': {bar: true}}, 'fo\\.ob\\.az.bar'), true);
});

test('prevent setting/getting `__proto__`', t => {
dotProp.set({}, '__proto__.unicorn', '🦄');
t.not({}.unicorn, '🦄'); // eslint-disable-line no-use-extend-native/no-use-extend-native

t.is(dotProp.get({}, '__proto__'), undefined);
});

0 comments on commit 3039c8c

Please sign in to comment.