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
95
96
97
import * as webpush from "jsr:@negrel/webpush@^0.3.0";
// https://github.com/web-push-libs/web-push/blob/v3.4.4/README.md#using-vapid-key-for-applicationserverkey
function urlBase64ToUint8Array(b64) {
const padding = "=".repeat((4 - (b64.length % 4)) % 4);
const base64 = (b64 + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = globalThis.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
// https://stackoverflow.com/a/56848917/9068081
function getPrivKeyJWK({ pubKey, privKey }: { pubKey: string; privKey: string }) {
const pubKeyArray = urlBase64ToUint8Array(pubKey);
const privKeyArray = urlBase64ToUint8Array(privKey);
const arrayBufToBase64UrlEncode = buf => {
let binary = "";
const bytes = new Uint8Array(buf);
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary)
.replace(/\//g, "_")
.replace(/=/g, "")
.replace(/\+/g, "-");
};
return {
kty: "EC",
crv: "P-256",
d: arrayBufToBase64UrlEncode(privKeyArray),
x: arrayBufToBase64UrlEncode(pubKeyArray.slice(1, 33)),
y: arrayBufToBase64UrlEncode(pubKeyArray.slice(33, 66)),
};
}
const vapidKeysAlgo = {
name: "ECDSA",
namedCurve: "P-256",
};
async function importVapidKeys(
exportedKeys: { pubKey: string; privKey: string },
{ crypto = globalThis.crypto.subtle, extractable = false }: {
crypto?: SubtleCrypto;
extractable?: boolean;
} = {},
): Promise<CryptoKeyPair> {
return {
publicKey: await crypto.importKey(
"raw",
urlBase64ToUint8Array(exportedKeys.pubKey),
vapidKeysAlgo,
true,
["verify"],
),
privateKey: await crypto.importKey(
"jwk",
getPrivKeyJWK(exportedKeys),
vapidKeysAlgo,
extractable,
["sign"],
),
};
}
export type PushParams = Parameters<ServiceWorkerRegistration["showNotification"]>;
export default async (
{ url, pubKey, privKey }: { url: string; pubKey: string; privKey: string },
subscription?: PushSubscriptionJSON,
...params: PushParams
) => {
const vapidKeys = await importVapidKeys({ pubKey, privKey }, {
extractable: false,
});
const appServer = await webpush.ApplicationServer.new({
contactInformation: url,
vapidKeys,
});
if (!subscription) throw new Error("subscription is nullish");
const subscriber = appServer.subscribe(subscription);
return await subscriber.pushTextMessage(JSON.stringify(params), {});
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 28, 2024