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
8 changes: 8 additions & 0 deletions __tests__/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
expect(data).toEqual({ name: 'afei' });
});

test('set can prevent prototype pollution', function () {
var data = {};
var operator = new NxObjectOperator(data);
operator.set('__proto__.polluted', 'Yes, its polluted.');
expect(data.polluted).toEqual(undefined);
expect({}.polluted).toEqual(undefined);
});

test('get should get the right value', function () {
var data = {};
var operator = new NxObjectOperator(data);
Expand Down
15 changes: 13 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,30 @@
var global = global || this || window || Function('return this')();
var nx = global.nx || require('@jswork/next');

var isPrototypePolluted = function(key) {
return ['__proto__', 'prototype', 'constructor'].includes(key);
}

var set = function(data, key, value) {
if (String(key).split(".").some(function(k) {
return isPrototypePolluted(k);
})) return false;
nx.set(data, key, value);
}

var NxObjectOperator = nx.declare('nx.ObjectOperator', {
methods: {
init: function (inData) {
this.data = inData;
},
set: function (inPath, inValue) {
nx.set(this.data, inPath, inValue);
set(this.data, inPath, inValue);
},
sets: function (inObject) {
nx.forIn(
inObject,
function (key, value) {
nx.set(this.data, key, value);
set(this.data, key, value);
},
this
);
Expand Down