Download backend/middleware/validation.middleware.js from felix-fx/fx-1: direct link, hf CLI and curl.
- Browser
- Download file 9.35 kB
-
https://huggingface.co/felix-fx/fx-1/resolve/main/backend/middleware/validation.middleware.js
- Command line
-
hf download hf://felix-fx/fx-1/backend/middleware/validation.middleware.js
-
curl -L -o validation.middleware.js https://huggingface.co/felix-fx/fx-1/resolve/main/backend/middleware/validation.middleware.js
9.35 kB
| /** | |
| * Request Validation Middleware | |
| * Validates and sanitizes incoming requests | |
| */ | |
| import Joi from 'joi'; | |
| import validator from 'validator'; | |
| // Common validation schemas | |
| const schemas = { | |
| // Auth schemas | |
| register: Joi.object({ | |
| email: Joi.string().email().required().max(255), | |
| password: Joi.string() | |
| .min(12) | |
| .max(128) | |
| .pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/) | |
| .required() | |
| .messages({ | |
| 'string.pattern.base': 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character' | |
| }), | |
| username: Joi.string() | |
| .alphanum() | |
| .min(3) | |
| .max(30) | |
| .required(), | |
| displayName: Joi.string().min(2).max(50).optional() | |
| }), | |
| login: Joi.object({ | |
| email: Joi.string().email().required(), | |
| password: Joi.string().required(), | |
| rememberMe: Joi.boolean().optional(), | |
| captchaToken: Joi.string().optional() | |
| }), | |
| // User schemas | |
| updateProfile: Joi.object({ | |
| displayName: Joi.string().min(2).max(50).optional(), | |
| bio: Joi.string().max(500).optional(), | |
| avatar: Joi.string().uri().optional(), | |
| socialLinks: Joi.object({ | |
| twitter: Joi.string().uri().optional(), | |
| github: Joi.string().uri().optional(), | |
| discord: Joi.string().optional() | |
| }).optional() | |
| }), | |
| // Mod/Addon schemas | |
| createMod: Joi.object({ | |
| name: Joi.string().min(3).max(100).required(), | |
| description: Joi.string().min(10).max(5000).required(), | |
| category: Joi.string().valid( | |
| 'adventure', 'survival', 'creative', 'pvp', 'minigames', | |
| 'tools', 'utility', 'decoration', 'mobs', 'blocks', 'items' | |
| ).required(), | |
| version: Joi.string().pattern(/^\d+\.\d+(\.\d+)?$/).required(), | |
| minecraftVersion: Joi.string().required(), | |
| tags: Joi.array().items(Joi.string().max(20)).max(10).optional(), | |
| license: Joi.string().valid('MIT', 'GPL', 'Apache', 'Custom', 'All Rights Reserved').optional() | |
| }), | |
| // Search schema | |
| search: Joi.object({ | |
| q: Joi.string().min(1).max(100).required(), | |
| category: Joi.string().optional(), | |
| sort: Joi.string().valid('relevance', 'downloads', 'rating', 'newest').optional(), | |
| page: Joi.number().integer().min(1).default(1), | |
| limit: Joi.number().integer().min(1).max(50).default(20) | |
| }), | |
| // ID parameter | |
| id: Joi.object({ | |
| id: Joi.string().pattern(/^[a-zA-Z0-9-_]+$/).required() | |
| }) | |
| }; | |
| // Sanitize string input | |
| const sanitizeString = (str) => { | |
| if (typeof str !== 'string') return str; | |
| return validator.escape( | |
| validator.trim(str) | |
| ); | |
| }; | |
| // Sanitize HTML content (allow only safe tags) | |
| const sanitizeHtml = (html) => { | |
| if (typeof html !== 'string') return html; | |
| // Remove all HTML tags for security | |
| // You can use a library like DOMPurify for more advanced sanitization | |
| return html.replace(/<[^>]*>/g, ''); | |
| }; | |
| // Deep sanitize object | |
| const sanitizeObject = (obj, allowHtml = false) => { | |
| if (typeof obj !== 'object' || obj === null) { | |
| return obj; | |
| } | |
| if (Array.isArray(obj)) { | |
| return obj.map(item => sanitizeObject(item, allowHtml)); | |
| } | |
| const sanitized = {}; | |
| for (const [key, value] of Object.entries(obj)) { | |
| if (typeof value === 'string') { | |
| sanitized[key] = allowHtml ? sanitizeHtml(value) : sanitizeString(value); | |
| } else if (typeof value === 'object') { | |
| sanitized[key] = sanitizeObject(value, allowHtml); | |
| } else { | |
| sanitized[key] = value; | |
| } | |
| } | |
| return sanitized; | |
| }; | |
| // Main validation middleware | |
| export const requestValidator = (req, res, next) => { | |
| // Sanitize query parameters | |
| if (req.query) { | |
| req.query = sanitizeObject(req.query); | |
| } | |
| // Sanitize body (no HTML allowed by default) | |
| if (req.body && typeof req.body === 'object') { | |
| req.body = sanitizeObject(req.body); | |
| } | |
| // Sanitize URL parameters | |
| if (req.params) { | |
| req.params = sanitizeObject(req.params); | |
| } | |
| next(); | |
| }; | |
| // Validate request body against schema | |
| export const validateBody = (schemaName) => { | |
| return (req, res, next) => { | |
| const schema = schemas[schemaName]; | |
| if (!schema) { | |
| console.error(`[Validation] Schema not found: ${schemaName}`); | |
| return next(); | |
| } | |
| const { error, value } = schema.validate(req.body, { | |
| abortEarly: false, | |
| stripUnknown: true | |
| }); | |
| if (error) { | |
| const errors = error.details.map(detail => ({ | |
| field: detail.path.join('.'), | |
| message: detail.message | |
| })); | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'Validation failed', | |
| errors | |
| }); | |
| } | |
| // Replace body with validated and sanitized values | |
| req.body = value; | |
| next(); | |
| }; | |
| }; | |
| // Validate query parameters | |
| export const validateQuery = (schemaName) => { | |
| return (req, res, next) => { | |
| const schema = schemas[schemaName]; | |
| if (!schema) { | |
| return next(); | |
| } | |
| const { error, value } = schema.validate(req.query, { | |
| abortEarly: false | |
| }); | |
| if (error) { | |
| const errors = error.details.map(detail => ({ | |
| field: detail.path.join('.'), | |
| message: detail.message | |
| })); | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'Invalid query parameters', | |
| errors | |
| }); | |
| } | |
| req.query = value; | |
| next(); | |
| }; | |
| }; | |
| // Validate URL parameters | |
| export const validateParams = (schemaName) => { | |
| return (req, res, next) => { | |
| const schema = schemas[schemaName]; | |
| if (!schema) { | |
| return next(); | |
| } | |
| const { error, value } = schema.validate(req.params, { | |
| abortEarly: false | |
| }); | |
| if (error) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'Invalid parameters', | |
| errors: error.details | |
| }); | |
| } | |
| req.params = value; | |
| next(); | |
| }; | |
| }; | |
| // File upload validation | |
| export const validateFileUpload = (options = {}) => { | |
| const { | |
| maxSize = 50 * 1024 * 1024, // 50MB | |
| allowedTypes = ['.mcaddon', '.mcpack', '.zip', '.json'], | |
| maxFiles = 1 | |
| } = options; | |
| return (req, res, next) => { | |
| if (!req.files || req.files.length === 0) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'No files uploaded' | |
| }); | |
| } | |
| if (req.files.length > maxFiles) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: `Maximum ${maxFiles} file(s) allowed` | |
| }); | |
| } | |
| for (const file of req.files) { | |
| // Check file size | |
| if (file.size > maxSize) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: `File too large. Maximum size: ${maxSize / 1024 / 1024}MB` | |
| }); | |
| } | |
| // Check file extension | |
| const ext = '.' + file.originalname.split('.').pop().toLowerCase(); | |
| if (!allowedTypes.includes(ext)) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: `Invalid file type. Allowed: ${allowedTypes.join(', ')}` | |
| }); | |
| } | |
| // Check MIME type | |
| const allowedMimeTypes = [ | |
| 'application/zip', | |
| 'application/x-zip-compressed', | |
| 'application/json', | |
| 'application/octet-stream' | |
| ]; | |
| if (!allowedMimeTypes.includes(file.mimetype)) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'Invalid file type' | |
| }); | |
| } | |
| } | |
| next(); | |
| }; | |
| }; | |
| // Custom validation for specific fields | |
| export const validateField = (field, rules) => { | |
| return (req, res, next) => { | |
| const value = req.body[field]; | |
| const errors = []; | |
| for (const rule of rules) { | |
| switch (rule.type) { | |
| case 'required': | |
| if (!value || (typeof value === 'string' && !value.trim())) { | |
| errors.push(rule.message || `${field} is required`); | |
| } | |
| break; | |
| case 'min': | |
| if (value && value.length < rule.value) { | |
| errors.push(rule.message || `${field} must be at least ${rule.value} characters`); | |
| } | |
| break; | |
| case 'max': | |
| if (value && value.length > rule.value) { | |
| errors.push(rule.message || `${field} must be at most ${rule.value} characters`); | |
| } | |
| break; | |
| case 'email': | |
| if (value && !validator.isEmail(value)) { | |
| errors.push(rule.message || 'Invalid email format'); | |
| } | |
| break; | |
| case 'url': | |
| if (value && !validator.isURL(value)) { | |
| errors.push(rule.message || 'Invalid URL format'); | |
| } | |
| break; | |
| case 'alphanumeric': | |
| if (value && !validator.isAlphanumeric(value)) { | |
| errors.push(rule.message || `${field} must be alphanumeric`); | |
| } | |
| break; | |
| case 'regex': | |
| if (value && !rule.pattern.test(value)) { | |
| errors.push(rule.message || `${field} format is invalid`); | |
| } | |
| break; | |
| } | |
| } | |
| if (errors.length > 0) { | |
| return res.status(400).json({ | |
| success: false, | |
| message: 'Validation failed', | |
| errors: errors.map(msg => ({ field, message: msg })) | |
| }); | |
| } | |
| next(); | |
| }; | |
| }; | |
| export default requestValidator; | |