diff --git a/src/app/features/push/PushNotification.tsx b/src/app/features/push/PushNotification.tsx index bf81640c..a818354e 100644 --- a/src/app/features/push/PushNotification.tsx +++ b/src/app/features/push/PushNotification.tsx @@ -4,7 +4,8 @@ import { SettingTile } from '../../components/setting-tile'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { getNotificationState, usePermissionState } from '../../hooks/usePermission'; import type { ActivePushConfig } from './config'; -import { disablePush, enablePush } from './pusher'; +import { pushSessionToSW } from '../../../sw-session'; +import { disablePush, enablePush, pushIsOn } from './pusher'; export const pushSupported = (): boolean => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; @@ -21,10 +22,10 @@ export function PushNotification({ cfg }: { cfg: ActivePushConfig }) { useEffect(() => { readyManager() - .then((m) => m.getSubscription()) - .then((s) => setOn(!!s)) + .then((m) => pushIsOn(mx, m, cfg)) + .then(setOn) .catch(() => undefined); - }, [cfg]); + }, [cfg, mx]); const toggle = useCallback( async (enable: boolean) => { @@ -39,6 +40,8 @@ export function PushNotification({ cfg }: { cfg: ActivePushConfig }) { } else { await disablePush(mx, await readyManager(), cfg); } + // The worker keeps the token only while a subscription exists: tell it the new state. + pushSessionToSW(mx.baseUrl, mx.getAccessToken() ?? undefined); setOn(enable); } catch (e) { setError(e instanceof Error ? e.message : 'Could not change background notifications.'); diff --git a/src/app/features/push/pusher.test.ts b/src/app/features/push/pusher.test.ts index 73b270cb..ffefa1f4 100644 --- a/src/app/features/push/pusher.test.ts +++ b/src/app/features/push/pusher.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from 'vitest'; import type { IPusherRequest } from 'matrix-js-sdk'; -import { disablePush, enablePush, PushManagerPort, vapidKeyBytes, webPushPusher } from './pusher'; +import { + disablePush, + enablePush, + PushManagerPort, + pushIsOn, + vapidKeyBytes, + webPushPusher, +} from './pusher'; const cfg = { vapidPublicKey: 'BAUD', @@ -9,8 +16,9 @@ const cfg = { }; const key = (...b: number[]) => Uint8Array.from(b).buffer; -function subscription(unsubscribed: string[] = []): PushSubscription { +function subscription(unsubscribed: string[], serverKey?: ArrayBuffer): PushSubscription { return { + options: { applicationServerKey: serverKey ?? vapidKeyBytes(cfg.vapidPublicKey).buffer }, endpoint: 'https://push.example/send/abc', getKey: (n: string) => (n === 'p256dh' ? key(251, 255, 1) : key(250, 2)), unsubscribe: async () => { @@ -30,6 +38,16 @@ function world() { calls.push(p.kind === null ? 'delete-pusher' : 'set-pusher'); pushers.push(p); }, + // The account's pushers as the homeserver would list them: what setPusher last wrote, minus deletions. + getPushers: async () => ({ + pushers: pushers + .filter( + (p, i) => + p.kind !== null && + !pushers.slice(i + 1).some((q) => q.kind === null && q.pushkey === p.pushkey) + ) + .map((p) => ({ app_id: p.app_id, pushkey: p.pushkey })), + }), }; const push: PushManagerPort = { getSubscription: async () => sub, @@ -39,7 +57,10 @@ function world() { return sub; }, }; - return { mx, push, calls, pushers, unsub }; + const swapSub = (s: PushSubscription | null) => { + sub = s; + }; + return { mx, push, calls, pushers, unsub, swapSub }; } describe('web push pusher', () => { @@ -47,7 +68,10 @@ describe('web push pusher', () => { expect([...vapidKeyBytes('-_8')]).toEqual([251, 255]); }); it('is the Sygnal webpush shape: app id, p256dh pushkey, subscription in data, ids only', () => { - const p = webPushPusher(cfg, subscription(), 'phone') as unknown as Record & { + const p = webPushPusher(cfg, subscription([]), 'phone') as unknown as Record< + string, + unknown + > & { data: Record; }; expect(p).toMatchObject({ @@ -91,4 +115,29 @@ describe('web push pusher', () => { await expect(disablePush(w.mx, w.push, cfg)).rejects.toThrow('homeserver said no'); expect(w.unsub).toEqual([]); }); + it('the toggle is on only with a subscription and the pusher of this account for it', async () => { + const w = world(); + expect(await pushIsOn(w.mx, w.push, cfg)).toBe(false); + await enablePush(w.mx, w.push, cfg, 'phone'); + expect(await pushIsOn(w.mx, w.push, cfg)).toBe(true); + // another account on the same browser: the subscription exists, its pusher does not + const other = { ...w.mx, getPushers: async () => ({ pushers: [] }) }; + expect(await pushIsOn(other, w.push, cfg)).toBe(false); + await disablePush(w.mx, w.push, cfg); + expect(await pushIsOn(w.mx, w.push, cfg)).toBe(false); + }); + it('a subscription made under another VAPID key is replaced, not reused', async () => { + const w = world(); + const old = [] as string[]; + w.swapSub(subscription(old, Uint8Array.from([9, 9, 9]).buffer)); + await enablePush(w.mx, w.push, cfg, 'phone'); + expect(old).toEqual(['x']); + expect(w.calls).toEqual(['subscribe:true:3', 'set-pusher']); + }); + it('a failed pusher write after subscribing leaves the toggle off', async () => { + const w = world(); + const fail = { ...w.mx, setPusher: async () => Promise.reject(new Error('no')) }; + await expect(enablePush(fail, w.push, cfg, 'phone')).rejects.toThrow('no'); + expect(await pushIsOn(w.mx, w.push, cfg)).toBe(false); + }); }); diff --git a/src/app/features/push/pusher.ts b/src/app/features/push/pusher.ts index 65c0aca4..d57c2821 100644 --- a/src/app/features/push/pusher.ts +++ b/src/app/features/push/pusher.ts @@ -4,6 +4,7 @@ import type { ActivePushConfig } from './config'; /** What the page needs of the homeserver client and the browser's push manager, so tests supply fakes. */ export interface PusherClient { setPusher(p: IPusherRequest): Promise; + getPushers(): Promise<{ pushers: { app_id: string; pushkey: string }[] }>; } export interface PushManagerPort { getSubscription(): Promise; @@ -54,22 +55,42 @@ export function webPushPusher( } as IPusherRequest; } +const sameKey = (sub: PushSubscription, vapid: Uint8Array): boolean => { + const have = sub.options?.applicationServerKey; + return !have || b64url(have) === b64url(vapid.buffer as ArrayBuffer); +}; + +/** Subscribe (replacing a subscription made under another VAPID key), then register the pusher for this account. */ export async function enablePush( mx: PusherClient, push: PushManagerPort, cfg: ActivePushConfig, deviceName: string ): Promise { - const sub = - (await push.getSubscription()) ?? - (await push.subscribe({ - userVisibleOnly: true, - applicationServerKey: vapidKeyBytes(cfg.vapidPublicKey), - })); + const key = vapidKeyBytes(cfg.vapidPublicKey); + let sub = await push.getSubscription(); + if (sub && !sameKey(sub, key)) { + await sub.unsubscribe(); + sub = null; + } + sub = sub ?? (await push.subscribe({ userVisibleOnly: true, applicationServerKey: key })); await mx.setPusher(webPushPusher(cfg, sub, deviceName)); } -/** Delete the pusher, then the subscription. The order matters: a pusher with no subscription would keep failing at the gateway. */ +/** On only when this browser holds a subscription AND this account has a pusher for it (the two live in different places). */ +export async function pushIsOn( + mx: PusherClient, + push: PushManagerPort, + cfg: ActivePushConfig +): Promise { + const sub = await push.getSubscription(); + if (!sub) return false; + const pushkey = b64url(sub.getKey('p256dh')); + const { pushers } = await mx.getPushers(); + return pushers.some((p) => p.app_id === cfg.appId && p.pushkey === pushkey); +} + +/** Delete this account's pusher, then the subscription. The order matters: a pusher with no subscription would keep failing at the gateway. */ export async function disablePush( mx: PusherClient, push: PushManagerPort, diff --git a/src/app/features/push/sessionStore.test.ts b/src/app/features/push/sessionStore.test.ts index 81668a5f..86cf9147 100644 --- a/src/app/features/push/sessionStore.test.ts +++ b/src/app/features/push/sessionStore.test.ts @@ -29,6 +29,21 @@ describe('sessionStore', () => { await s.save('https://hs/', 5); expect(await s.load()).toBeUndefined(); }); + it('keeps the token only while a push subscription exists', async () => { + const port = memory(); + const s = sessionStore(port); + await s.saveIfSubscribed('https://hs/', 'tok', async () => false); + expect(port.held).toBeUndefined(); + await s.saveIfSubscribed('https://hs/', 'tok', async () => true); + expect(await s.load()).toEqual({ baseUrl: 'https://hs/', accessToken: 'tok' }); + await s.saveIfSubscribed('https://hs/', 'tok', async () => false); + expect(port.held).toBeUndefined(); + await s.saveIfSubscribed('https://hs/', 'tok', async () => true); + await s.saveIfSubscribed('https://hs/', 'tok', () => + Promise.reject(new Error('no push manager')) + ); + expect(port.held).toBeUndefined(); + }); it('ignores a record that is not a session', async () => { const port = memory(); port.held = { baseUrl: 1 }; diff --git a/src/app/features/push/sessionStore.ts b/src/app/features/push/sessionStore.ts index adaa711b..f1835e9c 100644 --- a/src/app/features/push/sessionStore.ts +++ b/src/app/features/push/sessionStore.ts @@ -1,7 +1,8 @@ // The one thing a push needs that a closed app cannot give: the access token, to fetch the event a push names. // Stored: `{ baseUrl, accessToken }`, one record, in this origin's IndexedDB `ratatoskr-sw` (not reachable by other -// origins; the token is already in the page's own storage). Written when the page hands the worker its session, -// deleted when the page hands it none (logout). Nothing else is stored, and nothing else reads it but the push handler. +// origins; the token is already in the page's own storage). Written when the page hands the worker its session +// while this browser holds a push subscription; deleted when the page hands it none (logout) or the subscription is +// gone. A browser that never turned push on stores nothing. Nothing else reads it but the push handler. export interface SessionRecord { baseUrl: string; accessToken: string; @@ -68,6 +69,15 @@ export function sessionStore(port: RecordPort) { : undefined ); }, + /** The token is kept only while this browser holds a push subscription; without one the record is deleted. */ + async saveIfSubscribed( + baseUrl: unknown, + accessToken: unknown, + subscribed: () => Promise + ): Promise { + const keep = await subscribed().catch(() => false); + await this.save(keep ? baseUrl : undefined, keep ? accessToken : undefined); + }, async load(): Promise { const v = (await port.read()) as Partial | undefined; return v && typeof v.baseUrl === 'string' && typeof v.accessToken === 'string' diff --git a/src/app/features/push/worker.test.ts b/src/app/features/push/worker.test.ts index f1f766ce..5eaad32f 100644 --- a/src/app/features/push/worker.test.ts +++ b/src/app/features/push/worker.test.ts @@ -59,6 +59,11 @@ describe('push against a mock gateway and homeserver', () => { expect(shown[0].options.tag).toBeUndefined(); expect(shown[0].options.data).toBeUndefined(); }); + it('shows even when the window list cannot be read', async () => { + const { w, shown } = port({ windows: () => Promise.reject(new Error('no clients')) }); + await handlePush(matrixNotify('!r:x', '$e'), w); + expect(shown).toHaveLength(1); + }); it('shows nothing while a window is visible and focused, and shows when the window is hidden', async () => { const win = (visibilityState: string, focused: boolean) => ({ visibilityState, diff --git a/src/app/features/push/worker.ts b/src/app/features/push/worker.ts index 5e3ccd75..a98f873d 100644 --- a/src/app/features/push/worker.ts +++ b/src/app/features/push/worker.ts @@ -27,7 +27,8 @@ export interface PushTarget { /** A push shows a notification, unless the app is open and focused (browsers allow that, and the page notifies itself). */ export async function handlePush(raw: unknown, w: WorkerPort): Promise { const ids = parsePush(raw); - if ((await w.windows()).some((c) => c.visibilityState === 'visible' && c.focused)) return; + const open = await w.windows().catch(() => []); + if (open.some((c) => c.visibilityState === 'visible' && c.focused)) return; const shown = await describePush(ids, await w.loadSession(), w.fetch); await w.show(shown.title, { body: shown.body, diff --git a/src/sw.ts b/src/sw.ts index 4df85a88..ce9878c9 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -36,7 +36,13 @@ async function cleanupDeadClients() { } function setSession(clientId: string, accessToken: any, baseUrl: any) { - persisted.save(baseUrl, accessToken).catch(() => undefined); + persisted + .saveIfSubscribed( + baseUrl, + accessToken, + async () => !!(await self.registration.pushManager.getSubscription()) + ) + .catch(() => undefined); if (typeof accessToken === 'string' && typeof baseUrl === 'string') { sessions.set(clientId, { accessToken, baseUrl }); } else {