File size: 1,826 Bytes
d53e5b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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 <script> is ripped out
                        });
                    }
                }
            }

            // Validate against Zod Schema
            await schema.parseAsync({
                body: req.body,
                query: req.query,
                params: req.params,
            });

            return next();
        } catch (error) {
            if (error instanceof ZodError) {
                return res.status(400).json({
                    error: 'Validation failed',
                    details: error.errors.map(err => ({
                        path: err.path.join('.'),
                        message: err.message
                    }))
                });
            }
            return res.status(500).json({ error: 'Internal server error during validation' });
        }
    };
};