'use client' // apps/web/src/lib/web-push-session.ts // One production orchestration boundary for browser device + Web Push state. import webPackage from '../../package.json' import { ensureCurrentWebDevice, findCurrentWebDevice, type WebDeviceEnvironment, } from './web-device' import { getWebPushBrowserStatus, registerExistingWebPushSubscription, requestWebPushPermission, subscribeWebPush, unsubscribeBrowserWebPush, unregisterWebPushServer, WebPushError, type WebPushBrowserStatus, } from './web-push' export type WebPushConnectionStatus = | WebPushBrowserStatus | 'orphaned' | 'revoked' export interface WebPushSessionEnvironment extends WebDeviceEnvironment { vapidPublicKey?: string registration?: ServiceWorkerRegistration | null remoteCleanupTimeoutMs?: number } export const WEB_APP_VERSION = webPackage.version const DISABLED_INTENT_KEY_PREFIX = 'd3ro.voice.web-push.disabled.v1.' const DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS = 5_000 export function reconcileFailedWebPushEnable( currentStatus: WebPushConnectionStatus, ): { enabled: boolean; status: WebPushConnectionStatus | 'error' } { const enabled = currentStatus === 'subscribed' return { enabled, status: enabled ? 'error' : currentStatus, } } export async function signOutWithoutWaitingForWebPushCleanup( cleanup: () => Promise, signOut: () => Promise, ): Promise { try { void cleanup().catch(() => undefined) } catch { // Cleanup is best effort. Logout remains independently available. } await signOut() } function withSessionCleanupTimeout( operation: Promise, timeoutMs: number, ): Promise { const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS return new Promise((resolve, reject) => { const timer = setTimeout(() => { reject(new WebPushError( 'persistence-failed', 'Timed out while resolving the server Web Push registration', )) }, boundedTimeoutMs) operation.then( (value) => { clearTimeout(timer) resolve(value) }, (error: unknown) => { clearTimeout(timer) reject(error) }, ) }) } function disabledIntentKey(userId: string): string { return `${DISABLED_INTENT_KEY_PREFIX}${userId}` } function sessionStorage(environment: WebPushSessionEnvironment): Pick { if (environment.storage) return environment.storage if (typeof window === 'undefined') { throw new Error('Browser storage is unavailable') } return window.localStorage } function hasDisabledIntent(userId: string, environment: WebPushSessionEnvironment): boolean { return sessionStorage(environment).getItem(disabledIntentKey(userId)) === '1' } function recordDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void { sessionStorage(environment).setItem(disabledIntentKey(userId), '1') } function clearDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void { sessionStorage(environment).removeItem(disabledIntentKey(userId)) } export async function getCurrentWebPushConnectionStatus( userId: string, environment: WebPushSessionEnvironment = {}, ): Promise { const browserStatus = await getWebPushBrowserStatus( environment.vapidPublicKey, undefined, environment.registration, ) if (browserStatus !== 'subscribed') return browserStatus if (hasDisabledIntent(userId, environment)) return 'orphaned' const device = await findCurrentWebDevice(userId, environment) if (!device) return 'orphaned' if (device.revokedAt) return 'revoked' // A local PushSubscription is not proof that its server token still exists. // Re-registering is idempotent and makes the server RPC the authority before // the UI can report that Web Push is connected. await registerExistingWebPushSubscription({ userId, deviceId: device.id, client: environment.client, registration: environment.registration, }) return 'subscribed' } export async function enableCurrentWebPush( userId: string, environment: WebPushSessionEnvironment = {}, ): Promise { // Invoke the permission prompt before any network await so this call still // carries the user's transient activation from the sidebar switch gesture. await requestWebPushPermission(environment.vapidPublicKey) const device = await ensureCurrentWebDevice(userId, WEB_APP_VERSION, environment) await subscribeWebPush({ userId, deviceId: device.id, vapidPublicKey: environment.vapidPublicKey, client: environment.client, registration: environment.registration ?? undefined, }) clearDisabledIntent(userId, environment) } export async function disableCurrentWebPush( userId: string, environment: WebPushSessionEnvironment = {}, ): Promise { let intentFailure: unknown try { // Record intent before either remote or local cleanup. If local unsubscribe // fails, the next load stays fail-closed and retries cleanup instead of // treating the stale browser subscription as connected. recordDisabledIntent(userId, environment) } catch (error) { intentFailure = error } const browserCleanup = unsubscribeBrowserWebPush({ registration: environment.registration, }) const remoteCleanupOperation = (async () => { const device = await findCurrentWebDevice(userId, environment) if (!device) return false return unregisterWebPushServer({ deviceId: device.id, client: environment.client, timeoutMs: environment.remoteCleanupTimeoutMs, }) })() const remoteCleanup = withSessionCleanupTimeout( remoteCleanupOperation, environment.remoteCleanupTimeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS, ) const [browserResult, remoteResult] = await Promise.allSettled([ browserCleanup, remoteCleanup, ]) if (browserResult.status === 'rejected') throw browserResult.reason if (remoteResult.status === 'rejected') throw remoteResult.reason if (intentFailure) throw intentFailure }