#!/usr/bin/env node 'use strict'; // 独立本地演示:禁止导入正式应用、数据库或账号配置。 const http = require('node:http'); const fs = require('node:fs'); const path = require('node:path'); const os = require('node:os'); const { DemoError, createSeed, applyCommand, buildReport, publicState, purchasePreview } = require('./engine'); const DEFAULT_STATE_FILE = '/tmp/weiguang-capital-demo-20261028/state.json'; const DEFAULT_PORT = 3102; const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.png': 'image/png' }; function validateStoredState(state) { if (!state || state.version !== 1 || !state.demo || state.demo.fictional !== true || !['default', 'complex'].includes(state.demo.name)) throw new Error('演示状态格式不符,未读取或修改其他文件。'); for (const key of ['members', 'opening', 'purchases', 'orders', 'transfers', 'requests']) if (!Array.isArray(state[key])) throw new Error(`演示状态缺少${key}。`); if (!Number.isSafeInteger(state.nextSequence) || state.nextSequence < 1) throw new Error('演示序号无效。'); if (state.opening.length !== 3 || state.opening.some((item) => !['owner', 'assistant', 'assistant2'].includes(item.member) || !Number.isSafeInteger(item.amount) || item.amount < 0 || item.date !== state.demo.startDate)) throw new Error('演示期初格式无效。'); for (const [key, amounts] of [['purchases', ['weightMg', 'totalCents']], ['orders', ['weightMg', 'saleCents', 'expenseCents', 'directMaterialCostCents']], ['transfers', ['amountCents']]]) { for (const item of state[key]) { if (typeof item.id !== 'string' || !Number.isSafeInteger(item.sequence) || !/^\d{4}-\d{2}-\d{2}$/.test(item.date)) throw new Error('演示交易格式无效。'); for (const amount of amounts) if (!Number.isSafeInteger(item[amount]) || item[amount] < 0) throw new Error('演示金额或重量格式无效。'); } } const lastDate = [...state.purchases, ...state.orders, ...state.transfers].reduce((latest, item) => item.date > latest ? item.date : latest, state.demo.startDate); buildReport(state, lastDate); return state; } function createStore(stateFile) { const resolved = path.resolve(stateFile); const temporaryRoot = path.resolve(os.tmpdir()); // 测试可另设临时文件;运行数据不能写进产品目录或正式账本。 if (!resolved.startsWith('/tmp/') && !resolved.startsWith(`${temporaryRoot}${path.sep}`)) throw new Error('演示持久文件必须显式位于系统临时目录。'); let state = fs.existsSync(resolved) ? validateStoredState(JSON.parse(fs.readFileSync(resolved, 'utf8'))) : createSeed(); function persist(next) { fs.mkdirSync(path.dirname(resolved), { recursive: true, mode: 0o700 }); const temporaryFile = `${resolved}.${process.pid}.new`; try { fs.writeFileSync(temporaryFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 }); fs.renameSync(temporaryFile, resolved); } finally { if (fs.existsSync(temporaryFile)) fs.unlinkSync(temporaryFile); } state = next; } if (!fs.existsSync(resolved)) persist(state); return { get: () => state, mutate(type, payload) { const next = applyCommand(state, type, payload); persist(next); return state; }, stateFile: resolved, }; } function createDemoServer(options = {}) { const store = createStore(options.stateFile || DEFAULT_STATE_FILE); const publicDirectory = path.resolve(options.publicDirectory || path.join(__dirname, 'public')); const server = http.createServer(async (req, res) => { function headers(contentType) { return { 'Content-Type': contentType, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Content-Security-Policy': "default-src 'self'; connect-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", }; } function json(status, data) { res.writeHead(status, headers('application/json; charset=utf-8')); res.end(JSON.stringify(data)); } try { const port = server.address().port; const permittedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]); if (!permittedHosts.has(req.headers.host)) throw new DemoError('INVALID_HOST', '本演示只接受本机地址。', undefined, 403); if (req.headers.origin !== undefined && req.headers.origin !== `http://${req.headers.host}`) throw new DemoError('INVALID_ORIGIN', '本演示只接受本机同源请求。', undefined, 403); const url = new URL(req.url, `http://${req.headers.host}`); if (url.pathname.startsWith('/api/')) { if (req.method === 'GET') { const date = url.searchParams.get('date') || undefined; if (url.pathname === '/api/demo/state') return json(200, { ok: true, data: publicState(store.get(), date) }); if (url.pathname === '/api/demo/report') return json(200, { ok: true, data: buildReport(store.get(), date) }); if (url.pathname === '/api/demo/purchase-preview') return json(200, { ok: true, data: purchasePreview({ grams: url.searchParams.get('grams'), total: url.searchParams.get('total') }) }); throw new DemoError('NOT_FOUND', '演示接口不存在。', undefined, 404); } if (req.method !== 'POST') throw new DemoError('METHOD_NOT_ALLOWED', '该演示接口只接受GET或POST。', undefined, 405); const match = /^\/api\/demo\/(opening|purchase|order|transfer|reset|scenario)$/.exec(url.pathname); if (!match) throw new DemoError('NOT_FOUND', '演示接口不存在。', undefined, 404); if (!(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) throw new DemoError('JSON_REQUIRED', '请以JSON对象提交演示数据。', undefined, 415); const chunks = []; let bytes = 0; for await (const chunk of req) { bytes += chunk.length; if (bytes > 65536) throw new DemoError('BODY_TOO_LARGE', '单次演示输入不能超过64KB。', undefined, 413); chunks.push(chunk); } let payload; try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new DemoError('INVALID_JSON', 'JSON内容无效。'); } // 同步原子落盘,保证并发请求不会丢单;验证全部通过后才替换持久状态。 const next = store.mutate(match[1], payload); const selectedDate = match[1] === 'reset' || match[1] === 'scenario' ? next.demo.defaultDate : (payload.date || next.demo.defaultDate); return json(200, { ok: true, data: publicState(next, selectedDate) }); } if (!['GET', 'HEAD'].includes(req.method)) throw new DemoError('METHOD_NOT_ALLOWED', '静态文件只支持GET。', undefined, 405); let requestedPath; try { requestedPath = decodeURIComponent(url.pathname); } catch { throw new DemoError('INVALID_PATH', '文件路径无效。'); } if (requestedPath.includes('\0') || requestedPath.includes('\\')) throw new DemoError('INVALID_PATH', '文件路径无效。'); const relative = requestedPath === '/' ? 'index.html' : requestedPath.replace(/^\/public\//, '').replace(/^\//, ''); const file = path.resolve(publicDirectory, relative); if (!file.startsWith(`${publicDirectory}${path.sep}`) || !MIME[path.extname(file)]) throw new DemoError('NOT_FOUND', '演示文件不存在。', undefined, 404); if (!fs.existsSync(file) || !fs.statSync(file).isFile() || !fs.realpathSync(file).startsWith(`${fs.realpathSync(publicDirectory)}${path.sep}`)) throw new DemoError('NOT_FOUND', '演示文件不存在。', undefined, 404); const content = fs.readFileSync(file); res.writeHead(200, { ...headers(MIME[path.extname(file)]), 'Content-Length': content.length }); res.end(req.method === 'HEAD' ? undefined : content); } catch (error) { if (res.headersSent) return res.destroy(); const known = error instanceof DemoError; json(known ? error.status : 500, { ok: false, error: { code: known ? error.code : 'INTERNAL_ERROR', message: known ? error.message : '演示服务暂时无法完成操作,原状态未修改。', ...(known && error.field ? { field: error.field } : {}) } }); } }); return server; } if (require.main === module) { try { const server = createDemoServer(); server.on('error', (error) => { process.stderr.write(error.code === 'EADDRINUSE' ? '3102端口已占用。若演示已经打开,请使用原窗口。\n' : `演示启动失败:${error.message}\n`); process.exitCode = 1; }); server.listen(DEFAULT_PORT, '127.0.0.1', () => { process.stdout.write(`周转金方案本地演示:http://127.0.0.1:${DEFAULT_PORT}\n仅虚构数据:${DEFAULT_STATE_FILE}\n按Control+C关闭。\n`); }); } catch (error) { process.stderr.write(`演示启动失败:${error.message}\n`); process.exitCode = 1; } } module.exports = { createDemoServer, DEFAULT_STATE_FILE, DEFAULT_PORT };