Files
weiguang-jewelry-ledger/新账系统/server/dispatcher.js
T
黄健铭andClaude Opus 5.5 40bff0be94 新版界面挂载:/next/ 提供 web/dist 构建,单页回退并限制在目录内
试用、演示模式默认开启,云端需设置 WEB_NEXT=1;其余地址行为不变。

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

104 lines
4.7 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('../core/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 { serveWebNext, webNextEnabled, isNextPath } = require('./middleware/web-next');
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
// → 路由(含未匹配)→ 新版界面 /next/(启用时)→ 静态文件 → 统一错误响应。
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);
}
if (isNextPath(pathname) && webNextEnabled(app)) return serveWebNext(res, pathname, isPost);
serveStatic(res, pathname, isPost);
} catch (e) {
sendError(res, e);
}
};
}
module.exports = { createHandler, runRoute, UNMATCHED };