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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🖼️ fix: Paint the Shared Link Tenant's Deployment Theme (#16333)
Marco Beretta3c4aa1a78439
diff --git a/api/server/routes/share.js b/api/server/routes/share.jsindex 3cd5761cb1..b64c278f70 100644--- a/api/server/routes/share.js+++ b/api/server/routes/share.js@@ -60,6 +60,10 @@ const configMiddleware = require('~/server/middleware/config/app');const { getAppConfig } = require('~/server/services/Config/app');const router = express.Router();const sharedLinkConfigMiddleware = createSharedLinkConfigMiddleware({ getAppConfig });+const sharedStartupConfigMiddleware = createSharedLinkConfigMiddleware({+ getAppConfig,+ failClosed: true,+});const getSharedLangfuseSessionUrl = createSharedLangfuseSessionResolver({getHeldCapabilities,@@ -346,7 +350,7 @@ if (allowSharedLinks) {'/:shareId/config',optionalJwtAuth,canAccessSharedLink,- sharedLinkConfigMiddleware,+ sharedStartupConfigMiddleware,(req, res) => {try {const payload = buildSharedLinkStartupPayload(req.config);diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsxindex f1138a3804..fadafaeb2b 100644--- a/client/src/Providers/DeploymentTheme.tsx+++ b/client/src/Providers/DeploymentTheme.tsx@@ -1,4 +1,13 @@-import { useEffect, useMemo, useReducer, useRef, useState } from 'react';+import {+ useRef,+ useMemo,+ useState,+ useEffect,+ useReducer,+ useContext,+ createContext,+ useLayoutEffect,+} from 'react';import { QueryKeys } from 'librechat-data-provider';import { notifyManager, useQueryClient } from '@tanstack/react-query';import {@@ -116,6 +125,32 @@ function useRebindOnStartupConfigRebuild() {);}+/** A route's own deployment theme source; `undefined` defers to the startup config. */+type ThemeOverride = { theme: DeploymentThemeValue } | undefined;++const DeploymentThemeOverrideContext = createContext<(override: ThemeOverride) => void>(+ () => undefined,+);++/**+ * Lets a route whose policy comes from another tenant paint that tenant's theme:+ * once `ready`, `theme` replaces `interface.theme` from the startup config, an+ * absent theme included, until the route unmounts. A route whose theme source+ * failed passes `ready` with no theme, so the viewer's theme does not stand in+ * for the link's. Registered in a layout effect so the wrapper re-renders in the+ * same commit; `ThemeProvider` still applies the change in its own effects.+ */+export function useDeploymentThemeOverride(ready: boolean, theme: DeploymentThemeValue) {+ const setOverride = useContext(DeploymentThemeOverrideContext);+ useLayoutEffect(() => {+ if (!ready) {+ return;+ }+ setOverride({ theme });+ return () => setOverride(undefined);+ }, [ready, theme, setOverride]);+}+/*** Supplies the deployment theme from the startup config to `ThemeProvider`.* Precedence: high-contrast modes (inside the provider), then `interface.theme`,@@ -126,7 +161,8 @@ export default function DeploymentTheme({ children }: { children: React.ReactNodconst envTheme = useMemo(() => getThemeFromEnv(), []);useRebindOnStartupConfigRebuild();const { data: startupConfig } = useGetStartupConfig({ keepPreviousData: true });- const configTheme = startupConfig?.interface?.theme;+ const [override, setOverride] = useState<ThemeOverride>(undefined);+ const configTheme = override ? override.theme : startupConfig?.interface?.theme;const themeDefinition = useMemo(() => resolveDeploymentTheme(configTheme), [configTheme]);/**@@ -167,5 +203,9 @@ export default function DeploymentTheme({ children }: { children: React.ReactNod...(persistenceOff && { persistThemeDefinition: false }),};- return <ThemeProvider {...props}>{children}</ThemeProvider>;+ return (+ <DeploymentThemeOverrideContext.Provider value={setOverride}>+ <ThemeProvider {...props}>{children}</ThemeProvider>+ </DeploymentThemeOverrideContext.Provider>+ );}diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsxindex 4376e4360e..79f2d141d5 100644--- a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx+++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx@@ -5,8 +5,8 @@ import { act, render, waitFor } from '@testing-library/react';import { QueryKeys, dataService } from 'librechat-data-provider';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { TStartupConfig } from 'librechat-data-provider';+import DeploymentTheme, { useDeploymentThemeOverride } from '../DeploymentTheme';import { useGetStartupConfig } from '~/data-provider';-import DeploymentTheme from '../DeploymentTheme';const mockGetThemeFromEnv = jest.fn();@@ -72,12 +72,27 @@ function LateRoute() {return mounted ? <StartupConsumer /> : null;}+let showSharedRoute: (theme: ConfigTheme | null) => void = () => undefined;++/** Stands in for the share route; `null` unmounts it, `undefined` serves no theme. */+function SharedRoute() {+ const [route, setRoute] = useState<{ theme: ConfigTheme } | null>(null);+ showSharedRoute = (theme) => setRoute(theme === null ? null : { theme });+ return route ? <SharedThemeSource theme={route.theme} /> : null;+}++function SharedThemeSource({ theme }: { theme: ConfigTheme }) {+ useDeploymentThemeOverride(true, theme);+ return null;+}+function renderTheme(queryClient: QueryClient) {return render(<RecoilRoot><QueryClientProvider client={queryClient}><DeploymentTheme><LateRoute />+ <SharedRoute /><ThemeEditor /></DeploymentTheme></QueryClientProvider>@@ -283,6 +298,31 @@ describe('DeploymentTheme', () => {expect(snapshotStorage()).toEqual(before);});+ it('paints the theme a route supplies over the startup config until it unmounts', async () => {+ serveTheme('clickhouse');+ renderTheme(queryClient);+ await waitFor(() => expect(root().dataset.theme).toBe('clickhouse'));++ act(() => showSharedRoute(inlineTheme));+ await waitFor(() => expect(root().dataset.theme).toBe('acme'));+ expect(root().style.getPropertyValue('--surface-primary')).toBe('10 20 30');++ act(() => showSharedRoute(null));+ await waitFor(() => expect(root().dataset.theme).toBe('clickhouse'));+ expect(localStorage.getItem('theme-definition')).toBe(JSON.stringify(storedDefinition));+ });++ it('shows the stored theme when a route supplies no deployment theme', async () => {+ serveTheme('clickhouse');+ renderTheme(queryClient);+ await waitFor(() => expect(root().dataset.theme).toBe('clickhouse'));++ act(() => showSharedRoute(undefined));+ await waitFor(() => expect(root().dataset.theme).toBe('stored'));+ expect(root().style.getPropertyValue('--accent-primary')).toBe('1 2 3');+ expect(localStorage.getItem('theme-definition')).toBe(JSON.stringify(storedDefinition));+ });+it('picks up the theme after the auth flow removes the startup config query', async () => {const before = snapshotStorage();getStartupConfig.mockReturnValueOnce(new Promise(() => undefined));diff --git a/client/src/components/Share/ShareView.tsx b/client/src/components/Share/ShareView.tsxindex a9d231ef70..6ff8538151 100644--- a/client/src/components/Share/ShareView.tsx+++ b/client/src/components/Share/ShareView.tsx@@ -27,6 +27,7 @@ import {import SharedSubagentActivityDialog from '~/components/Chat/Subagents/SharedSubagentActivityDialog';import { cn, DEFAULT_APP_TITLE, getResponseStatus, selectActiveBranchTail } from '~/utils';import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';+import { useDeploymentThemeOverride } from '~/Providers/DeploymentTheme';import { useLocalize, useDocumentTitle, useAuthContext } from '~/hooks';import { ThemeSelector, LangSelector } from '~/components/Appearance';import { ShareMessagesProvider } from './ShareMessagesProvider';@@ -50,7 +51,14 @@ function SharedView() {const { theme, setTheme } = useContext(ThemeContext);const { shareId } = useParams();const jotaiStore = useStore();- const { data: config } = useGetSharedStartupConfig(shareId, { enabled: isAuthReady });+ const {+ data: config,+ isError: configFailed,+ isInitialLoading: configLoading,+ } = useGetSharedStartupConfig(shareId, {+ enabled: isAuthReady,+ });+ useDeploymentThemeOverride(config != null || configFailed, config?.interface?.theme);const { data, isLoading, isFetching, refetch } = useGetSharedMessages(shareId ?? '', {enabled: isAuthReady,});@@ -175,7 +183,7 @@ function SharedView() {);let content: JSX.Element;- if (!isAuthReady || isLoading) {+ if (!isAuthReady || isLoading || configLoading) {content = (<div className="flex h-screen items-center justify-center"><Spinner className="" />@@ -215,7 +223,7 @@ function SharedView() {}const footer = (- <div className="from-surface-secondary pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-40% to-transparent">+ <div className="from-presentation pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-40% to-transparent"><FooterstartupConfig={config ?? null}className="text-text-secondary pointer-events-auto relative mx-auto flex max-w-7xl flex-wrap items-center justify-center gap-2 px-3 pt-6 pb-4 text-center text-xs"@@ -224,7 +232,7 @@ function SharedView() {);const mainContent = (- <div className="bg-surface-secondary relative flex h-full w-full flex-1 flex-col items-stretch overflow-hidden pt-0">+ <div className="bg-presentation relative flex h-full w-full flex-1 flex-col items-stretch overflow-hidden pt-0"><div className="text-text-primary relative flex h-full min-h-0 flex-col" role="presentation">{content}{footer}@@ -251,8 +259,8 @@ function SharedView() {value={{ isSharedConvo: true, shareId, hasConfiguredSender: data?.hasConfiguredSender }}><AppChatSurface>- <div className="dark:bg-surface-secondary relative flex h-screen w-full overflow-hidden">- <main className="dark:bg-surface-secondary relative flex w-full grow overflow-hidden">+ <div className="bg-presentation relative flex h-screen w-full overflow-hidden">+ <main className="bg-presentation relative flex w-full grow overflow-hidden">{artifactsContainer}</main></div>diff --git a/e2e/specs/mock/scenarios/share-deployment-theme.spec.ts b/e2e/specs/mock/scenarios/share-deployment-theme.spec.tsnew file mode 100644index 0000000000..149b6762b0--- /dev/null+++ b/e2e/specs/mock/scenarios/share-deployment-theme.spec.ts@@ -0,0 +1,206 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';+import { defaultTheme } from '../../../../packages/client/src/theme/themes/default';+import { darkTheme } from '../../../../packages/client/src/theme/themes/dark';+import {+ sendMessageAndWaitForCompletion,+ selectMockEndpoint,+ getAccessToken,+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+} from '../helpers';+import { themeValue } from './style.helpers';++/**+ * A shared link resolves its policy from the tenant that owns it, so the viewer's+ * tenant and the link's tenant can configure different `interface.theme` values.+ * The two tenants are stood in for by the two payloads: `/api/config` carries the+ * viewer tenant's theme and `/api/share/:shareId/config` the link tenant's, each+ * layered over the real server response.+ */++type Mode = 'light' | 'dark';+/** `null` serves a payload with no `interface.theme`. */+type ConfigTheme = string | Record<string, unknown> | null;++const VIEWER_THEME = {+ version: 1,+ name: 'viewer',+ modes: {+ light: { colors: { 'rgb-surface-primary': '240 244 255' } },+ dark: { colors: { 'rgb-surface-primary': '12 16 32' } },+ },+};++async function serveThemes(page: Page, viewer: ConfigTheme, link: ConfigTheme) {+ const withTheme = (payload: { interface?: Record<string, unknown> }, theme: ConfigTheme) => {+ const served = { ...payload.interface };+ delete served.theme;+ if (theme !== null) {+ served.theme = theme;+ }+ return { ...payload, interface: served };+ };+ await page.route(+ (url) => url.pathname === '/api/config',+ async (route) => {+ const response = await route.fetch();+ await route.fulfill({ response, json: withTheme(await response.json(), viewer) });+ },+ );+ await page.route(+ (url) => /^\/api\/share\/[^/]+\/config$/.test(url.pathname),+ async (route) => {+ const response = await route.fetch();+ await route.fulfill({ response, json: withTheme(await response.json(), link) });+ },+ );+}++/** Creates a public link to a fresh conversation through the share API. */+async function createSharedLink(page: Page, text = `Shared theme ${Date.now()}`): Promise<string> {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, text);+ await expect(page).toHaveURL(/\/c\/(?!new)[0-9a-fA-F-]{36}$/);+ const conversationId = new URL(page.url()).pathname.split('/').pop();+ const token = await getAccessToken(page);+ const response = await page.request.post(`/api/share/${conversationId}`, {+ headers: { Authorization: `Bearer ${token}` },+ data: {},+ });+ expect(response.ok()).toBeTruthy();+ const { shareId } = (await response.json()) as { shareId?: string };+ if (!shareId) {+ throw new Error('Expected create-share response to include a shareId');+ }+ return shareId;+}++async function openSharedLink(page: Page, shareId: string) {+ await Promise.all([+ page.waitForResponse(+ (res) => new URL(res.url()).pathname === `/api/share/${shareId}/config` && res.ok(),+ ),+ page.goto(`/share/${shareId}`, { timeout: 10000 }),+ ]);+ await expect(page.getByTestId('messages-view')).toBeVisible({ timeout: 20000 });+}++const backgroundOf = (page: Page, selector: string) =>+ page+ .locator(selector)+ .first()+ .evaluate((node) => getComputedStyle(node).backgroundColor);++async function resolvedMode(page: Page): Promise<Mode> {+ const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));+ return dark ? 'dark' : 'light';+}++async function expectViewerTheme(page: Page) {+ const mode = await resolvedMode(page);+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'viewer');+ expect(await themeValue(page, '--surface-primary')).toBe(+ VIEWER_THEME.modes[mode].colors['rgb-surface-primary'],+ );+}++test.describe('deployment theme on a shared link', () => {+ test("a shared link paints its own tenant's deployment theme, not the viewer's @scenario:shared-link-paints-link-tenant-theme", async ({+ page,+ }) => {+ test.setTimeout(120000);+ await serveThemes(page, VIEWER_THEME, 'clickhouse');+ const shareId = await createSharedLink(page);+ await expectViewerTheme(page);++ await openSharedLink(page, shareId);+ const colors = clickHouseTheme.modes[await resolvedMode(page)]?.colors ?? {};+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');+ expect(await themeValue(page, '--surface-primary')).toBe(colors['rgb-surface-primary']);+ expect(await page.evaluate(() => localStorage.getItem('theme-definition'))).toBeNull();++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await expectViewerTheme(page);+ });++ test("a shared link whose tenant sets no theme does not paint the viewer's @scenario:shared-link-without-theme-skips-viewer-theme", async ({+ page,+ }) => {+ test.setTimeout(120000);+ await serveThemes(page, VIEWER_THEME, null);+ const shareId = await createSharedLink(page);+ await expectViewerTheme(page);++ await openSharedLink(page, shareId);+ const palette = (await resolvedMode(page)) === 'dark' ? darkTheme : defaultTheme;+ await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'viewer');+ expect(await themeValue(page, '--surface-primary')).toBe(palette['rgb-surface-primary']);+ });++ test('the user bubble on a shared link stands out from the page like it does in chat @scenario:shared-link-user-bubble-visible', async ({+ page,+ }) => {+ test.setTimeout(120000);+ const text = `Bubble ${Date.now()}`;+ await serveThemes(page, null, 'clickhouse');+ const shareId = await createSharedLink(page, text);++ await openSharedLink(page, shareId);+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');+ const bubble = page.getByTestId('message-body').filter({ hasText: text });+ await expect(bubble).toBeVisible();+ const bubbleColor = await bubble.evaluate((node) => getComputedStyle(node).backgroundColor);+ expect(await backgroundOf(page, 'main')).toBe(+ await page.evaluate(() => {+ const probe = document.createElement('div');+ probe.className = 'bg-presentation';+ document.body.appendChild(probe);+ const color = getComputedStyle(probe).backgroundColor;+ probe.remove();+ return color;+ }),+ );+ expect(bubbleColor).not.toBe(await backgroundOf(page, 'main'));+ });++ test("a shared link whose config request fails does not keep the viewer's theme @scenario:shared-link-config-failure-drops-viewer-theme", async ({+ page,+ }) => {+ test.setTimeout(120000);+ await serveThemes(page, VIEWER_THEME, null);+ const shareId = await createSharedLink(page);+ await expectViewerTheme(page);+ await page.route(+ (url) => url.pathname === `/api/share/${shareId}/config`,+ (route) => route.fulfill({ status: 500, json: { message: 'unavailable' } }),+ );++ await page.goto(`/share/${shareId}`, { timeout: 10000 });+ await expect(page.getByTestId('messages-view')).toBeVisible({ timeout: 20000 });+ await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'viewer', {+ timeout: 30000,+ });+ });++ test("a slow shared config never shows the conversation in the viewer's theme @scenario:shared-link-waits-for-link-theme", async ({+ page,+ }) => {+ test.setTimeout(120000);+ await serveThemes(page, VIEWER_THEME, 'clickhouse');+ const shareId = await createSharedLink(page);+ await page.route(+ (url) => url.pathname === `/api/share/${shareId}/config`,+ async (route) => {+ await new Promise((resolve) => setTimeout(resolve, 3000));+ await route.fallback();+ },+ );++ await page.goto(`/share/${shareId}`, { timeout: 10000 });+ await page.getByTestId('messages-view').waitFor({ timeout: 20000 });+ expect(await page.locator('html').getAttribute('data-theme')).toBe('clickhouse');+ });+});diff --git a/packages/api/src/shared-links/config.test.ts b/packages/api/src/shared-links/config.test.tsindex b89b2bb344..356a55d8cd 100644--- a/packages/api/src/shared-links/config.test.ts+++ b/packages/api/src/shared-links/config.test.ts@@ -1,5 +1,6 @@import { FileSources } from 'librechat-data-provider';import { getTenantId, SYSTEM_TENANT_ID } from '@librechat/data-schemas';+import type { TThemeDefinitionConfig } from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';import {resolveSharedLinkConfig,@@ -63,6 +64,37 @@ describe('shared-link config resolution', () => {);});+describe('fail-closed shared-link config', () => {+ const overridesUnavailable = new Error('overrides unavailable');+ /** Mirrors getAppConfig: a failed override lookup substitutes the base config unless failClosed. */+ const getAppConfig = jest.fn(async (options?: { failClosed?: boolean }) => {+ if (options?.failClosed) {+ throw overridesUnavailable;+ }+ return appConfig({ interfaceConfig: { theme: 'librechat' } });+ });++ it('rejects instead of serving the base config for a tenant link when failClosed', async () => {+ const middleware = createSharedLinkConfigMiddleware({ getAppConfig, failClosed: true });+ const req = Object.assign({} as Parameters<typeof middleware>[0], {+ shareTenantId: 'tenant-owner',+ });+ const next = jest.fn();++ await middleware(req, {} as Parameters<typeof middleware>[1], next);++ expect(next).toHaveBeenCalledWith(overridesUnavailable);+ expect(req.config).toBeUndefined();+ });++ it('keeps the base-config fallback for the default middleware', async () => {+ const config = await resolveSharedLinkConfig(getAppConfig, 'tenant-owner');++ expect(getAppConfig).toHaveBeenLastCalledWith({ tenantId: 'tenant-owner' });+ expect(config.interfaceConfig?.theme).toBe('librechat');+ });+});+describe('isFileSnapshotEnabled', () => {const original = process.env.SHARED_LINKS_SNAPSHOT_FILES;@@ -150,6 +182,46 @@ describe('buildSharedLinkStartupPayload', () => {});});+ it.each<[string, TThemeDefinitionConfig | string]>([+ ['a bundled name', 'clickhouse'],+ [+ 'an inline definition',+ {+ version: 1,+ name: 'acme',+ modes: { light: { colors: { 'rgb-surface-primary': '1 2 3' } } },+ },+ ],+ ])('carries the link tenant deployment theme as %s', (_label, theme) => {+ const payload = buildSharedLinkStartupPayload(+ appConfig({ interfaceConfig: { theme, modelSelect: true } }),+ {},+ );++ expect(payload).toEqual({ appTitle: 'LibreChat', interface: { theme } });+ });++ it('omits a theme that does not match the deployment theme schema', () => {+ const payload = buildSharedLinkStartupPayload(+ appConfig({ interfaceConfig: { theme: { name: 'broken', modes: {} } } }),+ {},+ );++ expect(payload).toEqual({ appTitle: 'LibreChat' });+ });++ it('serves the share tenant theme rather than the viewer tenant theme', async () => {+ const configs: Record<string, AppConfig> = {+ 'tenant-owner': appConfig({ interfaceConfig: { theme: 'clickhouse' } }),+ 'tenant-viewer': appConfig({ interfaceConfig: { theme: 'librechat' } }),+ };+ const getAppConfig = jest.fn(async () => configs[getTenantId() ?? ''] ?? appConfig());++ const config = await resolveSharedLinkConfig(getAppConfig, 'tenant-owner');++ expect(buildSharedLinkStartupPayload(config, {}).interface).toEqual({ theme: 'clickhouse' });+ });+it('defaults the app title and omits unrelated interface config', () => {const payload = buildSharedLinkStartupPayload(appConfig({ interfaceConfig: { modelSelect: true } }),diff --git a/packages/api/src/shared-links/config.ts b/packages/api/src/shared-links/config.tsindex d6952683a1..987ae5efec 100644--- a/packages/api/src/shared-links/config.ts+++ b/packages/api/src/shared-links/config.ts@@ -1,3 +1,4 @@+import { deploymentThemeSchema } from 'librechat-data-provider';import { tenantStorage, SYSTEM_TENANT_ID } from '@librechat/data-schemas';import type { TSharedLinkStartupConfig } from 'librechat-data-provider';import type { Request, Response, NextFunction } from 'express';@@ -14,27 +15,35 @@ interface SharedLinkConfigRequest extends Request {interface SharedLinkConfigMiddlewareDeps {getAppConfig: (options?: GetAppConfigOptions) => Promise<AppConfig>;+ /** Reject instead of substituting the base config when the tenant's overrides fail to load. */+ failClosed?: boolean;}/** Resolve shared-link policy independently of the authenticated viewer. */export async function resolveSharedLinkConfig(getAppConfig: SharedLinkConfigMiddlewareDeps['getAppConfig'],tenantId?: string,+ failClosed?: boolean,): Promise<AppConfig> {if (tenantId && tenantId !== SYSTEM_TENANT_ID) {- return tenantStorage.run({ tenantId }, () => getAppConfig({ tenantId }));+ return tenantStorage.run({ tenantId }, () =>+ getAppConfig({ tenantId, ...(failClosed && { failClosed }) }),+ );}return getAppConfig({ baseOnly: true });}-export function createSharedLinkConfigMiddleware({ getAppConfig }: SharedLinkConfigMiddlewareDeps) {+export function createSharedLinkConfigMiddleware({+ getAppConfig,+ failClosed,+}: SharedLinkConfigMiddlewareDeps) {return async function sharedLinkConfigMiddleware(req: SharedLinkConfigRequest,_res: Response,next: NextFunction,): Promise<void> {try {- req.config = await resolveSharedLinkConfig(getAppConfig, req.shareTenantId);+ req.config = await resolveSharedLinkConfig(getAppConfig, req.shareTenantId, failClosed);next();} catch (error) {next(error);@@ -96,11 +105,14 @@ export function buildSharedLinkStartupPayload(const { privacyPolicy, termsOfService, codeHighlightThrottleMs } =appConfig?.interfaceConfig ?? {};- if (privacyPolicy || termsOfService || codeHighlightThrottleMs != null) {+ const parsedTheme = deploymentThemeSchema.safeParse(appConfig?.interfaceConfig?.theme);+ const theme = parsedTheme.success ? parsedTheme.data : undefined;+ if (privacyPolicy || termsOfService || codeHighlightThrottleMs != null || theme) {payload.interface = {...(codeHighlightThrottleMs != null ? { codeHighlightThrottleMs } : {}),...(privacyPolicy ? { privacyPolicy } : {}),...(termsOfService ? { termsOfService } : {}),+ ...(theme ? { theme } : {}),};}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 934eb8a2f0..8b66fdf554 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -2316,10 +2316,12 @@ export const themeDefinitionSchema = zexport type TThemeDefinitionConfig = z.infer<typeof themeDefinitionSchema>;+/** A bundled theme name or an inline theme definition applied to every user. */+export const deploymentThemeSchema = z.union([z.string().trim().min(1), themeDefinitionSchema]);+export const interfaceSchema = z.object({- /** A bundled theme name or an inline theme definition applied to every user. */- theme: z.union([z.string().trim().min(1), themeDefinitionSchema]).optional(),+ theme: deploymentThemeSchema.optional(),privacyPolicy: z.object({externalUrl: z.string().optional(),@@ -2833,7 +2835,7 @@ export type TStartupConfig = {export type TSharedLinkStartupInterface = Pick<Partial<TInterfaceConfig>,- 'privacyPolicy' | 'termsOfService' | 'codeHighlightThrottleMs'+ 'privacyPolicy' | 'termsOfService' | 'codeHighlightThrottleMs' | 'theme'>;export type TSharedLinkStartupConfig = Pick<TStartupConfig, 'appTitle'> &