路由表化:新增路由匹配器、中间件与表驱动分发,迁移店铺设置/员工/货盘路由
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2b9cb825be
commit
e082069f55
14 files changed
+525
-197
No files matched your search
@@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
const { fail } = require('../../ledger');
|
||||
// 保持原样(含按块拼接字符串的已知问题),修正留到下一阶段。
|
||||
async function readBody(req) {
|
||||
let raw = '';
|
||||
for await (const chunk of req) {
|
||||
raw += chunk;
|
||||
if (Buffer.byteLength(raw) > 300000) fail('内容过大', 413);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw || '{}');
|
||||
} catch {
|
||||
fail('请求内容不是有效JSON');
|
||||
}
|
||||
}
|
||||
module.exports = { readBody };
|
||||
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const { send } = require('../http');
|
||||
function sendError(res, e) {
|
||||
if (!res.headersSent)
|
||||
send(res, e.status || 400, {
|
||||
error:
|
||||
e.status || e.message?.startsWith('打印')
|
||||
? e.message
|
||||
: e.code?.startsWith('SQLITE')
|
||||
? '保存失败,请保留操作内容并联系维护者'
|
||||
: e.message || '操作失败',
|
||||
...(e.code === 'ACCOUNT_CHANGED' ? { code: e.code } : {}),
|
||||
...(e.code === 'EMPLOYEE_HAS_BUSINESS' ? { code: e.code, businessUsage: e.businessUsage } : {}),
|
||||
...(e.code === 'RECOVERY_MATERIAL_IN_USE' ? { code: e.code, blockedUsages: e.blockedUsages } : {}),
|
||||
});
|
||||
else res.end();
|
||||
}
|
||||
module.exports = { sendError };
|
||||
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
const { fail } = require('../../ledger');
|
||||
// 访问地址、请求方式与 POST 来源校验;顺序:Host → 解析地址 → 405 → Origin/X-Requested-With/Content-Type。
|
||||
function checkRequest(req, production) {
|
||||
const expected = production ? new URL(process.env.PUBLIC_URL).host : req.headers.host;
|
||||
if (production && req.headers.host !== expected) fail('访问地址不匹配', 403);
|
||||
if (!production && !/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || ''))
|
||||
fail('仅允许本机地址访问', 403);
|
||||
const url = new URL(req.url, 'http://' + req.headers.host);
|
||||
const route = url.pathname;
|
||||
const isPost = req.method === 'POST';
|
||||
if (!['GET', 'POST'].includes(req.method)) fail('不支持的请求方式', 405);
|
||||
if (isPost) {
|
||||
const expectedOrigin = production ? new URL(process.env.PUBLIC_URL).origin : 'http://' + req.headers.host;
|
||||
if (
|
||||
req.headers.origin !== expectedOrigin ||
|
||||
req.headers['x-requested-with'] !== 'maimai-ledger' ||
|
||||
!req.headers['content-type']?.startsWith('application/json')
|
||||
)
|
||||
fail('请从系统页面提交操作', 403);
|
||||
}
|
||||
return { url, route, isPost };
|
||||
}
|
||||
module.exports = { checkRequest };
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
function securityHeaders(res) {
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||
);
|
||||
}
|
||||
module.exports = { securityHeaders };
|
||||
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
const crypto = require('node:crypto');
|
||||
const TeamMembers = require('../../team-members');
|
||||
const ShopSettings = require('../../shop-settings');
|
||||
const { fail } = require('../../ledger');
|
||||
const { sha } = require('../hash');
|
||||
|
||||
function sessionToken(req) {
|
||||
return req.headers.cookie
|
||||
?.split(';')
|
||||
.map(s => s.trim())
|
||||
.find(s => s.startsWith('mm_session='))
|
||||
?.slice(11);
|
||||
}
|
||||
function sessionUser(ledger, u) {
|
||||
if (!u) return null;
|
||||
const member = ledger.memberFor(u);
|
||||
return {
|
||||
id: u.id,
|
||||
name: u.name,
|
||||
role: u.role,
|
||||
member,
|
||||
operatorName:
|
||||
ShopSettings.read(ledger).members.find(row => row.member === member)?.operatorName ||
|
||||
TeamMembers.label(ledger, member) ||
|
||||
u.name,
|
||||
label: TeamMembers.label(ledger, member) || u.name,
|
||||
};
|
||||
}
|
||||
function createSessions(ledger, { production }) {
|
||||
function user(req) {
|
||||
const cookie = sessionToken(req);
|
||||
if (!cookie) return null;
|
||||
return sessionUser(
|
||||
ledger,
|
||||
ledger.one(
|
||||
'SELECT u.id,u.name,u.role FROM sessions s JOIN users u ON u.id=s.user_id JOIN team_user_members t ON t.user_id=u.id JOIN team_members m ON m.member=t.member WHERE s.hash=? AND s.expires>? AND m.enabled=1',
|
||||
sha(cookie),
|
||||
Date.now(),
|
||||
) || null,
|
||||
);
|
||||
}
|
||||
function session(res, u) {
|
||||
if (!u) fail('账号不可用', 401);
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
ledger.run('DELETE FROM sessions WHERE expires<?', Date.now());
|
||||
ledger.run('INSERT INTO sessions VALUES (?,?,?)', sha(token), u.id, Date.now() + 8 * 60 * 60 * 1000);
|
||||
res.setHeader(
|
||||
'Set-Cookie',
|
||||
`mm_session=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800${production ? '; Secure' : ''}`,
|
||||
);
|
||||
return { user: sessionUser(ledger, u) };
|
||||
}
|
||||
return { user, session };
|
||||
}
|
||||
// /api/ 与 /print/:未登录 401;页面记住的原账号与 cookie 不一致时 409。
|
||||
function requireActor(req, actor) {
|
||||
if (!actor) fail('请先登录', 401);
|
||||
// 仅校验本次页面的原账号与cookie一致,实际授权仍由登录和成员权限决定。
|
||||
if (req.headers['x-ledger-user'] !== undefined && req.headers['x-ledger-user'] !== actor.id) {
|
||||
const error = new Error('登录账号已在其他页面切换,请刷新后继续;原操作已暂停。');
|
||||
error.status = 409;
|
||||
error.code = 'ACCOUNT_CHANGED';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
module.exports = { sessionToken, sessionUser, createSessions, requireActor };
|
||||
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { fail } = require('../../ledger');
|
||||
const { send } = require('../http');
|
||||
const PUBLIC_DIR = path.join(__dirname, '..', '..', 'public');
|
||||
const ASSETS = {
|
||||
'/': 'index.html',
|
||||
'/private-operations-ui.js': 'private-operations-ui.js',
|
||||
'/app.js': 'app.js',
|
||||
'/order-copy.js': 'order-copy.js',
|
||||
'/order-templates.js': 'order-templates.js',
|
||||
'/order-templates-ui.js': 'order-templates-ui.js',
|
||||
'/order-edit-ui.js': 'order-edit-ui.js',
|
||||
'/order-cancellations-ui.js': 'order-cancellations-ui.js',
|
||||
'/order-changes-ui.js': 'order-changes-ui.js',
|
||||
'/order-after-sales-ui.js': 'order-after-sales-ui.js',
|
||||
'/order-ownership-ui.js': 'order-ownership-ui.js',
|
||||
'/daily-funds-ui.js': 'daily-funds-ui.js',
|
||||
'/team-funds-ui.js': 'team-funds-ui.js',
|
||||
'/cost-funding-ui.js': 'cost-funding-ui.js',
|
||||
'/price-locks-ui.js': 'price-locks-ui.js',
|
||||
'/price-lock-changes-ui.js': 'price-lock-changes-ui.js',
|
||||
'/material-pools-ui.js': 'material-pools-ui.js',
|
||||
'/recoveries-ui.js': 'recoveries-ui.js',
|
||||
'/recovery-changes-ui.js': 'recovery-changes-ui.js',
|
||||
'/inventory-changes-ui.js': 'inventory-changes-ui.js',
|
||||
'/pockets-ui.js': 'pockets-ui.js',
|
||||
'/shop-settings-ui.js': 'shop-settings-ui.js',
|
||||
'/employees-ui.js': 'employees-ui.js',
|
||||
'/credit-card-fees.js': 'credit-card-fees.js',
|
||||
'/calculations.js': 'calculations.js',
|
||||
'/order-formula.js': 'order-formula.js',
|
||||
'/fee-estimates.js': 'fee-estimates.js',
|
||||
'/order-cost-presets-ui.js': 'order-cost-presets-ui.js',
|
||||
'/app.css': 'app.css',
|
||||
'/print.js': 'print.js',
|
||||
};
|
||||
// 白名单静态文件;其余(含任何 POST)一律 404。
|
||||
function serveStatic(res, route, isPost) {
|
||||
const file = ASSETS[route];
|
||||
if (!file || isPost) fail('地址不存在', 404);
|
||||
send(
|
||||
res,
|
||||
200,
|
||||
fs.readFileSync(path.join(PUBLIC_DIR, file)),
|
||||
file.endsWith('.js')
|
||||
? 'application/javascript; charset=utf-8'
|
||||
: file.endsWith('.css')
|
||||
? 'text/css; charset=utf-8'
|
||||
: 'text/html; charset=utf-8',
|
||||
);
|
||||
}
|
||||
module.exports = { serveStatic, ASSETS };
|
||||
Reference in new issue
Block a user