Add backend health check, fetch timeouts, stale token cleanup, and error screen #4

Merged
josh merged 1 commits from feature/auth-invites into main 2026-04-27 19:56:53 -04:00
4 changed files with 117 additions and 43 deletions
+34 -3
View File
@@ -7,7 +7,7 @@ import { InviteGateScreen } from '@/components/game/InviteGateScreen';
import { useGameLoop } from '@/hooks/useGameLoop'; import { useGameLoop } from '@/hooks/useGameLoop';
import { useAuthGate } from '@/hooks/useAuthGate'; import { useAuthGate } from '@/hooks/useAuthGate';
import { TICK_INTERVAL_MS } from '@ai-tycoon/shared'; import { TICK_INTERVAL_MS } from '@ai-tycoon/shared';
import { Sparkles } from 'lucide-react'; import { Sparkles, RefreshCw, WifiOff } from 'lucide-react';
function LoadingScreen() { function LoadingScreen() {
return ( return (
@@ -25,8 +25,35 @@ function LoadingScreen() {
); );
} }
function BackendErrorScreen({ error, onRetry }: { error: string; onRetry: () => void }) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-surface-950 to-surface-900">
<div className="max-w-md w-full mx-4 text-center">
<div className="inline-flex items-center gap-2 mb-6">
<Sparkles className="text-accent-light" size={32} />
<h1 className="text-4xl font-bold bg-gradient-to-r from-accent-light to-accent bg-clip-text text-transparent">
AI Tycoon
</h1>
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-6 space-y-4">
<WifiOff className="mx-auto text-danger" size={40} />
<h2 className="text-lg font-semibold text-surface-100">Cannot Connect to Server</h2>
<p className="text-sm text-surface-400">{error}</p>
<button
onClick={onRetry}
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-accent hover:bg-accent-dark text-white font-medium text-sm transition-colors"
>
<RefreshCw size={16} /> Retry
</button>
</div>
</div>
</div>
);
}
export function App() { export function App() {
const { loading: authLoading, needsInvite, needsPasswordReset, setRegistered, setNeedsPasswordReset } = useAuthGate(); const { loading: authLoading, backendError, needsInvite, needsPasswordReset, setRegistered, setNeedsPasswordReset, retry } = useAuthGate();
const companyName = useGameStore((s) => s.meta.companyName); const companyName = useGameStore((s) => s.meta.companyName);
const lastTickTimestamp = useGameStore((s) => s.meta.lastTickTimestamp); const lastTickTimestamp = useGameStore((s) => s.meta.lastTickTimestamp);
const [catchUpTicks, setCatchUpTicks] = useState<number | null>(null); const [catchUpTicks, setCatchUpTicks] = useState<number | null>(null);
@@ -43,12 +70,16 @@ export function App() {
} }
}, [companyName, lastTickTimestamp, catchUpDone]); }, [companyName, lastTickTimestamp, catchUpDone]);
useGameLoop(!catchUpDone || authLoading || needsInvite || needsPasswordReset); useGameLoop(!catchUpDone || authLoading || !!backendError || needsInvite || needsPasswordReset);
if (authLoading) { if (authLoading) {
return <LoadingScreen />; return <LoadingScreen />;
} }
if (backendError) {
return <BackendErrorScreen error={backendError} onRetry={retry} />;
}
if (needsInvite || needsPasswordReset) { if (needsInvite || needsPasswordReset) {
return ( return (
<InviteGateScreen <InviteGateScreen
+44 -27
View File
@@ -1,9 +1,10 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useCallback } from 'react';
import { api, getTokenPayload, isRegistered as checkRegistered, needsPasswordReset as checkNeedsReset, setAuthToken } from '@/lib/api'; import { api, getTokenPayload, isRegistered as checkRegistered, needsPasswordReset as checkNeedsReset, validateStoredToken } from '@/lib/api';
import { ensureAuth } from './useCloudSave'; import { ensureAuth } from './useCloudSave';
interface AuthGateState { interface AuthGateState {
loading: boolean; loading: boolean;
backendError: string | null;
needsInvite: boolean; needsInvite: boolean;
needsPasswordReset: boolean; needsPasswordReset: boolean;
registered: boolean; registered: boolean;
@@ -11,46 +12,60 @@ interface AuthGateState {
config: { requireInvite: boolean; userInvitations: number } | null; config: { requireInvite: boolean; userInvitations: number } | null;
setRegistered: (value: boolean) => void; setRegistered: (value: boolean) => void;
setNeedsPasswordReset: (value: boolean) => void; setNeedsPasswordReset: (value: boolean) => void;
retry: () => void;
} }
export function useAuthGate(): AuthGateState { export function useAuthGate(): AuthGateState {
const [config, setConfig] = useState<{ requireInvite: boolean; userInvitations: number } | null>(null); const [config, setConfig] = useState<{ requireInvite: boolean; userInvitations: number } | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [backendError, setBackendError] = useState<string | null>(null);
const [registered, setRegistered] = useState(false); const [registered, setRegistered] = useState(false);
const [passwordReset, setPasswordReset] = useState(false); const [passwordReset, setPasswordReset] = useState(false);
const [admin, setAdmin] = useState(false); const [admin, setAdmin] = useState(false);
const [initCount, setInitCount] = useState(0);
useEffect(() => { const init = useCallback(async () => {
let cancelled = false; setLoading(true);
setBackendError(null);
async function init() { validateStoredToken();
try {
const [cfg] = await Promise.all([
api.config.get(),
ensureAuth(),
]);
if (cancelled) return; try {
await api.health();
setConfig(cfg); } catch (e) {
setBackendError(e instanceof Error ? e.message : 'Cannot connect to server');
const payload = getTokenPayload(); setLoading(false);
const reg = checkRegistered(); return;
setRegistered(reg);
setPasswordReset(checkNeedsReset());
setAdmin(payload?.role === 'admin');
} catch {
// Config fetch failed — allow game to load (fail open)
setConfig({ requireInvite: false, userInvitations: 0 });
} finally {
if (!cancelled) setLoading(false);
}
} }
init(); try {
return () => { cancelled = true; }; const cfg = await api.config.get();
setConfig(cfg);
} catch {
setConfig({ requireInvite: false, userInvitations: 0 });
}
try {
await ensureAuth();
} catch {
// auth failed — will show as unregistered
}
const payload = getTokenPayload();
setRegistered(checkRegistered());
setPasswordReset(checkNeedsReset());
setAdmin(payload?.role === 'admin');
setLoading(false);
}, []); }, []);
// Run init on mount and on retry
useState(() => { init(); });
const retry = useCallback(() => {
setInitCount(c => c + 1);
init();
}, [init]);
const handleSetRegistered = useCallback((value: boolean) => { const handleSetRegistered = useCallback((value: boolean) => {
setRegistered(value); setRegistered(value);
const payload = getTokenPayload(); const payload = getTokenPayload();
@@ -68,6 +83,7 @@ export function useAuthGate(): AuthGateState {
return { return {
loading, loading,
backendError,
needsInvite, needsInvite,
needsPasswordReset: passwordReset, needsPasswordReset: passwordReset,
registered, registered,
@@ -75,5 +91,6 @@ export function useAuthGate(): AuthGateState {
config, config,
setRegistered: handleSetRegistered, setRegistered: handleSetRegistered,
setNeedsPasswordReset: handleSetPasswordReset, setNeedsPasswordReset: handleSetPasswordReset,
retry,
}; };
} }
+6 -3
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { useGameStore } from '@/store'; import { useGameStore } from '@/store';
import { api, getAuthToken, setAuthToken } from '@/lib/api'; import { api, getAuthToken, setAuthToken, clearAuthToken, decodeTokenPayload } from '@/lib/api';
import { AUTO_SAVE_INTERVAL_TICKS } from '@ai-tycoon/shared'; import { AUTO_SAVE_INTERVAL_TICKS } from '@ai-tycoon/shared';
export function useCloudSave() { export function useCloudSave() {
@@ -31,8 +31,11 @@ export function useCloudSave() {
} }
export async function ensureAuth(): Promise<string | null> { export async function ensureAuth(): Promise<string | null> {
let token = getAuthToken(); const token = getAuthToken();
if (token) return token; if (token) {
if (decodeTokenPayload(token)) return token;
clearAuthToken();
}
try { try {
const result = await api.auth.anonymous(); const result = await api.auth.anonymous();
+33 -10
View File
@@ -63,30 +63,53 @@ export function needsPasswordReset(): boolean {
return payload?.mustResetPassword === true; return payload?.mustResetPassword === true;
} }
async function request<T>(path: string, options: RequestInit = {}): Promise<T> { async function request<T>(path: string, options: RequestInit & { timeoutMs?: number } = {}): Promise<T> {
const { timeoutMs = 10_000, ...fetchOptions } = options;
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...(options.headers as Record<string, string>), ...(fetchOptions.headers as Record<string, string>),
}; };
if (authToken) { if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`; headers['Authorization'] = `Bearer ${authToken}`;
} }
const res = await fetch(`${API_BASE}${path}`, { const controller = new AbortController();
...options, const timeout = setTimeout(() => controller.abort(), timeoutMs);
headers,
});
if (!res.ok) { try {
const body = await res.json().catch(() => ({ error: 'Unknown error' })); const res = await fetch(`${API_BASE}${path}`, {
throw new Error(body.error || `HTTP ${res.status}`); ...fetchOptions,
headers,
signal: controller.signal,
});
if (!res.ok) {
const body = await res.json().catch(() => ({ error: 'Unknown error' }));
throw new Error(body.error || `HTTP ${res.status}`);
}
return res.json();
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') {
throw new Error('Request timed out — server may be unreachable');
}
throw e;
} finally {
clearTimeout(timeout);
} }
}
return res.json(); export function validateStoredToken(): void {
const token = getAuthToken();
if (token && !decodeTokenPayload(token)) {
clearAuthToken();
}
} }
export const api = { export const api = {
health: () => request<{ status: string }>('/health', { timeoutMs: 5_000 }),
auth: { auth: {
anonymous: () => request<{ userId: string; token: string }>('/api/auth/anonymous', { method: 'POST' }), anonymous: () => request<{ userId: string; token: string }>('/api/auth/anonymous', { method: 'POST' }),
login: (login: string, password: string) => login: (login: string, password: string) =>