Replace Basic-auth login with an API token set in Settings
Some checks failed
Build & Release APK / build (push) Has been cancelled

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>
This commit is contained in:
marcus
2026-11-19 23:07:00 -08:00
parent 81632a4275
commit 65bf540ea0
7 changed files with 123 additions and 168 deletions

View File

@@ -22,62 +22,33 @@ 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: '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<T>(url: string): Promise<T> {
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<boolean>;
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<boolean>;
clearToken: () => void;
}
const Ctx = createContext<AuthCtx>({
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 <Ctx.Provider value={{ ready, authed, login, logout }}>{children}</Ctx.Provider>;
return <Ctx.Provider value={{ ready, hasToken, saveToken, clearToken }}>{children}</Ctx.Provider>;
}