Skip to content

Commit ff828d3

Browse files
committed
fix(webpush): add backend subscription check to determine if a valid push subscription exists.
Signed-off-by: 0xsysr3ll <[email protected]>
1 parent d0a6104 commit ff828d3

File tree

1 file changed

+41
-8
lines changed

1 file changed

+41
-8
lines changed

src/utils/pushSubscriptionHelpers.ts

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,53 @@ export const verifyPushSubscription = async (
3232
return false;
3333
}
3434

35+
let hasBackendSubscriptions = false;
36+
try {
37+
const { data: backendSubscriptions } = await axios.get<
38+
UserPushSubscription[]
39+
>(`/api/v1/user/${userId}/pushSubscriptions`);
40+
hasBackendSubscriptions = backendSubscriptions.length > 0;
41+
} catch {
42+
hasBackendSubscriptions = false;
43+
}
44+
3545
try {
3646
const { subscription } = await getPushSubscription();
3747

3848
if (!subscription) {
39-
return false;
49+
return hasBackendSubscriptions;
4050
}
4151

4252
const appServerKey = subscription.options?.applicationServerKey;
4353
if (!(appServerKey instanceof ArrayBuffer)) {
44-
return false;
54+
return hasBackendSubscriptions;
4555
}
4656

4757
const currentServerKey = new Uint8Array(appServerKey).toString();
4858
const expectedServerKey = urlBase64ToUint8Array(
4959
currentSettings.vapidPublic
5060
).toString();
5161

52-
const endpoint = subscription.endpoint;
62+
if (currentServerKey !== expectedServerKey) {
63+
return hasBackendSubscriptions;
64+
}
5365

54-
const { data } = await axios.get<UserPushSubscription>(
55-
`/api/v1/user/${userId}/pushSubscription/${encodeURIComponent(endpoint)}`
56-
);
66+
const endpoint = subscription.endpoint;
5767

58-
return expectedServerKey === currentServerKey && data.endpoint === endpoint;
68+
try {
69+
const { data } = await axios.get<UserPushSubscription>(
70+
`/api/v1/user/${userId}/pushSubscription/${encodeURIComponent(
71+
endpoint
72+
)}`
73+
);
74+
75+
return data.endpoint === endpoint;
76+
} catch {
77+
// iOS endpoint refresh: browser has new endpoint but backend has old one
78+
return hasBackendSubscriptions;
79+
}
5980
} catch (error) {
60-
return false;
81+
return hasBackendSubscriptions;
6182
}
6283
};
6384

@@ -71,6 +92,18 @@ export const verifyAndResubscribePushSubscription = async (
7192
return true;
7293
}
7394

95+
try {
96+
const { data: backendSubscriptions } = await axios.get<
97+
UserPushSubscription[]
98+
>(`/api/v1/user/${userId}/pushSubscriptions`);
99+
100+
if (backendSubscriptions.length > 0) {
101+
return true;
102+
}
103+
} catch {
104+
// Continue with resubscribe logic
105+
}
106+
74107
if (currentSettings.enablePushRegistration) {
75108
try {
76109
// Unsubscribe from the backend to clear the existing push subscription (keys and endpoint)

0 commit comments

Comments
 (0)