-
-
Notifications
You must be signed in to change notification settings - Fork 310
/
sign.ts
47 lines (40 loc) · 1.43 KB
/
sign.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
import type QUnit from 'qunit'
import type * as jose from '../src/index.js'
import random from './random.js'
function isKeyPair(
input: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult,
): input is jose.GenerateKeyPairResult {
return 'publicKey' in input && 'privateKey' in input
}
export async function jws(
t: typeof QUnit.assert,
lib: typeof jose,
alg: string,
secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult,
payload = random(),
) {
const sKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair
const vKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair
const jws = await new lib.FlattenedSign(payload).setProtectedHeader({ alg }).sign(sKey)
const verified = await lib.flattenedVerify(jws, vKey)
t.deepEqual([...verified.payload], [...payload])
}
export async function jwt(
t: typeof QUnit.assert,
lib: typeof jose,
alg: string,
secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult,
) {
const sKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair
const vKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair
const jwt = await new lib.SignJWT({ foo: 'bar' }).setProtectedHeader({ alg }).sign(sKey)
const verified = await lib.jwtVerify(jwt, vKey)
t.deepEqual(verified, {
payload: {
foo: 'bar',
},
protectedHeader: {
alg,
},
})
}