diff --git a/index.js b/index.js index 26163d8..cf14df4 100644 --- a/index.js +++ b/index.js @@ -11,7 +11,7 @@ var randomBytes = require('randombytes'); // Generate an internal UID to make the regexp pattern harder to guess. var UID_LENGTH = 16; var UID = generateUID(); -var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I)-' + UID + '-(\\d+)__@"', 'g'); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I|B)-' + UID + '-(\\d+)__@"', 'g'); var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; var IS_PURE_FUNCTION = /function.*?\(/; @@ -70,6 +70,7 @@ module.exports = function serialize(obj, options) { var sets = []; var undefs = []; var infinities= []; + var bigInts = []; // Returns placeholders for functions and regexps (identified by index) // which are later replaced by their string representation. @@ -119,6 +120,10 @@ module.exports = function serialize(obj, options) { return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@'; } + if (type === 'bigint') { + return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@'; + } + return value; } @@ -192,7 +197,7 @@ module.exports = function serialize(obj, options) { str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); } - if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0) { + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0) { return str; } @@ -231,6 +236,10 @@ module.exports = function serialize(obj, options) { return infinities[valueIndex]; } + if (type === 'B') { + return "BigInt(\"" + bigInts[valueIndex] + "\")"; + } + var fn = functions[valueIndex]; return serializeFunc(fn); diff --git a/test/unit/serialize.js b/test/unit/serialize.js index 88b3603..a618dae 100644 --- a/test/unit/serialize.js +++ b/test/unit/serialize.js @@ -414,6 +414,24 @@ describe('serialize( obj )', function () { }); }); + describe('BigInt', function () { + it('should serialize BigInt', function () { + var b = BigInt(9999); + expect(serialize(b)).to.equal('BigInt("9999")'); + expect(serialize({t: [b]})).to.be.a('string').equal('{"t":[BigInt("9999")]}'); + }); + + it('should deserialize BigInt', function () { + var d = eval(serialize(BigInt(9999))); + expect(d).to.be.a('BigInt'); + expect(d.toString()).to.equal('9999'); + }); + + it('should throw error for invalid bigint', function () { + expect(() => serialize(BigInt('abc'))).to.throw(Error); + }); + }); + describe('XSS', function () { it('should encode unsafe HTML chars to Unicode', function () { expect(serialize('')).to.equal('"\\u003C\\u002Fscript\\u003E"');