feat(native): the UI knows when it runs inside the app

Everything the server's UI does differently inside the iOS and Android app
lives under src/native and is inert in a browser.

Sign-in: SSO and the passkey button go through the system browser
(signInThroughBrowser), because identity providers refuse embedded
browsers and WebAuthn needs a domain association no build can have for
every server. The browser end is the new /native-handoff page: it signs
the user in if needed and hands the session over only after an explicit
tap, so a link carrying somebody else's challenge cannot pass a session
on silently. The verifier is hashed with @noble/hashes because
crypto.subtle is missing on the plain-http servers many home networks
use. An OIDC-only install no longer bounces to the IdP inside the
WebView, and passkey management is hidden in the app.

Downloads: the WebView cannot save a blob, so downloadBlob, downloadFile
and openFile write to the app cache and open the share sheet. The eight
places that built their own download anchor now use downloadBlob, which
they should have anyway.

The rest: "Change server" on the login page and in the account settings,
the splash hides after the first frame, Android's back button walks
history before it leaves the app, the status bar follows the scheme, and
on iOS the start page is refreshed and every chunk of the build (listed
in the new asset-manifest.json) is pulled into WebKit's cache so the app
can start without network.
This commit is contained in:
Maurice
2026-09-24 12:42:34 +02:00
parent c5765bbf15
commit ae0d4e4520
37 changed files with 1153 additions and 88 deletions
+63
View File
@@ -0,0 +1,63 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { sha256 } from '@noble/hashes/sha2'
import { bytesToHex } from '@noble/hashes/utils'
import { BrowserSignInCancelled, createHandoffSecret, handoffUrl, signInThroughBrowser } from './browserSignIn'
import { TrekShell } from './trekShell'
import { nativeAuthApi } from '../api/nativeAuth'
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }))
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: 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('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()
})
})
+61
View File
@@ -0,0 +1,61 @@
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
}
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<void> {
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 })
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { App } from '@capacitor/app'
import { SplashScreen } from '@capacitor/splash-screen'
import { StatusBar, Style } from '@capacitor/status-bar'
import { startNativeApp } from './nativeApp'
import { isNativeApp, isNativeIos } from './platform'
import { keepOfflineShellFresh } from './offlineShell'
import { isEffectivelyOffline } from '../sync/networkMode'
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: 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')
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('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 warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
startNativeApp()
vi.advanceTimersByTime(15_000)
await vi.waitFor(() => expect(warn).toHaveBeenCalled())
})
})
+49
View File
@@ -0,0 +1,49 @@
import { App } from '@capacitor/app'
import { SplashScreen } from '@capacitor/splash-screen'
import { StatusBar, Style } from '@capacitor/status-bar'
import { isNativeApp, isNativeIos } from './platform'
import { keepOfflineShellFresh } from './offlineShell'
import { isEffectivelyOffline } from '../sync/networkMode'
/** 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()) {
window.setTimeout(() => {
if (isEffectivelyOffline()) return
keepOfflineShellFresh().catch((err) => console.warn('[native] offline start page not refreshed', 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 <html>, 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'] })
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Directory, Filesystem } from '@capacitor/filesystem'
import { Share } from '@capacitor/share'
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"<e>|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')
})
})
+46
View File
@@ -0,0 +1,46 @@
import { Directory, Filesystem } from '@capacitor/filesystem'
import { Share } from '@capacitor/share'
function toBase64(blob: Blob): Promise<string> {
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 last = url.split('?')[0]!.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<void> {
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
}
}
+66
View File
@@ -0,0 +1,66 @@
import { describe, it, expect, vi, beforeEach } 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)
})
})
+51
View File
@@ -0,0 +1,51 @@
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<string>()
for (const chunk of Object.values(manifest as Record<string, ManifestChunk>)) {
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<unknown>): Promise<void> {
const queue = [...files]
const worker = async (): Promise<void> => {
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
// One missing chunk must not stop the rest; the next launch tries again.
await fetchFile(`/${path}`).catch(() => undefined)
}
}
await Promise.all(Array.from({ length: CONCURRENCY }, worker))
}
export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise<void> {
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()))
}
+15
View File
@@ -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
}