Skip to content

Commit d49e7b9

Browse files
SauceXStudiosImad Phelpsclaudemiguel-heygen
authored
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 <[email protected]> * 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 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Miguel Angel Simon Sierra <[email protected]>
1 parent 9cee2bd commit d49e7b9

25 files changed

Lines changed: 1387 additions & 338 deletions

‎.oxlintrc.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"registry/blocks/**/lib/*.iife.js",
1616
"registry/blocks/{glass-shard-title,code-slice-hero,cuboid-carousel,frost-sequence-camera-orbit,orbit-card}/**/*.{js,mjs}",
1717
"registry/blocks/frost-sequence-camera-orbit/source/**",
18-
"chrome/"
18+
"chrome/",
19+
"packages/cli/src/media-use/lib/svg-sanitize.mjs"
1920
],
2021
"overrides": [
2122
{

‎.prettierignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ packages/**/__goldens__/
1212
# vendored third-party bundles inside skills — never reformat
1313
skills/**/assets/vendor/
1414
skills/**/*.min.js
15+
# esbuild-minified media-use svg sanitizer, generated by
16+
# scripts/generate-media-use-svg-sanitize.mjs — never hand-edit or reformat.
17+
packages/cli/src/media-use/lib/svg-sanitize.mjs
1518
# vendored/bundled third-party JS inside registry blocks — never reformat.
1619
# Without this the format hook silently re-pretty-prints a minified bundle,
1720
# roughly doubling its size. Listed by exact file: these blocks also ship

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
"player:perf": "bun run --filter @hyperframes/player perf",
5353
"format:check": "oxfmt --check .",
5454
"knip": "knip",
55-
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
55+
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
5656
"typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json",
5757
"test:skills": "node --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'",
5858
"generate:previews": "tsx scripts/generate-template-previews.ts",

‎packages/cli/src/media-use/lib/coverage.test.mjs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ test("weakness: audio-only → media-use resolves image + icon", () => {
2929

3030
test("weakness: no third-party brand logos → media-use resolves logo", () => {
3131
assert.ok(listTypes().includes("logo"), "logo type missing");
32-
assert.ok(getProviders("logo").length >= 4, "logo cascade incomplete");
32+
assert.deepEqual(
33+
getProviders("logo").map((p) => p.name),
34+
["thesvg", "github.avatar", "favicon.ddg"],
35+
"logo cascade incomplete",
36+
);
3337
});
3438

3539
test("weakness: no voice/audio gen → media-use exposes voice + the audio engine", () => {

‎packages/cli/src/media-use/lib/freeze.mjs‎

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,51 @@
1-
import { fetchMedia, isPublicMediaUrl } from "./media-fetch.mjs";
2-
import { writeFileSync, copyFileSync, mkdirSync } from "node:fs";
1+
import { fetchMedia, isPublicMediaUrl, readCappedBody } from "./media-fetch.mjs";
2+
import { sanitizeSvg } from "./svg-sanitize.mjs";
3+
import { writeFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs";
34
import { dirname } from "node:path";
45

56
// ponytail: bound the download so a hostile/runaway URL can't fill the disk.
67
// 256MB covers any real media asset; raise if 4K video sources ever exceed it.
78
const MAX_FREEZE_BYTES = 256 * 1024 * 1024;
9+
// Bounds only the wait for response headers; a large video body may stream for minutes.
10+
const FREEZE_HEADERS_TIMEOUT_MS = 10_000;
11+
12+
const isSvgPath = (destPath) => /\.svg$/i.test(destPath);
13+
14+
// Every logo/icon SVG comes from a third-party host (theSVG, a --from URL, a local file), so it
15+
// passes the Figma import's sanitizeSvg allowlist before it touches disk.
16+
function writeFrozen(destPath, buffer) {
17+
mkdirSync(dirname(destPath), { recursive: true });
18+
const bytes = isSvgPath(destPath) ? Buffer.from(sanitizeSvg(buffer.toString("utf8"))) : buffer;
19+
writeFileSync(destPath, bytes);
20+
return bytes.byteLength;
21+
}
822

923
export async function freezeUrl(url, destPath) {
1024
const where = String(url).slice(0, 80);
11-
const res = await fetchMedia(url);
25+
const headerWait = new AbortController();
26+
const timer = setTimeout(
27+
() =>
28+
headerWait.abort(
29+
new Error(`freeze failed: no response within ${FREEZE_HEADERS_TIMEOUT_MS} ms for ${where}`),
30+
),
31+
FREEZE_HEADERS_TIMEOUT_MS,
32+
);
33+
const res = await fetchMedia(url, { signal: headerWait.signal }).finally(() =>
34+
clearTimeout(timer),
35+
);
1236
if (!res.ok) throw new Error(`freeze failed: HTTP ${res.status} for ${where}`);
1337

14-
// Fail fast on an advertised oversize body before reading a single byte.
15-
const declared = Number(res.headers.get("content-length"));
16-
if (declared > MAX_FREEZE_BYTES)
17-
throw new Error(
18-
`freeze failed: ${declared} bytes exceeds ${MAX_FREEZE_BYTES} cap for ${where}`,
19-
);
20-
21-
// Stream and abort once the cap is crossed, so a lying/chunked hostile URL
22-
// can't buffer the whole payload into memory before the check (M1).
23-
const chunks = [];
24-
let total = 0;
25-
for await (const chunk of res.body) {
26-
total += chunk.length;
27-
if (total > MAX_FREEZE_BYTES)
28-
throw new Error(`freeze failed: stream exceeds ${MAX_FREEZE_BYTES} cap for ${where}`);
29-
chunks.push(chunk);
30-
}
31-
if (total === 0) throw new Error(`freeze failed: empty response for ${where}`);
38+
const body = await readCappedBody(res, MAX_FREEZE_BYTES, `freeze failed for ${where}`);
39+
if (body.byteLength === 0) throw new Error(`freeze failed: empty response for ${where}`);
3240

33-
mkdirSync(dirname(destPath), { recursive: true });
34-
writeFileSync(destPath, Buffer.concat(chunks, total));
35-
return total;
41+
return writeFrozen(destPath, body);
3642
}
3743

3844
export function freezeLocalFile(srcPath, destPath) {
45+
if (isSvgPath(destPath)) {
46+
writeFrozen(destPath, readFileSync(srcPath));
47+
return;
48+
}
3949
mkdirSync(dirname(destPath), { recursive: true });
4050
copyFileSync(srcPath, destPath);
4151
}

‎packages/cli/src/media-use/lib/freeze.test.mjs‎

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import { strict as assert } from "node:assert";
22
import { test } from "node:test";
3-
import { isDirectMediaUrl } from "./freeze.mjs";
3+
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
4+
import { tmpdir } from "node:os";
5+
import { join } from "node:path";
6+
import { isDirectMediaUrl, freezeUrl, freezeLocalFile } from "./freeze.mjs";
7+
8+
const HOSTILE_SVG =
9+
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script>' +
10+
'<rect onload="alert(2)" width="1" height="1"/>' +
11+
'<a href="javascript:alert(3)"><circle r="1"/></a></svg>';
412

513
test("accepts direct public media URLs", () => {
614
assert.equal(isDirectMediaUrl("https://cdn.example.com/clip.mp4"), true);
@@ -44,3 +52,87 @@ test("rejects local / private hosts (SSRF guard, m11)", () => {
4452
assert.equal(isDirectMediaUrl("https://172.40.0.1/a.mp4"), true, "172.40 is public");
4553
assert.equal(isDirectMediaUrl("https://11.example.com/a.mp4"), true);
4654
});
55+
56+
test("freezeUrl strips <script>, on* handlers and javascript: hrefs from a fetched SVG", async (t) => {
57+
t.mock.method(
58+
globalThis,
59+
"fetch",
60+
async () =>
61+
new Response(HOSTILE_SVG, { status: 200, headers: { "content-type": "image/svg+xml" } }),
62+
);
63+
const dest = join(mkdtempSync(join(tmpdir(), "media-use-freeze-")), "logo.svg");
64+
await freezeUrl("https://example.com/hostile.svg", dest);
65+
const out = readFileSync(dest, "utf8");
66+
assert.ok(!out.includes("<script"), "script element stripped");
67+
assert.ok(!out.includes("onload="), "event handler stripped");
68+
assert.ok(!out.includes("javascript:"), "javascript: href stripped");
69+
assert.ok(out.includes("<circle"), "benign markup survives");
70+
});
71+
72+
// Puts setTimeout and AbortSignal.timeout on node:test's fake clock.
73+
function fakeClock(t) {
74+
t.mock.timers.enable({ apis: ["setTimeout"] });
75+
t.mock.method(AbortSignal, "timeout", (ms) => {
76+
const controller = new AbortController();
77+
setTimeout(() => controller.abort(new DOMException("timed out", "TimeoutError")), ms);
78+
return controller.signal;
79+
});
80+
}
81+
82+
test("freezeUrl keeps streaming a slow body past the header timeout", async (t) => {
83+
fakeClock(t);
84+
let body;
85+
t.mock.method(globalThis, "fetch", async (_url, { signal }) => {
86+
const stream = new ReadableStream({
87+
start(controller) {
88+
body = controller;
89+
// undici aborts the body stream too when the request signal fires.
90+
signal.addEventListener("abort", () => controller.error(signal.reason));
91+
controller.enqueue(new Uint8Array([1, 2, 3]));
92+
},
93+
});
94+
return new Response(stream, { status: 200 });
95+
});
96+
const dest = join(mkdtempSync(join(tmpdir(), "media-use-freeze-")), "clip.mp4");
97+
const frozen = freezeUrl("https://cdn.example.com/clip.mp4", dest);
98+
await new Promise(setImmediate);
99+
t.mock.timers.tick(60_000);
100+
body.enqueue(new Uint8Array([4, 5]));
101+
body.close();
102+
assert.equal(await frozen, 5);
103+
assert.deepEqual([...readFileSync(dest)], [1, 2, 3, 4, 5]);
104+
});
105+
106+
test("freezeUrl times out when no response headers arrive", { timeout: 5_000 }, async (t) => {
107+
fakeClock(t);
108+
t.mock.method(
109+
globalThis,
110+
"fetch",
111+
(_url, { signal }) =>
112+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))),
113+
);
114+
const dest = join(mkdtempSync(join(tmpdir(), "media-use-freeze-")), "clip.mp4");
115+
const frozen = freezeUrl("https://cdn.example.com/clip.mp4", dest);
116+
t.mock.timers.tick(10_000);
117+
await assert.rejects(frozen, /no response within 10000 ms/);
118+
});
119+
120+
test("freezeLocalFile strips the same hostile SVG content from a local source", () => {
121+
const srcDir = mkdtempSync(join(tmpdir(), "media-use-freeze-src-"));
122+
const src = join(srcDir, "in.svg");
123+
writeFileSync(src, HOSTILE_SVG);
124+
const dest = join(mkdtempSync(join(tmpdir(), "media-use-freeze-dest-")), "logo.svg");
125+
freezeLocalFile(src, dest);
126+
const out = readFileSync(dest, "utf8");
127+
assert.ok(!out.includes("<script"));
128+
assert.ok(!out.includes("onload="));
129+
});
130+
131+
test("freezeLocalFile still byte-copies a non-SVG file untouched", () => {
132+
const srcDir = mkdtempSync(join(tmpdir(), "media-use-freeze-src-"));
133+
const src = join(srcDir, "in.png");
134+
writeFileSync(src, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
135+
const dest = join(mkdtempSync(join(tmpdir(), "media-use-freeze-dest-")), "logo.png");
136+
freezeLocalFile(src, dest);
137+
assert.deepEqual(readFileSync(dest), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
138+
});

0 commit comments

Comments
 (0)