Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
fix(mobile): trust user-installed CAs and allow cleartext to local servers (#79) (#82)
Carter92b8c9cff9e0
diff --git a/.gitignore b/.gitignoreindex 0f52b17..dfc41b3 100644--- a/.gitignore+++ b/.gitignore@@ -62,3 +62,17 @@ web/playwright-report/# Local Fable/Sonnet porting specs (working artifacts, not committed).workouts-port/++# Built mobile APKs — pulled from EAS for local testing, ~107MB each. Releases are+# distributed as GitHub release assets, never committed.+/releases/++# Ad-hoc screenshots dropped at the repo root during local testing. Scoped to the+# root only — mobile/assets, web/public and README screenshots stay tracked.+/*.png++# Design-system export (fonts, ui_kits, raw asset dumps) — local working material.+/design/++# MCP server config: machine-specific absolute paths, not portable across checkouts.+.mcp.jsondiff --git a/mobile/README.md b/mobile/README.mdindex 87437ba..0292190 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -5,7 +5,7 @@ Zustand stores — with the web app via [`@lyftr/shared`](../packages/shared). U(SwiftUI/Kotlin-backed RN primitives), styled with NativeWind.## Stack-- **Expo (SDK 52)** + **expo-router** (file-based routes in `app/`)+- **Expo (SDK 54)** + **expo-router** (file-based routes in `app/`)- **NativeWind** (Tailwind for RN) — tokens ported from the web `tailwind.config.ts`- **@lyftr/shared** — the platform-agnostic core (storage-injected)- **expo-secure-store** (tokens → Keychain) + **AsyncStorage** (prefs)@@ -35,6 +35,24 @@ The **Server URL** field in the Settings tab configures the backend origin (valithe Tailscale URL, e.g. `https://claude-code.tail2b1098.ts.net:3000`. Demo login:`[email protected]` / `password123`.+## Native networking config+`network_security_config.xml` is an Android+[network security config](https://developer.android.com/privacy-and-security/security-config)+permitting cleartext HTTP and trusting the user-installed CA store (issue #79). The file's+own header explains why and what it deliberately does *not* do. It's copied into the build+by [`expo-network-security-config`](https://github.com/pchalupa/expo-network-security-config),+wired up in `app.json` — a maintained plugin rather than a hand-rolled one, so tracking+Expo SDK changes to the underlying dangerous mod isn't our job.++What matters when working on it: it's applied at prebuild, so changes only take effect in a+**new build** — EAS Update cannot deliver them. To inspect the generated output:+```bash+npx expo prebuild -p android --clean --no-install+cat android/app/src/main/res/xml/network_security_config.xml+rm -rf android # generated, gitignored — don't commit it+```+Note `expo prebuild` rewrites the `android`/`ios` npm scripts to `expo run:*`; revert that.+## MVP scope (this PR)Auth (login/register) → Dashboard summary → Weight (log / list / delete + trend chart).Later: Food + barcode, Workouts + active session, Programs, gym mode, and the first Swiftdiff --git a/mobile/app.json b/mobile/app.jsonindex 8100230..85a1143 100644--- a/mobile/app.json+++ b/mobile/app.json@@ -3,7 +3,7 @@"name": "Lyftr","slug": "lyftr","scheme": "lyftr",- "version": "0.1.0",+ "version": "0.3.0","orientation": "portrait","userInterfaceStyle": "automatic","newArchEnabled": true,@@ -16,7 +16,11 @@"supportsTablet": true,"bundleIdentifier": "local.lyftr.app","infoPlist": {- "NSCameraUsageDescription": "Lyftr uses the camera to scan food barcodes so you can log nutrition quickly."+ "NSCameraUsageDescription": "Lyftr uses the camera to scan food barcodes so you can log nutrition quickly.",+ "NSLocalNetworkUsageDescription": "Lyftr connects to your self-hosted Lyftr server on your local network.",+ "NSAppTransportSecurity": {+ "NSAllowsLocalNetworking": true+ }}},"android": {@@ -27,7 +31,8 @@},"permissions": ["android.permission.CAMERA"- ]+ ],+ "versionCode": 3},"web": {"bundler": "metro",@@ -54,7 +59,14 @@}],"expo-font",- "@react-native-community/datetimepicker"+ "@react-native-community/datetimepicker",+ [+ "expo-network-security-config",+ {+ "enable": true,+ "networkSecurityConfig": "./network_security_config.xml"+ }+ ]],"experiments": {"typedRoutes": truediff --git a/mobile/app/(tabs)/settings.tsx b/mobile/app/(tabs)/settings.tsxindex bd99608..2263a3a 100644--- a/mobile/app/(tabs)/settings.tsx+++ b/mobile/app/(tabs)/settings.tsx@@ -5,6 +5,7 @@ import {ArrowLeft,CalendarDays,Clock,+ AlertTriangle,Dumbbell,LogOut,Mail,@@ -16,7 +17,12 @@ import {Timer,Trash2,} from 'lucide-react-native'-import { normalizeServerUrl, testServerConnection } from '@lyftr/shared'+import {+ normalizeServerUrl,+ testServerConnection,+ isInsecureServerUrl,+ INSECURE_SERVER_WARNING,+} from '@lyftr/shared'import {AppText,Button,@@ -61,7 +67,7 @@ export default function SettingsScreen() {const setRestEnabled = useSettingsStore((s) => s.setRestEnabled)const setRestSeconds = useSettingsStore((s) => s.setRestSeconds)- const { mode, setMode, colors } = useTheme()+ const { mode, setMode, colors, brand } = useTheme()const [toast, setToast] = useState<ToastState | null>(null)@@ -74,6 +80,7 @@ export default function SettingsScreen() {// Server repoint (same warn-but-save flow as the sign-in screens / web ServerSettings).const [urlInput, setUrlInput] = useState(serverUrl)+ const insecureServer = isInsecureServerUrl(serverUrl)const [serverMsg, setServerMsg] = useState<string | null>(null)const [testing, setTesting] = useState(false)@@ -142,7 +149,7 @@ export default function SettingsScreen() {// Warn-but-save: the choice is authoritative right away; the probe is advisory.await setServerUrl(base)const result = await testServerConnection(base)- setServerMsg(result.ok ? `Connected · ${result.info.name} v${result.info.version}` : `Saved, but ${result.message}`)+ setServerMsg(result.ok ? `Connected · ${result.info.name} v${result.info.version}` : `Saved — ${result.message}`)setTesting(false)}@@ -340,8 +347,11 @@ export default function SettingsScreen() {label="Backend"right={<View className="max-w-[60%] flex-row items-center gap-2">- <View className="h-1.5 w-1.5 rounded-full bg-success-500" />- <AppText variant="body" color="muted" numberOfLines={1}>+ {/* Amber, not green, whenever traffic leaves the device unencrypted (#79). */}+ {insecureServer+ ? <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} />+ : <View className="h-1.5 w-1.5 rounded-full bg-success-500" />}+ <AppText variant="body" color={insecureServer ? 'warning' : 'muted'} numberOfLines={1}>{serverUrl || 'Default backend'}</AppText></View>@@ -358,6 +368,14 @@ export default function SettingsScreen() {placeholder="https://your-server.example.com"/>{serverMsg ? <AppText variant="caption" className="mt-2 text-brand-400">{serverMsg}</AppText> : null}+ {insecureServer ? (+ <View className="mt-2 flex-row items-start gap-1.5">+ <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} style={{ marginTop: 1 }} />+ <AppText variant="caption" color="warning" className="flex-1">+ {INSECURE_SERVER_WARNING}+ </AppText>+ </View>+ ) : null}<Button title="Test & save" variant="secondary" onPress={saveServer} loading={testing} className="mt-3" /></View></SettingsGroup>diff --git a/mobile/network_security_config.xml b/mobile/network_security_config.xmlnew file mode 100644index 0000000..90cb796--- /dev/null+++ b/mobile/network_security_config.xml@@ -0,0 +1,31 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Android network security config, applied by expo-network-security-config (see app.json).++ Lyftr is self-hosted: the backend is usually a LAN box on plain HTTP, or HTTPS with a+ certificate from the owner's own CA installed on their device. Android's release defaults+ block both — cleartext since API 28, user-installed CAs since API 24 — so the documented+ "point the app at http://<lan-ip>:8080" setup could not work at all (issue #79).++ This opts into exactly those two things and nothing else. HTTPS is still fully validated+ (chain, expiry, hostname/SAN); the only change is that roots the device owner deliberately+ installed also count. It is NOT "ignore certificate errors".++ base-config applies app-wide rather than being scoped to a <domain-config>, which is NOT+ what Android recommends. We can't follow that guidance: the server URL is entered by the+ user at runtime and this file is resolved at build time, so there is no hostname to+ enumerate. Scoping trust to the configured host needs a runtime X509TrustManager /+ NSURLSession delegate — tracked in #81. Until then the app compensates with visibility:+ isInsecureServerUrl in @lyftr/shared drives an amber "Not encrypted" marker on every+ server-URL surface, and the docs lead with HTTPS.++ Changes here only take effect in a NEW build — EAS Update cannot deliver them.+-->+<network-security-config>+ <base-config cleartextTrafficPermitted="true">+ <trust-anchors>+ <certificates src="system" />+ <certificates src="user" />+ </trust-anchors>+ </base-config>+</network-security-config>diff --git a/mobile/package.json b/mobile/package.jsonindex b888d74..91e011c 100644--- a/mobile/package.json+++ b/mobile/package.json@@ -33,6 +33,7 @@"expo-keep-awake": "~15.0.8","expo-linear-gradient": "~15.0.8","expo-linking": "~8.0.12",+ "expo-network-security-config": "^1.1.2","expo-router": "~6.0.24","expo-secure-store": "~15.0.8","expo-splash-screen": "~31.0.13",diff --git a/mobile/src/components/authui.tsx b/mobile/src/components/authui.tsxindex 134b51d..35f0dd9 100644--- a/mobile/src/components/authui.tsx+++ b/mobile/src/components/authui.tsx@@ -11,10 +11,15 @@ import {} from 'react-native'import { LinearGradient } from 'expo-linear-gradient'import Reanimated, { useSharedValue, useAnimatedStyle, withTiming, interpolateColor } from 'react-native-reanimated'-import { AlertCircle, Mail, Lock, Eye, EyeOff, Server, ChevronDown, LogIn, Play } from 'lucide-react-native'+import { AlertCircle, AlertTriangle, Mail, Lock, Eye, EyeOff, Server, ChevronDown, LogIn, Play } from 'lucide-react-native'import { useServerStore } from '../lib/lyftr'import { useTheme } from '../theme/useTheme'-import { testServerConnection, normalizeServerUrl } from '@lyftr/shared'+import {+ testServerConnection,+ normalizeServerUrl,+ isInsecureServerUrl,+ INSECURE_SERVER_WARNING,+} from '@lyftr/shared'const FONT = {label: 'PlusJakartaSans_800ExtraBold',@@ -223,6 +228,7 @@ export function ServerRow() {const [msg, setMsg] = useState<string | null>(null)const [ok, setOk] = useState(false)const [testing, setTesting] = useState(false)+ const insecure = isInsecureServerUrl(serverUrl)const save = async () => {setTesting(true)@@ -234,15 +240,17 @@ export function ServerRow() {setTesting(false)return}+ // Warn-but-save, matching Settings: gating the save on a successful probe means a user+ // whose server is unreachable for any reason can never store a URL from this screen —+ // exactly the dead end hit when the device itself blocks the connection (issue #79).+ await setServerUrl(base)const result = await testServerConnection(base)- if (result.ok) {- await setServerUrl(url)- setOk(true)- setMsg(`Connected to ${result.info.name} v${result.info.version}`)- } else {- setOk(false)- setMsg(result.message)- }+ setOk(result.ok)+ setMsg(+ result.ok+ ? `Connected to ${result.info.name} v${result.info.version}`+ : `Saved — ${result.message}`,+ )setTesting(false)}@@ -264,7 +272,9 @@ export function ServerRow() {><Server size={16} color={brand.violet} strokeWidth={2} /><Text style={{ flex: 1, fontFamily: FONT.body, fontSize: 13, color: colors.txPrimary }}>Server settings</Text>- <Text style={{ fontFamily: FONT.body, fontSize: 12, color: colors.txSecondary }}>+ {/* Stays visible while the row is collapsed — the risk outlives the moment of entry. */}+ {insecure ? <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} /> : null}+ <Text style={{ fontFamily: FONT.body, fontSize: 12, color: insecure ? brand.warning : colors.txSecondary }}>{serverUrl ? serverUrl.replace(/^https?:\/\//, '') : 'default'}</Text><ChevronDown size={14} color={colors.txMuted} strokeWidth={2.4} />@@ -274,7 +284,7 @@ export function ServerRow() {<TextInputvalue={url}onChangeText={(t) => { setMsg(null); setUrl(t) }}- placeholder="http://your-server:3000"+ placeholder="https://your-server.example.com"placeholderTextColor={colors.txMuted}autoCapitalize="none"autoCorrect={false}@@ -294,6 +304,14 @@ export function ServerRow() {{msg ? (<Text style={{ fontFamily: FONT.body, fontSize: 12, color: ok ? brand.success : brand.error }}>{msg}</Text>) : null}+ {insecure ? (+ <View style={{ flexDirection: 'row', gap: 6, alignItems: 'flex-start' }}>+ <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} style={{ marginTop: 1 }} />+ <Text style={{ flex: 1, fontFamily: FONT.body, fontSize: 12, color: brand.warning }}>+ {INSECURE_SERVER_WARNING}+ </Text>+ </View>+ ) : null}<PressableonPress={save}style={{diff --git a/mobile/src/components/ui/Typography.tsx b/mobile/src/components/ui/Typography.tsxindex c4128ef..b6f409a 100644--- a/mobile/src/components/ui/Typography.tsx+++ b/mobile/src/components/ui/Typography.tsx@@ -26,6 +26,7 @@ export type TextColor =| 'inverse'| 'brand'| 'success'+ | 'warning'| 'error'| 'white'@@ -48,6 +49,7 @@ const COLOR: Record<TextColor, string> = {inverse: 'text-tx-inverse',brand: 'text-brand-500',success: 'text-success-500',+ warning: 'text-warning-400',error: 'text-error-400',white: 'text-white',}diff --git a/package-lock.json b/package-lock.jsonindex d62454c..dee6139 100644--- a/package-lock.json+++ b/package-lock.json@@ -34,6 +34,7 @@"expo-keep-awake": "~15.0.8","expo-linear-gradient": "~15.0.8","expo-linking": "~8.0.12",+ "expo-network-security-config": "^1.1.2","expo-router": "~6.0.24","expo-secure-store": "~15.0.8","expo-splash-screen": "~31.0.13",@@ -8578,6 +8579,14 @@"react-native": "*"}},+ "node_modules/expo-network-security-config": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/expo-network-security-config/-/expo-network-security-config-1.1.2.tgz",+ "integrity": "sha512-6QA/ykQIZyKPirZG8VyvVbfGcpyEDAtTbVj374kgWHUJFItQW7gElyRWMFf8Ui7G33ODC4dsNBN5HUPqlsGOqw==",+ "peerDependencies": {+ "expo": ">=50.0.0"+ }+ },"node_modules/expo-router": {"version": "6.0.24","resolved": "https://registry.npmjs.org/expo-router/-/expo-router-6.0.24.tgz",diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex 65d0a0a..42a88db 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -2,6 +2,7 @@ import axios, { AxiosInstance } from 'axios'import * as types from './types'import { StorageAdapter, STORAGE_KEYS } from './storage'import { normalizeServerUrl } from './utils/serverUrl'+import { networkFailureMessage } from './utils/networkError'// Every API call lives under this versioned path. `origin` is an absolute server// origin for a cross-origin backend, or '' for the same-origin reverse proxy (web).@@ -22,9 +23,11 @@ export interface ClientOptions {baseUrlOverride?: string}-// Turn an axios error into an actionable message. Network/CORS/connection failures-// (no response) and proxy misconfig (404/405) are distinguished from real auth and-// server errors, so connectivity problems don't masquerade as "Registration failed."+// Turn an axios error into an actionable message. Proxy misconfig (404/405) is+// distinguished from real auth and server errors, so connectivity problems don't+// masquerade as "Registration failed." Response-less failures go to the classifier,+// which separates a blocked-cleartext or untrusted-certificate failure from a genuinely+// unreachable server — they are indistinguishable from the axios error alone.export const apiErrorMessage = (err: any, fallback: string): string => {if (err?.response) {const serverError = err.response.data?.error@@ -36,7 +39,7 @@ export const apiErrorMessage = (err: any, fallback: string): string => {if (status >= 500) return 'Server error. Please try again shortly.'return fallback}- return "Can't reach the server. Check the URL, that the backend is running, and that it allows this app's origin (CORS)."+ return networkFailureMessage(err)}// Probe a server's public /info endpoint to confirm it's reachable and is a Lyftr@@ -70,8 +73,18 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})return apiUrl(base)}+ // Without an explicit timeout axios waits forever (default 0), so a silently dropped or+ // policy-blocked request hangs the UI instead of surfacing an error. A timeout is the+ // floor, not the whole answer — see BULK_TIMEOUT below for where one global value breaks.+ //+ // 20s rather than the 5s often quoted for web: the server here is someone's home box,+ // possibly a Pi waking a cold SQLite cache over wifi, and a false timeout is worse than a+ // slow response — it sends a self-hoster debugging a server that is actually fine, which+ // is the failure mode this whole change exists to stop. The /info probe in+ // testServerConnection stays at 8s because there the whole point is to fail fast.const api: AxiosInstance = axios.create({headers: { 'Content-Type': 'application/json' },+ timeout: 20000,})api.interceptors.request.use(async (config) => {@@ -133,6 +146,13 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})delete: (id: number) => api.delete(`/workouts/${id}`),}+ // axios maps `timeout` to xhr.timeout, which bounds the WHOLE request, not just the+ // connect — so a large body on a slow link trips the global 20s even though nothing is+ // wrong. The seeded exercise list measures ~820 KB, which needs roughly 33s at 200 kbps;+ // every other endpoint returns a few KB. It's fetched once and cached below, so the+ // longer bound costs nothing and removes the one place the global value is too tight.+ const BULK_TIMEOUT = 60000+let exerciseCache: types.Exercise[] | null = nulllet exerciseCachePromise: Promise<types.Exercise[]> | null = nullconst exerciseAPI = {@@ -142,7 +162,7 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})}if (exerciseCache) return Promise.resolve(exerciseCache)if (exerciseCachePromise) return exerciseCachePromise- exerciseCachePromise = api.get<{ data: types.Exercise[] }>('/exercises', { params: { limit: 1000 } })+ exerciseCachePromise = api.get<{ data: types.Exercise[] }>('/exercises', { params: { limit: 1000 }, timeout: BULK_TIMEOUT }).then((res) => {exerciseCache = unwrap(res)exerciseCachePromise = nulldiff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 06a5765..a1a7097 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -6,6 +6,7 @@ export * from './types'export * from './storage'export * from './client'export * from './utils/serverUrl'+export * from './utils/networkError'export * from './utils/weight'export * from './utils/dateUtils'export * from './utils/programUtils'diff --git a/packages/shared/src/utils/networkError.test.ts b/packages/shared/src/utils/networkError.test.tsnew file mode 100644index 0000000..b95cc8c--- /dev/null+++ b/packages/shared/src/utils/networkError.test.ts@@ -0,0 +1,130 @@+import { classifyNetworkError, nativeErrorDetail, networkFailureMessage } from './networkError'++// Builds the shape axios actually produces on React Native: message is always the literal+// 'Network Error' (RN dispatches a bare Event with no .message), and the real reason is+// only on the XHR's `_response`. See networkError.ts for the source references.+const rnError = (nativeMessage: string) => ({+ message: 'Network Error',+ code: 'ERR_NETWORK',+ request: { _response: nativeMessage, responseType: '' },+})++describe('classifyNetworkError', () => {+ // Exact strings observed from OkHttp / NSURLError. Host names are interpolated by the+ // platform, so the matchers must tolerate any host.+ const cases: Array<[string, string, string]> = [+ [+ 'android cleartext',+ 'CLEARTEXT communication to 10.0.2.2 not permitted by network security policy',+ 'cleartext-blocked',+ ],+ [+ 'ios ATS',+ 'The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.',+ 'cleartext-blocked',+ ],+ [+ 'android untrusted CA',+ 'java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.',+ 'certificate-untrusted',+ ],+ [+ 'ios invalid certificate',+ 'The certificate for this server is invalid. You might be connecting to a server that is pretending to be “10.0.2.2” which could put your confidential information at risk.',+ 'certificate-untrusted',+ ],+ ['ios generic TLS', 'An SSL error has occurred and a secure connection to the server cannot be made.', 'certificate-untrusted'],+ [+ 'android hostname mismatch',+ 'Hostname 10.0.2.2 not verified:\n certificate: sha256/abc=\n DN: CN=lyftr.lan\n subjectAltNames: [lyftr.lan]',+ 'hostname-mismatch',+ ],+ ['android connection refused', 'Failed to connect to /10.0.2.2:3000', 'unreachable'],+ ['ios connection refused', 'Could not connect to the server.', 'unreachable'],+ ]++ it.each(cases)('classifies %s', (_name, native, expected) => {+ expect(classifyNetworkError(rnError(native))).toBe(expected)+ })++ // A hostname mismatch is also an SSL failure, so ordering must not let the generic+ // certificate patterns swallow it.+ it('prefers hostname-mismatch over the generic certificate verdicts', () => {+ const native = 'Hostname 10.0.2.2 not verified: SSLHandshakeException'+ expect(classifyNetworkError(rnError(native))).toBe('hostname-mismatch')+ })++ it('reports a timeout from the axios code', () => {+ expect(classifyNetworkError({ code: 'ECONNABORTED', message: 'timeout of 8000ms exceeded' })).toBe('timeout')+ })++ it('reports a timeout flagged on the XHR', () => {+ expect(classifyNetworkError({ code: 'ERR_NETWORK', request: { _timedOut: true } })).toBe('timeout')+ })++ it('treats an HTTP response as not-a-transport-failure', () => {+ expect(classifyNetworkError({ response: { status: 500, data: {} } })).toBe('unknown')+ })++ it('falls back to unknown with no request (web axios)', () => {+ expect(classifyNetworkError({ message: 'Network Error', code: 'ERR_NETWORK' })).toBe('unknown')+ })++ it('falls back to unknown on an unrecognised native string', () => {+ expect(classifyNetworkError(rnError('something nobody has seen before'))).toBe('unknown')+ })+})++describe('nativeErrorDetail', () => {+ it('reads _response', () => {+ expect(nativeErrorDetail(rnError('boom'))).toBe('boom')+ })++ // The `response` getter returns '' once _hasError is set, so reading it instead of+ // `_response` would silently lose every native reason.+ it('ignores the wiped `response` getter and prefers _response', () => {+ const err = { request: { _response: 'real reason', response: '', responseType: '' } }+ expect(nativeErrorDetail(err)).toBe('real reason')+ })++ it('returns empty when responseText throws for a non-text responseType', () => {+ const err = {+ request: {+ get responseText(): string {+ throw new Error("responseText is only available if responseType is '' or 'text'")+ },+ },+ }+ expect(nativeErrorDetail(err)).toBe('')+ })++ it('returns empty with no request', () => {+ expect(nativeErrorDetail({ message: 'Network Error' })).toBe('')+ })+})++describe('networkFailureMessage', () => {+ it('never blames CORS on a native transport failure', () => {+ const msg = networkFailureMessage(+ rnError('CLEARTEXT communication to 10.0.2.2 not permitted by network security policy'),+ )+ expect(msg).not.toMatch(/CORS/)+ expect(msg).toMatch(/http:\/\//)+ })++ it('tells a private-CA user how to install their certificate', () => {+ const msg = networkFailureMessage(rnError('Trust anchor for certification path not found.'))+ expect(msg).toMatch(/certificate/i)+ expect(msg).toMatch(/Encryption & credentials/)+ })++ it('appends the raw native reason when it matches nothing, rather than guessing', () => {+ const msg = networkFailureMessage(rnError('brand new platform error'))+ expect(msg).toContain('brand new platform error')+ })++ // testEnvironment is 'node', so `document` is undefined — the native wording applies.+ it('omits the CORS hint when there is no document (native)', () => {+ expect(networkFailureMessage({ message: 'Network Error', request: {} })).not.toMatch(/CORS/)+ })+})diff --git a/packages/shared/src/utils/networkError.ts b/packages/shared/src/utils/networkError.tsnew file mode 100644index 0000000..237848b--- /dev/null+++ b/packages/shared/src/utils/networkError.ts@@ -0,0 +1,95 @@+// Classifies transport-level failures (no HTTP response) into something actionable.+//+// Why this exists: axios reports every response-less failure identically. RN's XHR+// dispatches a bare `new Event('error')` with no `.message`, and axios falls back to the+// literal string 'Network Error' with code ERR_NETWORK (axios/lib/adapters/xhr.js). So a+// blocked-cleartext request, an untrusted certificate, a refused connection and a DNS+// failure are indistinguishable from `err.message` alone — which is how a self-hosted+// user hit two different native blocks and got told to check CORS (issue #79).++export type NetworkFailure =+ | 'cleartext-blocked'+ | 'certificate-untrusted'+ | 'hostname-mismatch'+ | 'timeout'+ | 'unreachable'+ | 'unknown'++// React Native stashes the real native error on the XHR: RCTNetworking passes Android's+// Throwable.getMessage() / iOS's NSError.localizedDescription into __didCompleteResponse,+// which assigns it to `_response` and sets `_hasError`. Read `_response`/`responseText`+// and NEVER `response` — the `response` getter returns '' once `_hasError` is set+// (react-native/Libraries/Network/XMLHttpRequest.js). On web this is always empty.+export const nativeErrorDetail = (err: any): string => {+ const xhr = err?.request+ if (!xhr) return ''+ try {+ return String(xhr._response ?? xhr.responseText ?? '').trim()+ } catch {+ // responseText throws unless responseType is '' or 'text'.+ return ''+ }+}++// Ordered most-specific first: a hostname mismatch and a missing trust anchor are both+// SSL failures, so the narrow patterns have to win before the generic SSL ones.+const PATTERNS: ReadonlyArray<[RegExp, NetworkFailure]> = [+ [/CLEARTEXT communication to .* not permitted/i, 'cleartext-blocked'],+ [/App Transport Security policy requires the use of a secure connection/i, 'cleartext-blocked'],+ [/Hostname .* not verified/i, 'hostname-mismatch'],+ [/Trust anchor for certification path not found/i, 'certificate-untrusted'],+ [/CertPathValidatorException|SSLHandshakeException/i, 'certificate-untrusted'],+ [/certificate for this server is invalid/i, 'certificate-untrusted'],+ [/An SSL error has occurred/i, 'certificate-untrusted'],+ [/Failed to connect to|Could not connect to the server|ECONNREFUSED/i, 'unreachable'],+]++export const classifyNetworkError = (err: any): NetworkFailure => {+ // A response means the request completed; this is an HTTP-level problem, not transport.+ if (err?.response) return 'unknown'+ if (err?.code === 'ECONNABORTED' || err?.code === 'ETIMEDOUT') return 'timeout'+ if (err?.request?._timedOut) return 'timeout'++ const detail = nativeErrorDetail(err)+ if (!detail) return 'unknown'++ for (const [pattern, verdict] of PATTERNS) {+ if (pattern.test(detail)) return verdict+ }+ return 'unknown'+}++// CORS is a browser concept — a native app sends no Origin header, so the backend never+// evaluates it. Mentioning it on mobile sends self-hosters chasing a non-existent problem.+const isWeb = (): boolean => typeof document !== 'undefined'++export const networkFailureMessage = (err: any): string => {+ switch (classifyNetworkError(err)) {+ // Deliberately does NOT say "update the app". This build already permits cleartext, so+ // if the OS still blocked it the cause is something an update can't fix — most likely+ // iOS, where NSAllowsLocalNetworking covers LAN IPs, `.local` and unqualified names but+ // NOT a custom TLD like `.lan`. Promising an update would send that user in circles.+ case 'cleartext-blocked':+ return 'This device blocked the connection because the URL uses plain http://. Switch the server to https:// — a reverse proxy can issue a certificate for a LAN-only hostname with no ports open.'+ // Leads with the real-certificate path on purpose. Installing a CA is a device-wide+ // action — it affects every app that trusts the user store, not just Lyftr — so it is+ // offered as the fallback it is, not as the headline fix.+ case 'certificate-untrusted':+ return "The server's certificate isn't trusted by this device. Best fix: give the server a real certificate — a reverse proxy can issue one for a LAN-only hostname with no ports open. Or install your own CA under Settings → Security → Encryption & credentials, which trusts it for every app on the device, not just Lyftr."+ case 'hostname-mismatch':+ return "The server's certificate doesn't cover this address. Reissue it with this hostname or IP listed in the certificate's Subject Alternative Name (SAN)."+ case 'timeout':+ return "The server didn't respond in time. Check that it's running and reachable from this device."+ case 'unreachable':+ return "Couldn't connect to the server. Check the URL and that the backend is running."+ default: {+ const base = isWeb()+ ? "Can't reach the server. Check the URL, that the backend is running, and that it allows this app's origin (CORS)."+ : "Can't reach the server. Check the URL and that the backend is running and reachable from this device."+ // Surface the raw native reason rather than guessing: an unmatched string is exactly+ // the case where our copy would otherwise be confidently wrong.+ const detail = nativeErrorDetail(err)+ return detail ? `${base} (${detail})` : base+ }+ }+}diff --git a/packages/shared/src/utils/serverUrl.test.ts b/packages/shared/src/utils/serverUrl.test.tsindex 2bdbd1b..cde5e40 100644--- a/packages/shared/src/utils/serverUrl.test.ts+++ b/packages/shared/src/utils/serverUrl.test.ts@@ -1,4 +1,4 @@-import { normalizeServerUrl } from './serverUrl'+import { normalizeServerUrl, isInsecureServerUrl } from './serverUrl'describe('normalizeServerUrl', () => {it('empty input -> empty (default backend)', () => {@@ -17,3 +17,34 @@ describe('normalizeServerUrl', () => {expect(normalizeServerUrl('has space')).toBe('')})})++describe('isInsecureServerUrl', () => {+ it('flags plain http:// to a network address', () => {+ expect(isInsecureServerUrl('http://192.168.1.10:8080')).toBe(true)+ expect(isInsecureServerUrl('http://lyftr.lan')).toBe(true)+ expect(isInsecureServerUrl('http://10.0.2.2:3000')).toBe(true)+ })++ it('does not flag https://', () => {+ expect(isInsecureServerUrl('https://lyftr.example.com')).toBe(false)+ expect(isInsecureServerUrl('https://192.168.1.10:8443')).toBe(false)+ })++ // Loopback traffic never reaches a network, so there is nobody to intercept it.+ it('does not flag loopback over http', () => {+ expect(isInsecureServerUrl('http://localhost:3000')).toBe(false)+ expect(isInsecureServerUrl('http://127.0.0.1:3000')).toBe(false)+ expect(isInsecureServerUrl('http://[::1]:3000')).toBe(false)+ })++ // A hostname that merely starts with "localhost" is a different host entirely.+ it('flags lookalike hostnames', () => {+ expect(isInsecureServerUrl('http://localhost.evil.com')).toBe(true)+ expect(isInsecureServerUrl('http://127.0.0.1.evil.com')).toBe(true)+ })++ it('empty (default backend) and garbage are not flagged', () => {+ expect(isInsecureServerUrl('')).toBe(false)+ expect(isInsecureServerUrl('not a url')).toBe(false)+ })+})diff --git a/packages/shared/src/utils/serverUrl.ts b/packages/shared/src/utils/serverUrl.tsindex 7a1bd6b..7324b5a 100644--- a/packages/shared/src/utils/serverUrl.ts+++ b/packages/shared/src/utils/serverUrl.ts@@ -19,3 +19,33 @@ export const normalizeServerUrl = (raw: string): string => {return ''}}++// Loopback never leaves the device (or, on web, the machine), so http:// to it carries+// none of the on-network exposure below. Everything else on http:// does.+const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)$/i++// True when this server URL sends traffic unencrypted over a network: every request+// carries the `Authorization: Bearer` token in the clear and the refresh token crosses+// the wire on login, so anyone sharing the network can capture a credential that stays+// valid until it expires — the backend has no revocation list.+//+// Android blocks cleartext by default; Lyftr opts back in so a LAN install works at all+// (#79), which is why the app has to surface this itself — the platform no longer does.+//+// Pass the *saved* server URL, not an input buffer: a half-typed "http" would otherwise+// flash a warning while the user is still typing.+// One wording for every surface (login server row, Settings, web) so the risk reads the+// same wherever it appears. Names the concrete consequence rather than "not secure" —+// a vague warning is the kind users learn to scroll past.+export const INSECURE_SERVER_WARNING =+ 'Not encrypted — anyone on this network can read your login and stay signed in as you. Use https:// if you can.'++export const isInsecureServerUrl = (serverUrl: string): boolean => {+ if (!serverUrl) return false // '' = same-origin/default backend, not a user choice+ try {+ const u = new URL(serverUrl)+ return u.protocol === 'http:' && !LOOPBACK.test(u.hostname)+ } catch {+ return false+ }+}diff --git a/site/src/content/docs/https.md b/site/src/content/docs/https.mdindex c5e2030..f18d816 100644--- a/site/src/content/docs/https.md+++ b/site/src/content/docs/https.md@@ -3,8 +3,12 @@ title: HTTPS & Reverse Proxydescription: Put Lyftr behind Caddy or nginx with automatic HTTPS (Let's Encrypt) for a public, secure instance.----Lyftr's container serves plain HTTP on a host port. To expose it publicly — and to use the **mobile-app**, which needs a real hostname — put it behind a reverse proxy that terminates HTTPS.+Lyftr's container serves plain HTTP on a host port. Put it behind a reverse proxy that terminates+HTTPS — **this is the recommended setup for every install, not just public ones.** Your login token+travels on every request, and on plain HTTP anyone else on the network can read it.++If Lyftr never leaves your LAN you can still have a genuine, publicly-trusted certificate with no+ports open to the internet — see [LAN-only](#lan-only-get-a-real-certificate-anyway-recommended) below.:::caution[Port conflict]By default the compose file publishes Lyftr on host port **80** (`PORT=80`). A reverse proxy also@@ -46,6 +50,67 @@ Then issue a certificate with [Certbot](https://certbot.eff.org):sudo certbot --nginx -d lyftr.example.com```+## LAN-only? Get a real certificate anyway (recommended)++If Lyftr never leaves your network, you can still have a genuine, publicly-trusted+certificate — no ports open to the internet. Use a domain you own, point a record at a+private address, and let Caddy prove ownership over DNS instead of HTTP:++```caddyfile+lyftr.home.example.com {+ tls {+ dns cloudflare {env.CF_API_TOKEN}+ }+ reverse_proxy localhost:8080+}+```++This is the best option by a distance: every device trusts it out of the box, nothing is+exposed, and renewal is automatic. It needs a domain you control and a DNS provider with an+API — [Caddy's DNS provider modules](https://github.com/caddy-dns) cover most of them.++## Private CA / self-signed certificates++If you have no domain and must use your own CA, the mobile app can work with it, but there+are rules that trip people up:++- **Install the CA on the device**, not just the server. On Android: *Settings → Security →+ Encryption & credentials → Install a certificate → CA certificate*. On iOS: install the+ profile, then enable it under *Settings → General → About → Certificate Trust Settings*.+- **The certificate must carry a Subject Alternative Name.** A Common Name alone has not+ been accepted for years. If you connect by IP, the IP must be in the SAN as an+ `IP Address` entry — a `DNS` entry will not match.+- Use RSA ≥ 2048 or EC ≥ 256, SHA-256 or better, and TLS 1.2+.+- **Use a current Android build.** The app trusts the device's user-installed CA store;+ older builds ignored it entirely and reported that they couldn't reach the server even+ though the server was fine. If a private CA isn't working, update the app first.++Your own CA is enough for the web app's barcode scanner too — browsers grant camera access+based on the page being `https://`, not on who issued the certificate. You don't need a+publicly-trusted certificate for that, though you do need the CA installed so the browser+stops warning.++:::caution[Plain HTTP is an escape hatch, not a setup]+Android blocks unencrypted HTTP by default. The Lyftr Android app opts back in, so+`http://<lan-ip>:8080` works for a standard `docker compose` install — otherwise the+documented quick-start would be unusable on a phone. But understand what you're accepting:++Nothing is encrypted. Every request carries your login token in the clear, so **anyone else+on that network can read it and stay signed in as you** — on a home LAN that includes guests+and any compromised device. Captured tokens stay valid until they expire and cannot be+revoked; the only way to invalidate them is to change `JWT_SECRET`, which signs out every+user on the instance.++**Barcode scanning stops working in the web app.** Browsers only allow camera access on a+secure page, so on plain HTTP the scanner can't open. This is a browser rule, not a Lyftr+setting — no configuration turns it back on. The Android app is unaffected: it uses the+phone's camera directly.++Use it to get running, then move to HTTPS. If you own a domain, the DNS-01 route above gets+you a real certificate on a LAN-only hostname with no ports open — that is the fix, not a+workaround. The app shows an amber **Not encrypted** marker while plain HTTP is in effect.+:::+## Point Lyftr at your public originAfter the proxy is up, set `CORS_ORIGIN` to your HTTPS URL so browser and mobile clients arediff --git a/site/src/content/docs/mobile.md b/site/src/content/docs/mobile.mdindex f1d523a..76555f1 100644--- a/site/src/content/docs/mobile.md+++ b/site/src/content/docs/mobile.md@@ -20,12 +20,34 @@ auto-update are on the roadmap.## Pointing the app at your server-The app connects to your self-hosted instance, so it needs a URL it can actually reach:--- **`localhost` won't work** from a phone — it refers to the phone itself.-- On the same network, use your server's **LAN IP** (e.g. `http://192.168.1.10:8080`).-- Best: a **real hostname over HTTPS** so it works anywhere — see [HTTPS & Reverse Proxy](../https/).-- Make sure your server URL is in `CORS_ORIGIN` (see [Configuration](../configuration/)).+The app connects to your self-hosted instance, so it needs a URL it can actually reach.+**Use `https://`.** Everything below assumes that; plain HTTP is covered after, as the+exception it should be.++- **Point it at a real hostname over HTTPS** — see [HTTPS & Reverse Proxy](../https/).+ This works from anywhere, not just your home network. A LAN-only hostname can still get+ a genuine, publicly-trusted certificate via DNS-01, with no ports open to the internet.+- **`localhost` won't work** from a phone — it refers to the phone itself. Use a hostname+ or your server's LAN IP.+- Running your own CA instead? Install it on the phone — the app trusts the device's+ user-installed CA store. See [HTTPS & Reverse Proxy](../https/).+- `CORS_ORIGIN` only matters for the **web** app (see [Configuration](../configuration/)).+ Native apps send no `Origin` header and are never subject to CORS.++### If you must use plain HTTP++`http://192.168.1.10:8080` works — Android blocks unencrypted traffic by default and the+app opts back in, so a bare `docker compose` install is usable. If it fails outright,+update to the latest build.++:::caution[What plain HTTP costs you]+Nothing is encrypted. Every request carries your login token in the clear, so **anyone+else on that network can read it and stay signed in as you**, and a captured token can't+be revoked. The app shows an amber **Not encrypted** marker while this is in effect.++Full detail and the fix: [HTTPS & Reverse Proxy](../https/). Treat plain HTTP as a+temporary state, not a setup.+:::## iOSdiff --git a/site/src/content/docs/troubleshooting.md b/site/src/content/docs/troubleshooting.mdindex 564cfc6..a9375f0 100644--- a/site/src/content/docs/troubleshooting.md+++ b/site/src/content/docs/troubleshooting.md@@ -37,11 +37,36 @@ If host port 80 is taken (another web server, or a reverse proxy), move Lyftr to## The mobile app or another device can't connect-- The app needs a reachable server URL — `localhost` won't work from a phone. Use your server's LAN- IP or, better, a real hostname over HTTPS ([reverse proxy](../https/)).+- The app needs a reachable server URL. Use a real hostname over HTTPS+ ([reverse proxy](../https/)) — `localhost` won't work from a phone, and plain HTTP exposes+ your login token to everyone on the network.- Add that origin to `CORS_ORIGIN` (comma-separated), or use `*` to allow any (the API isBearer-token based, so there are no cookies to protect).+:::note[On mobile this is usually not CORS]+A native app sends no `Origin` header, so the backend never applies CORS to it. If the phone+app says it can't reach the server but the same URL works in the phone's **browser**, the+device is blocking the connection, not the server. The two common causes:++- **Plain `http://`** — blocked by Android's defaults. The app opts back in, at the cost of+ sending your login token unencrypted; prefer HTTPS. See [HTTPS & Reverse Proxy](../https/).+- **A private or self-signed CA** — apps ignore the user-installed CA store unless they opt+ in. The app does, but the CA still has to be installed on the device. See+ [HTTPS & Reverse Proxy](../https/).++Both need a current build, which also names the specific cause in the error message instead+of guessing. If you get a generic message mentioning CORS, update the app first.+:::++## Barcode scanner won't open in the web app++It says **Camera needs HTTPS** because your instance is served over plain `http://`. No+Lyftr setting changes this — put it behind [HTTPS](../https/) and the scanner works. Your+own private CA is enough.++Unaffected: `http://localhost` **on the server itself**, and the Android app, which uses+the phone's camera rather than the browser's.+## No exercises show upThey seed in the background on first startup and appear within a few seconds. If the list is empty,diff --git a/web/src/components/BarcodeScanner.tsx b/web/src/components/BarcodeScanner.tsxindex 25654bd..09f0899 100644--- a/web/src/components/BarcodeScanner.tsx+++ b/web/src/components/BarcodeScanner.tsx@@ -12,6 +12,13 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {const resolvedRef = useRef(false)const [cameraError, setCameraError] = useState<string | null>(null)+ // getUserMedia is a secure-context API, so on a plain-http origin navigator.mediaDevices+ // is undefined and ZXing fails with a raw internal error. Detect it up front and explain+ // the actual cause — the raw message ("Cannot read properties of undefined") tells a+ // self-hoster nothing about what to change. Checked, not caught, because the failure+ // shape varies by browser.+ const insecureContext = typeof window !== 'undefined' && !window.isSecureContext+const { ref } = useZxing({constraints: {audio: false,@@ -53,7 +60,33 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {</div><div className="flex-1 flex items-center justify-center relative">- {!cameraError && (+ {/* Failure states live inside the flex-1 area so they centre. Rendering them below+ it left an empty stretched container that pushed the text onto the tab bar. */}+ {insecureContext ? (+ <div className="flex flex-col items-center gap-3 px-6 text-center">+ <AlertCircle className="w-8 h-8 text-error-400" />+ <p className="text-white text-sm font-medium">Camera needs HTTPS</p>+ <p className="text-white/60 text-xs leading-relaxed">+ Browsers only allow camera access on secure pages. This site is served over+ plain <span className="font-mono">http://</span> — put it behind a reverse proxy+ with HTTPS to scan barcodes.+ </p>+ <button onClick={onClose} className="btn-primary btn-sm mt-2">+ Search by name instead+ </button>+ </div>+ ) : cameraError ? (+ <div className="flex flex-col items-center gap-3 px-6 text-center">+ <AlertCircle className="w-8 h-8 text-error-400" />+ <p className="text-white text-sm font-medium">Camera unavailable</p>+ <p className="text-white/50 text-xs font-mono break-all">{cameraError}</p>+ <button onClick={onClose} className="btn-primary btn-sm mt-2">+ Search by name instead+ </button>+ </div>+ ) : null}++ {!cameraError && !insecureContext && (<video// react-zxing ref type doesn't match HTMLVideoElement exactly; cast is safe as useZxing always returns a video refref={ref as React.RefObject<HTMLVideoElement>}@@ -63,7 +96,7 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {/>)}- {!cameraError && (+ {!cameraError && !insecureContext && (<div className="absolute pointer-events-none" style={{ width: 260, height: 160 }}><div className="absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-brand-400 rounded-tl" /><div className="absolute top-0 right-0 w-8 h-8 border-t-2 border-r-2 border-brand-400 rounded-tr" />@@ -77,16 +110,7 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {)}</div>- {cameraError ? (- <div className="flex flex-col items-center gap-3 px-6 pb-10 text-center">- <AlertCircle className="w-8 h-8 text-error-400" />- <p className="text-white text-sm font-medium">Camera unavailable</p>- <p className="text-white/50 text-xs font-mono break-all">{cameraError}</p>- <button onClick={onClose} className="btn-primary btn-sm mt-2">- Search by name instead- </button>- </div>- ) : (+ {!insecureContext && !cameraError && (<p className="text-center text-white/60 text-xs pb-8 px-4">Point camera at barcode — it will scan automatically</p>diff --git a/web/src/components/ServerSettings.tsx b/web/src/components/ServerSettings.tsxindex 6eeafe8..c2899c0 100644--- a/web/src/components/ServerSettings.tsx+++ b/web/src/components/ServerSettings.tsx@@ -1,6 +1,13 @@import { useState } from 'react'import { ChevronDown, Server, CheckCircle2, AlertTriangle, Loader } from 'lucide-react'-import { useServerStore, normalizeServerUrl } from '../stores/server'+import {+ useServerStore,+ normalizeServerUrl,+ isInsecureServerUrl,+ INSECURE_SERVER_WARNING,+ isMixedContentBlocked,+ MIXED_CONTENT_WARNING,+} from '../stores/server'import { testServerConnection } from '../services/api'type Status =@@ -19,6 +26,10 @@ export default function ServerSettings() {const [open, setOpen] = useState(false)const [input, setInput] = useState(serverUrl)const [status, setStatus] = useState<Status>({ kind: 'idle' })+ // Blocked wins over insecure: both are true for http-from-https, but one is a hard+ // failure the user must fix and the other is a risk they may knowingly accept.+ const blocked = isMixedContentBlocked(serverUrl)+ const insecure = !blocked && isInsecureServerUrl(serverUrl)const handleSave = async () => {const raw = input.trim()@@ -39,7 +50,7 @@ export default function ServerSettings() {setStatus(result.ok? { kind: 'ok', message: `Connected · ${result.info.name} ${result.info.version}` }- : { kind: 'warn', message: `Saved, but ${result.message}` },+ : { kind: 'warn', message: `Saved — ${result.message}` },)}@@ -52,6 +63,19 @@ export default function ServerSettings() {><Server className="w-3.5 h-3.5" /><span>Server settings</span>+ {/* Stays visible while the panel is collapsed — the problem outlives the moment of entry. */}+ {blocked && (+ <span className="flex items-center gap-1 text-error-400" title={MIXED_CONTENT_WARNING}>+ <AlertTriangle className="w-3 h-3" />+ Blocked+ </span>+ )}+ {insecure && (+ <span className="flex items-center gap-1 text-warning-400" title={INSECURE_SERVER_WARNING}>+ <AlertTriangle className="w-3 h-3" />+ Not encrypted+ </span>+ )}<ChevronDown className={`w-3 h-3 ml-auto transition-transform ${open ? 'rotate-180' : ''}`} /></button>@@ -70,9 +94,22 @@ export default function ServerSettings() {/><p className="text-[11px] leading-relaxed text-tx-muted">- Full URL, e.g. <span className="font-mono text-tx-secondary">http://192.168.1.10:3000</span>+ Full URL, e.g. <span className="font-mono text-tx-secondary">https://lyftr.example.com</span></p>+ {blocked && (+ <p className="flex items-start gap-1.5 text-xs text-error-400">+ <AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />+ <span>{MIXED_CONTENT_WARNING}</span>+ </p>+ )}+ {insecure && (+ <p className="flex items-start gap-1.5 text-xs text-warning-400">+ <AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />+ <span>{INSECURE_SERVER_WARNING}</span>+ </p>+ )}+{status.kind === 'error' && <p className="text-xs text-error-400">{status.message}</p>}{status.kind === 'warn' && (<p className="flex items-start gap-1.5 text-xs text-warning-400">diff --git a/web/src/stores/server.test.ts b/web/src/stores/server.test.tsindex 2e40b0b..0717008 100644--- a/web/src/stores/server.test.ts+++ b/web/src/stores/server.test.ts@@ -1,5 +1,10 @@-import { describe, it, expect, beforeEach } from 'vitest'-import { normalizeServerUrl, useServerStore } from './server'+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import {+ normalizeServerUrl,+ useServerStore,+ isInsecureServerUrl,+ isMixedContentBlocked,+} from './server'describe('normalizeServerUrl', () => {it('returns empty for blank or whitespace-only input', () => {@@ -69,3 +74,78 @@ describe('useServerStore', () => {expect(useServerStore.getState().getServerUrl()).toBe('https://example.com')})})++describe('isInsecureServerUrl', () => {+ it('flags plain http:// to a network address', () => {+ expect(isInsecureServerUrl('http://192.168.1.10:8080')).toBe(true)+ expect(isInsecureServerUrl('http://lyftr.lan')).toBe(true)+ })++ it('does not flag https://', () => {+ expect(isInsecureServerUrl('https://lyftr.example.com')).toBe(false)+ })++ // Loopback traffic never reaches a network, so there is nobody to intercept it.+ it('does not flag loopback over http', () => {+ expect(isInsecureServerUrl('http://localhost:3000')).toBe(false)+ expect(isInsecureServerUrl('http://127.0.0.1:3000')).toBe(false)+ expect(isInsecureServerUrl('http://[::1]:3000')).toBe(false)+ })++ // A host that merely starts with "localhost" is a different host entirely.+ it('flags lookalike hostnames', () => {+ expect(isInsecureServerUrl('http://localhost.evil.com')).toBe(true)+ expect(isInsecureServerUrl('http://127.0.0.1.evil.com')).toBe(true)+ })++ it('empty (same origin) and garbage are not flagged', () => {+ expect(isInsecureServerUrl('')).toBe(false)+ expect(isInsecureServerUrl('not a url')).toBe(false)+ })+})++describe('isMixedContentBlocked', () => {+ const setPageProtocol = (protocol: 'http:' | 'https:') => {+ Object.defineProperty(window, 'location', {+ value: { ...window.location, protocol },+ writable: true,+ configurable: true,+ })+ }+ const original = window.location+ afterEach(() => {+ Object.defineProperty(window, 'location', { value: original, writable: true, configurable: true })+ })++ it('blocks http:// server from an https:// page', () => {+ setPageProtocol('https:')+ expect(isMixedContentBlocked('http://192.168.1.10:8080')).toBe(true)+ expect(isMixedContentBlocked('http://lyftr.lan')).toBe(true)+ })++ // Loopback is "potentially trustworthy", so mixed-content checks let it through.+ it('allows loopback over http even from an https:// page', () => {+ setPageProtocol('https:')+ expect(isMixedContentBlocked('http://localhost:3000')).toBe(false)+ expect(isMixedContentBlocked('http://127.0.0.1:3000')).toBe(false)+ expect(isMixedContentBlocked('http://[::1]:3000')).toBe(false)+ })++ it('allows https:// server from an https:// page', () => {+ setPageProtocol('https:')+ expect(isMixedContentBlocked('https://lyftr.example.com')).toBe(false)+ })++ // Upgrading from an http page to an https server is never mixed content.+ it('never blocks from an http:// page', () => {+ setPageProtocol('http:')+ expect(isMixedContentBlocked('http://192.168.1.10:8080')).toBe(false)+ expect(isMixedContentBlocked('https://lyftr.example.com')).toBe(false)+ })++ it('empty (same origin) and garbage are never blocked', () => {+ setPageProtocol('https:')+ expect(isMixedContentBlocked('')).toBe(false)+ expect(isMixedContentBlocked('not a url')).toBe(false)+ })+})diff --git a/web/src/stores/server.ts b/web/src/stores/server.tsindex e932a75..3737de3 100644--- a/web/src/stores/server.ts+++ b/web/src/stores/server.ts@@ -21,6 +21,49 @@ export const normalizeServerUrl = (raw: string): string => {}}+// Loopback never leaves the machine, so http:// to it is not exposed on any network.+const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)$/i++// Mirrors isInsecureServerUrl in @lyftr/shared — see there for why unencrypted traffic+// costs what it does. Duplicated only because web doesn't consume the shared package+// yet; the two converge under #67.+export const isInsecureServerUrl = (serverUrl: string): boolean => {+ if (!serverUrl) return false // '' = same origin, not a user choice+ try {+ const u = new URL(serverUrl)+ return u.protocol === 'http:' && !LOOPBACK.test(u.hostname)+ } catch {+ return false+ }+}++// Kept identical to the shared copy so the risk reads the same on every surface.+export const INSECURE_SERVER_WARNING =+ 'Not encrypted — anyone on this network can read your login and stay signed in as you. Use https:// if you can.'++// True when the browser will refuse this URL outright as active mixed content: an HTTPS+// page cannot call an http:// origin, and the page cannot opt out — no header, CSP+// directive or fetch option grants an exception (upgrade-insecure-requests rewrites to+// https rather than permitting http). Only the user can override it, per-site, in their+// own browser settings.+//+// Loopback is exempt: it is a "potentially trustworthy" origin under the Secure Contexts+// spec, so mixed-content checks let it through even from an HTTPS page.+export const isMixedContentBlocked = (serverUrl: string): boolean => {+ if (!serverUrl) return false // same origin — never mixed+ if (typeof window === 'undefined') return false+ if (window.location.protocol !== 'https:') return false+ try {+ const u = new URL(serverUrl)+ return u.protocol === 'http:' && !LOOPBACK.test(u.hostname)+ } catch {+ return false+ }+}++export const MIXED_CONTENT_WARNING =+ "This browser will block it — an HTTPS page can't call an http:// server. Use https:// for the server too, or leave this blank to use this site's own backend."+interface ServerStore {serverUrl: string // '' = same origin (reverse proxy)setServerUrl: (url: string) => void