vapid-keys.js 951 B

1234567891011121314151617181920212223242526272829303132333435
  1. import webPush from 'web-push';
  2. import { db } from '../database/db.js';
  3. let cachedKeys = null;
  4. function ensureVapidKeys() {
  5. if (cachedKeys) return cachedKeys;
  6. const row = db.prepare('SELECT public_key, private_key FROM vapid_keys ORDER BY id DESC LIMIT 1').get();
  7. if (row) {
  8. cachedKeys = { publicKey: row.public_key, privateKey: row.private_key };
  9. return cachedKeys;
  10. }
  11. const keys = webPush.generateVAPIDKeys();
  12. db.prepare('INSERT INTO vapid_keys (public_key, private_key) VALUES (?, ?)').run(keys.publicKey, keys.privateKey);
  13. cachedKeys = keys;
  14. return cachedKeys;
  15. }
  16. function getPublicKey() {
  17. return ensureVapidKeys().publicKey;
  18. }
  19. function configureWebPush() {
  20. const keys = ensureVapidKeys();
  21. webPush.setVapidDetails(
  22. 'mailto:noreply@pilotdeck.local',
  23. keys.publicKey,
  24. keys.privateKey
  25. );
  26. console.log('Web Push notifications configured');
  27. }
  28. export { ensureVapidKeys, getPublicKey, configureWebPush };