From 65bf540ea0f3b9f540db9a255e6515ffb0de5449 Mon Sep 17 00:00:00 2001 From: marcus Date: Thu, 19 Nov 2026 23:07:00 -0800 Subject: [PATCH] Replace Basic-auth login with an API token set in Settings The app no longer shows a login screen. It opens straight to the Today screen, which shows nothing until a bearer API token is saved in the new Settings screen. The token is verified against health-meta.json before it is stored in the keychain, and can be removed from the same screen. Server side: health-auth accepts Authorization: Bearer (read + write for the Fitbit sync, but not admin-only /life/* paths). Co-Authored-By: Claude Sonnet 5.5 --- README.md | 7 ++- src/app/_layout.tsx | 5 +-- src/app/index.tsx | 25 +++++------ src/app/settings.tsx | 74 ++++++++++++++++++++++++++++++++ src/components/login.tsx | 84 ------------------------------------ src/lib/api.tsx | 93 +++++++++++++--------------------------- src/lib/use-load.ts | 3 +- 7 files changed, 123 insertions(+), 168 deletions(-) create mode 100644 src/app/settings.tsx delete mode 100644 src/components/login.tsx diff --git a/README.md b/README.md index e422390..2ecd792 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Cross-platform (iOS + Android) Expo app β€” native front end for the private health dashboard at **https://health.rehbock.xyz**. The app is a pure client: all data lives on the server and is fetched live over -HTTPS with HTTP Basic auth. Nothing is stored on the device except the auth +HTTPS with a bearer API token. Nothing is stored on the device except the auth token (in the platform keychain via `expo-secure-store`). ## Screens @@ -30,7 +30,10 @@ npm install npx expo start # scan the QR with Expo Go (iOS or Android) ``` -Log in with the same Basic-auth credentials as the website. +There is no login screen. Open **Settings** (βš™οΈ on the Today screen) and paste the API token; +without one the app has no data. The server accepts it via `HEALTH_APP_TOKEN` in +`health-auth` (`~/personal/health-auth/.env` on the VPS, passed through `docker-compose.yml`). +Rotate it by changing that value and running `docker compose up -d`. ## Android release APK diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index 3289291..6c503d2 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -4,12 +4,10 @@ import React from 'react'; import { View } from 'react-native'; import { AuthProvider, useAuth } from '../lib/api'; import { C } from '../lib/theme'; -import { LoginScreen } from '../components/login'; function Gate() { - const { ready, authed } = useAuth(); + const { ready } = useAuth(); if (!ready) return ; - if (!authed) return ; return ( + ); } diff --git a/src/app/index.tsx b/src/app/index.tsx index 8a4bee4..8585d95 100644 --- a/src/app/index.tsx +++ b/src/app/index.tsx @@ -1,6 +1,6 @@ -import { Stack } from 'expo-router'; +import { Link, Stack } from 'expo-router'; import React from 'react'; -import { Alert, Pressable, Text, View } from 'react-native'; +import { Text, View } from 'react-native'; import { NavCard, PriorityCard, Screen, Sec } from '../components/ui'; import { useAuth } from '../lib/api'; import { agoTxt, fmtD, fmtDY, hm, num, cap } from '../lib/format'; @@ -13,7 +13,7 @@ import type { import { loadAll, useLoad } from '../lib/use-load'; export default function Today() { - const { logout } = useAuth(); + const { hasToken } = useAuth(); const { data, loading, refresh } = useLoad(() => loadAll({ meta: 'meta', bio: 'biomarkers', wo: 'workouts', sApi: 'sleepApi', @@ -120,16 +120,9 @@ export default function Today() { ( - - Alert.alert('Lock the dashboard?', 'You will need the password to get back in.', [ - { text: 'Cancel', style: 'cancel' }, - { text: 'Lock', style: 'destructive', onPress: logout }, - ]) - }> - πŸ”’ - + + βš™οΈ + ), }} /> @@ -139,7 +132,11 @@ export default function Today() { weekday: 'long', month: 'long', day: 'numeric', })} /> - {loading && !r ? ( + {!hasToken ? ( + + Add your API token in Settings to load your data β†’ + + ) : loading && !r ? ( Loading… diff --git a/src/app/settings.tsx b/src/app/settings.tsx new file mode 100644 index 0000000..4a0ad9f --- /dev/null +++ b/src/app/settings.tsx @@ -0,0 +1,74 @@ +import React, { useState } from 'react'; +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { Screen } from '../components/ui'; +import { BASE, useAuth } from '../lib/api'; +import { C } from '../lib/theme'; + +export default function Settings() { + const { hasToken, saveToken, clearToken } = useAuth(); + const [value, setValue] = useState(''); + const [msg, setMsg] = useState(''); + const [busy, setBusy] = useState(false); + + const save = async () => { + setBusy(true); + setMsg(''); + try { + if (await saveToken(value)) { + setValue(''); + setMsg('Saved.'); + } else setMsg('The server rejected that token.'); + } catch { + setMsg('Network error β€” are you online?'); + } finally { + setBusy(false); + } + }; + + return ( + + SERVER + {BASE} + API TOKEN {hasToken ? 'Β· saved' : 'Β· not set'} + + + Save token + + {hasToken ? ( + + Remove token from this device + + ) : null} + + {msg} + + + ); +} + +const s = StyleSheet.create({ + lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 16, marginBottom: 6 }, + val: { fontSize: 15, color: C.text }, + input: { + paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1, + borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15, + }, + go: { marginTop: 16, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center' }, + goTxt: { color: '#fff', fontWeight: '600', fontSize: 15 }, + clear: { marginTop: 20, alignItems: 'center', padding: 8 }, + msg: { marginTop: 12, fontSize: 12.5, color: C.muted }, +}); diff --git a/src/components/login.tsx b/src/components/login.tsx deleted file mode 100644 index e22e7cd..0000000 --- a/src/components/login.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import React, { useState } from 'react'; -import { - KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View, -} from 'react-native'; -import { useAuth } from '../lib/api'; -import { C } from '../lib/theme'; - -export function LoginScreen() { - const { login } = useAuth(); - const [user, setUser] = useState('admin'); - const [pass, setPass] = useState(''); - const [err, setErr] = useState(''); - const [busy, setBusy] = useState(false); - - const go = async () => { - setBusy(true); - setErr(''); - try { - const ok = await login(user.trim(), pass); - if (!ok) setErr('Wrong password.'); - else setPass(''); - } catch { - setErr('Network error β€” are you online?'); - } finally { - setBusy(false); - } - }; - - return ( - - - βš•οΈ - Health Dashboard - health.rehbock.xyz β€” private - USER - - PASSWORD - - - Unlock - - {err} - - - ); -} - -const s = StyleSheet.create({ - wrap: { - flex: 1, backgroundColor: C.bg, alignItems: 'center', justifyContent: 'center', padding: 24, - }, - card: { - width: '100%', maxWidth: 340, backgroundColor: C.surface, borderWidth: 1, - borderColor: C.border, borderRadius: 16, paddingVertical: 28, paddingHorizontal: 24, - }, - h1: { fontSize: 18, fontWeight: '600', color: C.text, marginBottom: 4 }, - sub: { fontSize: 12, color: C.muted, marginBottom: 20 }, - lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 12, marginBottom: 5 }, - input: { - paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1, - borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15, - }, - go: { - marginTop: 20, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center', - }, - err: { marginTop: 12, fontSize: 12.5, color: C.red, minHeight: 18 }, -}); diff --git a/src/lib/api.tsx b/src/lib/api.tsx index d3b2976..9b7e1c3 100644 --- a/src/lib/api.tsx +++ b/src/lib/api.tsx @@ -22,62 +22,33 @@ export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`; /* authenticated POST (fitbit sync) */ export async function postJson(url: string, body: unknown): Promise { + if (!token) throw new Error(NO_TOKEN); const r = await fetch(url, { method: 'POST', - headers: { Authorization: 'Basic ' + token, 'Content-Type': 'application/json' }, + headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); - if (r.status === 401 || r.status === 403) { - onUnauthorized?.(); - throw new Error('unauthorized'); - } + if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN); if (!r.ok) throw new Error(`${url} β†’ ${r.status}`); return r.json(); } export type EpKey = keyof typeof EP; -const AUTH_KEY = 'hd.auth'; +const AUTH_KEY = 'hd.token'; + +export const NO_TOKEN = 'No API token β€” add one in Settings.'; +export const BAD_TOKEN = 'API token rejected β€” check it in Settings.'; let token: string | null = null; -let onUnauthorized: (() => void) | null = null; - -/* base64 without Buffer/btoa dependency quirks across Hermes versions */ -const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; -export function b64(str: string): string { - const bytes: number[] = []; - for (let i = 0; i < str.length; i++) { - const code = str.codePointAt(i)!; - if (code > 0xffff) i++; - if (code < 0x80) bytes.push(code); - else if (code < 0x800) bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63)); - else if (code < 0x10000) - bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63)); - else - bytes.push( - 0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), - 0x80 | ((code >> 6) & 63), 0x80 | (code & 63), - ); - } - let out = ''; - for (let i = 0; i < bytes.length; i += 3) { - const [a, b, c] = [bytes[i], bytes[i + 1], bytes[i + 2]]; - out += B64[a >> 2] + B64[((a & 3) << 4) | (b ?? 0) >> 4]; - out += b === undefined ? '=' : B64[((b & 15) << 2) | (c ?? 0) >> 6]; - out += c === undefined ? '=' : B64[c & 63]; - } - return out; -} async function authFetch(url: string): Promise { + if (!token) throw new Error(NO_TOKEN); const r = await fetch(url, { - headers: { Authorization: 'Basic ' + token }, + headers: { Authorization: 'Bearer ' + token }, cache: 'no-store', }); - if (r.status === 401 || r.status === 403) { - onUnauthorized?.(); - throw new Error('unauthorized'); - } + if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN); if (!r.ok) throw new Error(`${url} β†’ ${r.status}`); return r.json(); } @@ -107,62 +78,58 @@ export function invalidate(...keys: EpKey[]) { interface AuthCtx { ready: boolean; - authed: boolean; - login: (user: string, pass: string) => Promise; - logout: () => void; + /** an API token is stored (it may still be rejected by the server) */ + hasToken: boolean; + /** verify against the server, then store; false = server rejected it */ + saveToken: (t: string) => Promise; + clearToken: () => void; } const Ctx = createContext({ ready: false, - authed: false, - login: async () => false, - logout: () => {}, + hasToken: false, + saveToken: async () => false, + clearToken: () => {}, }); export const useAuth = () => useContext(Ctx); export function AuthProvider({ children }: { children: React.ReactNode }) { const [ready, setReady] = useState(false); - const [authed, setAuthed] = useState(false); + const [hasToken, setHasToken] = useState(false); useEffect(() => { SecureStore.getItemAsync(AUTH_KEY) .then((t) => { if (t) { token = t; - setAuthed(true); + setHasToken(true); } }) + .catch(() => {}) .finally(() => setReady(true)); }, []); - const logout = useCallback(() => { + const clearToken = useCallback(() => { token = null; clearCache(); SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {}); - setAuthed(false); + setHasToken(false); }, []); - useEffect(() => { - onUnauthorized = logout; - return () => { - onUnauthorized = null; - }; - }, [logout]); - - const login = useCallback(async (user: string, pass: string) => { - const tok = b64(`${user}:${pass}`); + const saveToken = useCallback(async (raw: string) => { + const t = raw.trim(); const r = await fetch(EP.meta, { - headers: { Authorization: 'Basic ' + tok }, + headers: { Authorization: 'Bearer ' + t }, cache: 'no-store', }); if (!r.ok) return false; - token = tok; + token = t; clearCache(); - await SecureStore.setItemAsync(AUTH_KEY, tok); - setAuthed(true); + await SecureStore.setItemAsync(AUTH_KEY, t); + setHasToken(true); return true; }, []); - return {children}; + return {children}; } diff --git a/src/lib/use-load.ts b/src/lib/use-load.ts index cf3534a..e3033a0 100644 --- a/src/lib/use-load.ts +++ b/src/lib/use-load.ts @@ -19,8 +19,7 @@ export function useLoad(fn: () => Promise): LoadState & { refresh: () = .then((data) => live && setState({ data, loading: false })) .catch((e) => { if (!live) return; - const msg = e instanceof Error ? e.message : String(e); - if (msg !== 'unauthorized') setState({ err: msg, loading: false }); + setState({ err: e instanceof Error ? e.message : String(e), loading: false }); }); return () => { live = false;