captcha.ts 8.06 KB
import { randomBytes, randomInt, timingSafeEqual } from 'node:crypto';

/**
 * 图形验证码(服务端签发 + 服务端校验)。
 *
 * 设计要点,逐条都对应一种真实攻击:
 *
 * 1. **码只存在服务端**。接口回给前端的是 `{ id, image }`,`image` 是服务端渲染好的
 *    SVG data URI。前端拿不到明文码,也就没法「本地比对」——那种写法(把答案塞进
 *    JS 变量再在浏览器里比)等于没做验证码,任何人看一眼源码就能绕。
 * 2. **一次性 + 有 TTL**。验证成功即销毁;错满 MAX_TRIES 次也销毁。否则一张图可以被
 *    无限次试(32^4 的空间,慢慢试总能中)。
 * 3. **按 IP 限流签发**。防止有人写脚本狂拉 /api/captcha 把内存撑爆,也顺手把
 *    自动化爆破的单 IP 吞吐压到没有意义。
 * 4. **常量时间比较**。用 timingSafeEqual,避免按字节提前返回泄露信息(这里是 4 位码,
 *    收益有限,但成本为零)。
 *
 * 注意:验证码不是密码的替代品。它挡的是「脚本批量撞库」,挡不住「针对单个账号的
 * 人工社工」。登录失败计数(index.ts 里的 rateLimit)是另一层,两者都要有。
 */

/** 去掉易混字符:0/O、1/I/l、2/Z、5/S、8/B 在噪点图里会被看错 */
const ALPHABET = '346789ACDEFGHJKMNPQRTUVWXY';
const CODE_LENGTH = 4;
const TTL_MS = 2 * 60 * 1000;
/** 同一张图允许试错次数,超了必须换图 */
const MAX_TRIES = 3;
/** 内存里最多同时挂多少张未使用的图,超了淘汰最早的(Map 保持插入序) */
const MAX_PENDING = 3000;
/** 单 IP 每分钟签发上限 */
const ISSUE_LIMIT = 40;

interface Entry {
  code: string;
  expiresAt: number;
  tries: number;
}

const store = new Map<string, Entry>();
const issueWindow = new Map<string, { count: number; resetAt: number }>();

export interface CaptchaChallenge {
  id: string;
  /** `data:image/svg+xml;base64,...`,可直接塞进 <img src> */
  image: string;
  /** 秒,给前端做倒计时提示用 */
  expiresIn: number;
}

export type CaptchaVerdict = 'ok' | 'invalid' | 'expired' | 'missing';

export class CaptchaRateLimited extends Error {
  constructor() {
    super('captcha_rate_limited');
  }
}

function issueAllowed(ip: string): boolean {
  const now = Date.now();
  const rec = issueWindow.get(ip);
  if (!rec || now >= rec.resetAt) {
    issueWindow.set(ip, { count: 1, resetAt: now + 60_000 });
    return true;
  }
  if (rec.count >= ISSUE_LIMIT) return false;
  rec.count += 1;
  return true;
}

function sweep(now: number): void {
  for (const [id, entry] of store) {
    if (entry.expiresAt <= now) store.delete(id);
  }
  for (const [ip, rec] of issueWindow) {
    if (rec.resetAt <= now) issueWindow.delete(ip);
  }
}

/**
 * 定时清理。`unref()` 很关键:不然这个 interval 会把 Node 进程钉死,
 * 容器里 `docker stop` 要等到超时才退,本地 tsx 也会挂住终端。
 */
const sweeper = setInterval(() => sweep(Date.now()), 60_000);
sweeper.unref();

function pick<T>(arr: readonly T[]): T {
  return arr[randomInt(0, arr.length)];
}

function rand(min: number, max: number): number {
  return min + Math.random() * (max - min);
}

function buildCode(): string {
  let out = '';
  for (let i = 0; i < CODE_LENGTH; i += 1) out += ALPHABET[randomInt(0, ALPHABET.length)];
  return out;
}

/** 噪点颜色都偏深偏灰蓝,保证在黑字与浅底之间有足够对比,不做成「一片糊」 */
const INK = ['#1f2a5e', '#2b3a7a', '#39406b', '#4653a2', '#243049', '#3c2f5e'];
const NOISE = ['#8f9bc4', '#a9b4d6', '#6f7bab', '#c0c8e0'];

function buildSvg(code: string): string {
  const W = 132;
  const H = 44;

  const chars = [...code].map((ch, i) => {
    // 字符故意轻微重叠(步长 26 < 字宽 ~27),配合旋转就断开了「逐字切分」这条路。
    // 字号取 25~29:图在登录框里只显示 108×36,源图字号再小一档,缩放后 4 个字符就
    // 挤成一条毛边(实测 23~27 时第 4 位最容易认错)。
    const x = 15 + i * 26 + rand(-2.5, 2.5);
    const y = 31 + rand(-2.5, 2.5);
    const rot = rand(-24, 24);
    const size = rand(25, 29);
    return `<text x="${x.toFixed(1)}" y="${y.toFixed(1)}" font-size="${size.toFixed(
      1,
    )}" font-weight="700" fill="${pick(INK)}" transform="rotate(${rot.toFixed(
      1,
    )} ${x.toFixed(1)} ${y.toFixed(1)})">${ch}</text>`;
  });

  const curves = Array.from({ length: 3 }, () => {
    const y1 = rand(6, H - 6);
    const y2 = rand(6, H - 6);
    return `<path d="M${rand(-8, 4).toFixed(1)} ${y1.toFixed(1)} C ${rand(24, 48).toFixed(
      1,
    )} ${rand(-4, H + 4).toFixed(1)}, ${rand(84, 108).toFixed(1)} ${rand(-4, H + 4).toFixed(
      1,
    )}, ${rand(W - 4, W + 8).toFixed(1)} ${y2.toFixed(
      1,
    )}" fill="none" stroke="${pick(NOISE)}" stroke-width="${rand(0.8, 1.5).toFixed(
      2,
    )}" stroke-linecap="round" opacity="${rand(0.5, 0.9).toFixed(2)}"/>`;
  }).join('');

  const dots = Array.from({ length: 34 }, () => {
    return `<circle cx="${rand(0, W).toFixed(1)}" cy="${rand(0, H).toFixed(
      1,
    )}" r="${rand(0.5, 1.4).toFixed(2)}" fill="${pick(NOISE)}" opacity="${rand(
      0.35,
      0.8,
    ).toFixed(2)}"/>`;
  }).join('');

  // 中间横穿一条干扰线:专门打掉「按行投影切字符」的简单 OCR
  const strikeY = rand(14, 30).toFixed(1);

  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" role="img">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#f6f8fd"/><stop offset="52%" stop-color="#eaeef9"/><stop offset="100%" stop-color="#dde4f4"/>
</linearGradient>
<filter id="warp" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="${randomInt(
    1,
    99,
  )}" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="1.6" xChannelSelector="R" yChannelSelector="G"/>
</filter>
</defs>
<rect width="${W}" height="${H}" fill="url(#bg)"/>
<g opacity="0.55">${dots}</g>
<g>${curves}</g>
<g filter="url(#warp)" font-family="'DejaVu Sans Mono','Liberation Mono',Consolas,'Courier New',monospace" letter-spacing="0.5">${chars}</g>
<line x1="${rand(4, 14).toFixed(1)}" y1="${strikeY}" x2="${rand(W - 14, W - 4).toFixed(
    1,
  )}" y2="${rand(14, 30).toFixed(1)}" stroke="${pick(NOISE)}" stroke-width="1.1" opacity="0.75"/>
</svg>`;
}

export function createCaptcha(ip: string): CaptchaChallenge {
  if (!issueAllowed(ip)) throw new CaptchaRateLimited();

  const now = Date.now();
  if (store.size >= MAX_PENDING) sweep(now);
  while (store.size >= MAX_PENDING) {
    const oldest = store.keys().next();
    if (oldest.done) break;
    store.delete(oldest.value);
  }

  const id = randomBytes(16).toString('hex');
  const code = buildCode();
  store.set(id, { code, expiresAt: now + TTL_MS, tries: 0 });

  return {
    id,
    image: `data:image/svg+xml;base64,${Buffer.from(buildSvg(code), 'utf-8').toString('base64')}`,
    expiresIn: Math.floor(TTL_MS / 1000),
  };
}

/**
 * 校验并消耗。返回值刻意区分 expired / invalid:
 * 前端据此决定提示语(「已过期,已换一张」vs「填错了」),但两者都不是安全信息,
 * 攻击者本来就知道自己的码有没有过期。
 */
export function verifyCaptcha(id: string | undefined, input: string | undefined): CaptchaVerdict {
  if (!id || !input) return 'missing';

  const entry = store.get(id);
  if (!entry) return 'expired';
  if (entry.expiresAt <= Date.now()) {
    store.delete(id);
    return 'expired';
  }

  entry.tries += 1;
  const normalized = input.trim().toUpperCase();
  const expected = Buffer.from(entry.code, 'utf-8');
  const actual = Buffer.from(normalized, 'utf-8');
  const matched =
    expected.length === actual.length && timingSafeEqual(expected, actual);

  if (matched) {
    store.delete(id);
    return 'ok';
  }
  if (entry.tries >= MAX_TRIES) store.delete(id);
  return 'invalid';
}

/** 仅测试用:清空所有未使用的挑战 */
export function __resetCaptchaStore(): void {
  store.clear();
  issueWindow.clear();
}