diff --git a/lib/verify-stream.js b/lib/verify-stream.js index d9bfa2b..44ed594 100644 --- a/lib/verify-stream.js +++ b/lib/verify-stream.js @@ -11,10 +11,10 @@ function isObject(thing) { return Object.prototype.toString.call(thing) === '[object Object]'; } -function safeJsonParse(thing) { +function safeJsonParse(thing, encoding) { if (isObject(thing)) return thing; - try { return JSON.parse(thing); } + try { return JSON.parse(thing, encoding); } catch (e) { return undefined; } } @@ -67,8 +67,10 @@ function jwsDecode(jwsSig, opts) { return null; var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); + if (header.typ === 'JWT' || opts.json){ + payload = safeJsonParse(payload, opts.encoding); + if (!payload) { return null; } + } return { header: header, diff --git a/test/jws.test.js b/test/jws.test.js index 063969b..4ff2f82 100644 --- a/test/jws.test.js +++ b/test/jws.test.js @@ -279,6 +279,7 @@ if (SUPPORTS_ENCRYPTED_KEYS) { test('jws.decode: not a jws signature', function (t) { t.same(jws.decode('some garbage string'), null); t.same(jws.decode('http://sub.domain.org'), null); + t.same(jws.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e3.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'), null); t.end(); }); @@ -295,10 +296,8 @@ test('jws.decode: with invalid json in body', function (t) { const header = Buffer('{"alg":"HS256","typ":"JWT"}').toString('base64'); const payload = Buffer('sup').toString('base64'); const sig = header + '.' + payload + '.'; - var parts; - t.throws(function () { - parts = jws.decode(sig); - }) + const parts = jws.decode(sig); + t.same(parts, null); t.end(); });