Skip to content
Permalink
Browse files Browse the repository at this point in the history
fix(unflat): fix potential for prototype pollution
  • Loading branch information
jessie-codes committed Jan 24, 2021
1 parent 9432b6e commit 4b9b7db
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.js
Expand Up @@ -45,13 +45,15 @@ const flatten = (obj, delimiter) => {
const unflatten = (obj, delimiter) => {
const result = {}
const seperator = delimiter || defaultDelimiter
const proto = ['__proto__', 'constructor', 'prototype']

if (typeof obj !== 'object' || isDate(obj)) return obj

const unflat = (original) => {
Object.keys(original).forEach((key) => {
const newKeys = key.split(seperator)
newKeys.reduce((o, k, i) => {
if (proto.includes(newKeys[i])) return o
return o[k] || (o[k] = isNaN(Number(newKeys[i + 1])) ? (newKeys.length - 1 === i ? original[key] : {}) : [])
}, result)
})
Expand Down
12 changes: 12 additions & 0 deletions test/unflatten.spec.js
Expand Up @@ -150,3 +150,15 @@ test('it should handle date objects', (t) => {

t.deepEqual(unflatten(original), expected)
})

test('it should not pollute the prototype', (t) => {
const original = {
'__proto__.polluted': 'Attempt to pollute the prototype',
'a.prototype.polluted': 'Attempt to pollute the prototype',
'a.b': 'This attribute is safe',
'c.constructor.polluted': 'Attempt to pollute the prototype',
'constructor.polluted': 'Attempt to pollute the prototype'
}
unflatten(original)
t.assert({}.polluted == null)
})

0 comments on commit 4b9b7db

Please sign in to comment.