feat(notifications): android push over webpush for embedded FCM and UnifiedPush (#1141)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-19 21:42:58 +00:00
commit 0d7397eac2
13 files changed
+324 -123

No files matched your search

+19 -19
View File
@@ -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]]
+3 -3
View File
@@ -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" }
@@ -11,7 +11,8 @@ import * as NativePushNotifications from './NativePushNotifications';
const nativePushApi = vi.hoisted(() => ({
isPermissionGranted: vi.fn<() => Promise<boolean>>(),
requestPermission: vi.fn<() => Promise<string>>(),
registerForPushNotifications: vi.fn<() => Promise<string>>(),
registerForPushNotifications:
vi.fn<(vapid?: string) => Promise<{ deviceToken: string; p256dh?: string; auth?: string }>>(),
unregisterForPushNotifications: vi.fn<() => Promise<void>>(),
}));
@@ -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 () => {
@@ -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<NotificationPermiss
return api.requestPermission();
}
export async function ensureNativePushRegistered(): Promise<NativePushRegistrationResult> {
export async function ensureNativePushRegistered(
vapid?: string
): Promise<NativePushRegistrationResult> {
const permission = (await isNativePushPermissionGranted())
? 'granted'
: await requestNativePushPermission();
@@ -67,10 +94,22 @@ export async function ensureNativePushRegistered(): Promise<NativePushRegistrati
}
const api = await getNativePushNotificationsApi();
const token = await api.registerForPushNotifications();
let registration;
try {
registration = await api.registerForPushNotifications(vapid);
} catch (error) {
throw new Error(describeNativePushRegistrationError(error), { cause: error });
}
if (!registration?.deviceToken) {
throw new Error('Native push registration returned no device token.');
}
return {
permission: 'granted',
token,
token: registration.deviceToken,
p256dh: registration.p256dh,
auth: registration.auth,
};
}
@@ -79,30 +118,6 @@ export async function ensureNativePushUnregistered(): Promise<void> {
await api.unregisterForPushNotifications();
}
async function getCurrentNativePushToken(): Promise<string | null> {
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<void> {
const deviceId = mx.getDeviceId() ?? '';
if (!deviceId) {
@@ -143,7 +158,8 @@ export async function enableNativePush(
mx: MatrixClient,
clientConfig: ClientConfig
): Promise<string> {
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<void> {
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();
}
@@ -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<boolean>;
requestPermission: () => Promise<NotificationPermission>;
registerForPushNotifications: () => Promise<string>;
registerForPushNotifications: (vapid?: string) => Promise<NativePushRegistration>;
unregisterForPushNotifications: () => Promise<void>;
};
@@ -9,8 +17,17 @@ let nativePushNotificationsApiPromise: Promise<NativePushNotificationsApi> | nul
export async function getNativePushNotificationsApi(): Promise<NativePushNotificationsApi> {
if (!nativePushNotificationsApiPromise) {
nativePushNotificationsApiPromise =
import('@choochmeque/tauri-plugin-notifications-api') as unknown as Promise<NativePushNotificationsApi>;
nativePushNotificationsApiPromise = import('@choochmeque/tauri-plugin-notifications-api').then(
(notificationsApi) => ({
isPermissionGranted: notificationsApi.isPermissionGranted,
requestPermission: notificationsApi.requestPermission,
registerForPushNotifications: (vapid?: string) =>
invoke<NativePushRegistration>('plugin:notifications|register_for_push_notifications', {
vapid,
}),
unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications,
})
);
}
return nativePushNotificationsApiPromise;
@@ -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 {
@@ -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<string | null>(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]);
@@ -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);
@@ -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<UnifiedPushRegistrationResult, { status: 'registered' }>;
async function registerUnifiedPushWithTimeout(): Promise<UnifiedPushRegistrationResult> {
async function registerUnifiedPushWithTimeout(
vapid?: string
): Promise<UnifiedPushRegistrationResult> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
@@ -89,7 +95,7 @@ async function registerUnifiedPushWithTimeout(): Promise<UnifiedPushRegistration
});
try {
return await Promise.race([registerUnifiedPushTransport(), timeout]);
return await Promise.race([registerUnifiedPushTransport(vapid), timeout]);
} finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
@@ -111,13 +117,42 @@ export async function tryEnableUnifiedPush(
vibration: true,
});
const registration = await registerUnifiedPushWithTimeout();
const registration = await registerUnifiedPushWithTimeout(config?.vapidPublicKey);
if (registration.status !== 'registered') {
return registration;
}
const { endpoint } = registration;
const deviceDisplayName =
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Android Device';
if (registration.p256dh && registration.auth && config?.webPushAppID && config?.pushNotifyUrl) {
await mx.setPusher({
kind: 'http',
app_id: config.webPushAppID,
pushkey: registration.p256dh,
app_display_name: 'Sable (UnifiedPush)',
device_display_name: deviceDisplayName,
lang: navigator.language || 'en',
data: {
url: config.pushNotifyUrl,
format: 'event_id_only',
endpoint,
p256dh: registration.p256dh,
auth: registration.auth,
},
append: false,
} as unknown as IPusherRequest);
return {
status: 'registered',
endpoint,
gatewayUrl: config.pushNotifyUrl,
distributor: registration.distributor,
};
}
const resolvedConfig = resolveUnifiedPushPusherConfig(config);
const gatewayUrl = resolvedConfig.gatewayUrl ?? UP_PUBLIC_GATEWAY;
@@ -130,8 +165,7 @@ export async function tryEnableUnifiedPush(
app_id: resolvedConfig.appId,
pushkey: endpoint,
app_display_name: 'Sable (UnifiedPush)',
device_display_name:
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Android Device',
device_display_name: deviceDisplayName,
lang: navigator.language || 'en',
data: pusherData,
append: false,
@@ -231,6 +265,20 @@ export async function disableUnifiedPush(
)
);
const webPushAppId = trimConfigValue(options.config?.webPushAppID);
if (webPushAppId && webPushAppId !== appId) {
const webPushKeys = await getCurrentDeviceUnifiedPushPushkeys(mx, webPushAppId);
await Promise.allSettled(
webPushKeys.map((pushkey) =>
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);
});
@@ -11,7 +11,8 @@ import {
const unifiedPushApi = vi.hoisted(() => ({
isPermissionGranted: vi.fn<() => Promise<boolean>>(),
requestPermission: vi.fn<() => Promise<string>>(),
registerForPushNotifications: vi.fn<() => Promise<string>>(),
registerForPushNotifications:
vi.fn<(vapid?: string) => Promise<{ deviceToken: string; p256dh?: string; auth?: string }>>(),
unregisterForPushNotifications: vi.fn<() => Promise<void>>(),
listDistributors: vi.fn<() => Promise<string[]>>(),
setDistributor: vi.fn<(name: string) => Promise<void>>(),
@@ -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',
@@ -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<T>(
}
}
export async function registerUnifiedPushTransport(): Promise<UnifiedPushRegistrationResult> {
export async function registerUnifiedPushTransport(
vapid?: string
): Promise<UnifiedPushRegistrationResult> {
let permissionState: UnifiedPushPermissionState = 'default';
let selectedDistributor: string | undefined;
@@ -224,7 +228,8 @@ export async function registerUnifiedPushTransport(): Promise<UnifiedPushRegistr
}
const api = await getUnifiedPushTransportApi();
const endpoint = await api.registerForPushNotifications();
const registration = await api.registerForPushNotifications(vapid);
const endpoint = registration?.deviceToken;
if (!endpoint || !endpoint.trim()) {
return {
status: 'hard-failure',
@@ -239,6 +244,8 @@ export async function registerUnifiedPushTransport(): Promise<UnifiedPushRegistr
permissionState: 'granted',
endpoint,
distributor,
p256dh: registration.p256dh,
auth: registration.auth,
};
} catch (error) {
const failureStatus = classifyUnifiedPushFailure(error);
@@ -1,7 +1,15 @@
import { invoke } from '@tauri-apps/api/core';
export type UnifiedPushRegistration = {
deviceToken: string;
p256dh?: string;
auth?: string;
};
export type UnifiedPushTransportApi = {
isPermissionGranted: () => Promise<boolean>;
requestPermission: () => Promise<NotificationPermission>;
registerForPushNotifications: () => Promise<string>;
registerForPushNotifications: (vapid?: string) => Promise<UnifiedPushRegistration>;
unregisterForPushNotifications: () => Promise<void>;
listDistributors: () => Promise<string[]>;
setDistributor: (name: string) => Promise<void>;
@@ -13,7 +21,10 @@ export async function getUnifiedPushTransportApi(): Promise<UnifiedPushTransport
return {
isPermissionGranted: notificationsApi.isPermissionGranted,
requestPermission: notificationsApi.requestPermission,
registerForPushNotifications: notificationsApi.registerForPushNotifications,
registerForPushNotifications: (vapid?: string) =>
invoke<UnifiedPushRegistration>('plugin:notifications|register_for_push_notifications', {
vapid,
}),
unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications,
listDistributors: notificationsApi.listDistributors,
setDistributor: notificationsApi.setDistributor,
+4
View File
@@ -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) => {