/** * Push on the web and desktop (Electron) editions (omni-plan §7.6, Unit baseline). * * Both end with an FCM token registered on the variant's push subject as Platform 3 (Core keeps those on a web * channel beside the subscriber's phones). They differ in where the token comes from: * - a browser mints it with the Firebase JS SDK against /service-worker.js, which shows each push and hands clicks * back here; * - Electron has no browser push service, so its main process holds an FCM connection of its own * (apps/desktop/src/main/push-receiver.js) and shows notifications natively; the preload bridge * (`window.electronAPI.pushStart/pushStop/pushTakePendingClick/onPushReceived/onPushNotificationClick`) hands the * token and clicks to this page. * The Firebase web app comes from Core's config (WebPush* fields, injected as `getWebPushConfig`); without it there is * no push here. * * Every SDK and IPC step has its own timeout, so a stalled one releases the queue and sign-out can still remove the * previous token. Nothing registered outlives its session: sign-out takes the token off the server and kills it on * this device (queued behind any sync in flight), and a different subject/department rotates the token first. */ import { isPushRegistrationAccepted, pushSourceFor, type PushSubject, registerPushDevice, unregisterPushToken } from '@resgrid/api'; import { isElectron, logger } from '@resgrid/core'; import { toDevProxyUrl } from '@resgrid/core/env/dev-proxy'; import { getApps, initializeApp } from 'firebase/app'; import { deleteToken, getMessaging, getToken, isSupported, type Messaging } from 'firebase/messaging'; import { useEffect, useState } from 'react'; import { z } from 'zod'; import { getOptionalNotificationsDependencies, getPushSource, getPushSubjectKind, isDesktopPushEnabled, type NotificationsDependencies, type PushSubjectKind, readActiveUnitId, readSession, readSignedIn, type WebPushFirebaseConfig, } from './configure'; import { openNotification } from './deep-links'; import { type PushNotificationData, usePushNotificationModalStore } from './push-modal-store'; import { type PushPermissionState, recordPushBlocked, recordPushPermission, recordPushRegistered, resetPushRegistrationStatus } from './push-status'; import { clearRegisteredPushToken, notifyPushTokenRegistered } from './push-token-listeners'; import type { PushNotificationService, PushRegistrationTrigger, RegisterOptions, SignedOutNoticeContent, UsePushNotificationsResult } from './push-types'; import { isRegistrationRefreshDue, PUSH_REGISTRATION_CHECK_INTERVAL_MS, PUSH_REGISTRATION_REFRESH_MS } from './registration-refresh'; import { isRemovalConfirmed, PENDING_SIGN_OUT_MAX_AGE_MS } from './registration-storage'; /** One push as the service worker or the Electron main process hands it over (Core's webPush data block). */ export interface WebPushPayload { title: string; body: string; eventCode: string; type?: string; category?: string; } /** What apps/desktop/src/preload.js exposes for push on `window.electronAPI`. */ export interface DesktopPushBridge { pushStart: (config: WebPushFirebaseConfig) => Promise<{ token?: string; error?: string } | null>; pushStop: (forget: boolean) => Promise; pushTakePendingClick: () => Promise; onPushReceived: (callback: (payload: WebPushPayload) => void) => () => void; onPushNotificationClick: (callback: (payload: WebPushPayload) => void) => () => void; } interface WebIdentity { kind: Exclude; subject: PushSubject; userId: string; prefix: string; unitId?: string; } interface StoredRegistration { key: string; token: string; prefix: string; registeredAt: number; /** Absent on Unit's legacy records (always a unit). */ kind?: Exclude; unitId?: string; userId?: string; /** * The `Source` a `user` registration was made with (Dispatch's `Dispatch`). Removal sends this one, never the app's * current one: a record from before the app had a Source has none, and is taken off without one. */ source?: string; } /** Platforms.Web on the server. */ export const WEB_PUSH_PLATFORM = 3; export const SERVICE_WORKER_URL = '/service-worker.js'; /** Unit's keys (kept, so an upgraded browser's registration is still found and taken off at sign-out). */ export const WEB_PUSH_REGISTRATION_KEY = 'rg.webPush.registration'; /** * A sign-out whose cleanup has not run yet (the ended session's token and server): written before the cleanup is queued * and removed once it ran, so a tab closed during sign-out still kills the token and takes it off on the next load. */ export const WEB_PUSH_PENDING_SIGN_OUT_KEY = 'rg.webPush.pendingSignOut'; /** When the permission prompt was last dismissed without an answer. */ export const WEB_PUSH_ASKED_KEY = 'rg.webPush.asked'; /** A dismissed prompt waits a week: browsers stop a site's prompts for a while after a few dismissals. */ export const ASK_AGAIN_AFTER_MS = 7 * 24 * 60 * 60 * 1000; /** FCM rotates web tokens and the server can lose a registration: sent again as often as the phones' (`registration-refresh.ts`). */ export const REREGISTER_AFTER_MS = PUSH_REGISTRATION_REFRESH_MS; /** A stalled SDK or IPC operation must release the queue so sign-out can remove the previous token. */ export const PUSH_OPERATION_TIMEOUT_MS = 10_000; const FIREBASE_APP_NAME = 'rg-web-push'; async function withPushTimeout(operation: string, work: (signal: AbortSignal) => Promise): Promise { const controller = new AbortController(); let timer: ReturnType | undefined; const timeout = new Promise((_resolve, reject) => { timer = setTimeout(() => { reject(new Error(`Web push: ${operation} timed out`)); controller.abort(); }, PUSH_OPERATION_TIMEOUT_MS); }); try { return await Promise.race([work(controller.signal), timeout]); } finally { clearTimeout(timer); } } const statusListeners = new Set<() => void>(); function notifyStatus(): void { statusListeners.forEach((listener) => listener()); } /** Calls back whenever this device's push status may have changed. Returns the unsubscribe. */ export function subscribeWebPush(listener: () => void): () => void { statusListeners.add(listener); return () => { statusListeners.delete(listener); }; } function readJson(key: string): T | null { try { const raw = window.localStorage.getItem(key); return raw ? (JSON.parse(raw) as T) : null; } catch { return null; } } /** Resolves whether storage took the write. */ function writeJson(key: string, value: unknown): boolean { try { if (value === null) window.localStorage.removeItem(key); else window.localStorage.setItem(key, JSON.stringify(value)); return true; } catch { // Storage unavailable (full, or blocked): the registration just isn't remembered across reloads. return false; } } const readRegistration = (): StoredRegistration | null => { const stored = readJson(WEB_PUSH_REGISTRATION_KEY); return stored && typeof stored.token === 'string' && typeof stored.prefix === 'string' ? stored : null; }; const writeRegistration = (registration: StoredRegistration | null): boolean => writeJson(WEB_PUSH_REGISTRATION_KEY, registration); /** The Electron push bridge, when this page runs in the desktop shell and the variant has desktop push. */ export function getDesktopPushBridge(): DesktopPushBridge | null { if (typeof window === 'undefined' || !isElectron() || !isDesktopPushEnabled()) { return null; } const api = (window as unknown as { electronAPI?: Partial }).electronAPI; return api && typeof api.pushStart === 'function' && typeof api.pushStop === 'function' ? (api as DesktopPushBridge) : null; } function isWebPushConfig(value: unknown): value is WebPushFirebaseConfig { if (!value || typeof value !== 'object') return false; const config = value as Record; return ['apiKey', 'projectId', 'messagingSenderId', 'appId', 'vapidKey'].every((field) => typeof config[field] === 'string' && (config[field] as string).length > 0); } export function getWebPushConfig(deps: NotificationsDependencies | null = getOptionalNotificationsDependencies()): WebPushFirebaseConfig | null { try { const config = deps?.getWebPushConfig?.() ?? null; return isWebPushConfig(config) ? config : null; } catch { return null; } } function browserCanPush(): boolean { return typeof window !== 'undefined' && window.isSecureContext === true && typeof navigator !== 'undefined' && 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; } /** The browser's notification permission as the push status shows it (the desktop receiver needs none). */ const webPermissionOf = (permission: NotificationPermission): PushPermissionState => (permission === 'granted' ? 'granted' : permission === 'denied' ? 'denied' : 'undetermined'); function currentIdentity(deps: NotificationsDependencies | null): WebIdentity | null { if (!deps || !readSignedIn(deps)) return null; const kind = getPushSubjectKind(); if (kind === 'none') return null; const session = readSession(deps); if (!session) return null; if (kind === 'unit') { const unitId = readActiveUnitId(deps); return unitId ? { kind, subject: { kind: 'unit', unitId }, userId: session.userId, prefix: session.departmentCode, unitId } : null; } return { kind, subject: kind === 'icUser' ? { kind: 'icUser' } : { kind: 'user', source: getPushSource() }, userId: session.userId, prefix: session.departmentCode }; } /** Unit keeps its legacy `unit:{unitId}:{prefix}` key; person subjects key on the user. */ const keyOf = (identity: WebIdentity): string => (identity.kind === 'unit' ? `unit:${identity.unitId}:${identity.prefix}` : `${identity.kind}:${identity.userId}:${identity.prefix}`); const subjectOfStored = (stored: StoredRegistration): PushSubject => { const kind = stored.kind ?? (stored.unitId ? 'unit' : 'user'); if (kind === 'unit' && stored.unitId) return { kind: 'unit', unitId: stored.unitId }; if (kind === 'icUser') return { kind: 'icUser' }; return stored.source ? { kind: 'user', source: stored.source } : { kind: 'user' }; }; /** The `Source` a `user` registration for `identity` is made with now (none for unit and IC subjects). */ const sourceOf = (identity: WebIdentity): string | undefined => (identity.subject.kind === 'user' ? identity.subject.source : undefined); // --- Browser (Firebase JS SDK) --- async function loadMessaging(config: WebPushFirebaseConfig): Promise { if (!(await withPushTimeout('messaging support', () => isSupported()))) { return null; } const app = getApps().find((candidate) => candidate.name === FIREBASE_APP_NAME) ?? initializeApp({ apiKey: config.apiKey, authDomain: config.authDomain, projectId: config.projectId, messagingSenderId: config.messagingSenderId, appId: config.appId }, FIREBASE_APP_NAME); return getMessaging(app); } async function findServiceWorker(): Promise { const registrations = await withPushTimeout('find service worker', () => navigator.serviceWorker.getRegistrations()); return ( registrations.find((registration) => { const worker = registration.active ?? registration.waiting ?? registration.installing; return !!worker && new URL(worker.scriptURL).pathname === SERVICE_WORKER_URL; }) ?? null ); } async function mintBrowserToken(config: WebPushFirebaseConfig): Promise { const messaging = await loadMessaging(config); if (!messaging) { return null; } const serviceWorkerRegistration = await withPushTimeout('register service worker', () => navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: '/' })); if (!serviceWorkerRegistration.active) { await withPushTimeout('service worker readiness', () => navigator.serviceWorker.ready); } // Each wait is bounded on its own: a late worker must not start getToken after this operation timed out. return (await withPushTimeout('mint browser token', () => getToken(messaging, { vapidKey: config.vapidKey, serviceWorkerRegistration }))) || null; } /** Kills the browser's token at FCM, so every channel still holding it stops delivering here. Resolves whether it did. */ async function deleteBrowserToken(config: WebPushFirebaseConfig | null): Promise { let registration: ServiceWorkerRegistration | null; try { registration = await findServiceWorker(); } catch { return false; } if (!registration) { // No push worker: nothing in this browser receives with a token. return true; } try { const messaging = config ? await loadMessaging(config) : null; if (messaging && config && Notification.permission === 'granted') { // deleteToken acts on the worker getToken last named; with a token stored this getToken is a local read. await withPushTimeout('read browser token', () => getToken(messaging, { vapidKey: config.vapidKey, serviceWorkerRegistration: registration })); await withPushTimeout('delete browser token', () => deleteToken(messaging)); return true; } } catch (error) { logger.warn({ message: 'Web push: the FCM token could not be deleted', context: { error } }); } // Without Firebase, dropping the push subscription still leaves FCM nowhere to deliver. try { const subscription = await registration.pushManager.getSubscription(); return subscription ? await subscription.unsubscribe() : true; } catch { return false; } } // --- Desktop (Electron main process) --- async function startDesktop(bridge: DesktopPushBridge, config: WebPushFirebaseConfig): Promise { const result = await withPushTimeout('start desktop receiver', () => bridge.pushStart(config)); if (!result?.token) { logger.warn({ message: 'Desktop push could not start', context: { error: result?.error } }); return null; } return result.token; } /** Kills this device's token (browser or desktop receiver). Resolves whether nothing here can receive with it any more. */ async function deleteLocalToken(config: WebPushFirebaseConfig | null): Promise { const desktop = getDesktopPushBridge(); if (desktop) { // Forgetting the credentials leaves nothing on this device able to receive with the old token. try { await withPushTimeout('stop desktop receiver', () => desktop.pushStop(true)); return true; } catch (error) { logger.warn({ message: 'Desktop push: the receiver could not be stopped', context: { error } }); return false; } } return browserCanPush() ? deleteBrowserToken(config) : true; } // --- Registration --- async function unregisterQuietly(deps: NotificationsDependencies, registration: StoredRegistration): Promise { try { await withPushTimeout('unregister previous token', (signal) => unregisterPushToken(deps.getApiContext(), subjectOfStored(registration), 'web', { token: registration.token, prefix: registration.prefix }, { signal })); } catch (error) { logger.warn({ message: 'Web push: the previous registration could not be removed', context: { error } }); } } function readSessionAccess(deps: NotificationsDependencies): { accessToken: string; apiUrl: string; headers: Record } | null { try { const accessToken = deps.getAccessToken?.() ?? null; const apiUrl = deps.getBaseApiUrl(); return accessToken && apiUrl ? { accessToken, apiUrl, headers: deps.getRequestHeaders?.() ?? {} } : null; } catch { return null; } } async function runSync(): Promise { const deps = getOptionalNotificationsDependencies(); const identity = currentIdentity(deps); const config = getWebPushConfig(deps); if (!deps || !identity) { return; } const desktop = getDesktopPushBridge(); // No Firebase web app from the server (web push is off there), or a browser that cannot push. if (!config || (!desktop && !browserCanPush())) { recordPushPermission('unsupported'); recordPushBlocked('unsupported'); return; } recordPushPermission(desktop ? 'granted' : webPermissionOf(Notification.permission)); // A sign-out whose cleanup has not worked yet goes first: until it has, the ended session's registration may still // deliver to the token this sync is about to register. While the stored ones cannot be read, those this load holds. for (const pending of readPendingSignOuts() ?? withUnrecorded([])) { await signOutCleanup(pending, config, deps.getRequestHeaders?.() ?? {}); } // A stored list that cannot be read may hold a sign-out still registered on this device's token, so it is never taken // for an empty one: registration waits for a read that works (the next sync). if (readPendingJournal() === null) { logger.warn({ message: 'Web push: registration waits until the stored sign-outs can be read' }); recordPushBlocked('pendingSignOut'); notifyStatus(); return; } const stored = readRegistration(); if (stored && stored.key !== keyOf(identity)) { // Another subject or department on this device: take the device off the old one, then rotate the token so the old // channel holds a dead one even if that call failed. await unregisterQuietly(deps, stored); writeRegistration(null); await deleteLocalToken(config); } if (!desktop && Notification.permission !== 'granted') { recordPushBlocked('permission'); notifyStatus(); return; } const token = desktop ? await startDesktop(desktop, config) : await mintBrowserToken(config); if (!token) { recordPushBlocked('noToken'); notifyStatus(); return; } // Signed out or moved on while the token was minted: the sign-out cleanup or the sync queued behind this one owns // the device now, and registering here would put the token on a session that has ended. const latest = currentIdentity(deps); if (!latest || keyOf(latest) !== keyOf(identity)) { return; } // Still registered for an ended session whose cleanup failed: registering it here would deliver both sessions' pushes // to this device. The next sync tries that cleanup again first. A list that cannot be read now waits the same way. const pendingSignOuts = readPendingSignOuts(); if (pendingSignOuts === null || pendingSignOuts.some((pending) => pending.registration?.token === token)) { logger.warn({ message: pendingSignOuts === null ? 'Web push: registration waits until the stored sign-outs can be read' : 'Web push: registration waits until the previous session has taken this token off', }); recordPushBlocked('pendingSignOut'); notifyStatus(); return; } const current = readRegistration(); const source = sourceOf(identity); if (current && current.key === keyOf(identity) && current.token === token && current.source === source && !isRegistrationRefreshDue(current.registeredAt)) { notifyPushTokenRegistered({ token, platform: WEB_PUSH_PLATFORM }); recordPushRegistered(token, current.registeredAt); return; } // A new token, or the same token under another Source (a record from before the app had one): take the old // registration off as it was made, so it does not outlive the one that replaces it. if (current && (current.token !== token || current.source !== source)) { await unregisterQuietly(deps, current); } // This session's credentials, read before anything can end it, for taking the registration back off if it does. const sessionAccess = readSessionAccess(deps); const registration: StoredRegistration = { key: keyOf(identity), kind: identity.kind, token, prefix: identity.prefix, userId: identity.userId, ...(identity.unitId ? { unitId: identity.unitId } : {}), registeredAt: Date.now(), }; if (source) registration.source = source; let accepted: boolean; let serverStatus: string | null; try { const result = await withPushTimeout('register device', (signal) => registerPushDevice(deps.getApiContext(), identity.subject, { token, platform: WEB_PUSH_PLATFORM, deviceUuid: deps.getDeviceUuid(), prefix: identity.prefix }, { signal }) ); accepted = isPushRegistrationAccepted(result); serverStatus = result?.Status ?? null; } catch (error) { // A timed-out request may have reached Core: keep the token for the queued sign-out cleanup, but not as registered. writeRegistration({ ...registration, registeredAt: 0 }); recordPushBlocked('error'); throw error; } const registeredIdentity = currentIdentity(deps); if (!registeredIdentity || keyOf(registeredIdentity) !== keyOf(identity)) { // The session ended (or moved to another subject) while Core accepted it: take it off as that session and kill the // token here. The record is kept unmarked first, so when neither works (or there is no session token to do it with) // the sign-out cleanup or the sync queued behind this one still finds it, takes it off and rotates the token. const unmarked = { ...registration, registeredAt: 0 }; writeRegistration(unmarked); if (sessionAccess) { const [removed, tokenKilled] = await Promise.all([unregisterAtServer(registration, sessionAccess.accessToken, sessionAccess.apiUrl, sessionAccess.headers), deleteLocalToken(config)]); if (removed || tokenKilled) { freeSlotIfHolds(unmarked); } notifyStatus(); } return; } if (!accepted) { // RegisterDevice answers 200 when it refuses: not registered, so nobody follows this token and the next sync tries // again. The record stays unmarked for the sign-out cleanup, as after a timeout. writeRegistration({ ...registration, registeredAt: 0 }); recordPushBlocked('notAccepted', { serverStatus }); notifyStatus(); return; } writeRegistration(registration); // Subscribers that follow this registration (the Dispatch desk's own subscriber) take the same token. notifyPushTokenRegistered({ token, platform: WEB_PUSH_PLATFORM }); recordPushRegistered(token, registration.registeredAt); notifyStatus(); } let syncQueue: Promise = Promise.resolve(); let askArmed = false; /** Registration work (syncs and sign-out cleanups) runs one at a time, in the order it was asked for. */ function enqueue(work: () => Promise): Promise { const run = syncQueue.then(work, work); syncQueue = run.catch(() => undefined); return run; } /** Brings this device's registration in line with the signed-in subject. Calls run one at a time. */ export function syncWebPush(): Promise { return enqueue(runSync); } /** * Asks for notification permission the way the phone app does after sign-in, once. Browsers only show the prompt from * a click, so it waits for the first one. A granted permission registers this browser straight away. */ export function askForPermissionOnce(): void { if (getDesktopPushBridge() || !getWebPushConfig() || !browserCanPush() || Notification.permission !== 'default' || askArmed) { return; } const lastAsked = readJson(WEB_PUSH_ASKED_KEY); if (lastAsked && Date.now() - lastAsked < ASK_AGAIN_AFTER_MS) { return; } askArmed = true; const ask = (): void => { document.removeEventListener('click', ask, true); // Asked inside the click, while the browser still counts it as the person's. void Notification.requestPermission() .then((permission) => { // Denied is remembered by the browser; a dismissed prompt waits a week before asking again. writeJson(WEB_PUSH_ASKED_KEY, permission === 'default' ? Date.now() : null); notifyStatus(); return permission === 'granted' ? syncWebPush() : undefined; }) .catch((error: unknown) => logger.warn({ message: 'Web push: the permission request failed', context: { error } })) .finally(() => { askArmed = false; }); }; document.addEventListener('click', ask, true); } /** Resolves whether the server confirmed the token is off the ended session (not just answered). */ async function unregisterAtServer(registration: StoredRegistration, accessToken: string, apiUrl: string, headers: Record): Promise { // Straight to the server, not through the api client: its 401 handling would re-enter logout. Awaited (sign-out waits // on it), so no keepalive: some browsers refuse keepalive on a cross-origin call that needs a preflight. const subject = subjectOfStored(registration); try { const removed = await withPushTimeout('unregister at sign-out', async (signal) => { const response = await fetch(toDevProxyUrl(`${apiUrl.replace(/\/+$/, '')}/Devices/UnRegisterWebPush`), { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` }, body: JSON.stringify({ Token: registration.token, Prefix: registration.prefix, ...(subject.kind === 'unit' ? { UnitId: subject.unitId } : {}), Source: pushSourceFor(subject), }), signal, }); return response.ok && (await isRemovalConfirmed(response)); }); if (!removed) { logger.warn({ message: 'Web push: the server did not take the token off at sign-out' }); } return removed; } catch (error) { logger.warn({ message: 'Web push: the token could not be unregistered at sign-out', context: { error } }); return false; } } /** A registration as a sign-out's record keeps it (the shape `readRegistration()` accepts, Unit's legacy records included). */ const keptRegistrationSchema = z.object({ key: z.string().catch(''), token: z.string().min(1), prefix: z.string(), registeredAt: z.number().catch(0), kind: z.enum(['user', 'unit', 'icUser']).optional().catch(undefined), unitId: z.string().optional().catch(undefined), userId: z.string().optional().catch(undefined), source: z.string().optional().catch(undefined), }); const pendingSignOutSchema = z.object({ id: z.string().min(1), accessToken: z.string().min(1).nullable(), apiUrl: z.string(), signedOutAt: z.number(), /** * The ended session's registration, moved here from its own slot when the cleanup first ran (null: none was stored). * Absent until then: the cleanup reads it as it runs, behind any sync still writing it. */ registration: keptRegistrationSchema.nullable().optional(), }); type PendingWebSignOut = z.infer; let pendingSignOutSequence = 0; /** * A sign-out record's id. Every window of this origin shares the stored list, and a cleanup removes its record by id, so * two windows signing out in the same millisecond (each with its own sequence) must not get the same one. */ const newPendingSignOutId = (): string => { pendingSignOutSequence += 1; return `${Date.now()}-${pendingSignOutSequence}-${Math.random().toString(36).slice(2, 10)}`; }; /** * Sign-outs storage refused to record this load (or whose registration it refused to add), by id. Kept until a write * takes them or their cleanup worked: the next sync still waits for them, and each cleanup tries to record them again. */ const unrecordedSignOuts = new Map(); /** The sign-outs a stored list holds; a corrupt list holds none to take off (the next write replaces it). */ const parsePendingJournal = (raw: string): PendingWebSignOut[] => { try { const parsed = z.array(z.unknown()).safeParse(JSON.parse(raw)); return parsed.success ? parsed.data.flatMap((entry) => { const record = pendingSignOutSchema.safeParse(entry); return record.success ? [record.data] : []; }) : []; } catch { return []; } }; /** The stored sign-outs; null when storage could not be read, which is never taken for none. */ const readPendingJournal = (): PendingWebSignOut[] | null => { let raw: string | null; try { raw = window.localStorage.getItem(WEB_PUSH_PENDING_SIGN_OUT_KEY); } catch { return null; } return raw ? parsePendingJournal(raw) : []; }; /** `journal` with what this load knows and could not record: sign-outs it holds alone, registrations it read for them. */ const withUnrecorded = (journal: PendingWebSignOut[]): PendingWebSignOut[] => [ ...journal.map((entry) => { const known = unrecordedSignOuts.get(entry.id); return entry.registration === undefined && known?.registration !== undefined ? { ...entry, registration: known.registration } : entry; }), ...[...unrecordedSignOuts.values()].filter((known) => !journal.some((entry) => entry.id === known.id)), ]; /** * Every sign-out whose cleanup has not worked yet, the stored ones and those only this load holds. Null while the stored * ones cannot be read: never taken for none (`withUnrecorded([])` is what this load knows). */ const readPendingSignOuts = (): PendingWebSignOut[] | null => { const journal = readPendingJournal(); return journal === null ? null : withUnrecorded(journal); }; /** * Writes the stored sign-outs as `change` leaves them, with everything this load could not record before. Writes nothing * when the stored ones cannot be read, so none is lost. Answers whether storage took it. */ const writePendingSignOuts = (change: (records: PendingWebSignOut[]) => PendingWebSignOut[]): boolean => { const journal = readPendingJournal(); if (journal === null) { return false; } const records = change(withUnrecorded(journal)); const stored = writeJson(WEB_PUSH_PENDING_SIGN_OUT_KEY, records.length > 0 ? records : null); if (stored) { unrecordedSignOuts.clear(); } return stored; }; /** * Empties the registration slot when it still holds `registration` (same token, key and registration time), so a newer * registration written there since is never freed. */ function freeSlotIfHolds(registration: StoredRegistration | PendingWebSignOut['registration']): void { const slot = keptRegistrationSchema.safeParse(readJson(WEB_PUSH_REGISTRATION_KEY)); const kept = keptRegistrationSchema.safeParse(registration); if (slot.success && kept.success && slot.data.token === kept.data.token && slot.data.key === kept.data.key && slot.data.registeredAt === kept.data.registeredAt) { writeRegistration(null); } } /** * Kills the token here and takes the ended session's registration off the server as that session (its token, while Core * still accepts it). Either one stops that session's pushes reaching this device, so the record goes once either has * worked, or when nothing was registered; otherwise it stays, for the next load and the next sync (`runSync`). */ async function signOutCleanup(queued: PendingWebSignOut, config: WebPushFirebaseConfig | null, headers: Record): Promise { const journal = readPendingJournal(); const pending = withUnrecorded(journal ?? []).find((entry) => entry.id === queued.id) ?? queued; // The ended session's registration is read once, when its cleanup first runs, and kept with the record: its slot is // freed then, and a later try must not take off whatever registers there after this. const registration = pending.registration === undefined ? readRegistration() : pending.registration; // Only once storage holds it with the record: until then it stays in its slot too, for a later load to find. A sign-out // storage has not recorded (or could not be read for) is kept for this load with the registration, so the next sync // still waits for it, and recording it is tried again now. One no longer pending (finished already) is not brought back. let recorded = journal?.find((entry) => entry.id === pending.id)?.registration !== undefined; if (!recorded && (journal === null || journal.some((entry) => entry.id === pending.id) || unrecordedSignOuts.has(pending.id))) { unrecordedSignOuts.set(pending.id, { ...pending, registration }); recorded = writePendingSignOuts((records) => records); } // Also on a later try: a run stopped between recording it and freeing the slot left it in both. if (recorded && registration) { freeSlotIfHolds(registration); } const accessToken = Date.now() - pending.signedOutAt < PENDING_SIGN_OUT_MAX_AGE_MS ? pending.accessToken : null; // Killing the token runs beside the server call, not after it: sign-out only waits so long, and this device has to // stop showing the session's pushes even when the server is slow to answer. const [tokenKilled, removed] = await Promise.all([deleteLocalToken(config), registration && accessToken && pending.apiUrl ? unregisterAtServer(registration, accessToken, pending.apiUrl, headers) : false]); notifyStatus(); if (!registration || tokenKilled || removed) { unrecordedSignOuts.delete(pending.id); writePendingSignOuts((records) => records.filter((entry) => entry.id !== pending.id)); // A registration the record could not hold stayed in its slot: it is dealt with now. if (registration) freeSlotIfHolds(registration); return; } logger.warn({ message: 'Web push: the sign-out cleanup did not finish; it runs again before the next registration and on the next load' }); } /** Runs a sign-out cleanup in the queue. Its record goes only once the cleanup has worked, so a closed tab runs it again. */ function runSignOutCleanup(pending: PendingWebSignOut, config: WebPushFirebaseConfig | null, headers: Record): Promise { return enqueue(() => signOutCleanup(pending, config, headers)).catch((error: unknown) => { logger.warn({ message: 'Web push sign-out cleanup failed', context: { error } }); }); } /** Sign-out: read the session's config and server NOW (a server switch applies once sign-out returns), then clean up in order. */ function unregisterWebPushAtSignOut(accessToken: string | null): Promise { const deps = getOptionalNotificationsDependencies(); const config = getWebPushConfig(deps); const apiUrl = deps?.getBaseApiUrl() ?? ''; const headers = deps?.getRequestHeaders?.() ?? {}; const pending: PendingWebSignOut = { id: newPendingSignOutId(), accessToken, apiUrl, signedOutAt: Date.now() }; // Before anything is awaited: a tab or window closed during sign-out finishes this cleanup on its next load. One record // per sign-out, so a cleanup that finishes never takes another sign-out's record with it. One storage refuses is kept // for this load (the next sync waits for it), and each try of its cleanup records it again. unrecordedSignOuts.set(pending.id, pending); if (!writePendingSignOuts((records) => records)) { logger.warn({ message: 'Web push: the sign-out could not be recorded; it is kept for this page and recorded on its next try' }); } // Queued behind any sync in flight, so the registration that sync is still writing is the one taken off. The next // sign-in's sync queues behind this in turn. return runSignOutCleanup(pending, config, headers); } /** Sign-outs the last load did not finish, queued first, so no registration of the next session runs before them. */ function resumePendingSignOuts(): void { const deps = getOptionalNotificationsDependencies(); (readPendingSignOuts() ?? withUnrecorded([])).forEach((pending) => { void runSignOutCleanup(pending, getWebPushConfig(deps), deps?.getRequestHeaders?.() ?? {}); }); } // --- Incoming pushes --- const toNotificationData = (payload: WebPushPayload): PushNotificationData => ({ eventCode: payload.eventCode, ...(payload.title ? { title: payload.title } : {}), ...(payload.body ? { body: payload.body } : {}), data: { ...payload }, }); function showInApp(payload: WebPushPayload | null | undefined): void { if (!payload?.eventCode) { return; } // The browser/desktop played nothing for a push to a focused page, so the in-app alert brings its own sound. void usePushNotificationModalStore.getState().showNotificationModal(toNotificationData(payload), { playSound: true }); } /** A clicked notification goes where a tapped one does on the phone; anything that does not route shows the in-app alert. */ export async function openWebPush(payload: WebPushPayload | null | undefined): Promise { if (!payload?.eventCode) { return false; } return openNotification(toNotificationData(payload)); } /** A push arriving while the person is looking at the page gets the in-app alert, as on the phone. */ function onServiceWorkerPush(payload: WebPushPayload): void { if (typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus()) { showInApp(payload); } } let detachListeners: (() => void) | null = null; /** Wires clicks and foreground pushes to the app. Safe to call repeatedly. */ export function attachWebPushListeners(): void { if (detachListeners || typeof window === 'undefined') { return; } const desktop = getDesktopPushBridge(); if (desktop) { const offReceived = desktop.onPushReceived(showInApp); const offClick = desktop.onPushNotificationClick((payload) => void openWebPush(payload)); detachListeners = () => { offReceived(); offClick(); }; // A click that started (or re-opened) the window arrived before this page could listen. void withPushTimeout('take pending click', () => desktop.pushTakePendingClick()) .then((payload) => (payload ? openWebPush(payload) : undefined)) .catch(() => undefined); return; } if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) { return; } const onMessage = (event: MessageEvent): void => { const message = event.data as { type?: string; data?: WebPushPayload } | undefined; if (message?.type === 'NOTIFICATION_CLICK' && message.data) { void openWebPush(message.data); } else if (message?.type === 'PUSH_RECEIVED' && message.data) { onServiceWorkerPush(message.data); } }; navigator.serviceWorker.addEventListener('message', onMessage); detachListeners = () => navigator.serviceWorker.removeEventListener('message', onMessage); // If the worker opened this window for a click, it hands the click over once told the page is ready. void findServiceWorker() .then((registration) => (navigator.serviceWorker.controller ?? registration?.active)?.postMessage({ type: 'CLIENT_READY' })) .catch(() => undefined); } async function clearWebBadge(): Promise { try { const nav = typeof navigator === 'undefined' ? null : (navigator as Navigator & { clearAppBadge?: () => Promise }); await nav?.clearAppBadge?.(); } catch { // Badging API unsupported or refused. } } /** Test hook. */ export function resetWebPushForTests(): void { detachListeners?.(); detachListeners = null; syncQueue = Promise.resolve(); askArmed = false; statusListeners.clear(); unrecordedSignOuts.clear(); } // --- The app's push API, as the native module offers it --- export const pushNotificationService: PushNotificationService & { resetForTests(): void } = { initialize: async (): Promise => { resumePendingSignOuts(); attachWebPushListeners(); }, registerForPushNotifications: async (options?: RegisterOptions): Promise => { // Asked from a click (Settings → Register again): the browser shows its prompt only from one, and only while it // has not been answered. if (options?.requestPermission && !getDesktopPushBridge() && getWebPushConfig() && browserCanPush() && Notification.permission === 'default') { await Notification.requestPermission().catch(() => logger.warn({ message: 'Web push: the permission request failed' })); } await syncWebPush(); return readRegistration()?.token ?? null; }, unregisterAtSignOut: (accessToken: string | null): Promise => unregisterWebPushAtSignOut(accessToken), // The sign-out cleanup already took the token off the server and killed it here. clearLocalState: async (): Promise => { clearRegisteredPushToken(); resetPushRegistrationStatus(); usePushNotificationModalStore.getState().hideNotificationModal(); await clearWebBadge(); }, // The next sync sends the registration again (Settings → Register again): one not marked registered is due. resetRegistration: (): void => { const current = typeof window === 'undefined' ? null : readRegistration(); if (current && current.registeredAt !== 0) { writeRegistration({ ...current, registeredAt: 0 }); } }, // A browser or desktop app shows the sign-in screen the next time it is looked at. showSignedOutNotice: async (_content: SignedOutNoticeContent): Promise => undefined, getPushToken: (): string | null => readRegistration()?.token ?? null, clearBadge: clearWebBadge, openNotification: (notification: PushNotificationData): Promise => openNotification(notification), cleanup: (): void => { detachListeners?.(); detachListeners = null; }, resetForTests: resetWebPushForTests, }; const syncInBackground = (): void => { syncWebPush().catch((error) => logger.error({ message: 'Web push registration failed', context: { error } })); }; /** * Keeps this browser/desktop registered while signed in: syncs when the session's identity changes, every * `PUSH_REGISTRATION_CHECK_INTERVAL_MS` while the page stays open (a dispatch desk or a wall runs for days) and when a * hidden tab is shown again (timers stop while a laptop sleeps). Each sync sends the registration again once it is due * (`REREGISTER_AFTER_MS`) and picks up a token the browser or the desktop receiver replaced. */ export const usePushNotifications = (trigger: PushRegistrationTrigger): UsePushNotificationsResult => { const [pushToken, setPushToken] = useState(() => (typeof window === 'undefined' ? null : (readRegistration()?.token ?? null))); const key = trigger.signedIn && trigger.userId && trigger.departmentCode && trigger.webPushConfigured ? [trigger.serverUrl ?? '', trigger.userId, trigger.departmentCode, trigger.unitId ?? ''].join('|') : null; useEffect(() => { attachWebPushListeners(); return subscribeWebPush(() => setPushToken(readRegistration()?.token ?? null)); }, []); useEffect(() => { // Registering before auth settles would send a stale token (see the native hook). if (!key) { return; } syncInBackground(); askForPermissionOnce(); }, [key]); useEffect(() => { if (!key) { return undefined; } const timer = setInterval(syncInBackground, PUSH_REGISTRATION_CHECK_INTERVAL_MS); const onVisibilityChange = (): void => { if (document.visibilityState === 'visible') syncInBackground(); }; const canWatchVisibility = typeof document !== 'undefined'; if (canWatchVisibility) document.addEventListener('visibilitychange', onVisibilityChange); return () => { clearInterval(timer); if (canWatchVisibility) document.removeEventListener('visibilitychange', onVisibilityChange); }; }, [key]); return { pushToken }; };