Files
weiguang-jewelry-ledger/新账系统/server/dispatcher.js
T

134 lines
6.4 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'(登录前处理)| 'session'(当前 cookie)| 'user'(默认;同时检查原页面账号)
// 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, readBody, access, actor, ledger, rawLedger, app}
// write 路由的处理函数可设 ctx.afterRollback:事务回滚后调用一次(如登记失败审计),
// 之后照常抛出原错误
// 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404,
// 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。
const path = require('node:path');
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 { requireBusinessHours, restricted, checkAccount } = require('./middleware/shop-access');
const { sendLoginPage } = require('./login-page');
const { requireActor, sessionInfo } = require('./middleware/session');
const { serveStatic } = require('./middleware/static');
const { serveWebNext, webNextEnabled, isNextPath, nextFile, DIST_DIR } = 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 ctx.readBody();
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/来源/店内网络 → 登录前路由 → 解析账号、复核营业时段 → 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 access = app.access.forRequest(req);
const hit = router.match(req.method, pathname, enabled);
const ctx = {
req,
res,
url,
params: hit?.params ?? {},
query: Object.fromEntries(url.searchParams),
access,
body: undefined,
readBody: () =>
readBody(req, () => {
// 登录由认证后的目标账号决定。其它慢速写请求在 body 收齐时重新核对营业时段。
if (pathname === '/api/login' || pathname === '/api/demo-login' || pathname === '/api/logout') return;
const period = app.access.currentWindow();
if (restricted(period)) requireBusinessHours(app.user(req), period);
}),
actor: null,
ledger: null,
rawLedger: app.ledger,
app,
};
if (hit?.route.auth === 'public') return await runRoute(hit.route, ctx);
ctx.actor = app.user(req);
const next = isNextPath(pathname) && webNextEnabled(app);
const closedToActor = restricted(access.period) && ctx.actor?.role !== 'owner';
if (
!isPost &&
((pathname === '/' && (!ctx.actor || closedToActor)) ||
(closedToActor && next && nextFile(pathname) === path.join(DIST_DIR, 'index.html')))
) {
return sendLoginPage(res, sessionInfo(app.ledger, app.mode, null, access));
}
checkAccount(ctx.actor, access);
if (ctx.actor && ctx.actor.role !== 'owner' && access.period?.state === 'open') {
res.remainingBusinessTime = () => access.period.closesAt - app.access.hoursClock();
}
ctx.ledger = app.ledger.asActor(ctx.actor);
if (pathname.startsWith('/api/') || pathname.startsWith('/print/')) {
if (hit?.route.auth === 'session') {
// 营业时段两个入口只看当前 cookie;店主专用入口由 runRoute 返回其原有的 403。
if (!ctx.actor && !hit.route.role) fail('请先登录', 401);
} else {
requireActor(req, ctx.actor);
}
return await runRoute(hit?.route ?? UNMATCHED[req.method], ctx);
}
if (next) return serveWebNext(res, pathname, isPost);
serveStatic(res, pathname, isPost);
} catch (e) {
sendError(res, e);
}
};
}
module.exports = { createHandler, runRoute, UNMATCHED };