javascript / expert
Snippet
Defensive Object Recursion against Prototype Poisoning in React State Hydration
When hydrating React client state from unverified external JSON payloads, attackers can exploit prototype poisoning vectors via '__proto__' or 'constructor'. By recursively constructing null-prototype objects with Object.create(null) and stripping hazardous keys, this routine ensures input objects cannot corrupt Object.prototype before state entry.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function sanitizeHydratedState(target) {if (target === null || typeof target !== 'object') return target;const safeObj = Object.create(null);for (const key of Object.keys(target)) {if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;const value = target[key];safeObj[key] = typeof value === 'object' && value !== null ? sanitizeHydratedState(value) : value;}return Object.freeze(safeObj);}
react
Breakdown
1
const safeObj = Object.create(null);
Instantiates a dictionary with no prototype inheritance chain to prevent prototype property resolution.
2
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
Filters out prototype manipulation keys that could contaminate global Object properties.
3
return Object.freeze(safeObj);
Locks down the sanitized object tree to guarantee immutability across React render cycles.