Files
health-app/src/lib/api.tsx
marcus 65bf540ea0
Some checks failed
Build & Release APK / build (push) Has been cancelled
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 <HEALTH_APP_TOKEN>
(read + write for the Fitbit sync, but not admin-only /life/* paths).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 23:07:00 -08:00

136 lines
3.9 KiB
TypeScript

import * as SecureStore from 'expo-secure-store';
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
export const BASE = 'https://health.rehbock.xyz';
export const EP = {
meta: `${BASE}/health-meta.json`,
biomarkers: `${BASE}/api/health/v1/biomarkers`,
draws: `${BASE}/api/health/v1/draws`,
workouts: `${BASE}/api/health/v1/workouts`,
sleepApi: `${BASE}/api/health/v1/sleep`,
sleepCycle: `${BASE}/sleep-data.json`,
dexa: `${BASE}/dexa-scans.json`,
medStats: `${BASE}/api/meditation/v1/stats`,
medSessions: `${BASE}/api/meditation/v1/sessions?limit=1000`,
traits: `${BASE}/ancestry-traits.json`,
fitbitSummary: `${BASE}/api/health/v1/fitbit/summary?days=30`,
fitbitLatest: `${BASE}/api/health/v1/fitbit/latest`,
} as const;
export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`;
/* authenticated POST (fitbit sync) */
export async function postJson<T>(url: string, body: unknown): Promise<T> {
if (!token) throw new Error(NO_TOKEN);
const r = await fetch(url, {
method: 'POST',
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
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.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;
async function authFetch<T>(url: string): Promise<T> {
if (!token) throw new Error(NO_TOKEN);
const r = await fetch(url, {
headers: { Authorization: 'Bearer ' + token },
cache: 'no-store',
});
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
if (!r.ok) throw new Error(`${url} → ${r.status}`);
return r.json();
}
/* module-level promise cache, cleared on refresh/logout */
let cache: Partial<Record<EpKey, Promise<unknown>>> = {};
export function load<T>(key: EpKey): Promise<T> {
if (!cache[key])
cache[key] = authFetch<T>(EP[key]).catch((e) => {
delete cache[key];
throw e;
});
return cache[key] as Promise<T>;
}
export function clearCache() {
cache = {};
}
/* drop specific endpoints from the cache so the next load() refetches */
export function invalidate(...keys: EpKey[]) {
for (const k of keys) delete cache[k];
}
/* ---- auth context ---- */
interface AuthCtx {
ready: boolean;
/** 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<boolean>;
clearToken: () => void;
}
const Ctx = createContext<AuthCtx>({
ready: false,
hasToken: false,
saveToken: async () => false,
clearToken: () => {},
});
export const useAuth = () => useContext(Ctx);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [ready, setReady] = useState(false);
const [hasToken, setHasToken] = useState(false);
useEffect(() => {
SecureStore.getItemAsync(AUTH_KEY)
.then((t) => {
if (t) {
token = t;
setHasToken(true);
}
})
.catch(() => {})
.finally(() => setReady(true));
}, []);
const clearToken = useCallback(() => {
token = null;
clearCache();
SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {});
setHasToken(false);
}, []);
const saveToken = useCallback(async (raw: string) => {
const t = raw.trim();
const r = await fetch(EP.meta, {
headers: { Authorization: 'Bearer ' + t },
cache: 'no-store',
});
if (!r.ok) return false;
token = t;
clearCache();
await SecureStore.setItemAsync(AUTH_KEY, t);
setHasToken(true);
return true;
}, []);
return <Ctx.Provider value={{ ready, hasToken, saveToken, clearToken }}>{children}</Ctx.Provider>;
}