Spaces:
Running

bacteriaqh's picture
Deploy 5313b66 từ GitHub Actions
e913295 verified
Raw History Blame
4.81 kB
/**
* @fileoverview API routes for archive operations.
* Configures multer for file uploads and applies security middleware.
* @module routes/api
*/
import { Router } from 'express';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
import {
createUploadRateLimiter,
validateSessionIdMiddleware,
validatePathMiddleware,
validateUploadedFile,
} from '../middleware/security.js';
import {
uploadArchive,
getFileTree,
downloadFile,
viewFile,
downloadFolder,
deleteSession,
} from '../controllers/archiveController.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = Router();
/**
* Maximum file size for uploads.
* @constant {number}
*/
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE) || 104857600; // 100MB
/**
* Configure multer storage.
* Files are stored with unique names to prevent conflicts.
*/
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadsDir = path.resolve(__dirname, '../../uploads');
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
// Generate unique filename to prevent conflicts
const uniqueId = uuidv4();
const ext = path.extname(file.originalname).toLowerCase();
cb(null, `${uniqueId}${ext}`);
},
});
/**
* Multer file filter.
* Only allows .zip and .rar files.
*/
const fileFilter = (req, file, cb) => {
cb(null, true);
};
/**
* Multer upload configuration.
*/
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: MAX_FILE_SIZE,
files: 10, // Allow up to 10 files at a time
},
});
/**
* Rate limiter for upload endpoint.
*/
const uploadRateLimiter = createUploadRateLimiter();
/**
* Error handler wrapper for async route handlers.
*
* @param {Function} fn - Async route handler
* @returns {Function} Wrapped handler with error catching
*/
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
/**
* Multer error handler middleware.
*
* @param {Error} err - Error object
* @param {Object} req - Express request
* @param {Object} res - Express response
* @param {Function} next - Next middleware
*/
const multerErrorHandler = (err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({
error: true,
message: `File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB`,
code: 'FILE_TOO_LARGE',
});
}
if (err.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({
error: true,
message: 'Only one file can be uploaded at a time',
code: 'TOO_MANY_FILES',
});
}
return res.status(400).json({
error: true,
message: err.message,
code: 'UPLOAD_ERROR',
});
}
next(err);
};
// ============================================
// Routes
// ============================================
/*
* GET/api/health
* Wake up server
* */
router.get('/health', asyncHandler(async (req, res) => {
return res.status(200).json({greet: "Hello"})
}))
/**
* POST /api/upload
* Upload and extract archive files (supports multiple files).
*
* Rate limited to 10 uploads per hour per IP.
* Validates file extension and magic bytes.
*/
router.post(
'/upload',
uploadRateLimiter,
upload.array('file', 10),
multerErrorHandler,
asyncHandler(validateUploadedFile),
asyncHandler(uploadArchive)
);
/**
* GET /api/files/:sessionId
* Get the file tree structure for an extracted archive.
*/
router.get(
'/files/:sessionId',
validateSessionIdMiddleware,
asyncHandler(getFileTree)
);
/**
* GET /api/download/:sessionId/file
* Download an individual file from the extracted archive.
* Query param: path - relative path to the file
*/
router.get(
'/download/:sessionId/file',
validateSessionIdMiddleware,
validatePathMiddleware,
asyncHandler(downloadFile)
);
/**
* GET /api/view/:sessionId/file
* View an individual file inline in the browser.
* Query param: path - relative path to the file
*/
router.get(
'/view/:sessionId/file',
validateSessionIdMiddleware,
validatePathMiddleware,
asyncHandler(viewFile)
);
/**
* GET /api/download/:sessionId/folder
* Download a folder as a ZIP archive.
* Query param: path - relative path to the folder (optional, defaults to root)
*/
router.get(
'/download/:sessionId/folder',
validateSessionIdMiddleware,
asyncHandler(downloadFolder)
);
/**
* DELETE /api/session/:sessionId
* Manually delete a session and its files.
*/
router.delete(
'/session/:sessionId',
validateSessionIdMiddleware,
asyncHandler(deleteSession)
);
export default router;