import type { NextFunction, Request, RequestHandler, Response } from "express"; /** * 内存滑动窗口限流器(防刷)。 * * 按 (动作名, IP) 维度维护每个窗口内的请求时间戳: * - 窗口内请求数达到 max 时返回 429; * - 时间戳滑出窗口后自动放行(滑动窗口,无需定时器); * - 周期性清理空桶,防止内存无限增长。 * * 内存实现适合单进程部署;多进程/多实例部署时应换成 Redis 等共享存储。 */ /** 限流配置 */ export interface RateLimitConfig { /** 窗口大小(毫秒) */ windowMs: number; /** 窗口内每个 IP 允许的最大请求数 */ max: number; } /** * 各动作的限流配置(单位:次/小时/IP)。 * 常量导出供路由与测试共用。 */ export const RATE_LIMITS = { /** 兑换码兑换:10 次/小时/IP */ redeem: { windowMs: 60 * 60 * 1000, max: 10 }, /** 兑换码核销(下载消耗):30 次/小时/IP */ consume: { windowMs: 60 * 60 * 1000, max: 30 }, /** 创建支付订单:5 次/小时/IP */ orders: { windowMs: 60 * 60 * 1000, max: 5 }, /** AI 生成:10 次/小时/IP */ chibiGenerate: { windowMs: 60 * 60 * 1000, max: 10 }, } as const; /** 429 响应文案 */ export const RATE_LIMIT_MESSAGE = "操作过于频繁,请稍后再试"; /** * 限流中间件工厂。 * 用法:createRateLimiter(RATE_LIMITS.redeem)("redeem") * 返回的中间件以 action 名称 + req.ip 为键独立计数。 */ export function createRateLimiter(config: RateLimitConfig): (action: string) => RequestHandler { /** key = `${action}:${ip}` → 窗口内请求时间戳(升序) */ const buckets = new Map(); let lastCleanup = Date.now(); const pruneExpired = (now: number): void => { for (const [key, timestamps] of buckets) { while (timestamps.length > 0 && timestamps[0]! <= now - config.windowMs) { timestamps.shift(); } if (timestamps.length === 0) { buckets.delete(key); } } }; return (action: string): RequestHandler => { return (req: Request, res: Response, next: NextFunction): void => { const now = Date.now(); // 周期性清理过期桶(每个窗口周期一次,摊销成本) if (now - lastCleanup > config.windowMs) { pruneExpired(now); lastCleanup = now; } const ip = req.ip ?? "unknown"; const key = `${action}:${ip}`; // 剔除已滑出窗口的时间戳 const timestamps = buckets.get(key) ?? []; while (timestamps.length > 0 && timestamps[0]! <= now - config.windowMs) { timestamps.shift(); } if (timestamps.length >= config.max) { res.status(429).json({ error: RATE_LIMIT_MESSAGE }); return; } timestamps.push(now); buckets.set(key, timestamps); next(); }; }; }