/** 统一同源客户端。会话只放 HttpOnly Cookie;API Key 不进入前端环境或 localStorage。 */ export class ApiError extends Error { readonly status: number readonly code: string constructor(status: number, code: string, message: string) { super(message); this.status = status; this.code = code } } let csrf: { token: string; headerName: string } | null = null export async function refreshCsrf() { const response = await fetch('/api/auth/csrf', { credentials: 'same-origin' }) if (!response.ok) throw new ApiError(response.status, 'CSRF_UNAVAILABLE', '无法连接登录服务,请检查后端是否启动') csrf = await response.json() } /** 不自动重试写请求,尤其是可能收费的任务;幂等重试必须沿用调用方保留的键。 */ export async function api(path: string, options: RequestInit = {}): Promise { const method = (options.method ?? 'GET').toUpperCase() const headers = new Headers(options.headers) if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) { if (!csrf) await refreshCsrf() if (csrf) headers.set(csrf.headerName, csrf.token) if (options.body && !(options.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json') } let response: Response try { response = await fetch(`/api${path}`, { ...options, method, headers, credentials: 'same-origin' }) } catch { throw new ApiError(0, 'NETWORK_ERROR', '网络连接失败,请检查后端;提交结果未知时请保留原任务键重试') } const data = await response.json().catch(() => ({})) if (!response.ok) { if (response.status === 401 && path !== '/auth/login') window.dispatchEvent(new Event('session-expired')) if (response.status === 403) csrf = null throw new ApiError(response.status, data.code ?? 'REQUEST_FAILED', data.message ?? '服务请求失败,请稍后重试') } return data as T } export async function login(username: string, password: string) { await refreshCsrf() await api('/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ username, password }), }) // Spring Security 在认证成功后轮换会话与 CSRF token,必须重新获取。 csrf = null await refreshCsrf() } export async function logout() { await api('/auth/logout', { method: 'POST' }) csrf = null }