* feat: enforce required two-factor authentication
Require local and LDAP accounts to enroll in TOTP before they can use the
app when ENFORCE_TWO_FACTOR_AUTHENTICATION is set. Sign-in, refresh, bearer
verification, optional share auth and image authorization all route an
unenrolled account into a staged setup flow, and every bearer credential
minted before enrollment or a password reset is retired.
Password reset retirement uses the existing credentialsChangedAt stamp, and
commitPasswordReset clears any staged enrollment in the same write. Passkey
sign-in follows the same enrollment gate as password sign-in.
* test: cover passkey sign-in handing off to required enrollment
* refactor: keep Mongoose user types out of two-factor auth contracts
* fix: withdraw a minted session when its retirement recheck fails
* fix: hold Agent API keys and the reset CLI to the required two-factor policy
* fix: adopt a setup token handed off after the setup screen mounted
* fix: move every tab that receives an enrollment hand-off into setup
* fix: read the enrollment gate's retirement cutoff in system scope
* fix: clear minted session cookies before the fallible session deletion
* fix: adopt a setup token persisted before the setup screen subscribed
* feat: passkey authentication with WebAuthn sign-in and management
* refactor: tighten passkey account protections
Require password confirmation before adding or removing a passkey, and rate
limit those confirmations per user in their own namespace. Restrict passkey
enrollment and sign-in to local accounts, and re-evaluate account status once
the credential owner is resolved. Require user verification on the sign-in
ceremony. Invalidate outstanding access tokens on password reset. Tighten
redirect target validation and sanitize ceremony failure logs.
Adds coverage across the passkey controller, the WebAuthn helpers, the step-up
limiter, both JWT strategies, the redirect utility and the passkey settings UI.
* fix: localize passkey default name and respect router basename
Send a localized default credential label at enrollment so non-English
locales no longer persist the server's English fallback, and route the
passkey post-login and 2FA navigations through the deployment base path
so subdirectory installs stay inside the router.
Also mock syncStaticTools in the server boot specs; without it the
post-listen MCP initialization calls undefined and exits the worker.
* fix: harden passkey counter checks and reach stranded credentials
Make the signature counter write a compare-and-swap so two assertions
that verified against the same stored counter cannot both commit, and
reject the losing one; a cloned authenticator is otherwise accepted
inside that window. Counterless authenticators keep restamping at 0.
Keep the passkey panel reachable for identity-provider accounts, which
already get passwordless removal server-side but had no way in, while
hiding the add control they cannot use. Cascade passkey deletion from
the admin user-deletion path so credential IDs are not stranded.
* fix: reject stale 2FA temp tokens and surface passkey load failures
A temporary 2FA token proves only the first factor, so honouring one
minted before a password reset let anyone holding the second factor
survive account recovery. Apply the same credentials-changed cutoff the
JWT strategy uses.
Also distinguish a failed passkey query from an empty list; the error
state previously rendered as "no passkeys yet", which misreports what
is protecting the account.
* fix: fail closed when the passkey counter write cannot commit
Returning success on a storage error bypassed the compare-and-swap it
exists to enforce, so a cloned authenticator could be accepted while the
stored counter stayed stale. A database that cannot take this write
cannot mint the session either, so little is gained by failing open.
Counterless credentials carry no clone signal and keep their old path.
* fix: keep the passkey 2FA handoff inside the router
A full-page navigation to the 2FA screen remounted AuthContextProvider,
which silent-refreshes on mount; no refresh session exists yet at that
point, so it bounced back to login before the code could be entered.
Route through the router like the password flow does.
Also reveal the removal step-up field when the server refuses a
passwordless attempt, so an account migrated to an identity provider
without its old hash cleared can still clear its credentials; drop the
staged password when the dialog closes; and revoke passkeys in the CLI
password reset, which bypassed the HTTP controller's cleanup.
* fix: apply one email-verification policy across login methods
Accounts predating mandatory verification are marked verified as they
sign in when no email is configured, but only the password strategy did
it, so the same legacy account was admitted by password and refused by
passkey. Extract the rule into a shared helper and call it from both.
* fix: refuse a passkey sign-in when the ban check cannot complete
checkBan defaults next to a no-op, so calling it bare discarded any
internal failure and left req.banned unset, letting the request fall
through and be issued tokens. Capture the error the middleware chain
would have propagated and reject instead.
* fix: refine passkey management dialogs
* test: stabilize passkey tooltip assertions
* test: reconcile passkey specs with the canary reset and deletion flows
The credentialsChangedAt stamp now lives in commitPasswordReset, so its
assertion moves to the passwordReset unit spec. Restores the describe
blocks the rebase merged together.
* test: mock passkey routes in the cross-site login suite
* refactor: move passkey handlers and credential checks into packages/api
The passkey controller, the credentialsChangedAt predicate and the legacy
email-verification grandfathering now live in TypeScript with injected
dependencies; /api keeps only the wiring that builds the handlers.
* style: align passkey UI with Tailwind v4 order and design-rule lint
* fix: revoke earlier access tokens on a CLI password reset
passwordVersion is not a user schema field, so the write was dropped and
tokens issued before the reset kept verifying.
* test: cover passkey sign-in and credential revocation end to end
* fix: hide passkey sign-in when email login is disabled
The passkey endpoints already refuse under ALLOW_EMAIL_LOGIN=false, so
advertising the button only led to a 403.
* fix: let only one concurrent verification consume a passkey challenge
Without a native getDel the challenge was read then deleted, so two
concurrent verifications could both use it. The delete now arbitrates:
only the caller whose delete removed the key gets the challenge.
* test: run passkey ceremonies on the localhost relying party
WebAuthn refuses an IP address as the RP ID, and the harness serves the
app on 127.0.0.1. The reset scenario runs once per project, so the mock
harness lifts the per-IP reset request limit as it does for forks.
* fix: keep passkey management when email login is disabled
Gate only the sign-in button on emailLoginEnabled, since only the sign-in
routes sit behind that gate; list, rename and remove stay reachable.
* fix: build the passkey credential index before the first registration
With MONGO_AUTO_INDEX=false the unique credentialId index was never
created, so concurrent registrations could store the same credential.
* test: enable password reset in the mock harness and cover email-login-off passkeys
* fix: stop re-exporting the passkey cap from data-schemas
The bundler left every import of methods/passkey.ts unlinked while that
module re-exported MAX_PASSKEYS_PER_USER from librechat-data-provider, so
the index build and the counter-failure log threw ReferenceError at
runtime. Consumers now import the cap from librechat-data-provider.
* test: close nested settings dialogs before logging out in passkey scenarios
* fix: reject cross-site passkey assertions
The verify route accepted a form posted from another site, which let an
attacker sign a victim into the attacker's account. It now runs the same
requireSameOrigin guard as password login and the 2FA step.
* fix: end refresh sessions on a CLI password reset
A surviving refresh session could mint an access token issued after the
credentialsChangedAt stamp, so the CLI now deletes sessions like the web
reset does.
* fix: keep the passkey button locked when it supersedes autofill
Starting the modal ceremony aborts the pending autofill one, and the
autofill error path cleared the shared lock and busy state while the
modal ceremony was still running.
(cherry picked from commit 471abaa64d)
Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/14715
* refactor: `packages/api` build scripts for better inline debugging
* refactor: Explicitly select secure fields as no longer returned by default, exclude backupCodes from user data retrieval in authentication and 2FA processes
* refactor: Backup Codes UI to not expect backup codes, only regeneration
* refactor: Ensure secure fields are deleted from user data in getUserController
* refactor: move model definitions and database-related methods to packages/data-schemas
* ci: update tests due to new DB structure
fix: disable mocking `librechat-data-provider`
feat: Add schema exports to data-schemas package
- Introduced a new schema module that exports various schemas including action, agent, and user schemas.
- Updated index.ts to include the new schema exports for better modularity and organization.
ci: fix appleStrategy tests
fix: Agent.spec.js
ci: refactor handleTools tests to use MongoMemoryServer for in-memory database
fix: getLogStores imports
ci: update banViolation tests to use MongoMemoryServer and improve session mocking
test: refactor samlStrategy tests to improve mock configurations and user handling
ci: fix crypto mock in handleText tests for improved accuracy
ci: refactor spendTokens tests to improve model imports and setup
ci: refactor Message model tests to use MongoMemoryServer and improve database interactions
* refactor: streamline IMessage interface and move feedback properties to types/message.ts
* refactor: use exported initializeRoles from `data-schemas`, remove api workspace version (this serves as an example of future migrations that still need to happen)
* refactor: update model imports to use destructuring from `~/db/models` for consistency and clarity
* refactor: remove unused mongoose imports from model files for cleaner code
* refactor: remove unused mongoose imports from Share, Prompt, and Transaction model files for cleaner code
* refactor: remove unused import in Transaction model for cleaner code
* ci: update deploy workflow to reference new Docker Dev Branch Images Build and add new workflow for building Docker images on dev branch
* chore: cleanup imports
* 🚀 feat: Implement v3 encryption and decryption methods for TOTP secrets
* 🚀 feat: Refactor Two-Factor Authentication methods and enhance 2FA verification process
* 🚀 feat: Update encryption methods to use hex decoding for legacy keys and improve error handling for AES-256-CTR
* 🚀 feat: Update import paths in TwoFactorController for consistency and clarity
* 🌟 feat: Implement Two-Factor Authentication (2FA) functionality
* fix: Two-Factor Authentication Logic and State Management
* 🌟 feat: Add LICENSE file and update package version to 0.0.2 with MIT license
* 🔒 feat: add Two-Factor Authentication (2FA) with backup codes & QR support (#5684)
* working version for generating TOTP and authenticate.
* better looking UI
* refactored + better TOTP logic
* fixed issue with UI
* fixed issue: remove initial setup when closing window before completion.
* added: onKeyDown for verify and disable
* refactored some code and cleaned it up a bit.
* refactored some code and cleaned it up a bit.
* refactored some code and cleaned it up a bit.
* refactored some code and cleaned it up a bit.
* fixed issue after updating to new main branch
* updated example
* refactored controllers
* removed `passport-totp` not used.
* update the generateBackupCodes function to generate 10 codes by default:
* update the backup codes to an object.
* fixed issue with backup codes not working
* be able to disable 2FA with backup codes.
* removed new env. replaced with JWT_SECRET
* ✨ style: improved a11y and style for TwoFactorAuthentication
* 🔒 fix: small types checks
* ✨ feat: improve 2FA UI components
* fix: remove unnecessary console log
* add option to disable 2FA with backup codes
* - add option to refresh backup codes
- (optional) maybe show the user which backup codes have already been used?
* removed text to be able to merge the main.
* removed eng tx to be able to merge
* fix: migrated lang to new format.
* feat: rewrote whole 2FA UI + refactored 2FA backend
* chore: resolving conflicts
* chore: resolving conflicts
* fix: missing packages, because of resolving conflicts.
* fix: UI issue and improved a11y
* fix: 2FA backup code not working
* fix: update localization keys for UI consistency
* fix: update button label to use localized text
* fix: refactor backup codes regeneration and update localization keys
* fix: remove outdated translation for shared links management
* fix: remove outdated 2FA code prompts from translation.json
* fix: add cursor styles for backup codes item based on usage state
* fix: resolve conflict issue
* fix: resolve conflict issue
* fix: resolve conflict issue
* fix: missing packages in package-lock.json
* fix: add disabled opacity to the verify button in TwoFactorScreen
* ⚙ fix: update 2FA logic to rely on backup codes instead of TOTP status
* ⚙️ fix: Simplify user retrieval in 2FA logic by removing unnecessary TOTP secret query
* ⚙️ test: Add unit tests for TwoFactorAuthController and twoFactorControllers
* ⚙️ fix: Ensure backup codes are validated as an array before usage in 2FA components
* ⚙️ fix: Update module path mappings in tests to use relative paths
* ⚙️ fix: Update moduleNameMapper in jest.config.js to remove the caret from path mapping
* ⚙️ refactor: Simplify import paths in TwoFactorAuthController and twoFactorControllers test files
* ⚙️ test: Mock twoFactorService methods in twoFactorControllers tests
* ⚙️ refactor: Comment out unused imports and mock setups in test files for two-factor authentication
* ⚙️ refactor: removed files
* refactor: Exclude totpSecret from user data retrieval in AuthController, LoginController, and jwtStrategy
* refactor: Consolidate backup code verification to apply DRY and remove default array in user schema
* refactor: Enhance two-factor authentication ux/flow with improved error handling and loading state management, prevent redirect to /login
---------
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>