fix: 写接口限流、WS 有界与 token 不再进日志

新增进程内限流并挂到订单/档案写接口;WS 设 maxPayload、同连接串行处理、按用户限频;鉴权只读请求头并区分登录失效与用户服务故障;访问日志只记路径,避免 token 落盘;陪诊师列表分页夹紧。
This commit is contained in:
lik
2026-10-24 22:24:50 +08:00
committed by trae-solo-agent
parent f21b3711df
commit 68faf840cf
6 changed files with 154 additions and 14 deletions
+3 -1
View File
@@ -32,7 +32,9 @@ class APP {
const start = Date.now(); const start = Date.now();
await next(); await next();
const ms = Date.now() - start; const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`); // 只记录路径,不记录查询串:URL 里可能带 token、手机号等敏感参数,
// 一旦进入 access log 就等于把凭证/隐私落盘
console.log(`${ctx.method} ${ctx.path} - ${ctx.status} - ${ms}ms`);
}); });
} }
+6 -2
View File
@@ -28,6 +28,8 @@ import ResponseUtil from "../utils/responseUtil.js";
const MIN_PUBLIC_REVIEW_COUNT = 5; const MIN_PUBLIC_REVIEW_COUNT = 5;
class HandlerEmployee { class HandlerEmployee {
// 公示列表单页上限:避免一次请求把整张表拖出来
static MAX_PAGE_SIZE = 50;
// 姓名脱敏:只留姓 + 「陪诊师」,不给全名,降低私下联系(跳单)的可能 // 姓名脱敏:只留姓 + 「陪诊师」,不给全名,降低私下联系(跳单)的可能
static maskName(name) { static maskName(name) {
const trimmed = String(name || "").trim(); const trimmed = String(name || "").trim();
@@ -105,8 +107,10 @@ class HandlerEmployee {
// 公示信息本身不敏感,且避免登录态异常导致页面空白 // 公示信息本身不敏感,且避免登录态异常导致页面空白
async getAttendants(ctx) { async getAttendants(ctx) {
try { try {
const page = parseInt(ctx.request.query.page) || 1; // 分页参数夹紧:pageSize 未上限时可用一个请求把整表拖出来
const pageSize = parseInt(ctx.request.query.pageSize) || 50; const page = Math.max(1, parseInt(ctx.request.query.page) || 1);
const rawSize = parseInt(ctx.request.query.pageSize) || 50;
const pageSize = Math.min(Math.max(1, rawSize), HandlerEmployee.MAX_PAGE_SIZE);
// 只取在职陪诊员。 // 只取在职陪诊员。
// 排序不按 attendantInfo.rating(无可信来源),改按服务年限 / 累计接单数 // 排序不按 attendantInfo.rating(无可信来源),改按服务年限 / 累计接单数
+81
View File
@@ -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 };
+26 -9
View File
@@ -6,19 +6,36 @@ import { HandlerEmployee } from "../handler/employee.js";
import ResponseUtil from "../utils/responseUtil.js"; import ResponseUtil from "../utils/responseUtil.js";
import { getUserByToken } from "../utils/user_service.js"; import { getUserByToken } from "../utils/user_service.js";
import { isAdmin } from "../utils/permissions.js"; import { isAdmin } from "../utils/permissions.js";
import { rateLimit } from "../middleware/ratelimit.js";
// 写接口限流:下单最容易造成脏数据与费用纠纷,给最紧的额度;
// 修改/取消次之;查询不限制(列表页会轮询刷新)
const createLimit = rateLimit(5);
const updateLimit = rateLimit(20);
const deleteLimit = rateLimit(10);
/** /**
* 鉴权中间件:校验 token 并将用户信息挂到 ctx.state.user * 鉴权中间件:校验 token 并将用户信息挂到 ctx.state.user
* token→user 结果带 5 分钟进程内缓存(见 utils/user_service.js) * token→user 结果带 5 分钟进程内缓存(见 utils/user_service.js)
*
* token 只从请求头读取:曾支持 ?token= 传参,但 access log 会原样记录 URL,
* 等于把登录凭证写进日志。另兼容 "Bearer xxx" 头格式,与 user 服务口径一致。
*/ */
async function requireAuth(ctx, next) { async function requireAuth(ctx, next) {
const token = ctx.header["token"] || ctx.header["authorization"] || ctx.request.query?.token; const raw = ctx.header["token"] || ctx.header["authorization"];
const token = raw ? String(raw).replace(/^Bearer\s+/i, "").trim() : "";
if (!token) { if (!token) {
ResponseUtil.unauthorized(ctx, "缺少token"); ResponseUtil.unauthorized(ctx, "缺少token");
return; return;
} }
const user = await getUserByToken(token); let user;
try {
user = await getUserByToken(token, { strict: true });
} catch (err) {
// 用户服务故障不等于登录失效:区分开才能让前端提示「稍后重试」而不是踢回登录
return ResponseUtil.error(ctx, "服务暂不可用,请稍后重试", null, 503);
}
if (!user) { if (!user) {
ResponseUtil.unauthorized(ctx, "登录已失效"); ResponseUtil.unauthorized(ctx, "登录已失效");
return; return;
@@ -63,17 +80,17 @@ function registerRoutes(app) {
// 全量查询属管理端能力,必须管理员 // 全量查询属管理端能力,必须管理员
router.get("/escort-record", requireAuth, requireAdmin, handlerEscortRecord.getRecords.bind(handlerEscortRecord)); router.get("/escort-record", requireAuth, requireAdmin, handlerEscortRecord.getRecords.bind(handlerEscortRecord));
router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord)); router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord));
router.post("/escort-record", requireAuth, handlerEscortRecord.createRecord.bind(handlerEscortRecord)); router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
router.put("/escort-record/:id", requireAuth, handlerEscortRecord.updateRecord.bind(handlerEscortRecord)); router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord));
router.patch("/escort-record/:id/status", requireAuth, handlerEscortRecord.updateStatus.bind(handlerEscortRecord)); router.patch("/escort-record/:id/status", requireAuth, updateLimit, handlerEscortRecord.updateStatus.bind(handlerEscortRecord));
router.delete("/escort-record/:id", requireAuth, handlerEscortRecord.deleteRecord.bind(handlerEscortRecord)); router.delete("/escort-record/:id", requireAuth, deleteLimit, handlerEscortRecord.deleteRecord.bind(handlerEscortRecord));
// C 端"我的健康档案":userId 一律取自 token,必须注册在 /health-profile/:id 之前 // C 端"我的健康档案":userId 一律取自 token,必须注册在 /health-profile/:id 之前
router.get("/health-profile/mine", requireAuth, handlerHealthProfile.getMyProfiles.bind(handlerHealthProfile)); router.get("/health-profile/mine", requireAuth, handlerHealthProfile.getMyProfiles.bind(handlerHealthProfile));
router.post("/health-profile/mine", requireAuth, handlerHealthProfile.createMyProfile.bind(handlerHealthProfile)); router.post("/health-profile/mine", requireAuth, createLimit, handlerHealthProfile.createMyProfile.bind(handlerHealthProfile));
router.get("/health-profile/mine/:id", requireAuth, handlerHealthProfile.getMyProfileById.bind(handlerHealthProfile)); router.get("/health-profile/mine/:id", requireAuth, handlerHealthProfile.getMyProfileById.bind(handlerHealthProfile));
router.put("/health-profile/mine/:id", requireAuth, handlerHealthProfile.updateMyProfile.bind(handlerHealthProfile)); router.put("/health-profile/mine/:id", requireAuth, updateLimit, handlerHealthProfile.updateMyProfile.bind(handlerHealthProfile));
router.delete("/health-profile/mine/:id", requireAuth, handlerHealthProfile.deleteMyProfile.bind(handlerHealthProfile)); router.delete("/health-profile/mine/:id", requireAuth, deleteLimit, handlerHealthProfile.deleteMyProfile.bind(handlerHealthProfile));
// 以下为管理端档案接口(C 端一律走 /mine),必须管理员 // 以下为管理端档案接口(C 端一律走 /mine),必须管理员
router.get("/health-profile", requireAuth, requireAdmin, handlerHealthProfile.getProfiles.bind(handlerHealthProfile)); router.get("/health-profile", requireAuth, requireAdmin, handlerHealthProfile.getProfiles.bind(handlerHealthProfile));
+11 -1
View File
@@ -4,6 +4,7 @@ const USER_SERVICE_URL = process.env.USER_SERVICE_URL || "http://127.0.0.1:9010"
const CACHE_TTL = 5 * 60 * 1000; // 成功结果缓存 5 分钟 const CACHE_TTL = 5 * 60 * 1000; // 成功结果缓存 5 分钟
const NEGATIVE_TTL = 60 * 1000; // 无效 token 短缓存,防止打爆 user 服务 const NEGATIVE_TTL = 60 * 1000; // 无效 token 短缓存,防止打爆 user 服务
const MAX_CACHE_SIZE = 2000; const MAX_CACHE_SIZE = 2000;
const LOOKUP_TIMEOUT = 5000; // user 服务偶发无响应时不能拖住 health 的全部请求
// key -> { user, expiresAt },Map 按插入序实现简易 LRU // key -> { user, expiresAt },Map 按插入序实现简易 LRU
const cache = new Map(); const cache = new Map();
@@ -33,6 +34,7 @@ async function lookup(body) {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(body), body: JSON.stringify(body),
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
}); });
const data = await res.json(); const data = await res.json();
return data?.data?.user || null; return data?.data?.user || null;
@@ -48,9 +50,12 @@ async function lookup(body) {
* 故不存在 userId 兜底,避免凭 userId 冒充他人身份。 * 故不存在 userId 兜底,避免凭 userId 冒充他人身份。
* *
* @param {string} token 登录 token * @param {string} token 登录 token
* @param {Object} [options]
* @param {boolean} [options.strict] 严格模式:user 服务不可用时不返回 null,
* 而是抛出 code = USER_SERVICE_UNAVAILABLE 的错误,供接口区分「登录失效」与「服务故障」
* @returns {Promise<Object|null>} 用户信息或 null * @returns {Promise<Object|null>} 用户信息或 null
*/ */
export async function getUserByToken(token) { export async function getUserByToken(token, options = {}) {
if (!token) return null; if (!token) return null;
const key = `tk:${token}`; const key = `tk:${token}`;
@@ -68,6 +73,11 @@ export async function getUserByToken(token) {
} catch (err) { } catch (err) {
// 网络异常不缓存,避免把故障期内的问题固化 5 分钟 // 网络异常不缓存,避免把故障期内的问题固化 5 分钟
console.error("getUserByToken error:", err.message); console.error("getUserByToken error:", err.message);
if (options.strict) {
const unavailable = new Error("用户服务暂不可用");
unavailable.code = "USER_SERVICE_UNAVAILABLE";
throw unavailable;
}
} }
return null; return null;
+27 -1
View File
@@ -5,9 +5,15 @@ import { chatTask } from "./agent/bots/bot-escort/task.js";
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js" import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
import { getUserByToken } from "./utils/user_service.js"; import { getUserByToken } from "./utils/user_service.js";
import { isAdmin } from "./utils/permissions.js"; import { isAdmin } from "./utils/permissions.js";
import { createUserLimiter } from "./middleware/ratelimit.js";
let systemMessageSequence = 0; let systemMessageSequence = 0;
// 单连接上行帧上限:超限会被 ws 直接断开,避免超大 JSON 占用内存与 CPU
const MAX_PAYLOAD_BYTES = 256 * 1024;
// 单用户聊天频次限制:AI 调用有成本,且同一用户的会话本就串行处理
const chatLimiter = createUserLimiter(20);
// 所有下行帧保持同一结构,调用方无需按消息类型猜测字段。 // 所有下行帧保持同一结构,调用方无需按消息类型猜测字段。
const sendFrame = (ws, source, type, content = '', id = '') => { const sendFrame = (ws, source, type, content = '', id = '') => {
if (ws.readyState !== WebSocket.OPEN) return; if (ws.readyState !== WebSocket.OPEN) return;
@@ -34,6 +40,7 @@ export default class WebSocketServerManager {
this.wss = new WebSocketServer({ this.wss = new WebSocketServer({
server: this.server, server: this.server,
maxPayload: MAX_PAYLOAD_BYTES,
perMessageDeflate: { perMessageDeflate: {
zlibDeflateOptions: { zlibDeflateOptions: {
chunkSize: 1024, chunkSize: 1024,
@@ -71,9 +78,18 @@ export default class WebSocketServerManager {
_handleChatConnection(ws) { _handleChatConnection(ws) {
sendFrame(ws, 'system', 'connected', 'Connected to chat server'); sendFrame(ws, 'system', 'connected', 'Connected to chat server');
ws.on('message', (data) => this._handleMessage(ws, data)); // 同一连接的消息串行处理:agent 的 messages 数组是共享状态,
// 并发跑同一个 agent 会让上下文交错、回复错乱
ws.messageQueue = Promise.resolve();
ws.on('message', (data) => {
ws.messageQueue = ws.messageQueue
.then(() => this._handleMessage(ws, data))
.catch((err) => console.error('WebSocket message handling error:', err));
});
ws.on('close', () => { ws.on('close', () => {
// 断开后释放队列引用,避免连接对象被闭包长期持有
ws.messageQueue = null;
console.log('Chat client disconnected'); console.log('Chat client disconnected');
}); });
@@ -114,6 +130,16 @@ export default class WebSocketServerManager {
send('system', 'error', '请先登录', msg.id); send('system', 'error', '请先登录', msg.id);
return; return;
} }
// 频次限制按用户维度:防止单账号刷 AI 调用(同一账号多连接共享额度)
if (msg.type === 'chat') {
const limit = chatLimiter(String(userInfo._id));
if (!limit.allowed) {
send('system', 'error', `操作过于频繁,请 ${limit.retryAfter} 秒后重试`, msg.id);
return;
}
}
if (msg.agent === 'escort-admin') { if (msg.agent === 'escort-admin') {
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权 // 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权
if (!isAdmin(userInfo)) { if (!isAdmin(userInfo)) {