Spaces:
Running

docker / extractor /server /services /extractionService.js
bacteriaqh's picture
Deploy 5313b66 từ GitHub Actions
e913295 verified
Raw History Blame
10.8 kB
/**
* @fileoverview Archive extraction service for ZIP and RAR files.
* Handles recursive extraction with security measures including zip bomb protection.
* @module services/extractionService
*/
import AdmZip from 'adm-zip';
import { createExtractorFromFile } from 'node-unrar-js';
import fs from 'fs-extra';
import path from 'path';
import { sanitizeFilename, validatePath } from '../middleware/security.js';
/**
* Maximum size for individual extracted files (zip bomb protection).
* @constant {number}
*/
const MAX_EXTRACTED_FILE_SIZE = parseInt(process.env.MAX_EXTRACTED_FILE_SIZE) || 52428800; // 50MB
/**
* Archive extensions that should be recursively extracted.
* @constant {Set<string>}
*/
const NESTED_ARCHIVE_EXTENSIONS = new Set(['.zip', '.rar']);
/**
* Extracts an archive file to a destination directory.
* Automatically detects archive type and handles nested archives.
*
* @async
* @param {string} archivePath - Path to the archive file
* @param {string} destPath - Destination directory for extraction
* @param {Object} options - Extraction options
* @param {string} [options.password] - Password for encrypted archives
* @returns {Promise<{success: boolean, error?: string, code?: string}>} Extraction result
*/
export const extractArchive = async (archivePath, destPath, options = {}) => {
const ext = path.extname(archivePath).toLowerCase();
const { password } = options;
try {
// Ensure destination directory exists with restricted permissions
await fs.ensureDir(destPath, { mode: 0o755 });
if (ext === '.zip') {
return await extractZip(archivePath, destPath, password);
} else if (ext === '.rar') {
return await extractRar(archivePath, destPath, password);
} else {
return {
success: false,
error: 'Unsupported archive format',
code: 'UNSUPPORTED_FORMAT',
};
}
} catch (error) {
console.error('Extraction error:', error);
return {
success: false,
error: error.message || 'Extraction failed',
code: 'EXTRACTION_FAILED',
};
}
};
/**
* Extracts a ZIP archive.
* Uses adm-zip library with security validations.
*
* @async
* @param {string} zipPath - Path to the ZIP file
* @param {string} destPath - Destination directory
* @param {string} [password] - Password for encrypted archives
* @returns {Promise<{success: boolean, error?: string, code?: string}>}
*/
const extractZip = async (zipPath, destPath, password = null) => {
try {
const zip = new AdmZip(zipPath);
// Check if archive is encrypted and we have a password
const entries = zip.getEntries();
const hasEncryptedEntries = entries.some(entry => entry.header.encripted);
if (hasEncryptedEntries && !password) {
return {
success: false,
error: 'Archive is password protected. Please provide a password.',
code: 'PASSWORD_PROTECTED',
};
}
for (const entry of entries) {
// Skip directories, they'll be created with files
if (entry.isDirectory) {
continue;
}
// SECURITY: Validate and sanitize entry path
const entryPath = entry.entryName;
const pathValidation = validatePath(entryPath);
if (!pathValidation.valid) {
console.warn(`Skipping unsafe entry: ${entryPath}`);
continue;
}
// SECURITY: Check for zip bomb (decompression ratio attack)
if (entry.header.size > MAX_EXTRACTED_FILE_SIZE) {
console.warn(`Skipping oversized entry: ${entryPath} (${entry.header.size} bytes)`);
continue;
}
// Sanitize each path component
const pathParts = entryPath.split('/').filter(Boolean);
const sanitizedParts = pathParts.map((part, index) => {
// Don't sanitize extension for the last part (filename)
if (index === pathParts.length - 1) {
return sanitizeFilename(part);
}
return sanitizeFilename(part);
});
const sanitizedPath = sanitizedParts.join(path.sep);
const fullDestPath = path.join(destPath, sanitizedPath);
// SECURITY: Ensure file stays within destination directory
const normalizedDest = path.normalize(fullDestPath);
if (!normalizedDest.startsWith(path.normalize(destPath))) {
console.warn(`Path escape attempt blocked: ${entryPath}`);
continue;
}
// Create parent directory
await fs.ensureDir(path.dirname(fullDestPath), { mode: 0o755 });
// Extract file (with password if provided)
let content;
try {
content = password ? entry.getData(password) : entry.getData();
} catch (decryptError) {
if (decryptError.message?.includes('password') || decryptError.message?.includes('decrypt')) {
return {
success: false,
error: 'Incorrect password for archive',
code: 'INCORRECT_PASSWORD',
};
}
throw decryptError;
}
// SECURITY: Final size check on actual extracted data
if (content.length > MAX_EXTRACTED_FILE_SIZE) {
console.warn(`Extracted content too large: ${entryPath}`);
continue;
}
await fs.writeFile(fullDestPath, content, { mode: 0o644 });
// Check if extracted file is a nested archive
const ext = path.extname(fullDestPath).toLowerCase();
if (NESTED_ARCHIVE_EXTENSIONS.has(ext)) {
const nestedDestPath = fullDestPath.replace(/\.(zip|rar)$/i, '');
const nestedResult = await extractArchive(fullDestPath, nestedDestPath);
if (nestedResult.success) {
// Remove the nested archive after extraction
await fs.remove(fullDestPath);
}
}
}
return { success: true };
} catch (error) {
// Handle specific ZIP errors
if (error.message?.includes('password')) {
return {
success: false,
error: 'Archive is password protected',
code: 'PASSWORD_PROTECTED',
};
}
if (error.message?.includes('Invalid') || error.message?.includes('corrupt')) {
return {
success: false,
error: 'Archive appears to be corrupted',
code: 'CORRUPTED_ARCHIVE',
};
}
throw error;
}
};
/**
* Extracts a RAR archive.
* Uses node-unrar-js library with security validations.
*
* @async
* @param {string} rarPath - Path to the RAR file
* @param {string} destPath - Destination directory
* @param {string} [password] - Password for encrypted archives
* @returns {Promise<{success: boolean, error?: string, code?: string}>}
*/
const extractRar = async (rarPath, destPath, password = null) => {
try {
const extractorOptions = {
filepath: rarPath,
targetPath: destPath,
};
// Add password if provided
if (password) {
extractorOptions.password = password;
}
const extractor = await createExtractorFromFile(extractorOptions);
// Get list of files first to validate
const list = extractor.getFileList();
const fileHeaders = [...list.fileHeaders];
// Check for password protection
for (const header of fileHeaders) {
if (header.flags?.encrypted) {
if (!password) {
return {
success: false,
error: 'Archive is password protected. Please provide a password.',
code: 'PASSWORD_PROTECTED',
};
}
break; // Password provided, continue with extraction
}
}
// Extract files
const extracted = extractor.extract();
const files = [...extracted.files];
// Process extracted files
for (const file of files) {
if (file.fileHeader.flags?.directory) {
continue;
}
const filePath = file.fileHeader.name;
// SECURITY: Validate path
const pathValidation = validatePath(filePath);
if (!pathValidation.valid) {
const fullPath = path.join(destPath, filePath);
await fs.remove(fullPath).catch(() => {});
console.warn(`Removed unsafe entry: ${filePath}`);
continue;
}
// SECURITY: Check extracted file size
const fullPath = path.join(destPath, filePath);
try {
const stats = await fs.stat(fullPath);
if (stats.size > MAX_EXTRACTED_FILE_SIZE) {
await fs.remove(fullPath);
console.warn(`Removed oversized entry: ${filePath}`);
continue;
}
} catch (e) {
// File might not exist if extraction failed
}
// Check for nested archives
const ext = path.extname(fullPath).toLowerCase();
if (NESTED_ARCHIVE_EXTENSIONS.has(ext)) {
const nestedDestPath = fullPath.replace(/\.(zip|rar)$/i, '');
const nestedResult = await extractArchive(fullPath, nestedDestPath);
if (nestedResult.success) {
await fs.remove(fullPath);
}
}
}
return { success: true };
} catch (error) {
// Handle specific RAR errors
if (error.message?.includes('password') || error.message?.includes('encrypted')) {
if (password) {
return {
success: false,
error: 'Incorrect password for archive',
code: 'INCORRECT_PASSWORD',
};
}
return {
success: false,
error: 'Archive is password protected. Please provide a password.',
code: 'PASSWORD_PROTECTED',
};
}
if (error.message?.includes('Invalid') || error.message?.includes('corrupt') ||
error.message?.includes('Bad')) {
return {
success: false,
error: 'Archive appears to be corrupted',
code: 'CORRUPTED_ARCHIVE',
};
}
throw error;
}
};
/**
* Checks if a file is an archive that can be extracted.
*
* @param {string} filePath - Path to check
* @returns {boolean} True if file is a supported archive
*/
export const isArchive = (filePath) => {
const ext = path.extname(filePath).toLowerCase();
return NESTED_ARCHIVE_EXTENSIONS.has(ext);
};
/**
* Gets extraction statistics for a session.
*
* @async
* @param {string} sessionPath - Path to the extracted session
* @returns {Promise<{totalFiles: number, totalSize: number}>}
*/
export const getExtractionStats = async (sessionPath) => {
let totalFiles = 0;
let totalSize = 0;
const walk = async (dir) => {
const entries = await fs.readdir(dir);
for (const entry of entries) {
const fullPath = path.join(dir, entry);
const stats = await fs.stat(fullPath);
if (stats.isDirectory()) {
await walk(fullPath);
} else {
totalFiles++;
totalSize += stats.size;
}
}
};
await walk(sessionPath);
return { totalFiles, totalSize };
};