diff --git a/.env.example b/.env.example index 19e0e6155a..c3c02f2d18 100644 --- a/.env.example +++ b/.env.example @@ -849,6 +849,12 @@ LOGIN_MAX=7 LOGIN_WINDOW=5 REGISTER_MAX=5 REGISTER_WINDOW=60 +# Two-factor code attempts (login challenge and enrollment confirmation); defaults to LOGIN_MAX/LOGIN_WINDOW. +# TWO_FACTOR_TEMP_MAX=7 +# TWO_FACTOR_TEMP_WINDOW=5 +# Two-factor enrollment steps that check no guessable code; kept separate so wrong codes cannot strand an enrollment. +# TWO_FACTOR_SETUP_MAX=20 +# TWO_FACTOR_SETUP_WINDOW=5 # Password-reset email requests and token submissions are limited separately. # Submission values inherit the matching request value when omitted; all default to 2. @@ -894,6 +900,7 @@ ALLOW_EMAIL_LOGIN=true ALLOW_REGISTRATION=true ALLOW_SOCIAL_LOGIN=false ALLOW_SOCIAL_REGISTRATION=false +# A successful password reset invalidates existing sessions and bearer tokens, independently of 2FA enforcement. ALLOW_PASSWORD_RESET=false # ALLOW_ACCOUNT_DELETION=true # note: enabled by default if omitted/commented out # ALLOW_EMAIL_CHANGE=true # note: enabled by default if omitted/commented out @@ -902,6 +909,11 @@ ALLOW_PASSWORD_RESET=false # nodes issue and accept password reset links that carry no address binding, so one held by # a previous address owner can outlive the change and reset the renamed account. ALLOW_UNVERIFIED_EMAIL_LOGIN=true +# Requires email/password and LDAP users to enroll in 2FA before a full session is issued. +# Federated identity providers remain responsible for enforcing their own MFA policies. +# This policy and the TWO_FACTOR_SETUP_* quotas are process-wide environment settings, like the +# existing pre-authentication login limits, because they apply before request/tenant config is available. +ENFORCE_TWO_FACTOR_AUTHENTICATION=false SESSION_EXPIRY=1000 * 60 * 15 REFRESH_TOKEN_EXPIRY=(1000 * 60 * 60 * 24) * 7 diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js index f5e3a230f0..a261ace60c 100644 --- a/api/server/controllers/AuthController.js +++ b/api/server/controllers/AuthController.js @@ -1,6 +1,5 @@ const cookies = require('cookie'); const jwt = require('jsonwebtoken'); -const crypto = require('node:crypto'); const { logger, runAsSystem, tenantStorage } = require('@librechat/data-schemas'); const { math, @@ -12,6 +11,13 @@ const { isOpenIDSessionMissingError, isOpenIDSessionIdentityMatch, OPENID_EXPIRY_BUFFER_SECONDS, + clearCloudFrontCookies, + createLocalRefreshHandler, + generateTwoFactorSetupToken, + getValidOpenIDReuseCredential, + isTokenRetired, + isTwoFactorEnrollmentRequired, + sanitizeUserForAuthResponse, } = require('@librechat/api'); const { requestPasswordReset, @@ -25,6 +31,7 @@ const { deleteAllUserSessions, deletePasskeysByUser, awaitAuthUserDocEviction, + deleteSession, getUserById, findSession, updateUser, @@ -81,19 +88,6 @@ const registrationController = async (req, res) => { } }; -const sanitizeUserForAuthResponse = (user) => { - const source = (typeof user?.toObject === 'function' ? user.toObject() : user) || {}; - const { - password: _pw, - __v: _v, - totpSecret: _ts, - backupCodes: _bc, - federatedTokens: _ft, - ...safeUser - } = source; - return safeUser; -}; - const runInUserTenant = (user, fn) => user.tenantId ? tenantStorage.run( @@ -102,30 +96,6 @@ const runInUserTenant = (user, fn) => ) : runAsSystem(fn); -const getValidOpenIDReuseUserId = (parsedCookies, refreshToken) => { - const openidUserId = parsedCookies.openid_user_id; - if (!openidUserId || !process.env.JWT_REFRESH_SECRET) { - return null; - } - - try { - const payload = jwt.verify(openidUserId, process.env.JWT_REFRESH_SECRET); - if (typeof payload !== 'object' || payload == null || typeof payload.id !== 'string') { - return null; - } - if (refreshToken == null) { - return payload.id; - } - if (typeof payload.refreshTokenHash !== 'string') { - return null; - } - const refreshTokenHash = crypto.createHash('sha256').update(refreshToken).digest('base64url'); - return payload.refreshTokenHash === refreshTokenHash ? payload.id : null; - } catch { - return null; - } -}; - const selectOpenIDRefreshToken = (openidTokens, parsedCookies) => { const sessionRefreshToken = openidTokens?.refreshToken; const browserRefreshToken = parsedCookies.refreshToken; @@ -330,6 +300,20 @@ const resetPasswordController = createResetPasswordController({ awaitAuthUserDocEviction, }); +const refreshLocalSession = createLocalRefreshHandler({ + userProjection: AUTH_REFRESH_USER_PROJECTION, + getUserById, + findSession, + setAuthTokens, + deleteAllUserSessions, + deleteSession, + generateTwoFactorSetupToken, + isTwoFactorEnrollmentRequired, + clearCloudFrontCookies, + warn: (message) => logger.warn(message), + error: (message, cause) => logger.error(message, cause), +}); + const refreshController = async (req, res) => { const parsedCookies = req.headers.cookie ? cookies.parse(req.headers.cookie) : {}; const token_provider = parsedCookies.token_provider; @@ -352,7 +336,10 @@ const refreshController = async (req, res) => { const reusableSessionToken = cookieDiffersFromSession ? null : getReusableOpenIDSessionToken(req.session?.openidTokens); - const reuseUserId = reusableSessionToken ? getValidOpenIDReuseUserId(parsedCookies) : null; + const reuseCredential = reusableSessionToken + ? getValidOpenIDReuseCredential(parsedCookies, process.env.JWT_REFRESH_SECRET) + : null; + const reuseUserId = reuseCredential?.userId; if (reuseUserId) { const reuseSessionTokens = req.session?.openidTokens; try { @@ -366,7 +353,11 @@ const refreshController = async (req, res) => { const user = await runAsSystem(async () => getUserById(reuseUserId, AUTH_REFRESH_USER_PROJECTION), ); - if (!user || !isReusableOpenIDSessionIdentity(reuseSessionTokens, user)) { + if ( + !user || + isTokenRetired(reuseCredential, user) || + !isReusableOpenIDSessionIdentity(reuseSessionTokens, user) + ) { return undefined; } return sendAuthorized(() => { @@ -397,7 +388,8 @@ const refreshController = async (req, res) => { } const refreshUserId = - req.session?.openidTokens?.appUserId ?? getValidOpenIDReuseUserId(parsedCookies); + req.session?.openidTokens?.appUserId ?? + getValidOpenIDReuseCredential(parsedCookies, process.env.JWT_REFRESH_SECRET)?.userId; if (!refreshUserId) { return res.status(403).send('Invalid OpenID refresh token'); } @@ -532,7 +524,11 @@ const refreshController = async (req, res) => { const bridgeSourceToken = parsedCookies.refreshToken; if (isInvalidGrantError(error) && bridgeSourceToken) { // Bridge lookup uses the signed user-id cookie because /refresh is unauthenticated. - const userId = getValidOpenIDReuseUserId(parsedCookies, bridgeSourceToken); + const userId = getValidOpenIDReuseCredential( + parsedCookies, + process.env.JWT_REFRESH_SECRET, + bridgeSourceToken, + )?.userId; if (userId) { try { const bridgeUser = await runAsSystem(async () => @@ -602,51 +598,8 @@ const refreshController = async (req, res) => { } } - /** For non-OpenID users, read refresh token from cookies */ - const refreshToken = parsedCookies.refreshToken; - if (!refreshToken) { - return res.status(200).send('Refresh token not provided'); - } - - try { - const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET); - const user = await getUserById(payload.id, AUTH_REFRESH_USER_PROJECTION); - if (!user) { - return res.status(401).redirect('/login'); - } - - const userId = payload.id; - - if (process.env.NODE_ENV === 'CI') { - const token = await setAuthTokens(userId, res, null, req); - return res.status(200).send({ token, user: sanitizeUserForAuthResponse(user) }); - } - - /** Session with the hashed refresh token */ - const session = await findSession( - { - userId: userId, - refreshToken: refreshToken, - }, - { lean: false }, - ); - - if (session && session.expiration > new Date()) { - const token = await setAuthTokens(userId, res, session, req); - - res.status(200).send({ token, user: sanitizeUserForAuthResponse(user) }); - } else if (req?.query?.retry) { - // Retrying from a refresh token request that failed (401) - res.status(403).send('No session found'); - } else if (payload.exp < Date.now() / 1000) { - res.status(403).redirect('/login'); - } else { - res.status(401).send('Refresh token expired or not found for this user'); - } - } catch (err) { - logger.error(`[refreshController] Invalid refresh token:`, err); - res.status(403).send('Invalid refresh token'); - } + /** For non-OpenID users, delegate refresh to the typed local handler. */ + return refreshLocalSession(req, res, parsedCookies.refreshToken); }; const graphTokenController = async (req, res) => { diff --git a/api/server/controllers/AuthController.spec.js b/api/server/controllers/AuthController.spec.js index 6a1866c1f9..40fb8d2a0b 100644 --- a/api/server/controllers/AuthController.spec.js +++ b/api/server/controllers/AuthController.spec.js @@ -115,13 +115,29 @@ jest.mock('@librechat/api', () => ({ } return params; }), + clearCloudFrontCookies: jest.fn(), + createLocalRefreshHandler: jest.requireActual('@librechat/api').createLocalRefreshHandler, + getValidOpenIDReuseCredential: jest.requireActual('@librechat/api').getValidOpenIDReuseCredential, + sanitizeUserForAuthResponse: jest.requireActual('@librechat/api').sanitizeUserForAuthResponse, + generateTwoFactorSetupToken: jest.fn(() => 'setup-token'), + isTwoFactorEnrollmentRequired: jest.fn(() => false), + /** The retirement cutoff is the assertion under test, so it runs for real rather than stubbed. */ + isTokenRetired: jest.requireActual('@librechat/api').isTokenRetired, + TOKEN_RETIREMENT_FIELDS: jest.requireActual('@librechat/api').TOKEN_RETIREMENT_FIELDS, })); const { createHash } = require('node:crypto'); const openIdClient = require('openid-client'); const jwt = require('jsonwebtoken'); const { logger } = require('@librechat/data-schemas'); -const { isEnabled, findOpenIDUser, buildOpenIDRefreshParams } = require('@librechat/api'); +const { + isEnabled, + clearCloudFrontCookies, + findOpenIDUser, + buildOpenIDRefreshParams, + generateTwoFactorSetupToken, + isTwoFactorEnrollmentRequired, +} = require('@librechat/api'); const { graphTokenController, refreshController, @@ -536,6 +552,18 @@ describe('refreshController – OpenID path', () => { options, ); + /** `setOpenIDAuthTokens` stamps this cookie to the millisecond, so the cutoffs can date it */ + const makeSignedReuseCookie = (issuedAtMs, id = 'user-db-id') => + jwt.sign( + { + id, + issuedAtMs, + refreshTokenHash: createHash('sha256').update('stored-refresh').digest('base64url'), + }, + process.env.JWT_REFRESH_SECRET, + { expiresIn: '1h' }, + ); + const setOpenIDReuseCookies = (signedUserId = makeSignedUserId()) => { req.headers.cookie = [ 'token_provider=openid', @@ -1201,6 +1229,61 @@ describe('refreshController – OpenID path', () => { expectOpenIDRefreshGrant(); }); + /** Arms the reuse shortcut so only the cookie's mint time decides whether it is taken. */ + const armOpenIDReuse = (issuedAtMs) => { + setOpenIDReuseCookies(makeSignedReuseCookie(issuedAtMs)); + req.session = { + openidTokens: { + accessToken: 'session-access-token', + idToken: makeSessionToken(), + refreshToken: 'stored-refresh', + lastRefreshedAt: Date.now(), + appUserId: defaultUser._id, + openidSubject: baseClaims.sub, + tenantId: defaultUser.tenantId, + openidIssuer: baseClaims.iss, + }, + }; + }; + + it('declines the reuse shortcut for a cookie minted before enrollment', async () => { + const twoFactorEnrolledAt = new Date(); + armOpenIDReuse(twoFactorEnrolledAt.getTime() - 1); + getUserById.mockResolvedValue({ ...defaultUser, twoFactorEnrolledAt }); + + await refreshController(req, res); + + expect(setCloudFrontAuthCookies).not.toHaveBeenCalled(); + expectOpenIDRefreshGrant(); + }); + + it('declines the reuse shortcut for a cookie minted in the resetting millisecond', async () => { + const credentialsChangedAt = new Date(); + armOpenIDReuse(credentialsChangedAt.getTime()); + getUserById.mockResolvedValue({ ...defaultUser, credentialsChangedAt }); + + await refreshController(req, res); + + expect(setCloudFrontAuthCookies).not.toHaveBeenCalled(); + expectOpenIDRefreshGrant(); + }); + + it('keeps the reuse shortcut for a cookie minted after both cutoffs', async () => { + const twoFactorEnrolledAt = new Date(); + armOpenIDReuse(twoFactorEnrolledAt.getTime() + 1); + getUserById.mockResolvedValue({ + ...defaultUser, + twoFactorEnrolledAt, + credentialsChangedAt: new Date(twoFactorEnrolledAt.getTime() - 60_000), + }); + + await refreshController(req, res); + + expect(openIdClient.refreshTokenGrant).not.toHaveBeenCalled(); + expect(setCloudFrontAuthCookies).toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(200); + }); + it('falls through to full OpenID refresh when session tokens are stale', async () => { setOpenIDReuseCookies(); req.session = { @@ -2311,7 +2394,8 @@ describe('refreshController – LibreChat path', () => { process.env.JWT_REFRESH_SECRET = refreshSecret; process.env.NODE_ENV = 'test'; setAuthTokens.mockResolvedValue('local-app-token'); - findSession.mockResolvedValue({ expiration: new Date(Date.now() + 60_000) }); + findSession.mockResolvedValue({ _id: 'session-id', expiration: new Date(Date.now() + 60_000) }); + isTwoFactorEnrollmentRequired.mockReturnValue(false); const refreshToken = jwt.sign({ id: 'local-user-id' }, refreshSecret, { expiresIn: '1h', @@ -2325,6 +2409,7 @@ describe('refreshController – LibreChat path', () => { status: jest.fn().mockReturnThis(), send: jest.fn().mockReturnThis(), redirect: jest.fn(), + clearCookie: jest.fn(), }; }); @@ -2361,7 +2446,7 @@ describe('refreshController – LibreChat path', () => { expect(setAuthTokens).toHaveBeenCalledWith( 'local-user-id', res, - { expiration: expect.any(Date) }, + expect.objectContaining({ expiration: expect.any(Date) }), req, ); expect(sentPayload).toEqual({ @@ -2373,6 +2458,244 @@ describe('refreshController – LibreChat path', () => { }); }); + it('requires enrollment before issuing tokens from an existing local refresh session', async () => { + const user = { + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: false, + email: 'local@example.com', + }; + getUserById.mockResolvedValue(user); + isTwoFactorEnrollmentRequired.mockReturnValue(true); + + await refreshController(req, res); + + expect(generateTwoFactorSetupToken).toHaveBeenCalledWith( + 'local-user-id', + process.env.JWT_SECRET, + ); + expect(res.send).toHaveBeenCalledWith({ + code: 'TWO_FACTOR_ENROLLMENT_REQUIRED', + twoFAPending: true, + twoFASetupRequired: true, + tempToken: 'setup-token', + }); + expect(findSession).toHaveBeenCalledWith( + { + userId: 'local-user-id', + refreshToken: expect.any(String), + }, + { lean: false }, + ); + expect(setAuthTokens).not.toHaveBeenCalled(); + expect(deleteSession).toHaveBeenCalledWith({ sessionId: 'session-id' }); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(clearCloudFrontCookies).toHaveBeenCalledWith(res, { + userId: 'local-user-id', + tenantId: undefined, + storageRegion: undefined, + }); + + findSession.mockResolvedValue(null); + jest.clearAllMocks(); + isTwoFactorEnrollmentRequired.mockReturnValue(true); + + await refreshController(req, res); + + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + /** + * `findSession` resolves before anything is minted, so recovery landing in that gap is caught by + * neither gate: the token handed back postdates `credentialsChangedAt`, and `setAuthTokens` re-saves + * the very session document recovery had already deleted. + */ + describe('a password reset landing after the session lookup', () => { + const racingRead = (user) => { + getUserById + .mockResolvedValueOnce(user) + .mockResolvedValueOnce({ credentialsChangedAt: new Date(Date.now() + 60_000) }); + }; + + it('withdraws the session it had already minted', async () => { + racingRead({ _id: 'local-user-id', provider: 'local', twoFactorEnabled: true }); + + await refreshController(req, res); + + expect(setAuthTokens).toHaveBeenCalled(); + expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'local-user-id' }); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.send).toHaveBeenCalledWith('Refresh token expired or not found for this user'); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.clearCookie).toHaveBeenCalledWith('token_provider'); + }); + + it('withdraws the session it had already minted when the recheck cannot complete', async () => { + getUserById + .mockResolvedValueOnce({ _id: 'local-user-id', provider: 'local', twoFactorEnabled: true }) + .mockRejectedValueOnce(new Error('database unavailable')); + + await refreshController(req, res); + + expect(setAuthTokens).toHaveBeenCalled(); + expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'local-user-id' }); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.send).not.toHaveBeenCalledWith( + expect.objectContaining({ token: 'local-app-token' }), + ); + }); + + it('withholds the enrollment token it had already minted', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + racingRead({ _id: 'local-user-id', provider: 'local', twoFactorEnabled: false }); + + await refreshController(req, res); + + expect(generateTwoFactorSetupToken).toHaveBeenCalled(); + expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'local-user-id' }); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.send).not.toHaveBeenCalledWith( + expect.objectContaining({ tempToken: 'setup-token' }), + ); + }); + + it('reads the cutoff again only once the credential exists', async () => { + const order = []; + getUserById + .mockResolvedValueOnce({ _id: 'local-user-id', provider: 'local', twoFactorEnabled: true }) + .mockImplementationOnce(async () => { + order.push('recheck'); + return {}; + }); + setAuthTokens.mockImplementationOnce(async () => { + order.push('mint'); + return 'local-app-token'; + }); + + await refreshController(req, res); + + expect(order).toEqual(['mint', 'recheck']); + expect(getUserById).toHaveBeenLastCalledWith( + 'local-user-id', + 'twoFactorEnrolledAt credentialsChangedAt', + ); + expect(res.status).toHaveBeenCalledWith(200); + }); + }); + + it('refuses a refresh credential that predates required enrollment', async () => { + getUserById.mockResolvedValue({ + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: true, + twoFactorEnrolledAt: new Date(Date.now() + 60_000), + }); + + await refreshController(req, res); + + /** Promotion lands before revocation, so the cutoff is what denies the older cookie. */ + expect(setAuthTokens).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + }); + + it('refuses a stale refresh credential even on the CI shortcut', async () => { + process.env.NODE_ENV = 'CI'; + getUserById.mockResolvedValue({ + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: true, + twoFactorEnrolledAt: new Date(Date.now() + 60_000), + }); + + await refreshController(req, res); + + process.env.NODE_ENV = 'test'; + expect(setAuthTokens).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('accepts a refresh credential minted after enrollment', async () => { + getUserById.mockResolvedValue({ + _id: 'local-user-id', + email: 'local@example.com', + provider: 'local', + twoFactorEnabled: true, + twoFactorEnrolledAt: new Date(Date.now() - 60_000), + }); + + await refreshController(req, res); + + expect(setAuthTokens).toHaveBeenCalled(); + expect(res.send).toHaveBeenCalledWith(expect.objectContaining({ token: 'local-app-token' })); + }); + + it('leaves refresh alone for accounts that never enrolled through the policy', async () => { + getUserById.mockResolvedValue({ + _id: 'local-user-id', + email: 'local@example.com', + provider: 'local', + twoFactorEnabled: true, + twoFactorEnrolledAt: null, + }); + + await refreshController(req, res); + + expect(setAuthTokens).toHaveBeenCalled(); + }); + + it('does not issue an enrollment token for a revoked local refresh session', async () => { + getUserById.mockResolvedValue({ + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: false, + }); + isTwoFactorEnrollmentRequired.mockReturnValue(true); + findSession.mockResolvedValue(null); + + await refreshController(req, res); + + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(setAuthTokens).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.send).toHaveBeenCalledWith('Refresh token expired or not found for this user'); + }); + + it('does not issue an enrollment token for an expired local refresh session', async () => { + getUserById.mockResolvedValue({ + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: false, + }); + isTwoFactorEnrollmentRequired.mockReturnValue(true); + findSession.mockResolvedValue({ expiration: new Date(Date.now() - 60_000) }); + + await refreshController(req, res); + + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(setAuthTokens).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.send).toHaveBeenCalledWith('Refresh token expired or not found for this user'); + }); + + it('preserves CI refresh compatibility without session lookup', async () => { + process.env.NODE_ENV = 'CI'; + getUserById.mockResolvedValue({ + _id: 'local-user-id', + provider: 'local', + twoFactorEnabled: false, + }); + isTwoFactorEnrollmentRequired.mockReturnValue(true); + + await refreshController(req, res); + + expect(findSession).not.toHaveBeenCalled(); + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(setAuthTokens).toHaveBeenCalledWith('local-user-id', res, null, req); + }); + it('sanitizes user documents before returning CI refresh responses', async () => { process.env.NODE_ENV = 'CI'; getUserById.mockResolvedValue({ diff --git a/api/server/controllers/TwoFactorController.js b/api/server/controllers/TwoFactorController.js index 18a0ee3f5a..1844332acb 100644 --- a/api/server/controllers/TwoFactorController.js +++ b/api/server/controllers/TwoFactorController.js @@ -1,4 +1,5 @@ const { encryptV3, logger } = require('@librechat/data-schemas'); +const { clearEnrollmentNonces } = require('@librechat/api'); const { verifyOTPOrBackupCode, generateBackupCodes, @@ -43,10 +44,13 @@ const enable2FA = async (req, res) => { const { plainCodes, codeObjects } = await generateBackupCodes(); const encryptedSecret = encryptV3(secret); - const user = await updateUser(userId, { - pendingTotpSecret: encryptedSecret, - pendingBackupCodes: codeObjects, - }); + const user = await updateUser( + userId, + clearEnrollmentNonces({ + pendingTotpSecret: encryptedSecret, + pendingBackupCodes: codeObjects, + }), + ); const email = user.email || (existingUser && existingUser.email) || ''; const otpauthUrl = `otpauth://totp/${safeAppTitle}:${email}?secret=${secret}&issuer=${safeAppTitle}`; @@ -119,7 +123,7 @@ const confirm2FA = async (req, res) => { if (user.pendingBackupCodes?.length) { update.backupCodes = user.pendingBackupCodes; } - await updateUser(userId, update); + await updateUser(userId, clearEnrollmentNonces(update)); return res.status(200).json(); } return res.status(400).json({ message: 'Invalid token.' }); @@ -151,13 +155,16 @@ const disable2FA = async (req, res) => { return res.status(result.status ?? 400).json({ message: msg }); } } - await updateUser(userId, { - totpSecret: null, - backupCodes: [], - twoFactorEnabled: false, - pendingTotpSecret: null, - pendingBackupCodes: [], - }); + await updateUser( + userId, + clearEnrollmentNonces({ + totpSecret: null, + backupCodes: [], + twoFactorEnabled: false, + pendingTotpSecret: null, + pendingBackupCodes: [], + }), + ); return res.status(200).json(); } catch (err) { logger.error('[disable2FA]', err); diff --git a/api/server/controllers/__tests__/TwoFactorController.spec.js b/api/server/controllers/__tests__/TwoFactorController.spec.js index 62531d94a1..edea2c0f82 100644 --- a/api/server/controllers/__tests__/TwoFactorController.spec.js +++ b/api/server/controllers/__tests__/TwoFactorController.spec.js @@ -4,8 +4,11 @@ const mockVerifyOTPOrBackupCode = jest.fn(); const mockGenerateTOTPSecret = jest.fn(); const mockGenerateBackupCodes = jest.fn(); const mockEncryptV3 = jest.fn(); +const mockGetTOTPSecret = jest.fn(); +const mockVerifyTOTP = jest.fn(); jest.mock('@librechat/data-schemas', () => ({ + ...jest.requireActual('@librechat/data-schemas'), encryptV3: (...args) => mockEncryptV3(...args), logger: { error: jest.fn() }, })); @@ -15,8 +18,8 @@ jest.mock('~/server/services/twoFactorService', () => ({ generateBackupCodes: (...args) => mockGenerateBackupCodes(...args), generateTOTPSecret: (...args) => mockGenerateTOTPSecret(...args), verifyBackupCode: jest.fn(), - getTOTPSecret: jest.fn(), - verifyTOTP: jest.fn(), + getTOTPSecret: (...args) => mockGetTOTPSecret(...args), + verifyTOTP: (...args) => mockVerifyTOTP(...args), })); jest.mock('~/models', () => ({ @@ -24,7 +27,12 @@ jest.mock('~/models', () => ({ updateUser: (...args) => mockUpdateUser(...args), })); -const { enable2FA, regenerateBackupCodes } = require('~/server/controllers/TwoFactorController'); +const { + enable2FA, + confirm2FA, + disable2FA, + regenerateBackupCodes, +} = require('~/server/controllers/TwoFactorController'); function createRes() { const res = {}; @@ -45,6 +53,66 @@ beforeEach(() => { mockGenerateTOTPSecret.mockReturnValue('NEWSECRET'); mockGenerateBackupCodes.mockResolvedValue({ plainCodes: PLAIN_CODES, codeObjects: CODE_OBJECTS }); mockEncryptV3.mockReturnValue('encrypted-secret'); + mockGetTOTPSecret.mockResolvedValue('plain-secret'); + mockVerifyTOTP.mockResolvedValue(true); +}); + +/** Any write that moves the pending or live credentials strands an in-flight required enrollment. */ +const CLEARED_NONCES = { + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, +}; + +describe('required-enrollment nonce cleanup', () => { + it('clears stale nonce state when setup is regenerated', async () => { + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false, email: 'a@b.com' }); + mockUpdateUser.mockResolvedValue({ email: 'a@b.com' }); + + await enable2FA({ user: { id: 'user1' }, body: {} }, createRes()); + + expect(mockUpdateUser.mock.calls[0][1]).toMatchObject(CLEARED_NONCES); + }); + + it('clears stale nonce state when 2FA is confirmed from account settings', async () => { + mockGetUserById.mockResolvedValue({ + _id: 'user1', + twoFactorEnabled: false, + pendingTotpSecret: 'encrypted-secret', + pendingBackupCodes: CODE_OBJECTS, + }); + mockUpdateUser.mockResolvedValue({}); + const res = createRes(); + + await confirm2FA({ user: { id: 'user1' }, body: { token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockUpdateUser.mock.calls[0][1]).toMatchObject({ + twoFactorEnabled: true, + pendingTotpSecret: null, + pendingBackupCodes: [], + ...CLEARED_NONCES, + }); + }); + + it('clears stale nonce state when 2FA is disabled', async () => { + mockGetUserById.mockResolvedValue({ + _id: 'user1', + twoFactorEnabled: true, + totpSecret: 'enc-secret', + }); + mockVerifyOTPOrBackupCode.mockResolvedValue({ verified: true }); + mockUpdateUser.mockResolvedValue({}); + const res = createRes(); + + await disable2FA({ user: { id: 'user1' }, body: { token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockUpdateUser.mock.calls[0][1]).toMatchObject({ + twoFactorEnabled: false, + totpSecret: null, + ...CLEARED_NONCES, + }); + }); }); describe('enable2FA', () => { diff --git a/api/server/controllers/auth/LoginController.js b/api/server/controllers/auth/LoginController.js index bf606b1dea..593c081a80 100644 --- a/api/server/controllers/auth/LoginController.js +++ b/api/server/controllers/auth/LoginController.js @@ -1,30 +1,14 @@ -const { logger } = require('@librechat/data-schemas'); +const { createLoginController, clearCloudFrontCookies } = require('@librechat/api'); const { generate2FATempToken } = require('~/server/services/twoFactorService'); +const { getUserById, deleteAllUserSessions } = require('~/models'); const { setAuthTokens } = require('~/server/services/AuthService'); -const loginController = async (req, res) => { - try { - if (!req.user) { - return res.status(400).json({ message: 'Invalid credentials' }); - } +const loginController = createLoginController({ + generate2FATempToken, + getUserById, + deleteAllUserSessions, + setAuthTokens, + clearCloudFrontCookies, +}); - if (req.user.twoFactorEnabled) { - const tempToken = generate2FATempToken(req.user._id); - return res.status(200).json({ twoFAPending: true, tempToken }); - } - - const { password: _p, totpSecret: _t, __v, ...user } = req.user; - user.id = user._id.toString(); - - const token = await setAuthTokens(req.user._id, res, null, req); - - return res.status(200).send({ token, user }); - } catch (err) { - logger.error('[loginController]', err); - return res.status(500).json({ message: 'Something went wrong' }); - } -}; - -module.exports = { - loginController, -}; +module.exports = { loginController }; diff --git a/api/server/controllers/auth/LoginController.spec.js b/api/server/controllers/auth/LoginController.spec.js new file mode 100644 index 0000000000..d012f8536c --- /dev/null +++ b/api/server/controllers/auth/LoginController.spec.js @@ -0,0 +1,319 @@ +const mockGenerate2FATempToken = jest.fn(() => 'challenge-token'); +const mockSetAuthTokens = jest.fn(() => Promise.resolve('auth-token')); +const mockClearCloudFrontCookies = jest.fn(); +const mockDeleteAllUserSessions = jest.fn(() => Promise.resolve({ deletedCount: 1 })); + +/** What the record carries right now, so a reset can land mid-request the way recovery does. */ +const record = { credentialsChangedAt: null }; +const mockGetUserById = jest.fn(async () => ({ + credentialsChangedAt: record.credentialsChangedAt, +})); + +jest.mock('@librechat/data-schemas', () => ({ + logger: { error: jest.fn(), warn: jest.fn() }, +})); + +jest.mock('@librechat/api', () => ({ + ...jest.requireActual('@librechat/api'), + clearCloudFrontCookies: (...args) => mockClearCloudFrontCookies(...args), +})); + +jest.mock('~/server/services/twoFactorService', () => ({ + generate2FATempToken: (...args) => mockGenerate2FATempToken(...args), +})); + +jest.mock('~/server/services/AuthService', () => ({ + setAuthTokens: (...args) => mockSetAuthTokens(...args), +})); + +jest.mock('~/models', () => ({ + getUserById: (...args) => mockGetUserById(...args), + deleteAllUserSessions: (...args) => mockDeleteAllUserSessions(...args), +})); + +const { loginController } = require('./LoginController'); +const { verifyTwoFactorSetupToken } = require('@librechat/api'); + +function createResponse() { + return { + status: jest.fn().mockReturnThis(), + json: jest.fn().mockReturnThis(), + send: jest.fn().mockReturnThis(), + clearCookie: jest.fn().mockReturnThis(), + }; +} + +describe('loginController', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + const originalSecret = process.env.JWT_SECRET; + + beforeEach(() => { + jest.clearAllMocks(); + record.credentialsChangedAt = null; + process.env.JWT_SECRET = 'jwt-secret'; + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + }); + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + if (originalSecret === undefined) { + delete process.env.JWT_SECRET; + } else { + process.env.JWT_SECRET = originalSecret; + } + }); + + it('uses the existing 2FA challenge for enrolled users', async () => { + const req = { user: { _id: 'user-1', twoFactorEnabled: true } }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockGenerate2FATempToken).toHaveBeenCalledWith('user-1'); + expect(res.json).toHaveBeenCalledWith({ + twoFAPending: true, + tempToken: 'challenge-token', + }); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('requires purpose-scoped enrollment before issuing auth tokens', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = { user: { _id: 'user-2', twoFactorEnabled: false } }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockClearCloudFrontCookies).toHaveBeenCalledWith(res, { + userId: 'user-2', + tenantId: undefined, + storageRegion: undefined, + }); + expect(res.json).toHaveBeenCalledWith({ + code: 'TWO_FACTOR_ENROLLMENT_REQUIRED', + twoFAPending: true, + twoFASetupRequired: true, + tempToken: expect.any(String), + }); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + expect(verifyTwoFactorSetupToken(res.json.mock.calls[0][0].tempToken, 'jwt-secret')).toEqual( + expect.objectContaining({ userId: 'user-2' }), + ); + }); + + it('keeps optional 2FA login behavior unchanged when enforcement is disabled', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const req = { + user: { + _id: 'user-3', + password: 'secret', + totpSecret: 'totp', + email: 'user@example.com', + }, + }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockSetAuthTokens).toHaveBeenCalledWith('user-3', res, null, req); + expect(res.send).toHaveBeenCalledWith({ + token: 'auth-token', + user: { + _id: 'user-3', + email: 'user@example.com', + id: 'user-3', + }, + }); + }); + + it('does not offer local enrollment to federated users', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = { + user: { _id: 'user-4', provider: 'openid', email: 'federated@example.com' }, + }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + /** + * A password reset assigns a password without consulting `provider`, so a federated record can + * be signed in through the local strategy. Under enforcement that login checks neither the + * identity provider's MFA nor this policy, and enrollment cannot remedy it. + */ + it('refuses a password login for a federated record under enforcement', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = { + user: { _id: 'user-4', provider: 'openid', email: 'federated@example.com' }, + }; + const res = createResponse(); + + await loginController(req, res); + + expect(res.status).toHaveBeenCalledWith(403); + /** The code carries the reason: a bare 403 is rendered as a ban by getLoginError. */ + expect(res.json).toHaveBeenCalledWith({ + code: 'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED', + message: 'Sign in with your identity provider to continue.', + }); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + expect(res.send).not.toHaveBeenCalled(); + }); + + it('refuses a federated password login even when LibreChat 2FA is already enabled', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = { user: { _id: 'user-5', provider: 'openid', twoFactorEnabled: true } }; + const res = createResponse(); + + await loginController(req, res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ + code: 'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED', + message: 'Sign in with your identity provider to continue.', + }); + expect(mockGenerate2FATempToken).not.toHaveBeenCalled(); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('leaves federated password logins alone when enforcement is disabled', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const req = { + user: { _id: 'user-6', provider: 'openid', email: 'federated@example.com' }, + }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockSetAuthTokens).toHaveBeenCalledWith('user-6', res, null, req); + }); + + /** + * The strategy compared the password against a document read before hashing it, so recovery + * landing before the response revokes the credential this request is still holding. Everything + * minted here is stamped after that reset, which is precisely what `isTokenRetired` cannot catch, + * so the reset lands during the mint in each of these and the login has to lose the race. + */ + describe('a password reset landing mid-login', () => { + const resetDuring = (mock, value) => + mock.mockImplementationOnce(() => { + record.credentialsChangedAt = new Date('2026-01-01T00:00:00.000Z'); + return value; + }); + + it('refuses the session it had already minted', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + resetDuring(mockSetAuthTokens, Promise.resolve('auth-token')); + const req = { user: { _id: 'user-7', email: 'user@example.com' } }; + const res = createResponse(); + + await loginController(req, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Invalid credentials' }); + expect(res.send).not.toHaveBeenCalled(); + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-7' }); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.clearCookie).toHaveBeenCalledWith('token_provider'); + }); + + it('withdraws the session it had already minted when the recheck cannot complete', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + mockGetUserById.mockRejectedValueOnce(new Error('database unavailable')); + const req = { user: { _id: 'user-9', email: 'user@example.com' } }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockSetAuthTokens).toHaveBeenCalledTimes(1); + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-9' }); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.status).toHaveBeenCalledWith(500); + expect(res.send).not.toHaveBeenCalled(); + }); + + /** Otherwise the holder of the revoked password picks the second factor the account keeps. */ + it('withholds the enrollment token it had already minted', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + mockGetUserById.mockImplementationOnce(async () => { + record.credentialsChangedAt = new Date('2026-01-01T00:00:00.000Z'); + return { credentialsChangedAt: record.credentialsChangedAt }; + }); + const req = { user: { _id: 'user-8', twoFactorEnabled: false } }; + const res = createResponse(); + + await loginController(req, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Invalid credentials' }); + expect(res.json).not.toHaveBeenCalledWith( + expect.objectContaining({ tempToken: expect.any(String) }), + ); + }); + + it('withholds the second-factor challenge it had already minted', async () => { + resetDuring(mockGenerate2FATempToken, 'challenge-token'); + const req = { user: { _id: 'user-9', twoFactorEnabled: true } }; + const res = createResponse(); + + await loginController(req, res); + + expect(mockGenerate2FATempToken).toHaveBeenCalledWith('user-9'); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Invalid credentials' }); + expect(res.json).not.toHaveBeenCalledWith( + expect.objectContaining({ tempToken: 'challenge-token' }), + ); + }); + + it('reads the stamp again only after the credential exists', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const order = []; + mockSetAuthTokens.mockImplementationOnce(async () => { + order.push('mint'); + return 'auth-token'; + }); + mockGetUserById.mockImplementationOnce(async () => { + order.push('recheck'); + return { credentialsChangedAt: record.credentialsChangedAt }; + }); + const res = createResponse(); + + await loginController({ user: { _id: 'user-10', email: 'user@example.com' } }, res); + + expect(order).toEqual(['mint', 'recheck']); + expect(mockGetUserById).toHaveBeenCalledWith( + 'user-10', + 'twoFactorEnrolledAt credentialsChangedAt', + ); + }); + }); + + /** A stamp the authenticating read already saw is not a reset, and must not refuse the login. */ + it('signs in an account whose password reset predates the login', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + record.credentialsChangedAt = new Date('2026-01-01T00:00:00.000Z'); + const req = { + user: { + _id: 'user-11', + email: 'user@example.com', + credentialsChangedAt: new Date('2026-01-01T00:00:00.000Z'), + }, + }; + const res = createResponse(); + + await loginController(req, res); + + expect(res.send).toHaveBeenCalledWith({ + token: 'auth-token', + user: expect.objectContaining({ id: 'user-11' }), + }); + expect(mockDeleteAllUserSessions).not.toHaveBeenCalled(); + }); +}); diff --git a/api/server/controllers/auth/TwoFactorAuthController.js b/api/server/controllers/auth/TwoFactorAuthController.js index a75f7c2653..2eac6c4860 100644 --- a/api/server/controllers/auth/TwoFactorAuthController.js +++ b/api/server/controllers/auth/TwoFactorAuthController.js @@ -1,71 +1,21 @@ -const jwt = require('jsonwebtoken'); -const { logger } = require('@librechat/data-schemas'); -const { isTokenIssuedBeforeCredentialChange } = require('@librechat/api'); +const { createEnrollmentControllers, clearCloudFrontCookies } = require('@librechat/api'); const { verifyTOTP, getTOTPSecret, verifyBackupCode, + generateBackupCodes, } = require('~/server/services/twoFactorService'); const { setAuthTokens } = require('~/server/services/AuthService'); -const { getUserById } = require('~/models'); +const { getUserById, updateTwoFactorEnrollment, deleteAllUserSessions } = require('~/models'); -/** - * Verifies the 2FA code during login using a temporary token. - */ -const verify2FAWithTempToken = async (req, res) => { - try { - const { tempToken, token, backupCode } = req.body; - if (!tempToken) { - return res.status(400).json({ message: 'Missing temporary token' }); - } - - let payload; - try { - payload = jwt.verify(tempToken, process.env.JWT_SECRET); - } catch (err) { - logger.error('Failed to verify temporary token:', err); - return res.status(401).json({ message: 'Invalid or expired temporary token' }); - } - - const user = await getUserById(payload.userId, '+totpSecret +backupCodes'); - if (!user || !user.twoFactorEnabled) { - return res.status(400).json({ message: '2FA is not enabled for this user' }); - } - - /** - * The first factor was proven before the reset, so honouring this token would let a - * password reset be survived by anyone who also holds the second factor. - */ - if (isTokenIssuedBeforeCredentialChange(payload, user)) { - logger.warn('[verify2FAWithTempToken] Rejected a token issued before a credential change'); - return res.status(401).json({ message: 'Invalid or expired temporary token' }); - } - - const secret = await getTOTPSecret(user.totpSecret); - let isVerified = false; - if (token) { - isVerified = await verifyTOTP(secret, token); - } else if (backupCode) { - isVerified = await verifyBackupCode({ user, backupCode }); - } - - if (!isVerified) { - return res.status(401).json({ message: 'Invalid 2FA code or backup code' }); - } - - const userData = user.toObject ? user.toObject() : { ...user }; - delete userData.__v; - delete userData.password; - delete userData.totpSecret; - delete userData.backupCodes; - userData.id = user._id.toString(); - - const authToken = await setAuthTokens(user._id, res, null, req); - return res.status(200).json({ token: authToken, user: userData }); - } catch (err) { - logger.error('[verify2FAWithTempToken]', err); - return res.status(500).json({ message: 'Something went wrong' }); - } -}; - -module.exports = { verify2FAWithTempToken }; +module.exports = createEnrollmentControllers({ + getUserById, + getTOTPSecret, + verifyTOTP, + verifyBackupCode, + generateBackupCodes, + updateTwoFactorEnrollment, + deleteAllUserSessions, + setAuthTokens, + clearCloudFrontCookies, +}); diff --git a/api/server/controllers/auth/TwoFactorAuthController.spec.js b/api/server/controllers/auth/TwoFactorAuthController.spec.js index 82f72e13fa..53da727c91 100644 --- a/api/server/controllers/auth/TwoFactorAuthController.spec.js +++ b/api/server/controllers/auth/TwoFactorAuthController.spec.js @@ -1,18 +1,20 @@ const jwt = require('jsonwebtoken'); -const mockLogger = { warn: jest.fn(), error: jest.fn(), debug: jest.fn() }; -const mockGetUserById = jest.fn(); +const mockSetAuthTokens = jest.fn(() => Promise.resolve('auth-token')); +const mockDeleteAllUserSessions = jest.fn(() => Promise.resolve({ deletedCount: 0 })); const mockGetTOTPSecret = jest.fn(); const mockVerifyTOTP = jest.fn(); const mockVerifyBackupCode = jest.fn(); -const mockSetAuthTokens = jest.fn(); -jest.mock('@librechat/data-schemas', () => ({ logger: mockLogger })); +jest.mock('@librechat/data-schemas', () => ({ + logger: { error: jest.fn(), warn: jest.fn() }, +})); jest.mock('~/server/services/twoFactorService', () => ({ getTOTPSecret: (...args) => mockGetTOTPSecret(...args), verifyTOTP: (...args) => mockVerifyTOTP(...args), verifyBackupCode: (...args) => mockVerifyBackupCode(...args), + generateBackupCodes: (...args) => store.generateBackupCodes(...args), })); jest.mock('~/server/services/AuthService', () => ({ @@ -20,47 +22,210 @@ jest.mock('~/server/services/AuthService', () => ({ })); jest.mock('~/models', () => ({ - getUserById: (...args) => mockGetUserById(...args), + getUserById: (...args) => store.getUserById(...args), + updateTwoFactorEnrollment: (...args) => store.updateTwoFactorEnrollment(...args), + deleteAllUserSessions: (...args) => mockDeleteAllUserSessions(...args), })); -const { verify2FAWithTempToken } = require('./TwoFactorAuthController'); +const ELIGIBLE_PROVIDERS = new Set(['local', 'ldap']); -const USER_ID = '65f0c1b2c3d4e5f6a7b8c9d0'; -const SECRET = 'test-jwt-secret'; - -const buildRes = () => { - const res = {}; - res.status = jest.fn(() => res); - res.json = jest.fn(() => res); - return res; +/** + * Minimal in-memory user store with the same compare-and-swap semantics as the Mongo-backed + * `updateTwoFactorEnrollment`, so the controller chain is exercised against real lifecycle state. + */ +const store = { + doc: null, + codeCounter: 0, + reset(overrides = {}) { + this.codeCounter = 0; + this.doc = { + _id: 'user-1', + email: 'user@example.com', + password: 'password-hash', + provider: 'local', + /** + * These queries select with `+field` tokens only, which leaves Mongoose no projection to + * send, so the stored document arrives whole. The session records ride along with it. + */ + refreshToken: [{ refreshToken: 'live-session-token' }], + twoFactorEnabled: false, + totpSecret: null, + backupCodes: [], + pendingTotpSecret: 'encrypted-secret', + pendingBackupCodes: [{ codeHash: 'staged-hash', used: false }], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + ...overrides, + }; + }, + async getUserById() { + return this.doc ? { ...this.doc } : null; + }, + async generateBackupCodes() { + this.codeCounter += 1; + return { + plainCodes: [`plain-${this.codeCounter}`], + codeObjects: [{ codeHash: `hash-${this.codeCounter}`, used: false, usedAt: null }], + }; + }, + async updateTwoFactorEnrollment(_userId, guard, update) { + if (this.doc.twoFactorEnabled) { + return null; + } + if (this.doc.provider != null && !ELIGIBLE_PROVIDERS.has(this.doc.provider)) { + return null; + } + const matches = Object.entries(guard).every( + ([key, value]) => JSON.stringify(this.doc[key] ?? null) === JSON.stringify(value ?? null), + ); + if (!matches) { + return null; + } + this.doc = { ...this.doc, ...update }; + return { ...this.doc }; + }, }; -/** Signs a real temp token so `iat` is genuine rather than hand-stamped. */ -const tempTokenFor = (userId) => jwt.sign({ userId }, SECRET, { expiresIn: '5m' }); +const { + verify2FAWithTempToken, + confirm2FASetupWithTempToken, + acknowledge2FASetup, + finalize2FASetup, +} = require('./TwoFactorAuthController'); +const { + generateTwoFactorLoginChallengeToken, + verifyTwoFactorSetupAcknowledgementToken, + verifyTwoFactorSetupFinalizationToken, +} = require('@librechat/api'); + +function createResponse() { + return { + status: jest.fn().mockReturnThis(), + json: jest.fn().mockReturnThis(), + clearCookie: jest.fn().mockReturnThis(), + }; +} + +/** Drives the request pipeline the routes wire up: credential validation, then the controller. */ +async function runAcknowledge(acknowledgementToken) { + const credential = verifyTwoFactorSetupAcknowledgementToken( + acknowledgementToken, + process.env.JWT_SECRET, + ); + const req = { + user: credential ? { id: credential.userId } : undefined, + twoFactorEnrollmentNonce: credential?.nonce, + body: { acknowledgementToken }, + }; + const res = createResponse(); + await acknowledge2FASetup(req, res); + return res; +} + +async function runFinalize(finalizationToken) { + const credential = verifyTwoFactorSetupFinalizationToken( + finalizationToken, + process.env.JWT_SECRET, + ); + const req = { + user: credential ? { id: credential.userId } : undefined, + twoFactorEnrollmentNonce: credential?.nonce, + body: { finalizationToken }, + }; + const res = createResponse(); + await finalize2FASetup(req, res); + return res; +} + +async function runConfirm(token = '123456') { + const req = { user: { id: 'user-1' }, body: { token } }; + const res = createResponse(); + await confirm2FASetupWithTempToken(req, res); + return res; +} + +const jsonPayload = (res) => res.json.mock.calls[0][0]; + +const originalSecret = process.env.JWT_SECRET; +const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; beforeEach(() => { jest.clearAllMocks(); - process.env.JWT_SECRET = SECRET; - mockGetTOTPSecret.mockResolvedValue('totp-secret'); + process.env.JWT_SECRET = 'jwt-secret'; + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + mockGetTOTPSecret.mockResolvedValue('plain-secret'); mockVerifyTOTP.mockResolvedValue(true); - mockSetAuthTokens.mockResolvedValue('auth-token'); + store.reset(); }); -describe('verify2FAWithTempToken credential-change cutoff', () => { - const userDoc = (overrides = {}) => ({ - _id: { toString: () => USER_ID }, - twoFactorEnabled: true, - totpSecret: 'totp-secret', - ...overrides, +afterAll(() => { + if (originalSecret === undefined) { + delete process.env.JWT_SECRET; + } else { + process.env.JWT_SECRET = originalSecret; + } + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } +}); + +/** The recheck after minting is a read like any other, and it can fail after the cookies are set. */ +const failRecheckAfterMint = () => + mockSetAuthTokens.mockImplementationOnce(async () => { + jest.spyOn(store, 'getUserById').mockRejectedValueOnce(new Error('database unavailable')); + return 'auth-token'; }); - it('rejects a temp token minted before the credentials changed', async () => { - const tempToken = tempTokenFor(USER_ID); - /** Stamp the reset a minute into the future so the token unambiguously predates it. */ - mockGetUserById.mockResolvedValue( - userDoc({ credentialsChangedAt: new Date(Date.now() + 60_000) }), +describe('verify2FAWithTempToken', () => { + beforeEach(() => { + store.reset({ twoFactorEnabled: true, totpSecret: 'encrypted-secret' }); + }); + + it('accepts a normal login challenge token and creates the app session', async () => { + const tempToken = jwt.sign( + { userId: 'user-1', purpose: 'login_2fa_challenge' }, + process.env.JWT_SECRET, ); - const res = buildRes(); + const req = { body: { tempToken, token: '123456' } }; + const res = createResponse(); + + await verify2FAWithTempToken(req, res); + + expect(mockSetAuthTokens).toHaveBeenCalledWith('user-1', res, null, req); + expect(res.status).toHaveBeenCalledWith(200); + }); + + it('refuses a federated password challenge under enforcement', async () => { + store.reset({ provider: 'openid', twoFactorEnabled: true, totpSecret: 'encrypted-secret' }); + const tempToken = jwt.sign( + { userId: 'user-1', purpose: 'login_2fa_challenge' }, + process.env.JWT_SECRET, + ); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(jsonPayload(res)).toEqual({ + code: 'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED', + message: 'Sign in with your identity provider to continue.', + }); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it.each([ + 'required_2fa_setup', + 'required_2fa_acknowledgement', + 'required_2fa_finalization', + undefined, + ])('rejects a %s token before creating a session', async (purpose) => { + const claims = purpose + ? { userId: 'user-1', purpose, nonce: 'nonce' } + : { userId: 'user-1', nonce: 'nonce' }; + const tempToken = jwt.sign(claims, process.env.JWT_SECRET); + const res = createResponse(); await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); @@ -68,27 +233,459 @@ describe('verify2FAWithTempToken credential-change cutoff', () => { expect(mockSetAuthTokens).not.toHaveBeenCalled(); }); - it('accepts a temp token minted after the credentials changed', async () => { - const tempToken = tempTokenFor(USER_ID); - mockGetUserById.mockResolvedValue( - userDoc({ credentialsChangedAt: new Date(Date.now() - 60_000) }), + it('strips every secret and enrollment nonce from the session response', async () => { + const tempToken = jwt.sign( + { userId: 'user-1', purpose: 'login_2fa_challenge' }, + process.env.JWT_SECRET, ); - const res = buildRes(); + const res = createResponse(); await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); - expect(res.status).toHaveBeenCalledWith(200); - expect(mockSetAuthTokens).toHaveBeenCalled(); + expect(jsonPayload(res).user).toEqual({ + _id: 'user-1', + id: 'user-1', + email: 'user@example.com', + provider: 'local', + twoFactorEnabled: true, + }); }); - it('accepts a temp token when the account never changed credentials', async () => { - const tempToken = tempTokenFor(USER_ID); - mockGetUserById.mockResolvedValue(userDoc()); - const res = buildRes(); + /** + * The challenge buys a session without presenting the password again, so recovery has to reach + * it: redeeming one minted beforehand would hand back exactly the access `deleteAllUserSessions` + * had just revoked. + */ + it('refuses a challenge minted before a password reset', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + store.doc.credentialsChangedAt = new Date(Date.now() + 1000); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('keeps a challenge minted after a password reset', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + store.doc.credentialsChangedAt = new Date(Date.now() - 60_000); + const res = createResponse(); await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); expect(res.status).toHaveBeenCalledWith(200); - expect(mockSetAuthTokens).toHaveBeenCalled(); + expect(mockSetAuthTokens).toHaveBeenCalledTimes(1); + }); + + /** `iat` cannot separate these two, so the millisecond claim is what decides both cases. */ + it('orders the challenge against a reset landing in the same second', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + const { issuedAtMs } = jwt.decode(tempToken); + + store.doc.credentialsChangedAt = new Date(issuedAtMs - 1); + const accepted = createResponse(); + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, accepted); + expect(accepted.status).toHaveBeenCalledWith(200); + + store.doc.credentialsChangedAt = new Date(issuedAtMs); + const refused = createResponse(); + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, refused); + expect(refused.status).toHaveBeenCalledWith(401); + }); + + it('surrenders the resetting second for a challenge minted before the claim existed', async () => { + const issuedAt = Math.floor(Date.now() / 1000); + const tempToken = jwt.sign( + { userId: 'user-1', purpose: 'login_2fa_challenge', iat: issuedAt }, + process.env.JWT_SECRET, + ); + store.doc.credentialsChangedAt = new Date(issuedAt * 1000 + 500); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + /** + * Verifying the factor is a decrypt and a comparison, so recovery can land inside it. The session + * minted afterwards postdates `credentialsChangedAt`, which is the one thing the cutoff cannot retire, + * and it is created after recovery has already swept the sessions away. + */ + describe('a password reset landing mid-verification', () => { + const resetDuring = (mock) => + mock.mockImplementationOnce(async () => { + store.doc.credentialsChangedAt = new Date(Date.now() + 1000); + return true; + }); + + it('withdraws the session it had already minted for a TOTP code', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + resetDuring(mockVerifyTOTP); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(mockSetAuthTokens).toHaveBeenCalledTimes(1); + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-1' }); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.clearCookie).toHaveBeenCalledWith('token_provider'); + expect(res.status).toHaveBeenCalledWith(401); + expect(jsonPayload(res)).toEqual({ message: 'Invalid or expired temporary token' }); + }); + + /** Backup codes are the slower comparison of the two, so the window is wider here. */ + it('withdraws the session it had already minted for a backup code', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + resetDuring(mockVerifyBackupCode); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, backupCode: 'backup-1' } }, res); + + expect(mockSetAuthTokens).toHaveBeenCalledTimes(1); + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-1' }); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('withdraws the minted session when the recheck cannot complete', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + mockVerifyTOTP.mockResolvedValueOnce(true); + failRecheckAfterMint(); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-1' }); + expect(mockDeleteAllUserSessions.mock.invocationCallOrder[0]).toBeGreaterThan( + mockSetAuthTokens.mock.invocationCallOrder[0], + ); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.status).toHaveBeenCalledWith(500); + }); + + it('leaves a verification no reset raced through alone', async () => { + const tempToken = generateTwoFactorLoginChallengeToken('user-1', process.env.JWT_SECRET); + const res = createResponse(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockDeleteAllUserSessions).not.toHaveBeenCalled(); + }); + }); +}); + +describe('confirm2FASetupWithTempToken', () => { + it('returns deliverable codes and an acknowledgement credential without a session', async () => { + const res = await runConfirm(); + + expect(res.status).toHaveBeenCalledWith(200); + expect(jsonPayload(res).backupCodes).toEqual(['plain-1']); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + expect(store.doc.twoFactorEnabled).toBe(false); + expect(store.doc.totpSecret).toBeNull(); + expect(store.doc.pendingBackupCodes).toEqual([ + { codeHash: 'hash-1', used: false, usedAt: null }, + ]); + expect( + verifyTwoFactorSetupAcknowledgementToken( + jsonPayload(res).acknowledgementToken, + process.env.JWT_SECRET, + ), + ).toEqual({ userId: 'user-1', nonce: expect.any(String) }); + }); + + it('is retryable after a lost response, rotating codes and retiring the old credential', async () => { + const first = await runConfirm(); + const second = await runConfirm(); + + expect(jsonPayload(second).backupCodes).toEqual(['plain-2']); + expect(jsonPayload(second).acknowledgementToken).not.toBe( + jsonPayload(first).acknowledgementToken, + ); + + const staleAcknowledgement = await runAcknowledge(jsonPayload(first).acknowledgementToken); + + expect(staleAcknowledgement.status).toHaveBeenCalledWith(400); + expect(store.doc.twoFactorEnabled).toBe(false); + }); + + it('does not issue auth tokens when the TOTP is wrong', async () => { + mockVerifyTOTP.mockResolvedValue(false); + + const res = await runConfirm('000000'); + + expect(res.status).toHaveBeenCalledWith(400); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + expect(store.doc.twoFactorAcknowledgementNonceHash).toBeNull(); + }); + + it('rejects requests without a validated setup user', async () => { + const res = createResponse(); + + await confirm2FASetupWithTempToken({ body: { token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); +}); + +describe('acknowledge2FASetup', () => { + it('exchanges a one-time acknowledgement nonce for a finalization credential', async () => { + const confirmed = await runConfirm(); + + const res = await runAcknowledge(jsonPayload(confirmed).acknowledgementToken); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + expect(store.doc.twoFactorEnabled).toBe(false); + expect(store.doc.twoFactorAcknowledgementNonceHash).toBeNull(); + expect( + verifyTwoFactorSetupFinalizationToken( + jsonPayload(res).finalizationToken, + process.env.JWT_SECRET, + ), + ).toEqual({ userId: 'user-1', nonce: expect.any(String) }); + }); + + it('rejects a replayed acknowledgement credential without minting anything', async () => { + const confirmed = await runConfirm(); + await runAcknowledge(jsonPayload(confirmed).acknowledgementToken); + + const replay = await runAcknowledge(jsonPayload(confirmed).acknowledgementToken); + + expect(replay.status).toHaveBeenCalledWith(400); + expect(jsonPayload(replay)).not.toHaveProperty('finalizationToken'); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects acknowledgement without a validated identity', async () => { + const res = createResponse(); + + await acknowledge2FASetup({ body: {} }, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); +}); + +describe('finalize2FASetup', () => { + async function reachFinalization() { + const confirmed = await runConfirm(); + const acknowledged = await runAcknowledge(jsonPayload(confirmed).acknowledgementToken); + return jsonPayload(acknowledged).finalizationToken; + } + + it.each(['local', 'ldap', undefined])( + 'promotes an eligible %s enrollment and only then creates the session', + async (provider) => { + store.reset({ provider }); + const finalizationToken = await reachFinalization(); + + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + + const res = await runFinalize(finalizationToken); + + expect(mockSetAuthTokens).toHaveBeenCalledWith('user-1', res, null, expect.any(Object)); + expect(store.doc).toMatchObject({ + twoFactorEnabled: true, + totpSecret: 'encrypted-secret', + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + /** Dates the tokens issued before enrollment, so it is stamped but never published. */ + twoFactorEnrolledAt: expect.any(Date), + }); + expect(jsonPayload(res)).toEqual({ + token: 'auth-token', + user: { + _id: 'user-1', + id: 'user-1', + email: 'user@example.com', + provider, + twoFactorEnabled: true, + }, + }); + }, + ); + + it('revokes pre-enrollment sessions before minting the enrolled one', async () => { + const finalizationToken = await reachFinalization(); + + await runFinalize(finalizationToken); + + expect(mockDeleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-1' }); + /** Revoking after minting would drop the session this response hands back. */ + expect(mockDeleteAllUserSessions.mock.invocationCallOrder[0]).toBeLessThan( + mockSetAuthTokens.mock.invocationCallOrder[0], + ); + }); + + it('withdraws the enrolled session when the recheck cannot complete', async () => { + const finalizationToken = await reachFinalization(); + failRecheckAfterMint(); + + const res = await runFinalize(finalizationToken); + + expect(mockDeleteAllUserSessions).toHaveBeenCalledTimes(2); + expect(mockDeleteAllUserSessions.mock.invocationCallOrder[1]).toBeGreaterThan( + mockSetAuthTokens.mock.invocationCallOrder[0], + ); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.status).toHaveBeenCalledWith(500); + }); + + it('leaves existing sessions alone when finalization is rejected', async () => { + const finalizationToken = await reachFinalization(); + store.doc.pendingTotpSecret = null; + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(400); + expect(mockDeleteAllUserSessions).not.toHaveBeenCalled(); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects a replayed finalization credential without a second session', async () => { + const finalizationToken = await reachFinalization(); + await runFinalize(finalizationToken); + mockSetAuthTokens.mockClear(); + + const replay = await runFinalize(finalizationToken); + + expect(replay.status).toHaveBeenCalledWith(400); + expect(jsonPayload(replay)).not.toHaveProperty('token'); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects a finalization credential retired by a later confirmation', async () => { + const finalizationToken = await reachFinalization(); + await runConfirm(); + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(400); + expect(store.doc.twoFactorEnabled).toBe(false); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects a user whose provider becomes federated before finalization', async () => { + const finalizationToken = await reachFinalization(); + store.doc.provider = 'openid'; + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(400); + expect(store.doc.twoFactorEnabled).toBe(false); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects finalization when global enforcement is disabled', async () => { + const finalizationToken = await reachFinalization(); + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(400); + expect(store.doc.twoFactorEnabled).toBe(false); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('withdraws the session when password recovery lands after the promotion', async () => { + const finalizationToken = await reachFinalization(); + /** + * Recovery cannot be staged up front: clearing the pending enrollment first would fail the + * compare-and-swap, which is the half already covered. Landing it while the hand-off runs is + * the ordering that leaves a token postdating the cutoff. + */ + mockSetAuthTokens.mockImplementationOnce(async () => { + store.doc.credentialsChangedAt = new Date(Date.now() + 1000); + return 'auth-token'; + }); + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(401); + expect(jsonPayload(res)).not.toHaveProperty('token'); + expect(res.clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(res.clearCookie).toHaveBeenCalledWith('token_provider'); + /** The session minted in that gap has to go, not just the token this response withholds. */ + expect(mockDeleteAllUserSessions).toHaveBeenCalledTimes(2); + expect(mockDeleteAllUserSessions.mock.invocationCallOrder[1]).toBeGreaterThan( + mockSetAuthTokens.mock.invocationCallOrder[0], + ); + }); + + it('hands off normally when the account was recovered before the enrollment', async () => { + store.reset({ credentialsChangedAt: new Date(Date.now() - 60_000) }); + const finalizationToken = await reachFinalization(); + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(200); + expect(jsonPayload(res)).toHaveProperty('token', 'auth-token'); + expect(mockDeleteAllUserSessions).toHaveBeenCalledTimes(1); + }); + + it('rejects finalization once the pending setup has been cleared', async () => { + const finalizationToken = await reachFinalization(); + store.doc.pendingTotpSecret = null; + store.doc.pendingBackupCodes = []; + + const res = await runFinalize(finalizationToken); + + expect(res.status).toHaveBeenCalledWith(400); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('rejects finalization without a validated identity', async () => { + const res = createResponse(); + + await finalize2FASetup({ body: {} }, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockSetAuthTokens).not.toHaveBeenCalled(); + }); + + it('never leaks secrets or enrollment nonces in the session response', async () => { + const finalizationToken = await reachFinalization(); + + const res = await runFinalize(finalizationToken); + const { user } = jsonPayload(res); + + for (const field of [ + 'password', + 'totpSecret', + 'backupCodes', + 'refreshToken', + 'pendingTotpSecret', + 'pendingBackupCodes', + 'twoFactorAcknowledgementNonceHash', + 'twoFactorFinalizationNonceHash', + ]) { + expect(user).not.toHaveProperty(field); + } + }); + + /** + * Naming the secrets one by one only ever catches the secrets already thought of, and this + * response is built from an unprojected document. Pinning the whole shape is what keeps a field + * added to the schema later from arriving here unannounced. + */ + it('sends only allowlisted fields in the session response', async () => { + const finalizationToken = await reachFinalization(); + + const res = await runFinalize(finalizationToken); + + expect(jsonPayload(res).user).toEqual({ + _id: 'user-1', + id: 'user-1', + email: 'user@example.com', + provider: 'local', + twoFactorEnabled: true, + }); }); }); diff --git a/api/server/middleware/__tests__/requireJwtAuth.spec.js b/api/server/middleware/__tests__/requireJwtAuth.spec.js index bbadd5fb04..7f81760181 100644 --- a/api/server/middleware/__tests__/requireJwtAuth.spec.js +++ b/api/server/middleware/__tests__/requireJwtAuth.spec.js @@ -14,6 +14,12 @@ const jwt = require('jsonwebtoken'); let mockPassportError = null; let mockRegisteredStrategies = new Set(['jwt']); +/** The post-mint retirement read; defaults to an account no recovery has touched. */ +let mockGetUserById = jest.fn(async () => ({})); + +jest.mock('~/models', () => ({ + getUserById: (...args) => mockGetUserById(...args), +})); jest.mock('passport', () => ({ _strategy: jest.fn((strategy) => (mockRegisteredStrategies.has(strategy) ? {} : undefined)), @@ -44,6 +50,7 @@ jest.mock('@librechat/data-schemas', () => { getUserId: () => tenantStorage.getStore()?.userId, getRequestId: () => tenantStorage.getStore()?.requestId, logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() }, + runAsSystem: (fn) => tenantStorage.run({ tenantId: '__SYSTEM__' }, fn), tenantStorage, }; }); @@ -68,6 +75,13 @@ jest.mock('@librechat/api', () => { normalizeContextValue(req.headers?.['x-correlation-id']); return { isEnabled: jest.fn(() => false), + createRequiredTwoFactorGate: actualApi.createRequiredTwoFactorGate, + clearCloudFrontCookies: jest.fn(), + generateTwoFactorSetupToken: jest.fn(() => 'setup-token'), + isTwoFactorEnrollmentRequired: jest.fn(() => false), + /** Real dating logic: the ordering these tests exercise is the whole point. */ + isTokenRetired: actualApi.isTokenRetired, + TOKEN_RETIREMENT_FIELDS: actualApi.TOKEN_RETIREMENT_FIELDS, recordRumProxyRequest: jest.fn(), getAuthFailureReasonCategory: actualApi.getAuthFailureReasonCategory, buildSafeAuthLogContext: actualApi.buildSafeAuthLogContext, @@ -106,8 +120,11 @@ const { requireRumProxyAuth } = requireJwtAuth; const { getTenantId, getUserId, logger } = require('@librechat/data-schemas'); const { isEnabled, + clearCloudFrontCookies, maybeRefreshCloudFrontAuthCookiesMiddleware, recordRumProxyRequest, + generateTwoFactorSetupToken, + isTwoFactorEnrollmentRequired, } = require('@librechat/api'); const passport = require('passport'); @@ -129,6 +146,9 @@ function mockRes() { }; } +/** The enrollment policy re-reads the retirement cutoff, so its response lands a tick later. */ +const flushPolicy = () => new Promise((resolve) => setImmediate(resolve)); + /** Runs requireJwtAuth and returns the tenantId observed inside next(). */ function runAuth(user) { return new Promise((resolve) => { @@ -152,7 +172,11 @@ describe('requireJwtAuth tenant context chaining', () => { afterEach(() => { mockPassportError = null; mockRegisteredStrategies = new Set(['jwt']); + mockGetUserById = jest.fn(async () => ({})); isEnabled.mockReturnValue(false); + isTwoFactorEnrollmentRequired.mockReturnValue(false); + generateTwoFactorSetupToken.mockClear(); + clearCloudFrontCookies.mockClear(); maybeRefreshCloudFrontAuthCookiesMiddleware.mockClear(); logger.debug.mockClear(); logger.info.mockClear(); @@ -200,6 +224,162 @@ describe('requireJwtAuth tenant context chaining', () => { expect(next).toHaveBeenCalled(); }); + it('blocks protected API access for unenrolled local users', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { method: 'GET', baseUrl: '/api/convos', path: '/' }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + await flushPolicy(); + + expect(generateTwoFactorSetupToken).toHaveBeenCalledWith('user-123', process.env.JWT_SECRET); + expect(clearCloudFrontCookies).toHaveBeenCalledWith(res, { + userId: 'user-123', + tenantId: undefined, + storageRegion: undefined, + }); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ + code: 'TWO_FACTOR_ENROLLMENT_REQUIRED', + twoFAPending: true, + twoFASetupRequired: true, + tempToken: 'setup-token', + }); + expect(next).not.toHaveBeenCalled(); + }); + + it('allows only the exact logout route through the enrollment policy', () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { method: 'POST', baseUrl: '/api/auth', path: '/logout' }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(next).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['a trailing slash', { method: 'POST', baseUrl: '/api/auth', path: '/logout/' }], + ['an uppercase path', { method: 'POST', baseUrl: '/API/AUTH', path: '/LOGOUT' }], + ['mixed case and a trailing slash', { method: 'POST', baseUrl: '/Api/Auth', path: '/Logout/' }], + ])('allows the logout route through the enrollment policy with %s', (_label, requestShape) => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + requestShape, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + + expect(generateTwoFactorSetupToken).not.toHaveBeenCalled(); + expect(res.status).not.toHaveBeenCalledWith(403); + expect(next).toHaveBeenCalledTimes(1); + }); + + it('still blocks a non-logout route that merely ends in a slash', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { method: 'POST', baseUrl: '/api/auth', path: '/logout/extra' }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + await flushPolicy(); + + expect(res.status).toHaveBeenCalledWith(403); + expect(next).not.toHaveBeenCalled(); + }); + + it('withdraws the setup token when recovery lands between the strategy read and the mint', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const issuedAtMs = Date.now(); + /** The reset commits after the bearer was minted, so it revokes the credential in flight. */ + mockGetUserById = jest.fn(async () => ({ credentialsChangedAt: new Date(issuedAtMs + 1000) })); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { + method: 'GET', + baseUrl: '/api/convos', + path: '/', + headers: { + authorization: `Bearer ${jwt.sign({ id: 'user-123', issuedAtMs }, jwtSecret)}`, + }, + }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + await flushPolicy(); + + expect(mockGetUserById).toHaveBeenCalledWith( + 'user-123', + 'twoFactorEnrolledAt credentialsChangedAt', + ); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Unauthorized' }); + expect(res.json).not.toHaveBeenCalledWith( + expect.objectContaining({ tempToken: 'setup-token' }), + ); + expect(next).not.toHaveBeenCalled(); + }); + + it('still hands back a setup token when no recovery raced the request', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + const issuedAtMs = Date.now(); + mockGetUserById = jest.fn(async () => ({ credentialsChangedAt: new Date(issuedAtMs - 1000) })); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { + method: 'GET', + baseUrl: '/api/convos', + path: '/', + headers: { + authorization: `Bearer ${jwt.sign({ id: 'user-123', issuedAtMs }, jwtSecret)}`, + }, + }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + await flushPolicy(); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ tempToken: 'setup-token' })); + expect(next).not.toHaveBeenCalled(); + }); + + it('withdraws the setup token for a bearer that carries no datable claim', async () => { + isTwoFactorEnrollmentRequired.mockReturnValue(true); + mockGetUserById = jest.fn(async () => ({ credentialsChangedAt: new Date() })); + const req = mockReq( + { id: 'user-123', provider: 'local', twoFactorEnabled: false }, + { method: 'GET', baseUrl: '/api/convos', path: '/', headers: {} }, + ); + const res = mockRes(); + const next = jest.fn(); + + requireJwtAuth(req, res, next); + await flushPolicy(); + + expect(res.status).toHaveBeenCalledWith(401); + expect(next).not.toHaveBeenCalled(); + }); + it('refreshes CloudFront auth cookies inside the request context', () => { let observedContext; maybeRefreshCloudFrontAuthCookiesMiddleware.mockImplementationOnce( diff --git a/api/server/middleware/blockRetiredSetupToken.js b/api/server/middleware/blockRetiredSetupToken.js new file mode 100644 index 0000000000..51005f4ba5 --- /dev/null +++ b/api/server/middleware/blockRetiredSetupToken.js @@ -0,0 +1,4 @@ +const { createBlockRetiredSetupToken } = require('@librechat/api'); +const { getUserById } = require('~/models'); + +module.exports = createBlockRetiredSetupToken({ getUserById }); diff --git a/api/server/middleware/index.js b/api/server/middleware/index.js index 852b23b7f6..774ee44a2b 100644 --- a/api/server/middleware/index.js +++ b/api/server/middleware/index.js @@ -1,5 +1,8 @@ +const blockRetiredSetupToken = require('./blockRetiredSetupToken'); const validatePasswordReset = require('./validatePasswordReset'); const setTwoFactorTempUser = require('./setTwoFactorTempUser'); +const { setTwoFactorAcknowledgementTempUser, setTwoFactorFinalizationTempUser } = + setTwoFactorTempUser; const validateRegistration = require('./validateRegistration'); const buildEndpointOption = require('./buildEndpointOption'); const validateEmailLogin = require('./validateEmailLogin'); @@ -50,6 +53,9 @@ module.exports = { requireJwtAuth, requireRumProxyAuth, setTwoFactorTempUser, + setTwoFactorAcknowledgementTempUser, + setTwoFactorFinalizationTempUser, + blockRetiredSetupToken, checkInviteUser, requireLdapAuth, requireLocalAuth, diff --git a/api/server/middleware/limiters/index.js b/api/server/middleware/limiters/index.js index 45397e9f1d..757afc6018 100644 --- a/api/server/middleware/limiters/index.js +++ b/api/server/middleware/limiters/index.js @@ -21,6 +21,8 @@ const passkeyStepUpLimiter = require('./passkeyStepUpLimiter'); const verifyEmailSubmissionLimiter = require('./verifyEmailSubmissionLimiter'); const resetPasswordSubmissionLimiter = require('./resetPasswordSubmissionLimiter'); +const { twoFactorSetupLimiter } = twoFactorTempLimiter; + module.exports = { ...uploadLimiters, ...importLimiters, @@ -43,4 +45,5 @@ module.exports = { verifyEmailSubmissionLimiter, resetPasswordSubmissionLimiter, twoFactorTempLimiter, + twoFactorSetupLimiter, }; diff --git a/api/server/middleware/limiters/twoFactorTempLimiter.js b/api/server/middleware/limiters/twoFactorTempLimiter.js index 97d0861af6..ffbe1328be 100644 --- a/api/server/middleware/limiters/twoFactorTempLimiter.js +++ b/api/server/middleware/limiters/twoFactorTempLimiter.js @@ -1,101 +1,12 @@ -const jwt = require('jsonwebtoken'); -const { createHash } = require('crypto'); -const rateLimit = require('express-rate-limit'); -const { ViolationTypes } = require('librechat-data-provider'); -const { limiterCache, removePorts } = require('@librechat/api'); +const { createTwoFactorLimiters, limiterCache, removePorts } = require('@librechat/api'); const { logViolation } = require('~/cache'); -const { - LOGIN_WINDOW = 5, - LOGIN_MAX = 7, - LOGIN_VIOLATION_SCORE, - TWO_FACTOR_TEMP_WINDOW = LOGIN_WINDOW, - TWO_FACTOR_TEMP_MAX = LOGIN_MAX, - TWO_FACTOR_TEMP_VIOLATION_SCORE, -} = process.env; -const windowMs = TWO_FACTOR_TEMP_WINDOW * 60 * 1000; -const max = TWO_FACTOR_TEMP_MAX; -const score = TWO_FACTOR_TEMP_VIOLATION_SCORE ?? LOGIN_VIOLATION_SCORE; -const windowInMinutes = windowMs / 60000; -const message = `Too many verification attempts, please try again after ${windowInMinutes} minutes.`; - -const hashLimiterKey = (value) => createHash('sha256').update(value).digest('hex'); - -const getUserLimiterKey = (req) => { - const userId = req.user?.id ?? req.user?._id; - if (userId) { - return `user:${userId.toString()}`; - } - - const tempToken = req.body?.tempToken; - if (typeof tempToken === 'string' && tempToken) { - return `temp:${hashLimiterKey(tempToken)}`; - } - - const ip = removePorts(req); - return ip ? `ip:${ip}` : 'ip:unknown'; -}; - -const getTempTokenUserId = (tempToken) => { - if (!tempToken) { - return null; - } - - try { - const payload = jwt.verify(tempToken, process.env.JWT_SECRET); - return payload?.userId ?? null; - } catch { - return null; - } -}; - -const createHandler = (limiter) => async (req, res) => { - const type = ViolationTypes.LOGINS; - const errorMessage = { - type, - max, - limiter, - windowInMinutes, - }; - - const userId = getTempTokenUserId(req.body?.tempToken); - if (userId && !req.user) { - req.user = { id: userId }; - } else if (userId && !req.user.id && !req.user._id) { - req.user.id = userId; - } - - await logViolation(req, res, type, errorMessage, score); - return res.status(429).json({ message }); -}; - -const ipLimiterOptions = { - windowMs, - max, - handler: createHandler('ip'), - keyGenerator: removePorts, - store: limiterCache('two_factor_temp_limiter'), -}; - -const userLimiterOptions = { - windowMs, - max, - handler: createHandler('user'), - keyGenerator: getUserLimiterKey, - store: limiterCache('two_factor_temp_user_limiter'), -}; - -const twoFactorTempIpLimiter = rateLimit(ipLimiterOptions); -const twoFactorTempUserLimiter = rateLimit(userLimiterOptions); - -const twoFactorTempLimiter = (req, res, next) => { - twoFactorTempIpLimiter(req, res, (err) => { - if (err) { - return next(err); - } - - return twoFactorTempUserLimiter(req, res, next); - }); -}; +const { twoFactorTempLimiter, twoFactorSetupLimiter } = createTwoFactorLimiters({ + env: process.env, + limiterCache, + removePorts, + logViolation, +}); module.exports = twoFactorTempLimiter; +module.exports.twoFactorSetupLimiter = twoFactorSetupLimiter; diff --git a/api/server/middleware/limiters/twoFactorTempLimiter.test.js b/api/server/middleware/limiters/twoFactorTempLimiter.test.js index 37b06c7fdb..da2965c2c5 100644 --- a/api/server/middleware/limiters/twoFactorTempLimiter.test.js +++ b/api/server/middleware/limiters/twoFactorTempLimiter.test.js @@ -1,25 +1,30 @@ const jwt = require('jsonwebtoken'); const express = require('express'); const request = require('supertest'); +const { createTwoFactorLimiters, createTwoFactorTempUser } = jest.requireActual('@librechat/api'); const originalEnv = process.env; const jwtSecret = 'test-two-factor-secret'; -const createToken = (userId) => - jwt.sign({ userId, twoFAPending: true }, jwtSecret, { expiresIn: '5m' }); +const createToken = (userId, purpose = 'login_2fa_challenge') => + jwt.sign({ userId, purpose }, jwtSecret, { expiresIn: '5m' }); -const createApp = () => { +const createApp = (max = '2', setupMax = '2') => { jest.resetModules(); process.env = { ...originalEnv, JWT_SECRET: jwtSecret, LOGIN_MAX: '2', LOGIN_WINDOW: '5', - TWO_FACTOR_TEMP_MAX: '2', + TWO_FACTOR_TEMP_MAX: max, TWO_FACTOR_TEMP_WINDOW: '5', + TWO_FACTOR_SETUP_MAX: setupMax, + TWO_FACTOR_SETUP_WINDOW: '5', }; jest.doMock('@librechat/api', () => ({ + createTwoFactorLimiters, + createTwoFactorTempUser, limiterCache: jest.fn(() => undefined), removePorts: (req) => req?.['ip'], })); @@ -28,7 +33,10 @@ const createApp = () => { })); const setTwoFactorTempUser = require('../setTwoFactorTempUser'); + const { setTwoFactorAcknowledgementTempUser, setTwoFactorFinalizationTempUser } = + setTwoFactorTempUser; const twoFactorTempLimiter = require('./twoFactorTempLimiter'); + const { twoFactorSetupLimiter } = twoFactorTempLimiter; const { logViolation } = require('~/cache'); const app = express(); @@ -37,6 +45,28 @@ const createApp = () => { app.post('/verify', setTwoFactorTempUser, twoFactorTempLimiter, (req, res) => res.status(204).end(), ); + app.post('/finalize', setTwoFactorFinalizationTempUser, twoFactorTempLimiter, (req, res) => + res.status(204).end(), + ); + app.post('/acknowledge', setTwoFactorAcknowledgementTempUser, twoFactorTempLimiter, (req, res) => + res.status(204).end(), + ); + /** Mirrors the production split: code checks on one quota, enrollment transitions on the other. */ + app.post('/setup', setTwoFactorTempUser, twoFactorSetupLimiter, (req, res) => + res.status(204).end(), + ); + app.post( + '/setup/acknowledge', + setTwoFactorAcknowledgementTempUser, + twoFactorSetupLimiter, + (req, res) => res.status(204).end(), + ); + app.post('/setup/confirm', setTwoFactorTempUser, twoFactorTempLimiter, (req, res) => + res.status(204).end(), + ); + app.post('/setup/finalize', setTwoFactorFinalizationTempUser, twoFactorSetupLimiter, (req, res) => + res.status(204).end(), + ); return { app, logViolation }; }; @@ -81,7 +111,7 @@ describe('twoFactorTempLimiter', () => { }); }); - it('keeps the existing source IP limit before the user limit', async () => { + it('keeps the source IP limit across valid challenge tokens for different users', async () => { const { app, logViolation } = createApp(); await request(app) @@ -108,4 +138,198 @@ describe('twoFactorTempLimiter', () => { windowInMinutes: 5, }); }); + + it('does not charge enrollment transitions against the shared code-attempt IP quota', async () => { + const { app, logViolation } = createApp('7', '20'); + const sourceIp = '198.51.100.10'; + + for (const userId of ['user-a', 'user-b']) { + const setupToken = createToken(userId, 'required_2fa_setup'); + const acknowledgementToken = createToken(userId, 'required_2fa_acknowledgement'); + const finalizationToken = createToken(userId, 'required_2fa_finalization'); + + await request(app) + .post('/setup') + .set('X-Forwarded-For', sourceIp) + .send({ tempToken: setupToken }) + .expect(204); + await request(app) + .post('/setup/confirm') + .set('X-Forwarded-For', sourceIp) + .send({ tempToken: setupToken, token: '000000' }) + .expect(204); + await request(app) + .post('/setup/acknowledge') + .set('X-Forwarded-For', sourceIp) + .send({ acknowledgementToken }) + .expect(204); + await request(app) + .post('/setup/finalize') + .set('X-Forwarded-For', sourceIp) + .send({ finalizationToken }) + .expect(204); + } + + expect(logViolation).not.toHaveBeenCalled(); + }); + + it.each([ + ['login challenge', 'tempToken', 'login_2fa_challenge', '/verify'], + ['required setup', 'tempToken', 'required_2fa_setup', '/verify'], + [ + 'required acknowledgement', + 'acknowledgementToken', + 'required_2fa_acknowledgement', + '/acknowledge', + ], + ['required finalization', 'finalizationToken', 'required_2fa_finalization', '/finalize'], + ])('applies the same per-user limit to a %s token', async (_name, field, purpose, route) => { + const { app, logViolation } = createApp(); + const token = createToken('user-shared', purpose); + + await request(app) + .post(route) + .set('X-Forwarded-For', '203.0.113.10') + .send({ [field]: token }) + .expect(204); + await request(app) + .post(route) + .set('X-Forwarded-For', '203.0.113.11') + .send({ [field]: token }) + .expect(204); + await request(app) + .post(route) + .set('X-Forwarded-For', '203.0.113.12') + .send({ [field]: token }) + .expect(429); + + expect(logViolation.mock.calls[0][0].user).toEqual({ id: 'user-shared' }); + }); + + it('binds finalization limiting to the finalization token when both fields are present', async () => { + const { app, logViolation } = createApp(); + const finalizationToken = createToken('finalization-user', 'required_2fa_finalization'); + + for (let attempt = 0; attempt < 2; attempt++) { + await request(app) + .post('/finalize') + .set('X-Forwarded-For', `203.0.113.${20 + attempt}`) + .send({ + tempToken: createToken(`decoy-${attempt}`), + finalizationToken, + }) + .expect(204); + } + + await request(app) + .post('/finalize') + .set('X-Forwarded-For', '203.0.113.22') + .send({ tempToken: createToken('decoy-2'), finalizationToken }) + .expect(429); + + expect(logViolation.mock.calls[0][0].user).toEqual({ id: 'finalization-user' }); + }); + + /** + * Sharing one quota let a handful of wrong codes strand a user who already held their backup + * codes: confirmation succeeded, then finalization was refused and nothing was ever promoted. + */ + it('keeps exhausted code attempts from blocking enrollment transitions', async () => { + const { app, logViolation } = createApp(); + const tempToken = createToken('split-user', 'required_2fa_setup'); + const finalizationToken = createToken('split-user', 'required_2fa_finalization'); + + await request(app) + .post('/setup/confirm') + .set('X-Forwarded-For', '203.0.113.40') + .send({ tempToken, token: '000000' }) + .expect(204); + await request(app) + .post('/setup/confirm') + .set('X-Forwarded-For', '203.0.113.41') + .send({ tempToken, token: '000001' }) + .expect(204); + await request(app) + .post('/setup/confirm') + .set('X-Forwarded-For', '203.0.113.42') + .send({ tempToken, token: '000002' }) + .expect(429); + + const finalized = await request(app) + .post('/setup/finalize') + .set('X-Forwarded-For', '203.0.113.43') + .send({ finalizationToken }) + .expect(204); + + expect(finalized.status).toBe(204); + /** Only the exhausted code attempt was a violation; finalization drew on its own budget. */ + expect(logViolation).toHaveBeenCalledTimes(1); + expect(logViolation.mock.calls[0][3]).toMatchObject({ limiter: 'user', max: '2' }); + }); + + it.each([ + ['acknowledge', 'acknowledgementToken'], + ['finalize', 'finalizationToken'], + ])( + 'keeps invalid %s credentials in one bucket despite rotating decoys and IPs', + async (route, field) => { + const { app, logViolation } = createApp(); + for (let attempt = 0; attempt < 3; attempt++) { + await request(app) + .post(`/${route}`) + .set('X-Forwarded-For', `203.0.113.${70 + attempt}`) + .send({ tempToken: `decoy-${attempt}`, [field]: 'invalid-enrollment-token' }) + .expect(attempt < 2 ? 204 : 429); + } + expect(logViolation.mock.calls[0][3]).toMatchObject({ limiter: 'user' }); + }, + ); + + it('still bounds the enrollment transition quota on its own budget', async () => { + const { app, logViolation } = createApp('7', '2'); + const finalizationToken = createToken('transition-user', 'required_2fa_finalization'); + + for (let attempt = 0; attempt < 2; attempt++) { + await request(app) + .post('/setup/finalize') + .set('X-Forwarded-For', `203.0.113.${50 + attempt}`) + .send({ finalizationToken }) + .expect(204); + } + + const response = await request(app) + .post('/setup/finalize') + .set('X-Forwarded-For', '203.0.113.52') + .send({ finalizationToken }) + .expect(429); + + expect(response.body).toEqual({ + message: 'Too many two-factor setup requests, please try again after 5 minutes.', + }); + expect(logViolation.mock.calls[0][0].user).toEqual({ id: 'transition-user' }); + }); + + it('binds acknowledgement limiting to the acknowledgement token when a decoy setup token is present', async () => { + const { app, logViolation } = createApp(); + const acknowledgementToken = createToken( + 'acknowledgement-user', + 'required_2fa_acknowledgement', + ); + + for (let attempt = 0; attempt < 2; attempt++) { + await request(app) + .post('/acknowledge') + .set('X-Forwarded-For', `203.0.113.${30 + attempt}`) + .send({ tempToken: createToken(`decoy-${attempt}`), acknowledgementToken }) + .expect(204); + } + + await request(app) + .post('/acknowledge') + .set('X-Forwarded-For', '203.0.113.32') + .send({ tempToken: createToken('decoy-2'), acknowledgementToken }) + .expect(429); + + expect(logViolation.mock.calls[0][0].user).toEqual({ id: 'acknowledgement-user' }); + }); }); diff --git a/api/server/middleware/optionalJwtAuth.js b/api/server/middleware/optionalJwtAuth.js index 853579415e..6dcf82e948 100644 --- a/api/server/middleware/optionalJwtAuth.js +++ b/api/server/middleware/optionalJwtAuth.js @@ -1,6 +1,12 @@ const cookies = require('cookie'); const passport = require('passport'); -const { isEnabled, tenantContextMiddleware } = require('@librechat/api'); +const { + isEnabled, + clearCloudFrontCookies, + continueAfterOptionalAuth, + tenantContextMiddleware, + isTwoFactorEnrollmentRequired, +} = require('@librechat/api'); const hasPassportStrategy = (strategy) => typeof passport._strategy === 'function' && passport._strategy(strategy) != null; @@ -20,9 +26,15 @@ const optionalJwtAuth = (req, res, next) => { return next(err); } if (user) { - req.user = user; - req.authStrategy = useOpenIdJwt ? 'openidJwt' : 'jwt'; - return tenantContextMiddleware(req, res, next); + return continueAfterOptionalAuth( + req, + res, + next, + user, + useOpenIdJwt ? 'openidJwt' : 'jwt', + tenantContextMiddleware, + { clearCloudFrontCookies, enrollmentRequired: isTwoFactorEnrollmentRequired }, + ); } next(); }; diff --git a/api/server/middleware/optionalJwtAuth.spec.js b/api/server/middleware/optionalJwtAuth.spec.js new file mode 100644 index 0000000000..2e8e755459 --- /dev/null +++ b/api/server/middleware/optionalJwtAuth.spec.js @@ -0,0 +1,73 @@ +const mockAuthenticate = jest.fn(); +const mockTenantContextMiddleware = jest.fn((_req, _res, next) => next()); +const mockIsTwoFactorEnrollmentRequired = jest.fn(() => false); +const mockClearCloudFrontCookies = jest.fn(); + +jest.mock('passport', () => ({ + _strategy: jest.fn(() => undefined), + authenticate: (...args) => mockAuthenticate(...args), +})); + +jest.mock('@librechat/api', () => ({ + continueAfterOptionalAuth: jest.requireActual('@librechat/api').continueAfterOptionalAuth, + isEnabled: jest.fn(() => false), + clearCloudFrontCookies: (...args) => mockClearCloudFrontCookies(...args), + isTwoFactorEnrollmentRequired: (...args) => mockIsTwoFactorEnrollmentRequired(...args), + tenantContextMiddleware: (...args) => mockTenantContextMiddleware(...args), +})); + +const optionalJwtAuth = require('./optionalJwtAuth'); + +const run = (user) => { + const req = { headers: {}, _mockUser: user }; + const res = {}; + const next = jest.fn(); + optionalJwtAuth(req, res, next); + return { req, res, next }; +}; + +describe('optionalJwtAuth', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockIsTwoFactorEnrollmentRequired.mockReturnValue(false); + mockAuthenticate.mockImplementation((_strategy, _options, callback) => { + return (req) => callback(null, req._mockUser ?? false); + }); + }); + + it('establishes authenticated context when enrollment is not required', () => { + const user = { id: 'viewer-1', provider: 'local', twoFactorEnabled: true }; + + const { req, next } = run(user); + + expect(req.user).toBe(user); + expect(req.authStrategy).toBe('jwt'); + expect(mockTenantContextMiddleware).toHaveBeenCalledTimes(1); + expect(next).toHaveBeenCalledTimes(1); + }); + + it('treats a viewer with incomplete required enrollment as unauthenticated', () => { + const user = { id: 'viewer-required', provider: 'local', twoFactorEnabled: false }; + mockIsTwoFactorEnrollmentRequired.mockReturnValue(true); + + const { req, res, next } = run(user); + + expect(req.user).toBeUndefined(); + expect(req.authStrategy).toBeUndefined(); + expect(mockClearCloudFrontCookies).toHaveBeenCalledWith(res, { + userId: 'viewer-required', + tenantId: undefined, + storageRegion: undefined, + }); + expect(mockTenantContextMiddleware).not.toHaveBeenCalled(); + expect(next).toHaveBeenCalledTimes(1); + }); + + it('continues anonymously when authentication does not resolve a user', () => { + const { req, next } = run(undefined); + + expect(req.user).toBeUndefined(); + expect(mockTenantContextMiddleware).not.toHaveBeenCalled(); + expect(next).toHaveBeenCalledTimes(1); + }); +}); diff --git a/api/server/middleware/optionalShareFileAuth.js b/api/server/middleware/optionalShareFileAuth.js index bebf087d20..6d17573af8 100644 --- a/api/server/middleware/optionalShareFileAuth.js +++ b/api/server/middleware/optionalShareFileAuth.js @@ -1,88 +1,22 @@ const cookie = require('cookie'); -const jwt = require('jsonwebtoken'); -const { isEnabled } = require('@librechat/api'); const { logger, runAsSystem } = require('@librechat/data-schemas'); -const { SystemRoles } = require('librechat-data-provider'); +const { + createOptionalShareFileAuth, + clearCloudFrontCookies, + isTwoFactorEnrollmentRequired, + isTokenRetired, + isEnabled, +} = require('@librechat/api'); const { getUserById, findSession } = require('~/models'); -const verifySignedUserId = (token) => { - try { - const payload = jwt.verify(token, process.env.JWT_REFRESH_SECRET); - return typeof payload?.id === 'string' ? payload.id : null; - } catch { - return null; - } -}; - -const getRefreshTokenUserId = async (token) => { - const userId = verifySignedUserId(token); - if (!userId) { - return null; - } - - const session = await runAsSystem(() => findSession({ userId, refreshToken: token })); - return session ? userId : null; -}; - -const getOpenIdUserId = (parsed, req) => { - if (parsed.token_provider !== 'openid' || !isEnabled(process.env.OPENID_REUSE_TOKENS)) { - return null; - } - - const sessionRefreshToken = req.session?.openidTokens?.refreshToken; - if (!parsed.refreshToken || parsed.refreshToken !== sessionRefreshToken) { - return null; - } - - return verifySignedUserId(parsed.openid_user_id); -}; - -/** - * Fallback auth for share file routes that are hit by ``/anchor requests, - * which can't carry the bearer access token. Resolves the viewer from the - * `refreshToken` cookie (or an active OpenID session plus signed `openid_user_id` - * cookie) so non-public shared links can authorize the viewer's ACL. Never - * blocks: on any failure it leaves `req.user` unset and lets - * `canAccessSharedLink` decide (public access, 401, or 403). - */ -const optionalShareFileAuth = async (req, res, next) => { - if (req.user) { - return next(); - } - - try { - const cookieHeader = req.headers.cookie; - if (!cookieHeader) { - return next(); - } - - const parsed = cookie.parse(cookieHeader); - const userId = - getOpenIdUserId(parsed, req) || - (parsed.refreshToken ? await getRefreshTokenUserId(parsed.refreshToken) : null); - if (!userId) { - return next(); - } - - // Resolve in system context: this runs before canAccessSharedLink establishes - // the share tenant, so under strict tenant isolation a tenant-scoped User - // query would otherwise throw. The viewer's id comes from verified, active - // cookie auth; the share's tenant-scoped ACL check still gates access. - const user = await runAsSystem(() => - getUserById(userId, '-password -__v -totpSecret -backupCodes'), - ); - if (user) { - user.id = user._id.toString(); - if (!user.role) { - user.role = SystemRoles.USER; - } - req.user = user; - } - } catch (error) { - logger.warn('[optionalShareFileAuth] cookie auth failed:', error?.message); - } - - return next(); -}; - -module.exports = optionalShareFileAuth; +module.exports = createOptionalShareFileAuth({ + parseCookie: cookie.parse, + getUserById, + findSession, + runAsSystem, + clearCloudFrontCookies, + enrollmentRequired: isTwoFactorEnrollmentRequired, + tokenRetired: isTokenRetired, + enabled: isEnabled, + warn: (...args) => logger.warn(...args), +}); diff --git a/api/server/middleware/optionalShareFileAuth.spec.js b/api/server/middleware/optionalShareFileAuth.spec.js index f68a356abf..f5580ee28f 100644 --- a/api/server/middleware/optionalShareFileAuth.spec.js +++ b/api/server/middleware/optionalShareFileAuth.spec.js @@ -2,23 +2,23 @@ const mockVerify = jest.fn(); const mockGetUserById = jest.fn(); const mockFindSession = jest.fn(); const mockRunAsSystem = jest.fn((fn) => fn()); +const mockIsTwoFactorEnrollmentRequired = jest.fn(() => false); +const mockIsTokenRetired = jest.fn(() => false); +const mockClearCloudFrontCookies = jest.fn(); jest.mock('jsonwebtoken', () => ({ verify: (...args) => mockVerify(...args) })); -/** Installed packages need real module IDs when Jest reuses a resolver across suites. */ -jest.mock('@librechat/api', () => ({ isEnabled: (v) => v === 'true' || v === true }), { - virtual: false, -}); -jest.mock( - '@librechat/data-schemas', - () => ({ - logger: { warn: jest.fn(), error: jest.fn() }, - runAsSystem: (...args) => mockRunAsSystem(...args), - }), - { virtual: false }, -); -jest.mock('librechat-data-provider', () => ({ SystemRoles: { USER: 'USER' } }), { - virtual: false, -}); +jest.mock('@librechat/api', () => ({ + createOptionalShareFileAuth: jest.requireActual('@librechat/api').createOptionalShareFileAuth, + isEnabled: (v) => v === 'true' || v === true, + clearCloudFrontCookies: (...args) => mockClearCloudFrontCookies(...args), + isTwoFactorEnrollmentRequired: (...args) => mockIsTwoFactorEnrollmentRequired(...args), + isTokenRetired: (...args) => mockIsTokenRetired(...args), +})); +jest.mock('@librechat/data-schemas', () => ({ + ...jest.requireActual('@librechat/data-schemas'), + logger: { warn: jest.fn(), error: jest.fn() }, + runAsSystem: (...args) => mockRunAsSystem(...args), +})); jest.mock('~/models', () => ({ getUserById: (...args) => mockGetUserById(...args), findSession: (...args) => mockFindSession(...args), @@ -35,6 +35,8 @@ const run = async (req) => { describe('optionalShareFileAuth', () => { beforeEach(() => { jest.clearAllMocks(); + mockIsTwoFactorEnrollmentRequired.mockReturnValue(false); + mockIsTokenRetired.mockReturnValue(false); process.env.JWT_REFRESH_SECRET = 'test-secret'; }); @@ -47,6 +49,28 @@ describe('optionalShareFileAuth', () => { expect(mockFindSession).not.toHaveBeenCalled(); }); + it('removes an existing viewer when required enrollment is incomplete', async () => { + mockIsTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = { + user: { id: 'u1', provider: 'local', twoFactorEnabled: false }, + authStrategy: 'jwt', + headers: { cookie: 'refreshToken=x' }, + }; + + const next = await run(req); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.user).toBeUndefined(); + expect(req.authStrategy).toBeUndefined(); + expect(mockClearCloudFrontCookies).toHaveBeenCalledWith(expect.any(Object), { + userId: 'u1', + tenantId: undefined, + storageRegion: undefined, + }); + expect(mockGetUserById).not.toHaveBeenCalled(); + expect(mockFindSession).not.toHaveBeenCalled(); + }); + it('resolves the viewer from a valid refreshToken cookie with a live session', async () => { mockVerify.mockReturnValue({ id: 'viewer-1' }); mockFindSession.mockResolvedValue({ _id: 'session-1' }); @@ -60,6 +84,98 @@ describe('optionalShareFileAuth', () => { expect(req.user).toMatchObject({ id: 'viewer-1', role: 'USER' }); }); + it('does not restore a cookie viewer when required enrollment is incomplete', async () => { + mockVerify.mockReturnValue({ id: 'viewer-required' }); + mockFindSession.mockResolvedValue({ _id: 'session-required' }); + mockGetUserById.mockResolvedValue({ + _id: 'viewer-required', + role: 'USER', + provider: 'local', + twoFactorEnabled: false, + }); + mockIsTwoFactorEnrollmentRequired.mockReturnValue(true); + const req = { headers: { cookie: 'refreshToken=good.jwt' } }; + + const next = await run(req); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.user).toBeUndefined(); + expect(mockClearCloudFrontCookies).toHaveBeenCalledWith(expect.any(Object), { + userId: 'viewer-required', + tenantId: undefined, + storageRegion: undefined, + }); + expect(mockGetUserById).toHaveBeenCalledTimes(1); + }); + + it('does not restore a cookie viewer minted before two-factor enrollment', async () => { + mockVerify.mockReturnValue({ id: 'viewer-stale', iat: 1000 }); + mockFindSession.mockResolvedValue({ _id: 'session-stale' }); + mockGetUserById.mockResolvedValue({ + _id: 'viewer-stale', + role: 'USER', + provider: 'local', + twoFactorEnabled: true, + twoFactorEnrolledAt: new Date(2000 * 1000), + }); + mockIsTokenRetired.mockReturnValue(true); + const req = { headers: { cookie: 'refreshToken=stale.jwt' } }; + + const next = await run(req); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.user).toBeUndefined(); + expect(mockClearCloudFrontCookies).toHaveBeenCalledWith(expect.any(Object), { + userId: 'viewer-stale', + tenantId: undefined, + storageRegion: undefined, + }); + }); + + it('dates the cookie by its own mint stamps rather than discarding them', async () => { + const enrolledAt = new Date(2000 * 1000); + mockVerify.mockReturnValue({ id: 'viewer-dated', iat: 1234, issuedAtMs: 1234_500 }); + mockFindSession.mockResolvedValue({ _id: 'session-dated' }); + mockGetUserById.mockResolvedValue({ + _id: 'viewer-dated', + role: 'USER', + twoFactorEnrolledAt: enrolledAt, + }); + const req = { headers: { cookie: 'refreshToken=dated.jwt' } }; + + await run(req); + + expect(mockIsTokenRetired).toHaveBeenCalledWith( + expect.objectContaining({ issuedAt: 1234, issuedAtMs: 1234_500 }), + expect.objectContaining({ twoFactorEnrolledAt: enrolledAt }), + ); + }); + + it('dates an OpenID cookie viewer by its own mint stamps too', async () => { + process.env.OPENID_REUSE_TOKENS = 'true'; + const enrolledAt = new Date(2000 * 1000); + mockVerify.mockReturnValue({ id: 'viewer-openid', iat: 4321, issuedAtMs: 4321_500 }); + mockGetUserById.mockResolvedValue({ + _id: 'viewer-openid', + role: 'USER', + twoFactorEnrolledAt: enrolledAt, + }); + const req = { + headers: { + cookie: 'refreshToken=live.jwt; token_provider=openid; openid_user_id=signed.jwt', + }, + session: { openidTokens: { refreshToken: 'live.jwt' } }, + }; + + await run(req); + + expect(mockIsTokenRetired).toHaveBeenCalledWith( + expect.objectContaining({ issuedAt: 4321, issuedAtMs: 4321_500 }), + expect.objectContaining({ twoFactorEnrolledAt: enrolledAt }), + ); + delete process.env.OPENID_REUSE_TOKENS; + }); + it('defaults the role to USER when the record has none', async () => { mockVerify.mockReturnValue({ id: 'viewer-2' }); mockFindSession.mockResolvedValue({ _id: 'session-2' }); diff --git a/api/server/middleware/requireJwtAuth.js b/api/server/middleware/requireJwtAuth.js index 74232012f2..ca01269675 100644 --- a/api/server/middleware/requireJwtAuth.js +++ b/api/server/middleware/requireJwtAuth.js @@ -3,13 +3,19 @@ const passport = require('passport'); const { logger } = require('@librechat/data-schemas'); const { isEnabled, + isTokenRetired, + createRequiredTwoFactorGate, + clearCloudFrontCookies, tenantContextMiddleware, getAuthFailureReasonCategory, buildSafeAuthLogContext, maybeRefreshCloudFrontAuthCookiesMiddleware, recordRumProxyRequest, getValidOpenIdReuseUserId, + generateTwoFactorSetupToken, + isTwoFactorEnrollmentRequired, } = require('@librechat/api'); +const { getUserById } = require('~/models'); const hasPassportStrategy = (strategy) => typeof passport._strategy === 'function' && passport._strategy(strategy) != null; @@ -65,6 +71,15 @@ const getRumProxyEndpoint = (req) => { const isOpenIdReuseUser = (strategy, user, openIdReuseUserId) => strategy !== 'openidJwt' || getAuthenticatedUserId(user) === openIdReuseUserId; +const requiredTwoFactorGate = createRequiredTwoFactorGate({ + clearCloudFrontCookies, + getUserById, + warn: (message) => logger.warn(message), + generateSetupToken: generateTwoFactorSetupToken, + enrollmentRequired: isTwoFactorEnrollmentRequired, + tokenRetired: isTokenRetired, +}); + /** * Custom Middleware to handle JWT authentication, with support for OpenID token reuse. * Switches between JWT and OpenID authentication based on cookies and environment settings. @@ -185,11 +200,13 @@ const requireJwtAuth = (req, res, next) => { req.user = user; req.authStrategy = strategy; logFallbackSuccess(strategy); - tenantContextMiddleware(req, res, (tenantErr) => { - if (tenantErr) { - return next(tenantErr); - } - refreshCloudFrontCookies(req, res, next); + return requiredTwoFactorGate(req, res, next, () => { + tenantContextMiddleware(req, res, (tenantErr) => { + if (tenantErr) { + return next(tenantErr); + } + refreshCloudFrontCookies(req, res, next); + }); }); })(req, res, next); }; diff --git a/api/server/middleware/setTwoFactorTempUser.js b/api/server/middleware/setTwoFactorTempUser.js index facbbcba9a..06b1156fc3 100644 --- a/api/server/middleware/setTwoFactorTempUser.js +++ b/api/server/middleware/setTwoFactorTempUser.js @@ -1,25 +1,12 @@ -const jwt = require('jsonwebtoken'); - -const setTwoFactorTempUser = (req, _res, next) => { - if (req.user?.id || req.user?._id) { - return next(); - } - - const { tempToken } = req.body ?? {}; - if (!tempToken) { - return next(); - } - - try { - const payload = jwt.verify(tempToken, process.env.JWT_SECRET); - if (payload?.userId) { - req.user = { id: payload.userId }; - } - } catch { - return next(); - } - - return next(); -}; +const { createTwoFactorTempUser } = require('@librechat/api'); +const setTwoFactorTempUser = createTwoFactorTempUser('tempToken', process.env); module.exports = setTwoFactorTempUser; +module.exports.setTwoFactorAcknowledgementTempUser = createTwoFactorTempUser( + 'acknowledgementToken', + process.env, +); +module.exports.setTwoFactorFinalizationTempUser = createTwoFactorTempUser( + 'finalizationToken', + process.env, +); diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 557cdecce9..c6eb406b35 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -87,6 +87,7 @@ afterEach(() => { delete process.env.ALLOW_REGISTRATION; delete process.env.ALLOW_SOCIAL_LOGIN; delete process.env.ALLOW_PASSWORD_RESET; + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; delete process.env.DOMAIN_SERVER; delete process.env.GOOGLE_CLIENT_ID; delete process.env.GOOGLE_CLIENT_SECRET; @@ -316,6 +317,16 @@ describe('GET /api/config', () => { expect(response.body).toHaveProperty('serverDomain'); }); + it('should expose the effective two-factor enforcement policy', async () => { + mockGetAppConfig.mockResolvedValue(baseAppConfig); + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const app = createApp(null); + + const response = await request(app).get('/api/config'); + + expect(response.body.twoFactorAuthenticationRequired).toBe(true); + }); + it('should omit CloudFront cookie refresh from unauthenticated response (#12688)', async () => { mockGetAppConfig.mockResolvedValue(baseAppConfig); mockGetCloudFrontConfig.mockReturnValue({ diff --git a/api/server/routes/admin/auth.refresh.test.js b/api/server/routes/admin/auth.refresh.test.js index c6e0287054..b14bf1312d 100644 --- a/api/server/routes/admin/auth.refresh.test.js +++ b/api/server/routes/admin/auth.refresh.test.js @@ -60,8 +60,9 @@ jest.mock('@librechat/api', () => { }; }); +const mockAdminLoginController = jest.fn((req, res) => res.status(200).end()); jest.mock('~/server/controllers/auth/LoginController', () => ({ - loginController: jest.fn((req, res) => res.status(200).end()), + loginController: (...args) => mockAdminLoginController(...args), })); jest.mock('~/server/middleware/roles/capabilities', () => ({ @@ -634,6 +635,27 @@ describe('admin local login route', () => { expect(middleware.requireLocalAuth).not.toHaveBeenCalled(); }); + it('preserves the additive required-setup response contract for admin clients', async () => { + mockAdminLoginController.mockImplementationOnce((req, res) => + res.status(200).json({ + twoFAPending: true, + twoFASetupRequired: true, + tempToken: 'setup-token', + }), + ); + + const response = await request(app).post('/api/admin/login/local').send({ + email: 'admin@example.com', + password: 'password', + }); + + expect(response.body).toEqual({ + twoFAPending: true, + twoFASetupRequired: true, + tempToken: 'setup-token', + }); + }); + it('stops before local auth when the email login gate rejects the request', async () => { middleware.validateEmailLogin.mockImplementationOnce((req, res) => res.status(403).json({ message: 'Email login is not allowed.' }), diff --git a/api/server/routes/auth.2fa-ratelimit.test.js b/api/server/routes/auth.2fa-ratelimit.test.js index cd496cce33..a6b145a292 100644 --- a/api/server/routes/auth.2fa-ratelimit.test.js +++ b/api/server/routes/auth.2fa-ratelimit.test.js @@ -2,9 +2,20 @@ const express = require('express'); const request = require('supertest'); const mockSetTwoFactorTempUser = jest.fn((req, res, next) => next()); +const mockSetTwoFactorAcknowledgementTempUser = jest.fn((req, res, next) => next()); +const mockSetTwoFactorFinalizationTempUser = jest.fn((req, res, next) => next()); const mockTwoFactorTempLimiter = jest.fn((req, res, next) => next()); +const mockTwoFactorSetupLimiter = jest.fn((req, res, next) => next()); const mockCheckBan = jest.fn((req, res, next) => next()); +const mockRequireTwoFactorSetupToken = jest.fn((req, res, next) => next()); +const mockBlockRetiredSetupToken = jest.fn((req, res, next) => next()); +const mockRequireTwoFactorSetupAcknowledgementToken = jest.fn((req, res, next) => next()); +const mockRequireTwoFactorSetupFinalizationToken = jest.fn((req, res, next) => next()); const mockVerify2FAWithTempToken = jest.fn((req, res) => res.status(204).end()); +const mockEnable2FA = jest.fn((req, res) => res.status(204).end()); +const mockConfirm2FASetupWithTempToken = jest.fn((req, res) => res.status(204).end()); +const mockAcknowledge2FASetup = jest.fn((req, res) => res.status(204).end()); +const mockFinalize2FASetup = jest.fn((req, res) => res.status(204).end()); jest.mock('@librechat/api', () => ({ limiterCache: jest.fn(() => undefined), @@ -13,7 +24,13 @@ jest.mock('@librechat/api', () => ({ ...args, ), createSetBalanceConfig: jest.fn(() => (req, res, next) => next()), + requireTwoFactorSetupToken: (...args) => mockRequireTwoFactorSetupToken(...args), + requireTwoFactorSetupAcknowledgementToken: (...args) => + mockRequireTwoFactorSetupAcknowledgementToken(...args), + requireTwoFactorSetupFinalizationToken: (...args) => + mockRequireTwoFactorSetupFinalizationToken(...args), forceRefreshCloudFrontAuthCookies: jest.fn(), + blockTwoFactorDisableWhenRequired: jest.fn((req, res, next) => next()), })); jest.mock('~/server/controllers/AuthController', () => ({ @@ -25,7 +42,7 @@ jest.mock('~/server/controllers/AuthController', () => ({ })); jest.mock('~/server/controllers/TwoFactorController', () => ({ - enable2FA: jest.fn((req, res) => res.status(204).end()), + enable2FA: (...args) => mockEnable2FA(...args), verify2FA: jest.fn((req, res) => res.status(204).end()), confirm2FA: jest.fn((req, res) => res.status(204).end()), disable2FA: jest.fn((req, res) => res.status(204).end()), @@ -34,6 +51,9 @@ jest.mock('~/server/controllers/TwoFactorController', () => ({ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args), + confirm2FASetupWithTempToken: (...args) => mockConfirm2FASetupWithTempToken(...args), + acknowledge2FASetup: (...args) => mockAcknowledge2FASetup(...args), + finalize2FASetup: (...args) => mockFinalize2FASetup(...args), })); jest.mock('~/server/controllers/auth/PasskeyController', () => ({ @@ -72,8 +92,13 @@ jest.mock('~/server/middleware', () => { passkeyLimiter: pass, passkeyStepUpLimiter: pass, setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args), + setTwoFactorAcknowledgementTempUser: (...args) => + mockSetTwoFactorAcknowledgementTempUser(...args), + setTwoFactorFinalizationTempUser: (...args) => mockSetTwoFactorFinalizationTempUser(...args), twoFactorTempLimiter: (...args) => mockTwoFactorTempLimiter(...args), + twoFactorSetupLimiter: (...args) => mockTwoFactorSetupLimiter(...args), checkBan: (...args) => mockCheckBan(...args), + blockRetiredSetupToken: (...args) => mockBlockRetiredSetupToken(...args), validateEmailLogin: pass, requireLocalAuth: pass, requireLdapAuth: pass, @@ -193,15 +218,151 @@ describe('POST /api/auth/2fa/verify-temp rate limiting', () => { beforeEach(() => { jest.clearAllMocks(); mockSetTwoFactorTempUser.mockImplementation((req, res, next) => next()); + mockSetTwoFactorAcknowledgementTempUser.mockImplementation((req, res, next) => next()); + mockSetTwoFactorFinalizationTempUser.mockImplementation((req, res, next) => next()); mockTwoFactorTempLimiter.mockImplementation((req, res, next) => next()); + mockTwoFactorSetupLimiter.mockImplementation((req, res, next) => next()); mockCheckBan.mockImplementation((req, res, next) => next()); + mockRequireTwoFactorSetupToken.mockImplementation((req, res, next) => next()); + mockBlockRetiredSetupToken.mockImplementation((req, res, next) => next()); + mockRequireTwoFactorSetupAcknowledgementToken.mockImplementation((req, res, next) => next()); + mockRequireTwoFactorSetupFinalizationToken.mockImplementation((req, res, next) => next()); mockVerify2FAWithTempToken.mockImplementation((req, res) => res.status(204).end()); + mockEnable2FA.mockImplementation((req, res) => res.status(204).end()); + mockConfirm2FASetupWithTempToken.mockImplementation((req, res) => res.status(204).end()); + mockAcknowledge2FASetup.mockImplementation((req, res) => res.status(204).end()); + mockFinalize2FASetup.mockImplementation((req, res) => res.status(204).end()); app = express(); app.use(express.json()); app.use('/api/auth', authRouter); }); + it('protects finalization with limiting, ban checks, and purpose validation', async () => { + await request(app) + .post('/api/auth/2fa/setup/finalize') + .send({ finalizationToken: 'finalization-token' }) + .expect(204); + + expect(mockSetTwoFactorFinalizationTempUser).toHaveBeenCalledTimes(1); + expect(mockTwoFactorSetupLimiter).toHaveBeenCalledTimes(1); + /** Redeeming a nonce checks no guessable code, so it must not draw on the code-attempt quota. */ + expect(mockTwoFactorTempLimiter).not.toHaveBeenCalled(); + expect(mockCheckBan).toHaveBeenCalledTimes(1); + expect(mockRequireTwoFactorSetupFinalizationToken).toHaveBeenCalledTimes(1); + expect(mockFinalize2FASetup).toHaveBeenCalledTimes(1); + expect(mockSetTwoFactorFinalizationTempUser.mock.invocationCallOrder[0]).toBeLessThan( + mockTwoFactorSetupLimiter.mock.invocationCallOrder[0], + ); + expect(mockTwoFactorSetupLimiter.mock.invocationCallOrder[0]).toBeLessThan( + mockCheckBan.mock.invocationCallOrder[0], + ); + expect(mockCheckBan.mock.invocationCallOrder[0]).toBeLessThan( + mockRequireTwoFactorSetupFinalizationToken.mock.invocationCallOrder[0], + ); + expect(mockRequireTwoFactorSetupFinalizationToken.mock.invocationCallOrder[0]).toBeLessThan( + mockFinalize2FASetup.mock.invocationCallOrder[0], + ); + }); + + it('protects acknowledgement with field-specific identity, limiting, ban checks, and purpose validation', async () => { + await request(app) + .post('/api/auth/2fa/setup/acknowledge') + .send({ acknowledgementToken: 'acknowledgement-token' }) + .expect(204); + + expect(mockSetTwoFactorAcknowledgementTempUser).toHaveBeenCalledTimes(1); + expect(mockTwoFactorSetupLimiter).toHaveBeenCalledTimes(1); + expect(mockTwoFactorTempLimiter).not.toHaveBeenCalled(); + expect(mockCheckBan).toHaveBeenCalledTimes(1); + expect(mockRequireTwoFactorSetupAcknowledgementToken).toHaveBeenCalledTimes(1); + expect(mockAcknowledge2FASetup).toHaveBeenCalledTimes(1); + expect(mockSetTwoFactorAcknowledgementTempUser.mock.invocationCallOrder[0]).toBeLessThan( + mockTwoFactorSetupLimiter.mock.invocationCallOrder[0], + ); + expect(mockTwoFactorSetupLimiter.mock.invocationCallOrder[0]).toBeLessThan( + mockCheckBan.mock.invocationCallOrder[0], + ); + expect(mockCheckBan.mock.invocationCallOrder[0]).toBeLessThan( + mockRequireTwoFactorSetupAcknowledgementToken.mock.invocationCallOrder[0], + ); + expect(mockRequireTwoFactorSetupAcknowledgementToken.mock.invocationCallOrder[0]).toBeLessThan( + mockAcknowledge2FASetup.mock.invocationCallOrder[0], + ); + }); + + it('does not finalize after the limiter or ban check rejects the request', async () => { + mockCheckBan.mockImplementation((req, res) => res.status(403).json({ message: 'Banned' })); + + await request(app) + .post('/api/auth/2fa/setup/finalize') + .send({ finalizationToken: 'finalization-token' }) + .expect(403); + + expect(mockRequireTwoFactorSetupFinalizationToken).not.toHaveBeenCalled(); + expect(mockFinalize2FASetup).not.toHaveBeenCalled(); + }); + + it.each([ + ['/api/auth/2fa/setup', mockEnable2FA, mockTwoFactorSetupLimiter], + ['/api/auth/2fa/setup/confirm', mockConfirm2FASetupWithTempToken, mockTwoFactorTempLimiter], + ])( + 'protects %s with temp-token limiting and setup validation', + async (path, controller, limiter) => { + await request(app).post(path).send({ tempToken: 'temp-token' }).expect(204); + + expect(mockSetTwoFactorTempUser).toHaveBeenCalledTimes(1); + expect(limiter).toHaveBeenCalledTimes(1); + expect(mockCheckBan).toHaveBeenCalledTimes(1); + expect(mockRequireTwoFactorSetupToken).toHaveBeenCalledTimes(1); + expect(controller).toHaveBeenCalledTimes(1); + expect(mockSetTwoFactorTempUser.mock.invocationCallOrder[0]).toBeLessThan( + limiter.mock.invocationCallOrder[0], + ); + expect(limiter.mock.invocationCallOrder[0]).toBeLessThan( + mockCheckBan.mock.invocationCallOrder[0], + ); + expect(mockCheckBan.mock.invocationCallOrder[0]).toBeLessThan( + mockRequireTwoFactorSetupToken.mock.invocationCallOrder[0], + ); + expect(mockRequireTwoFactorSetupToken.mock.invocationCallOrder[0]).toBeLessThan( + controller.mock.invocationCallOrder[0], + ); + }, + ); + + it.each([ + ['/api/auth/2fa/setup', mockEnable2FA], + ['/api/auth/2fa/setup/confirm', mockConfirm2FASetupWithTempToken], + ])( + 'dates the setup token on %s once its signature has been verified', + async (path, controller) => { + await request(app).post(path).send({ tempToken: 'temp-token' }).expect(204); + + expect(mockBlockRetiredSetupToken).toHaveBeenCalledTimes(1); + expect(mockRequireTwoFactorSetupToken.mock.invocationCallOrder[0]).toBeLessThan( + mockBlockRetiredSetupToken.mock.invocationCallOrder[0], + ); + expect(mockBlockRetiredSetupToken.mock.invocationCallOrder[0]).toBeLessThan( + controller.mock.invocationCallOrder[0], + ); + }, + ); + + it.each([['/api/auth/2fa/setup'], ['/api/auth/2fa/setup/confirm']])( + 'does not stage enrollment on %s when the setup token has been retired', + async (path) => { + mockBlockRetiredSetupToken.mockImplementation((req, res) => + res.status(401).json({ message: 'Invalid or expired two-factor setup token' }), + ); + + await request(app).post(path).send({ tempToken: 'temp-token' }).expect(401); + + expect(mockEnable2FA).not.toHaveBeenCalled(); + expect(mockConfirm2FASetupWithTempToken).not.toHaveBeenCalled(); + }, + ); + it('sets the temp user before limiting, checking bans, and verifying temp 2FA tokens', async () => { await request(app).post('/api/auth/2fa/verify-temp').send({ token: '123456' }).expect(204); diff --git a/api/server/routes/auth.cloudfront.test.js b/api/server/routes/auth.cloudfront.test.js index 764cb169aa..84b7e6ddd3 100644 --- a/api/server/routes/auth.cloudfront.test.js +++ b/api/server/routes/auth.cloudfront.test.js @@ -7,7 +7,11 @@ jest.mock('@librechat/api', () => ({ limiterCache: jest.fn(), createTwoFactorManagementLimiter: jest.fn(() => (req, res, next) => next()), createSetBalanceConfig: jest.fn(() => (req, res, next) => next()), + requireTwoFactorSetupToken: jest.fn((req, res, next) => next()), + requireTwoFactorSetupAcknowledgementToken: jest.fn((req, res, next) => next()), + requireTwoFactorSetupFinalizationToken: jest.fn((req, res, next) => next()), forceRefreshCloudFrontAuthCookies: (...args) => mockForceRefreshCloudFrontAuthCookies(...args), + blockTwoFactorDisableWhenRequired: jest.fn((req, res, next) => next()), })); jest.mock('~/server/controllers/AuthController', () => ({ @@ -28,6 +32,9 @@ jest.mock('~/server/controllers/TwoFactorController', () => ({ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: jest.fn((req, res) => res.status(200).end()), + confirm2FASetupWithTempToken: jest.fn((req, res) => res.status(200).end()), + acknowledge2FASetup: jest.fn((req, res) => res.status(200).end()), + finalize2FASetup: jest.fn((req, res) => res.status(200).end()), })); jest.mock('~/server/controllers/auth/PasskeyController', () => ({ @@ -66,8 +73,12 @@ jest.mock('~/server/middleware', () => { passkeyLimiter: pass, passkeyStepUpLimiter: pass, setTwoFactorTempUser: pass, + setTwoFactorAcknowledgementTempUser: pass, + setTwoFactorFinalizationTempUser: pass, twoFactorTempLimiter: pass, + twoFactorSetupLimiter: pass, checkBan: pass, + blockRetiredSetupToken: pass, validateEmailLogin: pass, requireLocalAuth: pass, requireLdapAuth: pass, diff --git a/api/server/routes/auth.cross-site.test.js b/api/server/routes/auth.cross-site.test.js index 8cf0ee6c16..eb32a3b368 100644 --- a/api/server/routes/auth.cross-site.test.js +++ b/api/server/routes/auth.cross-site.test.js @@ -36,6 +36,9 @@ jest.mock('~/server/controllers/TwoFactorController', () => ({ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args), + confirm2FASetupWithTempToken: jest.fn((req, res) => res.status(204).end()), + acknowledge2FASetup: jest.fn((req, res) => res.status(204).end()), + finalize2FASetup: jest.fn((req, res) => res.status(204).end()), })); jest.mock('~/server/controllers/auth/PasskeyController', () => ({ @@ -74,7 +77,11 @@ jest.mock('~/server/middleware', () => { passkeyLimiter: pass, passkeyStepUpLimiter: pass, setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args), + setTwoFactorAcknowledgementTempUser: pass, + setTwoFactorFinalizationTempUser: pass, twoFactorTempLimiter: pass, + twoFactorSetupLimiter: pass, + blockRetiredSetupToken: pass, checkBan: pass, validateEmailLogin: jest.requireActual('~/server/middleware/validateEmailLogin'), requireLocalAuth: (...args) => mockRequireLocalAuth(...args), diff --git a/api/server/routes/auth.js b/api/server/routes/auth.js index c8539b33eb..6557dd7cd2 100644 --- a/api/server/routes/auth.js +++ b/api/server/routes/auth.js @@ -2,8 +2,12 @@ const express = require('express'); const { limiterCache, createSetBalanceConfig, + requireTwoFactorSetupToken, createTwoFactorManagementLimiter, forceRefreshCloudFrontAuthCookies, + blockTwoFactorDisableWhenRequired, + requireTwoFactorSetupAcknowledgementToken, + requireTwoFactorSetupFinalizationToken, } = require('@librechat/api'); const { resetPasswordRequestController, @@ -28,7 +32,12 @@ const { registerPasskeyOptions, registerPasskeyVerify, } = require('~/server/controllers/auth/PasskeyController'); -const { verify2FAWithTempToken } = require('~/server/controllers/auth/TwoFactorAuthController'); +const { + verify2FAWithTempToken, + confirm2FASetupWithTempToken, + acknowledge2FASetup, + finalize2FASetup, +} = require('~/server/controllers/auth/TwoFactorAuthController'); const { logoutController } = require('~/server/controllers/auth/LogoutController'); const { loginController } = require('~/server/controllers/auth/LoginController'); const { findBalanceByUser, upsertBalanceFields } = require('~/models'); @@ -108,6 +117,40 @@ router.post( router.post('/2fa/enable', middleware.requireJwtAuth, twoFactorManagementLimiter, enable2FA); router.post('/2fa/verify', middleware.requireJwtAuth, twoFactorManagementLimiter, verify2FA); +router.post( + '/2fa/setup', + middleware.setTwoFactorTempUser, + middleware.twoFactorSetupLimiter, + middleware.checkBan, + requireTwoFactorSetupToken, + middleware.blockRetiredSetupToken, + enable2FA, +); +router.post( + '/2fa/setup/confirm', + middleware.setTwoFactorTempUser, + middleware.twoFactorTempLimiter, + middleware.checkBan, + requireTwoFactorSetupToken, + middleware.blockRetiredSetupToken, + confirm2FASetupWithTempToken, +); +router.post( + '/2fa/setup/acknowledge', + middleware.setTwoFactorAcknowledgementTempUser, + middleware.twoFactorSetupLimiter, + middleware.checkBan, + requireTwoFactorSetupAcknowledgementToken, + acknowledge2FASetup, +); +router.post( + '/2fa/setup/finalize', + middleware.setTwoFactorFinalizationTempUser, + middleware.twoFactorSetupLimiter, + middleware.checkBan, + requireTwoFactorSetupFinalizationToken, + finalize2FASetup, +); router.post( '/2fa/verify-temp', middleware.requireSameOrigin, @@ -117,7 +160,13 @@ router.post( verify2FAWithTempToken, ); router.post('/2fa/confirm', middleware.requireJwtAuth, twoFactorManagementLimiter, confirm2FA); -router.post('/2fa/disable', middleware.requireJwtAuth, twoFactorManagementLimiter, disable2FA); +router.post( + '/2fa/disable', + middleware.requireJwtAuth, + twoFactorManagementLimiter, + blockTwoFactorDisableWhenRequired, + disable2FA, +); router.post( '/2fa/backup/regenerate', middleware.requireJwtAuth, diff --git a/api/server/routes/auth.reset-password-ratelimit.test.js b/api/server/routes/auth.reset-password-ratelimit.test.js index f8f8ead7d8..4fe6bc23b2 100644 --- a/api/server/routes/auth.reset-password-ratelimit.test.js +++ b/api/server/routes/auth.reset-password-ratelimit.test.js @@ -10,7 +10,11 @@ jest.mock('@librechat/api', () => ({ limiterCache: jest.fn(), createTwoFactorManagementLimiter: jest.fn(() => (req, res, next) => next()), createSetBalanceConfig: jest.fn(() => (req, res, next) => next()), + requireTwoFactorSetupToken: jest.fn((req, res, next) => next()), + requireTwoFactorSetupAcknowledgementToken: jest.fn((req, res, next) => next()), + requireTwoFactorSetupFinalizationToken: jest.fn((req, res, next) => next()), forceRefreshCloudFrontAuthCookies: jest.fn(), + blockTwoFactorDisableWhenRequired: jest.fn((req, res, next) => next()), })); jest.mock('~/server/controllers/AuthController', () => ({ @@ -31,6 +35,9 @@ jest.mock('~/server/controllers/TwoFactorController', () => ({ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: jest.fn((req, res) => res.status(204).end()), + confirm2FASetupWithTempToken: jest.fn((req, res) => res.status(204).end()), + acknowledge2FASetup: jest.fn((req, res) => res.status(204).end()), + finalize2FASetup: jest.fn((req, res) => res.status(204).end()), })); jest.mock('~/server/controllers/auth/PasskeyController', () => ({ @@ -69,8 +76,12 @@ jest.mock('~/server/middleware', () => { passkeyLimiter: pass, passkeyStepUpLimiter: pass, setTwoFactorTempUser: pass, + setTwoFactorAcknowledgementTempUser: pass, + setTwoFactorFinalizationTempUser: pass, twoFactorTempLimiter: pass, + twoFactorSetupLimiter: pass, checkBan: (...args) => mockCheckBan(...args), + blockRetiredSetupToken: pass, validateEmailLogin: pass, requireLocalAuth: pass, requireLdapAuth: pass, diff --git a/api/server/routes/config.js b/api/server/routes/config.js index 6a585bfb2d..1fec348ad4 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -108,6 +108,7 @@ function buildPreLoginPayload() { socialLoginEnabled: isEnabled(process.env.ALLOW_SOCIAL_LOGIN), emailEnabled: checkEmailConfig(), passwordResetEnabled, + twoFactorAuthenticationRequired: isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION), }; const minPasswordLength = parseInt(process.env.MIN_PASSWORD_LENGTH, 10); diff --git a/api/server/services/twoFactorService.js b/api/server/services/twoFactorService.js index 081fa611bd..f70e00dc83 100644 --- a/api/server/services/twoFactorService.js +++ b/api/server/services/twoFactorService.js @@ -1,5 +1,6 @@ const { webcrypto, timingSafeEqual } = require('node:crypto'); const { hashBackupCode, decryptV3, decryptV2 } = require('@librechat/data-schemas'); +const { generateTwoFactorLoginChallengeToken } = require('@librechat/api'); const { updateUser } = require('~/models'); // Base32 alphabet for TOTP secret encoding. @@ -268,8 +269,7 @@ const getTOTPSecret = async (storedSecret) => { * @returns {string} */ const generate2FATempToken = (userId) => { - const { sign } = require('jsonwebtoken'); - return sign({ userId, twoFAPending: true }, process.env.JWT_SECRET, { expiresIn: '5m' }); + return generateTwoFactorLoginChallengeToken(userId, process.env.JWT_SECRET); }; module.exports = { diff --git a/api/strategies/jwtStrategy.js b/api/strategies/jwtStrategy.js index 1d5423aa8c..989b6d1b07 100644 --- a/api/strategies/jwtStrategy.js +++ b/api/strategies/jwtStrategy.js @@ -1,7 +1,11 @@ -const { AGENT_TRIGGER_SCOPE, isTokenIssuedBeforeCredentialChange } = require('@librechat/api'); const { logger, runAsSystem } = require('@librechat/data-schemas'); const { SystemRoles } = require('librechat-data-provider'); const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt'); +const { + AGENT_TRIGGER_SCOPE, + isTokenRetired, + continueAfterBearerRetirement, +} = require('@librechat/api'); const { getUserById, updateUser } = require('~/models'); const AGENT_TRIGGER_ADMISSION_PATHS = ['/api/agents/chat/agents', '/api/agents/chat/steer/deliver']; @@ -48,21 +52,25 @@ const jwtLogin = () => return; } if (user) { - if (isTokenIssuedBeforeCredentialChange(payload, user)) { - logger.warn( - '[jwtLogin] JwtStrategy => token predates the last credential change: ' + payload?.id, - ); - done(null, false); - return; - } - user.id = user._id.toString(); - /** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */ - user.idOnTheSource ??= null; - if (!user.role) { - user.role = SystemRoles.USER; - await runAsSystem(() => updateUser(user.id, { role: user.role })); - } - done(null, user); + return await continueAfterBearerRetirement( + user, + { issuedAt: payload?.iat, issuedAtMs: payload?.issuedAtMs }, + 'jwt', + payload?.id, + done, + (message) => logger.warn(message), + async () => { + user.id = user._id.toString(); + /** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */ + user.idOnTheSource ??= null; + if (!user.role) { + user.role = SystemRoles.USER; + await runAsSystem(() => updateUser(user.id, { role: user.role })); + } + done(null, user); + }, + isTokenRetired, + ); } else { logger.warn('[jwtLogin] JwtStrategy => no user found: ' + payload?.id); done(null, false); diff --git a/api/strategies/jwtStrategy.spec.js b/api/strategies/jwtStrategy.spec.js index 5764b91eaa..0ca5cb6864 100644 --- a/api/strategies/jwtStrategy.spec.js +++ b/api/strategies/jwtStrategy.spec.js @@ -21,8 +21,8 @@ jest.mock('@librechat/data-schemas', () => ({ jest.mock('@librechat/api', () => ({ AGENT_TRIGGER_SCOPE: 'agent_trigger', - isTokenIssuedBeforeCredentialChange: - jest.requireActual('@librechat/api').isTokenIssuedBeforeCredentialChange, + isTokenRetired: jest.requireActual('@librechat/api').isTokenRetired, + continueAfterBearerRetirement: jest.requireActual('@librechat/api').continueAfterBearerRetirement, })); jest.mock('~/models', () => ({ @@ -222,11 +222,23 @@ describe('jwtStrategy', () => { expect(user).toBe(false); }); - it('accepts a token issued in the same second as a reset stamped on the second boundary', async () => { + it('rejects a token issued in the same second as a reset stamped on the second boundary', async () => { mockUserWithStamp(new Date(1700000010000)); const { user } = await invokeVerify({ id: 'user-reset', iat: 1700000010 }); + expect(user).toBe(false); + }); + + it('accepts a token dated after a boundary reset to the millisecond', async () => { + mockUserWithStamp(new Date(1700000010000)); + + const { user } = await invokeVerify({ + id: 'user-reset', + iat: 1700000010, + issuedAtMs: 1700000010001, + }); + expect(user.id).toBe('user-reset'); }); @@ -257,4 +269,87 @@ describe('jwtStrategy', () => { expect(user).toBe(false); }); }); + + describe('two-factor enrollment cutoff', () => { + const enrolledAt = new Date('2026-01-01T00:00:10.500Z'); + const enrolledSecond = Math.floor(enrolledAt.getTime() / 1000); + + const mockEnrolledUser = () => + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-3' }, + role: SystemRoles.USER, + twoFactorEnabled: true, + twoFactorEnrolledAt: enrolledAt, + }); + + it('refuses an access token minted before enrollment', async () => { + mockEnrolledUser(); + + const { user } = await invokeVerify({ id: 'user-3', iat: enrolledSecond - 1 }); + + expect(user).toBe(false); + }); + + it('refuses an access token minted before a password reset', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-3' }, + role: SystemRoles.USER, + twoFactorEnrolledAt: null, + credentialsChangedAt: enrolledAt, + }); + + const { user } = await invokeVerify({ id: 'user-3', iat: enrolledSecond - 1 }); + + expect(user).toBe(false); + }); + + it('accepts an access token minted after a password reset', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-3' }, + role: SystemRoles.USER, + twoFactorEnrolledAt: null, + credentialsChangedAt: enrolledAt, + }); + + const { user } = await invokeVerify({ id: 'user-3', iat: enrolledSecond + 60 }); + + expect(user.id).toBe('user-3'); + }); + + it('accepts the session minted within the enrolling second', async () => { + mockEnrolledUser(); + + const { user } = await invokeVerify({ id: 'user-3', iat: enrolledSecond }); + + expect(user.id).toBe('user-3'); + }); + + it('accepts an access token minted after enrollment', async () => { + mockEnrolledUser(); + + const { user } = await invokeVerify({ id: 'user-3', iat: enrolledSecond + 60 }); + + expect(user.id).toBe('user-3'); + }); + + it('refuses an undatable token once the account is enrolled', async () => { + mockEnrolledUser(); + + const { user } = await invokeVerify({ id: 'user-3' }); + + expect(user).toBe(false); + }); + + it('leaves accounts that never enrolled untouched', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-4' }, + role: SystemRoles.USER, + twoFactorEnrolledAt: null, + }); + + const { user } = await invokeVerify({ id: 'user-4', iat: 0 }); + + expect(user.id).toBe('user-4'); + }); + }); }); diff --git a/api/strategies/openIdJwtStrategy.js b/api/strategies/openIdJwtStrategy.js index 435edb837c..ca4edd7829 100644 --- a/api/strategies/openIdJwtStrategy.js +++ b/api/strategies/openIdJwtStrategy.js @@ -5,6 +5,8 @@ const { CacheKeys, SystemRoles } = require('librechat-data-provider'); const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt'); const { isEnabled, + isTokenRetired, + continueAfterBearerRetirement, findOpenIDUser, getOpenIdEmail, getOpenIdIssuer, @@ -18,7 +20,6 @@ const { getHttpsProxyAgent, isAccessTokenJwt, math, - isTokenIssuedBeforeCredentialChange, } = require('@librechat/api'); const { updateUser, findUser, isAgentTriggerPrincipalActive } = require('~/models'); const getLogStores = require('~/cache/getLogStores'); @@ -196,96 +197,101 @@ const openIdJwtLogin = (openIdConfig) => { } if (user) { - if (isTokenIssuedBeforeCredentialChange(payload, user)) { - logger.warn( - '[openIdJwtLogin] openId JwtStrategy => token predates the last credential change: ' + - payload?.sub, - ); - done(null, false); - return; - } - user.id = user._id.toString(); - if (!(await runAsSystem(() => isAgentTriggerPrincipalActive(user.id)))) { - done(null, false, { - message: 'Account deletion is in progress', - code: 'ACCOUNT_DELETION_IN_PROGRESS', - }); - return; - } - /** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */ - user.idOnTheSource ??= null; + return await continueAfterBearerRetirement( + user, + { issuedAt: payload?.iat }, + 'openidJwt', + payload?.sub, + done, + (message) => logger.warn(message), + async () => { + user.id = user._id.toString(); + if (!(await runAsSystem(() => isAgentTriggerPrincipalActive(user.id)))) { + done(null, false, { + message: 'Account deletion is in progress', + code: 'ACCOUNT_DELETION_IN_PROGRESS', + }); + return; + } + /** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */ + user.idOnTheSource ??= null; - const updateData = {}; - if (migration) { - updateData.provider = 'openid'; - updateData.openidId = payload?.sub; - if (openidIssuer) { - updateData.openidIssuer = openidIssuer; - } - } - if (!user.role) { - user.role = SystemRoles.USER; - updateData.role = user.role; - } + const updateData = {}; + if (migration) { + updateData.provider = 'openid'; + updateData.openidId = payload?.sub; + if (openidIssuer) { + updateData.openidIssuer = openidIssuer; + } + } + if (!user.role) { + user.role = SystemRoles.USER; + updateData.role = user.role; + } - if (Object.keys(updateData).length > 0) { - await updateUser(user.id, updateData); - } + if (Object.keys(updateData).length > 0) { + await updateUser(user.id, updateData); + } - if (authUserCacheStore && authUserCacheKey) { - if (Object.keys(updateData).length > 0) { - await invalidateCachedAuthUserDoc(authUserCacheStore, { - userId: user.id, - cacheKey: authUserCacheKey, - }); - } else if (!servedCachedUser && isUserInAuthCacheScope(user, authUserCacheScope)) { - await setCachedAuthUserDoc(authUserCacheStore, authUserCacheKey, user); - } - } + if (authUserCacheStore && authUserCacheKey) { + if (Object.keys(updateData).length > 0) { + await invalidateCachedAuthUserDoc(authUserCacheStore, { + userId: user.id, + cacheKey: authUserCacheKey, + }); + } else if (!servedCachedUser && isUserInAuthCacheScope(user, authUserCacheScope)) { + await setCachedAuthUserDoc(authUserCacheStore, authUserCacheKey, user); + } + } - /** Read tokens from session (server-side) to avoid large cookie issues */ - const sessionTokens = req.session?.openidTokens; - let accessToken = sessionTokens?.accessToken; - let idToken = sessionTokens?.idToken; - let refreshToken = sessionTokens?.refreshToken; + /** Read tokens from session (server-side) to avoid large cookie issues */ + const sessionTokens = req.session?.openidTokens; + let accessToken = sessionTokens?.accessToken; + let idToken = sessionTokens?.idToken; + let refreshToken = sessionTokens?.refreshToken; - /** Fallback to cookies for backward compatibility */ - if (!accessToken || !refreshToken || !idToken) { - accessToken = accessToken || parsedCookies.openid_access_token; - idToken = idToken || parsedCookies.openid_id_token; - refreshToken = refreshToken || parsedCookies.refreshToken; - } + /** Fallback to cookies for backward compatibility */ + if (!accessToken || !refreshToken || !idToken) { + accessToken = accessToken || parsedCookies.openid_access_token; + idToken = idToken || parsedCookies.openid_id_token; + refreshToken = refreshToken || parsedCookies.refreshToken; + } - /** - * The raw bearer only stands in for a missing stored access token when it is - * identifiable as one. It cleared this strategy's audience check, but an ID token - * clears the same check, and an ID token used as the OBO assertion is rejected by the - * IdP (Entra answers `AADSTS240002`). An unrecognised token is left unset so - * `isOpenIDTokenValid` fails closed with an actionable error instead. - */ - let reusableRawToken; - if (!accessToken) { - reusableRawToken = isAccessTokenJwt(rawToken, payload, audienceConfig) - ? rawToken - : undefined; - if (!reusableRawToken) { - /** Per-request on the reuse path, so the actionable warning is left to the consumer that actually needs the credential */ - logger.debug( - '[openIdJwtLogin] No stored OpenID access token, and the request bearer is not identifiable as one; leaving it unset', - ); - } - } + /** + * The raw bearer only stands in for a missing stored access token when it is + * identifiable as one. It cleared this strategy's audience check, but an ID token + * clears the same check, and an ID token used as the OBO assertion is rejected by the + * IdP (Entra answers `AADSTS240002`). An unrecognised token is left unset so + * `isOpenIDTokenValid` fails closed with an actionable error instead. + */ + let reusableRawToken; + if (!accessToken) { + reusableRawToken = isAccessTokenJwt(rawToken, payload, audienceConfig) + ? rawToken + : undefined; + if (!reusableRawToken) { + /** Per-request on the reuse path, so the actionable warning is left to the consumer that actually needs the credential */ + logger.debug( + '[openIdJwtLogin] No stored OpenID access token, and the request bearer is not identifiable as one; leaving it unset', + ); + } + } - const resolvedAccessToken = accessToken || reusableRawToken; - user.federatedTokens = { - access_token: resolvedAccessToken, - id_token: idToken, - refresh_token: refreshToken, - expires_at: - resolvedAccessToken === rawToken ? payload.exp : decodeJwtExpiry(resolvedAccessToken), - }; + const resolvedAccessToken = accessToken || reusableRawToken; + user.federatedTokens = { + access_token: resolvedAccessToken, + id_token: idToken, + refresh_token: refreshToken, + expires_at: + resolvedAccessToken === rawToken + ? payload.exp + : decodeJwtExpiry(resolvedAccessToken), + }; - done(null, user); + done(null, user); + }, + isTokenRetired, + ); } else { logger.warn( '[openIdJwtLogin] openId JwtStrategy => no user found with the sub claims: ' + diff --git a/api/strategies/openIdJwtStrategy.spec.js b/api/strategies/openIdJwtStrategy.spec.js index a2563533bc..6615e39eee 100644 --- a/api/strategies/openIdJwtStrategy.spec.js +++ b/api/strategies/openIdJwtStrategy.spec.js @@ -34,12 +34,12 @@ jest.mock('@librechat/data-schemas', () => ({ })); jest.mock('@librechat/api', () => ({ isEnabled: jest.fn(() => false), + isTokenRetired: jest.requireActual('@librechat/api').isTokenRetired, + continueAfterBearerRetirement: jest.requireActual('@librechat/api').continueAfterBearerRetirement, findOpenIDUser: jest.fn(), getOpenIdEmail: jest.requireActual('@librechat/api').getOpenIdEmail, getOpenIdIssuer: jest.fn(() => 'https://issuer.example.com'), normalizeOpenIdIssuer: jest.requireActual('@librechat/api').normalizeOpenIdIssuer, - isTokenIssuedBeforeCredentialChange: - jest.requireActual('@librechat/api').isTokenIssuedBeforeCredentialChange, buildAuthUserDocCacheKey: jest.fn(() => 'auth-user-doc-key'), getAuthUserDocCacheMode: jest.fn(() => 'off'), getCachedAuthUserDoc: jest.fn(), @@ -777,6 +777,119 @@ describe('openIdJwtStrategy – auth user document cache', () => { }); }); +describe('openIdJwtStrategy: retired token cutoffs', () => { + const req = { headers: { authorization: 'Bearer tok' }, session: {} }; + + const baseUser = { + _id: { toString: () => 'user-abc' }, + role: SystemRoles.USER, + provider: 'openid', + email: 'test@example.com', + }; + + const enrolledAt = new Date('2026-01-01T00:00:30.500Z'); + const enrolledSecond = Math.floor(enrolledAt.getTime() / 1000); + + /** The provider mints this token, so `iat` is the only stamp it can ever carry. */ + const makePayload = (iat) => ({ + sub: 'oidc-123', + email: 'test@example.com', + iss: 'https://issuer.example.com', + exp: 9999999999, + ...(iat === undefined ? {} : { iat }), + }); + + beforeEach(() => { + jest.clearAllMocks(); + resetAuthUserDocCacheMocks(); + updateUser.mockResolvedValue({}); + openIdJwtLogin(mockOpenIdConfig); + }); + + it('refuses a federated bearer minted before enrollment', async () => { + findOpenIDUser.mockResolvedValue({ + user: { ...baseUser, twoFactorEnrolledAt: enrolledAt }, + error: null, + migration: false, + }); + + const { user, info } = await invokeVerify(req, makePayload(enrolledSecond - 1)); + + expect(user).toBe(false); + expect(info).toEqual({ message: 'Token predates enrollment or password reset' }); + expect(updateUser).not.toHaveBeenCalled(); + }); + + it('surrenders the resetting second, which whole-second `iat` cannot tell apart', async () => { + const credentialsChangedAt = new Date('2026-01-01T00:00:30.500Z'); + findOpenIDUser.mockResolvedValue({ + user: { ...baseUser, credentialsChangedAt }, + error: null, + migration: false, + }); + + const { user } = await invokeVerify( + req, + makePayload(Math.floor(credentialsChangedAt.getTime() / 1000)), + ); + + expect(user).toBe(false); + }); + + it('accepts a federated bearer minted after both cutoffs', async () => { + findOpenIDUser.mockResolvedValue({ + user: { + ...baseUser, + twoFactorEnrolledAt: enrolledAt, + credentialsChangedAt: new Date('2025-06-01T00:00:00.000Z'), + }, + error: null, + migration: false, + }); + + const { user } = await invokeVerify(req, makePayload(enrolledSecond + 1)); + + expect(user).toMatchObject({ id: 'user-abc', email: 'test@example.com' }); + }); + + it('leaves an account that carries neither cutoff alone, undatable token included', async () => { + findOpenIDUser.mockResolvedValue({ user: { ...baseUser }, error: null, migration: false }); + + const { user } = await invokeVerify(req, makePayload(undefined)); + + expect(user).toMatchObject({ id: 'user-abc' }); + }); + + it('refuses a bearer it cannot date at all once a cutoff is set', async () => { + findOpenIDUser.mockResolvedValue({ + user: { ...baseUser, twoFactorEnrolledAt: enrolledAt }, + error: null, + migration: false, + }); + + const { user } = await invokeVerify(req, makePayload(undefined)); + + expect(user).toBe(false); + }); + + it('dates the bearer against a cached stamp that came back serialized', async () => { + getAuthUserDocCacheMode.mockReturnValue('on'); + getCachedAuthUserDoc.mockResolvedValue({ + _id: 'cached-user', + role: SystemRoles.USER, + provider: 'openid', + email: 'cached@example.com', + /** Redis round-trips `Date` through JSON, so the cutoff arrives as an ISO string */ + twoFactorEnrolledAt: enrolledAt.toISOString(), + }); + + const { user } = await invokeVerify(req, makePayload(enrolledSecond - 1)); + + expect(user).toBe(false); + expect(findOpenIDUser).not.toHaveBeenCalled(); + }); +}); + describe('openIdJwtStrategy – idOnTheSource boundary coercion', () => { const payload = { sub: 'oidc-123', diff --git a/client/src/common/types.ts b/client/src/common/types.ts index 4ba4299949..a3e0a9b319 100644 --- a/client/src/common/types.ts +++ b/client/src/common/types.ts @@ -508,6 +508,7 @@ export type TAuthContext = { error: string | undefined; login: (data: t.TLoginUser) => void; logout: (redirect?: string) => void; + completeAuthentication: (token: string, user: t.TUser) => void; setError: React.Dispatch>; roles?: Record; }; diff --git a/client/src/components/Auth/AuthLayout.tsx b/client/src/components/Auth/AuthLayout.tsx index 25a1360b35..fdd43eaea2 100644 --- a/client/src/components/Auth/AuthLayout.tsx +++ b/client/src/components/Auth/AuthLayout.tsx @@ -8,6 +8,7 @@ import { BlinkAnimation } from './BlinkAnimation'; import LegalConsent from './LegalConsent'; import { Banner } from '../Banners'; import Footer from './Footer'; +import { cn } from '~/utils'; function AuthLayout({ children, @@ -53,6 +54,7 @@ function AuthLayout({ /** The bar is dropped exactly when the sentence is on the screen, so a * reader never meets both and never meets neither. */ const statesConsent = registrationStatesConsent || statesConsentBelowProviders; + const isTwoFactorSetup = pathname === '/login/2fa/setup'; const DisplayError = () => { if (hasStartupConfigError) { return ( @@ -103,7 +105,12 @@ function AuthLayout({
-
+
{!hasStartupConfigError && !isFetching && header && (

{ + const value = otpauthUrl.match(/[?&]secret=([^&]+)/)?.[1]; + return value ? decodeURIComponent(value) : ''; +}; + +const getResponseStatus = (error: unknown): number | undefined => + (error as { response?: { status?: number } } | undefined)?.response?.status; + +/** + * Every setup route gates on the enforcement policy and on the ban list before it reaches a + * controller, and both answer 403. Either way the flow is retired rather than merely rejected, so + * no phase can make progress and a reload would only replay it. Rate limiting answers 429 and a + * wrong or spent code answers 400, so neither retryable state is caught here. + */ +const isRetiredSetupFlow = (error: unknown): boolean => getResponseStatus(error) === 403; + +const isExpiredSetupCredential = (error: unknown): boolean => + getResponseStatus(error) === 401 || isRetiredSetupFlow(error); + +/** + * Acknowledgement and finalization nonces are single-use and answer 400 once consumed, so a lost + * response leaves the screen replaying a credential the server can never accept again. Spent and + * expired both have to land somewhere the user can act from rather than on an endless retry. + */ +const isSpentTransitionCredential = (error: unknown): boolean => { + const status = getResponseStatus(error); + return status === 400 || status === 401 || isRetiredSetupFlow(error); +}; + +const TwoFactorSetupScreen: React.FC = React.memo(() => { + const [searchParams] = useSearchParams(); + const navigate = useNavigate(); + const localize = useLocalize(); + const { completeAuthentication } = useAuthContext(); + const phaseRef = useRef(null); + /** + * Read at mount and adopted later only while empty: the credential arrives out of band rather + * than in the query string, a refresh on this route can hand one off after the screen rendered, + * and consuming it on completion must not flip the screen to the expired state mid-navigation. + */ + const [tempToken, setTempToken] = useState(readTwoFactorSetupToken); + const [phase, setPhase] = useState('setup'); + const [secret, setSecret] = useState(''); + const [otpauthUrl, setOtpauthUrl] = useState(''); + const [backupCodes, setBackupCodes] = useState([]); + const [verificationToken, setVerificationToken] = useState(''); + const [acknowledgementToken, setAcknowledgementToken] = useState(''); + const [finalizationToken, setFinalizationToken] = useState(''); + const [downloaded, setDownloaded] = useState(false); + const [error, setError] = useState(null); + const { mutate: enableSetup, isLoading: isGenerating } = useEnableTwoFactorSetupMutation(); + const { mutate: confirmSetup, isLoading: isVerifying } = useConfirmTwoFactorSetupMutation(); + const { mutate: acknowledgeSetup, isLoading: isAcknowledging } = + useAcknowledgeTwoFactorSetupMutation(); + const { mutate: finalizeSetup, isLoading: isFinalizing } = useFinalizeTwoFactorSetupMutation(); + const redirectTo = searchParams.get('redirect_to'); + const restartLoginPath = + redirectTo && isSafeRedirect(redirectTo) + ? `/login?redirect_to=${encodeURIComponent(redirectTo)}` + : '/login'; + + useEffect(() => { + phaseRef.current?.focus(); + }, [phase]); + + useEffect(() => { + const adoptToken = () => setTempToken((current) => current || readTwoFactorSetupToken()); + const unsubscribe = subscribeTwoFactorSetupToken(adoptToken); + adoptToken(); + return unsubscribe; + }, []); + + const restartLogin = useCallback(() => { + clearTwoFactorSetupToken(); + navigate(restartLoginPath, { replace: true }); + }, [navigate, restartLoginPath]); + + const restartLoginWhenExpired = useCallback( + (mutationError: unknown): boolean => { + if (!isExpiredSetupCredential(mutationError)) { + return false; + } + restartLogin(); + return true; + }, + [restartLogin], + ); + + const restartLoginWhenSpent = useCallback( + (mutationError: unknown): boolean => { + if (!isSpentTransitionCredential(mutationError)) { + return false; + } + restartLogin(); + return true; + }, + [restartLogin], + ); + + const handleGenerate = useCallback(() => { + setError(null); + enableSetup( + { tempToken }, + { + onSuccess: (data) => { + setOtpauthUrl(data.otpauthUrl); + setSecret(getSecret(data.otpauthUrl)); + setBackupCodes(data.backupCodes); + setPhase('qr'); + }, + onError: (mutationError) => { + if (!restartLoginWhenExpired(mutationError)) { + setError(localize('com_auth_two_factor_setup_expired')); + } + }, + }, + ); + }, [enableSetup, localize, restartLoginWhenExpired, tempToken]); + + const handleVerify = useCallback(() => { + if (verificationToken.length !== 6) { + return; + } + + setError(null); + confirmSetup( + { tempToken, token: verificationToken }, + { + onSuccess: (data) => { + if (!data.acknowledgementToken || !data.backupCodes.length) { + setError(localize('com_ui_2fa_invalid')); + return; + } + setBackupCodes(data.backupCodes); + setAcknowledgementToken(data.acknowledgementToken); + /** Confirming again rotates the codes server-side, retiring any earlier credential. */ + setFinalizationToken(''); + setDownloaded(false); + setPhase('backup'); + }, + onError: (mutationError) => { + if (!restartLoginWhenExpired(mutationError)) { + setError(localize('com_ui_2fa_invalid')); + } + }, + }, + ); + }, [confirmSetup, localize, restartLoginWhenExpired, tempToken, verificationToken]); + + const handleDownload = useCallback(() => { + if (!backupCodes.length) { + return; + } + + const blob = new Blob([backupCodes.join('\n')], { type: 'text/plain;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = 'backup-codes.txt'; + anchor.click(); + URL.revokeObjectURL(url); + setDownloaded(true); + }, [backupCodes]); + + const runFinalize = useCallback( + (token: string) => { + finalizeSetup( + { finalizationToken: token }, + { + onSuccess: ({ token: authToken, user }) => completeAuthentication(authToken, user), + onError: (mutationError) => { + if (!restartLoginWhenSpent(mutationError)) { + setError(localize('com_auth_two_factor_setup_finalize_error')); + } + }, + }, + ); + }, + [completeAuthentication, finalizeSetup, localize, restartLoginWhenSpent], + ); + + const handleComplete = useCallback(() => { + setError(null); + /** Acknowledgement nonces are single-use, so a retry reuses the finalization credential. */ + if (finalizationToken) { + runFinalize(finalizationToken); + return; + } + if (!acknowledgementToken) { + return; + } + + acknowledgeSetup( + { acknowledgementToken }, + { + onSuccess: ({ finalizationToken: issuedToken }) => { + setFinalizationToken(issuedToken); + runFinalize(issuedToken); + }, + onError: (mutationError) => { + if (!restartLoginWhenSpent(mutationError)) { + setError(localize('com_auth_two_factor_setup_finalize_error')); + } + }, + }, + ); + }, [ + acknowledgementToken, + acknowledgeSetup, + finalizationToken, + localize, + restartLoginWhenSpent, + runFinalize, + ]); + + /** + * The layout hides the sign-in controls on every setup path, so without this action a screen that + * lost its credential has nowhere to go: the message tells the user to return to sign in and the + * page offers no way to do it. Reloading only replays the same empty state. + */ + if (!tempToken) { + return ( +
+ {localize('com_auth_two_factor_setup_expired')} + +
+ ); + } + + return ( +
+

+ {localize('com_auth_two_factor_setup_required_description')} +

+ {error && {error}} +
+ {phase === 'setup' && ( + setPhase('qr')} + onError={() => setError(localize('com_auth_two_factor_setup_expired'))} + /> + )} + {phase === 'qr' && ( + setPhase('verify')} + onError={() => setError(localize('com_auth_two_factor_setup_expired'))} + /> + )} + {phase === 'verify' && ( + setError(localize('com_ui_2fa_invalid'))} + /> + )} + {phase === 'backup' && ( + setError(localize('com_ui_2fa_invalid'))} + /> + )} +
+
+ ); +}); + +export default TwoFactorSetupScreen; diff --git a/client/src/components/Auth/__tests__/TwoFactorSetupScreen.spec.tsx b/client/src/components/Auth/__tests__/TwoFactorSetupScreen.spec.tsx new file mode 100644 index 0000000000..6b0a698a8c --- /dev/null +++ b/client/src/components/Auth/__tests__/TwoFactorSetupScreen.spec.tsx @@ -0,0 +1,573 @@ +/** + * @jest-environment @happy-dom/jest-environment + */ +import React, { useCallback, useLayoutEffect, useState } from 'react'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { createMemoryRouter, MemoryRouter, RouterProvider, useNavigate } from 'react-router-dom'; +import { + readTwoFactorSetupToken, + clearTwoFactorSetupToken, + persistTwoFactorSetupToken, +} from 'librechat-data-provider'; +import type { TUser } from 'librechat-data-provider'; +import TwoFactorSetupScreen from '../TwoFactorSetupScreen'; +import StartupLayout from '~/routes/Layouts/Startup'; +import { getPostLoginRedirect } from '~/utils'; + +const mockEnableMutate = jest.fn(); +const mockConfirmMutate = jest.fn(); +const mockAcknowledgeMutate = jest.fn(); +const mockFinalizeMutate = jest.fn(); +const mockCompleteAuthentication = jest.fn(); +let mockCompleteAuthenticationImpl: (token: string, user: TUser) => void = + mockCompleteAuthentication; + +jest.mock('~/data-provider', () => ({ + useEnableTwoFactorSetupMutation: () => ({ mutate: mockEnableMutate, isLoading: false }), + useConfirmTwoFactorSetupMutation: () => ({ mutate: mockConfirmMutate, isLoading: false }), + useAcknowledgeTwoFactorSetupMutation: () => ({ + mutate: mockAcknowledgeMutate, + isLoading: false, + }), + useFinalizeTwoFactorSetupMutation: () => ({ mutate: mockFinalizeMutate, isLoading: false }), + useGetStartupConfig: () => ({ data: null, isFetching: false, error: null }), +})); + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, + useAuthContext: () => ({ completeAuthentication: mockCompleteAuthenticationImpl }), +})); + +jest.mock('~/components/Auth/AuthLayout', () => ({ children }: { children: React.ReactNode }) => ( +
{children}
+)); + +jest.mock('~/components/Nav/SettingsTabs/Account/TwoFactorPhases', () => ({ + SetupPhase: ({ onGenerate }: { onGenerate: () => void }) => ( + + ); return (
- + {localize('com_nav_2fa')}
- + {isDisableBlockedByPolicy ? ( + + ) : ( + actionButton + )}
); diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorAuthentication.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorAuthentication.tsx index 6baaa76c66..8d4fd77f4d 100644 --- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorAuthentication.tsx +++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorAuthentication.tsx @@ -2,6 +2,11 @@ import React, { useCallback, useState, useRef } from 'react'; import { useSetRecoilState } from 'recoil'; import { SmartphoneIcon } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; +import { + isTwoFactorPolicyProvider, + type TUser, + type TVerify2FARequest, +} from 'librechat-data-provider'; import { OGDialog, useToastContext, @@ -10,12 +15,12 @@ import { OGDialogTitle, Progress, } from '@librechat/client'; -import type { TUser, TVerify2FARequest } from 'librechat-data-provider'; import type { Variants } from 'framer-motion'; import { useConfirmTwoFactorMutation, useDisableTwoFactorMutation, useEnableTwoFactorMutation, + useGetStartupConfig, useVerifyTwoFactorMutation, } from '~/data-provider'; import { SetupPhase, QRPhase, VerifyPhase, BackupPhase, DisablePhase } from './TwoFactorPhases'; @@ -35,6 +40,7 @@ const phaseVariants: Variants = { const TwoFactorAuthentication: React.FC = () => { const localize = useLocalize(); const { user } = useAuthContext(); + const { data: startupConfig } = useGetStartupConfig(); const setUser = useSetRecoilState(store.user); const { showToast } = useToastContext(); const showError = useTwoFactorError(); @@ -54,16 +60,23 @@ const TwoFactorAuthentication: React.FC = () => { const { mutate: verify2FAMutate, isLoading: isVerifying } = useVerifyTwoFactorMutation(); const { mutate: disable2FAMutate, isLoading: isDisabling } = useDisableTwoFactorMutation(); - const steps = ['Setup', 'Scan QR', 'Verify', 'Backup']; - const phasesLabel: Record = { - setup: 'Setup', - qr: 'Scan QR', - verify: 'Verify', - backup: 'Backup', - disable: '', + const steps = [ + localize('com_ui_2fa_setup'), + localize('com_ui_2fa_scan_qr'), + localize('com_ui_verify'), + localize('com_ui_backup_codes'), + ]; + const phaseIndex: Record = { + setup: 0, + qr: 1, + verify: 2, + backup: 3, + disable: -1, }; - - const currentStep = steps.indexOf(phasesLabel[phase]); + const currentStep = phaseIndex[phase]; + const isTwoFactorRequired = + startupConfig?.twoFactorAuthenticationRequired === true && + isTwoFactorPolicyProvider(user?.provider); const resetState = useCallback(() => { if (user?.twoFactorEnabled && otpauthUrl) { @@ -203,6 +216,7 @@ const TwoFactorAuthentication: React.FC = () => { > setDialogOpen(true)} disabled={isVerifying || isDisabling || isGenerating} buttonRef={buttonRef} @@ -226,23 +240,18 @@ const TwoFactorAuthentication: React.FC = () => { ? localize('com_ui_2fa_disable') : localize('com_ui_2fa_setup')} - {user?.twoFactorEnabled && phase !== 'disable' && ( + {phase !== 'disable' && (
-
+
{steps.map((step, index) => ( = index - ? 'rgb(var(--text-primary))' - : 'rgb(var(--text-tertiary))', - }} - className="font-medium" + animate={{ opacity: currentStep >= index ? 1 : 0.7 }} + className="text-text-primary font-medium" > {step} diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx index 48e6fc1bf6..82c3df65d4 100644 --- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx +++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/BackupPhase.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { motion } from 'framer-motion'; import { Download } from 'lucide-react'; -import { Button, Label } from '@librechat/client'; +import { Button } from '@librechat/client'; import { useLocalize } from '~/hooks'; const fadeAnimation = { @@ -17,6 +17,7 @@ interface BackupPhaseProps { backupCodes: string[]; onDownload: () => void; downloaded: boolean; + isCompleting?: boolean; } export const BackupPhase: React.FC = ({ @@ -24,35 +25,43 @@ export const BackupPhase: React.FC = ({ onDownload, downloaded, onNext, + isCompleting = false, }) => { const localize = useLocalize(); return ( - - -
+ +

+ {localize('com_ui_download_backup_tooltip')} +

+
{backupCodes.map((code, index) => (
- #{index + 1} - {code} + #{index + 1} + {code}
))}
- -
diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx index 2056ba5860..277e692d40 100644 --- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx +++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/DisablePhase.tsx @@ -31,9 +31,12 @@ export const DisablePhase: React.FC = ({ onDisable, isDisabli const [useBackup, setUseBackup] = useState(false); return ( - +
= ({ onDisable, isDisabli type="button" variant="link" onClick={() => setUseBackup(!useBackup)} - className="h-auto p-0 text-sm text-text-primary hover:underline" + className="text-text-primary h-auto p-0 text-sm hover:underline" > {useBackup ? localize('com_ui_use_2fa_code') : localize('com_ui_use_backup_code')} diff --git a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/QRPhase.tsx b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/QRPhase.tsx index 5bce67034e..6a9b9d47af 100644 --- a/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/QRPhase.tsx +++ b/client/src/components/Nav/SettingsTabs/Account/TwoFactorPhases/QRPhase.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { motion } from 'framer-motion'; import { QRCodeSVG } from 'qrcode.react'; -import { Button, Label, SecretInput } from '@librechat/client'; +import { Button, SecretInput } from '@librechat/client'; import { useLocalize } from '~/hooks'; const fadeAnimation = { @@ -23,19 +23,17 @@ export const QRPhase: React.FC = ({ secret, otpauthUrl, onNext }) const localize = useLocalize(); return ( - +
- +
- +

{localize('com_ui_secret_key')}

= ({ isGenerating, onGenerate const localize = useLocalize(); return ( - -
-

+ +
+

{localize('com_ui_2fa_account_security')}

+ +
+ ); +} + 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; + clearCloudFrontCookies: typeof clearCloudFrontCookies; + setAuthTokens: ( + userId: UserDocumentId, + res: Response, + unused: null, + req: Request, + ) => Promise; +} + +interface EnrollmentControllers { + verify2FAWithTempToken: (req: ChallengeRequest, res: Response) => Promise; + confirm2FASetupWithTempToken: (req: SetupRequest, res: Response) => Promise; + acknowledge2FASetup: (req: SetupRequest, res: Response) => Promise; + finalize2FASetup: (req: SetupRequest, res: Response) => Promise; +} + +export function createEnrollmentControllers( + deps: EnrollmentControllerDependencies, +): EnrollmentControllers { + const sanitizeUser = (user: StoredTwoFactorAccount) => ({ + ...sanitizeUserForResponse(user), + id: user._id.toString(), + }); + + const revokeMintedSession = ( + res: Response, + user: StoredTwoFactorAccount, + userId: string, + ): Promise => withdrawMintedSession(res, user, userId, deps); + + const verify2FAWithTempToken = async ( + req: ChallengeRequest, + res: Response, + ): Promise => { + try { + const { tempToken, token, backupCode } = req.body; + if (!tempToken) { + return res.status(400).json({ message: 'Missing temporary token' }); + } + + const credential = verifyTwoFactorLoginChallengeToken(tempToken, process.env.JWT_SECRET); + if (!credential) { + return res.status(401).json({ message: 'Invalid or expired temporary token' }); + } + + const user = await deps.getUserById(credential.userId, '+totpSecret +backupCodes'); + if (!user || !user.twoFactorEnabled) { + return res.status(400).json({ message: '2FA is not enabled for this user' }); + } + + if (isCredentialLoginBlockedByTwoFactorPolicy(user)) { + logger.warn( + `[verify2FAWithTempToken] Refused a password challenge for a federated record under required 2FA [provider: ${user.provider}]`, + ); + return res.status(403).json({ + code: TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE, + message: 'Sign in with your identity provider to continue.', + }); + } + + if (isTokenRetired(credential, user)) { + logger.warn( + `[verify2FAWithTempToken] Challenge predates enrollment or password reset: userId=${credential.userId}`, + ); + return res.status(401).json({ message: 'Invalid or expired temporary token' }); + } + + const secret = await deps.getTOTPSecret(user.totpSecret); + let isVerified = false; + if (token) { + isVerified = await deps.verifyTOTP(secret, token); + } else if (backupCode) { + isVerified = await deps.verifyBackupCode({ user, backupCode }); + } + + if (!isVerified) { + return res.status(401).json({ message: 'Invalid 2FA code or backup code' }); + } + + const userData = sanitizeUser(user); + const authToken = await deps.setAuthTokens(user._id, res, null, req); + const retirement = await recheckMintedCredential( + () => deps.getUserById(credential.userId, TOKEN_RETIREMENT_FIELDS), + () => revokeMintedSession(res, user, credential.userId), + ); + if (isTokenRetired(credential, retirement)) { + logger.warn( + `[verify2FAWithTempToken] Password was reset while the challenge was being verified: userId=${credential.userId}`, + ); + await revokeMintedSession(res, user, credential.userId); + return res.status(401).json({ message: 'Invalid or expired temporary token' }); + } + + return res.status(200).json({ token: authToken, user: userData }); + } catch (err) { + logger.error('[verify2FAWithTempToken]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + const confirm2FASetupWithTempToken = async ( + req: SetupRequest, + res: Response, + ): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ message: 'Invalid or expired two-factor setup token' }); + } + + const result = await confirmTwoFactorSetup(userId, req.body?.token, deps); + if (!result.ok) { + return res.status(result.status).json({ message: result.message }); + } + + const acknowledgementToken = generateTwoFactorSetupAcknowledgementToken( + userId, + result.acknowledgementNonce, + process.env.JWT_SECRET!, + ); + return res.status(200).json({ backupCodes: result.plainCodes, acknowledgementToken }); + } catch (err) { + logger.error('[confirm2FASetupWithTempToken]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + const acknowledge2FASetup = async (req: SetupRequest, res: Response): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + return res + .status(401) + .json({ message: 'Invalid or expired two-factor acknowledgement token' }); + } + + const result = await acknowledgeTwoFactorSetup(userId, req.twoFactorEnrollmentNonce, deps); + if (!result.ok) { + return res.status(result.status).json({ message: result.message }); + } + + const finalizationToken = generateTwoFactorSetupFinalizationToken( + userId, + result.finalizationNonce, + process.env.JWT_SECRET!, + ); + return res.status(200).json({ finalizationToken }); + } catch (err) { + logger.error('[acknowledge2FASetup]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + const finalize2FASetup = async (req: SetupRequest, res: Response): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + return res + .status(401) + .json({ message: 'Invalid or expired two-factor finalization token' }); + } + + const result = await finalizeTwoFactorSetup(userId, req.twoFactorEnrollmentNonce, deps); + if (!result.ok) { + return res.status(result.status).json({ message: result.message }); + } + + const userData = sanitizeUser(result.user); + await deps.deleteAllUserSessions({ userId: result.user._id.toString() }); + const authToken = await deps.setAuthTokens(result.user._id, res, null, req); + const retirement = await recheckMintedCredential( + () => deps.getUserById(userId, TOKEN_RETIREMENT_FIELDS), + () => revokeMintedSession(res, result.user, userId), + ); + if ( + isEnrollmentSupersededByRecovery( + result.user.twoFactorEnrolledAt, + retirement?.credentialsChangedAt, + ) + ) { + await revokeMintedSession(res, result.user, userId); + return res + .status(401) + .json({ message: 'Password was reset during setup, please sign in again' }); + } + + return res.status(200).json({ token: authToken, user: userData }); + } catch (err) { + logger.error('[finalize2FASetup]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + return { + verify2FAWithTempToken, + confirm2FASetupWithTempToken, + acknowledge2FASetup, + finalize2FASetup, + }; +} diff --git a/packages/api/src/auth/gates.spec.ts b/packages/api/src/auth/gates.spec.ts new file mode 100644 index 0000000000..ecc31a8247 --- /dev/null +++ b/packages/api/src/auth/gates.spec.ts @@ -0,0 +1,61 @@ +import { getTenantId, SYSTEM_TENANT_ID } from '@librechat/data-schemas'; +import type { NextFunction, Request, Response } from 'express'; +import { createRequiredTwoFactorGate } from './gates'; + +function createResponse(): { res: Response; status: jest.Mock; json: jest.Mock } { + const status = jest.fn(); + const json = jest.fn(); + const res = { status, json } as unknown as Response; + status.mockReturnValue(res); + return { res, status, json }; +} + +describe('required two-factor gate', () => { + 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; + } + }); + + /** + * The gate runs before tenant middleware, so under strict tenant isolation an unscoped user read + * throws and the hand-off becomes a 500. + */ + it('reads the retirement cutoff in system scope and hands off to setup', async () => { + let readScope: string | undefined; + const gate = createRequiredTwoFactorGate({ + clearCloudFrontCookies: jest.fn(), + warn: jest.fn(), + generateSetupToken: () => 'setup-token', + getUserById: jest.fn(async () => { + readScope = getTenantId(); + return {}; + }), + }); + const { res, status, json } = createResponse(); + const req = { + path: '/api/convos', + headers: {}, + user: { id: 'user-1', provider: 'local' }, + } as unknown as Request; + const onAllowed = jest.fn(); + const next = jest.fn() as NextFunction; + + gate(req, res, next, onAllowed); + await new Promise((resolve) => setImmediate(resolve)); + + expect(readScope).toBe(SYSTEM_TENANT_ID); + expect(status).toHaveBeenCalledWith(403); + expect(json).toHaveBeenCalledWith( + expect.objectContaining({ twoFASetupRequired: true, tempToken: 'setup-token' }), + ); + expect(onAllowed).not.toHaveBeenCalled(); + expect(next).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/api/src/auth/gates.ts b/packages/api/src/auth/gates.ts new file mode 100644 index 0000000000..e701fc0fb5 --- /dev/null +++ b/packages/api/src/auth/gates.ts @@ -0,0 +1,154 @@ +import jwt from 'jsonwebtoken'; +import { runAsSystem } from '@librechat/data-schemas'; +import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from 'librechat-data-provider'; +import type { NextFunction, Request, Response } from 'express'; +import type { TokenIssuance, TokenRetirementSignals, TwoFactorAccount } from './twoFactor'; +import type { CloudFrontCookieScope } from '~/cdn/cloudfront-cookies'; +import { + generateTwoFactorSetupToken, + isTokenRetired, + isTwoFactorEnrollmentRequired, + TOKEN_RETIREMENT_FIELDS, +} from './twoFactor'; + +type AuthUser = Pick< + TwoFactorAccount, + '_id' | 'id' | 'provider' | 'tenantId' | 'orgId' | 'storageRegion' | 'twoFactorEnabled' +>; + +type AuthRequest = Request & { user?: AuthUser; authStrategy?: string }; + +export interface TwoFactorGateDependencies { + clearCloudFrontCookies: (res: Response, scope: CloudFrontCookieScope) => void; + getUserById: (userId: string, projection: string) => Promise; + warn: (message: string) => void; + generateSetupToken?: typeof generateTwoFactorSetupToken; + enrollmentRequired?: typeof isTwoFactorEnrollmentRequired; + tokenRetired?: typeof isTokenRetired; +} + +export function clearEnrollmentViewer( + req: AuthRequest, + res: Response, + user: AuthUser | null | undefined, + deps: Pick, +): boolean { + if (!(deps.enrollmentRequired ?? isTwoFactorEnrollmentRequired)(user)) { + return false; + } + deps.clearCloudFrontCookies(res, { + userId: user?.id?.toString() ?? user?._id?.toString(), + tenantId: user?.tenantId ?? user?.orgId, + storageRegion: user?.storageRegion, + }); + delete req.user; + delete req.authStrategy; + return true; +} + +const normalizeRouteSegment = (value: string): string => + typeof value === 'string' ? value.toLowerCase().replace(/\/+$/, '') : ''; + +function isPolicyAllowlisted(req: Request): boolean { + return ( + req.method === 'POST' && + normalizeRouteSegment(req.baseUrl) === '/api/auth' && + normalizeRouteSegment(req.path) === '/logout' + ); +} + +function getAuthorizingCredential(req: Request): TokenIssuance { + const authorization = req.headers.authorization; + const value = Array.isArray(authorization) ? authorization[0] : authorization; + const token = typeof value === 'string' ? value.replace(/^Bearer\s+/i, '') : ''; + const decoded = token ? jwt.decode(token) : null; + const payload = decoded && typeof decoded === 'object' ? decoded : null; + return { + issuedAt: typeof payload?.iat === 'number' ? payload.iat : undefined, + issuedAtMs: typeof payload?.issuedAtMs === 'number' ? payload.issuedAtMs : undefined, + }; +} + +/** The cutoff read is deliberately after minting the setup token. */ +export function createRequiredTwoFactorGate(deps: TwoFactorGateDependencies) { + return (req: AuthRequest, res: Response, next: NextFunction, onAllowed: () => void): void => { + if ( + !(deps.enrollmentRequired ?? isTwoFactorEnrollmentRequired)(req.user) || + isPolicyAllowlisted(req) + ) { + onAllowed(); + return; + } + + void (async () => { + const user = req.user; + const userId = (user?.id?.toString() ?? user?._id?.toString()) as string; + deps.clearCloudFrontCookies(res, { + userId, + tenantId: user?.tenantId ?? user?.orgId, + storageRegion: user?.storageRegion, + }); + const tempToken = (deps.generateSetupToken ?? generateTwoFactorSetupToken)( + userId, + process.env.JWT_SECRET as string, + ); + /** Tenant context is established only after this gate, as the JWT strategy's own read is. */ + const retirement = await runAsSystem(() => deps.getUserById(userId, TOKEN_RETIREMENT_FIELDS)); + if ((deps.tokenRetired ?? isTokenRetired)(getAuthorizingCredential(req), retirement)) { + deps.warn( + `[requireJwtAuth] Password was reset while the request was in flight: userId=${userId}`, + ); + res.status(401).json({ message: 'Unauthorized' }); + return; + } + res.status(403).json({ + code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE, + twoFAPending: true, + twoFASetupRequired: true, + tempToken, + }); + })().catch(next); + }; +} + +export function continueAfterOptionalAuth( + req: AuthRequest, + res: Response, + next: NextFunction, + user: AuthUser, + strategy: string, + tenantContextMiddleware: (req: Request, res: Response, next: NextFunction) => void, + deps: Pick, +): void { + if (clearEnrollmentViewer(req, res, user, deps)) { + next(); + return; + } + req.user = user; + req.authStrategy = strategy; + tenantContextMiddleware(req, res, next); +} + +/** Keeps the strategy callback and its accepted-user path in the caller. */ +export function continueAfterBearerRetirement( + user: TokenRetirementSignals, + issuance: TokenIssuance, + kind: 'jwt' | 'openidJwt', + subject: string | undefined, + done: (error: null, user: false, info?: { message: string }) => void, + warn: (message: string) => void, + onAllowed: () => Promise | void, + tokenRetired: typeof isTokenRetired = isTokenRetired, +): Promise | void { + if (tokenRetired(issuance, user)) { + const label = kind === 'jwt' ? 'jwtLogin] JwtStrategy' : 'openIdJwtLogin] openId JwtStrategy'; + warn(`[${label} => token predates enrollment or password reset: ${subject}`); + done( + null, + false, + kind === 'openidJwt' ? { message: 'Token predates enrollment or password reset' } : undefined, + ); + return; + } + return onAllowed(); +} diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.ts index eaf2f21b94..97ec41de69 100644 --- a/packages/api/src/auth/index.ts +++ b/packages/api/src/auth/index.ts @@ -20,3 +20,14 @@ export * from './emailChangeStore'; export * from './passwordReset'; export * from './reuse'; export * from './openid/index'; +export * from './twoFactor'; +export * from './user'; +export * from './localRefresh'; +export * from './openid/reuseCredential'; +export * from './passwordResetUpdate'; +export * from './login'; +export * from './enrollment'; +export * from './gates'; +export * from './share'; +export * from './limiter'; +export * from './tempuser'; diff --git a/packages/api/src/auth/limiter.ts b/packages/api/src/auth/limiter.ts new file mode 100644 index 0000000000..16e8c2e70e --- /dev/null +++ b/packages/api/src/auth/limiter.ts @@ -0,0 +1,157 @@ +import jwt from 'jsonwebtoken'; +import { createHash } from 'node:crypto'; +import { rateLimit } from 'express-rate-limit'; +import { ViolationTypes } from 'librechat-data-provider'; +import type { NextFunction, Request, Response } from 'express'; +import type { Store } from 'express-rate-limit'; +import type { TwoFactorTempRequest } from './tempuser'; + +type ViolationMessage = { + type: ViolationTypes; + max: string | number; + limiter: string; + windowInMinutes: number; +}; + +export interface TwoFactorLimiterDependencies { + env: NodeJS.ProcessEnv; + limiterCache: (prefix: string) => Store | undefined; + removePorts: (req: Request) => string | undefined; + logViolation: ( + req: Request, + res: Response, + type: ViolationTypes, + message: ViolationMessage, + score: string | number | undefined, + ) => Promise; +} + +interface TwoFactorLimiterPolicy { + namespace: string; + windowMinutes: string | number; + max: string | number; + score: string | number | undefined; + describeAttempts: string; +} + +export function createTwoFactorLimiter( + deps: TwoFactorLimiterDependencies, + policy: TwoFactorLimiterPolicy, +) { + const { namespace, max, score, describeAttempts } = policy; + const windowMs = Number(policy.windowMinutes) * 60 * 1000; + const windowInMinutes = windowMs / 60000; + const message = `Too many ${describeAttempts}, please try again after ${windowInMinutes} minutes.`; + + const getEnrollmentToken = (req: TwoFactorTempRequest): string | undefined => + req.body?.[req.twoFactorTokenField ?? 'tempToken']; + + const getUserLimiterKey = (req: Request): string => { + const tempReq = req as TwoFactorTempRequest; + const userId = tempReq.user?.id ?? tempReq.user?._id; + if (userId) { + return `user:${userId.toString()}`; + } + const token = getEnrollmentToken(tempReq); + if (typeof token === 'string' && token) { + return `temp:${createHash('sha256').update(token).digest('hex')}`; + } + const ip = deps.removePorts(req); + return ip ? `ip:${ip}` : 'ip:unknown'; + }; + + const getTempTokenUserId = (token: string | undefined): string | null => { + if (!token) { + return null; + } + try { + const payload = jwt.verify(token, deps.env.JWT_SECRET ?? ''); + return typeof payload === 'object' && typeof payload.userId === 'string' + ? payload.userId + : null; + } catch { + return null; + } + }; + + const createHandler = + (limiter: string) => + async (req: Request, res: Response): Promise => { + const type = ViolationTypes.LOGINS; + const errorMessage = { type, max, limiter, windowInMinutes }; + const tempReq = req as TwoFactorTempRequest; + const userId = getTempTokenUserId(getEnrollmentToken(tempReq)); + if (userId && !tempReq.user) { + tempReq.user = { id: userId }; + } else if (userId && tempReq.user && !tempReq.user.id && !tempReq.user._id) { + tempReq.user.id = userId; + } + await deps.logViolation(req, res, type, errorMessage, score); + return res.status(429).json({ message }); + }; + + const ipLimiter = rateLimit({ + windowMs, + max: Number(max), + skip: (req) => + namespace === 'two_factor_setup' && + Boolean((req as TwoFactorTempRequest).user?.id ?? (req as TwoFactorTempRequest).user?._id), + handler: createHandler('ip'), + keyGenerator: deps.removePorts as (req: Request) => string, + store: deps.limiterCache(`${namespace}_limiter`), + }); + const userLimiter = rateLimit({ + windowMs, + max: Number(max), + handler: createHandler('user'), + keyGenerator: getUserLimiterKey, + store: deps.limiterCache(`${namespace}_user_limiter`), + }); + + return (req: Request, res: Response, next: NextFunction): void => { + ipLimiter(req, res, (error) => { + if (error) { + next(error); + return; + } + userLimiter(req, res, next); + }); + }; +} + +export function createTwoFactorLimiters(deps: TwoFactorLimiterDependencies): { + twoFactorTempLimiter: (req: Request, res: Response, next: NextFunction) => void; + twoFactorSetupLimiter: (req: Request, res: Response, next: NextFunction) => void; +} { + const { + LOGIN_WINDOW = 5, + LOGIN_MAX = 7, + LOGIN_VIOLATION_SCORE, + TWO_FACTOR_TEMP_WINDOW = LOGIN_WINDOW, + TWO_FACTOR_TEMP_MAX = LOGIN_MAX, + TWO_FACTOR_TEMP_VIOLATION_SCORE, + TWO_FACTOR_SETUP_WINDOW = TWO_FACTOR_TEMP_WINDOW, + TWO_FACTOR_SETUP_MAX = 20, + TWO_FACTOR_SETUP_VIOLATION_SCORE, + } = deps.env; + + return { + twoFactorTempLimiter: createTwoFactorLimiter(deps, { + namespace: 'two_factor_temp', + windowMinutes: TWO_FACTOR_TEMP_WINDOW, + max: TWO_FACTOR_TEMP_MAX, + score: TWO_FACTOR_TEMP_VIOLATION_SCORE ?? LOGIN_VIOLATION_SCORE, + describeAttempts: 'verification attempts', + }), + twoFactorSetupLimiter: createTwoFactorLimiter(deps, { + namespace: 'two_factor_setup', + windowMinutes: TWO_FACTOR_SETUP_WINDOW, + max: TWO_FACTOR_SETUP_MAX, + score: + TWO_FACTOR_SETUP_VIOLATION_SCORE ?? + TWO_FACTOR_TEMP_VIOLATION_SCORE ?? + LOGIN_VIOLATION_SCORE, + describeAttempts: 'two-factor setup requests', + }), + }; +} diff --git a/packages/api/src/auth/localRefresh.ts b/packages/api/src/auth/localRefresh.ts new file mode 100644 index 0000000000..6156e65e0f --- /dev/null +++ b/packages/api/src/auth/localRefresh.ts @@ -0,0 +1,197 @@ +import jwt from 'jsonwebtoken'; +import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from 'librechat-data-provider'; +import type { ISession, OIDCTokens } from '@librechat/data-schemas'; +import type { Request, Response } from 'express'; +import type { TokenIssuance, TwoFactorAccount } from './twoFactor'; +import { + generateTwoFactorSetupToken, + isTokenRetired, + recheckMintedCredential, + withdrawMintedSession, + isTwoFactorEnrollmentRequired, + TOKEN_RETIREMENT_FIELDS, +} from './twoFactor'; + +const EXPIRED_REFRESH_MESSAGE = 'Refresh token expired or not found for this user'; + +type UserIdentifier = string | { toString(): string }; + +type RefreshUser = Pick< + TwoFactorAccount, + | '_id' + | 'provider' + | 'tenantId' + | 'orgId' + | 'storageRegion' + | 'twoFactorEnabled' + | 'twoFactorEnrolledAt' + | 'credentialsChangedAt' +>; + +type RefreshSession = Pick & { _id: UserIdentifier }; +type SessionDeletionResult = { deletedCount?: number }; +type AuthResponseSource = TwoFactorAccount & { __v?: number; federatedTokens?: OIDCTokens }; + +interface LocalRefreshDependencies { + userProjection: string; + getUserById: (userId: string, projection: string) => Promise; + findSession: ( + query: { userId: string; refreshToken: string }, + options: { lean: false }, + ) => Promise; + setAuthTokens: ( + userId: string, + res: Response, + session: RefreshSession | null, + req: Request, + ) => Promise; + deleteSession: (query: { sessionId: string }) => Promise; + deleteAllUserSessions: (query: { userId: string }) => Promise; + clearCloudFrontCookies: ( + res: Response, + scope: { userId: string; tenantId?: string; storageRegion?: string }, + ) => void; + generateTwoFactorSetupToken?: typeof generateTwoFactorSetupToken; + isTwoFactorEnrollmentRequired?: typeof isTwoFactorEnrollmentRequired; + warn: (message: string) => void; + error: (message: string, cause: unknown) => void; +} + +/** + * Preserve the refresh response contract. The shared allowlist excludes `openidId`, which existing + * OpenID refresh clients receive and the controller tests assert, so switching sanitizers here + * would silently change the response shape. + */ +export function sanitizeUserForAuthResponse( + user: T | null | undefined, +): Partial { + const hydrated = user as (T & { toObject?: () => AuthResponseSource }) | null | undefined; + const source = (typeof hydrated?.toObject === 'function' ? hydrated.toObject() : hydrated) ?? {}; + const { + password: _password, + __v: _version, + totpSecret: _totpSecret, + backupCodes: _backupCodes, + pendingTotpSecret: _pendingTotpSecret, + pendingBackupCodes: _pendingBackupCodes, + twoFactorAcknowledgementNonceHash: _acknowledgementHash, + twoFactorFinalizationNonceHash: _finalizationHash, + federatedTokens: _federatedTokens, + ...safeUser + } = source as AuthResponseSource; + return safeUser as Partial; +} + +/** Handles only the local refresh branch after OpenID ownership has been resolved. */ +export function createLocalRefreshHandler(deps: LocalRefreshDependencies) { + const requiresEnrollment = deps.isTwoFactorEnrollmentRequired ?? isTwoFactorEnrollmentRequired; + const mintSetupToken = deps.generateTwoFactorSetupToken ?? generateTwoFactorSetupToken; + + /** + * The session lookup resolves before the response credential is minted. Recovery may land in + * between, deleting the old session while the newly minted token postdates credentialsChangedAt. + * Read the cutoff after minting so that race withdraws the resurrected session. + */ + const isCredentialRetired = async (userId: string, credential: TokenIssuance) => { + const current = await deps.getUserById(userId, TOKEN_RETIREMENT_FIELDS); + return isTokenRetired(credential, current); + }; + + const revokeSession = (res: Response, user: RefreshUser, userId: string) => + withdrawMintedSession(res, user, userId, deps); + + const withdrawSession = async (res: Response, user: RefreshUser, userId: string) => { + deps.warn( + `[refreshController] Password was reset while the refresh was in flight: userId=${userId}`, + ); + await revokeSession(res, user, userId); + return res.status(401).send(EXPIRED_REFRESH_MESSAGE); + }; + + return async ( + req: Request, + res: Response, + refreshToken: string | undefined, + ): Promise => { + if (!refreshToken) { + return res.status(200).send('Refresh token not provided'); + } + + try { + const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET ?? ''); + if (typeof payload === 'string' || typeof payload.id !== 'string') { + throw new Error('Invalid refresh token payload'); + } + const userId = payload.id; + const user = await deps.getUserById(userId, deps.userProjection); + if (!user) { + return res.status(401).redirect('/login'); + } + + const credential: TokenIssuance = { + issuedAt: payload.iat, + issuedAtMs: typeof payload.issuedAtMs === 'number' ? payload.issuedAtMs : undefined, + }; + /** + * Enrollment stamps its cutoff before session revocation. Dating the incoming credential + * closes that gap even if revocation fails, and also covers password recovery. + */ + if (isTokenRetired(credential, user)) { + deps.warn( + `[refreshController] Refresh token predates enrollment or password reset: userId=${userId}`, + ); + res.clearCookie('refreshToken'); + return res.status(401).send(EXPIRED_REFRESH_MESSAGE); + } + + if (process.env.NODE_ENV === 'CI') { + const token = await deps.setAuthTokens(userId, res, null, req); + return res.status(200).send({ token, user: sanitizeUserForAuthResponse(user) }); + } + + const session = await deps.findSession({ userId, refreshToken }, { lean: false }); + if (session && session.expiration > new Date()) { + if (requiresEnrollment(user)) { + await deps.deleteSession({ sessionId: session._id.toString() }); + res.clearCookie('refreshToken'); + deps.clearCloudFrontCookies(res, { + userId, + tenantId: user.tenantId ?? user.orgId, + storageRegion: user.storageRegion, + }); + /** The setup token outranks the refresh credential that bought it. */ + const tempToken = mintSetupToken(userId, process.env.JWT_SECRET ?? ''); + if (await isCredentialRetired(userId, credential)) { + return withdrawSession(res, user, userId); + } + return res.status(200).send({ + code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE, + twoFAPending: true, + twoFASetupRequired: true, + tempToken, + }); + } + + const token = await deps.setAuthTokens(userId, res, session, req); + const retired = await recheckMintedCredential( + () => isCredentialRetired(userId, credential), + () => revokeSession(res, user, userId), + ); + if (retired) { + return withdrawSession(res, user, userId); + } + return res.status(200).send({ token, user: sanitizeUserForAuthResponse(user) }); + } + if (req.query?.retry) { + return res.status(403).send('No session found'); + } + if (typeof payload.exp === 'number' && payload.exp < Date.now() / 1000) { + return res.status(403).redirect('/login'); + } + return res.status(401).send(EXPIRED_REFRESH_MESSAGE); + } catch (error) { + deps.error('[refreshController] Invalid refresh token:', error); + return res.status(403).send('Invalid refresh token'); + } + }; +} diff --git a/packages/api/src/auth/login.ts b/packages/api/src/auth/login.ts new file mode 100644 index 0000000000..bc5d70bead --- /dev/null +++ b/packages/api/src/auth/login.ts @@ -0,0 +1,117 @@ +import { logger } from '@librechat/data-schemas'; +import { + TWO_FACTOR_ENROLLMENT_REQUIRED_CODE, + TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE, +} from 'librechat-data-provider'; +import type { Request, Response } from 'express'; +import type { StoredTwoFactorAccount } from './twoFactor'; +import type { UserDocumentId } from '~/auth/verification'; +import { + TOKEN_RETIREMENT_FIELDS, + recheckMintedCredential, + withdrawMintedSession, + generateTwoFactorSetupToken, + hasPasswordResetSince, + isCredentialLoginBlockedByTwoFactorPolicy, + isTwoFactorEnrollmentRequired, +} from './twoFactor'; +import { clearCloudFrontCookies } from '~/cdn'; + +type LoginUser = StoredTwoFactorAccount & { __v?: number }; +type LoginRequest = Request & { user?: LoginUser }; + +export interface LoginDependencies { + getUserById: (userId: string, projection: string) => Promise; + deleteAllUserSessions: (input: { userId: string }) => Promise; + clearCloudFrontCookies: typeof clearCloudFrontCookies; + generate2FATempToken: (userId: UserDocumentId) => string; + setAuthTokens: ( + userId: UserDocumentId, + res: Response, + unused: null, + req: Request, + ) => Promise; +} + +export function createLoginController(deps: LoginDependencies) { + const wasPasswordRevokedDuringLogin = async (user: LoginUser): Promise => { + const current = await deps.getUserById(user._id.toString(), TOKEN_RETIREMENT_FIELDS); + return hasPasswordResetSince(user.credentialsChangedAt, current?.credentialsChangedAt); + }; + + const refuseRevokedLogin = (res: Response, user: LoginUser): Response => { + logger.warn( + `[loginController] Refused a login whose password was reset while it was in flight [userId: ${user._id}]`, + ); + return res.status(401).json({ message: 'Invalid credentials' }); + }; + + const withdrawLoginSession = (res: Response, user: LoginUser): Promise => + withdrawMintedSession(res, user, user._id.toString(), deps); + + return async (req: LoginRequest, res: Response): Promise => { + try { + if (!req.user) { + return res.status(400).json({ message: 'Invalid credentials' }); + } + + if (isCredentialLoginBlockedByTwoFactorPolicy(req.user)) { + logger.warn( + `[loginController] Refused a password login for a federated record under required 2FA [provider: ${req.user.provider}] [Request-IP: ${req.ip}]`, + ); + return res.status(403).json({ + code: TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE, + message: 'Sign in with your identity provider to continue.', + }); + } + + if (req.user.twoFactorEnabled) { + const tempToken = deps.generate2FATempToken(req.user._id); + if (await wasPasswordRevokedDuringLogin(req.user)) { + return refuseRevokedLogin(res, req.user); + } + return res.status(200).json({ twoFAPending: true, tempToken }); + } + + if (isTwoFactorEnrollmentRequired(req.user)) { + deps.clearCloudFrontCookies(res, { + userId: req.user._id.toString(), + tenantId: req.user.tenantId ?? req.user.orgId, + storageRegion: req.user.storageRegion, + }); + const tempToken = generateTwoFactorSetupToken( + req.user._id.toString(), + process.env.JWT_SECRET!, + ); + if (await wasPasswordRevokedDuringLogin(req.user)) { + return refuseRevokedLogin(res, req.user); + } + return res.status(200).json({ + code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE, + twoFAPending: true, + twoFASetupRequired: true, + tempToken, + }); + } + + const { password: _p, totpSecret: _t, __v, ...user } = req.user; + user.id = user._id.toString(); + + const loginUser = req.user; + const token = await deps.setAuthTokens(loginUser._id, res, null, req); + const revoked = await recheckMintedCredential( + () => wasPasswordRevokedDuringLogin(loginUser), + () => withdrawLoginSession(res, loginUser), + ); + if (revoked) { + await withdrawLoginSession(res, loginUser); + return refuseRevokedLogin(res, loginUser); + } + + return res.status(200).send({ token, user }); + } catch (err) { + logger.error('[loginController]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; +} diff --git a/packages/api/src/auth/openid/reuseCredential.ts b/packages/api/src/auth/openid/reuseCredential.ts new file mode 100644 index 0000000000..5a48eddc5e --- /dev/null +++ b/packages/api/src/auth/openid/reuseCredential.ts @@ -0,0 +1,41 @@ +import jwt from 'jsonwebtoken'; +import { createHash } from 'node:crypto'; +import type { TokenIssuance } from '../twoFactor'; + +export interface OpenIDReuseCredential extends TokenIssuance { + userId: string; +} + +/** Verify the identity cookie and, when supplied, bind it to the source refresh token. */ +export function getValidOpenIDReuseCredential( + parsedCookies: { openid_user_id?: string }, + jwtRefreshSecret: string | undefined, + refreshToken?: string, +): OpenIDReuseCredential | null { + if (!parsedCookies.openid_user_id || !jwtRefreshSecret) { + return null; + } + + try { + const payload = jwt.verify(parsedCookies.openid_user_id, jwtRefreshSecret); + if (typeof payload === 'string' || typeof payload.id !== 'string') { + return null; + } + if (refreshToken != null) { + if (typeof payload.refreshTokenHash !== 'string') { + return null; + } + const hash = createHash('sha256').update(refreshToken).digest('base64url'); + if (payload.refreshTokenHash !== hash) { + return null; + } + } + return { + userId: payload.id, + issuedAt: payload.iat, + issuedAtMs: typeof payload.issuedAtMs === 'number' ? payload.issuedAtMs : undefined, + }; + } catch { + return null; + } +} diff --git a/packages/api/src/auth/passwordReset.spec.ts b/packages/api/src/auth/passwordReset.spec.ts index 311f56dc34..dcc1f225ab 100644 --- a/packages/api/src/auth/passwordReset.spec.ts +++ b/packages/api/src/auth/passwordReset.spec.ts @@ -77,7 +77,14 @@ describe('commitPasswordReset', () => { await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); expect(deps.updateUser).toHaveBeenCalledWith( 'user-reset', - { password: 'hashed-password', credentialsChangedAt: expect.any(Date) }, + { + password: 'hashed-password', + credentialsChangedAt: expect.any(Date), + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }, { email: 'user@example.com' }, ); }); diff --git a/packages/api/src/auth/passwordReset.ts b/packages/api/src/auth/passwordReset.ts index 50fc044b99..b6d5efa735 100644 --- a/packages/api/src/auth/passwordReset.ts +++ b/packages/api/src/auth/passwordReset.ts @@ -1,5 +1,7 @@ import { logger } from '@librechat/data-schemas'; import type { Request, Response } from 'express'; +import type { PasswordResetUpdate } from './passwordResetUpdate'; +import { createPasswordResetUpdate } from './passwordResetUpdate'; import { EMAIL_CHANGE_TOKEN_TYPE } from './email'; /** The stored reset token, in both the typed shape and the untyped legacy one. */ @@ -23,7 +25,7 @@ export interface PasswordResetDeps { getUserById: (userId: string, select: string) => Promise; updateUser: ( userId: string, - update: { password: string; credentialsChangedAt: Date }, + update: PasswordResetUpdate, expectedState: { email: string }, ) => Promise; deleteTokens: (query: { userId: string; type: string }) => Promise; @@ -158,8 +160,7 @@ export async function commitPasswordReset( const user = await deps.updateUser( input.userId, - /** Stamped with the new password so access tokens issued before the reset stop verifying */ - { password: deps.hashPassword(input.password), credentialsChangedAt: new Date() }, + createPasswordResetUpdate(deps.hashPassword(input.password)), { email: account.email }, ); if (!user) { diff --git a/packages/api/src/auth/passwordResetUpdate.ts b/packages/api/src/auth/passwordResetUpdate.ts new file mode 100644 index 0000000000..1944ec739c --- /dev/null +++ b/packages/api/src/auth/passwordResetUpdate.ts @@ -0,0 +1,27 @@ +import type { TwoFactorEnrollmentUpdate } from '@librechat/data-schemas'; + +export type PasswordResetUpdate = { password?: string; credentialsChangedAt?: Date | null } & Pick< + TwoFactorEnrollmentUpdate, + | 'pendingTotpSecret' + | 'pendingBackupCodes' + | 'twoFactorAcknowledgementNonceHash' + | 'twoFactorFinalizationNonceHash' +>; + +/** + * Retire bearer credentials from the replaced password. Clearing the staged enrollment in this + * same write prevents an old setup credential from promoting its secret after recovery. + */ +export function createPasswordResetUpdate( + passwordHash: string, + resetAt: Date = new Date(), +): PasswordResetUpdate { + return { + password: passwordHash, + credentialsChangedAt: resetAt, + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }; +} diff --git a/packages/api/src/auth/share.ts b/packages/api/src/auth/share.ts new file mode 100644 index 0000000000..49bfd3fa98 --- /dev/null +++ b/packages/api/src/auth/share.ts @@ -0,0 +1,146 @@ +import jwt from 'jsonwebtoken'; +import { SystemRoles } from 'librechat-data-provider'; +import type { NextFunction, Request, Response } from 'express'; +import type { StoredTwoFactorAccount, TokenIssuance } from './twoFactor'; +import type { CloudFrontCookieScope } from '~/cdn/cloudfront-cookies'; +import { isTokenRetired, isTwoFactorEnrollmentRequired } from './twoFactor'; +import { clearEnrollmentViewer } from './gates'; +import { isEnabled } from '~/utils'; + +type ShareUser = Pick< + StoredTwoFactorAccount, + | '_id' + | 'id' + | 'provider' + | 'role' + | 'tenantId' + | 'orgId' + | 'storageRegion' + | 'twoFactorEnabled' + | 'twoFactorEnrolledAt' + | 'credentialsChangedAt' +>; +type ShareRequest = Request & { + user?: ShareUser; + authStrategy?: string; + session?: { openidTokens?: { refreshToken?: string } }; +}; +type VerifiedUser = TokenIssuance & { userId: string }; + +export interface ShareFileAuthDependencies { + parseCookie: (header: string) => Record; + getUserById: (userId: string, projection: string) => Promise; + findSession: (filter: { userId: string; refreshToken: string }) => Promise; + runAsSystem: (fn: () => Promise) => Promise; + clearCloudFrontCookies: (res: Response, scope: CloudFrontCookieScope) => void; + warn: (message: string, detail?: string) => void; + enrollmentRequired?: typeof isTwoFactorEnrollmentRequired; + tokenRetired?: typeof isTokenRetired; + enabled?: typeof isEnabled; +} + +export function createOptionalShareFileAuth(deps: ShareFileAuthDependencies) { + const verifySignedUser = (token: string | undefined): VerifiedUser | null => { + try { + const payload = jwt.verify(token ?? '', process.env.JWT_REFRESH_SECRET ?? ''); + if (typeof payload !== 'object' || typeof payload.id !== 'string') { + return null; + } + return { + userId: payload.id, + issuedAt: typeof payload.iat === 'number' ? payload.iat : undefined, + issuedAtMs: typeof payload.issuedAtMs === 'number' ? payload.issuedAtMs : undefined, + }; + } catch { + return null; + } + }; + + const getRefreshTokenUser = async (token: string): Promise => { + const verified = verifySignedUser(token); + if (!verified) { + return null; + } + const session = await deps.runAsSystem(() => + deps.findSession({ userId: verified.userId, refreshToken: token }), + ); + return session ? verified : null; + }; + + const getOpenIdUser = ( + parsed: Record, + req: ShareRequest, + ): VerifiedUser | null => { + if ( + parsed.token_provider !== 'openid' || + !(deps.enabled ?? isEnabled)(process.env.OPENID_REUSE_TOKENS) + ) { + return null; + } + const sessionRefreshToken = req.session?.openidTokens?.refreshToken; + if (!parsed.refreshToken || parsed.refreshToken !== sessionRefreshToken) { + return null; + } + return verifySignedUser(parsed.openid_user_id); + }; + + const clearCookies = (res: Response, user: ShareUser): void => { + deps.clearCloudFrontCookies(res, { + userId: user.id?.toString() ?? user._id?.toString(), + tenantId: user.tenantId ?? user.orgId, + storageRegion: user.storageRegion, + }); + }; + + return async (req: ShareRequest, res: Response, next: NextFunction): Promise => { + if (req.user) { + clearEnrollmentViewer(req, res, req.user, deps); + next(); + return; + } + + try { + const cookieHeader = req.headers.cookie; + if (!cookieHeader) { + next(); + return; + } + const parsed = deps.parseCookie(cookieHeader); + const verified = + getOpenIdUser(parsed, req) || + (parsed.refreshToken ? await getRefreshTokenUser(parsed.refreshToken) : null); + if (!verified) { + next(); + return; + } + + // This read precedes the share tenant, so it must use system context. + const user = await deps.runAsSystem(() => + deps.getUserById(verified.userId, '-password -__v -totpSecret -backupCodes'), + ); + if (!user) { + next(); + return; + } + if ( + (deps.enrollmentRequired ?? isTwoFactorEnrollmentRequired)(user) || + (deps.tokenRetired ?? isTokenRetired)(verified, user) + ) { + clearCookies(res, user); + next(); + return; + } + user.id = user._id.toString(); + if (!user.role) { + user.role = SystemRoles.USER; + } + req.user = user; + } catch (error) { + deps.warn( + '[optionalShareFileAuth] cookie auth failed:', + error instanceof Error ? error.message : undefined, + ); + } + next(); + }; +} diff --git a/packages/api/src/auth/tempuser.ts b/packages/api/src/auth/tempuser.ts new file mode 100644 index 0000000000..5a1c271293 --- /dev/null +++ b/packages/api/src/auth/tempuser.ts @@ -0,0 +1,33 @@ +import jwt from 'jsonwebtoken'; +import type { NextFunction, Request, Response } from 'express'; + +type TempTokenField = 'tempToken' | 'acknowledgementToken' | 'finalizationToken'; +export type TwoFactorTempRequest = Request & { + user?: { id?: string; _id?: { toString(): string } }; + twoFactorTokenField?: TempTokenField; + body: Partial>; +}; + +export function createTwoFactorTempUser(field: TempTokenField, env: NodeJS.ProcessEnv) { + return (req: TwoFactorTempRequest, _res: Response, next: NextFunction): void => { + req.twoFactorTokenField = field; + if (req.user?.id || req.user?._id) { + next(); + return; + } + const token = req.body?.[field]; + if (!token) { + next(); + return; + } + try { + const payload = jwt.verify(token, env.JWT_SECRET ?? ''); + if (typeof payload === 'object' && payload.userId) { + req.user = { id: payload.userId }; + } + } catch { + // A malformed token keeps the IP quota active until the route rejects it. + } + next(); + }; +} diff --git a/packages/api/src/auth/twoFactor.spec.ts b/packages/api/src/auth/twoFactor.spec.ts new file mode 100644 index 0000000000..9dc793e474 --- /dev/null +++ b/packages/api/src/auth/twoFactor.spec.ts @@ -0,0 +1,1556 @@ +import jwt from 'jsonwebtoken'; +import { createHash } from 'node:crypto'; +import type { + IUser, + TwoFactorEnrollmentGuard, + TwoFactorEnrollmentUpdate, +} from '@librechat/data-schemas'; +import type { NextFunction, Request, Response } from 'express'; +import type { + TokenIssuance, + TwoFactorEnrollmentDependencies, + TwoFactorEnrollmentRequest, +} from './twoFactor'; +import { + confirmTwoFactorSetup, + finalizeTwoFactorSetup, + acknowledgeTwoFactorSetup, + TWO_FACTOR_TOKEN_PURPOSE, + generateTwoFactorSetupFinalizationToken, + generateTwoFactorSetupAcknowledgementToken, + generateTwoFactorLoginChallengeToken, + generateTwoFactorSetupToken, + isTwoFactorEnrollmentRequired, + isTwoFactorSetupEligible, + isCredentialLoginBlockedByTwoFactorPolicy, + isTokenRetired, + isEnrollmentSupersededByRecovery, + hasPasswordResetSince, + requireTwoFactorSetupToken, + createBlockRetiredSetupToken, + requireTwoFactorSetupFinalizationToken, + requireTwoFactorSetupAcknowledgementToken, + verifyTwoFactorSetupToken, + verifyTwoFactorSetupFinalizationToken, + verifyTwoFactorSetupAcknowledgementToken, + verifyTwoFactorLoginChallengeToken, + blockTwoFactorDisableWhenRequired, + withdrawMintedSession, +} from './twoFactor'; + +const jwtSecret = 'two-factor-setup-test-secret'; +const nonce = 'test-nonce'; + +const sha256 = (value: string): string => createHash('sha256').update(value).digest('hex'); + +describe('isTwoFactorEnrollmentRequired', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + }); + + it.each(['local', 'ldap', undefined])('requires enrollment for %s users', (provider) => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + + expect(isTwoFactorEnrollmentRequired({ provider, twoFactorEnabled: false })).toBe(true); + }); + + it.each(['openid', 'google', 'saml'])('preserves federated provider scope for %s', (provider) => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + + expect(isTwoFactorEnrollmentRequired({ provider, twoFactorEnabled: false })).toBe(false); + }); + + it('does not require enrollment for enrolled users or when policy is disabled', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + expect(isTwoFactorEnrollmentRequired({ provider: 'local', twoFactorEnabled: true })).toBe( + false, + ); + + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + expect(isTwoFactorEnrollmentRequired({ provider: 'local', twoFactorEnabled: false })).toBe( + false, + ); + }); +}); + +describe('isTwoFactorSetupEligible', () => { + it.each(['local', 'ldap', undefined])('allows %s users', (provider) => { + expect(isTwoFactorSetupEligible({ provider })).toBe(true); + }); + + it.each(['openid', 'google', 'saml'])('rejects federated %s users', (provider) => { + expect(isTwoFactorSetupEligible({ provider })).toBe(false); + }); +}); + +describe('isCredentialLoginBlockedByTwoFactorPolicy', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + }); + + /** + * A reset assigns a password without consulting `provider`, and the local strategy authenticates + * on the password alone, so a federated record can be signed in with a password. + */ + it.each(['openid', 'google', 'saml'])('blocks a %s record under enforcement', (provider) => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + + expect(isCredentialLoginBlockedByTwoFactorPolicy({ provider })).toBe(true); + }); + + it.each(['local', 'ldap', undefined])('allows %s records under enforcement', (provider) => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + + expect(isCredentialLoginBlockedByTwoFactorPolicy({ provider })).toBe(false); + }); + + it('blocks nothing when the policy is disabled', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + + expect(isCredentialLoginBlockedByTwoFactorPolicy({ provider: 'openid' })).toBe(false); + }); + + it('treats a missing user as nothing to block', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + + expect(isCredentialLoginBlockedByTwoFactorPolicy(null)).toBe(false); + }); +}); + +describe('isTokenRetired', () => { + const enrolledAt = new Date('2026-01-01T00:00:10.500Z'); + const enrolledSecond = Math.floor(enrolledAt.getTime() / 1000); + + it('leaves accounts that never enrolled untouched', () => { + expect(isTokenRetired({ issuedAt: 0 }, { twoFactorEnrolledAt: null })).toBe(false); + expect(isTokenRetired({ issuedAt: 0 }, { twoFactorEnrolledAt: undefined })).toBe(false); + }); + + it('refuses a token issued before the enrolling second', () => { + expect( + isTokenRetired({ issuedAt: enrolledSecond - 1 }, { twoFactorEnrolledAt: enrolledAt }), + ).toBe(true); + }); + + it('keeps the session minted within the enrolling second', () => { + expect(isTokenRetired({ issuedAt: enrolledSecond }, { twoFactorEnrolledAt: enrolledAt })).toBe( + false, + ); + expect( + isTokenRetired({ issuedAt: enrolledSecond + 1 }, { twoFactorEnrolledAt: enrolledAt }), + ).toBe(false); + }); + + /** + * `finalizeTwoFactorSetup` stamps the enrollment inside the promoting compare-and-swap, and the + * session it hands back is minted after that write and a session sweep, so the survivor always + * postdates the cutoff. A token dated to the millisecond therefore does not need the whole second + * spared: keeping it would let a bearer minted just before the promotion outlive it, which is the + * one thing enrollment retirement exists to stop. + */ + it('retires a pre-enrollment bearer minted earlier in the enrolling second', () => { + expect( + isTokenRetired( + { issuedAt: enrolledSecond, issuedAtMs: enrolledAt.getTime() - 1 }, + { twoFactorEnrolledAt: enrolledAt }, + ), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt: enrolledSecond - 1, issuedAtMs: enrolledAt.getTime() - 1000 }, + { twoFactorEnrolledAt: enrolledAt }, + ), + ).toBe(true); + }); + + it('keeps the session finalization mints, which postdates the enrollment stamp', () => { + expect( + isTokenRetired( + { issuedAt: enrolledSecond, issuedAtMs: enrolledAt.getTime() }, + { twoFactorEnrolledAt: enrolledAt }, + ), + ).toBe(false); + expect( + isTokenRetired( + { issuedAt: enrolledSecond, issuedAtMs: enrolledAt.getTime() + 1 }, + { twoFactorEnrolledAt: enrolledAt }, + ), + ).toBe(false); + }); + + it('accepts a stamp that arrives as a string or epoch value', () => { + expect( + isTokenRetired( + { issuedAt: enrolledSecond - 1 }, + { + twoFactorEnrolledAt: enrolledAt.toISOString(), + }, + ), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt: enrolledSecond - 1 }, + { twoFactorEnrolledAt: enrolledAt.getTime() }, + ), + ).toBe(true); + }); + + it('refuses an undatable token once the account is enrolled', () => { + expect(isTokenRetired({ issuedAt: undefined }, { twoFactorEnrolledAt: enrolledAt })).toBe(true); + expect(isTokenRetired({ issuedAt: Number.NaN }, { twoFactorEnrolledAt: enrolledAt })).toBe( + true, + ); + }); + + it('ignores an unparseable stamp rather than locking every session out', () => { + expect( + isTokenRetired({ issuedAt: enrolledSecond }, { twoFactorEnrolledAt: 'not-a-date' }), + ).toBe(false); + }); + + describe('password recovery', () => { + const resetAt = new Date('2026-02-02T00:00:10.500Z'); + const resetMs = resetAt.getTime(); + const resetSecond = Math.floor(resetMs / 1000); + + it('refuses a token minted for the credential the reset revoked', () => { + expect(isTokenRetired({ issuedAt: resetSecond - 1 }, { credentialsChangedAt: resetAt })).toBe( + true, + ); + }); + + it('keeps a token minted from the new credential', () => { + expect(isTokenRetired({ issuedAt: resetSecond + 1 }, { credentialsChangedAt: resetAt })).toBe( + false, + ); + }); + + it('retires a token minted earlier in the resetting second', () => { + expect( + isTokenRetired( + { issuedAt: resetSecond, issuedAtMs: resetMs - 1 }, + { credentialsChangedAt: resetAt }, + ), + ).toBe(true); + }); + + it('retires a token minted in the very millisecond of the reset', () => { + expect( + isTokenRetired( + { issuedAt: resetSecond, issuedAtMs: resetMs }, + { credentialsChangedAt: resetAt }, + ), + ).toBe(true); + }); + + /** + * The session a sign-in lands in the resetting second buys is minted from the new credential, + * so retiring it would 401 every request until the user signed in again. + */ + it('keeps a token minted after the reset, even inside the same second', () => { + expect( + isTokenRetired( + { issuedAt: resetSecond, issuedAtMs: resetMs + 1 }, + { credentialsChangedAt: resetAt }, + ), + ).toBe(false); + }); + + /** Without the claim there is nothing to order within the second, so the whole second goes. */ + it('surrenders the resetting second for a token minted before the claim existed', () => { + expect(isTokenRetired({ issuedAt: resetSecond }, { credentialsChangedAt: resetAt })).toBe( + true, + ); + expect(isTokenRetired({ issuedAt: undefined }, { credentialsChangedAt: resetAt })).toBe(true); + }); + + it('keeps the enrolling second while refusing the resetting one', () => { + expect( + isTokenRetired({ issuedAt: enrolledSecond }, { twoFactorEnrolledAt: enrolledAt }), + ).toBe(false); + expect(isTokenRetired({ issuedAt: resetSecond }, { credentialsChangedAt: resetAt })).toBe( + true, + ); + }); + + it('leaves accounts that never reset untouched', () => { + expect(isTokenRetired({ issuedAt: 0 }, { credentialsChangedAt: null })).toBe(false); + expect(isTokenRetired({ issuedAt: 0 }, {})).toBe(false); + expect(isTokenRetired({ issuedAt: 0 }, null)).toBe(false); + expect(isTokenRetired({ issuedAt: resetSecond, issuedAtMs: resetMs }, {})).toBe(false); + expect(isTokenRetired({ issuedAt: resetSecond, issuedAtMs: resetMs }, null)).toBe(false); + }); + + it('retires on whichever cutoff the token predates', () => { + expect( + isTokenRetired( + { issuedAt: resetSecond - 1 }, + { twoFactorEnrolledAt: enrolledAt, credentialsChangedAt: resetAt }, + ), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt: enrolledSecond - 1 }, + { twoFactorEnrolledAt: enrolledAt, credentialsChangedAt: resetAt }, + ), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt: resetSecond + 1 }, + { twoFactorEnrolledAt: enrolledAt, credentialsChangedAt: resetAt }, + ), + ).toBe(false); + }); + + it('refuses an undatable token once the account has reset', () => { + expect(isTokenRetired({ issuedAt: undefined }, { credentialsChangedAt: resetAt })).toBe(true); + }); + + it('ignores an unparseable reset stamp rather than stranding the session', () => { + expect( + isTokenRetired( + { issuedAt: resetSecond, issuedAtMs: resetMs }, + { credentialsChangedAt: 'not-a-date' }, + ), + ).toBe(false); + }); + }); +}); + +describe('isEnrollmentSupersededByRecovery', () => { + const enrolledAt = new Date('2026-01-01T00:00:10.500Z'); + + it('reports nothing when either stamp is missing', () => { + expect(isEnrollmentSupersededByRecovery(null, new Date())).toBe(false); + expect(isEnrollmentSupersededByRecovery(enrolledAt, null)).toBe(false); + expect(isEnrollmentSupersededByRecovery(undefined, undefined)).toBe(false); + }); + + it('reports a reset that landed after the enrollment was promoted', () => { + expect(isEnrollmentSupersededByRecovery(enrolledAt, new Date(enrolledAt.getTime() + 1))).toBe( + true, + ); + }); + + it('leaves an enrollment that followed an older reset alone', () => { + expect(isEnrollmentSupersededByRecovery(enrolledAt, new Date(enrolledAt.getTime() - 1))).toBe( + false, + ); + }); + + /** `iat` rounds to whole seconds, so a same-millisecond reset is the race, not a coincidence. */ + it('resolves a tie against the enrollment', () => { + expect(isEnrollmentSupersededByRecovery(enrolledAt, new Date(enrolledAt.getTime()))).toBe(true); + }); + + it('accepts stamps that arrive as strings or epoch values', () => { + expect( + isEnrollmentSupersededByRecovery(enrolledAt.toISOString(), enrolledAt.getTime() + 1), + ).toBe(true); + }); + + it('ignores an unparseable stamp rather than withdrawing every enrollment', () => { + expect(isEnrollmentSupersededByRecovery('not-a-date', new Date())).toBe(false); + expect(isEnrollmentSupersededByRecovery(enrolledAt, 'not-a-date')).toBe(false); + }); +}); + +describe('hasPasswordResetSince', () => { + const seenAt = new Date('2026-01-01T00:00:10.500Z'); + + it('reports a reset that landed after the authenticating read', () => { + expect(hasPasswordResetSince(seenAt, new Date(seenAt.getTime() + 1))).toBe(true); + }); + + it('reports the first reset an account has ever had', () => { + expect(hasPasswordResetSince(null, seenAt)).toBe(true); + expect(hasPasswordResetSince(undefined, seenAt)).toBe(true); + }); + + it('leaves the stamp the authenticating read already saw alone', () => { + expect(hasPasswordResetSince(seenAt, new Date(seenAt.getTime()))).toBe(false); + expect(hasPasswordResetSince(seenAt, seenAt.toISOString())).toBe(false); + }); + + /** Nothing revoked the password, so an account that never reset one cannot be refused. */ + it('reports nothing when the record carries no reset at all', () => { + expect(hasPasswordResetSince(null, null)).toBe(false); + expect(hasPasswordResetSince(seenAt, undefined)).toBe(false); + }); + + it('accepts stamps that arrive as strings or epoch values', () => { + expect(hasPasswordResetSince(seenAt.toISOString(), seenAt.getTime() + 1)).toBe(true); + expect(hasPasswordResetSince(seenAt.getTime(), seenAt.toISOString())).toBe(false); + }); + + it('ignores an unparseable stamp rather than refusing every login', () => { + expect(hasPasswordResetSince(seenAt, 'not-a-date')).toBe(false); + }); + + /** An unreadable prior stamp is no evidence of what the authenticating read saw. */ + it('treats an unparseable prior stamp as a reset it cannot rule out', () => { + expect(hasPasswordResetSince('not-a-date', seenAt)).toBe(true); + }); +}); + +function createResponse(): Response { + return { + status: jest.fn().mockReturnThis(), + json: jest.fn().mockReturnThis(), + } as Partial as Response; +} + +describe('two-factor setup tokens', () => { + it('round-trips only a purpose-scoped login challenge token', () => { + const loginToken = generateTwoFactorLoginChallengeToken('user-1', jwtSecret); + const setupToken = generateTwoFactorSetupToken('user-1', jwtSecret); + const acknowledgementToken = generateTwoFactorSetupAcknowledgementToken( + 'user-1', + nonce, + jwtSecret, + ); + const finalizationToken = generateTwoFactorSetupFinalizationToken('user-1', nonce, jwtSecret); + + expect(verifyTwoFactorLoginChallengeToken(loginToken, jwtSecret)).toEqual({ + userId: 'user-1', + issuedAt: expect.any(Number), + issuedAtMs: expect.any(Number), + }); + expect(verifyTwoFactorLoginChallengeToken(setupToken, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorLoginChallengeToken(acknowledgementToken, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorLoginChallengeToken(finalizationToken, jwtSecret)).toBeUndefined(); + }); + + it('dates a login challenge to the millisecond so a same-second reset can retire it', () => { + const before = Date.now(); + const credential = verifyTwoFactorLoginChallengeToken( + generateTwoFactorLoginChallengeToken('user-1', jwtSecret), + jwtSecret, + ); + const after = Date.now(); + + expect(credential?.issuedAtMs).toBeGreaterThanOrEqual(before); + expect(credential?.issuedAtMs).toBeLessThanOrEqual(after); + expect( + isTokenRetired(credential as TokenIssuance, { + credentialsChangedAt: new Date(credential?.issuedAtMs as number), + }), + ).toBe(true); + expect( + isTokenRetired(credential as TokenIssuance, { + credentialsChangedAt: new Date((credential?.issuedAtMs as number) - 1), + }), + ).toBe(false); + }); + + it('reads a legacy login challenge that predates the millisecond claim', () => { + const legacyToken = jwt.sign( + { userId: 'user-1', purpose: TWO_FACTOR_TOKEN_PURPOSE.LOGIN_CHALLENGE }, + jwtSecret, + { expiresIn: '5m' }, + ); + + expect(verifyTwoFactorLoginChallengeToken(legacyToken, jwtSecret)).toEqual({ + userId: 'user-1', + issuedAt: expect.any(Number), + issuedAtMs: undefined, + }); + }); + + it('round-trips a purpose-scoped setup token', () => { + const token = generateTwoFactorSetupToken('user-2', jwtSecret); + + expect(verifyTwoFactorSetupToken(token, jwtSecret)).toEqual({ + userId: 'user-2', + issuedAt: expect.any(Number), + issuedAtMs: expect.any(Number), + }); + }); + + it('dates a setup token to the millisecond so a same-second reset can retire it', () => { + const before = Date.now(); + const credential = verifyTwoFactorSetupToken( + generateTwoFactorSetupToken('user-2', jwtSecret), + jwtSecret, + ); + const after = Date.now(); + + expect(credential?.issuedAtMs).toBeGreaterThanOrEqual(before); + expect(credential?.issuedAtMs).toBeLessThanOrEqual(after); + }); + + it('reads a legacy setup token that predates the millisecond claim', () => { + const legacyToken = jwt.sign( + { userId: 'user-2', purpose: TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_SETUP }, + jwtSecret, + { expiresIn: '10m' }, + ); + + expect(verifyTwoFactorSetupToken(legacyToken, jwtSecret)).toEqual({ + userId: 'user-2', + issuedAt: expect.any(Number), + issuedAtMs: undefined, + }); + }); + + it('rejects a normal 2FA challenge token for setup', () => { + const token = jwt.sign( + { userId: 'user-1', purpose: TWO_FACTOR_TOKEN_PURPOSE.LOGIN_CHALLENGE }, + jwtSecret, + { expiresIn: '5m' }, + ); + + expect(verifyTwoFactorSetupToken(token, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorSetupFinalizationToken(token, jwtSecret)).toBeUndefined(); + }); + + it('rejects legacy purpose-less tokens', () => { + const token = jwt.sign({ userId: 'user-1', twoFASetupRequired: true }, jwtSecret, { + expiresIn: '5m', + }); + + expect(verifyTwoFactorSetupToken(token, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorSetupFinalizationToken(token, jwtSecret)).toBeUndefined(); + }); + + it('rejects expired setup tokens', () => { + const token = jwt.sign( + { userId: 'user-1', purpose: TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_SETUP }, + jwtSecret, + { expiresIn: -1 }, + ); + + expect(verifyTwoFactorSetupToken(token, jwtSecret)).toBeUndefined(); + }); + + it('round-trips only purpose-scoped finalization credentials', () => { + const token = generateTwoFactorSetupFinalizationToken('user-1', nonce, jwtSecret); + const setupToken = generateTwoFactorSetupToken('user-1', jwtSecret); + + expect(verifyTwoFactorSetupFinalizationToken(token, jwtSecret)).toEqual({ + userId: 'user-1', + nonce, + }); + expect(verifyTwoFactorSetupFinalizationToken(setupToken, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorSetupToken(token, jwtSecret)).toBeUndefined(); + }); + + it('round-trips only purpose-scoped acknowledgement credentials', () => { + const token = generateTwoFactorSetupAcknowledgementToken('user-1', nonce, jwtSecret); + const setupToken = generateTwoFactorSetupToken('user-1', jwtSecret); + const finalizationToken = generateTwoFactorSetupFinalizationToken('user-1', nonce, jwtSecret); + + expect(verifyTwoFactorSetupAcknowledgementToken(token, jwtSecret)).toEqual({ + userId: 'user-1', + nonce, + }); + expect(verifyTwoFactorSetupAcknowledgementToken(setupToken, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorSetupAcknowledgementToken(finalizationToken, jwtSecret)).toBeUndefined(); + }); + + it.each([ + ['acknowledgement', generateTwoFactorSetupAcknowledgementToken], + ['finalization', generateTwoFactorSetupFinalizationToken], + ])('rejects a nonce-less %s credential', (_label, generate) => { + const purpose = + generate === generateTwoFactorSetupAcknowledgementToken + ? TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_ACKNOWLEDGEMENT + : TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_FINALIZATION; + const token = jwt.sign({ userId: 'user-1', purpose }, jwtSecret, { expiresIn: '5m' }); + + expect(verifyTwoFactorSetupAcknowledgementToken(token, jwtSecret)).toBeUndefined(); + expect(verifyTwoFactorSetupFinalizationToken(token, jwtSecret)).toBeUndefined(); + }); +}); + +describe('requireTwoFactorSetupAcknowledgementToken', () => { + beforeEach(() => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + process.env.JWT_SECRET = jwtSecret; + }); + + it('attaches the acknowledgement identity and its one-time nonce', () => { + const req = { + body: { + acknowledgementToken: generateTwoFactorSetupAcknowledgementToken( + 'user-5', + nonce, + jwtSecret, + ), + }, + } as Request; + const res = createResponse(); + const next = jest.fn(); + + requireTwoFactorSetupAcknowledgementToken(req, res, next); + + expect(req.user).toEqual({ id: 'user-5' }); + expect((req as TwoFactorEnrollmentRequest).twoFactorEnrollmentNonce).toBe(nonce); + expect(next).toHaveBeenCalledTimes(1); + }); + + it.each([ + generateTwoFactorSetupToken('user-5', jwtSecret), + generateTwoFactorSetupFinalizationToken('user-5', nonce, jwtSecret), + generateTwoFactorLoginChallengeToken('user-5', jwtSecret), + ])('rejects a wrong-purpose token', (acknowledgementToken) => { + const req = { body: { acknowledgementToken } } as Request; + const res = createResponse(); + const next = jest.fn(); + + requireTwoFactorSetupAcknowledgementToken(req, res, next); + + expect(res.status).toHaveBeenCalledWith(401); + expect(next).not.toHaveBeenCalled(); + }); +}); + +describe('requireTwoFactorSetupFinalizationToken', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + const originalSecret = process.env.JWT_SECRET; + + beforeEach(() => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + process.env.JWT_SECRET = jwtSecret; + }); + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + if (originalSecret === undefined) { + delete process.env.JWT_SECRET; + } else { + process.env.JWT_SECRET = originalSecret; + } + }); + + it('attaches the finalization identity and its one-time nonce', () => { + const req = { + body: { + finalizationToken: generateTwoFactorSetupFinalizationToken('user-4', nonce, jwtSecret), + }, + } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupFinalizationToken(req, res, next); + + expect(req.user).toEqual({ id: 'user-4' }); + expect((req as TwoFactorEnrollmentRequest).twoFactorEnrollmentNonce).toBe(nonce); + expect(next).toHaveBeenCalledTimes(1); + }); + + it('rejects invalid and wrong-purpose tokens', () => { + const tokens = [ + 'invalid', + generateTwoFactorSetupToken('user-4', jwtSecret), + generateTwoFactorSetupAcknowledgementToken('user-4', nonce, jwtSecret), + generateTwoFactorLoginChallengeToken('user-4', jwtSecret), + jwt.sign({ userId: 'user-4' }, jwtSecret), + ]; + + for (const finalizationToken of tokens) { + const req = { body: { finalizationToken } } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupFinalizationToken(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + } + }); + + it('rejects finalization when global enforcement is disabled', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const req = { + body: { + finalizationToken: generateTwoFactorSetupFinalizationToken('user-4', nonce, jwtSecret), + }, + } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupFinalizationToken(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + }); +}); + +describe('requireTwoFactorSetupToken', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + const originalSecret = process.env.JWT_SECRET; + + beforeEach(() => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + process.env.JWT_SECRET = jwtSecret; + }); + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + if (originalSecret === undefined) { + delete process.env.JWT_SECRET; + } else { + process.env.JWT_SECRET = originalSecret; + } + }); + + it('attaches the setup user and continues for a valid token', () => { + const req = { + body: { tempToken: generateTwoFactorSetupToken('user-2', jwtSecret) }, + } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupToken(req, res, next); + + expect(req.user).toEqual({ id: 'user-2' }); + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('stamps the mint time, so a later account event can retire the token', () => { + const req = { + body: { tempToken: generateTwoFactorSetupToken('user-2', jwtSecret) }, + } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupToken(req, res, next); + + const setupRequest = req as TwoFactorEnrollmentRequest; + const issuedAt = setupRequest.twoFactorSetupIssuedAt; + const issuedAtMs = setupRequest.twoFactorSetupIssuedAtMs; + expect(typeof issuedAt).toBe('number'); + expect(typeof issuedAtMs).toBe('number'); + expect( + isTokenRetired({ issuedAt }, { credentialsChangedAt: new Date((issuedAt as number) * 1000) }), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt }, + { credentialsChangedAt: new Date(((issuedAt as number) + 1) * 1000) }, + ), + ).toBe(true); + + /** The millisecond claim is what still spares a setup token minted after the reset landed. */ + expect( + isTokenRetired( + { issuedAt, issuedAtMs }, + { credentialsChangedAt: new Date((issuedAtMs as number) - 1) }, + ), + ).toBe(false); + }); + + it('rejects setup when the deployment policy is disabled', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const req = { + body: { tempToken: generateTwoFactorSetupToken('user-2', jwtSecret) }, + } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupToken(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + }); + + it('rejects missing or invalid setup tokens', () => { + const req = { body: { tempToken: 'invalid' } } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupToken(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('rejects login challenge, acknowledgement, and finalization tokens', () => { + const tokens = [ + jwt.sign({ userId: 'user-2', purpose: TWO_FACTOR_TOKEN_PURPOSE.LOGIN_CHALLENGE }, jwtSecret), + generateTwoFactorSetupAcknowledgementToken('user-2', nonce, jwtSecret), + generateTwoFactorSetupFinalizationToken('user-2', nonce, jwtSecret), + ]; + + for (const tempToken of tokens) { + const req = { body: { tempToken } } as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + requireTwoFactorSetupToken(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + } + }); +}); + +describe('createBlockRetiredSetupToken', () => { + const resetAt = new Date('2026-02-02T00:00:10.500Z'); + const resetSecond = Math.floor(resetAt.getTime() / 1000); + const getUserById = jest.fn(); + const blockRetiredSetupToken = createBlockRetiredSetupToken({ getUserById }); + + const run = async (req: Partial) => { + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + await blockRetiredSetupToken(req as Request, res, next); + return { res, next }; + }; + + beforeEach(() => { + getUserById.mockReset(); + getUserById.mockResolvedValue({ _id: 'user-1' }); + }); + + it('continues when nothing has retired the setup token', async () => { + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond, + }); + + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('refuses a setup token minted before the password reset', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', credentialsChangedAt: resetAt }); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond - 1, + }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('admits a setup token minted after the password reset', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', credentialsChangedAt: resetAt }); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond + 1, + }); + + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('refuses a setup token minted earlier in the second the password reset landed', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', credentialsChangedAt: resetAt }); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond, + twoFactorSetupIssuedAtMs: resetAt.getTime() - 1, + }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('admits a setup token minted later in the second the password reset landed', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', credentialsChangedAt: resetAt }); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond, + twoFactorSetupIssuedAtMs: resetAt.getTime() + 1, + }); + + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('refuses a setup token minted before enrollment promoted the account', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', twoFactorEnrolledAt: resetAt }); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond - 1, + }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('refuses an undatable setup token once a cutoff is set', async () => { + getUserById.mockResolvedValue({ _id: 'user-1', credentialsChangedAt: resetAt }); + + const { res, next } = await run({ user: { id: 'user-1' } }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('reads only the fields the cutoff needs', async () => { + await run({ user: { id: 'user-1' }, twoFactorSetupIssuedAt: resetSecond }); + + expect(getUserById).toHaveBeenCalledWith('user-1', 'twoFactorEnrolledAt credentialsChangedAt'); + }); + + it('refuses when the named account no longer exists', async () => { + getUserById.mockResolvedValue(null); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond, + }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('refuses when no setup user was stamped on the request', async () => { + const { res, next } = await run({}); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(getUserById).not.toHaveBeenCalled(); + }); + + it('fails closed when the lookup throws', async () => { + getUserById.mockRejectedValue(new Error('mongo is down')); + + const { res, next } = await run({ + user: { id: 'user-1' }, + twoFactorSetupIssuedAt: resetSecond, + }); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(500); + }); +}); + +type BackupCode = NonNullable[number]; + +interface EnrollmentDocument { + _id: string; + provider?: string; + twoFactorEnabled: boolean; + twoFactorEnrolledAt?: Date; + totpSecret?: string | null; + backupCodes?: BackupCode[]; + pendingTotpSecret?: string | null; + pendingBackupCodes?: BackupCode[]; + twoFactorAcknowledgementNonceHash?: string | null; + twoFactorFinalizationNonceHash?: string | null; +} + +const ELIGIBLE_PROVIDERS = new Set(['local', 'ldap']); + +/** + * A faithful in-memory stand-in for the guarded `updateTwoFactorEnrollment` write: it reproduces + * the invariant filter (unenrolled, policy-eligible provider) plus exact-value predicates, so + * replay and race behaviour is exercised for real rather than stubbed. + */ +function createEnrollmentStore(overrides: Partial = {}) { + let doc: EnrollmentDocument = { + _id: 'user-3', + provider: 'local', + twoFactorEnabled: false, + pendingTotpSecret: 'encrypted-secret', + pendingBackupCodes: [{ codeHash: 'staged-hash', used: false }], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + ...overrides, + }; + const writes: TwoFactorEnrollmentUpdate[] = []; + + const matchesGuard = (guard: TwoFactorEnrollmentGuard): boolean => { + if (doc.twoFactorEnabled) { + return false; + } + if (doc.provider != null && !ELIGIBLE_PROVIDERS.has(doc.provider)) { + return false; + } + return Object.entries(guard).every( + ([key, value]) => + JSON.stringify(doc[key as keyof EnrollmentDocument] ?? null) === + JSON.stringify(value ?? null), + ); + }; + + const deps: TwoFactorEnrollmentDependencies = { + getUserById: jest.fn(async () => ({ ...doc }) as unknown as IUser), + getTOTPSecret: jest.fn().mockResolvedValue('plain-secret'), + verifyTOTP: jest.fn().mockResolvedValue(true), + generateBackupCodes: jest.fn(async () => ({ + plainCodes: [`code-${writes.length + 1}`], + codeObjects: [{ codeHash: `hash-${writes.length + 1}`, used: false, usedAt: null }], + })), + updateTwoFactorEnrollment: jest.fn(async (_userId, guard, update) => { + if (!matchesGuard(guard)) { + return null; + } + writes.push(update); + doc = { ...doc, ...update }; + return { ...doc } as unknown as IUser; + }), + }; + + return { + deps, + writes, + read: () => ({ ...doc }), + mutate: (patch: Partial) => { + doc = { ...doc, ...patch }; + }, + }; +} + +describe('required two-factor enrollment lifecycle', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + + beforeEach(() => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + }); + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + }); + + it('stages deliverable codes and an acknowledgement nonce without enabling 2FA', async () => { + const store = createEnrollmentStore(); + + const result = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(result.ok).toBe(true); + if (!result.ok) { + return; + } + expect(result.plainCodes).toEqual(['code-1']); + expect(store.read()).toMatchObject({ + twoFactorEnabled: false, + pendingTotpSecret: 'encrypted-secret', + pendingBackupCodes: [{ codeHash: 'hash-1', used: false, usedAt: null }], + twoFactorAcknowledgementNonceHash: sha256(result.acknowledgementNonce), + twoFactorFinalizationNonceHash: null, + }); + expect(store.read().totpSecret).toBeFalsy(); + expect(isTwoFactorEnrollmentRequired(result.user)).toBe(true); + expect(store.deps.updateTwoFactorEnrollment).toHaveBeenCalledTimes(1); + expect(store.deps.updateTwoFactorEnrollment).toHaveBeenCalledWith( + 'user-3', + { + pendingTotpSecret: 'encrypted-secret', + pendingBackupCodes: [{ codeHash: 'staged-hash', used: false }], + }, + expect.objectContaining({ twoFactorFinalizationNonceHash: null }), + ); + }); + + it('stays retryable after a lost confirmation response, rotating codes and nonces', async () => { + const store = createEnrollmentStore(); + + const first = await confirmTwoFactorSetup('user-3', '123456', store.deps); + const second = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(first.ok && second.ok).toBe(true); + if (!first.ok || !second.ok) { + return; + } + expect(second.plainCodes).not.toEqual(first.plainCodes); + expect(second.acknowledgementNonce).not.toBe(first.acknowledgementNonce); + expect(store.read()).toMatchObject({ + twoFactorEnabled: false, + twoFactorAcknowledgementNonceHash: sha256(second.acknowledgementNonce), + }); + + const stale = await acknowledgeTwoFactorSetup('user-3', first.acknowledgementNonce, store.deps); + + expect(stale).toEqual({ + ok: false, + status: 400, + message: 'This two-factor setup step expired. Confirm your code again.', + }); + }); + + it('rejects users who already have 2FA enabled', async () => { + const store = createEnrollmentStore({ twoFactorEnabled: true }); + + const result = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.deps.generateBackupCodes).not.toHaveBeenCalled(); + expect(store.deps.updateTwoFactorEnrollment).not.toHaveBeenCalled(); + }); + + it('rejects a federated provider before generating anything', async () => { + const store = createEnrollmentStore({ provider: 'openid' }); + + const result = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.deps.generateBackupCodes).not.toHaveBeenCalled(); + }); + + it('rejects an invalid TOTP without mutating the user', async () => { + const store = createEnrollmentStore(); + (store.deps.verifyTOTP as jest.Mock).mockResolvedValue(false); + + const result = await confirmTwoFactorSetup('user-3', '000000', store.deps); + + expect(result).toEqual({ ok: false, status: 400, message: 'Invalid token' }); + expect(store.deps.generateBackupCodes).not.toHaveBeenCalled(); + expect(store.deps.updateTwoFactorEnrollment).not.toHaveBeenCalled(); + }); + + it('rejects confirmation when the deployment policy flips off before the write', async () => { + const store = createEnrollmentStore(); + (store.deps.verifyTOTP as jest.Mock).mockImplementation(async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + return true; + }); + + const result = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.deps.generateBackupCodes).toHaveBeenCalledTimes(1); + expect(store.deps.updateTwoFactorEnrollment).not.toHaveBeenCalled(); + }); + + it('fails closed when a concurrent setup regeneration moves the pending snapshot', async () => { + const store = createEnrollmentStore(); + (store.deps.verifyTOTP as jest.Mock).mockImplementation(async () => { + store.mutate({ pendingBackupCodes: [{ codeHash: 'regenerated', used: false }] }); + return true; + }); + + const result = await confirmTwoFactorSetup('user-3', '123456', store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.read().twoFactorAcknowledgementNonceHash).toBeNull(); + }); + + it('exchanges the acknowledgement nonce for a finalization nonce without enabling 2FA', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + + const result = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + + expect(result.ok).toBe(true); + if (!result.ok) { + return; + } + expect(store.read()).toMatchObject({ + twoFactorEnabled: false, + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: sha256(result.finalizationNonce), + }); + expect(store.read().totpSecret).toBeFalsy(); + expect(isTwoFactorEnrollmentRequired(result.user)).toBe(true); + }); + + it('rejects a replayed acknowledgement credential without issuing anything', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const first = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!first.ok) { + throw new Error('acknowledgement should succeed'); + } + + const replay = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + + expect(replay.ok).toBe(false); + expect(store.read().twoFactorFinalizationNonceHash).toBe(sha256(first.finalizationNonce)); + }); + + it('rejects acknowledgement when the deployment policy is disabled', async () => { + const store = createEnrollmentStore({ twoFactorAcknowledgementNonceHash: sha256('nonce-a') }); + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + + const result = await acknowledgeTwoFactorSetup('user-3', 'nonce-a', store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.deps.updateTwoFactorEnrollment).not.toHaveBeenCalled(); + }); + + it('promotes only at finalization and clears every enrollment field', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result.ok).toBe(true); + expect(store.read()).toMatchObject({ + twoFactorEnabled: true, + totpSecret: 'encrypted-secret', + backupCodes: [{ codeHash: 'hash-1', used: false, usedAt: null }], + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }); + expect(result.ok && isTwoFactorEnrollmentRequired(result.user)).toBe(false); + }); + + it('stamps the cutoff that retires pre-enrollment access tokens', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + const beforeFinalize = Date.now(); + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result.ok).toBe(true); + const enrolledAt = store.read().twoFactorEnrolledAt; + expect(enrolledAt).toBeInstanceOf(Date); + expect((enrolledAt as Date).getTime()).toBeGreaterThanOrEqual(beforeFinalize); + /** The token minted a moment earlier is now stale, the one finalization returns is not. */ + expect( + isTokenRetired( + { issuedAt: Math.floor(beforeFinalize / 1000) - 1 }, + { twoFactorEnrolledAt: enrolledAt as Date }, + ), + ).toBe(true); + expect( + isTokenRetired( + { issuedAt: Math.ceil(Date.now() / 1000) }, + { twoFactorEnrolledAt: enrolledAt as Date }, + ), + ).toBe(false); + }); + + it('leaves the cutoff unset on the steps that do not promote', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + expect(store.read().twoFactorEnrolledAt).toBeUndefined(); + + await acknowledgeTwoFactorSetup('user-3', confirmed.acknowledgementNonce, store.deps); + + expect(store.read().twoFactorEnrolledAt).toBeUndefined(); + }); + + it('rejects a replayed finalization credential without a second promotion', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + await finalizeTwoFactorSetup('user-3', acknowledged.finalizationNonce, store.deps); + const writesAfterFirst = store.writes.length; + + const replay = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(replay).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.writes).toHaveLength(writesAfterFirst); + }); + + it('rejects finalization carrying a stale nonce after a re-confirmation', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + await confirmTwoFactorSetup('user-3', '123456', store.deps); + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result).toEqual({ + ok: false, + status: 400, + message: 'This two-factor setup step expired. Confirm your code again.', + }); + expect(store.read().twoFactorEnabled).toBe(false); + }); + + it('rejects finalization without a nonce before reading the user', async () => { + const store = createEnrollmentStore(); + + const result = await finalizeTwoFactorSetup('user-3', undefined, store.deps); + + expect(result).toEqual({ + ok: false, + status: 400, + message: 'This two-factor setup step expired. Confirm your code again.', + }); + expect(store.deps.getUserById).not.toHaveBeenCalled(); + }); + + it.each([ + ['a federated provider transition', { provider: 'openid' }], + ['an already-enabled transition', { twoFactorEnabled: true }], + ])('rejects finalization after %s', async (_label, transition) => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + store.mutate(transition); + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.read().totpSecret).toBeFalsy(); + }); + + it('rejects finalization when the deployment policy is disabled', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result).toEqual({ + ok: false, + status: 400, + message: '2FA setup is not available for this user', + }); + expect(store.read().twoFactorEnabled).toBe(false); + }); + + it('rejects finalization once the pending setup has been cleared', async () => { + const store = createEnrollmentStore(); + const confirmed = await confirmTwoFactorSetup('user-3', '123456', store.deps); + if (!confirmed.ok) { + throw new Error('confirmation should succeed'); + } + const acknowledged = await acknowledgeTwoFactorSetup( + 'user-3', + confirmed.acknowledgementNonce, + store.deps, + ); + if (!acknowledged.ok) { + throw new Error('acknowledgement should succeed'); + } + store.mutate({ pendingTotpSecret: null, pendingBackupCodes: [] }); + + const result = await finalizeTwoFactorSetup( + 'user-3', + acknowledged.finalizationNonce, + store.deps, + ); + + expect(result).toEqual({ ok: false, status: 400, message: '2FA setup not initiated' }); + }); +}); + +describe('blockTwoFactorDisableWhenRequired', () => { + const originalPolicy = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + + afterAll(() => { + if (originalPolicy === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalPolicy; + } + }); + + it('blocks disabling 2FA when it is required', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = {} as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + blockTwoFactorDisableWhenRequired(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + }); + + it('allows disabling 2FA when it is optional', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; + const req = {} as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + blockTwoFactorDisableWhenRequired(req, res, next); + + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('allows federated users to manage provider-exempt 2FA', () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + const req = { user: { provider: 'openid' } } as Partial as Request; + const res = createResponse(); + const next = jest.fn() as jest.MockedFunction; + + blockTwoFactorDisableWhenRequired(req, res, next); + + expect(next).toHaveBeenCalledTimes(1); + expect(res.status).not.toHaveBeenCalled(); + }); +}); + +describe('withdrawMintedSession', () => { + /** A 500 that still carried the minted cookies could refresh once the database recovers. */ + it('clears the minted cookies even when the session deletion fails', async () => { + const clearCookie = jest.fn(); + const res = { clearCookie } as unknown as Response; + const clearCloudFrontCookies = jest.fn(); + const deletion = new Error('database unavailable'); + + await expect( + withdrawMintedSession(res, { tenantId: 'tenant-a' }, 'user-1', { + deleteAllUserSessions: jest.fn().mockRejectedValue(deletion), + clearCloudFrontCookies, + }), + ).rejects.toBe(deletion); + + expect(clearCookie).toHaveBeenCalledWith('refreshToken'); + expect(clearCookie).toHaveBeenCalledWith('token_provider'); + expect(clearCloudFrontCookies).toHaveBeenCalledWith(res, { + userId: 'user-1', + tenantId: 'tenant-a', + storageRegion: undefined, + }); + }); +}); diff --git a/packages/api/src/auth/twoFactor.ts b/packages/api/src/auth/twoFactor.ts new file mode 100644 index 0000000000..1cf864b647 --- /dev/null +++ b/packages/api/src/auth/twoFactor.ts @@ -0,0 +1,785 @@ +import jwt from 'jsonwebtoken'; +import { logger } from '@librechat/data-schemas'; +import { createHash, randomBytes } from 'node:crypto'; +import { isTwoFactorPolicyProvider } from 'librechat-data-provider'; +import type { TwoFactorEnrollmentGuard, TwoFactorEnrollmentUpdate } from '@librechat/data-schemas'; +import type { NextFunction, Request, Response } from 'express'; +import type { UserDocumentId } from '~/auth/verification'; +import { isEnabled } from '~/utils'; + +const TWO_FACTOR_SETUP_TOKEN_EXPIRY = '10m'; +const TWO_FACTOR_SETUP_ACKNOWLEDGEMENT_TOKEN_EXPIRY = '5m'; +const TWO_FACTOR_SETUP_FINALIZATION_TOKEN_EXPIRY = '5m'; +const TWO_FACTOR_LOGIN_CHALLENGE_TOKEN_EXPIRY = '5m'; +const TWO_FACTOR_SETUP_UNAVAILABLE = '2FA setup is not available for this user'; +const TWO_FACTOR_SETUP_NOT_INITIATED = '2FA setup not initiated'; +const TWO_FACTOR_SETUP_STALE = 'This two-factor setup step expired. Confirm your code again.'; +const TWO_FACTOR_INVALID_TOKEN = 'Invalid token'; +const TWO_FACTOR_ENROLLMENT_PROJECTION = + '+pendingTotpSecret +pendingBackupCodes _id twoFactorEnabled provider'; + +export const TWO_FACTOR_TOKEN_PURPOSE = { + LOGIN_CHALLENGE: 'login_2fa_challenge', + REQUIRED_SETUP: 'required_2fa_setup', + REQUIRED_ACKNOWLEDGEMENT: 'required_2fa_acknowledgement', + REQUIRED_FINALIZATION: 'required_2fa_finalization', +} as const; + +interface TwoFactorSetupBody { + tempToken?: string; + acknowledgementToken?: string; + finalizationToken?: string; +} + +/** + * The account events that retire every bearer token minted before them. + * + * Widened past the stored `Date`, because callers pass lean documents whose stamps can arrive + * already serialized, and a cutoff that fails to parse must not lock every session out. + */ +export interface TokenRetirementSignals { + twoFactorEnrolledAt?: Date | string | number | null; + credentialsChangedAt?: Date | string | number | null; +} + +/** A stored backup code: only its hash is persisted, and redemption marks it used. */ +export interface TwoFactorBackupCode { + codeHash: string; + used: boolean; + usedAt?: Date | null; +} + +/** + * The account fields the two-factor and credential routes read, as a plain shape: neither the + * request's user nor the data-layer results carry Mongoose types across the package boundary. + */ +export interface TwoFactorAccount extends TokenRetirementSignals { + _id?: UserDocumentId; + id?: string; + provider?: string; + role?: string; + tenantId?: string; + orgId?: string; + storageRegion?: string; + password?: string; + twoFactorEnabled?: boolean; + totpSecret?: string; + backupCodes?: TwoFactorBackupCode[]; + pendingTotpSecret?: string; + pendingBackupCodes?: TwoFactorBackupCode[]; + twoFactorAcknowledgementNonceHash?: string | null; + twoFactorFinalizationNonceHash?: string | null; +} + +/** An account as the data layer returns it, always addressed by its document id. */ +export type StoredTwoFactorAccount = TwoFactorAccount & { _id: UserDocumentId }; + +/** The user fields `isTokenRetired` needs, for callers that read with an explicit projection. */ +export const TOKEN_RETIREMENT_FIELDS = 'twoFactorEnrolledAt credentialsChangedAt'; + +/** Identity plus the one-time nonce a required-enrollment credential carries. */ +export interface TwoFactorEnrollmentCredential { + userId: string; + nonce: string; +} + +/** + * When a bearer token was minted, coarsely and exactly. + * + * `iat` is whole seconds, which cannot order a token against a cutoff that lands in the same + * second. `issuedAtMs` is stamped at mint time to settle exactly that, and is absent on tokens + * minted before the claim existed and on any this deployment did not sign. + */ +export interface TokenIssuance { + issuedAt?: number; + issuedAtMs?: number; +} + +/** Identity plus the mint time that lets a later account event retire the credential. */ +export interface TwoFactorTokenCredential extends TokenIssuance { + userId: string; +} + +/** An Express request that a required-enrollment credential has been validated for. */ +export type TwoFactorEnrollmentRequest = Request & { + user?: { id: string }; + twoFactorEnrollmentNonce?: string; + twoFactorSetupIssuedAt?: number; + twoFactorSetupIssuedAtMs?: number; +}; + +export type TwoFactorSetupUser = Pick< + StoredTwoFactorAccount, + '_id' | 'provider' | 'twoFactorEnabled' | 'pendingTotpSecret' | 'pendingBackupCodes' +>; + +export interface TwoFactorEnrollmentDependencies { + getUserById: (userId: string, projection: string) => Promise; + getTOTPSecret: (storedSecret: string) => Promise; + verifyTOTP: (secret: string, token: string) => Promise; + generateBackupCodes: () => Promise<{ + plainCodes: string[]; + codeObjects: TwoFactorBackupCode[]; + }>; + updateTwoFactorEnrollment: ( + userId: string, + guard: TwoFactorEnrollmentGuard, + update: TwoFactorEnrollmentUpdate, + ) => Promise; +} + +type TwoFactorEnrollmentFailure = { ok: false; status: 400; message: string }; + +export type TwoFactorConfirmResult = + | { ok: true; user: StoredTwoFactorAccount; plainCodes: string[]; acknowledgementNonce: string } + | TwoFactorEnrollmentFailure; + +export type TwoFactorAcknowledgeResult = + | { ok: true; user: StoredTwoFactorAccount; finalizationNonce: string } + | TwoFactorEnrollmentFailure; + +export type TwoFactorFinalizeResult = + | { ok: true; user: StoredTwoFactorAccount } + | TwoFactorEnrollmentFailure; + +const fail = (message: string): TwoFactorEnrollmentFailure => ({ ok: false, status: 400, message }); + +/** 256 bits of entropy, so the stored SHA-256 digest is not brute-forceable. */ +const createEnrollmentNonce = (): string => randomBytes(32).toString('hex'); + +const hashEnrollmentNonce = (nonce: string): string => + createHash('sha256').update(nonce).digest('hex'); + +export function isTwoFactorEnrollmentRequired( + user: Pick | null | undefined, +): boolean { + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION) || user?.twoFactorEnabled) { + return false; + } + + return isTwoFactorPolicyProvider(user?.provider); +} + +export function isTwoFactorSetupEligible( + user: Pick | null | undefined, +): boolean { + return isTwoFactorPolicyProvider(user?.provider); +} + +/** + * Whether a login that presented LibreChat-owned credentials must be refused outright. + * + * Only the local and LDAP strategies reach this point, so the credential was ours to check. A + * record left on a federated provider can still carry a password, because a reset assigns one + * without consulting `provider`, and the local strategy authenticates on the password alone. Such + * a login satisfies neither the identity provider's MFA nor this policy, and enrollment cannot + * remedy it because the account's credentials are not ours to promote. Under enforcement the + * federated sign-in path is the only way in. + */ +export function isCredentialLoginBlockedByTwoFactorPolicy( + user: Pick | null | undefined, +): boolean { + return ( + isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION) && + !isTwoFactorPolicyProvider(user?.provider) + ); +} + +function isTokenIssuedBefore( + issuance: TokenIssuance, + cutoff: Date | string | number | null | undefined, + retireTies: boolean, +): boolean { + if (cutoff == null) { + return false; + } + + const cutoffMs = new Date(cutoff).getTime(); + if (Number.isNaN(cutoffMs)) { + return false; + } + + const { issuedAtMs } = issuance; + if (typeof issuedAtMs === 'number' && Number.isFinite(issuedAtMs)) { + return retireTies ? issuedAtMs <= cutoffMs : issuedAtMs < cutoffMs; + } + + const { issuedAt } = issuance; + if (typeof issuedAt !== 'number' || !Number.isFinite(issuedAt)) { + return true; + } + + const cutoffSeconds = Math.floor(cutoffMs / 1000); + return retireTies ? issuedAt <= cutoffSeconds : issuedAt < cutoffSeconds; +} + +/** + * Whether a bearer token was minted before an account event that retires it. + * + * Bearer tokens carry no server-side state, so nothing stops honouring one the moment the account + * changes underneath it. Two events have to. Enrollment, because a token issued while the account + * still had no second factor was only ever accepted for that reason, so promotion has to retire it + * rather than reinstate it. And password recovery, because the credential the token was minted for + * has been revoked; `deleteAllUserSessions` already drops the refresh sessions on that path with + * the same intent, and a stateless token must not outlive the password that bought it. + * + * Both cutoffs are compared at whatever resolution the token can prove, and they differ only in how + * they resolve a tie. Enrollment keeps the token, because `finalizeTwoFactorSetup` stamps + * `twoFactorEnrolledAt` inside the promoting compare-and-swap and the session it hands back is + * minted after that write and a session sweep, so the survivor postdates the cutoff outright. + * Recovery retires it, because it mints nothing that has to live through it: a token dated to the + * resetting instant was bought with the credential the reset revoked. `issuedAtMs` is what makes + * either tie exact, sparing a token minted later in the same second that the whole-second fallback + * cannot tell apart, and retiring one minted earlier in it that the fallback would have spared. + * Tokens carrying no `issuedAtMs` surrender that whole second until they expire, and a token that + * cannot be dated at all is refused once any cutoff is set. + */ +export function isTokenRetired( + issuance: TokenIssuance, + user: TokenRetirementSignals | null | undefined, +): boolean { + return ( + isTokenIssuedBefore(issuance, user?.twoFactorEnrolledAt, false) || + isTokenIssuedBefore(issuance, user?.credentialsChangedAt, true) + ); +} + +export interface MintedSessionWithdrawal { + deleteAllUserSessions: (query: { userId: string }) => Promise; + clearCloudFrontCookies: ( + res: Response, + scope: { userId: string; tenantId?: string; storageRegion?: string }, + ) => void; +} + +/** + * Withdraws a session minted on this response. The cookies are cleared before the fallible session + * deletion, so a deletion that throws cannot leave the outgoing response carrying the credential. + */ +export async function withdrawMintedSession( + res: Response, + user: Pick, + userId: string, + deps: MintedSessionWithdrawal, +): Promise { + res.clearCookie('refreshToken'); + res.clearCookie('token_provider'); + deps.clearCloudFrontCookies(res, { + userId, + tenantId: user.tenantId ?? user.orgId, + storageRegion: user.storageRegion, + }); + await deps.deleteAllUserSessions({ userId }); +} + +/** + * Runs the retirement recheck that follows a mint. The minted credential postdates every cutoff, + * so a recheck that cannot complete withdraws it before failing rather than leaving it live. + */ +export async function recheckMintedCredential( + recheck: () => Promise, + withdraw: () => Promise, +): Promise { + try { + return await recheck(); + } catch (error) { + await withdraw(); + throw error; + } +} + +/** + * Whether password recovery landed after an enrollment was promoted. + * + * Recovery clears the staged enrollment in the same write that stamps `credentialsChangedAt`, so a reset + * that lands first loses `finalizeTwoFactorSetup`'s compare-and-swap. One that lands in the gap + * between that swap and the session hand-off does not, and the credential minted in that gap + * postdates the cutoff, so `isTokenRetired` has nothing to catch it by. Comparing the two stamps is + * what closes that ordering, and it is only meaningful against an enrollment just written. + * + * Compared at full resolution rather than the whole seconds `iat` forces, and ties resolve against + * the enrollment: a reset stamped in the very millisecond of promotion is the race, not a race-free + * coincidence. + */ +export function isEnrollmentSupersededByRecovery( + enrolledAt: Date | string | number | null | undefined, + credentialsChangedAt: Date | string | number | null | undefined, +): boolean { + if (enrolledAt == null || credentialsChangedAt == null) { + return false; + } + + const enrolledMs = new Date(enrolledAt).getTime(); + const resetMs = new Date(credentialsChangedAt).getTime(); + if (Number.isNaN(enrolledMs) || Number.isNaN(resetMs)) { + return false; + } + + return resetMs >= enrolledMs; +} + +/** + * Whether password recovery landed after the read that authorized a password login. + * + * A password is not a bearer token: it carries no mint stamp, so `isTokenRetired` cannot order it + * against `credentialsChangedAt`. The strategy compares the hash against a document it read beforehand, + * and every credential the login hands back is stamped after that comparison, so a reset landing in + * between produces a credential that postdates the cutoff and no downstream gate would retire it. + * Comparing the stamp the authenticating read saw against the stamp the record carries once the + * credential exists is what orders the two, and it is only meaningful against a read taken after + * the mint. A record that reports no reset at all is treated as unchanged rather than as evidence, + * so a lookup that comes back empty cannot lock out a login that nothing has revoked. + */ +export function hasPasswordResetSince( + seenAt: Date | string | number | null | undefined, + currentAt: Date | string | number | null | undefined, +): boolean { + const currentMs = toTimestamp(currentAt); + if (currentMs == null) { + return false; + } + + const seenMs = toTimestamp(seenAt); + return seenMs == null || currentMs > seenMs; +} + +function toTimestamp(value: Date | string | number | null | undefined): number | null { + if (value == null) { + return null; + } + + const ms = new Date(value).getTime(); + return Number.isNaN(ms) ? null : ms; +} + +/** + * Mints a credential that names a user and dates itself to the millisecond. + * + * Both credentials minted this way are redeemable without the account password, so both have to be + * refusable the moment recovery revokes it. `iat` alone cannot do that: it is whole seconds, so a + * token minted in the same second as the reset is indistinguishable from one minted just before it + * and would otherwise outlive the credential it was bought with. `issuedAtMs` orders the two. + */ +function generateDatedTwoFactorToken( + userId: string, + jwtSecret: string, + purpose: string, + expiresIn: jwt.SignOptions['expiresIn'], +): string { + return jwt.sign({ userId, purpose, issuedAtMs: Date.now() }, jwtSecret, { expiresIn }); +} + +export function generateTwoFactorSetupToken(userId: string, jwtSecret: string): string { + return generateDatedTwoFactorToken( + userId, + jwtSecret, + TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_SETUP, + TWO_FACTOR_SETUP_TOKEN_EXPIRY, + ); +} + +export function generateTwoFactorLoginChallengeToken(userId: string, jwtSecret: string): string { + return generateDatedTwoFactorToken( + userId, + jwtSecret, + TWO_FACTOR_TOKEN_PURPOSE.LOGIN_CHALLENGE, + TWO_FACTOR_LOGIN_CHALLENGE_TOKEN_EXPIRY, + ); +} + +function verifyDatedTwoFactorToken( + token: string | undefined, + jwtSecret: string | undefined, + purpose: string, +): TwoFactorTokenCredential | undefined { + if (!token || !jwtSecret) { + return undefined; + } + + try { + const payload = jwt.verify(token, jwtSecret); + if ( + typeof payload !== 'object' || + payload.purpose !== purpose || + typeof payload.userId !== 'string' || + !payload.userId + ) { + return undefined; + } + return { + userId: payload.userId, + issuedAt: payload.iat, + issuedAtMs: typeof payload.issuedAtMs === 'number' ? payload.issuedAtMs : undefined, + }; + } catch { + return undefined; + } +} + +export function verifyTwoFactorLoginChallengeToken( + tempToken: string | undefined, + jwtSecret: string | undefined, +): TwoFactorTokenCredential | undefined { + return verifyDatedTwoFactorToken(tempToken, jwtSecret, TWO_FACTOR_TOKEN_PURPOSE.LOGIN_CHALLENGE); +} + +export function generateTwoFactorSetupFinalizationToken( + userId: string, + nonce: string, + jwtSecret: string, +): string { + return jwt.sign( + { userId, nonce, purpose: TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_FINALIZATION }, + jwtSecret, + { expiresIn: TWO_FACTOR_SETUP_FINALIZATION_TOKEN_EXPIRY }, + ); +} + +export function generateTwoFactorSetupAcknowledgementToken( + userId: string, + nonce: string, + jwtSecret: string, +): string { + return jwt.sign( + { userId, nonce, purpose: TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_ACKNOWLEDGEMENT }, + jwtSecret, + { expiresIn: TWO_FACTOR_SETUP_ACKNOWLEDGEMENT_TOKEN_EXPIRY }, + ); +} + +function verifyEnrollmentCredential( + token: string | undefined, + jwtSecret: string | undefined, + purpose: string, +): TwoFactorEnrollmentCredential | undefined { + if (!token || !jwtSecret) { + return undefined; + } + + try { + const payload = jwt.verify(token, jwtSecret); + if ( + typeof payload !== 'object' || + payload.purpose !== purpose || + typeof payload.userId !== 'string' || + !payload.userId || + typeof payload.nonce !== 'string' || + !payload.nonce + ) { + return undefined; + } + return { userId: payload.userId, nonce: payload.nonce }; + } catch { + return undefined; + } +} + +export function verifyTwoFactorSetupAcknowledgementToken( + acknowledgementToken: string | undefined, + jwtSecret: string | undefined, +): TwoFactorEnrollmentCredential | undefined { + return verifyEnrollmentCredential( + acknowledgementToken, + jwtSecret, + TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_ACKNOWLEDGEMENT, + ); +} + +export function verifyTwoFactorSetupFinalizationToken( + finalizationToken: string | undefined, + jwtSecret: string | undefined, +): TwoFactorEnrollmentCredential | undefined { + return verifyEnrollmentCredential( + finalizationToken, + jwtSecret, + TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_FINALIZATION, + ); +} + +export function verifyTwoFactorSetupToken( + tempToken: string | undefined, + jwtSecret: string | undefined, +): TwoFactorTokenCredential | undefined { + return verifyDatedTwoFactorToken(tempToken, jwtSecret, TWO_FACTOR_TOKEN_PURPOSE.REQUIRED_SETUP); +} + +export interface BlockRetiredSetupTokenDependencies { + getUserById: (userId: string, projection: string) => Promise; +} + +/** + * Refuses a required-enrollment setup token that a later account event has retired. + * + * The setup token is the one credential in the enrollment chain carrying no server-side nonce, so + * nothing else can date it. Password recovery revokes the credential it was minted for and strands + * the staged enrollment, but a holder of the old credential could otherwise present a setup token + * from before the reset, stage a secret of their own, and promote it over the recovered account. + * The later steps are already covered, because recovery clears the nonce hashes they consume. + * + * Runs after `requireTwoFactorSetupToken`, which verifies the signature and stamps the request. + */ +export function createBlockRetiredSetupToken(deps: BlockRetiredSetupTokenDependencies) { + return async (req: Request, res: Response, next: NextFunction): Promise => { + try { + const setupRequest = req as TwoFactorEnrollmentRequest; + const userId = setupRequest.user?.id; + if (!userId) { + return res.status(401).json({ message: 'Invalid or expired two-factor setup token' }); + } + + const user = await deps.getUserById(userId, TOKEN_RETIREMENT_FIELDS); + if (!user) { + return res.status(401).json({ message: 'Invalid or expired two-factor setup token' }); + } + + if ( + isTokenRetired( + { + issuedAt: setupRequest.twoFactorSetupIssuedAt, + issuedAtMs: setupRequest.twoFactorSetupIssuedAtMs, + }, + user, + ) + ) { + logger.warn( + `[blockRetiredSetupToken] Setup token predates enrollment or password reset: userId=${userId}`, + ); + return res.status(401).json({ message: 'Invalid or expired two-factor setup token' }); + } + + next(); + } catch (err) { + logger.error('[blockRetiredSetupToken]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; +} + +export function requireTwoFactorSetupToken( + req: Request, + res: Response, + next: NextFunction, +): Response | void { + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return res.status(403).json({ message: 'Two-factor authentication setup is not required' }); + } + + const tempToken = (req.body as TwoFactorSetupBody | undefined)?.tempToken; + const credential = verifyTwoFactorSetupToken(tempToken, process.env.JWT_SECRET); + if (!credential) { + return res.status(401).json({ message: 'Invalid or expired two-factor setup token' }); + } + + const setupRequest = req as TwoFactorEnrollmentRequest; + setupRequest.user = { id: credential.userId }; + setupRequest.twoFactorSetupIssuedAt = credential.issuedAt; + setupRequest.twoFactorSetupIssuedAtMs = credential.issuedAtMs; + next(); +} + +export function requireTwoFactorSetupFinalizationToken( + req: Request, + res: Response, + next: NextFunction, +): Response | void { + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return res.status(403).json({ message: 'Two-factor authentication setup is not required' }); + } + + const finalizationToken = (req.body as TwoFactorSetupBody | undefined)?.finalizationToken; + const credential = verifyTwoFactorSetupFinalizationToken( + finalizationToken, + process.env.JWT_SECRET, + ); + if (!credential) { + return res.status(401).json({ message: 'Invalid or expired two-factor finalization token' }); + } + + const setupRequest = req as TwoFactorEnrollmentRequest; + setupRequest.user = { id: credential.userId }; + setupRequest.twoFactorEnrollmentNonce = credential.nonce; + next(); +} + +export function requireTwoFactorSetupAcknowledgementToken( + req: Request, + res: Response, + next: NextFunction, +): Response | void { + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return res.status(403).json({ message: 'Two-factor authentication setup is not required' }); + } + + const acknowledgementToken = (req.body as TwoFactorSetupBody | undefined)?.acknowledgementToken; + const credential = verifyTwoFactorSetupAcknowledgementToken( + acknowledgementToken, + process.env.JWT_SECRET, + ); + if (!credential) { + return res.status(401).json({ message: 'Invalid or expired two-factor acknowledgement token' }); + } + + const setupRequest = req as TwoFactorEnrollmentRequest; + setupRequest.user = { id: credential.userId }; + setupRequest.twoFactorEnrollmentNonce = credential.nonce; + next(); +} + +export function blockTwoFactorDisableWhenRequired( + req: Request, + res: Response, + next: NextFunction, +): Response | void { + if ( + !isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION) || + !isTwoFactorPolicyProvider( + (req.user as Pick | undefined)?.provider, + ) + ) { + next(); + return; + } + + return res.status(403).json({ + message: 'Two-factor authentication is required and cannot be disabled', + }); +} + +/** + * Verifies the current pending TOTP secret and stages deliverable backup codes. + * + * Nothing is promoted here: `twoFactorEnabled` stays false and the live secret is untouched, so + * every existing JWT and refresh session remains blocked until finalization. A lost response is + * safe to retry with the same setup token and a current TOTP; each attempt rotates the pending + * codes and mints a fresh acknowledgement nonce, invalidating any earlier one. + */ +export async function confirmTwoFactorSetup( + userId: string, + token: string | undefined, + deps: TwoFactorEnrollmentDependencies, +): Promise { + const user = await deps.getUserById(userId, TWO_FACTOR_ENROLLMENT_PROJECTION); + if (!user || user.twoFactorEnabled || !isTwoFactorSetupEligible(user)) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + if (!user.pendingTotpSecret || !user.pendingBackupCodes?.length) { + return fail(TWO_FACTOR_SETUP_NOT_INITIATED); + } + if (!token) { + return fail(TWO_FACTOR_INVALID_TOKEN); + } + + const secret = await deps.getTOTPSecret(user.pendingTotpSecret); + if (!secret) { + return fail(TWO_FACTOR_SETUP_NOT_INITIATED); + } + if (!(await deps.verifyTOTP(secret, token))) { + return fail(TWO_FACTOR_INVALID_TOKEN); + } + + const { plainCodes, codeObjects } = await deps.generateBackupCodes(); + const acknowledgementNonce = createEnrollmentNonce(); + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + + const updatedUser = await deps.updateTwoFactorEnrollment( + userId, + { + pendingTotpSecret: user.pendingTotpSecret, + pendingBackupCodes: user.pendingBackupCodes, + }, + { + pendingBackupCodes: codeObjects, + twoFactorAcknowledgementNonceHash: hashEnrollmentNonce(acknowledgementNonce), + twoFactorFinalizationNonceHash: null, + }, + ); + if (!updatedUser) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + + return { ok: true, user: updatedUser, plainCodes, acknowledgementNonce }; +} + +/** + * Consumes the acknowledgement nonce the user was handed with their backup codes and issues a + * finalization nonce in its place. Still no promotion and still no session. + */ +export async function acknowledgeTwoFactorSetup( + userId: string, + acknowledgementNonce: string | undefined, + deps: TwoFactorEnrollmentDependencies, +): Promise { + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + if (!acknowledgementNonce) { + return fail(TWO_FACTOR_SETUP_STALE); + } + + const finalizationNonce = createEnrollmentNonce(); + const updatedUser = await deps.updateTwoFactorEnrollment( + userId, + { twoFactorAcknowledgementNonceHash: hashEnrollmentNonce(acknowledgementNonce) }, + { + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: hashEnrollmentNonce(finalizationNonce), + }, + ); + if (!updatedUser) { + return fail(TWO_FACTOR_SETUP_STALE); + } + + return { ok: true, user: updatedUser, finalizationNonce }; +} + +/** + * The only step that promotes. It consumes the finalization nonce, the exact pending secret, and + * the exact pending backup-code snapshot in one compare-and-swap, after revalidating deployment + * policy and provider eligibility. A replayed credential finds no nonce and writes nothing. + */ +export async function finalizeTwoFactorSetup( + userId: string, + finalizationNonce: string | undefined, + deps: TwoFactorEnrollmentDependencies, +): Promise { + if (!finalizationNonce) { + return fail(TWO_FACTOR_SETUP_STALE); + } + + const user = await deps.getUserById(userId, TWO_FACTOR_ENROLLMENT_PROJECTION); + if (!user || user.twoFactorEnabled || !isTwoFactorSetupEligible(user)) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + if (!user.pendingTotpSecret || !user.pendingBackupCodes?.length) { + return fail(TWO_FACTOR_SETUP_NOT_INITIATED); + } + if (!isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION)) { + return fail(TWO_FACTOR_SETUP_UNAVAILABLE); + } + + const updatedUser = await deps.updateTwoFactorEnrollment( + userId, + { + pendingTotpSecret: user.pendingTotpSecret, + pendingBackupCodes: user.pendingBackupCodes, + twoFactorFinalizationNonceHash: hashEnrollmentNonce(finalizationNonce), + }, + { + totpSecret: user.pendingTotpSecret, + backupCodes: user.pendingBackupCodes, + twoFactorEnabled: true, + twoFactorEnrolledAt: new Date(), + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }, + ); + if (!updatedUser) { + return fail(TWO_FACTOR_SETUP_STALE); + } + + return { ok: true, user: updatedUser }; +} diff --git a/packages/api/src/auth/user.spec.ts b/packages/api/src/auth/user.spec.ts new file mode 100644 index 0000000000..929921b902 --- /dev/null +++ b/packages/api/src/auth/user.spec.ts @@ -0,0 +1,72 @@ +import type { IUser } from '@librechat/data-schemas'; +import { PUBLIC_USER_RESPONSE_FIELDS, sanitizeUserForResponse } from './user'; + +describe('sanitizeUserForResponse', () => { + const publicFields = { + _id: 'user-1', + email: 'user@example.com', + name: 'Test User', + provider: 'local', + role: 'USER', + twoFactorEnabled: true, + }; + + it('keeps the fields a client is allowed to receive', () => { + expect(sanitizeUserForResponse(publicFields as unknown as IUser)).toEqual(publicFields); + }); + + /** The queries behind these responses return the whole document, secrets included. */ + it('drops every field outside the allowlist', () => { + const stored = { + ...publicFields, + password: 'password-hash', + totpSecret: 'encrypted-secret', + backupCodes: [{ codeHash: 'hash', used: false }], + refreshToken: [{ refreshToken: 'live-session-token' }], + federatedTokens: [{ provider: 'openid', accessToken: 'token' }], + pendingTotpSecret: 'staged-secret', + pendingBackupCodes: [{ codeHash: 'staged', used: false }], + twoFactorAcknowledgementNonceHash: 'ack-hash', + twoFactorFinalizationNonceHash: 'final-hash', + twoFactorEnrolledAt: new Date(), + __v: 0, + }; + + expect(sanitizeUserForResponse(stored as unknown as IUser)).toEqual(publicFields); + }); + + /** A field added to the schema later must stay out until it is named here deliberately. */ + it('drops a field the allowlist has never heard of', () => { + const stored = { ...publicFields, someFieldAddedLater: 'sensitive' }; + + expect(sanitizeUserForResponse(stored as unknown as IUser)).not.toHaveProperty( + 'someFieldAddedLater', + ); + }); + + it('reads through a hydrated document', () => { + const hydrated = { + toObject: () => ({ ...publicFields, password: 'password-hash' }), + }; + + expect(sanitizeUserForResponse(hydrated)).toEqual(publicFields); + }); + + it('omits allowlisted fields the document does not carry', () => { + const sanitized = sanitizeUserForResponse({ _id: 'user-1' } as unknown as IUser); + + expect(sanitized).toEqual({ _id: 'user-1' }); + expect(sanitized).not.toHaveProperty('email'); + }); + + it('returns an empty object for a missing user', () => { + expect(sanitizeUserForResponse(null)).toEqual({}); + expect(sanitizeUserForResponse(undefined)).toEqual({}); + }); + + it('never names a credential field in the allowlist', () => { + for (const field of ['password', 'totpSecret', 'backupCodes', 'refreshToken']) { + expect(PUBLIC_USER_RESPONSE_FIELDS).not.toContain(field); + } + }); +}); diff --git a/packages/api/src/auth/user.ts b/packages/api/src/auth/user.ts new file mode 100644 index 0000000000..aa9203334d --- /dev/null +++ b/packages/api/src/auth/user.ts @@ -0,0 +1,61 @@ +import type { TwoFactorAccount } from './twoFactor'; + +/** + * Everything an authentication response may say about a user. + * + * An allowlist rather than a denylist, because the queries behind these responses do not reliably + * project: a `select()` built only from `+field` tokens leaves Mongoose with no projection to send, + * so the full stored document comes back, secrets and session records included. Subtracting known + * secrets from that would silently leak every field added to the schema afterwards. + */ +export const PUBLIC_USER_RESPONSE_FIELDS = [ + '_id', + 'id', + 'name', + 'username', + 'email', + 'emailVerified', + 'avatar', + 'provider', + 'role', + 'plugins', + 'twoFactorEnabled', + 'termsAccepted', + 'personalization', + 'favorites', + 'skillStates', + 'createdAt', + 'updatedAt', + 'tenantId', +] as const; + +type PublicUserField = (typeof PUBLIC_USER_RESPONSE_FIELDS)[number]; +export type PublicUser = Partial>; + +interface HydratedUser { + toObject?: () => Record; +} + +/** Reduces a user document, hydrated or lean, to the fields a client is allowed to receive. */ +export function sanitizeUserForResponse( + user: TwoFactorAccount | HydratedUser | null | undefined, +): PublicUser { + if (user == null) { + return {}; + } + + const source = ( + typeof (user as HydratedUser).toObject === 'function' + ? (user as HydratedUser).toObject?.() + : user + ) as Record; + + const publicUser: PublicUser = {}; + for (const field of PUBLIC_USER_RESPONSE_FIELDS) { + if (source[field] !== undefined) { + publicUser[field] = source[field]; + } + } + + return publicUser; +} diff --git a/packages/api/src/auth/userDocCache.ts b/packages/api/src/auth/userDocCache.ts index 4fa91a4772..9ae331ec25 100644 --- a/packages/api/src/auth/userDocCache.ts +++ b/packages/api/src/auth/userDocCache.ts @@ -131,6 +131,8 @@ function sanitizeUserForCache(user: Partial): CachedAuthUser { delete sanitized.pendingTotpSecret; delete sanitized.backupCodes; delete sanitized.pendingBackupCodes; + delete sanitized.twoFactorAcknowledgementNonceHash; + delete sanitized.twoFactorFinalizationNonceHash; delete sanitized.federatedTokens; delete sanitized.openidTokens; diff --git a/packages/api/src/images/authorization.spec.ts b/packages/api/src/images/authorization.spec.ts index 8f68909b8d..2c24a445ac 100644 --- a/packages/api/src/images/authorization.spec.ts +++ b/packages/api/src/images/authorization.spec.ts @@ -69,11 +69,20 @@ function signOpenIdUser(userId: string, refreshToken: string): string { } describe('createImageAuthorizationMiddleware', () => { + const originalEnforcement = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + afterAll(() => { + if (originalEnforcement === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalEnforcement; + } + }); let deps: ImageAuthorizationDeps; let response: Response; let next: jest.MockedFunction; beforeEach(() => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'false'; process.env.JWT_REFRESH_SECRET = 'image-authorization-secret'; deps = createDeps(); response = createResponse(); @@ -94,6 +103,130 @@ describe('createImageAuthorizationMiddleware', () => { expect(deps.findSession).toHaveBeenCalledWith({ userId: VIEWER_ID, refreshToken: token }); }); + describe('required enrollment and credential retirement', () => { + const originalEnforcement = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + + afterEach(() => { + if (originalEnforcement === undefined) { + delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION; + } else { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = originalEnforcement; + } + }); + + it.each(['local', 'ldap', undefined])( + 'refuses an unenrolled %s viewer without an extra owner read', + async (provider) => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + (deps.getUserById as jest.Mock).mockResolvedValue({ provider, twoFactorEnabled: false }); + const middleware = createImageAuthorizationMiddleware({}, deps); + + await middleware( + createRequest(`/images/${VIEWER_ID}/private.png`, `refreshToken=${signUser(VIEWER_ID)}`), + response, + next, + ); + + expect(next).not.toHaveBeenCalled(); + expect(response.status).toHaveBeenCalledWith(403); + expect(deps.getUserById).toHaveBeenCalledTimes(1); + }, + ); + + it.each(['local', 'openid', 'legacy-openid'])( + 'dates a %s credential against both account cutoffs', + async (kind) => { + const issuedAtMs = Date.now(); + const refreshToken = + kind === 'local' + ? jwt.sign({ id: VIEWER_ID, issuedAtMs }, process.env.JWT_REFRESH_SECRET as string, { + expiresIn: '1h', + }) + : 'provider-refresh'; + const marker = jwt.sign( + { + id: VIEWER_ID, + issuedAtMs, + ...(kind === 'openid' + ? { refreshTokenHash: createHash('sha256').update(refreshToken).digest('base64url') } + : {}), + }, + process.env.JWT_REFRESH_SECRET as string, + { expiresIn: '1h' }, + ); + (deps.isOpenIdReuseEnabled as jest.Mock).mockReturnValue(kind !== 'local'); + const cookie = + kind === 'local' + ? `refreshToken=${refreshToken}` + : `refreshToken=${refreshToken}; token_provider=openid; openid_user_id=${marker}`; + const req = Object.assign(createRequest(`/images/${VIEWER_ID}/private.png`, cookie), { + session: { openidTokens: { refreshToken } }, + }); + const middleware = createImageAuthorizationMiddleware({}, deps); + + for (const field of ['twoFactorEnrolledAt', 'credentialsChangedAt']) { + (deps.getUserById as jest.Mock).mockResolvedValue({ + [field]: new Date(issuedAtMs + 1), + twoFactorEnabled: true, + }); + await middleware(req, response, next); + expect(next).not.toHaveBeenCalled(); + expect(response.status).toHaveBeenCalledWith(403); + } + (deps.getUserById as jest.Mock).mockResolvedValue({ + twoFactorEnrolledAt: new Date(issuedAtMs - 1), + credentialsChangedAt: new Date(issuedAtMs - 1), + twoFactorEnabled: true, + }); + await middleware(req, response, next); + expect(next).toHaveBeenCalledTimes(1); + }, + ); + + it('checks the authenticated viewer rather than the image owner and preserves public access', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + (deps.getUserById as jest.Mock).mockImplementation(async (id: string) => ({ + role: 'USER', + tenantId: 'tenant-a', + provider: 'local', + twoFactorEnabled: id === OWNER_ID, + })); + (deps.getAgent as jest.Mock).mockResolvedValue({ _id: AGENT_DB_ID }); + (deps.hasPermission as jest.Mock).mockResolvedValue(false); + const middleware = createImageAuthorizationMiddleware({}, deps); + const req = createRequest(AGENT_PATH, `refreshToken=${signUser(VIEWER_ID)}`); + await middleware(req, response, next); + expect(next).not.toHaveBeenCalled(); + expect(deps.getUserPrincipals).not.toHaveBeenCalled(); + expect(deps.getUserById).toHaveBeenCalledTimes(2); + + (deps.hasPermission as jest.Mock).mockResolvedValue(true); + await middleware(req, response, next); + expect(next).toHaveBeenCalledTimes(1); + expect(deps.hasPermission).toHaveBeenLastCalledWith( + [{ principalType: 'public' }], + expect.anything(), + AGENT_DB_ID, + expect.anything(), + ); + }); + + it('keeps federated users exempt from the enrollment policy', async () => { + process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true'; + (deps.getUserById as jest.Mock).mockResolvedValue({ + provider: 'openid', + twoFactorEnabled: false, + }); + const middleware = createImageAuthorizationMiddleware({}, deps); + await middleware( + createRequest(`/images/${VIEWER_ID}/private.png`, `refreshToken=${signUser(VIEWER_ID)}`), + response, + next, + ); + expect(next).toHaveBeenCalledTimes(1); + }); + }); + it('rejects a signed refresh token whose session was revoked', async () => { (deps.findSession as jest.Mock).mockResolvedValue(null); const token = signUser(VIEWER_ID); @@ -368,9 +501,9 @@ describe('createImageAuthorizationMiddleware', () => { expect(deps.getUserById).toHaveBeenNthCalledWith( 1, OWNER_ID, - 'role tenantId idOnTheSource avatar', + 'role tenantId idOnTheSource avatar provider twoFactorEnabled twoFactorEnrolledAt credentialsChangedAt', ); - expect(deps.getUserById).toHaveBeenNthCalledWith(2, VIEWER_ID, 'tenantId'); + expect(deps.getUserById).toHaveBeenCalledTimes(2); }); it('denies the stored user avatar to a viewer from another tenant', async () => { diff --git a/packages/api/src/images/authorization.ts b/packages/api/src/images/authorization.ts index 20f0b5cb09..78170b9a81 100644 --- a/packages/api/src/images/authorization.ts +++ b/packages/api/src/images/authorization.ts @@ -11,17 +11,27 @@ import { import type { IAgent, IAssistant, AssistantQuery, SystemCapability } from '@librechat/data-schemas'; import type { Request, Response, NextFunction, RequestHandler } from 'express'; import type { FilterQuery, ProjectionType, Types } from 'mongoose'; +import type { TokenIssuance, TwoFactorAccount, TwoFactorTokenCredential } from '~/auth/twoFactor'; +import { + isTokenRetired, + isTwoFactorEnrollmentRequired, + TOKEN_RETIREMENT_FIELDS, +} from '~/auth/twoFactor'; const MAX_URL_LENGTH = 2048; const OBJECT_ID_PATTERN = /^[0-9a-f]{24}$/i; const AGENT_AVATAR_PATTERN = /^agent-(.+)-avatar-\d+\.[^/]+$/; +const IMAGE_USER_PROJECTION = `role tenantId idOnTheSource avatar provider twoFactorEnabled ${TOKEN_RETIREMENT_FIELDS}`; type Principal = { principalType: PrincipalType; principalId?: string | Types.ObjectId; }; -type ImageUser = { +type ImageUser = Pick< + TwoFactorAccount, + 'provider' | 'twoFactorEnabled' | 'twoFactorEnrolledAt' | 'credentialsChangedAt' +> & { role?: string | null; tenantId?: string; idOnTheSource?: string | null; @@ -54,12 +64,12 @@ type ResolvedImageConfig = { type CookieAuthResult = | { status: 'missing' } | { status: 'invalid' } - | { status: 'authenticated'; userId: string }; + | ({ status: 'authenticated' } & TwoFactorTokenCredential); type OpenIdCookieAuthResult = | { status: 'invalid' } - | { status: 'legacy'; userId: string } - | { status: 'authenticated'; userId: string }; + | ({ status: 'legacy'; userId: string } & TokenIssuance) + | ({ status: 'authenticated'; userId: string } & TokenIssuance); export interface ImageAuthorizationDeps { parseCookies: (cookieHeader: string) => Record; @@ -159,14 +169,16 @@ function parseImagePath(originalUrl: string, basePath: string): ImagePath | null }; } -function getSignedUserId(token: string | undefined): string | null { +function getSignedCredential(token: string | undefined): TwoFactorTokenCredential | null { const secret = process.env.JWT_REFRESH_SECRET; if (!token || !secret) { return null; } try { const payload = jwt.verify(token, secret) as JwtPayload; - return typeof payload.id === 'string' && OBJECT_ID_PATTERN.test(payload.id) ? payload.id : null; + return typeof payload.id === 'string' && OBJECT_ID_PATTERN.test(payload.id) + ? { userId: payload.id, issuedAt: payload.iat, issuedAtMs: payload.issuedAtMs } + : null; } catch (error) { logger.warn('[imageAuthorization] Invalid signed user token', error); return null; @@ -187,11 +199,21 @@ function getSignedOpenIdUserId( return { status: 'invalid' }; } if (typeof payload.refreshTokenHash !== 'string') { - return { status: 'legacy', userId: payload.id }; + return { + status: 'legacy', + userId: payload.id, + issuedAt: payload.iat, + issuedAtMs: payload.issuedAtMs, + }; } const refreshTokenHash = createHash('sha256').update(refreshToken).digest('base64url'); return payload.refreshTokenHash === refreshTokenHash - ? { status: 'authenticated', userId: payload.id } + ? { + status: 'authenticated', + userId: payload.id, + issuedAt: payload.iat, + issuedAtMs: payload.issuedAtMs, + } : { status: 'invalid' }; } catch (error) { logger.warn('[imageAuthorization] Invalid signed OpenID user token', error); @@ -231,7 +253,7 @@ async function authenticateRequest( } if (openIdAuth.status === 'legacy') { return refreshToken === req.session?.openidTokens?.refreshToken - ? { status: 'authenticated', userId: openIdAuth.userId } + ? { ...openIdAuth, status: 'authenticated' } : { status: 'invalid' }; } const session = await runAsSystem(() => @@ -240,12 +262,14 @@ async function authenticateRequest( return session ? openIdAuth : { status: 'invalid' }; } - const userId = getSignedUserId(refreshToken); - if (!userId) { + const credential = getSignedCredential(refreshToken); + if (!credential) { return { status: 'invalid' }; } - const session = await runAsSystem(() => deps.findSession({ userId, refreshToken })); - return session ? { status: 'authenticated', userId } : { status: 'invalid' }; + const session = await runAsSystem(() => + deps.findSession({ userId: credential.userId, refreshToken }), + ); + return session ? { status: 'authenticated', ...credential } : { status: 'invalid' }; } function isSharedAssistant(assistant: AssistantImageRecord, configs: AssistantConfig[]): boolean { @@ -285,6 +309,7 @@ async function loadPrincipals( async function canViewAgentAvatar( imagePath: ImagePath, viewerId: string | undefined, + viewer: ImageUser | null, owner: ImageUser, deps: ImageAuthorizationDeps, ): Promise { @@ -304,7 +329,6 @@ async function canViewAgentAvatar( return deps.hasPermission(publicPrincipal, ResourceType.AGENT, agent._id, PermissionBits.VIEW); } - const viewer = await runAsSystem(() => deps.getUserById(viewerId, 'role tenantId idOnTheSource')); if (!viewer || viewer.tenantId !== owner.tenantId) { return deps.hasPermission(publicPrincipal, ResourceType.AGENT, agent._id, PermissionBits.VIEW); } @@ -329,6 +353,7 @@ async function canViewAgentAvatar( async function canViewAssistantAvatar( imagePath: ImagePath, viewerId: string | undefined, + viewer: ImageUser | null, owner: ImageUser, configs: AssistantConfig[], deps: ImageAuthorizationDeps, @@ -344,7 +369,6 @@ async function canViewAssistantAvatar( return false; } - const viewer = await runAsSystem(() => deps.getUserById(viewerId, 'role tenantId idOnTheSource')); if (!viewer || viewer.tenantId !== owner.tenantId) { return false; } @@ -401,18 +425,6 @@ function isStoredUserAvatar( return storedAvatar?.canonicalPath === imagePath.canonicalPath; } -async function canViewUserAvatar( - viewerId: string | undefined, - owner: ImageUser, - deps: ImageAuthorizationDeps, -): Promise { - if (!viewerId) { - return false; - } - const viewer = await runAsSystem(() => deps.getUserById(viewerId, 'tenantId')); - return viewer != null && viewer.tenantId === owner.tenantId; -} - function denyRequest(res: Response, auth: CookieAuthResult): void { if (auth.status === 'missing') { res.status(401).send('Unauthorized'); @@ -447,7 +459,7 @@ export function createImageAuthorizationMiddleware( } const owner = await runAsSystem(() => - deps.getUserById(imagePath.ownerId, 'role tenantId idOnTheSource avatar'), + deps.getUserById(imagePath.ownerId, IMAGE_USER_PROJECTION), ); if (!owner) { if (options.secureImageLinks === false) { @@ -475,7 +487,19 @@ export function createImageAuthorizationMiddleware( } res.locals.privateImageCache = true; - const auth = await authPromise; + let auth = await authPromise; + let viewer: ImageUser | null = null; + if (auth.status === 'authenticated') { + const { userId } = auth; + viewer = + userId === imagePath.ownerId + ? owner + : await runAsSystem(() => deps.getUserById(userId, IMAGE_USER_PROJECTION)); + if (!viewer || isTokenRetired(auth, viewer) || isTwoFactorEnrollmentRequired(viewer)) { + auth = { status: 'invalid' }; + viewer = null; + } + } const viewerId = auth.status === 'authenticated' ? auth.userId : undefined; if (viewerId === imagePath.ownerId) { next(); @@ -484,15 +508,16 @@ export function createImageAuthorizationMiddleware( const authorizeSpecialAvatar = async (): Promise => { if (imagePath.agentId) { - return canViewAgentAvatar(imagePath, viewerId, owner, deps); + return canViewAgentAvatar(imagePath, viewerId, viewer, owner, deps); } if (isStoredUserAvatar(imagePath, owner, deps)) { - return canViewUserAvatar(viewerId, owner, deps); + return viewer != null && viewer.tenantId === owner.tenantId; } if (imageConfig.assistantEndpoints.length > 0) { const canViewAssistant = await canViewAssistantAvatar( imagePath, viewerId, + viewer, owner, imageConfig.assistantEndpoints, deps, diff --git a/packages/api/src/oauth/csrf.spec.ts b/packages/api/src/oauth/csrf.spec.ts index 5fb21a886a..b512ff4735 100644 --- a/packages/api/src/oauth/csrf.spec.ts +++ b/packages/api/src/oauth/csrf.spec.ts @@ -222,7 +222,10 @@ describe('setOpenIDMarkerCookies', () => { const signedUserId = (res.cookie as jest.Mock).mock.calls.find( ([name]) => name === OPENID_USER_ID_COOKIE, )?.[1]; - expect(jwt.verify(signedUserId, 'marker-secret')).toMatchObject({ id: 'user-123' }); + expect(jwt.verify(signedUserId, 'marker-secret')).toMatchObject({ + id: 'user-123', + issuedAtMs: expect.any(Number), + }); }); /** Preserves the marker's binding to the durable refresh-token session: a marker signed for one @@ -244,6 +247,7 @@ describe('setOpenIDMarkerCookies', () => { expect(jwt.verify(signedUserId, 'marker-secret')).toMatchObject({ id: 'user-123', refreshTokenHash: crypto.createHash('sha256').update('the-refresh-token').digest('base64url'), + issuedAtMs: expect.any(Number), }); }); diff --git a/packages/api/src/oauth/csrf.ts b/packages/api/src/oauth/csrf.ts index 4df6b1498f..08dd0bdf2e 100644 --- a/packages/api/src/oauth/csrf.ts +++ b/packages/api/src/oauth/csrf.ts @@ -118,7 +118,7 @@ export function setOpenIDMarkerCookies( ? crypto.createHash('sha256').update(refreshToken).digest('base64url') : undefined; const signedUserId = jwt.sign( - refreshTokenHash ? { id: userId, refreshTokenHash } : { id: userId }, + { id: userId, issuedAtMs: Date.now(), ...(refreshTokenHash ? { refreshTokenHash } : {}) }, secret, { expiresIn: refreshExpirySeconds }, ); diff --git a/packages/data-provider/specs/api-endpoints.spec.ts b/packages/data-provider/specs/api-endpoints.spec.ts index 415206e09b..cbc97a927e 100644 --- a/packages/data-provider/specs/api-endpoints.spec.ts +++ b/packages/data-provider/specs/api-endpoints.spec.ts @@ -6,6 +6,10 @@ import { buildLoginRedirectUrl, getSharedLinks, agentQueuedTurnsByConversation, + enableTwoFactorSetup, + confirmTwoFactorSetup, + acknowledgeTwoFactorSetup, + finalizeTwoFactorSetup, } from '../src/api-endpoints'; describe('buildLoginRedirectUrl', () => { @@ -117,3 +121,12 @@ describe('agent queued turns', () => { expect(agentQueuedTurn('turn/a b')).toBe('/api/agents/chat/queued-turns/turn%2Fa%20b'); }); }); + +describe('required two-factor setup endpoints', () => { + it('uses the purpose-specific setup paths', () => { + expect(enableTwoFactorSetup()).toBe('/api/auth/2fa/setup'); + expect(confirmTwoFactorSetup()).toBe('/api/auth/2fa/setup/confirm'); + expect(acknowledgeTwoFactorSetup()).toBe('/api/auth/2fa/setup/acknowledge'); + expect(finalizeTwoFactorSetup()).toBe('/api/auth/2fa/setup/finalize'); + }); +}); diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts index 16d2b05311..f520e8ffd8 100644 --- a/packages/data-provider/src/api-endpoints.ts +++ b/packages/data-provider/src/api-endpoints.ts @@ -585,6 +585,10 @@ export const feedback = (conversationId: string, messageId: string) => // Two-Factor Endpoints export const enableTwoFactor = () => `${BASE_URL}/api/auth/2fa/enable`; +export const enableTwoFactorSetup = () => `${BASE_URL}/api/auth/2fa/setup`; +export const confirmTwoFactorSetup = () => `${BASE_URL}/api/auth/2fa/setup/confirm`; +export const acknowledgeTwoFactorSetup = () => `${BASE_URL}/api/auth/2fa/setup/acknowledge`; +export const finalizeTwoFactorSetup = () => `${BASE_URL}/api/auth/2fa/setup/finalize`; export const verifyTwoFactor = () => `${BASE_URL}/api/auth/2fa/verify`; export const confirmTwoFactor = () => `${BASE_URL}/api/auth/2fa/confirm`; export const disableTwoFactor = () => `${BASE_URL}/api/auth/2fa/disable`; diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts index fbfd629f63..0b8d43e383 100644 --- a/packages/data-provider/src/config.spec.ts +++ b/packages/data-provider/src/config.spec.ts @@ -23,6 +23,7 @@ import { resolveMCPAppRateLimits, resolveMCPAppsPolicy, endpointSchema, + isTwoFactorPolicyProvider, resolveEndpointType, webSearchSchema, } from './config'; @@ -386,6 +387,16 @@ describe('scheduled MCP preflight config', () => { }); }); +describe('isTwoFactorPolicyProvider', () => { + it.each(['local', 'ldap', null, undefined])('includes provider %s', (provider) => { + expect(isTwoFactorPolicyProvider(provider)).toBe(true); + }); + + it.each(['openid', 'google', 'saml'])('excludes federated provider %s', (provider) => { + expect(isTwoFactorPolicyProvider(provider)).toBe(false); + }); +}); + describe('excludedKeys', () => { it.each([ '_id', diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index 8cb0a15cca..597caeb977 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -75,6 +75,18 @@ export { export const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml']; +export const TWO_FACTOR_ENROLLMENT_REQUIRED_CODE = 'TWO_FACTOR_ENROLLMENT_REQUIRED' as const; + +/** A federated record was refused a password login, so the only way in is its identity provider. */ +export const TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE = + 'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED' as const; + +const TWO_FACTOR_POLICY_PROVIDERS = new Set(['local', 'ldap']); + +export function isTwoFactorPolicyProvider(provider: string | null | undefined): boolean { + return provider == null || TWO_FACTOR_POLICY_PROVIDERS.has(provider); +} + /** How long a started social login may take to return to its callback before its `state` expires. */ export const DEFAULT_OAUTH_STATE_TTL_MS = 10 * 60 * 1000; @@ -2863,6 +2875,7 @@ export type TStartupConfig = { registrationEnabled: boolean; socialLoginEnabled: boolean; passwordResetEnabled: boolean; + twoFactorAuthenticationRequired?: boolean; emailEnabled: boolean; allowEmailChange: boolean; showBirthdayIcon: boolean; diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts index 455c805c0a..08b89f7c1d 100644 --- a/packages/data-provider/src/data-service.ts +++ b/packages/data-provider/src/data-service.ts @@ -1607,6 +1607,30 @@ export function enableTwoFactor(payload?: t.TEnable2FARequest): Promise { + return request.post(endpoints.enableTwoFactorSetup(), payload); +} + +export function confirmTwoFactorSetup( + payload: t.TConfirm2FASetupRequest, +): Promise { + return request.post(endpoints.confirmTwoFactorSetup(), payload); +} + +export function acknowledgeTwoFactorSetup( + payload: t.TAcknowledge2FASetupRequest, +): Promise { + return request.post(endpoints.acknowledgeTwoFactorSetup(), payload); +} + +export function finalizeTwoFactorSetup( + payload: t.TFinalize2FASetupRequest, +): Promise { + return request.post(endpoints.finalizeTwoFactorSetup(), payload); +} + export function verifyTwoFactor(payload: t.TVerify2FARequest): Promise { return request.post(endpoints.verifyTwoFactor(), payload); } diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.ts index 592c6a5ede..04c3883ff2 100644 --- a/packages/data-provider/src/index.ts +++ b/packages/data-provider/src/index.ts @@ -77,6 +77,7 @@ export * from './svg'; /* general helpers */ export * from './utils'; export * from './actions'; +export * from './twoFactor'; export { default as createPayload } from './createPayload'; // /* react query hooks */ // export * from './react-query/react-query-service'; diff --git a/packages/data-provider/src/request.spec.ts b/packages/data-provider/src/request.spec.ts new file mode 100644 index 0000000000..0175af45fb --- /dev/null +++ b/packages/data-provider/src/request.spec.ts @@ -0,0 +1,147 @@ +/** + * @jest-environment jsdom + */ +import { readTwoFactorSetupToken, clearTwoFactorSetupToken } from './twoFactor'; +import { getTokenHeader, setTokenHeader } from './headers-helpers'; +import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from './config'; +import request from './request'; + +interface AuthRecoveryWindow extends Window { + __librechatAuthRecovery?: unknown; +} + +const enrollmentBody = { + code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE, + twoFAPending: true, + twoFASetupRequired: true, + tempToken: 'setup-token', +}; + +const blockStorage = () => + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('storage blocked'); + }); + +describe('two-factor enrollment responses outside the interceptors', () => { + let pushState: jest.SpyInstance; + let redirectEvents: CustomEvent<{ href: string; inDocument: boolean }>[]; + + const captureRedirectEvent = (event: Event) => { + redirectEvents.push(event as CustomEvent<{ href: string; inDocument: boolean }>); + }; + + beforeEach(() => { + window.localStorage.clear(); + window.sessionStorage.clear(); + clearTwoFactorSetupToken(); + setTokenHeader(undefined); + delete (window as AuthRecoveryWindow).__librechatAuthRecovery; + window.history.pushState(null, '', '/c/new'); + pushState = jest.spyOn(window.history, 'pushState'); + redirectEvents = []; + window.addEventListener('authRedirectStarted', captureRedirectEvent); + }); + + afterEach(() => { + window.removeEventListener('authRedirectStarted', captureRedirectEvent); + jest.restoreAllMocks(); + }); + + it('opens setup from a parsed enrollment body', () => { + expect(request.redirectIfTwoFactorSetupPayload(enrollmentBody)).toBe(true); + expect(readTwoFactorSetupToken()).toBe('setup-token'); + }); + + /** Stream transports hand over the raw body, so the helper has to parse it itself. */ + it('opens setup from an enrollment body that arrives as text', () => { + expect(request.redirectIfTwoFactorSetupPayload(JSON.stringify(enrollmentBody))).toBe(true); + expect(readTwoFactorSetupToken()).toBe('setup-token'); + }); + + it('ignores a 403 body that is not an enrollment response', () => { + expect(request.redirectIfTwoFactorSetupPayload({ message: 'Forbidden' })).toBe(false); + expect(readTwoFactorSetupToken()).toBe(''); + expect(pushState).not.toHaveBeenCalled(); + }); + + it('ignores a body that is not JSON at all', () => { + expect(request.redirectIfTwoFactorSetupPayload('gateway')).toBe(false); + expect(readTwoFactorSetupToken()).toBe(''); + expect(pushState).not.toHaveBeenCalled(); + }); + + it('ignores an enrollment body with no usable token', () => { + expect(request.redirectIfTwoFactorSetupPayload({ ...enrollmentBody, tempToken: ' ' })).toBe( + false, + ); + expect(pushState).not.toHaveBeenCalled(); + }); + + /** + * Session storage outlives the document, so the redirect may replace it and clear the app state + * along the way. Routing in place here would leave that stale state behind. + */ + it('replaces the document when the token reached durable storage', () => { + request.redirectIfTwoFactorSetupPayload(enrollmentBody); + + expect(window.sessionStorage.getItem('two_factor_setup_token')).toBe('setup-token'); + expect(pushState).not.toHaveBeenCalled(); + expect(redirectEvents).toHaveLength(1); + expect(redirectEvents[0].detail.inDocument).toBe(false); + }); + + /** + * With storage blocked the in-memory mirror is the only copy, and replacing the document would + * destroy it, stranding the setup screen on its expired state with no way back. + */ + it('keeps the document when only the in-memory mirror holds the token', () => { + const setItem = blockStorage(); + + expect(request.redirectIfTwoFactorSetupPayload(enrollmentBody)).toBe(true); + + setItem.mockRestore(); + expect(pushState).toHaveBeenCalledTimes(1); + expect(window.location.pathname).toBe('/login/2fa/setup'); + expect(readTwoFactorSetupToken()).toBe('setup-token'); + }); + + /** + * The surviving document keeps the app mounted, so the hand-off has to say so: the session it + * redirects away from is still live and nothing else would tell the app to let it go. + */ + it('reports the surviving document to the app before routing in place', () => { + const setItem = blockStorage(); + + request.redirectIfTwoFactorSetupPayload(enrollmentBody); + + setItem.mockRestore(); + expect(redirectEvents).toHaveLength(1); + expect(redirectEvents[0].detail.inDocument).toBe(true); + expect(redirectEvents[0].detail.href).toContain('/login/2fa/setup'); + }); + + it('redirects once while a redirect is already under way', () => { + const setItem = blockStorage(); + + request.redirectIfTwoFactorSetupPayload(enrollmentBody); + request.redirectIfTwoFactorSetupPayload(enrollmentBody); + + setItem.mockRestore(); + expect(pushState).toHaveBeenCalledTimes(1); + }); + + /** + * Another tab writes the shared navigation marker first. This tab holds its own setup token and + * drops its own bearer, so it has to navigate too: without a bearer its 401s skip recovery. + */ + it('still navigates when another tab already started a redirect', () => { + window.localStorage.setItem('librechat.auth.redirect.startedAt', String(Date.now())); + setTokenHeader('retired-bearer'); + + expect(request.redirectIfTwoFactorSetupPayload(enrollmentBody)).toBe(true); + + expect(readTwoFactorSetupToken()).toBe('setup-token'); + expect(getTokenHeader()).toBeUndefined(); + expect(redirectEvents).toHaveLength(1); + }); +}); diff --git a/packages/data-provider/src/request.ts b/packages/data-provider/src/request.ts index 4291ae0b0c..acc8473502 100644 --- a/packages/data-provider/src/request.ts +++ b/packages/data-provider/src/request.ts @@ -2,6 +2,8 @@ import axios from 'axios'; import type { AxiosRequestConfig, AxiosResponse } from 'axios'; import type * as t from './types'; +import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from './config'; +import { persistTwoFactorSetupToken } from './twoFactor'; import { setTokenHeader } from './headers-helpers'; import * as endpoints from './api-endpoints'; @@ -188,6 +190,90 @@ const isAuthRedirectInProgress = () => { ); }; +/** Stream transports surface the body as text, while axios and fetch have already parsed it. */ +const parseSetupPayload = (payload: unknown): unknown => { + if (typeof payload !== 'string') { + return payload; + } + + try { + return JSON.parse(payload); + } catch { + return null; + } +}; + +const getTwoFactorSetupToken = (payload: unknown): string | null => { + if (typeof payload !== 'object' || payload == null) { + return null; + } + + const response = payload as { + code?: unknown; + twoFASetupRequired?: unknown; + tempToken?: unknown; + }; + if ( + response.code !== TWO_FACTOR_ENROLLMENT_REQUIRED_CODE || + response.twoFASetupRequired !== true || + typeof response.tempToken !== 'string' || + !response.tempToken.trim() + ) { + return null; + } + + return response.tempToken.trim(); +}; + +/** + * The setup token and the bearer it replaces are both tab-scoped, so a hand-off another tab + * started does nothing for this one: once the bearer is dropped, 401s skip recovery and the tab + * would stay on the app until reloaded. Only this tab's own navigation dedupes the hand-off. + */ +const isTabRedirectInProgress = () => { + const startedAt = getAuthRecoveryState().lastRedirectStartedAt; + return startedAt > 0 && Date.now() - startedAt < AUTH_REDIRECT_DEDUPE_MS; +}; + +const redirectToTwoFactorSetupOnce = (tempToken: string) => { + const isDurable = persistTwoFactorSetupToken(tempToken); + setTokenHeader(undefined); + if (isTabRedirectInProgress()) { + return; + } + + const loginRedirect = endpoints.buildLoginRedirectUrl(); + const redirectTo = new URL(loginRedirect, window.location.origin).searchParams.get('redirect_to'); + const searchParams = new URLSearchParams(); + if (redirectTo) { + searchParams.set('redirect_to', redirectTo); + } + const query = searchParams.toString(); + + const href = `${endpoints.apiBaseUrl()}/login/2fa/setup${query ? `?${query}` : ''}`; + setAuthRedirectStartedAt(); + window.dispatchEvent( + new CustomEvent(AUTH_REDIRECT_EVENT, { detail: { href, inDocument: !isDurable } }), + ); + if (isDurable) { + window.location.href = href; + return; + } + + /** + * Session storage refused the token, so only the in-memory mirror holds it and replacing the + * document would throw it away, stranding the setup screen on its expired state. Move the router + * instead: the history entry is the same one the hard navigation would have produced, and the + * router picks it up either from this event or, if it has yet to mount, from the location. + * + * The document surviving is also why the event above reports the hand-off as in-document: the + * session this redirect replaces would otherwise live on in whatever state the app already + * holds, which a replaced document would have discarded. + */ + window.history.pushState(null, '', href); + window.dispatchEvent(new PopStateEvent('popstate')); +}; + const dispatchAuthRecoveryEvent = (state: 'started' | 'finished') => { window.dispatchEvent(new CustomEvent(AUTH_RECOVERY_EVENT, { detail: { state } })); }; @@ -212,6 +298,11 @@ const startAuthRecovery = (retryRefresh?: boolean) => { dispatchAuthRecoveryEvent('started'); state.refreshPromise = refreshToken(retryRefresh) .then((response) => { + const setupToken = getTwoFactorSetupToken(response); + if (setupToken) { + redirectToTwoFactorSetupOnce(setupToken); + return null; + } const token = response?.token ?? ''; if (!token) { return null; @@ -234,7 +325,9 @@ const redirectToLoginOnce = () => { const href = endpoints.apiBaseUrl() + endpoints.buildLoginRedirectUrl(); setAuthRedirectStartedAt(); - window.dispatchEvent(new CustomEvent(AUTH_REDIRECT_EVENT, { detail: { href } })); + window.dispatchEvent( + new CustomEvent(AUTH_REDIRECT_EVENT, { detail: { href, inDocument: false } }), + ); window.location.href = href; }; @@ -305,6 +398,35 @@ const withAuthorization = (options: RequestInit | undefined, token: string | nul return { ...options, headers }; }; +/** + * Enforcement reaches the SSE hooks as an error event rather than a `Response`, because the stream + * transport is a raw `XMLHttpRequest` with neither the axios interceptor nor `_authenticatedFetch` + * in front of it. They hand the event body here so an enrollment 403 opens setup instead of being + * reported as a generic transport failure and retried against a condition that cannot clear. + */ +const redirectIfTwoFactorSetupPayload = (payload: unknown): boolean => { + const setupToken = getTwoFactorSetupToken(parseSetupPayload(payload)); + if (!setupToken) { + return false; + } + + redirectToTwoFactorSetupOnce(setupToken); + return true; +}; + +const redirectIfTwoFactorSetupRequired = async (response: Response): Promise => { + if (response.status !== 403) { + return false; + } + + return redirectIfTwoFactorSetupPayload( + await response + .clone() + .json() + .catch(() => null), + ); +}; + async function _authenticatedFetch(url: string, options?: RequestInit): Promise { if (typeof window === 'undefined') { return fetch(url, options); @@ -312,6 +434,9 @@ async function _authenticatedFetch(url: string, options?: RequestInit): Promise< const token = (await refreshBeforeRequest(url)) ?? getBearerToken(); const response = await fetch(url, withAuthorization(options, token)); + if (await redirectIfTwoFactorSetupRequired(response)) { + return response; + } if ( response.status !== 401 || isAuthRecoveryEndpoint(url) || @@ -335,7 +460,9 @@ async function _authenticatedFetch(url: string, options?: RequestInit): Promise< } await response.body?.cancel().catch(() => undefined); - return fetch(url, withAuthorization(options, refreshedToken)); + const retriedResponse = await fetch(url, withAuthorization(options, refreshedToken)); + await redirectIfTwoFactorSetupRequired(retriedResponse); + return retriedResponse; } if (typeof window !== 'undefined') { @@ -358,6 +485,14 @@ if (typeof window !== 'undefined') { return Promise.reject(error); } + if (error.response.status === 403) { + const setupToken = getTwoFactorSetupToken(error.response.data); + if (setupToken) { + redirectToTwoFactorSetupOnce(setupToken); + return Promise.reject(error); + } + } + const isRefreshRequest = originalRequest.url?.includes('/api/auth/refresh') === true; if (isAuthRecoveryEndpoint(originalRequest.url) && !isRefreshRequest) { return Promise.reject(error); @@ -432,4 +567,5 @@ export default { authenticatedFetch: _authenticatedFetch, refreshToken, dispatchTokenUpdatedEvent, + redirectIfTwoFactorSetupPayload, }; diff --git a/packages/data-provider/src/twoFactor.spec.ts b/packages/data-provider/src/twoFactor.spec.ts new file mode 100644 index 0000000000..6865756d01 --- /dev/null +++ b/packages/data-provider/src/twoFactor.spec.ts @@ -0,0 +1,83 @@ +/** + * @jest-environment jsdom + */ +import { + clearTwoFactorSetupToken, + persistTwoFactorSetupToken, + readTwoFactorSetupToken, +} from './twoFactor'; + +const STORAGE_KEY = 'two_factor_setup_token'; + +describe('two-factor setup token hand-off', () => { + beforeEach(() => { + window.sessionStorage.clear(); + clearTwoFactorSetupToken(); + }); + + it('round-trips a token without touching the URL', () => { + persistTwoFactorSetupToken('setup-token'); + + expect(readTwoFactorSetupToken()).toBe('setup-token'); + expect(window.sessionStorage.getItem(STORAGE_KEY)).toBe('setup-token'); + expect(window.location.search).toBe(''); + }); + + it('reads nothing before a token is handed over', () => { + expect(readTwoFactorSetupToken()).toBe(''); + }); + + it('trims the surrounding whitespace a transport may add', () => { + persistTwoFactorSetupToken(' setup-token '); + + expect(readTwoFactorSetupToken()).toBe('setup-token'); + }); + + it('drops the credential from both storage and memory when cleared', () => { + persistTwoFactorSetupToken('setup-token'); + + clearTwoFactorSetupToken(); + + expect(readTwoFactorSetupToken()).toBe(''); + expect(window.sessionStorage.getItem(STORAGE_KEY)).toBeNull(); + }); + + it('falls back to the in-memory mirror when session storage is unavailable', () => { + persistTwoFactorSetupToken('setup-token'); + const getItem = jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('storage blocked'); + }); + + expect(readTwoFactorSetupToken()).toBe('setup-token'); + + getItem.mockRestore(); + }); + + it('survives a persist that session storage refuses', () => { + const setItem = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('storage blocked'); + }); + + expect(() => persistTwoFactorSetupToken('setup-token')).not.toThrow(); + setItem.mockRestore(); + expect(readTwoFactorSetupToken()).toBe('setup-token'); + }); + + it('reports that a stored token outlives the current document', () => { + expect(persistTwoFactorSetupToken('setup-token')).toBe(true); + }); + + /** + * The mirror lives on `window`, so a caller that is about to replace the document has to know it + * is the only copy left. Reporting the refusal is what keeps that navigation in the same page. + */ + it('reports a refused persist so the caller can keep the document', () => { + const setItem = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('storage blocked'); + }); + + expect(persistTwoFactorSetupToken('setup-token')).toBe(false); + + setItem.mockRestore(); + }); +}); diff --git a/packages/data-provider/src/twoFactor.ts b/packages/data-provider/src/twoFactor.ts new file mode 100644 index 0000000000..430f33b9be --- /dev/null +++ b/packages/data-provider/src/twoFactor.ts @@ -0,0 +1,70 @@ +/** + * Hand-off channel for the required-enrollment setup token. + * + * The token is a bearer credential in its own right: it can generate a TOTP secret of the + * holder's choosing and then drive confirm, acknowledge, and finalize into a real session, with + * no victim secret involved. Carrying it in the query string would leave it in browser history, + * in access and reverse-proxy logs, and potentially in a Referer header, so it is handed to the + * setup screen out of band instead. + * + * Session storage survives the hard navigation the response interceptor performs and is scoped to + * the one tab. The in-memory mirror keeps the flow working where storage is blocked, which is why + * persisting reports whether it reached durable storage: a navigation that replaces the document + * would drop the mirror, so the interceptor stays inside the document when only the mirror holds. + */ + +const SETUP_TOKEN_STORAGE_KEY = 'two_factor_setup_token'; +const SETUP_TOKEN_EVENT = 'librechat:two-factor-setup-token'; + +interface TwoFactorSetupWindow extends Window { + __librechatTwoFactorSetupToken?: string; +} + +/** + * Returns whether the token reached storage that outlives the current document. Callers that were + * about to replace the document need to know, because the in-memory mirror does not survive that. + */ +export function persistTwoFactorSetupToken(tempToken: string): boolean { + const trimmed = tempToken.trim(); + (window as TwoFactorSetupWindow).__librechatTwoFactorSetupToken = trimmed; + let durable = true; + try { + window.sessionStorage.setItem(SETUP_TOKEN_STORAGE_KEY, trimmed); + } catch { + // Session storage can be blocked in embedded or private contexts. + durable = false; + } + window.dispatchEvent(new Event(SETUP_TOKEN_EVENT)); + return durable; +} + +/** + * Notifies a mounted setup screen when a token arrives after it rendered, as when a refresh on the + * setup route itself hands one off without navigating. Returns the unsubscribe function. + */ +export function subscribeTwoFactorSetupToken(listener: () => void): () => void { + window.addEventListener(SETUP_TOKEN_EVENT, listener); + return () => window.removeEventListener(SETUP_TOKEN_EVENT, listener); +} + +export function readTwoFactorSetupToken(): string { + try { + const stored = window.sessionStorage.getItem(SETUP_TOKEN_STORAGE_KEY)?.trim(); + if (stored) { + return stored; + } + } catch { + // Fall through to the in-memory mirror. + } + + return (window as TwoFactorSetupWindow).__librechatTwoFactorSetupToken?.trim() ?? ''; +} + +export function clearTwoFactorSetupToken(): void { + delete (window as TwoFactorSetupWindow).__librechatTwoFactorSetupToken; + try { + window.sessionStorage.removeItem(SETUP_TOKEN_STORAGE_KEY); + } catch { + // Ignore unavailable storage. + } +} diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts index 960d6b647d..236fa9882e 100644 --- a/packages/data-provider/src/types.ts +++ b/packages/data-provider/src/types.ts @@ -784,7 +784,9 @@ export type TLoginResponse = { token?: string; user?: TUser; twoFAPending?: boolean; + twoFASetupRequired?: boolean; tempToken?: string; + code?: 'TWO_FACTOR_ENROLLMENT_REQUIRED'; }; /** Shared payload for any operation that requires OTP or backup-code verification. */ @@ -801,6 +803,37 @@ export type TEnable2FAResponse = { message?: string; }; +export type TEnable2FASetupRequest = { + tempToken: string; +}; + +export type TConfirm2FASetupRequest = { + tempToken: string; + token: string; +}; + +export type TConfirm2FASetupResponse = { + backupCodes: string[]; + acknowledgementToken: string; +}; + +export type TAcknowledge2FASetupRequest = { + acknowledgementToken: string; +}; + +export type TAcknowledge2FASetupResponse = { + finalizationToken: string; +}; + +export type TFinalize2FASetupRequest = { + finalizationToken: string; +}; + +export type TFinalize2FASetupResponse = { + token: string; + user: TUser; +}; + export type TVerify2FARequest = TOTPVerificationPayload; export type TVerify2FAResponse = { @@ -1032,8 +1065,12 @@ export type TEmailChangeResponse = { }; export type TRefreshTokenResponse = { - token: string; - user: TUser; + token?: string; + user?: TUser; + twoFAPending?: boolean; + twoFASetupRequired?: boolean; + tempToken?: string; + code?: 'TWO_FACTOR_ENROLLMENT_REQUIRED'; }; export type TCheckUserKeyResponse = { diff --git a/packages/data-schemas/src/methods/session.ts b/packages/data-schemas/src/methods/session.ts index 5b8b42cae0..bc89c19bbe 100644 --- a/packages/data-schemas/src/methods/session.ts +++ b/packages/data-schemas/src/methods/session.ts @@ -301,6 +301,9 @@ export function createSessionMethods(mongoose: typeof import('mongoose')): { payload: { id: session.user, sessionId: session._id, + /** `iat` is whole seconds, too coarse to order this token against a password reset that + * lands in the same second. `isTokenRetired` reads this claim to settle that exactly. */ + issuedAtMs: Date.now(), }, secret: process.env.JWT_REFRESH_SECRET!, expirationTime: Math.floor((expiresIn - Date.now()) / 1000), diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.ts index 1ba6b2812d..ecdfe87a66 100644 --- a/packages/data-schemas/src/methods/user.methods.spec.ts +++ b/packages/data-schemas/src/methods/user.methods.spec.ts @@ -762,6 +762,314 @@ describe('User Methods - Database Tests', () => { }); }); + describe('updateTwoFactorEnrollment', () => { + const ACK_HASH = 'acknowledgement-nonce-hash'; + const FINAL_HASH = 'finalization-nonce-hash'; + + async function createEnrollingUser( + email: string, + overrides: Partial = {}, + ): Promise<{ id: string; pendingBackupCodes: NonNullable }> { + const user = await User.create({ + name: 'Enrolling User', + email, + provider: 'local', + twoFactorEnabled: false, + pendingTotpSecret: 'pending-secret', + pendingBackupCodes: [{ codeHash: 'staged-hash', used: false }], + ...overrides, + }); + const id = user._id.toString(); + const stored = await User.findById(user._id).select('+pendingBackupCodes').lean(); + return { id, pendingBackupCodes: stored?.pendingBackupCodes ?? [] }; + } + + function readEnrollment(userId: string) { + return User.findById(userId) + .select( + '+totpSecret +backupCodes +pendingTotpSecret +pendingBackupCodes +twoFactorAcknowledgementNonceHash +twoFactorFinalizationNonceHash', + ) + .lean(); + } + + test('stages rotated backup codes and an acknowledgement nonce without enabling 2FA', async () => { + const { id, pendingBackupCodes } = await createEnrollingUser('stage-2fa@example.com'); + + const updated = await methods.updateTwoFactorEnrollment( + id, + { pendingTotpSecret: 'pending-secret', pendingBackupCodes }, + { + pendingBackupCodes: [{ codeHash: 'deliverable-hash', used: false, usedAt: null }], + twoFactorAcknowledgementNonceHash: ACK_HASH, + twoFactorFinalizationNonceHash: null, + }, + ); + const stored = await readEnrollment(id); + + expect(updated).not.toBeNull(); + expect(stored?.twoFactorEnabled).toBe(false); + expect(stored?.totpSecret).toBeFalsy(); + expect(stored?.pendingTotpSecret).toBe('pending-secret'); + expect(stored?.pendingBackupCodes).toMatchObject([{ codeHash: 'deliverable-hash' }]); + expect(stored?.twoFactorAcknowledgementNonceHash).toBe(ACK_HASH); + expect(stored?.twoFactorFinalizationNonceHash).toBeNull(); + }); + + test('updates legacy enrolling users whose two-factor flag is missing', async () => { + const { id, pendingBackupCodes } = await createEnrollingUser('legacy-2fa@example.com'); + const objectId = new mongoose.Types.ObjectId(id); + await User.collection.updateOne({ _id: objectId }, { $unset: { twoFactorEnabled: '' } }); + + const legacyUser = await User.collection.findOne({ _id: objectId }); + expect(legacyUser).not.toHaveProperty('twoFactorEnabled'); + + const updated = await methods.updateTwoFactorEnrollment( + id, + { pendingTotpSecret: 'pending-secret', pendingBackupCodes }, + { twoFactorAcknowledgementNonceHash: ACK_HASH }, + ); + const stored = await readEnrollment(id); + + expect(updated).not.toBeNull(); + expect(stored?.twoFactorAcknowledgementNonceHash).toBe(ACK_HASH); + }); + + test('a second confirmation on the stale snapshot loses the race and writes nothing', async () => { + const { id, pendingBackupCodes } = await createEnrollingUser('confirm-race@example.com'); + const guard = { pendingTotpSecret: 'pending-secret', pendingBackupCodes }; + + const first = await methods.updateTwoFactorEnrollment(id, guard, { + pendingBackupCodes: [{ codeHash: 'first-hash', used: false, usedAt: null }], + twoFactorAcknowledgementNonceHash: 'first-ack', + }); + const second = await methods.updateTwoFactorEnrollment(id, guard, { + pendingBackupCodes: [{ codeHash: 'second-hash', used: false, usedAt: null }], + twoFactorAcknowledgementNonceHash: 'second-ack', + }); + const stored = await readEnrollment(id); + + expect(first).not.toBeNull(); + expect(second).toBeNull(); + expect(stored?.pendingBackupCodes).toMatchObject([{ codeHash: 'first-hash' }]); + expect(stored?.twoFactorAcknowledgementNonceHash).toBe('first-ack'); + }); + + test('consumes the acknowledgement nonce exactly once and keeps 2FA disabled', async () => { + const { id } = await createEnrollingUser('ack-2fa@example.com', { + twoFactorAcknowledgementNonceHash: ACK_HASH, + }); + + const first = await methods.updateTwoFactorEnrollment( + id, + { twoFactorAcknowledgementNonceHash: ACK_HASH }, + { + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: FINAL_HASH, + }, + ); + const replay = await methods.updateTwoFactorEnrollment( + id, + { twoFactorAcknowledgementNonceHash: ACK_HASH }, + { + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: 'replayed-finalization-hash', + }, + ); + const stored = await readEnrollment(id); + + expect(first).not.toBeNull(); + expect(replay).toBeNull(); + expect(stored?.twoFactorEnabled).toBe(false); + expect(stored?.twoFactorFinalizationNonceHash).toBe(FINAL_HASH); + }); + + test('promotes the pending enrollment once and clears every enrollment field', async () => { + const { id, pendingBackupCodes } = await createEnrollingUser('finalize-2fa@example.com', { + twoFactorFinalizationNonceHash: FINAL_HASH, + expiresAt: new Date(Date.now() + 604800 * 1000), + }); + const guard = { + pendingTotpSecret: 'pending-secret', + pendingBackupCodes, + twoFactorFinalizationNonceHash: FINAL_HASH, + }; + const promotion = { + totpSecret: 'pending-secret', + backupCodes: pendingBackupCodes, + twoFactorEnabled: true, + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }; + + const promoted = await methods.updateTwoFactorEnrollment(id, guard, promotion); + const replay = await methods.updateTwoFactorEnrollment(id, guard, promotion); + const stored = await readEnrollment(id); + + expect(promoted).not.toBeNull(); + expect(promoted).toMatchObject({ + name: 'Enrolling User', + email: 'finalize-2fa@example.com', + provider: 'local', + twoFactorEnabled: true, + }); + expect(promoted?.createdAt).toBeInstanceOf(Date); + expect(replay).toBeNull(); + expect(stored).toMatchObject({ + twoFactorEnabled: true, + totpSecret: 'pending-secret', + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }); + expect(stored?.backupCodes).toMatchObject([{ codeHash: 'staged-hash' }]); + expect(stored?.expiresAt).toBeUndefined(); + }); + + test('persists the enrollment cutoff that retires pre-enrollment access tokens', async () => { + const { id, pendingBackupCodes } = await createEnrollingUser('cutoff-2fa@example.com', { + twoFactorFinalizationNonceHash: FINAL_HASH, + }); + const twoFactorEnrolledAt = new Date(); + + const promoted = await methods.updateTwoFactorEnrollment( + id, + { + pendingTotpSecret: 'pending-secret', + pendingBackupCodes, + twoFactorFinalizationNonceHash: FINAL_HASH, + }, + { + totpSecret: 'pending-secret', + backupCodes: pendingBackupCodes, + twoFactorEnabled: true, + twoFactorEnrolledAt, + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }, + ); + const stored = await readEnrollment(id); + + expect(promoted).not.toBeNull(); + /** A path the schema does not declare is dropped in silence, so assert the round trip. */ + expect(stored?.twoFactorEnrolledAt).toBeInstanceOf(Date); + expect(stored?.twoFactorEnrolledAt?.getTime()).toBe(twoFactorEnrolledAt.getTime()); + }); + + test('leaves the enrollment cutoff null until a promotion writes it', async () => { + const { id } = await createEnrollingUser('no-cutoff-2fa@example.com'); + + const stored = await readEnrollment(id); + + expect(stored?.twoFactorEnrolledAt).toBeNull(); + }); + + const concurrentTransitions: Array<[string, Partial]> = [ + ['regenerated secret', { pendingTotpSecret: 'different-secret' }], + [ + 'regenerated backup codes', + { pendingBackupCodes: [{ codeHash: 'different-hash', used: false }] }, + ], + ['federated provider transition', { provider: 'openid' }], + ['already-enabled transition', { twoFactorEnabled: true }], + ['cleared finalization nonce', { twoFactorFinalizationNonceHash: null }], + ]; + + test.each(concurrentTransitions)( + 'does not promote after a concurrent %s', + async (name, concurrentUpdate) => { + const { id, pendingBackupCodes } = await createEnrollingUser( + `raced-2fa-${name.replace(/ /g, '-')}@example.com`, + { twoFactorFinalizationNonceHash: FINAL_HASH }, + ); + await User.findByIdAndUpdate(id, { $set: concurrentUpdate }); + + const promoted = await methods.updateTwoFactorEnrollment( + id, + { + pendingTotpSecret: 'pending-secret', + pendingBackupCodes, + twoFactorFinalizationNonceHash: FINAL_HASH, + }, + { + totpSecret: 'pending-secret', + backupCodes: pendingBackupCodes, + twoFactorEnabled: true, + pendingTotpSecret: null, + pendingBackupCodes: [], + twoFactorAcknowledgementNonceHash: null, + twoFactorFinalizationNonceHash: null, + }, + ); + const stored = await readEnrollment(id); + + expect(promoted).toBeNull(); + expect(stored?.totpSecret).toBeFalsy(); + expect(stored?.twoFactorEnabled).toBe(concurrentUpdate.twoFactorEnabled === true); + }, + ); + + test('never exposes nonce state on an unprojected read', async () => { + const { id } = await createEnrollingUser('nonce-projection@example.com', { + twoFactorAcknowledgementNonceHash: ACK_HASH, + twoFactorFinalizationNonceHash: FINAL_HASH, + }); + + const user = await methods.getUserById(id); + + expect(user).not.toBeNull(); + expect(user).not.toHaveProperty('twoFactorAcknowledgementNonceHash'); + expect(user).not.toHaveProperty('twoFactorFinalizationNonceHash'); + expect(user).not.toHaveProperty('pendingTotpSecret'); + }); + + test('invalidates cached auth user documents after a successful enrollment write', async () => { + enableAuthUserDocCache(); + const { id, pendingBackupCodes } = await createEnrollingUser('cached-2fa@example.com'); + const cache = { + get: jest.fn().mockResolvedValue(['cached-auth-document']), + delete: jest.fn().mockResolvedValue(true), + }; + const methodsWithCache = createUserMethods(mongoose, { + getCache: jest.fn().mockReturnValue(cache), + }); + + await methodsWithCache.updateTwoFactorEnrollment( + id, + { pendingTotpSecret: 'pending-secret', pendingBackupCodes }, + { twoFactorAcknowledgementNonceHash: ACK_HASH }, + ); + + expect(cache.delete).toHaveBeenCalledWith('cached-auth-document'); + expect(cache.delete).toHaveBeenCalledWith(`${AUTH_USER_DOC_BY_ID_PREFIX}:${id}`); + }); + + test('leaves the auth user document cache untouched when the guard loses', async () => { + enableAuthUserDocCache(); + const { id } = await createEnrollingUser('cached-2fa-miss@example.com'); + const cache = { + get: jest.fn().mockResolvedValue(['cached-auth-document']), + delete: jest.fn().mockResolvedValue(true), + }; + const methodsWithCache = createUserMethods(mongoose, { + getCache: jest.fn().mockReturnValue(cache), + }); + + const result = await methodsWithCache.updateTwoFactorEnrollment( + id, + { pendingTotpSecret: 'stale-secret' }, + { twoFactorAcknowledgementNonceHash: ACK_HASH }, + ); + + expect(result).toBeNull(); + expect(cache.delete).not.toHaveBeenCalled(); + }); + }); + describe('getUserById', () => { test('should get user by ID', async () => { const user = await User.create({ diff --git a/packages/data-schemas/src/methods/user.test.ts b/packages/data-schemas/src/methods/user.test.ts index 5e557805e4..fb2162aae4 100644 --- a/packages/data-schemas/src/methods/user.test.ts +++ b/packages/data-schemas/src/methods/user.test.ts @@ -1,7 +1,7 @@ import mongoose from 'mongoose'; +import type { IUser } from '~/types'; import { createUserMethods } from './user'; import { signPayload } from '~/crypto'; -import type { IUser } from '~/types'; jest.mock('~/crypto', () => ({ signPayload: jest.fn(), @@ -46,6 +46,7 @@ describe('User Methods', () => { username: mockUser.username, provider: mockUser.provider, email: mockUser.email, + issuedAtMs: expect.any(Number), }, secret: 'test-secret', expirationTime: 900, // 15 minutes in seconds (DEFAULT_SESSION_EXPIRY / 1000) @@ -64,6 +65,7 @@ describe('User Methods', () => { username: mockUser.username, provider: mockUser.provider, email: mockUser.email, + issuedAtMs: expect.any(Number), }, secret: 'test-secret', expirationTime: 900, // 15 minutes in seconds (DEFAULT_SESSION_EXPIRY / 1000) @@ -82,6 +84,7 @@ describe('User Methods', () => { username: mockUser.username, provider: mockUser.provider, email: mockUser.email, + issuedAtMs: expect.any(Number), }, secret: 'test-secret', expirationTime: 1800, // 30 minutes in seconds @@ -101,6 +104,7 @@ describe('User Methods', () => { username: mockUser.username, provider: mockUser.provider, email: mockUser.email, + issuedAtMs: expect.any(Number), }, secret: 'test-secret', expirationTime: 0, // 0 seconds diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts index cfa9057a10..ee4ad522a0 100644 --- a/packages/data-schemas/src/methods/user.ts +++ b/packages/data-schemas/src/methods/user.ts @@ -6,6 +6,7 @@ import { type StatefulCodeEnvironment, } from 'librechat-data-provider'; import type { IUser, BalanceConfig, CreateUserRequest, UserDeleteResult } from '~/types'; +import type { TwoFactorEnrollmentGuard, TwoFactorEnrollmentUpdate } from '~/types'; import type { CacheStore } from '~/types'; import { evictAuthUserDocs } from '~/utils/eviction'; import { escapeRegExp } from '~/utils/string'; @@ -19,6 +20,11 @@ export const USER_DELETION_FENCE_STALE_MS: number = 15 * 60_000; /** Bounds concurrent bulk deletions held for one owner at any moment. */ const MAX_SUBAGENT_ADMISSION_FENCES = 32; +/** Providers whose credentials LibreChat owns, and therefore the only ones it can enroll in 2FA. */ +const TWO_FACTOR_ENROLLMENT_PROVIDERS = [null, 'local', 'ldap']; +const TWO_FACTOR_ENROLLMENT_PROJECTION = + '+totpSecret +backupCodes +pendingTotpSecret +pendingBackupCodes +twoFactorAcknowledgementNonceHash +twoFactorFinalizationNonceHash'; + interface UserMethodDeps { getCache?: (key: string) => CacheStore | undefined; /** Resolves after the given milliseconds; tests pass one that need not wait out the cache TTL. */ @@ -70,6 +76,11 @@ export function createUserMethods( samlId: string, profileData: Pick, 'username' | 'name'>, ) => Promise; + updateTwoFactorEnrollment: ( + userId: string, + guard: TwoFactorEnrollmentGuard, + updateData: TwoFactorEnrollmentUpdate, + ) => Promise; acceptTerms: (userId: string) => Promise; searchUsers: ({ searchPattern, @@ -114,6 +125,8 @@ export function createUserMethods( used: boolean; usedAt?: Date | null; }>; + twoFactorAcknowledgementNonceHash?: string | null; + twoFactorFinalizationNonceHash?: string | null; refreshToken?: Array<{ refreshToken: string; }>; @@ -386,6 +399,36 @@ export function createUserMethods( return updated; } + /** + * Single compare-and-swap for every step of required two-factor enrollment. The filter always + * pins the user to an unenrolled, policy-eligible provider, and `guard` adds the exact pending + * secret, pending backup-code snapshot, or one-time nonce hash the caller observed. A step whose + * predicate has moved returns `null` instead of writing. + */ + async function updateTwoFactorEnrollment( + userId: string, + guard: TwoFactorEnrollmentGuard, + updateData: TwoFactorEnrollmentUpdate, + ): Promise { + const User = mongoose.models.User; + const updated = await User.findOneAndUpdate( + { + _id: userId, + twoFactorEnabled: { $ne: true }, + provider: { $in: TWO_FACTOR_ENROLLMENT_PROVIDERS }, + ...guard, + }, + { $set: updateData, $unset: { expiresAt: '' } }, + { new: true, runValidators: true }, + ) + .select(TWO_FACTOR_ENROLLMENT_PROJECTION) + .lean(); + if (updated) { + await invalidateAuthUserDocCache(userId); + } + return updated; + } + /** Resolves false only when a cached document for the user may still be served. */ async function invalidateAuthUserDocCache(userId: string): Promise { if (!isAuthUserDocCacheEnabled()) { @@ -655,6 +698,9 @@ export function createUserMethods( username: user.username, provider: user.provider, email: user.email, + /** `iat` is whole seconds, too coarse to order this token against a password reset that + * lands in the same second. `isTokenRetired` reads this claim to settle that exactly. */ + issuedAtMs: Date.now(), }, secret: process.env.JWT_SECRET, expirationTime: expires / 1000, @@ -760,6 +806,8 @@ export function createUserMethods( used: boolean; usedAt?: Date | null; }>; + twoFactorAcknowledgementNonceHash?: string | null; + twoFactorFinalizationNonceHash?: string | null; refreshToken?: Array<{ refreshToken: string; }>; @@ -887,6 +935,7 @@ export function createUserMethods( updateUser, awaitAuthUserDocEviction, claimSamlIdentity, + updateTwoFactorEnrollment, acceptTerms, searchUsers, getUserById, diff --git a/packages/data-schemas/src/schema/user.ts b/packages/data-schemas/src/schema/user.ts index de4fbab159..d705ba71bf 100644 --- a/packages/data-schemas/src/schema/user.ts +++ b/packages/data-schemas/src/schema/user.ts @@ -104,6 +104,10 @@ const userSchema: Schema = new Schema( type: Boolean, default: false, }, + twoFactorEnrolledAt: { + type: Date, + default: null, + }, totpSecret: { type: String, select: false, @@ -129,6 +133,16 @@ const userSchema: Schema = new Schema( credentialsChangedAt: { type: Date, }, + twoFactorAcknowledgementNonceHash: { + type: String, + select: false, + default: null, + }, + twoFactorFinalizationNonceHash: { + type: String, + select: false, + default: null, + }, refreshToken: { type: [SessionSchema], }, diff --git a/packages/data-schemas/src/types/user.ts b/packages/data-schemas/src/types/user.ts index 2928d227f6..c589705e5e 100644 --- a/packages/data-schemas/src/types/user.ts +++ b/packages/data-schemas/src/types/user.ts @@ -36,6 +36,11 @@ export interface IUser extends Document { plugins?: string[]; openidIssuer?: string; twoFactorEnabled?: boolean; + /** + * When required enrollment promoted this account. Access tokens are stateless, so this is the + * cutoff that retires the ones minted while the account still had no second factor. + */ + twoFactorEnrolledAt?: Date | null; totpSecret?: string; backupCodes?: Array<{ codeHash: string; @@ -48,8 +53,12 @@ export interface IUser extends Document { used: boolean; usedAt?: Date | null; }>; - /** Instant of the last credential change; access tokens issued before it are rejected */ - credentialsChangedAt?: Date; + /** Instant of the last credential change; bearer tokens issued before it are rejected */ + credentialsChangedAt?: Date | null; + /** SHA-256 hash of the one-time nonce that authorizes the backup-code acknowledgement step. */ + twoFactorAcknowledgementNonceHash?: string | null; + /** SHA-256 hash of the one-time nonce that authorizes required-enrollment finalization. */ + twoFactorFinalizationNonceHash?: string | null; refreshToken?: Array<{ refreshToken: string; }>; @@ -82,6 +91,30 @@ export interface IUser extends Document { openidTokens?: OIDCTokens; } +/** + * Predicates that bind a required two-factor enrollment mutation to the exact state its + * caller observed. Every supplied field is ANDed into the compare-and-swap filter, so a + * concurrent regeneration, acknowledgement, or finalization loses the race and fails closed. + */ +export interface TwoFactorEnrollmentGuard { + pendingTotpSecret?: string; + pendingBackupCodes?: NonNullable; + twoFactorAcknowledgementNonceHash?: string; + twoFactorFinalizationNonceHash?: string; +} + +/** Fields a required two-factor enrollment step may write; `null` clears the stored value. */ +export interface TwoFactorEnrollmentUpdate { + totpSecret?: string | null; + backupCodes?: NonNullable; + twoFactorEnabled?: boolean; + twoFactorEnrolledAt?: Date; + pendingTotpSecret?: string | null; + pendingBackupCodes?: NonNullable; + twoFactorAcknowledgementNonceHash?: string | null; + twoFactorFinalizationNonceHash?: string | null; +} + export interface OIDCTokens { access_token?: string; id_token?: string;