From 9e22529277769c0fc1a71200df684b6375e870a4 Mon Sep 17 00:00:00 2001 From: Louca Dufault <40028187+loucadufault@users.noreply.github.com> Date: Sun, 29 Jan 2023 21:15:54 -0800 Subject: [PATCH] Add support for encoding option to jws.decode, and fix forwarding of option from jws.createVerify --- lib/verify-stream.js | 6 +++--- readme.md | 4 ++++ test/jws.test.js | 15 ++++++++++++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/lib/verify-stream.js b/lib/verify-stream.js index 39f7c73..a7857ea 100644 --- a/lib/verify-stream.js +++ b/lib/verify-stream.js @@ -66,9 +66,9 @@ function jwsDecode(jwsSig, opts) { if (!header) return null; - var payload = payloadFromJWS(jwsSig); + var payload = payloadFromJWS(jwsSig, opts.encoding); if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); + payload = JSON.parse(payload); return { header: header, @@ -100,7 +100,7 @@ util.inherits(VerifyStream, Stream); VerifyStream.prototype.verify = function verify() { try { var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); + var obj = jwsDecode(this.signature.buffer, {encoding: this.encoding}); this.emit('done', valid, obj); this.emit('data', valid); this.emit('end'); diff --git a/readme.md b/readme.md index 2f32dca..b7aaf23 100644 --- a/readme.md +++ b/readme.md @@ -83,6 +83,10 @@ Note that the `"alg"` value from the signature header is ignored. (Synchronous) Returns the decoded header, decoded payload, and signature parts of the JWS Signature. +Options: + +* `encoding` (Optional, defaults to 'utf8') + Returns an object with three properties, e.g. ```js { header: { alg: 'HS256' }, diff --git a/test/jws.test.js b/test/jws.test.js index aa11bdd..22dfd4b 100644 --- a/test/jws.test.js +++ b/test/jws.test.js @@ -301,6 +301,20 @@ test('jws.decode: with invalid json in body', function (t) { t.end(); }); +test('jws.decode supports encoding option', function (t) { + const payloadString = 'åäöí'; + const encoding = 'latin1'; + const jwsObj = jws.sign({ + header: { alg: 'HS256' }, + payload: payloadString, + secret: 'shhh', + encoding: encoding + }); + const parts = jws.decode(jwsObj, {encoding: encoding}); + t.same(parts.payload, payloadString, 'should match payload'); + t.end(); +}); + test('jws.verify: missing or invalid algorithm', function (t) { const header = Buffer.from('{"something":"not an algo"}').toString('base64'); const payload = Buffer.from('sup').toString('base64'); @@ -316,7 +330,6 @@ test('jws.verify: missing or invalid algorithm', function (t) { t.end(); }); - test('jws.isValid', function (t) { const valid = jws.sign({ header: { alg: 'HS256' }, payload: 'hi', secret: 'shhh' }); const invalid = (function(){