Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ The Worker serves both the API (`/api/*`) and the compiled frontend, so there is
pnpm dev # turbo: runs both worker dev + web dev concurrently
pnpm build # turbo: typecheck + build web
pnpm typecheck # turbo: tsc --noEmit on both packages
pnpm test # turbo: worker unit tests (node --test, apps/worker/test/*.test.ts)
pnpm deploy # turbo: builds web then deploys worker
```

Expand Down
37 changes: 32 additions & 5 deletions apps/web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { lazy, type ReactNode, Suspense } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import { Link, Navigate, Route, Routes } from 'react-router-dom';
import { Button } from './components/ui/button.tsx';
import { useAuth } from './contexts/AuthContext.tsx';
import { useTranslation } from './i18n/index.tsx';

const AdminLayout = lazy(() => import('./components/layout/AdminLayout.tsx'));
const DashboardLayout = lazy(
Expand All @@ -27,23 +29,45 @@ function PageFallback() {
);
}

// FE-R1: Shown instead of the login redirect when the session could not be
// restored for a transient reason — the refresh cookie may still be valid.
function SessionRestoreFailed() {
const { retryRestore } = useAuth();
const { t } = useTranslation();
return (
<div className="flex h-screen flex-col items-center justify-center gap-4 text-center">
<p className="text-sm text-muted-foreground" role="alert">
{t('auth.sessionRestoreFailed')}
</p>
<Button type="button" onClick={retryRestore}>
{t('common.retry')}
</Button>
<Link to="/login" className="text-sm text-primary hover:underline">
{t('auth.signInLink')}
</Link>
</div>
);
}

function ProtectedRoute({ children }: { children: ReactNode }) {
const { user, isLoading } = useAuth();
const { user, isLoading, restoreFailed } = useAuth();
if (isLoading) return <PageFallback />;
if (!user && restoreFailed) return <SessionRestoreFailed />;
if (!user) return <Navigate to="/login" replace />;
return <>{children}</>;
}

function AdminRoute({ children }: { children: ReactNode }) {
const { user, isLoading } = useAuth();
const { user, isLoading, restoreFailed } = useAuth();
if (isLoading) return <PageFallback />;
if (!user && restoreFailed) return <SessionRestoreFailed />;
if (!user) return <Navigate to="/login" replace />;
if (user.role !== 'admin') return <Navigate to="/dashboard" replace />;
return <>{children}</>;
}

export default function App() {
const { user, isLoading } = useAuth();
const { user, isLoading, restoreFailed } = useAuth();

return (
<Suspense fallback={<PageFallback />}>
Expand Down Expand Up @@ -91,7 +115,10 @@ export default function App() {
isLoading ? (
<PageFallback />
) : (
<Navigate to={user ? '/dashboard' : '/login'} replace />
<Navigate
to={user || restoreFailed ? '/dashboard' : '/login'}
replace
/>
)
}
/>
Expand Down
75 changes: 57 additions & 18 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,35 @@

let accessToken: string | null = null;

// FE-R2: When a refresh is rejected, every request that was waiting on it sees
// the same failure. Handle the expiry once per session (instead of each request
// hard-navigating to /login) and let the app end the session in-SPA through the
// handler registered by AuthProvider.
let sessionExpiredHandled = false;
let sessionExpiredHandler: (() => void) | null = null;

export function setAccessToken(token: string | null) {
accessToken = token;
// A fresh token starts a new session, so a later expiry is handled again.
if (token) sessionExpiredHandled = false;
}

export function getAccessToken() {
return accessToken;
}

export function setSessionExpiredHandler(handler: (() => void) | null) {
sessionExpiredHandler = handler;
}

function handleSessionExpired() {
accessToken = null;
if (sessionExpiredHandled) return;
sessionExpiredHandled = true;
if (sessionExpiredHandler) sessionExpiredHandler();
else window.location.assign('/login');
}

const BASE = '/api';

interface ApiError {
Expand Down Expand Up @@ -38,8 +59,8 @@ async function request<T>(

if (res.status === 401 && !options.skipAuth) {
// Attempt silent refresh via HttpOnly cookie
const refreshed = await tryRefresh();
if (refreshed) {
const outcome = await tryRefresh();
if (outcome === 'ok') {
headers.Authorization = `Bearer ${accessToken}`;
const retryRes = await fetch(`${BASE}${path}`, {
...options,
Expand All @@ -54,9 +75,14 @@ async function request<T>(
}
return retryRes.json() as Promise<T>;
}
// Refresh failed — clear access token and redirect
setAccessToken(null);
window.location.href = '/login';
if (outcome === 'transient') {
// FE-R1: The refresh never got a verdict (offline, 5xx). The refresh
// cookie may still be valid, so keep the session and fail just this
// request — react-query retries, and the next 401 refreshes again.
throw new Error('Network error. Please try again.');
}
// The server rejected the refresh cookie — the session is really over.
handleSessionExpired();
throw new Error('Session expired');
}

Expand All @@ -78,7 +104,11 @@ async function request<T>(
// FE-S1: The dedup is additionally serialized across tabs via the Web Locks API, so
// sibling tabs refreshing from the same cookie wait for each other instead of
// rotating the refresh token out from under one another.
let refreshPromise: Promise<boolean> | null = null;
// FE-R1: 'transient' (network failure, 5xx, 408/429) says nothing about the
// session; only 'expired' — the server rejected the refresh cookie — ends it.
export type RefreshOutcome = 'ok' | 'expired' | 'transient';

let refreshPromise: Promise<RefreshOutcome> | null = null;

function withRefreshLock<T>(fn: () => Promise<T>): Promise<T> {
const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
Expand All @@ -92,36 +122,45 @@ function withRefreshLock<T>(fn: () => Promise<T>): Promise<T> {
return fn();
}

async function tryRefresh(): Promise<boolean> {
async function tryRefresh(): Promise<RefreshOutcome> {
if (refreshPromise) return refreshPromise;
refreshPromise = withRefreshLock(_doRefresh).finally(() => {
refreshPromise = null;
});
return refreshPromise;
}

async function _doRefresh(): Promise<boolean> {
async function _doRefresh(): Promise<RefreshOutcome> {
let res: Response;
try {
const res = await fetch(`${BASE}/auth/refresh`, {
res = await fetch(`${BASE}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
});
if (!res.ok) return false;
const data = (await res.json()) as { accessToken: string };
} catch {
return 'transient';
}
if (!res.ok) {
const transient =
res.status >= 500 || res.status === 408 || res.status === 429;
return transient ? 'transient' : 'expired';
}
try {
const data = (await res.json()) as { accessToken?: string };
if (!data.accessToken) return 'transient';
setAccessToken(data.accessToken);
return true;
return 'ok';
} catch {
return false;
return 'transient';
}
}

// Serialized silent refresh for the BroadcastChannel 'refresh' handler and the
// initial session restore — returns the new access token, or null when there is
// no valid session.
export async function refreshSession(): Promise<string | null> {
const ok = await tryRefresh();
return ok ? getAccessToken() : null;
// initial session restore. On 'ok' the new access token is already set; callers
// must keep 'transient' distinct from 'expired' (FE-R1).
export function refreshSession(): Promise<RefreshOutcome> {
return tryRefresh();
}

// ─── Auth API ─────────────────────────────────────────────────────────────────
Expand Down
23 changes: 20 additions & 3 deletions apps/web/src/contexts/AppConfigContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,39 @@ interface AppConfig {
interface AppConfigContextType {
appName: string;
registrationEnabled: boolean;
// FE-R3: Consumers must not act on `registrationEnabled` until the first
// /api/config response has arrived (`isLoading`), and must tell the user when
// it could not be loaded (`loadFailed`) instead of silently assuming "closed".
isLoading: boolean;
loadFailed: boolean;
reload: () => void;
}

const AppConfigContext = createContext<AppConfigContextType | null>(null);

async function fetchConfig(): Promise<AppConfig> {
const res = await fetch('/api/config');
if (!res.ok) return { appName: 'ShortLink', registrationEnabled: false };
if (!res.ok) throw new Error(`GET /api/config failed: ${res.status}`);
return res.json() as Promise<AppConfig>;
}

export function AppConfigProvider({ children }: { children: React.ReactNode }) {
const [appName, setAppName] = useState('ShortLink');
const [registrationEnabled, setRegistrationEnabled] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);

// Reloads keep the last known values on screen; only the first load shows as
// `isLoading`.
const load = useCallback(() => {
fetchConfig()
.then((c) => {
setAppName(c.appName);
setRegistrationEnabled(c.registrationEnabled);
setLoadFailed(false);
})
.catch(() => {});
.catch(() => setLoadFailed(true))
.finally(() => setIsLoading(false));
}, []);

useEffect(() => {
Expand All @@ -45,7 +56,13 @@ export function AppConfigProvider({ children }: { children: React.ReactNode }) {

return (
<AppConfigContext.Provider
value={{ appName, registrationEnabled, reload: load }}
value={{
appName,
registrationEnabled,
isLoading,
loadFailed,
reload: load,
}}
>
{children}
</AppConfigContext.Provider>
Expand Down
Loading
Loading