'use strict'; const { fail } = require('../../core/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 };