Spaces:
Running
Running
Download extractor/server/middleware/security.js from bacteriaqh/docker: direct link, hf CLI and curl.
- Browser
- Download file 9.89 kB
-
https://huggingface.co/spaces/bacteriaqh/docker/resolve/main/extractor/server/middleware/security.js
- Command line
-
hf download hf://spaces/bacteriaqh/docker/extractor/server/middleware/security.js
-
curl -L -o security.js https://huggingface.co/spaces/bacteriaqh/docker/resolve/main/extractor/server/middleware/security.js
9.89 kB
| /** | |
| * @fileoverview Security middleware for file upload validation and path sanitization. | |
| * Implements comprehensive security measures to prevent malicious uploads and path traversal attacks. | |
| * @module middleware/security | |
| */ | |
| import rateLimit from 'express-rate-limit'; | |
| import fs from 'fs-extra'; | |
| import path from 'path'; | |
| /** | |
| * Magic bytes signatures for supported archive formats. | |
| * These are the first bytes of valid archive files. | |
| * @constant {Object} | |
| */ | |
| const MAGIC_BYTES = { | |
| // ZIP magic bytes: PK\x03\x04 (also PK\x05\x06 for empty ZIP, PK\x07\x08 for spanned) | |
| zip: [ | |
| [0x50, 0x4b, 0x03, 0x04], // Standard ZIP | |
| [0x50, 0x4b, 0x05, 0x06], // Empty ZIP | |
| [0x50, 0x4b, 0x07, 0x08], // Spanned ZIP | |
| ], | |
| // RAR magic bytes - support both RAR4 and RAR5 | |
| // RAR4: Rar!\x1a\x07\x00 | |
| // RAR5: Rar!\x1a\x07\x01\x00 | |
| // Common prefix: Rar!\x1a\x07 (6 bytes) | |
| rar: [ | |
| [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07], // Common RAR signature (works for both RAR4 and RAR5) | |
| ], | |
| }; | |
| /** | |
| * Allowed file extensions for upload. | |
| * @constant {Set<string>} | |
| */ | |
| const ARCHIVE_EXTENSIONS = new Set(['.zip', '.rar']); | |
| /** | |
| * Maximum filename length to prevent filesystem issues. | |
| * @constant {number} | |
| */ | |
| const MAX_FILENAME_LENGTH = 255; | |
| /** | |
| * Regex pattern for characters to remove from filenames. | |
| * Allows alphanumeric, dots, hyphens, underscores, and spaces. | |
| * @constant {RegExp} | |
| */ | |
| const UNSAFE_FILENAME_CHARS = /[^a-zA-Z0-9.\-_\s]/g; | |
| /** | |
| * Creates a rate limiter middleware for upload endpoint. | |
| * Limits requests based on IP address to prevent abuse. | |
| * | |
| * @returns {Function} Express rate limit middleware | |
| */ | |
| export const createUploadRateLimiter = () => { | |
| const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW) || 3600000; // 1 hour | |
| const max = parseInt(process.env.RATE_LIMIT_MAX) || 10; | |
| return rateLimit({ | |
| windowMs, | |
| max, | |
| message: { | |
| error: true, | |
| message: 'Too many upload requests. Please try again later.', | |
| code: 'RATE_LIMIT_EXCEEDED', | |
| }, | |
| standardHeaders: true, | |
| legacyHeaders: false, | |
| // Use IP address for rate limiting | |
| keyGenerator: (req) => req.ip, | |
| }); | |
| }; | |
| /** | |
| * Validates file extension against allowed list. | |
| * | |
| * @param {string} filename - The filename to validate | |
| * @returns {boolean} True if extension is allowed | |
| */ | |
| export const isArchiveExtension = (filename) => { | |
| const ext = path.extname(filename).toLowerCase(); | |
| return ARCHIVE_EXTENSIONS.has(ext); | |
| }; | |
| /** | |
| * Validates file magic bytes to ensure file content matches extension. | |
| * SECURITY: This prevents malicious files disguised with wrong extensions. | |
| * | |
| * @async | |
| * @param {string} filePath - Path to the file to validate | |
| * @param {string} expectedType - Expected file type ('zip' or 'rar') | |
| * @returns {Promise<boolean>} True if magic bytes match expected type | |
| */ | |
| export const validateMagicBytes = async (filePath, expectedType) => { | |
| try { | |
| const expectedSignatures = MAGIC_BYTES[expectedType]; | |
| if (!expectedSignatures || expectedSignatures.length === 0) { | |
| return false; | |
| } | |
| // Find the maximum signature length we need to read | |
| const maxLength = Math.max(...expectedSignatures.map(sig => sig.length)); | |
| // Read the first bytes of the file | |
| const fileBuffer = await fs.readFile(filePath); | |
| const buffer = fileBuffer.slice(0, maxLength); | |
| // Debug logging | |
| console.log(`Validating ${expectedType} file, first ${maxLength} bytes:`, | |
| Array.from(buffer).map(b => '0x' + b.toString(16).padStart(2, '0')).join(', ') | |
| ); | |
| // Check against each possible signature | |
| for (const expectedBytes of expectedSignatures) { | |
| let matches = true; | |
| for (let i = 0; i < expectedBytes.length; i++) { | |
| if (buffer[i] !== expectedBytes[i]) { | |
| matches = false; | |
| break; | |
| } | |
| } | |
| if (matches) { | |
| console.log(`Magic bytes match for ${expectedType}`); | |
| return true; | |
| } | |
| } | |
| console.log(`No magic bytes match found for ${expectedType}`); | |
| return false; | |
| } catch (error) { | |
| console.error('Magic bytes validation error:', error.message); | |
| return false; | |
| } | |
| }; | |
| /** | |
| * Sanitizes a filename by removing dangerous characters and limiting length. | |
| * SECURITY: Prevents directory traversal and filesystem exploits through filenames. | |
| * | |
| * @param {string} filename - The filename to sanitize | |
| * @returns {string} Sanitized filename | |
| */ | |
| export const sanitizeFilename = (filename) => { | |
| if (!filename || typeof filename !== 'string') { | |
| return 'unnamed_file'; | |
| } | |
| // Remove path components | |
| let sanitized = path.basename(filename); | |
| // Remove unsafe characters | |
| sanitized = sanitized.replace(UNSAFE_FILENAME_CHARS, '_'); | |
| // Remove leading/trailing dots and spaces | |
| sanitized = sanitized.replace(/^[\s.]+|[\s.]+$/g, ''); | |
| // Limit length | |
| if (sanitized.length > MAX_FILENAME_LENGTH) { | |
| const ext = path.extname(sanitized); | |
| const name = path.basename(sanitized, ext); | |
| sanitized = name.substring(0, MAX_FILENAME_LENGTH - ext.length) + ext; | |
| } | |
| // Fallback if empty after sanitization | |
| if (!sanitized) { | |
| return 'unnamed_file'; | |
| } | |
| return sanitized; | |
| }; | |
| /** | |
| * Validates a path to prevent directory traversal attacks. | |
| * SECURITY: Rejects paths containing ".." or absolute path indicators. | |
| * | |
| * @param {string} requestedPath - The path to validate | |
| * @returns {{valid: boolean, error?: string}} Validation result | |
| */ | |
| export const validatePath = (requestedPath) => { | |
| if (!requestedPath || typeof requestedPath !== 'string') { | |
| return { valid: false, error: 'Path is required' }; | |
| } | |
| // SECURITY: Check for path traversal attempts | |
| if (requestedPath.includes('..')) { | |
| return { valid: false, error: 'Path traversal detected' }; | |
| } | |
| // SECURITY: Reject absolute paths | |
| if (path.isAbsolute(requestedPath)) { | |
| return { valid: false, error: 'Absolute paths not allowed' }; | |
| } | |
| // SECURITY: Check for null bytes (can be used to bypass some checks) | |
| if (requestedPath.includes('\0')) { | |
| return { valid: false, error: 'Invalid path characters' }; | |
| } | |
| return { valid: true }; | |
| }; | |
| /** | |
| * Validates a session ID format. | |
| * SECURITY: Only allows valid UUID v4 format to prevent injection. | |
| * | |
| * @param {string} sessionId - The session ID to validate | |
| * @returns {boolean} True if session ID is valid UUID v4 | |
| */ | |
| export const isValidSessionId = (sessionId) => { | |
| if (!sessionId || typeof sessionId !== 'string') { | |
| return false; | |
| } | |
| // UUID v4 pattern for legacy sessions and 8-digit pattern for share codes | |
| const uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | |
| const accessCodePattern = /^\d{8}$/; | |
| return uuidV4Pattern.test(sessionId) || accessCodePattern.test(sessionId); | |
| }; | |
| /** | |
| * Middleware to validate session ID parameter. | |
| * | |
| * @param {Object} req - Express request object | |
| * @param {Object} res - Express response object | |
| * @param {Function} next - Express next function | |
| */ | |
| export const validateSessionIdMiddleware = (req, res, next) => { | |
| const { sessionId } = req.params; | |
| if (!isValidSessionId(sessionId)) { | |
| return res.status(400).json({ | |
| error: true, | |
| message: 'Invalid session ID or 8-digit access code format', | |
| code: 'INVALID_SESSION_ID', | |
| }); | |
| } | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate file path query parameter. | |
| * | |
| * @param {Object} req - Express request object | |
| * @param {Object} res - Express response object | |
| * @param {Function} next - Express next function | |
| */ | |
| export const validatePathMiddleware = (req, res, next) => { | |
| const filePath = req.query.path; | |
| if (!filePath) { | |
| return res.status(400).json({ | |
| error: true, | |
| message: 'File path is required', | |
| code: 'MISSING_PATH', | |
| }); | |
| } | |
| const validation = validatePath(filePath); | |
| if (!validation.valid) { | |
| return res.status(400).json({ | |
| error: true, | |
| message: validation.error, | |
| code: 'INVALID_PATH', | |
| }); | |
| } | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate uploaded files. | |
| * Checks file existence, extension, and magic bytes. | |
| * Supports both single and multiple file uploads. | |
| * | |
| * @param {Object} req - Express request object | |
| * @param {Object} res - Express response object | |
| * @param {Function} next - Express next function | |
| */ | |
| export const validateUploadedFile = async (req, res, next) => { | |
| 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', | |
| }); | |
| } | |
| // Validate each file | |
| for (const file of files) { | |
| const { originalname, path: filePath } = file; | |
| // Only archives need strict magic-byte validation before extraction. | |
| if (!isArchiveExtension(originalname)) { | |
| continue; | |
| } | |
| // Determine expected archive type from extension | |
| const ext = path.extname(originalname).toLowerCase().slice(1); | |
| // Validate magic bytes | |
| const isValidMagic = await validateMagicBytes(filePath, ext); | |
| if (!isValidMagic) { | |
| // Clean up all uploaded files | |
| for (const f of files) { | |
| await fs.remove(f.path).catch(() => {}); | |
| } | |
| return res.status(400).json({ | |
| error: true, | |
| message: `Archive content does not match file extension: ${originalname}`, | |
| code: 'INVALID_MAGIC_BYTES', | |
| }); | |
| } | |
| } | |
| next(); | |
| } catch (error) { | |
| console.error('File validation error:', error); | |
| // Clean up on error | |
| const files = req.files || (req.file ? [req.file] : []); | |
| for (const file of files) { | |
| await fs.remove(file.path).catch(() => {}); | |
| } | |
| return res.status(500).json({ | |
| error: true, | |
| message: 'File validation failed', | |
| code: 'VALIDATION_ERROR', | |
| }); | |
| } | |
| }; | |