security: add safeImageUrl, un-break M-5's over-blocking of image-context SVG data URIs

M-5 made safeUrl() block data:image/svg+xml everywhere, including the
image-only sinks (<img src>, CSS url()) that Gallery's default images and
other SVG placeholders rely on. Loaded as an image, an SVG is rasterized
and never executes an inline <script>/onload= -- that only happens when
it's navigated to or loaded as an <iframe> document -- so M-5 over-blocked
the safe contexts and broke every published Gallery (and other components
using an SVG placeholder) using safeUrl's default images in prod.

Adds safeImageUrl(): identical javascript:/vbscript: handling to safeUrl,
but treats data: as an allowlist of image/* subtypes instead of a
blocklist -- allows all data:image/* (including svg+xml, with or without
base64), still blocks data:text/html and any other non-image data: type.

Swapped to safeImageUrl at IMAGE-src / CSS-image url() sinks only:
- Gallery.tsx img src + lightbox data-lb-src
- ImageBlock.tsx img src (toHtml)
- Logo.tsx / Navbar.tsx logo <img> src (their href/link targets keep safeUrl)
- style-helpers.ts sanitizeCssValue's url(...) handling (background-image
  for HeroSimple/BackgroundSection/Section/CallToAction)

Left on safeUrl (href/iframe/form-action/navigation sinks, where
data:image/svg+xml must stay blocked): ButtonLink, Icon link, SocialLinks,
Menu/Navbar link hrefs, PricingTable buttonHref, _cta-helpers,
ContentSlider buttonHref, FeaturesGrid buttonUrl, FormContainer action
(via form-relay-wiring), MapEmbed/VideoBlock iframe src.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 19:45:58 -07:00
parent 802938ec1a
commit 3f3c6fb851
8 changed files with 156 additions and 26 deletions
+59 -1
View File
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest';
import { escapeHtml, escapeAttr, safeUrl, stableHash, scopeId, sanitizeFormMethod, sanitizeInputType } from './escape';
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, stableHash, scopeId, sanitizeFormMethod, sanitizeInputType } from './escape';
describe('escapeHtml', () => {
test('escapes &, <, >, "', () => {
@@ -112,6 +112,64 @@ describe('safeUrl', () => {
});
});
describe('safeImageUrl (Bug 2: image-context sink -- data:image/svg+xml is safe as an <img>/CSS url() target)', () => {
test('allows data:image/svg+xml (a raw, non-base64 SVG data URI, as Gallery/ImageBlock placeholders use)', () => {
const s = 'data:image/svg+xml,<svg/>';
expect(safeImageUrl(s)).toBe(s);
});
test('allows data:image/svg+xml;base64 variant', () => {
const s = 'data:image/svg+xml;base64,PHN2Zy8+';
expect(safeImageUrl(s)).toBe(s);
});
test('allows other data:image/* types unchanged', () => {
expect(safeImageUrl('data:image/png;base64,x')).toBe('data:image/png;base64,x');
expect(safeImageUrl('data:image/jpeg;base64,x')).toBe('data:image/jpeg;base64,x');
expect(safeImageUrl('data:image/webp;base64,x')).toBe('data:image/webp;base64,x');
expect(safeImageUrl('data:image/gif;base64,x')).toBe('data:image/gif;base64,x');
});
test('still blocks javascript: scheme', () => {
expect(safeImageUrl('javascript:alert(1)')).toBe('');
});
test('still blocks vbscript: scheme', () => {
expect(safeImageUrl('vbscript:msgbox(1)')).toBe('');
});
test('still blocks data:text/html', () => {
expect(safeImageUrl('data:text/html,x')).toBe('');
});
test('still blocks non-image data: types generally (e.g. data:application/...)', () => {
expect(safeImageUrl('data:application/javascript,alert(1)')).toBe('');
});
test('blocks obfuscated (whitespace/case) javascript: scheme, same as safeUrl', () => {
expect(safeImageUrl(' JavaScript:alert(1)')).toBe('');
expect(safeImageUrl('java\tscript:alert(1)')).toBe('');
expect(safeImageUrl('&#106;avascript:alert(1)')).toBe('');
});
test('allows ordinary http(s)/relative urls unchanged, same as safeUrl', () => {
expect(safeImageUrl('https://example.com/photo.jpg')).toBe('https://example.com/photo.jpg');
expect(safeImageUrl('/assets/photo.jpg')).toBe('/assets/photo.jpg');
expect(safeImageUrl('')).toBe('');
});
test('coerces non-string to empty string', () => {
expect(safeImageUrl(null as any)).toBe('');
expect(safeImageUrl(undefined as any)).toBe('');
});
});
describe('safeUrl still blocks data:image/svg+xml (href/iframe/navigation context unchanged by safeImageUrl addition)', () => {
test('safeUrl(data:image/svg+xml,...) is still blocked', () => {
expect(safeUrl('data:image/svg+xml,<svg onload=alert(1)>')).toBe('');
});
});
describe('stableHash', () => {
test('same input always produces the same output', () => {
expect(stableHash('hello')).toBe(stableHash('hello'));
+56 -14
View File
@@ -64,20 +64,7 @@ export function safeUrl(s: string): string {
const trimmed = s.trim();
if (trimmed === '') return '';
// Build a normalized copy for scheme detection only: decode numeric HTML
// entities (catches e.g. &#106; -> 'j'), strip whitespace/control chars,
// and lowercase.
const normalized = decodeNumericEntities(trimmed)
.replace(/[\x00-\x20]+/g, '')
.toLowerCase();
// Strip any colons before matching the scheme prefix. This defeats
// obfuscation that splices extra colons into the scheme name itself
// (e.g. decoding &#58; mid-word produces "java:script:alert(1)", which
// would otherwise dodge a literal "^javascript:" check) while still
// reliably catching the real "javascript:"/"vbscript:"/"data:text/html"
// prefixes once their own colon is removed.
const collapsed = normalized.replace(/:/g, '');
const collapsed = normalizeForSchemeCheck(trimmed);
if (DANGEROUS_SCHEME_PREFIXES.some((prefix) => collapsed.startsWith(prefix))) {
return '';
@@ -86,6 +73,61 @@ export function safeUrl(s: string): string {
return trimmed;
}
/**
* Image-context variant of `safeUrl` for IMAGE sinks only (`<img src>`, CSS
* `url(...)` backgrounds). `data:image/svg+xml` is safe here -- loaded as an
* image, an SVG is rasterized and never executes an inline <script>/onload=
* the way it would as a navigation/iframe document -- so, unlike `safeUrl`,
* this ALLOWS every `data:image/*` subtype (svg+xml, png, jpeg, gif, webp,
* ..., with or without `;base64`).
*
* Still blocks `javascript:` / `vbscript:` (same obfuscation-resistant
* normalization as `safeUrl`), and -- because this is an image sink, not a
* general-purpose URL sink -- treats `data:` as an ALLOWLIST rather than a
* blocklist: any `data:` URI whose type is NOT `image/*` (`data:text/html`,
* `data:application/javascript`, `data:text/javascript`, etc.) is blocked
* too, since none of those are legitimate image sources.
*
* Do NOT use this for href/iframe/form-action/navigation sinks -- keep
* those on `safeUrl`, which still blocks `data:image/svg+xml`.
*/
export function safeImageUrl(s: unknown): string {
if (typeof s !== 'string') return '';
const trimmed = s.trim();
if (trimmed === '') return '';
const collapsed = normalizeForSchemeCheck(trimmed);
if (collapsed.startsWith('javascript') || collapsed.startsWith('vbscript')) {
return '';
}
if (collapsed.startsWith('data') && !collapsed.startsWith('dataimage')) {
// A data: URI whose MIME type isn't image/* -- e.g. data:text/html,
// data:application/javascript, data:text/javascript. No legitimate
// image source needs these; block unconditionally.
return '';
}
return trimmed;
}
// Normalizes a trimmed URL string for scheme-prefix matching only: decodes
// numeric HTML entities (catches e.g. &#106; -> 'j'), strips whitespace /
// control chars, lowercases, then strips every colon. Stripping colons
// defeats obfuscation that splices extra colons into the scheme name itself
// (e.g. decoding &#58; mid-word produces "java:script:alert(1)", which would
// otherwise dodge a literal "^javascript:" check) while still reliably
// catching the real "javascript:"/"vbscript:"/"data:..." prefixes once their
// own colon is removed. Used for prefix `.startsWith()` checks only -- the
// original (non-collapsed) string is always what gets returned/emitted.
function normalizeForSchemeCheck(trimmed: string): string {
return decodeNumericEntities(trimmed)
.replace(/[\x00-\x20]+/g, '')
.toLowerCase()
.replace(/:/g, '');
}
/**
* Neutralizes CSS-context breakout for a single design-token value (color,
* length, gradient, etc.) so it is safe to interpolate RAW into either CSS
+6 -2
View File
@@ -1,5 +1,5 @@
import { CSSProperties } from 'react';
import { escapeAttr, safeUrl } from './escape';
import { escapeAttr, safeImageUrl } from './escape';
const camelToKebab = (str: string): string =>
str.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
@@ -41,8 +41,12 @@ function sanitizeCssValue(raw: string): string {
// Neutralize the url(...) reference: validate/strip the scheme and
// re-wrap in single quotes with the contents escaped for attribute
// safety. This is already fully safe, `;` and all.
// Image-context sink (background/mask/border-image url()): use
// safeImageUrl, not safeUrl -- a data:image/svg+xml background is safe
// (rasterized, never executed as a document) and must survive here, the
// same way it must survive on an <img src>.
const inner = m[2];
out += `url('${escapeAttr(safeUrl(inner.trim()))}')`;
out += `url('${escapeAttr(safeImageUrl(inner.trim()))}')`;
lastIndex = URL_RE.lastIndex;
}
out += sanitizeBreakoutChars(raw.slice(lastIndex));