diff --git a/client/src/mobile/screens/settings/MSettings.tsx b/client/src/mobile/screens/settings/MSettings.tsx
index 9c92075d1..02689aff0 100644
--- a/client/src/mobile/screens/settings/MSettings.tsx
+++ b/client/src/mobile/screens/settings/MSettings.tsx
@@ -26,6 +26,7 @@ import MSettingsNotifications from './MSettingsNotifications'
import MSettingsIntegrations from './MSettingsIntegrations'
import MSettingsAccount from './MSettingsAccount'
import MSettingsAbout from './MSettingsAbout'
+import MSettingsServer from './MSettingsServer'
interface SectionTab {
id: string
@@ -118,6 +119,7 @@ export default function MSettings() {
{/* Per-plugin settings still reuse the existing responsive tab. */}
{active.id === 'plugins' && hasPlugins && !managed &&
}
{active.id === 'offline' &&
}
+ {active.id === 'account' &&
}
{active.id === 'account' &&
}
{active.id === 'about' && appVersion &&
}
diff --git a/client/src/mobile/screens/settings/MSettingsAbout.tsx b/client/src/mobile/screens/settings/MSettingsAbout.tsx
index a6f2a983e..8960bb3c0 100644
--- a/client/src/mobile/screens/settings/MSettingsAbout.tsx
+++ b/client/src/mobile/screens/settings/MSettingsAbout.tsx
@@ -2,6 +2,7 @@ import { Bug, BookOpen, Coffee, ExternalLink, Heart, Info, Lightbulb } from 'luc
import type { LucideIcon } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import { MSetCard } from './MSettingsUi'
+import { withoutDonationsInApp } from '../../../utils/donations'
interface AboutLink {
href: string
@@ -14,14 +15,14 @@ interface AboutLink {
export default function MSettingsAbout({ appVersion }: { appVersion: string }) {
const { t } = useTranslation()
- const links: AboutLink[] = [
+ const links: AboutLink[] = withoutDonationsInApp([
{ href: 'https://ko-fi.com/mauriceboe', icon: Coffee, title: 'Ko-fi', sub: t('admin.github.support') },
{ href: 'https://buymeacoffee.com/mauriceboe', icon: Heart, title: 'Buy Me a Coffee', sub: t('admin.github.support') },
{ href: 'https://discord.gg/NhZBDSd4qW', icon: Heart, title: 'Discord', sub: 'Join the community' },
{ href: 'https://github.com/liketrek/TREK/issues/new?template=bug_report.yml', icon: Bug, title: t('settings.about.reportBug'), sub: t('settings.about.reportBugHint') },
{ href: 'https://github.com/liketrek/TREK/discussions/new?category=feature-requests', icon: Lightbulb, title: t('settings.about.featureRequest'), sub: t('settings.about.featureRequestHint') },
{ href: 'https://github.com/liketrek/TREK/wiki', icon: BookOpen, title: 'Wiki', sub: t('settings.about.wikiHint') },
- ]
+ ])
return (
diff --git a/client/src/mobile/screens/settings/MSettingsServer.tsx b/client/src/mobile/screens/settings/MSettingsServer.tsx
new file mode 100644
index 000000000..d7fd34851
--- /dev/null
+++ b/client/src/mobile/screens/settings/MSettingsServer.tsx
@@ -0,0 +1,28 @@
+import { Server } from 'lucide-react';
+
+import { useNativeServer } from '../../../components/Settings/useNativeServer';
+import { useTranslation } from '../../../i18n';
+import { MSetButton, MSetCard, MSetHint } from './MSettingsUi';
+
+/** Only inside the iOS/Android app: which server it talks to, and the way to another one. */
+export default function MSettingsServer() {
+ const { t } = useTranslation();
+ const { host, changeServer, privacyUrl } = useNativeServer();
+ if (!host) return null;
+ return (
+
+ {t('native.settings.serverHint', { server: host })}
+
+ {t('native.changeServer')}
+
+
+ {t('native.privacy')}
+
+
+ );
+}
diff --git a/client/src/native/browserSignIn.test.ts b/client/src/native/browserSignIn.test.ts
new file mode 100644
index 000000000..7c95f3548
--- /dev/null
+++ b/client/src/native/browserSignIn.test.ts
@@ -0,0 +1,79 @@
+import { sha256 } from '@noble/hashes/sha2';
+import { bytesToHex } from '@noble/hashes/utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { nativeAuthApi } from '../api/nativeAuth';
+import {
+ BrowserSignInCancelled,
+ createHandoffSecret,
+ handoffUrl,
+ requestHandoffCode,
+ signInThroughBrowser,
+} from './browserSignIn';
+import { TrekShell } from './trekShell';
+
+vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }));
+vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }));
+
+beforeEach(() => {
+ vi.mocked(TrekShell.authenticate).mockReset();
+ vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue();
+});
+
+describe('createHandoffSecret', () => {
+ it('pairs a fresh 64-character verifier with the hex sha256 the server checks against', () => {
+ const { verifier, challenge } = createHandoffSecret();
+ expect(verifier).toMatch(/^[0-9a-f]{64}$/);
+ expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier))));
+ expect(createHandoffSecret().verifier).not.toBe(verifier);
+ });
+});
+
+describe('requestHandoffCode', () => {
+ it('asks the server for the one-time code bound to the challenge', async () => {
+ vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' });
+ await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1');
+ expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32));
+ });
+});
+
+describe('handoffUrl', () => {
+ it('points at the hand-off page with the challenge and an optional start', () => {
+ expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c');
+ expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe(
+ 'https://trek.example.com/native-handoff?challenge=c&start=oidc'
+ );
+ });
+});
+
+describe('signInThroughBrowser', () => {
+ it('opens the hand-off page and redeems the returned code with the verifier', async () => {
+ vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' });
+
+ await signInThroughBrowser('oidc');
+
+ const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url);
+ expect(opened.pathname).toBe('/native-handoff');
+ expect(opened.searchParams.get('start')).toBe('oidc');
+ expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek');
+ const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0];
+ expect(code).toBe('abc');
+ expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge'));
+ });
+
+ it('turns a closed browser into BrowserSignInCancelled', async () => {
+ vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' }));
+ await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled);
+ expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
+ });
+
+ it('passes other failures on', async () => {
+ vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser'));
+ await expect(signInThroughBrowser()).rejects.toThrow('no browser');
+ });
+
+ it('refuses a return without a code', async () => {
+ vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' });
+ await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code');
+ expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/native/browserSignIn.ts b/client/src/native/browserSignIn.ts
new file mode 100644
index 000000000..c088855c7
--- /dev/null
+++ b/client/src/native/browserSignIn.ts
@@ -0,0 +1,67 @@
+import { sha256 } from '@noble/hashes/sha2';
+import { bytesToHex } from '@noble/hashes/utils';
+import { nativeAuthApi } from '../api/nativeAuth';
+import { APP_URL_SCHEME, TrekShell } from './trekShell';
+
+/**
+ * SSO and passkeys cannot run inside the app's WebView: identity providers
+ * refuse embedded browsers, and WebAuthn wants the app to be associated with
+ * the server's domain, which no build can be for every server. So the app
+ * opens the server's /native-handoff page in the system browser, lets the user
+ * sign in there, and carries the session back with a one-time code.
+ *
+ * The verifier never leaves this function. Only its sha256 travels into the
+ * browser, and the code that comes back through the URL scheme is useless to
+ * anyone who does not also hold the verifier. The hash is computed in JS
+ * because crypto.subtle is missing on a plain-http server, which is how many
+ * home networks reach theirs.
+ */
+
+export const HANDOFF_PATH = '/native-handoff';
+
+export type BrowserSignInStart = 'oidc';
+
+export function createHandoffSecret(): { verifier: string; challenge: string } {
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
+ const verifier = bytesToHex(bytes);
+ return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) };
+}
+
+export function handoffUrl(origin: string, challenge: string, start?: BrowserSignInStart, invite?: string): string {
+ const url = new URL(HANDOFF_PATH, origin);
+ url.searchParams.set('challenge', challenge);
+ if (start) url.searchParams.set('start', start);
+ if (invite) url.searchParams.set('invite', invite);
+ return url.href;
+}
+
+/** The browser side: trade the signed-in session for a one-time code bound to `challenge`. */
+export async function requestHandoffCode(challenge: string): Promise {
+ const { code } = await nativeAuthApi.handoff(challenge);
+ return code;
+}
+
+export class BrowserSignInCancelled extends Error {
+ constructor() {
+ super('Sign-in cancelled');
+ this.name = 'BrowserSignInCancelled';
+ }
+}
+
+/** Resolves once the WebView holds a session cookie of its own. */
+export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise {
+ const { verifier, challenge } = createHandoffSecret();
+ let returned: string;
+ try {
+ ({ url: returned } = await TrekShell.authenticate({
+ url: handoffUrl(window.location.origin, challenge, start, invite),
+ callbackScheme: APP_URL_SCHEME,
+ }));
+ } catch (err) {
+ if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled();
+ throw err;
+ }
+ const code = new URL(returned).searchParams.get('code');
+ if (!code) throw new Error('The browser returned without a sign-in code');
+ await nativeAuthApi.exchange({ code, verifier });
+}
diff --git a/client/src/native/haptics.test.ts b/client/src/native/haptics.test.ts
new file mode 100644
index 000000000..4dc860c01
--- /dev/null
+++ b/client/src/native/haptics.test.ts
@@ -0,0 +1,44 @@
+import { Haptics, NotificationType } from '@capacitor/haptics';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { toastHaptic } from './haptics';
+import { isNativeApp } from './platform';
+
+vi.mock('@capacitor/haptics', () => ({
+ Haptics: { notification: vi.fn() },
+ NotificationType: { Success: 'SUCCESS', Warning: 'WARNING', Error: 'ERROR' },
+}));
+vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
+
+beforeEach(() => {
+ vi.mocked(Haptics.notification).mockReset().mockResolvedValue();
+ vi.mocked(isNativeApp).mockReturnValue(true);
+});
+
+describe('toastHaptic', () => {
+ it('taps for success, warning and error toasts in the app', () => {
+ toastHaptic('success');
+ toastHaptic('warning');
+ toastHaptic('error');
+ expect(vi.mocked(Haptics.notification).mock.calls.map(([o]) => o?.type)).toEqual([
+ NotificationType.Success,
+ NotificationType.Warning,
+ NotificationType.Error,
+ ]);
+ });
+
+ it('stays still for info toasts and in a browser', () => {
+ toastHaptic('info');
+ vi.mocked(isNativeApp).mockReturnValue(false);
+ toastHaptic('success');
+ expect(Haptics.notification).not.toHaveBeenCalled();
+ });
+
+ it('does not let a missing vibrator surface as an error', async () => {
+ const report = vi.fn();
+ vi.stubGlobal('reportError', report);
+ vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'));
+ toastHaptic('error');
+ await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/client/src/native/haptics.ts b/client/src/native/haptics.ts
new file mode 100644
index 000000000..b88f9605e
--- /dev/null
+++ b/client/src/native/haptics.ts
@@ -0,0 +1,20 @@
+import { Haptics, NotificationType } from '@capacitor/haptics';
+import { isNativeApp } from './platform';
+import { reportNativeFailure } from './reportFailure';
+
+const FEEDBACK: Record = {
+ success: NotificationType.Success,
+ warning: NotificationType.Warning,
+ error: NotificationType.Error,
+};
+
+/**
+ * The short tap a native app gives when something saved, warned or failed.
+ * Hung off the toasts because every save and delete already reports through
+ * one; plain info toasts stay silent. Does nothing in a browser.
+ */
+export function toastHaptic(type: string): void {
+ const feedback = FEEDBACK[type];
+ if (!feedback || !isNativeApp()) return;
+ Haptics.notification({ type: feedback }).catch(reportNativeFailure);
+}
diff --git a/client/src/native/iap.test.ts b/client/src/native/iap.test.ts
new file mode 100644
index 000000000..fd7a01643
--- /dev/null
+++ b/client/src/native/iap.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { fakeIapClient, nativeIapClient, productIdFor } from './iap';
+
+describe('in-app purchase client', () => {
+ it('names store products by the shared scheme', () => {
+ expect(productIdFor('start', 'month')).toBe('cloud.start.monthly');
+ expect(productIdFor('pro', 'year')).toBe('cloud.pro.yearly');
+ });
+
+ it('the native client is unavailable until the purchase plugin is wired', async () => {
+ expect(await nativeIapClient.isAvailable()).toBe(false);
+ expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' });
+ });
+
+ it('the fake client yields a receipt for the product asked for', async () => {
+ expect(await fakeIapClient.isAvailable()).toBe(true);
+ const outcome = await fakeIapClient.purchase('cloud.plus.monthly');
+ expect(outcome.kind).toBe('bought');
+ if (outcome.kind !== 'bought') return;
+ expect(outcome.purchase.productId).toBe('cloud.plus.monthly');
+ expect(outcome.purchase.platform).toBe('apple');
+ expect(outcome.purchase.receipt).toContain('cloud.plus.monthly');
+ });
+});
diff --git a/client/src/native/iap.ts b/client/src/native/iap.ts
new file mode 100644
index 000000000..0707f7548
--- /dev/null
+++ b/client/src/native/iap.ts
@@ -0,0 +1,89 @@
+/**
+ * In-app purchase, from the app's side. A seam, like {@link TrekShell}: the
+ * screens drive a plan to a receipt through this, and never touch the store
+ * plugin directly. Two implementations stand behind it — a fake one for
+ * development and preview, so the whole subscription flow can be walked without a
+ * store, and the native one that will call the platform plugin once the store
+ * products and accounts exist. Until then the native client reports itself
+ * unavailable and the plan picker falls back to finishing on the web, so nothing
+ * half-wired ever faces a customer.
+ */
+
+type IapPlatform = 'apple' | 'google';
+
+/** The receipt a completed purchase yields, in the shape `/api/iap/redeem` takes. */
+export interface Purchase {
+ platform: IapPlatform;
+ productId: string;
+ receipt: string;
+}
+
+/** What a purchase attempt came to. `cancelled` is the customer backing out, not an error. */
+type PurchaseOutcome = { kind: 'bought'; purchase: Purchase } | { kind: 'cancelled' } | { kind: 'failed' };
+
+export interface IapClient {
+ /** Whether this build can take a payment: the plugin is present and the store products exist. */
+ isAvailable(): Promise;
+ /** Runs the platform's purchase sheet for a product and resolves with what became of it. */
+ purchase(productId: string): Promise;
+}
+
+/**
+ * The store product id for a plan and interval. Must match the identifiers created
+ * in App Store Connect and the Play Console, and the control plane's catalog
+ * (`cloud..`); kept here as the one place the app names them.
+ */
+export function productIdFor(planId: string, interval: 'month' | 'year'): string {
+ return `cloud.${planId}.${interval === 'year' ? 'yearly' : 'monthly'}`;
+}
+
+/**
+ * The fake used in development and preview: it waits a beat, as a real sheet
+ * would, then returns a receipt the control plane's fake verifier accepts. Never
+ * reached in a store build.
+ */
+export const fakeIapClient: IapClient = {
+ async isAvailable() {
+ return true;
+ },
+ async purchase(productId) {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ return {
+ kind: 'bought',
+ purchase: { platform: 'apple', productId, receipt: `fake-receipt:${productId}:${Date.now()}` },
+ };
+ },
+};
+
+/**
+ * The store client. A stub until the purchase plugin is a dependency and the
+ * products exist: it reports itself unavailable, so the plan picker finishes on
+ * the web instead of offering a payment it cannot take. When the plugin lands,
+ * this is where it is wired; the screens do not change.
+ */
+export const nativeIapClient: IapClient = {
+ async isAvailable() {
+ return false;
+ },
+ async purchase() {
+ return { kind: 'failed' };
+ },
+};
+
+/**
+ * Whether to use the fake. On in a development build, and switchable on in a
+ * preview build with `localStorage['trek-iap-fake'] = '1'`, so the flow can be
+ * shown without a store. Off in a store build, where the native client decides.
+ */
+function fakeEnabled(): boolean {
+ try {
+ if (import.meta.env?.DEV) return true;
+ return typeof localStorage !== 'undefined' && localStorage.getItem('trek-iap-fake') === '1';
+ } catch {
+ return false;
+ }
+}
+
+export function getIapClient(): IapClient {
+ return fakeEnabled() ? fakeIapClient : nativeIapClient;
+}
diff --git a/client/src/native/links.ts b/client/src/native/links.ts
new file mode 100644
index 000000000..f367a8f9d
--- /dev/null
+++ b/client/src/native/links.ts
@@ -0,0 +1,16 @@
+/**
+ * Pages the apps link to outside the user's server. They open in the system
+ * browser: the WebView hands every navigation off the server's own origin to it.
+ */
+
+/** The privacy policy the store listings name too. */
+export const PRIVACY_URL = 'https://liketrek.com/privacy';
+
+/** What a TREK server is and how to run one, for someone who has none yet. */
+export const SERVER_DOCS_URL = 'https://github.com/liketrek/TREK#readme';
+
+/** The public demo the address screen offers to someone without a server. */
+export const DEMO_SERVER_URL = 'https://demo.liketrek.com';
+
+/** TREK Cloud, for someone who wants a hosted TREK rather than running their own. */
+export const CLOUD_URL = 'https://liketrek.com';
diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts
new file mode 100644
index 000000000..7710c502e
--- /dev/null
+++ b/client/src/native/nativeApp.test.ts
@@ -0,0 +1,127 @@
+import { App } from '@capacitor/app';
+import { Keyboard } from '@capacitor/keyboard';
+import { SplashScreen } from '@capacitor/splash-screen';
+import { StatusBar, Style } from '@capacitor/status-bar';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { isEffectivelyOffline } from '../sync/networkMode';
+import { startNativeApp } from './nativeApp';
+import { keepOfflineShellFresh } from './offlineShell';
+import { isNativeApp, isNativeIos } from './platform';
+
+vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }));
+vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } }));
+vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }));
+vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }));
+vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
+vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
+vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
+
+function backButtonHandler(): (event: { canGoBack: boolean }) => void {
+ const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton');
+ if (!call) throw new Error('no backButton listener');
+ return call[1] as unknown as (event: { canGoBack: boolean }) => void;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ vi.mocked(isNativeApp).mockReturnValue(true);
+ vi.mocked(isNativeIos).mockReturnValue(false);
+ vi.mocked(isEffectivelyOffline).mockReturnValue(false);
+ vi.mocked(keepOfflineShellFresh).mockResolvedValue();
+ document.documentElement.classList.remove('dark');
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('startNativeApp', () => {
+ it('does nothing in a browser', () => {
+ vi.mocked(isNativeApp).mockReturnValue(false);
+ startNativeApp();
+ expect(App.addListener).not.toHaveBeenCalled();
+ expect(StatusBar.setStyle).not.toHaveBeenCalled();
+ });
+
+ it('hides the splash after the first frame', () => {
+ startNativeApp();
+ vi.runOnlyPendingTimers();
+ expect(SplashScreen.hide).toHaveBeenCalled();
+ });
+
+ it('walks back through history before it leaves the app', () => {
+ const back = vi.spyOn(window.history, 'back').mockImplementation(() => {});
+ startNativeApp();
+ backButtonHandler()({ canGoBack: true });
+ expect(back).toHaveBeenCalled();
+ backButtonHandler()({ canGoBack: false });
+ expect(App.minimizeApp).toHaveBeenCalled();
+ });
+
+ it('keeps the status bar icons readable when the scheme changes', async () => {
+ startNativeApp();
+ expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light });
+ document.documentElement.classList.add('dark');
+ await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }));
+ });
+
+ it('hides the keyboard accessory bar on iOS only', () => {
+ startNativeApp();
+ expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled();
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ startNativeApp();
+ expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false });
+ });
+
+ it('refreshes the offline start on iOS once the first screen has settled', () => {
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ startNativeApp();
+ expect(keepOfflineShellFresh).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(15_000);
+ expect(keepOfflineShellFresh).toHaveBeenCalled();
+ });
+
+ it('skips the refresh while offline, and never on Android', () => {
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.mocked(isEffectivelyOffline).mockReturnValue(true);
+ startNativeApp();
+ vi.advanceTimersByTime(15_000);
+ expect(keepOfflineShellFresh).not.toHaveBeenCalled();
+
+ vi.mocked(isNativeIos).mockReturnValue(false);
+ vi.mocked(isEffectivelyOffline).mockReturnValue(false);
+ startNativeApp();
+ vi.advanceTimersByTime(15_000);
+ expect(keepOfflineShellFresh).not.toHaveBeenCalled();
+ });
+
+ it('logs a failed refresh instead of throwing', async () => {
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'));
+ const report = vi.fn();
+ vi.stubGlobal('reportError', report);
+ startNativeApp();
+ vi.advanceTimersByTime(15_000);
+ await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
+ vi.unstubAllGlobals();
+ });
+
+ it('stays quiet when the installed app is older than the offline copy', async () => {
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.mocked(keepOfflineShellFresh).mockRejectedValue(
+ Object.assign(new Error('not implemented'), { code: 'UNIMPLEMENTED' })
+ );
+ const report = vi.fn();
+ vi.stubGlobal('reportError', report);
+ startNativeApp();
+ vi.advanceTimersByTime(15_000);
+ await vi.waitFor(() => expect(keepOfflineShellFresh).toHaveBeenCalled());
+ // Let the rejection reach its handler.
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(report).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts
new file mode 100644
index 000000000..ba57310d6
--- /dev/null
+++ b/client/src/native/nativeApp.ts
@@ -0,0 +1,60 @@
+import { App } from '@capacitor/app';
+import { Keyboard } from '@capacitor/keyboard';
+import { SplashScreen } from '@capacitor/splash-screen';
+import { StatusBar, Style } from '@capacitor/status-bar';
+import { isEffectivelyOffline } from '../sync/networkMode';
+import { keepOfflineShellFresh } from './offlineShell';
+import { isNativeApp, isNativeIos } from './platform';
+import { reportNativeFailure } from './reportFailure';
+import { isUnimplemented } from './trekShell';
+
+/** Long enough that the warm-up never competes with the first screen's requests. */
+const OFFLINE_SHELL_DELAY_MS = 15_000;
+
+/**
+ * What the UI does differently when it runs inside the iOS or Android app.
+ * Everything else is the same UI a browser gets from this server.
+ */
+export function startNativeApp(): void {
+ if (!isNativeApp()) return;
+
+ followThemeInStatusBar();
+
+ // Android's back gesture: through the app's own history first, and only
+ // then out of the app, the way a browser tab would behave.
+ void App.addListener('backButton', ({ canGoBack }) => {
+ if (canGoBack) window.history.back();
+ else void App.minimizeApp();
+ });
+
+ requestAnimationFrame(() => {
+ void SplashScreen.hide();
+ });
+
+ if (isNativeIos()) {
+ // The "‹ › Done" strip above the keyboard is a web form's, not an app's.
+ void Keyboard.setAccessoryBarVisible({ isVisible: false });
+ window.setTimeout(() => {
+ if (isEffectivelyOffline()) return;
+ // Not refreshed this time is no harm: the next launch tries again. An app
+ // older than the offline copy has no such method, which is no failure.
+ keepOfflineShellFresh().catch((err: unknown) => {
+ if (!isUnimplemented(err)) reportNativeFailure(err);
+ });
+ }, OFFLINE_SHELL_DELAY_MS);
+ }
+}
+
+/**
+ * Light icons on the dark scheme and dark icons on the light one. Observing
+ * the class keeps applyAppearance() the only writer of , and it catches
+ * every way the scheme changes, including "follow the system".
+ */
+function followThemeInStatusBar(): void {
+ const root = document.documentElement;
+ const apply = (): void => {
+ void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light });
+ };
+ apply();
+ new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] });
+}
diff --git a/client/src/native/nativeFiles.test.ts b/client/src/native/nativeFiles.test.ts
new file mode 100644
index 000000000..ecf7df911
--- /dev/null
+++ b/client/src/native/nativeFiles.test.ts
@@ -0,0 +1,53 @@
+import { Directory, Filesystem } from '@capacitor/filesystem';
+import { Share } from '@capacitor/share';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles';
+
+vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } }));
+vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } }));
+
+beforeEach(() => {
+ vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' });
+ vi.mocked(Share.share).mockReset().mockResolvedValue({});
+});
+
+describe('cacheFileName', () => {
+ it('keeps a readable name but nothing that could leave the cache directory', () => {
+ expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf');
+ expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd');
+ expect(cacheFileName('a:b*c?"d"|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt');
+ expect(cacheFileName('...hidden')).toBe('hidden');
+ expect(cacheFileName(' ')).toBe('download');
+ });
+});
+
+describe('fileNameFromUrl', () => {
+ it('takes the decoded last path segment', () => {
+ expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf');
+ expect(fileNameFromUrl('/uploads/files/')).toBe('files');
+ expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A');
+ });
+});
+
+describe('shareFile', () => {
+ it('writes the blob to the cache and hands it to the share sheet', async () => {
+ await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt');
+
+ expect(Filesystem.writeFile).toHaveBeenCalledWith({
+ path: 'note.txt',
+ data: btoa('hello'),
+ directory: Directory.Cache,
+ });
+ expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] });
+ });
+
+ it('treats a dismissed sheet as the user changing their mind', async () => {
+ vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled'));
+ await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined();
+ });
+
+ it('passes a real failure on', async () => {
+ vi.mocked(Share.share).mockRejectedValue(new Error('No activity found'));
+ await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found');
+ });
+});
diff --git a/client/src/native/nativeFiles.ts b/client/src/native/nativeFiles.ts
new file mode 100644
index 000000000..a72b916ec
--- /dev/null
+++ b/client/src/native/nativeFiles.ts
@@ -0,0 +1,49 @@
+import { Directory, Filesystem } from '@capacitor/filesystem';
+import { Share } from '@capacitor/share';
+
+function toBase64(blob: Blob): Promise {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
+}
+
+/** Readable, but safe as a single path segment inside the cache directory. */
+export function cacheFileName(filename: string): string {
+ const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch))
+ .join('')
+ .trim();
+ return cleaned.replace(/^\.+/, '') || 'download';
+}
+
+export function fileNameFromUrl(url: string): string {
+ const [path = ''] = url.split('?', 1);
+ const last = path.split('/').filter(Boolean).pop() ?? '';
+ try {
+ return decodeURIComponent(last);
+ } catch {
+ return last;
+ }
+}
+
+/**
+ * The app's WebView cannot save a download on its own, so the file goes into
+ * the app's cache and from there into the system share sheet, which offers
+ * saving it to Files, opening it in another app or sending it on.
+ */
+export async function shareFile(blob: Blob, filename: string): Promise {
+ const { uri } = await Filesystem.writeFile({
+ path: cacheFileName(filename),
+ data: await toBase64(blob),
+ directory: Directory.Cache,
+ });
+ try {
+ await Share.share({ files: [uri] });
+ } catch (err) {
+ // Dismissing the sheet rejects; that is the user's choice, not a failure.
+ if (/cancel/i.test(String((err as Error)?.message))) return;
+ throw err;
+ }
+}
diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts
new file mode 100644
index 000000000..2c479d514
--- /dev/null
+++ b/client/src/native/offlineShell.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { keepOfflineShellFresh, manifestFiles } from './offlineShell';
+import { TrekShell } from './trekShell';
+
+vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } }));
+
+const manifest = {
+ 'index.html': {
+ file: 'assets/index-a1b2c3d4.js',
+ css: ['assets/index-e5f6a7b8.css'],
+ assets: ['assets/poppins-11223344.woff2'],
+ },
+ 'src/pages/AtlasPage.tsx': { file: 'assets/AtlasPage-99887766.js', css: ['assets/index-e5f6a7b8.css'] },
+ _shared: { file: 'assets/shared-55443322.js', assets: 'not-a-list' },
+ broken: null,
+};
+
+beforeEach(() => {
+ vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true });
+});
+
+describe('manifestFiles', () => {
+ it('collects every chunk, stylesheet and asset once', () => {
+ expect(manifestFiles(manifest).sort()).toEqual([
+ 'assets/AtlasPage-99887766.js',
+ 'assets/index-a1b2c3d4.js',
+ 'assets/index-e5f6a7b8.css',
+ 'assets/poppins-11223344.woff2',
+ 'assets/shared-55443322.js',
+ ]);
+ });
+
+ it('returns nothing for something that is not a manifest', () => {
+ expect(manifestFiles(null)).toEqual([]);
+ expect(manifestFiles('x')).toEqual([]);
+ });
+});
+
+describe('keepOfflineShellFresh', () => {
+ it('refreshes the stored start page and fetches every file of the build', async () => {
+ const fetched: string[] = [];
+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/asset-manifest.json') {
+ expect(init).toEqual({ cache: 'no-store' });
+ return new Response(JSON.stringify(manifest));
+ }
+ fetched.push(url);
+ if (url.includes('shared')) throw new Error('offline for a moment');
+ return new Response('x');
+ }) as unknown as typeof fetch;
+
+ await keepOfflineShellFresh(fetchImpl);
+
+ expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled();
+ expect(fetched.sort()).toEqual([
+ '/assets/AtlasPage-99887766.js',
+ '/assets/index-a1b2c3d4.js',
+ '/assets/index-e5f6a7b8.css',
+ '/assets/poppins-11223344.woff2',
+ '/assets/shared-55443322.js',
+ ]);
+ });
+
+ it('stops after the start page when the build has no manifest', async () => {
+ const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch;
+ await keepOfflineShellFresh(fetchImpl);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts
new file mode 100644
index 000000000..f509ba160
--- /dev/null
+++ b/client/src/native/offlineShell.ts
@@ -0,0 +1,54 @@
+import { TrekShell } from './trekShell';
+
+/**
+ * iOS only. WKWebView runs no service worker for a domain the app does not
+ * list at build time, so the app stands in for it: the native side keeps a
+ * copy of the start page (TrekShellPlugin.refreshOfflineCopy), and this pulls
+ * every chunk of the current build into WebKit's HTTP cache. The server marks
+ * them immutable, so a cold start without network can load the stored start
+ * page under the server's origin and find all its scripts, including the lazy
+ * routes nobody has opened yet.
+ */
+
+const MANIFEST_URL = '/asset-manifest.json';
+const CONCURRENCY = 4;
+
+interface ManifestChunk {
+ file?: string;
+ css?: string[];
+ assets?: string[];
+}
+
+export function manifestFiles(manifest: unknown): string[] {
+ if (typeof manifest !== 'object' || manifest === null) return [];
+ const files = new Set();
+ for (const chunk of Object.values(manifest as Record)) {
+ if (typeof chunk?.file === 'string') files.add(chunk.file);
+ for (const list of [chunk?.css, chunk?.assets]) {
+ if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f));
+ }
+ }
+ return [...files];
+}
+
+async function warmCache(files: string[], fetchFile: (path: string) => Promise): Promise {
+ const queue = [...files];
+ const worker = async (): Promise => {
+ for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
+ try {
+ await fetchFile(`/${path}`);
+ } catch {
+ // One missing chunk must not stop the rest; the next launch tries again.
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));
+}
+
+export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise {
+ await TrekShell.refreshOfflineCopy();
+ const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
+ if (!response.ok) return;
+ const files = manifestFiles(await response.json());
+ await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob()));
+}
diff --git a/client/src/native/offlineTiles.test.ts b/client/src/native/offlineTiles.test.ts
new file mode 100644
index 000000000..af235b99d
--- /dev/null
+++ b/client/src/native/offlineTiles.test.ts
@@ -0,0 +1,183 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ fromOfflineUrl,
+ installOfflineProtocol,
+ offlineProtocol,
+ offlineStyle,
+ rewriteDocument,
+ toOfflineUrl,
+} from './offlineTiles';
+import { isNativeIos } from './platform';
+
+vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
+
+const cached = new Map();
+const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) };
+
+beforeEach(() => {
+ cached.clear();
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.stubGlobal('caches', { open: vi.fn(async () => cache) });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function params(url: string, type: 'json' | 'arrayBuffer' | 'image' | 'string') {
+ return { url, type };
+}
+
+describe('URL rewriting', () => {
+ it('moves https URLs onto the protocol and back, and leaves everything else', () => {
+ expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe(
+ 'trek-offline://tiles.openfreemap.org/styles/positron'
+ );
+ expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe(
+ 'https://tiles.openfreemap.org/styles/positron'
+ );
+ expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12');
+ expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a');
+ });
+
+ it('rewrites the style only inside the iOS app with Cache Storage', () => {
+ const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc';
+ expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc');
+ expect(offlineStyle({ version: 8 })).toEqual({ version: 8 });
+
+ vi.mocked(isNativeIos).mockReturnValue(false);
+ expect(offlineStyle(style)).toBe(style);
+
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.stubGlobal('caches', undefined);
+ expect(offlineStyle(style)).toBe(style);
+ });
+
+ it('points sources, tiles, glyphs and sprites of a style at the protocol', () => {
+ expect(
+ rewriteDocument({
+ version: 8,
+ glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
+ sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
+ sources: {
+ openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
+ inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] },
+ broken: null,
+ },
+ layers: [],
+ })
+ ).toEqual({
+ version: 8,
+ glyphs: 'trek-offline://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
+ sprite: [{ id: 'default', url: 'trek-offline://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
+ sources: {
+ openmaptiles: { type: 'vector', url: 'trek-offline://tiles.openfreemap.org/planet' },
+ inline: { type: 'raster', tiles: ['trek-offline://a.test/{z}/{x}/{y}.png', 7] },
+ broken: null,
+ },
+ layers: [],
+ });
+ });
+
+ it('handles a TileJSON, a single sprite URL and things that are not documents', () => {
+ expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({
+ tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'],
+ });
+ expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' });
+ expect(rewriteDocument('x')).toBe('x');
+ expect(rewriteDocument([1])).toEqual([1]);
+ });
+});
+
+describe('offlineProtocol', () => {
+ it('answers a document from the network and rewrites it', async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] })));
+ vi.stubGlobal('fetch', fetchMock);
+ const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController());
+ expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' }));
+ expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] });
+ });
+
+ it('falls back to the cached document when the network is gone', async () => {
+ cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 })));
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('offline');
+ })
+ );
+ const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController());
+ expect(result.data).toEqual({ version: 8 });
+ });
+
+ it('serves tiles from the cache without asking the network', async () => {
+ cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3])));
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const result = await offlineProtocol(
+ params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'),
+ new AbortController()
+ );
+ expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3]));
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('fetches an uncached tile, and returns text for string requests', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('hello'))
+ );
+ const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController());
+ expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello');
+ const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController());
+ expect(text.data).toBe('hello');
+ });
+
+ it('fails loudly on an uncached tile offline or an HTTP error', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('offline');
+ })
+ );
+ await expect(
+ offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
+ ).rejects.toThrow('offline');
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('nope', { status: 404 }))
+ );
+ await expect(
+ offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
+ ).rejects.toThrow('HTTP 404');
+ await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow(
+ 'Not available offline'
+ );
+ });
+
+ it('passes an abort straight through for documents', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new DOMException('aborted', 'AbortError');
+ })
+ );
+ await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted');
+ });
+});
+
+describe('installOfflineProtocol', () => {
+ it('registers only inside the iOS app', () => {
+ const addProtocol = vi.fn();
+ installOfflineProtocol({ addProtocol });
+ expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol);
+
+ addProtocol.mockClear();
+ vi.mocked(isNativeIos).mockReturnValue(false);
+ installOfflineProtocol({ addProtocol });
+ expect(addProtocol).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/native/offlineTiles.ts b/client/src/native/offlineTiles.ts
new file mode 100644
index 000000000..9f3c2bd31
--- /dev/null
+++ b/client/src/native/offlineTiles.ts
@@ -0,0 +1,116 @@
+import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl';
+import { VECTOR_CACHE } from '../sync/glPrefetcher';
+import { isNativeIos } from './platform';
+
+/**
+ * Offline vector maps for the iOS app.
+ *
+ * In a browser the service worker answers MapLibre's requests from the
+ * 'gl-map-offline' cache that glPrefetcher fills for trips marked for offline.
+ * The iOS app has no service worker, so nothing reads that cache there. This
+ * protocol takes the service worker's place: the style URL is rewritten to
+ * trek-offline://, every https URL inside the style and its TileJSON gets the
+ * same scheme, and the handler serves them from the cache or the network.
+ *
+ * Mapbox GL has no protocol hook, so a Mapbox basemap stays online-only in
+ * the app.
+ */
+
+const OFFLINE_SCHEME = 'trek-offline';
+const PREFIX = `${OFFLINE_SCHEME}://`;
+
+function offlineTilesActive(): boolean {
+ return isNativeIos() && typeof caches !== 'undefined';
+}
+
+export function toOfflineUrl(url: string): string {
+ return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url;
+}
+
+export function fromOfflineUrl(url: string): string {
+ return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url;
+}
+
+/** The style URL to hand MapLibre: rewritten inside the iOS app, untouched anywhere else. */
+export function offlineStyle(style: T): T {
+ return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style;
+}
+
+type Doc = Record;
+/** What a protocol handler may hand MapLibre back. */
+type ProtocolData = Awaited>['data'];
+
+const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value);
+const rewriteList = (value: unknown): unknown =>
+ Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value;
+
+/**
+ * Points the URLs inside a style document or a TileJSON at the protocol, so
+ * that MapLibre asks this handler for the sprite, the glyphs, the TileJSON and
+ * the tiles as well, not only for the style.
+ */
+export function rewriteDocument(doc: unknown): unknown {
+ if (!isDoc(doc)) return doc;
+ const out: Doc = { ...doc };
+ if ('tiles' in out) out.tiles = rewriteList(out.tiles);
+ if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs);
+ if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite);
+ else if (Array.isArray(out.sprite)) {
+ out.sprite = out.sprite.map((entry) =>
+ isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry
+ );
+ }
+ if (isDoc(out.sources)) {
+ out.sources = Object.fromEntries(
+ Object.entries(out.sources).map(([id, source]) => {
+ if (!isDoc(source)) return [id, source];
+ const rewritten: Doc = { ...source };
+ if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url);
+ if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles);
+ return [id, rewritten];
+ })
+ );
+ }
+ return out;
+}
+
+/**
+ * Documents are asked of the network first so a changed style shows up, and
+ * fall back to the cache offline. Tiles, glyphs and sprites never change under
+ * their URL, so the cache goes first and saves the round trip.
+ */
+async function load(url: string, networkFirst: boolean, signal: AbortSignal): Promise {
+ const cache = await caches.open(VECTOR_CACHE);
+ if (!networkFirst) {
+ const cached = await cache.match(url);
+ if (cached) return cached;
+ }
+ try {
+ const response = await fetch(url, { mode: 'cors', signal });
+ if (response.ok) return response;
+ if (!networkFirst) return response;
+ } catch (err) {
+ if (signal.aborted || !networkFirst) throw err;
+ }
+ const cached = await cache.match(url);
+ if (cached) return cached;
+ throw new Error(`Not available offline: ${url}`);
+}
+
+export const offlineProtocol: AddProtocolAction = async (
+ params: RequestParameters,
+ abortController: AbortController
+): Promise> => {
+ const url = fromOfflineUrl(params.url);
+ const response = await load(url, params.type === 'json', abortController.signal);
+ if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
+ if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData };
+ if (params.type === 'string') return { data: await response.text() };
+ return { data: await response.arrayBuffer() };
+};
+
+export function installOfflineProtocol(maplibre: {
+ addProtocol: (name: string, action: AddProtocolAction) => void;
+}): void {
+ if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol);
+}
diff --git a/client/src/native/platform.test.ts b/client/src/native/platform.test.ts
new file mode 100644
index 000000000..96a50ce77
--- /dev/null
+++ b/client/src/native/platform.test.ts
@@ -0,0 +1,33 @@
+import { Capacitor } from '@capacitor/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { isNativeApp, isNativeIos, nativeServerHost } from './platform';
+
+vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } }));
+
+beforeEach(() => {
+ vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true);
+ vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
+});
+
+describe('platform', () => {
+ it('tells the app from a browser', () => {
+ expect(isNativeApp()).toBe(true);
+ vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
+ expect(isNativeApp()).toBe(false);
+ });
+
+ it('narrows to iOS', () => {
+ expect(isNativeIos()).toBe(true);
+ vi.mocked(Capacitor.getPlatform).mockReturnValue('android');
+ expect(isNativeIos()).toBe(false);
+ vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
+ vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
+ expect(isNativeIos()).toBe(false);
+ });
+
+ it('names the server the WebView sits on, only inside the app', () => {
+ expect(nativeServerHost()).toBe(window.location.host);
+ vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
+ expect(nativeServerHost()).toBeNull();
+ });
+});
diff --git a/client/src/native/platform.ts b/client/src/native/platform.ts
new file mode 100644
index 000000000..df1e5c5fd
--- /dev/null
+++ b/client/src/native/platform.ts
@@ -0,0 +1,15 @@
+import { Capacitor } from '@capacitor/core';
+
+/** True inside the iOS and Android apps, where the WebView shows this server's UI. */
+export function isNativeApp(): boolean {
+ return Capacitor.isNativePlatform();
+}
+
+export function isNativeIos(): boolean {
+ return isNativeApp() && Capacitor.getPlatform() === 'ios';
+}
+
+/** The server the app is connected to: the WebView sits on its origin. */
+export function nativeServerHost(): string | null {
+ return isNativeApp() ? window.location.host : null;
+}
diff --git a/client/src/native/reportFailure.test.ts b/client/src/native/reportFailure.test.ts
new file mode 100644
index 000000000..3cf9dee12
--- /dev/null
+++ b/client/src/native/reportFailure.test.ts
@@ -0,0 +1,22 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { reportNativeFailure } from './reportFailure';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('reportNativeFailure', () => {
+ it('hands the failure to the page error event', () => {
+ const report = vi.fn();
+ vi.stubGlobal('reportError', report);
+ const err = new Error('share failed');
+ reportNativeFailure(err);
+ expect(report).toHaveBeenCalledWith(err);
+ });
+
+ it('does nothing where the runtime has no reportError', () => {
+ vi.stubGlobal('reportError', undefined);
+ expect(() => reportNativeFailure(new Error('x'))).not.toThrow();
+ });
+});
diff --git a/client/src/native/reportFailure.ts b/client/src/native/reportFailure.ts
new file mode 100644
index 000000000..f02396c61
--- /dev/null
+++ b/client/src/native/reportFailure.ts
@@ -0,0 +1,9 @@
+/**
+ * For the app's best-effort calls (a haptic tap, the offline start page, a
+ * share sheet): the failure is not worth a toast, but it must not vanish
+ * either. reportError() hands it to the page's error event, which
+ * utils/globalErrorHandlers.ts logs like any other uncaught error.
+ */
+export function reportNativeFailure(err: unknown): void {
+ if (typeof globalThis.reportError === 'function') globalThis.reportError(err);
+}
diff --git a/client/src/native/serverAddress.test.ts b/client/src/native/serverAddress.test.ts
new file mode 100644
index 000000000..a66508093
--- /dev/null
+++ b/client/src/native/serverAddress.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it, vi } from 'vitest';
+import { candidateUrls, probeDemo, probeServer, type ProbeResponse } from './serverAddress';
+
+const features = (
+ url: string,
+ data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true }
+): ProbeResponse => ({ status: 200, data, url });
+
+describe('candidateUrls', () => {
+ it('tries https before http when no scheme was typed', () => {
+ expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com']);
+ expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001']);
+ });
+
+ it('keeps an explicit scheme and path, without query, hash or trailing slashes', () => {
+ expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek']);
+ expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com']);
+ });
+
+ it('returns nothing for empty input or other schemes', () => {
+ expect(candidateUrls(' ')).toEqual([]);
+ expect(candidateUrls('ftp://trek.example.com')).toEqual([]);
+ expect(candidateUrls('javascript://alert(1)')).toEqual([]);
+ });
+});
+
+describe('probeServer', () => {
+ it('accepts a server at the minimum native API version or above', async () => {
+ const data = { bookingImport: false, nativeApp: true, nativeApi: 1 };
+ const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data));
+ expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
+ });
+
+ it('calls a server below the minimum native API version too old', async () => {
+ const data = { bookingImport: false, nativeApp: true, nativeApi: 0 };
+ const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data));
+ expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: false, reason: 'tooOld' });
+ });
+
+ it('accepts a server that reports nativeApp and follows its redirect', async () => {
+ const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features'));
+ expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
+ expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features');
+ });
+
+ it('falls back to the candidate itself when the final URL is not the probe path', async () => {
+ const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login'));
+ expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
+ });
+
+ it('moves on to plain http when https cannot be reached', async () => {
+ const get = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('ECONNREFUSED'))
+ .mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features'));
+ expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' });
+ expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features');
+ });
+
+ it('names a TREK server without the native flag as too old', async () => {
+ const get = vi
+ .fn()
+ .mockResolvedValue(
+ features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false })
+ );
+ expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' });
+ });
+
+ it('tells a server that is not TREK apart from one that is not there', async () => {
+ const html = vi
+ .fn()
+ .mockResolvedValue({ status: 200, data: '', url: 'https://x.example.com/api/health/features' });
+ expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' });
+
+ const missing = vi
+ .fn()
+ .mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' });
+ expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' });
+
+ const down = vi.fn().mockRejectedValue(new Error('timeout'));
+ expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' });
+ });
+
+ it('keeps the most telling failure across candidates', async () => {
+ const get = vi
+ .fn()
+ .mockResolvedValueOnce(features('https://nas.local/api/health/features', { bookingImport: false }))
+ .mockRejectedValueOnce(new Error('ECONNREFUSED'));
+ expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' });
+ });
+
+ it('refuses input that is not an address', async () => {
+ const get = vi.fn();
+ expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' });
+ expect(get).not.toHaveBeenCalled();
+ });
+});
+
+describe('probeDemo', () => {
+ it('probes the public demo server the address screen offers', async () => {
+ const get = vi.fn().mockResolvedValue(features('https://demo.liketrek.com/api/health/features'));
+ expect(await probeDemo(get)).toEqual({ ok: true, url: 'https://demo.liketrek.com' });
+ expect(get).toHaveBeenCalledWith('https://demo.liketrek.com/api/health/features');
+ });
+});
diff --git a/client/src/native/serverAddress.ts b/client/src/native/serverAddress.ts
new file mode 100644
index 000000000..d2a51305f
--- /dev/null
+++ b/client/src/native/serverAddress.ts
@@ -0,0 +1,92 @@
+import { DEMO_SERVER_URL } from './links';
+
+/**
+ * Turns what someone typed into the app's address field into a TREK server it
+ * can load, or a reason it cannot.
+ */
+
+export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld';
+type ProbeResult = { ok: true; url: string; reason?: undefined } | { ok: false; reason: ProbeFailure; url?: undefined };
+
+export interface ProbeResponse {
+ status: number;
+ data: unknown;
+ /** The URL after redirects. */
+ url: string;
+}
+export type ProbeGet = (url: string) => Promise;
+
+const FEATURES_PATH = '/api/health/features';
+
+/**
+ * The oldest server API this app can work with (`nativeApi` in the features
+ * response). A server from before the field existed answers without it and is
+ * accepted while the minimum is 1.
+ */
+const MIN_NATIVE_API = 1;
+
+function normalize(raw: string): string | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(raw);
+ } catch {
+ return null;
+ }
+ if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null;
+ return parsed.origin + parsed.pathname.replace(/\/+$/, '');
+}
+
+/**
+ * Without a scheme, https comes first and plain http second: a server on the
+ * home network is often reached as a bare IP and port without TLS.
+ */
+export function candidateUrls(input: string): string[] {
+ const trimmed = input.trim();
+ if (!trimmed) return [];
+ const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
+ ? [normalize(trimmed)]
+ : [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)];
+ return candidates.filter((url): url is string => url !== null);
+}
+
+function isRecord(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null;
+}
+
+function judge(response: ProbeResponse): ProbeResult {
+ if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' };
+ if (response.data.nativeApp === true) {
+ const api = response.data.nativeApi;
+ if (typeof api === 'number' && api < MIN_NATIVE_API) return { ok: false, reason: 'tooOld' };
+ // Follow a redirect (http to https, a canonical host) so the app loads the
+ // address the server actually answers on.
+ const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null;
+ return { ok: true, url: (base && normalize(base)) || '' };
+ }
+ return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' };
+}
+
+const FAILURE_RANK: Record = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 };
+
+export async function probeServer(input: string, get: ProbeGet): Promise {
+ const candidates = candidateUrls(input);
+ if (!candidates.length) return { ok: false, reason: 'invalid' };
+
+ let failure: ProbeFailure = 'unreachable';
+ for (const candidate of candidates) {
+ let verdict: ProbeResult;
+ try {
+ verdict = judge(await get(candidate + FEATURES_PATH));
+ } catch {
+ continue;
+ }
+ if (verdict.ok) return { ok: true, url: verdict.url || candidate };
+ if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason;
+ }
+ return { ok: false, reason: failure };
+}
+
+/** The address screen's "Try the demo": the same probe, against the public demo server. */
+export function probeDemo(get: ProbeGet): Promise {
+ return probeServer(DEMO_SERVER_URL, get);
+}
diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts
new file mode 100644
index 000000000..548f12183
--- /dev/null
+++ b/client/src/native/trekShell.ts
@@ -0,0 +1,45 @@
+import { registerPlugin } from '@capacitor/core';
+
+/**
+ * The app's own native plugin, implemented in
+ * ios/App/App/TrekShellPlugin.swift and
+ * android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java.
+ *
+ * The app is a frame around the UI the user's server delivers, so what the
+ * web side needs from it is small: which server that is, a way to change it,
+ * a system browser for the sign-ins a WebView cannot do, and on iOS the
+ * offline copy of the start page that stands in for the missing service
+ * worker.
+ */
+export interface TrekShellPlugin {
+ getServer(): Promise<{ url: string | null }>;
+ /** Remembers the server and loads it. The current page is gone afterwards. */
+ setServer(options: { url: string }): Promise;
+ /** Forgets the server and returns to the address screen. */
+ resetServer(): Promise;
+ /** Loads the remembered server again, after it could not be reached. */
+ reload(): Promise;
+ /**
+ * Opens `url` in the system browser and resolves with the URL it was sent
+ * back to under `callbackScheme`. Rejects with code `CANCELLED` when the
+ * user closes the browser.
+ */
+ authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>;
+ /** iOS: stores the server's start page for a cold start without network. */
+ refreshOfflineCopy(): Promise<{ saved: boolean }>;
+ /** iOS: loads that copy under the server's origin. False when there is none. */
+ openOfflineCopy(): Promise<{ opened: boolean }>;
+}
+
+export const TrekShell = registerPlugin('TrekShell');
+
+export const APP_URL_SCHEME = 'com.liketrek.trek';
+
+/**
+ * True for the rejection Capacitor gives when the installed app has no such
+ * native method: the UI comes from the server, so a newer server can call into
+ * an app binary that predates the method.
+ */
+export function isUnimplemented(err: unknown): boolean {
+ return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'UNIMPLEMENTED';
+}
diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx
index 8b3cbfe67..5e0d8eae7 100644
--- a/client/src/pages/LoginPage.tsx
+++ b/client/src/pages/LoginPage.tsx
@@ -17,7 +17,7 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch';
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n';
import { IDP_LOGIN_URL, useLogin } from './login/useLogin';
import LoginWorld from './login/LoginWorld';
-import { clearSignedOut } from '../utils/signedOut'
+import NativeServerLink from './login/NativeServerLink';
import PasswordChecklist from '../components/shared/PasswordChecklist';
/** Fixed so the sky does not reshuffle on every render. */
@@ -85,9 +85,7 @@ export default function LoginPage(): React.ReactElement {
configWait,
idpSlow,
idpName,
- handleDemoLogin,
- handleSubmit,
- handlePasskeyLogin,
+ handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick,
} = useLogin();
const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly);
@@ -490,7 +488,7 @@ export default function LoginPage(): React.ReactElement {
{idpSlow && (
{t('login.oidcRedirectSlow', { name: idpName })}
@@ -534,7 +532,7 @@ export default function LoginPage(): React.ReactElement {
)}