Skip to content

Commit

Permalink
feat(jwt): add skewTime option that replaces NBF_SKEW if present (#140)
Browse files Browse the repository at this point in the history
  • Loading branch information
javiesses authored Nov 20, 2020
1 parent 012bf89 commit 8a8cb0f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/JWT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface JWTVerifyOptions {
audience?: string
callbackUrl?: string
resolver?: Resolvable
skewTime?: number
}

export interface DIDAuthenticator {
Expand Down Expand Up @@ -235,7 +236,8 @@ export async function verifyJWT(
resolver: null,
auth: null,
audience: null,
callbackUrl: null
callbackUrl: null,
skewTime: null
}
): Promise<JWTVerified> {
if (!options.resolver) throw new Error('No DID resolver has been configured')
Expand All @@ -248,16 +250,17 @@ export async function verifyJWT(
)
const signer: PublicKey = await verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)
const now: number = Math.floor(Date.now() / 1000)
const skewTime = options.skewTime >= 0 ? options.skewTime : NBF_SKEW
if (signer) {
const nowSkewed = now + NBF_SKEW
const nowSkewed = now + skewTime
if (payload.nbf) {
if (payload.nbf > nowSkewed) {
throw new Error(`JWT not valid before nbf: ${payload.nbf}`)
}
} else if (payload.iat && payload.iat > nowSkewed) {
throw new Error(`JWT not valid yet (issued in the future) iat: ${payload.iat}`)
}
if (payload.exp && payload.exp <= now - NBF_SKEW) {
if (payload.exp && payload.exp <= now - skewTime) {
throw new Error(`JWT has expired: exp: ${payload.exp} < now: ${now}`)
}
if (payload.aud) {
Expand Down
5 changes: 5 additions & 0 deletions src/__tests__/JWT-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,11 @@ describe('verifyJWT()', () => {
await expect(verifyJWT(jwt, { resolver })).rejects.toThrow(/JWT has expired/)
})

it('rejects an expired JWT without skew time', async () => {
const jwt = await createJWT({ exp: NOW - 1 }, { issuer: did, signer })
await expect(verifyJWT(jwt, { resolver, skewTime: 0 })).rejects.toThrow(/JWT has expired/)
})

it('accepts a valid audience', async () => {
const jwt = await createJWT({ aud }, { issuer: did, signer })
const { payload } = await verifyJWT(jwt, { resolver, audience: aud })
Expand Down

0 comments on commit 8a8cb0f

Please sign in to comment.