diff --git a/apps/web/src/themeCss.browser.test.ts b/apps/web/src/themeCss.browser.test.ts index 28fccece4c5c5..20f0d9f47ac64 100644 --- a/apps/web/src/themeCss.browser.test.ts +++ b/apps/web/src/themeCss.browser.test.ts @@ -24,6 +24,9 @@ it("applies theme CSS and drops every rule that would load a remote file", () => mask-image: v\\61r(--none, u\\72l(https://example.com/e)); @media (min-width: 0px) { cursor: url(https://example.com/c), auto; } } + [data-theme-css-probe] { background: var(--none, url(https://example.com/h)); } + [data-theme-css-probe] { mask: var(--none, url(https://example.com/k)); mask-size: auto; } + [data-workspace-area="conversation"] { --toggle: ; background: var(--theme-background-image) center / cover no-repeat; } `); const style = getComputedStyle(probe); @@ -36,8 +39,28 @@ it("applies theme CSS and drops every rule that would load a remote file", () => Array.from(sheet.cssRules, (rule) => rule.cssText), ); expect(kept.join("\n")).not.toContain("example.com"); + expect(kept.join("\n")).toContain( + "background: var(--theme-background-image) center / cover no-repeat;", + ); + expect(kept.join("\n")).toContain("--toggle:"); expect(style.cursor).toBe("auto"); + // Overriding one longhand hides a var() shorthand's text; a fetch in another rule must not drop it. + applyThemeCss(` + [data-theme-css-probe] { + --edge: 4px solid red; border: var(--edge); border-left-width: 0px; + background: var(--none, linear-gradient(red, blue)); background-color: red; + } + .unused { cursor: url(https://example.com/x), auto; } + `); + expect(style.borderTopWidth).toBe("4px"); + expect(style.backgroundImage).toContain("linear-gradient"); + + applyThemeCss(` + [data-theme-css-probe] { list-style: env(t3-none, url(https://example.com/l)); list-style-type: disc; } + `); + expect(style.listStyleImage).toBe("none"); + applyThemeCss(undefined); expect(getComputedStyle(probe).color).not.toBe("rgb(1, 2, 3)"); }); diff --git a/apps/web/src/themeCss.ts b/apps/web/src/themeCss.ts index 437182ce6a191..500e0ecb29fd8 100644 --- a/apps/web/src/themeCss.ts +++ b/apps/web/src/themeCss.ts @@ -1,4 +1,4 @@ -import { themeCssValueFetches } from "@t3tools/shared/themeCss"; +import { themeCssValueFetches, themeCssVarBlockFetches } from "@t3tools/shared/themeCss"; // Theme CSS comes from imported files and from agents, so it must not fetch: a // url() on an attribute selector can send what is on screen to another host. @@ -14,11 +14,23 @@ type RuleParent = Pick; const isRuleParent = (rule: CSSRule): rule is CSSRule & RuleParent => "cssRules" in rule && "deleteRule" in rule && !(rule instanceof CSSKeyframesRule); -function stripDeclarations(rule: CSSRule): boolean { +function stripDeclarations(rule: CSSRule, varSourceFetches: boolean): boolean { if (!("style" in rule) || !(rule.style instanceof CSSStyleDeclaration)) return false; + const pending: string[] = []; for (let item = rule.style.length - 1; item >= 0; item--) { const property = rule.style.item(item); - if (themeCssValueFetches(rule.style.getPropertyValue(property))) { + const value = rule.style.getPropertyValue(property); + // An empty custom property (`--on: ;`) is a real value, not a pending shorthand. + if (value === "" && !property.startsWith("--")) pending.push(property); + else if (themeCssValueFetches(value)) rule.style.removeProperty(property); + } + // A shorthand with var() leaves each longhand reading "". cssText shows the shorthand whole, + // or, once another declaration overrides one longhand, lists the rest bare with its text hidden. + // Only the theme's source still has that text, so a bare one goes when a var() block there fetches. + const text = rule.style.cssText; + const fetches = themeCssValueFetches(text); + for (const property of pending) { + if (fetches || (varSourceFetches && new RegExp(`(?:^|; )${property}:`).test(text))) { rule.style.removeProperty(property); } } @@ -26,15 +38,15 @@ function stripDeclarations(rule: CSSRule): boolean { } /** Keeps only rule shapes it can check, so a new at-rule that fetches is dropped by default. */ -function stripFetches(parent: RuleParent): void { +function stripFetches(parent: RuleParent, varSourceFetches: boolean): void { for (let index = parent.cssRules.length - 1; index >= 0; index--) { const rule = parent.cssRules[index]; if (!rule) continue; - const hasStyle = stripDeclarations(rule); + const hasStyle = stripDeclarations(rule, varSourceFetches); if (rule instanceof CSSKeyframesRule) { - for (const frame of rule.cssRules) stripDeclarations(frame); + for (const frame of rule.cssRules) stripDeclarations(frame, varSourceFetches); } else if (isRuleParent(rule)) { - stripFetches(rule); + stripFetches(rule, varSourceFetches); } else if (rule instanceof CSSPropertyRule) { // A registered property's initial value is used wherever var() reads it. if (themeCssValueFetches(rule.initialValue ?? "")) parent.deleteRule(index); @@ -60,5 +72,5 @@ export function applyThemeCss(css: string | undefined): void { document.adoptedStyleSheets = [...document.adoptedStyleSheets, themeSheet]; } themeSheet.replaceSync(next); - stripFetches(themeSheet); + stripFetches(themeSheet, themeCssVarBlockFetches(next)); } diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index 38cc33a793dbd..c63951d47ce77 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { themeCssLoadsRemoteFiles, themeCssValueFetches } from "./themeCss.ts"; +import { + themeCssLoadsRemoteFiles, + themeCssValueFetches, + themeCssVarBlockFetches, +} from "./themeCss.ts"; // %23 decodes to # inside the SVG, so url(%23g) names its own gradient. const SVG_WITH_OWN_GRADIENT = @@ -59,3 +63,17 @@ describe("themeCssLoadsRemoteFiles", () => { ).toBe(false); }); }); + +describe("themeCssVarBlockFetches", () => { + it.each([ + ["a { border: var(--edge); } b { cursor: url(https://e.com/x), auto; }", false], + ["a { mask: var(--none, url(https://e.com/k)); mask-size: auto; }", true], + ["a { background: env(t3-none, url(https://e.com/l)); background-color: red; }", true], + ['a { background: var(--none, "{" url(https://e.com/k)); }', true], + ["a { background: var(--none, { } url(https://e.com/k)); }", true], + ["a { background: v\\61r(--none, url(https://e.com/k)); }", true], + ["a { background: var(--none, url(data:image/png;base64,AA)); }", false], + ])("%s -> %s", (css, fetches) => { + expect(themeCssVarBlockFetches(css)).toBe(fetches); + }); +}); diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index 9668040f97be4..e017eaeb65b99 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -45,6 +45,33 @@ export function themeCssValueFetches(value: string): boolean { return code.includes("\\") || fetchesOutsideStrings(code); } +const SUBSTITUTES = /(?:var|env|attr|if)\(/i; + +/** + * Whether a declaration block that uses var(), env(), attr() or if(), or holds an escape, can + * load a remote file. Once a later declaration overrides one longhand, browsers hide such a + * shorthand's text, so only the source shows it. Blocks split at braces outside parentheses, + * after strings are removed. + */ +export function themeCssVarBlockFetches(css: string): boolean { + const code = withoutStrings(css, false); + let depth = 0; + let start = 0; + for (let index = 0; index <= code.length; index++) { + const char = code[index]; + if (char === "(") depth++; + else if (char === ")") depth = Math.max(0, depth - 1); + else if (index === code.length || (depth === 0 && (char === "{" || char === "}"))) { + const block = code.slice(start, index); + if (block.includes("\\") || (SUBSTITUTES.test(block) && fetchesOutsideStrings(block))) { + return true; + } + start = index + 1; + } + } + return false; +} + /** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */ export function themeCssLoadsRemoteFiles(css: string): boolean { const code = withoutStrings(css, true);