|
| 1 | +import type { NextFunction, Request, Response } from 'express'; |
| 2 | + |
| 3 | +/** Remove all NUL characters from a string. */ |
| 4 | +export function stripNullsFromString(input: string): string { |
| 5 | + // Fast path: avoid allocation when there's nothing to replace |
| 6 | + return input.indexOf('\u0000') === -1 ? input : input.replace(/[\x00]/g, ''); |
| 7 | +} |
| 8 | + |
| 9 | +function isPlainObject(value: unknown): value is Record<string, unknown> { |
| 10 | + return typeof value === 'object' && value !== null && !Array.isArray(value); |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * @function sanitizeDeep |
| 15 | + * Recursively sanitize JSON-like data (strings, arrays, plain objects). |
| 16 | + * @param value - The value to sanitize. |
| 17 | + * @returns The sanitized value. |
| 18 | + */ |
| 19 | +function sanitizeDeep(value: unknown): unknown { |
| 20 | + // Strip NUL characters from strings |
| 21 | + if (typeof value === 'string') return stripNullsFromString(value); |
| 22 | + |
| 23 | + // Recursively sanitize arrays items |
| 24 | + if (Array.isArray(value)) return value.map(sanitizeDeep); |
| 25 | + |
| 26 | + // Recursively sanitize plain objects |
| 27 | + if (typeof value === 'object' && value !== null) { |
| 28 | + const out: Record<string, unknown> = {}; |
| 29 | + for (const [k, v] of Object.entries(value)) out[k] = sanitizeDeep(v); |
| 30 | + return out; |
| 31 | + } |
| 32 | + return value; |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * @function requestSanitizer |
| 37 | + * @description Express middleware to sanitize incoming request bodies. |
| 38 | + * @param req - The Express request object. |
| 39 | + * @param _res - The Express response object. |
| 40 | + * @param next - The next middleware function. |
| 41 | + */ |
| 42 | +export function requestSanitizer(req: Request, _res: Response, next: NextFunction): void { |
| 43 | + if (typeof req.body !== 'undefined') { |
| 44 | + req.body = sanitizeDeep(req.body) as typeof req.body; |
| 45 | + } |
| 46 | + next(); |
| 47 | +} |
0 commit comments