diff --git a/catalyst-frontend/e2e/functional.spec.ts b/catalyst-frontend/e2e/functional.spec.ts index e87abc0b1..26ac7d9b8 100644 --- a/catalyst-frontend/e2e/functional.spec.ts +++ b/catalyst-frontend/e2e/functional.spec.ts @@ -39,6 +39,44 @@ async function login(page: Page) { await loginUser(page, testUser); } +/** + * Record every in-app path this document navigates through. React Router + * redirects via history.pushState/replaceState, which fire no Playwright + * navigation event, so a `framenavigated` listener would miss a client-side + * bounce to /login. Install before the reload under test. + */ +async function recordSpaPaths(page: Page) { + await page.addInitScript(() => { + const store = window as unknown as { __spaPaths: string[] }; + store.__spaPaths = [window.location.pathname]; + const historyMethods = history as unknown as Record< + string, + (state: unknown, title: string, url?: string | URL | null) => void + >; + const record = (url?: string | URL | null) => { + if (url === undefined || url === null) return; + try { + store.__spaPaths.push(new URL(String(url), window.location.origin).pathname); + } catch { + // Not a resolvable path — nothing to record. + } + }; + for (const method of ['pushState', 'replaceState']) { + const original = historyMethods[method].bind(history); + historyMethods[method] = (state, title, url) => { + record(url); + original(state, title, url); + }; + } + }); +} + +async function spaPaths(page: Page): Promise { + return page.evaluate( + () => (window as unknown as { __spaPaths?: string[] }).__spaPaths ?? [], + ); +} + // ─── Test suites ───────────────────────────────────────────────────────────── // 1. Authentication Flows @@ -226,6 +264,39 @@ test.describe('Authentication Flows', () => { .toBeVisible({ timeout: 10_000 }); }); + test('Reloading an authenticated page never paints the login page', async ({ page }) => { + test.setTimeout(60_000); + await login(page); + await recordSpaPaths(page); + + // EventSource streams keep the network busy, so networkidle can never settle; + // the sidebar locator below is the real "panel rendered" signal. + await page.goto('/servers', { waitUntil: 'domcontentloaded' }).catch(() => {}); + await page.locator('aside nav').first().waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}); + + expect.soft(await spaPaths(page)).not.toContain('/login'); + expect.soft(new URL(page.url()).pathname).toBe('/servers'); + }); + + test('Reloading with a slow session probe never paints the login page', async ({ page }) => { + test.setTimeout(60_000); + await login(page); + await recordSpaPaths(page); + + // Slow backend: this is the window in which the old bootstrap declared "no + // session" before /api/auth/me had answered, bouncing users to /login. + await page.route('**/api/auth/me*', async (route) => { + await new Promise((resolve) => setTimeout(resolve, 2_000)); + await route.continue(); + }); + + await page.goto('/servers', { waitUntil: 'domcontentloaded' }).catch(() => {}); + await page.locator('aside nav').first().waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}); + + expect.soft(await spaPaths(page)).not.toContain('/login'); + expect.soft(new URL(page.url()).pathname).toBe('/servers'); + }); + test('User can logout and is redirected', async ({ page }) => { test.setTimeout(30_000); await login(page); diff --git a/catalyst-frontend/src/App.tsx b/catalyst-frontend/src/App.tsx index da277bb84..db301ee42 100644 --- a/catalyst-frontend/src/App.tsx +++ b/catalyst-frontend/src/App.tsx @@ -1,5 +1,5 @@ import { lazy, Suspense, useEffect, useRef, useState } from 'react'; -import { Navigate, Route, Routes, useLocation } from 'react-router-dom'; +import { Link, Navigate, Route, Routes, useLocation } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import SetupPage from './pages/setup/SetupPage'; import { useSetupStatus } from './hooks/useSetupStatus'; @@ -71,6 +71,37 @@ function PageFallback() { ); } +/** + * Recovery screen for a boot session probe that never settled. Shown for every + * path except the auth routes, so a signed-out user still has a way in. + */ +function SessionCheckFailedPage() { + const { t } = useTranslation(['common', 'auth']); + const isRefreshing = useAuthStore((s) => s.isRefreshing); + const retrySession = useAuthStore((s) => s.init); + return ( +
+
+

{t('sessionCheck.failed')}

+ + + {t('auth:login.submit')} + +
+
+ ); +} + /** Smooth page transition wrapper */ function PageTransition({ children }: { children: React.ReactNode }) { const reducedMotion = useReducedMotion(); @@ -101,6 +132,7 @@ function App() { const user = useAuthStore((s) => s.user); const isAuthenticated = useAuthStore((s) => s.isAuthenticated); const isReady = useAuthStore((s) => s.isReady); + const sessionCheckFailed = useAuthStore((s) => s.sessionCheckFailed); const { setupRequired, isLoading: isSetupLoading, @@ -109,26 +141,45 @@ function App() { recheck: recheckSetup, } = useSetupStatus(); - // Backstop so a stalled backend can never leave the panel on Loading... - // Auth and setup hooks have their own shorter timeouts; this covers any - // other hang in the boot path. + // Backstop so a stalled boot step can never leave the panel on Loading... + // The auth hook bounds its own probe (and shows a retry screen) and the setup + // hook has its own timeout, so this only covers anything else that hangs — + // and it never overrides an in-flight session probe, because flipping the + // gate early is the login-page flash. const [bootTimedOut, setBootTimedOut] = useState(false); // Mirrors boot readiness so the backstop only reports when boot is // genuinely still stuck — previously the timer always fired 20s after // mount and reported on every session, even fast boots. const bootReadyRef = useRef(false); + const bootReportedRef = useRef(false); bootReadyRef.current = isReady && !isSetupLoading; useEffect(() => { - const timer = setTimeout(() => { + let timer: ReturnType | undefined; + const check = (delay: number) => { + timer = setTimeout(() => { if (bootReadyRef.current) return; + // A session probe still in flight is the one boot step this must not + // override: flipping the gate early is exactly the login-page flash. + // useAuthInit bounds that probe on its own (retry, then its retry + // screen), so keep watching instead of cancelling the backstop. + if (useAuthStore.getState().isRefreshing) { + check(5000); + return; + } setBootTimedOut(true); + if (bootReportedRef.current) return; + bootReportedRef.current = true; reportSystemError({ level: 'warn', component: 'App', message: 'Boot loading timed out, continuing without blocking on init', }); - }, 20000); - return () => clearTimeout(timer); + }, delay); + }; + check(20000); + return () => { + if (timer) clearTimeout(timer); + }; }, []); // Load public theme settings (including custom CSS) once on mount @@ -272,6 +323,33 @@ function App() { ); } + // The session probe never settled (slow or unreachable backend). Falling + // through to the router would paint /login for a user whose session may still + // be valid, so every other path gets a retry screen instead — but the auth + // routes stay reachable, because `/api/auth/me` alone can be broken while + // signing in still works. `init()` and `login()` both clear the flag. + if (sessionCheckFailed && !isAuthenticated) { + return ( + + + + + + + } /> + } /> + } /> + } /> + {/* 2FA is handled inline on LoginPage (totp dialog) — keep a redirect for old links */} + } /> + } /> + + + + + ); + } + return ( diff --git a/catalyst-frontend/src/__tests__/App.sessionCheck.test.tsx b/catalyst-frontend/src/__tests__/App.sessionCheck.test.tsx new file mode 100644 index 000000000..1bd989777 --- /dev/null +++ b/catalyst-frontend/src/__tests__/App.sessionCheck.test.tsx @@ -0,0 +1,79 @@ +/** + * The retry screen for a boot session probe that never settled must not trap a + * signed-out user away from the sign-in form: `/api/auth/me` alone can be + * broken while `/api/auth/login` still works. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { useAuthStore } from '../stores/authStore'; + +vi.mock('../hooks/useAuthInit', () => ({ useAuthInit: () => {} })); +vi.mock('../hooks/useStreamRecovery', () => ({ useStreamRecovery: () => {} })); +vi.mock('../hooks/useSetupStatus', () => ({ + useSetupStatus: () => ({ + setupRequired: false, + isLoading: false, + unreachable: false, + error: null, + recheck: () => {}, + }), +})); +vi.mock('../services/api/theme', () => ({ + themeApi: { getPublicSettings: vi.fn(async () => ({ customCss: '' })) }, +})); +vi.mock('../services/api/auth', () => ({ + authApi: { getOAuthProviders: vi.fn(async () => []) }, +})); +// The real provider pulls in the plugin loader's `@plugins` import glob, which +// vitest cannot resolve; the gate under test does not depend on it. +vi.mock('../plugins/PluginProvider', () => ({ + PluginProvider: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +// jsdom has no ResizeObserver and the login card's primitives touch it. +globalThis.ResizeObserver = class { + observe() {} + unobserve() {} + disconnect() {} +} as unknown as typeof ResizeObserver; + +import i18n from '../i18n'; +import App from '../App'; + +function renderAt(path: string) { + return render( + + + , + ); +} + +describe('App session-check retry screen', () => { + beforeEach(() => { + useAuthStore.setState({ + isReady: true, + isAuthenticated: false, + user: null, + sessionCheckFailed: true, + isRefreshing: false, + }); + }); + + afterEach(() => { + cleanup(); + useAuthStore.setState({ sessionCheckFailed: false, isReady: false }); + }); + + it('shows the retry screen for app routes', () => { + renderAt('/dashboard'); + expect(screen.getByText(i18n.t('sessionCheck.failed'))).toBeInTheDocument(); + }); + + it('offers a way to the sign-in form', async () => { + renderAt('/dashboard'); + fireEvent.click(await screen.findByRole('link')); + await waitFor(() => expect(document.querySelector('input#email')).not.toBeNull()); + }); +}); diff --git a/catalyst-frontend/src/hooks/useAuthInit.ts b/catalyst-frontend/src/hooks/useAuthInit.ts index 3247c6887..4746367bd 100644 --- a/catalyst-frontend/src/hooks/useAuthInit.ts +++ b/catalyst-frontend/src/hooks/useAuthInit.ts @@ -3,30 +3,66 @@ import { useAuthStore } from '../stores/authStore'; import { reportSystemError } from '../services/api/systemErrors'; const AUTH_INIT_TIMEOUT_MS = 12000; +/** One retry, so a slow-but-reachable backend still answers the probe. */ +const MAX_ATTEMPTS = 2; export function useAuthInit() { const init = useAuthStore((s) => s.init); useEffect(() => { - let settled = false; - const timer = setTimeout(() => { - if (!settled && !useAuthStore.getState().isReady) { - useAuthStore.setState({ isReady: true }); + let cancelled = false; + const timers = new Set>(); + + /** + * Run the boot probe under a time limit. Never writing `isReady` here is the + * point: the store announces readiness when the session question is actually + * answered, so a slow backend cannot bounce an authenticated user to /login. + */ + const start = (attempt: number) => { + let settled = false; + const timer = setTimeout(() => { + timers.delete(timer); + if (cancelled || settled || useAuthStore.getState().isReady) return; + if (attempt < MAX_ATTEMPTS) { + // Re-arm the deadline rather than declaring "no session": if the first + // probe already failed this starts a fresh one, and if it is still + // running the retry joins it instead of racing a second request. + start(attempt + 1); + return; + } + // Still unresolved: fail open so the panel renders, and say so rather + // than presenting a bare sign-in form. App renders the retry screen off + // this flag; the retry button calls init() again. + settled = true; + useAuthStore.setState({ isReady: true, sessionCheckFailed: true }); reportSystemError({ level: 'warn', component: 'useAuthInit', - message: `Auth init timed out after ${AUTH_INIT_TIMEOUT_MS}ms, continuing without session`, + message: `Auth init timed out after ${MAX_ATTEMPTS * AUTH_INIT_TIMEOUT_MS}ms, continuing without session`, + }); + }, AUTH_INIT_TIMEOUT_MS); + timers.add(timer); + + init() + .catch(() => {}) + .finally(() => { + // init() can return without answering (the loginGuard short-circuit + // leaves the session to login()); only stop the clock once the store + // says the question is answered. + if (!useAuthStore.getState().isReady) return; + settled = true; + clearTimeout(timer); + timers.delete(timer); }); - } - }, AUTH_INIT_TIMEOUT_MS); - // Silently handle 401 — expected when no session exists - init().catch(() => {}).finally(() => { - settled = true; - clearTimeout(timer); - }); + }; + + start(1); + + // Silently handle 401 — expected when no session exists. return () => { - settled = true; - clearTimeout(timer); + cancelled = true; + for (const timer of timers) clearTimeout(timer); + timers.clear(); }; }, [init]); -} +} \ No newline at end of file diff --git a/catalyst-frontend/src/i18n/locales/en/common.json b/catalyst-frontend/src/i18n/locales/en/common.json index 1a208242f..f210c63c9 100644 --- a/catalyst-frontend/src/i18n/locales/en/common.json +++ b/catalyst-frontend/src/i18n/locales/en/common.json @@ -141,6 +141,9 @@ "transfer": "Transfer server", "update": "Update server settings" }, + "sessionCheck": { + "failed": "We could not verify your session. The panel may still be starting up, or the backend may be unreachable. Try again in a moment." + }, "setupStatus": { "checkFailed": "Failed to check setup status", "timedOut": "Setup check timed out after {{ms}}ms" diff --git a/catalyst-frontend/src/i18n/locales/fr/common.json b/catalyst-frontend/src/i18n/locales/fr/common.json index 19221b1e9..c4fc1bf12 100644 --- a/catalyst-frontend/src/i18n/locales/fr/common.json +++ b/catalyst-frontend/src/i18n/locales/fr/common.json @@ -141,6 +141,9 @@ "transfer": "Transférer le serveur", "update": "Mettre à jour les paramètres du serveur" }, + "sessionCheck": { + "failed": "Impossible de vérifier votre session. Le panneau démarre peut-être encore ou le serveur est injoignable. Réessayez dans un instant." + }, "setupStatus": { "checkFailed": "Échec de la vérification de l’état de la configuration", "timedOut": "La vérification de la configuration a expiré après {{ms}} ms" diff --git a/catalyst-frontend/src/i18n/locales/ru/common.json b/catalyst-frontend/src/i18n/locales/ru/common.json index 719452442..29520b7a5 100644 --- a/catalyst-frontend/src/i18n/locales/ru/common.json +++ b/catalyst-frontend/src/i18n/locales/ru/common.json @@ -141,6 +141,9 @@ "transfer": "Перенос сервера", "update": "Обновить настройки сервера" }, + "sessionCheck": { + "failed": "Не удалось проверить сеанс. Панель может ещё запускаться, или сервер недоступен. Повторите попытку через мгновение." + }, "setupStatus": { "checkFailed": "Не удалось проверить статус настройки", "timedOut": "Время проверки установки истекло через {{ms}} мс" diff --git a/catalyst-frontend/src/i18n/locales/zh-CN/common.json b/catalyst-frontend/src/i18n/locales/zh-CN/common.json index 7ae0fa985..7c005ac8b 100644 --- a/catalyst-frontend/src/i18n/locales/zh-CN/common.json +++ b/catalyst-frontend/src/i18n/locales/zh-CN/common.json @@ -141,6 +141,9 @@ "transfer": "转移服务器", "update": "更新服务器设置" }, + "sessionCheck": { + "failed": "无法验证您的会话。面板可能仍在启动,或后端无法访问。请稍后重试。" + }, "setupStatus": { "checkFailed": "检查初始化状态失败", "timedOut": "初始化状态检查超时({{ms}}ms)" diff --git a/catalyst-frontend/src/services/api/__tests__/client.test.ts b/catalyst-frontend/src/services/api/__tests__/client.test.ts index f09ff2f6c..9e20ee915 100644 --- a/catalyst-frontend/src/services/api/__tests__/client.test.ts +++ b/catalyst-frontend/src/services/api/__tests__/client.test.ts @@ -1,5 +1,6 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { apiClient } from '../client'; +import { useAuthStore } from '../../../stores/authStore'; function stubFetch() { const calls: Array<{ url: string; init: RequestInit }> = []; @@ -20,6 +21,20 @@ afterEach(() => { vi.unstubAllGlobals(); }); +beforeEach(() => { + useAuthStore.setState({ + user: null, + token: null, + rememberMe: false, + isAuthenticated: false, + isLoading: false, + isReady: true, + isRefreshing: false, + sessionCheckFailed: false, + error: null, + }); +}); + describe('apiClient Content-Type handling', () => { it('omits Content-Type for FormData opted out with an empty string', async () => { const calls = stubFetch(); @@ -53,3 +68,26 @@ describe('apiClient Content-Type handling', () => { expect(headers['Content-Type']).toBe('application/merge-patch+json'); }); }); + +describe('apiClient 401 handling', () => { + it('leaves a live session alone when the session probe answers 401', async () => { + const user = { id: 'user-1', email: 'user@example.com', username: 'user', role: 'user' as const, permissions: [] }; + useAuthStore.setState({ user, isAuthenticated: true, isReady: true }); + + vi.stubGlobal('fetch', vi.fn(async () => ({ + ok: false, + status: 401, + headers: new Headers(), + json: async () => ({ error: 'Unauthorized', code: 'UNAUTHORIZED' }), + }))); + + // The probe's own answer is handled by the auth store's refresh(), which + // distinguishes a real sign-out from a transient failure. The interceptor + // must not clear state (or the query cache) behind its back. + await expect(apiClient.get('/api/auth/me')).rejects.toMatchObject({ status: 401 }); + + const state = useAuthStore.getState(); + expect(state.isAuthenticated).toBe(true); + expect(state.user).toEqual(user); + }); +}); diff --git a/catalyst-frontend/src/services/api/client.ts b/catalyst-frontend/src/services/api/client.ts index 3df2c7e86..7096f0112 100644 --- a/catalyst-frontend/src/services/api/client.ts +++ b/catalyst-frontend/src/services/api/client.ts @@ -247,8 +247,18 @@ class ApiClient { errorData = { message: response.statusText || `HTTP ${response.status}` }; } - // Global 401 handling — clears auth state, privileged cache, and redirects - if (response.status === 401 && !loginGuard.active) { + // Global 401 handling — clears auth state, privileged cache, and redirects. + // Public endpoints answer 401 as their ordinary "not signed in" reply: + // the session probe expects it on a fresh load, and the setup/theme probes + // are public. Never touch auth state for them — `/api/auth/me`'s answer is + // owned by the store's `refresh()`, which keeps a live session on a + // transient failure and signs out on a real 401. Clearing here let any + // background probe wipe a session behind the store's back. + const isPublicEndpoint = + path.startsWith('/api/auth/me') || + path.startsWith('/api/setup/status') || + path.startsWith('/api/theme-settings/public'); + if (!isPublicEndpoint && response.status === 401 && !loginGuard.active) { const code = errorData.code; if (code !== 'TWO_FACTOR_REQUIRED' && code !== 'PASSKEY_REQUIRED') { useAuthStore.setState({ @@ -256,6 +266,8 @@ class ApiClient { token: null, isAuthenticated: false, isReady: true, + sessionCheckFailed: false, + error: null, rememberMe: false, }); // Drop any privileged React Query cache so stale admin/server data @@ -271,15 +283,8 @@ class ApiClient { currentPath.startsWith('/forgot-password') || currentPath.startsWith('/reset-password') || currentPath.startsWith('/invites'); - // Session probe and other public endpoints expect 401 when logged - // out (fresh install, expired session check). Never hard-redirect - // for them — React router guards handle navigation. - const isPublicEndpoint = - path.startsWith('/api/auth/me') || - path.startsWith('/api/setup/status') || - path.startsWith('/api/theme-settings/public'); // Avoid redirect loops on public pages and during first-run setup. - if (!isPublicRoute && !isPublicEndpoint) { + if (!isPublicRoute) { const returnTo = encodeURIComponent(currentPath); window.location.assign(`/login?from=${returnTo}`); } diff --git a/catalyst-frontend/src/stores/__tests__/authStore.test.ts b/catalyst-frontend/src/stores/__tests__/authStore.test.ts new file mode 100644 index 000000000..c3ab72d0d --- /dev/null +++ b/catalyst-frontend/src/stores/__tests__/authStore.test.ts @@ -0,0 +1,188 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + refresh: vi.fn(), + reportSystemError: vi.fn(), + loginGuard: { active: false, enter: vi.fn(), exit: vi.fn() }, +})); + +vi.mock('../../services/api/auth', () => ({ + authApi: { + refresh: mocks.refresh, + login: vi.fn(), + register: vi.fn(), + logout: vi.fn(), + verifyTwoFactor: vi.fn(), + }, +})); +vi.mock('../../services/api/systemErrors', () => ({ + reportSystemError: mocks.reportSystemError, +})); +vi.mock('../../services/api/client', () => ({ loginGuard: mocks.loginGuard })); + +import i18n from '../../i18n'; +import { useAuthStore } from '../authStore'; +import type { User } from '../../types/user'; + +const baseUser: User = { + id: 'user-1', + email: 'user@example.com', + username: 'user', + role: 'user', + permissions: [], +}; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function statusError(message: string, status: number) { + return Object.assign(new Error(message), { status }); +} + +beforeEach(() => { + mocks.refresh.mockReset(); + mocks.reportSystemError.mockReset(); + mocks.loginGuard.active = false; + useAuthStore.setState({ + user: null, + token: null, + rememberMe: false, + isAuthenticated: false, + isLoading: false, + isReady: false, + isRefreshing: false, + sessionCheckFailed: false, + error: null, + }); +}); + +describe('authStore session bootstrap', () => { + it('does not mark auth ready until the session probe answers', async () => { + const probe = deferred<{ user: User }>(); + mocks.refresh.mockReturnValueOnce(probe.promise); + + const initPromise = useAuthStore.getState().init(); + await vi.waitFor(() => expect(mocks.refresh).toHaveBeenCalledTimes(1)); + // The reported bug: isReady flipped before the session question was answered. + expect(useAuthStore.getState().isReady).toBe(false); + + probe.resolve({ user: baseUser }); + await initPromise; + + const state = useAuthStore.getState(); + expect(state.isReady).toBe(true); + expect(state.isAuthenticated).toBe(true); + expect(state.user?.id).toBe(baseUser.id); + }); + + it('never writes isReady from a background refresh()', async () => { + mocks.refresh.mockResolvedValueOnce({ user: baseUser }); + + await useAuthStore.getState().refresh(); + + const state = useAuthStore.getState(); + expect(state.isReady).toBe(false); + expect(state.isAuthenticated).toBe(true); + }); + + it('settles a 401 into a signed-out, ready state', async () => { + mocks.refresh.mockRejectedValueOnce(statusError('Unauthorized', 401)); + + await expect(useAuthStore.getState().init()).rejects.toThrow('Unauthorized'); + + const state = useAuthStore.getState(); + expect(state.isReady).toBe(true); + expect(state.isAuthenticated).toBe(false); + expect(state.user).toBeNull(); + }); + + it('keeps a live session and explains a transient failure after boot', async () => { + useAuthStore.setState({ user: baseUser, isAuthenticated: true, isReady: true }); + mocks.refresh.mockRejectedValueOnce(statusError('Server error', 500)); + + await expect(useAuthStore.getState().refresh()).rejects.toThrow('Server error'); + + const state = useAuthStore.getState(); + expect(state.isAuthenticated).toBe(true); + expect(state.user).toEqual(baseUser); + expect(state.isReady).toBe(true); + expect(state.error).toBe(i18n.t('sessionCheck.failed')); + }); + + it('flags a transient boot-probe failure so App can offer a retry', async () => { + mocks.refresh.mockRejectedValueOnce(statusError('Service unavailable', 503)); + + await expect(useAuthStore.getState().init()).rejects.toThrow('Service unavailable'); + + let state = useAuthStore.getState(); + expect(state.isReady).toBe(true); + expect(state.isAuthenticated).toBe(false); + expect(state.sessionCheckFailed).toBe(true); + expect(state.error).toBe(i18n.t('sessionCheck.failed')); + + // A retry that fails the same way (429 from the cooldown short-circuit, say) + // must keep the retry screen up rather than dismissing it into /login. + mocks.refresh.mockRejectedValueOnce(statusError('Refresh cooldown active', 429)); + await expect(useAuthStore.getState().init()).rejects.toThrow('Refresh cooldown active'); + + state = useAuthStore.getState(); + expect(state.sessionCheckFailed).toBe(true); + expect(state.isAuthenticated).toBe(false); + + // A retry that answers clears the screen. + mocks.refresh.mockResolvedValueOnce({ user: baseUser }); + await useAuthStore.getState().init(); + state = useAuthStore.getState(); + expect(state.sessionCheckFailed).toBe(false); + expect(state.isAuthenticated).toBe(true); + }); + + it('answers the boot question once when init() and a background refresh overlap', async () => { + const backgroundProbe = deferred<{ user: User }>(); + const bootProbe = deferred<{ user: User }>(); + mocks.refresh + .mockReturnValueOnce(backgroundProbe.promise) + .mockReturnValueOnce(bootProbe.promise); + + // The background refresh starts first, init() follows and joins the queue. + const backgroundPromise = useAuthStore.getState().refresh(); + const initPromise = useAuthStore.getState().init(); + await vi.waitFor(() => expect(mocks.refresh).toHaveBeenCalledTimes(2)); + expect(useAuthStore.getState().isReady).toBe(false); + + bootProbe.resolve({ user: { ...baseUser, username: 'boot' } }); + await initPromise; + // The boot probe answered, so routing may proceed, but the background + // probe is still in flight and owns the isRefreshing transition. + expect(useAuthStore.getState().isReady).toBe(true); + expect(useAuthStore.getState().isRefreshing).toBe(true); + + backgroundProbe.resolve({ user: { ...baseUser, username: 'background' } }); + await backgroundPromise; + + const state = useAuthStore.getState(); + expect(state.isRefreshing).toBe(false); + expect(state.isReady).toBe(true); + // Last settle wins. + expect(state.user?.username).toBe('background'); + }); + + it('leaves the session and readiness to login() while a login is in flight', async () => { + mocks.loginGuard.active = true; + useAuthStore.setState({ user: baseUser, isAuthenticated: true }); + + await useAuthStore.getState().init(); + + const state = useAuthStore.getState(); + expect(mocks.refresh).not.toHaveBeenCalled(); + expect(state.isReady).toBe(false); + expect(state.isAuthenticated).toBe(true); + }); +}); \ No newline at end of file diff --git a/catalyst-frontend/src/stores/authStore.ts b/catalyst-frontend/src/stores/authStore.ts index 221a85076..121a33c1e 100644 --- a/catalyst-frontend/src/stores/authStore.ts +++ b/catalyst-frontend/src/stores/authStore.ts @@ -5,6 +5,7 @@ import { authApi } from '../services/api/auth'; import { reportSystemError } from '../services/api/systemErrors'; import { describeError } from '../utils/errors'; import { getLocalizedErrorMessage, getLocalizedFieldErrors } from '../i18n/api-errors'; +import i18n from '../i18n'; import type { User } from '../types/user'; import type { LoginSchema, RegisterSchema } from '../validators/auth'; @@ -14,8 +15,18 @@ interface AuthState { rememberMe: boolean; isAuthenticated: boolean; isLoading: boolean; + /** + * "The session question is answered." Auth gating (`App`, `ProtectedRoute`, + * `LoginPage`) keys off this, so only an actual answer may set it: the boot + * probe (`init`), the flows that establish or end a session + * (`login`/`register`/2FA/logout), and the global 401 handler for a + * protected call. Background refreshes must never flip it before the probe + * settles. + */ isReady: boolean; isRefreshing: boolean; + /** The boot probe never settled: render a retry screen instead of /login. */ + sessionCheckFailed: boolean; error: string | null; /** @internal AbortController for an in-flight server sign-out request */ _pendingLogoutController?: AbortController; @@ -53,6 +64,10 @@ function sanitizeImageUrl(url?: string | null): string | undefined { } const createAuthState: StateCreator = (set, get) => { + // Session probes in flight. `refresh()` also runs for background callers + // (SSE handlers, profile mutations, the profile poll), so only the last one + // may clear `isRefreshing`; `isReady` is left to `init()`. + let refreshesInFlight = 0; return { user: null, token: null, // No longer using localStorage tokens @@ -61,6 +76,7 @@ const createAuthState: StateCreator { // Abort any in-flight server sign-out from a previous logout — otherwise @@ -95,6 +111,7 @@ const createAuthState: StateCreator { - // With cookie-based auth, always try to refresh - cookies are sent automatically - (set as AuthSet)({ isRefreshing: true, error: null, isReady: true }); + // With cookie-based auth, always try to refresh - cookies are sent automatically. + // Deliberately never touches `isReady`: this runs on mount, on SSE events and + // after profile mutations, so announcing "auth decided" here is what made the + // router remount (and paint /login) while the session was still unknown. + const wasReady = (get as AuthGet)().isReady; + refreshesInFlight += 1; + (set as AuthSet)({ isRefreshing: true, error: null }); try { const { user } = await authApi.refresh(); (set as AuthSet)({ token: null, user: { ...user, image: sanitizeImageUrl(user.image) }, isAuthenticated: true, - isRefreshing: false, - isReady: true, + sessionCheckFailed: false, error: null, }); } catch (error: unknown) { const { loginGuard } = await import('../services/api/client'); if (loginGuard.active) { - (set as AuthSet)({ isRefreshing: false, isReady: true }); + // A login / 2FA handshake owns the session right now. Leave it alone: + // login() sets isAuthenticated and isReady when it completes. return; } const e = error as { status?: number; response?: { status?: number }; retryAfterMs?: number; message?: string }; @@ -181,7 +203,16 @@ const createAuthState: StateCreator= 500) || status === undefined; const isCooldown = e.message === 'Refresh cooldown active'; if (isTransient || isCooldown) { - (set as AuthSet)({ isRefreshing: false, isReady: true }); + // Keep the session: a 429/408/5xx/network blip is not a sign-out. + // Record the failure so the caller can explain the state. When this is + // the boot probe there is no session to keep yet, so App must show its + // retry screen rather than a bare /login — and a retry that fails the + // same way must not make that screen disappear. + (set as AuthSet)( + wasReady + ? { error: i18n.t('sessionCheck.failed') } + : { error: i18n.t('sessionCheck.failed'), sessionCheckFailed: true }, + ); reportSystemError({ level: 'warn', component: 'AuthStore:refresh', @@ -198,11 +229,19 @@ const createAuthState: StateCreator { - // Don't set isReady until refresh completes to prevent flashing authenticated - // content with a potentially expired server-side session. + // The boot probe, and the only path allowed to answer the "is there a + // session?" question for routing. `refresh()` settles the store first; + // isReady flips afterwards so no guard sees an unresolved session. // Guard: if login is in-flight (loginGuard.active), skip the refresh // entirely — login() will set isAuthenticated once it completes, and // we must not overwrite that with a stale 401 from the old session. const { loginGuard } = await import('../services/api/client'); if (loginGuard.active) { - (set as AuthSet)({ isReady: true }); return; } try { await (get as AuthGet)().refresh(); } finally { + // `refresh()` already recorded the outcome (including whether the check + // failed), so this only flips the gate. Clearing the failure flag here + // would make a failed retry dismiss the retry screen. (set as AuthSet)({ isReady: true }); } }, logout: async (opts?: { stay?: boolean }) => { localStorage.removeItem('catalyst-auth'); - (set as AuthSet)({ user: null, token: null, isAuthenticated: false, isReady: true, rememberMe: false }); + (set as AuthSet)({ user: null, token: null, isAuthenticated: false, isReady: true, sessionCheckFailed: false, error: null, rememberMe: false }); // Drop privileged React Query cache so admin/server data cannot flash // if the user signs back in as a different principal. try { @@ -273,6 +320,7 @@ const createAuthState: StateCreator()( if (typeof window !== 'undefined') { window.addEventListener('storage', (e) => { if (e.key === 'catalyst-auth') { - useAuthStore.getState().init(); + useAuthStore.getState().init().catch(() => {}); } }); @@ -329,7 +378,7 @@ if (typeof window !== 'undefined') { channel.onmessage = (event) => { if (event.data?.type === 'logout') { useAuthStore.setState({ - user: null, token: null, isAuthenticated: false, isReady: true, rememberMe: false, + user: null, token: null, isAuthenticated: false, isReady: true, sessionCheckFailed: false, rememberMe: false, }); // Best-effort cache clear so other tabs don't flash privileged data. import('../lib/queryClient')