From 671fc8fced4d84a42551632af116c44a03bdf31d Mon Sep 17 00:00:00 2001 From: Kiyoshi <44930252+Kiyo5hi@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:12:07 +0800 Subject: [PATCH] fix(web): preserve notification opt-out during recovery (#2308) --- web/src/hooks/usePushNotifications.test.ts | 56 ++++++++++++++++++++++ web/src/hooks/usePushNotifications.ts | 56 +++++++++++++++++----- 2 files changed, 99 insertions(+), 13 deletions(-) diff --git a/web/src/hooks/usePushNotifications.test.ts b/web/src/hooks/usePushNotifications.test.ts index 27df79c5..f28cd06b 100644 --- a/web/src/hooks/usePushNotifications.test.ts +++ b/web/src/hooks/usePushNotifications.test.ts @@ -169,4 +169,60 @@ describe('usePushNotifications VAPID rotation', () => { await act(async () => { expect(await settings.result.current.unsubscribe()).toBe(true) }) await waitFor(() => expect(startup.result.current.isSubscribed).toBe(false)) }) + + it('keeps an explicit opt-out when an older startup registration finishes later', async () => { + const subscription = createSubscription('https://push.test/current', true) + const manager = setupPushEnvironment(subscription, subscription) + let current: PushSubscriptionMock | null = subscription + manager.getSubscription.mockImplementation(async () => current) + subscription.unsubscribe.mockImplementation(async () => { current = null; return true }) + localStorage.setItem(VAPID_STORAGE_KEY, CURRENT_VAPID_KEY) + let finishRegistration!: () => void + const registration = new Promise(resolve => { finishRegistration = resolve }) + const api = createApi() + api.subscribePushNotifications.mockReturnValueOnce(registration) + const startup = renderHook(() => usePushNotifications(api as unknown as ApiClient)) + const settings = renderHook(() => usePushNotifications(api as unknown as ApiClient)) + await waitFor(() => expect(settings.result.current.isSubscribed).toBe(true)) + + let recovery!: Promise + act(() => { recovery = startup.result.current.subscribe() }) + await waitFor(() => expect(api.subscribePushNotifications).toHaveBeenCalledOnce()) + await act(async () => { expect(await settings.result.current.unsubscribe()).toBe(true) }) + expect(pushNotificationsDisabled()).toBe(true) + await act(async () => { finishRegistration(); expect(await recovery).toBe(false) }) + + expect(pushNotificationsDisabled()).toBe(true) + expect(settings.result.current.isSubscribed).toBe(false) + // The late registration is removed even if the first delete won the race. + expect(api.unsubscribePushNotifications).toHaveBeenCalledTimes(2) + }) + + it('registers a subsequent enable only after stale registration cleanup', async () => { + const oldSubscription = createSubscription('https://push.test/old', true) + const newSubscription = createSubscription('https://push.test/new', true) + const manager = setupPushEnvironment(oldSubscription, newSubscription) + let current: PushSubscriptionMock | null = oldSubscription + manager.getSubscription.mockImplementation(async () => current) + manager.subscribe.mockImplementation(async () => { current = newSubscription; return newSubscription }) + oldSubscription.unsubscribe.mockImplementation(async () => { current = null; return true }) + localStorage.setItem(VAPID_STORAGE_KEY, CURRENT_VAPID_KEY) + let finishOld!: () => void + const oldRequest = new Promise(resolve => { finishOld = resolve }) + const api = createApi() + api.subscribePushNotifications.mockReturnValueOnce(oldRequest) + const startup = renderHook(() => usePushNotifications(api as unknown as ApiClient)) + const settings = renderHook(() => usePushNotifications(api as unknown as ApiClient)) + await waitFor(() => expect(settings.result.current.isSubscribed).toBe(true)) + let oldRecovery!: Promise + act(() => { oldRecovery = startup.result.current.subscribe() }) + await waitFor(() => expect(api.subscribePushNotifications).toHaveBeenCalledOnce()) + await act(async () => { expect(await settings.result.current.unsubscribe()).toBe(true) }) + let enable!: Promise + act(() => { enable = settings.result.current.subscribe() }) + await act(async () => { finishOld(); expect(await oldRecovery).toBe(false); expect(await enable).toBe(true) }) + expect(api.subscribePushNotifications).toHaveBeenCalledTimes(2) + expect(api.unsubscribePushNotifications).toHaveBeenLastCalledWith({ endpoint: oldSubscription.endpoint }) + expect(pushNotificationsDisabled()).toBe(false) + }) }) diff --git a/web/src/hooks/usePushNotifications.ts b/web/src/hooks/usePushNotifications.ts index 33c8e8ae..20d8f3fe 100644 --- a/web/src/hooks/usePushNotifications.ts +++ b/web/src/hooks/usePushNotifications.ts @@ -31,6 +31,19 @@ const PUSH_VAPID_KEY_STORAGE = 'hapi.push.vapidKey' const PUSH_DISABLED_STORAGE = 'hapi.push.disabled' const PUSH_SUBSCRIPTION_CHANGED = 'hapi.push.subscriptionChanged' +// Subscription hooks are mounted independently in the app and settings. +// A later unsubscribe invalidates an earlier recovery, even while the hub +// request is in flight. Registrations are ordered so a stale registration's +// cleanup cannot remove a newer registration for the same endpoint. +let unsubscribeVersion = 0 +let registrationTail: Promise = Promise.resolve() + +function queueRegistration(work: () => Promise): Promise { + const result = registrationTail.then(work) + registrationTail = result.then(() => {}, () => {}) + return result +} + function notifySubscriptionChanged(): void { window.dispatchEvent(new Event(PUSH_SUBSCRIPTION_CHANGED)) } @@ -134,10 +147,12 @@ export function usePushNotifications(api: ApiClient | null) { return false } + const version = unsubscribeVersion try { const registration = await navigator.serviceWorker.ready const existing = await registration.pushManager.getSubscription() const { publicKey } = await api.getPushVapidPublicKey() + if (version !== unsubscribeVersion) return false const applicationServerKey = base64UrlToUint8Array(publicKey).buffer as ArrayBuffer // A subscription created against a previous hub or VAPID key can // never receive notifications from the current hub. Detect the @@ -147,6 +162,7 @@ export function usePushNotifications(api: ApiClient | null) { const staleEndpoint = existing.endpoint const unsubscribed = await existing.unsubscribe() if (!unsubscribed) return false + if (version !== unsubscribeVersion) return false // Prune the obsolete endpoint from the hub so it stops // receiving failed sends (VapidPkHashMismatch) for a // subscription that can no longer be reached. @@ -165,6 +181,12 @@ export function usePushNotifications(api: ApiClient | null) { userVisibleOnly: true, applicationServerKey }) + if (version !== unsubscribeVersion) { + // A disable may have run before the browser finished + // creating this subscription. + if (pushNotificationsDisabled()) await subscription.unsubscribe() + return false + } } const json = subscription.toJSON() @@ -172,22 +194,29 @@ export function usePushNotifications(api: ApiClient | null) { if (!json.endpoint || !keys?.p256dh || !keys.auth) { return false } + const endpoint = json.endpoint + const { p256dh, auth } = keys - await api.subscribePushNotifications({ - endpoint: json.endpoint, - keys: { - p256dh: keys.p256dh, - auth: keys.auth + return await queueRegistration(async () => { + if (version !== unsubscribeVersion) return false + await api.subscribePushNotifications({ + endpoint, + keys: { p256dh, auth } + }) + if (version !== unsubscribeVersion) { + // The delete may have reached the hub before this older + // registration. Remove it again before newer registrations. + if (pushNotificationsDisabled()) { + await api.unsubscribePushNotifications({ endpoint }) + } + return false } + // Persist the key only after the hub registration succeeds. + writeStoredVapidKey(publicKey) + setPushNotificationsDisabled(false) + setIsSubscribed(true) + return true }) - // Only record the key after the hub registration succeeded. A - // failed registration must leave the previous key in place so the - // next load retries the replacement instead of reusing a - // subscription the hub never learned about. - writeStoredVapidKey(publicKey) - setPushNotificationsDisabled(false) - setIsSubscribed(true) - return true } catch (error) { console.error('[PushNotifications] Failed to subscribe:', error) return false @@ -201,6 +230,7 @@ export function usePushNotifications(api: ApiClient | null) { return false } + unsubscribeVersion += 1 try { const registration = await navigator.serviceWorker.ready const subscription = await registration.pushManager.getSubscription()