From 9e21362aab9929a898474740d17ff0a71a36eff7 Mon Sep 17 00:00:00 2001 From: jun261930-tech Date: Sun, 17 May 2026 17:24:08 +0800 Subject: [PATCH 1/2] feat(api-client): add 401/403/5xx interceptor + AuthExpiredListener MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1 of MC code-quality plan (see PLAN.md / PR-api-client.md): - src/lib/api-client.ts (+120) ApiError + apiFetch wrapper - src/lib/__tests__/api-client.test.ts (+108) 8 vitest cases (200/401/403/500/network/loop/204/no-redirect) - src/components/auth-expired-listener.tsx (+30) global mc:auth-expired -> /login redirect - src/app/layout.tsx (+2) register listener - eslint.config.mjs (+31) no-restricted-syntax warn for bare fetch('/api/...') Quality gates passed: - pnpm vitest run src/lib/__tests__/api-client.test.ts: 8/8 (2.5s) - pnpm typecheck: 0 error - pnpm lint: 0 error, 343 warn (~baseline 334 bare fetch + 9 pre-existing) Out of scope: migrating existing 334 bare fetch sites (P2, separate PR). P0 verification: playwright captured 19/19 /api/* returning 200 after login, ruling out backend issue (cookie expired) — see p0-network-evidence.txt. --- eslint.config.mjs | 31 +++++ src/app/layout.tsx | 2 + src/components/auth-expired-listener.tsx | 33 ++++++ src/lib/__tests__/api-client.test.ts | 114 ++++++++++++++++++ src/lib/api-client.ts | 145 +++++++++++++++++++++++ 5 files changed, 325 insertions(+) create mode 100644 src/components/auth-expired-listener.tsx create mode 100644 src/lib/__tests__/api-client.test.ts create mode 100644 src/lib/api-client.ts diff --git a/eslint.config.mjs b/eslint.config.mjs index fc93951080..57ad41f70f 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -18,6 +18,37 @@ const config = [ 'react-hooks/immutability': 'off', }, }, + // P1.5 — Discourage bare `fetch('/api/...')`. + // The team must migrate to `apiFetch()` from `@/lib/api-client` so that + // 401 / 403 / 5xx / network failures are handled uniformly. + // Phase 1 (this PR): warn level, allow incremental migration. + // Phase 3 (final cleanup): upgrade to error and forbid merges that introduce + // new bare fetch('/api/...') sites. + // Selector rationale: + // - covers single-quoted, double-quoted, and template-literal forms + // - filters by /api prefix so cross-origin / external fetches stay untouched + // - exempts api-client.ts itself (the one allowed implementer) + { + files: ['src/**/*.{ts,tsx,js,jsx}'], + ignores: ['src/lib/api-client.ts'], + rules: { + 'no-restricted-syntax': [ + 'warn', + { + selector: + "CallExpression[callee.name='fetch'] > Literal[value=/^\\/api\\//]", + message: + "Use apiFetch() from '@/lib/api-client' instead of bare fetch('/api/...'). It handles 401 redirect, 403/5xx typed errors, and network failures uniformly. See PR-api-client.md.", + }, + { + selector: + "CallExpression[callee.name='fetch'] > TemplateLiteral.arguments:first-child[quasis.0.value.raw=/^\\/api\\//]", + message: + "Use apiFetch() from '@/lib/api-client' instead of bare fetch(`/api/...`). It handles 401 redirect, 403/5xx typed errors, and network failures uniformly.", + }, + ], + }, + }, ] export default config diff --git a/src/app/layout.tsx b/src/app/layout.tsx index e80a841622..70401fa04d 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -6,6 +6,7 @@ import { NextIntlClientProvider } from 'next-intl' import { getLocale, getMessages } from 'next-intl/server' import { THEME_IDS } from '@/lib/themes' import { ThemeBackground } from '@/components/ui/theme-background' +import { AuthExpiredListener } from '@/components/auth-expired-listener' import './globals.css' const inter = Inter({ @@ -114,6 +115,7 @@ export default async function RootLayout({ disableTransitionOnChange > +
{children}
diff --git a/src/components/auth-expired-listener.tsx b/src/components/auth-expired-listener.tsx new file mode 100644 index 0000000000..f376983084 --- /dev/null +++ b/src/components/auth-expired-listener.tsx @@ -0,0 +1,33 @@ +'use client' + +import { useEffect } from 'react' + +/** + * Listens for `mc:auth-expired` CustomEvent dispatched by `apiFetch()` when the + * server returns 401. The redirect to `/login?from=...` is already handled inside + * `apiFetch`; this listener exists so we have a single observability hook the + * team can extend (toast, telemetry, Sentry). + * + * Mounted once at the root layout. SSR-safe (effect runs only on the client). + * + * Why a separate component? + * - layout.tsx is a server component (uses `await headers()`); we cannot + * attach window listeners there directly. + * - Co-locating the listener with the api-client keeps the auth-failure + * contract in one place. + */ +export function AuthExpiredListener(): null { + useEffect(() => { + const onExpired = (e: Event) => { + const detail = (e as CustomEvent<{ path: string; status: number }>).detail + // No toast lib installed yet — log for now. Replace with sonner in next PR. + console.warn( + `[mc] session expired on ${detail?.path ?? 'unknown'} (status=${detail?.status ?? 401}), redirecting to /login` + ) + } + window.addEventListener('mc:auth-expired', onExpired) + return () => window.removeEventListener('mc:auth-expired', onExpired) + }, []) + + return null +} diff --git a/src/lib/__tests__/api-client.test.ts b/src/lib/__tests__/api-client.test.ts new file mode 100644 index 0000000000..a8f3bcee28 --- /dev/null +++ b/src/lib/__tests__/api-client.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { apiFetch, ApiError } from '../api-client' + +const realFetch = global.fetch +const realLocation = window.location + +function mockResponse(status: number, body: unknown = {}, opts: { json?: boolean } = { json: true }) { + return new Response(opts.json ? JSON.stringify(body) : String(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }) +} + +describe('apiFetch — global 401 / 403 / 5xx / network handling', () => { + let dispatched: CustomEvent[] = [] + let originalHref = '' + let authExpiredListener: ((e: Event) => void) | null = null + + beforeEach(() => { + dispatched = [] + authExpiredListener = (e) => dispatched.push(e as CustomEvent) + window.addEventListener('mc:auth-expired', authExpiredListener) + + // Stub location so redirect-to-login is observable + originalHref = window.location.href + Object.defineProperty(window, 'location', { + writable: true, + value: { + ...realLocation, + pathname: '/cost-tracker', + search: '', + href: 'http://127.0.0.1:3000/cost-tracker', + }, + }) + }) + + afterEach(() => { + if (authExpiredListener) { + window.removeEventListener('mc:auth-expired', authExpiredListener) + authExpiredListener = null + } + global.fetch = realFetch + Object.defineProperty(window, 'location', { writable: true, value: realLocation }) + window.location.href = originalHref + vi.restoreAllMocks() + }) + + it('returns parsed JSON on 200', async () => { + global.fetch = vi.fn().mockResolvedValue(mockResponse(200, { ok: true, count: 42 })) + const data = await apiFetch<{ ok: boolean; count: number }>('/api/tokens') + expect(data).toEqual({ ok: true, count: 42 }) + }) + + it('emits mc:auth-expired and redirects to /login on 401', async () => { + global.fetch = vi.fn().mockResolvedValue(mockResponse(401, { error: 'Authentication required' })) + await expect(apiFetch('/api/tokens')).rejects.toMatchObject({ + code: 'UNAUTHENTICATED', + status: 401, + }) + expect(dispatched).toHaveLength(1) + expect(dispatched[0].detail).toMatchObject({ path: '/api/tokens', status: 401 }) + expect(window.location.href).toContain('/login?from=%2Fcost-tracker') + }) + + it('does NOT redirect when redirectOnUnauthenticated=false', async () => { + global.fetch = vi.fn().mockResolvedValue(mockResponse(401, { error: 'Authentication required' })) + await expect( + apiFetch('/api/tokens', { redirectOnUnauthenticated: false }) + ).rejects.toThrow(ApiError) + expect(window.location.href).toBe('http://127.0.0.1:3000/cost-tracker') + }) + + it('throws FORBIDDEN on 403 without redirecting', async () => { + global.fetch = vi.fn().mockResolvedValue(mockResponse(403, { error: 'Requires admin role' })) + await expect(apiFetch('/api/tokens')).rejects.toMatchObject({ + code: 'FORBIDDEN', + status: 403, + }) + expect(window.location.href).toBe('http://127.0.0.1:3000/cost-tracker') + }) + + it('throws SERVER_ERROR on 500 with upstream message', async () => { + global.fetch = vi.fn().mockResolvedValue(mockResponse(500, { error: 'database is locked' })) + await expect(apiFetch('/api/tokens')).rejects.toMatchObject({ + code: 'SERVER_ERROR', + status: 500, + message: 'database is locked', + }) + }) + + it('throws NETWORK_ERROR when fetch rejects', async () => { + global.fetch = vi.fn().mockRejectedValue(new TypeError('Failed to fetch')) + await expect(apiFetch('/api/tokens')).rejects.toMatchObject({ + code: 'NETWORK_ERROR', + status: 0, + }) + }) + + it('does not redirect when already on /login (avoid infinite loop)', async () => { + Object.defineProperty(window, 'location', { + writable: true, + value: { ...realLocation, pathname: '/login', search: '', href: 'http://127.0.0.1:3000/login' }, + }) + global.fetch = vi.fn().mockResolvedValue(mockResponse(401)) + await expect(apiFetch('/api/auth/login', { method: 'POST' })).rejects.toThrow(ApiError) + expect(window.location.href).toBe('http://127.0.0.1:3000/login') + }) + + it('returns undefined for 204 No Content', async () => { + global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 })) + const data = await apiFetch('/api/sessions/123', { method: 'DELETE' }) + expect(data).toBeUndefined() + }) +}) diff --git a/src/lib/api-client.ts b/src/lib/api-client.ts new file mode 100644 index 0000000000..1e3edcc46f --- /dev/null +++ b/src/lib/api-client.ts @@ -0,0 +1,145 @@ +/** + * API client with global 401 / 403 / network handling. + * + * Why this exists + * --------------- + * Mission Control had no global auth-failure handler. When a session expired, + * `fetch('/api/...')` returned 401 silently and panels (cost-tracker, dashboard, + * activities) stuck on loading skeletons forever — users perceived "the service + * died" but the backend was healthy. Root cause logged in: + * src/lib/auth.ts:629 requireRole() + * + * Contract + * -------- + * apiFetch(path, init?) -> Promise + * + * - Always sends cookies (credentials: 'include') + * - On 401: emits an `mc:auth-expired` CustomEvent, redirects to /login?from=… + * - On 403: throws ApiError with code='FORBIDDEN' + * - On 5xx: throws ApiError with code='SERVER_ERROR' and the upstream message + * - On network failure: throws ApiError with code='NETWORK_ERROR' + * + * Listen once at app root: + * window.addEventListener('mc:auth-expired', () => showToast('Session expired')) + */ + +export type ApiErrorCode = + | 'UNAUTHENTICATED' + | 'FORBIDDEN' + | 'NOT_FOUND' + | 'SERVER_ERROR' + | 'NETWORK_ERROR' + | 'PARSE_ERROR' + +export class ApiError extends Error { + readonly code: ApiErrorCode + readonly status: number + readonly payload: unknown + + constructor(code: ApiErrorCode, status: number, message: string, payload?: unknown) { + super(message) + this.name = 'ApiError' + this.code = code + this.status = status + this.payload = payload + } +} + +// Browser-only redirect to /login. SSR / unit tests skip it. +function redirectToLogin(): void { + if (typeof window === 'undefined') return + const from = window.location.pathname + window.location.search + // Avoid redirect loops if user is already on /login + if (window.location.pathname === '/login') return + window.location.href = `/login?from=${encodeURIComponent(from)}` +} + +function emitAuthExpired(detail: { path: string; status: number }): void { + if (typeof window === 'undefined') return + window.dispatchEvent(new CustomEvent('mc:auth-expired', { detail })) +} +export interface ApiFetchOptions extends RequestInit { + /** When true (default) and the response is 401, redirect to /login. */ + redirectOnUnauthenticated?: boolean + /** When true, return raw Response instead of parsed JSON. */ + raw?: boolean +} + +export async function apiFetch( + path: string, + options: ApiFetchOptions = {} +): Promise { + const { + redirectOnUnauthenticated = true, + raw = false, + headers, + ...rest + } = options + + let response: Response + try { + response = await fetch(path, { + credentials: 'include', + headers: { + Accept: 'application/json', + ...(rest.body && !(rest.body instanceof FormData) + ? { 'Content-Type': 'application/json' } + : {}), + ...headers, + }, + ...rest, + }) + } catch (err) { + throw new ApiError( + 'NETWORK_ERROR', + 0, + err instanceof Error ? err.message : 'Network request failed' + ) + } + + // 401 — emit event, optionally redirect, always throw + if (response.status === 401) { + emitAuthExpired({ path, status: 401 }) + if (redirectOnUnauthenticated) redirectToLogin() + throw new ApiError('UNAUTHENTICATED', 401, 'Authentication required') + } + + // 403 — throw, do NOT redirect (user is logged in but lacks role) + if (response.status === 403) { + const payload = await safeParseJson(response) + throw new ApiError('FORBIDDEN', 403, 'Insufficient permissions', payload) + } + + if (response.status === 404) { + throw new ApiError('NOT_FOUND', 404, `Not found: ${path}`) + } + + if (response.status >= 500) { + const payload = await safeParseJson(response) + const msg = + (typeof payload === 'object' && payload !== null && 'error' in payload && + typeof (payload as { error: unknown }).error === 'string' + ? (payload as { error: string }).error + : null) || `Server error ${response.status}` + throw new ApiError('SERVER_ERROR', response.status, msg, payload) + } + + if (raw) return response as unknown as T + + if (response.status === 204) return undefined as T + + try { + return (await response.json()) as T + } catch { + throw new ApiError('PARSE_ERROR', response.status, 'Response was not valid JSON') + } +} + +async function safeParseJson(res: Response): Promise { + try { + return await res.json() + } catch { + return null + } +} + From 15885f15e3ff5fea6df49ad5d573b8a4a0fb2bec Mon Sep 17 00:00:00 2001 From: jun261930-tech Date: Sun, 17 May 2026 22:12:06 +0800 Subject: [PATCH 2/2] refactor(task-board-panel): migrate 26 bare fetch to apiFetch --- src/components/panels/task-board-panel.tsx | 107 +++++++++------------ 1 file changed, 46 insertions(+), 61 deletions(-) diff --git a/src/components/panels/task-board-panel.tsx b/src/components/panels/task-board-panel.tsx index 9638ed8390..f0ca38bd75 100644 --- a/src/components/panels/task-board-panel.tsx +++ b/src/components/panels/task-board-panel.tsx @@ -7,6 +7,7 @@ import { useMissionControl } from '@/store' import { useSmartPoll } from '@/lib/use-smart-poll' import { createClientLogger } from '@/lib/client-logger' +import { apiFetch } from '@/lib/api-client' import { useFocusTrap } from '@/lib/use-focus-trap' @@ -135,11 +136,10 @@ function useAgentSessions(agentName: string | undefined) { useEffect(() => { if (!agentName) { setSessions([]); return } let cancelled = false - fetch('/api/sessions') - .then(r => r.json()) + apiFetch<{ sessions?: Array<{ key: string; id: string; agent?: string; channel?: string; kind?: string; label?: string; active?: boolean }> }>('/api/sessions') .then(data => { if (cancelled) return - const all = (data.sessions || []) as Array<{ key: string; id: string; agent?: string; channel?: string; kind?: string; label?: string; active?: boolean }> + const all = data.sessions || [] const filtered = all.filter(s => s.agent?.toLowerCase() === agentName.toLowerCase() || s.key?.toLowerCase().includes(agentName.toLowerCase()) @@ -173,9 +173,7 @@ function useMentionTargets() { let cancelled = false const run = async () => { try { - const response = await fetch('/api/mentions?limit=200') - if (!response.ok) return - const data = await response.json() + const data = await apiFetch<{ mentions?: MentionOption[] }>('/api/mentions?limit=200') if (!cancelled) setMentionTargets(data.mentions || []) } catch { // mention autocomplete is non-critical @@ -340,10 +338,11 @@ function DunkItButton({ taskId, onDunked }: { taskId: number; onDunked: (id: num e.stopPropagation() if (phase !== 'idle') return try { - const res = await fetch(`/api/tasks/${taskId}`, { + const res = await apiFetch(`/api/tasks/${taskId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'done' }), + raw: true, }) if (!res.ok) throw new Error('Failed') setPhase('success') @@ -454,20 +453,12 @@ export function TaskBoardPanel() { } const tasksUrl = tasksQuery.toString() ? `/api/tasks?${tasksQuery.toString()}` : '/api/tasks' - const [tasksResponse, agentsResponse, projectsResponse] = await Promise.all([ - fetch(tasksUrl), - fetch('/api/agents'), - fetch('/api/projects') + const [tasksData, agentsData, projectsData] = await Promise.all([ + apiFetch<{ tasks?: Task[] }>(tasksUrl), + apiFetch<{ agents?: Agent[] }>('/api/agents'), + apiFetch<{ projects?: Project[] }>('/api/projects') ]) - if (!tasksResponse.ok || !agentsResponse.ok || !projectsResponse.ok) { - throw new Error('Failed to fetch data') - } - - const tasksData = await tasksResponse.json() - const agentsData = await agentsResponse.json() - const projectsData = await projectsResponse.json() - const tasksList = tasksData.tasks || [] const taskIds = tasksList.map((task: Task) => task.id) @@ -477,8 +468,7 @@ export function TaskBoardPanel() { setProjects(projectsData.projects || []) if (taskIds.length > 0) { - fetch(`/api/quality-review?taskIds=${taskIds.join(',')}`) - .then((reviewResponse) => reviewResponse.ok ? reviewResponse.json() : null) + apiFetch<{ latest?: Record }>(`/api/quality-review?taskIds=${taskIds.join(',')}`) .then((reviewData) => { const latest = reviewData?.latest || {} const newAegisMap: Record = Object.fromEntries( @@ -508,8 +498,7 @@ export function TaskBoardPanel() { // Fetch GNAP status useEffect(() => { - fetch('/api/gnap') - .then(r => r.ok ? r.json() : null) + apiFetch('/api/gnap') .then(data => { if (data) setGnapStatus(data) }) .catch(() => {}) }, []) @@ -517,7 +506,7 @@ export function TaskBoardPanel() { const handleGnapSync = useCallback(async () => { setGnapSyncing(true) try { - const res = await fetch('/api/gnap?action=sync', { method: 'POST' }) + const res = await apiFetch('/api/gnap?action=sync', { method: 'POST', raw: true }) if (res.ok) { const data = await res.json() setGnapStatus(prev => prev ? { ...prev, taskCount: data.pushed, lastSync: data.lastSync } : prev) @@ -604,11 +593,7 @@ export function TaskBoardPanel() { try { if (newStatus === 'done') { - const reviewResponse = await fetch(`/api/quality-review?taskId=${draggedTask.id}`) - if (!reviewResponse.ok) { - throw new Error('Unable to verify Aegis approval') - } - const reviewData = await reviewResponse.json() + const reviewData = await apiFetch<{ reviews?: any[] }>(`/api/quality-review?taskId=${draggedTask.id}`) const latest = reviewData.reviews?.find((review: any) => review.reviewer === 'aegis') if (!latest || latest.status !== 'approved') { throw new Error('Aegis approval is required before moving to done') @@ -622,12 +607,13 @@ export function TaskBoardPanel() { }) // Update on server - const response = await fetch('/api/tasks', { + const response = await apiFetch('/api/tasks', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tasks: [{ id: draggedTask.id, status: newStatus }] - }) + }), + raw: true, }) if (!response.ok) { @@ -677,12 +663,11 @@ export function TaskBoardPanel() { }) try { - const response = await fetch('/api/spawn', { + const result = await apiFetch<{ success?: boolean; agent?: string; sessionKey?: string; sessionInfo?: any; error?: string }>('/api/spawn', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(spawnFormData), }) - const result = await response.json() if (result.success) { updateSpawnRequest(spawnId, { @@ -1235,9 +1220,7 @@ function TaskDetailModal({ const fetchReviews = useCallback(async () => { try { - const response = await fetch(`/api/quality-review?taskId=${task.id}`) - if (!response.ok) throw new Error('Failed to fetch reviews') - const data = await response.json() + const data = await apiFetch<{ reviews: any[] }>(`/api/quality-review?taskId=${task.id}`) setReviews(data.reviews || []) } catch (error) { setReviewError('Failed to load quality reviews') @@ -1247,9 +1230,7 @@ function TaskDetailModal({ const fetchComments = useCallback(async () => { try { setLoadingComments(true) - const response = await fetch(`/api/tasks/${task.id}/comments`) - if (!response.ok) throw new Error('Failed to fetch comments') - const data = await response.json() + const data = await apiFetch<{ comments: any[] }>(`/api/tasks/${task.id}/comments`) setComments(data.comments || []) } catch (error) { setCommentError('Failed to load comments') @@ -1273,13 +1254,14 @@ function TaskDetailModal({ try { setCommentError(null) - const response = await fetch(`/api/tasks/${task.id}/comments`, { + const response = await apiFetch(`/api/tasks/${task.id}/comments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ author: commentAuthor || 'system', content: commentText - }) + }), + raw: true, }) if (!response.ok) throw new Error('Failed to add comment') setCommentText('') @@ -1296,13 +1278,14 @@ function TaskDetailModal({ try { setBroadcastStatus(null) - const response = await fetch(`/api/tasks/${task.id}/broadcast`, { + const response = await apiFetch(`/api/tasks/${task.id}/broadcast`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ author: commentAuthor || 'system', message: broadcastMessage - }) + }), + raw: true, }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Broadcast failed') @@ -1317,7 +1300,7 @@ function TaskDetailModal({ e.preventDefault() try { setReviewError(null) - const response = await fetch('/api/quality-review', { + const response = await apiFetch('/api/quality-review', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -1325,7 +1308,8 @@ function TaskDetailModal({ reviewer, status: reviewStatus, notes: reviewNotes - }) + }), + raw: true, }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Failed to submit review') @@ -1460,7 +1444,7 @@ function TaskDetailModal({ onClick={async () => { if (!confirm(t('deleteTaskConfirm', { title: task.title }))) return try { - const res = await fetch(`/api/tasks/${task.id}`, { method: 'DELETE' }) + const res = await apiFetch(`/api/tasks/${task.id}`, { method: 'DELETE', raw: true }) if (!res.ok) { const errorData = await res.json().catch(() => ({ error: 'Failed to delete task' })) throw new Error(errorData.error || 'Failed to delete task') @@ -1500,10 +1484,11 @@ function TaskDetailModal({