Files
pangolin/web/usercenter/lib/api/http.ts
T
wangjia e2646346a6 feat(web/usercenter): Next.js 用户中心静态导出 + mock/http 双数据层 (tsk_3FIPC8lSnAfJ)
新建 web/usercenter/:Next.js App Router + output:'export' 纯静态导出,
直接复用 design/ui_kits/usercenter React 源码(概览/订阅/兑换/邀请/设置)。

阶段 A(mock,本提交):
- 复刻五大页面,明/暗 × zh/en 四态;colors_and_type.css 原样链入;
  顶栏主题切换 + 语言段控,移动端底部 Tab + 左右滑动切换。
- 设置页新增:偏好(语言/主题) + 设备管理(列表/移除/二次确认+刷新) +
  TOTP 2FA(绑定二维码占位+密钥/验证/解禁),登录二段式 TOTP。
- 数据层 lib/api:ApiClient 抽象 + MockClient/HttpClient 双实现,构建期
  NEXT_PUBLIC_API_MODE 切换;统一错误体 {code,message_zh,message_en} → 双语映射。
- 会话:access token 仅内存,refresh header token + localStorage,静默续期,
  登出失效(取舍:静态导出无服务端 cookie 能力,详见 README)。
- 安全:构建期注入 SRI(sha384);_headers 严格 CSP + 安全基线;
  红线词扫描(铁律13) CI 红线,零命中。

阶段 B(占位待联调):HttpClient 已写好域名池+退避重试+401 续期;
TOTP/登录二段式端点占位待 #1 契约增补;me/redeem/devices 切真实链路依赖 #2/#3/#4。

验证:npm run lint / redline / build 均通过,静态产物 out/ 无服务端依赖。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 15:23:18 +08:00

171 lines
5.8 KiB
TypeScript

// http.ts — HttpClient:真实后端薄客户端(阶段 B 联调)。
// 特性:API 域名池(故障转移) + 指数退避重试 + 统一错误体解析 + 静默续期。
import {
ApiClient,
ApiError,
ApiErrorBody,
Device,
LoginResult,
Me,
RedeemResult,
Session,
SubscriptionInfo,
TotpSetup,
} from './types';
import {
accessValid,
clearSession,
getAccessToken,
getRefreshToken,
setSession,
} from './session';
function domains(): string[] {
const raw = process.env.NEXT_PUBLIC_API_DOMAINS || '';
const list = raw.split(',').map((s) => s.trim()).filter(Boolean);
return list.length ? list : ['/api'];
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
interface ReqOpts {
method?: string;
body?: unknown;
auth?: boolean;
/** 401 时是否尝试静默续期后重放(默认 true,refresh 自身置 false 防递归) */
allowRefresh?: boolean;
refreshToken?: string;
}
export class HttpClient implements ApiClient {
private refreshing: Promise<Session> | null = null;
/** 跨域名池 + 退避的核心请求 */
private async request<T>(path: string, opts: ReqOpts = {}): Promise<T> {
const { method = 'GET', body, auth = true, allowRefresh = true } = opts;
if (auth && !accessValid() && getRefreshToken()) {
await this.ensureFresh();
}
const pool = domains();
let lastErr: unknown;
for (let attempt = 0; attempt < pool.length * 2; attempt++) {
const base = pool[attempt % pool.length];
try {
const headers: Record<string, string> = { Accept: 'application/json' };
if (body !== undefined) headers['Content-Type'] = 'application/json';
const token = getAccessToken();
if (auth && token) headers['Authorization'] = `Bearer ${token}`;
if (opts.refreshToken) headers['X-Refresh-Token'] = opts.refreshToken;
const res = await fetch(base + path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
credentials: 'omit',
});
if (res.status === 401 && auth && allowRefresh && getRefreshToken()) {
await this.ensureFresh(true);
// 续期后重放一次(不再允许二次续期)
return this.request<T>(path, { ...opts, allowRefresh: false });
}
if (!res.ok) throw await this.toApiError(res);
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
} catch (err) {
lastErr = err;
// 业务错误(ApiError)不重试;仅网络/5xx 才退避换域名
if (err instanceof ApiError && err.code !== 'network') throw err;
await sleep(Math.min(1000 * 2 ** attempt, 4000));
}
}
throw lastErr instanceof ApiError
? lastErr
: new ApiError({ code: 'network', message_zh: '网络异常,请稍后重试', message_en: 'Network error, please retry' });
}
private async toApiError(res: Response): Promise<ApiError> {
let bodyJson: Partial<ApiErrorBody> = {};
try {
bodyJson = await res.json();
} catch {
/* non-json error */
}
const code = bodyJson.code || (res.status === 401 ? 'unauthorized' : 'unknown');
const retryAfter = Number(res.headers.get('Retry-After')) || undefined;
return new ApiError(
{
code,
message_zh: bodyJson.message_zh || '',
message_en: bodyJson.message_en || '',
},
retryAfter,
);
}
private ensureFresh(force = false): Promise<Session> {
if (!force && accessValid()) return Promise.resolve(null as unknown as Session);
if (this.refreshing) return this.refreshing;
this.refreshing = this.refresh().finally(() => {
this.refreshing = null;
});
return this.refreshing;
}
async login(email: string, password: string): Promise<LoginResult> {
const r = await this.request<
{ kind: 'session'; session: Session } | { kind: 'totp_required'; pending_token: string }
>('/v1/auth/login', { method: 'POST', body: { email, password }, auth: false });
if ('pending_token' in r) return { kind: 'totp_required', pendingToken: r.pending_token };
setSession(r.session);
return r;
}
async loginTotp(pendingToken: string, code: string): Promise<Session> {
const s = await this.request<Session>('/v1/auth/login/totp', {
method: 'POST',
body: { pending_token: pendingToken, code },
auth: false,
});
setSession(s);
return s;
}
async refresh(): Promise<Session> {
const rt = getRefreshToken();
if (!rt) throw new ApiError({ code: 'unauthorized', message_zh: '登录已失效', message_en: 'Session expired' });
const s = await this.request<Session>('/v1/auth/refresh', {
method: 'POST',
auth: false,
allowRefresh: false,
refreshToken: rt,
});
setSession(s);
return s;
}
getMe = () => this.request<Me>('/v1/me');
getSubscription = () => this.request<SubscriptionInfo>('/v1/me/subscription');
resetSubscription = () => this.request<SubscriptionInfo>('/v1/me/subscription/reset', { method: 'POST' });
listDevices = () => this.request<Device[]>('/v1/me/devices');
removeDevice = (id: string) => this.request<void>(`/v1/me/devices/${encodeURIComponent(id)}`, { method: 'DELETE' });
redeem = (code: string) => this.request<RedeemResult>('/v1/me/redeem', { method: 'POST', body: { code } });
// 契约增补待 #1 合入:POST /v1/me/totp/setup|verify|disable
totpSetup = () => this.request<TotpSetup>('/v1/me/totp/setup', { method: 'POST' });
totpVerify = (code: string) => this.request<void>('/v1/me/totp/verify', { method: 'POST', body: { code } });
totpDisable = (code: string) => this.request<void>('/v1/me/totp/disable', { method: 'POST', body: { code } });
async logout(): Promise<void> {
try {
await this.request<void>('/v1/auth/logout', { method: 'POST' });
} finally {
clearSession();
}
}
}