Enhance file name validation by allowing objects with toString method
| @@ -1,6 +1,15 @@ | ||
| 1 | 1 | import path from 'node:path'; |
| 2 | 2 | |
| 3 | 3 | /** |
| 4 | + * Checks if an object has a toString method. | |
| 5 | + * @param {object} o Object to check | |
| 6 | + * @returns {boolean} True if the object has a toString method, false otherwise | |
| 7 | + */ | |
| 8 | +function hasToString(o) { | |
| 9 | + return o != null && typeof o.toString === 'function'; | |
| 10 | +} | |
| 11 | + | |
| 12 | +/** | |
| 4 | 13 | * Gets a middleware function that validates the field in the request body. |
| 5 | 14 | * @param {string} fieldName Field name |
| 6 | 15 | * @returns {import('express').RequestHandler} Middleware function |
| @@ -13,7 +22,7 @@ export function getFileNameValidationFunction(fieldName) { | ||
| 13 | 22 | * @param {import('express').NextFunction} next Next middleware |
| 14 | 23 | */ |
| 15 | 24 | return function validateAvatarUrlMiddleware(req, res, next) { |
| 16 | 25 | if (req.body && fieldName in req.body && (typeof req.body[fieldName] === 'string' || hasToString(req.body[fieldName]))) { |
| 17 | 26 | const forbiddenRegExp = path.sep === '/' ? /[/\x00]/ : /[/\x00\\]/; |
| 18 | 27 | if (forbiddenRegExp.test(req.body[fieldName])) { |
| 19 | 28 | console.error('An error occurred while validating the request body', { |