quản lí robot

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

116
backend/document-files.js Normal file
View 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 };