diff --git a/jwt.js b/jwt.js index 60210b1..1e79b31 100644 --- a/jwt.js +++ b/jwt.js @@ -369,12 +369,12 @@ function fastifyJwt (fastify, options, next) { const localSignOptions = convertTemporalProps(options.sign) // New supported contract, options supports sign and can expand options = { - sign: mergeOptionsWithKey(Object.assign(signOptions, localSignOptions), true) + sign: mergeOptionsWithKey(Object.assign({}, signOptions, localSignOptions), true) } } else { const localOptions = convertTemporalProps(options) // Original contract, options supports only sign - options = mergeOptionsWithKey(Object.assign(signOptions, localOptions), true) + options = mergeOptionsWithKey(Object.assign({}, signOptions, localOptions), true) } if (!payload) { diff --git a/test/jwt.test.js b/test/jwt.test.js index e391d22..b7fe68b 100644 --- a/test/jwt.test.js +++ b/test/jwt.test.js @@ -3008,3 +3008,44 @@ test('decorator name should work after being changed in the options', async func t.equal(user.baz, undefined) t.equal(user.foo, 'bar') }) + +test('local sign options should not overwrite global sign options', async function (t) { + t.plan(2) + + const options = { + secret: 'test', + sign: { + expiresIn: '15m' + } + } + + const fastify = Fastify() + fastify.register(jwt, options) + + const tokensDifference = 85500 + + fastify.post('/sign', async function (request, reply) { + const { token, refreshToken } = request.body + const refreshTokenSigned = await reply.jwtSign(refreshToken, { expiresIn: '1d' }) + const tokenSigned = await reply.jwtSign(token) + return reply.send({ tokenSigned, refreshTokenSigned }) + }) + + await fastify.ready() + + const signResponse = await fastify.inject({ + method: 'post', + url: '/sign', + payload: { token: { foo: 'bar' }, refreshToken: { bar: 'foo' } } + }) + + const token = JSON.parse(signResponse.payload).tokenSigned + const refreshToken = JSON.parse(signResponse.payload).refreshTokenSigned + const decodedToken = fastify.jwt.verify(token) + const decodedRefreshToken = fastify.jwt.verify(refreshToken) + const calculatedDifference = decodedRefreshToken.exp - decodedToken.exp + // max 5 seconds of difference for safety + t.ok(calculatedDifference >= tokensDifference && calculatedDifference <= tokensDifference + 5) + + t.equal(fastify.jwt.options.sign.expiresIn, '15m') +})