fix: 写接口限流、WS 有界与 token 不再进日志
新增进程内限流并挂到订单/档案写接口;WS 设 maxPayload、同连接串行处理、按用户限频;鉴权只读请求头并区分登录失效与用户服务故障;访问日志只记路径,避免 token 落盘;陪诊师列表分页夹紧。
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
|
||||
/**
|
||||
* 进程内速率限制(health 服务的写接口)
|
||||
*
|
||||
* 与 user 服务的限流同构,但有两点差异:
|
||||
* - 键优先用登录 token(已通过 requireAuth),避免多个用户共用同一 NAT 出口 IP 时互相挤占;
|
||||
* - 无 token 时回退到 IP,保证匿名请求也受限。
|
||||
*
|
||||
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
|
||||
* 若后续横向扩容需换成 Redis 之类的共享计数)。
|
||||
*/
|
||||
const store = new Map();
|
||||
|
||||
const cleanupTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, record] of store.entries()) {
|
||||
if (now - record.resetAt > record.windowMs) store.delete(key);
|
||||
}
|
||||
}, 60_000);
|
||||
cleanupTimer.unref();
|
||||
|
||||
/**
|
||||
* 创建限流中间件
|
||||
* @param {number} max 窗口内最大请求数
|
||||
* @param {number} windowMs 窗口时长(毫秒)
|
||||
*/
|
||||
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 now = Date.now();
|
||||
|
||||
let record = store.get(key);
|
||||
if (!record || now - record.resetAt > windowMs) {
|
||||
record = { count: 0, resetAt: now, windowMs };
|
||||
store.set(key, record);
|
||||
}
|
||||
|
||||
record.count++;
|
||||
if (record.count > max) {
|
||||
const retryAfter = Math.ceil((record.resetAt + windowMs - now) / 1000);
|
||||
ctx.set("Retry-After", String(retryAfter));
|
||||
return ResponseUtil.error(ctx, "操作过于频繁,请稍后再试", null, 429);
|
||||
}
|
||||
|
||||
ctx.set("X-RateLimit-Limit", String(max));
|
||||
ctx.set("X-RateLimit-Remaining", String(Math.max(0, max - record.count)));
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按用户维度的限流(供 WebSocket 等无 ctx 的场景复用)
|
||||
* @param {string} identity 身份键(通常是 userId)
|
||||
* @param {number} max 窗口内最大次数
|
||||
* @param {number} windowMs 窗口时长(毫秒)
|
||||
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
|
||||
*/
|
||||
function createUserLimiter(max, windowMs = 60_000) {
|
||||
const buckets = new Map();
|
||||
|
||||
return (identity) => {
|
||||
const now = Date.now();
|
||||
let record = buckets.get(identity);
|
||||
if (!record || now - record.resetAt > windowMs) {
|
||||
record = { count: 0, resetAt: now };
|
||||
buckets.set(identity, record);
|
||||
}
|
||||
record.count++;
|
||||
if (record.count > max) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfter: Math.ceil((record.resetAt + windowMs - now) / 1000),
|
||||
};
|
||||
}
|
||||
return { allowed: true, retryAfter: 0 };
|
||||
};
|
||||
}
|
||||
|
||||
export { rateLimit, createUserLimiter };
|
||||
Reference in New Issue
Block a user