This repository has been archived by the owner on Jun 27, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.ts
80 lines (72 loc) · 1.79 KB
/
jwt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
import * as Jwt from 'djwt'
import { decode } from 'std/encoding/base64.ts'
import { Context } from './mod.ts'
interface Payload {
iss?: string
sub?: string
aud?: string[] | string
/**
* A `Date` object or a `number` (in seconds) when the JWT will expire.
*/
exp?: Date | number
/**
* A `Date` object or a `number` (in seconds) until which the JWT will be invalid.
*/
nbf?: Date | number
iat?: number
jti?: string
[key: string]: unknown
}
function importKey(key: string) {
return crypto.subtle.importKey(
'raw',
decode(key).buffer,
{ name: 'HMAC', hash: 'SHA-512' },
true,
['sign', 'verify'],
)
}
/**
* Sign a payload.
*/
// deno-lint-ignore ban-types
export async function sign<T extends Record<string, unknown> = {}>(
secret: string | Context,
payload: T & Payload,
) {
const key = typeof secret === 'string'
? await importKey(secret)
: await importKey(
(secret.env('jwt_secret') ?? secret.env('JWT_SECRET')) as string,
)
const { exp, nbf, ...rest } = payload
return await Jwt.create({ alg: 'HS512', typ: 'JWT' }, {
...(exp && { exp: Jwt.getNumericDate(exp) }),
...(nbf && { nbf: Jwt.getNumericDate(nbf) }),
...rest,
}, key)
}
/**
* Verify the validity of a JWT.
*/
export async function verify<T extends Record<string, unknown> = Payload>(
secret: string | Context,
token: string,
options?: Jwt.VerifyOptions,
) {
try {
const key = typeof secret === 'string'
? await importKey(secret)
: await importKey(
(secret.env('jwt_secret') ?? secret.env('JWT_SECRET')) as string,
)
return await Jwt.verify(token, key, options) as Jwt.Payload & T
} catch (_err) {
return
}
}
export default {
sign,
verify,
}