Skip to content

Commit 3039c8c

Browse files
committed
Prevent setting/getting some problematic path components
1 parent e0f8abf commit 3039c8c

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

index.js

+18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
'use strict';
22
const isObj = require('is-obj');
33

4+
const disallowedKeys = [
5+
'__proto__',
6+
'prototype',
7+
'constructor'
8+
];
9+
10+
const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.includes(segment));
11+
412
function getPathSegments(path) {
513
const pathArray = path.split('.');
614
const parts = [];
@@ -16,6 +24,10 @@ function getPathSegments(path) {
1624
parts.push(p);
1725
}
1826

27+
if (!isValidPath(parts)) {
28+
return [];
29+
}
30+
1931
return parts;
2032
}
2133

@@ -26,6 +38,9 @@ module.exports = {
2638
}
2739

2840
const pathArray = getPathSegments(path);
41+
if (pathArray.length === 0) {
42+
return;
43+
}
2944

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

107122
const pathArray = getPathSegments(path);
123+
if (pathArray.length === 0) {
124+
return false;
125+
}
108126

109127
for (let i = 0; i < pathArray.length; i++) {
110128
if (isObj(object)) {

readme.md

+2
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ Path of the property in the object, using `.` to separate each nested key.
8585

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

88+
The following path components are invalid and results in `undefined` being returned: `__proto__`, `prototype`, `constructor`.
89+
8890
#### value
8991

9092
Type: `unknown`

test.js

+7
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,10 @@ test('has', t => {
199199
t.is(dotProp.has({'foo.baz': {bar: true}}, 'foo\\.baz.bar'), true);
200200
t.is(dotProp.has({'fo.ob.az': {bar: true}}, 'fo\\.ob\\.az.bar'), true);
201201
});
202+
203+
test('prevent setting/getting `__proto__`', t => {
204+
dotProp.set({}, '__proto__.unicorn', '🦄');
205+
t.not({}.unicorn, '🦄'); // eslint-disable-line no-use-extend-native/no-use-extend-native
206+
207+
t.is(dotProp.get({}, '__proto__'), undefined);
208+
});

0 commit comments

Comments
 (0)