typescript / intermediate
Snippet
Hardening Object Dictionaries Against Prototype Pollution Attacks
Objects created with Object.create(null) lack prototype inheritance properties like __proto__ or toString. Freezing them provides an immutable dictionary resistant to prototype pollution vulnerabilities.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
type SafeDictionary<T> = Record<string, T>;function createSafeLookup<T>(): SafeDictionary<T> {return Object.freeze(Object.create(null));}const lookup = Object.assign(Object.create(null), {allowedKey: 'value'}) as Record<string, string>;const keyToTest = '__proto__';console.log(keyToTest in lookup);
Breakdown
1
function createSafeLookup<T>(): SafeDictionary<T> {
Defines a generic factory for producing prototype-less dictionary structures.
2
return Object.freeze(Object.create(null));
Creates an object with no prototype fallback chain and freezes it against structural modifications.
3
console.log(keyToTest in lookup);
Evaluates false because prototype properties do not exist on null-prototype objects.