When generating CSS from external data (JSON, user input, theme files), validate and sanitize both CSS property names and values before injecting them into style elements to prevent style-breaking input and XSS/style injection.

Motivation: Building CSS via string concatenation (e.g. --term-${key}: ${value};) can allow malicious or malformed keys/values to break the stylesheet or inject content. Use browser APIs and input validation to make this safe.

How to apply:

Example (adapted from the discussion):

// unsafe: --term-${key}: ${value}; // safer approach: function isValidKey(key) { // allow lowercase letters, numbers, and hyphens (adjust to your naming rules) return /^[a-z0-9-]+$/.test(key); }

function isValidValue(value) { if (typeof value !== ‘string’ || value.length > 200) return false; // disallow characters that can close or break CSS rules return !/[;{}<>]/.test(value); }

async function applyTheme(themeJson, styleEl) { for (const [key, value] of Object.entries(themeJson)) { if (!isValidKey(key) || !isValidValue(String(value))) continue; // reject invalid entries

// use CSS custom property API which avoids injecting raw CSS text
// ensure the property name is valid per your rules
styleEl.style.setProperty(`--term-${CSS.escape(key)}`, String(value));   } }

Notes:

References: [0]