import { Request, Response, NextFunction } from "express"; import { z } from "zod"; /** * Request validation middleware using Zod */ export const validate = (schema: z.ZodSchema) => { return (req: Request, res: Response, next: NextFunction) => { try { schema.parse(req.body); next(); } catch (error) { if (error instanceof z.ZodError) { return res.status(400).json({ error: "Validation failed", errors: error.errors, }); } next(error); } }; }; /** * Sanitize input to prevent XSS */ export const sanitizeInput = (req: Request, res: Response, next: NextFunction) => { const sanitize = (obj: any): any => { if (typeof obj === "string") { // Remove potentially dangerous characters return obj .replace(/)<[^<]*)*<\/script>/gi, "") .replace(/javascript:/gi, "") .replace(/on\w+\s*=/gi, ""); } if (Array.isArray(obj)) { return obj.map(sanitize); } if (obj && typeof obj === "object") { const sanitized: any = {}; for (const key in obj) { sanitized[key] = sanitize(obj[key]); } return sanitized; } return obj; }; if (req.body) { req.body = sanitize(req.body); } if (req.query) { req.query = sanitize(req.query); } next(); };