🧩 feat: Let Theme Readers Ignore Unknown Appearance Tokens (#16373)

A definition naming an appearance token this build does not know now
resolves with that token dropped and reported, instead of being rejected
whole. Unknown colours, invalid values for known tokens, and CSS or markup
carried by an unknown token still reject the definition.
This commit is contained in:
Marco Beretta 2026-09-25 21:12:20 +02:00 • committed by GitHub
parent 631fa64b39
commit 0ea3e27c8e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 386 additions and 9 deletions

View file

@ -148,6 +148,30 @@ describe('DeploymentTheme', () => {
expect(snapshotStorage()).toEqual(before);
});
it('applies an inline definition with an unknown appearance key and reports the key', async () => {
const before = snapshotStorage();
serveTheme({
...inlineTheme,
modes: {
...inlineTheme.modes,
light: {
...inlineTheme.modes.light,
appearance: { controlRadius: '2px', futureSpacing: '3rem' },
},
},
});
renderTheme(queryClient);
await waitFor(() => expect(root().dataset.theme).toBe('acme'));
expect(root().style.getPropertyValue('--surface-primary')).toBe('10 20 30');
expect(root().style.getPropertyValue('--theme-control-radius')).toBe('2px');
expect(root().getAttribute('style')).not.toContain('3rem');
expect(warn).toHaveBeenCalledWith(
'[ThemeProvider] Unknown light appearance token ignored: futureSpacing',
);
expect(snapshotStorage()).toEqual(before);
});
it('ignores an invalid inline definition with a warning and keeps the stored theme', async () => {
serveTheme({
...inlineTheme,

View file

@ -0,0 +1,118 @@
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { NEW_CHAT_PATH } from '../helpers';
import { themeValue } from './style.helpers';
/**
* A definition written for a newer frontend can name an appearance token this build does not
* know. The stored and deployment paths both keep the rest of such a definition and drop only
* that token, while a bad value for a known token or an injection attempt still rejects it.
*/
test.describe.configure({ timeout: 120_000 });
const withAppearance = (name: string, appearance: Record<string, unknown>) => ({
version: 1,
name,
modes: {
light: { colors: { 'rgb-surface-primary': '240 244 255' }, appearance },
dark: { colors: { 'rgb-surface-primary': '12 16 32' }, appearance },
},
});
const NEWER_THEME = withAppearance('e2e-newer', { controlRadius: '2px', futureSpacing: '3rem' });
async function storeTheme(page: Page, definition: Record<string, unknown>) {
await page.addInitScript((theme) => {
localStorage.setItem('color-theme', 'light');
localStorage.setItem('theme-definition', JSON.stringify(theme));
localStorage.setItem('theme-source', 'definition');
localStorage.removeItem('theme-colors');
localStorage.removeItem('theme-name');
}, definition);
}
async function serveTheme(page: Page, theme: Record<string, unknown>) {
await page.route(
(url) => url.pathname === '/api/config',
async (route) => {
const response = await route.fetch();
const body = await response.json();
await route.fulfill({ response, json: { ...body, interface: { ...body.interface, theme } } });
},
);
}
async function openChat(page: Page) {
await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
timeout: 30000,
});
}
async function expectNewerThemeApplied(page: Page) {
await expect(page.locator('html')).toHaveAttribute('data-theme', NEWER_THEME.name);
const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
expect(await themeValue(page, '--surface-primary')).toBe(dark ? '12 16 32' : '240 244 255');
expect(await themeValue(page, '--theme-control-radius')).toBe('2px');
expect(await page.locator('html').getAttribute('style')).not.toContain('3rem');
}
test.describe('appearance tokens this build does not know', () => {
test('a stored theme with an unknown appearance token keeps its colors and known tokens @scenario:stored-theme-unknown-appearance-token-applies-rest', async ({
page,
}) => {
const warnings: string[] = [];
page.on('console', (message) => {
if (message.type() === 'warning') {
warnings.push(message.text());
}
});
await storeTheme(page, NEWER_THEME);
await openChat(page);
await expectNewerThemeApplied(page);
expect(warnings.join('\n')).toContain('Unknown light appearance token ignored: futureSpacing');
const stored = await page.evaluate(() => localStorage.getItem('theme-definition'));
expect(JSON.parse(stored ?? '{}')).toEqual(NEWER_THEME);
});
test('a deployment theme with an unknown appearance token keeps its colors and known tokens @scenario:deployment-theme-unknown-appearance-token-applies-rest', async ({
page,
}) => {
await serveTheme(page, NEWER_THEME);
await openChat(page);
await expectNewerThemeApplied(page);
});
test('a stored theme with an invalid value for a known appearance token is still rejected @scenario:stored-theme-invalid-known-appearance-rejected', async ({
page,
}) => {
const theme = withAppearance('e2e-invalid-known', {
controlRadius: 'huge',
futureSpacing: '3rem',
});
await storeTheme(page, theme);
await openChat(page);
await expect(page.locator('html')).not.toHaveAttribute('data-theme', theme.name);
expect(await themeValue(page, '--theme-control-radius')).not.toBe('huge');
});
test('a deployment theme carrying CSS in an unknown appearance token is still rejected @scenario:deployment-theme-appearance-injection-rejected', async ({
page,
}) => {
const theme = withAppearance('e2e-injection', {
futureSpacing: '1rem; } body { display: none',
});
await serveTheme(page, theme);
await openChat(page);
await expect(page.locator('html')).not.toHaveAttribute('data-theme', theme.name);
await expect(page.locator('body')).toBeVisible();
});
});

View file

@ -701,6 +701,112 @@ describe('ThemeProvider', () => {
expect(JSON.parse(localStorage.getItem('theme-definition') ?? '{}')).toEqual(storedDefinition);
});
describe('a definition carrying an appearance token this reader does not know', () => {
const newerDefinition = {
version: 1 as const,
name: 'newer',
modes: {
light: {
colors: { 'rgb-accent-primary': '4 5 6' },
appearance: { controlRadius: '2px', futureSpacing: '3rem' },
},
},
};
let warn: jest.SpyInstance;
beforeEach(() => {
warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
warn.mockRestore();
});
const expectApplied = () => {
const root = document.documentElement;
expect(root.dataset.theme).toBe('newer');
expect(root.style.getPropertyValue('--accent-primary')).toBe('4 5 6');
expect(root.style.getPropertyValue('--theme-control-radius')).toBe('2px');
expect(root.getAttribute('style')).not.toContain('3rem');
expect(warn).toHaveBeenCalledWith(
'[ThemeProvider] Unknown light appearance token ignored: futureSpacing',
);
};
it('restores the stored definition with the rest applied and keeps the key stored', async () => {
localStorage.setItem('theme-definition', JSON.stringify(newerDefinition));
localStorage.setItem('theme-source', 'definition');
render(
<ThemeProvider initialTheme="light">
<Controls />
</ThemeProvider>,
);
await waitFor(expectApplied);
expect(screen.getAllByRole('status')[0]).toHaveTextContent('newer');
expect(JSON.parse(localStorage.getItem('theme-definition') ?? '{}')).toEqual(newerDefinition);
});
it('applies the same definition from a controlled deployment prop', async () => {
render(
<ThemeProvider
initialTheme="light"
persistThemeDefinition={false}
themeDefinition={newerDefinition}
>
<Controls />
</ThemeProvider>,
);
await waitFor(expectApplied);
expect(localStorage.getItem('theme-definition')).toBeNull();
});
it('still discards a stored definition whose known key has an invalid value', async () => {
const invalid = {
...newerDefinition,
modes: { light: { appearance: { controlRadius: 'huge', futureSpacing: '3rem' } } },
};
localStorage.setItem('theme-definition', JSON.stringify(invalid));
render(
<ThemeProvider initialTheme="light">
<Controls />
</ThemeProvider>,
);
await waitFor(() => {
expect(document.documentElement.classList.contains('light')).toBe(true);
});
expect(document.documentElement.dataset.theme).toBeUndefined();
expect(document.documentElement.style.getPropertyValue('--theme-control-radius')).toBe('');
});
it('still ignores a controlled definition that carries an injection attempt', async () => {
render(
<ThemeProvider
initialTheme="light"
persistThemeDefinition={false}
themeDefinition={{
...newerDefinition,
modes: {
light: { appearance: { futureSpacing: '1rem; } body { display: none' } },
},
}}
>
<Controls />
</ThemeProvider>,
);
await waitFor(() => {
expect(document.documentElement.classList.contains('light')).toBe(true);
});
expect(document.documentElement.dataset.theme).toBeUndefined();
expect(document.documentElement.getAttribute('style') ?? '').not.toContain('display');
});
});
it('uses a stable identity when a legacy consumer clears an active theme name', async () => {
render(
<ThemeProvider

View file

@ -12,6 +12,7 @@ import type { IThemeRGB, ThemeDefinition, ThemeMode } from '../types';
import {
fromLegacyTheme,
highContrastTheme,
collectThemeWarnings,
resolveTheme,
validateThemeDefinition,
} from '../registry';
@ -592,6 +593,14 @@ export function ThemeProvider({
setThemeRGB,
]);
/** Stored, controlled and deployment definitions all arrive here, so each is reported once. */
useEffect(() => {
const warnings = themeDefinition ? collectThemeWarnings(themeDefinition) : [];
if (warnings.length > 0) {
console.warn(`[ThemeProvider] ${warnings.join('; ')}`);
}
}, [themeDefinition]);
const applyThemeMode = useCallback(
(currentTheme: AppearanceMode) => {
const root = window.document.documentElement;

View file

@ -22,6 +22,7 @@ export {
export {
HIGH_CONTRAST_THEME_NAME,
THEME_VERSION,
collectThemeWarnings,
defaultAppearance,
defaultBrands,
fromLegacyTheme,

View file

@ -1,5 +1,6 @@
import type { ThemeDefinition } from './types';
import {
collectThemeWarnings,
defaultAppearance,
defaultBrands,
fromLegacyTheme,
@ -512,11 +513,97 @@ describe('theme registry', () => {
'Invalid appearance value for shadowXs: 0,',
'Invalid appearance value for shadowSm: 0 2px 4px var(--brand-shadow)',
'Invalid appearance value for shadow2xs: 0 env(safe-area-inset-tpo) 1px black',
'Unknown appearance token: unknownSpacing',
]);
expect(() => resolveTheme(invalidTheme, 'light')).toThrow(TypeError);
});
describe('appearance tokens this reader does not know', () => {
const newerTheme = {
version: 1,
name: 'newer',
modes: {
light: {
colors: { 'rgb-text-primary': '1 2 3' },
appearance: { controlRadius: '2px', shadowTint: '0 1px 2px black' },
},
dark: { appearance: { futureSpacing: '3rem' } },
},
brands: { 'provider-openai': '#123456' },
} as ThemeDefinition;
it('resolves the rest of the definition and reports the unknown key', () => {
expect(validateThemeDefinition(newerTheme)).toEqual([]);
expect(collectThemeWarnings(newerTheme)).toEqual([
'Unknown light appearance token ignored: shadowTint',
'Unknown dark appearance token ignored: futureSpacing',
]);
const light = resolveTheme(newerTheme, 'light');
expect(light.colors['rgb-text-primary']).toBe('1 2 3');
expect(light.appearance).toEqual({ ...defaultAppearance, controlRadius: '2px' });
expect(light.brands['provider-openai']).toBe('#123456');
expect(resolveTheme(newerTheme, 'dark').appearance).toEqual(defaultAppearance);
});
it('reports nothing for a definition that only uses known tokens', () => {
expect(collectThemeWarnings(compactTheme)).toEqual([]);
expect(collectThemeWarnings(libreChatTheme)).toEqual([]);
});
it('still rejects an invalid value for a known key beside an unknown one', () => {
const theme = {
version: 1,
name: 'mixed',
modes: { light: { appearance: { controlRadius: 'huge', futureSpacing: '1rem' } } },
} as ThemeDefinition;
expect(validateThemeDefinition(theme)).toEqual([
'Invalid appearance value for controlRadius: huge',
]);
expect(() => resolveTheme(theme, 'light')).toThrow(TypeError);
});
it('still rejects an unknown colour token', () => {
const theme = {
version: 1,
name: 'colour',
modes: {
light: { colors: { 'rgb-future': '1 2 3' }, appearance: { futureSpacing: '1rem' } },
},
} as ThemeDefinition;
expect(validateThemeDefinition(theme)).toEqual(['Unknown color token: rgb-future']);
});
it('still rejects an injection attempt carried by an unknown key', () => {
const theme = {
version: 1,
name: 'injection',
modes: {
light: {
appearance: {
futureSpacing: '1rem; } body { display: none',
futureImage: 'url(https://example.com/x.png)',
futureMarkup: '</style><script>',
futureObject: { nested: true },
'future-name;}': '1rem',
constructor: '1rem',
},
},
},
} as unknown as ThemeDefinition;
expect(validateThemeDefinition(theme)).toEqual([
'Invalid appearance value for futureSpacing: 1rem; } body { display: none',
'Invalid appearance value for futureImage: url(https://example.com/x.png)',
'Invalid appearance value for futureMarkup: </style><script>',
'Invalid appearance value for futureObject: [object Object]',
'Invalid appearance value for future-name;}: 1rem',
]);
expect(() => resolveTheme(theme, 'light')).toThrow(TypeError);
});
});
/** A caller may seed a theme from the exported defaults or round-trip a resolved theme. */
it('accepts its own appearance defaults, calc() radii included', () => {
const roundTrip = resolveTheme(

View file

@ -331,6 +331,36 @@ const appearanceValidators: Record<keyof IThemeAppearance, (value: unknown) => b
motionNormal: isDuration,
};
const isAppearanceKey = (key: string): key is keyof IThemeAppearance =>
Object.prototype.hasOwnProperty.call(appearanceValidators, key);
/**
* A token added after this reader shipped is ignored rather than rejected, so a newer definition
* degrades to the defaults for what this version cannot paint instead of losing every value it
* can. It never reaches the DOM, but it must still look like a token: a camelCase name and a
* plain CSS value, never a declaration or rule break.
*/
const isFutureAppearance = (key: string, value: unknown): boolean =>
/^[a-z][a-zA-Z0-9]*$/.test(key) && typeof value === 'string' && !/[;{}<>]|url\s*\(/i.test(value);
/** The appearance tokens this reader does not know, which `resolveTheme` leaves out. */
export function collectThemeWarnings(theme: ThemeDefinition): string[] {
if (!isPlainRecord(theme) || !isPlainRecord(theme.modes)) {
return [];
}
return (['light', 'dark'] as const).flatMap((mode) => {
const appearance: unknown = isPlainRecord(theme.modes[mode])
? theme.modes[mode]?.appearance
: undefined;
if (!isPlainRecord(appearance)) {
return [];
}
return Object.keys(appearance)
.filter((key) => !isAppearanceKey(key))
.map((key) => `Unknown ${mode} appearance token ignored: ${key}`);
});
}
/** Shared by the theme-wide `brands` and each mode's override block. */
function collectBrandErrors(brands: unknown): string[] {
if (!isPlainRecord(brands)) {
@ -417,13 +447,9 @@ export function validateThemeDefinition(theme: ThemeDefinition): string[] {
errors.push(`Theme appearance for ${mode} must be an object`);
} else {
Object.entries(definition.appearance ?? {}).forEach(([key, value]) => {
const appearanceKey = key as keyof IThemeAppearance;
const validator = appearanceValidators[appearanceKey];
if (!validator) {
errors.push(`Unknown appearance token: ${key}`);
return;
}
if (value !== undefined && !validator(value)) {
const isKnown = isAppearanceKey(key);
const isValid = isKnown ? appearanceValidators[key](value) : isFutureAppearance(key, value);
if (value !== undefined && !isValid) {
errors.push(`Invalid appearance value for ${key}: ${value}`);
}
});
@ -460,6 +486,12 @@ function definedEntries<T extends object>(values?: Partial<T>): Partial<T> {
) as Partial<T>;
}
function knownAppearance(appearance?: Partial<IThemeAppearance>): Partial<IThemeAppearance> {
return Object.fromEntries(
Object.entries(definedEntries(appearance)).filter(([key]) => isAppearanceKey(key)),
);
}
const shadowAppearanceKeys: ReadonlyArray<keyof IThemeAppearance> = [
'elevationSurface',
'shadow2xs',
@ -612,7 +644,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT
} as Required<IThemeRGB>,
appearance: withComposableShadows({
...defaultAppearance,
...definedEntries(definition?.appearance),
...knownAppearance(definition?.appearance),
}),
/** Mode last: a mode override is more specific than the theme-wide set. */
brands: {