aom aom -4 years ago 92
Javascript Question

Why don't newer versions of node remove __proto__ from request body?

When I send a

PUT
request to my express server,
req.body
sometimes has a
__proto__
property, and other times not.

Using node 0.10.26 and express 3.2.3:


  • When I put
    {"a":"b", "__proto__": {}}
    ,

  • Then
    req.body
    is
    {"a":"b"}



Using node 4.1.0 and express 3.2.3:


  • When I put
    {"a":"b", "__proto__": {}}
    ,

  • Then
    req.body
    is
    {"a":"b", "__proto__": {}}



So newer versions of node do not strip the
__proto__
property. I actually liked this behaviour; now I have to write my own middleware which strips away the property. I think this has something to do with
bodyparser
. The weird thing is, though, that both tests have the same version of
express
(and hence the same version of
bodyparser
).

Can anyone give any motivation as to why this was changed? What is the recommended way of resolving this?

Answer Source

Neither express nor node are responsible for this behavior. This has actually been changed a long time ago in V8, for compatibility and spec conformance.

  • Old behavior (__proto__ is stripped):

    > var x = JSON.parse('{"__proto__":[]}');
    > x.hasOwnProperty('__proto__');
    false
    
  • New behavior (__proto__ is not stripped):

    > var x = JSON.parse('{"__proto__":[]}');
    > x.hasOwnProperty('__proto__');
    true
    

Sources :

Solution:

Like you said, you can write a simple middleware to strip the property yourself:

function stripProto(req, res, next) {
  delete req.body.__proto__;
  next();
}
// ...
app.use(stripProto);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download