import assert from 'node:assert/strict'; import { after, before, test } from 'node:test'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; import { closeDatabases, getDatabase } from '../lib/server/database.ts'; import { attachmentIds, storeUpload, syncDemandAttachments, commitDemandAttachments, downloadAttachment, deleteStagedAttachment, listStagedAttachments } from '../lib/server/attachments.ts'; import { MAX_ATTACHMENT_BYTES } from '../lib/attachments.ts'; import { emptyFields, type Demand } from '../lib/demand.ts'; const directory = mkdtempSync(join(tmpdir(), 'demand-attachments-test-')); const previousEnvironment = { ...process.env }; let ownerId: string; before(() => { process.env.DATA_DIR = directory; process.env.APP_URL = 'https://attachments.example.test'; process.env.INITIAL_ADMIN_USERNAME = 'attachment_owner'; process.env.INITIAL_ADMIN_PASSWORD = 'Temporary test password 48362'; ownerId = getDatabase().prepare('SELECT id FROM accounts').first<{ id: string }>()!.id; }); after(() => { closeDatabases(); process.env = previousEnvironment; rmSync(directory, { recursive: true, force: true }); }); const now = () => new Date().toISOString(); function record(): Demand { return { id: randomUUID(), revision: 1, fields: { ...emptyFields }, status: '草稿', reviewReady: false, createdAt: now(), updatedAt: now(), history: [], changes: [] }; } function insert(d: Demand) { getDatabase().prepare('INSERT INTO demands (id, owner_id, payload, updated_at) VALUES (?, ?, ?, ?)').bind(d.id, ownerId, JSON.stringify(d), now()).run(); } function save(d: Demand, ids: string[]) { getDatabase().transaction(() => { syncDemandAttachments(d, ownerId, ids, now()); getDatabase().prepare('UPDATE demands SET payload = ? WHERE id = ?').bind(JSON.stringify(d), d.id).run(); commitDemandAttachments(d, ownerId); }); } test('version 1 databases gain attachment storage without changing existing accounts or demands', () => { const d = record(); insert(d); closeDatabases(); const native = new DatabaseSync(join(directory, 'demand-center.sqlite')); native.exec('DROP TABLE attachments; DROP TABLE feishu_notifications; DROP TABLE feishu_oauth_states; DROP TABLE feishu_identities; PRAGMA user_version = 1;'); native.close(); const database = getDatabase(); assert.equal(database.prepare('PRAGMA user_version').first<{ user_version: number }>()!.user_version, 3); assert.equal(database.prepare('SELECT id FROM accounts').first<{ id: string }>()!.id, ownerId); assert.equal(database.prepare('SELECT id FROM demands WHERE id = ?').bind(d.id).first<{ id: string }>()!.id, d.id); assert.equal(listStagedAttachments(ownerId).length, 0); }); test('uploads enforce size, filename and attachment count; staged data stays private and recoverable', () => { assert.throws(() => storeUpload(ownerId, 'empty.txt', new Uint8Array()), /空文件/); assert.throws(() => storeUpload(ownerId, 'large.bin', new Uint8Array(MAX_ATTACHMENT_BYTES + 1)), /20 MB/); assert.throws(() => attachmentIds(Array.from({ length: 11 }, () => randomUUID())), /最多 10/); const ids = Array.from({ length: 10 }, (_, i) => storeUpload(ownerId, `文件${i}.txt`, new Uint8Array([i]))); assert.equal(listStagedAttachments(ownerId).length, 10); assert.throws(() => storeUpload(ownerId, 'extra.txt', new Uint8Array([1])), /未保存附件/); assert.throws(() => downloadAttachment(ids[0].id, { userId: 'unrelated-account', role: 'user' }), /没有访问权限/); assert.throws(() => attachmentIds([ids[0].id, ids[0].id]), /附件列表无效/); ids.forEach(file => deleteStagedAttachment(file.id, ownerId)); }); test('failed demand saves do not claim uploads, and bound files cannot be stolen by another demand', () => { const d = record(); insert(d); const file = storeUpload(ownerId, '../需求说明\n.txt', new Uint8Array([1, 2, 3])); assert.equal(file.name, '.._需求说明_.txt'); assert.throws(() => getDatabase().transaction(() => { syncDemandAttachments(d, ownerId, [file.id], now()); commitDemandAttachments(d, ownerId); throw new Error('Simulated failed save'); }), /Simulated/); assert.equal(listStagedAttachments(ownerId).some(item => item.id === file.id), true); save(d, [file.id]); assert.throws(() => deleteStagedAttachment(file.id, ownerId), /已保存/); const other = record(); insert(other); assert.throws(() => save(other, [file.id]), /附件已失效或无法访问/); save(d, []); assert.throws(() => downloadAttachment(file.id, { userId: ownerId, role: 'user' }), /找不到/); }); test('expired uploads are rejected and removed during the next upload', () => { const file = storeUpload(ownerId, 'expired.txt', new Uint8Array([1])); getDatabase().prepare('UPDATE attachments SET created_at = ? WHERE id = ?').bind('2000-01-01T00:00:00Z', file.id).run(); const d = record(); insert(d); assert.throws(() => save(d, [file.id]), /附件已失效/); assert.throws(() => downloadAttachment(file.id, { userId: ownerId, role: 'user' }), /找不到/); const next = storeUpload(ownerId, 'next.txt', new Uint8Array([2])); assert.equal(getDatabase().prepare('SELECT id FROM attachments WHERE id = ?').bind(file.id).first(), null); deleteStagedAttachment(next.id, ownerId); }); test('administrator downloads follow formal-demand visibility and never expose private drafts', () => { const admin = { userId: 'observing-admin', role: 'admin' as const }; const other = { userId: 'unrelated-user', role: 'user' as const }; const file = storeUpload(ownerId, '管理员查看范围.txt', new Uint8Array([10, 20, 30])); assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/); const d = record(); // Even a stale developer assignment must not make a private draft visible. d.review = { developer: { userId: admin.userId, username: 'admin', displayName: '管理员' }, proposals: [] }; insert(d); save(d, [file.id]); assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/); assert.deepEqual([...downloadAttachment(file.id, { userId: ownerId, role: 'admin' }).bytes], [10, 20, 30]); d.status = '待评审'; delete d.review; save(d, [file.id]); assert.deepEqual([...downloadAttachment(file.id, admin).bytes], [10, 20, 30]); assert.throws(() => downloadAttachment(file.id, other), /没有访问权限/); d.status = '草稿'; save(d, [file.id]); assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/); save(d, []); });