From 3b4e41267502349d337c07c88e91c7d9edb3fc2f Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 19 Jul 2026 22:45:43 +0200 Subject: [PATCH] feat(notifications): android push over webpush for embedded FCM and UnifiedPush --- src-tauri/Cargo.lock | 38 ++--- src-tauri/Cargo.toml | 6 +- .../NativePushNotifications.test.ts | 92 ++++++++--- .../notifications/NativePushNotifications.ts | 146 +++++++++++------- .../NativePushNotificationsApiClient.ts | 23 ++- .../NotificationTransportRuntime.ts | 4 + .../NotificationTransportRuntimeFeature.tsx | 31 +++- .../notifications/SystemNotification.tsx | 4 + .../notifications/UnifiedPushNotifications.ts | 62 +++++++- .../UnifiedPushTransport.test.ts | 11 +- .../notifications/UnifiedPushTransport.ts | 11 +- .../UnifiedPushTransportApiClient.ts | 15 +- src/app/hooks/usePermission.ts | 4 + 13 files changed, 324 insertions(+), 123 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 20f90b9ab..0fa65b93e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -148,7 +148,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -159,7 +159,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -957,7 +957,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" dependencies = [ "lazy_static", - "windows-sys 0.59.0", + "windows-sys 0.48.0", ] [[package]] @@ -1481,7 +1481,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1783,7 +1783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2705,7 +2705,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.3", + "socket2 0.5.10", "system-configuration", "tokio", "tower-service", @@ -3530,7 +3530,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.18", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3654,7 +3654,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4040,7 +4040,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -4684,7 +4684,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.3", + "socket2 0.5.10", "thiserror 2.0.18", "tokio", "tracing", @@ -4721,7 +4721,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.3", + "socket2 0.5.10", "tracing", "windows-sys 0.60.2", ] @@ -5124,7 +5124,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5182,7 +5182,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5756,7 +5756,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6433,7 +6433,7 @@ dependencies = [ [[package]] name = "tauri-plugin-notifications" version = "0.5.0-rc.11" -source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=95c1574cf4c2be0f3e7c1d7b8102b2f7b59bcb68#95c1574cf4c2be0f3e7c1d7b8102b2f7b59bcb68" +source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=df09f08e64b840e4d51cde2720030836eed40f4c#df09f08e64b840e4d51cde2720030836eed40f4c" dependencies = [ "log", "notify-rust", @@ -6767,7 +6767,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7393,7 +7393,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.18", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7467,7 +7467,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8124,7 +8124,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 21ebe5f30..48aa95609 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -62,12 +62,12 @@ windows = { version = "0.61", features = [ tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] } [target.'cfg(any(windows, target_os = "linux"))'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "95c1574cf4c2be0f3e7c1d7b8102b2f7b59bcb68" } +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "df09f08e64b840e4d51cde2720030836eed40f4c" } # default-features = false drops notify-rust so macOS uses the native # UNUserNotificationCenter backend (needs a signed .app to deliver). [target.'cfg(target_os = "macos")'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "95c1574cf4c2be0f3e7c1d7b8102b2f7b59bcb68", default-features = false } +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "df09f08e64b840e4d51cde2720030836eed40f4c", default-features = false } [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] tauri-plugin-updater = "2" @@ -88,7 +88,7 @@ cef = { version = "=148.0.0", optional = true } libloading = "0.8" [target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "95c1574cf4c2be0f3e7c1d7b8102b2f7b59bcb68", features = [ +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "df09f08e64b840e4d51cde2720030836eed40f4c", features = [ "push-notifications", ] } tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" } diff --git a/src/app/features/settings/notifications/NativePushNotifications.test.ts b/src/app/features/settings/notifications/NativePushNotifications.test.ts index 6b9dfde81..96dae434d 100644 --- a/src/app/features/settings/notifications/NativePushNotifications.test.ts +++ b/src/app/features/settings/notifications/NativePushNotifications.test.ts @@ -11,7 +11,8 @@ import * as NativePushNotifications from './NativePushNotifications'; const nativePushApi = vi.hoisted(() => ({ isPermissionGranted: vi.fn<() => Promise>(), requestPermission: vi.fn<() => Promise>(), - registerForPushNotifications: vi.fn<() => Promise>(), + registerForPushNotifications: + vi.fn<(vapid?: string) => Promise<{ deviceToken: string; p256dh?: string; auth?: string }>>(), unregisterForPushNotifications: vi.fn<() => Promise>(), })); @@ -67,7 +68,7 @@ describe('native push permission flow', () => { describe('ensureNativePushRegistered', () => { it('registers immediately when permission is already granted', async () => { nativePushApi.isPermissionGranted.mockResolvedValue(true); - nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + nativePushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: 'native-token' }); await expect(ensureNativePushRegistered()).resolves.toEqual({ permission: 'granted', @@ -80,7 +81,7 @@ describe('ensureNativePushRegistered', () => { it('requests permission before registering and returns a token on grant', async () => { nativePushApi.isPermissionGranted.mockResolvedValue(false); nativePushApi.requestPermission.mockResolvedValue('granted'); - nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + nativePushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: 'native-token' }); await expect(ensureNativePushRegistered()).resolves.toEqual({ permission: 'granted', @@ -111,12 +112,34 @@ describe('ensureNativePushRegistered', () => { }); expect(nativePushApi.registerForPushNotifications).not.toHaveBeenCalled(); }); + + it('reports a clear error when the build has no Firebase configuration', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockRejectedValue( + new Error( + 'Default FirebaseApp is not initialized in this process moe.sable.client. Make sure to call FirebaseApp.initializeApp(Context) first.' + ) + ); + + await expect(ensureNativePushRegistered()).rejects.toThrow('google-services.json'); + }); + + it('surfaces the underlying reason for other registration failures', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockRejectedValue( + new Error('SERVICE_NOT_AVAILABLE') + ); + + await expect(ensureNativePushRegistered()).rejects.toThrow( + 'Native push registration failed: SERVICE_NOT_AVAILABLE' + ); + }); }); describe('native push pusher registration', () => { it('registers a Matrix pusher with the native device token', async () => { nativePushApi.isPermissionGranted.mockResolvedValue(true); - nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + nativePushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: 'native-token' }); await expect(enableNativePush(matrixClient as never, nativePushClientConfig)).resolves.toBe( 'native-token' @@ -137,7 +160,7 @@ describe('native push pusher registration', () => { it('rejects native push enablement when the app id is missing', async () => { nativePushApi.isPermissionGranted.mockResolvedValue(true); - nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + nativePushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: 'native-token' }); await expect( enableNativePush(matrixClient as never, { @@ -148,7 +171,45 @@ describe('native push pusher registration', () => { ).rejects.toThrow('nativePushAppID'); }); - it('removes native pushers and unregisters the platform token', async () => { + it('registers a Sygnal WebPush pusher when the distributor returns keys', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockResolvedValue({ + deviceToken: 'https://fcm.googleapis.com/fcm/send/endpoint', + p256dh: 'p256-key', + auth: 'auth-secret', + }); + + const webPushConfig = { + pushNotificationDetails: { + webPushAppID: 'moe.sable.app.sygnal', + nativePushAppID: 'moe.sable.mobile', + pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify', + vapidPublicKey: 'vapid-pub', + }, + } as const; + + await expect(enableNativePush(matrixClient as never, webPushConfig)).resolves.toBe('p256-key'); + expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledWith('vapid-pub'); + expect(localStorage.getItem('nativePushAppId')).toBe('moe.sable.app.sygnal'); + expect(localStorage.getItem('nativePushToken')).toBe('p256-key'); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: 'http', + app_id: 'moe.sable.app.sygnal', + pushkey: 'p256-key', + data: expect.objectContaining({ + url: 'https://sygnal.example/_matrix/push/v1/notify', + format: 'event_id_only', + endpoint: 'https://fcm.googleapis.com/fcm/send/endpoint', + p256dh: 'p256-key', + auth: 'auth-secret', + }), + }) + ); + }); + + it('removes the stored pusher and unregisters the platform token', async () => { + localStorage.setItem('nativePushAppId', 'moe.sable.mobile'); localStorage.setItem('nativePushToken', 'native-token'); await expect( @@ -164,24 +225,7 @@ describe('native push pusher registration', () => { ); expect(nativePushApi.unregisterForPushNotifications).toHaveBeenCalledOnce(); expect(localStorage.getItem('nativePushToken')).toBeNull(); - }); - - it('recovers the current token before removing the Matrix pusher when local storage is empty', async () => { - nativePushApi.isPermissionGranted.mockResolvedValue(true); - nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); - - await expect( - disableNativePush(matrixClient as never, nativePushClientConfig) - ).resolves.toBeUndefined(); - - expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce(); - expect(matrixClient.setPusher).toHaveBeenCalledWith( - expect.objectContaining({ - kind: null, - app_id: 'moe.sable.mobile', - pushkey: 'native-token', - }) - ); + expect(localStorage.getItem('nativePushAppId')).toBeNull(); }); it('falls back to removing current-device pushers when the token cannot be recovered', async () => { diff --git a/src/app/features/settings/notifications/NativePushNotifications.ts b/src/app/features/settings/notifications/NativePushNotifications.ts index 3659b5d82..96382e9e8 100644 --- a/src/app/features/settings/notifications/NativePushNotifications.ts +++ b/src/app/features/settings/notifications/NativePushNotifications.ts @@ -2,12 +2,15 @@ import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk'; import type { ClientConfig } from '$hooks/useClientConfig'; import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient'; -const NATIVE_PUSH_TOKEN_STORAGE_KEY = 'nativePushToken'; +const NATIVE_PUSH_PUSHKEY_STORAGE_KEY = 'nativePushToken'; +const NATIVE_PUSH_APP_ID_STORAGE_KEY = 'nativePushAppId'; export type NativePushRegistrationResult = | { permission: 'granted'; token: string; + p256dh?: string; + auth?: string; } | { permission: 'default' | 'denied'; @@ -16,16 +19,30 @@ export type NativePushRegistrationResult = export type { NativePushNotificationsApi } from './NativePushNotificationsApiClient'; -function storeNativePushToken(token: string): void { - localStorage.setItem(NATIVE_PUSH_TOKEN_STORAGE_KEY, token); +const FIREBASE_UNCONFIGURED_PATTERN = /firebaseapp is not initialized|default firebaseapp/i; + +function describeNativePushRegistrationError(error: unknown): string { + const detail = error instanceof Error ? error.message : String(error); + if (FIREBASE_UNCONFIGURED_PATTERN.test(detail)) { + return 'Native push (FCM) is unavailable: this build has no Firebase configuration (google-services.json).'; + } + return `Native push registration failed: ${detail}`; } -function getStoredNativePushToken(): string | null { - return localStorage.getItem(NATIVE_PUSH_TOKEN_STORAGE_KEY); +function storeNativePushRegistration(appId: string, pushkey: string): void { + localStorage.setItem(NATIVE_PUSH_APP_ID_STORAGE_KEY, appId); + localStorage.setItem(NATIVE_PUSH_PUSHKEY_STORAGE_KEY, pushkey); } -function clearStoredNativePushToken(): void { - localStorage.removeItem(NATIVE_PUSH_TOKEN_STORAGE_KEY); +function getStoredNativePushRegistration(): { appId: string; pushkey: string } | null { + const appId = localStorage.getItem(NATIVE_PUSH_APP_ID_STORAGE_KEY); + const pushkey = localStorage.getItem(NATIVE_PUSH_PUSHKEY_STORAGE_KEY); + return appId && pushkey ? { appId, pushkey } : null; +} + +function clearStoredNativePushRegistration(): void { + localStorage.removeItem(NATIVE_PUSH_APP_ID_STORAGE_KEY); + localStorage.removeItem(NATIVE_PUSH_PUSHKEY_STORAGE_KEY); } function getNativePushAppId(clientConfig: ClientConfig): string { @@ -36,6 +53,14 @@ function getNativePushAppId(clientConfig: ClientConfig): string { return appId; } +function getWebPushAppId(clientConfig: ClientConfig): string { + const appId = clientConfig.pushNotificationDetails?.webPushAppID; + if (!appId) { + throw new Error('WebPush push requires pushNotificationDetails.webPushAppID in config.json.'); + } + return appId; +} + function getPushGatewayUrl(clientConfig: ClientConfig): string { const pushGatewayUrl = clientConfig.pushNotificationDetails?.pushNotifyUrl; if (!pushGatewayUrl) { @@ -54,7 +79,9 @@ export async function requestNativePushPermission(): Promise { +export async function ensureNativePushRegistered( + vapid?: string +): Promise { const permission = (await isNativePushPermissionGranted()) ? 'granted' : await requestNativePushPermission(); @@ -67,10 +94,22 @@ export async function ensureNativePushRegistered(): Promise { await api.unregisterForPushNotifications(); } -async function getCurrentNativePushToken(): Promise { - const storedToken = getStoredNativePushToken(); - if (storedToken) { - return storedToken; - } - - if (!(await isNativePushPermissionGranted())) { - return null; - } - - try { - const api = await getNativePushNotificationsApi(); - const token = await api.registerForPushNotifications(); - if (!token) { - return null; - } - - storeNativePushToken(token); - return token; - } catch { - return null; - } -} - async function removeNativePushersForCurrentDevice(mx: MatrixClient, appId: string): Promise { const deviceId = mx.getDeviceId() ?? ''; if (!deviceId) { @@ -143,7 +158,8 @@ export async function enableNativePush( mx: MatrixClient, clientConfig: ClientConfig ): Promise { - const registration = await ensureNativePushRegistered(); + const vapid = clientConfig.pushNotificationDetails?.vapidPublicKey; + const registration = await ensureNativePushRegistered(vapid); if (registration.permission !== 'granted' || !registration.token) { throw new Error( @@ -153,16 +169,40 @@ export async function enableNativePush( ); } - const appId = getNativePushAppId(clientConfig); const pushGatewayUrl = getPushGatewayUrl(clientConfig); + const deviceDisplayName = + (await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Mobile Device'; + if (registration.p256dh && registration.auth) { + const appId = getWebPushAppId(clientConfig); + await mx.setPusher({ + kind: 'http', + app_id: appId, + pushkey: registration.p256dh, + app_display_name: 'Sable (Native Push)', + device_display_name: deviceDisplayName, + lang: navigator.language || 'en', + data: { + url: pushGatewayUrl, + format: 'event_id_only', + endpoint: registration.token, + p256dh: registration.p256dh, + auth: registration.auth, + }, + append: false, + } as unknown as IPusherRequest); + + storeNativePushRegistration(appId, registration.p256dh); + return registration.p256dh; + } + + const appId = getNativePushAppId(clientConfig); await mx.setPusher({ kind: 'http', app_id: appId, pushkey: registration.token, app_display_name: 'Sable (Native Push)', - device_display_name: - (await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Mobile Device', + device_display_name: deviceDisplayName, lang: navigator.language || 'en', data: { url: pushGatewayUrl, @@ -171,7 +211,7 @@ export async function enableNativePush( append: false, } as unknown as IPusherRequest); - storeNativePushToken(registration.token); + storeNativePushRegistration(appId, registration.token); return registration.token; } @@ -179,21 +219,21 @@ export async function disableNativePush( mx: MatrixClient, clientConfig: ClientConfig ): Promise { - const appId = clientConfig.pushNotificationDetails?.nativePushAppID; - if (appId) { - const token = await getCurrentNativePushToken(); - - if (token) { - await mx.setPusher({ - kind: null, - app_id: appId, - pushkey: token, - } as unknown as IPusherRequest); - } else { - await removeNativePushersForCurrentDevice(mx, appId); - } + const stored = getStoredNativePushRegistration(); + if (stored) { + await mx.setPusher({ + kind: null, + app_id: stored.appId, + pushkey: stored.pushkey, + } as unknown as IPusherRequest); + } else { + const appIds = [ + clientConfig.pushNotificationDetails?.webPushAppID, + clientConfig.pushNotificationDetails?.nativePushAppID, + ].filter((appId): appId is string => Boolean(appId)); + await Promise.all(appIds.map((appId) => removeNativePushersForCurrentDevice(mx, appId))); } await ensureNativePushUnregistered(); - clearStoredNativePushToken(); + clearStoredNativePushRegistration(); } diff --git a/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts index e1fb5c607..a30a028a7 100644 --- a/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts +++ b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts @@ -1,7 +1,15 @@ +import { invoke } from '@tauri-apps/api/core'; + +export type NativePushRegistration = { + deviceToken: string; + p256dh?: string; + auth?: string; +}; + export type NativePushNotificationsApi = { isPermissionGranted: () => Promise; requestPermission: () => Promise; - registerForPushNotifications: () => Promise; + registerForPushNotifications: (vapid?: string) => Promise; unregisterForPushNotifications: () => Promise; }; @@ -9,8 +17,17 @@ let nativePushNotificationsApiPromise: Promise | nul export async function getNativePushNotificationsApi(): Promise { if (!nativePushNotificationsApiPromise) { - nativePushNotificationsApiPromise = - import('@choochmeque/tauri-plugin-notifications-api') as unknown as Promise; + nativePushNotificationsApiPromise = import('@choochmeque/tauri-plugin-notifications-api').then( + (notificationsApi) => ({ + isPermissionGranted: notificationsApi.isPermissionGranted, + requestPermission: notificationsApi.requestPermission, + registerForPushNotifications: (vapid?: string) => + invoke('plugin:notifications|register_for_push_notifications', { + vapid, + }), + unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications, + }) + ); } return nativePushNotificationsApiPromise; diff --git a/src/app/features/settings/notifications/NotificationTransportRuntime.ts b/src/app/features/settings/notifications/NotificationTransportRuntime.ts index 09cfa540a..fcc4b1bf3 100644 --- a/src/app/features/settings/notifications/NotificationTransportRuntime.ts +++ b/src/app/features/settings/notifications/NotificationTransportRuntime.ts @@ -29,6 +29,10 @@ const defaultListenerFactories: NotificationTransportListenerFactories = { const { listenForUnifiedPushMessages } = await import('./UnifiedPushNotifications'); return listenForUnifiedPushMessages(getContext); }, + native: async (getContext) => { + const { listenForUnifiedPushMessages } = await import('./UnifiedPushNotifications'); + return listenForUnifiedPushMessages(getContext); + }, }; export class NotificationTransportRuntime { diff --git a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx index 0cac7c416..1c2c02e59 100644 --- a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx +++ b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx @@ -7,6 +7,7 @@ import { useClientConfig } from '$hooks/useClientConfig'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { enableUnifiedPush } from './UnifiedPushNotifications'; +import { enableNativePush } from './NativePushNotifications'; import { NotificationTransportRuntime, type NotificationTransportRuntimeContext, @@ -76,7 +77,13 @@ export function NotificationTransportRuntimeFeature() { void runtimeRef.current?.sync(provider, () => contextRef.current); }, [provider]); - const upConfigRef = useRef<{ unifiedPushAppID?: string; unifiedPushGatewayUrl?: string }>({}); + const upConfigRef = useRef<{ + unifiedPushAppID?: string; + unifiedPushGatewayUrl?: string; + vapidPublicKey?: string; + webPushAppID?: string; + pushNotifyUrl?: string; + }>({}); upConfigRef.current = { unifiedPushAppID: pushTransportOverride?.unifiedPushAppID ?? @@ -84,17 +91,23 @@ export function NotificationTransportRuntimeFeature() { unifiedPushGatewayUrl: pushTransportOverride?.unifiedPushGatewayUrl ?? clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl, + vapidPublicKey: clientConfig.pushNotificationDetails?.vapidPublicKey, + webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID, + pushNotifyUrl: clientConfig.pushNotificationDetails?.pushNotifyUrl, }; // Keep the pusher current: establish it when UnifiedPush becomes the active // transport (so it survives a fresh install/session, not just a manual toggle) // and refresh it whenever the distributor rotates the endpoint. Deduped by // endpoint so re-registration can't loop. + const clientConfigRef = useRef(clientConfig); + clientConfigRef.current = clientConfig; + const lastEndpointRef = useRef(null); useEffect(() => { - if (provider !== 'unifiedpush' || !mx) return undefined; + if (!mx) return undefined; - const establish = () => { + if (provider === 'unifiedpush') { enableUnifiedPush(mx, upConfigRef.current) .then((result) => { lastEndpointRef.current = result.endpoint; @@ -102,9 +115,15 @@ export function NotificationTransportRuntimeFeature() { .catch((error) => { log.warn('UnifiedPush pusher registration failed at startup', error); }); - }; - - establish(); + } else if (provider === 'native') { + enableNativePush(mx, clientConfigRef.current) + .then((token) => { + lastEndpointRef.current = token; + }) + .catch((error) => { + log.warn('Native push pusher registration failed at startup', error); + }); + } return () => {}; }, [provider, mx]); diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 329a21a9d..0a2e77cd1 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -589,6 +589,9 @@ function BackgroundPushNotificationSetting() { const buildUnifiedPushTransportConfig = (): UnifiedPushTransportConfigInput => ({ unifiedPushGatewayUrl: effectivePushTransport.unifiedPushGatewayUrl, unifiedPushAppID: effectivePushTransport.unifiedPushAppID, + vapidPublicKey: clientConfig.pushNotificationDetails?.vapidPublicKey, + webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID, + pushNotifyUrl: clientConfig.pushNotificationDetails?.pushNotifyUrl, }); const buildRegisteredUnifiedPushState = ( @@ -683,6 +686,7 @@ function BackgroundPushNotificationSetting() { config: { unifiedPushAppID: currentUnifiedPushState?.appId ?? effectivePushTransport.unifiedPushAppID, + webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID, }, }); setUnifiedPushEndpointState(null); diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index 3df707d01..4f369b855 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -50,7 +50,11 @@ const UP_REGISTER_TIMEOUT_MS = 30_000; export type UnifiedPushTransportConfigInput = Pick< PushTransportConfig, 'unifiedPushGatewayUrl' | 'unifiedPushAppID' ->; +> & { + vapidPublicKey?: string; + webPushAppID?: string; + pushNotifyUrl?: string; +}; type UnifiedPushPusherConfig = { appId: string; @@ -80,7 +84,9 @@ export type EnableUnifiedPushResult = } | Exclude; -async function registerUnifiedPushWithTimeout(): Promise { +async function registerUnifiedPushWithTimeout( + vapid?: string +): Promise { let timeoutId: ReturnType | undefined; const timeout = new Promise((_, reject) => { timeoutId = setTimeout(() => { @@ -89,7 +95,7 @@ async function registerUnifiedPushWithTimeout(): Promise + mx.setPusher({ + kind: null, + app_id: webPushAppId, + pushkey, + } as unknown as IPusherRequest) + ) + ); + } + await unregisterUnifiedPushTransport(); } @@ -598,7 +646,7 @@ export function listenForUnifiedPushMessages(getSettings: () => NotificationSett } ); - return addPluginListener('unifiedpush', 'push-message', (data: unknown) => { + return addPluginListener('notifications', 'push-message', (data: unknown) => { const notification = parseUnifiedPushMessage(data); if (notification) dispatch(notification); }); diff --git a/src/app/features/settings/notifications/UnifiedPushTransport.test.ts b/src/app/features/settings/notifications/UnifiedPushTransport.test.ts index 872efe7a4..72a726d25 100644 --- a/src/app/features/settings/notifications/UnifiedPushTransport.test.ts +++ b/src/app/features/settings/notifications/UnifiedPushTransport.test.ts @@ -11,7 +11,8 @@ import { const unifiedPushApi = vi.hoisted(() => ({ isPermissionGranted: vi.fn<() => Promise>(), requestPermission: vi.fn<() => Promise>(), - registerForPushNotifications: vi.fn<() => Promise>(), + registerForPushNotifications: + vi.fn<(vapid?: string) => Promise<{ deviceToken: string; p256dh?: string; auth?: string }>>(), unregisterForPushNotifications: vi.fn<() => Promise>(), listDistributors: vi.fn<() => Promise>(), setDistributor: vi.fn<(name: string) => Promise>(), @@ -49,7 +50,9 @@ describe('registerUnifiedPushTransport', () => { unifiedPushApi.requestPermission.mockResolvedValue('granted'); localStorage.removeItem('unifiedpush_distributor'); unifiedPushApi.listDistributors.mockResolvedValue(['org.unifiedpush.distributor.ntfy']); - unifiedPushApi.registerForPushNotifications.mockResolvedValue('https://up.example/endpoint'); + unifiedPushApi.registerForPushNotifications.mockResolvedValue({ + deviceToken: 'https://up.example/endpoint', + }); await expect(registerUnifiedPushTransport()).resolves.toEqual({ status: 'registered', @@ -108,7 +111,7 @@ describe('registerUnifiedPushTransport', () => { unifiedPushApi.isPermissionGranted.mockResolvedValue(true); localStorage.setItem('unifiedpush_distributor', 'org.example.up'); unifiedPushApi.listDistributors.mockResolvedValue(['org.example.up']); - unifiedPushApi.registerForPushNotifications.mockResolvedValue(''); + unifiedPushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: '' }); await expect(registerUnifiedPushTransport()).resolves.toMatchObject({ status: 'hard-failure', @@ -121,7 +124,7 @@ describe('registerUnifiedPushTransport', () => { unifiedPushApi.isPermissionGranted.mockResolvedValue(true); localStorage.setItem('unifiedpush_distributor', 'org.example.up'); unifiedPushApi.listDistributors.mockResolvedValue(['org.example.up']); - unifiedPushApi.registerForPushNotifications.mockResolvedValue(' '); + unifiedPushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: ' ' }); await expect(registerUnifiedPushTransport()).resolves.toMatchObject({ status: 'hard-failure', diff --git a/src/app/features/settings/notifications/UnifiedPushTransport.ts b/src/app/features/settings/notifications/UnifiedPushTransport.ts index a07261ac3..cf43752db 100644 --- a/src/app/features/settings/notifications/UnifiedPushTransport.ts +++ b/src/app/features/settings/notifications/UnifiedPushTransport.ts @@ -20,6 +20,8 @@ export type UnifiedPushRegistrationResult = permissionState: 'granted'; endpoint: string; distributor: string; + p256dh?: string; + auth?: string; } | { status: 'temp-unavailable'; @@ -191,7 +193,9 @@ export async function switchUnifiedPushDistributorSelection( } } -export async function registerUnifiedPushTransport(): Promise { +export async function registerUnifiedPushTransport( + vapid?: string +): Promise { let permissionState: UnifiedPushPermissionState = 'default'; let selectedDistributor: string | undefined; @@ -224,7 +228,8 @@ export async function registerUnifiedPushTransport(): Promise Promise; requestPermission: () => Promise; - registerForPushNotifications: () => Promise; + registerForPushNotifications: (vapid?: string) => Promise; unregisterForPushNotifications: () => Promise; listDistributors: () => Promise; setDistributor: (name: string) => Promise; @@ -13,7 +21,10 @@ export async function getUnifiedPushTransportApi(): Promise + invoke('plugin:notifications|register_for_push_notifications', { + vapid, + }), unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications, listDistributors: notificationsApi.listDistributors, setDistributor: notificationsApi.setDistributor, diff --git a/src/app/hooks/usePermission.ts b/src/app/hooks/usePermission.ts index 71a601be2..1a01d88ec 100644 --- a/src/app/hooks/usePermission.ts +++ b/src/app/hooks/usePermission.ts @@ -22,6 +22,10 @@ export function usePermissionState(name: PermissionName, initialValue: Permissio setPermissionState(this.state); } + if (!navigator.permissions?.query) { + return undefined; + } + navigator.permissions .query({ name }) .then((permStatus: PermissionStatus) => {