2

I want to set the depth of JSON parsing in Express middleware express.json().

For example, if I would set the option to parse the depth=1, then

'{ "email": { "$ne": "[email protected]" } }'

will be parsed to

{ email: "[object Object]" }

-- or --

When I set depth=2, then

'{ "email": { "$ne": "[email protected]" } }'

will be parsed to

{ email: { '$ne': '[email protected]' } }

And so on,

In this case, there will be no issue of default depth, as the developer will be aware of how many nesting they will allow while development.

PS: It will prevent the application from being vulnerable to NoSQL Injection.

3 Answers 3

1
+50

Just write you own middleware:

const get_depth = (obj) => {
    let depth = 0
    for(const key in obj) {
        if( obj[key] instanceof Object ) {
          depth = Math.max(get_depth(obj[key]), depth)
        }
    }
    return depth+1
}
const depth_limit = 2
const limit_depth = function(req, res, next) {
    if( get_depth(req.body) > depth_limit ) throw new Error("Possible NoSQL Injection")
    next()
}

app.use(limit_depth)

Or, if you prefer "[object Object]":

let limit_depth = (obj, current_depth, limit) => {
    for(const key in obj) {
        if( obj[key] instanceof Object ) {
          if( current_depth+1 === limit ) {
            obj[key] = "[object Object]" // or something similar
          }
          else limit_depth(obj[key], current_depth+1, limit)
        }
    }
}
app.use(function(req, res, next) { limit_depth(req.body, 0, depth_limit); next() })
2
  • Can I use it to create my own middleware?
    – tbhaxor
    Apr 20, 2020 at 21:09
  • limit_depth as it is is a complete middleware.
    – x00
    Apr 21, 2020 at 0:59
0

I write down the query, Maximum 6-8 depth goes. when use lookup inside the lookup.

  const [result] = await Collection.aggregate([
    { $match:statusObj },
     {
         $project:{
             _id:1,
             name:1
             }
     },
     {
      $lookup:{
           from:"articles",
            let: { "cat_id":"$_id"},
            pipeline:[
             {
                $match:{
                     $expr:{
                  $and: [
                         { $eq: ["$category_id", "$$cat_id"] }, 
                         { $eq: ["$isDeleted", false] },
                         { $eq: ["$type", type] }
                         ]
                     }

                    } 
                 },
                  {
      $lookup:{
           from:"view_articles",
            let: { "article_id":"$_id"},
            pipeline:[
             {
                $match:{
                     $expr:{
                  $and: [
                         { $eq: ["$article_id", "$$article_id"] }, 
                         { $eq: ["$isDeleted", false] }
                         ]
                     }

                    } 
                 }
                 ],
                 as:"viewCount"
          }    
    },
    {
      $addFields:{
          noOfViewCount : { $size:"$viewCount"}
          }   
      }          ],
                 as:"articleCategoryData"
          }    
    },
     {
      $addFields: {
      postCount: {$size:"$articleCategoryData"   },
      tempsArray: { $map:
        {
           input: "$articleCategoryData",
           as: "tempData",
           in: { $add: "$$tempData.noOfViewCount" }
        }
     },
                 },
      },
      {
        $addFields: {
          viewCount:{ $sum:"$tempsArray" }
              },
        },
        {
          $project:{
            _id: 1,
            name: 1,
            postCount: 1,
            viewCount: 1
              }
      },
      {
        $facet: {
          count: [
            {
              $count: "total"
            }
          ],
          result: [{ $match: {} }, { $skip: skipRecord }, { $limit: limit }]
        }
      }
]);

you can set depth to 10. If you feel JSON is coming wrong then increase it :)

2
  • This is part of MongoDB. The ques is regarding express js. Or in more depth body parser library by express. Read the ques once again.
    – tbhaxor
    Apr 20, 2020 at 15:55
  • Thanks got it and besides it help me in payload the limit. only specific depth of JSON receive in payload.
    – Nits
    Apr 21, 2020 at 8:43
0

In case anyone who doesn't want to change the value of req.body, can use this function from here

function serializer(payload: any, cdepth: number, options: Options): void {
  const main: any = {}
  const maxDepth = typeof options.maxNestingLevel == 'number' ? (options.maxNestingLevel == 0 ? 1 : options.maxNestingLevel) : 1

  for (const key in payload) {
    // check for object
    if (payload[key] instanceof Object) {
      // check if depth is limited, replace if needed
      if (cdepth === maxDepth) {
        main[key] = options.replaceWith
      } else {
        // serialize the nested
        main[key] = serializer(payload[key], cdepth + 1, options)
      }
    } else {
      // add to main object if not to be checked
      main[key] = payload[key]
    }
  }
  return main
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.