oms/backend/app/middleware/request_log.js
liufumingren 1847e17ba7 feat(auth): 接入微信扫码登录与微信绑定
- 新增网关客户端与通知验签(sha256(appSecret) 派生 HMAC-SHA256,5 分钟防重放),
  扫码会话与一次性结果存 Redis,openid 仅服务端保存
- 新增 user_wechat_binds 表与迁移:openid 唯一(一个微信只绑一个账号)、
  user_id 唯一(重新绑定覆盖旧微信)
- 新增 /api/auth/wechat/* 接口与 /api/wx/notify 网关回调;登录二维码按 IP 限流,
  未配置网关时相关接口返回 400 提示,不影响账号密码 / 邮箱验证码登录
- 前端:「微信登录」tab(二维码 + 倒计时 + 轮询)与「我的」页微信绑定 / 解绑
- 开发与生产各出一份 WX_GATEWAY_* 配置样板,生产权威副本走 shared-config 覆盖
- 同步补充 swagger 契约与请求日志脱敏字段(bind_code / sign)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 23:17:11 +08:00

113 lines
3.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/** 需要脱敏的请求头 */
const SENSITIVE_HEADERS = [ 'authorization', 'cookie', 'set-cookie' ];
/** 请求报文需脱敏字段(含邮箱验证码 code、微信绑定码与网关签名) */
const SENSITIVE_REQUEST_FIELDS = [ 'password', 'token', 'app_secret', 'code', 'salt', 'bindcode', 'bind_code', 'sign' ];
/** 响应报文需脱敏字段(业务状态码 code 不脱敏,仅脱敏凭据类) */
const SENSITIVE_RESPONSE_FIELDS = [ 'password', 'token', 'app_secret', 'salt' ];
/**
* 对请求头脱敏
* @param {Object} headers 原始请求头
* @return {Object} 脱敏后的请求头
*/
function maskHeaders(headers) {
if (!headers) return {};
const result = {};
for (const key of Object.keys(headers)) {
result[key] = SENSITIVE_HEADERS.includes(key.toLowerCase()) ? '***' : headers[key];
}
return result;
}
/**
* 对报文对象中的敏感字段脱敏(浅层递归)
* @param {*} value 原始值
* @param {Array} fields 需要脱敏的字段名
* @return {*} 脱敏后的值
*/
function maskValue(value, fields) {
if (!value || typeof value !== 'object') return value;
const result = Array.isArray(value) ? [ ...value ] : { ...value };
for (const key of Object.keys(result)) {
if (fields.includes(key.toLowerCase())) {
result[key] = '***';
} else if (result[key] && typeof result[key] === 'object') {
result[key] = maskValue(result[key], fields);
}
}
return result;
}
/**
* 序列化并限制长度
* @param {*} value 待序列化的数据
* @param {Number} maxLength 最大长度
* @param {Array} fields 需要脱敏的字段名,为空则不脱敏
* @return {String} 序列化后的字符串
*/
function serialize(value, maxLength, fields = []) {
if (value === undefined || value === null) return '';
let text;
try {
text = typeof value === 'string' ? value : JSON.stringify(maskValue(value, fields));
} catch (err) {
// 循环引用或流对象等无法序列化
text = '[unserializable]';
}
if (!text) return '';
return text.length > maxLength ? `${text.slice(0, maxLength)}...[truncated]` : text;
}
/**
* 请求日志中间件(洋葱模型):
* 进入时记录开始时间,await next() 执行后续中间件与控制器,
* 返回时再读取 ctx.userId(此时路由级 JWT 中间件已解析出用户)并异步落库
* @return {Function} koa 中间件
*/
module.exports = () => {
return async (ctx, next) => {
const config = ctx.app.config.requestLog;
if (config.excludePaths.some(prefix => ctx.path.startsWith(prefix))) {
await next();
return;
}
const start = Date.now();
try {
await next();
} catch (err) {
throw err;
} finally {
const log = {
method: ctx.method,
url: ctx.originalUrl,
headers: serialize(maskHeaders(ctx.request.headers), config.maxBodyLength),
request_body: serialize(ctx.request.body, config.maxBodyLength, SENSITIVE_REQUEST_FIELDS),
// 响应体仅脱敏凭据类字段(如登录返回的 token),保留业务状态码 code
response_body: serialize(ctx.body, config.maxBodyLength, SENSITIVE_RESPONSE_FIELDS),
status: ctx.status,
user_id: ctx.userId || null,
ip: ctx.ip,
duration: Date.now() - start,
};
// 后台异步写入,不阻塞响应
ctx.runInBackground(async () => {
try {
await ctx.model.RequestLog.create(log);
} catch (err) {
ctx.logger.error(`[request-log] 写入失败:${err.message}`);
}
});
}
};
};