mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +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:
@@ -24,6 +24,7 @@ vi.mock('./capabilities', () => ({
|
||||
}));
|
||||
vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() }));
|
||||
vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) }));
|
||||
vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}) }));
|
||||
vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) }));
|
||||
|
||||
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { checkAppUpdate, loadNativeCapabilities } from './capabilities';
|
||||
import { installNativeGeolocation } from './geolocation';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { startNativePush } from './push';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { startSharedFiles } from './sharedFiles';
|
||||
import { isUnimplemented } from './trekShell';
|
||||
@@ -30,6 +31,8 @@ export function startNativeApp(): void {
|
||||
void loadNativeCapabilities().then(() => installNativeGeolocation());
|
||||
// Booking documents shared to TREK, waiting for a trip to import into.
|
||||
void startSharedFiles();
|
||||
// Taps on TREK notifications open the place they point at.
|
||||
void loadNativeCapabilities().then(() => startNativePush());
|
||||
|
||||
// A tap on the status bar scrolls the list under it back to the top, as in
|
||||
// every iOS app (the status-bar plugin fires statusTap on iOS).
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeIos } from './platform';
|
||||
import {
|
||||
NativePushDenied,
|
||||
forgetNativePush,
|
||||
nativePushActive,
|
||||
nativePushEndpoint,
|
||||
openPushTarget,
|
||||
registerNativePush,
|
||||
startNativePush,
|
||||
} from './push';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: {
|
||||
registerPush: vi.fn(),
|
||||
takeOpenedPush: vi.fn(),
|
||||
addListener: vi.fn(async () => ({ remove: async () => {} })),
|
||||
},
|
||||
}));
|
||||
|
||||
const SUB = {
|
||||
endpoint: 'https://push.liketrek.com/v1/apns/production/abcd',
|
||||
keys: { p256dh: 'BPk', auth: 'aa' },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(true);
|
||||
vi.mocked(TrekShell.registerPush).mockReset().mockResolvedValue(SUB);
|
||||
vi.mocked(TrekShell.takeOpenedPush).mockReset().mockResolvedValue({ url: null });
|
||||
window.history.replaceState({}, '', '/dashboard');
|
||||
});
|
||||
|
||||
describe('native push', () => {
|
||||
it('is on only in an iOS binary that has it', () => {
|
||||
expect(nativePushActive()).toBe(true);
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
expect(nativePushActive()).toBe(false);
|
||||
});
|
||||
|
||||
it('remembers the relay endpoint it subscribed with, and forgets it again', async () => {
|
||||
expect(await registerNativePush()).toEqual(SUB);
|
||||
expect(nativePushEndpoint()).toBe(SUB.endpoint);
|
||||
forgetNativePush();
|
||||
expect(nativePushEndpoint()).toBeNull();
|
||||
});
|
||||
|
||||
it('tells a refused permission apart from a failure', async () => {
|
||||
vi.mocked(TrekShell.registerPush).mockRejectedValue({ code: 'DENIED' });
|
||||
await expect(registerNativePush()).rejects.toBeInstanceOf(NativePushDenied);
|
||||
vi.mocked(TrekShell.registerPush).mockRejectedValue(new Error('apns down'));
|
||||
await expect(registerNativePush()).rejects.toThrow('apns down');
|
||||
expect(nativePushEndpoint()).toBeNull();
|
||||
});
|
||||
|
||||
it('opens a tapped notification inside the app, and never another origin', () => {
|
||||
const pops = vi.fn();
|
||||
window.addEventListener('popstate', pops);
|
||||
openPushTarget('/trips/12?tab=chat');
|
||||
expect(window.location.pathname).toBe('/trips/12');
|
||||
expect(window.location.search).toBe('?tab=chat');
|
||||
openPushTarget('https://evil.example/phish');
|
||||
expect(window.location.pathname).toBe('/trips/12');
|
||||
expect(pops).toHaveBeenCalledTimes(1);
|
||||
window.removeEventListener('popstate', pops);
|
||||
});
|
||||
|
||||
it('follows the notification the app was opened from', async () => {
|
||||
vi.mocked(TrekShell.takeOpenedPush).mockResolvedValue({ url: '/trips/3' });
|
||||
await startNativePush();
|
||||
expect(window.location.pathname).toBe('/trips/3');
|
||||
expect(TrekShell.addListener).toHaveBeenCalledWith('pushOpened', expect.any(Function));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { PushSubscriptionInput } from '@trek/shared';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeIos } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* Push inside the app: the same Web Push subscription a browser makes, only
|
||||
* the app makes it (TrekShell.registerPush). Its endpoint is liketrek's relay
|
||||
* for this device's APNs token and its keys live on the device, so the server
|
||||
* encrypts exactly as for a browser and the relay hands on ciphertext that the
|
||||
* app's notification extension decrypts. push/webPush.ts takes this path
|
||||
* wherever the binary reports the nativePush feature; the settings card, the
|
||||
* test push and the logout teardown stay what they are.
|
||||
*
|
||||
* The endpoint is remembered on the device, the way a browser remembers its
|
||||
* subscription, so the card can say on or off and the logout can name it.
|
||||
*/
|
||||
const KEY = 'trek.nativePushEndpoint';
|
||||
|
||||
export function nativePushActive(): boolean {
|
||||
return isNativeIos() && hasNativeFeature('nativePush');
|
||||
}
|
||||
|
||||
export function nativePushEndpoint(): string | null {
|
||||
try {
|
||||
return window.localStorage.getItem(KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberEndpoint(endpoint: string | null): void {
|
||||
try {
|
||||
if (endpoint) window.localStorage.setItem(KEY, endpoint);
|
||||
else window.localStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// Storage refused: the card then reads off and offers to switch it on again.
|
||||
}
|
||||
}
|
||||
|
||||
export class NativePushDenied extends Error {}
|
||||
|
||||
/** Permission, APNs and the device keys, as a subscription the server can store. */
|
||||
export async function registerNativePush(): Promise<PushSubscriptionInput> {
|
||||
try {
|
||||
const subscription = await TrekShell.registerPush();
|
||||
rememberEndpoint(subscription.endpoint);
|
||||
return subscription;
|
||||
} catch (err) {
|
||||
if ((err as { code?: string } | null)?.code === 'DENIED') throw new NativePushDenied();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function forgetNativePush(): void {
|
||||
rememberEndpoint(null);
|
||||
}
|
||||
|
||||
/** Opens the place a tapped notification points at, inside the app's own routing. */
|
||||
export function openPushTarget(url: string): void {
|
||||
let target: URL;
|
||||
try {
|
||||
target = new URL(url, window.location.origin);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// Only this server's pages: a notification never navigates the app elsewhere.
|
||||
if (target.origin !== window.location.origin) return;
|
||||
window.history.pushState({}, '', `${target.pathname}${target.search}${target.hash}`);
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
}
|
||||
|
||||
/** Follows taps on notifications, including the one the app was opened from. */
|
||||
export async function startNativePush(): Promise<void> {
|
||||
if (!nativePushActive()) return;
|
||||
void TrekShell.addListener('pushOpened', ({ url }) => openPushTarget(url));
|
||||
try {
|
||||
const { url } = await TrekShell.takeOpenedPush();
|
||||
if (url) openPushTarget(url);
|
||||
} catch (err) {
|
||||
reportNativeFailure(err);
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,14 @@ export interface TrekShellPlugin {
|
||||
): Promise<{ remove: () => Promise<void> }>;
|
||||
/** Feature sharedFiles: the booking document shared to TREK before the UI ran. */
|
||||
takeSharedFile(): Promise<{ file: SharedFilePayload | null }>;
|
||||
/** Feature nativePush: permission, APNs and the device keys, as a Web Push subscription. Rejects with DENIED. */
|
||||
registerPush(): Promise<{ endpoint: string; keys: { p256dh: string; auth: string } }>;
|
||||
/** Feature nativePush: the notification the app was opened from, before the UI ran. */
|
||||
takeOpenedPush(): Promise<{ url: string | null }>;
|
||||
addListener(
|
||||
event: 'pushOpened',
|
||||
listener: (payload: { url: string }) => void
|
||||
): Promise<{ remove: () => Promise<void> }>;
|
||||
}
|
||||
|
||||
/** A document shared to TREK, as the native side reads it. */
|
||||
|
||||
Reference in New Issue
Block a user