javascript / expert
Snippet
Preventing Prototype Pollution Attacks in Dynamic JSON Deserialization
Prevents prototype pollution vulnerabilities during JSON parsing in Svelte data pipelines by rejecting dangerous property keys and stripping prototype inheritance chain via Object.setPrototypeOf.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function safeReviver(key, value) {if (key === '__proto__' || key === 'constructor' || key === 'prototype') {throw new TypeError(`Forbidden property key detected during parsing: ${key}`);}return Object.freeze(value && typeof value === 'object' ? Object.setPrototypeOf(value, null) : value);}export function parseSveltePayload(jsonString) {try {return JSON.parse(jsonString, safeReviver);} catch (err) {console.error('Payload validation failure:', err.message);return Object.create(null);}}
svelte
Breakdown
1
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
Detects malicious property keys that attempt to mutate the global Object prototype.
2
throw new TypeError(`Forbidden property key detected during parsing: ${key}`);
Aborts parsing immediately upon encountering suspicious structure injections.
3
return Object.freeze(value && typeof value === 'object' ? Object.setPrototypeOf(value, null) : value);
Removes inherited prototype methods and immutably freezes constructed data payload objects.
4
return Object.create(null);
Returns a pure fallback object without standard prototype properties on caught validation failure.