-
Notifications
You must be signed in to change notification settings - Fork 0
/
application_server.ts
94 lines (82 loc) · 2.16 KB
/
application_server.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { PushSubscriber, PushSubscription } from "./subscriber.ts";
/**
* ApplicationServer define a Push application server as specified in RFC 8291.
*
* See https://www.rfc-editor.org/rfc/rfc8291#section-1
*/
export class ApplicationServer {
public readonly crypto: SubtleCrypto;
// Application Server (AS) keys.
public readonly keys: CryptoKeyPair;
// AS public key in raw format.
private publicKeyRaw: Uint8Array | null = null;
// VAPID AS contact information.
public readonly contactInformation: string;
public readonly vapidKeys: CryptoKeyPair;
private publicVapidKeyRaw: Uint8Array | null = null;
constructor(
{
crypto = globalThis.crypto.subtle,
keys,
contactInformation,
vapidKeys,
}: {
crypto?: SubtleCrypto;
keys: CryptoKeyPair;
contactInformation: string;
vapidKeys: CryptoKeyPair;
},
) {
this.crypto = crypto;
this.contactInformation = contactInformation;
this.keys = keys;
this.vapidKeys = vapidKeys;
}
static async new(
{ crypto = globalThis.crypto.subtle, contactInformation, vapidKeys }: {
crypto?: SubtleCrypto;
contactInformation: string;
vapidKeys: CryptoKeyPair;
},
): Promise<ApplicationServer> {
const keys = await crypto.generateKey(
{
name: "ECDH",
namedCurve: "P-256",
},
false,
["deriveKey"],
);
return new ApplicationServer({
crypto,
keys,
contactInformation,
vapidKeys,
});
}
async getPublicKeyRaw(): Promise<Uint8Array> {
if (this.publicKeyRaw === null) {
this.publicKeyRaw = new Uint8Array(
await this.crypto.exportKey(
"raw",
this.keys.publicKey,
),
);
}
return this.publicKeyRaw;
}
async getVapidPublicKeyRaw(): Promise<Uint8Array> {
if (this.publicVapidKeyRaw === null) {
this.publicVapidKeyRaw = new Uint8Array(
await this.crypto.exportKey(
"raw",
this.vapidKeys.publicKey,
),
);
}
return this.publicVapidKeyRaw;
}
subscribe(sub: PushSubscription): PushSubscriber {
return new PushSubscriber(this, sub);
}
}