javascript / expert
Snippet
Absicherung von Svelte-Konfigurationsdaten mit Null-Prototyp-Objekten und Unveränderlichen Symbolen
Dieses Beispiel zeigt, wie Prototypen-Pollution und unbefugte Mutationen in Svelte-Stores verhindert werden, indem Objekte ohne Prototyp erstellt, mit Object.freeze geschützt und durch nicht exportierte Symbol-Schlüssel abgesichert werden.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { writable } from 'svelte/store';const SECRET_KEY = Symbol('config.auth.key');export function createSecureConfigStore(rawConfig) {const sanitizedConfig = Object.assign(Object.create(null), rawConfig);sanitizedConfig[SECRET_KEY] = crypto.randomUUID();const { subscribe, set } = writable(Object.freeze(sanitizedConfig));return {subscribe,updateKey: (accessSymbol, newConfig) => {if (accessSymbol !== SECRET_KEY) throw new Error('Unauthorized');const updated = Object.assign(Object.create(null), newConfig);updated[SECRET_KEY] = sanitizedConfig[SECRET_KEY];set(Object.freeze(updated));}};}
svelte
Erklärung
1
const SECRET_KEY = Symbol('config.auth.key');
Erstellt eine unschätzbare eindeutige Symbol-Kennung, die als Zugriffstoken dient.
2
const sanitizedConfig = Object.assign(Object.create(null), rawConfig);
Erstellt ein neues Wörterbuch ohne Prototypvererbung, was Prototype-Pollution-Schwachstellen verhindert.
3
const { subscribe, set } = writable(Object.freeze(sanitizedConfig));
Kapselt das unveränderliche, eingefrorene Objekt in einer schreibgeschützten Svelte-Store-Schnittstelle.