// ============================================================================ // JWT 令牌存储 —— 内存 + localStorage 折中方案 // ---------------------------------------------------------------------------- // 权衡(XSS vs 刷新留存): // - 纯内存:最抗 XSS(脚本注入也读不到跨标签持久令牌),但刷新即丢失,体验差。 // - 纯 localStorage:刷新留存,但任意 XSS 脚本可读取令牌 → 失窃风险高。 // - httpOnly Cookie:最抗 XSS(JS 读不到),但需后端配合 Set-Cookie + CSRF 防护, // 当前后端契约是「Authorization: Bearer」头(P2 报告),不下发 Cookie,故本期不用。 // 本期折中:运行内存为权威副本(请求注入用内存),localStorage 仅作刷新后的恢复源。 // - 收益:刷新不掉登录态。 // - 残留风险:XSS 仍可读 localStorage —— 缓解项见 README「安全权衡」: // 生产建议短有效期 + 后端轮转 + CSP 限制脚本来源;长期演进到 httpOnly Cookie + 刷新令牌。 // ============================================================================ const STORAGE_KEY = 'eip4_token'; const PROFILE_KEY = 'eip4_profile'; export interface UserProfile { userId: string; account: string; name: string; roles: string[]; } // 内存权威副本(请求注入读这里,避免每次同步访问 localStorage) let memoryToken: string | null = null; let memoryProfile: UserProfile | null = null; export function setSession(token: string, profile: UserProfile): void { memoryToken = token; memoryProfile = profile; try { localStorage.setItem(STORAGE_KEY, token); localStorage.setItem(PROFILE_KEY, JSON.stringify(profile)); } catch { // localStorage 不可用(隐私模式等)时退化为纯内存,登录态随刷新丢失,不阻断功能。 } } export function getToken(): string | null { if (memoryToken) return memoryToken; try { memoryToken = localStorage.getItem(STORAGE_KEY); } catch { memoryToken = null; } return memoryToken; } export function getProfile(): UserProfile | null { if (memoryProfile) return memoryProfile; try { const raw = localStorage.getItem(PROFILE_KEY); memoryProfile = raw ? (JSON.parse(raw) as UserProfile) : null; } catch { memoryProfile = null; } return memoryProfile; } export function clearSession(): void { memoryToken = null; memoryProfile = null; try { localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(PROFILE_KEY); } catch { // 忽略 } } export function isAuthenticated(): boolean { return !!getToken(); }