Skip to content

Commit ff749b8

Browse files
authored
fix(security): verify CDN script integrity before inlining (#3822)
* fix(security): verify CDN script integrity before inlining * fix(producer): normalize SRI algorithm case * fix(producer): abort compilation on integrity mismatch * fix(compiler): preserve nested script integrity requirements * fix(compiler): defer local inlining until integrity is known
1 parent 8d80530 commit ff749b8

16 files changed

Lines changed: 380 additions & 80 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
export interface ExternalScriptAttributes {
2+
integrity?: string;
3+
crossorigin?: string;
4+
}
5+
6+
export function readExternalScriptAttributes(el: Element): ExternalScriptAttributes {
7+
const attributes: ExternalScriptAttributes = {};
8+
if (el.hasAttribute("integrity")) attributes.integrity = el.getAttribute("integrity") || "";
9+
if (el.hasAttribute("crossorigin")) attributes.crossorigin = el.getAttribute("crossorigin") || "";
10+
return attributes;
11+
}
12+
13+
/** Deduplicate scripts without discarding a nested composition's integrity requirement. */
14+
export function ensureExternalScriptTag(
15+
doc: Document,
16+
src: string,
17+
attributes: ExternalScriptAttributes = {},
18+
): void {
19+
const existing = [...doc.querySelectorAll("script[src]")].filter(
20+
(el) => el.getAttribute("src")?.trim() === src,
21+
);
22+
const requirements = new Set(
23+
[attributes.integrity, ...existing.map((el) => el.getAttribute("integrity"))]
24+
.map((value) =>
25+
value
26+
?.trim()
27+
.replace(
28+
/(^|[\t\n\f\r ])(sha256|sha384|sha512)-/gi,
29+
(_match, space: string, algorithm: string) => `${space}${algorithm.toLowerCase()}-`,
30+
),
31+
)
32+
.filter((value): value is string => Boolean(value)),
33+
);
34+
if (requirements.size > 1) {
35+
throw new Error(`Conflicting script integrity requirements for ${src}`);
36+
}
37+
const integrity = [...requirements][0];
38+
const elements = existing.length ? existing : [doc.createElement("script")];
39+
for (const el of elements) {
40+
if (integrity) el.setAttribute("integrity", integrity);
41+
if (attributes.crossorigin !== undefined)
42+
el.setAttribute("crossorigin", attributes.crossorigin);
43+
}
44+
if (!existing.length) {
45+
const el = elements[0]!;
46+
el.setAttribute("src", src);
47+
doc.body.appendChild(el);
48+
}
49+
}

‎packages/core/src/compiler/htmlBundler.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { join } from "node:path";
55
import { parseHTML } from "linkedom";
66
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
77
import { bundleToSingleHtml, emitRootCompositionVariableStyles } from "./htmlBundler";
8+
import { ensureExternalScriptTag } from "./externalScripts";
89
import { resetUnknownEnumWarnings } from "../runtime/getVariables";
910
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
1011
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
@@ -1629,3 +1630,98 @@ describe("emitRootCompositionVariableStyles — <style> breakout", () => {
16291630
expect(css).toContain("#ff0066");
16301631
});
16311632
});
1633+
1634+
describe("nested script integrity", () => {
1635+
it("preserves and deduplicates a nested pin even when the root already loads that URL", async () => {
1636+
const src = "https://cdn.example.com/pinned.js";
1637+
const dir = makeTempProject({
1638+
"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>`,
1639+
"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>`,
1640+
});
1641+
try {
1642+
const bundled = await bundleToSingleHtml(dir);
1643+
const { document } = parseHTML(bundled);
1644+
const scripts = [...document.querySelectorAll("script[src]")].filter(
1645+
(el) => el.getAttribute("src") === src,
1646+
);
1647+
expect(scripts).toHaveLength(1);
1648+
expect(scripts[0]?.getAttribute("integrity")).toBe("sha384-YQ==");
1649+
expect(scripts[0]?.getAttribute("crossorigin")).toBe("anonymous");
1650+
} finally {
1651+
rmSync(dir, { recursive: true, force: true });
1652+
}
1653+
});
1654+
});
1655+
1656+
it("preserves every duplicate script pin and rejects conflicting requirements", () => {
1657+
const { document } = parseHTML(
1658+
'<html><body><script src="https://cdn.example.com/a.js"></script><script src="https://cdn.example.com/a.js"></script></body></html>',
1659+
);
1660+
const src = "https://cdn.example.com/a.js";
1661+
ensureExternalScriptTag(document, src, { integrity: "sha384-YQ==", crossorigin: "anonymous" });
1662+
ensureExternalScriptTag(document, src);
1663+
for (const el of document.querySelectorAll("script")) {
1664+
expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
1665+
expect(el.getAttribute("crossorigin")).toBe("anonymous");
1666+
}
1667+
expect(() => ensureExternalScriptTag(document, src, { integrity: "sha384-Yg==" })).toThrow(
1668+
"Conflicting script integrity",
1669+
);
1670+
});
1671+
1672+
it("keeps protected local scripts external when hoisting an inline template", async () => {
1673+
const dir = makeTempProject({
1674+
"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>`,
1675+
"local.js": "window.localPinWitness = true;",
1676+
});
1677+
try {
1678+
const bundled = await bundleToSingleHtml(dir);
1679+
const { document } = parseHTML(bundled);
1680+
const script = document.querySelector('script[src="local.js"]');
1681+
expect(script?.getAttribute("integrity")).toBe("sha384-YQ==");
1682+
expect(script?.getAttribute("crossorigin")).toBe("anonymous");
1683+
expect(bundled).not.toContain("window.localPinWitness = true;");
1684+
} finally {
1685+
rmSync(dir, { recursive: true, force: true });
1686+
}
1687+
});
1688+
1689+
it.each(["root", "sibling", "template"])(
1690+
"does not inline local bytes before a later %s integrity requirement",
1691+
async (placement) => {
1692+
const unpinned = '<script src="local.js"></script>';
1693+
const pinned =
1694+
'<script src="./local.js" integrity="sHa384-YQ==" crossorigin="anonymous"></script>';
1695+
const rootScript = placement === "root" ? unpinned : "";
1696+
const first =
1697+
placement === "sibling"
1698+
? '<div data-composition-id="first" data-composition-src="first.html"></div>'
1699+
: "";
1700+
const templates =
1701+
placement === "template"
1702+
? `<template id="first-template"><div data-composition-id="first">${unpinned}</div></template><template id="child-template"><div data-composition-id="child">${pinned}</div></template>`
1703+
: "";
1704+
const children =
1705+
placement === "template"
1706+
? '<div data-composition-id="first" data-start="0" data-duration="1"></div><div data-composition-id="child" data-start="0" data-duration="1"></div>'
1707+
: `${first}<div data-composition-id="child" data-composition-src="child.html"></div>`;
1708+
const dir = makeTempProject({
1709+
"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>`,
1710+
"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>`,
1711+
"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>`,
1712+
"local.js": "window.alteredLocalBytes = true;",
1713+
});
1714+
try {
1715+
const bundled = await bundleToSingleHtml(dir);
1716+
expect(bundled).not.toContain("window.alteredLocalBytes = true;");
1717+
const { document } = parseHTML(bundled);
1718+
const local = [...document.querySelectorAll("script[src]")].filter((el) =>
1719+
/local\.js$/.test(el.getAttribute("src") || ""),
1720+
);
1721+
expect(local.length).toBeGreaterThan(0);
1722+
for (const el of local) expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
1723+
} finally {
1724+
rmSync(dir, { recursive: true, force: true });
1725+
}
1726+
},
1727+
);

‎packages/core/src/compiler/htmlBundler.ts‎

Lines changed: 89 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import {
2+
ensureExternalScriptTag,
3+
readExternalScriptAttributes,
4+
type ExternalScriptAttributes,
5+
} from "./externalScripts";
16
import { markFlattenedInnerRoot } from "../runtime/flattenedRoot";
27
export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";
38
import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";
@@ -722,31 +727,55 @@ export interface BundleOptions {
722727
* - Inlines small textual assets as data URLs
723728
*/
724729

725-
function ensureExternalScriptTag(doc: Document, src: string): void {
726-
if (queryByAttr(doc, "src", src, "script")) return;
727-
const el = doc.createElement("script");
728-
el.setAttribute("src", src);
729-
doc.body.appendChild(el);
730+
type DeferredScriptChunk = string | (() => string);
731+
732+
function preserveLocalScriptIntegrity(
733+
doc: Document,
734+
src: string,
735+
resolvePath: (src: string) => string | null,
736+
): boolean {
737+
const path = resolvePath(src);
738+
if (!path) return false;
739+
const pinned = [...doc.querySelectorAll("script[src][integrity]")].filter((el) => {
740+
const candidate = el.getAttribute("src") || "";
741+
return (
742+
isRelativeUrl(candidate) &&
743+
resolvePath(candidate) === path &&
744+
el.getAttribute("integrity")?.trim()
745+
);
746+
});
747+
for (const el of pinned) ensureExternalScriptTag(doc, src, readExternalScriptAttributes(el));
748+
return pinned.length > 0;
730749
}
731750

732751
function hoistExternalScript(
733752
src: string,
734753
projectDir: string,
735754
doc: Document,
736755
seenSrcs: Set<string>,
737-
chunks: string[],
756+
chunks: DeferredScriptChunk[],
757+
attributes: ExternalScriptAttributes,
738758
): void {
759+
if (attributes.integrity?.trim()) {
760+
ensureExternalScriptTag(doc, src, attributes);
761+
seenSrcs.add(src);
762+
return;
763+
}
739764
if (seenSrcs.has(src)) return;
740765
seenSrcs.add(src);
741766
if (!isNonRelativeUrl(src) && !isAbsolute(src)) {
742767
const jsPath = resolveWithinProject(projectDir, src);
743768
const js = jsPath ? safeReadFile(jsPath) : null;
744769
if (js != null) {
745-
chunks.push(js);
770+
chunks.push(() =>
771+
preserveLocalScriptIntegrity(doc, src, (value) => resolveWithinProject(projectDir, value))
772+
? ""
773+
: js,
774+
);
746775
return;
747776
}
748777
}
749-
ensureExternalScriptTag(doc, src);
778+
ensureExternalScriptTag(doc, src, attributes);
750779
}
751780

752781
function hoistCompositionScripts(
@@ -759,7 +788,7 @@ function hoistCompositionScripts(
759788
runtimeCompId: string | undefined;
760789
authoredRootId: string | undefined;
761790
seenCompScriptSrcs: Set<string>;
762-
compScriptChunks: string[];
791+
compScriptChunks: DeferredScriptChunk[];
763792
},
764793
): void {
765794
for (const scriptEl of [...container.querySelectorAll("script")]) {
@@ -771,6 +800,7 @@ function hoistCompositionScripts(
771800
opts.document,
772801
opts.seenCompScriptSrcs,
773802
opts.compScriptChunks,
803+
readExternalScriptAttributes(scriptEl),
774804
);
775805
} else {
776806
opts.compScriptChunks.push(
@@ -857,42 +887,6 @@ export async function bundleToSingleHtml(
857887
}
858888
}
859889

860-
// Inline local JS
861-
const localJsChunks: string[] = [];
862-
let jsAnchorPlaced = false;
863-
for (const el of [...document.querySelectorAll("script[src]")]) {
864-
const src = el.getAttribute("src");
865-
if (!src || !isRelativeUrl(src)) continue;
866-
// Module scripts can contain static imports whose resolution is relative
867-
// to the script URL. Folding their source into a classic inline script
868-
// both drops module semantics and changes the import base URL.
869-
if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue;
870-
const jsPath = resolveEntryPath(src);
871-
const js = jsPath ? safeReadFile(jsPath) : null;
872-
if (js == null) continue;
873-
localJsChunks.push(js);
874-
if (!jsAnchorPlaced) {
875-
const anchor = document.createElement("script");
876-
anchor.setAttribute("data-hf-bundled-local-js", "1");
877-
el.replaceWith(anchor);
878-
jsAnchorPlaced = true;
879-
} else {
880-
el.remove();
881-
}
882-
}
883-
if (localJsChunks.length > 0) {
884-
const anchor = document.querySelector('script[data-hf-bundled-local-js="1"]');
885-
const joinedJs = joinJsChunks(localJsChunks);
886-
if (anchor) {
887-
anchor.removeAttribute("data-hf-bundled-local-js");
888-
anchor.textContent = joinedJs;
889-
} else {
890-
const script = document.createElement("script");
891-
script.textContent = joinedJs;
892-
document.body.appendChild(script);
893-
}
894-
}
895-
896890
// Inline sub-compositions (via shared function)
897891
const trackedCompositionHosts = getBundledTrackedCompositionHosts(document);
898892
const hostIdentityByElement = assignBundledRuntimeCompositionIds(trackedCompositionHosts);
@@ -927,7 +921,7 @@ export async function bundleToSingleHtml(
927921
},
928922
});
929923
const compStyleChunks: string[] = [...subCompResult.styles];
930-
const compScriptChunks: string[] = [];
924+
const compScriptChunks: DeferredScriptChunk[] = [];
931925
const compExternalLinks = [...subCompResult.externalLinks];
932926
const compVariablesByComp: Record<string, Record<string, unknown>> = {
933927
...subCompResult.variablesByComp,
@@ -939,21 +933,24 @@ export async function bundleToSingleHtml(
939933
continue;
940934
}
941935
const extSrc = scriptItem.src;
936+
if (scriptItem.integrity?.trim()) {
937+
ensureExternalScriptTag(document, extSrc, scriptItem);
938+
seenCompScriptSrcs.add(extSrc);
939+
continue;
940+
}
942941
if (seenCompScriptSrcs.has(extSrc)) continue;
943942
seenCompScriptSrcs.add(extSrc);
944943
if (isRelativeUrl(extSrc)) {
945944
const jsPath = resolveEntryPath(extSrc);
946945
const js = jsPath ? safeReadFile(jsPath) : null;
947946
if (js != null) {
948-
compScriptChunks.push(js);
947+
compScriptChunks.push(() =>
948+
preserveLocalScriptIntegrity(document, extSrc, resolveEntryPath) ? "" : js,
949+
);
949950
continue;
950951
}
951952
}
952-
if (!queryByAttr(document, "src", extSrc, "script")) {
953-
const extScript = document.createElement("script");
954-
extScript.setAttribute("src", extSrc);
955-
document.body.appendChild(extScript);
956-
}
953+
ensureExternalScriptTag(document, extSrc, scriptItem);
957954
}
958955

959956
// Inline template compositions: inject <template id="X-template"> content into
@@ -1068,6 +1065,43 @@ export async function bundleToSingleHtml(
10681065
templateEl.remove();
10691066
}
10701067

1068+
// Inline local JS
1069+
const localJsChunks: string[] = [];
1070+
let jsAnchorPlaced = false;
1071+
for (const el of [...document.querySelectorAll("script[src]")]) {
1072+
const src = el.getAttribute("src");
1073+
if (!src || !isRelativeUrl(src)) continue;
1074+
if (preserveLocalScriptIntegrity(document, src, resolveEntryPath)) continue;
1075+
// Module scripts can contain static imports whose resolution is relative
1076+
// to the script URL. Folding their source into a classic inline script
1077+
// both drops module semantics and changes the import base URL.
1078+
if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue;
1079+
const jsPath = resolveEntryPath(src);
1080+
const js = jsPath ? safeReadFile(jsPath) : null;
1081+
if (js == null) continue;
1082+
localJsChunks.push(js);
1083+
if (!jsAnchorPlaced) {
1084+
const anchor = document.createElement("script");
1085+
anchor.setAttribute("data-hf-bundled-local-js", "1");
1086+
el.replaceWith(anchor);
1087+
jsAnchorPlaced = true;
1088+
} else {
1089+
el.remove();
1090+
}
1091+
}
1092+
if (localJsChunks.length > 0) {
1093+
const anchor = document.querySelector('script[data-hf-bundled-local-js="1"]');
1094+
const joinedJs = joinJsChunks(localJsChunks);
1095+
if (anchor) {
1096+
anchor.removeAttribute("data-hf-bundled-local-js");
1097+
anchor.textContent = joinedJs;
1098+
} else {
1099+
const script = document.createElement("script");
1100+
script.textContent = joinedJs;
1101+
document.body.appendChild(script);
1102+
}
1103+
}
1104+
10711105
// Inject external scripts from sub-compositions (e.g., Lottie CDN)
10721106
// that aren't already present in the main document.
10731107
for (const link of compExternalLinks) {
@@ -1092,7 +1126,9 @@ export async function bundleToSingleHtml(
10921126
}
10931127
if (compScriptChunks.length) {
10941128
const compScript = document.createElement("script");
1095-
compScript.textContent = joinJsChunks(compScriptChunks);
1129+
compScript.textContent = joinJsChunks(
1130+
compScriptChunks.map((chunk) => (typeof chunk === "string" ? chunk : chunk())),
1131+
);
10961132
document.body.appendChild(compScript);
10971133
}
10981134

‎packages/core/src/compiler/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,5 @@ export {
9595
MEDIA_RENDER_ID_ATTR,
9696
assignMediaRenderIds,
9797
} from "./mediaRenderIds";
98+
99+
export { ensureExternalScriptTag } from "./externalScripts";

0 commit comments

Comments
 (0)