Skip to content

Write HTML. Render video. Built for agents.

fix(producer): localize remote @font-face src URLs before render (#1155)

Miguel Ángelb1b03782a136
diff --git a/packages/engine/src/utils/urlDownloader.test.ts b/packages/engine/src/utils/urlDownloader.test.ts
new file mode 100644
index 0000000000..22fae4f93a
--- /dev/null
+++ b/packages/engine/src/utils/urlDownloader.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { assertPublicHttpsUrl } from "./urlDownloader.js";
+
+describe("assertPublicHttpsUrl — SSRF guard", () => {
+ it("accepts public HTTPS URLs", () => {
+ expect(() =>
+ assertPublicHttpsUrl("https://gen-os-static.s3.us-east-2.amazonaws.com/fonts/font.ttf"),
+ ).not.toThrow();
+ expect(() => assertPublicHttpsUrl("https://cdn.jsdelivr.net/npm/gsap.min.js")).not.toThrow();
+ expect(() => assertPublicHttpsUrl("https://fonts.gstatic.com/s/font.woff2")).not.toThrow();
+ });
+
+ it("rejects http:// (non-HTTPS)", () => {
+ expect(() => assertPublicHttpsUrl("http://example.com/font.ttf")).toThrow("Only HTTPS");
+ });
+
+ it("rejects AWS IMDS (169.254.169.254)", () => {
+ expect(() =>
+ assertPublicHttpsUrl("https://169.254.169.254/latest/meta-data/iam/security-credentials/"),
+ ).toThrow("private/reserved");
+ expect(() => assertPublicHttpsUrl("http://169.254.169.254/latest/user-data")).toThrow();
+ });
+
+ it("rejects loopback (127.x.x.x)", () => {
+ expect(() => assertPublicHttpsUrl("https://127.0.0.1/font.ttf")).toThrow("private/reserved");
+ expect(() => assertPublicHttpsUrl("https://127.1.2.3/secret")).toThrow("private/reserved");
+ });
+
+ it("rejects localhost", () => {
+ expect(() => assertPublicHttpsUrl("https://localhost/font.ttf")).toThrow("private/reserved");
+ expect(() => assertPublicHttpsUrl("http://localhost:3000/secret")).toThrow();
+ });
+
+ it("rejects RFC1918 — 10.x", () => {
+ expect(() => assertPublicHttpsUrl("https://10.0.0.1/secret")).toThrow("private/reserved");
+ expect(() => assertPublicHttpsUrl("https://10.255.255.255/secret")).toThrow("private/reserved");
+ });
+
+ it("rejects RFC1918 — 172.16–172.31", () => {
+ expect(() => assertPublicHttpsUrl("https://172.16.0.1/secret")).toThrow("private/reserved");
+ expect(() => assertPublicHttpsUrl("https://172.31.255.255/secret")).toThrow("private/reserved");
+ });
+
+ it("allows 172.0–172.15 and 172.32+ (not RFC1918)", () => {
+ expect(() => assertPublicHttpsUrl("https://172.15.0.1/font.ttf")).not.toThrow();
+ expect(() => assertPublicHttpsUrl("https://172.32.0.1/font.ttf")).not.toThrow();
+ });
+
+ it("rejects RFC1918 — 192.168.x", () => {
+ expect(() => assertPublicHttpsUrl("https://192.168.1.1/secret")).toThrow("private/reserved");
+ });
+
+ it("rejects unspecified address (0.x)", () => {
+ expect(() => assertPublicHttpsUrl("https://0.0.0.0/secret")).toThrow("private/reserved");
+ });
+
+ it("rejects loopback IPv6 ([::1])", () => {
+ expect(() => assertPublicHttpsUrl("https://[::1]/secret")).toThrow("private/reserved");
+ });
+
+ it("rejects invalid URLs", () => {
+ expect(() => assertPublicHttpsUrl("not-a-url")).toThrow("Invalid URL");
+ expect(() => assertPublicHttpsUrl("")).toThrow("Invalid URL");
+ });
+});
diff --git a/packages/engine/src/utils/urlDownloader.ts b/packages/engine/src/utils/urlDownloader.ts
index 85655cd4ff..3dbd65321d 100644
--- a/packages/engine/src/utils/urlDownloader.ts
+++ b/packages/engine/src/utils/urlDownloader.ts
@@ -7,6 +7,62 @@ import { finished } from "stream/promises";
const downloadPathCache = new Map<string, string>();
const inFlightDownloads = new Map<string, Promise<string>>();
+// SSRF guard: these prefixes identify non-public address space that
+// compositions (customer-supplied) must never be able to reach via the
+// download path. Blocks AWS IMDS (169.254.169.254), loopback, RFC1918,
+// and unspecified addresses. All comparisons are on the raw hostname
+// string; DNS resolution is NOT performed here, so DNS-rebinding bypasses
+// are not closed by this check — that gap is acceptable for the risk level.
+const BLOCKED_HOST_PREFIXES = [
+ "169.254.", // link-local / AWS IMDS
+ "127.", // loopback IPv4
+ "10.", // RFC1918
+ "192.168.", // RFC1918
+ "0.", // unspecified
+ "[::1]", // loopback IPv6
+ "[fc", // RFC4193 unique-local IPv6
+ "[fd", // RFC4193 unique-local IPv6
+];
+// 172.16.0.0 – 172.31.255.255 (RFC1918)
+const BLOCKED_172_RANGE = { min: 16, max: 31 };
+
+function isBlockedHost(hostname: string): boolean {
+ const h = hostname.toLowerCase();
+ if (h === "localhost") return true;
+ if (BLOCKED_HOST_PREFIXES.some((p) => h.startsWith(p))) return true;
+ // 172.16–172.31
+ const m = h.match(/^172\.(\d{1,3})\./);
+ if (m) {
+ const octet = parseInt(m[1] ?? "0", 10);
+ if (octet >= BLOCKED_172_RANGE.min && octet <= BLOCKED_172_RANGE.max) return true;
+ }
+ return false;
+}
+
+/**
+ * Validate that a URL is safe to fetch on behalf of customer-supplied
+ * compositions. Throws if the URL is non-HTTPS or targets a private/reserved
+ * address range (SSRF guard).
+ */
+export function assertPublicHttpsUrl(url: string): void {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error(`[URLDownloader] Invalid URL: ${url}`);
+ }
+ if (parsed.protocol !== "https:") {
+ throw new Error(
+ `[URLDownloader] Only HTTPS URLs are permitted in compositions (got ${parsed.protocol}): ${url}`,
+ );
+ }
+ if (isBlockedHost(parsed.hostname)) {
+ throw new Error(
+ `[URLDownloader] URL targets a private/reserved address and is not permitted: ${url}`,
+ );
+ }
+}
+
function getFilenameFromUrl(url: string): string {
const hash = createHash("md5").update(url).digest("hex").slice(0, 12);
const urlObj = new URL(url);
@@ -19,6 +75,11 @@ export async function downloadToTemp(
destDir: string,
timeoutMs: number = 300000,
): Promise<string> {
+ // Reject non-HTTPS URLs and private/reserved address ranges before
+ // touching the cache or filesystem — customer-supplied compositions must
+ // not be able to trigger outbound fetches to internal infrastructure.
+ assertPublicHttpsUrl(url);
+
const cachedPath = downloadPathCache.get(url);
if (cachedPath && existsSync(cachedPath)) {
return cachedPath;
diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts
index 0363c71348..1581026633 100644
--- a/packages/producer/src/services/htmlCompiler.test.ts
+++ b/packages/producer/src/services/htmlCompiler.test.ts
@@ -11,6 +11,7 @@ import {
discoverAudioVolumeAutomationFromTimeline,
inlineExternalScripts,
localizeRemoteMediaSources,
+ localizeRemoteFontFaces,
recompileWithResolutions,
} from "./htmlCompiler.js";
@@ -949,6 +950,108 @@ describe("localizeRemoteMediaSources", () => {
});
});
+// ── localizeRemoteFontFaces ──────────────────────────────────────────────────
+
+describe("localizeRemoteFontFaces", () => {
+ const FONT_URL = "https://gen-os-static.s3.us-east-2.amazonaws.com/fonts/komika-axis.ttf";
+
+ it("rewrites @font-face url() inside <style> to _remote_media/ path", async () => {
+ const orig = globalThis.fetch;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).fetch = async () => new Response(new Uint8Array(16), { status: 200 });
+ try {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-"));
+ const html = `<style>
+@font-face {
+ font-family: "Komika Axis";
+ src: url("${FONT_URL}") format("truetype");
+}
+</style>`;
+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);
+ expect(result).not.toContain(FONT_URL);
+ expect(result).toContain("_remote_media/");
+ expect(remoteMediaAssets.size).toBe(1);
+ } finally {
+ globalThis.fetch = orig;
+ }
+ });
+
+ it("ignores url() references outside @font-face (e.g. background-image)", async () => {
+ const orig = globalThis.fetch;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).fetch = async () => new Response(new Uint8Array(16), { status: 200 });
+ try {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-bg-"));
+ const BG_URL = "https://cdn.example.com/bg.png";
+ const html = `<style>
+body { background-image: url("${BG_URL}"); }
+@font-face { font-family: "F"; src: url("${FONT_URL}") format("truetype"); }
+</style>`;
+ const { html: result } = await localizeRemoteFontFaces(html, dl);
+ // Font URL rewritten, background URL untouched
+ expect(result).not.toContain(FONT_URL);
+ expect(result).toContain(BG_URL);
+ } finally {
+ globalThis.fetch = orig;
+ }
+ });
+
+ it("preserves original URL when download fails", async () => {
+ const orig = globalThis.fetch;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).fetch = async () => new Response(null, { status: 403 });
+ try {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-fail-"));
+ const FAIL_URL = "https://fail-font.example.com/f.ttf";
+ const html = `<style>@font-face { font-family: "F"; src: url("${FAIL_URL}") format("truetype"); }</style>`;
+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);
+ expect(result).toContain(FAIL_URL);
+ expect(remoteMediaAssets.size).toBe(0);
+ } finally {
+ globalThis.fetch = orig;
+ }
+ });
+
+ it("deduplicates: same font URL in two @font-face blocks → 1 download", async () => {
+ const orig = globalThis.fetch;
+ let fetchCount = 0;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).fetch = async () => {
+ fetchCount++;
+ return new Response(new Uint8Array(16), { status: 200 });
+ };
+ try {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-dedup-"));
+ const DEDUP_URL = "https://dedup-font.example.com/d.ttf";
+ const html = `<style>
+@font-face { font-family: "F1"; src: url("${DEDUP_URL}") format("truetype"); font-weight: 400; }
+@font-face { font-family: "F2"; src: url("${DEDUP_URL}") format("truetype"); font-weight: 700; }
+</style>`;
+ const { remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);
+ expect(fetchCount).toBe(1);
+ expect(remoteMediaAssets.size).toBe(1);
+ } finally {
+ globalThis.fetch = orig;
+ }
+ });
+
+ it("no-ops when no @font-face blocks are present", async () => {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-noop-"));
+ const html = `<style>body { color: red; }</style>`;
+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);
+ expect(result).toBe(html);
+ expect(remoteMediaAssets.size).toBe(0);
+ });
+
+ it("ignores local (non-HTTP) @font-face src URLs", async () => {
+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-local-"));
+ const html = `<style>@font-face { font-family: "F"; src: url("assets/fonts/f.ttf") format("truetype"); }</style>`;
+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);
+ expect(result).toBe(html);
+ expect(remoteMediaAssets.size).toBe(0);
+ });
+});
+
describe("discoverAudioVolumeAutomationFromTimeline", () => {
it("samples video-derived audio volume without firing GSAP callbacks", async () => {
class TestAudioElement {}
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 85edddbc05..cd9c713c5a 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -888,40 +888,26 @@ const REMOTE_MEDIA_TAG_RE =
/<(?:video|audio)\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+)["'][^>]*>/gi;
/**
- * Download any remote `src` URLs on `<video>` and `<audio>` elements into a
- * local subdirectory of `downloadDir`, rewrite the HTML src attributes to
- * relative paths, and return the updated HTML along with a map of
- * `{ relativePath → absoluteLocalPath }` for callers to add to `externalAssets`.
- *
- * Skips URLs that fail to download (warns and preserves the original URL so
- * the browser can still attempt the remote fetch as a fallback).
+ * Download a set of remote URLs in parallel into `remoteDir`, build the
+ * `{ relPath → absPath }` asset map, and rewrite every occurrence of each
+ * URL inside `html` with its relative local path.
*
- * Why: remote S3 sources require Chrome to buffer every video file over the
- * network before `readyState >= 2` (HAVE_CURRENT_DATA). With 10+ large clips
- * this reliably exhausts `pageReadyTimeout`, producing blank black frames for
- * every clip. Localising the sources before the file server starts eliminates
- * the race entirely and keeps the render hermetic.
+ * The `warnLabel` appears in console.warn messages for download failures.
+ * The `logLabel` appears in the success console.log line.
+ * `extraRewrite`, if provided, is called per URL pair after the standard
+ * double/single-quote rewrite — used for url(...) CSS rewriting.
*/
-/** @internal exported for unit testing only */
-export async function localizeRemoteMediaSources(
+async function downloadAndRewriteUrls(
+ urlSet: Set<string>,
html: string,
- downloadDir: string,
+ remoteDir: string,
+ warnLabel: string,
+ logLabel: string,
+ extraRewrite?: (html: string, url: string, relPath: string) => string,
): Promise<{ html: string; remoteMediaAssets: Map<string, string> }> {
- const remoteDir = join(downloadDir, REMOTE_MEDIA_SUBDIR);
-
- // Collect unique HTTP URLs from <video>/<audio> src attributes.
- const urlSet = new Set<string>();
- const re = new RegExp(REMOTE_MEDIA_TAG_RE.source, REMOTE_MEDIA_TAG_RE.flags);
- let m: RegExpExecArray | null;
- while ((m = re.exec(html)) !== null) {
- if (m[1]) urlSet.add(m[1]);
- }
-
if (urlSet.size === 0) return { html, remoteMediaAssets: new Map() };
-
if (!existsSync(remoteDir)) mkdirSync(remoteDir, { recursive: true });
- // Download all unique URLs in parallel; collect {url → localPath} for successes.
const urlToLocal = new Map<string, string>();
await Promise.all(
[...urlSet].map(async (url) => {
@@ -930,7 +916,7 @@ export async function localizeRemoteMediaSources(
urlToLocal.set(url, localPath);
} catch (err) {
console.warn(
- `[Compiler] Remote media download failed for ${url} — using original URL as fallback. ${
+ `[Compiler] ${warnLabel} ${url} — using original URL as fallback. ${
err instanceof Error ? err.message : String(err)
}`,
);
@@ -940,9 +926,6 @@ export async function localizeRemoteMediaSources(
if (urlToLocal.size === 0) return { html, remoteMediaAssets: new Map() };
- // Build externalAssets map: relative key → local abs path.
- // The relative key ("_remote_media/<file>") becomes the path under compiledDir
- // that writeCompiledArtifacts copies the file to and the file server exposes.
const remoteMediaAssets = new Map<string, string>();
const urlToRelPath = new Map<string, string>();
for (const [url, absPath] of urlToLocal) {
@@ -951,20 +934,109 @@ export async function localizeRemoteMediaSources(
urlToRelPath.set(url, relPath);
}
- // Rewrite src attributes in HTML.
let result = html;
for (const [url, relPath] of urlToRelPath) {
- // Replace both quote styles; URLs are long enough to be unique without
- // anchoring to the surrounding attribute context.
result = result.replaceAll(`"${url}"`, `"${relPath}"`).replaceAll(`'${url}'`, `'${relPath}'`);
+ if (extraRewrite) result = extraRewrite(result, url, relPath);
}
- console.log(
- `[Compiler] Localized ${urlToLocal.size} remote media source(s) to ${REMOTE_MEDIA_SUBDIR}/`,
- );
+ console.log(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
return { html: result, remoteMediaAssets };
}
+/**
+ * Download any remote `src` URLs on `<video>` and `<audio>` elements into a
+ * local subdirectory of `downloadDir`, rewrite the HTML src attributes to
+ * relative paths, and return the updated HTML along with a map of
+ * `{ relativePath → absoluteLocalPath }` for callers to add to `externalAssets`.
+ *
+ * Skips URLs that fail to download (warns and preserves the original URL so
+ * the browser can still attempt the remote fetch as a fallback).
+ *
+ * Why: remote S3 sources require Chrome to buffer every video file over the
+ * network before `readyState >= 2` (HAVE_CURRENT_DATA). With 10+ large clips
+ * this reliably exhausts `pageReadyTimeout`, producing blank black frames for
+ * every clip. Localising the sources before the file server starts eliminates
+ * the race entirely and keeps the render hermetic.
+ */
+/** @internal exported for unit testing only */
+export async function localizeRemoteMediaSources(
+ html: string,
+ downloadDir: string,
+): Promise<{ html: string; remoteMediaAssets: Map<string, string> }> {
+ // Collect unique HTTP URLs from <video>/<audio> src attributes.
+ const urlSet = new Set<string>();
+ const re = new RegExp(REMOTE_MEDIA_TAG_RE.source, REMOTE_MEDIA_TAG_RE.flags);
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(html)) !== null) {
+ if (m[1]) urlSet.add(m[1]);
+ }
+ return downloadAndRewriteUrls(
+ urlSet,
+ html,
+ join(downloadDir, REMOTE_MEDIA_SUBDIR),
+ "Remote media download failed for",
+ "Localized remote media source(s)",
+ );
+}
+
+// Match url("https://...") or url('https://...') inside @font-face blocks.
+// We scan the full HTML (which includes <style> blocks) — matching against
+// @font-face context precisely would require a CSS parser; instead we match
+// any url(https?://...) that appears inside a @font-face rule by looking for
+// the surrounding context. Simple pattern: capture all HTTP url() references
+// that follow a @font-face opener (before the closing brace). The regex is
+// applied to the CSS text extracted from <style> blocks so it can't
+// accidentally match JavaScript string literals.
+const REMOTE_FONTFACE_URL_RE = /url\(["']?(https?:\/\/[^"')]+)["']?\)/gi;
+
+/**
+ * Download any remote font URLs from `@font-face` src declarations, rewrite
+ * the CSS `url(...)` references to local paths, and return a map of assets.
+ *
+ * Why: `@font-face { src: url("https://s3.../font.ttf") }` fails in the
+ * renderer because Chrome makes a CORS-mode fetch from the local file server
+ * origin (http://localhost:PORT) and S3 does not echo that origin back in
+ * Access-Control-Allow-Origin. The font load is rejected, Chrome falls back
+ * to the next font in the stack (e.g. Arial). Downloading the font file
+ * before render and rewriting to a local path eliminates the CORS race.
+ */
+/** @internal exported for unit testing only */
+export async function localizeRemoteFontFaces(
+ html: string,
+ downloadDir: string,
+): Promise<{ html: string; remoteMediaAssets: Map<string, string> }> {
+ // Only scan inside <style> blocks to avoid false-positive matches in JS.
+ const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
+ const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;
+ const urlSet = new Set<string>();
+
+ let styleMatch: RegExpExecArray | null;
+ while ((styleMatch = styleBlockRe.exec(html)) !== null) {
+ const cssText = styleMatch[1] ?? "";
+ const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);
+ let ffMatch: RegExpExecArray | null;
+ while ((ffMatch = ffRe.exec(cssText)) !== null) {
+ const block = ffMatch[1] ?? "";
+ const urlRe = new RegExp(REMOTE_FONTFACE_URL_RE.source, REMOTE_FONTFACE_URL_RE.flags);
+ let urlMatch: RegExpExecArray | null;
+ while ((urlMatch = urlRe.exec(block)) !== null) {
+ if (urlMatch[1]) urlSet.add(urlMatch[1]);
+ }
+ }
+ }
+
+ return downloadAndRewriteUrls(
+ urlSet,
+ html,
+ join(downloadDir, REMOTE_MEDIA_SUBDIR),
+ "Remote font download failed for",
+ "Localized remote font face(s)",
+ // Also rewrite unquoted url(https://...) CSS syntax.
+ (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`),
+ );
+}
+
/**
* Optional behavior toggles for {@link compileForRender}. All fields are
* additive; omitting `options` preserves the in-process renderer's defaults.
@@ -1088,7 +1160,7 @@ export async function compileForRender(
// Chrome to spend the entire pageReadyTimeout buffering 10+ large video files
// over the network; any that don't reach readyState >= 2 in time render as
// blank black frames. Localising them eliminates the race.
- const { html, remoteMediaAssets } = await localizeRemoteMediaSources(
+ const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
htmlWithPositionScript,
downloadDir,
);
@@ -1096,6 +1168,18 @@ export async function compileForRender(
externalAssets.set(relPath, absPath);
}
+ // Download remote @font-face src URLs and rewrite to local paths.
+ // Remote font URLs fail with a CORS rejection at render time (S3 does not
+ // allow http://localhost:PORT as origin), causing Chrome to silently fall
+ // back to the next font in the stack.
+ const { html, remoteMediaAssets: remoteFontAssets } = await localizeRemoteFontFaces(
+ htmlWithLocalMedia,
+ downloadDir,
+ );
+ for (const [relPath, absPath] of remoteFontAssets) {
+ externalAssets.set(relPath, absPath);
+ }
+
// Parse main HTML elements
const mainVideos = parseVideoElements(html);
const mainAudios = parseAudioElements(html);