1 | import * as error from '../error.js'
|
2 | import * as buffer from '../buffer.js'
|
3 | import * as string from '../string.js'
|
4 | import * as json from '../json.js'
|
5 | import * as ecdsa from '../crypto/ecdsa.js'
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | const _stringify = data => buffer.toBase64UrlEncoded(string.encodeUtf8(json.stringify(data)))
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | const _parse = base64url => json.parse(string.decodeUtf8(buffer.fromBase64UrlEncoded(base64url)))
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | export const encodeJwt = (privateKey, payload) => {
|
22 | const { name: algName, namedCurve: algCurve } = (privateKey.algorithm)
|
23 |
|
24 | if (algName !== 'ECDSA' || algCurve !== 'P-384') {
|
25 | error.unexpectedCase()
|
26 | }
|
27 | const header = {
|
28 | alg: 'ES384',
|
29 | typ: 'JWT'
|
30 | }
|
31 | const jwt = _stringify(header) + '.' + _stringify(payload)
|
32 | return ecdsa.sign(privateKey, string.encodeUtf8(jwt)).then(signature =>
|
33 | jwt + '.' + buffer.toBase64UrlEncoded(signature)
|
34 | )
|
35 | }
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | export const verifyJwt = async (publicKey, jwt) => {
|
42 | const [headerBase64, payloadBase64, signatureBase64] = jwt.split('.')
|
43 | const verified = await ecdsa.verify(publicKey, buffer.fromBase64UrlEncoded(signatureBase64), string.encodeUtf8(headerBase64 + '.' + payloadBase64))
|
44 |
|
45 | if (!verified) {
|
46 | throw new Error('Invalid JWT')
|
47 | }
|
48 | return {
|
49 | header: _parse(headerBase64),
|
50 | payload: _parse(payloadBase64)
|
51 | }
|
52 | }
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | export const unsafeDecode = jwt => {
|
60 | const [headerBase64, payloadBase64] = jwt.split('.')
|
61 | return {
|
62 | header: _parse(headerBase64),
|
63 | payload: _parse(payloadBase64)
|
64 | }
|
65 | }
|