'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), crypto = require('node:crypto'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const { Ledger } = require('../ledger'); const { createApp, createUser } = require('../server'); const Employees = require('../employee-management'); const OWNER_PW = 'owner-secret-password-1', ASSISTANT_PW = 'assistant-secret-password-2', NEW_PW = 'owner-new-secret-password-3', WRONG_PW = 'wrong-secret-password-4', LONG_UA = 'SecurityAuditTest/1.0 ' + 'x'.repeat(300); async function start(t, options) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-security-audit-')); const app = createApp({ port: 0, dataDir: dir, feishuConfig: { enabled: false }, ...options }); 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 }); }); const base = 'http://127.0.0.1:' + app.server.address().port; const client = { cookie: '', tokens: [] }; client.call = async (route, data, { write = false } = {}) => { const r = await fetch(base + route, { method: data ? 'POST' : 'GET', headers: { 'User-Agent': LONG_UA, ...(client.cookie ? { Cookie: client.cookie } : {}), ...(data ? { 'Content-Type': 'application/json', Origin: base, 'X-Requested-With': 'maimai-ledger' } : {}), ...(write ? { 'Idempotency-Key': crypto.randomUUID() } : {}), }, body: data ? JSON.stringify(data) : undefined, }); const cookie = r.headers.get('set-cookie'); if (cookie?.startsWith('mm_session=') && !cookie.startsWith('mm_session=;')) { client.cookie = cookie.split(';')[0]; client.tokens.push(client.cookie.slice(11)); } const type = r.headers.get('content-type') || ''; return { status: r.status, body: type.includes('json') ? await r.json() : Buffer.from(await r.arrayBuffer()) }; }; return { app, client, base }; } const auditRows = ledger => ledger.rows('SELECT * FROM audit ORDER BY id').map(row => ({ ...row, detail: JSON.parse(row.detail) })); const securityRows = ledger => auditRows(ledger).filter(row => /^auth:/.test(row.entity) || ['export', 'backup'].includes(row.entity)); const last = (ledger, action) => securityRows(ledger).findLast(row => row.action === action); function assertRequestInfo(row) { assert.match(row.detail.ip, /127\.0\.0\.1/); assert.equal(row.detail.userAgent, LONG_UA.slice(0, 200)); } function assertNoSecrets(ledger, client) { const secrets = [OWNER_PW, ASSISTANT_PW, NEW_PW, WRONG_PW, ...client.tokens]; for (const token of client.tokens) secrets.push(crypto.createHash('sha256').update(token).digest('hex')); for (const u of ledger.rows('SELECT salt,hash FROM users')) secrets.push(u.salt, u.hash); for (const s of ledger.rows('SELECT hash FROM sessions')) secrets.push(s.hash); const rows = securityRows(ledger); assert.ok(rows.length > 0); for (const row of rows) { const text = JSON.stringify(row); for (const secret of secrets) assert.ok(!text.includes(secret), row.action + ' 的审计内容含有敏感信息'); for (const key of Object.keys(row.detail)) assert.ok(!/password|hash|salt|token|cookie/i.test(key), row.action + ' 的审计字段 ' + key + ' 不应出现'); } } test('初始化、登录成功/失败、修改本人密码、导出、备份下载与登出均登记安全审计,响应不变', async t => { const { app, client } = await start(t, { mode: 'trial' }); const ledger = app.ledger; const setup = await client.call('/api/setup', { ownerPassword: OWNER_PW, assistantPassword: ASSISTANT_PW }); assert.equal(setup.status, 200); assert.deepEqual(Object.keys(setup.body), ['user']); const ownerId = setup.body.user.id; let row = last(ledger, '初始化账号'); assert.equal(row.entity, 'auth:' + ownerId); assert.equal(row.actor, '麦麦'); assertRequestInfo(row); assert.deepEqual(row.detail.actorIdentity, { id: ownerId, role: 'owner', member: 'owner' }); // 登录失败:未知账号、未设置密码、密码错误;响应保持 401 与原文,不下发 cookie。 const unset = createUser(ledger, '未设密码员工', 'assistant', crypto.randomUUID(), null, { passwordSet: false }); const failures = [ [{ name: '不存在的员工' + 'z'.repeat(80), password: WRONG_PW }, 'auth:unknown', 'unknown_user'], [{ name: '未设密码员工', password: WRONG_PW }, 'auth:' + unset, 'password_not_set'], [{ name: '麦麦', password: WRONG_PW }, 'auth:' + ownerId, 'wrong_password'], [{ member: 'owner', password: WRONG_PW }, 'auth:' + ownerId, 'wrong_password'], [{ name: { toString: 1 }, password: WRONG_PW }, 'auth:unknown', 'unknown_user'], ]; for (const [input, entity, reason] of failures) { client.cookie = ''; const r = await client.call('/api/login', input); assert.equal(r.status, 401); assert.deepEqual(r.body, { error: '账号或密码不正确' }); assert.equal(client.cookie, ''); row = last(ledger, '登录失败'); assert.equal(row.entity, entity); assert.equal(row.actor, '未登录'); assert.equal(row.detail.reason, reason); const attempted = input.member ?? input.name; assert.equal(row.detail.loginName, typeof attempted === 'string' ? attempted.slice(0, 50) : null); assert.deepEqual(row.detail.actorIdentity, { id: null, role: 'system', member: null }); assertRequestInfo(row); } assert.equal(last(ledger, '登录失败').detail.loginName, null); assert.equal(securityRows(ledger).filter(r => r.action === '登录失败')[0].detail.loginName.length, 50); const login = await client.call('/api/login', { name: '麦麦', password: OWNER_PW }); assert.equal(login.status, 200); assert.equal(login.body.user.id, ownerId); row = last(ledger, '登录成功'); assert.equal(row.entity, 'auth:' + ownerId); assert.equal(row.actor, '麦麦'); assertRequestInfo(row); // 原密码错误:仍为 400 原文,密码不变;失败记录在回滚后另行写入,不随事务撤销。 const wrong = await client.call('/api/password', { current: WRONG_PW, password: NEW_PW }, { write: true }); assert.equal(wrong.status, 400); assert.deepEqual(wrong.body, { error: '原密码不正确' }); row = last(ledger, '修改本人密码失败'); assert.equal(row.entity, 'auth:' + ownerId); assert.equal(row.detail.reason, 'wrong_password'); assertRequestInfo(row); assert.equal(last(ledger, '修改本人密码'), undefined); // 新密码过短仍按原样拒绝,不登记成功。 const short = await client.call('/api/password', { current: OWNER_PW, password: 'short' }, { write: true }); assert.deepEqual([short.status, short.body], [400, { error: '新密码至少12个字符' }]); assert.equal(last(ledger, '修改本人密码'), undefined); // 导出与备份下载。 const csv = await client.call('/api/export/inventory'); assert.equal(csv.status, 200); assert.ok(csv.body.toString('utf8').startsWith('货盘,')); row = last(ledger, '导出库存CSV'); assert.equal(row.entity, 'export'); assert.equal(row.actor, '麦麦'); assertRequestInfo(row); const xlsx = await client.call('/api/inventory/movements/export.xlsx?kind=manual&from=2020-01-01&to=2099-12-31'); assert.equal(xlsx.status, 200); assert.equal(xlsx.body.subarray(0, 2).toString(), 'PK'); row = last(ledger, '导出库存流水Excel'); assert.equal(row.entity, 'export'); assert.equal(row.detail.filters.kind, 'manual'); assert.equal(row.detail.filters.from, '2020-01-01'); assert.equal(row.detail.filters.to, '2099-12-31'); assert.ok('pocket' in row.detail.filters && 'hideDeleted' in row.detail.filters); assertRequestInfo(row); // 导出失败不登记。 const badExport = await client.call('/api/inventory/movements/export.xlsx?kind=bogus'); assert.equal(badExport.status, 400); assert.equal(securityRows(ledger).filter(r => r.action === '导出库存流水Excel').length, 1); const backup = await client.call('/api/backup', {}); assert.equal(backup.status, 200); const download = await client.call('/api/backup/' + backup.body.name); assert.equal(download.status, 200); assert.equal(download.body.subarray(0, 15).toString(), 'SQLite format 3'); row = last(ledger, '下载备份'); assert.equal(row.entity, 'backup'); assert.equal(row.detail.file, backup.body.name); assertRequestInfo(row); assert.deepEqual((await client.call('/api/backup/ledger-2000-01-01T00-00-00-000Z.sqlite')).status, 404); assert.equal(securityRows(ledger).filter(r => r.action === '下载备份').length, 1); const changed = await client.call('/api/password', { current: OWNER_PW, password: NEW_PW }, { write: true }); assert.deepEqual([changed.status, changed.body], [200, { ok: true }]); row = last(ledger, '修改本人密码'); assert.equal(row.entity, 'auth:' + ownerId); assertRequestInfo(row); assert.equal((await client.call('/api/state')).status, 401, '改密后旧会话仍应失效'); await client.call('/api/login', { name: '麦麦', password: NEW_PW }); const logout = await client.call('/api/logout', {}); assert.deepEqual([logout.status, logout.body], [200, { ok: true }]); row = last(ledger, '登出'); assert.equal(row.entity, 'auth:' + ownerId); assert.equal(row.actor, '麦麦'); assertRequestInfo(row); assertNoSecrets(ledger, client); // 员工登录与失败尝试不算业务数据,删除资格不变。 client.cookie = ''; await client.call('/api/login', { name: '助理', password: ASSISTANT_PW }); await client.call('/api/inventory/movements/export.xlsx'); await client.call('/api/logout', {}); await client.call('/api/login', { name: '助理', password: WRONG_PW }); const assistant = Employees.list(ledger, {}, { id: ownerId, name: '麦麦', role: 'owner' }).employees.find( e => e.member === 'assistant', ); assert.equal(assistant.hasBusinessData, false); assert.equal(assistant.canDelete, true); }); test('演示登录登记安全审计,无效成员不登记', async t => { const { app, client } = await start(t, { mode: 'demo' }); const r = await client.call('/api/demo-login', { member: 'assistant' }); assert.equal(r.status, 200); assert.equal(r.body.user.member, 'assistant'); const row = last(app.ledger, '演示登录'); assert.equal(row.entity, 'auth:' + r.body.user.id); assert.equal(row.actor, r.body.user.name); assertRequestInfo(row); const invalid = await client.call('/api/demo-login', { member: 'nobody' }); assert.deepEqual([invalid.status, invalid.body], [400, { error: '演示成员无效' }]); assert.equal(securityRows(app.ledger).filter(row => row.action === '演示登录').length, 1); assertNoSecrets(app.ledger, client); }); test('审计写入失败不改变登录、登出与改密的响应', async t => { const ledger = new Ledger(':memory:'); createUser(ledger, '合成店主', 'owner', OWNER_PW); const { client } = await start(t, { mode: 'trial', ledger }); ledger.audit = () => { throw new Error('合成审计故障'); }; const errors = []; const original = console.error; console.error = message => errors.push(String(message)); t.after(() => (console.error = original)); const failed = await client.call('/api/login', { name: '不存在', password: WRONG_PW }); assert.deepEqual([failed.status, failed.body], [401, { error: '账号或密码不正确' }]); const ok = await client.call('/api/login', { name: '合成店主', password: OWNER_PW }); assert.equal(ok.status, 200); assert.equal(ok.body.user.name, '合成店主'); const wrong = await client.call('/api/password', { current: WRONG_PW, password: NEW_PW }, { write: true }); assert.deepEqual([wrong.status, wrong.body], [400, { error: '原密码不正确' }]); const changed = await client.call('/api/password', { current: OWNER_PW, password: NEW_PW }, { write: true }); assert.deepEqual([changed.status, changed.body], [200, { ok: true }]); await client.call('/api/login', { name: '合成店主', password: NEW_PW }); const logout = await client.call('/api/logout', {}); assert.deepEqual([logout.status, logout.body], [200, { ok: true }]); assert.ok(errors.length >= 5 && errors.every(e => e.includes('安全审计写入失败'))); });