From 5ffeedf4ba95d5d47cab3f52150d55d5ade9eea7 Mon Sep 17 00:00:00 2001 From: JacopoPatroclo Date: Fri, 5 Jul 2024 16:00:44 +0200 Subject: [PATCH 1/2] fix #453: use nbf claim if present on body, solve false positive test related to nbf claim --- src/signer.js | 2 +- test/signer.spec.js | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/signer.js b/src/signer.js index 8151a36..98a7cff 100644 --- a/src/signer.js +++ b/src/signer.js @@ -102,7 +102,7 @@ function sign( ...fixedPayload, iat: noTimestamp ? undefined : Math.floor(iat / 1000), exp: payload.exp ? payload.exp : expiresIn ? Math.floor((iat + expiresIn) / 1000) : undefined, - nbf: notBefore ? Math.floor((iat + notBefore) / 1000) : undefined + nbf: payload.nbf ? payload.nbf : notBefore ? Math.floor((iat + notBefore) / 1000) : undefined } if (mutatePayload) { diff --git a/test/signer.spec.js b/test/signer.spec.js index cc5e662..c9343e0 100644 --- a/test/signer.spec.js +++ b/test/signer.spec.js @@ -382,12 +382,14 @@ test('it ignores invalid exp claim', async t => { test('it adds a nbf claim, overriding the payload one, only if the payload is a object', async t => { t.equal( sign({ a: 1, iat: 100 }, { notBefore: 1000 }), + // jwt that contains nbf claim to be 1000 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJpYXQiOjEwMCwibmJmIjoxMDF9.WhZeNowse7q1s5FSlcMcs_4KcxXpSdQ4yqv0xrGB3sU' ) t.equal( sign({ a: 1, iat: 100, nbf: 200 }, { notBefore: 1000 }), - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJpYXQiOjEwMCwibmJmIjoxMDF9.WhZeNowse7q1s5FSlcMcs_4KcxXpSdQ4yqv0xrGB3sU' + // jwt that contains nbf claim to be 200 + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJpYXQiOjEwMCwibmJmIjoyMDB9.HmHmbH-pOTlpj5FsVN61aT2PFhd6EN-tnQdExv_HUs4' ) }) From debf5ce0556feaf21340d8bad959228bcdc46f33 Mon Sep 17 00:00:00 2001 From: JacopoPatroclo Date: Tue, 9 Jul 2024 09:31:02 +0200 Subject: [PATCH 2/2] feat: test back and forth jwt parsing to check consistency --- test/sign-decode.spec.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 test/sign-decode.spec.js diff --git a/test/sign-decode.spec.js b/test/sign-decode.spec.js new file mode 100644 index 0000000..3eadff2 --- /dev/null +++ b/test/sign-decode.spec.js @@ -0,0 +1,27 @@ +'use strict' + +const { test } = require('tap') + +const { createDecoder, createSigner } = require('../src') + +const secret = 'secret' +const decoder = createDecoder({ key: secret }) +const signer = createSigner({ key: secret }) + +test('Should encode and decode the token, keeping a consistent payload', t => { + const p1 = { + a: 20, + iat: 999, + exp: 200000 + } + t.strictSame(decoder(signer(p1)), p1) + + const p2 = { + a: 'h', + iat: 999, + nbf: 999 + } + t.strictSame(decoder(signer(p2)), p2) + + t.end() +})