quản lí robot

This commit is contained in:
2026-10-19 15:21:04 +07:00
parent 2be2e075a0
commit 0dc83be4e7
15 changed files with 2095 additions and 184 deletions

166
backend/documents.test.js Normal file
View File

@@ -0,0 +1,166 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
const XLSX = require('xlsx');
const files = require('./document-files');
function officeZip(mainPart) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, '[Content_Types].xml', Buffer.from('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'));
XLSX.CFB.utils.cfb_add(container, mainPart, Buffer.from('<document/>'));
return XLSX.CFB.write(container, { type: 'buffer', fileType: 'zip', compression: true });
}
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['Robot', 'Model'], ['Cộng tác', 'CR10']]), 'Robots');
const examples = {
'manual.pdf': Buffer.from('%PDF-1.4\nmanual\n%%EOF'),
'manual.docx': officeZip('word/document.xml'),
'inventory.xlsx': XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }),
'inventory.xls': XLSX.write(workbook, { type: 'buffer', bookType: 'xls' }),
'slides.pptx': officeZip('ppt/presentation.xml'),
'photo.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64'),
'notes.txt': Buffer.from('Tài liệu robot tiếng Việt'),
'rows.csv': Buffer.from('name,model\nRobot,CR10'),
'notes.rtf': Buffer.from('{\\rtf1\\ansi Hello}'),
'bundle.zip': officeZip('manual.txt')
};
function productionWithPool(pool) {
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sandbox = { require: name => name === 'dotenv' ? { config() {} } : localRequire(name),
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console, testPool: pool,
process: { env: { NODE_ENV: 'test', DOCUMENT_MAX_FILE_SIZE_MB: '1', DATA_ENCRYPTION_SECRET: 'documents-test-only-secret-more-than-32-characters' }, on() {} } };
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool = testPool;`, sandbox, { filename });
return sandbox.module.exports.app;
}
async function fixture(t) {
const stored = new Map();
let nextId = 1, writes = 0;
const pool = { request() {
const inputs = {};
return { input(name, _type, value) { inputs[name] = value; return this; }, async query(query) {
if (query.includes('INSERT INTO Documents')) {
const document = { DocumentId: nextId++, Title: inputs.title, OriginalFileName: inputs.originalFileName,
MimeType: inputs.mimeType, FileSize: inputs.fileSize, FileData: inputs.fileData,
UploadedBy: 1, UploadedDate: '2026-10-19T10:00:00', CanDelete: true };
stored.set(document.DocumentId, document); writes++;
return { recordset: [document] };
}
if (inputs.documentId) return { recordset: stored.has(inputs.documentId) ? [stored.get(inputs.documentId)] : [] };
return { recordset: [...stored.values()] };
} };
} };
const production = productionWithPool(pool);
const app = express();
app.use(express.json());
app.use((req, res, next) => { req.user = { UserId: 1, Role: 'admin' }; res.setHeader('Cache-Control', 'no-store'); next(); });
// Exercise the actual multipart middleware, validators, SQL parameters and response headers.
for (const layer of production.router.stack) {
if (!layer.route?.path.startsWith('/api/documents')) continue;
for (const method of Object.keys(layer.route.methods)) {
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
}
app.use(production.router.stack.at(-1).handle);
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = `http://127.0.0.1:${server.address().port}/api/documents`;
return { stored, writes: () => writes, request: (suffix = '', options) => fetch(`${base}${suffix}`, options) };
}
function upload(name, buffer, type = 'application/octet-stream') {
const body = new FormData(); body.append('file', new Blob([buffer], { type }), name); return { method: 'POST', body };
}
test('document uploads retain actual extensions, canonical MIME types and exact download bytes', async t => {
const f = await fixture(t);
for (const [name, buffer] of Object.entries(examples)) {
const created = await f.request('', upload(name, buffer));
assert.equal(created.status, 201, `${name}: ${await created.clone().text()}`);
const document = (await created.json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.MimeType, files.getDocumentFormat(name).mimeType);
const response = await f.request(`/${document.DocumentId}/file?download=1`);
assert.equal(response.status, 200);
assert.match(response.headers.get('content-disposition'), /^attachment;/);
assert.ok(response.headers.get('content-disposition').includes(name));
assert.deepEqual(Buffer.from(await response.arrayBuffer()), Buffer.from(buffer));
}
assert.equal(f.writes(), Object.keys(examples).length);
});
test('PDF/image/text previews use their correct types; Office and ZIP always download', async t => {
const f = await fixture(t);
for (const name of ['manual.pdf', 'photo.png', 'notes.txt', 'manual.docx', 'inventory.xlsx', 'bundle.zip']) {
const id = (await (await f.request('', upload(name, examples[name]))).json()).data.DocumentId;
const response = await f.request(`/${id}/file`);
const format = files.getDocumentFormat(name);
assert.equal(response.headers.get('content-type').split(';')[0], format.mimeType);
assert.match(response.headers.get('content-disposition'), format.preview ? /^inline;/ : /^attachment;/);
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
}
});
test('wrong extensions, fake Office packages, damaged PDFs and oversized uploads never write data', async t => {
const f = await fixture(t);
for (const [name, buffer] of [['malware.exe', Buffer.from('MZ')], ['page.html', Buffer.from('<script/>')],
['image.svg', Buffer.from('<svg/>')], ['fake.pdf', Buffer.from('not PDF')], ['fake.docx', examples['bundle.zip']],
['wrong.xlsx', examples['manual.docx']], ['fake.png', examples['manual.pdf']], ['empty.txt', Buffer.alloc(0)],
['oversized.txt', Buffer.alloc(1024 * 1024 + 1, 65)]]) {
assert.equal((await f.request('', upload(name, buffer))).status, 400, name);
}
assert.equal(f.writes(), 0);
});
test('Vietnamese filenames remain readable and long names retain their actual extension', async t => {
const f = await fixture(t);
const name = 'Hướng dẫn vận hành.docx';
const document = (await (await f.request('', upload(name, examples['manual.docx']))).json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.Title, 'Hướng dẫn vận hành');
const response = await f.request(`/${document.DocumentId}/file`);
assert.ok(response.headers.get('content-disposition').includes(encodeURIComponent(name)));
const longName = files.sanitizeDocumentFileName(`${'a'.repeat(300)}.xlsx`);
assert.equal(longName.length, 255); assert.ok(longName.endsWith('.xlsx'));
assert.doesNotMatch(files.getDocumentContentDisposition('report\r\n.xlsx', true), /[\r\n]/);
});
test('ZIP directory validation is bounded and does not accept mismatched Office files', () => {
const damaged = Buffer.from(examples['bundle.zip']);
damaged.writeUInt32LE(0xffffffff, damaged.length - 22 + 16);
assert.equal(files.zipEntryNames(damaged), null);
assert.throws(() => files.validateDocumentFile({ originalname: 'manual.docx', buffer: examples['slides.pptx'] }));
assert.throws(() => files.validateDocumentFile({ originalname: 'data.csv', buffer: Buffer.from([1, 2, 0, 3]) }));
});
test('legacy Word and PowerPoint require their own OLE streams and retain their file types', () => {
for (const [name, stream] of [['manual.doc', 'WordDocument'], ['slides.ppt', 'PowerPoint Document']]) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, stream, Buffer.from('Legacy Office document stream'));
const buffer = XLSX.CFB.write(container, { type: 'buffer', fileType: 'cfb' });
assert.equal(files.validateDocumentFile({ originalname: name, buffer }).mimeType, files.getDocumentFormat(name).mimeType);
}
assert.throws(() => files.validateDocumentFile({ originalname: 'not-word.doc', buffer: examples['inventory.xls'] }));
});
test('document controls show per-format icons/previews and accept the same supported extensions', () => {
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {}, DocumentFormats: require('../public/js/document-formats') }, console });
vm.runInContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, { apiBase: '/api', documentSearchTerm: '', documentMaxFileSizeMb: 25,
documents: Object.keys(examples).map((name, index) => ({ DocumentId: index + 1, OriginalFileName: name, Title: name, FileSize: 123 })),
escapeHtml: value => String(value || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') });
const html = manager.getDocumentsContent();
assert.match(html, /Xem PDF/); assert.match(html, /Xem Ảnh/);
assert.doesNotMatch(html, /Xem Word|Xem Excel/);
for (const name of Object.keys(examples)) assert.equal(manager.isSupportedDocumentName(name), true);
assert.equal(manager.isSupportedDocumentName('bad.exe'), false);
assert.match(html, /\.docx/); assert.match(html, /\.xlsx/); assert.match(html, /\.png/);
});