javascript / expert
Snippet
Trusted Types Policy Encapsulation for Safe Svelte Context Injection
This pattern leverages W3C Trusted Types within a Svelte context module to systematically prevent DOM-based XSS vulnerabilities. By registering a Symbol-keyed context provider, components can safely request HTML sanitization functions without risking global scope pollution or direct innerHTML injection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { setContext, getContext } from 'svelte';const SECURITY_KEY = Symbol('SAFE_HTML_POLICY');export function createSecureHTMLContext() {const policy = window.trustedTypes?.createPolicy('svelte-safe-html', {createHTML: (string) => string.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')});const sanitize = (rawHTML) => policy ? policy.createHTML(rawHTML) : rawHTML;setContext(SECURITY_KEY, { sanitize });}export function useSecureHTML() {const ctx = getContext(SECURITY_KEY);if (!ctx) throw new Error('Secure HTML context missing');return ctx.sanitize;}
svelte
Breakdown
1
const SECURITY_KEY = Symbol('SAFE_HTML_POLICY');
Creates a unique, non-colliding Symbol key for referencing the secure context in Svelte.
2
const policy = window.trustedTypes?.createPolicy('svelte-safe-html', {
Defines a browser Trusted Types policy if supported by the runtime user agent.
3
createHTML: (string) => string.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
Sanitizes incoming strings by stripping executable script tags before DOM insertion.
4
setContext(SECURITY_KEY, { sanitize });
Binds the sanitization utility to the Svelte component tree context.
5
const ctx = getContext(SECURITY_KEY);
Retrieves the encapsulated security policy from the current component parent context.