/** * @fileoverview Archive controller handling all API endpoint logic. * Manages file uploads, extraction, file tree generation, and downloads. * @module controllers/archiveController */ import fs from 'fs-extra'; import path from 'path'; import { randomInt } from 'crypto'; import archiver from 'archiver'; import { fileURLToPath } from 'url'; import mime from 'mime-types'; import { extractArchive, getExtractionStats } from '../services/extractionService.js'; import { generateFileTree } from '../utils/fileTree.js'; import { validatePath, sanitizeFilename, isArchiveExtension } from '../middleware/security.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Base paths for file storage. * @constant {Object} */ const PATHS = { uploads: path.resolve(__dirname, '../../uploads'), extracted: path.resolve(__dirname, '../../extracted'), }; // Ensure directories exist await fs.ensureDir(PATHS.uploads); await fs.ensureDir(PATHS.extracted); /** * Stores active session information for cleanup. * @type {Map} */ const activeSessions = new Map(); /** * Session timeout duration. * @constant {number} */ const SESSION_TIMEOUT = parseInt(process.env.SESSION_TIMEOUT) || 60000; // 1 minute /** * 8-digit numeric access code pattern used as the public session identifier. * @constant {RegExp} */ const ACCESS_CODE_PATTERN = /^\d{8}$/; /** * Generates a unique 8-digit numeric code that maps directly to a session folder. * * @async * @returns {Promise} Unique access code */ const generateAccessCode = async () => { for (let attempt = 0; attempt < 30; attempt++) { const code = String(randomInt(0, 100000000)).padStart(8, '0'); const exists = await fs.pathExists(path.join(PATHS.extracted, code)); if (!exists && ACCESS_CODE_PATTERN.test(code)) { return code; } } throw new Error('Unable to generate a unique access code'); }; /** * Schedules automatic cleanup for a session. * * @param {string} sessionId - Session ID to schedule cleanup for */ const scheduleCleanup = (sessionId) => { const createdAt = Date.now(); const expiresAt = createdAt + SESSION_TIMEOUT; const timeout = setTimeout(async () => { await cleanupSession(sessionId); }, SESSION_TIMEOUT); activeSessions.set(sessionId, { createdAt, expiresAt, timeout, }); return { createdAt, expiresAt }; }; /** * Gets expiry information for a session. * * @param {string} sessionId - Session ID * @returns {{expiresAt: number|null, timeRemainingMs: number|null}} */ const getSessionExpiryInfo = (sessionId) => { const session = activeSessions.get(sessionId); if (!session?.expiresAt) { return { expiresAt: null, timeRemainingMs: null, }; } return { expiresAt: session.expiresAt, timeRemainingMs: Math.max(0, session.expiresAt - Date.now()), }; }; /** * Cleans up session files and data. * * @async * @param {string} sessionId - Session ID to cleanup * @returns {Promise} True if cleanup succeeded */ const cleanupSession = async (sessionId) => { try { const session = activeSessions.get(sessionId); if (session?.timeout) { clearTimeout(session.timeout); } activeSessions.delete(sessionId); // Remove extracted files const extractedPath = path.join(PATHS.extracted, sessionId); await fs.remove(extractedPath); // Remove uploaded file const uploadPattern = path.join(PATHS.uploads, `${sessionId}*`); const uploadFiles = await fs.readdir(PATHS.uploads); for (const file of uploadFiles) { if (file.startsWith(sessionId)) { await fs.remove(path.join(PATHS.uploads, file)); } } console.log(`Session cleaned up: ${sessionId}`); return true; } catch (error) { console.error(`Cleanup error for session ${sessionId}:`, error.message); return false; } }; /** * Handles file upload and extraction. * Supports both single and multiple file uploads. * POST /api/upload * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const uploadArchive = async (req, res) => { const createdSessions = []; const uploadPaths = []; try { // Support both single file (req.file) and multiple files (req.files) const files = req.files || (req.file ? [req.file] : []); if (files.length === 0) { return res.status(400).json({ error: true, message: 'No file uploaded', code: 'NO_FILE', }); } // Get password from request body (optional) const password = req.body?.password || null; const results = []; // Process each file for (const file of files) { const sessionId = await generateAccessCode(); const uploadPath = file.path; createdSessions.push(sessionId); uploadPaths.push(uploadPath); // Create session extraction directory const extractionPath = path.join(PATHS.extracted, sessionId); await fs.ensureDir(extractionPath, { mode: 0o755 }); const safeFilename = sanitizeFilename(file.originalname); const isArchive = isArchiveExtension(file.originalname); if (isArchive) { // Extract the archive (with password if provided) console.log(`Extracting ${file.originalname} to session ${sessionId}${password ? ' (with password)' : ''}`); const result = await extractArchive(uploadPath, extractionPath, { password }); if (!result.success) { // Clean up on extraction failure await fs.remove(extractionPath); await fs.remove(uploadPath); const statusCode = result.code === 'PASSWORD_PROTECTED' || result.code === 'INCORRECT_PASSWORD' || result.code === 'CORRUPTED_ARCHIVE' ? 422 : 500; return res.status(statusCode).json({ error: true, message: `${file.originalname}: ${result.error}`, code: result.code, }); } // Clean up uploaded archive (no longer needed) await fs.remove(uploadPath); } else { // Plain files do not need extraction. Store them directly in the session folder. await fs.move(uploadPath, path.join(extractionPath, safeFilename), { overwrite: false }); } // Get extraction stats const stats = await getExtractionStats(extractionPath); // Schedule automatic cleanup const expiryInfo = scheduleCleanup(sessionId); results.push({ sessionId, accessCode: sessionId, filename: safeFilename, type: isArchive ? 'archive' : 'file', expiresAt: expiryInfo.expiresAt, timeRemainingMs: Math.max(0, expiryInfo.expiresAt - Date.now()), stats: { totalFiles: stats.totalFiles, totalSize: stats.totalSize, }, }); } // Return response based on single or multiple files if (results.length === 1) { res.status(200).json({ success: true, ...results[0], }); } else { res.status(200).json({ success: true, count: results.length, archives: results, }); } } catch (error) { console.error('Upload error:', error); // Clean up on error for (const sessionId of createdSessions) { await fs.remove(path.join(PATHS.extracted, sessionId)).catch(() => {}); } for (const uploadPath of uploadPaths) { await fs.remove(uploadPath).catch(() => {}); } res.status(500).json({ error: true, message: 'Failed to process archive', code: 'INTERNAL_ERROR', }); } }; /** * Returns the file tree for a session. * GET /api/files/:sessionId * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const getFileTree = async (req, res) => { try { const { sessionId } = req.params; const sessionPath = path.join(PATHS.extracted, sessionId); // Check if session exists const exists = await fs.pathExists(sessionPath); if (!exists) { return res.status(404).json({ error: true, message: 'Session not found or expired', code: 'SESSION_NOT_FOUND', }); } // Generate file tree const tree = await generateFileTree(sessionPath); const expiryInfo = getSessionExpiryInfo(sessionId); res.status(200).json({ success: true, sessionId, expiresAt: expiryInfo.expiresAt, timeRemainingMs: expiryInfo.timeRemainingMs, tree, }); } catch (error) { console.error('Get file tree error:', error); res.status(500).json({ error: true, message: 'Failed to retrieve file structure', code: 'INTERNAL_ERROR', }); } }; /** * Downloads an individual file. * GET /api/download/:sessionId/file?path= * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const downloadFile = async (req, res) => { try { const { sessionId } = req.params; const filePath = req.query.path; // Path validation is done in middleware, but double-check const pathValidation = validatePath(filePath); if (!pathValidation.valid) { return res.status(400).json({ error: true, message: pathValidation.error, code: 'INVALID_PATH', }); } const sessionPath = path.join(PATHS.extracted, sessionId); const fullPath = path.join(sessionPath, filePath); // SECURITY: Ensure path stays within session directory const normalizedPath = path.normalize(fullPath); if (!normalizedPath.startsWith(path.normalize(sessionPath))) { return res.status(400).json({ error: true, message: 'Invalid file path', code: 'INVALID_PATH', }); } // Check if file exists const exists = await fs.pathExists(fullPath); if (!exists) { return res.status(404).json({ error: true, message: 'File not found', code: 'FILE_NOT_FOUND', }); } // Check if it's a file (not directory) const stats = await fs.stat(fullPath); if (stats.isDirectory()) { return res.status(400).json({ error: true, message: 'Cannot download a directory. Use folder download endpoint.', code: 'IS_DIRECTORY', }); } // Set headers and send file const filename = sanitizeFilename(path.basename(fullPath)); const contentType = mime.lookup(fullPath) || 'application/octet-stream'; res.setHeader('Content-Type', contentType); res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); res.setHeader('Content-Length', stats.size); const readStream = fs.createReadStream(fullPath); readStream.pipe(res); } catch (error) { console.error('Download file error:', error); res.status(500).json({ error: true, message: 'Failed to download file', code: 'INTERNAL_ERROR', }); } }; /** * Views an individual file inline when the browser supports the content type. * GET /api/view/:sessionId/file?path= * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const viewFile = async (req, res) => { try { const { sessionId } = req.params; const filePath = req.query.path; const pathValidation = validatePath(filePath); if (!pathValidation.valid) { return res.status(400).json({ error: true, message: pathValidation.error, code: 'INVALID_PATH', }); } const sessionPath = path.join(PATHS.extracted, sessionId); const fullPath = path.join(sessionPath, filePath); const normalizedPath = path.normalize(fullPath); if (!normalizedPath.startsWith(path.normalize(sessionPath))) { return res.status(400).json({ error: true, message: 'Invalid file path', code: 'INVALID_PATH', }); } const exists = await fs.pathExists(fullPath); if (!exists) { return res.status(404).json({ error: true, message: 'File not found', code: 'FILE_NOT_FOUND', }); } const stats = await fs.stat(fullPath); if (stats.isDirectory()) { return res.status(400).json({ error: true, message: 'Cannot view a directory. Open or download a file instead.', code: 'IS_DIRECTORY', }); } const filename = sanitizeFilename(path.basename(fullPath)); const contentType = mime.lookup(fullPath) || 'application/octet-stream'; res.setHeader('Content-Type', contentType); res.setHeader('Content-Disposition', `inline; filename="${filename}"`); res.setHeader('Content-Length', stats.size); res.setHeader('X-Content-Type-Options', 'nosniff'); const readStream = fs.createReadStream(fullPath); readStream.pipe(res); } catch (error) { console.error('View file error:', error); res.status(500).json({ error: true, message: 'Failed to view file', code: 'INTERNAL_ERROR', }); } }; /** * Downloads a folder as a ZIP archive. * GET /api/download/:sessionId/folder?path= * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const downloadFolder = async (req, res) => { try { const { sessionId } = req.params; const folderPath = req.query.path || '/'; // Path validation if (folderPath !== '/') { const pathValidation = validatePath(folderPath); if (!pathValidation.valid) { return res.status(400).json({ error: true, message: pathValidation.error, code: 'INVALID_PATH', }); } } const sessionPath = path.join(PATHS.extracted, sessionId); const fullPath = folderPath === '/' ? sessionPath : path.join(sessionPath, folderPath); // SECURITY: Ensure path stays within session directory const normalizedPath = path.normalize(fullPath); if (!normalizedPath.startsWith(path.normalize(sessionPath))) { return res.status(400).json({ error: true, message: 'Invalid folder path', code: 'INVALID_PATH', }); } // Check if folder exists const exists = await fs.pathExists(fullPath); if (!exists) { return res.status(404).json({ error: true, message: 'Folder not found', code: 'FILE_NOT_FOUND', }); } // Check if it's a directory const stats = await fs.stat(fullPath); if (!stats.isDirectory()) { return res.status(400).json({ error: true, message: 'Path is not a folder. Use file download endpoint.', code: 'NOT_DIRECTORY', }); } // Create ZIP archive const folderName = folderPath === '/' ? 'archive' : sanitizeFilename(path.basename(fullPath)); const zipFilename = `${folderName}.zip`; res.setHeader('Content-Type', 'application/zip'); res.setHeader('Content-Disposition', `attachment; filename="${zipFilename}"`); const archive = archiver('zip', { zlib: { level: 6 }, // Balanced compression }); archive.on('error', (err) => { console.error('Archiver error:', err); if (!res.headersSent) { res.status(500).json({ error: true, message: 'Failed to create archive', code: 'ARCHIVE_ERROR', }); } }); archive.pipe(res); archive.directory(fullPath, false); await archive.finalize(); } catch (error) { console.error('Download folder error:', error); if (!res.headersSent) { res.status(500).json({ error: true, message: 'Failed to download folder', code: 'INTERNAL_ERROR', }); } } }; /** * Manually deletes a session. * DELETE /api/session/:sessionId * * @async * @param {Object} req - Express request object * @param {Object} res - Express response object */ export const deleteSession = async (req, res) => { try { const { sessionId } = req.params; const sessionPath = path.join(PATHS.extracted, sessionId); // Check if session exists const exists = await fs.pathExists(sessionPath); if (!exists) { return res.status(404).json({ error: true, message: 'Session not found', code: 'SESSION_NOT_FOUND', }); } // Clean up the session const success = await cleanupSession(sessionId); if (success) { res.status(200).json({ success: true, message: 'Session deleted successfully', }); } else { res.status(500).json({ error: true, message: 'Failed to delete session', code: 'CLEANUP_ERROR', }); } } catch (error) { console.error('Delete session error:', error); res.status(500).json({ error: true, message: 'Failed to delete session', code: 'INTERNAL_ERROR', }); } }; /** * Gets session information. * Used internally for monitoring. * * @param {string} sessionId - Session ID * @returns {Object|null} Session info or null */ export const getSessionInfo = (sessionId) => { return activeSessions.get(sessionId) || null; }; /** * Gets count of active sessions. * * @returns {number} Number of active sessions */ export const getActiveSessionCount = () => { return activeSessions.size; };