fix: 限流分桶按路由模式归一并统一清理过期计数

- 分桶键用路由模式(如 /health/escort-record/:id)而非真实 path,
  防止换订单 ID 绕开额度
- 计数桶统一登记、单定时器清理,windowMs 写入记录供过期判断
This commit is contained in:
lik
2026-11-08 12:00:26 +08:00
parent b0b706a1c4
commit 9a1242ffbc
2 changed files with 174 additions and 10 deletions
+52 -10
View File
@@ -10,16 +10,57 @@ import ResponseUtil from "../utils/responseUtil.js";
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
* 若后续横向扩容需换成 Redis 之类的共享计数)。
*/
const store = new Map();
const cleanupInterval = 60_000;
const cleanupTimer = setInterval(() => {
const now = Date.now();
for (const [key, record] of store.entries()) {
if (now - record.resetAt > record.windowMs) store.delete(key);
// 所有计数桶统一登记,由一个定时器清理,避免为每个 limiter 各起一个 timer
const stores = new Set();
function registerStore(buckets) {
stores.add(buckets);
return buckets;
}
/**
* 清理所有过期计数(社区版只做内存回收,不影响限流语义:
* 访问时本身也会按窗口重置)
* @param {number} [now] 当前时间(测试可注入)
* @returns {number} 清理的条目数
*/
function sweepRateLimitStores(now = Date.now()) {
let removed = 0;
for (const buckets of stores) {
for (const [key, record] of buckets) {
if (now - record.resetAt > record.windowMs) {
buckets.delete(key);
removed += 1;
}
}
}
}, 60_000);
return removed;
}
const cleanupTimer = setInterval(() => sweepRateLimitStores(), cleanupInterval);
cleanupTimer.unref();
// 路径里可能带订单 ID;路由没匹配到模式时(理论上不该发生)兜底归一
const OBJECT_ID_SEGMENT = /\/[0-9a-fA-F]{24}(?=\/|$)/g;
function normalizeDynamicPath(path) {
return String(path || "").replace(OBJECT_ID_SEGMENT, "/:id");
}
/**
* 限流分桶键
*
* 用路由模式(如 /health/escort-record/:id)而不是真实 path:
* 否则同一用户在不同订单上各有一份额度,换个 ID 就能绕过限流。
*/
function resolveBucketPath(ctx) {
return ctx.routerPath || ctx._matchedRoute || normalizeDynamicPath(ctx.path);
}
const store = registerStore(new Map());
/**
* 创建限流中间件
* @param {number} max 窗口内最大请求数
@@ -28,7 +69,7 @@ cleanupTimer.unref();
function rateLimit(max, windowMs = 60_000) {
return async (ctx, next) => {
const identity = ctx.state.user?._id ? `u:${ctx.state.user._id}` : `ip:${ctx.ip}`;
const key = `${identity}:${ctx.method}:${ctx.path}`;
const key = `${identity}:${ctx.method}:${resolveBucketPath(ctx)}`;
const now = Date.now();
let record = store.get(key);
@@ -58,13 +99,14 @@ function rateLimit(max, windowMs = 60_000) {
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
*/
function createUserLimiter(max, windowMs = 60_000) {
const buckets = new Map();
// windowMs 写进记录,供统一清理逻辑判断过期
const buckets = registerStore(new Map());
return (identity) => {
const now = Date.now();
let record = buckets.get(identity);
if (!record || now - record.resetAt > windowMs) {
record = { count: 0, resetAt: now };
record = { count: 0, resetAt: now, windowMs };
buckets.set(identity, record);
}
record.count++;
@@ -78,4 +120,4 @@ function createUserLimiter(max, windowMs = 60_000) {
};
}
export { rateLimit, createUserLimiter };
export { rateLimit, createUserLimiter, sweepRateLimitStores, normalizeDynamicPath };
+122
View File
@@ -0,0 +1,122 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
rateLimit,
createUserLimiter,
sweepRateLimitStores,
normalizeDynamicPath,
} from "../middleware/ratelimit.js";
const ID_A = "64b000000000000000000001";
const ID_B = "64b000000000000000000002";
function unique(prefix) {
return `${prefix}-${Date.now()}-${Math.random()}`;
}
function createCtx({
userId = null,
method = "PUT",
path = "/health/test",
routerPath = undefined,
ip = "203.0.113.9",
} = {}) {
return {
state: { user: userId ? { _id: userId } : null },
method,
path,
routerPath,
ip,
headers: {},
status: 200,
body: null,
set(name, value) {
this.headers[name] = value;
},
};
}
test("限流按路由模式分桶,换订单 ID 不能绕过", async () => {
const user = unique("route");
const middleware = rateLimit(1, 60_000);
const first = createCtx({
userId: user,
path: `/health/escort-record/${ID_A}`,
routerPath: "/health/escort-record/:id",
});
const second = createCtx({
userId: user,
path: `/health/escort-record/${ID_B}`,
routerPath: "/health/escort-record/:id",
});
await middleware(first, async () => {});
await middleware(second, async () => {});
assert.equal(first.body, null);
assert.equal(second.body.code, 429);
assert.ok(Number(second.headers["Retry-After"]) > 0);
});
test("拿不到路由模式时把 ObjectId 路径段归一成 :id", async () => {
const user = unique("fallback");
const middleware = rateLimit(1, 60_000);
const first = createCtx({ userId: user, path: `/health/escort-record/${ID_A}` });
const second = createCtx({ userId: user, path: `/health/escort-record/${ID_B}` });
await middleware(first, async () => {});
await middleware(second, async () => {});
assert.equal(first.body, null);
assert.equal(second.body.code, 429);
assert.equal(
normalizeDynamicPath(`/health/escort-record/${ID_A}/pay`),
"/health/escort-record/:id/pay"
);
});
test("不同路由各自独立计数", async () => {
const user = unique("separate");
const middleware = rateLimit(1, 60_000);
const recordRoute = createCtx({
userId: user,
path: `/health/escort-record/${ID_A}`,
routerPath: "/health/escort-record/:id",
});
const profileRoute = createCtx({
userId: user,
path: `/health/health-profile/${ID_A}`,
routerPath: "/health/health-profile/:id",
});
await middleware(recordRoute, async () => {});
await middleware(profileRoute, async () => {});
assert.equal(recordRoute.body, null);
assert.equal(profileRoute.body, null);
});
test("按用户限流在窗口内生效,过期后可重新计数", () => {
const limiter = createUserLimiter(2, 60_000);
const userId = unique("ws");
assert.equal(limiter(userId).allowed, true);
assert.equal(limiter(userId).allowed, true);
assert.equal(limiter(userId).allowed, false);
// 推进到窗口之外,清理后重新计数
sweepRateLimitStores(Date.now() + 120_000);
assert.equal(limiter(userId).allowed, true);
});
test("统一清理会回收用户限流的过期桶", () => {
const limiter = createUserLimiter(5, 1000);
limiter(unique("sweep"));
const removed = sweepRateLimitStores(Date.now() + 5000);
assert.ok(removed >= 1);
});