javascript / expert
Snippet
Hardened DTO Parsing via Null Prototypes and Prototype Pollution Protection
In Node.js applications receiving untrusted dynamic inputs, standard dynamic property assignments can expose applications to Prototype Pollution attacks. Using Object.create(null) creates a prototype-less target object, preventing inheritance chain tampering. Combined with Reflect.ownKeys to catch Symbol properties and explicit key filtering, this technique creates immutable, hardened data transfer objects.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
function safeObjectAssign(target, source) {const safeTarget = target ?? Object.create(null);for (const key of Reflect.ownKeys(source)) {if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;const desc = Object.getOwnPropertyDescriptor(source, key);if (desc) Object.defineProperty(safeTarget, key, desc);}return Object.freeze(safeTarget);}
nodejs
Breakdown
1
const safeTarget = target ?? Object.create(null);
Ensures the destination object has a null prototype to isolate it from Object.prototype.
2
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
Guards against prototype pollution vectors by ignoring dangerous property keys.
3
return Object.freeze(safeTarget);
Prevents subsequent property additions, deletions, or mutations on the result object.