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
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ function escapeFunctionBody(str) {
return str;
}

// Keep in sync with the options read in `serialize()` below.
var OPTION_NAMES = ['space', 'isJSON', 'unsafe', 'ignoreFunction'];

// Copy only the options set on the object itself, so a value inherited from a
// polluted `Object.prototype` (e.g. `unsafe`) can't turn off escaping.
function ownOptions(options) {
var result = Object.create(null);
for (var i = 0; i < OPTION_NAMES.length; i++) {
if (Object.prototype.hasOwnProperty.call(options, OPTION_NAMES[i])) {
result[OPTION_NAMES[i]] = options[OPTION_NAMES[i]];
}
}
return result;
}

function generateUID() {
var bytes = crypto.getRandomValues(new Uint8Array(UID_LENGTH));
var result = '';
Expand All @@ -136,6 +151,8 @@ module.exports = function serialize(obj, options) {
options = {space: options};
}

options = ownOptions(options);

var functions = [];
var regexps = [];
var dates = [];
Expand Down
27 changes: 27 additions & 0 deletions test/unit/serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,33 @@ describe('serialize( obj )', function () {
'{"num":123,"str":"str"}'
);
});

it('should ignore options inherited from `Object.prototype`', function () {
var value = {
html: '</script><img src=x onerror=alert(1)>',
fn: function () { return '</script>'; },
map: new Map([['html', '</script>']])
};
var expected = serialize(value);
var expectedWithSpace = serialize(value, 2);

try {
Object.prototype.unsafe = true;
Object.prototype.isJSON = true;
Object.prototype.ignoreFunction = true;
Object.prototype.space = 2;

strictEqual(serialize(value), expected);
strictEqual(serialize(value, {}), expected);
strictEqual(serialize(value, true), expected);
strictEqual(serialize(value, 2), expectedWithSpace);
} finally {
delete Object.prototype.unsafe;
delete Object.prototype.isJSON;
delete Object.prototype.ignoreFunction;
delete Object.prototype.space;
}
});
});

describe('ignoring functions without changing the input', function () {
Expand Down