fix(webpush): add backend subscription check to determine if a valid push subscription exists.

Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me>
This commit is contained in:
0xsysr3ll
2025-12-07 15:15:49 +01:00
parent 7fabd0b1c0
commit 0de2ed2086

View File

@@ -32,16 +32,26 @@ export const verifyPushSubscription = async (
return false; return false;
} }
let hasBackendSubscriptions = false;
try {
const { data: backendSubscriptions } = await axios.get<
UserPushSubscription[]
>(`/api/v1/user/${userId}/pushSubscriptions`);
hasBackendSubscriptions = backendSubscriptions.length > 0;
} catch {
hasBackendSubscriptions = false;
}
try { try {
const { subscription } = await getPushSubscription(); const { subscription } = await getPushSubscription();
if (!subscription) { if (!subscription) {
return false; return hasBackendSubscriptions;
} }
const appServerKey = subscription.options?.applicationServerKey; const appServerKey = subscription.options?.applicationServerKey;
if (!(appServerKey instanceof ArrayBuffer)) { if (!(appServerKey instanceof ArrayBuffer)) {
return false; return hasBackendSubscriptions;
} }
const currentServerKey = new Uint8Array(appServerKey).toString(); const currentServerKey = new Uint8Array(appServerKey).toString();
@@ -49,15 +59,26 @@ export const verifyPushSubscription = async (
currentSettings.vapidPublic currentSettings.vapidPublic
).toString(); ).toString();
if (currentServerKey !== expectedServerKey) {
return hasBackendSubscriptions;
}
const endpoint = subscription.endpoint; const endpoint = subscription.endpoint;
const { data } = await axios.get<UserPushSubscription>( try {
`/api/v1/user/${userId}/pushSubscription/${encodeURIComponent(endpoint)}` const { data } = await axios.get<UserPushSubscription>(
); `/api/v1/user/${userId}/pushSubscription/${encodeURIComponent(
endpoint
)}`
);
return expectedServerKey === currentServerKey && data.endpoint === endpoint; return data.endpoint === endpoint;
} catch {
// iOS endpoint refresh: browser has new endpoint but backend has old one
return hasBackendSubscriptions;
}
} catch (error) { } catch (error) {
return false; return hasBackendSubscriptions;
} }
}; };
@@ -71,6 +92,18 @@ export const verifyAndResubscribePushSubscription = async (
return true; return true;
} }
try {
const { data: backendSubscriptions } = await axios.get<
UserPushSubscription[]
>(`/api/v1/user/${userId}/pushSubscriptions`);
if (backendSubscriptions.length > 0) {
return true;
}
} catch {
// Continue with resubscribe logic
}
if (currentSettings.enablePushRegistration) { if (currentSettings.enablePushRegistration) {
try { try {
// Unsubscribe from the backend to clear the existing push subscription (keys and endpoint) // Unsubscribe from the backend to clear the existing push subscription (keys and endpoint)