mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 19:40:34 +00:00
feat(native): push inside the iOS app, through an encrypted relay
The app subscribes to Web Push like a browser, only the app makes the subscription: it asks for permission, registers with APNs and keeps its own P-256 key pair and auth secret in a keychain group a notification extension can share. The endpoint is liketrek's relay for this device's token, so the server encrypts exactly as for a browser and nobody on the way can read the notification. The settings card, the test push, sign-in resync and the logout teardown all take this path where the binary has nativePush; a tapped notification opens the place it points at, also from a cold start. The App ID has push enabled, the app carries the aps-environment and keychain-group entitlements.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { pushApi } from '../api/push';
|
||||
import {
|
||||
NativePushDenied,
|
||||
forgetNativePush,
|
||||
nativePushActive,
|
||||
nativePushEndpoint,
|
||||
registerNativePush,
|
||||
} from '../native/push';
|
||||
import {
|
||||
WebPushError,
|
||||
disableWebPush,
|
||||
enableWebPush,
|
||||
forgetPushDeviceOnLogout,
|
||||
getWebPushSupport,
|
||||
readWebPushDeviceState,
|
||||
} from './webPush';
|
||||
|
||||
vi.mock('../native/push', () => {
|
||||
class NativePushDenied extends Error {}
|
||||
return {
|
||||
NativePushDenied,
|
||||
nativePushActive: vi.fn(),
|
||||
nativePushEndpoint: vi.fn(),
|
||||
registerNativePush: vi.fn(),
|
||||
forgetNativePush: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock('../api/push', () => ({ pushApi: { subscribe: vi.fn(), unsubscribe: vi.fn(), getPublicKey: vi.fn() } }));
|
||||
|
||||
const SUB = { endpoint: 'https://push.liketrek.com/v1/apns/production/abcd', keys: { p256dh: 'BPk', auth: 'aa' } };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(nativePushActive).mockReturnValue(true);
|
||||
vi.mocked(nativePushEndpoint).mockReturnValue(null);
|
||||
vi.mocked(registerNativePush).mockResolvedValue(SUB);
|
||||
vi.mocked(pushApi.subscribe).mockResolvedValue(undefined as never);
|
||||
vi.mocked(pushApi.unsubscribe).mockResolvedValue(undefined as never);
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response(null, { status: 204 }))
|
||||
);
|
||||
});
|
||||
|
||||
describe('web push inside the app', () => {
|
||||
it('counts as supported without a service worker, and reads on or off from the remembered endpoint', async () => {
|
||||
expect(getWebPushSupport()).toEqual({ supported: true, reason: null });
|
||||
expect(await readWebPushDeviceState()).toBe('off');
|
||||
vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint);
|
||||
expect(await readWebPushDeviceState()).toBe('on');
|
||||
});
|
||||
|
||||
it('switches on with the app subscription, and rolls it back when the server refuses', async () => {
|
||||
await enableWebPush('server-key');
|
||||
expect(pushApi.subscribe).toHaveBeenCalledWith(SUB);
|
||||
|
||||
vi.mocked(pushApi.subscribe).mockRejectedValueOnce(new Error('400'));
|
||||
await expect(enableWebPush('server-key')).rejects.toBeInstanceOf(WebPushError);
|
||||
expect(forgetNativePush).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reads a refused permission as denied', async () => {
|
||||
vi.mocked(registerNativePush).mockRejectedValue(new NativePushDenied());
|
||||
await expect(enableWebPush('server-key')).rejects.toMatchObject({ code: 'denied' });
|
||||
});
|
||||
|
||||
it('switches off and forgets the device at logout through the endpoint it remembers', async () => {
|
||||
vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint);
|
||||
await disableWebPush();
|
||||
expect(pushApi.unsubscribe).toHaveBeenCalledWith(SUB.endpoint);
|
||||
expect(forgetNativePush).toHaveBeenCalled();
|
||||
|
||||
await forgetPushDeviceOnLogout(500);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/notifications/push/subscriptions',
|
||||
expect.objectContaining({ method: 'DELETE' })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import type { PushSubscriptionInput, PushUnsubscribeRequest } from '@trek/shared
|
||||
import { pushApi } from '../api/push'
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import { isIosDevice, isIosStandalone } from '../utils/iosDevice'
|
||||
import { NativePushDenied, forgetNativePush, nativePushActive, nativePushEndpoint, registerNativePush } from '../native/push'
|
||||
|
||||
/**
|
||||
* Web Push on this device: whether it can work here, and switching it on and
|
||||
@@ -72,6 +73,9 @@ function hasPushApis(): boolean {
|
||||
*/
|
||||
export function getWebPushSupport(): WebPushSupport {
|
||||
if (typeof window === 'undefined') return unsupported('unsupported')
|
||||
// Inside the app the app makes the subscription (native/push.ts), with no
|
||||
// service worker and no Notification API in the WebView.
|
||||
if (nativePushActive()) return { supported: true, reason: null }
|
||||
// A service worker, and push with it, exists only in a secure context: HTTPS,
|
||||
// or localhost while developing. A plain http LAN address never gets one.
|
||||
if (window.isSecureContext === false) return unsupported('insecure')
|
||||
@@ -175,6 +179,7 @@ export async function loadPushPublicKey(): Promise<string | null> {
|
||||
|
||||
/** What the settings card shows for this device. Never rejects. */
|
||||
export async function readWebPushDeviceState(): Promise<WebPushDeviceState> {
|
||||
if (nativePushActive()) return nativePushEndpoint() ? 'on' : 'off'
|
||||
const { reason } = getWebPushSupport()
|
||||
if (reason) return reason
|
||||
if (getPushPermission() === 'denied') return 'denied'
|
||||
@@ -215,6 +220,7 @@ async function subscribeWithKey(
|
||||
* spend it. The permission request is therefore the first thing that runs.
|
||||
*/
|
||||
export async function enableWebPush(publicKey: string, registration?: ServiceWorkerRegistration | null): Promise<void> {
|
||||
if (nativePushActive()) return enableNativePush()
|
||||
const permission =
|
||||
Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission()
|
||||
if (permission === 'denied') throw new WebPushError('denied')
|
||||
@@ -247,6 +253,12 @@ export async function enableWebPush(publicKey: string, registration?: ServiceWor
|
||||
* push service answers 404 or 410 for on its next send.
|
||||
*/
|
||||
export async function disableWebPush(): Promise<void> {
|
||||
if (nativePushActive()) {
|
||||
const endpoint = nativePushEndpoint()
|
||||
if (endpoint) await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(endpoint))
|
||||
forgetNativePush()
|
||||
return
|
||||
}
|
||||
const subscription = await currentPushSubscription()
|
||||
if (!subscription) return
|
||||
await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(subscription.endpoint))
|
||||
@@ -265,6 +277,12 @@ export async function disableWebPush(): Promise<void> {
|
||||
* to switch it on. Never rejects.
|
||||
*/
|
||||
export async function resyncPushSubscription(): Promise<void> {
|
||||
if (nativePushActive()) {
|
||||
// The app's subscription carries no server key, so only the row is restored.
|
||||
if (!nativePushEndpoint() || isEffectivelyOffline()) return
|
||||
await bestEffort('re-registering this device', async () => pushApi.subscribe(await registerNativePush()))
|
||||
return
|
||||
}
|
||||
if (!getWebPushSupport().supported || getPushPermission() !== 'granted' || isEffectivelyOffline()) return
|
||||
await bestEffort('re-registering this device', async () => {
|
||||
const registration = await existingRegistration()
|
||||
@@ -325,6 +343,14 @@ async function forgetOnServerAtLogout(endpoint: string, timeoutMs: number): Prom
|
||||
* or 410.
|
||||
*/
|
||||
export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_MS): Promise<void> {
|
||||
if (nativePushActive()) {
|
||||
const endpoint = nativePushEndpoint()
|
||||
forgetNativePush()
|
||||
if (endpoint) {
|
||||
await withTimeout(bestEffort('forgetting this device at logout', () => forgetOnServerAtLogout(endpoint, timeoutMs)), timeoutMs, undefined)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!hasPushApis()) return
|
||||
const teardown = bestEffort('forgetting this device at logout', async () => {
|
||||
const subscription = await currentPushSubscription()
|
||||
@@ -336,3 +362,19 @@ export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_M
|
||||
})
|
||||
await withTimeout(teardown, timeoutMs, undefined)
|
||||
}
|
||||
|
||||
/** Push on for the app: its own subscription, then the server, rolled back if the server refuses. */
|
||||
async function enableNativePush(): Promise<void> {
|
||||
let subscription: PushSubscriptionInput
|
||||
try {
|
||||
subscription = await registerNativePush()
|
||||
} catch (err) {
|
||||
throw new WebPushError(err instanceof NativePushDenied ? 'denied' : 'failed', err)
|
||||
}
|
||||
try {
|
||||
await pushApi.subscribe(subscription)
|
||||
} catch (err) {
|
||||
forgetNativePush()
|
||||
throw err instanceof WebPushError ? err : new WebPushError('failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user