From 04e1d60e540a65b64f6162b6748b5596c09f4e39 Mon Sep 17 00:00:00 2001
From: Lim Chee Aun <cheeaun@gmail.com>
Date: Wed, 5 Jun 2024 18:53:59 +0800
Subject: [PATCH] Check vapidKey

---
 src/utils/push-notifications.js | 38 ++++++++++++++++++---------------
 1 file changed, 21 insertions(+), 17 deletions(-)

diff --git a/src/utils/push-notifications.js b/src/utils/push-notifications.js
index e186547c..598e54fe 100644
--- a/src/utils/push-notifications.js
+++ b/src/utils/push-notifications.js
@@ -147,24 +147,28 @@ export async function initSubscription() {
   if (subscription && !backendSubscription) {
     // check if account's vapidKey is same as subscription's applicationServerKey
     const { vapidKey } = getCurrentAccount();
-    const { applicationServerKey } = subscription.options;
-    const vapidKeyStr = urlBase64ToUint8Array(vapidKey).toString();
-    const applicationServerKeyStr = new Uint8Array(
-      applicationServerKey,
-    ).toString();
-    const sameKey = vapidKeyStr === applicationServerKeyStr;
-    if (sameKey) {
-      // Subscription didn't change
+    if (vapidKey) {
+      const { applicationServerKey } = subscription.options;
+      const vapidKeyStr = urlBase64ToUint8Array(vapidKey).toString();
+      const applicationServerKeyStr = new Uint8Array(
+        applicationServerKey,
+      ).toString();
+      const sameKey = vapidKeyStr === applicationServerKeyStr;
+      if (sameKey) {
+        // Subscription didn't change
+      } else {
+        // Subscription changed
+        console.error('🔔 Subscription changed', {
+          vapidKeyStr,
+          applicationServerKeyStr,
+          sameKey,
+        });
+        // Unsubscribe since backend doesn't have a subscription
+        await subscription.unsubscribe();
+        throw new Error('Subscription key and vapid key changed');
+      }
     } else {
-      // Subscription changed
-      console.error('🔔 Subscription changed', {
-        vapidKeyStr,
-        applicationServerKeyStr,
-        sameKey,
-      });
-      // Unsubscribe since backend doesn't have a subscription
-      await subscription.unsubscribe();
-      throw new Error('Subscription key and vapid key changed');
+      console.warn('No vapidKey found');
     }
   }