From 3eaa7919c0193247c45b96d2bdd7681d45a93dbd Mon Sep 17 00:00:00 2001 From: Jacopo Martinelli <42748150+JacopoPatroclo@users.noreply.github.com> Date: Mon, 15 Jul 2024 12:54:46 +0200 Subject: [PATCH] `nbf` claim not used when passed on the payload (solve #453) (#454) * fix #453: use nbf claim if present on body, solve false positive test related to nbf claim * feat: test back and forth jwt parsing to check consistency --- src/signer.js | 2 +- test/sign-decode.spec.js | 27 +++++++++++++++++++++++++++ test/signer.spec.js | 4 +++- 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 test/sign-decode.spec.js 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/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() +}) 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' ) })