javascript / expert
Snippet
Shielding Svelte Configuration Payloads with Null-Prototype Objects and Immutable Symbols
This snippet demonstrates how to prevent prototype pollution and unauthorized mutation in Svelte stores by creating null-prototype objects sealed with Object.freeze and guarded by unexported Symbol keys.
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
Breakdown
1
const SECRET_KEY = Symbol('config.auth.key');
Creates an un-forgeable unique Symbol identifier used as an access control token.
2
const sanitizedConfig = Object.assign(Object.create(null), rawConfig);
Constructs a fresh dictionary with no prototype inheritance, mitigating prototype pollution vulnerabilities.
3
const { subscribe, set } = writable(Object.freeze(sanitizedConfig));
Wraps the immutable, frozen dictionary in a read-only Svelte store interface.