javascript / expert
Snippet
Defense-in-Depth Deserialization Guard for Untrusted JSON Payloads
Safely parses raw JSON payloads by neutralizing prototype pollution vectors during revocation in the JSON parser reviver function. It then attaches properties onto a prototype-less object via Object.create(null) and deeply freezes it to ensure immutable, tamper-resistant React state.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useState, useCallback } from 'react';function sanitizePayload(rawJson) {const parsed = JSON.parse(rawJson, (key, value) => {if (key === '__proto__' || key === 'constructor') return undefined;return value;});return Object.freeze(Object.assign(Object.create(null), parsed));}export function useSecurePayloadState(initialJson) {const [state, setState] = useState(() => sanitizePayload(initialJson));const updatePayload = useCallback((newJson) => {setState(sanitizePayload(newJson));}, []);return [state, updatePayload];}
react
Breakdown
1
const parsed = JSON.parse(rawJson, (key, value) => {
Uses the reviver parameter of JSON.parse to inspect every key-value pair during parsing.
2
if (key === '__proto__' || key === 'constructor') return undefined;
Filters out Object prototype pollution attributes before object instantiation.
3
return Object.freeze(Object.assign(Object.create(null), parsed));
Creates a prototype-less dictionary and recursively freezes the object structure.