Files
weiguang-jewelry-ledger/新账系统/server/dispatcher.js
T
黄健铭andClaude Opus 5.5 a965becde3 安全审计:登记登录、登出、登录失败、修改本人密码、初始化、导出与备份下载
- 新增 server/security-audit.js:统一写入 {ip, userAgent(≤200字)} 及少量说明,写入失败只打印错误、不改变响应
- 登录失败用合成身份“未登录”(role=system),记录登录名(≤50字)与原因 unknown_user / password_not_set / wrong_password;判断顺序与原条件一致,未知账号照常计算哈希
- 修改本人密码失败会整体回滚:分发器新增 ctx.afterRollback,回滚后另行写入失败记录
- 导出库存流水Excel记录实际使用的筛选条件;下载备份记录文件名
- 员工业务数据判定忽略 auth:*、export、backup 审计,登录不影响员工删除资格
- 两处“只读不改库”测试改为忽略安全审计行

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 12:44:30 -08:00

102 lines
4.5 KiB
JavaScript
Raw 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';
// 路由表分发。路由字段:
// method, path 匹配条件(见 router.js)
// auth 'public'(登录前处理)| 'user'(默认;/api/ 与 /print/ 先 401/409 校验)
// when(app) 可选;返回 false 时视同未声明(如演示登录只在演示模式存在)
// role: 'owner' 店主专用;默认在读请求体之前校验,ownerCheck: 'transact' 改为在事务内校验
// direct: true POST 由处理函数自行读请求体(旧代码中在通用写入流程之前处理的 POST)
// write: true POST 在 transact(操作号幂等)内执行;syncTeamFunds 默认 true
// project(ctx, result) 写入结果(含幂等重放的缓存结果)发出前的投影
// contentType 非 JSON 响应类型(如打印 HTML)
// raw: true 处理函数自行写出响应(下载)
// handler(ctx) ctx = {req, res, url, params, query, body, actor, ledger, rawLedger, app}
// write 路由的处理函数可设 ctx.afterRollback:事务回滚后调用一次(如登记失败审计),
// 之后照常抛出原错误
// 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404,
// 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。
const { fail, owner } = require('../ledger');
const { createRouter } = require('./router');
const { send, notFound } = require('./http');
const { readBody } = require('./middleware/body');
const { securityHeaders } = require('./middleware/security-headers');
const { checkRequest } = require('./middleware/request-guard');
const { requireActor } = require('./middleware/session');
const { serveStatic } = require('./middleware/static');
const { sendError } = require('./middleware/errors');
const UNMATCHED = {
GET: { method: 'GET', handler: notFound },
POST: { method: 'POST', write: true, handler: notFound },
};
async function runRoute(route, ctx) {
const { req, res, actor, app } = ctx;
if (route.role === 'owner' && route.ownerCheck !== 'transact') owner(actor);
if (route.method === 'GET' || route.direct) {
const data = await route.handler(ctx);
if (!route.raw) send(res, 200, data, route.contentType);
return;
}
ctx.body = await readBody(req);
const key = req.headers['idempotency-key'];
// 读取请求体期间账号可能已被停用或重置密码,写入前再次核验会话。
const checkedActor = app.user(req);
if (!checkedActor || checkedActor.id !== actor.id) fail('登录已失效,请重新登录', 401);
if (!route.write) return send(res, 200, route.handler(ctx));
let result;
try {
result = ctx.ledger.transact(
key,
actor,
{ route: ctx.url.pathname, body: ctx.body },
() => {
if (route.role === 'owner' && route.ownerCheck === 'transact') owner(actor);
return route.handler(ctx);
},
{ syncTeamFunds: route.syncTeamFunds !== false },
);
} catch (e) {
ctx.afterRollback?.();
throw e;
}
send(res, 200, route.project ? route.project(ctx, result) : result);
}
// 处理顺序:安全响应头 → Host/405/来源校验 → 登录前路由 → 解析当前账号 → /api/、/print/ 的 401/409
// → 路由(含未匹配)→ 静态文件 → 统一错误响应。
function createHandler(app, routes) {
const router = createRouter(routes);
const enabled = route => !route.when || route.when(app);
return async (req, res) => {
securityHeaders(res);
try {
const { url, route: pathname, isPost } = checkRequest(req, app.production);
const hit = router.match(req.method, pathname, enabled);
const ctx = {
req,
res,
url,
params: hit?.params ?? {},
query: Object.fromEntries(url.searchParams),
body: undefined,
actor: null,
ledger: null,
rawLedger: app.ledger,
app,
};
if (hit?.route.auth === 'public') return await runRoute(hit.route, ctx);
ctx.actor = app.user(req);
ctx.ledger = app.ledger.asActor(ctx.actor);
if (pathname.startsWith('/api/') || pathname.startsWith('/print/')) {
requireActor(req, ctx.actor);
return await runRoute(hit?.route ?? UNMATCHED[req.method], ctx);
}
serveStatic(res, pathname, isPost);
} catch (e) {
sendError(res, e);
}
};
}
module.exports = { createHandler, runRoute, UNMATCHED };