mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-24 02:51:17 -08:00
feat(push): implement MSC4174 web push pusher kind
This commit is contained in:
16 files changed
+1347
-123
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type * as WebPushSupportModule from './webPushSupport';
|
||||
import {
|
||||
disableNativePush,
|
||||
enableNativePush,
|
||||
@@ -20,6 +21,10 @@ const getNativePushNotificationsApi = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<typeof nativePushApi>>().mockResolvedValue(nativePushApi)
|
||||
);
|
||||
|
||||
const getWebPushServerSupport = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<WebPushSupportModule.WebPushServerSupport>>()
|
||||
);
|
||||
|
||||
const matrixClient = vi.hoisted(() => ({
|
||||
setPusher: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
getDeviceId: vi.fn<() => string>(() => 'DEVICE'),
|
||||
@@ -29,6 +34,7 @@ const matrixClient = vi.hoisted(() => ({
|
||||
getPushers: vi
|
||||
.fn<() => Promise<{ pushers: Array<unknown> }>>()
|
||||
.mockResolvedValue({ pushers: [] }),
|
||||
getSafeUserId: vi.fn<() => string>(() => '@user:example.com'),
|
||||
}));
|
||||
|
||||
const nativePushClientConfig = {
|
||||
@@ -42,6 +48,15 @@ vi.mock('./NativePushNotificationsApiClient', () => ({
|
||||
getNativePushNotificationsApi,
|
||||
}));
|
||||
|
||||
vi.mock('./webPushSupport', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof WebPushSupportModule>();
|
||||
return { ...actual, getWebPushServerSupport };
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
@@ -208,6 +223,108 @@ describe('native push pusher registration', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('registers an MSC4174 webpush pusher with the homeserver VAPID key when supported', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: 'hs-vapid' });
|
||||
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('hs-vapid');
|
||||
expect(localStorage.getItem('nativePushAppId')).toBe('moe.sable.app.sygnal');
|
||||
expect(localStorage.getItem('nativePushToken')).toBe('p256-key');
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'org.matrix.msc4174.webpush',
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
pushkey: 'p256-key',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://fcm.googleapis.com/fcm/send/endpoint',
|
||||
auth: 'auth-secret',
|
||||
format: 'event_id_only',
|
||||
default_payload: { user_id: '@user:example.com' },
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('removes stale http gateway pushers when registering an MSC4174 webpush pusher', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: 'hs-vapid' });
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue({
|
||||
deviceToken: 'https://fcm.googleapis.com/fcm/send/endpoint',
|
||||
p256dh: 'p256-key',
|
||||
auth: 'auth-secret',
|
||||
});
|
||||
matrixClient.getPushers.mockResolvedValue({
|
||||
pushers: [
|
||||
{
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
pushkey: 'old-p256-key',
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'http',
|
||||
},
|
||||
{
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
pushkey: 'other-device-key',
|
||||
device_display_name: 'Other Phone',
|
||||
kind: 'http',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const webPushConfig = {
|
||||
pushNotificationDetails: {
|
||||
webPushAppID: 'moe.sable.app.sygnal',
|
||||
nativePushAppID: 'moe.sable.mobile',
|
||||
vapidPublicKey: 'vapid-pub',
|
||||
},
|
||||
} as const;
|
||||
|
||||
await expect(enableNativePush(matrixClient as never, webPushConfig)).resolves.toBe('p256-key');
|
||||
// One webpush registration + one stale http pusher removal.
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledTimes(2);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith({
|
||||
kind: null,
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
pushkey: 'old-p256-key',
|
||||
});
|
||||
});
|
||||
|
||||
it('honors the gateway URL override for plain-token native push', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue({ deviceToken: 'native-token' });
|
||||
|
||||
await expect(
|
||||
enableNativePush(
|
||||
matrixClient as never,
|
||||
nativePushClientConfig,
|
||||
'https://other-gateway.example/_matrix/push/v1/notify'
|
||||
)
|
||||
).resolves.toBe('native-token');
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'http',
|
||||
pushkey: 'native-token',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://other-gateway.example/_matrix/push/v1/notify',
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('removes the stored pusher and unregisters the platform token', async () => {
|
||||
localStorage.setItem('nativePushAppId', 'moe.sable.mobile');
|
||||
localStorage.setItem('nativePushToken', 'native-token');
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk';
|
||||
import type { ClientConfig } from '$hooks/useClientConfig';
|
||||
import { MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND } from '$unstable/prefixes';
|
||||
import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient';
|
||||
import { resolvePushNotifyUrl } from './PushPusherConfig';
|
||||
import { getWebPushServerSupport, removeStaleHttpPushers } from './webPushSupport';
|
||||
|
||||
const NATIVE_PUSH_PUSHKEY_STORAGE_KEY = 'nativePushToken';
|
||||
const NATIVE_PUSH_APP_ID_STORAGE_KEY = 'nativePushAppId';
|
||||
@@ -61,12 +64,12 @@ function getWebPushAppId(clientConfig: ClientConfig): string {
|
||||
return appId;
|
||||
}
|
||||
|
||||
function getPushGatewayUrl(clientConfig: ClientConfig): string {
|
||||
function getPushGatewayUrl(clientConfig: ClientConfig, pushNotifyUrlOverride?: string): string {
|
||||
const pushGatewayUrl = clientConfig.pushNotificationDetails?.pushNotifyUrl;
|
||||
if (!pushGatewayUrl) {
|
||||
if (!pushGatewayUrl && !pushNotifyUrlOverride?.trim()) {
|
||||
throw new Error('Native push requires pushNotificationDetails.pushNotifyUrl in config.json.');
|
||||
}
|
||||
return pushGatewayUrl;
|
||||
return resolvePushNotifyUrl(pushGatewayUrl, pushNotifyUrlOverride);
|
||||
}
|
||||
|
||||
export async function isNativePushPermissionGranted(): Promise<boolean | null> {
|
||||
@@ -136,7 +139,7 @@ async function removeNativePushersForCurrentDevice(mx: MatrixClient, appId: stri
|
||||
(pusher) =>
|
||||
pusher.app_id === appId &&
|
||||
pusher.device_display_name === deviceDisplayName &&
|
||||
pusher.kind === 'http'
|
||||
(pusher.kind === 'http' || pusher.kind === MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND)
|
||||
);
|
||||
|
||||
if (currentDevicePushers.length === 0) {
|
||||
@@ -156,9 +159,13 @@ async function removeNativePushersForCurrentDevice(mx: MatrixClient, appId: stri
|
||||
|
||||
export async function enableNativePush(
|
||||
mx: MatrixClient,
|
||||
clientConfig: ClientConfig
|
||||
clientConfig: ClientConfig,
|
||||
pushNotifyUrlOverride?: string
|
||||
): Promise<string> {
|
||||
const vapid = clientConfig.pushNotificationDetails?.vapidPublicKey;
|
||||
const webPushSupport = await getWebPushServerSupport(mx);
|
||||
const vapid = webPushSupport.supported
|
||||
? webPushSupport.vapidPublicKey
|
||||
: clientConfig.pushNotificationDetails?.vapidPublicKey;
|
||||
const registration = await ensureNativePushRegistered(vapid);
|
||||
|
||||
if (registration.permission !== 'granted' || !registration.token) {
|
||||
@@ -169,12 +176,36 @@ export async function enableNativePush(
|
||||
);
|
||||
}
|
||||
|
||||
const pushGatewayUrl = getPushGatewayUrl(clientConfig);
|
||||
const deviceDisplayName =
|
||||
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Mobile Device';
|
||||
|
||||
if (registration.p256dh && registration.auth) {
|
||||
const appId = getWebPushAppId(clientConfig);
|
||||
|
||||
if (webPushSupport.supported) {
|
||||
// MSC4174: registration.token is the web push endpoint (e.g. FCM's).
|
||||
await mx.setPusher({
|
||||
kind: MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND,
|
||||
app_id: appId,
|
||||
pushkey: registration.p256dh,
|
||||
app_display_name: 'Sable (Native Push)',
|
||||
device_display_name: deviceDisplayName,
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: registration.token,
|
||||
format: 'event_id_only',
|
||||
auth: registration.auth,
|
||||
default_payload: { user_id: mx.getSafeUserId() },
|
||||
},
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
|
||||
await removeStaleHttpPushers(mx, appId, [deviceDisplayName]);
|
||||
storeNativePushRegistration(appId, registration.p256dh);
|
||||
return registration.p256dh;
|
||||
}
|
||||
|
||||
const pushGatewayUrl = getPushGatewayUrl(clientConfig, pushNotifyUrlOverride);
|
||||
await mx.setPusher({
|
||||
kind: 'http',
|
||||
app_id: appId,
|
||||
@@ -196,6 +227,7 @@ export async function enableNativePush(
|
||||
return registration.p256dh;
|
||||
}
|
||||
|
||||
const pushGatewayUrl = getPushGatewayUrl(clientConfig, pushNotifyUrlOverride);
|
||||
const appId = getNativePushAppId(clientConfig);
|
||||
await mx.setPusher({
|
||||
kind: 'http',
|
||||
|
||||
@@ -125,6 +125,9 @@ export function NotificationTransportRuntimeFeature() {
|
||||
const clientConfigRef = useRef(clientConfig);
|
||||
clientConfigRef.current = clientConfig;
|
||||
|
||||
const pushNotifyUrlOverrideRef = useRef(pushNotifyUrlOverride);
|
||||
pushNotifyUrlOverrideRef.current = pushNotifyUrlOverride;
|
||||
|
||||
const lastEndpointRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!mx) return undefined;
|
||||
@@ -142,7 +145,11 @@ export function NotificationTransportRuntimeFeature() {
|
||||
const result = await enableUnifiedPush(mx, upConfigRef.current);
|
||||
lastEndpointRef.current = result.endpoint;
|
||||
} else if (provider === 'native') {
|
||||
const token = await enableNativePush(mx, clientConfigRef.current);
|
||||
const token = await enableNativePush(
|
||||
mx,
|
||||
clientConfigRef.current,
|
||||
pushNotifyUrlOverrideRef.current
|
||||
);
|
||||
lastEndpointRef.current = token;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
||||
import type * as WebPushSupportModule from './webPushSupport';
|
||||
|
||||
const isTauri = vi.hoisted(() => vi.fn<() => boolean>());
|
||||
const getWebPushServerSupport = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<WebPushSupportModule.WebPushServerSupport>>()
|
||||
);
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ isTauri }));
|
||||
vi.mock('./webPushSupport', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof WebPushSupportModule>();
|
||||
return { ...actual, getWebPushServerSupport };
|
||||
});
|
||||
|
||||
import {
|
||||
enablePushNotifications,
|
||||
@@ -10,13 +18,104 @@ import {
|
||||
togglePusher,
|
||||
} from './PushNotifications';
|
||||
|
||||
const matrixClient = vi.hoisted(() => ({
|
||||
getAccessToken: vi.fn<() => string>(() => 'token'),
|
||||
}));
|
||||
const clientConfig = {} as never;
|
||||
const MSC4174_KIND = 'org.matrix.msc4174.webpush';
|
||||
const VAPID =
|
||||
'BCnS4SbHjeOaqVFW4wjt5xDt_pYIL62qMzKePfYF9fl9PQU14RieIaObh7nLR_9dQf4sykZa-CTrcjkgMIE1mcg';
|
||||
const SERVER_VAPID =
|
||||
'BNbXV88MfMI0fSxB7cDngopoviZRTbxIS0qSS-O7BZCtG04khMOn-PP2uez_X7Aeci42n02kJ0-JJJ0uQ4ELRTs';
|
||||
const ENDPOINT = 'https://push.example.org/wpush/v2/subscription';
|
||||
const P256DH =
|
||||
'BLn9b-VR0ca83knDNZ32dCHGyjJp0000000000000000000000000000000000000000000000000000000000000000';
|
||||
const AUTH = '_ordMnz7uTCmrpBTeUV4Bw';
|
||||
|
||||
const setPushSubscription = vi.fn<(subscription: PushSubscription | null) => void>();
|
||||
|
||||
function base64UrlToArrayBuffer(value: string): ArrayBuffer {
|
||||
const base64 = value.replaceAll('-', '+').replaceAll('_', '/');
|
||||
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
||||
const binary = atob(padded);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
type MockSubscription = {
|
||||
endpoint: string;
|
||||
options: { applicationServerKey: ArrayBuffer | null };
|
||||
unsubscribe: Mock<() => Promise<void>>;
|
||||
toJSON: () => PushSubscriptionJSON;
|
||||
};
|
||||
|
||||
function makeSubscription(applicationServerKey: string | null): MockSubscription {
|
||||
return {
|
||||
endpoint: ENDPOINT,
|
||||
options: {
|
||||
applicationServerKey: applicationServerKey
|
||||
? base64UrlToArrayBuffer(applicationServerKey)
|
||||
: null,
|
||||
},
|
||||
unsubscribe: vi.fn<() => Promise<void>>(async () => {}),
|
||||
toJSON: () => ({ endpoint: ENDPOINT, keys: { p256dh: P256DH, auth: AUTH } }),
|
||||
};
|
||||
}
|
||||
|
||||
const postMessage = vi.fn<(message: unknown) => void>();
|
||||
const getSubscription = vi.fn<() => Promise<MockSubscription | null>>();
|
||||
const subscribe = vi.fn<(options: unknown) => Promise<MockSubscription>>();
|
||||
|
||||
function createMatrixClient() {
|
||||
return {
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
getAccessToken: vi.fn<() => string>(() => 'token'),
|
||||
getDeviceId: vi.fn<() => string>(() => 'DEVICE'),
|
||||
getDevice: vi.fn<() => Promise<{ display_name: string }>>(async () => ({
|
||||
display_name: 'Test Device',
|
||||
})),
|
||||
getSafeUserId: vi.fn<() => string>(() => '@alice:example.org'),
|
||||
getPushers: vi.fn<() => Promise<{ pushers: Array<Record<string, unknown>> }>>(async () => ({
|
||||
pushers: [],
|
||||
})),
|
||||
setPusher: vi.fn<() => Promise<Record<string, never>>>(async () => ({})),
|
||||
};
|
||||
}
|
||||
|
||||
const clientConfig = {
|
||||
pushNotificationDetails: {
|
||||
pushNotifyUrl: 'https://sygnal.example.org/_matrix/push/v1/notify',
|
||||
vapidPublicKey: VAPID,
|
||||
webPushAppID: 'moe.sable.app.sygnal',
|
||||
},
|
||||
} as never;
|
||||
|
||||
type TogglePushMessage = {
|
||||
url: string;
|
||||
type: string;
|
||||
token: string;
|
||||
pusherData: Record<string, unknown> & { kind?: unknown; data: Record<string, unknown> };
|
||||
};
|
||||
|
||||
function lastTogglePushMessage(): TogglePushMessage {
|
||||
return postMessage.mock.calls.at(-1)?.[0] as unknown as TogglePushMessage;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isTauri.mockReturnValue(false);
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: false });
|
||||
getSubscription.mockResolvedValue(null);
|
||||
subscribe.mockImplementation(async () => makeSubscription(VAPID));
|
||||
vi.stubGlobal('PushManager', {});
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
configurable: true,
|
||||
value: {
|
||||
ready: Promise.resolve({ pushManager: { getSubscription, subscribe } }),
|
||||
controller: { postMessage },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('enablePushNotifications', () => {
|
||||
@@ -24,12 +123,147 @@ describe('enablePushNotifications', () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
enablePushNotifications(matrixClient as never, clientConfig, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
enablePushNotifications({} as never, clientConfig, [null, setPushSubscription])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('registers an MSC4174 webpush pusher when the server supports it', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: SERVER_VAPID });
|
||||
const mx = createMatrixClient();
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [null, setPushSubscription]);
|
||||
|
||||
expect(subscribe).toHaveBeenCalledWith({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: SERVER_VAPID,
|
||||
});
|
||||
expect(postMessage).toHaveBeenCalledTimes(1);
|
||||
const message = lastTogglePushMessage();
|
||||
expect(message.type).toBe('togglePush');
|
||||
expect(message.url).toBe('https://matrix.example.org');
|
||||
expect(message.token).toBe('token');
|
||||
expect(message.pusherData.kind).toBe(MSC4174_KIND);
|
||||
expect(message.pusherData.pushkey).toBe(P256DH);
|
||||
expect(message.pusherData.app_id).toBe('moe.sable.app.sygnal');
|
||||
expect(message.pusherData.data).toMatchObject({
|
||||
url: ENDPOINT,
|
||||
auth: AUTH,
|
||||
format: 'event_id_only',
|
||||
});
|
||||
expect(message.pusherData.data).not.toHaveProperty('endpoint');
|
||||
expect(message.pusherData.data).not.toHaveProperty('p256dh');
|
||||
});
|
||||
|
||||
it('removes stale http gateway pushers for this device when switching to MSC4174', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: SERVER_VAPID });
|
||||
const mx = createMatrixClient();
|
||||
mx.getPushers.mockResolvedValue({
|
||||
pushers: [
|
||||
{
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
kind: 'http',
|
||||
pushkey: 'old-p256dh',
|
||||
device_display_name: 'Test Device',
|
||||
},
|
||||
{
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
kind: 'http',
|
||||
pushkey: 'other-device-p256dh',
|
||||
device_display_name: 'Some Other Device',
|
||||
},
|
||||
{ app_id: 'm.email', kind: 'email', pushkey: '[email protected]', device_display_name: '[email protected]' },
|
||||
],
|
||||
});
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [null, setPushSubscription]);
|
||||
|
||||
expect(mx.setPusher).toHaveBeenCalledTimes(1);
|
||||
expect(mx.setPusher).toHaveBeenCalledWith({
|
||||
kind: null,
|
||||
app_id: 'moe.sable.app.sygnal',
|
||||
pushkey: 'old-p256dh',
|
||||
});
|
||||
});
|
||||
|
||||
it('registers an http gateway pusher when the server does not support MSC4174', async () => {
|
||||
const mx = createMatrixClient();
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [null, setPushSubscription]);
|
||||
|
||||
expect(subscribe).toHaveBeenCalledWith({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: VAPID,
|
||||
});
|
||||
const message = lastTogglePushMessage();
|
||||
expect(message.pusherData.kind).toBe('http');
|
||||
expect(message.pusherData.data).toMatchObject({
|
||||
url: 'https://sygnal.example.org/_matrix/push/v1/notify',
|
||||
format: 'event_id_only',
|
||||
endpoint: ENDPOINT,
|
||||
p256dh: P256DH,
|
||||
auth: AUTH,
|
||||
});
|
||||
expect(mx.setPusher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('honors the gateway URL override for the http fallback', async () => {
|
||||
const mx = createMatrixClient();
|
||||
const override = 'https://other-gateway.example.org/_matrix/push/v1/notify';
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [null, setPushSubscription], override);
|
||||
|
||||
const message = lastTogglePushMessage();
|
||||
expect(message.pusherData.kind).toBe('http');
|
||||
expect(message.pusherData.data.url).toBe(override);
|
||||
});
|
||||
|
||||
it('rejects an invalid gateway URL override', async () => {
|
||||
const mx = createMatrixClient();
|
||||
|
||||
await expect(
|
||||
enablePushNotifications(
|
||||
mx as never,
|
||||
clientConfig,
|
||||
[null, setPushSubscription],
|
||||
'not-a-gateway-url'
|
||||
)
|
||||
).rejects.toThrow(/Push gateway URL/);
|
||||
expect(postMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses the existing subscription when endpoint and VAPID key match', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: SERVER_VAPID });
|
||||
getSubscription.mockResolvedValue(makeSubscription(SERVER_VAPID));
|
||||
const mx = createMatrixClient();
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [
|
||||
{ endpoint: ENDPOINT, keys: { p256dh: P256DH, auth: AUTH } },
|
||||
setPushSubscription,
|
||||
]);
|
||||
|
||||
expect(subscribe).not.toHaveBeenCalled();
|
||||
const message = lastTogglePushMessage();
|
||||
expect(message.pusherData.kind).toBe(MSC4174_KIND);
|
||||
});
|
||||
|
||||
it('re-subscribes when the stored subscription used a different VAPID key', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: SERVER_VAPID });
|
||||
const oldSubscription = makeSubscription(VAPID);
|
||||
getSubscription.mockResolvedValue(oldSubscription);
|
||||
subscribe.mockImplementation(async () => makeSubscription(SERVER_VAPID));
|
||||
const mx = createMatrixClient();
|
||||
|
||||
await enablePushNotifications(mx as never, clientConfig, [
|
||||
{ endpoint: ENDPOINT, keys: { p256dh: P256DH, auth: AUTH } },
|
||||
setPushSubscription,
|
||||
]);
|
||||
|
||||
expect(oldSubscription.unsubscribe).toHaveBeenCalled();
|
||||
expect(subscribe).toHaveBeenCalledWith({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: SERVER_VAPID,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('disablePushNotifications', () => {
|
||||
@@ -37,10 +271,7 @@ describe('disablePushNotifications', () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
disablePushNotifications(matrixClient as never, clientConfig, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
disablePushNotifications({} as never, clientConfig, [null, setPushSubscription])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -50,10 +281,7 @@ describe('togglePusher', () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
togglePusher(matrixClient as never, clientConfig, true, true, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
togglePusher({} as never, clientConfig, true, true, [null, setPushSubscription])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND } from '$unstable/prefixes';
|
||||
import type { ClientConfig } from '../../../hooks/useClientConfig';
|
||||
import { resolvePushNotifyUrl } from './PushPusherConfig';
|
||||
import { getWebPushServerSupport, removeStaleHttpPushers } from './webPushSupport';
|
||||
|
||||
const debugLog = createDebugLogger('PushNotifications');
|
||||
|
||||
const BROWSER_DEVICE_NAME = 'This Browser';
|
||||
|
||||
type PushSubscriptionState = [
|
||||
PushSubscriptionJSON | null,
|
||||
(subscription: PushSubscription | null) => void,
|
||||
@@ -28,10 +33,109 @@ export async function requestBrowserNotificationPermission(): Promise<Notificati
|
||||
}
|
||||
}
|
||||
|
||||
function base64UrlToBytes(value: string): Uint8Array {
|
||||
const base64 = value.replaceAll('-', '+').replaceAll('_', '/');
|
||||
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
||||
const binary = atob(padded);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i += 1) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the browser subscription was created with the given VAPID key.
|
||||
* A different key (gateway vs homeserver) requires a fresh subscription.
|
||||
*/
|
||||
function applicationServerKeyMatches(
|
||||
subscriptionKey: ArrayBuffer | null,
|
||||
vapidPublicKey: string | undefined
|
||||
): boolean {
|
||||
if (!vapidPublicKey) return subscriptionKey === null;
|
||||
if (!subscriptionKey) return false;
|
||||
const expected = base64UrlToBytes(vapidPublicKey);
|
||||
const actual = new Uint8Array(subscriptionKey);
|
||||
return actual.length === expected.length && actual.every((byte, i) => byte === expected[i]);
|
||||
}
|
||||
|
||||
/** Gateway URL for the legacy `http` pusher; validates the user override. */
|
||||
function resolveHttpGatewayUrl(
|
||||
clientConfig: ClientConfig,
|
||||
pushNotifyUrlOverride?: string
|
||||
): string | undefined {
|
||||
const configuredUrl = clientConfig.pushNotificationDetails?.pushNotifyUrl;
|
||||
if (!configuredUrl?.trim() && !pushNotifyUrlOverride?.trim()) return configuredUrl;
|
||||
return resolvePushNotifyUrl(configuredUrl, pushNotifyUrlOverride);
|
||||
}
|
||||
|
||||
type WebPusherOptions = {
|
||||
endpoint: string;
|
||||
pushkey: string;
|
||||
auth: string;
|
||||
deviceDisplayName: string;
|
||||
pushNotifyUrlOverride?: string;
|
||||
};
|
||||
|
||||
function buildWebPusherData(
|
||||
mx: MatrixClient,
|
||||
clientConfig: ClientConfig,
|
||||
useServerWebPush: boolean,
|
||||
options: WebPusherOptions
|
||||
): Record<string, unknown> {
|
||||
const { endpoint, pushkey, auth, deviceDisplayName, pushNotifyUrlOverride } = options;
|
||||
|
||||
if (useServerWebPush) {
|
||||
// MSC4174: data.url is the push subscription endpoint, not a gateway.
|
||||
return {
|
||||
kind: MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND,
|
||||
app_id: clientConfig.pushNotificationDetails?.webPushAppID,
|
||||
pushkey,
|
||||
app_display_name: 'Sable (Web Push)',
|
||||
device_display_name: deviceDisplayName,
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: endpoint,
|
||||
auth,
|
||||
format: 'event_id_only',
|
||||
default_payload: { user_id: mx.getSafeUserId() },
|
||||
},
|
||||
append: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'http' as const,
|
||||
app_id: clientConfig.pushNotificationDetails?.webPushAppID,
|
||||
pushkey,
|
||||
app_display_name: 'Cinny',
|
||||
device_display_name: deviceDisplayName,
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: resolveHttpGatewayUrl(clientConfig, pushNotifyUrlOverride),
|
||||
format: 'event_id_only' as const,
|
||||
endpoint,
|
||||
p256dh: pushkey,
|
||||
auth,
|
||||
},
|
||||
append: false,
|
||||
};
|
||||
}
|
||||
|
||||
function postPusherToServiceWorker(mx: MatrixClient, pusherData: Record<string, unknown>): void {
|
||||
navigator.serviceWorker.controller?.postMessage({
|
||||
url: mx.baseUrl,
|
||||
type: 'togglePush',
|
||||
pusherData,
|
||||
token: mx.getAccessToken(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function enablePushNotifications(
|
||||
mx: MatrixClient,
|
||||
clientConfig: ClientConfig,
|
||||
pushSubscriptionAtom: PushSubscriptionState
|
||||
pushSubscriptionAtom: PushSubscriptionState,
|
||||
pushNotifyUrlOverride?: string
|
||||
): Promise<void> {
|
||||
if (isTauri()) return;
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
@@ -42,41 +146,52 @@ export async function enablePushNotifications(
|
||||
throw new Error('Push messaging is not supported in this browser.');
|
||||
}
|
||||
debugLog.info('notification', 'Enabling push notifications');
|
||||
|
||||
const webPushSupport = await getWebPushServerSupport(mx);
|
||||
const useServerWebPush = webPushSupport.supported;
|
||||
const applicationServerKey = useServerWebPush
|
||||
? webPushSupport.vapidPublicKey
|
||||
: clientConfig.pushNotificationDetails?.vapidPublicKey;
|
||||
const deviceDisplayName =
|
||||
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Unknown Device';
|
||||
|
||||
const [pushSubAtom, setPushSubscription] = pushSubscriptionAtom;
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const currentBrowserSub = await registration.pushManager.getSubscription();
|
||||
|
||||
/* Self-Healing Check. Effectively checks if the browser has invalidated our subscription and recreates it
|
||||
only when necessary. This prevents us from needing an external call to get back the web push info.
|
||||
*/
|
||||
if (currentBrowserSub && pushSubAtom && currentBrowserSub.endpoint === pushSubAtom.endpoint) {
|
||||
Also requires the VAPID key to match the active transport. */
|
||||
if (
|
||||
currentBrowserSub &&
|
||||
pushSubAtom &&
|
||||
currentBrowserSub.endpoint === pushSubAtom.endpoint &&
|
||||
applicationServerKeyMatches(
|
||||
currentBrowserSub.options.applicationServerKey,
|
||||
applicationServerKey
|
||||
)
|
||||
) {
|
||||
debugLog.info('notification', 'Push subscription already exists and is valid - reusing', {
|
||||
endpoint: pushSubAtom.endpoint,
|
||||
});
|
||||
const { keys } = pushSubAtom;
|
||||
if (!keys?.p256dh || !keys.auth) return;
|
||||
const pusherData = {
|
||||
kind: 'http' as const,
|
||||
app_id: clientConfig.pushNotificationDetails?.webPushAppID,
|
||||
pushkey: keys.p256dh,
|
||||
app_display_name: 'Cinny',
|
||||
device_display_name: 'This Browser',
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: clientConfig.pushNotificationDetails?.pushNotifyUrl,
|
||||
format: 'event_id_only' as const,
|
||||
postPusherToServiceWorker(
|
||||
mx,
|
||||
buildWebPusherData(mx, clientConfig, useServerWebPush, {
|
||||
endpoint: pushSubAtom.endpoint,
|
||||
p256dh: keys.p256dh,
|
||||
pushkey: keys.p256dh,
|
||||
auth: keys.auth,
|
||||
},
|
||||
append: false,
|
||||
};
|
||||
navigator.serviceWorker.controller?.postMessage({
|
||||
url: mx.baseUrl,
|
||||
type: 'togglePush',
|
||||
pusherData,
|
||||
token: mx.getAccessToken(),
|
||||
});
|
||||
deviceDisplayName: BROWSER_DEVICE_NAME,
|
||||
pushNotifyUrlOverride,
|
||||
})
|
||||
);
|
||||
if (useServerWebPush) {
|
||||
await removeStaleHttpPushers(mx, clientConfig.pushNotificationDetails?.webPushAppID, [
|
||||
deviceDisplayName,
|
||||
BROWSER_DEVICE_NAME,
|
||||
]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -88,7 +203,7 @@ export async function enablePushNotifications(
|
||||
debugLog.info('notification', 'Creating new push subscription');
|
||||
const newSubscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: clientConfig.pushNotificationDetails?.vapidPublicKey,
|
||||
applicationServerKey,
|
||||
});
|
||||
|
||||
debugLog.info('notification', 'Push subscription created successfully', {
|
||||
@@ -102,30 +217,23 @@ export async function enablePushNotifications(
|
||||
debugLog.error('notification', 'Push subscription missing required keys');
|
||||
throw new Error('Push subscription keys missing.');
|
||||
}
|
||||
const pusherData = {
|
||||
kind: 'http' as const,
|
||||
app_id: clientConfig.pushNotificationDetails?.webPushAppID,
|
||||
pushkey: keys.p256dh,
|
||||
app_display_name: 'Cinny',
|
||||
device_display_name:
|
||||
(await mx.getDevice(mx.getDeviceId() ?? '')).display_name ?? 'Unknown Device',
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: clientConfig.pushNotificationDetails?.pushNotifyUrl,
|
||||
format: 'event_id_only' as const,
|
||||
endpoint: newSubscription.endpoint,
|
||||
p256dh: keys.p256dh,
|
||||
auth: keys.auth,
|
||||
},
|
||||
append: false,
|
||||
};
|
||||
|
||||
navigator.serviceWorker.controller?.postMessage({
|
||||
url: mx.baseUrl,
|
||||
type: 'togglePush',
|
||||
pusherData,
|
||||
token: mx.getAccessToken(),
|
||||
});
|
||||
postPusherToServiceWorker(
|
||||
mx,
|
||||
buildWebPusherData(mx, clientConfig, useServerWebPush, {
|
||||
endpoint: newSubscription.endpoint,
|
||||
pushkey: keys.p256dh,
|
||||
auth: keys.auth,
|
||||
deviceDisplayName,
|
||||
pushNotifyUrlOverride,
|
||||
})
|
||||
);
|
||||
if (useServerWebPush) {
|
||||
await removeStaleHttpPushers(mx, clientConfig.pushNotificationDetails?.webPushAppID, [
|
||||
deviceDisplayName,
|
||||
BROWSER_DEVICE_NAME,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,13 +287,14 @@ export async function togglePusher(
|
||||
visible: boolean,
|
||||
usePushNotifications: boolean,
|
||||
pushSubscriptionAtom: PushSubscriptionState,
|
||||
keepEnabledWhenVisible = false
|
||||
keepEnabledWhenVisible = false,
|
||||
pushNotifyUrlOverride?: string
|
||||
): Promise<void> {
|
||||
if (usePushNotifications) {
|
||||
if (visible && !keepEnabledWhenVisible) {
|
||||
await disablePushNotifications(mx, clientConfig, pushSubscriptionAtom);
|
||||
} else {
|
||||
await enablePushNotifications(mx, clientConfig, pushSubscriptionAtom);
|
||||
await enablePushNotifications(mx, clientConfig, pushSubscriptionAtom, pushNotifyUrlOverride);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,9 +104,8 @@ function getNativePushConfigError(clientConfig: ReturnType<typeof useClientConfi
|
||||
return 'Native push requires pushNotificationDetails.nativePushAppID in config.json.';
|
||||
}
|
||||
|
||||
if (!clientConfig.pushNotificationDetails?.pushNotifyUrl) {
|
||||
return 'Native push requires pushNotificationDetails.pushNotifyUrl in config.json.';
|
||||
}
|
||||
// pushNotifyUrl is intentionally not required here: MSC4174 web push needs no
|
||||
// gateway, and legacy paths surface a missing gateway at registration time.
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -343,7 +342,10 @@ function BackgroundPushNotificationSetting() {
|
||||
'pushTransportOverride'
|
||||
);
|
||||
const [useRichPushPayloads] = useSetting(settingsAtom, 'useRichPushPayloads');
|
||||
const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride');
|
||||
const [pushNotifyUrlOverride, setPushNotifyUrlOverride] = useSetting(
|
||||
settingsAtom,
|
||||
'pushNotifyUrlOverride'
|
||||
);
|
||||
const pushSubAtom = useAtom(pushSubscriptionAtom);
|
||||
const [upEndpoint, setUpEndpoint] = useAtom(unifiedPushEndpointAtom);
|
||||
const unifiedPushStateRef = useRef<UnifiedPushState>(upEndpoint);
|
||||
@@ -503,7 +505,7 @@ function BackgroundPushNotificationSetting() {
|
||||
throw new Error('Browser notification permission was not granted.');
|
||||
}
|
||||
}
|
||||
await enablePushNotifications(mx, clientConfig, pushSubAtom);
|
||||
await enablePushNotifications(mx, clientConfig, pushSubAtom, pushNotifyUrlOverride);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -528,7 +530,7 @@ function BackgroundPushNotificationSetting() {
|
||||
throw new Error(nativePushConfigError);
|
||||
}
|
||||
|
||||
await enableNativePush(mx, clientConfig);
|
||||
await enableNativePush(mx, clientConfig, pushNotifyUrlOverride);
|
||||
};
|
||||
|
||||
const deactivateTransport = async (kind: BackgroundPushKind | null) => {
|
||||
@@ -838,6 +840,22 @@ function BackgroundPushNotificationSetting() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{backgroundPushSupported && (
|
||||
<NotificationTransportOverrideInput
|
||||
focusId="web-push-gateway-url"
|
||||
title="Push Gateway URL"
|
||||
description={`Used only when the homeserver does not support MSC4174 web push. Default: ${
|
||||
clientConfig.pushNotificationDetails?.pushNotifyUrl ?? 'none'
|
||||
}`}
|
||||
name="pushNotifyUrlOverride"
|
||||
value={pushNotifyUrlOverride ?? ''}
|
||||
placeholder={
|
||||
clientConfig.pushNotificationDetails?.pushNotifyUrl ??
|
||||
'https://sygnal.example.org/_matrix/push/v1/notify'
|
||||
}
|
||||
onSave={(nextValue) => setPushNotifyUrlOverride(nextValue.trim() || undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type * as WebPushSupportModule from './webPushSupport';
|
||||
import {
|
||||
DEFAULT_UNIFIED_PUSH_APP_ID,
|
||||
disableUnifiedPush,
|
||||
@@ -53,6 +54,13 @@ const invoke = vi.hoisted(() =>
|
||||
vi.fn<(cmd: string, args?: Record<string, unknown>) => Promise<unknown>>()
|
||||
);
|
||||
|
||||
const getWebPushServerSupport = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<WebPushSupportModule.WebPushServerSupport>>()
|
||||
);
|
||||
const acknowledgeWebPushPusher = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<void>>().mockResolvedValue(undefined)
|
||||
);
|
||||
|
||||
const addPluginListener = vi.hoisted(() =>
|
||||
vi.fn<
|
||||
(
|
||||
@@ -79,6 +87,11 @@ vi.mock('$utils/fetch', () => ({
|
||||
fetch: (...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args),
|
||||
}));
|
||||
|
||||
vi.mock('./webPushSupport', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof WebPushSupportModule>();
|
||||
return { ...actual, getWebPushServerSupport, acknowledgeWebPushPusher };
|
||||
});
|
||||
|
||||
function makeRoom() {
|
||||
return {
|
||||
name: 'Room',
|
||||
@@ -106,6 +119,8 @@ describe('UnifiedPushNotifications', () => {
|
||||
notificationsApi.createChannel.mockResolvedValue(undefined);
|
||||
notificationsApi.removeChannel.mockResolvedValue(undefined);
|
||||
getTauriNotificationsApi.mockResolvedValue(notificationsApi);
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: false });
|
||||
acknowledgeWebPushPusher.mockResolvedValue(undefined);
|
||||
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
@@ -630,6 +645,102 @@ describe('UnifiedPushNotifications', () => {
|
||||
);
|
||||
}, 15_000);
|
||||
|
||||
it('registers an MSC4174 webpush pusher without a gateway when supported', async () => {
|
||||
getWebPushServerSupport.mockResolvedValue({ supported: true, vapidPublicKey: 'hs-vapid' });
|
||||
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
endpoint: 'https://fcm.googleapis.com/fcm/send/device',
|
||||
distributor: 'embedded.fcm.distributor',
|
||||
p256dh: 'p256-key',
|
||||
auth: 'auth-secret',
|
||||
});
|
||||
|
||||
await expect(
|
||||
tryEnableUnifiedPush(matrixClient as never, {
|
||||
webPushAppID: 'moe.sable.app',
|
||||
vapidPublicKey: 'gateway-vapid',
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: 'registered',
|
||||
endpoint: 'https://fcm.googleapis.com/fcm/send/device',
|
||||
});
|
||||
|
||||
expect(unifiedPushTransport.registerUnifiedPushTransport).toHaveBeenCalledWith('hs-vapid');
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'org.matrix.msc4174.webpush',
|
||||
app_id: 'moe.sable.app',
|
||||
pushkey: 'p256-key',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://fcm.googleapis.com/fcm/send/device',
|
||||
auth: 'auth-secret',
|
||||
format: 'event_id_only',
|
||||
default_payload: { user_id: '@user:example.com' },
|
||||
}),
|
||||
})
|
||||
);
|
||||
}, 15_000);
|
||||
|
||||
it('keeps the gateway webpush pusher when the homeserver does not support MSC4174', async () => {
|
||||
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
endpoint: 'https://up.example/device',
|
||||
distributor: 'org.unifiedpush.distributor.ntfy',
|
||||
p256dh: 'p256-key',
|
||||
auth: 'auth-secret',
|
||||
});
|
||||
|
||||
await tryEnableUnifiedPush(matrixClient as never, {
|
||||
webPushAppID: 'moe.sable.app',
|
||||
pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify',
|
||||
vapidPublicKey: 'gateway-vapid',
|
||||
});
|
||||
|
||||
expect(unifiedPushTransport.registerUnifiedPushTransport).toHaveBeenCalledWith('gateway-vapid');
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'http',
|
||||
app_id: 'moe.sable.app',
|
||||
pushkey: 'p256-key',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://sygnal.example/_matrix/push/v1/notify',
|
||||
endpoint: 'https://up.example/device',
|
||||
p256dh: 'p256-key',
|
||||
auth: 'auth-secret',
|
||||
}),
|
||||
})
|
||||
);
|
||||
}, 15_000);
|
||||
|
||||
it('acknowledges MSC4174 activation pushes instead of notifying', async () => {
|
||||
await listenForUnifiedPushMessages(() => makeSettings() as never);
|
||||
|
||||
pushHandler({
|
||||
message: JSON.stringify({ app_id: 'moe.sable.app', ack_token: 'token-123' }),
|
||||
});
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(acknowledgeWebPushPusher).toHaveBeenCalledWith(
|
||||
matrixClient,
|
||||
'moe.sable.app',
|
||||
'token-123'
|
||||
)
|
||||
);
|
||||
expect(notificationsApi.sendNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('acknowledges MSC4174 activation pushes even without a user_id match', async () => {
|
||||
await listenForUnifiedPushMessages(() => makeSettings() as never);
|
||||
|
||||
pushHandler({
|
||||
message: JSON.stringify({ app_id: 'moe.sable.app', ack_token: 'token-456' }),
|
||||
});
|
||||
|
||||
await vi.waitFor(() => expect(acknowledgeWebPushPusher).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it('clears the UnifiedPush registration timeout after successful registration', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
@@ -669,6 +780,12 @@ describe('UnifiedPushNotifications', () => {
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'http',
|
||||
},
|
||||
{
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-webpush-key',
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'org.matrix.msc4174.webpush',
|
||||
},
|
||||
{
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'other-device-endpoint',
|
||||
@@ -684,7 +801,7 @@ describe('UnifiedPushNotifications', () => {
|
||||
},
|
||||
});
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledTimes(2);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledTimes(3);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
@@ -699,6 +816,13 @@ describe('UnifiedPushNotifications', () => {
|
||||
pushkey: 'stale-endpoint-2',
|
||||
})
|
||||
);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-webpush-key',
|
||||
})
|
||||
);
|
||||
expect(unifiedPushTransport.unregisterUnifiedPushTransport).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,13 @@ import {
|
||||
withPushPayloadFormat,
|
||||
type PushPusherSettings,
|
||||
} from './PushPusherConfig';
|
||||
import {
|
||||
acknowledgeWebPushPusher,
|
||||
getWebPushServerSupport,
|
||||
isWebPushActivationPayload,
|
||||
removeStaleHttpPushers,
|
||||
} from './webPushSupport';
|
||||
import { MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND } from '$unstable/prefixes';
|
||||
|
||||
const UP_PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
|
||||
export const DEFAULT_UNIFIED_PUSH_APP_ID = 'moe.sable.up';
|
||||
@@ -147,7 +154,10 @@ export async function tryEnableUnifiedPush(
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
await ensureNotificationChannels(notificationsApi);
|
||||
|
||||
const registration = await registerUnifiedPushWithTimeout(config?.vapidPublicKey);
|
||||
// MSC4174: subscribe with the homeserver VAPID key when it pushes directly.
|
||||
const webPushSupport = await getWebPushServerSupport(mx);
|
||||
const vapid = webPushSupport.supported ? webPushSupport.vapidPublicKey : config?.vapidPublicKey;
|
||||
const registration = await registerUnifiedPushWithTimeout(vapid);
|
||||
|
||||
if (registration.status !== 'registered') {
|
||||
return registration;
|
||||
@@ -157,34 +167,69 @@ export async function tryEnableUnifiedPush(
|
||||
const deviceDisplayName =
|
||||
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Android Device';
|
||||
|
||||
if (registration.p256dh && registration.auth && config?.webPushAppID && config?.pushNotifyUrl) {
|
||||
const pushNotifyUrl = resolvePushNotifyUrl(config.pushNotifyUrl, config?.pushNotifyUrlOverride);
|
||||
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: withPushPayloadFormat(
|
||||
{
|
||||
url: pushNotifyUrl,
|
||||
endpoint,
|
||||
p256dh: registration.p256dh,
|
||||
auth: registration.auth,
|
||||
default_payload: { user_id: mx.getSafeUserId() },
|
||||
},
|
||||
config?.useRichPushPayloads
|
||||
),
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
if (registration.p256dh && registration.auth && config?.webPushAppID) {
|
||||
if (webPushSupport.supported) {
|
||||
// MSC4174: data.url is the distributor's push endpoint, not a gateway.
|
||||
await mx.setPusher({
|
||||
kind: MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND,
|
||||
app_id: config.webPushAppID,
|
||||
pushkey: registration.p256dh,
|
||||
app_display_name: 'Sable (UnifiedPush)',
|
||||
device_display_name: deviceDisplayName,
|
||||
lang: navigator.language || 'en',
|
||||
data: withPushPayloadFormat(
|
||||
{
|
||||
url: endpoint,
|
||||
auth: registration.auth,
|
||||
default_payload: { user_id: mx.getSafeUserId() },
|
||||
},
|
||||
config?.useRichPushPayloads
|
||||
),
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
|
||||
return {
|
||||
status: 'registered',
|
||||
endpoint,
|
||||
gatewayUrl: pushNotifyUrl,
|
||||
distributor: registration.distributor,
|
||||
};
|
||||
await removeStaleHttpPushers(mx, config.webPushAppID, [deviceDisplayName]);
|
||||
|
||||
return {
|
||||
status: 'registered',
|
||||
endpoint,
|
||||
gatewayUrl: endpoint,
|
||||
distributor: registration.distributor,
|
||||
};
|
||||
}
|
||||
|
||||
if (config?.pushNotifyUrl) {
|
||||
const pushNotifyUrl = resolvePushNotifyUrl(
|
||||
config.pushNotifyUrl,
|
||||
config?.pushNotifyUrlOverride
|
||||
);
|
||||
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: withPushPayloadFormat(
|
||||
{
|
||||
url: pushNotifyUrl,
|
||||
endpoint,
|
||||
p256dh: registration.p256dh,
|
||||
auth: registration.auth,
|
||||
default_payload: { user_id: mx.getSafeUserId() },
|
||||
},
|
||||
config?.useRichPushPayloads
|
||||
),
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
|
||||
return {
|
||||
status: 'registered',
|
||||
endpoint,
|
||||
gatewayUrl: pushNotifyUrl,
|
||||
distributor: registration.distributor,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedConfig = resolveUnifiedPushPusherConfig(config);
|
||||
@@ -253,7 +298,7 @@ async function getCurrentDeviceUnifiedPushPushkeys(
|
||||
(pusher) =>
|
||||
pusher.app_id === appId &&
|
||||
pusher.device_display_name === deviceDisplayName &&
|
||||
pusher.kind === 'http' &&
|
||||
(pusher.kind === 'http' || pusher.kind === MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND) &&
|
||||
isNonEmptyString(pusher.pushkey)
|
||||
)
|
||||
.map((pusher) => pusher.pushkey);
|
||||
@@ -1027,12 +1072,27 @@ async function handleUnifiedPushPayload(
|
||||
) {
|
||||
const settings = getSettings();
|
||||
|
||||
const pushData = (raw.extra ?? raw) as UnifiedPushPayload;
|
||||
|
||||
// MSC4174 validation push: not a notification, ack even while visible.
|
||||
if (isWebPushActivationPayload(pushData)) {
|
||||
try {
|
||||
await acknowledgeWebPushPusher(settings.mx, pushData.app_id, pushData.ack_token);
|
||||
} catch (error) {
|
||||
unifiedPushLog.warn(
|
||||
'notification',
|
||||
'MSC4174 pusher activation failed',
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip system notification when in-app banners are active and visible.
|
||||
if (document.visibilityState === 'visible' && settings.useInAppNotifications) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pushData = (raw.extra ?? raw) as UnifiedPushPayload;
|
||||
const eventType = pushData?.type as EventType | undefined;
|
||||
const userId = isNonEmptyString(pushData?.user_id) ? pushData.user_id.trim() : undefined;
|
||||
if (!userId || userId !== settings.mx.getUserId()) {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { getWebPushServerSupport } from './webPushSupport';
|
||||
|
||||
const VAPID =
|
||||
'BNbXV88MfMI0fSxB7cDngopoviZRTbxIS0qSS-O7BZCtG04khMOn-PP2uez_X7Aeci42n02kJ0-JJJ0uQ4ELRTs';
|
||||
|
||||
type SupportMocks = {
|
||||
versionsAdvertised?: boolean;
|
||||
versionsError?: Error;
|
||||
capabilities?: Record<string, unknown>;
|
||||
capabilitiesError?: Error;
|
||||
};
|
||||
|
||||
function createMatrixClient({
|
||||
versionsAdvertised = false,
|
||||
versionsError,
|
||||
capabilities = {},
|
||||
capabilitiesError,
|
||||
}: SupportMocks = {}) {
|
||||
return {
|
||||
doesServerSupportUnstableFeature: vi.fn<(feature: string) => Promise<boolean>>(
|
||||
async (feature: string) => {
|
||||
if (feature !== 'org.matrix.msc4174') return false;
|
||||
if (versionsError) throw versionsError;
|
||||
return versionsAdvertised;
|
||||
}
|
||||
),
|
||||
getCapabilities: vi.fn<() => Promise<Record<string, unknown>>>(async () => {
|
||||
if (capabilitiesError) throw capabilitiesError;
|
||||
return capabilities;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('getWebPushServerSupport', () => {
|
||||
it('reports unsupported when /versions does not advertise MSC4174', async () => {
|
||||
const mx = createMatrixClient({ versionsAdvertised: false });
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({ supported: false });
|
||||
expect(mx.getCapabilities).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports unsupported when the /versions check fails', async () => {
|
||||
const mx = createMatrixClient({ versionsError: new Error('network down') });
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({ supported: false });
|
||||
});
|
||||
|
||||
it('returns the VAPID key from the stable capability', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilities: { 'm.webpush': { enabled: true, vapid: VAPID } },
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({
|
||||
supported: true,
|
||||
vapidPublicKey: VAPID,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the VAPID key from the unstable capability', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilities: { 'org.matrix.msc4174.webpush': { enabled: true, vapid: VAPID } },
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({
|
||||
supported: true,
|
||||
vapidPublicKey: VAPID,
|
||||
});
|
||||
});
|
||||
|
||||
it('prefers the stable capability over the unstable one', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilities: {
|
||||
'm.webpush': { enabled: true, vapid: VAPID },
|
||||
'org.matrix.msc4174.webpush': { enabled: true, vapid: 'unstable-key' },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({
|
||||
supported: true,
|
||||
vapidPublicKey: VAPID,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports unsupported when the capability is not enabled', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilities: { 'm.webpush': { enabled: false, vapid: VAPID } },
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({ supported: false });
|
||||
});
|
||||
|
||||
it('reports unsupported when the capability has no VAPID key', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilities: { 'm.webpush': { enabled: true } },
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({ supported: false });
|
||||
});
|
||||
|
||||
it('reports unsupported when fetching capabilities fails', async () => {
|
||||
const mx = createMatrixClient({
|
||||
versionsAdvertised: true,
|
||||
capabilitiesError: new Error('no capabilities'),
|
||||
});
|
||||
|
||||
await expect(getWebPushServerSupport(mx as never)).resolves.toEqual({ supported: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk';
|
||||
import { Method } from '$types/matrix-sdk';
|
||||
import {
|
||||
MATRIX_STABLE_MSC4174_WEBPUSH_CAPABILITY_NAME,
|
||||
MATRIX_UNSTABLE_MSC4174_FEATURE_NAME,
|
||||
MATRIX_UNSTABLE_MSC4174_PUSHERS_ACK_PATH,
|
||||
MATRIX_UNSTABLE_MSC4174_WEBPUSH_CAPABILITY_NAME,
|
||||
} from '$unstable/prefixes';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
|
||||
const debugLog = createDebugLogger('webPushSupport');
|
||||
|
||||
export type WebPushServerSupport =
|
||||
| { supported: true; vapidPublicKey: string }
|
||||
| { supported: false };
|
||||
|
||||
type WebPushCapability = {
|
||||
enabled?: unknown;
|
||||
vapid?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* MSC4174 support: advertised in /versions unstable features, VAPID key taken
|
||||
* from the m.webpush capability in /capabilities.
|
||||
*/
|
||||
export async function getWebPushServerSupport(mx: MatrixClient): Promise<WebPushServerSupport> {
|
||||
let versionsAdvertised = false;
|
||||
try {
|
||||
versionsAdvertised = await mx.doesServerSupportUnstableFeature(
|
||||
MATRIX_UNSTABLE_MSC4174_FEATURE_NAME
|
||||
);
|
||||
} catch {
|
||||
return { supported: false };
|
||||
}
|
||||
if (!versionsAdvertised) return { supported: false };
|
||||
|
||||
try {
|
||||
const capabilities = await mx.getCapabilities();
|
||||
const capability = (capabilities?.[MATRIX_STABLE_MSC4174_WEBPUSH_CAPABILITY_NAME] ??
|
||||
capabilities?.[MATRIX_UNSTABLE_MSC4174_WEBPUSH_CAPABILITY_NAME]) as
|
||||
| WebPushCapability
|
||||
| undefined;
|
||||
|
||||
if (
|
||||
capability?.enabled === true &&
|
||||
typeof capability.vapid === 'string' &&
|
||||
capability.vapid.trim()
|
||||
) {
|
||||
return { supported: true, vapidPublicKey: capability.vapid };
|
||||
}
|
||||
|
||||
debugLog.warn(
|
||||
'notification',
|
||||
'Server advertises MSC4174 in /versions but no usable m.webpush capability'
|
||||
);
|
||||
} catch {
|
||||
// fall through to unsupported
|
||||
}
|
||||
|
||||
return { supported: false };
|
||||
}
|
||||
|
||||
/** MSC4174 validation push: `{ app_id, ack_token }` and nothing else. */
|
||||
export function isWebPushActivationPayload(
|
||||
data: unknown
|
||||
): data is { app_id: string; ack_token: string } {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const d = data as Record<string, unknown>;
|
||||
return (
|
||||
typeof d.app_id === 'string' &&
|
||||
typeof d.ack_token === 'string' &&
|
||||
d.room_id === undefined &&
|
||||
d.event_id === undefined &&
|
||||
d.type === undefined &&
|
||||
typeof d.unread !== 'number'
|
||||
);
|
||||
}
|
||||
|
||||
/** POSTs the ack_token received by validation push to activate the pusher. */
|
||||
export async function acknowledgeWebPushPusher(
|
||||
mx: MatrixClient,
|
||||
appId: string,
|
||||
ackToken: string
|
||||
): Promise<void> {
|
||||
await mx.http.authedRequest(
|
||||
Method.Post,
|
||||
MATRIX_UNSTABLE_MSC4174_PUSHERS_ACK_PATH,
|
||||
undefined,
|
||||
{ app_id: appId, ack_token: ackToken },
|
||||
{ prefix: '' }
|
||||
);
|
||||
}
|
||||
|
||||
/** Removes this device's http gateway pushers to avoid duplicate pushes (MSC4174). */
|
||||
export async function removeStaleHttpPushers(
|
||||
mx: MatrixClient,
|
||||
appId: string | undefined,
|
||||
deviceDisplayNames: string[]
|
||||
): Promise<void> {
|
||||
if (!appId || deviceDisplayNames.length === 0) return;
|
||||
try {
|
||||
const response = await mx.getPushers();
|
||||
const stalePushers = (response.pushers ?? []).filter(
|
||||
(pusher) =>
|
||||
pusher.app_id === appId &&
|
||||
pusher.kind === 'http' &&
|
||||
deviceDisplayNames.includes(pusher.device_display_name)
|
||||
);
|
||||
await Promise.allSettled(
|
||||
stalePushers.map((pusher) =>
|
||||
mx.setPusher({
|
||||
kind: null,
|
||||
app_id: pusher.app_id,
|
||||
pushkey: pusher.pushkey,
|
||||
} as unknown as IPusherRequest)
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
// best effort cleanup
|
||||
}
|
||||
}
|
||||
@@ -210,6 +210,7 @@ export const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly s
|
||||
'unified-push-app-id',
|
||||
'unified-push-distributor',
|
||||
'unified-push-gateway-url',
|
||||
'web-push-gateway-url',
|
||||
],
|
||||
devices: [
|
||||
'device-dashboard',
|
||||
|
||||
@@ -15,6 +15,7 @@ const debugLog = createDebugLogger('AppVisibility');
|
||||
export function useAppVisibility(mx: MatrixClient | undefined) {
|
||||
const clientConfig = useClientConfig();
|
||||
const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled');
|
||||
const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride');
|
||||
const pushSubAtom = useAtom(pushSubscriptionAtom);
|
||||
const isMobile = isMobileOrTablet();
|
||||
|
||||
@@ -43,12 +44,20 @@ export function useAppVisibility(mx: MatrixClient | undefined) {
|
||||
if (!mx) return undefined;
|
||||
|
||||
const handleVisibilityForNotifications = (isVisible: boolean) => {
|
||||
togglePusher(mx, clientConfig, isVisible, backgroundPushEnabled, pushSubAtom, isMobile);
|
||||
togglePusher(
|
||||
mx,
|
||||
clientConfig,
|
||||
isVisible,
|
||||
backgroundPushEnabled,
|
||||
pushSubAtom,
|
||||
isMobile,
|
||||
pushNotifyUrlOverride
|
||||
);
|
||||
};
|
||||
|
||||
appEvents.onVisibilityChange = handleVisibilityForNotifications;
|
||||
return () => {
|
||||
appEvents.onVisibilityChange = null;
|
||||
};
|
||||
}, [mx, clientConfig, backgroundPushEnabled, pushSubAtom, isMobile]);
|
||||
}, [mx, clientConfig, backgroundPushEnabled, pushSubAtom, isMobile, pushNotifyUrlOverride]);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
||||
import type { swTestHooks as swTestHooksHelper } from './sw';
|
||||
|
||||
vi.mock('workbox-precaching', () => ({
|
||||
cleanupOutdatedCaches: vi.fn<() => void>(),
|
||||
precacheAndRoute: vi.fn<() => void>(),
|
||||
}));
|
||||
|
||||
type SwTestHooks = typeof swTestHooksHelper;
|
||||
|
||||
type SwCacheStub = {
|
||||
delete: () => Promise<boolean>;
|
||||
match: () => Promise<Response | undefined>;
|
||||
put: (key: string, response: Response) => Promise<void>;
|
||||
};
|
||||
|
||||
const ACK_PATH = '/_matrix/client/unstable/org.matrix.msc4174/pushers/ack';
|
||||
|
||||
describe('service worker MSC4174 web push activation', () => {
|
||||
let swTestHooks: SwTestHooks;
|
||||
let clients: Map<string, Client>;
|
||||
let addEventListener: Mock<(type: string, handler: (event: PushEvent) => void) => void>;
|
||||
let persistedSessions: string | undefined;
|
||||
let fetchMock: Mock<typeof globalThis.fetch>;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
clients = new Map();
|
||||
addEventListener = vi.fn<(type: string, handler: (event: PushEvent) => void) => void>();
|
||||
persistedSessions = undefined;
|
||||
vi.stubGlobal('self', {
|
||||
__WB_MANIFEST: [],
|
||||
addEventListener,
|
||||
caches: {
|
||||
open: vi.fn<() => Promise<SwCacheStub>>(async () => ({
|
||||
delete: vi.fn<() => Promise<boolean>>(async () => true),
|
||||
match: vi.fn<() => Promise<Response | undefined>>(async () =>
|
||||
persistedSessions ? new Response(persistedSessions) : undefined
|
||||
),
|
||||
put: vi.fn<(key: string, response: Response) => Promise<void>>(
|
||||
async (_key: string, response: Response) => {
|
||||
persistedSessions = await response.text();
|
||||
}
|
||||
),
|
||||
})),
|
||||
},
|
||||
clients: {
|
||||
claim: vi.fn<() => void>(),
|
||||
get: vi.fn<(id: string) => Promise<Client | undefined>>(async (id: string) =>
|
||||
clients.get(id)
|
||||
),
|
||||
matchAll: vi.fn<() => Promise<Client[]>>(async () => Array.from(clients.values())),
|
||||
},
|
||||
registration: {},
|
||||
});
|
||||
fetchMock = vi.fn<typeof globalThis.fetch>();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
swTestHooks = (await import('./sw')).swTestHooks;
|
||||
});
|
||||
|
||||
const dispatchPush = async (payload: unknown): Promise<void> => {
|
||||
const pushHandler = addEventListener.mock.calls.find(([type]) => type === 'push')?.[1];
|
||||
expect(pushHandler).toBeTypeOf('function');
|
||||
|
||||
let pending: Promise<void> | undefined;
|
||||
pushHandler?.({
|
||||
data: { json: () => payload },
|
||||
waitUntil: (promise: Promise<void>) => {
|
||||
pending = promise;
|
||||
},
|
||||
} as unknown as PushEvent);
|
||||
await pending;
|
||||
};
|
||||
|
||||
it('classifies activation payloads', () => {
|
||||
expect(swTestHooks.isWebPushActivationPayload({ app_id: 'app', ack_token: 'token' })).toBe(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
swTestHooks.isWebPushActivationPayload({
|
||||
app_id: 'app',
|
||||
ack_token: 'token',
|
||||
room_id: '!room:example.org',
|
||||
})
|
||||
).toBe(false);
|
||||
expect(swTestHooks.isWebPushActivationPayload({ app_id: 'app' })).toBe(false);
|
||||
expect(swTestHooks.isWebPushActivationPayload({ room_id: '!room', event_id: '$event' })).toBe(
|
||||
false
|
||||
);
|
||||
expect(swTestHooks.isWebPushActivationPayload(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('acknowledges an activation push with the live session', async () => {
|
||||
await swTestHooks.setSession(
|
||||
'alice-window',
|
||||
'alice-token',
|
||||
'https://matrix.example.org',
|
||||
'@alice:example.org'
|
||||
);
|
||||
fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));
|
||||
|
||||
await dispatchPush({ app_id: 'moe.sable.app', ack_token: '6fc76b70-5fad-4eb7-93ea' });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(`https://matrix.example.org${ACK_PATH}`);
|
||||
expect(init.method).toBe('POST');
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer alice-token');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
app_id: 'moe.sable.app',
|
||||
ack_token: '6fc76b70-5fad-4eb7-93ea',
|
||||
});
|
||||
});
|
||||
|
||||
it('acknowledges even when a visible client is open', async () => {
|
||||
clients.set('visible-window', { visibilityState: 'visible' } as unknown as Client);
|
||||
await swTestHooks.setSession(
|
||||
'alice-window',
|
||||
'alice-token',
|
||||
'https://matrix.example.org',
|
||||
'@alice:example.org'
|
||||
);
|
||||
fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));
|
||||
|
||||
await dispatchPush({ app_id: 'moe.sable.app', ack_token: 'token-1' });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toContain(ACK_PATH);
|
||||
});
|
||||
|
||||
it('falls back to the persisted session after an SW restart', async () => {
|
||||
persistedSessions = JSON.stringify({
|
||||
'@bob:example.org': {
|
||||
accessToken: 'bob-token',
|
||||
baseUrl: 'https://other.example.org',
|
||||
userId: '@bob:example.org',
|
||||
},
|
||||
});
|
||||
fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));
|
||||
|
||||
await dispatchPush({ app_id: 'moe.sable.app', ack_token: 'token-2' });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(`https://other.example.org${ACK_PATH}`);
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer bob-token');
|
||||
});
|
||||
|
||||
it('tries the next account when the homeserver rejects the ack', async () => {
|
||||
await swTestHooks.setSession(
|
||||
'alice-window',
|
||||
'alice-token',
|
||||
'https://matrix.example.org',
|
||||
'@alice:example.org'
|
||||
);
|
||||
await swTestHooks.setSession(
|
||||
'bob-window',
|
||||
'bob-token',
|
||||
'https://matrix.example.org',
|
||||
'@bob:example.org'
|
||||
);
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(new Response('{"errcode":"M_NOT_FOUND"}', { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response('{}', { status: 200 }));
|
||||
|
||||
await dispatchPush({ app_id: 'moe.sable.app', ack_token: 'token-3' });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const firstInit = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
const secondInit = fetchMock.mock.calls[1] as unknown as [string, RequestInit];
|
||||
expect((firstInit[1].headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer alice-token'
|
||||
);
|
||||
expect((secondInit[1].headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer bob-token'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not treat regular notifications as activation pushes', async () => {
|
||||
clients.set('visible-window', { visibilityState: 'visible' } as unknown as Client);
|
||||
await swTestHooks.setSession(
|
||||
'alice-window',
|
||||
'alice-token',
|
||||
'https://matrix.example.org',
|
||||
'@alice:example.org'
|
||||
);
|
||||
|
||||
// Visible client suppresses the notification before any network access.
|
||||
await dispatchPush({ room_id: '!room:example.org', event_id: '$event:example.org' });
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@
|
||||
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
|
||||
import { EventType } from 'matrix-js-sdk/lib/@types/event';
|
||||
|
||||
import { MATRIX_UNSTABLE_MSC4174_PUSHERS_ACK_PATH } from '$unstable/prefixes';
|
||||
import { createPushNotifications } from './sw/pushNotification';
|
||||
import { readPersistedSession } from './sw-session-persistence';
|
||||
|
||||
@@ -810,14 +811,12 @@ function respondWithInflightMedia(
|
||||
// mode: "no-cors", which prevents the Authorization header above from reaching the server.
|
||||
// Preserve Range header for streaming audio and video.
|
||||
const promise = fetch(request.url, { ...fetchConfig(token, request), redirect })
|
||||
.then(
|
||||
async (res): Promise<BufferedMediaResponse> => ({
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
headers: new Headers(res.headers),
|
||||
body: await res.arrayBuffer(),
|
||||
})
|
||||
)
|
||||
.then(async (res): Promise<BufferedMediaResponse> => ({
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
headers: new Headers(res.headers),
|
||||
body: await res.arrayBuffer(),
|
||||
}))
|
||||
.finally(() => {
|
||||
inflightMediaFetches.delete(key);
|
||||
});
|
||||
@@ -869,6 +868,8 @@ export const swTestHooks = {
|
||||
requestSessionWithTimeout,
|
||||
respondWithMediaAuthRecovery,
|
||||
setSession,
|
||||
isWebPushActivationPayload,
|
||||
acknowledgeWebPushActivation,
|
||||
};
|
||||
|
||||
self.addEventListener('message', (event: ExtendableMessageEvent) => {
|
||||
@@ -950,6 +951,69 @@ self.addEventListener('fetch', (event: FetchEvent) => {
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MSC4174 web push activation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** MSC4174 validation push: `{ app_id, ack_token }` and nothing else. */
|
||||
function isWebPushActivationPayload(data: unknown): data is { app_id: string; ack_token: string } {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const d = data as Record<string, unknown>;
|
||||
return (
|
||||
typeof d.app_id === 'string' &&
|
||||
typeof d.ack_token === 'string' &&
|
||||
d.room_id === undefined &&
|
||||
d.event_id === undefined &&
|
||||
d.type === undefined &&
|
||||
typeof d.unread !== 'number'
|
||||
);
|
||||
}
|
||||
|
||||
async function postWebPushAck(
|
||||
session: SessionInfo,
|
||||
appId: string,
|
||||
ackToken: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${session.baseUrl}${MATRIX_UNSTABLE_MSC4174_PUSHERS_ACK_PATH}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ app_id: appId, ack_token: ackToken }),
|
||||
});
|
||||
if (res.ok) return true;
|
||||
console.warn('[SW push] MSC4174 ack rejected with HTTP', res.status);
|
||||
} catch (err) {
|
||||
console.warn('[SW push] MSC4174 ack failed', err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acknowledges a MSC4174 validation push. The payload does not identify the
|
||||
* account that registered the pusher, so each known session is tried in turn.
|
||||
*/
|
||||
async function acknowledgeWebPushActivation(appId: string, ackToken: string): Promise<boolean> {
|
||||
const candidates: SessionInfo[] = [...sessions.values()];
|
||||
const seen = new Set(candidates.map((session) => session.userId).filter(Boolean));
|
||||
const persisted = await loadPersistedSessions();
|
||||
Object.values(persisted).forEach((session) => {
|
||||
if (!seen.has(session.userId)) {
|
||||
candidates.push(session);
|
||||
seen.add(session.userId);
|
||||
}
|
||||
});
|
||||
|
||||
// Chain sessions sequentially to avoid await-in-loop.
|
||||
return candidates.reduce(
|
||||
(prevPromise, session) =>
|
||||
prevPromise.then((acked) => acked || postWebPushAck(session, appId, ackToken)),
|
||||
Promise.resolve(false)
|
||||
);
|
||||
}
|
||||
|
||||
// Detect a minimal (event_id_only) payload: has room_id + event_id but no
|
||||
// event type field — meaning the homeserver stripped the event content.
|
||||
function isMinimalPushPayload(
|
||||
@@ -963,6 +1027,14 @@ function isMinimalPushPayload(
|
||||
const onPushNotification = async (event: PushEvent) => {
|
||||
if (!event?.data) return;
|
||||
|
||||
const pushData = event.data.json();
|
||||
|
||||
// MSC4174 validation push: not a notification, ack even while visible.
|
||||
if (isWebPushActivationPayload(pushData)) {
|
||||
await acknowledgeWebPushActivation(pushData.app_id, pushData.ack_token);
|
||||
return;
|
||||
}
|
||||
|
||||
// The SW may have been restarted by the OS (iOS is aggressive about this),
|
||||
// so in-memory settings would be at their defaults. Reload from cache and
|
||||
// match active clients in parallel — they are independent operations.
|
||||
@@ -989,7 +1061,6 @@ const onPushNotification = async (event: PushEvent) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const pushData = event.data.json();
|
||||
console.debug('[SW push] raw payload:', JSON.stringify(pushData, null, 2));
|
||||
|
||||
try {
|
||||
|
||||
@@ -5,3 +5,4 @@ export * from './event_misc';
|
||||
export * from './profile';
|
||||
export * from './accountdata';
|
||||
export * from './state_events';
|
||||
export * from './push';
|
||||
@@ -0,0 +1,19 @@
|
||||
// push related unstable prefixes
|
||||
// don't import this file directly, import '$unstable/prefixes'
|
||||
// all defined in MSC4174 https://github.com/matrix-org/matrix-spec-proposals/pull/4174
|
||||
|
||||
/** unstable /versions feature flag for MSC4174 web push support */
|
||||
export const MATRIX_UNSTABLE_MSC4174_FEATURE_NAME = 'org.matrix.msc4174';
|
||||
|
||||
/** stable capability name in /capabilities */
|
||||
export const MATRIX_STABLE_MSC4174_WEBPUSH_CAPABILITY_NAME = 'm.webpush';
|
||||
|
||||
/** unstable capability name in /capabilities */
|
||||
export const MATRIX_UNSTABLE_MSC4174_WEBPUSH_CAPABILITY_NAME = 'org.matrix.msc4174.webpush';
|
||||
|
||||
/** unstable pusher kind for /pushers/set */
|
||||
export const MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND = 'org.matrix.msc4174.webpush';
|
||||
|
||||
/** unstable endpoint to activate a webpush pusher with its ack_token */
|
||||
export const MATRIX_UNSTABLE_MSC4174_PUSHERS_ACK_PATH =
|
||||
'/_matrix/client/unstable/org.matrix.msc4174/pushers/ack';
|
||||
Reference in new issue
Block a user