Enhance file name validation by allowing objects with toString method

4efed978f048cced3217f18523abdcc9f6e07743

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +10 -1Ignore whitespace
src/middleware/validateFileName.js+10 -1
@@ -1,6 +1,15 @@
1import path from 'node:path';1import path from 'node:path';
22
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 */
8function 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 name14 * @param {string} fieldName Field name
6 * @returns {import('express').RequestHandler} Middleware function15 * @returns {import('express').RequestHandler} Middleware function
@@ -13,7 +22,7 @@ export function getFileNameValidationFunction(fieldName) {
13 * @param {import('express').NextFunction} next Next middleware22 * @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', {