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

🪪 fix: Boot-Paint a Cached Theme Only for Its Signed-In Owner (#16926)

Marco Beretta80e370796405
diff --git a/api/cache/banViolation.js b/api/cache/banViolation.js
index acae73b91e..c4ee7ac469 100644
--- a/api/cache/banViolation.js
+++ b/api/cache/banViolation.js
@@ -1,6 +1,12 @@
const { logger } = require('@librechat/data-schemas');
const { ViolationTypes } = require('librechat-data-provider');
-const { isEnabled, math, removePorts, getBanIp } = require('@librechat/api');
+const {
+ isEnabled,
+ math,
+ removePorts,
+ getBanIp,
+ clearSessionHintCookie,
+} = require('@librechat/api');
const { deleteAllUserSessions } = require('~/models');
const getLogStores = require('./getLogStores');
@@ -57,6 +63,7 @@ const banViolation = async (req, res, errorMessage) => {
res.clearCookie('openid_id_token');
res.clearCookie('openid_user_id');
res.clearCookie('token_provider');
+ clearSessionHintCookie(res);
const banLogs = getLogStores(ViolationTypes.BAN);
const duration = errorMessage.duration || banLogs.opts.ttl;
diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js
index 3299baa8c7..c814548472 100644
--- a/api/server/controllers/AuthController.js
+++ b/api/server/controllers/AuthController.js
@@ -19,6 +19,7 @@ const {
isTwoFactorEnrollmentRequired,
getSafeErrorMetadata,
sanitizeUserForAuthResponse,
+ clearSessionHintCookie,
} = require('@librechat/api');
const {
requestPasswordReset,
@@ -328,6 +329,7 @@ const refreshController = async (req, res) => {
selectOpenIDRefreshToken(req.session?.openidTokens, parsedCookies);
if (!refreshToken) {
+ clearSessionHintCookie(res);
return res.status(200).send('Refresh token not provided');
}
@@ -395,6 +397,7 @@ const refreshController = async (req, res) => {
req.session?.openidTokens?.appUserId ??
getValidOpenIDReuseCredential(parsedCookies, process.env.JWT_REFRESH_SECRET)?.userId;
if (!refreshUserId) {
+ clearSessionHintCookie(res);
return res.status(403).send('Invalid OpenID refresh token');
}
@@ -402,6 +405,7 @@ const refreshController = async (req, res) => {
getUserById(refreshUserId, AUTH_REFRESH_USER_PROJECTION),
);
if (!refreshUser) {
+ clearSessionHintCookie(res);
return res.status(403).send('Invalid OpenID refresh token');
}
@@ -442,6 +446,7 @@ const refreshController = async (req, res) => {
logger.warn(
`[refreshController] Redirecting to /login: error=${error ?? 'null'}, user=${user ? 'exists' : 'null'}`,
);
+ clearSessionHintCookie(res);
return res.status(401).redirect('/login');
}
@@ -453,6 +458,7 @@ const refreshController = async (req, res) => {
resolvedUserId: user._id.toString(),
},
);
+ clearSessionHintCookie(res);
return res.status(401).redirect('/login');
}
@@ -539,6 +545,7 @@ const refreshController = async (req, res) => {
getUserById(userId, AUTH_REFRESH_USER_PROJECTION),
);
if (!bridgeUser) {
+ clearSessionHintCookie(res);
return res.status(403).send('Invalid OpenID refresh token');
}
@@ -598,6 +605,7 @@ const refreshController = async (req, res) => {
}
}
+ clearSessionHintCookie(res);
return res.status(403).send('Invalid OpenID refresh token');
}
}
diff --git a/api/server/controllers/AuthController.spec.js b/api/server/controllers/AuthController.spec.js
index ead5410d6a..62b3307c6f 100644
--- a/api/server/controllers/AuthController.spec.js
+++ b/api/server/controllers/AuthController.spec.js
@@ -671,6 +671,7 @@ describe('refreshController – OpenID path', () => {
status: jest.fn().mockReturnThis(),
send: jest.fn().mockReturnThis(),
redirect: jest.fn(),
+ clearCookie: jest.fn(),
};
});
@@ -1573,6 +1574,44 @@ describe('refreshController – OpenID path', () => {
expect(res.send).toHaveBeenCalledWith('Invalid OpenID refresh token');
});
+ it('retires the readable session hint when the IdP rejects the refresh token', async () => {
+ openIdClient.refreshTokenGrant.mockRejectedValue(new Error('invalid_grant'));
+
+ await refreshController(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ });
+
+ it('retires the readable session hint when the refreshed identity resolves a different user', async () => {
+ findOpenIDUser.mockResolvedValue({
+ user: { ...defaultUser, _id: 'different-user-id' },
+ error: null,
+ migration: false,
+ });
+
+ await refreshController(req, res);
+
+ expect(res.redirect).toHaveBeenCalledWith('/login');
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ });
+
+ it('retires the readable session hint when the refresh owner no longer exists', async () => {
+ getUserById.mockResolvedValue(null);
+
+ await refreshController(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ });
+
+ it('keeps the readable session hint on a successful OpenID refresh', async () => {
+ await refreshController(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.clearCookie).not.toHaveBeenCalledWith('session_hint');
+ });
+
it('does not use the bridge when signed user-id cookie payload is invalid', async () => {
setOpenIDReuseCookies(jwt.sign({ id: 123 }, process.env.JWT_REFRESH_SECRET));
openIdClient.refreshTokenGrant.mockRejectedValue(new Error('invalid_grant'));
@@ -2384,6 +2423,7 @@ describe('refreshController – OpenID path', () => {
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith('Refresh token not provided');
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
});
});
@@ -2682,6 +2722,44 @@ describe('refreshController – LibreChat path', () => {
expect(res.send).toHaveBeenCalledWith('Refresh token expired or not found for this user');
});
+ it('clears the readable session hint when no refresh token is sent', async () => {
+ req.headers.cookie = '';
+
+ await refreshController(req, res);
+
+ expect(res.send).toHaveBeenCalledWith('Refresh token not provided');
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ });
+
+ it('clears the readable session hint when the refresh session is gone', async () => {
+ getUserById.mockResolvedValue({ _id: 'local-user-id', provider: 'local' });
+ findSession.mockResolvedValue(null);
+
+ await refreshController(req, res);
+
+ expect(setAuthTokens).not.toHaveBeenCalled();
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ expect(res.status).toHaveBeenCalledWith(401);
+ });
+
+ it('clears the readable session hint when the refresh token is invalid', async () => {
+ req.headers.cookie = 'refreshToken=not-a-jwt';
+
+ await refreshController(req, res);
+
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
+ expect(res.status).toHaveBeenCalledWith(403);
+ });
+
+ it('keeps the readable session hint on a successful refresh', async () => {
+ getUserById.mockResolvedValue({ _id: 'local-user-id', provider: 'local' });
+
+ await refreshController(req, res);
+
+ expect(setAuthTokens).toHaveBeenCalled();
+ expect(res.clearCookie).not.toHaveBeenCalledWith('session_hint');
+ });
+
it('preserves CI refresh compatibility without session lookup', async () => {
process.env.NODE_ENV = 'CI';
getUserById.mockResolvedValue({
@@ -2847,6 +2925,7 @@ describe('resetPasswordController', () => {
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
+ clearCookie: jest.fn(),
};
});
@@ -2861,6 +2940,7 @@ describe('resetPasswordController', () => {
expect(resetPassword).toHaveBeenCalledWith('user-123', 'reset-token', 'new-password');
expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-123' });
expect(deletePasskeysByUser).toHaveBeenCalledWith('user-123');
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(serviceResult);
});
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js
index 9c57a6d584..446b017201 100644
--- a/api/server/controllers/UserController.js
+++ b/api/server/controllers/UserController.js
@@ -20,6 +20,7 @@ const {
deleteAllSharedLinksWithCleanup,
revokeUserCodeEnvironmentWorkers,
finalizeMCPAuthorizationMutation,
+ clearSessionHintCookie,
} = require('@librechat/api');
const { Tools, Constants, FileSources, ResourceType } = require('librechat-data-provider');
const { updateUserPluginAuth, deleteUserPluginAuth } = require('~/server/services/PluginService');
@@ -537,6 +538,7 @@ const deleteUserController = async (req, res) => {
await db.deleteMessages({ user: user.id });
await db.deleteAllUserSessions({ userId: user.id });
+ clearSessionHintCookie(res);
await db.deletePasskeysByUser(user.id);
await db.deleteTransactions({ user: user.id });
await db.deleteUserKey({ userId: user.id, all: true });
diff --git a/api/server/controllers/UserController.spec.js b/api/server/controllers/UserController.spec.js
index 51a3654068..db724279a8 100644
--- a/api/server/controllers/UserController.spec.js
+++ b/api/server/controllers/UserController.spec.js
@@ -568,6 +568,7 @@ describe('deleteUserController', () => {
status: jest.fn().mockReturnThis(),
send: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
+ clearCookie: jest.fn(),
};
beforeEach(() => {
@@ -584,6 +585,7 @@ describe('deleteUserController', () => {
expect(mockRes.status).toHaveBeenCalledWith(200);
expect(mockRes.send).toHaveBeenCalledWith({ message: 'User deleted' });
+ expect(mockRes.clearCookie).toHaveBeenCalledWith('session_hint');
expect(deletePasskeysByUser).toHaveBeenCalledWith(userIdStr);
expect(beginAgentTriggerUserDeletion).toHaveBeenCalledWith(userId.toString(), expect.any(Date));
expect(mockPrepareAgentTriggerUserPurge).toHaveBeenCalledWith(
diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.js
index da4efd59ac..dce796d6e8 100644
--- a/api/server/controllers/__tests__/deleteUser.spec.js
+++ b/api/server/controllers/__tests__/deleteUser.spec.js
@@ -49,6 +49,7 @@ jest.mock('librechat-data-provider', () => ({
}));
jest.mock('@librechat/api', () => ({
+ clearSessionHintCookie: jest.fn(),
createEmailChangeService: jest.fn(() => ({
requestEmailChange: jest.fn(),
confirmEmailChange: jest.fn(),
@@ -180,7 +181,7 @@ jest.mock('~/cache', () => ({
}));
const { deleteUserController } = require('~/server/controllers/UserController');
-const { deleteOwnedAgentCheckpoints } = require('@librechat/api');
+const { deleteOwnedAgentCheckpoints, clearSessionHintCookie } = require('@librechat/api');
function createRes() {
const res = {};
@@ -229,6 +230,24 @@ beforeEach(() => {
stubDeletionMocks();
});
+describe('deleteUserController - session hint', () => {
+ it('retires the session hint once sessions are revoked, even when a later cleanup fails', async () => {
+ const req = { user: { id: 'user1', _id: 'user1', email: '[email protected]' }, body: {} };
+ const res = createRes();
+ mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false });
+ mockDeletePresets.mockRejectedValue(new Error('preset store unavailable'));
+
+ await deleteUserController(req, res);
+
+ expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user1' });
+ expect(clearSessionHintCookie).toHaveBeenCalledWith(res);
+ expect(mockDeleteAllUserSessions.mock.invocationCallOrder[0]).toBeLessThan(
+ clearSessionHintCookie.mock.invocationCallOrder[0],
+ );
+ expect(res.status).toHaveBeenCalledWith(500);
+ });
+});
+
describe('deleteUserController - 2FA enforcement', () => {
it('proceeds with deletion when 2FA is not enabled', async () => {
const req = { user: { id: 'user1', _id: 'user1', email: '[email protected]' }, body: {} };
diff --git a/api/server/controllers/auth/LogoutController.js b/api/server/controllers/auth/LogoutController.js
index a9023c84f7..9ff8606b5a 100644
--- a/api/server/controllers/auth/LogoutController.js
+++ b/api/server/controllers/auth/LogoutController.js
@@ -1,5 +1,10 @@
const cookies = require('cookie');
-const { isEnabled, math, clearCloudFrontCookies } = require('@librechat/api');
+const {
+ isEnabled,
+ math,
+ clearCloudFrontCookies,
+ clearSessionHintCookie,
+} = require('@librechat/api');
const { logger, DEFAULT_REFRESH_TOKEN_EXPIRY } = require('@librechat/data-schemas');
const { logoutUser } = require('~/server/services/AuthService');
const { deleteAllRefreshTokenBridges } = require('~/server/services/RefreshTokenBridge');
@@ -88,6 +93,7 @@ const logoutController = async (req, res) => {
res.clearCookie('openid_id_token');
res.clearCookie('openid_user_id');
res.clearCookie('token_provider');
+ clearSessionHintCookie(res);
clearCloudFrontCookies(res, {
userId: req.user?.id ?? req.user?._id?.toString?.(),
tenantId: req.user?.tenantId,
diff --git a/api/server/controllers/auth/LogoutController.spec.js b/api/server/controllers/auth/LogoutController.spec.js
index 06a051a66a..1159e9d4d7 100644
--- a/api/server/controllers/auth/LogoutController.spec.js
+++ b/api/server/controllers/auth/LogoutController.spec.js
@@ -10,6 +10,7 @@ const mockRevokeOpenIDRefreshTokenChain = jest.fn();
jest.mock('cookie');
jest.mock('@librechat/api', () => ({
+ clearSessionHintCookie: (res) => res.clearCookie('session_hint'),
isEnabled: (...args) => mockIsEnabled(...args),
math: (_value, fallback) => fallback,
clearCloudFrontCookies: (...args) => mockClearCloudFrontCookies(...args),
@@ -360,6 +361,7 @@ describe('LogoutController', () => {
expect(res.clearCookie).toHaveBeenCalledWith('openid_access_token');
expect(res.clearCookie).toHaveBeenCalledWith('openid_id_token');
expect(res.clearCookie).toHaveBeenCalledWith('openid_user_id');
+ expect(res.clearCookie).toHaveBeenCalledWith('session_hint');
expect(res.clearCookie).toHaveBeenCalledWith('token_provider');
});
diff --git a/api/server/services/AuthService.js b/api/server/services/AuthService.js
index 21c7f41cfb..ec3d8d4591 100644
--- a/api/server/services/AuthService.js
+++ b/api/server/services/AuthService.js
@@ -7,7 +7,12 @@ const {
DEFAULT_SESSION_EXPIRY,
DEFAULT_REFRESH_TOKEN_EXPIRY,
} = require('@librechat/data-schemas');
-const { ErrorTypes, SystemRoles, errorsToString } = require('librechat-data-provider');
+const {
+ ErrorTypes,
+ SystemRoles,
+ errorsToString,
+ SESSION_HINT_COOKIE,
+} = require('librechat-data-provider');
const {
math,
isEnabled,
@@ -21,6 +26,7 @@ const {
shouldUseSecureCookie,
setRefreshTokenCookie,
setOpenIDMarkerCookies,
+ setLocalSessionCookies,
clearCloudFrontCookies,
normalizeExpiresIn,
createOpenIDSessionIdentity,
@@ -207,6 +213,7 @@ const clearOpenIDAuthTokens = (req, res, userId, tenantId) => {
'openid_id_token',
'openid_user_id',
'token_provider',
+ SESSION_HINT_COOKIE,
]) {
res.clearCookie?.(name);
}
@@ -719,17 +726,11 @@ const setAuthTokens = async (userId, res, _session = null, req = null) => {
const sessionExpiry = math(process.env.SESSION_EXPIRY, DEFAULT_SESSION_EXPIRY);
const token = await generateToken(user, sessionExpiry);
- res.cookie('refreshToken', refreshToken, {
- expires: new Date(refreshTokenExpires),
- httpOnly: true,
- secure: shouldUseSecureCookie(),
- sameSite: 'strict',
- });
- res.cookie('token_provider', 'librechat', {
+ setLocalSessionCookies(res, {
+ refreshToken,
expires: new Date(refreshTokenExpires),
- httpOnly: true,
- secure: shouldUseSecureCookie(),
- sameSite: 'strict',
+ userId: user?._id ?? userId,
+ tenantId: user?.tenantId,
});
setCloudFrontAuthCookies(req, res, user, { userId: user?._id ?? userId });
@@ -929,6 +930,7 @@ const setOpenIDAuthTokens = (
setOpenIDMarkerCookies(res, {
userId,
+ tenantId,
expires: expirationDate,
refreshExpiryMs: expiryInMilliseconds,
refreshToken,
diff --git a/api/server/services/AuthService.spec.js b/api/server/services/AuthService.spec.js
index c3c224d99b..bf6e7f0aae 100644
--- a/api/server/services/AuthService.spec.js
+++ b/api/server/services/AuthService.spec.js
@@ -16,6 +16,7 @@ jest.mock(
ErrorTypes: {},
SystemRoles: { USER: 'USER', ADMIN: 'ADMIN' },
errorsToString: jest.fn(),
+ SESSION_HINT_COOKIE: 'session_hint',
}),
{ virtual: false },
);
@@ -39,6 +40,7 @@ jest.mock(
sameSite: 'strict',
});
}),
+ setLocalSessionCookies: jest.fn(),
setOpenIDMarkerCookies: jest.fn((res, { userId, expires }) => {
res.cookie('token_provider', 'openid', {
expires,
@@ -138,6 +140,7 @@ let isEmailDomainAllowed;
let resolveAppConfigForUser;
let setRefreshTokenCookie;
let setOpenIDMarkerCookies;
+let setLocalSessionCookies;
let setCloudFrontCookies;
let getCloudFrontConfig;
let parseCloudFrontCookieScope;
@@ -182,6 +185,7 @@ jest.isolateModules(() => {
commitPasswordReset,
setRefreshTokenCookie,
setOpenIDMarkerCookies,
+ setLocalSessionCookies,
setCloudFrontCookies,
getCloudFrontConfig,
parseCloudFrontCookieScope,
@@ -1699,6 +1703,39 @@ describe('CloudFront cookie integration', () => {
);
});
+ it('names the session owner and expiry in the readable cookie the theme replay checks', async () => {
+ const expiration = new Date(Date.now() + 604800000);
+ createSession.mockResolvedValueOnce({
+ session: { expiration },
+ refreshToken: 'mock-refresh-token',
+ });
+ const res = mockResponse();
+
+ await setAuthTokens('user-123', res);
+
+ expect(setLocalSessionCookies).toHaveBeenCalledWith(res, {
+ refreshToken: 'mock-refresh-token',
+ expires: expiration,
+ userId: 'user-123',
+ tenantId: 'tenantA',
+ });
+ });
+
+ it('re-stamps the expiry of the session a refresh keeps', async () => {
+ const expiration = new Date(Date.now() + 3600000);
+ const res = mockResponse();
+
+ await setAuthTokens('user-123', res, { _id: 'session-1', expiration });
+
+ expect(createSession).not.toHaveBeenCalled();
+ expect(setLocalSessionCookies).toHaveBeenCalledWith(res, {
+ refreshToken: 'mock-refresh-token',
+ expires: expiration,
+ userId: 'user-123',
+ tenantId: 'tenantA',
+ });
+ });
+
it('succeeds even when setCloudFrontCookies returns false', async () => {
setCloudFrontCookies.mockReturnValue(false);
diff --git a/api/server/services/OpenIDSessionRefresh.spec.js b/api/server/services/OpenIDSessionRefresh.spec.js
index 022bd80fce..1e02b6efe9 100644
--- a/api/server/services/OpenIDSessionRefresh.spec.js
+++ b/api/server/services/OpenIDSessionRefresh.spec.js
@@ -689,6 +689,7 @@ describe('OpenIDSessionRefresh', () => {
expect(setOpenIDMarkerCookies).toHaveBeenCalledTimes(1);
expect(setOpenIDMarkerCookies).toHaveBeenCalledWith(res, {
userId: 'local-id-1',
+ tenantId: 'tenant-1',
expires: expect.any(Date),
refreshExpiryMs: 1000 * 60 * 60 * 24 * 7,
refreshToken: 'rt-rotated',
diff --git a/client/index.html b/client/index.html
index a6eb922b13..6dcb8e8530 100644
--- a/client/index.html
+++ b/client/index.html
@@ -113,8 +113,11 @@
/* The deployment theme (`interface.theme`) arrives with /api/config, so a
* signed-in reload replays the copy DeploymentTheme cached under
* `deployment-theme` (client/src/Providers/themeCache.ts) to paint it
- * before the bundle runs. High contrast outranks it, as in ThemeProvider,
- * which drops this copy (`data-theme-boot`) once it applies its own. */
+ * before the bundle runs. The session cookies are unreadable here, so the
+ * copy paints only for the identity this tab last saw signed in
+ * (`deployment-theme-owner` in session storage); any other tab waits for
+ * its own answer. High contrast outranks it, as in ThemeProvider, which
+ * drops this copy (`data-theme-boot`) once it applies its own. */
const base = document.querySelector('base');
const basePath = base ? new URL(base.href).pathname : '/';
const path =
@@ -130,8 +133,21 @@
if (!contrast && !publicRoute) {
try {
const cached = JSON.parse(localStorage.getItem('deployment-theme') || 'null');
+ /* The server names the session's owner and expiry here (`<expiry>~<owner>`), since
+ * the session cookies are unreadable: only a live session of the cache's owner replays it. */
+ const hint = /(?:^|;\s*)session_hint=([^;]*)/.exec(document.cookie);
+ const session = hint ? decodeURIComponent(hint[1]) : '';
+ const separator = session.indexOf('~');
const boot =
- cached && cached.v === '__THEME_CACHE_VERSION__' && cached.modes && cached.modes[dark ? 'dark' : 'light'];
+ cached &&
+ separator > 0 &&
+ Number(session.slice(0, separator)) > Date.now() &&
+ session.slice(separator + 1) === cached.owner &&
+ cached.v === '__THEME_CACHE_VERSION__' &&
+ typeof cached.owner === 'string' &&
+ cached.owner === sessionStorage.getItem('deployment-theme-owner') &&
+ cached.modes &&
+ cached.modes[dark ? 'dark' : 'light'];
if (boot && Array.isArray(boot.properties)) {
let surface;
let canvas;
diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsx
index f164038ddc..7b4b590609 100644
--- a/client/src/Providers/DeploymentTheme.tsx
+++ b/client/src/Providers/DeploymentTheme.tsx
@@ -29,10 +29,11 @@ import {
themeOwner,
appBasePath,
isPublicRoute,
- readThemeCache,
+ setThemeOwner,
clearThemeCache,
buildThemeCache,
writeThemeCache,
+ readOwnedThemeCache,
reconcileThemeCache,
} from './themeCache';
import { getThemeFromEnv } from '~/utils/getThemeFromEnv';
@@ -145,16 +146,20 @@ function useRebindOnStartupConfigRebuild() {
* The cached deployment theme, as last read or written. Losing the signed-in user drops
* it, whichever way the session ended (logout, an empty silent refresh, a failed user
* query, account deletion), so the next person on this browser does not get the
- * previous identity's theme painted before their own config answers.
+ * previous identity's theme painted before their own config answers. The cache is read
+ * only for the owner this tab last saw signed in, which the same session end forgets.
*/
function useThemeCache(owner?: string) {
const queryClient = useQueryClient();
const [cached, setCached] = useState(() =>
- isPublicRoute(window.location.pathname, appBasePath()) ? undefined : readThemeCache(),
+ isPublicRoute(window.location.pathname, appBasePath()) ? undefined : readOwnedThemeCache(),
);
const signedIn = useRef(owner);
useEffect(() => {
- if (signedIn.current && !owner) {
+ if (owner) {
+ setThemeOwner(owner);
+ } else if (signedIn.current) {
+ setThemeOwner(undefined);
clearThemeCache();
setCached(undefined);
}
@@ -168,6 +173,7 @@ function useThemeCache(owner?: string) {
*/
useEffect(() => {
const drop = () => {
+ setThemeOwner(undefined);
clearThemeCache();
setCached(undefined);
};
diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
index 24e699fe5b..c6ab8963e7 100644
--- a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
+++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
@@ -3,10 +3,22 @@ import { RecoilRoot, useSetRecoilState } from 'recoil';
import { useTheme, clickHouseTheme } from '@librechat/client';
import { act, render, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { QueryKeys, MutationKeys, dataService } from 'librechat-data-provider';
+import {
+ QueryKeys,
+ MutationKeys,
+ dataService,
+ formatSessionHint,
+ SESSION_HINT_COOKIE,
+} from 'librechat-data-provider';
import type { TStartupConfig, TUser } from 'librechat-data-provider';
import type { ThemeDefinition } from '@librechat/client';
-import { buildThemeCache, writeThemeCache, THEME_CACHE_KEY } from '../themeCache';
+import {
+ setThemeOwner,
+ buildThemeCache,
+ writeThemeCache,
+ THEME_CACHE_KEY,
+ THEME_OWNER_KEY,
+} from '../themeCache';
import DeploymentTheme, { useDeploymentThemeOverride } from '../DeploymentTheme';
import { useGetStartupConfig } from '~/data-provider';
import store from '~/store';
@@ -415,21 +427,34 @@ describe('DeploymentTheme', () => {
});
});
+/** The readable hint the server sets beside the session cookies; no `expires` removes it. */
+function sessionHint(expires?: number, owner = 'tenant-a:user-1') {
+ document.cookie =
+ expires === undefined
+ ? `${SESSION_HINT_COOKIE}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
+ : `${SESSION_HINT_COOKIE}=${encodeURIComponent(formatSessionHint({ expires, owner }))}; path=/`;
+}
+
describe('DeploymentTheme cache', () => {
const user = { id: 'user-1', tenantId: 'tenant-a' };
let queryClient: QueryClient;
let getStartupConfig: jest.SpyInstance;
let warn: jest.SpyInstance;
+ /** What a tab that was served `theme` as `owner` leaves behind. */
const cacheTheme = (owner = 'tenant-a:user-1', theme: ConfigTheme = 'clickhouse') => {
const definition = theme === 'clickhouse' ? clickHouseTheme : (theme as ThemeDefinition);
writeThemeCache(buildThemeCache(owner, theme as NonNullable<ConfigTheme>, definition));
+ setThemeOwner(owner);
+ sessionHint(Date.now() + 60000, owner);
};
const cachedEntry = () => JSON.parse(localStorage.getItem(THEME_CACHE_KEY) ?? 'null');
const pending = () => getStartupConfig.mockReturnValue(new Promise(() => undefined));
beforeEach(() => {
localStorage.clear();
+ sessionStorage.clear();
+ sessionHint(undefined);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
getStartupConfig = jest.spyOn(dataService, 'getStartupConfig');
mockGetThemeFromEnv.mockReturnValue(undefined);
@@ -451,6 +476,72 @@ describe('DeploymentTheme cache', () => {
expect(localStorage.getItem('theme-definition')).toBeNull();
});
+ it('paints no cached theme in a tab that has not seen its owner signed in', () => {
+ cacheTheme();
+ sessionStorage.clear();
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBeUndefined();
+ expect(cachedEntry()?.owner).toBe('tenant-a:user-1');
+ });
+
+ it.each([
+ ['has ended', Date.now() - 1000],
+ ['left no expiry', undefined],
+ ])('paints no cached theme for the tab owner when the session %s', (_, at) => {
+ cacheTheme();
+ sessionHint(at);
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('paints no cached theme when the live session belongs to someone who signed in since', () => {
+ cacheTheme();
+ sessionHint(Date.now() + 60000, 'tenant-b:user-2');
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('paints no cached theme in a tab whose identity changed elsewhere', () => {
+ cacheTheme('tenant-b:user-2');
+ setThemeOwner('tenant-a:user-1');
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('records the signed-in owner for the tab and forgets it at sign-out', async () => {
+ getStartupConfig.mockResolvedValue(configWith(inlineTheme));
+ let signOut: () => void = () => undefined;
+ function SignOut() {
+ const setUser = useSetRecoilState(store.user);
+ signOut = () => setUser(undefined);
+ return null;
+ }
+ render(
+ <RecoilRoot initializeState={({ set }) => set(store.user, user as TUser)}>
+ <QueryClientProvider client={queryClient}>
+ <DeploymentTheme>
+ <SignOut />
+ </DeploymentTheme>
+ </QueryClientProvider>
+ </RecoilRoot>,
+ );
+
+ await waitFor(() => expect(cachedEntry()?.owner).toBe('tenant-a:user-1'));
+ expect(sessionStorage.getItem(THEME_OWNER_KEY)).toBe('tenant-a:user-1');
+
+ act(() => signOut());
+ await waitFor(() => expect(sessionStorage.getItem(THEME_OWNER_KEY)).toBeNull());
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
it('does not seed the cache on a shared link, which paints its own tenant', () => {
cacheTheme();
pending();
@@ -648,6 +739,7 @@ describe('DeploymentTheme cache', () => {
.execute();
});
expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ expect(sessionStorage.getItem(THEME_OWNER_KEY)).toBeNull();
});
const runMutation = (key: string, mutationFn: () => Promise<unknown>) =>
@@ -681,6 +773,7 @@ describe('DeploymentTheme cache', () => {
await runMutation(MutationKeys.refreshToken, refresh);
expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ expect(sessionStorage.getItem(THEME_OWNER_KEY)).toBeNull();
});
it('keeps the cache when the silent refresh restores a session', async () => {
diff --git a/client/src/Providers/__tests__/bootScript.spec.tsx b/client/src/Providers/__tests__/bootScript.spec.tsx
index 4eba68a637..74432b5523 100644
--- a/client/src/Providers/__tests__/bootScript.spec.tsx
+++ b/client/src/Providers/__tests__/bootScript.spec.tsx
@@ -1,10 +1,12 @@
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 type { ThemeDefinition } from '@librechat/client';
import {
isPublicRoute,
+ setThemeOwner,
buildThemeCache,
writeThemeCache,
THEME_CACHE_KEY,
@@ -40,6 +42,14 @@ const acme: ThemeDefinition = {
const root = () => document.documentElement;
+/** The readable hint the server sets beside the session cookies; no `expires` removes it. */
+function sessionHint(expires?: number, owner = 'tenant-a:user-1') {
+ document.cookie =
+ expires === undefined
+ ? `${SESSION_HINT_COOKIE}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
+ : `${SESSION_HINT_COOKIE}=${encodeURIComponent(formatSessionHint({ expires, owner }))}; path=/`;
+}
+
function mockMedia(dark: boolean) {
window.matchMedia = jest.fn().mockImplementation((query: string) => ({
matches: dark && query === '(prefers-color-scheme: dark)',
@@ -63,6 +73,7 @@ function appliedStyle(mode: 'light' | 'dark') {
describe('index.html deployment theme boot script', () => {
beforeEach(() => {
localStorage.clear();
+ sessionStorage.clear();
root().removeAttribute('style');
root().removeAttribute('class');
[...root().attributes].forEach(({ name }) => {
@@ -77,6 +88,8 @@ describe('index.html deployment theme boot script', () => {
mockMedia(false);
window.history.pushState({}, '', '/c/new');
writeThemeCache(buildThemeCache('tenant-a:user-1', 'acme', acme));
+ setThemeOwner('tenant-a:user-1');
+ sessionHint(Date.now() + 60000);
});
it.each(['light', 'dark'] as const)(
@@ -116,6 +129,47 @@ describe('index.html deployment theme boot script', () => {
expect(root().hasAttribute('data-theme')).toBe(false);
});
+ it.each([
+ ['a tab that has not seen its owner signed in', undefined],
+ ['a tab last signed in as someone else', 'tenant-b:user-2'],
+ ])('paints no cached theme in %s', (_, tabOwner) => {
+ setThemeOwner(tabOwner);
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(root().hasAttribute('data-theme-boot')).toBe(false);
+ expect(document.head.textContent).toContain('background-color: #ffffff');
+ });
+
+ it.each([
+ ['has ended', Date.now() - 1000],
+ ['left no expiry', undefined],
+ ])('paints no cached theme for the tab owner when the session %s', (_, at) => {
+ sessionHint(at);
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(root().hasAttribute('data-theme-boot')).toBe(false);
+ expect(document.head.textContent).toContain('background-color: #ffffff');
+ });
+
+ it('paints no cached theme when the live session belongs to someone who signed in since', () => {
+ sessionHint(Date.now() + 60000, 'tenant-b:user-2');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(root().hasAttribute('data-theme-boot')).toBe(false);
+ expect(document.head.textContent).toContain('background-color: #ffffff');
+ });
+
+ it('paints no cached theme that names no owner', () => {
+ const stored = JSON.parse(localStorage.getItem(THEME_CACHE_KEY) ?? 'null');
+ localStorage.setItem(THEME_CACHE_KEY, JSON.stringify({ ...stored, owner: undefined }));
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ });
+
it('paints nothing on a first-ever visit, leaving the operator theme to the config answer', () => {
localStorage.clear();
boot();
diff --git a/client/src/Providers/themeCache.ts b/client/src/Providers/themeCache.ts
index e48b45ff77..8ccc8fda99 100644
--- a/client/src/Providers/themeCache.ts
+++ b/client/src/Providers/themeCache.ts
@@ -1,5 +1,10 @@
-import { themeRoleFingerprint } from 'librechat-data-provider';
import { resolveTheme, describeResolvedTheme } from '@librechat/client';
+import {
+ themeOwnerKey,
+ parseSessionHint,
+ SESSION_HINT_COOKIE,
+ themeRoleFingerprint,
+} from 'librechat-data-provider';
import type { ResolvedThemeStyle, ThemeDefinition } from '@librechat/client';
import type { TInterfaceConfig, TUser } from 'librechat-data-provider';
@@ -16,6 +21,13 @@ export const THEME_CACHE_KEY = 'deployment-theme';
* `client/vite.config.ts` writes the same value into the boot script's version check.
*/
export const THEME_CACHE_VERSION = themeRoleFingerprint();
+/**
+ * The owner this tab last saw signed in. Session storage lives and dies with the tab, so
+ * the cache is replayed only on a reload of a tab that was serving its owner; a new tab,
+ * or one whose identity changed elsewhere, waits for its own answer. The boot script
+ * reads this key too.
+ */
+export const THEME_OWNER_KEY = 'deployment-theme-owner';
export type ThemeCacheEntry = {
v: string;
@@ -65,7 +77,7 @@ export function isPublicRoute(pathname: string, basePath = '/'): boolean {
}
export const themeOwner = (user?: Pick<TUser, 'id' | 'tenantId'>): string | undefined =>
- user?.id ? `${user.tenantId ?? ''}:${user.id}` : undefined;
+ user?.id ? themeOwnerKey(user.id, user.tenantId) : undefined;
const isStyle = (value: unknown): value is ResolvedThemeStyle =>
typeof value === 'object' &&
@@ -97,6 +109,42 @@ export function readThemeCache(): ThemeCacheEntry | undefined {
return undefined;
}
+const sessionHintPattern = new RegExp(`(?:^|;\\s*)${SESSION_HINT_COOKIE}=([^;]*)`);
+
+/** Whether the server's readable session hint names a live session of `owner`. */
+export function isLiveSessionOf(owner: string): boolean {
+ const value = sessionHintPattern.exec(document.cookie)?.[1];
+ const hint = value ? parseSessionHint(decodeURIComponent(value)) : undefined;
+ return hint != null && hint.expires > Date.now() && hint.owner === owner;
+}
+
+/**
+ * The cache, only when this tab last saw its owner signed in and the browser's live session is
+ * that owner's, so the replay cannot cross identities or outlive the session.
+ */
+export function readOwnedThemeCache(): ThemeCacheEntry | undefined {
+ try {
+ const tabOwner = sessionStorage.getItem(THEME_OWNER_KEY);
+ const entry = tabOwner && isLiveSessionOf(tabOwner) ? readThemeCache() : undefined;
+ return entry?.owner === tabOwner ? entry : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Records the tab's signed-in owner, or forgets it once no one is signed in. */
+export function setThemeOwner(owner?: string): void {
+ try {
+ if (owner) {
+ sessionStorage.setItem(THEME_OWNER_KEY, owner);
+ } else {
+ sessionStorage.removeItem(THEME_OWNER_KEY);
+ }
+ } catch {
+ // Without session storage no owner is known, so the cache is never replayed.
+ }
+}
+
export function clearThemeCache(): void {
try {
localStorage.removeItem(THEME_CACHE_KEY);
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 f66433a470..bd1df41658 100644
--- a/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
+++ b/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
@@ -1,4 +1,6 @@
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 { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
import { resolveTheme } from '../../../../packages/client/src/theme/registry';
@@ -11,10 +13,12 @@ import { resolveTheme } from '../../../../packages/client/src/theme/registry';
* cache, so every frame before the answer already wears it.
*
* The reload runs throttled (400 ms latency, 1.5 Mbps, 4x CPU) and the config
- * answer is held back further, so frames of both the loading shell and the
- * rendered app (the chat layout paints before the config answers; the composer
- * waits for it) land before it. Every frame is sampled in a
- * `requestAnimationFrame` callback, which runs before the frame paints.
+ * answer is held until the rendered app has painted (the chat layout paints
+ * before the config answers; the composer waits for it), so frames of both the
+ * loading shell and the app land before it. A fixed hold is not enough: under
+ * load the throttled main thread can paint no frame at all for longer than it.
+ * Every frame is sampled in a `requestAnimationFrame` callback, which runs
+ * before the frame paints.
*/
type Mode = 'light' | 'dark';
@@ -34,15 +38,21 @@ declare global {
}
}
-const CONFIG_HOLD_MS = 1500;
+const APP_PAINT_TIMEOUT_MS = 45000;
const CACHE_KEY = 'deployment-theme';
/**
- * Serves `theme` as `interface.theme` (`null` removes it), holding the answer while
- * `held()`. Returns when each signed-in answer was sent: that answer is the one
- * carrying the signed-in theme, so the frames before it are the ones under test.
+ * Serves `theme` as `interface.theme` (`null` removes it), holding the answer until the
+ * app has painted while `held()`. Returns when each signed-in answer was sent: that
+ * answer is the one carrying the signed-in theme, so the frames before it are the ones
+ * under test. Without `signedInOnly`, every answer counts, signed out ones included.
*/
-async function serveTheme(page: Page, theme: () => string | null, held: () => boolean) {
+async function serveTheme(
+ page: Page,
+ theme: () => string | null,
+ held: () => boolean,
+ signedInOnly = true,
+) {
const answeredAt: number[] = [];
await page.route(
(url) => url.pathname === '/api/config',
@@ -56,9 +66,13 @@ async function serveTheme(page: Page, theme: () => string | null, held: () => bo
served.theme = value;
}
if (held()) {
- await new Promise((resolve) => setTimeout(resolve, CONFIG_HOLD_MS));
+ await page
+ .waitForFunction(() => window.__themeFrames?.some((frame) => frame.app), undefined, {
+ timeout: APP_PAINT_TIMEOUT_MS,
+ })
+ .catch(() => undefined);
}
- if (route.request().headers()['authorization']) {
+ if (!signedInOnly || route.request().headers()['authorization']) {
answeredAt.push(Date.now());
}
await route.fulfill({ response, json: { ...body, interface: served } });
@@ -101,11 +115,49 @@ async function throttle(page: Page) {
await session.send('Emulation.setCPUThrottlingRate', { rate: 4 });
}
+/**
+ * Frames sampled before the signed-in answer, checked to cover both surfaces: the first
+ * frame showing content is the loading shell (a frame sampled before `#root` is parsed
+ * shows neither), and the app painted too.
+ */
+async function framesBeforeAnswer(page: Page, answeredAt: number[], reloadedAt: number) {
+ await expect.poll(() => answeredAt.some((at) => at > reloadedAt)).toBe(true);
+ const answered = Math.min(...answeredAt.filter((at) => at > reloadedAt));
+ const frames = (await page.evaluate(() => window.__themeFrames ?? [])).filter(
+ (frame) => frame.at < answered,
+ );
+ expect(frames.find((frame) => frame.shell !== null || frame.app)?.shell).toBeTruthy();
+ expect(frames.some((frame) => frame.app)).toBe(true);
+ return frames;
+}
+
async function openChat(page: Page) {
await page.goto('/c/new');
await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 30000 });
}
+/** The session expiry the server mirrors in a page-readable cookie, in epoch milliseconds. */
+async function sessionHint(page: Page): Promise<SessionHint | undefined> {
+ const value = await page.evaluate(
+ (name) => new RegExp(`(?:^|;\\s*)${name}=([^;]*)`).exec(document.cookie)?.[1],
+ SESSION_HINT_COOKIE,
+ );
+ return value ? parseSessionHint(decodeURIComponent(value)) : undefined;
+}
+
+/** Rewrites the page-readable session hint as `change` says, leaving the session cookies alone. */
+async function rewriteSessionHint(page: Page, change: (hint: SessionHint) => SessionHint) {
+ const hint = await sessionHint(page);
+ expect(hint).toBeDefined();
+ const value = encodeURIComponent(formatSessionHint(change(hint as SessionHint)));
+ await page.evaluate(
+ ([name, rewritten]) => {
+ document.cookie = `${name}=${rewritten}; path=/`;
+ },
+ [SESSION_HINT_COOKIE, value],
+ );
+}
+
const rgb = (channels?: string) => `rgb(${(channels ?? '').split(' ').join(', ')})`;
/** Reloads throttled with the config held, and checks every frame before the answer. */
@@ -123,6 +175,12 @@ async function expectFirstPaint(page: Page, mode: Mode) {
await expect
.poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY))
.not.toBeNull();
+ /** The reload happens inside a live session of the identity the cache belongs to. */
+ const hint = await sessionHint(page);
+ expect(hint?.expires).toBeGreaterThan(Date.now());
+ expect(hint?.owner).toBe(
+ await page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? 'null')?.owner, CACHE_KEY),
+ );
await sampleFrames(page);
await throttle(page);
@@ -130,17 +188,7 @@ async function expectFirstPaint(page: Page, mode: Mode) {
const reloadedAt = Date.now();
await page.reload();
await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 60000 });
- await expect.poll(() => answeredAt.some((at) => at > reloadedAt)).toBe(true);
-
- const answered = Math.min(...answeredAt.filter((at) => at > reloadedAt));
- const frames = (await page.evaluate(() => window.__themeFrames ?? [])).filter(
- (frame) => frame.at < answered,
- );
-
- /** Frames of both surfaces landed before the answer, so both were tested. */
- expect(frames.length).toBeGreaterThan(0);
- expect(frames[0].shell).not.toBeNull();
- expect(frames.some((frame) => frame.app)).toBe(true);
+ const frames = await framesBeforeAnswer(page, answeredAt, reloadedAt);
for (const frame of frames) {
expect(frame.theme).toBe('clickhouse');
@@ -198,3 +246,188 @@ test('a deployment theme removed since the last visit wins once the config answe
await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'clickhouse');
await expect.poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY)).toBeNull();
});
+
+/**
+ * The session cookies are unreadable before the bundle runs, so the cache is replayed only
+ * in a tab that last saw its owner signed in. A cache left by another identity, or a tab
+ * with no signed-in owner yet, paints the default shell until the config answers. The
+ * signed-out answer counts: it carries the deployment theme too, and with no cache replayed
+ * it is the first source the app may paint it from.
+ */
+async function expectNoCachedPaint(page: Page, open: (page: Page) => Promise<void>) {
+ let held = false;
+ const answeredAt = await serveTheme(
+ page,
+ () => 'clickhouse',
+ () => held,
+ false,
+ );
+ await openChat(page);
+ await expect
+ .poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY))
+ .not.toBeNull();
+
+ await open(page);
+ await sampleFrames(page);
+ await throttle(page);
+ held = true;
+ const reloadedAt = Date.now();
+ await page.reload();
+ await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 60000 });
+ const frames = await framesBeforeAnswer(page, answeredAt, reloadedAt);
+ for (const frame of frames) {
+ expect(frame.theme).toBeNull();
+ }
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect
+ .poll(() =>
+ page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? 'null')?.owner, CACHE_KEY),
+ )
+ .not.toBe('tenant-x:someone-else');
+}
+
+/** What a browser that last held another identity's theme carries into this tab. */
+const cacheForSomeoneElse = (page: Page) =>
+ page.evaluate((key) => {
+ const entry = JSON.parse(localStorage.getItem(key) ?? 'null');
+ localStorage.setItem(key, JSON.stringify({ ...entry, owner: 'tenant-x:someone-else' }));
+ }, CACHE_KEY);
+
+/** A fresh tab: the session cookies are shared, the tab's own session storage is not. */
+const forgetTabOwner = (page: Page) => page.evaluate(() => sessionStorage.clear());
+
+/** A tab that outlived its session: the owner marker and the cache still match, the hint has expired. */
+/**
+ * A reload of a tab whose session ended. The refresh is refused the way the server refuses an
+ * expired session, so the app lands on the login page, and the signed-out config answers with
+ * the deployment theme too: no frame before the first answer of any kind may wear the cached
+ * theme, and the session end drops the cache and the tab owner.
+ */
+async function expectEndedSessionPaint(page: Page, open: (page: Page) => Promise<void>) {
+ let held = false;
+ const answeredAt = await serveTheme(
+ page,
+ () => 'clickhouse',
+ () => held,
+ false,
+ );
+ await openChat(page);
+ await expect
+ .poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY))
+ .not.toBeNull();
+
+ await open(page);
+ await page.route(
+ (url) => url.pathname === '/api/auth/refresh',
+ (route) =>
+ route.fulfill({ status: 401, body: 'Refresh token expired or not found for this user' }),
+ );
+ await sampleFrames(page);
+ await throttle(page);
+ held = true;
+ const reloadedAt = Date.now();
+ await page.reload();
+ await expect(page).toHaveURL(/\/login/, { timeout: 60000 });
+ const frames = await framesBeforeAnswer(page, answeredAt, reloadedAt);
+ for (const frame of frames) {
+ expect(frame.theme).toBeNull();
+ }
+ await expect.poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY)).toBeNull();
+ expect(await page.evaluate(() => sessionStorage.getItem('deployment-theme-owner'))).toBeNull();
+}
+
+const endSession = (page: Page) =>
+ rewriteSessionHint(page, (hint) => ({ ...hint, expires: Date.now() - 1000 }));
+
+/**
+ * Another identity's session, signed in since through a flow that ends in a full navigation
+ * (an OAuth callback): the tab's owner marker and the cache still name the previous identity.
+ */
+const otherSession = (page: Page) =>
+ rewriteSessionHint(page, (hint) => ({ ...hint, owner: 'tenant-x:someone-else' }));
+
+test.describe('cached theme owner (light)', () => {
+ test.use({ colorScheme: 'light', viewport: { width: 1280, height: 800 } });
+
+ test('a reload paints no deployment theme cached for another identity in light @scenario:cached-theme-other-owner-not-boot-painted-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectNoCachedPaint(page, cacheForSomeoneElse);
+ });
+
+ test('a tab that has not seen its owner signed in paints no cached deployment theme in light @scenario:cached-theme-unknown-owner-not-boot-painted-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectNoCachedPaint(page, forgetTabOwner);
+ });
+
+ test('a tab whose session has ended paints no cached deployment theme in light @scenario:cached-theme-expired-session-not-boot-painted-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectEndedSessionPaint(page, endSession);
+ });
+
+ test('a tab now signed in as someone else paints no cached deployment theme in light @scenario:cached-theme-other-session-not-boot-painted-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectEndedSessionPaint(page, otherSession);
+ });
+});
+
+test.describe('cached theme owner (dark)', () => {
+ test.use({ colorScheme: 'dark', viewport: { width: 1280, height: 800 } });
+
+ test('a reload paints no deployment theme cached for another identity in dark @scenario:cached-theme-other-owner-not-boot-painted-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectNoCachedPaint(page, cacheForSomeoneElse);
+ });
+
+ test('a tab that has not seen its owner signed in paints no cached deployment theme in dark @scenario:cached-theme-unknown-owner-not-boot-painted-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectNoCachedPaint(page, forgetTabOwner);
+ });
+
+ test('a tab whose session has ended paints no cached deployment theme in dark @scenario:cached-theme-expired-session-not-boot-painted-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectEndedSessionPaint(page, endSession);
+ });
+
+ test('a tab now signed in as someone else paints no cached deployment theme in dark @scenario:cached-theme-other-session-not-boot-painted-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectEndedSessionPaint(page, otherSession);
+ });
+});
+
+test('a session refresh keeps the readable session hint on the refresh session expiry and owner @scenario:session-refresh-keeps-hint-aligned', async ({
+ page,
+}) => {
+ await openChat(page);
+ const before = await sessionHint(page);
+ expect(before?.expires).toBeGreaterThan(Date.now());
+
+ const refreshed = await page.evaluate(async () => {
+ const response = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' });
+ return response.ok;
+ });
+ expect(refreshed).toBe(true);
+
+ const after = await sessionHint(page);
+ const refreshCookie = (await page.context().cookies()).find(
+ (cookie) => cookie.name === 'refreshToken',
+ );
+ expect(after?.owner).toBe(before?.owner);
+ expect(after?.expires).toBeGreaterThanOrEqual(before?.expires ?? Number.POSITIVE_INFINITY);
+ expect(Math.floor((after?.expires ?? 0) / 1000)).toBe(Math.floor(refreshCookie?.expires ?? -1));
+});
diff --git a/packages/api/src/auth/localRefresh.ts b/packages/api/src/auth/localRefresh.ts
index 6156e65e0f..0088435e4f 100644
--- a/packages/api/src/auth/localRefresh.ts
+++ b/packages/api/src/auth/localRefresh.ts
@@ -11,6 +11,7 @@ import {
isTwoFactorEnrollmentRequired,
TOKEN_RETIREMENT_FIELDS,
} from './twoFactor';
+import { clearSessionHintCookie } from '~/oauth/csrf';
const EXPIRED_REFRESH_MESSAGE = 'Refresh token expired or not found for this user';
@@ -114,6 +115,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
refreshToken: string | undefined,
): Promise<Response | void> => {
if (!refreshToken) {
+ clearSessionHintCookie(res);
return res.status(200).send('Refresh token not provided');
}
@@ -125,6 +127,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
const userId = payload.id;
const user = await deps.getUserById(userId, deps.userProjection);
if (!user) {
+ clearSessionHintCookie(res);
return res.status(401).redirect('/login');
}
@@ -141,6 +144,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
`[refreshController] Refresh token predates enrollment or password reset: userId=${userId}`,
);
res.clearCookie('refreshToken');
+ clearSessionHintCookie(res);
return res.status(401).send(EXPIRED_REFRESH_MESSAGE);
}
@@ -154,6 +158,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
if (requiresEnrollment(user)) {
await deps.deleteSession({ sessionId: session._id.toString() });
res.clearCookie('refreshToken');
+ clearSessionHintCookie(res);
deps.clearCloudFrontCookies(res, {
userId,
tenantId: user.tenantId ?? user.orgId,
@@ -182,6 +187,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
}
return res.status(200).send({ token, user: sanitizeUserForAuthResponse(user) });
}
+ clearSessionHintCookie(res);
if (req.query?.retry) {
return res.status(403).send('No session found');
}
@@ -191,6 +197,7 @@ export function createLocalRefreshHandler(deps: LocalRefreshDependencies) {
return res.status(401).send(EXPIRED_REFRESH_MESSAGE);
} catch (error) {
deps.error('[refreshController] Invalid refresh token:', error);
+ clearSessionHintCookie(res);
return res.status(403).send('Invalid refresh token');
}
};
diff --git a/packages/api/src/auth/openid/session.ts b/packages/api/src/auth/openid/session.ts
index 28cbb8c383..b1f285d9ed 100644
--- a/packages/api/src/auth/openid/session.ts
+++ b/packages/api/src/auth/openid/session.ts
@@ -1,3 +1,4 @@
+import { SESSION_HINT_COOKIE } from 'librechat-data-provider';
import type {
AuthIdentityContext,
AuthIdentitySource,
@@ -85,6 +86,7 @@ interface OpenIDSessionRefreshDeps {
res: OpenIDResponse,
args: {
userId?: string;
+ tenantId?: string;
expires: Date;
refreshExpiryMs: number;
refreshToken: string;
@@ -898,6 +900,7 @@ export function createOpenIDSessionRefreshService(
setRefreshTokenCookie(res, newRefreshToken, expirationDate);
setOpenIDMarkerCookies(res, {
userId,
+ tenantId,
expires: expirationDate,
refreshExpiryMs: expiryInMilliseconds,
refreshToken: newRefreshToken,
@@ -1378,6 +1381,7 @@ export function createOpenIDSessionRefreshService(
'openid_id_token',
'openid_user_id',
'token_provider',
+ SESSION_HINT_COOKIE,
]) {
res?.clearCookie?.(name);
}
diff --git a/packages/api/src/auth/passwordReset.ts b/packages/api/src/auth/passwordReset.ts
index b6d5efa735..3b52235218 100644
--- a/packages/api/src/auth/passwordReset.ts
+++ b/packages/api/src/auth/passwordReset.ts
@@ -2,6 +2,7 @@ import { logger } from '@librechat/data-schemas';
import type { Request, Response } from 'express';
import type { PasswordResetUpdate } from './passwordResetUpdate';
import { createPasswordResetUpdate } from './passwordResetUpdate';
+import { clearSessionHintCookie } from '~/oauth/csrf';
import { EMAIL_CHANGE_TOKEN_TYPE } from './email';
/** The stored reset token, in both the typed shape and the untyped legacy one. */
@@ -87,6 +88,7 @@ export function createResetPasswordController(deps: PasswordResetControllerDeps)
}
/** After the revocations, so nothing can mint a post-stamp token while it waits. */
await deps.awaitAuthUserDocEviction(userId);
+ clearSessionHintCookie(res);
return res.status(200).json(result);
} catch (error) {
diff --git a/packages/api/src/auth/twoFactor.ts b/packages/api/src/auth/twoFactor.ts
index 1cf864b647..432e784a4b 100644
--- a/packages/api/src/auth/twoFactor.ts
+++ b/packages/api/src/auth/twoFactor.ts
@@ -1,7 +1,7 @@
import jwt from 'jsonwebtoken';
import { logger } from '@librechat/data-schemas';
import { createHash, randomBytes } from 'node:crypto';
-import { isTwoFactorPolicyProvider } from 'librechat-data-provider';
+import { SESSION_HINT_COOKIE, isTwoFactorPolicyProvider } from 'librechat-data-provider';
import type { TwoFactorEnrollmentGuard, TwoFactorEnrollmentUpdate } from '@librechat/data-schemas';
import type { NextFunction, Request, Response } from 'express';
import type { UserDocumentId } from '~/auth/verification';
@@ -264,6 +264,7 @@ export async function withdrawMintedSession(
): Promise<void> {
res.clearCookie('refreshToken');
res.clearCookie('token_provider');
+ res.clearCookie(SESSION_HINT_COOKIE);
deps.clearCloudFrontCookies(res, {
userId,
tenantId: user.tenantId ?? user.orgId,
diff --git a/packages/api/src/oauth/csrf.spec.ts b/packages/api/src/oauth/csrf.spec.ts
index 548d7288cb..e26f336da6 100644
--- a/packages/api/src/oauth/csrf.spec.ts
+++ b/packages/api/src/oauth/csrf.spec.ts
@@ -1,10 +1,13 @@
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
+import { SESSION_HINT_COOKIE } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import {
shouldUseSecureCookie,
setRefreshTokenCookie,
setOpenIDMarkerCookies,
+ setSessionHintCookie,
+ setLocalSessionCookies,
REFRESH_TOKEN_COOKIE,
TOKEN_PROVIDER_COOKIE,
OPENID_USER_ID_COOKIE,
@@ -250,6 +253,77 @@ describe('setRefreshTokenCookie', () => {
});
});
+describe('setSessionHintCookie', () => {
+ it('names the owner and expiry, readable by the page and expiring with the session', () => {
+ const res = { cookie: jest.fn() } as unknown as import('express').Response;
+ const expires = new Date(Date.now() + 3600000);
+
+ setSessionHintCookie(res, expires, { userId: { toString: () => 'user-1' }, tenantId: 'acme' });
+
+ expect(res.cookie).toHaveBeenCalledWith(
+ SESSION_HINT_COOKIE,
+ `${expires.getTime()}~acme:user-1`,
+ expect.not.objectContaining({ httpOnly: true }),
+ );
+ expect((res.cookie as jest.Mock).mock.calls[0][2]).toMatchObject({
+ expires,
+ sameSite: 'strict',
+ });
+ });
+
+ it('names a tenantless owner the way the client cache does', () => {
+ const res = { cookie: jest.fn() } as unknown as import('express').Response;
+ const expires = new Date(Date.now() + 3600000);
+
+ setSessionHintCookie(res, expires, { userId: 'user-1' });
+
+ expect(res.cookie).toHaveBeenCalledWith(
+ SESSION_HINT_COOKIE,
+ `${expires.getTime()}~:user-1`,
+ expect.anything(),
+ );
+ });
+
+ it('clears a previous hint when the session names no user', () => {
+ const res = { cookie: jest.fn(), clearCookie: jest.fn() } as unknown as Response;
+
+ setSessionHintCookie(res, new Date(Date.now() + 3600000), { userId: null });
+
+ expect(res.cookie).not.toHaveBeenCalled();
+ expect(res.clearCookie).toHaveBeenCalledWith(SESSION_HINT_COOKIE);
+ });
+});
+
+describe('setLocalSessionCookies', () => {
+ it('issues the refresh token, provider marker and session hint on one expiry and owner', () => {
+ const res = { cookie: jest.fn() } as unknown as Response;
+ const expires = new Date(Date.now() + 3600000);
+
+ setLocalSessionCookies(res, {
+ refreshToken: 'rt-1',
+ expires,
+ userId: 'user-1',
+ tenantId: 'acme',
+ });
+
+ expect(res.cookie).toHaveBeenCalledWith(
+ REFRESH_TOKEN_COOKIE,
+ 'rt-1',
+ expect.objectContaining({ expires, httpOnly: true, sameSite: 'strict' }),
+ );
+ expect(res.cookie).toHaveBeenCalledWith(
+ TOKEN_PROVIDER_COOKIE,
+ 'librechat',
+ expect.objectContaining({ expires, httpOnly: true, sameSite: 'strict' }),
+ );
+ expect(res.cookie).toHaveBeenCalledWith(
+ SESSION_HINT_COOKIE,
+ `${expires.getTime()}~acme:user-1`,
+ expect.objectContaining({ expires, sameSite: 'strict' }),
+ );
+ });
+});
+
describe('setOpenIDMarkerCookies', () => {
const originalEnv = process.env;
@@ -299,6 +373,31 @@ describe('setOpenIDMarkerCookies', () => {
});
});
+ it('names the session owner and expiry in a readable cookie beside the provider marker', () => {
+ process.env.NODE_ENV = 'production';
+ process.env.DOMAIN_SERVER = 'https://myapp.example.com';
+ const res = { cookie: jest.fn() } as unknown as import('express').Response;
+ const expires = new Date(Date.now() + 604800000);
+
+ setOpenIDMarkerCookies(res, {
+ userId: 'user-123',
+ tenantId: 'acme',
+ expires,
+ refreshExpiryMs: 604800000,
+ reuseTokens: false,
+ });
+
+ expect(res.cookie).toHaveBeenCalledWith(
+ SESSION_HINT_COOKIE,
+ `${expires.getTime()}~acme:user-123`,
+ {
+ expires,
+ secure: true,
+ sameSite: 'strict',
+ },
+ );
+ });
+
/** Preserves the marker's binding to the durable refresh-token session: a marker signed for one
* session must not stand in for another once the refresh token has rotated. */
it('binds the signed user marker to the refresh token it was issued with', () => {
@@ -335,7 +434,7 @@ describe('setOpenIDMarkerCookies', () => {
});
it('updates token_provider even when the signed user marker is not applicable', () => {
- const res = { cookie: jest.fn() } as unknown as import('express').Response;
+ const res = { cookie: jest.fn(), clearCookie: jest.fn() } as unknown as Response;
const expires = new Date(Date.now() + 604800000);
setOpenIDMarkerCookies(res, {
@@ -345,6 +444,7 @@ describe('setOpenIDMarkerCookies', () => {
});
expect(res.cookie).toHaveBeenCalledTimes(1);
+ expect(res.clearCookie).toHaveBeenCalledWith(SESSION_HINT_COOKIE);
expect(res.cookie).toHaveBeenCalledWith(
TOKEN_PROVIDER_COOKIE,
'openid',
diff --git a/packages/api/src/oauth/csrf.ts b/packages/api/src/oauth/csrf.ts
index 0d30a45c1b..6a6821ddc6 100644
--- a/packages/api/src/oauth/csrf.ts
+++ b/packages/api/src/oauth/csrf.ts
@@ -1,5 +1,6 @@
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
+import { SESSION_HINT_COOKIE, themeOwnerKey, formatSessionHint } from 'librechat-data-provider';
import type { Request, Response, NextFunction } from 'express';
import { getOAuthCallbackUrl } from './url';
import { isEnabled } from '~/utils/common';
@@ -71,8 +72,65 @@ export function setRefreshTokenCookie(res: Response, refreshToken: string, expir
});
}
+export interface SessionHintOwner {
+ userId?: string | { toString(): string } | null;
+ tenantId?: string | null;
+}
+
+/**
+ * Names the session's owner and expiry where the page can read them before the app runs, so a
+ * replay of something the owner cached skips a session that ended or belongs to someone else.
+ * A session with no known user clears it rather than leaving a previous owner's hint behind.
+ */
+export function setSessionHintCookie(
+ res: Response,
+ expires: Date,
+ { userId, tenantId }: SessionHintOwner,
+): void {
+ if (!userId) {
+ res.clearCookie(SESSION_HINT_COOKIE);
+ return;
+ }
+ const owner = themeOwnerKey(userId.toString(), tenantId);
+ res.cookie(SESSION_HINT_COOKIE, formatSessionHint({ expires: expires.getTime(), owner }), {
+ expires,
+ secure: shouldUseSecureCookie(),
+ sameSite: 'strict',
+ });
+}
+
+export interface LocalSessionCookieOptions extends SessionHintOwner {
+ refreshToken: string;
+ expires: Date;
+}
+
+/**
+ * Issues the cookies of a LibreChat-managed session together: the refresh token, its provider
+ * marker and the readable hint naming the owner, so all three share one expiry and owner.
+ */
+export function setLocalSessionCookies(
+ res: Response,
+ { refreshToken, expires, userId, tenantId }: LocalSessionCookieOptions,
+): void {
+ setRefreshTokenCookie(res, refreshToken, expires);
+ res.cookie(TOKEN_PROVIDER_COOKIE, 'librechat', {
+ expires,
+ httpOnly: true,
+ secure: shouldUseSecureCookie(),
+ sameSite: 'strict',
+ });
+ setSessionHintCookie(res, expires, { userId, tenantId });
+}
+
+/** Retires the readable session hint when a request proves there is no session to vouch for. */
+export function clearSessionHintCookie(res: Response): void {
+ res.clearCookie(SESSION_HINT_COOKIE);
+}
+
export interface OpenIDMarkerCookieOptions {
userId?: string | null;
+ /** Names the session's owner in the readable session hint alongside `userId`. */
+ tenantId?: string | null;
expires: Date;
refreshExpiryMs: number;
reuseTokens?: boolean;
@@ -84,6 +142,7 @@ export function setOpenIDMarkerCookies(
res: Response,
{
userId,
+ tenantId,
expires,
refreshExpiryMs,
reuseTokens = isEnabled(process.env.OPENID_REUSE_TOKENS),
@@ -98,6 +157,7 @@ export function setOpenIDMarkerCookies(
};
res.cookie(TOKEN_PROVIDER_COOKIE, 'openid', cookieOptions);
+ setSessionHintCookie(res, expires, { userId, tenantId });
if (!userId || !reuseTokens) {
return;
diff --git a/packages/data-provider/specs/theme.spec.ts b/packages/data-provider/specs/theme.spec.ts
index 6758457b73..fb1ad0437a 100644
--- a/packages/data-provider/specs/theme.spec.ts
+++ b/packages/data-provider/specs/theme.spec.ts
@@ -1,4 +1,9 @@
-import { collectThemeIssues } from '../src/theme';
+import {
+ themeOwnerKey,
+ parseSessionHint,
+ formatSessionHint,
+ collectThemeIssues,
+} from '../src/theme';
import { deploymentThemeSchema } from '../src/config';
/** A deployment theme as `librechat.yaml` delivers it, with appearance only in the given modes. */
@@ -120,3 +125,22 @@ describe('field fill roles in a theme definition', () => {
expect(messages(newer)).toEqual([]);
});
});
+
+describe('session hint', () => {
+ it('round-trips an owner whose key carries the separator', () => {
+ const hint = { expires: 1791000000000, owner: themeOwnerKey('user~1', 'acme') };
+ expect(parseSessionHint(formatSessionHint(hint))).toEqual(hint);
+ });
+
+ it('names a tenantless owner with an empty tenant', () => {
+ expect(themeOwnerKey('user-1')).toBe(':user-1');
+ expect(themeOwnerKey('user-1', null)).toBe(':user-1');
+ });
+
+ it.each(['', '~:user-1', 'soon~:user-1', '1791000000000'])(
+ 'rejects the malformed %p',
+ (value) => {
+ expect(parseSessionHint(value)).toBeUndefined();
+ },
+ );
+});
diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.ts
index 5a194fdeb2..69acd4a389 100644
--- a/packages/data-provider/src/theme.ts
+++ b/packages/data-provider/src/theme.ts
@@ -565,6 +565,33 @@ export const themeAppearanceTokens = Object.freeze(
Object.keys(appearanceValidators) as ThemeAppearanceToken[],
);
+/**
+ * A page-readable cookie naming the signed-in session's owner and expiry, set beside the httpOnly
+ * session cookies with the same lifetime and cleared with them. The session cookies are
+ * unreadable, so the theme boot replay reads this one to replay a cached theme only into a live
+ * session of the identity that cached it. It holds no credential.
+ */
+export const SESSION_HINT_COOKIE = 'session_hint';
+
+export type SessionHint = { expires: number; owner: string };
+
+/** The identity a cached deployment theme belongs to, as the cache and the session hint name it. */
+export const themeOwnerKey = (userId: string, tenantId?: string | null): string =>
+ `${tenantId ?? ''}:${userId}`;
+
+/** `<expiry epoch ms>~<owner key>`; the expiry never contains the separator, the owner may. */
+export const formatSessionHint = ({ expires, owner }: SessionHint): string => `${expires}~${owner}`;
+
+/** Reads a decoded session hint value, or `undefined` when it is malformed. */
+export function parseSessionHint(value: string): SessionHint | undefined {
+ const separator = value.indexOf('~');
+ const expires = Number(value.slice(0, separator));
+ if (separator < 1 || !Number.isFinite(expires)) {
+ return undefined;
+ }
+ return { expires, owner: value.slice(separator + 1) };
+}
+
/**
* Bumped by hand when a release changes what resolving a theme emits without changing its roles
* (a palette value, a fallback derivation, an emitted attribute), so cached entries are rebuilt.