1
0

Compare commits

...

2 Commits

Author SHA1 Message Date
e503b163e9 add clock tolerance 2024-02-22 22:49:24 +01:00
3f62636645 update editorconfig 2024-02-22 22:49:01 +01:00
3 changed files with 44 additions and 7 deletions

View File

@@ -4,7 +4,12 @@ root = true
end_of_line = lf end_of_line = lf
insert_final_newline = false insert_final_newline = false
[src/**/*.ts] [{src,tests}/*.ts]
charset = utf-8 charset = utf-8
indent_style = space indent_style = space
indent_size = 4 indent_size = 4
[{src,tests}/**/*.ts]
charset = utf-8
indent_style = space
indent_size = 4

View File

@@ -99,6 +99,11 @@ export type JwtSignOptions<T> = {
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`) * @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
*/ */
export type JwtVerifyOptions = { export type JwtVerifyOptions = {
/**
* Clock tolerance to help with slightly out of sync systems
*/
clockTolerance?: number
/** /**
* If `true` throw error if checks fail. (default: `false`) * If `true` throw error if checks fail. (default: `false`)
* *
@@ -178,11 +183,10 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
* @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue. * @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`. * @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
*/ */
export async function verify(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> { export async function verify(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = 'HS256'): Promise<boolean> {
if (typeof options === 'string') if (typeof options === 'string')
options = { algorithm: options, throwError: false } options = { algorithm: options }
options = { algorithm: 'HS256', clockTolerance: 0, throwError: false, ...options }
options = { algorithm: 'HS256', throwError: false, ...options }
if (typeof token !== 'string') if (typeof token !== 'string')
throw new Error('token must be a string') throw new Error('token must be a string')
@@ -215,10 +219,12 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto
if (!payload) if (!payload)
throw new Error('PARSE_ERROR') throw new Error('PARSE_ERROR')
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) const now = Math.floor(Date.now() / 1000)
if (payload.nbf && Math.abs(payload.nbf - now) > (options.clockTolerance ?? 0))
throw new Error('NOT_YET_VALID') throw new Error('NOT_YET_VALID')
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) if (payload.exp && Math.abs(payload.exp - now) > (options.clockTolerance ?? 0))
throw new Error('EXPIRED') throw new Error('EXPIRED')
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ['verify']) const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ['verify'])

View File

@@ -119,4 +119,30 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
const verified = await jwt.verify(token, data.public, algorithm) const verified = await jwt.verify(token, data.public, algorithm)
expect(verified).toBeTruthy() expect(verified).toBeTruthy()
}) })
})
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 notYetValidToken = await jwt.sign({ sub: 'me', nbf }, secret)
const expiredToken = await jwt.sign({ sub: 'me', exp }, secret)
test('Not yet valid', () => {
expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError('NOT_YET_VALID')
})
test('Expired', () => {
console.log({ exp, now: Math.floor(Date.now() / 1000) })
expect(jwt.verify(expiredToken, secret, { throwError: true })).rejects.toThrowError('EXPIRED')
})
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)
})
}) })