(
@@ -101,8 +116,10 @@ function renderProvider() {
- ,
+
);
+ const result = render(tree());
+ return { ...result, rerenderProvider: () => result.rerender(tree()) };
}
/** Renders without test:true so silentRefresh actually runs */
@@ -142,7 +159,7 @@ function renderOptionalProvider() {
);
}
-describe('AuthContextProvider — test mode', () => {
+describe('AuthContextProvider: test mode', () => {
beforeEach(() => {
jest.clearAllMocks();
});
@@ -153,9 +170,188 @@ describe('AuthContextProvider — test mode', () => {
expect(getByTestId('consumer')).toHaveAttribute('data-auth-ready', 'true');
expect(mockRefreshMutate).not.toHaveBeenCalled();
});
+
+ it('preserves auth context when mutation result objects change without an auth change', () => {
+ const { rerenderProvider } = renderProvider();
+ const previousContext = capturedAuthContext;
+
+ rerenderProvider();
+
+ expect(capturedAuthContext?.login).toBe(previousContext?.login);
+ expect(capturedAuthContext?.logout).toBe(previousContext?.logout);
+ expect(capturedAuthContext).toBe(previousContext);
+ });
});
-describe('AuthContextProvider — login onError redirect handling', () => {
+describe('AuthContextProvider two-factor login handoff', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ sessionStorage.clear();
+ capturedAuthContext = undefined;
+ window.history.replaceState({}, '', '/login');
+ });
+
+ afterEach(() => {
+ sessionStorage.clear();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('routes unenrolled users to required setup', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'setup-token',
+ });
+ });
+
+ expect(mockNavigate).toHaveBeenCalledWith('/login/2fa/setup', { replace: true });
+ /** The credential is handed over out of band, never through the address bar. */
+ expect(readTwoFactorSetupToken()).toBe('setup-token');
+ });
+
+ it('retains a non-default destination through setup reload and consumes it after completion', () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/login?redirect_to=%2Fc%2Fredirect-lifecycle-proof%3Fmodel%3Dtest',
+ );
+ const firstRender = renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'setup-token',
+ });
+ });
+
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe('/c/redirect-lifecycle-proof?model=test');
+ firstRender.unmount();
+ window.history.replaceState({}, '', '/login/2fa/setup');
+ renderProvider();
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+
+ expect(mockNavigate).toHaveBeenLastCalledWith('/c/redirect-lifecycle-proof?model=test', {
+ replace: true,
+ });
+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+ expect(mockNavigate).toHaveBeenLastCalledWith('/c/new', { replace: true });
+ });
+
+ it('keeps enrolled users on the existing verification route', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ tempToken: 'challenge-token',
+ });
+ });
+
+ expect(mockNavigate).toHaveBeenCalledWith('/login/2fa?tempToken=challenge-token', {
+ replace: true,
+ });
+ });
+
+ /**
+ * An abandoned setup token outlives the screen that staged it, so a later sign-in in the same tab
+ * must not leave the previous user's enrollment credential available to finish.
+ */
+ it('drops an abandoned setup token when the next sign-in succeeds', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'abandoned-token',
+ });
+ });
+ expect(readTwoFactorSetupToken()).toBe('abandoned-token');
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ token: 'other-user-token',
+ user: { id: 'user-2' },
+ });
+ });
+
+ expect(readTwoFactorSetupToken()).toBe('');
+ });
+
+ it('drops an abandoned setup token when the next sign-in is challenged', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'abandoned-token',
+ });
+ });
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ tempToken: 'challenge-token',
+ });
+ });
+
+ expect(readTwoFactorSetupToken()).toBe('');
+ });
+
+ it('drops an abandoned setup token when the next sign-in fails', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'abandoned-token',
+ });
+ });
+
+ act(() => {
+ mockCapturedLoginOptions.onError({ response: { status: 401 } });
+ });
+
+ expect(readTwoFactorSetupToken()).toBe('');
+ });
+
+ it('still hands the fresh credential to a setup that follows another sign-in', () => {
+ renderProvider();
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'first-token',
+ });
+ });
+
+ act(() => {
+ mockCapturedLoginOptions.onSuccess({
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'second-token',
+ });
+ });
+
+ expect(readTwoFactorSetupToken()).toBe('second-token');
+ });
+});
+
+describe('AuthContextProvider: login onError redirect handling', () => {
beforeEach(() => {
jest.clearAllMocks();
window.history.replaceState({}, '', '/login');
@@ -213,21 +409,24 @@ describe('AuthContextProvider — login onError redirect handling', () => {
expect(mockNavigate).toHaveBeenCalledWith('/login', { replace: true });
});
- it('surfaces the cross-origin rejection code instead of the HTTP status message', () => {
- jest.useFakeTimers();
- const { getByTestId } = renderProvider();
+ it.each(['auth_cross_origin', 'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED'])(
+ 'surfaces the recognized %s rejection code instead of the HTTP status message',
+ (code) => {
+ jest.useFakeTimers();
+ const { getByTestId } = renderProvider();
- act(() => {
- mockCapturedLoginOptions.onError({
- message: 'Request failed with status code 403',
- response: { data: { message: 'Cross-site request rejected', code: 'auth_cross_origin' } },
+ act(() => {
+ mockCapturedLoginOptions.onError({
+ message: 'Request failed with status code 403',
+ response: { data: { code } },
+ });
+ jest.advanceTimersByTime(400);
});
- jest.advanceTimersByTime(400);
- });
- expect(getByTestId('consumer')).toHaveAttribute('data-error', 'auth_cross_origin');
- jest.useRealTimers();
- });
+ expect(getByTestId('consumer')).toHaveAttribute('data-error', code);
+ jest.useRealTimers();
+ },
+ );
it('keeps the HTTP status message for other rejections that carry a code', () => {
jest.useFakeTimers();
@@ -376,6 +575,50 @@ describe('AuthContextProvider — silentRefresh post-login redirect', () => {
jest.useRealTimers();
});
+ /**
+ * A federated sign-in lands here rather than through the login mutation, so the previous user's
+ * abandoned enrollment credential has to be dropped on this path too.
+ */
+ it('drops an abandoned setup token when a refresh sign-in is accepted', () => {
+ jest.useFakeTimers();
+ persistTwoFactorSetupToken('abandoned-token');
+
+ renderProviderLive();
+
+ const [, refreshOptions] = mockRefreshMutate.mock.calls[0] as [
+ unknown,
+ { onSuccess: (data: unknown) => void },
+ ];
+
+ act(() => {
+ refreshOptions.onSuccess({ user: { id: '1', role: 'USER' }, token: 'new-token' });
+ });
+ act(() => {
+ jest.advanceTimersByTime(100);
+ });
+
+ expect(readTwoFactorSetupToken()).toBe('');
+ jest.useRealTimers();
+ });
+
+ it('routes an unenrolled refresh session to setup and preserves the requested destination', () => {
+ window.history.replaceState({}, '', '/c/requested?model=test#latest');
+ renderProviderLive();
+ const [, refreshOptions] = mockRefreshMutate.mock.calls[0] as [
+ unknown,
+ { onSuccess: (data: unknown) => void },
+ ];
+
+ act(() => {
+ refreshOptions.onSuccess({ twoFASetupRequired: true, tempToken: 'setup token' });
+ });
+
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe('/c/requested?model=test#latest');
+ expect(mockNavigate).toHaveBeenCalledWith('/login/2fa/setup', { replace: true });
+ /** Carried verbatim rather than URL-encoded, because it never enters a URL. */
+ expect(readTwoFactorSetupToken()).toBe('setup token');
+ });
+
it('navigates to current URL when no stored redirect exists', () => {
jest.useFakeTimers();
window.history.replaceState({}, '', '/c/new');
@@ -399,6 +642,57 @@ describe('AuthContextProvider — silentRefresh post-login redirect', () => {
jest.useRealTimers();
});
+ it('keeps the enforcement destination when refresh lands on the setup route', () => {
+ window.history.replaceState({}, '', '/login/2fa/setup?redirect_to=%2Fc%2Frequested');
+ persistTwoFactorSetupToken('setup-token');
+ renderProviderLive();
+ const [, refreshOptions] = mockRefreshMutate.mock.calls[0] as [
+ unknown,
+ { onSuccess: (data: unknown) => void },
+ ];
+
+ act(() => {
+ refreshOptions.onSuccess({ twoFASetupRequired: true, tempToken: 'refreshed token' });
+ });
+
+ /** Replacing the route again would drop the query holding the only copy of the destination. */
+ expect(mockNavigate).not.toHaveBeenCalled();
+ expect(window.location.search).toBe('?redirect_to=%2Fc%2Frequested');
+ /** The setup route is not a safe redirect, so it must never be banked as one either. */
+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
+ expect(readTwoFactorSetupToken()).toBe('refreshed token');
+ });
+
+ it('keeps a required setup route mounted when refresh fails after reload', () => {
+ window.history.replaceState({}, '', '/login/2fa/setup');
+ persistTwoFactorSetupToken('setup-token');
+ renderProviderLive();
+ const [, refreshOptions] = mockRefreshMutate.mock.calls[0] as [
+ unknown,
+ { onError: (error: Error) => void },
+ ];
+
+ act(() => refreshOptions.onError(new Error('No refresh session')));
+
+ expect(mockNavigate).not.toHaveBeenCalled();
+ expect(window.location.pathname).toBe('/login/2fa/setup');
+ });
+
+ it('keeps a required setup route mounted when refresh returns no token after reload', () => {
+ window.history.replaceState({}, '', '/login/2fa/setup');
+ persistTwoFactorSetupToken('setup-token');
+ renderProviderLive();
+ const [, refreshOptions] = mockRefreshMutate.mock.calls[0] as [
+ unknown,
+ { onSuccess: (data: unknown) => void },
+ ];
+
+ act(() => refreshOptions.onSuccess({}));
+
+ expect(mockNavigate).not.toHaveBeenCalled();
+ expect(window.location.pathname).toBe('/login/2fa/setup');
+ });
+
it('does not re-trigger silentRefresh after successful redirect', () => {
jest.useFakeTimers();
sessionStorage.setItem(SESSION_KEY, '/c/abc?endpoint=bedrock');
@@ -716,3 +1010,115 @@ describe('AuthContextProvider — custom role detection and fetching', () => {
jest.useRealTimers();
});
});
+
+describe('AuthContextProvider: enrollment hand-off that keeps the document', () => {
+ const mockUseGetUserQuery = jest.requireMock('~/data-provider').useGetUserQuery;
+
+ const dispatchHandoff = (inDocument: boolean) =>
+ act(() => {
+ window.dispatchEvent(
+ new CustomEvent('authRedirectStarted', {
+ detail: { href: '/login/2fa/setup', inDocument },
+ }),
+ );
+ });
+
+ const lastUserQueryConfig = () => {
+ const calls = mockUseGetUserQuery.mock.calls;
+ return calls[calls.length - 1][0];
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ sessionStorage.clear();
+ clearTwoFactorSetupToken();
+ capturedAuthContext = undefined;
+ window.history.replaceState({}, '', '/c/some-chat');
+ });
+
+ afterEach(() => {
+ clearRetainedFileDeletions();
+ sessionStorage.clear();
+ clearTwoFactorSetupToken();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('finishes enrollment with a ready session that can retain its own failed deletions', () => {
+ clearRetainedFileDeletions();
+ const { getByTestId } = renderProviderLive();
+ expect(getByTestId('consumer')).toHaveAttribute('data-auth-ready', 'false');
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+ const deletion = {
+ file_id: 'enrolled-user-file',
+ embedded: false,
+ filepath: '/uploads/user-1/file.txt',
+ source: FileSources.local,
+ };
+ retainFileDeletion(deletion);
+
+ expect(getByTestId('consumer')).toHaveAttribute('data-auth-ready', 'true');
+ expect(takeRetainedFileDeletions()).toEqual([deletion]);
+
+ dispatchHandoff(true);
+ expect(takeRetainedFileDeletions()).toEqual([]);
+ retainFileDeletion(deletion);
+ expect(takeRetainedFileDeletions()).toEqual([]);
+ });
+
+ /**
+ * Where session storage is blocked the hand-off routes in place instead of replacing the
+ * document, so this provider stays mounted and the session it redirects away from would live on.
+ * An enabled user query leaves for the login page as soon as it fails, which would pull the user
+ * off the enrollment the server is demanding.
+ */
+ it('releases the replaced session so its user query cannot navigate away', () => {
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(chatFilterStatusAtom, 'archived');
+ jotaiStore.set(chatFilterTagsAtom, ['previous-session']);
+ const { getByTestId } = renderProvider();
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+ expect(getByTestId('consumer').getAttribute('data-authenticated')).toBe('true');
+ expect(lastUserQueryConfig()).toEqual(expect.objectContaining({ enabled: true }));
+
+ dispatchHandoff(true);
+
+ expect(getByTestId('consumer').getAttribute('data-authenticated')).toBe('false');
+ expect(lastUserQueryConfig()).toEqual(expect.objectContaining({ enabled: false }));
+ expect(jotaiStore.get(chatFilterStatusAtom)).toBe('active');
+ expect(jotaiStore.get(chatFilterTagsAtom)).toEqual([]);
+ });
+
+ /** A replaced document discards the session on its own, so nothing is released early here. */
+ it('leaves the session alone when the hand-off replaces the document', () => {
+ const { getByTestId } = renderProvider();
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+
+ dispatchHandoff(false);
+
+ expect(getByTestId('consumer').getAttribute('data-authenticated')).toBe('true');
+ expect(lastUserQueryConfig()).toEqual(expect.objectContaining({ enabled: true }));
+ });
+
+ /** With storage blocked the in-memory mirror is the only copy the setup screen can read. */
+ it('keeps the setup credential the surviving document is holding', () => {
+ renderProvider();
+
+ act(() => {
+ capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
+ });
+ persistTwoFactorSetupToken('setup-token');
+
+ dispatchHandoff(true);
+
+ expect(readTwoFactorSetupToken()).toBe('setup-token');
+ });
+});
diff --git a/client/src/hooks/useTimeout.tsx b/client/src/hooks/useTimeout.tsx
index 456dfd1800..e008d14f1a 100644
--- a/client/src/hooks/useTimeout.tsx
+++ b/client/src/hooks/useTimeout.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useCallback } from 'react';
type TUseTimeoutParams = {
callback: (error: string | number | boolean | null) => void;
@@ -9,20 +9,23 @@ type TTimeout = ReturnType
| null;
function useTimeout({ callback, delay = 400 }: TUseTimeoutParams) {
const timeout = useRef(null);
- const callOnTimeout = (value?: string) => {
- // Clear existing timeout
- if (timeout.current !== null) {
- clearTimeout(timeout.current);
- }
+ const callOnTimeout = useCallback(
+ (value?: string) => {
+ // Clear existing timeout
+ if (timeout.current !== null) {
+ clearTimeout(timeout.current);
+ }
- // Set new timeout
- if (value != null && value) {
- console.log(value);
- timeout.current = setTimeout(() => {
- callback(value);
- }, delay);
- }
- };
+ // Set new timeout
+ if (value != null && value) {
+ console.log(value);
+ timeout.current = setTimeout(() => {
+ callback(value);
+ }, delay);
+ }
+ },
+ [callback, delay],
+ );
// Clear timeout when the component unmounts
useEffect(() => {
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index c2e9973cc8..d5c24812b6 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -317,6 +317,7 @@
"com_auth_error_login": "Unable to login with the information provided. Please check your credentials and try again.",
"com_auth_error_login_ban": "Your account has been temporarily banned due to violations of our service.",
"com_auth_error_login_cross_origin": "Sign-in was blocked because the request did not come from this site. Open the login page directly and try again.",
+ "com_auth_error_login_federated_two_factor": "This account signs in through your identity provider. Use that option to continue.",
"com_auth_error_login_rl": "Too many login attempts in a short amount of time. Please try again later.",
"com_auth_error_login_server": "There was an internal server error. Please wait a few moments and try again.",
"com_auth_error_login_unverified": "Your account has not been verified. Please check your email for a verification link.",
@@ -361,6 +362,10 @@
"com_auth_to_reset_your_password": "to reset your password.",
"com_auth_to_try_again": "to try again.",
"com_auth_two_factor": "Check your preferred one-time password application for a code",
+ "com_auth_two_factor_setup_expired": "This two-factor setup session is missing or expired. Return to sign in and try again.",
+ "com_auth_two_factor_setup_finalize_error": "We could not finish signing you in. Your two-factor setup is saved. Try completing setup again.",
+ "com_auth_two_factor_setup_required": "Two-Factor Authentication Required",
+ "com_auth_two_factor_setup_required_description": "Your administrator requires two-factor authentication. Set it up before continuing.",
"com_auth_username": "Username (optional)",
"com_auth_username_max_length": "Username must be less than 20 characters",
"com_auth_username_min_length": "Username must be at least 2 characters",
@@ -989,6 +994,8 @@
"com_ui_2fa_enabled": "2FA has been enabled",
"com_ui_2fa_generate_error": "There was an error generating two-factor authentication settings",
"com_ui_2fa_invalid": "Invalid two-factor authentication code",
+ "com_ui_2fa_required": "Required by administrator",
+ "com_ui_2fa_scan_qr": "Scan QR Code",
"com_ui_2fa_setup": "Setup 2FA",
"com_ui_2fa_verification_required": "Enter your 2FA code to continue",
"com_ui_2fa_verified": "Successfully verified Two-Factor Authentication",
diff --git a/client/src/routes/Layouts/Startup.tsx b/client/src/routes/Layouts/Startup.tsx
index 7775b770b4..5dfe1a222f 100644
--- a/client/src/routes/Layouts/Startup.tsx
+++ b/client/src/routes/Layouts/Startup.tsx
@@ -1,7 +1,12 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import type { TStartupConfig } from 'librechat-data-provider';
-import { DEFAULT_APP_TITLE, REDIRECT_PARAM, hasStoredRedirect, setDocumentTitle } from '~/utils';
+import {
+ DEFAULT_APP_TITLE,
+ setDocumentTitle,
+ getPostLoginRedirect,
+ isRequiredTwoFactorSetupRoute,
+} from '~/utils';
import { TranslationKeys, useLocalize } from '~/hooks';
import { useGetStartupConfig } from '~/data-provider';
import AuthLayout from '~/components/Auth/AuthLayout';
@@ -12,6 +17,7 @@ const headerMap: Record = {
'/forgot-password': 'com_auth_reset_password',
'/reset-password': 'com_auth_reset_password',
'/login/2fa': 'com_auth_verify_your_identity',
+ '/login/2fa/setup': 'com_auth_two_factor_setup_required',
};
export default function StartupLayout({ isAuthenticated }: { isAuthenticated?: boolean }) {
@@ -29,18 +35,32 @@ export default function StartupLayout({ isAuthenticated }: { isAuthenticated?: b
const navigate = useNavigate();
const location = useLocation();
+ const navigateRef = useRef(navigate);
+ navigateRef.current = navigate;
+
+ /**
+ * Only an already-authenticated arrival is this layout's to redirect. When authentication
+ * completes while an auth route is mounted, the auth context has already consumed the pending
+ * destination and navigated there; re-resolving it here would find nothing left and replace that
+ * destination with `/c/new`. Mandatory enrollment is the one arrival that stays put: the user
+ * holding a setup token is authenticated precisely until they enroll, so sending them on would
+ * bounce them straight back out of the screen the server is demanding they complete.
+ */
useEffect(() => {
- if (isAuthenticated) {
- const hasPendingRedirect =
- new URLSearchParams(window.location.search).has(REDIRECT_PARAM) || hasStoredRedirect();
- if (!hasPendingRedirect) {
- navigate('/c/new', { replace: true });
- }
+ if (!isAuthenticated || isRequiredTwoFactorSetupRoute()) {
+ return;
}
+ const destination =
+ getPostLoginRedirect(new URLSearchParams(window.location.search)) ?? '/c/new';
+ navigateRef.current(destination, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only by design; see comment above
+ }, []);
+
+ useEffect(() => {
if (data) {
setStartupConfig(data);
}
- }, [isAuthenticated, navigate, data]);
+ }, [data]);
useEffect(() => {
setDocumentTitle(startupConfig?.appTitle || DEFAULT_APP_TITLE, true);
diff --git a/client/src/routes/__tests__/StartupLayout.spec.tsx b/client/src/routes/__tests__/StartupLayout.spec.tsx
index 647c53006b..c95a2ec8ad 100644
--- a/client/src/routes/__tests__/StartupLayout.spec.tsx
+++ b/client/src/routes/__tests__/StartupLayout.spec.tsx
@@ -1,7 +1,8 @@
/* eslint-disable i18next/no-literal-string */
import React from 'react';
-import { render, waitFor } from '@testing-library/react';
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { clearTwoFactorSetupToken, persistTwoFactorSetupToken } from 'librechat-data-provider';
import StartupLayout from '~/routes/Layouts/Startup';
import { SESSION_KEY } from '~/utils';
@@ -32,6 +33,20 @@ function NewConversation() {
return New Conversation
;
}
+/** Reproduces the real sequence: the layout mounts unauthenticated, then authentication lands. */
+function AuthFlipRoute() {
+ const [isAuthenticated, setIsAuthenticated] = React.useState(false);
+
+ return (
+
+
+
+
+ );
+}
+
const createTestRouter = (initialEntry: string, isAuthenticated: boolean) =>
createMemoryRouter(
[
@@ -44,6 +59,10 @@ const createTestRouter = (initialEntry: string, isAuthenticated: boolean) =>
path: '/c/new',
element: ,
},
+ {
+ path: '/c/:conversationId',
+ element: ,
+ },
],
{ initialEntries: [initialEntry] },
);
@@ -69,27 +88,50 @@ describe('StartupLayout — redirect race condition', () => {
});
});
- it('does NOT navigate to /c/new when redirect_to URL param is present', async () => {
+ it('navigates to the URL redirect when authentication completes', async () => {
window.history.replaceState({}, '', '/login?redirect_to=%2Fc%2Fabc123');
const router = createTestRouter('/login?redirect_to=%2Fc%2Fabc123', true);
render();
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- expect(router.state.location.pathname).toBe('/login');
+ await waitFor(() => expect(router.state.location.pathname).toBe('/c/abc123'));
});
- it('does NOT navigate to /c/new when sessionStorage redirect is present', async () => {
+ it('navigates to the stored redirect when authentication completes', async () => {
window.history.replaceState({}, '', '/login');
sessionStorage.setItem(SESSION_KEY, '/c/abc123');
const router = createTestRouter('/login', true);
render();
+ await waitFor(() => expect(router.state.location.pathname).toBe('/c/abc123'));
+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
+ });
+
+ it('leaves the pending redirect alone when authentication completes after mount', async () => {
+ window.history.replaceState({}, '', '/login');
+ sessionStorage.setItem(SESSION_KEY, '/c/abc123');
+
+ const router = createMemoryRouter(
+ [
+ {
+ path: '/login',
+ element: ,
+ children: [{ index: true, element: }],
+ },
+ { path: '/c/new', element: },
+ { path: '/c/:conversationId', element: },
+ ],
+ { initialEntries: ['/login'] },
+ );
+ render();
+
+ fireEvent.click(screen.getByTestId('authenticate'));
await new Promise((resolve) => setTimeout(resolve, 100));
+ /** The auth context owns this transition, so the stored destination must still be intact. */
expect(router.state.location.pathname).toBe('/login');
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe('/c/abc123');
});
it('does NOT navigate when not authenticated', async () => {
@@ -103,3 +145,70 @@ describe('StartupLayout — redirect race condition', () => {
expect(router.state.location.pathname).toBe('/login');
});
});
+
+describe('StartupLayout: mandatory enrollment', () => {
+ const createSetupRouter = (initialEntry: string) =>
+ createMemoryRouter(
+ [
+ {
+ path: '/login/2fa/setup',
+ element: ,
+ children: [{ index: true, element: }],
+ },
+ { path: '/c/new', element: },
+ { path: '/c/:conversationId', element: },
+ ],
+ { initialEntries: [initialEntry] },
+ );
+
+ beforeEach(() => {
+ sessionStorage.clear();
+ clearTwoFactorSetupToken();
+ });
+
+ afterEach(() => {
+ clearTwoFactorSetupToken();
+ window.history.replaceState({}, '', '/');
+ jest.restoreAllMocks();
+ });
+
+ /**
+ * The in-document hand-off leaves the auth context authenticated, so without the exemption this
+ * layout redirects the user straight back out of the setup the server is demanding.
+ */
+ it('stays on the setup route when an authenticated user holds a setup token', async () => {
+ window.history.replaceState({}, '', '/login/2fa/setup');
+ persistTwoFactorSetupToken('setup-token');
+
+ const router = createSetupRouter('/login/2fa/setup');
+ render();
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ expect(router.state.location.pathname).toBe('/login/2fa/setup');
+ });
+
+ it('keeps the pending destination banked while enrollment is outstanding', async () => {
+ window.history.replaceState({}, '', '/login/2fa/setup');
+ sessionStorage.setItem(SESSION_KEY, '/c/abc123');
+ persistTwoFactorSetupToken('setup-token');
+
+ const router = createSetupRouter('/login/2fa/setup');
+ render();
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ expect(router.state.location.pathname).toBe('/login/2fa/setup');
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe('/c/abc123');
+ });
+
+ /** The exemption is the live credential, not the path, so a stale visit still moves on. */
+ it('redirects an authenticated arrival that carries no setup token', async () => {
+ window.history.replaceState({}, '', '/login/2fa/setup');
+
+ const router = createSetupRouter('/login/2fa/setup');
+ render();
+
+ await waitFor(() => expect(router.state.location.pathname).toBe('/c/new'));
+ });
+});
diff --git a/client/src/routes/__tests__/skillsRoutes.spec.tsx b/client/src/routes/__tests__/skillsRoutes.spec.tsx
index f391a84921..18feeec50b 100644
--- a/client/src/routes/__tests__/skillsRoutes.spec.tsx
+++ b/client/src/routes/__tests__/skillsRoutes.spec.tsx
@@ -7,6 +7,7 @@ jest.mock('~/components/Auth', () => ({
ResetPassword: () => null,
ApiErrorWatcher: () => null,
TwoFactorScreen: () => null,
+ TwoFactorSetupScreen: () => null,
RequestPasswordReset: () => null,
}));
diff --git a/client/src/routes/index.tsx b/client/src/routes/index.tsx
index 873b3e86db..90106aa84d 100644
--- a/client/src/routes/index.tsx
+++ b/client/src/routes/index.tsx
@@ -6,6 +6,7 @@ import {
ResetPassword,
ApiErrorWatcher,
TwoFactorScreen,
+ TwoFactorSetupScreen,
RequestPasswordReset,
} from '~/components/Auth';
import { OAuthSuccess, OAuthError } from '~/components/OAuth';
@@ -119,6 +120,10 @@ export const router = createBrowserRouter(
path: 'login/2fa',
element: ,
},
+ {
+ path: 'login/2fa/setup',
+ element: ,
+ },
],
},
dashboardRoutes,
diff --git a/client/src/utils/__tests__/getLoginError.test.ts b/client/src/utils/__tests__/getLoginError.test.ts
new file mode 100644
index 0000000000..79e923936a
--- /dev/null
+++ b/client/src/utils/__tests__/getLoginError.test.ts
@@ -0,0 +1,28 @@
+import { TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE } from 'librechat-data-provider';
+import getLoginError from '../getLoginError';
+
+describe('getLoginError', () => {
+ it('falls back to the generic message without error text', () => {
+ expect(getLoginError('')).toBe('com_auth_error_login');
+ });
+
+ it.each([
+ ['Request failed with status code 429', 'com_auth_error_login_rl'],
+ ['Request failed with status code 403', 'com_auth_error_login_ban'],
+ ['Request failed with status code 500', 'com_auth_error_login_server'],
+ ['Request failed with status code 422', 'com_auth_error_login_unverified'],
+ ['something unmapped', 'com_auth_error_login'],
+ ])('maps %s', (errorText, expected) => {
+ expect(getLoginError(errorText)).toBe(expected);
+ });
+
+ /**
+ * A refused federated password login is also a 403, so it has to win over the ban case; that
+ * mapping is the only thing standing between the user and a false "account banned" message.
+ */
+ it('reports a refused federated password login rather than a ban', () => {
+ expect(getLoginError(TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE)).toBe(
+ 'com_auth_error_login_federated_two_factor',
+ );
+ });
+});
diff --git a/client/src/utils/__tests__/redirect.test.ts b/client/src/utils/__tests__/redirect.test.ts
index 83667b0cf4..780bf083c8 100644
--- a/client/src/utils/__tests__/redirect.test.ts
+++ b/client/src/utils/__tests__/redirect.test.ts
@@ -1,9 +1,11 @@
import {
+ isRequiredTwoFactorSetupRoute,
persistRedirectToSession,
+ clearPostLoginRedirect,
getPostLoginRedirect,
+ peekPostLoginRedirect,
isSafeRedirect,
withBasePath,
- hasStoredRedirect,
SESSION_KEY,
} from '../redirect';
@@ -43,6 +45,44 @@ describe('withBasePath', () => {
});
});
+describe('isRequiredTwoFactorSetupRoute', () => {
+ const setPathname = (pathname: string) => {
+ window.history.replaceState({}, '', pathname);
+ };
+
+ afterEach(() => {
+ sessionStorage.clear();
+ setPathname('/');
+ });
+
+ /** The router matches these spellings, so the guard has to recognise them too. */
+ it.each([
+ '/login/2fa/setup',
+ '/login/2fa/setup/',
+ '/LOGIN/2FA/SETUP',
+ '/Login/2FA/Setup/',
+ '/librechat/login/2fa/setup/',
+ ])('recognises %s as the enrollment screen', (pathname) => {
+ sessionStorage.setItem('two_factor_setup_token', 'setup-token');
+ setPathname(pathname);
+
+ expect(isRequiredTwoFactorSetupRoute()).toBe(true);
+ });
+
+ it('does not claim the route without a live setup token', () => {
+ setPathname('/login/2fa/setup/');
+
+ expect(isRequiredTwoFactorSetupRoute()).toBe(false);
+ });
+
+ it('does not claim a route that merely contains the setup path', () => {
+ sessionStorage.setItem('two_factor_setup_token', 'setup-token');
+ setPathname('/login/2fa/setup/extra');
+
+ expect(isRequiredTwoFactorSetupRoute()).toBe(false);
+ });
+});
+
describe('isSafeRedirect', () => {
it('accepts a simple relative path', () => {
expect(isSafeRedirect('/c/new')).toBe(true);
@@ -217,6 +257,18 @@ describe('getPostLoginRedirect', () => {
});
});
+describe('peekPostLoginRedirect', () => {
+ beforeEach(() => sessionStorage.clear());
+
+ it('preserves a safe stored destination across repeated setup mounts', () => {
+ sessionStorage.setItem(SESSION_KEY, '/c/deep-link?model=test');
+
+ expect(peekPostLoginRedirect(new URLSearchParams())).toBe('/c/deep-link?model=test');
+ expect(peekPostLoginRedirect(new URLSearchParams())).toBe('/c/deep-link?model=test');
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe('/c/deep-link?model=test');
+ });
+});
+
describe('login error redirect_to preservation (AuthContext onError pattern)', () => {
/** Mirrors the logic in AuthContext.tsx loginUser.onError */
function buildLoginErrorPath(search: string): string {
@@ -273,39 +325,101 @@ describe('persistRedirectToSession', () => {
});
});
+/**
+ * Embedded and private contexts deny session storage by throwing on access. The destination is a
+ * convenience, so a denial must degrade rather than take down the sign-in that carries it.
+ */
describe('blocked session storage', () => {
- /** Embedded and private contexts throw on access rather than answering null. */
- const originalDescriptor = Object.getOwnPropertyDescriptor(window, 'sessionStorage');
+ const denyStorage = () => {
+ const denied = () => {
+ throw new DOMException('denied', 'SecurityError');
+ };
+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(denied);
+ jest.spyOn(Storage.prototype, 'getItem').mockImplementation(denied);
+ jest.spyOn(Storage.prototype, 'removeItem').mockImplementation(denied);
+ };
beforeEach(() => {
- Object.defineProperty(window, 'sessionStorage', {
- configurable: true,
- get() {
- throw new DOMException('Storage is blocked in this context', 'SecurityError');
- },
- });
+ clearPostLoginRedirect();
});
- afterAll(() => {
- if (originalDescriptor != null) {
- Object.defineProperty(window, 'sessionStorage', originalDescriptor);
- }
+ afterEach(() => {
+ jest.restoreAllMocks();
+ clearPostLoginRedirect();
});
- it('persisting a destination does not take down the sign-in', () => {
- expect(() => persistRedirectToSession('/c/new')).not.toThrow();
+ it('does not throw when persisting a destination', () => {
+ denyStorage();
+ expect(() => persistRedirectToSession('/c/abc123')).not.toThrow();
});
- it('a blocked store reads as empty so the URL param still resolves', () => {
- const params = new URLSearchParams('redirect_to=%2Fc%2Fnew');
- expect(getPostLoginRedirect(params)).toBe('/c/new');
+ it('does not throw when consuming a destination', () => {
+ denyStorage();
+ expect(() => getPostLoginRedirect(new URLSearchParams())).not.toThrow();
});
- it('no destination resolves when only the blocked store exists', () => {
+ it('does not throw when clearing a destination', () => {
+ denyStorage();
+ expect(() => clearPostLoginRedirect()).not.toThrow();
+ });
+
+ it('still resolves the URL destination while storage is denied', () => {
+ denyStorage();
+ expect(getPostLoginRedirect(new URLSearchParams('redirect_to=%2Fc%2Fabc123'))).toBe(
+ '/c/abc123',
+ );
+ });
+
+ /** The in-document hand-off never replaces the document, so the mirror still reaches it. */
+ it('carries the destination in memory across a persist and consume pair', () => {
+ denyStorage();
+ persistRedirectToSession('/c/abc123');
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBe('/c/abc123');
+ });
+
+ it('consumes the in-memory destination exactly once', () => {
+ denyStorage();
+ persistRedirectToSession('/c/abc123');
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBe('/c/abc123');
expect(getPostLoginRedirect(new URLSearchParams())).toBeNull();
});
- it('hasStoredRedirect counts a blocked store as empty', () => {
- expect(hasStoredRedirect()).toBe(false);
+ it('drops the in-memory destination on clear', () => {
+ denyStorage();
+ persistRedirectToSession('/c/abc123');
+ clearPostLoginRedirect();
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBeNull();
+ });
+
+ it('still refuses an unsafe destination while storage is denied', () => {
+ denyStorage();
+ persistRedirectToSession('https://evil.com');
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBeNull();
+ });
+
+ /**
+ * Storage answers here, so it is the authority. A mirror written on every persist would outlive
+ * a destination cleared straight out of storage and resurrect it on the next sign-in.
+ */
+ it('does not resurrect a destination dropped straight from storage', () => {
+ persistRedirectToSession('/c/abc123');
+ sessionStorage.clear();
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBeNull();
+ });
+
+ it('does not let a denied write outlive a later working one', () => {
+ denyStorage();
+ persistRedirectToSession('/c/denied');
+ jest.restoreAllMocks();
+
+ persistRedirectToSession('/c/stored');
+ sessionStorage.clear();
+
+ expect(getPostLoginRedirect(new URLSearchParams())).toBeNull();
});
});
diff --git a/client/src/utils/getLoginError.ts b/client/src/utils/getLoginError.ts
index 602c6dfc85..28b47f6d32 100644
--- a/client/src/utils/getLoginError.ts
+++ b/client/src/utils/getLoginError.ts
@@ -1,4 +1,4 @@
-import { ErrorTypes } from 'librechat-data-provider';
+import { ErrorTypes, TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE } from 'librechat-data-provider';
import { TranslationKeys } from '~/hooks';
const getLoginError = (errorText: string): TranslationKeys => {
@@ -11,6 +11,9 @@ const getLoginError = (errorText: string): TranslationKeys => {
switch (true) {
case errorText === ErrorTypes.AUTH_CROSS_ORIGIN:
return 'com_auth_error_login_cross_origin';
+ /** Must precede the status cases: this is also a 403, but it is not a ban. */
+ case errorText.includes(TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE):
+ return 'com_auth_error_login_federated_two_factor';
case errorText.includes('429'):
return 'com_auth_error_login_rl';
case errorText.includes('403'):
diff --git a/client/src/utils/redirect.ts b/client/src/utils/redirect.ts
index 0cde6615d8..737547a5b9 100644
--- a/client/src/utils/redirect.ts
+++ b/client/src/utils/redirect.ts
@@ -1,3 +1,5 @@
+import { readTwoFactorSetupToken } from 'librechat-data-provider';
+
export const REDIRECT_PARAM = 'redirect_to';
export const SESSION_KEY = 'post_login_redirect_to';
@@ -31,35 +33,64 @@ function resolvesToSameOrigin(url: string): boolean {
}
}
-/** Session storage is blocked outright in embedded and private contexts, where it throws on
- * access rather than returning null. The destination is a convenience, never a credential, so a
- * blocked store must cost the deep link, never the sign-in that carries it: every access
- * degrades to "no destination stored". Every other session-storage consumer in the client is
- * already guarded this way; the redirect flow was the one reaching for the store bare-handed. */
-export const readStoredRedirect = (): string | null => {
- try {
- return sessionStorage.getItem(SESSION_KEY);
- } catch {
- return null;
- }
-};
+interface PostLoginRedirectWindow extends Window {
+ __librechatPostLoginRedirect?: string;
+}
-export const dropStoredRedirect = (): void => {
+/**
+ * Session storage is blocked outright in embedded and private contexts, where it throws on access
+ * rather than returning null. The destination is a convenience, never a credential, so a blocked
+ * store must never take down the sign-in that carries it: access degrades to an in-memory mirror,
+ * which still reaches the hand-offs that stay inside the document.
+ *
+ * Storage stays authoritative whenever it answers, and the mirror is written only where storage
+ * refused. Mirroring every write would let a destination that storage has since dropped come back
+ * from the dead.
+ */
+const readStoredRedirect = (): string | null => {
try {
- sessionStorage.removeItem(SESSION_KEY);
+ return window.sessionStorage.getItem(SESSION_KEY);
} catch {
- // A blocked store holds nothing to drop.
+ return (window as PostLoginRedirectWindow).__librechatPostLoginRedirect ?? null;
}
};
const writeStoredRedirect = (value: string): void => {
try {
- sessionStorage.setItem(SESSION_KEY, value);
+ window.sessionStorage.setItem(SESSION_KEY, value);
+ delete (window as PostLoginRedirectWindow).__librechatPostLoginRedirect;
} catch {
- // The destination cannot cross a document swap in this context; the sign-in continues.
+ (window as PostLoginRedirectWindow).__librechatPostLoginRedirect = value;
}
};
+const dropStoredRedirect = (): void => {
+ delete (window as PostLoginRedirectWindow).__librechatPostLoginRedirect;
+ try {
+ window.sessionStorage.removeItem(SESSION_KEY);
+ } catch {
+ // Ignore unavailable storage.
+ }
+};
+
+/** Suffix rather than whole path, so a deployment served under a basename still matches. */
+const SETUP_PATH_SUFFIX = '/login/2fa/setup';
+
+/**
+ * The mandatory enrollment screen holding a live setup token is a destination in its own right, so
+ * it is exempt from the post-login redirects that would otherwise send an authenticated but
+ * unenrolled user on to the app.
+ *
+ * The router matches case-insensitively and ignores a trailing slash, so recognising the route by
+ * its exact spelling would strand anyone whose URL differs only in those: the screen renders, this
+ * reports it unprotected, and the redirect pulls them off a live enrollment. Normalize the same way
+ * the router does before comparing.
+ */
+export function isRequiredTwoFactorSetupRoute(): boolean {
+ const pathname = window.location.pathname.toLowerCase().replace(/\/+$/, '');
+ return pathname.endsWith(SETUP_PATH_SUFFIX) && !!readTwoFactorSetupToken();
+}
+
/** Validates that a redirect target is a safe relative path (not an absolute or protocol-relative URL) */
export function isSafeRedirect(url: string): boolean {
if (hasControlChar(url)) {
@@ -75,23 +106,27 @@ export function isSafeRedirect(url: string): boolean {
return resolvesToSameOrigin(url);
}
-/** Whether a destination is waiting to be consumed; storage that refuses to answer counts as none. */
-export const hasStoredRedirect = (): boolean => readStoredRedirect() != null;
-
/**
* Resolves the post-login redirect from URL params and sessionStorage,
* cleans up both sources, and returns the validated target (or null).
*/
export function getPostLoginRedirect(searchParams: URLSearchParams): string | null {
+ const target = peekPostLoginRedirect(searchParams);
+ dropStoredRedirect();
+ return target;
+}
+
+/** Drops a pending destination, so a later sign-in starts from a clean slate. */
+export function clearPostLoginRedirect(): void {
+ dropStoredRedirect();
+}
+
+export function peekPostLoginRedirect(searchParams: URLSearchParams): string | null {
const urlRedirect = searchParams.get(REDIRECT_PARAM);
const storedRedirect = readStoredRedirect();
const target = urlRedirect ?? storedRedirect;
- if (storedRedirect) {
- dropStoredRedirect();
- }
-
if (target == null || !isSafeRedirect(target)) {
return null;
}
diff --git a/config/reset-password.js b/config/reset-password.js
index 3144ade839..3081a24fb0 100644
--- a/config/reset-password.js
+++ b/config/reset-password.js
@@ -2,6 +2,7 @@ const path = require('path');
const bcrypt = require('bcryptjs');
const readline = require('readline');
const mongoose = require('mongoose');
+const { createPasswordResetUpdate } = require('@librechat/api');
const { createModels, createMethods } = require('@librechat/data-schemas');
const { User, Passkey, Session } = createModels(mongoose);
require('module-alias')({ base: path.resolve(__dirname, '..', 'api') });
@@ -67,11 +68,8 @@ const resetPassword = async () => {
*/
const updated = await methods.updateUser(
user._id.toString(),
- {
- password: hashedPassword,
- /** Access tokens minted before this stamp stop verifying */
- credentialsChangedAt: new Date(),
- },
+ /** Stamps credentialsChangedAt and drops any staged enrollment, as the web reset does. */
+ createPasswordResetUpdate(hashedPassword),
{},
{ preserveExpiresAt: true },
);
diff --git a/e2e/playwright.config.mock.ts b/e2e/playwright.config.mock.ts
index 544ed50845..a94fda2745 100644
--- a/e2e/playwright.config.mock.ts
+++ b/e2e/playwright.config.mock.ts
@@ -167,6 +167,7 @@ const vanillaOverrides = {
ALLOW_SOCIAL_LOGIN: 'false',
ALLOW_SOCIAL_REGISTRATION: 'false',
ALLOW_SHARED_LINKS_PUBLIC: 'true',
+ ENFORCE_TWO_FACTOR_AUTHENTICATION: 'false',
STREAM_KEEP_COMPLETED_JOBS: 'true',
FORK_IP_MAX: '100',
FORK_USER_MAX: '100',
diff --git a/e2e/specs/mock/scenarios/passkeys.spec.ts b/e2e/specs/mock/scenarios/passkeys.spec.ts
index 58f359b0a3..a0376d4139 100644
--- a/e2e/specs/mock/scenarios/passkeys.spec.ts
+++ b/e2e/specs/mock/scenarios/passkeys.spec.ts
@@ -369,6 +369,48 @@ test.describe('passkeys', () => {
await expect(page.getByTestId('nav-user')).toHaveCount(0);
});
+ test('a passkey sign-in on an account that must enroll opens two-factor setup @scenario:required-2fa-passkey-sign-in-hands-off-setup', async ({
+ browser,
+ playwright,
+ baseURL,
+ }) => {
+ test.setTimeout(90000);
+ const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) });
+ user = await createFreshUser(request);
+ context = await openContextFor(browser, request, passkeyBaseURL(baseURL));
+ await request.dispose();
+ const page = await context.newPage();
+ await addVirtualAuthenticator(page);
+
+ await addPasskey(page, user.password);
+ await logOut(page);
+ /**
+ * The harness runs with enforcement off, so the ceremony is verified for real and the
+ * answer is replaced with the payload the server returns under enforcement.
+ */
+ await context.route('**/api/auth/passkey/login/verify', async (route) => {
+ const response = await route.fetch();
+ expect(response.ok()).toBeTruthy();
+ await route.fulfill({
+ response,
+ json: {
+ code: 'TWO_FACTOR_ENROLLMENT_REQUIRED',
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'passkey-setup-token',
+ },
+ });
+ });
+ await signInWithPasskey(page);
+
+ await expect(page).toHaveURL(/\/login\/2fa\/setup$/, { timeout: 15000 });
+ expect(await page.evaluate(() => window.sessionStorage.getItem('two_factor_setup_token'))).toBe(
+ 'passkey-setup-token',
+ );
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ await expect(page.getByTestId('nav-user')).toHaveCount(0);
+ });
+
test('a password reset revokes earlier access tokens and removes passkeys @scenario:password-reset-revokes-tokens-and-passkeys', async ({
playwright,
baseURL,
diff --git a/e2e/specs/mock/scenarios/two-factor-required.spec.ts b/e2e/specs/mock/scenarios/two-factor-required.spec.ts
new file mode 100644
index 0000000000..bfde7abb00
--- /dev/null
+++ b/e2e/specs/mock/scenarios/two-factor-required.spec.ts
@@ -0,0 +1,320 @@
+import { randomUUID } from 'node:crypto';
+import { expect, test } from '@playwright/test';
+import type { Route } from '@playwright/test';
+import type { TStartupConfig, TUser } from 'librechat-data-provider';
+import { NEW_CHAT_PATH } from '../helpers';
+import { seedConversations, seedMessages } from '../db';
+import { loginAdmin } from '../content-filters.helpers';
+
+/**
+ * Acceptance scenarios for deployment-wide 2FA enforcement. The mock harness starts the server
+ * with ENFORCE_TWO_FACTOR_AUTHENTICATION disabled (an inherited deployment .env would otherwise
+ * hold every other spec's user out of the app), so each policy response is produced at the route
+ * boundary exactly as the server emits it under enforcement, matching two-factor-required.spec.ts.
+ */
+
+/** No query string: the setup credential is handed over out of band, never through the URL. */
+const SETUP_ROUTE_PATTERN = /\/login\/2fa\/setup$/;
+/** Enforcement redirects park the destination in the query, so the route may carry one. */
+const SETUP_URL_PATTERN = /\/login\/2fa\/setup(?:\?[^#]*)?$/;
+const LOGIN_ROUTE_PATTERN = /\/login$/;
+const SETUP_TOKEN_STORAGE_KEY = 'two_factor_setup_token';
+
+const ENFORCEMENT_PAYLOAD = {
+ code: 'TWO_FACTOR_ENROLLMENT_REQUIRED',
+ twoFAPending: true,
+ twoFASetupRequired: true,
+ tempToken: 'scenario-setup-token',
+};
+
+const json = (route: Route, body: unknown, status = 200) =>
+ route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
+
+test.describe('required two-factor enrollment · unauthenticated arrival', () => {
+ /** The PWA service worker serves API GETs itself, which would bypass every `page.route` below. */
+ test.use({ storageState: { cookies: [], origins: [] }, serviceWorkers: 'block' });
+
+ test('a password login hands an unenrolled user to setup instead of a session @scenario:required-2fa-login-hands-off-setup', async ({
+ page,
+ }, testInfo) => {
+ test.setTimeout(60000);
+ await page.route('**/api/auth/login', (route) => json(route, ENFORCEMENT_PAYLOAD));
+
+ await page.goto('/login');
+ await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
+ await page.getByRole('textbox', { name: 'Password' }).fill('password');
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ expect(page.url()).not.toContain('tempToken');
+ expect(
+ await page.evaluate((key) => window.sessionStorage.getItem(key), SETUP_TOKEN_STORAGE_KEY),
+ ).toBe('scenario-setup-token');
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ await testInfo.attach('required-two-factor-setup', {
+ body: await page.screenshot(),
+ contentType: 'image/png',
+ });
+ });
+
+ test('a direct visit to setup adopts the token a later refresh hands off @scenario:required-2fa-setup-adopts-refreshed-token', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ let releaseRefresh!: () => void;
+ const refreshReleased = new Promise((resolve) => {
+ releaseRefresh = resolve;
+ });
+ /** Held until the screen has rendered without a credential, so the hand-off arrives late. */
+ await page.route('**/api/auth/refresh', async (route) => {
+ await refreshReleased;
+ await json(route, ENFORCEMENT_PAYLOAD);
+ });
+
+ await page.goto('/login/2fa/setup');
+ const expired = page.getByRole('alert').filter({ hasText: 'missing or expired' });
+ await expect(expired).toBeVisible();
+
+ releaseRefresh();
+
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ await expect(expired).toHaveCount(0);
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ });
+
+ test('completing enrollment lands on the original deep link @scenario:required-2fa-enrollment-preserves-deep-link', async ({
+ page,
+ request,
+ }) => {
+ test.setTimeout(90000);
+ /** The separate API cookie jar leaves the browser unauthenticated until finalization. */
+ const authToken = await loginAdmin(request);
+ const userResponse = await request.get('/api/user', {
+ headers: { Authorization: `Bearer ${authToken}` },
+ });
+ expect(userResponse.ok()).toBe(true);
+ const enrolledUser = { ...((await userResponse.json()) as TUser), twoFactorEnabled: true };
+ /** A real destination lets the app load it instead of correctly redirecting a missing chat. */
+ const conversationId = randomUUID();
+ const deepLink = `/c/${conversationId}?source=required-2fa-test`;
+ const deepLinkPattern = new RegExp(`/c/${conversationId}\\?source=required-2fa-test$`);
+ const transcriptMarker = 'Conversation restored after required two-factor enrollment';
+ await seedConversations(enrolledUser.email, [
+ { conversationId, title: 'Required enrollment destination', updatedAt: new Date() },
+ ]);
+ await seedMessages(enrolledUser.email, conversationId, [
+ {
+ messageId: randomUUID(),
+ parentMessageId: '00000000-0000-0000-0000-000000000000',
+ text: transcriptMarker,
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ },
+ ]);
+ /** Flips only once finalization has promoted the enrollment and minted the session. */
+ let finalized = false;
+
+ await page.route('**/api/auth/login', (route) => json(route, ENFORCEMENT_PAYLOAD));
+ /** Before finalization the user holds no refresh session, exactly as the server leaves them
+ * after a required-enrollment login; afterwards the promoted session refreshes normally. */
+ await page.route('**/api/auth/refresh', async (route) => {
+ if (!finalized) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'text/html; charset=utf-8',
+ body: 'Refresh token not provided',
+ });
+ return;
+ }
+ await json(route, { token: authToken, user: enrolledUser });
+ });
+ await page.route('**/api/user', async (route) => {
+ if (!finalized) {
+ await json(route, { message: 'Unauthorized' }, 401);
+ return;
+ }
+ await json(route, enrolledUser);
+ });
+ await page.route('**/api/roles/**', (route) => json(route, { name: 'USER', permissions: {} }));
+ await page.route('**/api/auth/2fa/setup', (route) =>
+ json(route, {
+ otpauthUrl: 'otpauth://totp/LibreChat:user@example.com?secret=ABC123&issuer=LibreChat',
+ backupCodes: ['backup01', 'backup02'],
+ }),
+ );
+ await page.route('**/api/auth/2fa/setup/confirm', (route) =>
+ json(route, {
+ backupCodes: ['confirmed-backup01', 'confirmed-backup02'],
+ acknowledgementToken: 'acknowledgement-token',
+ }),
+ );
+ await page.route('**/api/auth/2fa/setup/acknowledge', (route) =>
+ json(route, { finalizationToken: 'finalization-token' }),
+ );
+ await page.route('**/api/auth/2fa/setup/finalize', async (route) => {
+ finalized = true;
+ await json(route, { token: authToken, user: enrolledUser });
+ });
+
+ await page.goto(`/login?redirect_to=${encodeURIComponent(deepLink)}`);
+ await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
+ await page.getByRole('textbox', { name: 'Password' }).fill('password');
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ await page.getByRole('button', { name: 'Generate QR Code' }).click();
+ await expect(page.getByRole('img', { name: 'Scan QR Code' })).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByLabel('Enter your 2FA code to continue').fill('123456');
+ await page.getByRole('button', { name: 'Verify' }).click();
+
+ const completeButton = page.getByRole('button', { name: 'Complete Setup' });
+ await expect(completeButton).toBeDisabled();
+ await page.getByRole('button', { name: 'Download Backup Codes' }).click();
+ await expect(completeButton).toBeEnabled();
+ const enrollmentDestination = page.waitForURL(deepLinkPattern);
+ await completeButton.click();
+ await enrollmentDestination;
+ /** The authenticated shell mounts and settles here rather than bouncing back to /login. */
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+ await expect(
+ page.locator('.message-render').filter({ hasText: transcriptMarker }),
+ ).toBeVisible();
+ /** Loading a conversation canonicalizes its URL after the complete destination is delivered. */
+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
+ });
+
+ test('an expired setup credential returns the user to sign in @scenario:required-2fa-expired-credential-returns-to-signin', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await page.addInitScript(([key, value]) => window.sessionStorage.setItem(key, value), [
+ SETUP_TOKEN_STORAGE_KEY,
+ 'spent-setup-token',
+ ] as const);
+ await page.route('**/api/auth/2fa/setup', (route) =>
+ json(route, { message: 'Invalid or expired two-factor setup token' }, 401),
+ );
+
+ await page.goto('/login/2fa/setup');
+ await page.getByRole('button', { name: 'Generate QR Code' }).click();
+
+ /** The screen retires itself rather than replaying a credential the server can never accept. */
+ await expect(page).toHaveURL(LOGIN_ROUTE_PATTERN);
+ expect(
+ await page.evaluate((key) => window.sessionStorage.getItem(key), SETUP_TOKEN_STORAGE_KEY),
+ ).toBeNull();
+ await expect(page.getByRole('textbox', { name: 'Email' })).toBeVisible();
+ });
+});
+
+test.describe('required two-factor enrollment · authenticated arrival', () => {
+ test('an enforcement 403 moves a loaded app into setup without a reload @scenario:required-2fa-enforcement-403-redirects-loaded-app', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await page.route('**/api/convos**', (route) => json(route, ENFORCEMENT_PAYLOAD, 403));
+ /** Under enforcement the refresh endpoint hands off to setup as well, so the hard navigation
+ * that follows the redirect cannot silently refresh its way back into the app. */
+ await page.route('**/api/auth/refresh', (route) => json(route, ENFORCEMENT_PAYLOAD));
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+
+ await expect(page).toHaveURL(SETUP_URL_PATTERN, { timeout: 15000 });
+ expect(
+ await page.evaluate((key) => window.sessionStorage.getItem(key), SETUP_TOKEN_STORAGE_KEY),
+ ).toBe('scenario-setup-token');
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ });
+
+ test('a tab still moves into setup after a sibling tab started its hand-off @scenario:required-2fa-sibling-tab-hands-off-setup', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ let releaseEnforcement!: () => void;
+ const enforcementReleased = new Promise((resolve) => {
+ releaseEnforcement = resolve;
+ });
+ /** Held until the sibling tab's navigation marker is in the shared storage. */
+ await page.route('**/api/convos**', async (route) => {
+ await enforcementReleased;
+ await json(route, ENFORCEMENT_PAYLOAD, 403);
+ });
+ await page.route('**/api/auth/refresh', (route) => json(route, ENFORCEMENT_PAYLOAD));
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ await page.evaluate(() =>
+ window.localStorage.setItem('librechat.auth.redirect.startedAt', String(Date.now())),
+ );
+ releaseEnforcement();
+
+ await expect(page).toHaveURL(SETUP_URL_PATTERN, { timeout: 15000 });
+ expect(
+ await page.evaluate((key) => window.sessionStorage.getItem(key), SETUP_TOKEN_STORAGE_KEY),
+ ).toBe('scenario-setup-token');
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ });
+
+ test('a refresh hand-off moves a loaded app into setup @scenario:required-2fa-refresh-response-hands-off-setup', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ /** A 401 on a protected query is what drives the client into its refresh-recovery path. */
+ await page.route('**/api/convos**', (route) => json(route, { message: 'Unauthorized' }, 401));
+ await page.route('**/api/auth/refresh', (route) => json(route, ENFORCEMENT_PAYLOAD));
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+
+ await expect(page).toHaveURL(SETUP_URL_PATTERN, { timeout: 15000 });
+ expect(
+ await page.evaluate((key) => window.sessionStorage.getItem(key), SETUP_TOKEN_STORAGE_KEY),
+ ).toBe('scenario-setup-token');
+ await expect(page.getByRole('button', { name: 'Generate QR Code' })).toBeVisible();
+ });
+
+ test('the Disable 2FA control stays visible and locked with its reason @scenario:required-2fa-disable-control-locked', async ({
+ page,
+ isMobile,
+ }, testInfo) => {
+ test.setTimeout(60000);
+ await page.route('**/api/config', async (route) => {
+ const response = await route.fetch();
+ const config = (await response.json()) as TStartupConfig;
+ config.twoFactorAuthenticationRequired = true;
+ await route.fulfill({ response, json: config });
+ });
+ await page.route('**/api/user', async (route) => {
+ const response = await route.fetch();
+ const user = (await response.json()) as { twoFactorEnabled?: boolean };
+ user.twoFactorEnabled = true;
+ await route.fulfill({ response, json: user });
+ });
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ if (isMobile) {
+ await page.getByRole('button', { name: 'Open sidebar' }).click();
+ }
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menuitem', { name: 'Settings' }).click();
+ await page.getByRole('tab', { name: 'Account' }).click();
+
+ const disableButton = page.getByRole('button', { name: 'Disable 2FA' });
+ const tooltipTrigger = page.getByTestId('required-2fa-disable-control');
+ await expect(disableButton).toBeVisible();
+ await expect(disableButton).toBeDisabled();
+
+ /** The reason reaches keyboard users, not just pointer users. */
+ for (let tabCount = 0; tabCount < 20; tabCount++) {
+ await page.keyboard.press('Tab');
+ if (await tooltipTrigger.evaluate((element) => document.activeElement === element)) {
+ break;
+ }
+ }
+ await expect(tooltipTrigger).toBeFocused();
+ await expect(page.getByRole('tooltip')).toHaveText('Required by administrator');
+ await testInfo.attach('required-two-factor-disable-control', {
+ body: await page.screenshot(),
+ contentType: 'image/png',
+ });
+ });
+});
diff --git a/e2e/specs/mock/two-factor-required.spec.ts b/e2e/specs/mock/two-factor-required.spec.ts
new file mode 100644
index 0000000000..e376a7637e
--- /dev/null
+++ b/e2e/specs/mock/two-factor-required.spec.ts
@@ -0,0 +1,129 @@
+import { expect, test } from '@playwright/test';
+import type { Route } from '@playwright/test';
+
+/** A non-default destination: reaching it proves the deep link outlived the whole enrollment. */
+const DEEP_LINK = '/c/redirect-lifecycle-proof?model=test';
+const DEEP_LINK_PATTERN = /\/c\/redirect-lifecycle-proof\?model=test$/;
+/** No query string: the setup credential is handed over out of band, never through the URL. */
+const SETUP_ROUTE_PATTERN = /\/login\/2fa\/setup$/;
+
+const ENROLLED_USER = {
+ id: 'user-1',
+ _id: 'user-1',
+ name: 'Two Factor User',
+ username: 'twofactor',
+ email: 'user@example.com',
+ provider: 'local',
+ role: 'USER',
+ emailVerified: true,
+ twoFactorEnabled: true,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+};
+
+const json = (route: Route, body: unknown, status = 200) =>
+ route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
+
+/** The PWA service worker serves API GETs itself, which would bypass every `page.route` below. */
+test.use({ storageState: { cookies: [], origins: [] }, serviceWorkers: 'block' });
+
+test.describe('required two-factor enrollment', () => {
+ test('completes setup after backup acknowledgement and holds the deep link', async ({ page }) => {
+ test.setTimeout(60000);
+ /** Flips only once finalization has promoted the enrollment and minted the session. */
+ let finalized = false;
+
+ await page.route('**/api/auth/login', (route) =>
+ json(route, { twoFAPending: true, twoFASetupRequired: true, tempToken: 'setup-token' }),
+ );
+ /** Before finalization the user holds no refresh session, exactly as the server leaves them
+ * after a required-enrollment login; afterwards the promoted session refreshes normally. */
+ await page.route('**/api/auth/refresh', async (route) => {
+ if (!finalized) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'text/html; charset=utf-8',
+ body: 'Refresh token not provided',
+ });
+ return;
+ }
+ await json(route, { token: 'auth-token', user: ENROLLED_USER });
+ });
+ await page.route('**/api/user', async (route) => {
+ if (!finalized) {
+ await json(route, { message: 'Unauthorized' }, 401);
+ return;
+ }
+ await json(route, ENROLLED_USER);
+ });
+ await page.route('**/api/roles/**', (route) => json(route, { name: 'USER', permissions: {} }));
+ await page.route('**/api/auth/2fa/setup', (route) =>
+ json(route, {
+ otpauthUrl: 'otpauth://totp/LibreChat:user@example.com?secret=ABC123&issuer=LibreChat',
+ backupCodes: ['backup01', 'backup02'],
+ }),
+ );
+ await page.route('**/api/auth/2fa/setup/confirm', (route) =>
+ json(route, {
+ backupCodes: ['confirmed-backup01', 'confirmed-backup02'],
+ acknowledgementToken: 'acknowledgement-token',
+ }),
+ );
+ await page.route('**/api/auth/2fa/setup/acknowledge', async (route) => {
+ expect(route.request().postDataJSON()).toEqual({
+ acknowledgementToken: 'acknowledgement-token',
+ });
+ await json(route, { finalizationToken: 'finalization-token' });
+ });
+ await page.route('**/api/auth/2fa/setup/finalize', async (route) => {
+ expect(route.request().postDataJSON()).toEqual({ finalizationToken: 'finalization-token' });
+ finalized = true;
+ await json(route, { token: 'auth-token', user: ENROLLED_USER });
+ });
+
+ await page.goto(`/login?redirect_to=${encodeURIComponent(DEEP_LINK)}`);
+ await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
+ await page.getByRole('textbox', { name: 'Password' }).fill('password');
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ expect(await page.evaluate(() => window.sessionStorage.getItem('two_factor_setup_token'))).toBe(
+ 'setup-token',
+ );
+ await page.reload();
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ const generateButton = page.getByRole('button', { name: 'Generate QR Code' });
+ const setupCardBox = await generateButton.locator('..').boundingBox();
+ expect(setupCardBox?.width).toBeGreaterThanOrEqual(430);
+ await generateButton.click();
+
+ await expect(page.getByRole('img', { name: 'Scan QR Code' })).toBeVisible();
+ await expect(page.getByLabel('Secret Key')).toHaveValue('ABC123');
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByLabel('Enter your 2FA code to continue').fill('123456');
+ await page.getByRole('button', { name: 'Verify' }).click();
+
+ const completeButton = page.getByRole('button', { name: 'Complete Setup' });
+ await expect(page).toHaveURL(SETUP_ROUTE_PATTERN);
+ await expect(completeButton).toBeDisabled();
+ const downloadPromise = page.waitForEvent('download');
+ await page.getByRole('button', { name: 'Download Backup Codes' }).click();
+ const download = await downloadPromise;
+ expect(download.suggestedFilename()).toBe('backup-codes.txt');
+ await expect(completeButton).toBeEnabled();
+ await completeButton.click();
+
+ await expect(page).toHaveURL(DEEP_LINK_PATTERN);
+ /** The authenticated shell mounts and settles here rather than bouncing back to /login. */
+ await expect(page.getByTestId('nav-user')).toBeVisible();
+ /** A fixed window is the point: the destination must survive the follow-up auth traffic. */
+ await page.waitForTimeout(3000);
+ await expect(page).toHaveURL(DEEP_LINK_PATTERN);
+
+ /** A reload now authenticates through the refreshed session and stays on the deep link. */
+ await page.reload();
+ await expect(page.getByTestId('nav-user')).toBeVisible();
+ await page.waitForTimeout(3000);
+ await expect(page).toHaveURL(DEEP_LINK_PATTERN);
+ });
+});
diff --git a/e2e/specs/mock/two-factor.spec.ts b/e2e/specs/mock/two-factor.spec.ts
index 40da3dba61..c8a1f2a208 100644
--- a/e2e/specs/mock/two-factor.spec.ts
+++ b/e2e/specs/mock/two-factor.spec.ts
@@ -1,4 +1,5 @@
import { expect, test } from '@playwright/test';
+import type { TStartupConfig } from 'librechat-data-provider';
import { NEW_CHAT_PATH } from './helpers';
/**
@@ -86,4 +87,47 @@ test.describe('account settings · two-factor dialog', () => {
`framer-motion threw while rendering the 2FA dialog: ${framerErrors.join(' | ')}`,
).toEqual([]);
});
+
+ test('explains why an administrator-required 2FA control cannot be disabled', async ({
+ page,
+ }) => {
+ await page.route('**/api/config', async (route) => {
+ const response = await route.fetch();
+ const config = (await response.json()) as TStartupConfig;
+ config.twoFactorAuthenticationRequired = true;
+ await route.fulfill({ response, json: config });
+ });
+ await page.route('**/api/user', async (route) => {
+ const response = await route.fetch();
+ const user = (await response.json()) as { twoFactorEnabled?: boolean };
+ user.twoFactorEnabled = true;
+ await route.fulfill({ response, json: user });
+ });
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menuitem', { name: 'Settings' }).click();
+ await page.getByRole('tab', { name: 'Account' }).click();
+
+ const disableButton = page.getByRole('button', { name: 'Disable 2FA' });
+ const tooltipTrigger = page.getByTestId('required-2fa-disable-control');
+
+ await expect(disableButton).toBeDisabled();
+ await expect(tooltipTrigger).toHaveCSS('cursor', 'not-allowed');
+
+ for (let tabCount = 0; tabCount < 20; tabCount++) {
+ await page.keyboard.press('Tab');
+ if (await tooltipTrigger.evaluate((element) => document.activeElement === element)) {
+ break;
+ }
+ }
+ await expect(tooltipTrigger).toBeFocused();
+ await expect(page.getByRole('tooltip')).toHaveText('Required by administrator');
+
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('tooltip')).toBeHidden();
+ await page.mouse.move(0, 0);
+ await tooltipTrigger.hover();
+ await expect(page.getByRole('tooltip')).toHaveText('Required by administrator');
+ });
});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 07cbcd1899..072fbfc2d3 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -1198,7 +1198,7 @@
},
"client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/QRPhase.tsx": {
"shadcn/no-restyle": {
- "count": 4
+ "count": 3
}
},
"client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/VerifyPhase.tsx": {
diff --git a/packages/api/src/apiKeys/middleware.auth.spec.ts b/packages/api/src/apiKeys/middleware.auth.spec.ts
index e78e94ed5c..787007cf61 100644
--- a/packages/api/src/apiKeys/middleware.auth.spec.ts
+++ b/packages/api/src/apiKeys/middleware.auth.spec.ts
@@ -1,4 +1,5 @@
import { Types } from 'mongoose';
+import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from 'librechat-data-provider';
import type { NextFunction, Response } from 'express';
import type { ApiKeyAuthRequest } from './middleware';
import { createRequireApiKeyAuth } from './middleware';
@@ -68,6 +69,57 @@ describe('remote Agent API key authentication', () => {
expect(next).toHaveBeenCalledWith();
});
+ describe('under required two-factor enforcement', () => {
+ const original = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION;
+ beforeEach(() => {
+ process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true';
+ });
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION;
+ } else {
+ process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = original;
+ }
+ });
+
+ const authenticate = async (owner: Record) => {
+ const userId = new Types.ObjectId();
+ const middleware = createRequireApiKeyAuth({
+ validateAgentApiKey: jest.fn().mockResolvedValue({ userId, keyId: new Types.ObjectId() }),
+ findUser: jest.fn().mockResolvedValue({ _id: userId, ...owner }),
+ isPrincipalActive: jest.fn().mockResolvedValue(true),
+ });
+ const req = createRequest();
+ const response = createResponse();
+ const next = jest.fn() as NextFunction;
+ await middleware(req, response.res, next);
+ return { req, next, ...response };
+ };
+
+ it('refuses a key whose local owner has not enrolled', async () => {
+ const { req, next, status, json } = await authenticate({ provider: 'local' });
+
+ expect(status).toHaveBeenCalledWith(403);
+ expect(json).toHaveBeenCalledWith({
+ error: expect.objectContaining({ code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE }),
+ });
+ expect(req.user).toBeUndefined();
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('admits a key whose owner has enrolled', async () => {
+ const { next } = await authenticate({ provider: 'local', twoFactorEnabled: true });
+
+ expect(next).toHaveBeenCalledWith();
+ });
+
+ it('admits a key whose owner signs in through a federated provider', async () => {
+ const { next } = await authenticate({ provider: 'openid' });
+
+ expect(next).toHaveBeenCalledWith();
+ });
+ });
+
it('starts the user and deletion-fence reads together', async () => {
const userId = new Types.ObjectId();
let resolveUser!: (user: { _id: Types.ObjectId }) => void;
diff --git a/packages/api/src/apiKeys/middleware.ts b/packages/api/src/apiKeys/middleware.ts
index f18c693bf6..ba6082726b 100644
--- a/packages/api/src/apiKeys/middleware.ts
+++ b/packages/api/src/apiKeys/middleware.ts
@@ -1,8 +1,14 @@
import { logger } from '@librechat/data-schemas';
-import { ResourceType, PermissionBits, hasPermissions } from 'librechat-data-provider';
+import {
+ ResourceType,
+ PermissionBits,
+ hasPermissions,
+ TWO_FACTOR_ENROLLMENT_REQUIRED_CODE,
+} from 'librechat-data-provider';
import type { Request, Response, NextFunction, RequestHandler } from 'express';
import type { IUser } from '@librechat/data-schemas';
import type { Types } from 'mongoose';
+import { isTwoFactorEnrollmentRequired } from '~/auth/twoFactor';
import { getRemoteAgentPermissions } from './service';
export interface ApiKeyAuthDependencies {
@@ -12,6 +18,7 @@ export interface ApiKeyAuthDependencies {
} | null>;
findUser: (query: { _id: string | Types.ObjectId }) => Promise;
isPrincipalActive: (userId: string) => Promise;
+ enrollmentRequired?: typeof isTwoFactorEnrollmentRequired;
}
export interface RemoteAgentAccessDependencies {
@@ -107,6 +114,16 @@ export function createRequireApiKeyAuth(deps: ApiKeyAuthDependencies) {
},
});
}
+ /** A key outlives the enforcement switch, so it waits on enrollment like the owner's session. */
+ if ((deps.enrollmentRequired ?? isTwoFactorEnrollmentRequired)(user)) {
+ return res.status(403).json({
+ error: {
+ message: 'Two-factor authentication must be enabled for this account',
+ type: 'permission_error',
+ code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE,
+ },
+ });
+ }
req.user = user as IUser & { id: string };
req.apiKeyId = keyValidation.keyId;
diff --git a/packages/api/src/auth/enrollment.ts b/packages/api/src/auth/enrollment.ts
new file mode 100644
index 0000000000..78c0fb74e1
--- /dev/null
+++ b/packages/api/src/auth/enrollment.ts
@@ -0,0 +1,251 @@
+import { logger } from '@librechat/data-schemas';
+import { TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE } from 'librechat-data-provider';
+import type { TwoFactorEnrollmentUpdate } from '@librechat/data-schemas';
+import type { Request, Response } from 'express';
+import type { TwoFactorEnrollmentDependencies, StoredTwoFactorAccount } from './twoFactor';
+import type { UserDocumentId } from '~/auth/verification';
+import {
+ TOKEN_RETIREMENT_FIELDS,
+ acknowledgeTwoFactorSetup,
+ confirmTwoFactorSetup,
+ finalizeTwoFactorSetup,
+ generateTwoFactorSetupAcknowledgementToken,
+ generateTwoFactorSetupFinalizationToken,
+ isCredentialLoginBlockedByTwoFactorPolicy,
+ isEnrollmentSupersededByRecovery,
+ isTokenRetired,
+ recheckMintedCredential,
+ withdrawMintedSession,
+ verifyTwoFactorLoginChallengeToken,
+} from './twoFactor';
+import { sanitizeUserForResponse } from './user';
+import { clearCloudFrontCookies } from '~/cdn';
+
+type LoginChallengeBody = { tempToken?: string; token?: string; backupCode?: string };
+type SetupBody = { token?: string };
+type ChallengeRequest = Request, object, LoginChallengeBody>;
+type SetupRequest = Request, object, SetupBody> & {
+ user?: { id: string };
+ twoFactorEnrollmentNonce?: string;
+};
+
+export function clearEnrollmentNonces(
+ update: TwoFactorEnrollmentUpdate,
+): TwoFactorEnrollmentUpdate {
+ return {
+ ...update,
+ twoFactorAcknowledgementNonceHash: null,
+ twoFactorFinalizationNonceHash: null,
+ };
+}
+
+export interface EnrollmentControllerDependencies
+ extends Omit {
+ getUserById: (userId: string, projection: string) => Promise;
+ getTOTPSecret: (storedSecret: string | null | undefined) => Promise;
+ verifyTOTP: (secret: string | null, token: string) => Promise;
+ verifyBackupCode: (input: {
+ user: StoredTwoFactorAccount;
+ backupCode: string;
+ }) => Promise;
+ deleteAllUserSessions: (input: { userId: string }) => Promise