Skip to content

Commit

Permalink
fix falsly invalid tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
tsndr committed Feb 23, 2024
1 parent 0cd10e1 commit f3dfdff
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,10 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto

const now = Math.floor(Date.now() / 1000)

if (payload.nbf && Math.abs(payload.nbf - now) > (options.clockTolerance ?? 0))
if (payload.nbf && payload.nbf > now && Math.abs(payload.nbf - now) > (options.clockTolerance ?? 0))
throw new Error('NOT_YET_VALID')

if (payload.exp && Math.abs(payload.exp - now) > (options.clockTolerance ?? 0))
if (payload.exp && payload.exp <= now && Math.abs(payload.exp - now) > (options.clockTolerance ?? 0))
throw new Error('EXPIRED')

const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ['verify'])
Expand Down
23 changes: 16 additions & 7 deletions tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,21 @@ describe('Verify', async () => {
const secret = 'super-secret'

const now = Math.floor(Date.now() / 1000)
const off = 30 // 30 seconds
const nbf = now + off // Not valid before 30 seconds from now
const exp = now - off // Expired 30 seconds ago
const offset = 30 // 30 seconds

const notYetValidToken = await jwt.sign({ sub: 'me', nbf }, secret)
const expiredToken = await jwt.sign({ sub: 'me', exp }, secret)
const validToken = await jwt.sign({ sub: 'me', nbf: now - offset }, secret)
const notYetExpired = await jwt.sign({ sub: 'me', exp: now + offset }, secret)

const notYetValidToken = await jwt.sign({ sub: 'me', nbf: now + offset }, secret)
const expiredToken = await jwt.sign({ sub: 'me', exp: now - offset }, secret)

test('Valid', () => {
expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBe(true)
})

test('Not yet expired', () => {
expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBe(true)
})

test('Not yet valid', () => {
expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError('NOT_YET_VALID')
Expand All @@ -141,7 +150,7 @@ describe('Verify', async () => {
})

test('Clock offset', () => {
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: off, throwError: true })).resolves.toBe(true)
expect(jwt.verify(expiredToken, secret, { clockTolerance: off, throwError: true })).resolves.toBe(true)
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
})
})

0 comments on commit f3dfdff

Please sign in to comment.