diff --git a/__tests__/index.spec.js b/__tests__/index.spec.js index 8da8b9c..60e58d7 100644 --- a/__tests__/index.spec.js +++ b/__tests__/index.spec.js @@ -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); diff --git a/src/index.js b/src/index.js index a7e3e63..bff0ba1 100644 --- a/src/index.js +++ b/src/index.js @@ -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 );