-
Notifications
You must be signed in to change notification settings - Fork 0
/
vapid.ts
70 lines (66 loc) · 1.58 KB
/
vapid.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
/**
* Output of exportVapidKeys() that can be stored serialized in JSON and stored.
*/
export interface ExportedVapidKeys {
publicKey: JsonWebKey;
privateKey: JsonWebKey;
}
const vapidKeysAlgo = {
name: "ECDSA",
namedCurve: "P-256",
};
/**
* Generates a new pair of VAPID keys.
* See https://www.rfc-editor.org/rfc/rfc8292.
*/
export async function generateVapidKeys(
{ extractable = false, crypto = globalThis.crypto.subtle }: {
extractable?: boolean;
crypto?: SubtleCrypto;
} = {},
): Promise<CryptoKeyPair> {
return await crypto.generateKey(
vapidKeysAlgo,
extractable,
["sign", "verify"],
);
}
/**
* Import VAPID keys previously exported using exportVapidKeys() (JWK format).
*/
export async function importVapidKeys(
exportedKeys: ExportedVapidKeys,
{ crypto = globalThis.crypto.subtle, extractable = false }: {
crypto?: SubtleCrypto;
extractable?: boolean;
} = {},
): Promise<CryptoKeyPair> {
return {
publicKey: await crypto.importKey(
"jwk",
exportedKeys.publicKey,
vapidKeysAlgo,
true,
["verify"],
),
privateKey: await crypto.importKey(
"jwk",
exportedKeys.privateKey,
vapidKeysAlgo,
extractable,
["sign"],
),
};
}
/**
* Export VAPID keys in JWK format.
*/
export async function exportVapidKeys(
keys: CryptoKeyPair,
{ crypto = globalThis.crypto.subtle }: { crypto?: SubtleCrypto } = {},
): Promise<ExportedVapidKeys> {
return {
publicKey: await crypto.exportKey("jwk", keys.publicKey),
privateKey: await crypto.exportKey("jwk", keys.privateKey),
};
}