diff --git a/新账系统/.prettierignore b/新账系统/.prettierignore index 4567104..496fe99 100644 --- a/新账系统/.prettierignore +++ b/新账系统/.prettierignore @@ -14,6 +14,8 @@ data/ backups/ node_modules/ e2e/node_modules/ +# 新版界面有自己的格式化与构建产物。 +web/ *.md *.html *.json diff --git a/新账系统/eslint.config.js b/新账系统/eslint.config.js index c82825a..acdb308 100644 --- a/新账系统/eslint.config.js +++ b/新账系统/eslint.config.js @@ -21,7 +21,8 @@ const sharedScriptGlobals = Object.keys(browserScripts).map(file => ({ module.exports = [ { - ignores: ['node_modules/', 'e2e/node_modules/', 'e2e/out/', 'e2e/baseline/', 'data/', 'backups/'], + // web/ 是新版界面(TypeScript + React),有自己的 ESLint 配置与依赖。 + ignores: ['node_modules/', 'e2e/node_modules/', 'e2e/out/', 'e2e/baseline/', 'data/', 'backups/', 'web/'], }, js.configs.recommended, { diff --git a/新账系统/server/dispatcher.js b/新账系统/server/dispatcher.js index eb76ca6..a7712e3 100644 --- a/新账系统/server/dispatcher.js +++ b/新账系统/server/dispatcher.js @@ -22,6 +22,7 @@ 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 = { @@ -63,7 +64,7 @@ async function runRoute(route, ctx) { } // 处理顺序:安全响应头 → Host/405/来源校验 → 登录前路由 → 解析当前账号 → /api/、/print/ 的 401/409 -// → 路由(含未匹配)→ 静态文件 → 统一错误响应。 +// → 路由(含未匹配)→ 新版界面 /next/(启用时)→ 静态文件 → 统一错误响应。 function createHandler(app, routes) { const router = createRouter(routes); const enabled = route => !route.when || route.when(app); @@ -91,6 +92,7 @@ function createHandler(app, routes) { 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); diff --git a/新账系统/server/middleware/web-next.js b/新账系统/server/middleware/web-next.js new file mode 100644 index 0000000..e657b68 --- /dev/null +++ b/新账系统/server/middleware/web-next.js @@ -0,0 +1,62 @@ +'use strict'; +// 新版界面(web/dist 的生产构建)挂在 /next/ 下:试用、演示模式默认开启;云端仅在 WEB_NEXT=1 时开启。 +// 带扩展名的路径按资源文件查找,找不到就 404;其余 /next、/next/* 一律返回 index.html(单页应用回退)。 +// 路径解码后必须仍落在 web/dist 之内,否则按未知地址 404。 +const fs = require('node:fs'); +const path = require('node:path'); +const { fail } = require('../../core/ledger'); +const DIST_DIR = path.join(__dirname, '..', '..', 'web', 'dist'); +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'application/javascript; charset=utf-8', + '.mjs': 'application/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ttf': 'font/ttf', + '.txt': 'text/plain; charset=utf-8', + '.map': 'application/json; charset=utf-8', +}; +const isNextPath = pathname => pathname === '/next' || pathname.startsWith('/next/'); +function webNextEnabled(app) { + return app.mode === 'demo' || app.mode === 'trial' || process.env.WEB_NEXT === '1'; +} +function readFile(file) { + try { + const stat = fs.statSync(file); + return stat.isFile() ? fs.readFileSync(file) : null; + } catch { + return null; + } +} +function serveWebNext(res, pathname, isPost, { distDir = DIST_DIR } = {}) { + if (isPost) fail('地址不存在', 404); + let relative; + try { + relative = decodeURIComponent(pathname.slice('/next'.length)); + } catch { + fail('地址不存在', 404); + } + if (relative.includes('\0') || relative.includes('\\')) fail('地址不存在', 404); + const root = path.resolve(distDir); + const target = path.resolve(root, '.' + path.posix.normalize('/' + relative)); + if (target !== root && !target.startsWith(root + path.sep)) fail('地址不存在', 404); + const last = relative.split('/').pop(); + const asset = last.includes('.'); + const file = asset ? target : path.join(root, 'index.html'); + const type = TYPES[path.extname(file).toLowerCase()]; + const body = type ? readFile(file) : null; + if (!body) fail('地址不存在', 404); + // 直接写出原始字节:通用 send() 会把 JSON 类型的内容再序列化一次。 + res.writeHead(200, { 'Content-Type': type }); + res.end(body); +} +module.exports = { serveWebNext, webNextEnabled, isNextPath, DIST_DIR }; diff --git a/新账系统/test/web-next-static.test.js b/新账系统/test/web-next-static.test.js new file mode 100644 index 0000000..f5b1e49 --- /dev/null +++ b/新账系统/test/web-next-static.test.js @@ -0,0 +1,204 @@ +'use strict'; +// 新版界面 /next/:资源类型、单页回退、目录限制,以及按模式开启(云端需 WEB_NEXT=1)。 +const test = require('node:test'), + assert = require('node:assert/strict'), + fs = require('node:fs'), + http = require('node:http'), + os = require('node:os'), + path = require('node:path'); +const { createApp } = require('../server'); +const { serveWebNext, webNextEnabled, isNextPath, DIST_DIR } = require('../server/middleware/web-next'); + +function fakeDist(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-dist-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.mkdirSync(path.join(dir, 'assets')); + fs.writeFileSync(path.join(dir, 'index.html'), 'next'); + fs.writeFileSync(path.join(dir, 'assets', 'app-1.js'), 'console.log(1)'); + fs.writeFileSync(path.join(dir, 'assets', 'app-1.css'), 'body{}'); + fs.writeFileSync(path.join(dir, 'assets', 'data.json'), '{"a":1}'); + fs.writeFileSync(path.join(dir, 'assets', 'logo.svg'), ''); + fs.writeFileSync(path.join(dir, 'assets', 'unknown.bin'), 'x'); + fs.writeFileSync(path.join(path.dirname(dir), path.basename(dir) + '-secret.txt'), 'secret'); + t.after(() => fs.rmSync(path.join(path.dirname(dir), path.basename(dir) + '-secret.txt'), { force: true })); + return dir; +} +function call(pathname, distDir, isPost = false) { + const res = { + status: null, + headers: null, + body: null, + writeHead(status, headers) { + this.status = status; + this.headers = headers; + }, + end(body) { + this.body = Buffer.from(body).toString('utf8'); + }, + }; + try { + serveWebNext(res, pathname, isPost, { distDir }); + } catch (error) { + return { status: error.status, error: error.message }; + } + return { status: res.status, type: res.headers['Content-Type'], body: res.body }; +} + +test('isNextPath 只匹配 /next 与 /next/ 开头,不误伤相似前缀', () => { + for (const p of ['/next', '/next/', '/next/create', '/next/assets/a.js']) assert.equal(isNextPath(p), true, p); + for (const p of ['/', '/nextx', '/next.js', '/api/next', '/print/next']) assert.equal(isNextPath(p), false, p); +}); + +test('资源按扩展名给出正确类型并原样返回字节(JSON 不被二次序列化)', t => { + const dir = fakeDist(t); + assert.deepEqual(call('/next/assets/app-1.js', dir), { + status: 200, + type: 'application/javascript; charset=utf-8', + body: 'console.log(1)', + }); + assert.equal(call('/next/assets/app-1.css', dir).type, 'text/css; charset=utf-8'); + assert.equal(call('/next/assets/logo.svg', dir).type, 'image/svg+xml'); + assert.deepEqual(call('/next/assets/data.json', dir), { + status: 200, + type: 'application/json; charset=utf-8', + body: '{"a":1}', + }); + assert.equal(call('/next/index.html', dir).type, 'text/html; charset=utf-8'); +}); + +test('非资源路径回退到 index.html;缺失或未知类型的资源 404,不回退', t => { + const dir = fakeDist(t); + for (const p of ['/next', '/next/', '/next/create', '/next/login', '/next/a/b/c', '/next/assets']) + assert.deepEqual( + call(p, dir), + { status: 200, type: 'text/html; charset=utf-8', body: 'next' }, + p, + ); + for (const p of ['/next/assets/missing.js', '/next/missing.css', '/next/assets/unknown.bin']) + assert.deepEqual(call(p, dir), { status: 404, error: '地址不存在' }, p); + assert.deepEqual(call('/next/', dir, true), { status: 404, error: '地址不存在' }); +}); + +test('路径限制在 dist 目录内:解码后的 ..、反斜杠与空字节都不能越界', t => { + const dir = fakeDist(t), + secret = '/next/..%2F' + path.basename(dir) + '-secret.txt'; + for (const p of [ + secret, + '/next/%2e%2e/%2e%2e/package.json', + '/next/assets/..%2f..%2f' + path.basename(dir) + '-secret.txt', + '/next/..%5c..%5cpackage.json', + '/next/a%00.js', + '/next/%E0%A4%A', + ]) { + const r = call(p, dir); + assert.notEqual(r.body, 'secret', p); + assert.equal(r.status, 404, p); + } +}); + +test('webNextEnabled:试用、演示默认开启;云端只在 WEB_NEXT=1 时开启', t => { + const saved = process.env.WEB_NEXT; + t.after(() => (saved === undefined ? delete process.env.WEB_NEXT : (process.env.WEB_NEXT = saved))); + delete process.env.WEB_NEXT; + assert.equal(webNextEnabled({ mode: 'trial' }), true); + assert.equal(webNextEnabled({ mode: 'demo' }), true); + assert.equal(webNextEnabled({ mode: 'production' }), false); + process.env.WEB_NEXT = 'true'; + assert.equal(webNextEnabled({ mode: 'production' }), false); + process.env.WEB_NEXT = '1'; + assert.equal(webNextEnabled({ mode: 'production' }), true); +}); + +function request(port, pathname, { host = '127.0.0.1:' + port, method = 'GET', headers = {} } = {}) { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, path: pathname, method, headers: { Host: host, ...headers } }); + req.on('response', res => { + const chunks = []; + res.on('data', c => chunks.push(c)); + res.on('end', () => + resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString('utf8') }), + ); + }); + req.on('error', reject); + req.end(); + }); +} +async function startApp(t, mode, extra = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-app-')); + const app = createApp({ mode, port: 0, dataDir: dir, feishuConfig: { enabled: false }, ...extra }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + t.after(async () => { + await new Promise(r => { + app.server.closeAllConnections(); + app.server.close(r); + }); + app.ledger.close(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + return app.server.address().port; +} + +const hasDist = fs.existsSync(path.join(DIST_DIR, 'index.html')); + +test('HTTP:试用模式提供 /next/ 页面与资源,带安全响应头;旧界面与未知地址行为不变', { skip: !hasDist }, async t => { + const port = await startApp(t, 'trial'); + const index = await request(port, '/next/'); + assert.equal(index.status, 200); + assert.match(index.headers['content-type'], /^text\/html/); + assert.match(index.headers['content-security-policy'], /script-src 'self';/); + assert.equal(index.headers['x-content-type-options'], 'nosniff'); + const deep = await request(port, '/next/create?draft=1'); + assert.equal(deep.body, index.body); + const script = index.body.match(/src="(\/next\/assets\/[^"]+\.js)"/)?.[1]; + assert.ok(script, '入口脚本应使用 /next/assets/ 绝对路径'); + const js = await request(port, script); + assert.equal(js.status, 200); + assert.match(js.headers['content-type'], /^application\/javascript/); + assert.equal((await request(port, '/next/assets/no-such-file.js')).status, 404); + assert.equal((await request(port, '/next/..%2Fpackage.json')).status, 404); + const old = await request(port, '/'); + assert.equal(old.status, 200); + assert.match(old.body, /\/app\.js/); + assert.equal((await request(port, '/nextx')).status, 404); + const post = await request(port, '/next/', { + method: 'POST', + headers: { + Origin: 'http://127.0.0.1:' + port, + 'X-Requested-With': 'maimai-ledger', + 'Content-Type': 'application/json', + }, + }); + assert.equal(post.status, 404); +}); + +test('HTTP:演示模式同样开启 /next/', { skip: !hasDist }, async t => { + const port = await startApp(t, 'demo'); + assert.equal((await request(port, '/next/')).status, 200); +}); + +test('HTTP:云端模式默认不提供 /next/(按未知地址 404),设置 WEB_NEXT=1 后提供', { skip: !hasDist }, async t => { + const names = ['PUBLIC_URL', 'DATA_DIR', 'OWNER_INITIAL_PASSWORD', 'ASSISTANT_INITIAL_PASSWORD', 'WEB_NEXT']; + const saved = Object.fromEntries(names.map(name => [name, process.env[name]])); + t.after(() => { + for (const name of names) saved[name] === undefined ? delete process.env[name] : (process.env[name] = saved[name]); + }); + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-prod-')); + t.after(() => fs.rmSync(dataDir, { recursive: true, force: true })); + Object.assign(process.env, { + PUBLIC_URL: 'https://shop.example.test', + DATA_DIR: dataDir, + OWNER_INITIAL_PASSWORD: 'production-owner-pass', + ASSISTANT_INITIAL_PASSWORD: 'production-assistant-pass', + }); + delete process.env.WEB_NEXT; + const port = await startApp(t, 'production', { dataDir, host: '127.0.0.1' }); + const host = 'shop.example.test'; + const off = await request(port, '/next/', { host }); + assert.equal(off.status, 404); + assert.deepEqual(JSON.parse(off.body), { error: '地址不存在' }); + assert.equal((await request(port, '/', { host })).status, 200); + process.env.WEB_NEXT = '1'; + const on = await request(port, '/next/', { host }); + assert.equal(on.status, 200); + assert.match(on.headers['content-type'], /^text\/html/); +});