Prevent prototype pollution when merging objects
Merge objects without letting __proto__, constructor or prototype keys through, so user JSON cannot change Object.prototype for the whole process.
A recursive merge that copies keys blindly will follow a __proto__ key from user JSON into Object.prototype, and every object in the process then inherits the attacker's values.
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
target[key] = safeMerge(Object.hasOwn(target, key) ? target[key] : {}, source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const payload = JSON.parse('{"__proto__":{"isAdmin":true},"name":"ana"}');
const result = safeMerge({}, payload);
console.log(result.name, ({}).isAdmin);ana undefinedJSON.parse creates __proto__ as an ordinary own key, which is why Object.keys sees it and a naive target[key] = ... then writes through the setter. Skipping the three keys and using Object.hasOwn instead of in stops the walk before it reaches the prototype. See the MDN note on prototype pollution.
Skip-lists are easy to get wrong in a deeper path. Where you can, merge into Object.create(null) or a Map, or copy only the keys you declared.