captcha.ts 970 Bytes
/**
 * 登录验证码客户端。
 *
 * 只有一件事:向 `/api/captcha` 要一张图。**前端不生成、也不校验**——码的明文由服务端
 * 持有,登录时把 `id + 用户输入` 一起回传,由服务端比对。任何「前端画一张、前端比对」
 * 的写法都不构成验证。
 */

export interface CaptchaImage {
  id: string;
  /** `data:image/svg+xml;base64,...` */
  image: string;
  /** 有效期(秒) */
  expiresIn: number;
}

export async function fetchCaptcha(signal?: AbortSignal): Promise<CaptchaImage> {
  const res = await fetch('/api/captcha', {
    // 验证码必须每次都是新的:禁用缓存,也不允许中间层复用
    cache: 'no-store',
    credentials: 'same-origin',
    signal,
  });
  if (!res.ok) {
    if (res.status === 429) throw new Error('验证码请求过于频繁,请稍后再试');
    throw new Error('验证码加载失败');
  }
  return (await res.json()) as CaptchaImage;
}