From 0dc83be4e79b4dbfecc2c16be53cf06f1b964f8e Mon Sep 17 00:00:00 2001 From: DungTT Date: Mon, 19 Oct 2026 15:21:04 +0700 Subject: [PATCH] =?UTF-8?q?qu=E1=BA=A3n=20l=C3=AD=20robot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 2 +- backend/document-files.js | 116 +++++++ backend/documents.test.js | 166 ++++++++++ backend/robot-schema.sql | 71 +++++ backend/robots-sql.test.js | 171 ++++++++++ backend/robots.js | 317 +++++++++++++++++++ backend/robots.test.js | 322 +++++++++++++++++++ backend/server.js | 88 +++--- database/setup.sql | 75 +++++ docs/README.md | 24 +- public/css/main.css | 2 +- public/css/responsive.css | 116 +++++++ public/js/app.js | 569 ++++++++++++++++++++++++++++++++-- public/js/document-formats.js | 26 ++ public/pages/index.html | 214 ++++++------- 15 files changed, 2095 insertions(+), 184 deletions(-) create mode 100644 backend/document-files.js create mode 100644 backend/documents.test.js create mode 100644 backend/robot-schema.sql create mode 100644 backend/robots-sql.test.js create mode 100644 backend/robots.js create mode 100644 backend/robots.test.js create mode 100644 public/js/document-formats.js diff --git a/.env.example b/.env.example index f283cc8..01e6354 100644 --- a/.env.example +++ b/.env.example @@ -44,5 +44,5 @@ SMTP_FROM= EMAIL_VERIFY_TOKEN_TTL_MINUTES=30 PASSWORD_RESET_TOKEN_TTL_MINUTES=30 -# Maximum size for each uploaded PDF document (1-100 MB). +# Maximum size for each uploaded document (1-100 MB), including robot attachments. DOCUMENT_MAX_FILE_SIZE_MB=25 diff --git a/backend/document-files.js b/backend/document-files.js new file mode 100644 index 0000000..848879e --- /dev/null +++ b/backend/document-files.js @@ -0,0 +1,116 @@ +const path = require('node:path'); +const { formats, accept, description } = require('../public/js/document-formats'); + +function documentError(message) { + return Object.assign(new Error(message), { status: 400, code: 'DOCUMENT_VALIDATION' }); +} + +function getDocumentFormat(fileName) { + return formats[path.extname(String(fileName || '')).toLowerCase()] || null; +} + +function isPdfBuffer(value) { + return Buffer.isBuffer(value) && value.length >= 10 + && value.subarray(0, 5).toString('ascii') === '%PDF-' + && value.subarray(Math.max(0, value.length - 2048)).includes(Buffer.from('%%EOF')); +} + +// Inspect the ZIP directory without inflating any entry, including oversized compressed data. +function zipEntryNames(buffer) { + if (buffer.length < 22) return null; + for (let end = buffer.length - 22; end >= Math.max(0, buffer.length - 65557); end--) { + if (buffer.readUInt32LE(end) !== 0x06054b50 || end + 22 + buffer.readUInt16LE(end + 20) !== buffer.length) continue; + if (buffer.readUInt16LE(end + 4) !== 0 || buffer.readUInt16LE(end + 6) !== 0) return null; + const count = buffer.readUInt16LE(end + 10); + if (count !== buffer.readUInt16LE(end + 8)) return null; + const size = buffer.readUInt32LE(end + 12), offset = buffer.readUInt32LE(end + 16); + if (offset + size !== end) return null; + const names = new Set(); + let cursor = offset; + for (let index = 0; index < count; index++) { + if (cursor + 46 > end || buffer.readUInt32LE(cursor) !== 0x02014b50) return null; + const nameSize = buffer.readUInt16LE(cursor + 28), extraSize = buffer.readUInt16LE(cursor + 30), commentSize = buffer.readUInt16LE(cursor + 32); + const next = cursor + 46 + nameSize + extraSize + commentSize; + if (next > end) return null; + const localOffset = buffer.readUInt32LE(cursor + 42); + if (localOffset + 30 > offset || buffer.readUInt32LE(localOffset) !== 0x04034b50) return null; + const dataStart = localOffset + 30 + buffer.readUInt16LE(localOffset + 26) + buffer.readUInt16LE(localOffset + 28); + if (dataStart + buffer.readUInt32LE(cursor + 20) > offset) return null; + names.add(buffer.toString('utf8', cursor + 46, cursor + 46 + nameSize)); + cursor = next; + } + return cursor === offset + size ? names : null; + } + return null; +} + +function isCompoundFile(buffer) { + return buffer.length >= 512 && buffer.subarray(0, 8).equals(Buffer.from('d0cf11e0a1b11ae1', 'hex')); +} + +function hasStream(buffer, name) { return buffer.includes(Buffer.from(`${name}\0`, 'utf16le')); } + +function documentContentMatches(buffer, extension) { + if (!Buffer.isBuffer(buffer) || !buffer.length) return false; + const starts = hex => buffer.length >= hex.length / 2 && buffer.subarray(0, hex.length / 2).equals(Buffer.from(hex, 'hex')); + const textStart = buffer.subarray(0, 8192).toString('utf8').trimStart(); + switch (extension) { + case '.pdf': return isPdfBuffer(buffer); + case '.png': return buffer.length >= 24 && starts('89504e470d0a1a0a'); + case '.jpg': case '.jpeg': return buffer.length >= 12 && starts('ffd8ff'); + case '.gif': return buffer.length >= 13 && ['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6)); + case '.webp': return buffer.length >= 12 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP'; + case '.bmp': return buffer.length >= 26 && starts('424d'); + case '.tif': case '.tiff': return buffer.length >= 8 && (starts('49492a00') || starts('4d4d002a')); + case '.txt': case '.csv': + if (buffer.length >= 4 && (starts('fffe') || starts('feff'))) return buffer.length % 2 === 0; + return !buffer.some(byte => byte < 32 && ![9, 10, 13].includes(byte)); + case '.rtf': return textStart.startsWith('{\\rtf'); + case '.doc': return (isCompoundFile(buffer) && hasStream(buffer, 'WordDocument')) || textStart.startsWith('{\\rtf'); + case '.xls': return (isCompoundFile(buffer) && (hasStream(buffer, 'Workbook') || hasStream(buffer, 'Book'))) + || (buffer.length >= 8 && [0x0009, 0x0209, 0x0409, 0x0809].includes(buffer.readUInt16LE(0))) + || (textStart.includes('urn:schemas-microsoft-com:office:spreadsheet') && / character.charCodeAt(0) > 255)) return name; + const bytes = Buffer.from(name, 'latin1'), decoded = bytes.toString('utf8'); + return Buffer.from(decoded, 'utf8').equals(bytes) ? decoded : name; +} + +function sanitizeDocumentFileName(value) { + const cleaned = String(value || 'document.pdf').replace(/[\u0000-\u001f\u007f]/g, '') + .replace(/[\\/:*?"<>|]/g, '_').trim(); + const extension = path.extname(cleaned) || '.pdf'; + const base = path.extname(cleaned) ? cleaned.slice(0, -extension.length) : cleaned; + return `${(base || 'document').slice(0, Math.max(1, 255 - extension.length))}${extension.slice(0, 254)}`; +} + +function getDocumentContentDisposition(fileName, download = false) { + const safeName = sanitizeDocumentFileName(fileName); + const asciiName = safeName.normalize('NFKD').replace(/[^\x20-\x7e]/g, '').replace(/["\\]/g, '_').trim() || 'document'; + const encodedName = encodeURIComponent(safeName).replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`); + return `${download ? 'attachment' : 'inline'}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`; +} + +module.exports = { formats, accept, description, getDocumentFormat, isPdfBuffer, validateDocumentFile, + normalizeUploadedFileName, sanitizeDocumentFileName, getDocumentContentDisposition, zipEntryNames }; diff --git a/backend/documents.test.js b/backend/documents.test.js new file mode 100644 index 0000000..fe621e8 --- /dev/null +++ b/backend/documents.test.js @@ -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('')); + XLSX.CFB.utils.cfb_add(container, mainPart, Buffer.from('')); + 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('', Model: 'CR10', TypeId: 1, Type: 'Cộng tác', DocumentCount: 2 }], + robotTypes: [{ TypeId: 1, Name: 'Cộng tác', RobotCount: 1 }], + apiBase: '/api', currentUser: { Role: 'user' }, robotPage: 1, robotPageSize: 12, robotSearchTerm: '', robotTypeFilter: '', + robotLoadError: '', escapeHtml: value => String(value ?? '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') }); + let html = manager.getRobotsContent(); + assert.match(html, /<script>Robot/); + assert.doesNotMatch(html, / @@ -46,25 +46,6 @@ transform: scale(1); } - .tree-label { - letter-spacing: 0.08em; - text-transform: uppercase; - font-size: 10px; - font-weight: 800; - color: #64748b; - padding: 0 0.75rem; - margin-bottom: 0.35rem; - } - - .tree-branch { - margin-left: 0.75rem; - border-left: 1px dashed rgba(100, 116, 139, 0.5); - padding-left: 0.6rem; - display: flex; - flex-direction: column; - gap: 0.2rem; - } - body.app-shell { overflow: hidden; } @@ -268,102 +249,126 @@ } - + -