Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 38 additions & 3 deletions apps/web/src/themeCss.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)); }
@keyframes shorthand { to { border-image: var(--none, url(https://example.com/i)); } }
[data-workspace-area="conversation"] { background: var(--theme-background-image) center / cover no-repeat; }
`);

const style = getComputedStyle(probe);
Expand All @@ -32,12 +35,44 @@ it("applies theme CSS and drops every rule that would load a remote file", () =>
expect(style.listStyleImage).toBe("none");
expect(style.borderImageSource).toBe("none");
expect(style.maskImage).toBe("none");
const kept = document.adoptedStyleSheets.flatMap((sheet) =>
Array.from(sheet.cssRules, (rule) => rule.cssText),
const themeCssText = () =>
document.adoptedStyleSheets
.flatMap((sheet) => Array.from(sheet.cssRules, (rule) => rule.cssText))
.join("\n");
expect(themeCssText()).not.toContain("example.com");
expect(themeCssText()).toContain(
"background: var(--theme-background-image) center / cover no-repeat;",
);
expect(kept.join("\n")).not.toContain("example.com");
expect(style.cursor).toBe("auto");

// A later longhand hides the shorthand's text from CSSOM, and the browser still loads its url().
applyThemeCss(`
[data-theme-css-probe] { mask: v\\61r(--none, u\\72l(https://example.com/k)); mask-size: auto; }
[data-theme-css-probe] { list-style: env(t3-none, url(https://example.com/l)); list-style-type: disc; }
@keyframes hidden { to { background: var(--none, url(https://example.com/m)); background-color: red; } }
[data-theme-css-probe] { border-image: var(--none, url(https://example.com/n)); border-image-slice: 1; }
[data-theme-css-probe] { animation: hidden 1s forwards paused; animation-delay: -1s; }
`);
expect(style.maskImage).toBe("none");
expect(style.listStyleImage).toBe("none");
expect(style.borderImageSource).toBe("none");
expect(style.backgroundImage).toBe("none");
expect(style.backgroundColor).toBe("rgb(255, 0, 0)");

// The same shape without a fetch stays, whatever the rest of the sheet holds.
applyThemeCss(`
[data-theme-css-probe] {
--edge: 4px solid red; border: var(--edge); border-left-width: 0;
background: var(--none, linear-gradient(red, blue)); background-color: red;
}
.unused { c\\6flor: red; b\\61 ckground: var(--none); cursor: url(https://example.com/x), auto; }
.unused { background: var(--none, url(https://example.com/y)); background-size: auto; }
`);
expect(themeCssText()).not.toContain("example.com");
expect(style.borderTopWidth).toBe("4px");
expect(style.borderLeftWidth).toBe("0px");
expect(style.backgroundImage).toContain("linear-gradient");

applyThemeCss(undefined);
expect(getComputedStyle(probe).color).not.toBe("rgb(1, 2, 3)");
});
57 changes: 55 additions & 2 deletions apps/web/src/themeCss.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { themeCssValueFetches } from "@t3tools/shared/themeCss";
import { themeCssValueFetches, themeCssWithoutDeclarations } 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.
Expand All @@ -14,6 +14,56 @@ type RuleParent = Pick<CSSStyleSheet, "cssRules" | "deleteRule">;
const isRuleParent = (rule: CSSRule): rule is CSSRule & RuleParent =>
"cssRules" in rule && "deleteRule" in rule && !(rule instanceof CSSKeyframesRule);

// A shorthand holding var() leaves its longhands reading "" until substitution.
function pendingLonghands(style: CSSStyleDeclaration): string[] {
return Array.from(style).filter(
(property) => !property.startsWith("--") && style.getPropertyValue(property) === "",
);
}

/** Every declaration block the browser finds in `text`, parsed apart from the theme sheet. */
function parsedStyles(text: string): CSSStyleDeclaration[] {
const styles: CSSStyleDeclaration[] = [];
const collect = (rules: CSSRuleList) => {
for (const rule of rules) {
if ("style" in rule && rule.style instanceof CSSStyleDeclaration) styles.push(rule.style);
if ("cssRules" in rule && rule.cssRules instanceof CSSRuleList) collect(rule.cssRules);
}
};
const sheet = new CSSStyleSheet();
sheet.replaceSync(text);
collect(sheet.cssRules);
return styles;
}

/**
* Whether a shorthand that `style` leaves pending can fetch. cssText shows its text until a later
* declaration overrides one of its longhands; `hiddenFetches` says what to make of one that then
* does not come back from parsing cssText.
*/
function pendingShorthandFetches(style: CSSStyleDeclaration, hiddenFetches: boolean): boolean {
const pending = pendingLonghands(style);
if (pending.length === 0) return false;
const text = style.cssText;
if (themeCssValueFetches(text)) return true;
if (!hiddenFetches) return false;
const shown = new Set(parsedStyles(`x{${text}}`).flatMap(pendingLonghands));
return pending.some((longhand) => !shown.has(longhand));
}

/**
* The theme's source without the var() shorthands that can fetch, so that none is left for a later
* declaration to hide. The browser parses each candidate alone, as rules and as a block, so
* escapes resolve as they will.
*/
function withoutFetchingShorthands(css: string): string {
return themeCssWithoutDeclarations(css, (candidate) =>
[...parsedStyles(candidate), ...parsedStyles(`x{${candidate}}`)].some((style) =>
pendingShorthandFetches(style, true),
),
);
}

function stripDeclarations(rule: CSSRule): boolean {
if (!("style" in rule) || !(rule.style instanceof CSSStyleDeclaration)) return false;
for (let item = rule.style.length - 1; item >= 0; item--) {
Expand All @@ -22,6 +72,9 @@ function stripDeclarations(rule: CSSRule): boolean {
rule.style.removeProperty(property);
}
}
if (pendingShorthandFetches(rule.style, false)) {
for (const longhand of pendingLonghands(rule.style)) rule.style.removeProperty(longhand);
}
return true;
}

Expand Down Expand Up @@ -59,6 +112,6 @@ export function applyThemeCss(css: string | undefined): void {
themeSheet = new CSSStyleSheet();
document.adoptedStyleSheets = [...document.adoptedStyleSheets, themeSheet];
}
themeSheet.replaceSync(next);
themeSheet.replaceSync(withoutFetchingShorthands(next));
stripFetches(themeSheet);
}
47 changes: 46 additions & 1 deletion packages/shared/src/themeCss.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";

import { themeCssLoadsRemoteFiles, themeCssValueFetches } from "./themeCss.ts";
import {
themeCssLoadsRemoteFiles,
themeCssValueFetches,
themeCssWithoutDeclarations,
} from "./themeCss.ts";

// %23 decodes to # inside the SVG, so url(%23g) names its own gradient.
const SVG_WITH_OWN_GRADIENT =
Expand Down Expand Up @@ -59,3 +63,44 @@ describe("themeCssLoadsRemoteFiles", () => {
).toBe(false);
});
});

describe("themeCssWithoutDeclarations", () => {
it.each([
// A harmless var() shorthand and an escape elsewhere name no shorthand that fetches.
["a { border: var(--edge); border-left-width: 0; } .b { c\\6flor: red; }", [" c\\6flor: red"]],
[
"a { mask: var(--none, url(https://e.com/k)); mask-size: auto; }",
[" mask: var(--none, url(https://e.com/k))"],
],
["a { background: var(--none, url(data:image/png;base64,AA)); color: red }", []],
// Brackets, strings, comments and url() addresses do not end a declaration.
[
'a { background: var(--none, { ; } "}" /* } */ [;] url(https://e.com/;}) url(x)); b: c }',
[' background: var(--none, { ; } "}" /* } */ [;] url(https://e.com/;}) url(x))'],
],
// An unquoted url() ends at its first unescaped ")", so the quote after this one opens a string.
[
'a { color: u\\72l(a"b) c" ); background: var(--none, url(https://e.com/k)); d: "" }',
[' color: u\\72l(a"b) c" ); background: var(--none, url(https://e.com/k)); d: "" '],
],
[
"a { color: url(a\\)b;c); background: v\\61r(--none, url(x)) }",
[" color: url(a\\)b;c)", " background: v\\61r(--none, url(x)) "],
],
// A closing bracket of another kind closes nothing, so the declaration stays whole.
["a { background: var(--none, ( ] ; url(x))); }", [" background: var(--none, ( ] ; url(x)))"]],
])("%s", (css, candidates) => {
const asked: string[] = [];
expect(themeCssWithoutDeclarations(css, (candidate) => asked.push(candidate) < 0)).toBe(css);
expect(asked).toEqual(candidates);
});

it("removes only the declarations that are refused", () => {
expect(
themeCssWithoutDeclarations(
"a { mask: var(--none, url(https://e.com/k)); mask-size: auto } b { cursor: url(x) }",
(candidate) => candidate.includes("mask"),
),
).toBe("a {; mask-size: auto } b { cursor: url(x) }");
});
});
62 changes: 62 additions & 0 deletions packages/shared/src/themeCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,68 @@ export function themeCssValueFetches(value: string): boolean {
return code.includes("\\") || fetchesOutsideStrings(code);
}

const WHITESPACE = String.raw`[ \t\n\f\r]`;
const NAME_ESCAPE = String.raw`\\(?:[0-9a-fA-F]{1,6}(?:\r\n|${WHITESPACE})?|[^\n\r\f0-9a-fA-F])`;
const NAME = String.raw`(?:${NAME_ESCAPE}|[-\w\u0080-\uffff])+`;
const BLOCK_TOKENS = new RegExp(
String.raw`\/\*[\s\S]*?(?:\*\/|$)|${STRING}|(${NAME})(\()?|[()[\]{};]`,
"g",
);
// An unquoted url() is one token: quotes, comments and brackets inside it are part of the address.
const UNQUOTED_URL = new RegExp(String.raw`(?!${WHITESPACE}*["'])(?:${NAME_ESCAPE}|[^)])*\)?`, "y");
const NAME_ESCAPES = new RegExp(
String.raw`\\(?:([0-9a-fA-F]{1,6})(?:\r\n|${WHITESPACE})?|([^]))`,
"g",
);
const CLOSERS: Record<string, string> = { "(": ")", "[": "]", "{": "}" };

const isUrlFunction = (name: string) =>
name
.replace(NAME_ESCAPES, (_, hex?: string, char?: string) =>
hex ? String.fromCodePoint(Math.min(Number.parseInt(hex, 16), 0x10ffff)) : (char ?? ""),
)
.toLowerCase() === "url";

/**
* The CSS without the declarations that `drop` refuses, asked only for text that could load a
* remote file. A browser hides a var() shorthand's text once a later declaration overrides one of
* its longhands, so only the source has it. Brackets are tracked as the CSS parser does; an unsure
* split is left out, so one candidate can hold several declarations or rules.
*/
export function themeCssWithoutDeclarations(
css: string,
drop: (candidate: string) => boolean,
): string {
let kept = "";
const open: string[] = [];
let start = 0;
const cut = (end: number) => {
const text = css.slice(start, end);
const candidate = text.includes("\\") || fetchesOutsideStrings(text);
kept += (candidate && drop(text) ? "" : text) + css.slice(end, end + 1);
start = end + 1;
};
BLOCK_TOKENS.lastIndex = 0;
for (let match = BLOCK_TOKENS.exec(css); match; match = BLOCK_TOKENS.exec(css)) {
const [token, name, paren] = match;
if (name !== undefined) {
if (!paren) continue;
UNQUOTED_URL.lastIndex = BLOCK_TOKENS.lastIndex;
const url = isUrlFunction(name) && UNQUOTED_URL.test(css);
if (url) BLOCK_TOKENS.lastIndex = UNQUOTED_URL.lastIndex;
else open.push(")");
} else if (token in CLOSERS && (token !== "{" || open.length > 0)) {
open.push(CLOSERS[token] ?? "");
} else if (token === open.at(-1)) {
open.pop();
} else if (open.length === 0 && (token === ";" || token === "{" || token === "}")) {
cut(match.index);
}
}
cut(css.length);
return kept;
}

/** 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);
Expand Down
Loading