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: Strengthen Two-Factor Recovery Credentials (#16742)

Danny Avilab6b24741dae9
diff --git a/.env.example b/.env.example
index 0e771a7d94..4146dc3e5a 100644
--- a/.env.example
+++ b/.env.example
@@ -937,6 +937,15 @@ ALLOW_UNVERIFIED_EMAIL_LOGIN=true
# existing pre-authentication login limits, because they apply before request/tenant config is available.
ENFORCE_TWO_FACTOR_AUTHENTICATION=false
+# Strong recovery codes require matching backend and client versions. This process-wide
+# issuance gate defaults to legacy when unset, so upgrades do not strand older replicas/clients.
+# During a rolling upgrade, leave this unset or set legacy on every replica. After every
+# backend is upgraded and users reload the updated client, set strong on every replica.
+# Replacements issued in legacy mode retain the previous 32-bit strength. Switching to
+# strong does not rewrite existing codes; users must regenerate them. Do not roll back
+# to an older backend after strong codes have been issued without replacing those codes.
+TWO_FACTOR_BACKUP_CODE_FORMAT=strong
+
SESSION_EXPIRY=1000 * 60 * 15
REFRESH_TOKEN_EXPIRY=(1000 * 60 * 60 * 24) * 7
# Overrides the Secure attribute for session/auth cookies when set to true or false;
diff --git a/api/server/services/twoFactorService.js b/api/server/services/twoFactorService.js
index f70e00dc83..b2d4e2c83a 100644
--- a/api/server/services/twoFactorService.js
+++ b/api/server/services/twoFactorService.js
@@ -1,33 +1,16 @@
const { webcrypto, timingSafeEqual } = require('node:crypto');
-const { hashBackupCode, decryptV3, decryptV2 } = require('@librechat/data-schemas');
-const { generateTwoFactorLoginChallengeToken } = require('@librechat/api');
-const { updateUser } = require('~/models');
+const { decryptV3, decryptV2 } = require('@librechat/data-schemas');
+const {
+ generateTwoFactorLoginChallengeToken,
+ generateTOTPSecret,
+ createBackupCodeGenerator,
+ createBackupCodeVerifier,
+} = require('@librechat/api');
+const { consumeBackupCode } = require('~/models');
-// Base32 alphabet for TOTP secret encoding.
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
-
-/**
- * Encodes a Buffer into a Base32 string.
- * @param {Buffer} buffer
- * @returns {string}
- */
-const encodeBase32 = (buffer) => {
- let bits = 0;
- let value = 0;
- let output = '';
- for (const byte of buffer) {
- value = (value << 8) | byte;
- bits += 8;
- while (bits >= 5) {
- output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
- bits -= 5;
- }
- }
- if (bits > 0) {
- output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
- }
- return output;
-};
+const verifyBackupCode = createBackupCodeVerifier(consumeBackupCode);
+const generateBackupCodes = createBackupCodeGenerator(process.env.TWO_FACTOR_BACKUP_CODE_FORMAT);
/**
* Decodes a Base32 string into a Buffer.
@@ -54,16 +37,6 @@ const decodeBase32 = (base32Str) => {
return Buffer.from(output);
};
-/**
- * Generates a new TOTP secret (Base32 encoded).
- * @returns {string}
- */
-const generateTOTPSecret = () => {
- const randomArray = new Uint8Array(10);
- webcrypto.getRandomValues(randomArray);
- return encodeBase32(Buffer.from(randomArray));
-};
-
/**
* Generates a TOTP code based on the secret and time.
* Uses a 30-second time step and produces a 6-digit code.
@@ -146,74 +119,12 @@ const verifyTOTP = async (secret, token) => {
return false;
};
-/**
- * Generates backup codes (default count: 10).
- * Each code is an 8-character hexadecimal string and stored with its SHA-256 hash.
- * @param {number} [count=10]
- * @returns {Promise<{ plainCodes: string[], codeObjects: Array<{ codeHash: string, used: boolean, usedAt: Date | null }> }>}
- */
-const generateBackupCodes = async (count = 10) => {
- const plainCodes = [];
- const codeObjects = [];
- const encoder = new TextEncoder();
-
- for (let i = 0; i < count; i++) {
- const randomArray = new Uint8Array(4);
- webcrypto.getRandomValues(randomArray);
- const code = Array.from(randomArray)
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('');
- plainCodes.push(code);
-
- const codeBuffer = encoder.encode(code);
- const hashBuffer = await webcrypto.subtle.digest('SHA-256', codeBuffer);
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const codeHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
- codeObjects.push({ codeHash, used: false, usedAt: null });
- }
- return { plainCodes, codeObjects };
-};
-
-/**
- * Verifies a backup code and, if valid, marks it as used.
- * @param {Object} params
- * @param {Object} params.user
- * @param {string} params.backupCode
- * @param {boolean} [params.persist=true] - Whether to persist the used-mark to the database.
- * Pass `false` when the caller will immediately overwrite `backupCodes` (e.g. re-enrollment).
- * @returns {Promise<boolean>}
- */
-const verifyBackupCode = async ({ user, backupCode, persist = true }) => {
- if (!backupCode || !user || !Array.isArray(user.backupCodes)) {
- return false;
- }
-
- const hashedInput = await hashBackupCode(backupCode.trim());
- const matchingCode = user.backupCodes.find(
- (codeObj) => codeObj.codeHash === hashedInput && !codeObj.used,
- );
-
- if (!matchingCode) {
- return false;
- }
-
- if (persist) {
- const updatedBackupCodes = user.backupCodes.map((codeObj) =>
- codeObj.codeHash === hashedInput && !codeObj.used
- ? { ...codeObj, used: true, usedAt: new Date() }
- : codeObj,
- );
- await updateUser(user._id, { backupCodes: updatedBackupCodes });
- }
- return true;
-};
-
/**
* Verifies a user's identity via TOTP token or backup code.
* @param {Object} params
* @param {Object} params.user - The user document (must include totpSecret and backupCodes).
* @param {string} [params.token] - A 6-digit TOTP token.
- * @param {string} [params.backupCode] - An 8-character backup code.
+ * @param {string} [params.backupCode] - A recovery code (legacy or current format).
* @param {boolean} [params.persistBackupUse=true] - Whether to mark the backup code as used in the DB.
* @returns {Promise<{ verified: boolean, status?: number, message?: string }>}
*/
diff --git a/api/server/services/twoFactorService.spec.js b/api/server/services/twoFactorService.spec.js
index 81cd03d152..5d46e03765 100644
--- a/api/server/services/twoFactorService.spec.js
+++ b/api/server/services/twoFactorService.spec.js
@@ -14,11 +14,24 @@ jest.mock('@librechat/data-schemas', () => ({
decryptV2: jest.fn(),
}));
-jest.mock('~/models', () => ({ updateUser: jest.fn() }));
+jest.mock('~/models', () => ({ consumeBackupCode: jest.fn() }));
+
+jest.mock('@librechat/api', () => ({
+ generateTwoFactorLoginChallengeToken: jest.fn(),
+ ...jest.requireActual('../../../packages/api/src/auth/recovery'),
+}));
const { generateTOTP, verifyTOTP, generateTOTPSecret } = require('./twoFactorService');
describe('verifyTOTP', () => {
+ it('keeps existing 80-bit TOTP enrollments valid', async () => {
+ const secret = 'JBSWY3DPEHPK3PXP';
+ await expect(verifyTOTP(secret, await generateTOTP(secret))).resolves.toBe(true);
+ });
+
+ it('produces a 160-bit secret for new enrollments', () => {
+ expect(generateTOTPSecret()).toMatch(/^[A-Z2-7]{32}$/);
+ });
it('accepts a valid current TOTP code', async () => {
const secret = generateTOTPSecret();
const code = await generateTOTP(secret);
diff --git a/client/src/components/Auth/BackupCodeInput.tsx b/client/src/components/Auth/BackupCodeInput.tsx
new file mode 100644
index 0000000000..708b047fbd
--- /dev/null
+++ b/client/src/components/Auth/BackupCodeInput.tsx
@@ -0,0 +1,25 @@
+import { Input } from '@librechat/client';
+import { useLocalize } from '~/hooks';
+
+export const isBackupCode = (code: string): boolean =>
+ /^(?:[a-f0-9]{8}|[a-f0-9]{32})$/.test(code.trim());
+
+export default function BackupCodeInput({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ const localize = useLocalize();
+ return (
+ <Input
+ aria-label={localize('com_ui_backup_code_verification_required')}
+ value={value}
+ onChange={(event) => onChange(event.target.value.trim())}
+ autoComplete="one-time-code"
+ autoCapitalize="none"
+ spellCheck={false}
+ />
+ );
+}
diff --git a/client/src/components/Auth/TwoFactorScreen.tsx b/client/src/components/Auth/TwoFactorScreen.tsx
index ffb8772aad..32dd7929b2 100644
--- a/client/src/components/Auth/TwoFactorScreen.tsx
+++ b/client/src/components/Auth/TwoFactorScreen.tsx
@@ -1,9 +1,9 @@
import React, { useState, useCallback } from 'react';
+import { REGEXP_ONLY_DIGITS } from 'input-otp';
import { useSearchParams } from 'react-router-dom';
import { useToastContext } from '@librechat/client';
import { ErrorTypes } from 'librechat-data-provider';
import { useForm, Controller } from 'react-hook-form';
-import { REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';
import {
Label,
Button,
@@ -13,6 +13,7 @@ import {
InputOTPSeparator,
} from '@librechat/client';
import { useVerifyTwoFactorTempMutation } from '~/data-provider';
+import BackupCodeInput from './BackupCodeInput';
import { useLocalize } from '~/hooks';
interface VerifyPayload {
@@ -127,24 +128,7 @@ const TwoFactorScreen: React.FC = React.memo(() => {
name="backupCode"
control={control}
render={({ field: { onChange, value } }) => (
- <InputOTP
- maxLength={8}
- value={value != null ? value : ''}
- onChange={onChange}
- pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
- aria-label={localize('com_ui_backup_code_verification_required')}
- >
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- <InputOTPSlot index={6} />
- <InputOTPSlot index={7} />
- </InputOTPGroup>
- </InputOTP>
+ <BackupCodeInput value={value ?? ''} onChange={onChange} />
)}
/>
{errors.backupCode && (
diff --git a/client/src/components/Auth/__tests__/BackupCodeInput.spec.tsx b/client/src/components/Auth/__tests__/BackupCodeInput.spec.tsx
new file mode 100644
index 0000000000..35e4dff2c8
--- /dev/null
+++ b/client/src/components/Auth/__tests__/BackupCodeInput.spec.tsx
@@ -0,0 +1,60 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { DisablePhase } from '~/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase';
+import { BackupPhase } from '~/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase';
+import BackupCodeInput, { isBackupCode } from '../BackupCodeInput';
+
+jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
+
+describe('backup-code form validation', () => {
+ it('shows the complete long code in a wrapping single-column layout', () => {
+ const code = '0123456789abcdef0123456789abcdef';
+ const { container } = render(
+ <BackupPhase
+ backupCodes={[code]}
+ downloaded
+ onNext={jest.fn()}
+ onDownload={jest.fn()}
+ onError={jest.fn()}
+ />,
+ );
+ expect(screen.getByText(code)).toHaveClass('break-all', 'min-w-0');
+ expect(container.querySelector('.grid')).toHaveClass('grid-cols-1');
+ });
+ it('does not truncate whitespace-padded input before normalization', () => {
+ const onChange = jest.fn();
+ render(<BackupCodeInput value="" onChange={onChange} />);
+ const input = screen.getByRole('textbox');
+ expect(input).not.toHaveAttribute('maxlength');
+ fireEvent.change(input, { target: { value: ' 0123456789abcdef0123456789abcdef\n' } });
+ expect(onChange).toHaveBeenCalledWith('0123456789abcdef0123456789abcdef');
+ });
+ it.each(['deadbeef', '0123456789abcdef0123456789abcdef'])(
+ 'allows disabling 2FA with either backup-code format: %s',
+ (code) => {
+ const onDisable = jest.fn();
+ render(<DisablePhase onDisable={onDisable} isDisabling={false} />);
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_use_backup_code' }));
+ const submit = screen.getByRole('button', { name: 'com_ui_2fa_disable' });
+ expect(submit).toBeDisabled();
+ fireEvent.change(
+ screen.getByRole('textbox', { name: 'com_ui_backup_code_verification_required' }),
+ { target: { value: code } },
+ );
+ expect(submit).toBeEnabled();
+ fireEvent.click(submit);
+ expect(onDisable).toHaveBeenCalledWith(code, true);
+ },
+ );
+ it.each(['deadbeef', '0123456789abcdef0123456789abcdef', ' deadbeef '])(
+ 'accepts legacy and current codes: %s',
+ (code) => {
+ expect(isBackupCode(code)).toBe(true);
+ },
+ );
+ it.each(['', 'deadbee', 'deadbeef0', 'a'.repeat(31), 'a'.repeat(33), 'g'.repeat(32)])(
+ 'rejects incomplete and malformed codes: %s',
+ (code) => {
+ expect(isBackupCode(code)).toBe(false);
+ },
+ );
+});
diff --git a/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx
index 215df2ced8..98cbd2aa17 100644
--- a/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx
+++ b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx
@@ -1,9 +1,10 @@
import { MemoryRouter } from 'react-router-dom';
-import { act, render } from '@testing-library/react';
import { ErrorTypes } from 'librechat-data-provider';
+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';
import TwoFactorScreen from '../TwoFactorScreen';
const mockShowToast = jest.fn();
+const mockVerify = jest.fn();
let mockVerifyOptions: { onError: (error: unknown) => void } | undefined;
jest.mock('@librechat/client', () => ({
@@ -18,7 +19,7 @@ jest.mock('~/hooks', () => ({
jest.mock('~/data-provider', () => ({
useVerifyTwoFactorTempMutation: (options: { onError: (error: unknown) => void }) => {
mockVerifyOptions = options;
- return { mutate: jest.fn() };
+ return { mutate: mockVerify };
},
}));
@@ -36,6 +37,23 @@ describe('TwoFactorScreen verification errors', () => {
mockVerifyOptions = undefined;
});
+ it.each(['deadbeef', '0123456789abcdef0123456789abcdef'])(
+ 'submits the full legacy or new backup code: %s',
+ async (code) => {
+ renderScreen();
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_use_backup_code' }));
+ const input = screen.getByRole('textbox', {
+ name: 'com_ui_backup_code_verification_required',
+ });
+ expect(input).not.toHaveAttribute('maxlength');
+ fireEvent.change(input, { target: { value: code } });
+ fireEvent.click(screen.getByTestId('login-button'));
+ await waitFor(() =>
+ expect(mockVerify).toHaveBeenCalledWith({ tempToken: 'temp-token', backupCode: code }),
+ );
+ },
+ );
+
it('shows a localized message when the server rejects a cross-origin submission', () => {
renderScreen();
diff --git a/client/src/components/Nav/SettingsTabs/Account/BackupCodesItem.tsx b/client/src/components/Nav/SettingsTabs/Account/BackupCodesItem.tsx
index 7bc78c4db2..564d40c814 100644
--- a/client/src/components/Nav/SettingsTabs/Account/BackupCodesItem.tsx
+++ b/client/src/components/Nav/SettingsTabs/Account/BackupCodesItem.tsx
@@ -1,8 +1,8 @@
import React, { useState } from 'react';
import { RefreshCcw } from 'lucide-react';
import { useSetRecoilState } from 'recoil';
+import { REGEXP_ONLY_DIGITS } from 'input-otp';
import { motion, AnimatePresence } from 'framer-motion';
-import { REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';
import {
InputOTPSeparator,
InputOTPGroup,
@@ -24,6 +24,7 @@ import type {
TBackupCode,
TUser,
} from 'librechat-data-provider';
+import BackupCodeInput, { isBackupCode } from '~/components/Auth/BackupCodeInput';
import { useRegenerateBackupCodesMutation } from '~/data-provider';
import { useAuthContext, useLocalize } from '~/hooks';
import { useTwoFactorError } from './errors';
@@ -79,7 +80,7 @@ const BackupCodesItem: React.FC = () => {
fetchBackupCodes(false);
};
- const otpReady = !needs2FA || otpToken.length === (useBackup ? 8 : 6);
+ const otpReady = !needs2FA || (useBackup ? isBackupCode(otpToken) : otpToken.length === 6);
return (
<OGDialog open={isDialogOpen} onOpenChange={setDialogOpen}>
@@ -213,25 +214,16 @@ const BackupCodesItem: React.FC = () => {
{localize('com_ui_2fa_verification_required')}
</Label>
<div className="flex justify-center">
- <InputOTP
- value={otpToken}
- onChange={setOtpToken}
- maxLength={useBackup ? 8 : 6}
- pattern={useBackup ? REGEXP_ONLY_DIGITS_AND_CHARS : REGEXP_ONLY_DIGITS}
- className="gap-2"
- >
- {useBackup ? (
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- <InputOTPSlot index={6} />
- <InputOTPSlot index={7} />
- </InputOTPGroup>
- ) : (
+ {useBackup ? (
+ <BackupCodeInput value={otpToken} onChange={setOtpToken} />
+ ) : (
+ <InputOTP
+ value={otpToken}
+ onChange={setOtpToken}
+ maxLength={6}
+ pattern={REGEXP_ONLY_DIGITS}
+ className="gap-2"
+ >
<>
<InputOTPGroup>
<InputOTPSlot index={0} />
@@ -245,8 +237,8 @@ const BackupCodesItem: React.FC = () => {
<InputOTPSlot index={5} />
</InputOTPGroup>
</>
- )}
- </InputOTP>
+ </InputOTP>
+ )}
</div>
<Button
type="button"
diff --git a/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx b/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx
index 6eadb74f1d..c92ee79d39 100644
--- a/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx
+++ b/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx
@@ -1,6 +1,6 @@
import React, { useState, useCallback } from 'react';
import { LockIcon, Trash } from 'lucide-react';
-import { REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';
+import { REGEXP_ONLY_DIGITS } from 'input-otp';
import {
InputOTPSeparator,
OGDialogContent,
@@ -17,6 +17,7 @@ import {
Input,
} from '@librechat/client';
import type { TDeleteUserRequest } from 'librechat-data-provider';
+import BackupCodeInput, { isBackupCode } from '~/components/Auth/BackupCodeInput';
import { useDeleteUserMutation } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
import { LocalizeFunction } from '~/common';
@@ -59,7 +60,7 @@ const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolea
[user?.email],
);
- const otpReady = !needs2FA || otpToken.length === (useBackup ? 8 : 6);
+ const otpReady = !needs2FA || (useBackup ? isBackupCode(otpToken) : otpToken.length === 6);
return (
<>
@@ -79,12 +80,12 @@ const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolea
</div>
<OGDialogContent className="w-11/12 max-w-md">
<OGDialogHeader>
- <OGDialogTitle className="text-lg font-medium leading-6">
+ <OGDialogTitle className="text-lg leading-6 font-medium">
{localize('com_nav_delete_account_confirm')}
</OGDialogTitle>
</OGDialogHeader>
- <div className="mb-8 text-sm text-text-primary">
- <ul className="font-semibold text-text-warning">
+ <div className="text-text-primary mb-8 text-sm">
+ <ul className="text-text-warning font-semibold">
<li>{localize('com_nav_delete_warning')}</li>
<li>{localize('com_nav_delete_data_info')}</li>
</ul>
@@ -104,25 +105,16 @@ const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolea
{localize('com_ui_2fa_verification_required')}
</Label>
<div className="flex justify-center">
- <InputOTP
- value={otpToken}
- onChange={setOtpToken}
- maxLength={useBackup ? 8 : 6}
- pattern={useBackup ? REGEXP_ONLY_DIGITS_AND_CHARS : REGEXP_ONLY_DIGITS}
- className="gap-2"
- >
- {useBackup ? (
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- <InputOTPSlot index={6} />
- <InputOTPSlot index={7} />
- </InputOTPGroup>
- ) : (
+ {useBackup ? (
+ <BackupCodeInput value={otpToken} onChange={setOtpToken} />
+ ) : (
+ <InputOTP
+ value={otpToken}
+ onChange={setOtpToken}
+ maxLength={6}
+ pattern={REGEXP_ONLY_DIGITS}
+ className="gap-2"
+ >
<>
<InputOTPGroup>
<InputOTPSlot index={0} />
@@ -136,8 +128,8 @@ const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolea
<InputOTPSlot index={5} />
</InputOTPGroup>
</>
- )}
- </InputOTP>
+ </InputOTP>
+ )}
</div>
<Button
type="button"
@@ -146,7 +138,7 @@ const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolea
setUseBackup(!useBackup);
setOtpToken('');
}}
- className="h-auto p-0 text-sm font-normal text-text-primary hover:underline"
+ className="text-text-primary h-auto p-0 text-sm font-normal hover:underline"
>
{useBackup ? localize('com_ui_use_2fa_code') : localize('com_ui_use_backup_code')}
</Button>
@@ -183,7 +175,7 @@ const renderDeleteButton = (
<Button
variant="destructive"
className={cn(
- 'mt-4 w-full gap-0 bg-surface-tertiary text-text-primary transition-all duration-200 hover:bg-surface-tertiary',
+ 'bg-surface-tertiary text-text-primary hover:bg-surface-tertiary mt-4 w-full gap-0 transition-all duration-200',
isLocked
? 'cursor-not-allowed opacity-30 disabled:opacity-30'
: 'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover disabled:opacity-100',
diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx
index 82c3df65d4..7d5ed7225c 100644
--- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx
+++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx
@@ -34,18 +34,18 @@ export const BackupPhase: React.FC<BackupPhaseProps> = ({
<p className="text-text-primary text-sm break-keep">
{localize('com_ui_download_backup_tooltip')}
</p>
- <div className="bg-surface-secondary grid grid-cols-2 gap-4 rounded-xl p-6">
+ <div className="bg-surface-secondary grid grid-cols-1 gap-4 rounded-xl p-4">
{backupCodes.map((code, index) => (
<motion.div
key={code}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
- className="bg-surface-tertiary rounded-lg p-3"
+ className="bg-surface-tertiary min-w-0 rounded-lg p-3"
>
- <div className="flex items-center justify-between">
- <span className="text-text-primary hidden text-sm sm:inline">#{index + 1}</span>
- <span className="text-text-primary font-mono text-lg">{code}</span>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-text-primary shrink-0 text-sm">#{index + 1}</span>
+ <span className="text-text-primary min-w-0 font-mono text-sm break-all">{code}</span>
</div>
</motion.div>
))}
diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx
index 277e692d40..c1acda7926 100644
--- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx
+++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx
@@ -1,6 +1,6 @@
import React, { useState } from 'react';
import { motion } from 'framer-motion';
-import { REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';
+import { REGEXP_ONLY_DIGITS } from 'input-otp';
import {
Button,
InputOTP,
@@ -9,6 +9,7 @@ import {
InputOTPSeparator,
Spinner,
} from '@librechat/client';
+import BackupCodeInput, { isBackupCode } from '~/components/Auth/BackupCodeInput';
import { useLocalize } from '~/hooks';
const fadeAnimation = {
@@ -33,28 +34,17 @@ export const DisablePhase: React.FC<DisablePhaseProps> = ({ onDisable, isDisabli
return (
<motion.div {...fadeAnimation} className="text-text-primary space-y-8">
<div className="flex justify-center">
- <InputOTP
- aria-label={localize(
- useBackup ? 'com_ui_use_backup_code' : 'com_ui_2fa_verification_required',
- )}
- value={token}
- onChange={setToken}
- maxLength={useBackup ? 8 : 6}
- pattern={useBackup ? REGEXP_ONLY_DIGITS_AND_CHARS : REGEXP_ONLY_DIGITS}
- className="gap-2"
- >
- {useBackup ? (
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- <InputOTPSlot index={6} />
- <InputOTPSlot index={7} />
- </InputOTPGroup>
- ) : (
+ {useBackup ? (
+ <BackupCodeInput value={token} onChange={setToken} />
+ ) : (
+ <InputOTP
+ aria-label={localize('com_ui_2fa_verification_required')}
+ value={token}
+ onChange={setToken}
+ maxLength={6}
+ pattern={REGEXP_ONLY_DIGITS}
+ className="gap-2"
+ >
<>
<InputOTPGroup>
<InputOTPSlot index={0} />
@@ -68,13 +58,13 @@ export const DisablePhase: React.FC<DisablePhaseProps> = ({ onDisable, isDisabli
<InputOTPSlot index={5} />
</InputOTPGroup>
</>
- )}
- </InputOTP>
+ </InputOTP>
+ )}
</div>
<Button
variant="destructive"
onClick={() => onDisable(token, useBackup)}
- disabled={isDisabling || token.length !== (useBackup ? 8 : 6)}
+ disabled={isDisabling || !(useBackup ? isBackupCode(token) : token.length === 6)}
className="w-full rounded-xl px-6 py-3 transition-all disabled:opacity-50"
>
{isDisabling && <Spinner className="mr-2" />}
diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.ts
index 97ec41de69..3c57d149a3 100644
--- a/packages/api/src/auth/index.ts
+++ b/packages/api/src/auth/index.ts
@@ -7,6 +7,7 @@ export * from './refresh';
export * from './googleRefresh';
export * from './agent';
export * from './password';
+export * from './recovery';
export * from './passkey';
export * from './passkey/handlers';
export * from './credentials';
diff --git a/packages/api/src/auth/recovery.spec.ts b/packages/api/src/auth/recovery.spec.ts
new file mode 100644
index 0000000000..23e100eab2
--- /dev/null
+++ b/packages/api/src/auth/recovery.spec.ts
@@ -0,0 +1,113 @@
+import { createHash } from 'node:crypto';
+import {
+ createBackupCodeVerifier,
+ createBackupCodeGenerator,
+ generateBackupCodes,
+ generateTOTPSecret,
+ matchesBackupCode,
+} from './recovery';
+
+describe('two-factor credential generation', () => {
+ it.each([undefined, 'legacy', 'invalid'])(
+ 'keeps issuance compatible before activation: %s',
+ async (format) => {
+ const { plainCodes, codeObjects } = await createBackupCodeGenerator(format)(2);
+ plainCodes.forEach((code, index) => {
+ expect(code).toMatch(/^[a-f0-9]{8}$/);
+ expect(codeObjects[index].codeHash).toBe(createHash('sha256').update(code).digest('hex'));
+ });
+ },
+ );
+
+ it('activates strong issuance only when explicitly configured', async () => {
+ const { plainCodes, codeObjects } = await createBackupCodeGenerator('strong')(1);
+ expect(plainCodes[0]).toHaveLength(32);
+ expect(matchesBackupCode(plainCodes[0], codeObjects[0].codeHash)).toBe(true);
+ });
+ it('generates a 160-bit Base32 TOTP secret', () => {
+ expect(generateTOTPSecret()).toMatch(/^[A-Z2-7]{32}$/);
+ expect(generateTOTPSecret()).not.toBe(generateTOTPSecret());
+ });
+
+ it('generates ten 128-bit backup codes with individual salts', async () => {
+ const { plainCodes, codeObjects } = await generateBackupCodes();
+ expect(plainCodes).toHaveLength(10);
+ expect(new Set(plainCodes).size).toBe(10);
+ expect(new Set(codeObjects.map((entry) => entry.codeHash.split(':')[1])).size).toBe(10);
+ plainCodes.forEach((code, i) => {
+ expect(code).toMatch(/^[a-f0-9]{32}$/);
+ expect(codeObjects[i].codeHash).toMatch(/^sha256:[a-f0-9]{32}:[a-f0-9]{64}$/);
+ expect(matchesBackupCode(code, codeObjects[i].codeHash)).toBe(true);
+ expect(matchesBackupCode('not-the-code', codeObjects[i].codeHash)).toBe(false);
+ expect(codeObjects[i]).toMatchObject({ used: false, usedAt: null });
+ });
+ });
+
+ it('accepts legacy unsalted SHA-256 digests', () => {
+ const hash = createHash('sha256').update('deadbeef').digest('hex');
+ expect(matchesBackupCode('deadbeef', hash)).toBe(true);
+ expect(matchesBackupCode('feedface', hash)).toBe(false);
+ });
+
+ it.each(['', 'sha256:x:y', 'sha256:' + 'a'.repeat(32) + ':bad', 'bcrypt:invalid'])(
+ 'rejects malformed stored hashes: %s',
+ (hash) => {
+ expect(matchesBackupCode('deadbeef', hash)).toBe(false);
+ },
+ );
+
+ it('consumes the matched code without changing remaining codes', async () => {
+ const { plainCodes, codeObjects } = await generateBackupCodes(2);
+ const user = { _id: 'user', backupCodes: codeObjects };
+ const consumeBackupCode = jest.fn(async (_id: string, hash: string) => {
+ const entry = user.backupCodes.find((code) => code.codeHash === hash && !code.used);
+ if (!entry) {
+ return false;
+ }
+ entry.used = true;
+ return true;
+ });
+ const verify = createBackupCodeVerifier(consumeBackupCode);
+ expect(await verify({ user, backupCode: ` ${plainCodes[0]} ` })).toBe(true);
+ expect(consumeBackupCode).toHaveBeenCalledWith('user', codeObjects[0].codeHash);
+ expect(user.backupCodes[1].used).toBe(false);
+ expect(await verify({ user, backupCode: plainCodes[0] })).toBe(false);
+ expect(await verify({ user, backupCode: plainCodes[1], persist: false })).toBe(true);
+ expect(consumeBackupCode).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects an otherwise matching code when atomic consumption loses', async () => {
+ const { plainCodes, codeObjects } = await generateBackupCodes(1);
+ const consumeBackupCode = jest.fn().mockResolvedValue(false);
+ expect(
+ await createBackupCodeVerifier(consumeBackupCode)({
+ user: { _id: 'user', backupCodes: codeObjects },
+ backupCode: plainCodes[0],
+ }),
+ ).toBe(false);
+ });
+
+ it('allows an existing legacy code without persistence during replacement', async () => {
+ const updateUser = jest.fn();
+ const user = {
+ _id: 'user',
+ backupCodes: [
+ {
+ codeHash: createHash('sha256').update('deadbeef').digest('hex'),
+ used: false,
+ },
+ ],
+ };
+ expect(
+ await createBackupCodeVerifier(updateUser)({ user, backupCode: 'deadbeef', persist: false }),
+ ).toBe(true);
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('does not persist an invalid code', async () => {
+ const updateUser = jest.fn();
+ const user = { _id: 'user', backupCodes: (await generateBackupCodes()).codeObjects };
+ expect(await createBackupCodeVerifier(updateUser)({ user, backupCode: 'bad' })).toBe(false);
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/auth/recovery.ts b/packages/api/src/auth/recovery.ts
new file mode 100644
index 0000000000..9bde9c0e6a
--- /dev/null
+++ b/packages/api/src/auth/recovery.ts
@@ -0,0 +1,108 @@
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
+import type { StoredTwoFactorAccount, TwoFactorBackupCode } from './twoFactor';
+
+interface BackupCodeVerificationParams {
+ user: StoredTwoFactorAccount;
+ backupCode: string;
+ persist?: boolean;
+}
+
+/** 160-bit secrets match the recommended HMAC-SHA1 key size. */
+export function generateTOTPSecret(): string {
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
+ let bits = 0;
+ let value = 0;
+ let output = '';
+ for (const byte of randomBytes(20)) {
+ value = (value << 8) | byte;
+ bits += 8;
+ while (bits >= 5) {
+ output += alphabet[(value >>> (bits - 5)) & 31];
+ bits -= 5;
+ }
+ }
+ return output;
+}
+
+function digest(code: string, salt = ''): string {
+ return createHash('sha256').update(salt).update(code).digest('hex');
+}
+
+/** High-entropy recovery credentials do not require password-style key stretching. */
+export async function generateBackupCodes(
+ count = 10,
+ legacy = false,
+): Promise<{
+ plainCodes: string[];
+ codeObjects: TwoFactorBackupCode[];
+}> {
+ const plainCodes: string[] = [];
+ const codeObjects: TwoFactorBackupCode[] = [];
+ for (let i = 0; i < count; i++) {
+ const code = randomBytes(legacy ? 4 : 16).toString('hex');
+ if (legacy) {
+ plainCodes.push(code);
+ codeObjects.push({ codeHash: digest(code), used: false, usedAt: null });
+ continue;
+ }
+ const salt = randomBytes(16).toString('hex');
+ plainCodes.push(code);
+ codeObjects.push({
+ codeHash: `sha256:${salt}:${digest(code, salt)}`,
+ used: false,
+ usedAt: null,
+ });
+ }
+ return { plainCodes, codeObjects };
+}
+
+/** Keep issuance compatible until the operator completes the backend/client rollout. */
+export function createBackupCodeGenerator(format?: string): typeof generateBackupCodes {
+ return (count = 10) => generateBackupCodes(count, format !== 'strong');
+}
+
+/** Accept legacy digests until the user regenerates their recovery codes. */
+export function matchesBackupCode(code: string, storedHash: string): boolean {
+ const parts = storedHash.split(':');
+ const legacy = /^[a-f0-9]{64}$/.test(storedHash);
+ if (
+ !legacy &&
+ (parts.length !== 3 ||
+ parts[0] !== 'sha256' ||
+ !/^[a-f0-9]{32}$/.test(parts[1]) ||
+ !/^[a-f0-9]{64}$/.test(parts[2]))
+ ) {
+ return false;
+ }
+ const expected = Buffer.from(legacy ? storedHash : parts[2], 'hex');
+ const actual = Buffer.from(digest(code, legacy ? '' : parts[1]), 'hex');
+ return timingSafeEqual(expected, actual);
+}
+
+export function createBackupCodeVerifier(
+ consumeBackupCode: (id: string, codeHash: string) => Promise<boolean>,
+): (params: BackupCodeVerificationParams) => Promise<boolean> {
+ return async ({
+ user,
+ backupCode,
+ persist = true,
+ }: BackupCodeVerificationParams): Promise<boolean> => {
+ if (typeof backupCode !== 'string' || !user || !Array.isArray(user.backupCodes)) {
+ return false;
+ }
+ const code = backupCode.trim();
+ if (!/^(?:[a-f0-9]{8}|[a-f0-9]{32})$/.test(code)) {
+ return false;
+ }
+ const matching = user.backupCodes.find(
+ (entry) => !entry.used && matchesBackupCode(code, entry.codeHash),
+ );
+ if (!matching) {
+ return false;
+ }
+ if (persist) {
+ return consumeBackupCode(String(user._id), matching.codeHash);
+ }
+ return true;
+ };
+}
diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.ts
index ecdfe87a66..290cb0974b 100644
--- a/packages/data-schemas/src/methods/user.methods.spec.ts
+++ b/packages/data-schemas/src/methods/user.methods.spec.ts
@@ -65,6 +65,64 @@ afterEach(() => {
restoreAuthUserCacheEnv();
});
+describe('consumeBackupCode', () => {
+ async function createRecoveryUser() {
+ return User.create({
+ email: '[email protected]',
+ backupCodes: [
+ { codeHash: 'hash-a', used: false },
+ { codeHash: 'hash-b', used: false },
+ ],
+ });
+ }
+
+ it('permits exactly one simultaneous redemption of the same code', async () => {
+ const user = await createRecoveryUser();
+ const results = await Promise.all([
+ methods.consumeBackupCode(String(user._id), 'hash-a'),
+ methods.consumeBackupCode(String(user._id), 'hash-a'),
+ ]);
+ expect(results.sort()).toEqual([false, true]);
+ const stored = await User.findById(user._id).select('+backupCodes').lean();
+ expect(stored?.backupCodes?.[0]).toMatchObject({ used: true, usedAt: expect.any(Date) });
+ expect(stored?.backupCodes?.[1].used).toBe(false);
+ });
+
+ it('does not restore a consumed code when different codes redeem simultaneously', async () => {
+ const user = await createRecoveryUser();
+ expect(
+ await Promise.all([
+ methods.consumeBackupCode(String(user._id), 'hash-a'),
+ methods.consumeBackupCode(String(user._id), 'hash-b'),
+ ]),
+ ).toEqual([true, true]);
+ const stored = await User.findById(user._id).select('+backupCodes').lean();
+ expect(stored?.backupCodes?.every((code) => code.used)).toBe(true);
+ });
+
+ it('rejects a stale hash after regeneration', async () => {
+ const user = await createRecoveryUser();
+ await User.updateOne(
+ { _id: user._id },
+ { $set: { backupCodes: [{ codeHash: 'replacement', used: false }] } },
+ );
+ expect(await methods.consumeBackupCode(String(user._id), 'hash-a')).toBe(false);
+ });
+
+ it('evicts the auth cache after successful consumption', async () => {
+ enableAuthUserDocCache();
+ const user = await createRecoveryUser();
+ const cache = {
+ get: jest.fn().mockResolvedValue(['cached-user']),
+ set: jest.fn().mockResolvedValue(true),
+ delete: jest.fn().mockResolvedValue(true),
+ };
+ const cachedMethods = createUserMethods(mongoose, { getCache: () => cache });
+ expect(await cachedMethods.consumeBackupCode(String(user._id), 'hash-a')).toBe(true);
+ expect(cache.delete).toHaveBeenCalledWith('cached-user');
+ });
+});
+
describe('User schema indexes', () => {
test('should define an issuer-bound idOnTheSource lookup index', async () => {
await User.syncIndexes();
diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts
index ee4ad522a0..b2508bf7c5 100644
--- a/packages/data-schemas/src/methods/user.ts
+++ b/packages/data-schemas/src/methods/user.ts
@@ -71,6 +71,7 @@ export function createUserMethods(
options?: { preserveExpiresAt?: boolean },
) => Promise<IUser | null>;
awaitAuthUserDocEviction: (userId: string) => Promise<void>;
+ consumeBackupCode: (userId: string, codeHash: string) => Promise<boolean>;
claimSamlIdentity: (
userId: string,
samlId: string,
@@ -374,6 +375,19 @@ export function createUserMethods(
await (deps.delay ?? wait)(AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS);
}
+ /** Only the request that atomically consumes an unused recovery code may authenticate. */
+ async function consumeBackupCode(userId: string, codeHash: string): Promise<boolean> {
+ const result = await mongoose.models.User.updateOne(
+ { _id: userId, backupCodes: { $elemMatch: { codeHash, used: false } } },
+ { $set: { 'backupCodes.$.used': true, 'backupCodes.$.usedAt': new Date() } },
+ );
+ if (result.modifiedCount !== 1) {
+ return false;
+ }
+ await invalidateAuthUserDocCache(userId);
+ return true;
+ }
+
/** Atomically updates a SAML user only when the incoming identity can claim the document. */
async function claimSamlIdentity(
userId: string,
@@ -934,6 +948,7 @@ export function createUserMethods(
createUser,
updateUser,
awaitAuthUserDocEviction,
+ consumeBackupCode,
claimSamlIdentity,
updateTwoFactorEnrollment,
acceptTerms,