fix(builder): sanitize style-string emission
cssPropsToString() joined raw CSSProperties values into a style="..." attribute with zero escaping, so any component spreading user-controlled values into inline styles (background-image url(), etc.) could break out of the attribute or inject a second declaration -- this is what made BackgroundSection/HeroSimple/CallToAction/Section's bg-image url() sites (flagged in the A3 brief) safe without needing a per-call- site fix, since they already route through this helper. Each string value is now sanitized: url(...) contents are validated through safeUrl and re-wrapped escaped, stray `;` (the only way to inject a second live declaration) is stripped, and any raw `"` is entity-encoded so it can't terminate the attribute early. Legitimate multi-part values (box-shadow, gradients) that contain none of these characters pass through byte-identical. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,13 +1,36 @@
|
||||
import { CSSProperties } from 'react';
|
||||
import { escapeAttr, safeUrl } from './escape';
|
||||
|
||||
const camelToKebab = (str: string): string =>
|
||||
str.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
|
||||
|
||||
const URL_RE = /url\(\s*(['"]?)([\s\S]*?)\1\s*\)/gi;
|
||||
|
||||
/**
|
||||
* Sanitizes a single CSS declaration value so it can never terminate the
|
||||
* `style="..."` attribute early, inject an extra declaration via a stray
|
||||
* `;`, or smuggle a `javascript:`/`vbscript:`/`data:text/html` URL through
|
||||
* a `url(...)` reference. Legitimate multi-part values (box-shadow,
|
||||
* gradients, etc.) that contain none of these characters pass through
|
||||
* unchanged.
|
||||
*/
|
||||
function sanitizeCssValue(raw: string): string {
|
||||
// Neutralize url(...) references: validate/strip the scheme and re-wrap
|
||||
// in single quotes with the contents escaped for attribute safety.
|
||||
let val = raw.replace(URL_RE, (_m, _q, inner) => `url('${escapeAttr(safeUrl(inner.trim()))}')`);
|
||||
// A `;` in a CSS value is never legitimate (declarations are separated by
|
||||
// it) -- stray semicolons are how a breakout injects a second property.
|
||||
val = val.replace(/;/g, '');
|
||||
// Any remaining raw `"` would close the `style="..."` attribute early.
|
||||
val = val.replace(/"/g, '"');
|
||||
return val;
|
||||
}
|
||||
|
||||
export function cssPropsToString(style: CSSProperties | undefined): string {
|
||||
if (!style) return '';
|
||||
return Object.entries(style)
|
||||
.filter(([, v]) => v !== undefined && v !== null && v !== '')
|
||||
.map(([k, v]) => `${camelToKebab(k)}:${v}`)
|
||||
.map(([k, v]) => `${camelToKebab(k)}:${typeof v === 'string' ? sanitizeCssValue(v) : v}`)
|
||||
.join(';');
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user