javascript / expert
Snippet
Bereinigung von Prototyp-Pollution mittels Object.create(null) in React-State-Reducern
Beim Anwenden dynamischer Payload-Updates auf den Zustand in React-Reducern aus externen APIs oder Benutzereingaben können bösartige Schlüssel wie __proto__ das Object.prototype verseuchen. Die Verwendung von Null-Prototyp-Objekten via Object.create(null) in Kombination mit Reflect.ownKeys-Filterung garantiert die Integrität der Prototypen-Kette ohne geerbte Objekteigenschaften.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React, { useReducer } from 'react';const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);function safeStateReducer(state, action) {if (action.type === 'PATCH_UNTRUSTED') {const safePatch = Object.create(null);for (const key of Reflect.ownKeys(action.payload)) {if (typeof key === 'string' && DANGEROUS_KEYS.has(key)) continue;Object.defineProperty(safePatch, key, {value: action.payload[key],writable: true,enumerable: true,configurable: true});}return Object.assign(Object.create(null), state, safePatch);}return state;}
react
Erklärung
1
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
Erstellt ein Set mit konstanter Nachschlagezeit, das typische Vektoren für Prototype-Pollution-Angriffe enthält.
2
const safePatch = Object.create(null);
Erzeugt ein reine Wörterbuch-Objekt ohne Prototypenkette, um Delegationen bei Eigenschaftsabfragen zu verhindern.
3
for (const key of Reflect.ownKeys(action.payload)) {
Iteriert über alle eigenen Eigenschaftsschlüssel einschließlich nicht-aufzählsbarer Eigenschaften und Symbole.
4
if (typeof key === 'string' && DANGEROUS_KEYS.has(key)) continue;
Überspringt die Zuweisung, wenn der Eigenschaftsschlüssel einer bekannten Prototype-Pollution-Zeichenkette entspricht.
5
return Object.assign(Object.create(null), state, safePatch);
Führt bereinigte Eigenschaften in einem neuen Null-Prototyp-Zustandsobjekt zusammen, um den State von Object.prototype zu entkoppeln.