fx-1 / backend /middleware /fileScanner.middleware.js
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
10.2 kB
/**
* File Scanner Middleware — فحص الملفات المرفوعة بشكل شامل
* يفحص:
* - Magic Bytes (نوع الملف الحقيقي)
* - التشفير وحماية كلمة المرور في ZIP
* - SHA-256 Hash لضمان الثبات (Immutability)
* - حجم الملف وامتداده
*/
import crypto from 'crypto';
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
// ===== Magic Bytes Definitions =====
const MAGIC_SIGNATURES = {
ZIP: { bytes: [0x50, 0x4b, 0x03, 0x04], name: 'ZIP' },
ZIP_EMPTY: { bytes: [0x50, 0x4b, 0x05, 0x06], name: 'ZIP (Empty)' },
ZIP_SPAN: { bytes: [0x50, 0x4b, 0x07, 0x08], name: 'ZIP (Spanned)' },
RAR: { bytes: [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07], name: 'RAR' },
SEVENZIP: { bytes: [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c], name: '7-Zip' },
JAR: { bytes: [0x50, 0x4b, 0x03, 0x04], name: 'JAR (ZIP)' },
PNG: { bytes: [0x89, 0x50, 0x4e, 0x47], name: 'PNG' },
JPEG: { bytes: [0xff, 0xd8, 0xff], name: 'JPEG' },
WEBP: { bytes: [0x52, 0x49, 0x46, 0x46], name: 'WEBP/RIFF' },
GIF: { bytes: [0x47, 0x49, 0x46, 0x38], name: 'GIF' },
PDF: { bytes: [0x25, 0x50, 0x44, 0x46], name: 'PDF' },
EXE: { bytes: [0x4d, 0x5a], name: 'Windows EXE' },
ELF: { bytes: [0x7f, 0x45, 0x4c, 0x46], name: 'Linux ELF' },
CLASS: { bytes: [0xca, 0xfe, 0xba, 0xbe], name: 'Java Class' },
};
// امتدادات المرفوعة يجب أن تكون ZIP
const ZIP_EXTENSIONS = new Set(['.mcaddon', '.mcpack', '.mcworld', '.mctemplate', '.jar', '.zip']);
// امتدادات الصور المسموح بها
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
// الحد الأقصى لحجم الملف
const MAX_ADDON_SIZE = 100 * 1024 * 1024; // 100 MB
const MAX_IMAGE_SIZE = 5 * 1024 * 1024; // 5 MB
/**
* قراءة أول N بايت من Buffer
*/
function readMagicBytes(buffer, count = 8) {
return Array.from(buffer.slice(0, count));
}
/**
* مطابقة توقيع Magic Bytes
*/
function matchSignature(bytes, signature) {
return signature.every((b, i) => bytes[i] === b);
}
/**
* الكشف عن نوع الملف الحقيقي من Magic Bytes
*/
function detectFileType(buffer) {
const bytes = readMagicBytes(buffer, 8);
for (const [key, sig] of Object.entries(MAGIC_SIGNATURES)) {
if (matchSignature(bytes, sig.bytes)) {
return { type: key, name: sig.name };
}
}
return { type: 'UNKNOWN', name: 'Unknown' };
}
/**
* فحص ما إذا كان ملف ZIP مشفراً أو محمياً بكلمة مرور
* يفحص الـ General Purpose Bit Flag في كل Local File Header
*/
function checkZipEncryption(buffer) {
let offset = 0;
const maxOffset = Math.min(buffer.length - 30, 8192); // فحص أول 8KB
while (offset < maxOffset) {
// Local file header signature: PK\x03\x04
if (
buffer[offset] === 0x50 &&
buffer[offset + 1] === 0x4b &&
buffer[offset + 2] === 0x03 &&
buffer[offset + 3] === 0x04
) {
// General Purpose Bit Flag (bytes 6-7 من بداية header)
const flagLow = buffer[offset + 6];
const isEncrypted = (flagLow & 0x01) !== 0; // Bit 0: Traditional encryption
const isStrongEncrypted = (flagLow & 0x40) !== 0; // Bit 6: Strong encryption (AES)
if (isEncrypted || isStrongEncrypted) {
return {
encrypted: true,
method: isStrongEncrypted ? 'AES/Strong Encryption' : 'ZipCrypto',
};
}
// تحديد حجم اسم الملف للانتقال للإدخال التالي
const fileNameLength = buffer.readUInt16LE(offset + 26);
const extraFieldLength = buffer.readUInt16LE(offset + 28);
const compressedSize = buffer.readUInt32LE(offset + 18);
if (compressedSize === 0 || fileNameLength === 0) break;
offset += 30 + fileNameLength + extraFieldLength + compressedSize;
} else {
break;
}
}
return { encrypted: false, method: null };
}
/**
* حساب SHA-256 Hash لـ Buffer
*/
function computeSHA256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex');
}
/**
* حساب SHA-256 من Stream (للملفات الكبيرة)
*/
async function computeSHA256FromStream(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = createReadStream(filePath);
stream.on('data', (chunk) => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
/**
* Middleware رئيسي: فحص الملف المرفوع
*/
export const scanFile = async (req, res, next) => {
if (!req.file && (!req.files || req.files.length === 0)) {
return next();
}
const file = req.file || req.files[0];
const errors = [];
const scanResults = {};
try {
// قراءة محتوى الملف (أو Buffer إذا كان في الذاكرة)
const buffer = file.buffer || (file.path ? require('fs').readFileSync(file.path) : null);
if (!buffer) {
return res.status(400).json({
success: false,
message: 'تعذر قراءة الملف المرفوع',
code: 'FILE_READ_ERROR',
});
}
const ext = (file.originalname || '').toLowerCase().match(/\.[^.]+$/)?.[0] || '';
// 1. فحص الحجم
if (IMAGE_EXTENSIONS.has(ext) && file.size > MAX_IMAGE_SIZE) {
errors.push(`حجم الصورة كبير جداً. الحد الأقصى: ${MAX_IMAGE_SIZE / 1024 / 1024} ميجابايت`);
} else if (ZIP_EXTENSIONS.has(ext) && file.size > MAX_ADDON_SIZE) {
errors.push(`حجم الملف كبير جداً. الحد الأقصى: ${MAX_ADDON_SIZE / 1024 / 1024} ميجابايت`);
}
// 2. فحص Magic Bytes
const { type: detectedType, name: detectedName } = detectFileType(buffer);
scanResults.detectedType = detectedType;
scanResults.detectedName = detectedName;
// التحقق من توافق الامتداد مع النوع الحقيقي
if (ZIP_EXTENSIONS.has(ext)) {
if (!['ZIP', 'ZIP_EMPTY', 'ZIP_SPAN', 'JAR'].includes(detectedType)) {
if (['RAR', 'SEVENZIP'].includes(detectedType)) {
errors.push(`نوع الملف الحقيقي (${detectedName}) لا يطابق الامتداد (.${ext.slice(1).toUpperCase()}). استخدم ملف ZIP صحيح.`);
} else if (['EXE', 'ELF'].includes(detectedType)) {
errors.push(`الملف يحتوي على كود تنفيذي (${detectedName}) — مرفوض لأسباب أمنية.`);
} else if (detectedType !== 'UNKNOWN') {
errors.push(`تنسيق الملف غير متوافق: ${detectedName}. الامتداد .${ext.slice(1)} يتطلب ملف ZIP صحيح.`);
}
}
// 3. فحص التشفير في ZIP
if (['ZIP', 'ZIP_EMPTY', 'ZIP_SPAN', 'JAR'].includes(detectedType)) {
const { encrypted, method } = checkZipEncryption(buffer);
scanResults.encrypted = encrypted;
scanResults.encryptionMethod = method;
if (encrypted) {
errors.push(`الملف محمي بكلمة مرور أو مشفر (${method}). لا يمكن قبول الملفات المشفرة — قم بفك الضغط أولاً ثم أعد الضغط بدون كلمة مرور.`);
}
}
}
// 4. رفض الملفات التنفيذية
if (['EXE', 'ELF', 'CLASS'].includes(detectedType)) {
errors.push(`الملف من نوع تنفيذي (${detectedName}) — محظور تماماً.`);
}
// إذا كانت هناك أخطاء، أوقف العملية
if (errors.length > 0) {
return res.status(400).json({
success: false,
message: errors[0],
errors,
scan: {
detectedType: detectedName,
encrypted: scanResults.encrypted || false,
},
code: 'FILE_SCAN_FAILED',
});
}
// 5. حساب SHA-256 Hash
const sha256 = computeSHA256(buffer);
scanResults.sha256 = sha256;
scanResults.fileSize = file.size;
scanResults.originalName = file.originalname;
// إرفاق نتائج الفحص بالطلب
req.fileScanResult = {
...scanResults,
scannedAt: new Date().toISOString(),
passed: true,
};
req.log?.info({ sha256, detectedType, fileSize: file.size }, 'File scan passed');
next();
} catch (err) {
req.log?.error({ err }, 'File scan error');
return res.status(500).json({
success: false,
message: 'حدث خطأ أثناء فحص الملف',
code: 'SCAN_ERROR',
});
}
};
/**
* Middleware للتحقق من Immutability — منع استبدال الملفات المعتمدة
* يجب استخدامه قبل السماح بتحديث ملف في قاعدة البيانات
*/
export const enforceImmutability = (db) => async (req, res, next) => {
const { modId } = req.params;
if (!modId) return next();
try {
// جلب الملف من قاعدة البيانات للتحقق من حالته
const existingMod = await db('mods').where({ id: modId }).first();
if (!existingMod) return next();
// الملفات المعتمدة (approved/verified) لا يمكن استبدالها
if (existingMod.file_status === 'approved' || existingMod.file_status === 'verified') {
return res.status(403).json({
success: false,
message: 'لا يمكن تعديل أو استبدال ملف معتمد. الملفات المعتمدة محمية (Read-Only).',
code: 'FILE_IMMUTABLE',
fileStatus: existingMod.file_status,
sha256: existingMod.file_sha256,
});
}
next();
} catch (err) {
next(err);
}
};
/**
* التحقق من SHA-256 Hash لملف موجود مسبقاً
*/
export const verifyFileIntegrity = async (filePath, expectedHash) => {
try {
const actualHash = await computeSHA256FromStream(filePath);
return {
valid: actualHash === expectedHash,
actualHash,
expectedHash,
};
} catch {
return { valid: false, actualHash: null, expectedHash };
}
};
export { computeSHA256, detectFileType, checkZipEncryption };