来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
155 lines
5.8 KiB
TypeScript
155 lines
5.8 KiB
TypeScript
import type { NextFunction, Response } from 'express';
|
||
import type { AuthRequest } from './auth';
|
||
import { writeAuditLog } from '../services/auditService';
|
||
import { readOperatingBranchCode } from '../services/tenantScope';
|
||
import { redactAuditValue } from '../services/auditRedaction';
|
||
|
||
const SKIP_PATH_PREFIXES = [
|
||
'/api/health',
|
||
'/api/public',
|
||
'/api/workflow/audit/logs',
|
||
'/api/auth/token',
|
||
'/api/auth/unified-login',
|
||
'/api/mobile/login',
|
||
];
|
||
|
||
/**
|
||
* 审计脱敏(2026-09-24 加固):**唯一实现已下沉到 services/auditRedaction.ts**,
|
||
* 由 `auditService.writeAuditLog`(唯一收口)与这里共用。
|
||
* 这里保留 `SENSITIVE_KEY` / `redactValue` 的导出名以兼容既有契约测试与调用方。
|
||
*/
|
||
export { SENSITIVE_KEY, redactAuditValue as redactValue } from '../services/auditRedaction';
|
||
|
||
/** 已有业务 writeAuditLog 的精确 path,禁止宽前缀 */
|
||
function isExactBusinessAuditedPath(method: string, path: string): boolean {
|
||
if (method === 'DELETE' && path === '/api/mobile/inspection/photo') return true;
|
||
if (method === 'POST' && path === '/api/workflow/purchase/self-purchase-stock-inbound') return true;
|
||
if (method === 'POST' && path === '/api/mobile/purchase/self-purchase-stock-inbound') return true;
|
||
if (
|
||
method === 'PATCH' &&
|
||
/^\/api\/workflow\/purchase\/self-purchase-stock-inbound\/[^/]+$/.test(path)
|
||
) {
|
||
return true;
|
||
}
|
||
if (
|
||
method === 'DELETE' &&
|
||
/^\/api\/workflow\/purchase\/self-purchase-stock-inbound\/[^/]+$/.test(path)
|
||
) {
|
||
return true;
|
||
}
|
||
if (
|
||
method === 'POST' &&
|
||
/^\/api\/workflow\/purchase\/self-purchase-stock-inbound\/[^/]+\/void$/.test(path)
|
||
) {
|
||
return true;
|
||
}
|
||
if (method === 'POST' && path === '/api/workflow/cost/free-cost') return true;
|
||
if (method === 'POST' && /^\/api\/workflow\/cost\/free-cost\/entries\/[^/]+\/approve$/.test(path)) {
|
||
return true;
|
||
}
|
||
if (method === 'POST' && /^\/api\/workflow\/cost\/free-cost\/entries\/[^/]+\/reject$/.test(path)) {
|
||
return true;
|
||
}
|
||
if (method === 'DELETE' && /^\/api\/workflow\/cost\/free-cost\/entries\/[^/]+$/.test(path)) {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function shouldSkip(req: AuthRequest): boolean {
|
||
const method = String(req.method || 'GET').toUpperCase();
|
||
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return true;
|
||
const path = String(req.originalUrl || req.url || '').split('?')[0];
|
||
if (isExactBusinessAuditedPath(method, path)) return true;
|
||
if (SKIP_PATH_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`) || path.startsWith(p))) {
|
||
return true;
|
||
}
|
||
if (method === 'POST' && (path === '/api/data/query' || path === '/api/data/batch')) return true;
|
||
return false;
|
||
}
|
||
|
||
function inferCategory(path: string, dataAction?: string): string {
|
||
if (dataAction) return 'data';
|
||
if (path.includes('/orders') || path.includes('/allocation')) return 'order';
|
||
if (path.includes('/purchase') || path.includes('/prep')) return 'purchase';
|
||
if (path.includes('/finance') || path.includes('/statement') || path.includes('/cost')) {
|
||
return 'finance';
|
||
}
|
||
if (path.includes('/inventory')) return 'inventory';
|
||
if (path.includes('/exception')) return 'exception';
|
||
return 'api';
|
||
}
|
||
|
||
function inferOperationType(method: string, path: string, dataAction?: string): string {
|
||
if (dataAction) return `data_${dataAction}`;
|
||
return `api_${method.toLowerCase()}`;
|
||
}
|
||
|
||
/**
|
||
* 变更类 HTTP 请求结束后异步写入 operation_logs(失败不阻断响应)。
|
||
* 须挂在 express.json 之后;依赖 auth 中间件已设置 userId(未登录则跳过)。
|
||
*/
|
||
export function operationAuditMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
|
||
if (shouldSkip(req)) {
|
||
next();
|
||
return;
|
||
}
|
||
|
||
const started = Date.now();
|
||
res.on('finish', () => {
|
||
if (!req.userId) return;
|
||
const status = res.statusCode || 0;
|
||
// 未认证/禁止访问不记(避免刷日志);5xx 仍记便于排查
|
||
if (status === 401 || status === 403) return;
|
||
|
||
const path = String(req.originalUrl || req.url || '').split('?')[0];
|
||
const method = String(req.method || 'POST').toUpperCase();
|
||
const body = req.body as Record<string, unknown> | undefined;
|
||
const dataAction =
|
||
path.startsWith('/api/data') && body && typeof body.action === 'string'
|
||
? String(body.action).toLowerCase()
|
||
: path.includes('/batch')
|
||
? 'batch'
|
||
: '';
|
||
const table =
|
||
body && typeof body.table === 'string'
|
||
? String(body.table)
|
||
: path.split('/').filter(Boolean).slice(1, 3).join('/') || undefined;
|
||
|
||
const branchCode =
|
||
readOperatingBranchCode(req) ||
|
||
(typeof req.headers['x-branch-code'] === 'string' ? req.headers['x-branch-code'] : null);
|
||
|
||
const targetIdRaw =
|
||
body && (body.id != null || body.order_code != null)
|
||
? String(body.id ?? body.order_code)
|
||
: path.split('/').filter(Boolean).pop() || undefined;
|
||
|
||
void writeAuditLog({
|
||
operatorId: req.userId,
|
||
operationType: inferOperationType(method, path, dataAction || undefined),
|
||
actionCategory: inferCategory(path, dataAction || undefined),
|
||
targetTable: table,
|
||
targetId: targetIdRaw,
|
||
branchCode: branchCode || null,
|
||
// 只用 Express 解析后的 req.ip(由 app.set('trust proxy', …) 决定);
|
||
// ⚠️ 不得改回读原始 x-forwarded-for:nginx/CLB 都是「追加式」代理,
|
||
// 其第一段是客户端自填的 → 审计 ip_address 会被任意伪造(2026-09-24 实测确认)。
|
||
ipAddress: req.ip || req.socket?.remoteAddress || null,
|
||
newValue: {
|
||
method,
|
||
path,
|
||
status,
|
||
ms: Date.now() - started,
|
||
action: dataAction || undefined,
|
||
table: table || undefined,
|
||
body: redactAuditValue(body),
|
||
},
|
||
}).catch((error) => {
|
||
console.error('[audit] operationAuditMiddleware write failed:', error);
|
||
});
|
||
});
|
||
|
||
next();
|
||
}
|