Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎨 feat: Paint the Operator Theme on a First-Ever Visit (#16962)

Marco Beretta37ec4b56c9b0
diff --git a/api/server/experimental.js b/api/server/experimental.js
index 4807103983..b7b15cedb8 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -39,6 +39,8 @@ const {
maybeInjectQueryDevtoolsBootstrap,
injectConfiguredFooterBootstrap,
injectColorModeHandoff,
+ readBundledThemeBoot,
+ createDeploymentThemeShell,
preAuthTenantMiddleware,
requestContextMiddleware,
configureServerTimeouts,
@@ -547,6 +549,11 @@ if (cluster.isMaster) {
});
indexHTML = injectColorModeHandoff(indexHTML, baseAppConfig?.interfaceConfig?.colorModeFromUrl);
+ const indexShell = createDeploymentThemeShell(
+ indexHTML,
+ baseAppConfig?.interfaceConfig?.theme,
+ readBundledThemeBoot(appConfig.paths.dist),
+ );
const cspPolicy = createCspPolicy();
const shellCache = shellCacheHeaders(cspPolicy != null);
@@ -557,7 +564,10 @@ if (cluster.isMaster) {
const lang = req.cookies.lang || req.headers['accept-language']?.split(',')[0] || 'en-US';
const saneLang = escapeHtmlAttribute(lang);
- let updatedIndexHtml = indexHTML.replace(/lang="en-US"/g, () => `lang="${saneLang}"`);
+ let updatedIndexHtml = indexShell(req, res).replace(
+ /lang="en-US"/g,
+ () => `lang="${saneLang}"`,
+ );
updatedIndexHtml = maybeInjectQueryDevtoolsBootstrap(updatedIndexHtml, req);
/* Nonce last: every injected script above must be stamped too. */
diff --git a/api/server/index.js b/api/server/index.js
index 324d1ed4e9..3300895b05 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -46,6 +46,8 @@ const {
maybeInjectQueryDevtoolsBootstrap,
injectConfiguredFooterBootstrap,
injectColorModeHandoff,
+ readBundledThemeBoot,
+ createDeploymentThemeShell,
preAuthTenantMiddleware,
requestContextMiddleware,
registerShutdownTask,
@@ -305,6 +307,11 @@ const startServer = async () => {
});
indexHTML = injectColorModeHandoff(indexHTML, appConfig.interfaceConfig?.colorModeFromUrl);
+ const indexShell = createDeploymentThemeShell(
+ indexHTML,
+ appConfig.interfaceConfig?.theme,
+ readBundledThemeBoot(appConfig.paths.dist),
+ );
const cspPolicy = createCspPolicy();
const shellCache = shellCacheHeaders(cspPolicy != null);
@@ -315,7 +322,10 @@ const startServer = async () => {
const lang = req.cookies.lang || req.headers['accept-language']?.split(',')[0] || 'en-US';
const saneLang = escapeHtmlAttribute(lang);
- let updatedIndexHtml = indexHTML.replace(/lang="en-US"/g, () => `lang="${saneLang}"`);
+ let updatedIndexHtml = indexShell(req, res).replace(
+ /lang="en-US"/g,
+ () => `lang="${saneLang}"`,
+ );
updatedIndexHtml = maybeInjectQueryDevtoolsBootstrap(updatedIndexHtml, req);
/* Nonce last: every injected script above must be stamped too. */
diff --git a/client/index.html b/client/index.html
index 6dcb8e8530..049c2e3fc4 100644
--- a/client/index.html
+++ b/client/index.html
@@ -130,6 +130,8 @@
/^(?:share|oauth|login|register|forgot-password|reset-password|verify)(?:\/|$)/i.test(
path,
);
+ const mode = dark ? 'dark' : 'light';
+ let boot = null;
if (!contrast && !publicRoute) {
try {
const cached = JSON.parse(localStorage.getItem('deployment-theme') || 'null');
@@ -138,7 +140,7 @@
const hint = /(?:^|;\s*)session_hint=([^;]*)/.exec(document.cookie);
const session = hint ? decodeURIComponent(hint[1]) : '';
const separator = session.indexOf('~');
- const boot =
+ boot =
cached &&
separator > 0 &&
Number(session.slice(0, separator)) > Date.now() &&
@@ -147,8 +149,26 @@
typeof cached.owner === 'string' &&
cached.owner === sessionStorage.getItem('deployment-theme-owner') &&
cached.modes &&
- cached.modes[dark ? 'dark' : 'light'];
- if (boot && Array.isArray(boot.properties)) {
+ cached.modes[mode];
+ } catch (e) {
+ /* Denied or corrupt storage replays no cached copy. */
+ }
+ }
+ /* With no copy of its own, the tab paints the deployment's base theme, which the
+ * server embeds in the shell for a bundled name (`readShellTheme` in themeCache.ts),
+ * so even a first-ever visit wears it. Shared links paint their own tenant's. */
+ if (!contrast && !boot && !/^share(?:\/|$)/i.test(path)) {
+ try {
+ const block = document.getElementById('deployment-theme-boot');
+ const shell = block && JSON.parse(block.textContent);
+ boot = shell && shell.modes && shell.modes[mode];
+ } catch (e) {
+ /* A malformed block paints the stock shell. */
+ }
+ }
+ if (boot) {
+ try {
+ if (Array.isArray(boot.properties)) {
let surface;
let canvas;
/* Only the conversation paints the canvas, and the redirects that land on it; other routes keep the split surface. */
@@ -193,7 +213,7 @@
}
}
} catch (e) {
- /* Denied or corrupt storage paints the stock shell, as before. */
+ /* A malformed copy paints the stock shell, as before. */
}
}
diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsx
index 7b4b590609..d20c6590be 100644
--- a/client/src/Providers/DeploymentTheme.tsx
+++ b/client/src/Providers/DeploymentTheme.tsx
@@ -11,18 +11,8 @@ import {
import { useRecoilValue } from 'recoil';
import { notifyManager, useQueryClient } from '@tanstack/react-query';
import { QueryKeys, MutationKeys, isBundledThemeName } from 'librechat-data-provider';
-import {
- ThemeProvider,
- clickHouseTheme,
- libreChatTheme,
- fromLegacyTheme,
- validateThemeDefinition,
-} from '@librechat/client';
-import type {
- TInterfaceConfig,
- BundledThemeName,
- TRefreshTokenResponse,
-} from 'librechat-data-provider';
+import { ThemeProvider, fromLegacyTheme, validateThemeDefinition } from '@librechat/client';
+import type { TInterfaceConfig, TRefreshTokenResponse } from 'librechat-data-provider';
import type { IThemeRGB, ThemeDefinition } from '@librechat/client';
import type { ComponentProps } from 'react';
import {
@@ -30,6 +20,7 @@ import {
appBasePath,
isPublicRoute,
setThemeOwner,
+ readShellTheme,
clearThemeCache,
buildThemeCache,
writeThemeCache,
@@ -38,15 +29,11 @@ import {
} from './themeCache';
import { getThemeFromEnv } from '~/utils/getThemeFromEnv';
import { useGetStartupConfig } from '~/data-provider';
+import { bundledThemes } from './bootVersion';
import store from '~/store';
type DeploymentThemeValue = TInterfaceConfig['theme'];
-const bundledThemes: Readonly<Record<BundledThemeName, ThemeDefinition>> = {
- librechat: libreChatTheme,
- clickhouse: clickHouseTheme,
-};
-
/**
* Resolves `interface.theme` from librechat.yaml to a theme definition: a bundled
* name, or an inline definition that passes the registry's validation. Anything
@@ -259,6 +246,7 @@ export default function DeploymentTheme({ children }: { children: React.ReactNod
signedOutAnswer.current = startupConfig;
}
const [cached, setCached] = useThemeCache(owner);
+ const [shell] = useState(() => readShellTheme(window.location.pathname, appBasePath()));
const [override, setOverride] = useState<ThemeOverride>(undefined);
/** A route override is another tenant's theme: it neither reads nor writes the cache. */
const decision = override
@@ -271,6 +259,7 @@ export default function DeploymentTheme({ children }: { children: React.ReactNod
current: !isPreviousData,
signedOut: startupConfig === signedOutAnswer.current,
},
+ shell,
});
const configTheme = decision.theme;
const themeDefinition = useMemo(() => resolveDeploymentTheme(configTheme), [configTheme]);
diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
index c6ab8963e7..b221b7d9ac 100644
--- a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
+++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
@@ -9,6 +9,7 @@ import {
dataService,
formatSessionHint,
SESSION_HINT_COOKIE,
+ DEPLOYMENT_THEME_BOOT_ID,
} from 'librechat-data-provider';
import type { TStartupConfig, TUser } from 'librechat-data-provider';
import type { ThemeDefinition } from '@librechat/client';
@@ -542,6 +543,69 @@ describe('DeploymentTheme cache', () => {
expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
});
+ describe("the shell's base theme", () => {
+ const embed = (source: NonNullable<ConfigTheme>) => {
+ const block = document.createElement('script');
+ block.type = 'application/json';
+ block.id = DEPLOYMENT_THEME_BOOT_ID;
+ block.textContent = JSON.stringify({ source });
+ document.head.append(block);
+ };
+
+ afterEach(() => {
+ document.getElementById(DEPLOYMENT_THEME_BOOT_ID)?.remove();
+ window.history.pushState({}, '', '/');
+ });
+
+ it('paints a first-ever visit in the first commit, before the config answers', () => {
+ embed('clickhouse');
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBe('clickhouse');
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ expect(localStorage.getItem('theme-definition')).toBeNull();
+ });
+
+ it('resolves an inline definition the build could not', () => {
+ embed(inlineTheme as NonNullable<ConfigTheme>);
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBe(inlineTheme.name);
+ });
+
+ it("yields to the owner's cache", () => {
+ embed('librechat');
+ cacheTheme();
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBe('clickhouse');
+ });
+
+ it('yields to the answer once it arrives', async () => {
+ embed('clickhouse');
+ let answer: (config: TStartupConfig) => void = () => undefined;
+ getStartupConfig.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ renderTheme(queryClient, user);
+ expect(root().dataset.theme).toBe('clickhouse');
+
+ await act(async () => answer(configWith(undefined)));
+ await waitFor(() => expect(root().dataset.theme).toBeUndefined());
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ it('does not paint on a shared link, which paints its own tenant', () => {
+ embed('clickhouse');
+ pending();
+ window.history.pushState({}, '', '/share/abc');
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBeUndefined();
+ });
+ });
+
it('does not seed the cache on a shared link, which paints its own tenant', () => {
cacheTheme();
pending();
diff --git a/client/src/Providers/__tests__/bootScript.spec.tsx b/client/src/Providers/__tests__/bootScript.spec.tsx
index 74432b5523..d9738271d9 100644
--- a/client/src/Providers/__tests__/bootScript.spec.tsx
+++ b/client/src/Providers/__tests__/bootScript.spec.tsx
@@ -1,8 +1,18 @@
import { resolve } from 'path';
import { readFileSync } from 'fs';
import { render } from '@testing-library/react';
-import { formatSessionHint, SESSION_HINT_COOKIE } from 'librechat-data-provider';
-import { ThemeProvider, applyResolvedTheme, resolveTheme } from '@librechat/client';
+import {
+ ThemeProvider,
+ resolveTheme,
+ clickHouseTheme,
+ applyResolvedTheme,
+} from '@librechat/client';
+import {
+ formatSessionHint,
+ SESSION_HINT_COOKIE,
+ DEPLOYMENT_THEME_BOOT_ID,
+} from 'librechat-data-provider';
+import type { DeploymentThemeBoot } from 'librechat-data-provider';
import type { ThemeDefinition } from '@librechat/client';
import {
isPublicRoute,
@@ -12,7 +22,11 @@ import {
THEME_CACHE_KEY,
THEME_CACHE_VERSION,
} from '../themeCache';
-import { THEME_CACHE_VERSION_PLACEHOLDER, injectThemeCacheVersion } from '../bootVersion';
+import {
+ bundledThemeBoot,
+ injectThemeCacheVersion,
+ THEME_CACHE_VERSION_PLACEHOLDER,
+} from '../bootVersion';
/** The inline shell script in `client/index.html`, run as the browser runs it. */
const bootScript = (() => {
@@ -64,12 +78,26 @@ function boot() {
}
/** What `applyResolvedTheme` writes for `mode`, read off a detached element. */
-function appliedStyle(mode: 'light' | 'dark') {
+function appliedStyle(mode: 'light' | 'dark', theme: ThemeDefinition = acme) {
const element = document.createElement('div');
- applyResolvedTheme(resolveTheme(acme, mode), element);
+ applyResolvedTheme(resolveTheme(theme, mode), element);
return element;
}
+/** The block the server embeds ahead of the boot script for the deployment's base theme. */
+function embedShellTheme(boot: DeploymentThemeBoot | string) {
+ const block = document.createElement('script');
+ block.type = 'application/json';
+ block.id = DEPLOYMENT_THEME_BOOT_ID;
+ block.textContent = typeof boot === 'string' ? boot : JSON.stringify(boot);
+ document.head.prepend(block);
+}
+
+const clickhouseShell = (): DeploymentThemeBoot => ({
+ source: 'clickhouse',
+ modes: bundledThemeBoot().clickhouse,
+});
+
describe('index.html deployment theme boot script', () => {
beforeEach(() => {
localStorage.clear();
@@ -81,7 +109,9 @@ describe('index.html deployment theme boot script', () => {
root().removeAttribute(name);
}
});
- document.head.querySelectorAll('style, base').forEach((element) => element.remove());
+ document.head
+ .querySelectorAll(`style, base, #${DEPLOYMENT_THEME_BOOT_ID}`)
+ .forEach((element) => element.remove());
const base = document.createElement('base');
base.href = '/';
document.head.append(base);
@@ -170,7 +200,7 @@ describe('index.html deployment theme boot script', () => {
expect(root().hasAttribute('data-theme')).toBe(false);
});
- it('paints nothing on a first-ever visit, leaving the operator theme to the config answer', () => {
+ it('paints nothing on a first-ever visit to a shell no server embedded a theme in', () => {
localStorage.clear();
boot();
expect(root().getAttribute('style')).toBeNull();
@@ -179,6 +209,99 @@ describe('index.html deployment theme boot script', () => {
expect(root().classList.contains('light')).toBe(true);
});
+ describe('the deployment theme the server embeds in the shell', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ embedShellTheme(clickhouseShell());
+ });
+
+ it.each(['light', 'dark'] as const)(
+ 'paints a first-ever visit in %s exactly as the provider would',
+ (mode) => {
+ localStorage.setItem('color-theme', mode);
+ boot();
+
+ const expected = appliedStyle(mode, clickHouseTheme);
+ expect(root().getAttribute('style')).toBe(expected.getAttribute('style'));
+ expect(root().dataset.theme).toBe('clickhouse');
+ expect(root().hasAttribute('data-theme-boot')).toBe(true);
+ const canvas = resolveTheme(clickHouseTheme, mode).colors['rgb-surface-canvas'];
+ expect(document.head.textContent).toContain(
+ `background-color: rgb(${canvas?.split(' ').join(', ')})`,
+ );
+ },
+ );
+
+ it('yields to the copy this tab cached for its signed-in owner', () => {
+ writeThemeCache(buildThemeCache('tenant-a:user-1', 'acme', acme));
+ setThemeOwner('tenant-a:user-1');
+ boot();
+ expect(root().dataset.theme).toBe('acme');
+ });
+
+ it('stands in for a copy cached for someone else', () => {
+ writeThemeCache(buildThemeCache('tenant-a:user-1', 'acme', acme));
+ setThemeOwner('tenant-b:user-2');
+ boot();
+ expect(root().dataset.theme).toBe('clickhouse');
+ });
+
+ it.each([
+ ['has ended', Date.now() - 1000, 'tenant-a:user-1'],
+ ['belongs to someone who signed in since', Date.now() + 60000, 'tenant-b:user-2'],
+ ])('stands in for the owned copy when the session %s', (_, expires, owner) => {
+ writeThemeCache(buildThemeCache('tenant-a:user-1', 'acme', acme));
+ setThemeOwner('tenant-a:user-1');
+ sessionHint(expires, owner);
+ boot();
+ expect(root().dataset.theme).toBe('clickhouse');
+ });
+
+ it.each(['/login', '/register', '/oauth/success'])(
+ 'paints on %s, which renders the same signed-out theme',
+ (path) => {
+ window.history.pushState({}, '', path);
+ boot();
+ expect(root().dataset.theme).toBe('clickhouse');
+ },
+ );
+
+ it.each(['/share/abc', '/Share/abc'])(
+ "does not paint on %s, which paints its own tenant's theme",
+ (path) => {
+ window.history.pushState({}, '', path);
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ },
+ );
+
+ it('leaves the shell alone under high contrast', () => {
+ localStorage.setItem('color-theme', 'high-contrast-light');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ });
+
+ it('leaves an inline definition, which the build has not resolved, to the bundle', () => {
+ document.getElementById(DEPLOYMENT_THEME_BOOT_ID)?.remove();
+ embedShellTheme(JSON.stringify({ source: acme }));
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ });
+
+ it('paints the stock shell for a malformed block', () => {
+ document.getElementById(DEPLOYMENT_THEME_BOOT_ID)?.remove();
+ embedShellTheme('{not json');
+ localStorage.setItem('color-theme', 'dark');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(document.head.textContent).toContain('background-color: #0d0d0d');
+ });
+ });
+
it('follows the OS scheme under `system`', () => {
mockMedia(true);
boot();
diff --git a/client/src/Providers/__tests__/themeCache.spec.ts b/client/src/Providers/__tests__/themeCache.spec.ts
index 8305a60593..bae575caed 100644
--- a/client/src/Providers/__tests__/themeCache.spec.ts
+++ b/client/src/Providers/__tests__/themeCache.spec.ts
@@ -105,6 +105,41 @@ describe('reconcileThemeCache', () => {
).toEqual({ theme: undefined, cache: 'keep' });
});
+ it("lets the shell's base theme stand in wherever nothing else would paint", () => {
+ const shell = 'clickhouse';
+ expect(reconcileThemeCache({ shell })).toEqual({ theme: 'clickhouse', cache: 'keep' });
+ expect(reconcileThemeCache({ owner: OWNER, shell })).toEqual({
+ theme: 'clickhouse',
+ cache: 'keep',
+ });
+ expect(
+ reconcileThemeCache({ owner: OWNER, answer: { theme: 'librechat', current: false }, shell }),
+ ).toEqual({ theme: 'clickhouse', cache: 'keep' });
+ expect(reconcileThemeCache({ cached, owner: 'tenant-b:user-1', shell })).toEqual({
+ theme: 'clickhouse',
+ cache: 'disown',
+ });
+ expect(reconcileThemeCache({ cached: { ...cached, disowned: true }, shell })).toEqual({
+ theme: 'clickhouse',
+ cache: 'keep',
+ });
+ });
+
+ it("ranks the shell's base theme below the owner's cache and any answer", () => {
+ const shell = 'librechat';
+ expect(reconcileThemeCache({ cached, owner: OWNER, shell }).theme).toBe('clickhouse');
+ expect(reconcileThemeCache({ answer: { theme: undefined, current: true }, shell })).toEqual({
+ theme: undefined,
+ cache: 'keep',
+ });
+ expect(
+ reconcileThemeCache({
+ answer: { theme: 'clickhouse', current: false, signedOut: true },
+ shell,
+ }).theme,
+ ).toBe('clickhouse');
+ });
+
it('stamps entries with a version derived from the registry roles', () => {
expect(cached.v).toBe(themeRoleFingerprint());
expect(THEME_CACHE_VERSION).toBe(themeRoleFingerprint());
diff --git a/client/src/Providers/bootVersion.ts b/client/src/Providers/bootVersion.ts
index cc093db1da..50682d146e 100644
--- a/client/src/Providers/bootVersion.ts
+++ b/client/src/Providers/bootVersion.ts
@@ -1,7 +1,35 @@
-import { themeRoleFingerprint } from 'librechat-data-provider';
+import { bundledThemeNames, themeRoleFingerprint } from 'librechat-data-provider';
+import {
+ resolveTheme,
+ clickHouseTheme,
+ libreChatTheme,
+ describeResolvedTheme,
+} from '@librechat/client';
+import type { BundledThemeBoot, BundledThemeName } from 'librechat-data-provider';
+import type { ThemeDefinition } from '@librechat/client';
export const THEME_CACHE_VERSION_PLACEHOLDER = '__THEME_CACHE_VERSION__';
/** Writes the cache version into the boot script's check, as the Vite build does for `index.html`. */
export const injectThemeCacheVersion = (html: string): string =>
html.replace(THEME_CACHE_VERSION_PLACEHOLDER, themeRoleFingerprint());
+
+export const bundledThemes: Readonly<Record<BundledThemeName, ThemeDefinition>> = {
+ librechat: libreChatTheme,
+ clickhouse: clickHouseTheme,
+};
+
+/**
+ * Each bundled theme in both modes as the boot script replays it. The build writes this to
+ * the `THEME_BOOT_FILE` asset, and the server hands the deployment's own to the shell of a first visit.
+ */
+export const bundledThemeBoot = (): BundledThemeBoot =>
+ Object.fromEntries(
+ bundledThemeNames.map((name) => [
+ name,
+ {
+ light: describeResolvedTheme(resolveTheme(bundledThemes[name], 'light')),
+ dark: describeResolvedTheme(resolveTheme(bundledThemes[name], 'dark')),
+ },
+ ]),
+ );
diff --git a/client/src/Providers/themeCache.ts b/client/src/Providers/themeCache.ts
index 8ccc8fda99..f5d85ecd61 100644
--- a/client/src/Providers/themeCache.ts
+++ b/client/src/Providers/themeCache.ts
@@ -4,9 +4,10 @@ import {
parseSessionHint,
SESSION_HINT_COOKIE,
themeRoleFingerprint,
+ DEPLOYMENT_THEME_BOOT_ID,
} from 'librechat-data-provider';
+import type { TInterfaceConfig, TUser, DeploymentThemeBoot } from 'librechat-data-provider';
import type { ResolvedThemeStyle, ThemeDefinition } from '@librechat/client';
-import type { TInterfaceConfig, TUser } from 'librechat-data-provider';
type DeploymentThemeValue = TInterfaceConfig['theme'];
@@ -68,12 +69,38 @@ export function appBasePath(): string {
return base ? new URL(base.href).pathname : '/';
}
+const routePath = (pathname: string, basePath: string): string =>
+ pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname.replace(/^\//, '');
+
/** `pathname` relative to the app's base path. */
export function isPublicRoute(pathname: string, basePath = '/'): boolean {
- const path = pathname.startsWith(basePath)
- ? pathname.slice(basePath.length)
- : pathname.replace(/^\//, '');
- return PUBLIC_ROUTE.test(path);
+ return PUBLIC_ROUTE.test(routePath(pathname, basePath));
+}
+
+/** Shared links paint their own tenant's theme, so the deployment's base theme never stands in. */
+const SHARE_ROUTE = /^share(?:\/|$)/i;
+
+/**
+ * The deployment's base `interface.theme`, which the server embeds in the shell
+ * (`DEPLOYMENT_THEME_BOOT_ID`) for the boot script to paint before `/api/config` answers.
+ * Absent on a shared link and wherever no server said (the Vite dev server).
+ */
+export function readShellTheme(
+ pathname: string,
+ basePath = '/',
+): NonNullable<DeploymentThemeValue> | undefined {
+ if (SHARE_ROUTE.test(routePath(pathname, basePath))) {
+ return undefined;
+ }
+ try {
+ const block = document.getElementById(DEPLOYMENT_THEME_BOOT_ID);
+ const boot = block
+ ? (JSON.parse(block.textContent ?? '') as Partial<DeploymentThemeBoot>)
+ : null;
+ return boot?.source ?? undefined;
+ } catch {
+ return undefined;
+ }
}
export const themeOwner = (user?: Pick<TUser, 'id' | 'tenantId'>): string | undefined =>
@@ -193,16 +220,20 @@ export function writeThemeCache(entry: ThemeCacheEntry): void {
* - otherwise the previous answer keeps painting while it is the signed-out one, which is
* the same deployment's; one from another signed-in key may be another identity's, so
* nothing paints until the current answer arrives.
+ * Wherever nothing would paint, the deployment's base theme from the shell (`shell`) stands
+ * in, as the signed-out answer does: it is served to everyone, so it is no one else's.
* A theme that turns out invalid is cleared by the caller, which resolves it.
*/
export function reconcileThemeCache({
cached,
owner,
answer,
+ shell,
}: {
cached?: ThemeCacheEntry;
owner?: string;
answer?: ThemeAnswer;
+ shell?: DeploymentThemeValue;
}): { theme: DeploymentThemeValue; cache: ThemeCacheAction } {
if (answer?.current) {
if (!owner) {
@@ -211,16 +242,16 @@ export function reconcileThemeCache({
return { theme: answer.theme, cache: answer.theme == null ? 'clear' : 'write' };
}
if (cached?.disowned) {
- return { theme: undefined, cache: 'keep' };
+ return { theme: shell, cache: 'keep' };
}
if (cached && owner !== undefined && cached.owner !== owner) {
- return { theme: undefined, cache: 'disown' };
+ return { theme: shell, cache: 'disown' };
}
if (cached) {
return { theme: cached.source, cache: 'keep' };
}
if (answer && !answer.current && !answer.signedOut) {
- return { theme: undefined, cache: 'keep' };
+ return { theme: shell, cache: 'keep' };
}
- return { theme: answer?.theme, cache: 'keep' };
+ return { theme: answer ? answer.theme : shell, cache: 'keep' };
}
diff --git a/client/vite.config.ts b/client/vite.config.ts
index f187e47e89..d9858ea3cb 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -3,12 +3,13 @@ import fs from 'fs';
import path from 'path';
import { constants } from 'zlib';
import { defineConfig } from 'vite';
+import { THEME_BOOT_FILE } from 'librechat-data-provider';
import { createRequire } from 'module';
import { VitePWA } from 'vite-plugin-pwa';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import { compression, defineAlgorithm } from 'vite-plugin-compression2';
import type { Plugin } from 'vite';
-import { injectThemeCacheVersion } from './src/Providers/bootVersion.ts';
+import { bundledThemeBoot, injectThemeCacheVersion } from './src/Providers/bootVersion.ts';
const require = createRequire(import.meta.url);
@@ -460,12 +461,20 @@ export default defineConfig(({ command }) => ({
/**
* Writes the deployment-theme cache version into the boot script's check, the same value
* `themeCache.ts` stamps on the entries it stores, so a role added to the registry retires
- * every entry stored before it without anyone remembering to bump a number.
+ * every entry stored before it without anyone remembering to bump a number. It also emits
+ * the bundled themes resolved for the boot script, which the server embeds in a first visit.
*/
export function themeCacheVersion(): Plugin {
return {
name: 'theme-cache-version',
transformIndexHtml: injectThemeCacheVersion,
+ generateBundle() {
+ this.emitFile({
+ type: 'asset',
+ fileName: THEME_BOOT_FILE,
+ source: JSON.stringify(bundledThemeBoot()),
+ });
+ },
};
}
diff --git a/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts b/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
index bd1df41658..fa2b069ae9 100644
--- a/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
+++ b/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
@@ -1,7 +1,12 @@
+import { resolve } from 'node:path';
import { expect, test } from '@playwright/test';
import { parseSessionHint, formatSessionHint, SESSION_HINT_COOKIE } from 'librechat-data-provider';
import type { SessionHint } from 'librechat-data-provider';
import type { Page } from '@playwright/test';
+import {
+ readBundledThemeBoot,
+ injectDeploymentThemeBoot,
+} from '../../../../packages/api/src/html/theme';
import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
import { resolveTheme } from '../../../../packages/client/src/theme/registry';
@@ -431,3 +436,141 @@ test('a session refresh keeps the readable session hint on the refresh session e
expect(after?.expires).toBeGreaterThanOrEqual(before?.expires ?? Number.POSITIVE_INFINITY);
expect(Math.floor((after?.expires ?? 0) / 1000)).toBe(Math.floor(refreshCookie?.expires ?? -1));
});
+
+/**
+ * A first-ever visit has nothing cached, so the server embeds the deployment's base
+ * `interface.theme` in the shell it serves (`createDeploymentThemeShell`). The mock lane's
+ * yaml sets no theme, so each document is fetched from the server and passed through the same
+ * injection, with the `theme-boot.json` this build emitted, as a server configured with
+ * `interface.theme: clickhouse` serves it.
+ */
+async function serveThemedShell(page: Page) {
+ const bundled = readBundledThemeBoot(resolve(__dirname, '../../../../client/dist'));
+ expect(bundled.clickhouse).toBeDefined();
+ await page.route(
+ () => true,
+ async (route) => {
+ if (route.request().resourceType() !== 'document') {
+ return route.fallback();
+ }
+ const response = await route.fetch();
+ const html = injectDeploymentThemeBoot(await response.text(), 'clickhouse', bundled);
+ await route.fulfill({ response, body: html });
+ },
+ );
+}
+
+/** Every `/api/config` answer, signed in or not, held until the app paints: the first one ends the window under test. */
+function holdConfig(page: Page) {
+ return serveTheme(
+ page,
+ () => 'clickhouse',
+ () => true,
+ false,
+ );
+}
+
+/** Opens `path` in a browser that has never cached a deployment theme, throttled, and returns the frames before the config answers. */
+async function firstVisitFrames(page: Page, path: string, ready: () => Promise<void>) {
+ await page.addInitScript((key) => {
+ localStorage.removeItem(key);
+ sessionStorage.clear();
+ }, CACHE_KEY);
+ await serveThemedShell(page);
+ const answeredAt = await holdConfig(page);
+ await sampleFrames(page);
+ await throttle(page);
+ await page.goto(path);
+ await ready();
+ await expect.poll(() => answeredAt.length).toBeGreaterThan(0);
+
+ const answered = Math.min(...answeredAt);
+ return (await page.evaluate(() => window.__themeFrames ?? [])).filter(
+ (frame) => frame.at < answered,
+ );
+}
+
+/** A signed-in first visit: every frame before the answer, shell and app alike, wears the theme. */
+async function expectFirstVisit(page: Page, mode: Mode) {
+ const { colors } = resolveTheme(clickHouseTheme, mode);
+ const frames = await firstVisitFrames(page, '/c/new', () =>
+ expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 60000 }),
+ );
+
+ /** Frames of both the shell and the first render landed before the answer. */
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames[0].shell).not.toBeNull();
+ expect(frames.some((frame) => frame.app)).toBe(true);
+ for (const frame of frames) {
+ expect(frame.theme).toBe('clickhouse');
+ expect(frame.surface).toBe(colors['rgb-surface-primary']);
+ if (frame.shell !== null) {
+ expect(frame.shell).toBe(rgb(colors['rgb-surface-canvas']));
+ }
+ }
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect(page.locator('html')).not.toHaveAttribute('data-theme-boot');
+}
+
+/** A signed-out first visit to the login page, which is where a new browser lands. */
+async function expectFirstVisitLogin(page: Page, mode: Mode) {
+ const { colors } = resolveTheme(clickHouseTheme, mode);
+ const frames = await firstVisitFrames(page, '/login', () =>
+ expect(page.getByTestId('login-button')).toBeVisible({ timeout: 60000 }),
+ );
+
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames[0].shell).not.toBeNull();
+ for (const frame of frames) {
+ expect(frame.theme).toBe('clickhouse');
+ expect(frame.surface).toBe(colors['rgb-surface-primary']);
+ if (frame.shell !== null) {
+ expect(frame.shell).toBe(rgb(colors['rgb-surface-primary-alt']));
+ }
+ }
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+}
+
+test.describe('deployment theme first-ever visit (light)', () => {
+ test.use({ colorScheme: 'light', viewport: { width: 1280, height: 800 } });
+
+ test('a first-ever signed-in visit paints the operator theme from the first frame in light @scenario:deployment-theme-first-visit-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstVisit(page, 'light');
+ });
+
+ test.describe('signed out', () => {
+ test.use({ storageState: { cookies: [], origins: [] } });
+
+ test('a first-ever visit to the login page paints the operator theme from the first frame in light @scenario:deployment-theme-first-visit-login-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstVisitLogin(page, 'light');
+ });
+ });
+});
+
+test.describe('deployment theme first-ever visit (dark)', () => {
+ test.use({ colorScheme: 'dark', viewport: { width: 1280, height: 800 } });
+
+ test('a first-ever signed-in visit paints the operator theme from the first frame in dark @scenario:deployment-theme-first-visit-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstVisit(page, 'dark');
+ });
+
+ test.describe('signed out', () => {
+ test.use({ storageState: { cookies: [], origins: [] } });
+
+ test('a first-ever visit to the login page paints the operator theme from the first frame in dark @scenario:deployment-theme-first-visit-login-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstVisitLogin(page, 'dark');
+ });
+ });
+});
diff --git a/packages/api/src/html/index.ts b/packages/api/src/html/index.ts
index c13fd0ddf7..88c5d8c93f 100644
--- a/packages/api/src/html/index.ts
+++ b/packages/api/src/html/index.ts
@@ -2,3 +2,4 @@ export * from './bootstrap';
export * from './devtools';
export * from './footer';
export * from './handoff';
+export * from './theme';
diff --git a/packages/api/src/html/theme.spec.ts b/packages/api/src/html/theme.spec.ts
new file mode 100644
index 0000000000..cd5041758f
--- /dev/null
+++ b/packages/api/src/html/theme.spec.ts
@@ -0,0 +1,145 @@
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { logger } from '@librechat/data-schemas';
+import { THEME_BOOT_FILE, DEPLOYMENT_THEME_BOOT_ID } from 'librechat-data-provider';
+import type { BundledThemeBoot, DeploymentThemeBoot } from 'librechat-data-provider';
+import type { Request, Response } from 'express';
+import {
+ readBundledThemeBoot,
+ injectDeploymentThemeBoot,
+ createDeploymentThemeShell,
+} from './theme';
+import { applyCspNonce } from '~/security/csp';
+
+const SHELL =
+ '<!DOCTYPE html><html><head><base href="/" /><script>boot()</script></head>' +
+ '<body><div id="root"></div><script type="module" src="/assets/index.js"></script></body></html>';
+
+const style = (surface: string) => ({
+ properties: [['--surface-primary', surface]] as Array<[string, string]>,
+ attributes: { 'data-theme': 'clickhouse' },
+});
+
+const bundled: BundledThemeBoot = {
+ clickhouse: { light: style('255 255 255'), dark: style('0 0 0') },
+};
+
+const BLOCK = new RegExp(
+ `<script type="application/json" id="${DEPLOYMENT_THEME_BOOT_ID}">(.*?)</script>`,
+);
+
+const bootOf = (html: string): DeploymentThemeBoot | undefined => {
+ const match = BLOCK.exec(html);
+ return match ? JSON.parse(match[1]) : undefined;
+};
+
+const request = (headers: Record<string, string> = {}) =>
+ ({ get: (name: string) => headers[name.toLowerCase()] }) as Pick<Request, 'get'>;
+
+const response = () => {
+ const vary = jest.fn();
+ const res: Pick<Response, 'vary'> = { vary };
+ return { res, vary };
+};
+
+describe('injectDeploymentThemeBoot', () => {
+ it('embeds a bundled name with both resolved modes ahead of the boot script', () => {
+ const html = injectDeploymentThemeBoot(SHELL, 'clickhouse', bundled);
+
+ expect(bootOf(html)).toEqual({ source: 'clickhouse', modes: bundled.clickhouse });
+ expect(html.indexOf(DEPLOYMENT_THEME_BOOT_ID)).toBeLessThan(html.indexOf('boot()'));
+ });
+
+ it('embeds only the source of an inline definition, which the bundle resolves', () => {
+ const inline = { version: 1 as const, name: 'acme', modes: { light: {}, dark: {} } };
+ expect(bootOf(injectDeploymentThemeBoot(SHELL, inline, bundled))).toEqual({ source: inline });
+ });
+
+ it('embeds only the source when the build carries no resolved copy of the name', () => {
+ expect(bootOf(injectDeploymentThemeBoot(SHELL, 'clickhouse', {}))).toEqual({
+ source: 'clickhouse',
+ });
+ });
+
+ it('leaves the shell alone without a deployment theme', () => {
+ expect(injectDeploymentThemeBoot(SHELL, undefined, bundled)).toBe(SHELL);
+ });
+
+ it('does not stack a second block on a shell that has one', () => {
+ const once = injectDeploymentThemeBoot(SHELL, 'clickhouse', bundled);
+ expect(injectDeploymentThemeBoot(once, 'clickhouse', bundled)).toBe(once);
+ });
+
+ it('keeps a `<` in an inline definition from closing the block', () => {
+ const inline = { version: 1 as const, name: '</script><script>alert(1)</script>', modes: {} };
+ const html = injectDeploymentThemeBoot(SHELL, inline, bundled);
+
+ expect(html).not.toContain('</script><script>alert(1)');
+ expect(bootOf(html)?.source).toEqual(inline);
+ });
+
+ it('is not an executable script a strict CSP would have to allow', () => {
+ const html = applyCspNonce(injectDeploymentThemeBoot(SHELL, 'clickhouse', bundled), 'n0nce');
+ expect(bootOf(html.replace(/ nonce="n0nce"/g, ''))?.source).toBe('clickhouse');
+ });
+});
+
+describe('createDeploymentThemeShell', () => {
+ it('serves the themed shell to every request of a single-tenant deployment', () => {
+ const shellFor = createDeploymentThemeShell(SHELL, 'clickhouse', bundled, {});
+ const { res, vary } = response();
+
+ expect(bootOf(shellFor(request({ 'x-tenant-id': 'acme' }), res))?.source).toBe('clickhouse');
+ expect(vary).not.toHaveBeenCalled();
+ });
+
+ it('serves a request scoped to a trusted tenant the shell without the base theme, as the config resolves it', () => {
+ const shellFor = createDeploymentThemeShell(SHELL, 'clickhouse', bundled, {
+ TRUST_TENANT_HEADER: 'true',
+ });
+ const tenant = response();
+ const base = response();
+
+ expect(shellFor(request({ 'x-tenant-id': 'acme' }), tenant.res)).toBe(SHELL);
+ expect(bootOf(shellFor(request(), base.res))?.source).toBe('clickhouse');
+ expect(tenant.vary).toHaveBeenCalledWith('X-Tenant-Id');
+ for (const ignored of ['__SYSTEM__', 'a:b', 'x'.repeat(129), ' ']) {
+ expect(bootOf(shellFor(request({ 'x-tenant-id': ignored }), response().res))?.source).toBe(
+ 'clickhouse',
+ );
+ }
+ expect(base.vary).toHaveBeenCalledWith('X-Tenant-Id');
+ });
+
+ it('serves the plain shell when no theme is configured', () => {
+ const shellFor = createDeploymentThemeShell(SHELL, undefined, bundled, {
+ TRUST_TENANT_HEADER: 'true',
+ });
+ const { res, vary } = response();
+
+ expect(shellFor(request(), res)).toBe(SHELL);
+ expect(vary).not.toHaveBeenCalled();
+ });
+});
+
+describe('readBundledThemeBoot', () => {
+ it('reads what the client build emitted, nothing when it is missing, and reports a broken one', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const dist = fs.mkdtempSync(path.join(os.tmpdir(), 'theme-boot-'));
+ try {
+ expect(readBundledThemeBoot(dist)).toEqual({});
+ fs.writeFileSync(path.join(dist, THEME_BOOT_FILE), JSON.stringify(bundled));
+ expect(readBundledThemeBoot(dist)).toEqual(bundled);
+ expect(warn).not.toHaveBeenCalled();
+ fs.writeFileSync(path.join(dist, THEME_BOOT_FILE), 'null');
+ expect(readBundledThemeBoot(dist)).toEqual({});
+ fs.writeFileSync(path.join(dist, THEME_BOOT_FILE), '{"clickhouse":');
+ expect(readBundledThemeBoot(dist)).toEqual({});
+ expect(warn).toHaveBeenCalledTimes(2);
+ } finally {
+ fs.rmSync(dist, { recursive: true, force: true });
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/packages/api/src/html/theme.ts b/packages/api/src/html/theme.ts
new file mode 100644
index 0000000000..13da41eb9e
--- /dev/null
+++ b/packages/api/src/html/theme.ts
@@ -0,0 +1,81 @@
+import fs from 'fs';
+import path from 'path';
+import { logger } from '@librechat/data-schemas';
+import {
+ THEME_BOOT_FILE,
+ isBundledThemeName,
+ DEPLOYMENT_THEME_BOOT_ID,
+} from 'librechat-data-provider';
+import type { BundledThemeBoot, DeploymentThemeBoot } from 'librechat-data-provider';
+import type { Request, Response } from 'express';
+import { rejectTenantHeader } from '../middleware/tenantHeader';
+import { isEnabled } from '../utils/common';
+
+const TENANT_HEADER = 'X-Tenant-Id';
+
+/**
+ * The bundled themes the client build resolved. Empty when the build predates them, which
+ * leaves a bundled name to the bundle's first render, as for an inline definition; a file that
+ * exists but cannot be read is reported, since the deployment then loses the first paint.
+ */
+export function readBundledThemeBoot(distPath: string): BundledThemeBoot {
+ const file = path.join(distPath, THEME_BOOT_FILE);
+ try {
+ const bundled = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (typeof bundled === 'object' && bundled !== null) {
+ return bundled;
+ }
+ logger.warn(`[DeploymentTheme] Ignoring ${file}: it does not hold an object`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ logger.warn(`[DeploymentTheme] Ignoring unreadable ${file}`, error);
+ }
+ }
+ return {};
+}
+
+/**
+ * Embeds the deployment's `interface.theme` ahead of the shell's boot script, so a first-ever
+ * visit paints it before `/api/config` answers. A bundled name carries both resolved modes for
+ * the boot script; an inline definition carries only its source, which the bundle resolves at
+ * its first render.
+ */
+export function injectDeploymentThemeBoot(
+ html: string,
+ source: DeploymentThemeBoot['source'] | undefined,
+ bundled: BundledThemeBoot,
+): string {
+ if (source == null || html.includes(`id="${DEPLOYMENT_THEME_BOOT_ID}"`)) {
+ return html;
+ }
+ const modes =
+ typeof source === 'string' && isBundledThemeName(source) ? bundled[source] : undefined;
+ const boot: DeploymentThemeBoot = { source, ...(modes && { modes }) };
+ /** A `<` in the payload could close the block; it never has to be raw. */
+ const payload = JSON.stringify(boot).replace(/</g, '\\u003c');
+ const block = `<script type="application/json" id="${DEPLOYMENT_THEME_BOOT_ID}">${payload}</script>`;
+ return html.replace(/<head([^>]*)>/i, (match) => `${match}${block}`);
+}
+
+/**
+ * The shell for a request. The deployment's base theme is only the right first paint where
+ * the signed-out config resolves to the base: a request whose trusted `X-Tenant-Id` header
+ * scopes it to a tenant, by the rule `preAuthTenantMiddleware` applies, gets the shell without
+ * it, since that tenant's theme may differ.
+ */
+export function createDeploymentThemeShell(
+ html: string,
+ source: DeploymentThemeBoot['source'] | undefined,
+ bundled: BundledThemeBoot,
+ env: NodeJS.ProcessEnv = process.env,
+): (req: Pick<Request, 'get'>, res: Pick<Response, 'vary'>) => string {
+ const themed = injectDeploymentThemeBoot(html, source, bundled);
+ if (themed === html || !isEnabled(env.TRUST_TENANT_HEADER)) {
+ return () => themed;
+ }
+ return (req, res) => {
+ res.vary(TENANT_HEADER);
+ const tenantId = req.get(TENANT_HEADER)?.trim();
+ return tenantId && !rejectTenantHeader(tenantId) ? html : themed;
+ };
+}
diff --git a/packages/api/src/middleware/preAuthTenant.ts b/packages/api/src/middleware/preAuthTenant.ts
index 90ea29e01a..4aa41d332e 100644
--- a/packages/api/src/middleware/preAuthTenant.ts
+++ b/packages/api/src/middleware/preAuthTenant.ts
@@ -1,6 +1,7 @@
-import { logger, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import { logger } from '@librechat/data-schemas';
import type { Request, Response, NextFunction } from 'express';
import { buildRequestContext, runWithTenantContext } from './tenant';
+import { rejectTenantHeader } from './tenantHeader';
import { isEnabled } from '~/utils';
/**
@@ -32,9 +33,6 @@ import { isEnabled } from '~/utils';
* If no header is present, downstream runs without tenant ALS context (same as
* single-tenant mode), while request logging context can still propagate.
*/
-const MAX_TENANT_ID_LENGTH = 128;
-const VALID_TENANT_ID = /^[-a-zA-Z0-9_.]+$/;
-
export function preAuthTenantMiddleware(req: Request, res: Response, next: NextFunction): void {
const raw = req.headers['x-tenant-id'];
const requestContext = buildRequestContext(req);
@@ -51,7 +49,8 @@ export function preAuthTenantMiddleware(req: Request, res: Response, next: NextF
return;
}
- if (tenantId === SYSTEM_TENANT_ID) {
+ const rejection = rejectTenantHeader(tenantId);
+ if (rejection === 'system') {
runWithTenantContext(requestContext, () => {
logger.warn('[preAuthTenant] Rejected __SYSTEM__ sentinel in X-Tenant-Id header', {
ip: req.ip,
@@ -62,7 +61,7 @@ export function preAuthTenantMiddleware(req: Request, res: Response, next: NextF
return;
}
- if (tenantId.length > MAX_TENANT_ID_LENGTH || !VALID_TENANT_ID.test(tenantId)) {
+ if (rejection === 'malformed') {
runWithTenantContext(requestContext, () => {
logger.warn('[preAuthTenant] Rejected malformed X-Tenant-Id header', {
ip: req.ip,
diff --git a/packages/api/src/middleware/tenantHeader.ts b/packages/api/src/middleware/tenantHeader.ts
new file mode 100644
index 0000000000..8ce3aeca83
--- /dev/null
+++ b/packages/api/src/middleware/tenantHeader.ts
@@ -0,0 +1,18 @@
+import { SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+
+const MAX_TENANT_ID_LENGTH = 128;
+const VALID_TENANT_ID = /^[-a-zA-Z0-9_.]+$/;
+
+/**
+ * Why a trusted `X-Tenant-Id` value names no tenant: the system sentinel, or a value that is
+ * too long or carries characters outside the tenant id alphabet. `undefined` accepts it.
+ */
+export function rejectTenantHeader(tenantId: string): 'system' | 'malformed' | undefined {
+ if (tenantId === SYSTEM_TENANT_ID) {
+ return 'system';
+ }
+ if (tenantId.length > MAX_TENANT_ID_LENGTH || !VALID_TENANT_ID.test(tenantId)) {
+ return 'malformed';
+ }
+ return undefined;
+}
diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts
index 93c8354393..20e237f365 100644
--- a/packages/client/src/theme/utils/applyTheme.ts
+++ b/packages/client/src/theme/utils/applyTheme.ts
@@ -1,3 +1,4 @@
+import type { ThemeBootStyle } from 'librechat-data-provider';
import type { IThemeAppearance, IThemeBrands, IThemeRGB, ResolvedThemeDefinition } from '../types';
import type { RenamedThemeRGB } from '../registry';
import {
@@ -236,10 +237,7 @@ export function clearAppliedTheme(root: HTMLElement = document.documentElement):
}
/** What `applyResolvedTheme` writes on the root, as plain data a boot script can replay. */
-export type ResolvedThemeStyle = {
- properties: Array<[string, string]>;
- attributes: Record<string, string>;
-};
+export type ResolvedThemeStyle = ThemeBootStyle;
export function describeResolvedTheme(theme: ResolvedThemeDefinition): ResolvedThemeStyle {
return {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 595609df31..20253a1ee1 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2751,6 +2751,32 @@ export function normalizeCodeHighlightThrottleMs(value: unknown): number {
: DEFAULT_CODE_HIGHLIGHT_THROTTLE_MS;
}
+/** One resolved theme mode as plain data: what the shell's boot script replays on the root. */
+export type ThemeBootStyle = {
+ properties: Array<[string, string]>;
+ attributes: Record<string, string>;
+};
+
+export type ThemeBootModes = { light: ThemeBootStyle; dark: ThemeBootStyle };
+
+/** Each bundled theme resolved at build time, in `THEME_BOOT_FILE` beside the shell. */
+export type BundledThemeBoot = Record<string, ThemeBootModes>;
+
+/** The build output the server reads to hand a bundled theme to the shell's boot script. */
+export const THEME_BOOT_FILE = 'theme-boot.json';
+
+/**
+ * The id of the JSON block the server embeds in the HTML shell with the deployment's base
+ * `interface.theme`, so a first-ever visit paints it before `/api/config` answers. `modes`
+ * is present only for a bundled name; an inline definition is resolved by the bundle.
+ */
+export const DEPLOYMENT_THEME_BOOT_ID = 'deployment-theme-boot';
+
+export type DeploymentThemeBoot = {
+ source: z.infer<typeof deploymentThemeSchema>;
+ modes?: ThemeBootModes;
+};
+
/** Single source for the agents panel selector's unsearched list cap; the
* schema default and the client fallback both read it. */
export const DEFAULT_AGENT_SELECTOR_LIMIT = 10;