Files
hereconnect/services/message-delivery-method-web-push/src/setupVapidDetails.ts
T

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-11-27 15:57:11 +02:00
import webpush from "web-push";
2024-12-03 13:56:24 +02:00
import { publicSettingsDb, serverSettingsDb } from "./dbs";
import PouchDB from "./PouchDB";
2024-11-27 15:57:11 +02:00
export const setupVapidDetails = async () => {
2024-12-03 13:56:24 +02:00
const subject = process.env.VAPID_SUBJECT;
if (!subject) {
throw new Error("VAPID_SUBJECT env is empty!");
}
2024-11-27 15:57:11 +02:00
const changes = serverSettingsDb.changes({
since: "now",
live: true,
include_docs: true,
2024-12-03 13:56:24 +02:00
doc_ids: ["server_settings:message_delivery_method_web_push_vapid_keys"],
2024-11-27 15:57:11 +02:00
});
2024-12-03 13:56:24 +02:00
const vapidDetailsKeysDoc = await serverSettingsDb
.get("server_settings:message_delivery_method_web_push_vapid_keys")
.catch(async (error) => {
if (error.name !== "not_found") {
throw new Error(
`server_settings:message_delivery_method_web_push_vapid_keys not found: ${error}`,
);
}
2024-11-27 15:57:11 +02:00
2024-12-03 13:56:24 +02:00
const vapidKeys = webpush.generateVAPIDKeys();
const doc = {
_id: "server_settings:message_delivery_method_web_push_vapid_keys",
type: "server_settings",
name: "message_delivery_method_web_push_vapid_keys",
value: vapidKeys,
created_at: new Date().toISOString(),
} as const;
2024-11-27 15:57:11 +02:00
2024-12-03 13:56:24 +02:00
await Promise.all([
serverSettingsDb.put(doc),
publicSettingsDb.put({
_id: "public_settings:message_delivery_method_web_push_vapid_public_key",
type: "public_settings",
name: "message_delivery_method_web_push_vapid_public_key",
value: vapidKeys.publicKey,
created_at: new Date().toISOString(),
}),
]);
console.log("created new vapid keys");
return doc;
});
2024-11-27 15:57:11 +02:00
webpush.setVapidDetails(
2024-12-03 13:56:24 +02:00
subject,
vapidDetailsKeysDoc.value.publicKey,
vapidDetailsKeysDoc.value.privateKey,
2024-11-27 15:57:11 +02:00
);
2024-12-03 13:56:24 +02:00
if (process.env.GCM_API_KEY) {
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
}
2024-12-03 13:56:24 +02:00
changes.on("change", (change) => {
const doc = change.doc;
if (!doc) {
2024-11-27 15:57:11 +02:00
return;
}
2024-12-03 13:56:24 +02:00
console.log("update vapid details");
webpush.setVapidDetails(subject, doc.value.publicKey, doc.value.privateKey);
return;
2024-11-27 15:57:11 +02:00
});
};