113 lines
3.5 KiB
JavaScript
113 lines
3.5 KiB
JavaScript
'use strict';
|
||
|
||
/** 需要脱敏的请求头 */
|
||
const SENSITIVE_HEADERS = [ 'authorization', 'cookie', 'set-cookie' ];
|
||
/** 请求报文需脱敏字段(含邮箱验证码 code) */
|
||
const SENSITIVE_REQUEST_FIELDS = [ 'password', 'token', 'app_secret', 'code', 'salt' ];
|
||
/** 响应报文需脱敏字段(业务状态码 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}`);
|
||
}
|
||
});
|
||
}
|
||
};
|
||
};
|