import { Request, Response, NextFunction } from 'express'; import { AnyZodObject, ZodError } from 'zod'; import xss from 'xss'; /** * Validates request body, query, or params against a Zod schema. * Automatically sanitizes strings in `req.body` using the `xss` library before validation. */ export const validateRequest = (schema: AnyZodObject) => { return async (req: Request, res: Response, next: NextFunction) => { try { // Traverse and sanitize string fields in req.body if (req.body && typeof req.body === 'object') { for (const key of Object.keys(req.body)) { if (typeof req.body[key] === 'string') { req.body[key] = xss(req.body[key], { whiteList: {}, // completely strip all HTML tags stripIgnoreTag: true, stripIgnoreTagBody: ['script'] // ensures inner content of