quản lí robot
This commit is contained in:
116
backend/document-files.js
Normal file
116
backend/document-files.js
Normal file
@@ -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') && /<Workbook\b/.test(textStart));
|
||||
case '.ppt': return isCompoundFile(buffer) && hasStream(buffer, 'PowerPoint Document');
|
||||
case '.docx': case '.xlsx': case '.pptx': {
|
||||
if (isCompoundFile(buffer) && hasStream(buffer, 'EncryptedPackage') && hasStream(buffer, 'EncryptionInfo')) return true;
|
||||
const names = zipEntryNames(buffer);
|
||||
const mainPart = { '.docx': 'word/document.xml', '.xlsx': 'xl/workbook.xml', '.pptx': 'ppt/presentation.xml' }[extension];
|
||||
return Boolean(names?.has('[Content_Types].xml') && names.has(mainPart));
|
||||
}
|
||||
case '.zip': return zipEntryNames(buffer) !== null;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validateDocumentFile(file) {
|
||||
const extension = path.extname(String(file.originalname || '')).toLowerCase();
|
||||
const format = formats[extension];
|
||||
if (!format) throw documentError(`Định dạng chưa được hỗ trợ. Chấp nhận: ${description}.`);
|
||||
if (!documentContentMatches(file.buffer, extension)) throw documentError(`Nội dung file không đúng định dạng ${extension} hoặc file bị hỏng`);
|
||||
return format;
|
||||
}
|
||||
|
||||
function normalizeUploadedFileName(value) {
|
||||
const name = String(value || '');
|
||||
if ([...name].some(character => 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 };
|
||||
166
backend/documents.test.js
Normal file
166
backend/documents.test.js
Normal 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, '<').replace(/>/g, '>') });
|
||||
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/);
|
||||
});
|
||||
71
backend/robot-schema.sql
Normal file
71
backend/robot-schema.sql
Normal file
@@ -0,0 +1,71 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF OBJECT_ID('dbo.RobotTypes', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.RobotTypes (
|
||||
TypeId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||
Name NVARCHAR(100) NOT NULL,
|
||||
Description NVARCHAR(500) NULL,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
CONSTRAINT UQ_RobotTypes_Name UNIQUE (Name)
|
||||
);
|
||||
END;
|
||||
IF OBJECT_ID('dbo.Robots', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.Robots (
|
||||
RobotId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||
Name NVARCHAR(255) NOT NULL,
|
||||
Model NVARCHAR(255) NOT NULL,
|
||||
Type NVARCHAR(100) NOT NULL,
|
||||
AvatarData VARBINARY(MAX) NULL,
|
||||
AvatarMimeType NVARCHAR(100) NULL,
|
||||
CreatedBy INT NULL,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
CONSTRAINT FK_Robots_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
|
||||
);
|
||||
CREATE INDEX IX_Robots_Name ON dbo.Robots(Name);
|
||||
END;
|
||||
IF COL_LENGTH('dbo.Robots', 'TypeId') IS NULL
|
||||
ALTER TABLE dbo.Robots ADD TypeId INT NULL;
|
||||
|
||||
-- A separate compilation scope is required when TypeId was just added.
|
||||
-- Only unmigrated rows seed the catalog, so renamed types stay renamed.
|
||||
EXEC(N'
|
||||
INSERT INTO dbo.RobotTypes (Name)
|
||||
SELECT DISTINCT COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
|
||||
FROM dbo.Robots r
|
||||
WHERE r.TypeId IS NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM dbo.RobotTypes t
|
||||
WHERE t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
|
||||
);
|
||||
UPDATE r SET TypeId = t.TypeId, Type = t.Name
|
||||
FROM dbo.Robots r JOIN dbo.RobotTypes t
|
||||
ON t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
|
||||
WHERE r.TypeId IS NULL;
|
||||
');
|
||||
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'TypeId' AND is_nullable = 1)
|
||||
EXEC(N'ALTER TABLE dbo.Robots ALTER COLUMN TypeId INT NOT NULL;');
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_Robots_Type')
|
||||
EXEC(N'ALTER TABLE dbo.Robots ADD CONSTRAINT FK_Robots_Type FOREIGN KEY (TypeId) REFERENCES dbo.RobotTypes(TypeId);');
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'IX_Robots_TypeId')
|
||||
EXEC(N'CREATE INDEX IX_Robots_TypeId ON dbo.Robots(TypeId);');
|
||||
IF OBJECT_ID('dbo.RobotDocuments', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.RobotDocuments (
|
||||
RobotId INT NOT NULL,
|
||||
DocumentId INT NOT NULL,
|
||||
CONSTRAINT PK_RobotDocuments PRIMARY KEY (RobotId, DocumentId),
|
||||
CONSTRAINT FK_RobotDocuments_Robot FOREIGN KEY (RobotId) REFERENCES dbo.Robots(RobotId) ON DELETE CASCADE,
|
||||
CONSTRAINT FK_RobotDocuments_Document FOREIGN KEY (DocumentId) REFERENCES dbo.Documents(DocumentId)
|
||||
);
|
||||
CREATE INDEX IX_RobotDocuments_DocumentId ON dbo.RobotDocuments(DocumentId);
|
||||
END;
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
171
backend/robots-sql.test.js
Normal file
171
backend/robots-sql.test.js
Normal file
@@ -0,0 +1,171 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const express = require('express');
|
||||
const sql = require('mssql');
|
||||
const { createRobotRouter, ensureRobotSchema } = require('./robots');
|
||||
|
||||
// Explicit opt-in to a disposable loopback SQL Server; never load application credentials.
|
||||
test('SQL Server preserves shared PDFs, migrates repeatedly, and rolls back an entire failed robot save', {
|
||||
skip: process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1' ? false
|
||||
: 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 and explicit local SQL test credentials',
|
||||
timeout: 120000
|
||||
}, async () => {
|
||||
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
|
||||
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
|
||||
assert.ok(password, 'Explicit local test password is required');
|
||||
assert.ok(Number.isInteger(port) && port > 0 && port < 65536);
|
||||
const database = `AccManagerRobotsTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
|
||||
const config = { server: '127.0.0.1', port, user: 'sa', password, database: 'master',
|
||||
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true, useUTC: false },
|
||||
pool: { min: 0, max: 3, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 30000 };
|
||||
const admin = await new sql.ConnectionPool(config).connect();
|
||||
let pool, server, created = false;
|
||||
try {
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await pool.request().batch(`
|
||||
CREATE TABLE dbo.Users (UserId INT IDENTITY PRIMARY KEY, Username NVARCHAR(100));
|
||||
INSERT dbo.Users (Username) VALUES ('test');
|
||||
CREATE TABLE dbo.Documents (
|
||||
DocumentId INT IDENTITY PRIMARY KEY, Title NVARCHAR(255) NOT NULL,
|
||||
OriginalFileName NVARCHAR(255) NOT NULL, MimeType NVARCHAR(100) NOT NULL DEFAULT 'application/pdf',
|
||||
FileSize BIGINT NOT NULL, FileData VARBINARY(MAX) NOT NULL, UploadedBy INT NULL,
|
||||
UploadedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
FOREIGN KEY (UploadedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
|
||||
);
|
||||
INSERT dbo.Documents (Title, OriginalFileName, FileSize, FileData, UploadedBy)
|
||||
VALUES (N'Existing manual', 'existing.pdf', 12, 0x255044462D, 1),
|
||||
(N'Failure case', 'failure.pdf', 12, 0x255044462D, 1);
|
||||
CREATE TABLE dbo.Robots (
|
||||
RobotId INT IDENTITY PRIMARY KEY, Name NVARCHAR(255) NOT NULL, Model NVARCHAR(255) NOT NULL,
|
||||
Type NVARCHAR(100) NOT NULL, AvatarData VARBINARY(MAX) NULL, AvatarMimeType NVARCHAR(100) NULL,
|
||||
CreatedBy INT NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
|
||||
);
|
||||
INSERT dbo.Robots (Name, Model, Type) VALUES (N'Legacy robot', 'LEGACY', N'Robot thử nghiệm');
|
||||
`);
|
||||
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
|
||||
const migrated = (await pool.request().query('SELECT r.TypeId, r.Type, t.Name FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId')).recordset;
|
||||
assert.equal(migrated.length, 1);
|
||||
assert.equal(migrated[0].Name, 'Robot thử nghiệm');
|
||||
const typeId = migrated[0].TypeId;
|
||||
await pool.request().query('DELETE dbo.Robots');
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { req.user = { UserId: 1, Role: 'asset' }; next(); });
|
||||
app.use('/robots', createRobotRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
|
||||
documentMaxBytes: 1024 * 1024, documentMaxMb: 1,
|
||||
isPdfBuffer: b => b.subarray(0, 5).toString() === '%PDF-' && b.includes(Buffer.from('%%EOF')),
|
||||
sanitizeDocumentFileName: name => name,
|
||||
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
|
||||
}));
|
||||
server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
|
||||
const request = (suffix, options) => fetch(`http://127.0.0.1:${server.address().port}/robots${suffix}`, options);
|
||||
const pdf = Buffer.from('%PDF-1.4\nNew manual\n%%EOF');
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
|
||||
const form = (name, documentIds = '[1]') => {
|
||||
const body = new FormData();
|
||||
for (const [key, value] of Object.entries({ name, model: 'SQL-TEST', typeId: String(typeId), documentIds })) body.append(key, value);
|
||||
return body;
|
||||
};
|
||||
const snapshot = async () => (await pool.request().query(`
|
||||
SELECT COUNT(*) AS n FROM dbo.Robots;
|
||||
SELECT COUNT(*) AS n FROM dbo.Documents;
|
||||
SELECT COUNT(*) AS n FROM dbo.RobotDocuments;
|
||||
`)).recordsets.map(rows => rows[0].n);
|
||||
|
||||
const body = form('Robot thử SQL');
|
||||
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
|
||||
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'new.pdf');
|
||||
const create = await request('', { method: 'POST', body });
|
||||
assert.equal(create.status, 201, await create.clone().text());
|
||||
const firstId = (await create.json()).data.RobotId;
|
||||
assert.deepEqual(await snapshot(), [1, 3, 2]);
|
||||
const avatar = await request(`/${firstId}/avatar`);
|
||||
assert.deepEqual(Buffer.from(await avatar.arrayBuffer()), png);
|
||||
let details = await (await request(`/${firstId}`)).json();
|
||||
assert.equal(details.data.Name, 'Robot thử SQL');
|
||||
assert.equal(details.data.Documents.length, 2);
|
||||
const uploadedId = details.data.Documents.find(doc => doc.OriginalFileName === 'new.pdf').DocumentId;
|
||||
const savedBytes = (await pool.request().input('id', sql.Int, uploadedId)
|
||||
.query('SELECT FileData FROM dbo.Documents WHERE DocumentId = @id')).recordset[0].FileData;
|
||||
assert.deepEqual(savedBytes, pdf);
|
||||
|
||||
// A second robot shares an existing PDF without duplicating its content.
|
||||
const second = await request('', { method: 'POST', body: form('Robot thứ hai') });
|
||||
assert.equal(second.status, 201);
|
||||
const secondId = (await second.json()).data.RobotId;
|
||||
assert.deepEqual(await snapshot(), [2, 3, 3]);
|
||||
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
|
||||
await ensureRobotSchema(pool);
|
||||
assert.deepEqual(await snapshot(), [2, 3, 3]);
|
||||
|
||||
// An actual SQL constraint failure happens after metadata/PDF insertion.
|
||||
await pool.request().query('ALTER TABLE dbo.RobotDocuments ADD CONSTRAINT CK_RobotLinks_Test CHECK (DocumentId <> 2)');
|
||||
const failure = form('Must roll back', '[2]');
|
||||
failure.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback.pdf');
|
||||
assert.equal((await request('', { method: 'POST', body: failure })).status, 500);
|
||||
assert.deepEqual(await snapshot(), [2, 3, 3]);
|
||||
const failedEdit = form('Must not overwrite existing robot', '[2]');
|
||||
failedEdit.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback-edit.pdf');
|
||||
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: failedEdit })).status, 500);
|
||||
assert.deepEqual(await snapshot(), [2, 3, 3]);
|
||||
details = await (await request(`/${firstId}`)).json();
|
||||
assert.equal(details.data.Name, 'Robot thử SQL'); assert.equal(details.data.Documents.length, 2);
|
||||
await pool.request().query('ALTER TABLE dbo.RobotDocuments DROP CONSTRAINT CK_RobotLinks_Test');
|
||||
|
||||
const partial = await request(`/${firstId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Đã sửa', model: 'NEW', typeId }) });
|
||||
assert.equal(partial.status, 200);
|
||||
details = await (await request(`/${firstId}`)).json();
|
||||
assert.equal(details.data.Documents.length, 2); assert.equal(details.data.HasAvatar, true);
|
||||
const clear = form('Đã gỡ liên kết', '[]'); clear.append('removeAvatar', 'true');
|
||||
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: clear })).status, 200);
|
||||
assert.deepEqual(await snapshot(), [2, 3, 1]);
|
||||
assert.equal((await request(`/${firstId}/avatar`)).status, 404);
|
||||
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
|
||||
assert.equal((await request(`/${secondId}`, { method: 'DELETE' })).status, 200);
|
||||
assert.deepEqual(await snapshot(), [1, 3, 0]);
|
||||
await pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1');
|
||||
assert.deepEqual(await snapshot(), [1, 2, 0]);
|
||||
|
||||
const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 409);
|
||||
assert.equal((await request('/types', { method: 'POST', ...json({ name: 'Robot thử nghiệm' }) })).status, 409);
|
||||
const extraType = await request('/types', { method: 'POST', ...json({ name: 'Robot di động', description: 'AMR/AGV' }) });
|
||||
assert.equal(extraType.status, 201);
|
||||
const extraId = (await extraType.json()).data.TypeId;
|
||||
// An in-use type can be renamed without changing its identity or its robots.
|
||||
assert.equal((await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Thể loại đã đổi tên', description: 'Updated' }) })).status, 200);
|
||||
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
|
||||
const catalog = (await (await request('/types')).json()).data;
|
||||
assert.equal(catalog.length, 2);
|
||||
assert.equal(catalog.find(type => type.TypeId === typeId).RobotCount, 1);
|
||||
details = await (await request(`/${firstId}`)).json();
|
||||
assert.equal(details.data.TypeId, typeId);
|
||||
assert.equal(details.data.Type, 'Thể loại đã đổi tên');
|
||||
const duplicateRename = await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Robot di động' }) });
|
||||
assert.equal(duplicateRename.status, 409);
|
||||
assert.equal((await (await request(`/${firstId}`)).json()).data.Type, 'Thể loại đã đổi tên');
|
||||
// Reassignment releases the old type, while the new type becomes protected.
|
||||
const reassign = form('Chuyển thể loại'); reassign.set('typeId', String(extraId)); reassign.set('documentIds', '[]');
|
||||
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: reassign })).status, 200);
|
||||
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 200);
|
||||
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 409);
|
||||
assert.equal((await request(`/${firstId}`, { method: 'DELETE' })).status, 200);
|
||||
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 200);
|
||||
const stale = form('Must reject stale type'); stale.set('typeId', String(extraId));
|
||||
assert.equal((await request('', { method: 'POST', body: stale })).status, 400);
|
||||
assert.deepEqual(await snapshot(), [0, 2, 0]);
|
||||
} finally {
|
||||
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
if (pool) await pool.close();
|
||||
try {
|
||||
if (created) {
|
||||
assert.match(database, /^AccManagerRobotsTest_\d+_[a-f0-9]{12}$/);
|
||||
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
|
||||
await admin.request().query(`DROP DATABASE [${database}]`);
|
||||
}
|
||||
} finally { await admin.close(); }
|
||||
}
|
||||
});
|
||||
317
backend/robots.js
Normal file
317
backend/robots.js
Normal file
@@ -0,0 +1,317 @@
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { getDocumentFormat, validateDocumentFile, normalizeUploadedFileName } = require('./document-files');
|
||||
|
||||
const AVATAR_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const MAX_DOCUMENT_UPLOADS = 10;
|
||||
const MAX_LINKED_DOCUMENTS = 100;
|
||||
|
||||
async function ensureRobotSchema(pool) {
|
||||
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-schema.sql'), 'utf8'));
|
||||
}
|
||||
|
||||
function invalid(message) {
|
||||
return Object.assign(new Error(message), { status: 400 });
|
||||
}
|
||||
|
||||
function positiveId(value) {
|
||||
const id = Number(value);
|
||||
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(id) || id < 1 || id > 2147483647) {
|
||||
throw invalid('Mã dữ liệu không hợp lệ');
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
function parseDocumentIds(value) {
|
||||
if (value === undefined) return undefined;
|
||||
let ids = value;
|
||||
if (typeof value === 'string') {
|
||||
try { ids = JSON.parse(value); } catch { throw invalid('Danh sách tài liệu không hợp lệ'); }
|
||||
}
|
||||
if (!Array.isArray(ids) || ids.length > MAX_LINKED_DOCUMENTS) {
|
||||
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
|
||||
}
|
||||
return [...new Set(ids.map(positiveId))].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function isAvatarBuffer(buffer, mimeType) {
|
||||
if (!Buffer.isBuffer(buffer) || buffer.length < 12) return false;
|
||||
if (mimeType === 'image/png') return buffer.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'));
|
||||
if (mimeType === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
|
||||
if (mimeType === 'image/webp') return buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP';
|
||||
return false;
|
||||
}
|
||||
|
||||
function createRobotRouter({ getPool, sql, requireManage, documentMaxBytes, documentMaxMb,
|
||||
sanitizeDocumentFileName, sendInternalError }) {
|
||||
const router = express.Router();
|
||||
const upload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
limits: { fileSize: Math.max(documentMaxBytes, AVATAR_MAX_BYTES), files: MAX_DOCUMENT_UPLOADS + 1,
|
||||
fields: 6, parts: MAX_DOCUMENT_UPLOADS + 8, fieldSize: 64 * 1024 },
|
||||
fileFilter(_req, file, callback) {
|
||||
const extension = path.extname(file.originalname).toLowerCase();
|
||||
const avatarTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
|
||||
const valid = file.fieldname === 'avatar'
|
||||
? avatarTypes[extension] === file.mimetype
|
||||
: file.fieldname === 'documents' && Boolean(getDocumentFormat(file.originalname));
|
||||
callback(valid ? null : invalid('Ảnh đại diện chỉ nhận JPG, PNG, WebP; định dạng tài liệu chưa được hỗ trợ'), valid);
|
||||
}
|
||||
}).fields([{ name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: MAX_DOCUMENT_UPLOADS }]);
|
||||
|
||||
const robotColumns = `r.RobotId, r.Name, r.Model, r.TypeId, t.Name AS Type, r.CreatedBy, r.CreatedDate, r.UpdatedDate,
|
||||
CAST(CASE WHEN r.AvatarData IS NULL THEN 0 ELSE 1 END AS BIT) AS HasAvatar,
|
||||
(SELECT COUNT(*) FROM dbo.RobotDocuments rd WHERE rd.RobotId = r.RobotId) AS DocumentCount`;
|
||||
|
||||
function fail(res, error) {
|
||||
if (error.status === 400) return res.status(400).json({ success: false, message: error.message });
|
||||
return sendInternalError(res, error, 'Không thể xử lý thông tin robot');
|
||||
}
|
||||
|
||||
function failType(res, error) {
|
||||
if ([2601, 2627].includes(error.number)) {
|
||||
return res.status(409).json({ success: false, message: 'Tên thể loại robot đã tồn tại' });
|
||||
}
|
||||
if (error.number === 547) {
|
||||
return res.status(409).json({ success: false, message: 'Thể loại đang được sử dụng. Hãy chuyển các robot sang thể loại khác trước khi xóa.' });
|
||||
}
|
||||
return fail(res, error);
|
||||
}
|
||||
|
||||
function typeFields(body = {}) {
|
||||
if (typeof body.name !== 'string' || !body.name.trim() || body.name.trim().length > 100) {
|
||||
throw invalid('Vui lòng nhập tên thể loại, tối đa 100 ký tự');
|
||||
}
|
||||
if (body.description != null && (typeof body.description !== 'string' || body.description.trim().length > 500)) {
|
||||
throw invalid('Mô tả thể loại tối đa 500 ký tự');
|
||||
}
|
||||
return { name: body.name.trim(), description: body.description?.trim() || null };
|
||||
}
|
||||
|
||||
// Declare catalog routes before /:id so "types" cannot be parsed as a robot ID.
|
||||
router.get('/types', async (_req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().query(`SELECT t.TypeId, t.Name, t.Description, t.CreatedDate, t.UpdatedDate,
|
||||
(SELECT COUNT(*) FROM dbo.Robots r WHERE r.TypeId = t.TypeId) AS RobotCount
|
||||
FROM dbo.RobotTypes t ORDER BY t.Name, t.TypeId`);
|
||||
res.json({ success: true, data: result.recordset });
|
||||
} catch (error) { failType(res, error); }
|
||||
});
|
||||
|
||||
router.post('/types', requireManage, async (req, res) => {
|
||||
try {
|
||||
const fields = typeFields(req.body);
|
||||
const result = await getPool().request().input('name', sql.NVarChar(100), fields.name)
|
||||
.input('description', sql.NVarChar(500), fields.description).query(`
|
||||
INSERT INTO dbo.RobotTypes (Name, Description)
|
||||
OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description
|
||||
VALUES (@name, @description)`);
|
||||
res.status(201).json({ success: true, data: result.recordset[0], message: 'Đã thêm thể loại robot' });
|
||||
} catch (error) { failType(res, error); }
|
||||
});
|
||||
|
||||
router.put('/types/:id', requireManage, async (req, res) => {
|
||||
let transaction, begun = false;
|
||||
try {
|
||||
const typeId = positiveId(req.params.id);
|
||||
const fields = typeFields(req.body);
|
||||
transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin(); begun = true;
|
||||
const result = await new sql.Request(transaction).input('typeId', sql.Int, typeId)
|
||||
.input('name', sql.NVarChar(100), fields.name).input('description', sql.NVarChar(500), fields.description)
|
||||
.query(`UPDATE dbo.RobotTypes SET Name = @name, Description = @description,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description WHERE TypeId = @typeId`);
|
||||
if (!result.recordset.length) {
|
||||
await transaction.rollback(); begun = false;
|
||||
return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' });
|
||||
}
|
||||
await new sql.Request(transaction).input('typeId', sql.Int, typeId).input('name', sql.NVarChar(100), fields.name)
|
||||
.query(`UPDATE dbo.Robots SET Type = @name, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE TypeId = @typeId`);
|
||||
await transaction.commit(); begun = false;
|
||||
res.json({ success: true, data: result.recordset[0], message: 'Đã cập nhật thể loại robot' });
|
||||
} catch (error) {
|
||||
if (begun) { try { await transaction.rollback(); } catch { /* The driver may have rolled back. */ } }
|
||||
failType(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/types/:id', requireManage, async (req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().input('typeId', sql.Int, positiveId(req.params.id))
|
||||
.query('DELETE FROM dbo.RobotTypes OUTPUT DELETED.TypeId WHERE TypeId = @typeId');
|
||||
if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' });
|
||||
res.json({ success: true, message: 'Đã xóa thể loại robot' });
|
||||
} catch (error) { failType(res, error); }
|
||||
});
|
||||
|
||||
router.get('/', async (_req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().query(`SELECT ${robotColumns} FROM dbo.Robots r
|
||||
JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId ORDER BY r.CreatedDate DESC, r.RobotId DESC`);
|
||||
res.json({ success: true, data: result.recordset, maxFileSizeMb: documentMaxMb, avatarMaxFileSizeMb: 5 });
|
||||
} catch (error) { fail(res, error); }
|
||||
});
|
||||
|
||||
router.get('/:id/avatar', async (req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id))
|
||||
.query('SELECT AvatarData, AvatarMimeType FROM dbo.Robots WHERE RobotId = @robotId');
|
||||
const robot = result.recordset[0];
|
||||
if (!robot?.AvatarData) return res.status(404).json({ success: false, message: 'Robot chưa có ảnh đại diện' });
|
||||
res.setHeader('Content-Type', robot.AvatarMimeType);
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.send(robot.AvatarData);
|
||||
} catch (error) { fail(res, error); }
|
||||
});
|
||||
|
||||
router.get('/:id', async (req, res) => {
|
||||
try {
|
||||
const robotId = positiveId(req.params.id);
|
||||
const result = await getPool().request().input('robotId', sql.Int, robotId)
|
||||
.query(`SELECT ${robotColumns} FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId WHERE r.RobotId = @robotId`);
|
||||
if (!result.recordset[0]) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
|
||||
const documents = await getPool().request().input('robotId', sql.Int, robotId).query(`
|
||||
SELECT d.DocumentId, d.Title, d.OriginalFileName, d.MimeType, d.FileSize, d.UploadedDate
|
||||
FROM dbo.RobotDocuments rd JOIN dbo.Documents d ON d.DocumentId = rd.DocumentId
|
||||
WHERE rd.RobotId = @robotId ORDER BY d.Title, d.DocumentId`);
|
||||
res.json({ success: true, data: { ...result.recordset[0], Documents: documents.recordset } });
|
||||
} catch (error) { fail(res, error); }
|
||||
});
|
||||
|
||||
async function saveRobot(req, res) {
|
||||
let transaction;
|
||||
let begun = false;
|
||||
try {
|
||||
req.body ||= {};
|
||||
const robotId = req.params.id === undefined ? null : positiveId(req.params.id);
|
||||
const fields = {};
|
||||
for (const [key, limit] of [['name', 255], ['model', 255]]) {
|
||||
if (typeof req.body[key] !== 'string' || !req.body[key].trim() || req.body[key].trim().length > limit) {
|
||||
throw invalid('Vui lòng nhập tên và model robot, tối đa 255 ký tự');
|
||||
}
|
||||
fields[key] = req.body[key].trim();
|
||||
}
|
||||
const typeId = positiveId(req.body.typeId);
|
||||
const documentIds = parseDocumentIds(req.body.documentIds);
|
||||
const avatar = req.files?.avatar?.[0];
|
||||
const documents = req.files?.documents || [];
|
||||
if (avatar && (avatar.size > AVATAR_MAX_BYTES || !isAvatarBuffer(avatar.buffer, avatar.mimetype))) {
|
||||
throw invalid('Ảnh đại diện phải là JPG, PNG hoặc WebP hợp lệ, tối đa 5 MB');
|
||||
}
|
||||
for (const file of documents) {
|
||||
if (file.size > documentMaxBytes) throw invalid(`Tài liệu tối đa ${documentMaxMb} MB mỗi file`);
|
||||
file.documentFormat = validateDocumentFile(file);
|
||||
}
|
||||
if ((documentIds?.length || 0) + documents.length > MAX_LINKED_DOCUMENTS) {
|
||||
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
|
||||
}
|
||||
if (req.body.removeAvatar !== undefined && !['true', 'false'].includes(String(req.body.removeAvatar))) {
|
||||
throw invalid('Yêu cầu xóa ảnh không hợp lệ');
|
||||
}
|
||||
|
||||
transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin();
|
||||
begun = true;
|
||||
const request = () => new sql.Request(transaction);
|
||||
// Lock the type before the robot, matching the catalog rename lock order.
|
||||
const selectedType = await request().input('typeId', sql.Int, typeId)
|
||||
.query('SELECT TypeId, Name FROM dbo.RobotTypes WITH (UPDLOCK, HOLDLOCK) WHERE TypeId = @typeId');
|
||||
if (!selectedType.recordset.length) throw invalid('Thể loại đã bị xóa hoặc không tồn tại. Vui lòng chọn lại.');
|
||||
fields.type = selectedType.recordset[0].Name;
|
||||
if (robotId !== null) {
|
||||
const existing = await request().input('robotId', sql.Int, robotId)
|
||||
.query('SELECT RobotId FROM dbo.Robots WITH (UPDLOCK, HOLDLOCK) WHERE RobotId = @robotId');
|
||||
if (!existing.recordset.length) {
|
||||
await transaction.rollback(); begun = false;
|
||||
return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
|
||||
}
|
||||
}
|
||||
for (const documentId of documentIds || []) {
|
||||
const existing = await request().input('documentId', sql.Int, documentId).query(`
|
||||
SELECT DocumentId FROM dbo.Documents WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE DocumentId = @documentId`);
|
||||
if (!existing.recordset.length) throw invalid('Một tài liệu đã bị xóa. Vui lòng chọn lại.');
|
||||
}
|
||||
// A partial API update preserves existing links; the form always supplies the full selection.
|
||||
if (documentIds === undefined && robotId !== null) {
|
||||
const count = await request().input('robotId', sql.Int, robotId)
|
||||
.query('SELECT COUNT(*) AS DocumentCount FROM dbo.RobotDocuments WHERE RobotId = @robotId');
|
||||
if (Number(count.recordset[0].DocumentCount) + documents.length > MAX_LINKED_DOCUMENTS) {
|
||||
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
|
||||
}
|
||||
}
|
||||
const replaceAvatar = Boolean(avatar) || String(req.body.removeAvatar) === 'true';
|
||||
const write = request().input('name', sql.NVarChar(255), fields.name)
|
||||
.input('model', sql.NVarChar(255), fields.model).input('type', sql.NVarChar(100), fields.type)
|
||||
.input('typeId', sql.Int, typeId)
|
||||
.input('avatarData', sql.VarBinary(sql.MAX), avatar?.buffer || null)
|
||||
.input('avatarMimeType', sql.NVarChar(100), avatar?.mimetype || null);
|
||||
let savedId;
|
||||
if (robotId === null) {
|
||||
const saved = await write.input('createdBy', sql.Int, req.user.UserId).query(`
|
||||
INSERT INTO dbo.Robots (Name, Model, Type, TypeId, AvatarData, AvatarMimeType, CreatedBy)
|
||||
OUTPUT INSERTED.RobotId VALUES (@name, @model, @type, @typeId, @avatarData, @avatarMimeType, @createdBy)`);
|
||||
savedId = saved.recordset[0].RobotId;
|
||||
} else {
|
||||
await write.input('robotId', sql.Int, robotId).input('replaceAvatar', sql.Bit, replaceAvatar).query(`
|
||||
UPDATE dbo.Robots SET Name = @name, Model = @model, Type = @type, TypeId = @typeId,
|
||||
AvatarData = CASE WHEN @replaceAvatar = 1 THEN @avatarData ELSE AvatarData END,
|
||||
AvatarMimeType = CASE WHEN @replaceAvatar = 1 THEN @avatarMimeType ELSE AvatarMimeType END,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE RobotId = @robotId`);
|
||||
savedId = robotId;
|
||||
}
|
||||
if (documentIds !== undefined) {
|
||||
await request().input('robotId', sql.Int, savedId)
|
||||
.query('DELETE FROM dbo.RobotDocuments WHERE RobotId = @robotId');
|
||||
}
|
||||
const allIds = [...(documentIds || [])];
|
||||
for (const file of documents) {
|
||||
const filename = sanitizeDocumentFileName(normalizeUploadedFileName(file.originalname));
|
||||
const saved = await request().input('title', sql.NVarChar(255), filename.replace(/\.[^.]+$/, '') || 'Tài liệu')
|
||||
.input('originalFileName', sql.NVarChar(255), filename).input('fileSize', sql.BigInt, file.size)
|
||||
.input('mimeType', sql.NVarChar(100), file.documentFormat.mimeType)
|
||||
.input('fileData', sql.VarBinary(sql.MAX), file.buffer).input('uploadedBy', sql.Int, req.user.UserId)
|
||||
.query(`INSERT INTO dbo.Documents (Title, OriginalFileName, MimeType, FileSize, FileData, UploadedBy)
|
||||
OUTPUT INSERTED.DocumentId VALUES (@title, @originalFileName, @mimeType, @fileSize, @fileData, @uploadedBy)`);
|
||||
allIds.push(saved.recordset[0].DocumentId);
|
||||
}
|
||||
for (const documentId of allIds) {
|
||||
await request().input('robotId', sql.Int, savedId).input('documentId', sql.Int, documentId)
|
||||
.query('INSERT INTO dbo.RobotDocuments (RobotId, DocumentId) VALUES (@robotId, @documentId)');
|
||||
}
|
||||
await transaction.commit(); begun = false;
|
||||
res.status(robotId === null ? 201 : 200).json({ success: true, data: { RobotId: savedId }, message: 'Đã lưu thông tin robot' });
|
||||
} catch (error) {
|
||||
if (begun) {
|
||||
try { await transaction.rollback(); } catch { /* Driver may already have rolled back. */ }
|
||||
}
|
||||
fail(res, error);
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/', requireManage, upload, saveRobot);
|
||||
router.put('/:id', requireManage, upload, saveRobot);
|
||||
router.delete('/:id', requireManage, async (req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id))
|
||||
.query('DELETE FROM dbo.Robots OUTPUT DELETED.RobotId WHERE RobotId = @robotId');
|
||||
if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
|
||||
res.json({ success: true, message: 'Đã xóa robot. Tài liệu vẫn được giữ trong kho tài liệu.' });
|
||||
} catch (error) { fail(res, error); }
|
||||
});
|
||||
router.use((error, _req, res, next) => {
|
||||
if (error instanceof multer.MulterError) {
|
||||
return res.status(400).json({ success: false, message: error.code === 'LIMIT_FILE_SIZE'
|
||||
? `Ảnh đại diện tối đa 5 MB; tài liệu tối đa ${documentMaxMb} MB mỗi file`
|
||||
: `Tối đa 1 ảnh đại diện và ${MAX_DOCUMENT_UPLOADS} tài liệu; vui lòng kiểm tra tệp tải lên` });
|
||||
}
|
||||
if (error.status === 400) return fail(res, error);
|
||||
next(error);
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
module.exports = { ensureRobotSchema, createRobotRouter, parseDocumentIds, isAvatarBuffer };
|
||||
322
backend/robots.test.js
Normal file
322
backend/robots.test.js
Normal file
@@ -0,0 +1,322 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const express = require('express');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { createRequire } = require('node:module');
|
||||
const { createRobotRouter, parseDocumentIds } = require('./robots');
|
||||
|
||||
const pdf = Buffer.from('%PDF-1.4\nrobot manual\n%%EOF\n');
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
|
||||
|
||||
async function fixture(t, { answer, role = 'asset', maxBytes = 1024 * 1024 } = {}) {
|
||||
const queries = [], transactions = [];
|
||||
class Request {
|
||||
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
|
||||
input(name, _type, value) { this.inputs[name] = value; return this; }
|
||||
async query(query) {
|
||||
const call = { query, inputs: this.inputs, transaction: this.transaction };
|
||||
queries.push(call);
|
||||
const result = answer?.(call);
|
||||
if (result !== undefined) return result;
|
||||
if (query.includes('SELECT TypeId, Name FROM dbo.RobotTypes')) return { recordset: [{ TypeId: this.inputs.typeId, Name: 'Cộng tác' }] };
|
||||
if (query.includes('INSERT INTO dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
|
||||
if (query.includes('INSERT INTO dbo.Documents')) return { recordset: [{ DocumentId: 51 }] };
|
||||
if (query.includes('SELECT DocumentId FROM dbo.Documents')) return { recordset: [{ DocumentId: this.inputs.documentId }] };
|
||||
if (query.includes('SELECT RobotId FROM dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
|
||||
if (query.includes('COUNT(*) AS DocumentCount')) return { recordset: [{ DocumentCount: 2 }] };
|
||||
return { recordset: [] };
|
||||
}
|
||||
}
|
||||
class Transaction {
|
||||
constructor() { transactions.push(this); }
|
||||
async begin() { this.begun = true; }
|
||||
async commit() { this.committed = true; }
|
||||
async rollback() { this.rolledBack = true; }
|
||||
}
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader('Cache-Control', 'no-store'); next();
|
||||
});
|
||||
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
|
||||
app.use('/api/robots', createRobotRouter({
|
||||
getPool: () => ({ request: () => new Request() }),
|
||||
sql: { ...require('mssql'), Request, Transaction },
|
||||
requireManage(req, res, next) {
|
||||
if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false });
|
||||
next();
|
||||
},
|
||||
documentMaxBytes: maxBytes, documentMaxMb: 1,
|
||||
isPdfBuffer: buffer => buffer.subarray(0, 5).toString() === '%PDF-' && buffer.includes(Buffer.from('%%EOF')),
|
||||
sanitizeDocumentFileName: name => name.replace(/[\\/\r\n]/g, '_'),
|
||||
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
|
||||
}));
|
||||
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)); });
|
||||
return { queries, transactions, request: (suffix = '', options) => fetch(`http://127.0.0.1:${server.address().port}/api/robots${suffix}`, options) };
|
||||
}
|
||||
|
||||
function form(extra = {}) {
|
||||
const body = new FormData();
|
||||
for (const [key, value] of Object.entries({ name: 'Robot hàn', model: 'CR10', typeId: '1', documentIds: '[3,2,3]', ...extra })) {
|
||||
if (value !== undefined) body.append(key, value);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
test('creating a robot saves its avatar, new PDFs and existing links in one transaction', async t => {
|
||||
const f = await fixture(t);
|
||||
const body = form();
|
||||
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
|
||||
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
||||
const response = await f.request('', { method: 'POST', body });
|
||||
assert.equal(response.status, 201);
|
||||
assert.equal((await response.json()).data.RobotId, 17);
|
||||
assert.equal(f.transactions[0].committed, true);
|
||||
assert.ok(f.queries.every(query => query.transaction === f.transactions[0]));
|
||||
const robot = f.queries.find(q => q.query.includes('INSERT INTO dbo.Robots'));
|
||||
assert.equal(robot.inputs.name, 'Robot hàn');
|
||||
assert.equal(robot.inputs.typeId, 1);
|
||||
assert.equal(robot.inputs.type, 'Cộng tác');
|
||||
assert.deepEqual(robot.inputs.avatarData, png);
|
||||
const links = f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments'));
|
||||
assert.deepEqual(links.map(q => q.inputs.documentId), [2, 3, 51]);
|
||||
assert.equal(f.queries.filter(q => q.query.includes('INSERT INTO dbo.Documents')).length, 1);
|
||||
});
|
||||
|
||||
test('a PDF storage failure rolls back robot metadata and every link', async t => {
|
||||
const f = await fixture(t, { answer({ query }) {
|
||||
if (query.includes('INSERT INTO dbo.Documents')) throw new Error('Storage failed');
|
||||
} });
|
||||
const body = form(); body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
||||
assert.equal((await f.request('', { method: 'POST', body })).status, 500);
|
||||
assert.equal(f.transactions[0].rolledBack, true);
|
||||
assert.equal(f.transactions[0].committed, undefined);
|
||||
assert.equal(f.queries.some(q => q.query.includes('INSERT INTO dbo.RobotDocuments')), false);
|
||||
});
|
||||
|
||||
test('a missing library PDF rejects the whole save before inserting a robot', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT DocumentId FROM dbo.Documents') ? { recordset: [] } : undefined });
|
||||
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
|
||||
assert.equal(f.transactions[0].rolledBack, true);
|
||||
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
|
||||
});
|
||||
|
||||
test('editing replaces selected links while retaining the avatar unless requested', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: '[8]' }) })).status, 200);
|
||||
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
|
||||
assert.equal(update.inputs.replaceAvatar, false);
|
||||
assert.match(update.query, /ELSE AvatarData END/);
|
||||
assert.ok(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')));
|
||||
assert.deepEqual(f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments')).map(q => q.inputs.documentId), [8]);
|
||||
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.Documents')), false);
|
||||
});
|
||||
|
||||
test('partial edits preserve document links and can explicitly remove the avatar', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: undefined, removeAvatar: 'true' }) })).status, 200);
|
||||
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
|
||||
assert.equal(update.inputs.replaceAvatar, true);
|
||||
assert.equal(update.inputs.avatarData, null);
|
||||
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')), false);
|
||||
});
|
||||
|
||||
test('forged image/PDF contents and oversized avatars are rejected before database access', async t => {
|
||||
const f = await fixture(t);
|
||||
for (const [field, type, name, bytes] of [
|
||||
['avatar', 'image/png', 'bad.png', Buffer.from('not an image')],
|
||||
['documents', 'application/pdf', 'bad.pdf', Buffer.from('not a PDF')],
|
||||
['avatar', 'image/png', 'large.png', Buffer.alloc(5 * 1024 * 1024 + 1)]
|
||||
]) {
|
||||
const body = form(); body.append(field, new Blob([bytes], { type }), name);
|
||||
assert.equal((await f.request('', { method: 'POST', body })).status, 400);
|
||||
}
|
||||
assert.equal(f.queries.length, 0);
|
||||
assert.equal(f.transactions.length, 0);
|
||||
});
|
||||
|
||||
test('PDF size configuration, image extensions and upload counts are enforced', async t => {
|
||||
const f = await fixture(t, { maxBytes: 20 });
|
||||
const oversizedPdf = form(); oversizedPdf.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
||||
const svg = form(); svg.append('avatar', new Blob(['<svg/>'], { type: 'image/svg+xml' }), 'image.svg');
|
||||
const many = form();
|
||||
for (let i = 0; i < 11; i++) many.append('documents', new Blob([pdf], { type: 'application/pdf' }), `${i}.pdf`);
|
||||
for (const body of [oversizedPdf, svg, many]) assert.equal((await f.request('', { method: 'POST', body })).status, 400);
|
||||
assert.equal(f.transactions.length, 0);
|
||||
});
|
||||
|
||||
test('invalid metadata and document IDs return useful errors without writes', async t => {
|
||||
const f = await fixture(t);
|
||||
for (const extra of [{ name: ' ' }, { model: '' }, { typeId: undefined }, { typeId: '0' }, { typeId: '2147483648' }, { documentIds: 'invalid' },
|
||||
{ documentIds: '[0]' }, { documentIds: '["3 OR 1=1"]' }, { documentIds: '[2147483648]' }]) {
|
||||
assert.equal((await f.request('', { method: 'POST', body: form(extra) })).status, 400);
|
||||
}
|
||||
assert.equal((await f.request('', { method: 'POST' })).status, 400);
|
||||
assert.equal((await f.request('/17x', { method: 'PUT', body: form() })).status, 400);
|
||||
assert.equal(f.transactions.length, 0);
|
||||
assert.throws(() => parseDocumentIds(Array.from({ length: 101 }, (_, i) => i + 1)));
|
||||
});
|
||||
|
||||
test('missing robots cannot be edited or silently recreated', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT RobotId FROM dbo.Robots') ? { recordset: [] } : undefined });
|
||||
assert.equal((await f.request('/17', { method: 'PUT', body: form() })).status, 404);
|
||||
assert.equal(f.transactions[0].rolledBack, true);
|
||||
assert.equal(f.queries.some(q => q.query.includes('UPDATE') && !q.query.includes('UPDLOCK')), false);
|
||||
});
|
||||
|
||||
test('ordinary users can read robot data but cannot add, update or delete robots', async t => {
|
||||
const f = await fixture(t, { role: 'user' });
|
||||
assert.equal((await f.request()).status, 200);
|
||||
for (const [method, suffix] of [['POST', ''], ['PUT', '/17'], ['DELETE', '/17']]) {
|
||||
assert.equal((await f.request(suffix, { method, ...(method === 'DELETE' ? {} : { body: form() }) })).status, 403);
|
||||
}
|
||||
assert.equal(f.transactions.length, 0);
|
||||
assert.equal(f.queries.length, 1);
|
||||
});
|
||||
|
||||
test('avatar endpoints return the stored bytes and safe content type', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT AvatarData') ? { recordset: [{ AvatarData: png, AvatarMimeType: 'image/png' }] } : undefined });
|
||||
const response = await f.request('/17/avatar');
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers.get('content-type'), 'image/png');
|
||||
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
|
||||
assert.equal(response.headers.get('cache-control'), 'no-store');
|
||||
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
|
||||
});
|
||||
|
||||
test('deleting a robot never deletes shared PDF documents', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.startsWith('DELETE FROM dbo.Robots') ? { recordset: [{ RobotId: 17 }] } : undefined });
|
||||
assert.equal((await f.request('/17', { method: 'DELETE' })).status, 200);
|
||||
assert.equal(f.queries.length, 1);
|
||||
assert.match(f.queries[0].query, /^DELETE FROM dbo.Robots/);
|
||||
assert.doesNotMatch(f.queries[0].query, /DELETE FROM (?:dbo\.)?Documents/);
|
||||
});
|
||||
|
||||
test('robot cards escape user content, search name/model/type, and hide edit actions for viewers', () => {
|
||||
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
||||
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {} }, console });
|
||||
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
|
||||
const manager = context.manager;
|
||||
Object.assign(manager, { robots: [{ RobotId: 17, Name: '<script>Robot</script>', 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, '>').replace(/"/g, '"') });
|
||||
let html = manager.getRobotsContent();
|
||||
assert.match(html, /<script>Robot/);
|
||||
assert.doesNotMatch(html, /<script>Robot/);
|
||||
assert.match(html, /2 tài liệu/);
|
||||
assert.doesNotMatch(html, /data-robot-action="edit"|data-robot-action="delete"|id="addRobotBtn"/);
|
||||
manager.currentUser.Role = 'admin';
|
||||
assert.match(manager.getRobotsContent(), /data-robot-action="edit"/);
|
||||
for (const keyword of ['robot', 'cr10', 'cộng tác']) {
|
||||
manager.robotSearchTerm = keyword; assert.equal(manager.getFilteredRobots().length, 1);
|
||||
}
|
||||
manager.robotTypeFilter = 'AMR'; assert.equal(manager.getFilteredRobots().length, 0);
|
||||
manager.robotTypeFilter = '1'; assert.equal(manager.getFilteredRobots().length, 1);
|
||||
manager.robotSearchTerm = ''; manager.robotTypeFilter = ''; manager.robotLoadError = 'Server unavailable';
|
||||
html = manager.getRobotsContent(); assert.match(html, /role="alert"/); assert.match(html, /Server unavailable/);
|
||||
});
|
||||
|
||||
function serverWithPool(pool) {
|
||||
const serverPath = path.join(__dirname, 'server.js');
|
||||
const serverRequire = createRequire(serverPath);
|
||||
const sandbox = {
|
||||
require: name => name === 'dotenv' ? { config() {} } : serverRequire(name),
|
||||
module: { exports: {} }, __dirname, __filename: serverPath, Buffer, URL, console,
|
||||
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'robot-tests-only-key-with-more-than-32-characters' }, on() {} },
|
||||
robotTestPool: pool
|
||||
};
|
||||
vm.runInNewContext(`${fs.readFileSync(serverPath, 'utf8')}\npool = robotTestPool;`, sandbox, { filename: serverPath });
|
||||
return sandbox.module.exports.app;
|
||||
}
|
||||
|
||||
test('all robot endpoints require an authenticated session in the production application', async t => {
|
||||
const app = serverWithPool(null);
|
||||
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/robots`;
|
||||
for (const [method, suffix] of [['GET', ''], ['GET', '/17'], ['GET', '/17/avatar'], ['POST', ''], ['PUT', '/17'], ['DELETE', '/17'],
|
||||
['GET', '/types'], ['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
|
||||
const response = await fetch(`${base}${suffix}`, { method, headers: { 'X-User-Id': '1', 'X-User-Role': 'admin' } });
|
||||
assert.equal(response.status, 401);
|
||||
}
|
||||
});
|
||||
|
||||
test('a deleted or unknown robot type rejects the save before inserting robot data', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT TypeId, Name FROM dbo.RobotTypes') ? { recordset: [] } : undefined });
|
||||
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
|
||||
assert.equal(f.transactions[0].rolledBack, true);
|
||||
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
|
||||
});
|
||||
|
||||
test('viewers can read the type catalog but cannot create, rename or delete types', async t => {
|
||||
const f = await fixture(t, { role: 'user' });
|
||||
assert.equal((await f.request('/types')).status, 200);
|
||||
for (const [method, suffix] of [['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
|
||||
assert.equal((await f.request(suffix, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 403);
|
||||
}
|
||||
assert.equal(f.queries.length, 1);
|
||||
assert.equal(f.transactions.length, 0);
|
||||
});
|
||||
|
||||
test('type input is validated and duplicate type names return a conflict', async t => {
|
||||
const f = await fixture(t, { answer({ query }) {
|
||||
if (query.includes('INSERT INTO dbo.RobotTypes')) throw Object.assign(new Error('duplicate'), { number: 2627 });
|
||||
} });
|
||||
for (const body of [{ name: '' }, { name: ' ' }, { name: 'a'.repeat(101) }, { name: [] }, { name: 'AMR', description: 'a'.repeat(501) }]) {
|
||||
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).status, 400);
|
||||
}
|
||||
assert.equal(f.queries.length, 0);
|
||||
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 409);
|
||||
});
|
||||
|
||||
test('renaming a type updates the catalog and robot display values atomically', async t => {
|
||||
const f = await fixture(t, { answer: ({ query }) => query.includes('UPDATE dbo.RobotTypes') ? { recordset: [{ TypeId: 1, Name: 'Cộng tác mới' }] } : undefined });
|
||||
const response = await f.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Cộng tác mới', description: 'New description' }) });
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(f.transactions[0].committed, true);
|
||||
assert.ok(f.queries.every(call => call.transaction === f.transactions[0]));
|
||||
assert.ok(f.queries.some(call => call.query.includes('UPDATE dbo.Robots SET Type = @name') && call.inputs.name === 'Cộng tác mới'));
|
||||
});
|
||||
|
||||
test('rename failures roll back; used types cannot be deleted, and missing types return 404', async t => {
|
||||
const failed = await fixture(t, { answer({ query }) {
|
||||
if (query.includes('UPDATE dbo.RobotTypes')) return { recordset: [{ TypeId: 1 }] };
|
||||
if (query.includes('UPDATE dbo.Robots')) throw new Error('Storage failure');
|
||||
} });
|
||||
assert.equal((await failed.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Rename' }) })).status, 500);
|
||||
assert.equal(failed.transactions[0].rolledBack, true);
|
||||
for (const mode of ['used', 'missing', 'unused']) {
|
||||
const f = await fixture(t, { answer({ query }) {
|
||||
if (query.includes('DELETE FROM dbo.RobotTypes')) {
|
||||
if (mode === 'used') throw Object.assign(new Error('FK conflict'), { number: 547 });
|
||||
return { recordset: mode === 'unused' ? [{ TypeId: 1 }] : [] };
|
||||
}
|
||||
} });
|
||||
assert.equal((await f.request('/types/1', { method: 'DELETE' })).status, mode === 'used' ? 409 : mode === 'missing' ? 404 : 200);
|
||||
}
|
||||
});
|
||||
|
||||
test('document deletion blocks robot links and concurrent foreign-key conflicts while retaining owner permissions', async () => {
|
||||
for (const mode of ['linked', 'unlinked', 'concurrent', 'other-owner']) {
|
||||
let calls = 0;
|
||||
const app = serverWithPool({ request() {
|
||||
return { input() { return this; }, async query(query) {
|
||||
calls++;
|
||||
if (query.startsWith('SELECT')) return { recordset: [{ DocumentId: 3, UploadedBy: mode === 'other-owner' ? 2 : 1 }] };
|
||||
assert.match(query, /NOT EXISTS \(SELECT 1 FROM dbo.RobotDocuments/);
|
||||
if (mode === 'concurrent') throw Object.assign(new Error('FK conflict'), { number: 547 });
|
||||
return { recordset: mode === 'unlinked' ? [{ DocumentId: 3 }] : [] };
|
||||
} };
|
||||
} });
|
||||
const route = app.router.stack.find(layer => layer.route?.path === '/api/documents/:id' && layer.route.methods.delete).route;
|
||||
const response = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return this; } };
|
||||
await route.stack.at(-1).handle({ params: { id: '3' }, user: { UserId: 1, Role: 'user' } }, response);
|
||||
assert.equal(response.statusCode, mode === 'other-owner' ? 403 : mode === 'unlinked' ? 200 : 409);
|
||||
assert.equal(calls, mode === 'other-owner' ? 1 : 2);
|
||||
}
|
||||
});
|
||||
@@ -16,6 +16,9 @@ const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
|
||||
const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations } = require('./asset-project-allocations');
|
||||
const { buildExportRequestWorkbook } = require('./export-request-workbook');
|
||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||
const { ensureRobotSchema, createRobotRouter } = require('./robots');
|
||||
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
|
||||
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -2291,47 +2294,13 @@ const documentUpload = multer({
|
||||
parts: 7
|
||||
},
|
||||
fileFilter(req, file, callback) {
|
||||
const extension = require('path').extname(String(file.originalname || '')).toLowerCase();
|
||||
const mimeType = String(file.mimetype || '').toLowerCase();
|
||||
if (extension !== '.pdf' || mimeType !== 'application/pdf') {
|
||||
return callback(new Error('Chỉ chấp nhận file PDF'));
|
||||
if (!getDocumentFormat(file.originalname)) {
|
||||
return callback(Object.assign(new Error('Định dạng tài liệu chưa được hỗ trợ'), { code: 'DOCUMENT_VALIDATION' }));
|
||||
}
|
||||
callback(null, true);
|
||||
}
|
||||
});
|
||||
|
||||
function isPdfBuffer(value) {
|
||||
if (!Buffer.isBuffer(value) || value.length < 10 || value.subarray(0, 5).toString('ascii') !== '%PDF-') {
|
||||
return false;
|
||||
}
|
||||
const trailerStart = Math.max(0, value.length - 2048);
|
||||
return value.subarray(trailerStart).includes(Buffer.from('%%EOF', 'ascii'));
|
||||
}
|
||||
|
||||
function sanitizeDocumentFileName(value) {
|
||||
const cleaned = String(value || 'document.pdf')
|
||||
.replace(/[\u0000-\u001f\u007f]/g, '')
|
||||
.replace(/[\\/:*?"<>|]/g, '_')
|
||||
.trim()
|
||||
.slice(0, 255);
|
||||
const baseName = cleaned || 'document.pdf';
|
||||
return baseName.toLowerCase().endsWith('.pdf')
|
||||
? baseName
|
||||
: `${baseName.slice(0, 251)}.pdf`;
|
||||
}
|
||||
|
||||
function getDocumentContentDisposition(fileName, download = false) {
|
||||
const safeFileName = sanitizeDocumentFileName(fileName);
|
||||
const asciiFileName = safeFileName
|
||||
.normalize('NFKD')
|
||||
.replace(/[^\x20-\x7e]/g, '')
|
||||
.replace(/["\\]/g, '_')
|
||||
.trim() || 'document.pdf';
|
||||
const encodedFileName = encodeURIComponent(safeFileName)
|
||||
.replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
||||
return `${download ? 'attachment' : 'inline'}; filename="${asciiFileName}"; filename*=UTF-8''${encodedFileName}`;
|
||||
}
|
||||
|
||||
// Serve static files from /public
|
||||
const path = require('path');
|
||||
const publicDir = path.join(__dirname, '..', 'public');
|
||||
@@ -3129,6 +3098,7 @@ async function createTables() {
|
||||
// Fail startup if history preservation cannot be installed.
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
await ensureRobotSchema(pool);
|
||||
await pool.request().query(`
|
||||
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
|
||||
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
|
||||
@@ -9550,9 +9520,15 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// API ROUTES - PDF Documents
|
||||
// API ROUTES - Shared Documents
|
||||
// ==========================================
|
||||
|
||||
app.use('/api/robots', createRobotRouter({
|
||||
getPool: () => pool, sql, requireManage: requireAssetOrAdmin,
|
||||
documentMaxBytes: DOCUMENT_MAX_FILE_SIZE_BYTES, documentMaxMb: DOCUMENT_MAX_FILE_SIZE_MB,
|
||||
sanitizeDocumentFileName, sendInternalError
|
||||
}));
|
||||
|
||||
app.get('/api/documents', async (req, res) => {
|
||||
try {
|
||||
const search = String(req.query.search || '').trim().slice(0, 255);
|
||||
@@ -9583,7 +9559,8 @@ app.get('/api/documents', async (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
data: result.recordset,
|
||||
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB
|
||||
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB,
|
||||
acceptedExtensions: documentAccept
|
||||
});
|
||||
} catch (err) {
|
||||
sendInternalError(res, err, 'Không thể tải danh sách tài liệu');
|
||||
@@ -9593,20 +9570,18 @@ app.get('/api/documents', async (req, res) => {
|
||||
app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
|
||||
try {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ success: false, message: 'Vui lòng chọn file PDF' });
|
||||
}
|
||||
if (!isPdfBuffer(req.file.buffer)) {
|
||||
return res.status(400).json({ success: false, message: 'Nội dung file không phải là PDF hợp lệ' });
|
||||
return res.status(400).json({ success: false, message: 'Vui lòng chọn tài liệu' });
|
||||
}
|
||||
const format = validateDocumentFile(req.file);
|
||||
|
||||
const originalFileName = sanitizeDocumentFileName(req.file.originalname);
|
||||
const originalFileName = sanitizeDocumentFileName(normalizeUploadedFileName(req.file.originalname));
|
||||
const requestedTitle = String(req.body.title || '').trim();
|
||||
const defaultTitle = originalFileName.replace(/\.pdf$/i, '').trim() || 'Tài liệu PDF';
|
||||
const defaultTitle = originalFileName.replace(/\.[^.]+$/, '').trim() || 'Tài liệu';
|
||||
const title = (requestedTitle || defaultTitle).slice(0, 255);
|
||||
const result = await pool.request()
|
||||
.input('title', sql.NVarChar(255), title)
|
||||
.input('originalFileName', sql.NVarChar(255), originalFileName)
|
||||
.input('mimeType', sql.NVarChar(100), 'application/pdf')
|
||||
.input('mimeType', sql.NVarChar(100), format.mimeType)
|
||||
.input('fileSize', sql.BigInt, req.file.size)
|
||||
.input('fileData', sql.VarBinary(sql.MAX), req.file.buffer)
|
||||
.input('uploadedBy', sql.Int, req.user.UserId)
|
||||
@@ -9619,10 +9594,11 @@ app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Đã lưu tài liệu PDF',
|
||||
message: 'Đã lưu tài liệu',
|
||||
data: result.recordset[0]
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === 'DOCUMENT_VALIDATION') return res.status(400).json({ success: false, message: err.message });
|
||||
sendInternalError(res, err, 'Không thể lưu tài liệu');
|
||||
}
|
||||
});
|
||||
@@ -9646,8 +9622,10 @@ app.get('/api/documents/:id/file', async (req, res) => {
|
||||
return res.status(404).json({ success: false, message: 'Không tìm thấy tài liệu' });
|
||||
}
|
||||
|
||||
const shouldDownload = String(req.query.download || '') === '1';
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
const format = getDocumentFormat(document.OriginalFileName);
|
||||
const shouldDownload = String(req.query.download || '') === '1' || !format?.preview;
|
||||
res.setHeader('Content-Type', format?.mimeType || 'application/octet-stream');
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Content-Length', String(document.FileSize));
|
||||
res.setHeader('Content-Disposition', getDocumentContentDisposition(document.OriginalFileName, shouldDownload));
|
||||
res.send(document.FileData);
|
||||
@@ -9677,11 +9655,19 @@ app.delete('/api/documents/:id', async (req, res) => {
|
||||
return res.status(403).json({ success: false, message: 'Bạn không có quyền xóa tài liệu này' });
|
||||
}
|
||||
|
||||
await pool.request()
|
||||
const deletedResult = await pool.request()
|
||||
.input('documentId', sql.Int, documentId)
|
||||
.query('DELETE FROM Documents WHERE DocumentId = @documentId');
|
||||
.query(`DELETE FROM Documents OUTPUT DELETED.DocumentId
|
||||
WHERE DocumentId = @documentId
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.RobotDocuments WHERE DocumentId = @documentId)`);
|
||||
if (!deletedResult.recordset.length) {
|
||||
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
|
||||
}
|
||||
res.json({ success: true, message: 'Đã xóa tài liệu' });
|
||||
} catch (err) {
|
||||
if (err.number === 547) {
|
||||
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
|
||||
}
|
||||
sendInternalError(res, err, 'Không thể xóa tài liệu');
|
||||
}
|
||||
});
|
||||
@@ -9739,7 +9725,7 @@ app.use((err, req, res, next) => {
|
||||
: err.message;
|
||||
return res.status(400).json({ success: false, message });
|
||||
}
|
||||
if (err.message === 'Only .xls and .xlsx files are allowed' || err.message === 'Chỉ chấp nhận file PDF') {
|
||||
if (err.message === 'Only .xls and .xlsx files are allowed' || err.code === 'DOCUMENT_VALIDATION') {
|
||||
return res.status(400).json({ success: false, message: err.message });
|
||||
}
|
||||
res.status(500).json({ success: false, message: 'Internal server error' });
|
||||
|
||||
Reference in New Issue
Block a user