Enhance file name validation by allowing objects with toString method
| @@ -1,6 +1,15 @@ | |||
| 1 | import path from 'node:path'; | 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 | * Gets a middleware function that validates the field in the request body. | 13 | * Gets a middleware function that validates the field in the request body. |
| 5 | * @param {string} fieldName Field name | 14 | * @param {string} fieldName Field name |
| 6 | * @returns {import('express').RequestHandler} Middleware function | 15 | * @returns {import('express').RequestHandler} Middleware function |
| @@ -13,7 +22,7 @@ export function getFileNameValidationFunction(fieldName) { | |||
| 13 | * @param {import('express').NextFunction} next Next middleware | 22 | * @param {import('express').NextFunction} next Next middleware |
| 14 | */ | 23 | */ |
| 15 | return function validateAvatarUrlMiddleware(req, res, next) { | 24 | return function validateAvatarUrlMiddleware(req, res, next) { |
| 16 | if (req.body && fieldName in req.body && typeof req.body[fieldName] === 'string') { | 25 | if (req.body && fieldName in req.body && (typeof req.body[fieldName] === 'string' || hasToString(req.body[fieldName]))) { |
| 17 | const forbiddenRegExp = path.sep === '/' ? /[/\x00]/ : /[/\x00\\]/; | 26 | const forbiddenRegExp = path.sep === '/' ? /[/\x00]/ : /[/\x00\\]/; |
| 18 | if (forbiddenRegExp.test(req.body[fieldName])) { | 27 | if (forbiddenRegExp.test(req.body[fieldName])) { |
| 19 | console.error('An error occurred while validating the request body', { | 28 | console.error('An error occurred while validating the request body', { |