Skip to content

Write HTML. Render video. Built for agents.

fix(security): verify CDN script integrity before inlining (#3822)

James Russoff749b870555
diff --git a/packages/core/src/compiler/externalScripts.ts b/packages/core/src/compiler/externalScripts.ts
new file mode 100644
index 0000000000..796a5f46c6
--- /dev/null
+++ b/packages/core/src/compiler/externalScripts.ts
@@ -0,0 +1,49 @@
+export interface ExternalScriptAttributes {
+ integrity?: string;
+ crossorigin?: string;
+}
+
+export function readExternalScriptAttributes(el: Element): ExternalScriptAttributes {
+ const attributes: ExternalScriptAttributes = {};
+ if (el.hasAttribute("integrity")) attributes.integrity = el.getAttribute("integrity") || "";
+ if (el.hasAttribute("crossorigin")) attributes.crossorigin = el.getAttribute("crossorigin") || "";
+ return attributes;
+}
+
+/** Deduplicate scripts without discarding a nested composition's integrity requirement. */
+export function ensureExternalScriptTag(
+ doc: Document,
+ src: string,
+ attributes: ExternalScriptAttributes = {},
+): void {
+ const existing = [...doc.querySelectorAll("script[src]")].filter(
+ (el) => el.getAttribute("src")?.trim() === src,
+ );
+ const requirements = new Set(
+ [attributes.integrity, ...existing.map((el) => el.getAttribute("integrity"))]
+ .map((value) =>
+ value
+ ?.trim()
+ .replace(
+ /(^|[\t\n\f\r ])(sha256|sha384|sha512)-/gi,
+ (_match, space: string, algorithm: string) => `${space}${algorithm.toLowerCase()}-`,
+ ),
+ )
+ .filter((value): value is string => Boolean(value)),
+ );
+ if (requirements.size > 1) {
+ throw new Error(`Conflicting script integrity requirements for ${src}`);
+ }
+ const integrity = [...requirements][0];
+ const elements = existing.length ? existing : [doc.createElement("script")];
+ for (const el of elements) {
+ if (integrity) el.setAttribute("integrity", integrity);
+ if (attributes.crossorigin !== undefined)
+ el.setAttribute("crossorigin", attributes.crossorigin);
+ }
+ if (!existing.length) {
+ const el = elements[0]!;
+ el.setAttribute("src", src);
+ doc.body.appendChild(el);
+ }
+}
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index 43c2b94caf..3939288be5 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { parseHTML } from "linkedom";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { bundleToSingleHtml, emitRootCompositionVariableStyles } from "./htmlBundler";
+import { ensureExternalScriptTag } from "./externalScripts";
import { resetUnknownEnumWarnings } from "../runtime/getVariables";
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
@@ -1629,3 +1630,98 @@ describe("emitRootCompositionVariableStyles — <style> breakout", () => {
expect(css).toContain("#ff0066");
});
});
+
+describe("nested script integrity", () => {
+ it("preserves and deduplicates a nested pin even when the root already loads that URL", async () => {
+ const src = "https://cdn.example.com/pinned.js";
+ const dir = makeTempProject({
+ "index.html": `<html><head><script src="${src}"></script></head><body><div data-composition-id="root" data-width="320" data-height="180" data-duration="1"><div data-composition-id="child" data-composition-src="child.html"></div></div></body></html>`,
+ "child.html": `<html><head><script src="${src}" integrity="sha384-YQ==" crossorigin="anonymous"></script></head><body><div data-composition-id="child" data-width="320" data-height="180" data-duration="1">Child</div></body></html>`,
+ });
+ try {
+ const bundled = await bundleToSingleHtml(dir);
+ const { document } = parseHTML(bundled);
+ const scripts = [...document.querySelectorAll("script[src]")].filter(
+ (el) => el.getAttribute("src") === src,
+ );
+ expect(scripts).toHaveLength(1);
+ expect(scripts[0]?.getAttribute("integrity")).toBe("sha384-YQ==");
+ expect(scripts[0]?.getAttribute("crossorigin")).toBe("anonymous");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+it("preserves every duplicate script pin and rejects conflicting requirements", () => {
+ const { document } = parseHTML(
+ '<html><body><script src="https://cdn.example.com/a.js"></script><script src="https://cdn.example.com/a.js"></script></body></html>',
+ );
+ const src = "https://cdn.example.com/a.js";
+ ensureExternalScriptTag(document, src, { integrity: "sha384-YQ==", crossorigin: "anonymous" });
+ ensureExternalScriptTag(document, src);
+ for (const el of document.querySelectorAll("script")) {
+ expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
+ expect(el.getAttribute("crossorigin")).toBe("anonymous");
+ }
+ expect(() => ensureExternalScriptTag(document, src, { integrity: "sha384-Yg==" })).toThrow(
+ "Conflicting script integrity",
+ );
+});
+
+it("keeps protected local scripts external when hoisting an inline template", async () => {
+ const dir = makeTempProject({
+ "index.html": `<html><body><template id="child-template"><div data-composition-id="child" data-width="320" data-height="180"><script src="local.js" integrity="sha384-YQ==" crossorigin="anonymous"></script></div></template><div data-composition-id="root" data-width="320" data-height="180" data-duration="1"><div data-composition-id="child" data-start="0" data-duration="1"></div></div></body></html>`,
+ "local.js": "window.localPinWitness = true;",
+ });
+ try {
+ const bundled = await bundleToSingleHtml(dir);
+ const { document } = parseHTML(bundled);
+ const script = document.querySelector('script[src="local.js"]');
+ expect(script?.getAttribute("integrity")).toBe("sha384-YQ==");
+ expect(script?.getAttribute("crossorigin")).toBe("anonymous");
+ expect(bundled).not.toContain("window.localPinWitness = true;");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+it.each(["root", "sibling", "template"])(
+ "does not inline local bytes before a later %s integrity requirement",
+ async (placement) => {
+ const unpinned = '<script src="local.js"></script>';
+ const pinned =
+ '<script src="./local.js" integrity="sHa384-YQ==" crossorigin="anonymous"></script>';
+ const rootScript = placement === "root" ? unpinned : "";
+ const first =
+ placement === "sibling"
+ ? '<div data-composition-id="first" data-composition-src="first.html"></div>'
+ : "";
+ const templates =
+ placement === "template"
+ ? `<template id="first-template"><div data-composition-id="first">${unpinned}</div></template><template id="child-template"><div data-composition-id="child">${pinned}</div></template>`
+ : "";
+ const children =
+ placement === "template"
+ ? '<div data-composition-id="first" data-start="0" data-duration="1"></div><div data-composition-id="child" data-start="0" data-duration="1"></div>'
+ : `${first}<div data-composition-id="child" data-composition-src="child.html"></div>`;
+ const dir = makeTempProject({
+ "index.html": `<html><head>${rootScript}</head><body>${templates}<div data-composition-id="root" data-width="320" data-height="180" data-duration="1">${children}</div></body></html>`,
+ "first.html": `<html><head>${unpinned}</head><body><div data-composition-id="first" data-width="320" data-height="180" data-duration="1">First</div></body></html>`,
+ "child.html": `<html><head>${pinned}</head><body><div data-composition-id="child" data-width="320" data-height="180" data-duration="1">Child</div></body></html>`,
+ "local.js": "window.alteredLocalBytes = true;",
+ });
+ try {
+ const bundled = await bundleToSingleHtml(dir);
+ expect(bundled).not.toContain("window.alteredLocalBytes = true;");
+ const { document } = parseHTML(bundled);
+ const local = [...document.querySelectorAll("script[src]")].filter((el) =>
+ /local\.js$/.test(el.getAttribute("src") || ""),
+ );
+ expect(local.length).toBeGreaterThan(0);
+ for (const el of local) expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index 1eff4f9624..aaed300fb7 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -1,3 +1,8 @@
+import {
+ ensureExternalScriptTag,
+ readExternalScriptAttributes,
+ type ExternalScriptAttributes,
+} from "./externalScripts";
import { markFlattenedInnerRoot } from "../runtime/flattenedRoot";
export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";
import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";
@@ -722,11 +727,25 @@ export interface BundleOptions {
* - Inlines small textual assets as data URLs
*/
-function ensureExternalScriptTag(doc: Document, src: string): void {
- if (queryByAttr(doc, "src", src, "script")) return;
- const el = doc.createElement("script");
- el.setAttribute("src", src);
- doc.body.appendChild(el);
+type DeferredScriptChunk = string | (() => string);
+
+function preserveLocalScriptIntegrity(
+ doc: Document,
+ src: string,
+ resolvePath: (src: string) => string | null,
+): boolean {
+ const path = resolvePath(src);
+ if (!path) return false;
+ const pinned = [...doc.querySelectorAll("script[src][integrity]")].filter((el) => {
+ const candidate = el.getAttribute("src") || "";
+ return (
+ isRelativeUrl(candidate) &&
+ resolvePath(candidate) === path &&
+ el.getAttribute("integrity")?.trim()
+ );
+ });
+ for (const el of pinned) ensureExternalScriptTag(doc, src, readExternalScriptAttributes(el));
+ return pinned.length > 0;
}
function hoistExternalScript(
@@ -734,19 +753,29 @@ function hoistExternalScript(
projectDir: string,
doc: Document,
seenSrcs: Set<string>,
- chunks: string[],
+ chunks: DeferredScriptChunk[],
+ attributes: ExternalScriptAttributes,
): void {
+ if (attributes.integrity?.trim()) {
+ ensureExternalScriptTag(doc, src, attributes);
+ seenSrcs.add(src);
+ return;
+ }
if (seenSrcs.has(src)) return;
seenSrcs.add(src);
if (!isNonRelativeUrl(src) && !isAbsolute(src)) {
const jsPath = resolveWithinProject(projectDir, src);
const js = jsPath ? safeReadFile(jsPath) : null;
if (js != null) {
- chunks.push(js);
+ chunks.push(() =>
+ preserveLocalScriptIntegrity(doc, src, (value) => resolveWithinProject(projectDir, value))
+ ? ""
+ : js,
+ );
return;
}
}
- ensureExternalScriptTag(doc, src);
+ ensureExternalScriptTag(doc, src, attributes);
}
function hoistCompositionScripts(
@@ -759,7 +788,7 @@ function hoistCompositionScripts(
runtimeCompId: string | undefined;
authoredRootId: string | undefined;
seenCompScriptSrcs: Set<string>;
- compScriptChunks: string[];
+ compScriptChunks: DeferredScriptChunk[];
},
): void {
for (const scriptEl of [...container.querySelectorAll("script")]) {
@@ -771,6 +800,7 @@ function hoistCompositionScripts(
opts.document,
opts.seenCompScriptSrcs,
opts.compScriptChunks,
+ readExternalScriptAttributes(scriptEl),
);
} else {
opts.compScriptChunks.push(
@@ -857,42 +887,6 @@ export async function bundleToSingleHtml(
}
}
- // Inline local JS
- const localJsChunks: string[] = [];
- let jsAnchorPlaced = false;
- for (const el of [...document.querySelectorAll("script[src]")]) {
- const src = el.getAttribute("src");
- if (!src || !isRelativeUrl(src)) continue;
- // Module scripts can contain static imports whose resolution is relative
- // to the script URL. Folding their source into a classic inline script
- // both drops module semantics and changes the import base URL.
- if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue;
- const jsPath = resolveEntryPath(src);
- const js = jsPath ? safeReadFile(jsPath) : null;
- if (js == null) continue;
- localJsChunks.push(js);
- if (!jsAnchorPlaced) {
- const anchor = document.createElement("script");
- anchor.setAttribute("data-hf-bundled-local-js", "1");
- el.replaceWith(anchor);
- jsAnchorPlaced = true;
- } else {
- el.remove();
- }
- }
- if (localJsChunks.length > 0) {
- const anchor = document.querySelector('script[data-hf-bundled-local-js="1"]');
- const joinedJs = joinJsChunks(localJsChunks);
- if (anchor) {
- anchor.removeAttribute("data-hf-bundled-local-js");
- anchor.textContent = joinedJs;
- } else {
- const script = document.createElement("script");
- script.textContent = joinedJs;
- document.body.appendChild(script);
- }
- }
-
// Inline sub-compositions (via shared function)
const trackedCompositionHosts = getBundledTrackedCompositionHosts(document);
const hostIdentityByElement = assignBundledRuntimeCompositionIds(trackedCompositionHosts);
@@ -927,7 +921,7 @@ export async function bundleToSingleHtml(
},
});
const compStyleChunks: string[] = [...subCompResult.styles];
- const compScriptChunks: string[] = [];
+ const compScriptChunks: DeferredScriptChunk[] = [];
const compExternalLinks = [...subCompResult.externalLinks];
const compVariablesByComp: Record<string, Record<string, unknown>> = {
...subCompResult.variablesByComp,
@@ -939,21 +933,24 @@ export async function bundleToSingleHtml(
continue;
}
const extSrc = scriptItem.src;
+ if (scriptItem.integrity?.trim()) {
+ ensureExternalScriptTag(document, extSrc, scriptItem);
+ seenCompScriptSrcs.add(extSrc);
+ continue;
+ }
if (seenCompScriptSrcs.has(extSrc)) continue;
seenCompScriptSrcs.add(extSrc);
if (isRelativeUrl(extSrc)) {
const jsPath = resolveEntryPath(extSrc);
const js = jsPath ? safeReadFile(jsPath) : null;
if (js != null) {
- compScriptChunks.push(js);
+ compScriptChunks.push(() =>
+ preserveLocalScriptIntegrity(document, extSrc, resolveEntryPath) ? "" : js,
+ );
continue;
}
}
- if (!queryByAttr(document, "src", extSrc, "script")) {
- const extScript = document.createElement("script");
- extScript.setAttribute("src", extSrc);
- document.body.appendChild(extScript);
- }
+ ensureExternalScriptTag(document, extSrc, scriptItem);
}
// Inline template compositions: inject <template id="X-template"> content into
@@ -1068,6 +1065,43 @@ export async function bundleToSingleHtml(
templateEl.remove();
}
+ // Inline local JS
+ const localJsChunks: string[] = [];
+ let jsAnchorPlaced = false;
+ for (const el of [...document.querySelectorAll("script[src]")]) {
+ const src = el.getAttribute("src");
+ if (!src || !isRelativeUrl(src)) continue;
+ if (preserveLocalScriptIntegrity(document, src, resolveEntryPath)) continue;
+ // Module scripts can contain static imports whose resolution is relative
+ // to the script URL. Folding their source into a classic inline script
+ // both drops module semantics and changes the import base URL.
+ if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue;
+ const jsPath = resolveEntryPath(src);
+ const js = jsPath ? safeReadFile(jsPath) : null;
+ if (js == null) continue;
+ localJsChunks.push(js);
+ if (!jsAnchorPlaced) {
+ const anchor = document.createElement("script");
+ anchor.setAttribute("data-hf-bundled-local-js", "1");
+ el.replaceWith(anchor);
+ jsAnchorPlaced = true;
+ } else {
+ el.remove();
+ }
+ }
+ if (localJsChunks.length > 0) {
+ const anchor = document.querySelector('script[data-hf-bundled-local-js="1"]');
+ const joinedJs = joinJsChunks(localJsChunks);
+ if (anchor) {
+ anchor.removeAttribute("data-hf-bundled-local-js");
+ anchor.textContent = joinedJs;
+ } else {
+ const script = document.createElement("script");
+ script.textContent = joinedJs;
+ document.body.appendChild(script);
+ }
+ }
+
// Inject external scripts from sub-compositions (e.g., Lottie CDN)
// that aren't already present in the main document.
for (const link of compExternalLinks) {
@@ -1092,7 +1126,9 @@ export async function bundleToSingleHtml(
}
if (compScriptChunks.length) {
const compScript = document.createElement("script");
- compScript.textContent = joinJsChunks(compScriptChunks);
+ compScript.textContent = joinJsChunks(
+ compScriptChunks.map((chunk) => (typeof chunk === "string" ? chunk : chunk())),
+ );
document.body.appendChild(compScript);
}
diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts
index 91d01e36b8..8d02e655bb 100644
--- a/packages/core/src/compiler/index.ts
+++ b/packages/core/src/compiler/index.ts
@@ -95,3 +95,5 @@ export {
MEDIA_RENDER_ID_ATTR,
assignMediaRenderIds,
} from "./mediaRenderIds";
+
+export { ensureExternalScriptTag } from "./externalScripts";
diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts
index 11ece33c0c..57d42ec5d9 100644
--- a/packages/core/src/compiler/inlineSubCompositions.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.ts
@@ -1,3 +1,4 @@
+import { readExternalScriptAttributes, type ExternalScriptAttributes } from "./externalScripts";
/**
* Shared sub-composition inlining logic.
*
@@ -128,7 +129,10 @@ export interface InlineSubCompositionsResult {
styles: string[];
scripts: string[];
externalScriptSrcs: string[];
- scriptItems: Array<{ kind: "inline"; content: string } | { kind: "external"; src: string }>;
+ scriptItems: Array<
+ | { kind: "inline"; content: string }
+ | ({ kind: "external"; src: string } & ExternalScriptAttributes)
+ >;
externalLinks: { href: string; rel: string; crossorigin?: string }[];
variablesByComp: Record<string, Record<string, unknown>>;
}
@@ -335,7 +339,11 @@ export function inlineSubCompositions(
if (!externalScriptSrcs.includes(externalSrc)) {
externalScriptSrcs.push(externalSrc);
}
- scriptItems.push({ kind: "external", src: externalSrc });
+ scriptItems.push({
+ kind: "external",
+ src: externalSrc,
+ ...readExternalScriptAttributes(scriptEl),
+ });
} else {
const wrappedScript = scriptCompositionId
? wrapScopedCompositionScript(
diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts
index 804b6bcc2d..edfb63a8b0 100644
--- a/packages/producer/src/services/htmlCompiler.test.ts
+++ b/packages/producer/src/services/htmlCompiler.test.ts
@@ -1,6 +1,7 @@
// fallow-ignore-file code-duplication
import { describe, expect, it, mock, beforeAll } from "bun:test";
-import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runInThisContext } from "node:vm";
@@ -321,6 +322,49 @@ describe("inlineExternalScripts", () => {
}
});
+ it("verifies raw script bytes using the strongest supported SRI metadata", async () => {
+ // Include a BOM: decoding before hashing would incorrectly reject these bytes.
+ const bytes = Buffer.from("\ufeffwindow.integrityWitness = true;");
+ const digest = (algorithm: string, data = bytes) =>
+ `${algorithm}-${createHash(algorithm).update(data).digest("base64")}`;
+ const good384 = digest("sha384");
+ const bad384 = digest("sha384", Buffer.from("changed CDN bytes"));
+ const cases = [
+ { metadata: good384, accepted: true },
+ { metadata: good384.replace("sha384", "SHA384"), accepted: true },
+ { metadata: bad384.replace("sha384", "SHA384"), accepted: false },
+ { metadata: bad384.replace("sha384", "sHa384"), accepted: false },
+ { metadata: `${digest("sha256")} ${bad384.replace("sha384", "SHA384")}`, accepted: false },
+ { metadata: bad384, accepted: false },
+ { metadata: `${digest("sha256")} ${bad384}`, accepted: false },
+ { metadata: `${bad384} ${good384}`, accepted: true },
+ { metadata: `${good384} ${digest("sha512", Buffer.from("changed"))}`, accepted: false },
+ { metadata: `${bad384} ${digest("sha512")}`, accepted: true },
+ { metadata: `\t${good384}?reserved\n`, accepted: true },
+ { metadata: good384.replaceAll("+", "-").replaceAll("/", "_"), accepted: true },
+ { metadata: "sha384-YQ==", accepted: false },
+ { metadata: "sha1-unknown malformed", accepted: true },
+ ];
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = mock(async () => new Response(bytes)) as any;
+ try {
+ for (const { metadata, accepted } of cases) {
+ const html = `<script src="https://cdn.example.com/script.js" integrity="${metadata}" crossorigin="anonymous"></script>`;
+ if (!accepted) {
+ await expect(inlineExternalScripts(html)).rejects.toThrow(
+ "Subresource integrity mismatch",
+ );
+ continue;
+ }
+ const result = await inlineExternalScripts(html);
+ expect(result).toContain("window.integrityWitness = true;");
+ expect(result).not.toContain('src="https://cdn.example.com/script.js"');
+ }
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
it("preserves non-src script attributes when inlining", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = mock(
@@ -2960,3 +3004,32 @@ describe("STUDIO-5433 — ffprobe failure includes src URL for attribution", ()
);
});
});
+
+describe("nested CDN integrity", () => {
+ it("verifies a nested pin before returning compiled HTML, including a duplicate root script", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-nested-sri-"));
+ const src = "https://cdn.example.com/pinned.js";
+ const bytes = "window.nestedIntegrityWitness = true;";
+ const integrity = `sha384-${createHash("sha384").update(bytes).digest("base64")}`;
+ writeFileSync(
+ join(dir, "index.html"),
+ `<html><head><script src="${src}"></script></head><body><div data-composition-id="root" data-width="320" data-height="180" data-duration="1"><div data-composition-id="child" data-composition-src="child.html"></div></div></body></html>`,
+ );
+ writeFileSync(
+ join(dir, "child.html"),
+ `<html><head><script src="${src}" integrity="${integrity}" crossorigin="anonymous"></script></head><body><div data-composition-id="child" data-width="320" data-height="180" data-duration="1">Child</div></body></html>`,
+ );
+ const originalFetch = globalThis.fetch;
+ try {
+ globalThis.fetch = mock(async () => new Response(bytes)) as any;
+ await expect(compileForRender(dir, join(dir, "index.html"), dir)).resolves.toBeDefined();
+ globalThis.fetch = mock(async () => new Response("window.compromised = true;")) as any;
+ await expect(compileForRender(dir, join(dir, "index.html"), dir)).rejects.toThrow(
+ "Subresource integrity mismatch",
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 004e443ce1..e1180d86d8 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -10,6 +10,7 @@
* recursively extracting nested media from sub-sub-compositions.
*/
+import { createHash } from "node:crypto";
import { createReadStream, existsSync, mkdirSync, readFileSync } from "fs";
import { join, dirname, resolve, basename, relative } from "path";
import { parseHTML } from "linkedom";
@@ -38,6 +39,7 @@ import {
type BundledHostCompositionIdentity,
buildVariablesByCompScript,
inlineSubCompositions as inlineSubCompositionsShared,
+ ensureExternalScriptTag,
prepareFlattenedInnerRoot,
emitRootCompositionVariableStyles,
readDeclaredDefaults,
@@ -1061,19 +1063,9 @@ function inlineSubCompositions(
// Inject external CDN scripts before inline scripts so plugins (e.g.
// TextPlugin, ScrollTrigger) are registered before composition code runs.
// Deduplicate against scripts already present in the document.
- if (result.externalScriptSrcs.length && body) {
- const existingScriptSrcs = new Set(
- Array.from(document.querySelectorAll("script[src]")).map((el: Element) =>
- (el.getAttribute("src") || "").trim(),
- ),
- );
- for (const src of result.externalScriptSrcs) {
- if (!existingScriptSrcs.has(src)) {
- const scriptEl = document.createElement("script");
- scriptEl.setAttribute("src", src);
- body.appendChild(scriptEl);
- existingScriptSrcs.add(src);
- }
+ if (body) {
+ for (const item of result.scriptItems) {
+ if (item.kind === "external") ensureExternalScriptTag(document, item.src, item);
}
}
@@ -1161,6 +1153,27 @@ function injectTextRenderingRule(html: string): string {
return document.toString();
}
+class ScriptIntegrityError extends Error {}
+
+/** Match SRI's strongest supported digest before decoding or rewriting script bytes. */
+function matchesScriptIntegrity(bytes: Uint8Array, metadata: string): boolean {
+ const hashes = [
+ ...metadata.matchAll(
+ /(?:^|[\t\n\f\r ])(sha256|sha384|sha512)-([A-Za-z0-9+/_-]+={0,2})(?:\?[\x21-\x7e]*)?(?=$|[\t\n\f\r ])/gi,
+ ),
+ ];
+ const strongest = ["sha512", "sha384", "sha256"].find((alg) =>
+ hashes.some((hash) => hash[1]?.toLowerCase() === alg),
+ );
+ // Browsers ignore metadata containing no supported, syntactically valid hash.
+ if (!strongest) return true;
+ const actual = createHash(strongest).update(bytes).digest();
+ return hashes.some(
+ (hash) =>
+ hash[1]?.toLowerCase() === strongest && actual.equals(Buffer.from(hash[2]!, "base64")),
+ );
+}
+
/**
* Download external CDN scripts and inline them into the HTML so rendering
* works without network access (Docker, CI, restricted environments).
@@ -1182,12 +1195,16 @@ export async function inlineExternalScripts(html: string): Promise<string> {
if (externalScripts.length === 0) return html;
const downloads = await Promise.allSettled(
- externalScripts.map(async ({ src }) => {
+ externalScripts.map(async ({ el, src }) => {
const response = await fetch(src, {
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
- return { src, text: await response.text() };
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ if (!matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "")) {
+ throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
+ }
+ return { src, text: new TextDecoder().decode(bytes) };
}),
);
@@ -1208,6 +1225,9 @@ export async function inlineExternalScripts(html: string): Promise<string> {
el.replaceWith(inlineScript);
defaultLogger.info(`[Compiler] Inlined CDN script: ${src}`);
} else {
+ // A verified mismatch must never fall back to an executable external tag:
+ // browser support for integrity metadata (including casing) can differ.
+ if (download.reason instanceof ScriptIntegrityError) throw download.reason;
defaultLogger.warn(
`[Compiler] WARNING: Failed to download CDN script: ${src} — ${download.reason}. ` +
`The render may fail if this script is required (e.g. GSAP). ` +
diff --git a/packages/producer/tests/distributed/css-var-fonts/src/index.html b/packages/producer/tests/distributed/css-var-fonts/src/index.html
index 9534fb1ea8..c54bf722a9 100644
--- a/packages/producer/tests/distributed/css-var-fonts/src/index.html
+++ b/packages/producer/tests/distributed/css-var-fonts/src/index.html
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>CSS var() font-family regression fixture</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js" integrity="sha384-d+vyQ0dYcymoP8ndq2hW7FGC50nqGdXUEgoOUGxbbkAJwZqL7h+jKN0GGgn9hFDS" crossorigin="anonymous"></script>
<style>
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;700&family=Montserrat:wght@400;700;900&display=swap");
diff --git a/packages/producer/tests/distributed/static-volume-future-set/src/index.html b/packages/producer/tests/distributed/static-volume-future-set/src/index.html
index ed07f0f8ce..fad1d97c86 100644
--- a/packages/producer/tests/distributed/static-volume-future-set/src/index.html
+++ b/packages/producer/tests/distributed/static-volume-future-set/src/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<title>Static volume with future nested set</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js" integrity="sha384-d+vyQ0dYcymoP8ndq2hW7FGC50nqGdXUEgoOUGxbbkAJwZqL7h+jKN0GGgn9hFDS" crossorigin="anonymous"></script>
<style>
html,
body {
diff --git a/packages/producer/tests/distributed/three-boundary-deferred/src/index.html b/packages/producer/tests/distributed/three-boundary-deferred/src/index.html
index 65a290a8a6..2f4912a9dd 100644
--- a/packages/producer/tests/distributed/three-boundary-deferred/src/index.html
+++ b/packages/producer/tests/distributed/three-boundary-deferred/src/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<title>chunk-boundary: Three.js (setTimeout-deferred)</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js" integrity="sha384-d+vyQ0dYcymoP8ndq2hW7FGC50nqGdXUEgoOUGxbbkAJwZqL7h+jKN0GGgn9hFDS" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<style>
body,
diff --git a/packages/producer/tests/distributed/webm-vp9/src/index.html b/packages/producer/tests/distributed/webm-vp9/src/index.html
index 03b9b25ebe..61bce4e4aa 100644
--- a/packages/producer/tests/distributed/webm-vp9/src/index.html
+++ b/packages/producer/tests/distributed/webm-vp9/src/index.html
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>webm VP9 distributed fixture</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js" integrity="sha384-d+vyQ0dYcymoP8ndq2hW7FGC50nqGdXUEgoOUGxbbkAJwZqL7h+jKN0GGgn9hFDS" crossorigin="anonymous"></script>
<style>
@import url("https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap");
diff --git a/packages/producer/tests/fast-capture-gsap/src/index.html b/packages/producer/tests/fast-capture-gsap/src/index.html
index 454b8b3f88..5cf1448650 100644
--- a/packages/producer/tests/fast-capture-gsap/src/index.html
+++ b/packages/producer/tests/fast-capture-gsap/src/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1080, height=1080">
- <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js" integrity="sha384-d+vyQ0dYcymoP8ndq2hW7FGC50nqGdXUEgoOUGxbbkAJwZqL7h+jKN0GGgn9hFDS" crossorigin="anonymous"></script>
<style>
body { margin: 0; background: #0d1117; width: 1080px; height: 1080px; overflow: hidden; }
#box {
diff --git a/registry/blocks/liquid-glass-context-menu/liquid-glass-context-menu.html b/registry/blocks/liquid-glass-context-menu/liquid-glass-context-menu.html
index a3fd2c0f5d..441e9f1b16 100644
--- a/registry/blocks/liquid-glass-context-menu/liquid-glass-context-menu.html
+++ b/registry/blocks/liquid-glass-context-menu/liquid-glass-context-menu.html
@@ -5,7 +5,11 @@
<meta name="viewport" content="width=1920, height=1080" />
<title>Liquid Glass Context Menu</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <script
+ src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"
+ integrity="sha384-CI3ELBVUz9XQO+97x6nwMDPosPR5XvsxW2ua7N1Xeygeh1IxtgqtCkGfQY9WWdHu"
+ crossorigin="anonymous"
+ ></script>
<script src="lib/liquid-glass.iife.js"></script>
<style>
*,
diff --git a/registry/blocks/liquid-glass-media-controls/liquid-glass-media-controls.html b/registry/blocks/liquid-glass-media-controls/liquid-glass-media-controls.html
index c5fb811d6e..673516bb3a 100644
--- a/registry/blocks/liquid-glass-media-controls/liquid-glass-media-controls.html
+++ b/registry/blocks/liquid-glass-media-controls/liquid-glass-media-controls.html
@@ -5,7 +5,11 @@
<meta name="viewport" content="width=1920, height=1080" />
<title>Liquid Glass Media Controls</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <script
+ src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"
+ integrity="sha384-CI3ELBVUz9XQO+97x6nwMDPosPR5XvsxW2ua7N1Xeygeh1IxtgqtCkGfQY9WWdHu"
+ crossorigin="anonymous"
+ ></script>
<script src="lib/liquid-glass.iife.js"></script>
<style>
*,
diff --git a/registry/blocks/liquid-glass-notification/liquid-glass-notification.html b/registry/blocks/liquid-glass-notification/liquid-glass-notification.html
index 85f968d54d..541dfd06e4 100644
--- a/registry/blocks/liquid-glass-notification/liquid-glass-notification.html
+++ b/registry/blocks/liquid-glass-notification/liquid-glass-notification.html
@@ -4,7 +4,11 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <script
+ src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"
+ integrity="sha384-CI3ELBVUz9XQO+97x6nwMDPosPR5XvsxW2ua7N1Xeygeh1IxtgqtCkGfQY9WWdHu"
+ crossorigin="anonymous"
+ ></script>
<script src="lib/liquid-glass.iife.js"></script>
<style>
* {
diff --git a/registry/blocks/liquid-glass-widgets/liquid-glass-widgets.html b/registry/blocks/liquid-glass-widgets/liquid-glass-widgets.html
index de6ac24be8..f6352dc38a 100644
--- a/registry/blocks/liquid-glass-widgets/liquid-glass-widgets.html
+++ b/registry/blocks/liquid-glass-widgets/liquid-glass-widgets.html
@@ -5,7 +5,11 @@
<meta name="viewport" content="width=1920, height=1080" />
<title>Liquid Glass Widgets</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <script
+ src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"
+ integrity="sha384-CI3ELBVUz9XQO+97x6nwMDPosPR5XvsxW2ua7N1Xeygeh1IxtgqtCkGfQY9WWdHu"
+ crossorigin="anonymous"
+ ></script>
<script src="lib/liquid-glass.iife.js"></script>
<style>
*,