Skip to content

Commit

Permalink
fix local sign options
Browse files Browse the repository at this point in the history
  • Loading branch information
mattiapv committed Oct 6, 2023
1 parent fdc8f79 commit 780fcc1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
4 changes: 2 additions & 2 deletions jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
41 changes: 41 additions & 0 deletions test/jwt.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})

0 comments on commit 780fcc1

Please sign in to comment.