diff --git a/.env.example b/.env.example index 922fd6e8e4..5fb11aa22b 100644 --- a/.env.example +++ b/.env.example @@ -861,6 +861,10 @@ REGISTER_WINDOW=60 # VERIFY_EMAIL_SUBMISSION_MAX=2 # VERIFY_EMAIL_SUBMISSION_WINDOW=2 +# Passkey enrollment, keyed by user id (the routes require a signed-in session). +PASSKEY_STEPUP_MAX=20 +PASSKEY_STEPUP_WINDOW=15 + LIMIT_CONCURRENT_MESSAGES=true CONCURRENT_MESSAGE_MAX=2 @@ -941,6 +945,20 @@ APPLE_KEY_ID= APPLE_PRIVATE_KEY_PATH= APPLE_CALLBACK_URL=/oauth/apple/callback +# Passkeys (WebAuthn) +# Requires HTTPS in production; localhost is exempt. +ALLOW_PASSKEY_LOGIN=false +# Optional. Defaults to the hostname of DOMAIN_CLIENT. Pin this if DOMAIN_CLIENT +# may change: existing passkeys stop working when the RP ID changes. +# PASSKEY_RP_ID= +# Optional. Name shown by the authenticator. Defaults to APP_TITLE. +# PASSKEY_RP_NAME= +# Optional. Comma-separated allowed origins. Defaults to DOMAIN_CLIENT and DOMAIN_SERVER. +# PASSKEY_ORIGINS= +# Adding a passkey requires re-entering the account password, since a passkey is a +# durable single-factor login. PASSKEY_STEPUP_MAX / PASSKEY_STEPUP_WINDOW in the +# Moderation section cap how many enrollment attempts an account may make. + # OpenID OPENID_CLIENT_ID= OPENID_CLIENT_SECRET= diff --git a/api/cache/getLogStores.js b/api/cache/getLogStores.js index 72e36bc09e..1edae18156 100644 --- a/api/cache/getLogStores.js +++ b/api/cache/getLogStores.js @@ -71,6 +71,7 @@ const namespaces = { CacheKeys.ADMIN_OAUTH_EXCHANGE, Time.THIRTY_SECONDS, ), + [CacheKeys.PASSKEY_CHALLENGE]: standardCache(CacheKeys.PASSKEY_CHALLENGE, Time.FIVE_MINUTES), }; /** diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js index 7d7843d320..e3902a83a9 100644 --- a/api/server/controllers/AuthController.js +++ b/api/server/controllers/AuthController.js @@ -22,6 +22,7 @@ const { } = require('~/server/services/AuthService'); const { deleteAllUserSessions, + deletePasskeysByUser, getUserById, findSession, updateUser, @@ -331,6 +332,7 @@ const resetPasswordController = async (req, res) => { return res.status(400).json(resetPasswordService); } else { await deleteAllUserSessions({ userId: req.body.userId }); + await deletePasskeysByUser(req.body.userId); return res.status(200).json(resetPasswordService); } } catch (e) { diff --git a/api/server/controllers/AuthController.spec.js b/api/server/controllers/AuthController.spec.js index e0f0892bf1..03a165d619 100644 --- a/api/server/controllers/AuthController.spec.js +++ b/api/server/controllers/AuthController.spec.js @@ -41,6 +41,7 @@ jest.mock('openid-client', () => ({ refreshTokenGrant: jest.fn() })); jest.mock('~/models', () => ({ deleteSession: jest.fn(), deleteAllUserSessions: jest.fn(), + deletePasskeysByUser: jest.fn(), getUserById: jest.fn(), findSession: jest.fn(), updateUser: jest.fn(), @@ -124,6 +125,7 @@ const { graphTokenController, refreshController, registrationController, + resetPasswordController, } = require('./AuthController'); const { getGraphApiToken } = require('~/server/services/GraphTokenService'); const { @@ -134,9 +136,18 @@ const { setCloudFrontAuthCookies, setAuthTokens, registerUser, + resetPassword, } = require('~/server/services/AuthService'); const { getOpenIdConfig, getOpenIdEmail } = require('~/strategies'); -const { deleteSession, getUserById, findSession, updateUser, deleteTokens } = require('~/models'); +const { + deleteSession, + getUserById, + findSession, + updateUser, + deleteTokens, + deleteAllUserSessions, + deletePasskeysByUser, +} = require('~/models'); const { createRefreshTokenBridgeFlightKey, deleteRefreshTokenBridges, @@ -2462,3 +2473,49 @@ describe('registrationController - invite consumption', () => { expect(res.send).toHaveBeenCalledWith({ message: 'ok' }); }); }); + +describe('resetPasswordController', () => { + let req, res; + + beforeEach(() => { + jest.clearAllMocks(); + req = { + body: { + userId: 'user-123', + token: 'reset-token', + password: 'new-password', + }, + }; + res = { + status: jest.fn().mockReturnThis(), + json: jest.fn(), + }; + }); + + it('revokes sessions and passkeys on successful password reset', async () => { + const serviceResult = { message: 'Password reset successful' }; + resetPassword.mockResolvedValue(serviceResult); + deleteAllUserSessions.mockResolvedValue(undefined); + deletePasskeysByUser.mockResolvedValue(undefined); + + await resetPasswordController(req, res); + + expect(resetPassword).toHaveBeenCalledWith('user-123', 'reset-token', 'new-password'); + expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-123' }); + expect(deletePasskeysByUser).toHaveBeenCalledWith('user-123'); + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith(serviceResult); + }); + + it('does not revoke sessions or passkeys when reset fails', async () => { + const resetError = new Error('Invalid token'); + resetPassword.mockResolvedValue(resetError); + + await resetPasswordController(req, res); + + expect(deleteAllUserSessions).not.toHaveBeenCalled(); + expect(deletePasskeysByUser).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith(resetError); + }); +}); diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js index 2df1017a9a..f3f8b5d34b 100644 --- a/api/server/controllers/UserController.js +++ b/api/server/controllers/UserController.js @@ -531,6 +531,7 @@ const deleteUserController = async (req, res) => { await db.deleteMessages({ user: user.id }); await db.deleteAllUserSessions({ userId: user.id }); + await db.deletePasskeysByUser(user.id); await db.deleteTransactions({ user: user.id }); await db.deleteUserKey({ userId: user.id, all: true }); await db.deleteBalances({ user: user._id }); diff --git a/api/server/controllers/UserController.spec.js b/api/server/controllers/UserController.spec.js index 0912feca0e..4b283ae4a4 100644 --- a/api/server/controllers/UserController.spec.js +++ b/api/server/controllers/UserController.spec.js @@ -45,6 +45,7 @@ jest.mock('~/models', () => { const _mongoose = require('mongoose'); return { deleteAllUserSessions: jest.fn().mockResolvedValue(undefined), + deletePasskeysByUser: jest.fn().mockResolvedValue(undefined), deleteAllSharedLinks: jest.fn().mockResolvedValue(undefined), deleteAllAgentApiKeys: jest.fn().mockResolvedValue(undefined), deleteConversationTags: jest.fn().mockResolvedValue(undefined), @@ -188,6 +189,7 @@ const { findUser, deleteConvos, acceptTerms, + deletePasskeysByUser, deleteUserById, deleteUserCodeEnvironments, deleteMessages, @@ -569,12 +571,14 @@ describe('deleteUserController', () => { it('should return 200 on successful deletion', async () => { const userId = new mongoose.Types.ObjectId(); - const req = { user: { id: userId.toString(), _id: userId, email: 'test@test.com' } }; + const userIdStr = userId.toString(); + const req = { user: { id: userIdStr, _id: userId, email: 'test@test.com' } }; await deleteUserController(req, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); expect(mockRes.send).toHaveBeenCalledWith({ message: 'User deleted' }); + expect(deletePasskeysByUser).toHaveBeenCalledWith(userIdStr); expect(beginAgentTriggerUserDeletion).toHaveBeenCalledWith(userId.toString(), expect.any(Date)); expect(mockPrepareAgentTriggerUserPurge).toHaveBeenCalledWith( userId.toString(), diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.js index 0294b05bb5..15cb6b8ba9 100644 --- a/api/server/controllers/__tests__/deleteUser.spec.js +++ b/api/server/controllers/__tests__/deleteUser.spec.js @@ -34,6 +34,7 @@ const mockCancelAndDrainSubagentThreads = jest.fn(); const mockQuiesceUserSchedules = jest.fn(); const mockDeleteSchedulesByUser = jest.fn(); const mockRevokeUserCodeEnvironmentWorkers = jest.fn(); +const mockDeletePasskeysByUser = jest.fn(); jest.mock('@librechat/data-schemas', () => ({ logger: { error: jest.fn(), info: jest.fn() }, @@ -86,6 +87,7 @@ jest.mock('@librechat/api', () => ({ jest.mock('~/models', () => ({ deleteAllUserSessions: (...args) => mockDeleteAllUserSessions(...args), + deletePasskeysByUser: (...args) => mockDeletePasskeysByUser(...args), deleteAllSharedLinks: (...args) => mockDeleteAllSharedLinks(...args), updateUserPlugins: (...args) => mockUpdateUserPlugins(...args), deleteUserById: (...args) => mockDeleteUserById(...args), @@ -219,6 +221,7 @@ function stubDeletionMocks() { mockQuiesceUserSchedules.mockResolvedValue(true); mockDeleteSchedulesByUser.mockResolvedValue(); mockRevokeUserCodeEnvironmentWorkers.mockResolvedValue(0); + mockDeletePasskeysByUser.mockResolvedValue(); } beforeEach(() => { @@ -244,6 +247,7 @@ describe('deleteUserController - 2FA enforcement', () => { expect(mockRevokeUserCodeEnvironmentWorkers).toHaveBeenCalledWith( expect.objectContaining({ userId: 'user1' }), ); + expect(mockDeletePasskeysByUser).toHaveBeenCalledWith('user1'); expect(mockVerifyOTPOrBackupCode).not.toHaveBeenCalled(); expect(mockBeginAgentTriggerUserDeletion.mock.invocationCallOrder[0]).toBeLessThan( mockPrepareAgentTriggerUserPurge.mock.invocationCallOrder[0], diff --git a/api/server/controllers/auth/PasskeyController.js b/api/server/controllers/auth/PasskeyController.js new file mode 100644 index 0000000000..dd6c830755 --- /dev/null +++ b/api/server/controllers/auth/PasskeyController.js @@ -0,0 +1,21 @@ +const bcrypt = require('bcryptjs'); +const { CacheKeys } = require('librechat-data-provider'); +const { createPasskeyHandlers } = require('@librechat/api'); +const { checkBan } = require('~/server/middleware'); +const { getLogStores } = require('~/cache'); +const db = require('~/models'); + +module.exports = createPasskeyHandlers({ + checkBan, + compare: bcrypt.compare, + getChallengeCache: () => getLogStores(CacheKeys.PASSKEY_CHALLENGE), + getUserById: db.getUserById, + updateUser: db.updateUser, + createPasskey: db.createPasskey, + deletePasskey: db.deletePasskey, + renamePasskey: db.renamePasskey, + recordPasskeyUse: db.recordPasskeyUse, + findPasskeysByUser: db.findPasskeysByUser, + countPasskeysByUser: db.countPasskeysByUser, + findPasskeyByCredentialId: db.findPasskeyByCredentialId, +}); diff --git a/api/server/controllers/auth/PasskeyController.spec.js b/api/server/controllers/auth/PasskeyController.spec.js new file mode 100644 index 0000000000..ee7b317e84 --- /dev/null +++ b/api/server/controllers/auth/PasskeyController.spec.js @@ -0,0 +1,132 @@ +const mockCheckBan = jest.fn(); +const mockGetLogStores = jest.fn(); +const mockModels = { + getUserById: jest.fn(), + updateUser: jest.fn(), + createPasskey: jest.fn(), + deletePasskey: jest.fn(), + renamePasskey: jest.fn(), + recordPasskeyUse: jest.fn(), + findPasskeysByUser: jest.fn(), + countPasskeysByUser: jest.fn(), + findPasskeyByCredentialId: jest.fn(), +}; + +jest.mock('@librechat/api', () => { + const actual = jest.requireActual('@librechat/api'); + return { ...actual, createPasskeyHandlers: jest.fn(actual.createPasskeyHandlers) }; +}); +jest.mock('~/models', () => mockModels); +jest.mock('~/cache', () => ({ getLogStores: (...args) => mockGetLogStores(...args) })); +jest.mock('~/server/middleware', () => ({ + checkBan: (...args) => mockCheckBan(...args), +})); + +const bcrypt = require('bcryptjs'); +const { CacheKeys } = require('librechat-data-provider'); +const { createPasskeyHandlers } = require('@librechat/api'); +const controller = require('./PasskeyController'); + +const [deps] = createPasskeyHandlers.mock.calls[0]; + +const PASSWORD = 'correct horse battery staple'; + +function buildRes() { + return { + status: jest.fn().mockReturnThis(), + json: jest.fn().mockReturnThis(), + }; +} + +const originalAllow = process.env.ALLOW_PASSKEY_LOGIN; + +beforeAll(() => { + process.env.ALLOW_PASSKEY_LOGIN = 'true'; +}); + +afterAll(() => { + if (originalAllow === undefined) { + delete process.env.ALLOW_PASSKEY_LOGIN; + } else { + process.env.ALLOW_PASSKEY_LOGIN = originalAllow; + } +}); + +describe('PasskeyController wiring', () => { + it('exports the handlers the auth routes mount', () => { + expect(Object.keys(controller).sort()).toEqual( + [ + 'authenticatePasskey', + 'listPasskeys', + 'loginPasskeyOptions', + 'registerPasskeyOptions', + 'registerPasskeyVerify', + 'removePasskey', + 'updatePasskey', + ].sort(), + ); + }); + + it('hands the model methods, bcrypt and the ban check to the handler factory', () => { + expect(deps.compare).toBe(bcrypt.compare); + for (const name of Object.keys(mockModels)) { + expect(deps[name]).toBe(mockModels[name]); + } + + const args = [{}, {}, jest.fn()]; + deps.checkBan(...args); + expect(mockCheckBan).toHaveBeenCalledWith(...args); + }); + + it('backs the challenge store with the passkey challenge cache namespace', () => { + const cache = {}; + mockGetLogStores.mockReturnValue(cache); + + expect(deps.getChallengeCache()).toBe(cache); + expect(mockGetLogStores).toHaveBeenCalledWith(CacheKeys.PASSKEY_CHALLENGE); + }); + + it('confirms a step-up against a real bcrypt hash', async () => { + mockModels.getUserById.mockResolvedValue({ + _id: 'u1', + password: bcrypt.hashSync(PASSWORD, 4), + }); + mockModels.deletePasskey.mockResolvedValue({ deletedCount: 1 }); + const res = buildRes(); + + await controller.removePasskey( + { user: { id: 'u1' }, params: { passkeyId: 'p1' }, body: { password: PASSWORD } }, + res, + ); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockModels.deletePasskey).toHaveBeenCalledWith('p1', 'u1'); + }); + + it('fails a sign-in closed when the challenge cache holds no challenge for the session', async () => { + mockModels.findPasskeyByCredentialId.mockResolvedValue({ + user: 'u1', + credentialId: 'cred-1', + publicKey: Buffer.from('pk'), + counter: 0, + transports: [], + }); + const res = buildRes(); + const next = jest.fn(); + mockGetLogStores.mockReturnValue({ + get: async () => undefined, + set: async () => true, + delete: async () => true, + }); + + await controller.authenticatePasskey( + { body: { credential: { id: 'cred-1', response: {} }, sessionId: 's1' } }, + res, + next, + ); + + expect(res.status).toHaveBeenCalledWith(401); + expect(next).not.toHaveBeenCalled(); + expect(mockCheckBan).not.toHaveBeenCalled(); + }); +}); diff --git a/api/server/controllers/auth/TwoFactorAuthController.js b/api/server/controllers/auth/TwoFactorAuthController.js index 23cdd8b078..a75f7c2653 100644 --- a/api/server/controllers/auth/TwoFactorAuthController.js +++ b/api/server/controllers/auth/TwoFactorAuthController.js @@ -1,5 +1,6 @@ const jwt = require('jsonwebtoken'); const { logger } = require('@librechat/data-schemas'); +const { isTokenIssuedBeforeCredentialChange } = require('@librechat/api'); const { verifyTOTP, getTOTPSecret, @@ -31,6 +32,15 @@ const verify2FAWithTempToken = async (req, res) => { 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) { diff --git a/api/server/controllers/auth/TwoFactorAuthController.spec.js b/api/server/controllers/auth/TwoFactorAuthController.spec.js new file mode 100644 index 0000000000..82f72e13fa --- /dev/null +++ b/api/server/controllers/auth/TwoFactorAuthController.spec.js @@ -0,0 +1,94 @@ +const jwt = require('jsonwebtoken'); + +const mockLogger = { warn: jest.fn(), error: jest.fn(), debug: jest.fn() }; +const mockGetUserById = jest.fn(); +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('~/server/services/twoFactorService', () => ({ + getTOTPSecret: (...args) => mockGetTOTPSecret(...args), + verifyTOTP: (...args) => mockVerifyTOTP(...args), + verifyBackupCode: (...args) => mockVerifyBackupCode(...args), +})); + +jest.mock('~/server/services/AuthService', () => ({ + setAuthTokens: (...args) => mockSetAuthTokens(...args), +})); + +jest.mock('~/models', () => ({ + getUserById: (...args) => mockGetUserById(...args), +})); + +const { verify2FAWithTempToken } = require('./TwoFactorAuthController'); + +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; +}; + +/** Signs a real temp token so `iat` is genuine rather than hand-stamped. */ +const tempTokenFor = (userId) => jwt.sign({ userId }, SECRET, { expiresIn: '5m' }); + +beforeEach(() => { + jest.clearAllMocks(); + process.env.JWT_SECRET = SECRET; + mockGetTOTPSecret.mockResolvedValue('totp-secret'); + mockVerifyTOTP.mockResolvedValue(true); + mockSetAuthTokens.mockResolvedValue('auth-token'); +}); + +describe('verify2FAWithTempToken credential-change cutoff', () => { + const userDoc = (overrides = {}) => ({ + _id: { toString: () => USER_ID }, + twoFactorEnabled: true, + totpSecret: 'totp-secret', + ...overrides, + }); + + 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) }), + ); + const res = buildRes(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(401); + 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) }), + ); + const res = buildRes(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockSetAuthTokens).toHaveBeenCalled(); + }); + + it('accepts a temp token when the account never changed credentials', async () => { + const tempToken = tempTokenFor(USER_ID); + mockGetUserById.mockResolvedValue(userDoc()); + const res = buildRes(); + + await verify2FAWithTempToken({ body: { tempToken, token: '123456' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(mockSetAuthTokens).toHaveBeenCalled(); + }); +}); diff --git a/api/server/middleware/limiters/index.js b/api/server/middleware/limiters/index.js index 317278fe51..45397e9f1d 100644 --- a/api/server/middleware/limiters/index.js +++ b/api/server/middleware/limiters/index.js @@ -2,6 +2,7 @@ const createTTSLimiters = require('./ttsLimiters'); const createSTTLimiters = require('./sttLimiters'); const loginLimiter = require('./loginLimiter'); +const passkeyLimiter = require('./passkeyLimiter'); const importLimiters = require('./importLimiters'); const uploadLimiters = require('./uploadLimiters'); const forkLimiters = require('./forkLimiters'); @@ -16,6 +17,7 @@ const emailChangeSubmissionLimiter = require('./emailChangeSubmissionLimiter'); const emailChangeSubmissionIpLimiter = require('./emailChangeSubmissionIpLimiter'); const resetPasswordLimiter = require('./resetPasswordLimiter'); const twoFactorTempLimiter = require('./twoFactorTempLimiter'); +const passkeyStepUpLimiter = require('./passkeyStepUpLimiter'); const verifyEmailSubmissionLimiter = require('./verifyEmailSubmissionLimiter'); const resetPasswordSubmissionLimiter = require('./resetPasswordSubmissionLimiter'); @@ -27,6 +29,8 @@ module.exports = { ...shareLimiters, ...promptUsageLimiter, loginLimiter, + passkeyLimiter, + passkeyStepUpLimiter, registerLimiter, toolCallLimiter, createTTSLimiters, diff --git a/api/server/middleware/limiters/passkeyLimiter.js b/api/server/middleware/limiters/passkeyLimiter.js new file mode 100644 index 0000000000..d88f78f945 --- /dev/null +++ b/api/server/middleware/limiters/passkeyLimiter.js @@ -0,0 +1,31 @@ +const rateLimit = require('express-rate-limit'); +const { ViolationTypes } = require('librechat-data-provider'); +const { limiterCache, removePorts } = require('@librechat/api'); +const { logViolation } = require('~/cache'); + +const { PASSKEY_WINDOW = 5, PASSKEY_MAX = 20, LOGIN_VIOLATION_SCORE: score } = process.env; +const windowMs = PASSKEY_WINDOW * 60 * 1000; +const max = PASSKEY_MAX; +const windowInMinutes = windowMs / 60000; +const message = `Too many passkey attempts, please try again after ${windowInMinutes} minutes.`; + +const handler = async (req, res) => { + const type = ViolationTypes.LOGINS; + await logViolation(req, res, type, { type, max, windowInMinutes }, score); + return res.status(429).json({ message }); +}; + +/** + * Guards the unauthenticated passkey endpoints. A single sign-in spends two + * requests (options, then verify), so this is deliberately more permissive than + * `loginLimiter` and tracked separately from password attempts. + */ +const passkeyLimiter = rateLimit({ + windowMs, + max, + handler, + keyGenerator: removePorts, + store: limiterCache('passkey_limiter'), +}); + +module.exports = passkeyLimiter; diff --git a/api/server/middleware/limiters/passkeyStepUpLimiter.js b/api/server/middleware/limiters/passkeyStepUpLimiter.js new file mode 100644 index 0000000000..951236ca24 --- /dev/null +++ b/api/server/middleware/limiters/passkeyStepUpLimiter.js @@ -0,0 +1,35 @@ +const rateLimit = require('express-rate-limit'); +const { limiterCache } = require('@librechat/api'); + +const { PASSKEY_STEPUP_WINDOW = 15, PASSKEY_STEPUP_MAX = 20 } = process.env; +const windowMs = PASSKEY_STEPUP_WINDOW * 60 * 1000; +const max = PASSKEY_STEPUP_MAX; +const windowInMinutes = windowMs / 60000; +const message = `Too many passkey confirmation attempts, please try again after ${windowInMinutes} minutes.`; + +/** + * Caps password-confirmed passkey management attempts, covering both enrollment + * and deletion. One shared budget is deliberate: each of those routes verifies + * the account password, so separate budgets would hand an attacker holding a + * stolen token twice the guesses. + * + * Keyed by user id, not by IP: the routes sit behind `requireJwtAuth`, and an + * IP key would let unrelated traffic from a shared NAT exhaust a legitimate + * user's budget. It also gets its own cache namespace so the unauthenticated + * sign-in limiter and these routes never share a bucket. + * + * No violation is logged. A password typo here is not a login attempt, and + * feeding it into the login ban system would let a signed-in user lock + * themselves out of the application. + */ +const passkeyStepUpLimiter = rateLimit({ + windowMs, + max, + handler: (req, res) => res.status(429).json({ message }), + keyGenerator: function (req) { + return req.user?.id; + }, + store: limiterCache('passkey_stepup_limiter'), +}); + +module.exports = passkeyStepUpLimiter; diff --git a/api/server/middleware/limiters/passkeyStepUpLimiter.spec.js b/api/server/middleware/limiters/passkeyStepUpLimiter.spec.js new file mode 100644 index 0000000000..1be600a943 --- /dev/null +++ b/api/server/middleware/limiters/passkeyStepUpLimiter.spec.js @@ -0,0 +1,92 @@ +const express = require('express'); +const request = require('supertest'); + +const originalEnv = process.env; + +const createApp = () => { + jest.resetModules(); + process.env = { + ...originalEnv, + PASSKEY_STEPUP_MAX: '2', + PASSKEY_STEPUP_WINDOW: '15', + }; + + jest.doMock('@librechat/api', () => ({ + limiterCache: jest.fn(() => undefined), + removePorts: (req) => req?.['ip'], + })); + jest.doMock('~/cache', () => ({ + logViolation: jest.fn().mockResolvedValue(undefined), + })); + + const passkeyStepUpLimiter = require('./passkeyStepUpLimiter'); + const { logViolation } = require('~/cache'); + + const app = express(); + app.set('trust proxy', 1); + app.use(express.json()); + app.post( + '/passkey/register/options', + (req, res, next) => { + req.user = { id: req.get('X-Test-User') }; + next(); + }, + passkeyStepUpLimiter, + (req, res) => res.status(204).end(), + ); + + return { app, logViolation }; +}; + +const post = (app, userId, ip) => + request(app) + .post('/passkey/register/options') + .set('X-Test-User', userId) + .set('X-Forwarded-For', ip) + .send({ password: 'secret' }); + +describe('passkeyStepUpLimiter', () => { + afterEach(() => { + jest.dontMock('@librechat/api'); + jest.dontMock('~/cache'); + process.env = originalEnv; + }); + + it('limits one user across rotating source IPs', async () => { + const { app } = createApp(); + + await post(app, 'user-1', '203.0.113.1').expect(204); + await post(app, 'user-1', '203.0.113.2').expect(204); + + const response = await post(app, 'user-1', '203.0.113.3').expect(429); + + expect(response.body).toEqual({ + message: 'Too many passkey confirmation attempts, please try again after 15 minutes.', + }); + }); + + it('keys by user id, so a shared source IP does not exhaust another account', async () => { + const { app } = createApp(); + + await post(app, 'user-a', '198.51.100.1').expect(204); + await post(app, 'user-a', '198.51.100.1').expect(204); + const exhausted = await post(app, 'user-a', '198.51.100.1'); + + const first = await post(app, 'user-b', '198.51.100.1'); + const second = await post(app, 'user-b', '198.51.100.1'); + + expect(exhausted.status).toBe(429); + expect(first.status).toBe(204); + expect(second.status).toBe(204); + }); + + it('does not feed enrollment attempts into the login ban system', async () => { + const { app, logViolation } = createApp(); + + await post(app, 'user-1', '203.0.113.1').expect(204); + await post(app, 'user-1', '203.0.113.1').expect(204); + await post(app, 'user-1', '203.0.113.1').expect(429); + + expect(logViolation).not.toHaveBeenCalled(); + }); +}); diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 8a55fc4f2c..dc38482309 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -259,6 +259,37 @@ describe('GET /api/config', () => { expect(response.body).not.toHaveProperty('interface'); }); + it('keeps passkeys advertised for management when email login is disabled', async () => { + mockGetAppConfig.mockResolvedValue(baseAppConfig); + const previous = { + ALLOW_EMAIL_LOGIN: process.env.ALLOW_EMAIL_LOGIN, + ALLOW_PASSKEY_LOGIN: process.env.ALLOW_PASSKEY_LOGIN, + }; + process.env.ALLOW_EMAIL_LOGIN = 'false'; + process.env.ALLOW_PASSKEY_LOGIN = 'true'; + try { + let isolatedRoute; + jest.isolateModules(() => { + isolatedRoute = require('../config'); + }); + const app = express(); + app.use('/api/config', isolatedRoute); + + const response = await request(app).get('/api/config'); + + expect(response.body.emailLoginEnabled).toBe(false); + expect(response.body.passkeyLoginEnabled).toBe(true); + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + } + }); + it('should include shared env var fields', async () => { mockGetAppConfig.mockResolvedValue(baseAppConfig); process.env.APP_TITLE = 'Test App'; diff --git a/api/server/routes/admin/users.js b/api/server/routes/admin/users.js index b07c222c77..bbad3a3582 100644 --- a/api/server/routes/admin/users.js +++ b/api/server/routes/admin/users.js @@ -39,6 +39,7 @@ const handlers = createAdminUsersHandlers({ invalidateCodeEnvironmentConfigCache, deleteConfig: db.deleteConfig, deleteAclEntries: db.deleteAclEntries, + deletePasskeysByUser: db.deletePasskeysByUser, }); router.use(requireJwtAuth, requireAdminAccess); diff --git a/api/server/routes/auth.2fa-ratelimit.test.js b/api/server/routes/auth.2fa-ratelimit.test.js index be769e7b37..cd496cce33 100644 --- a/api/server/routes/auth.2fa-ratelimit.test.js +++ b/api/server/routes/auth.2fa-ratelimit.test.js @@ -36,6 +36,16 @@ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args), })); +jest.mock('~/server/controllers/auth/PasskeyController', () => ({ + listPasskeys: jest.fn((req, res) => res.status(204).end()), + updatePasskey: jest.fn((req, res) => res.status(204).end()), + removePasskey: jest.fn((req, res) => res.status(204).end()), + authenticatePasskey: jest.fn((req, res, next) => next()), + loginPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyVerify: jest.fn((req, res) => res.status(204).end()), +})); + jest.mock('~/server/controllers/auth/LogoutController', () => ({ logoutController: jest.fn((req, res) => res.status(204).end()), })); @@ -59,6 +69,8 @@ jest.mock('~/server/middleware', () => { logHeaders: pass, requireSameOrigin: pass, loginLimiter: pass, + passkeyLimiter: pass, + passkeyStepUpLimiter: pass, setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args), twoFactorTempLimiter: (...args) => mockTwoFactorTempLimiter(...args), checkBan: (...args) => mockCheckBan(...args), diff --git a/api/server/routes/auth.cloudfront.test.js b/api/server/routes/auth.cloudfront.test.js index e5487096a8..764cb169aa 100644 --- a/api/server/routes/auth.cloudfront.test.js +++ b/api/server/routes/auth.cloudfront.test.js @@ -30,6 +30,16 @@ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: jest.fn((req, res) => res.status(200).end()), })); +jest.mock('~/server/controllers/auth/PasskeyController', () => ({ + listPasskeys: jest.fn((req, res) => res.status(204).end()), + updatePasskey: jest.fn((req, res) => res.status(204).end()), + removePasskey: jest.fn((req, res) => res.status(204).end()), + authenticatePasskey: jest.fn((req, res, next) => next()), + loginPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyVerify: jest.fn((req, res) => res.status(204).end()), +})); + jest.mock('~/server/controllers/auth/LogoutController', () => ({ logoutController: jest.fn((req, res) => res.status(200).end()), })); @@ -53,6 +63,8 @@ jest.mock('~/server/middleware', () => { logHeaders: pass, requireSameOrigin: pass, loginLimiter: pass, + passkeyLimiter: pass, + passkeyStepUpLimiter: pass, setTwoFactorTempUser: pass, twoFactorTempLimiter: pass, checkBan: pass, diff --git a/api/server/routes/auth.cross-site.test.js b/api/server/routes/auth.cross-site.test.js index 0613d66adb..0ed216b372 100644 --- a/api/server/routes/auth.cross-site.test.js +++ b/api/server/routes/auth.cross-site.test.js @@ -38,6 +38,16 @@ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args), })); +jest.mock('~/server/controllers/auth/PasskeyController', () => ({ + listPasskeys: jest.fn((req, res) => res.status(204).end()), + updatePasskey: jest.fn((req, res) => res.status(204).end()), + removePasskey: jest.fn((req, res) => res.status(204).end()), + authenticatePasskey: jest.fn((req, res, next) => next()), + loginPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyVerify: jest.fn((req, res) => res.status(204).end()), +})); + jest.mock('~/server/controllers/auth/LogoutController', () => ({ logoutController: jest.fn((req, res) => res.status(204).end()), })); @@ -61,6 +71,8 @@ jest.mock('~/server/middleware', () => { logHeaders: pass, requireSameOrigin: jest.requireActual('~/server/middleware/requireSameOrigin'), loginLimiter: (...args) => mockLoginLimiter(...args), + passkeyLimiter: pass, + passkeyStepUpLimiter: pass, setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args), twoFactorTempLimiter: pass, checkBan: pass, @@ -126,6 +138,22 @@ describe('local login endpoints reject cross-site submissions', () => { expect(mockLoginController).not.toHaveBeenCalled(); }); + it('rejects a cross-site passkey assertion before verifying it', async () => { + const { authenticatePasskey } = require('~/server/controllers/auth/PasskeyController'); + + await request(app) + .post('/api/auth/passkey/login/verify') + .set('Host', 'chat.example.com') + .set('Sec-Fetch-Site', 'cross-site') + .set('Origin', OTHER_ORIGIN) + .type('form') + .send({ sessionId: 'attacker-session', 'credential[id]': 'attacker-credential' }) + .expect(403); + + expect(authenticatePasskey).not.toHaveBeenCalled(); + expect(mockLoginController).not.toHaveBeenCalled(); + }); + it('rejects a cross-site temp-token 2FA submission before verifying it', async () => { await request(app) .post('/api/auth/2fa/verify-temp') diff --git a/api/server/routes/auth.js b/api/server/routes/auth.js index cd5d0347da..933c2e236c 100644 --- a/api/server/routes/auth.js +++ b/api/server/routes/auth.js @@ -19,6 +19,15 @@ const { enable2FA, verify2FA, } = require('~/server/controllers/TwoFactorController'); +const { + listPasskeys, + updatePasskey, + removePasskey, + authenticatePasskey, + loginPasskeyOptions, + registerPasskeyOptions, + registerPasskeyVerify, +} = require('~/server/controllers/auth/PasskeyController'); const { verify2FAWithTempToken } = require('~/server/controllers/auth/TwoFactorAuthController'); const { logoutController } = require('~/server/controllers/auth/LogoutController'); const { loginController } = require('~/server/controllers/auth/LoginController'); @@ -116,6 +125,47 @@ router.post( regenerateBackupCodes, ); +/* Passkeys (WebAuthn) */ +router.post( + '/passkey/login/options', + middleware.logHeaders, + middleware.passkeyLimiter, + middleware.validateEmailLogin, + middleware.checkBan, + loginPasskeyOptions, +); +router.post( + '/passkey/login/verify', + middleware.logHeaders, + middleware.requireSameOrigin, + middleware.passkeyLimiter, + middleware.validateEmailLogin, + middleware.checkBan, + authenticatePasskey, + setBalanceConfig, + loginController, +); +router.get('/passkey', middleware.requireJwtAuth, listPasskeys); +router.post( + '/passkey/register/options', + middleware.requireJwtAuth, + middleware.passkeyStepUpLimiter, + registerPasskeyOptions, +); +router.post( + '/passkey/register/verify', + middleware.requireJwtAuth, + middleware.passkeyStepUpLimiter, + registerPasskeyVerify, +); +router.patch('/passkey/:passkeyId', middleware.requireJwtAuth, updatePasskey); +router.delete( + '/passkey/:passkeyId', + middleware.requireJwtAuth, + middleware.passkeyStepUpLimiter, + removePasskey, +); + router.get('/graph-token', middleware.requireJwtAuth, graphTokenController); module.exports = router; diff --git a/api/server/routes/auth.reset-password-ratelimit.test.js b/api/server/routes/auth.reset-password-ratelimit.test.js index 74ea8c923c..f8f8ead7d8 100644 --- a/api/server/routes/auth.reset-password-ratelimit.test.js +++ b/api/server/routes/auth.reset-password-ratelimit.test.js @@ -33,6 +33,16 @@ jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({ verify2FAWithTempToken: jest.fn((req, res) => res.status(204).end()), })); +jest.mock('~/server/controllers/auth/PasskeyController', () => ({ + listPasskeys: jest.fn((req, res) => res.status(204).end()), + updatePasskey: jest.fn((req, res) => res.status(204).end()), + removePasskey: jest.fn((req, res) => res.status(204).end()), + authenticatePasskey: jest.fn((req, res, next) => next()), + loginPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyOptions: jest.fn((req, res) => res.status(204).end()), + registerPasskeyVerify: jest.fn((req, res) => res.status(204).end()), +})); + jest.mock('~/server/controllers/auth/LogoutController', () => ({ logoutController: jest.fn((req, res) => res.status(204).end()), })); @@ -56,6 +66,8 @@ jest.mock('~/server/middleware', () => { logHeaders: pass, requireSameOrigin: pass, loginLimiter: pass, + passkeyLimiter: pass, + passkeyStepUpLimiter: pass, setTwoFactorTempUser: pass, twoFactorTempLimiter: pass, checkBan: (...args) => mockCheckBan(...args), diff --git a/api/server/routes/config.js b/api/server/routes/config.js index 7cb97fdef9..7ca103e9af 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -15,8 +15,8 @@ const { isFileSnapshotEnabled, getEndpointsDropParamsMap, resolveCodeEnvironmentDecisionVersion, - resolveCodeEnvironmentMoveCapabilities, - resolveCodeEnvironmentTransitionVersion, + resolveCodeEnvironmentMoveVersion, + isPasskeyEnabled, } = require('@librechat/api'); const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider'); const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas'); @@ -85,6 +85,7 @@ function buildPreLoginPayload() { !!process.env.APPLE_TEAM_ID && !!process.env.APPLE_KEY_ID && !!process.env.APPLE_PRIVATE_KEY_PATH, + passkeyLoginEnabled: isPasskeyEnabled(), openidLoginEnabled: isOpenIdEnabled, openidLabel: process.env.OPENID_BUTTON_LABEL || 'Continue with OpenID', openidImageUrl: process.env.OPENID_IMAGE_URL, diff --git a/api/strategies/jwtStrategy.js b/api/strategies/jwtStrategy.js index d5de52276b..1d5423aa8c 100644 --- a/api/strategies/jwtStrategy.js +++ b/api/strategies/jwtStrategy.js @@ -1,4 +1,4 @@ -const { AGENT_TRIGGER_SCOPE } = require('@librechat/api'); +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'); @@ -48,6 +48,13 @@ 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; diff --git a/api/strategies/jwtStrategy.spec.js b/api/strategies/jwtStrategy.spec.js index da405ecb0c..5764b91eaa 100644 --- a/api/strategies/jwtStrategy.spec.js +++ b/api/strategies/jwtStrategy.spec.js @@ -21,6 +21,8 @@ jest.mock('@librechat/data-schemas', () => ({ jest.mock('@librechat/api', () => ({ AGENT_TRIGGER_SCOPE: 'agent_trigger', + isTokenIssuedBeforeCredentialChange: + jest.requireActual('@librechat/api').isTokenIssuedBeforeCredentialChange, })); jest.mock('~/models', () => ({ @@ -183,4 +185,76 @@ describe('jwtStrategy', () => { '-password -__v -totpSecret -backupCodes +agentTriggerDeletionStartedAt', ); }); + + describe('credentialsChangedAt revocation', () => { + /** Reset landed 500ms into second 1700000010 */ + const credentialsChangedAt = new Date(1700000010500); + + const mockUserWithStamp = (stamp) => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-reset' }, + role: SystemRoles.USER, + credentialsChangedAt: stamp, + }); + }; + + it('rejects an access token issued before the password reset', async () => { + mockUserWithStamp(credentialsChangedAt); + + const { user } = await invokeVerify({ id: 'user-reset', iat: 1700000009 }); + + expect(user).toBe(false); + }); + + it('accepts an access token issued after the password reset', async () => { + mockUserWithStamp(credentialsChangedAt); + + const { user } = await invokeVerify({ id: 'user-reset', iat: 1700000011 }); + + expect(user.id).toBe('user-reset'); + }); + + it('rejects a token whose issuing second started before the reset instant', async () => { + mockUserWithStamp(credentialsChangedAt); + + const { user } = await invokeVerify({ id: 'user-reset', iat: 1700000010 }); + + expect(user).toBe(false); + }); + + it('accepts 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.id).toBe('user-reset'); + }); + + it('accepts a stale token when the user never changed credentials', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-1' }, + role: SystemRoles.USER, + }); + + const { user } = await invokeVerify({ id: 'user-1', iat: 1 }); + + expect(user.id).toBe('user-1'); + }); + + it('rejects a token without iat once credentials have changed', async () => { + mockUserWithStamp(credentialsChangedAt); + + const { user } = await invokeVerify({ id: 'user-reset' }); + + expect(user).toBe(false); + }); + + it('honors a stamp deserialized as a string', async () => { + mockUserWithStamp(credentialsChangedAt.toISOString()); + + const { user } = await invokeVerify({ id: 'user-reset', iat: 1700000009 }); + + expect(user).toBe(false); + }); + }); }); diff --git a/api/strategies/localStrategy.js b/api/strategies/localStrategy.js index df0290a375..95e43a8c0e 100644 --- a/api/strategies/localStrategy.js +++ b/api/strategies/localStrategy.js @@ -2,13 +2,14 @@ const bcrypt = require('bcryptjs'); const { logger } = require('@librechat/data-schemas'); const { errorsToString } = require('librechat-data-provider'); const { Strategy: PassportLocalStrategy } = require('passport-local'); -const { isEnabled, checkEmailConfig, comparePassword } = require('@librechat/api'); +const { + isEnabled, + comparePassword, + grandfatherLegacyEmailVerification, +} = require('@librechat/api'); const { findUser, updateUser } = require('~/models'); const { loginSchema } = require('./validators'); -// Unix timestamp for 2024-06-07 15:20:18 Eastern Time -const verificationEnabledTimestamp = 1717788018; - async function validateLoginRequest(req) { const { error } = loginSchema.safeParse(req.body); return error ? errorsToString(error.errors) : null; @@ -43,17 +44,7 @@ async function passportLogin(req, email, password, done) { return done(null, false, { message: 'Incorrect password.' }); } - const emailEnabled = checkEmailConfig(); - const userCreatedAtTimestamp = Math.floor(new Date(user.createdAt).getTime() / 1000); - - if ( - !emailEnabled && - !user.emailVerified && - userCreatedAtTimestamp < verificationEnabledTimestamp - ) { - await updateUser(user._id, { emailVerified: true }); - user.emailVerified = true; - } + await grandfatherLegacyEmailVerification({ updateUser }, user); const unverifiedAllowed = isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN); if (user.expiresAt && unverifiedAllowed) { diff --git a/api/strategies/openIdJwtStrategy.js b/api/strategies/openIdJwtStrategy.js index 7af8329e59..435edb837c 100644 --- a/api/strategies/openIdJwtStrategy.js +++ b/api/strategies/openIdJwtStrategy.js @@ -18,6 +18,7 @@ const { getHttpsProxyAgent, isAccessTokenJwt, math, + isTokenIssuedBeforeCredentialChange, } = require('@librechat/api'); const { updateUser, findUser, isAgentTriggerPrincipalActive } = require('~/models'); const getLogStores = require('~/cache/getLogStores'); @@ -195,6 +196,14 @@ 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, { diff --git a/api/strategies/openIdJwtStrategy.spec.js b/api/strategies/openIdJwtStrategy.spec.js index dd19c66a4e..a2563533bc 100644 --- a/api/strategies/openIdJwtStrategy.spec.js +++ b/api/strategies/openIdJwtStrategy.spec.js @@ -38,6 +38,8 @@ jest.mock('@librechat/api', () => ({ 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(), @@ -254,6 +256,48 @@ describe('openIdJwtStrategy – token validation', () => { expect(result).toBeTruthy(); expect(findOpenIDUser).toHaveBeenCalled(); }); + + describe('credentialsChangedAt revocation', () => { + /** Reset landed 500ms into second 1700000010 */ + const credentialsChangedAt = new Date(1700000010500); + + const runVerify = async (iat) => { + findOpenIDUser.mockResolvedValue({ + user: { + _id: { toString: () => 'user-abc' }, + role: SystemRoles.USER, + provider: 'openid', + credentialsChangedAt, + }, + error: null, + migration: false, + }); + updateUser.mockResolvedValue({}); + openIdJwtLogin(mockOpenIdConfig); + + const req = { headers: { authorization: 'Bearer tok' }, session: {} }; + return invokeVerify(req, { + sub: 'oidc-123', + email: 'test@example.com', + iss: 'https://issuer.example.com', + exp: 9999999999, + iat, + }); + }; + + it('rejects an OpenID JWT issued before the credential change', async () => { + const { user } = await runVerify(1700000009); + + expect(user).toBe(false); + }); + + it('accepts an OpenID JWT issued after the credential change', async () => { + const { user } = await runVerify(1700000011); + + expect(user).toBeTruthy(); + expect(user.id).toBe('user-abc'); + }); + }); }); describe('openIdJwtStrategy – token source handling', () => { diff --git a/client/package.json b/client/package.json index 925d728bc3..d5eb5240b0 100644 --- a/client/package.json +++ b/client/package.json @@ -59,6 +59,7 @@ "@radix-ui/react-tabs": "^1.1.21", "@radix-ui/react-toast": "^1.2.23", "@react-spring/web": "^9.7.5", + "@simplewebauthn/browser": "^13.3.0", "@tanstack/react-query": "^4.28.0", "@tanstack/react-table": "^8.11.7", "@tanstack/react-virtual": "3.13.23", diff --git a/client/src/components/Auth/AuthLayout.tsx b/client/src/components/Auth/AuthLayout.tsx index 784bb69e8b..25a1360b35 100644 --- a/client/src/components/Auth/AuthLayout.tsx +++ b/client/src/components/Auth/AuthLayout.tsx @@ -113,7 +113,9 @@ function AuthLayout({ )} {children} - {showsSocialLogin && } + {showsSocialLogin && ( + + )} {statesConsentBelowProviders && } diff --git a/client/src/components/Auth/LoginForm.tsx b/client/src/components/Auth/LoginForm.tsx index 2db07d81a7..8a42928650 100644 --- a/client/src/components/Auth/LoginForm.tsx +++ b/client/src/components/Auth/LoginForm.tsx @@ -31,6 +31,11 @@ const LoginForm: React.FC = ({ onSubmit, startupConfig, error, const useUsernameLogin = config?.ldap?.username; const validTheme = isDark(theme) ? 'dark' : 'light'; const requireCaptcha = Boolean(startupConfig.turnstile?.siteKey); + /** The `webauthn` token lets the browser offer a passkey inline in this field's autofill. */ + const baseAutoComplete = useUsernameLogin ? 'username' : 'email'; + const emailAutoComplete = startupConfig.passkeyLoginEnabled + ? `${baseAutoComplete} webauthn` + : baseAutoComplete; const authInputClassName = 'webkit-dark-styles transition-color peer h-auto w-full rounded-2xl border border-border-light bg-surface-primary px-3.5 pb-2.5 pt-3 text-text-primary duration-200 hover:border-border-light focus:border-accent-primary focus-visible:border-accent-primary'; const authSecretInputClassName = `${authInputClassName} pr-12`; @@ -99,7 +104,7 @@ const LoginForm: React.FC = ({ onSubmit, startupConfig, error, + + + ); +} + +export default React.memo(PasskeySignIn); diff --git a/client/src/components/Auth/SocialLoginRender.tsx b/client/src/components/Auth/SocialLoginRender.tsx index 1fbb34131e..24630afd6f 100644 --- a/client/src/components/Auth/SocialLoginRender.tsx +++ b/client/src/components/Auth/SocialLoginRender.tsx @@ -8,13 +8,18 @@ import { AppleIcon, SamlIcon, } from '@librechat/client'; + +import PasskeySignIn from './PasskeySignIn'; import SocialButton from './SocialButton'; import { useLocalize } from '~/hooks'; function SocialLoginRender({ startupConfig, + /** Passkeys sign an existing account in, so they are offered on login only. */ + showPasskey = false, }: { startupConfig: TStartupConfig | null | undefined; + showPasskey?: boolean; }) { const localize = useLocalize(); @@ -114,24 +119,36 @@ function SocialLoginRender({ ), }; + /** The passkey sign-in routes sit behind the email-login gate; management does not. */ + const passkeyEnabled = + showPasskey && + startupConfig.passkeyLoginEnabled === true && + startupConfig.emailLoginEnabled !== false; + const socialEnabled = + startupConfig.socialLoginEnabled === true && (startupConfig.socialLogins?.length ?? 0) > 0; + + if (!passkeyEnabled && !socialEnabled) { + return null; + } + return ( - startupConfig.socialLoginEnabled && ( - <> - {startupConfig.emailLoginEnabled && ( - <> -
-
- {localize('com_auth_or')} -
+ <> + {startupConfig.emailLoginEnabled && ( + <> +
+
+ {localize('com_auth_or')}
-
- - )} -
- {startupConfig.socialLogins?.map((provider) => providerComponents[provider] || null)} -
- - ) +
+
+ + )} +
+ + {socialEnabled && + startupConfig.socialLogins?.map((provider) => providerComponents[provider] || null)} +
+ ); } diff --git a/client/src/components/Auth/__tests__/LoginForm.spec.tsx b/client/src/components/Auth/__tests__/LoginForm.spec.tsx index f1c6e1d54c..93e4b014df 100644 --- a/client/src/components/Auth/__tests__/LoginForm.spec.tsx +++ b/client/src/components/Auth/__tests__/LoginForm.spec.tsx @@ -18,6 +18,7 @@ const mockStartupConfig: TStartupConfig = { githubLoginEnabled: true, googleLoginEnabled: true, openidLoginEnabled: true, + passkeyLoginEnabled: false, appleLoginEnabled: false, openidLabel: 'Test OpenID', openidImageUrl: 'http://test-server.com', diff --git a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx index 81c68fd833..402f9cedd6 100644 --- a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx +++ b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx @@ -17,6 +17,7 @@ const ctx: SettingsContextValue = { isLocalProvider: true, emailEnabled: true, allowEmailChange: true, + passkeyLoginEnabled: false, twoFactorEnabled: false, allowAccountDeletion: true, aboutEnabled: false, diff --git a/client/src/components/Nav/Settings/__tests__/registry.spec.ts b/client/src/components/Nav/Settings/__tests__/registry.spec.ts index dbd4388e5a..84edb5fcee 100644 --- a/client/src/components/Nav/Settings/__tests__/registry.spec.ts +++ b/client/src/components/Nav/Settings/__tests__/registry.spec.ts @@ -19,6 +19,7 @@ const settingsContext: SettingsContextValue = { isLocalProvider: true, emailEnabled: true, allowEmailChange: true, + passkeyLoginEnabled: false, twoFactorEnabled: false, allowAccountDeletion: true, aboutEnabled: false, diff --git a/client/src/components/Nav/Settings/context.tsx b/client/src/components/Nav/Settings/context.tsx index 3f56491db4..6be7e0d49a 100644 --- a/client/src/components/Nav/Settings/context.tsx +++ b/client/src/components/Nav/Settings/context.tsx @@ -33,6 +33,7 @@ export function useSettingsContext(): SettingsContextValue { const isLocalProvider = user?.provider === 'local'; const emailEnabled = startupConfig?.emailEnabled === true; const allowEmailChange = startupConfig?.allowEmailChange === true; + const passkeyLoginEnabled = startupConfig?.passkeyLoginEnabled === true; const twoFactorEnabled = user?.twoFactorEnabled === true; const allowAccountDeletion = startupConfig?.allowAccountDeletion !== false; const aboutEnabled = startupConfig?.interface?.buildInfo !== false; @@ -67,6 +68,7 @@ export function useSettingsContext(): SettingsContextValue { isLocalProvider, emailEnabled, allowEmailChange, + passkeyLoginEnabled, twoFactorEnabled, allowAccountDeletion, aboutEnabled, @@ -89,6 +91,7 @@ export function useSettingsContext(): SettingsContextValue { isLocalProvider, emailEnabled, allowEmailChange, + passkeyLoginEnabled, twoFactorEnabled, allowAccountDeletion, aboutEnabled, diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsx index 4c7aaa7210..df6568e7d8 100644 --- a/client/src/components/Nav/Settings/registry.tsx +++ b/client/src/components/Nav/Settings/registry.tsx @@ -51,6 +51,7 @@ import { TokenCredits, AutoRefill } from './BillingControls'; import AdminPanel from '../SettingsTabs/General/AdminPanel'; import SharedLinks from '../SettingsTabs/Data/SharedLinks'; import ImageResize from '../SettingsTabs/Chat/ImageResize'; +import Passkeys from '../SettingsTabs/Account/Passkeys'; import { showThinkingAtom } from '~/store/showThinking'; import ProviderKeys from '../SettingsTabs/ProviderKeys'; import { autoScrollAtom } from '~/store/autoScroll'; @@ -797,6 +798,15 @@ export const registry: SettingEntry[] = [ show: (ctx) => ctx.isLocalProvider && ctx.twoFactorEnabled, Component: BackupCodesItem, }, + { + id: 'passkeys', + tab: ACCOUNT, + section: 'security', + labelKey: 'com_ui_passkeys', + keywords: ['passkey', 'webauthn', 'fido', 'security key', 'passwordless'], + show: (ctx) => ctx.passkeyLoginEnabled, + Component: Passkeys, + }, // Account · Billing { id: 'tokenCredits', diff --git a/client/src/components/Nav/Settings/types.ts b/client/src/components/Nav/Settings/types.ts index 13263e7179..592df6a86b 100644 --- a/client/src/components/Nav/Settings/types.ts +++ b/client/src/components/Nav/Settings/types.ts @@ -50,6 +50,7 @@ export interface SettingsContextValue { isLocalProvider: boolean; emailEnabled: boolean; allowEmailChange: boolean; + passkeyLoginEnabled: boolean; twoFactorEnabled: boolean; allowAccountDeletion: boolean; aboutEnabled: boolean; diff --git a/client/src/components/Nav/SettingsTabs/Account/Passkeys/PasskeyItem.tsx b/client/src/components/Nav/SettingsTabs/Account/Passkeys/PasskeyItem.tsx new file mode 100644 index 0000000000..d4c43e56fb --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/Passkeys/PasskeyItem.tsx @@ -0,0 +1,326 @@ +import React, { useCallback, useId, useMemo, useRef, useState } from 'react'; +import { Check, Pencil, Trash2, X } from 'lucide-react'; +import { + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, + Button, + Input, + Label, + PasskeyIcon, + SecretInput, + Spinner, + TooltipAnchor, +} from '@librechat/client'; +import type { TPasskey } from 'librechat-data-provider'; +import { useLocalize } from '~/hooks'; + +const MAX_NAME_LENGTH = 60; + +/** Moves focus into the rename field as it mounts, then selects the current label. */ +const focusOnMount = (input: HTMLInputElement | null): void => { + input?.select(); +}; + +const formatDate = (value: string | null): string | null => { + if (value == null || value === '') { + return null; + } + const date = new Date(value); + return Number.isNaN(date.getTime()) ? null : date.toLocaleDateString(); +}; + +/** Restores focus to the rename control after the inline editor unmounts. */ +const returnRenameFocusRef = + (pending: React.MutableRefObject) => + (button: HTMLButtonElement | null): void => { + if (button && pending.current) { + pending.current = false; + button.focus(); + } + }; + +/** Outcome of a removal attempt, so a rejected password lands next to its field. */ +export type PasskeyRemovalResult = 'removed' | 'incorrect-password' | 'failed'; + +type PasskeyItemProps = { + passkey: TPasskey; + isRenaming: boolean; + isBusy: boolean; + /** False for an account with no local password, which cannot be asked for one. */ + requiresPassword: boolean; + onStartRename: (passkeyId: string | null) => void; + onRename: (passkeyId: string, name: string) => void; + onDelete: (passkeyId: string, password: string) => Promise; +}; + +function PasskeyItem({ + passkey, + isRenaming, + isBusy, + requiresPassword, + onStartRename, + onRename, + onDelete, +}: PasskeyItemProps) { + const localize = useLocalize(); + const [draftName, setDraftName] = useState(passkey.name); + const [isConfirming, setIsConfirming] = useState(false); + const [password, setPassword] = useState(''); + const [hasPasswordError, setHasPasswordError] = useState(false); + /** + * The server waives the step-up only for accounts carrying no password hash, which the + * client cannot see. Reveal the field when the server actually asks, so credentials + * from an account that changed providers remain removable. + */ + const [serverDemandedPassword, setServerDemandedPassword] = useState(false); + const showPasswordField = requiresPassword || serverDemandedPassword; + const passwordRef = useRef(null); + const returnFocusToRename = useRef(false); + const rowId = useId(); + const passwordFieldId = `${rowId}-password`; + const passwordErrorId = `${rowId}-password-error`; + + const added = formatDate(passkey.createdAt); + const lastUsed = formatDate(passkey.lastUsedAt); + + const beginRename = useCallback(() => { + setDraftName(passkey.name); + onStartRename(passkey.id); + }, [passkey.id, passkey.name, onStartRename]); + + const cancelRename = useCallback(() => { + setDraftName(passkey.name); + returnFocusToRename.current = true; + onStartRename(null); + }, [passkey.name, onStartRename]); + + const submitRename = useCallback(() => { + const trimmed = draftName.trim(); + if (!trimmed || trimmed === passkey.name) { + cancelRename(); + return; + } + onRename(passkey.id, trimmed); + }, [draftName, passkey.id, passkey.name, onRename, cancelRename]); + + /** Callback ref so the step-up field takes focus as soon as it appears. */ + const bindPasswordField = useCallback((input: HTMLInputElement | null) => { + passwordRef.current = input; + input?.focus(); + }, []); + + const bindRenameButton = useMemo(() => returnRenameFocusRef(returnFocusToRename), []); + + const handleDeleteOpenChange = useCallback((open: boolean) => { + setIsConfirming(open); + setPassword(''); + setHasPasswordError(false); + }, []); + + const handleDeleteOpenAutoFocus = useCallback( + (event: Event) => { + if (!showPasswordField) { + return; + } + event.preventDefault(); + passwordRef.current?.focus(); + }, + [showPasswordField], + ); + + const submitDelete = useCallback( + async (event: React.FormEvent) => { + event.preventDefault(); + setHasPasswordError(false); + const result = await onDelete(passkey.id, password); + if (result === 'removed') { + setPassword(''); + setIsConfirming(false); + return; + } + if (result === 'incorrect-password') { + setHasPasswordError(true); + setServerDemandedPassword(true); + } + /** Put focus back on the field the error describes so it can be corrected. */ + passwordRef.current?.focus(); + }, + [onDelete, passkey.id, password], + ); + + const onRenameKeyDown = useCallback( + (event: React.KeyboardEvent) => { + if (event.key === 'Enter') { + event.preventDefault(); + submitRename(); + } else if (event.key === 'Escape') { + event.preventDefault(); + cancelRename(); + } + }, + [submitRename, cancelRename], + ); + + return ( + +
+ + + + + {isRenaming ? ( +
+ setDraftName(event.target.value)} + onKeyDown={onRenameKeyDown} + aria-label={localize('com_ui_passkey_name')} + className="h-10" + /> + +
+ ) : ( + <> +
+

{passkey.name}

+

+ {added != null && localize('com_ui_passkey_added_on', { date: added })} + {added != null && ' · '} + {lastUsed != null + ? localize('com_ui_passkey_last_used', { date: lastUsed }) + : localize('com_ui_passkey_never_used')} +

+
+ + {passkey.backedUp && ( + + {localize('com_ui_passkey_synced')} + + )} + + +
+ + + + + {localize('com_ui_passkey_remove_confirm', { name: passkey.name })} + + + {localize('com_ui_passkey_remove_description')} + + + +
+ {showPasswordField && ( + <> + + setPassword(event.target.value)} + aria-invalid={hasPasswordError} + aria-describedby={hasPasswordError ? passwordErrorId : undefined} + /> + {hasPasswordError && ( + + )} + + )} + + + + + + + + +
+
+ ); +} + +export default React.memo(PasskeyItem); diff --git a/client/src/components/Nav/SettingsTabs/Account/Passkeys/Passkeys.tsx b/client/src/components/Nav/SettingsTabs/Account/Passkeys/Passkeys.tsx new file mode 100644 index 0000000000..d05b8d5d3a --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/Passkeys/Passkeys.tsx @@ -0,0 +1,330 @@ +import React, { useCallback, useRef, useState } from 'react'; +import { Plus } from 'lucide-react'; +import { AnimatePresence, motion } from 'framer-motion'; +import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider'; +import { + Button, + Label, + OGDialog, + OGDialogClose, + OGDialogContent, + OGDialogDescription, + OGDialogFooter, + OGDialogHeader, + OGDialogTitle, + OGDialogTrigger, + PasskeyIcon, + SecretInput, + Skeleton, + Spinner, + useToastContext, +} from '@librechat/client'; +import type { PasskeyRemovalResult } from './PasskeyItem'; +import { + useDeletePasskeyMutation, + usePasskeysQuery, + useRenamePasskeyMutation, +} from '~/data-provider'; +import { isPasswordRejection, usePasskeyRegistration } from '~/hooks/Auth/usePasskey'; +import { useAuthContext, useLocalize } from '~/hooks'; +import PasskeyItem from './PasskeyItem'; + +const PASSWORD_FIELD_ID = 'passkey-confirm-password'; +const PASSWORD_ERROR_ID = 'passkey-confirm-password-error'; +const PASSWORD_FORM_ID = 'passkey-confirm-password-form'; +const ADD_DIALOG_ID = 'add-passkey-dialog'; + +function Passkeys() { + const localize = useLocalize(); + const { user } = useAuthContext(); + const { showToast } = useToastContext(); + const [isDialogOpen, setDialogOpen] = useState(false); + const [isAddDialogOpen, setAddDialogOpen] = useState(false); + const [renamingId, setRenamingId] = useState(null); + const [pendingId, setPendingId] = useState(null); + const [password, setPassword] = useState(''); + const addButtonRef = useRef(null); + const passwordRef = useRef(null); + const renameAfterCloseRef = useRef(null); + + const { data, isLoading, isError } = usePasskeysQuery({ enabled: isDialogOpen }); + const { registerPasskey, isRegistering, passwordErrorKey, clearPasswordError } = + usePasskeyRegistration(); + const { mutate: renameMutate } = useRenamePasskeyMutation(); + const { mutateAsync: deleteMutate } = useDeletePasskeyMutation(); + + const passkeys = data?.passkeys ?? []; + const atLimit = passkeys.length >= MAX_PASSKEYS_PER_USER; + /** + * Removing a passkey is password-confirmed, but an account provisioned by an + * identity provider has no password to confirm with. The server waives the + * check for those accounts so a credential enrolled before the provider check + * existed stays removable, and the form must not demand one either. Those same + * accounts cannot enroll new credentials, so the panel stays reachable for + * cleanup while the add control is hidden. + */ + const isLocalAccount = user?.provider === 'local'; + + /** Callback ref so the field takes focus the moment the step-up form appears. */ + const bindPasswordField = useCallback((input: HTMLInputElement | null) => { + passwordRef.current = input; + input?.focus(); + }, []); + + const handleAdd = useCallback(() => { + clearPasswordError(); + setPassword(''); + setAddDialogOpen(true); + }, [clearPasswordError]); + + const handleAddOpenChange = useCallback( + (open: boolean) => { + setAddDialogOpen(open); + if (!open) { + setPassword(''); + clearPasswordError(); + } + }, + [clearPasswordError], + ); + + const handleAddCloseAutoFocus = useCallback((event: Event) => { + event.preventDefault(); + const passkeyId = renameAfterCloseRef.current; + renameAfterCloseRef.current = null; + if (passkeyId != null) { + setRenamingId(passkeyId); + return; + } + addButtonRef.current?.focus(); + }, []); + + const handleConfirmAdd = useCallback( + async (event: React.FormEvent) => { + event.preventDefault(); + const passkey = await registerPasskey(password); + if (!passkey) { + /** Put focus back on the field the error describes so it can be corrected. */ + passwordRef.current?.focus(); + return; + } + setPassword(''); + /** Start rename after the child dialog releases its focus trap. */ + renameAfterCloseRef.current = passkey.id; + setAddDialogOpen(false); + }, + [password, registerPasskey], + ); + + const handleRename = useCallback( + (passkeyId: string, name: string) => { + setPendingId(passkeyId); + renameMutate( + { passkeyId, name }, + { + onSuccess: () => setRenamingId(null), + onError: () => + showToast({ message: localize('com_ui_passkey_rename_error'), status: 'error' }), + onSettled: () => setPendingId(null), + }, + ); + }, + [renameMutate, localize, showToast], + ); + + const handleDelete = useCallback( + async (passkeyId: string, password: string): Promise => { + setPendingId(passkeyId); + try { + await deleteMutate({ passkeyId, password: password === '' ? undefined : password }); + showToast({ message: localize('com_ui_passkey_removed') }); + return 'removed'; + } catch (error) { + if (isPasswordRejection(error)) { + return 'incorrect-password'; + } + showToast({ message: localize('com_ui_passkey_remove_error'), status: 'error' }); + return 'failed'; + } finally { + setPendingId(null); + } + }, + [deleteMutate, localize, showToast], + ); + + /** + * Escape, the backdrop and the close button all route through here. The step-up form + * holds the account password, so closing must drop it rather than leave it staged to + * reappear the next time the dialog opens. + */ + const handleOpenChange = useCallback( + (open: boolean) => { + setDialogOpen(open); + if (open) { + return; + } + setPassword(''); + setAddDialogOpen(false); + setRenamingId(null); + renameAfterCloseRef.current = null; + clearPasswordError(); + }, + [clearPasswordError], + ); + + return ( + +
+
+ +
+ + + +
+ + + + +
+ + + + {localize('com_ui_passkeys')} +
+
+ {localize('com_ui_passkeys_description')} +
+ +
+ {isLoading && ( +
+ + +
+ )} + {!isLoading && isError && ( +
+ + + +

{localize('com_ui_passkey_load_error')}

+
+ )} + {!isLoading && !isError && passkeys.length === 0 && ( +
+ + + +

{localize('com_ui_passkey_empty')}

+
+ )} + {!isLoading && passkeys.length > 0 && ( +
    + + {passkeys.map((passkey) => ( + + + + ))} + +
+ )} +
+ + {isLocalAccount && ( +
+ + {atLimit && ( +

+ {localize('com_ui_passkey_limit_reached')} +

+ )} +
+ )} +
+ + + + + {localize('com_ui_passkey_add')} + + {localize('com_ui_passkey_confirm_password_description')} + + + +
+ + setPassword(event.target.value)} + aria-invalid={passwordErrorKey != null} + aria-describedby={passwordErrorKey != null ? PASSWORD_ERROR_ID : undefined} + /> + {passwordErrorKey != null && ( + + )} + + + + + + + +
+
+
+ ); +} + +export default React.memo(Passkeys); diff --git a/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/PasskeyItem.spec.tsx b/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/PasskeyItem.spec.tsx new file mode 100644 index 0000000000..54ad6081ee --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/PasskeyItem.spec.tsx @@ -0,0 +1,180 @@ +import React from 'react'; +import userEvent from '@testing-library/user-event'; +import type { TPasskey } from 'librechat-data-provider'; +import type { PasskeyRemovalResult } from '../PasskeyItem'; +import { fireEvent, render, screen, waitFor } from 'test/layout-test-utils'; +import PasskeyItem from '../PasskeyItem'; + +const passkey: TPasskey = { + id: 'p1', + name: 'Work laptop', + deviceType: 'multiDevice', + backedUp: false, + transports: ['internal'], + createdAt: '2026-01-01T00:00:00.000Z', + lastUsedAt: null, +}; + +type Overrides = { + requiresPassword?: boolean; + onDelete?: jest.Mock>; + isRenaming?: boolean; +}; + +function setup({ requiresPassword = true, onDelete, isRenaming = false }: Overrides = {}) { + const deleteMock = onDelete ?? jest.fn().mockResolvedValue('removed'); + render( + , + ); + return { deleteMock, user: userEvent.setup() }; +} + +const openConfirmation = async (user: ReturnType) => { + const removeButton = screen.getByRole('button', { name: 'Remove passkey' }); + expect(removeButton).toHaveClass('hover:bg-surface-hover'); + expect(removeButton).not.toHaveClass('bg-surface-destructive'); + await user.click(removeButton); + expect(await screen.findByRole('alertdialog', { name: /Remove/ })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Delete' })).toHaveClass('bg-surface-destructive'); +}; + +describe('PasskeyItem rename controls', () => { + it('matches the input height with square save and cancel buttons', () => { + setup({ isRenaming: true }); + const input = screen.getByRole('textbox', { name: 'Passkey name' }); + const saveButton = screen.getByRole('button', { name: 'Save' }); + const cancelButton = screen.getByRole('button', { name: 'Cancel' }); + + expect(input).toHaveClass('h-10'); + expect(input.parentElement?.parentElement).toHaveClass('py-2'); + expect(saveButton).toHaveClass('size-10'); + expect(cancelButton).toHaveClass('size-10'); + expect(cancelButton).toHaveClass('bg-surface-secondary'); + }); + + it.each(['Save', 'Cancel'])('labels the %s control with a tooltip', async (label) => { + setup({ isRenaming: true }); + const button = screen.getByRole('button', { name: label }); + + fireEvent.mouseEnter(button); + fireEvent.mouseMove(button, { screenX: 1 }); + + expect(await screen.findByRole('tooltip', {}, { timeout: 3000 })).toHaveTextContent(label); + }); +}); + +describe('PasskeyItem removal step-up', () => { + it('asks for the password before removing the credential', async () => { + const { deleteMock, user } = setup(); + await openConfirmation(user); + + const field = screen.getByLabelText('Confirm your password'); + expect(field).toHaveAttribute('type', 'password'); + expect(field).toHaveFocus(); + expect(screen.getByRole('button', { name: 'Show secret' })).toBeInTheDocument(); + expect( + screen.queryByText( + 'Removing a passkey takes away a way to sign in, so we need your password first.', + ), + ).not.toBeInTheDocument(); + + await user.type(field, 'correct horse'); + await user.click(screen.getByRole('button', { name: 'Delete' })); + + await waitFor(() => expect(deleteMock).toHaveBeenCalledWith('p1', 'correct horse')); + }); + + it('keeps the delete action unavailable until a password is typed', async () => { + const { deleteMock, user } = setup(); + await openConfirmation(user); + + expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled(); + await user.type(screen.getByLabelText('Confirm your password'), 'x'); + expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled(); + expect(deleteMock).not.toHaveBeenCalled(); + }); + + it('reports a rejected password inline and returns focus to the field', async () => { + const onDelete = jest.fn().mockResolvedValue('incorrect-password'); + const { user } = setup({ onDelete }); + await openConfirmation(user); + + const field = screen.getByLabelText('Confirm your password'); + expect(field).toHaveAttribute('aria-invalid', 'false'); + + await user.type(field, 'wrong'); + await user.click(screen.getByRole('button', { name: 'Delete' })); + + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('Incorrect password. Please try again.'); + expect(field).toHaveAttribute('aria-invalid', 'true'); + expect(field).toHaveAttribute('aria-describedby', alert.id); + await waitFor(() => expect(field).toHaveFocus()); + }); + + it('does not ask an account without a local password for one', async () => { + const { deleteMock, user } = setup({ requiresPassword: false }); + await openConfirmation(user); + + expect(screen.queryByLabelText('Confirm your password')).not.toBeInTheDocument(); + const confirm = screen.getByRole('button', { name: 'Delete' }); + expect(confirm).toBeEnabled(); + + await user.click(confirm); + await waitFor(() => expect(deleteMock).toHaveBeenCalledWith('p1', '')); + }); + + /** + * The waiver is keyed on the password hash server-side, which the client cannot see, + * so an SSO account that kept its old hash is only discovered by being refused. + */ + it('reveals the password field when the server refuses a passwordless removal', async () => { + const deleteMock = jest + .fn, [string, string]>() + .mockResolvedValueOnce('incorrect-password') + .mockResolvedValueOnce('removed'); + const { user } = setup({ requiresPassword: false, onDelete: deleteMock }); + await openConfirmation(user); + + expect(screen.queryByLabelText('Confirm your password')).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Delete' })); + + const field = await screen.findByLabelText('Confirm your password'); + await user.type(field, 'hunter2'); + await user.click(screen.getByRole('button', { name: 'Delete' })); + + await waitFor(() => expect(deleteMock).toHaveBeenLastCalledWith('p1', 'hunter2')); + }); + + it('cancels back to the row and returns focus to the remove control', async () => { + const { deleteMock, user } = setup(); + await openConfirmation(user); + + await user.type(screen.getByLabelText('Confirm your password'), 'typed'); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + + expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(); + expect(deleteMock).not.toHaveBeenCalled(); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Remove passkey' })).toHaveFocus(), + ); + }); + + it('clears a typed password when the confirmation is reopened', async () => { + const { user } = setup(); + await openConfirmation(user); + await user.type(screen.getByLabelText('Confirm your password'), 'typed'); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await openConfirmation(user); + + expect(screen.getByLabelText('Confirm your password')).toHaveValue(''); + }); +}); diff --git a/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/Passkeys.spec.tsx b/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/Passkeys.spec.tsx new file mode 100644 index 0000000000..f868033238 --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/Passkeys/__tests__/Passkeys.spec.tsx @@ -0,0 +1,69 @@ +import React from 'react'; +import userEvent from '@testing-library/user-event'; +import { render, screen, waitFor, within } from '@testing-library/react'; +import Passkeys from '../Passkeys'; + +const mockClearPasswordError = jest.fn(); +const mockRegisterPasskey = jest.fn(); + +jest.mock('~/data-provider', () => ({ + usePasskeysQuery: () => ({ data: { passkeys: [] }, isLoading: false, isError: false }), + useRenamePasskeyMutation: () => ({ mutate: jest.fn() }), + useDeletePasskeyMutation: () => ({ mutateAsync: jest.fn() }), +})); + +jest.mock('~/hooks/Auth/usePasskey', () => ({ + isPasswordRejection: () => false, + usePasskeyRegistration: () => ({ + registerPasskey: mockRegisterPasskey, + isRegistering: false, + passwordErrorKey: null, + clearPasswordError: mockClearPasswordError, + }), +})); + +jest.mock('~/hooks', () => ({ + useAuthContext: () => ({ user: { provider: 'local' } }), + useLocalize: () => (key: string) => + ({ + com_ui_passkeys: 'Passkeys', + com_ui_passkeys_description: 'Passkeys description', + com_ui_manage: 'Manage', + com_ui_passkey_empty: 'No passkeys', + com_ui_passkey_add: 'Add passkey', + com_ui_passkey_confirm_password: 'Confirm your password', + com_ui_passkey_confirm_password_description: 'Confirm before adding a passkey', + com_ui_passkey_limit_reached: 'Passkey limit reached', + com_ui_cancel: 'Cancel', + com_ui_confirm: 'Confirm', + })[key] ?? key, +})); + +describe('Passkeys enrollment dialog', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('opens password confirmation in a separate dialog and restores focus on cancel', async () => { + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole('button', { name: 'Passkeys' })); + const manageDialog = screen.getByRole('dialog', { name: 'Passkeys' }); + const addButton = screen.getByRole('button', { name: 'Add passkey' }); + + await user.click(addButton); + + const addDialog = screen.getByRole('dialog', { name: 'Add passkey' }); + expect(addDialog).not.toBe(manageDialog); + expect(manageDialog).not.toContainElement(addDialog); + expect(within(addDialog).getByLabelText('Confirm your password')).toHaveFocus(); + expect(within(addDialog).getByRole('button', { name: 'Show secret' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + + await waitFor(() => expect(addButton).toHaveFocus()); + expect(screen.queryByRole('dialog', { name: 'Add passkey' })).not.toBeInTheDocument(); + expect(screen.getByRole('dialog', { name: 'Passkeys' })).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Nav/SettingsTabs/Account/Passkeys/index.ts b/client/src/components/Nav/SettingsTabs/Account/Passkeys/index.ts new file mode 100644 index 0000000000..89b11edca2 --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/Passkeys/index.ts @@ -0,0 +1 @@ +export { default } from './Passkeys'; diff --git a/client/src/data-provider/Auth/mutations.ts b/client/src/data-provider/Auth/mutations.ts index 205f028b8a..02a3211fd6 100644 --- a/client/src/data-provider/Auth/mutations.ts +++ b/client/src/data-provider/Auth/mutations.ts @@ -240,3 +240,59 @@ export const useVerifyTwoFactorTempMutation = ( }, ); }; + +/* passkeys */ +export const useRegisterPasskeyMutation = (): UseMutationResult< + t.TPasskeyResponse, + unknown, + t.TVerifyPasskeyRegistrationRequest, + unknown +> => { + const queryClient = useQueryClient(); + return useMutation( + [MutationKeys.registerPasskey], + (payload: t.TVerifyPasskeyRegistrationRequest) => + dataService.verifyPasskeyRegistration(payload), + { + onSuccess: () => { + queryClient.invalidateQueries([QueryKeys.passkeys]); + }, + }, + ); +}; + +export const useRenamePasskeyMutation = (): UseMutationResult< + t.TPasskeyResponse, + unknown, + t.TRenamePasskeyRequest, + unknown +> => { + const queryClient = useQueryClient(); + return useMutation( + [MutationKeys.renamePasskey], + (payload: t.TRenamePasskeyRequest) => dataService.renamePasskey(payload), + { + onSuccess: () => { + queryClient.invalidateQueries([QueryKeys.passkeys]); + }, + }, + ); +}; + +export const useDeletePasskeyMutation = (): UseMutationResult< + { message: string }, + unknown, + t.TDeletePasskeyRequest, + unknown +> => { + const queryClient = useQueryClient(); + return useMutation( + [MutationKeys.deletePasskey], + (payload: t.TDeletePasskeyRequest) => dataService.deletePasskey(payload), + { + onSuccess: () => { + queryClient.invalidateQueries([QueryKeys.passkeys]); + }, + }, + ); +}; diff --git a/client/src/data-provider/Auth/queries.ts b/client/src/data-provider/Auth/queries.ts index f830e95600..d5214ad714 100644 --- a/client/src/data-provider/Auth/queries.ts +++ b/client/src/data-provider/Auth/queries.ts @@ -42,3 +42,16 @@ export const useGraphTokenQuery = ( ...config, }); }; + +export const usePasskeysQuery = ( + config?: UseQueryOptions, +): QueryObserverResult => { + const queriesEnabled = useRecoilValue(store.queriesEnabled); + return useQuery([QueryKeys.passkeys], () => dataService.getPasskeys(), { + refetchOnWindowFocus: false, + refetchOnReconnect: false, + retry: false, + ...config, + enabled: (config?.enabled ?? true) === true && queriesEnabled, + }); +}; diff --git a/client/src/hooks/Auth/__tests__/usePasskey.spec.tsx b/client/src/hooks/Auth/__tests__/usePasskey.spec.tsx new file mode 100644 index 0000000000..447a432c3a --- /dev/null +++ b/client/src/hooks/Auth/__tests__/usePasskey.spec.tsx @@ -0,0 +1,95 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { usePasskeySignIn } from '../usePasskey'; + +type Deferred = { + promise: Promise; + reject: (error: unknown) => void; +}; + +function deferred(): Deferred { + let reject: (error: unknown) => void = () => undefined; + const promise = new Promise((_resolve, rejectPromise) => { + reject = rejectPromise; + }); + return { promise, reject }; +} + +const mockStartAuthentication = jest.fn(); +const mockGetPasskeyLoginOptions = jest.fn(); +const mockVerifyPasskeyLogin = jest.fn(); +const mockShowToast = jest.fn(); +const mockNavigate = jest.fn(); +const mockLocalize = (key: string) => key; +const mockToastContext = { showToast: mockShowToast }; + +jest.mock('@simplewebauthn/browser', () => ({ + startAuthentication: (...args: unknown[]) => mockStartAuthentication(...args), + browserSupportsWebAuthn: () => true, + browserSupportsWebAuthnAutofill: async () => true, +})); + +jest.mock('librechat-data-provider', () => ({ + ...jest.requireActual('librechat-data-provider'), + dataService: { + getPasskeyLoginOptions: (...args: unknown[]) => mockGetPasskeyLoginOptions(...args), + verifyPasskeyLogin: (...args: unknown[]) => mockVerifyPasskeyLogin(...args), + }, +})); + +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useNavigate: () => mockNavigate, +})); + +jest.mock('@librechat/client', () => ({ + useToastContext: () => mockToastContext, +})); + +jest.mock('~/hooks/useLocalize', () => ({ + __esModule: true, + default: () => mockLocalize, +})); + +jest.mock('~/data-provider', () => ({ + useRegisterPasskeyMutation: () => ({ mutateAsync: jest.fn() }), +})); + +describe('usePasskeySignIn', () => { + beforeEach(() => { + jest.clearAllMocks(); + Object.defineProperty(window, 'PublicKeyCredential', { + configurable: true, + value: function PublicKeyCredential() {}, + }); + mockGetPasskeyLoginOptions.mockResolvedValue({ options: {}, sessionId: 'session' }); + }); + + it('keeps the manual ceremony locked when it aborts the pending autofill ceremony', async () => { + const autofill = deferred(); + const manual = deferred(); + mockStartAuthentication.mockImplementation(({ useBrowserAutofill }) => + useBrowserAutofill ? autofill.promise : manual.promise, + ); + + const { result } = renderHook(() => usePasskeySignIn({ enabled: true })); + await waitFor(() => expect(mockStartAuthentication).toHaveBeenCalledTimes(1)); + + act(() => { + void result.current.signIn(); + }); + await waitFor(() => expect(mockStartAuthentication).toHaveBeenCalledTimes(2)); + expect(result.current.isSigningIn).toBe(true); + + await act(async () => { + autofill.reject(Object.assign(new Error('superseded'), { name: 'AbortError' })); + await autofill.promise.catch(() => undefined); + }); + + expect(result.current.isSigningIn).toBe(true); + await act(async () => { + await result.current.signIn(); + }); + expect(mockGetPasskeyLoginOptions).toHaveBeenCalledTimes(2); + expect(mockStartAuthentication).toHaveBeenCalledTimes(2); + }); +}); diff --git a/client/src/hooks/Auth/index.ts b/client/src/hooks/Auth/index.ts new file mode 100644 index 0000000000..d40e5afded --- /dev/null +++ b/client/src/hooks/Auth/index.ts @@ -0,0 +1 @@ +export * from './usePasskey'; diff --git a/client/src/hooks/Auth/usePasskey.ts b/client/src/hooks/Auth/usePasskey.ts new file mode 100644 index 0000000000..34bfa9d16c --- /dev/null +++ b/client/src/hooks/Auth/usePasskey.ts @@ -0,0 +1,282 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { useToastContext } from '@librechat/client'; +import { dataService } from 'librechat-data-provider'; +import type { + TPasskey, + TPasskeyTransport, + TPasskeyAuthenticationResponse, + TPasskeyRegistrationResponse, +} from 'librechat-data-provider'; +import type { + PublicKeyCredentialCreationOptionsJSON, + PublicKeyCredentialRequestOptionsJSON, +} from '@simplewebauthn/browser'; +import type { TranslationKeys } from '~/hooks/useLocalize'; +import { SESSION_KEY, withBasePath, isSafeRedirect, REDIRECT_PARAM } from '~/utils/redirect'; +import { useRegisterPasskeyMutation } from '~/data-provider'; +import useLocalize from '~/hooks/useLocalize'; + +async function loadWebAuthn() { + return import('@simplewebauthn/browser'); +} + +/** Thrown by the browser when the user dismisses or times out the native prompt. */ +const isDismissal = (error: unknown): boolean => { + const name = (error as { name?: string } | null)?.name; + return name === 'NotAllowedError' || name === 'AbortError'; +}; + +/** + * The server answers a rejected step-up with 403 rather than 401, so a mistyped + * password is an inline error instead of a token refresh and a sign-out. + */ +export const isPasswordRejection = (error: unknown): boolean => + (error as { response?: { status?: number } } | null)?.response?.status === 403; + +/** Maps a WebAuthn ceremony failure onto a message the user can act on. */ +const ceremonyErrorKey = (error: unknown): TranslationKeys => { + const name = (error as { name?: string } | null)?.name; + if (name === 'InvalidStateError') { + return 'com_auth_passkey_already_registered'; + } + if (name === 'SecurityError') { + return 'com_auth_passkey_origin_error'; + } + return 'com_auth_passkey_error'; +}; + +/** + * Mirrors the server's `defaultPasskeyName` transport mapping. The chosen label is + * persisted verbatim and rendered back to the user, so it is resolved here where a + * locale is available rather than falling back to the server's English default. + */ +const defaultNameKey = (transports: TPasskeyTransport[] = []): TranslationKeys => { + if (transports.includes('hybrid')) { + return 'com_ui_passkey_default_phone'; + } + if (transports.includes('usb') || transports.includes('nfc')) { + return 'com_ui_passkey_default_security_key'; + } + if (transports.includes('internal')) { + return 'com_ui_passkey_default_this_device'; + } + return 'com_ui_passkey_default_generic'; +}; + +/** Sync capability check without loading the WebAuthn browser package. */ +export const passkeysSupported = (): boolean => + typeof window !== 'undefined' && typeof window.PublicKeyCredential !== 'undefined'; + +/** + * Resolves where to send the user after a successful passkey login. + * Mirrors password-flow sessionStorage + query handling without needing a router. + */ +function resolvePostLoginHref(): string { + try { + const params = new URLSearchParams(window.location.search); + const fromQuery = params.get(REDIRECT_PARAM); + const fromSession = sessionStorage.getItem(SESSION_KEY); + if (fromSession) { + sessionStorage.removeItem(SESSION_KEY); + } + const target = fromQuery ?? fromSession; + if (target && isSafeRedirect(target)) { + return withBasePath(target); + } + } catch { + /* ignore storage / URL access failures */ + } + return withBasePath('/'); +} + +/** + * Drives the passkey sign-in ceremony. + * + * `signIn` runs the modal ceremony from an explicit user action. Separately, if + * the browser supports conditional mediation, an autofill ceremony is started + * once on mount so a passkey is offered inline from the login form's email + * field. + * + * A completed sign-in navigates the whole document so the app boots against the + * new session. The 2FA handoff must not: no refresh cookie exists yet, so a + * remount of `AuthContextProvider` would silent-refresh, find nothing and bounce + * back to login before the code can be entered. That step stays inside the + * router, matching the password flow in `AuthContext`. + */ +export function usePasskeySignIn({ enabled }: { enabled: boolean }) { + const localize = useLocalize(); + const navigate = useNavigate(); + const { showToast } = useToastContext(); + const [isSigningIn, setIsSigningIn] = useState(false); + /** Guards against a second autofill ceremony on React 18 double-invoked effects. */ + const autofillStarted = useRef(false); + /** Re-entry guard for both button sign-in and autofill complete paths. */ + const inFlightRef = useRef(false); + + const complete = useCallback( + async (credential: TPasskeyAuthenticationResponse, sessionId: string) => { + const result = await dataService.verifyPasskeyLogin({ credential, sessionId }); + if (result.twoFAPending === true && result.tempToken != null) { + navigate(`/login/2fa?tempToken=${encodeURIComponent(result.tempToken)}`, { replace: true }); + return; + } + window.location.href = resolvePostLoginHref(); + }, + [navigate], + ); + + const signIn = useCallback(async () => { + if (!enabled || inFlightRef.current) { + return; + } + if (!passkeysSupported()) { + showToast({ message: localize('com_auth_passkey_not_supported'), status: 'error' }); + return; + } + + inFlightRef.current = true; + setIsSigningIn(true); + let navigated = false; + try { + const { startAuthentication, browserSupportsWebAuthn } = await loadWebAuthn(); + if (!browserSupportsWebAuthn()) { + showToast({ message: localize('com_auth_passkey_not_supported'), status: 'error' }); + return; + } + const { options, sessionId } = await dataService.getPasskeyLoginOptions(); + const credential = (await startAuthentication({ + optionsJSON: options as PublicKeyCredentialRequestOptionsJSON, + })) as TPasskeyAuthenticationResponse; + await complete(credential, sessionId); + navigated = true; + // On success we navigate away; keep busy state until unload. + } catch (error) { + if (!isDismissal(error)) { + showToast({ message: localize(ceremonyErrorKey(error)), status: 'error' }); + } + } finally { + if (!navigated) { + inFlightRef.current = false; + setIsSigningIn(false); + } + } + }, [enabled, complete, localize, showToast]); + + useEffect(() => { + if (!enabled || autofillStarted.current) { + return; + } + autofillStarted.current = true; + + let cancelled = false; + const startAutofill = async () => { + try { + const { startAuthentication, browserSupportsWebAuthnAutofill } = await loadWebAuthn(); + if (!(await browserSupportsWebAuthnAutofill())) { + return; + } + const { options, sessionId } = await dataService.getPasskeyLoginOptions(); + const credential = (await startAuthentication({ + optionsJSON: options as PublicKeyCredentialRequestOptionsJSON, + useBrowserAutofill: true, + })) as TPasskeyAuthenticationResponse; + if (cancelled || inFlightRef.current) { + return; + } + inFlightRef.current = true; + setIsSigningIn(true); + try { + await complete(credential, sessionId); + // On success we navigate away; keep busy state until unload. + } catch (error) { + if (!isDismissal(error)) { + showToast({ message: localize(ceremonyErrorKey(error)), status: 'error' }); + } + inFlightRef.current = false; + setIsSigningIn(false); + } + } catch { + /** + * Autofill is a progressive enhancement: a failure leaves the form usable. + * It holds the lock only inside the inner try, which releases it itself, so + * an autofill ceremony superseded by the button must not unlock that one. + */ + } + }; + + void startAutofill(); + return () => { + cancelled = true; + }; + }, [enabled, complete, localize, showToast]); + + return { signIn, isSigningIn }; +} + +/** + * Drives passkey enrollment for the signed-in user. Both server steps require the + * account password, so `registerPasskey` takes it and reports a rejected password + * through `passwordErrorKey` rather than a toast, keeping the error next to the + * field that caused it. + * + * Resolves to the stored credential so callers can put it straight into rename + * mode, or `null` when the ceremony was dismissed or failed. + */ +export function usePasskeyRegistration() { + const localize = useLocalize(); + const { showToast } = useToastContext(); + const [isRegistering, setIsRegistering] = useState(false); + const [passwordErrorKey, setPasswordErrorKey] = useState(null); + const inFlightRef = useRef(false); + const { mutateAsync: verifyRegistration } = useRegisterPasskeyMutation(); + + const clearPasswordError = useCallback(() => setPasswordErrorKey(null), []); + + const registerPasskey = useCallback( + async (password: string): Promise => { + if (inFlightRef.current) { + return null; + } + if (!passkeysSupported()) { + showToast({ message: localize('com_auth_passkey_not_supported'), status: 'error' }); + return null; + } + + inFlightRef.current = true; + setIsRegistering(true); + setPasswordErrorKey(null); + try { + const { startRegistration, browserSupportsWebAuthn } = await loadWebAuthn(); + if (!browserSupportsWebAuthn()) { + showToast({ message: localize('com_auth_passkey_not_supported'), status: 'error' }); + return null; + } + const options = await dataService.getPasskeyRegistrationOptions({ password }); + const credential = (await startRegistration({ + optionsJSON: options as PublicKeyCredentialCreationOptionsJSON, + })) as TPasskeyRegistrationResponse; + const { passkey } = await verifyRegistration({ + credential, + password, + name: localize(defaultNameKey(credential.response?.transports)), + }); + showToast({ message: localize('com_ui_passkey_added'), status: 'success' }); + return passkey; + } catch (error) { + if (isPasswordRejection(error)) { + setPasswordErrorKey('com_ui_passkey_password_incorrect'); + } else if (!isDismissal(error)) { + showToast({ message: localize(ceremonyErrorKey(error)), status: 'error' }); + } + return null; + } finally { + inFlightRef.current = false; + setIsRegistering(false); + } + }, + [verifyRegistration, localize, showToast], + ); + + return { registerPasskey, isRegistering, passwordErrorKey, clearPasswordError }; +} diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.ts index 78edeec7d3..6220c1c2dd 100644 --- a/client/src/hooks/index.ts +++ b/client/src/hooks/index.ts @@ -1,4 +1,5 @@ export * from './Audio'; +export * from './Auth'; export * from './Assistants'; export * from './Agents'; export * from './Chat'; diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 7b39d8b810..59d97a3fd4 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -333,6 +333,11 @@ "com_auth_name_required": "Name is required", "com_auth_no_account": "Don't have an account?", "com_auth_or": "Or", + "com_auth_passkey_already_registered": "This device already has a passkey for your account", + "com_auth_passkey_error": "Passkey sign-in failed. Please try again.", + "com_auth_passkey_login": "Sign in with a passkey", + "com_auth_passkey_not_supported": "This browser does not support passkeys", + "com_auth_passkey_origin_error": "Passkeys are not available on this domain", "com_auth_password": "Password", "com_auth_password_confirm": "Confirm password", "com_auth_password_forgot": "Forgot Password?", @@ -1997,6 +2002,32 @@ "com_ui_output": "Output", "com_ui_page": "Page", "com_ui_parameters": "Parameters", + "com_ui_passkey_add": "Add passkey", + "com_ui_passkey_added": "Passkey added", + "com_ui_passkey_added_on": "Added {{date}}", + "com_ui_passkey_confirm_password": "Confirm your password", + "com_ui_passkey_confirm_password_description": "A passkey signs you in on its own, so we need your password before adding one.", + "com_ui_passkey_default_generic": "Passkey", + "com_ui_passkey_default_phone": "Phone or tablet", + "com_ui_passkey_default_security_key": "Security key", + "com_ui_passkey_default_this_device": "This device", + "com_ui_passkey_empty": "You have not added any passkeys yet", + "com_ui_passkey_last_used": "Last used {{date}}", + "com_ui_passkey_limit_reached": "You have reached the maximum number of passkeys", + "com_ui_passkey_load_error": "Your passkeys could not be loaded, so this list may be incomplete", + "com_ui_passkey_name": "Passkey name", + "com_ui_passkey_never_used": "Never used", + "com_ui_passkey_password_incorrect": "Incorrect password. Please try again.", + "com_ui_passkey_remove": "Remove passkey", + "com_ui_passkey_remove_confirm": "Remove \u201c{{name}}\u201d?", + "com_ui_passkey_remove_description": "This passkey will no longer be available for sign-in.", + "com_ui_passkey_remove_error": "Could not remove the passkey", + "com_ui_passkey_removed": "Passkey removed", + "com_ui_passkey_rename": "Rename passkey", + "com_ui_passkey_rename_error": "Could not rename the passkey", + "com_ui_passkey_synced": "Synced", + "com_ui_passkeys": "Passkeys", + "com_ui_passkeys_description": "Sign in without a password using your device screen lock or a security key.", "com_ui_pasted_text_edit": "Edit pasted text", "com_ui_pasted_text_edit_chip": "Edit pasted text, {{0}}", "com_ui_pasted_text_move_inline": "Move back into message", diff --git a/client/src/utils/__tests__/redirect.test.ts b/client/src/utils/__tests__/redirect.test.ts index f59031f484..4d8e171851 100644 --- a/client/src/utils/__tests__/redirect.test.ts +++ b/client/src/utils/__tests__/redirect.test.ts @@ -2,10 +2,46 @@ import { persistRedirectToSession, getPostLoginRedirect, isSafeRedirect, - hasStoredRedirect, + withBasePath, SESSION_KEY, } from '../redirect'; +describe('withBasePath', () => { + afterEach(() => { + document.querySelector('base')?.remove(); + }); + + const setBaseHref = (href: string) => { + const base = document.createElement('base'); + base.setAttribute('href', href); + document.head.appendChild(base); + }; + + it('returns the path unchanged when no base element is present', () => { + expect(withBasePath('/c/new')).toBe('/c/new'); + }); + + it('returns the path unchanged for a root base href', () => { + setBaseHref('/'); + expect(withBasePath('/c/new')).toBe('/c/new'); + }); + + it('prefixes a subdirectory base href', () => { + setBaseHref('/librechat/'); + expect(withBasePath('/c/new')).toBe('/librechat/c/new'); + }); + + it('prefixes a subdirectory base href without a trailing slash', () => { + setBaseHref('/librechat'); + expect(withBasePath('/')).toBe('/librechat/'); + }); + + it('uses only the pathname of an absolute base href', () => { + setBaseHref('https://example.com/librechat/'); + expect(withBasePath('/login/2fa?tempToken=abc')).toBe('/librechat/login/2fa?tempToken=abc'); + }); +}); + describe('isSafeRedirect', () => { it('accepts a simple relative path', () => { expect(isSafeRedirect('/c/new')).toBe(true); @@ -70,6 +106,35 @@ describe('isSafeRedirect', () => { it('accepts the root path', () => { expect(isSafeRedirect('/')).toBe(true); }); + + /** + * The URL parser strips ASCII tab and newline before resolving, so these clear the + * prefix checks as written but navigate to `//evil.com`. + */ + it('rejects a tab-smuggled protocol-relative URL', () => { + expect(isSafeRedirect(decodeURIComponent('/%09/evil.com'))).toBe(false); + }); + + it('rejects a newline-smuggled protocol-relative URL', () => { + expect(isSafeRedirect(decodeURIComponent('/%0A/evil.com'))).toBe(false); + }); + + it('rejects a carriage-return-smuggled protocol-relative URL', () => { + expect(isSafeRedirect(decodeURIComponent('/%0D/evil.com'))).toBe(false); + }); + + it('rejects a control character anywhere in the path', () => { + expect(isSafeRedirect(decodeURIComponent('/c/new%09x'))).toBe(false); + }); + + /** The login guard reads the raw path, so a target that only normalizes onto /login stays rejected */ + it('rejects a path that reaches /login before normalization', () => { + expect(isSafeRedirect('/login/../c/new')).toBe(false); + }); + + it('accepts a same-origin path containing dot segments', () => { + expect(isSafeRedirect('/c/../dashboard')).toBe(true); + }); }); describe('getPostLoginRedirect', () => { diff --git a/client/src/utils/redirect.ts b/client/src/utils/redirect.ts index f13e61e68e..ceca700521 100644 --- a/client/src/utils/redirect.ts +++ b/client/src/utils/redirect.ts @@ -4,42 +4,46 @@ export const SESSION_KEY = 'post_login_redirect_to'; /** Matches `/login` as a full path segment, with optional basename prefix (e.g. `/librechat/login/2fa`) */ const LOGIN_PATH_RE = /(?:^|\/)login(?:\/|$)/; -/** 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; +/** + * The URL parser removes every ASCII tab and newline before resolving, so a target + * like `/\t/evil.com` would clear the prefix checks below and then resolve to + * `//evil.com`. Reject C0 controls outright rather than trying to match the parser. + */ +function hasControlChar(url: string): boolean { + for (let i = 0; i < url.length; i++) { + if (url.charCodeAt(i) <= 0x1f) { + return true; + } } -}; + return false; +} -export const dropStoredRedirect = (): void => { - try { - sessionStorage.removeItem(SESSION_KEY); - } catch { - // A blocked store holds nothing to drop. +/** Confirms the target resolves to this origin, which is what the browser will actually navigate to */ +function resolvesToSameOrigin(url: string): boolean { + const origin = typeof window === 'undefined' ? undefined : window.location?.origin; + if (origin == null || origin === 'null') { + return false; } -}; - -const writeStoredRedirect = (value: string): void => { try { - sessionStorage.setItem(SESSION_KEY, value); + return new URL(url, origin).origin === origin; } catch { - // The destination cannot cross a document swap in this context; the sign-in continues. + return false; } -}; +} /** 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)) { + return false; + } if (!url.startsWith('/') || url.startsWith('//') || url.includes('\\')) { return false; } const path = url.split('?')[0].split('#')[0]; - return !LOGIN_PATH_RE.test(path); + if (LOGIN_PATH_RE.test(path)) { + return false; + } + return resolvesToSameOrigin(url); } /** Whether a destination is waiting to be consumed; storage that refuses to answer counts as none. */ @@ -66,6 +70,28 @@ export function getPostLoginRedirect(searchParams: URLSearchParams): string | nu return target; } +/** + * Prefixes an app-relative path with the deployment's `` so installs served + * from a subdirectory navigate inside the router instead of to the host root. Reads the + * same source the router uses for its basename, keeping full-page navigations aligned + * with router navigations. + */ +export function withBasePath(path: string): string { + if (typeof document === 'undefined') { + return path; + } + const href = document.querySelector('base')?.getAttribute('href'); + if (href == null || href === '') { + return path; + } + try { + const base = new URL(href, window.location.origin).pathname.replace(/\/+$/, ''); + return base ? `${base}${path}` : path; + } catch { + return path; + } +} + export function persistRedirectToSession(value: string): void { if (isSafeRedirect(value)) { writeStoredRedirect(value); diff --git a/config/delete-user.js b/config/delete-user.js index 333d50d9a7..5c678b8f25 100644 --- a/config/delete-user.js +++ b/config/delete-user.js @@ -18,6 +18,7 @@ const { Balance, Message, Session, + Passkey, AclEntry, ToolCall, Assistant, @@ -216,6 +217,7 @@ async function gracefulExit(code = 0) { PromptGroup.deleteMany({ author: uid }), Preset.deleteMany({ user: uid }), Session.deleteMany({ user: uid }), + Passkey.deleteMany({ user: uid }), SharedLink.deleteMany({ user: uid }), ToolCall.deleteMany({ user: uid }), Token.deleteMany({ userId: uid }), diff --git a/config/reset-password.js b/config/reset-password.js index 4fdc3631a0..548cd8ab45 100644 --- a/config/reset-password.js +++ b/config/reset-password.js @@ -2,7 +2,7 @@ const path = require('path'); const bcrypt = require('bcryptjs'); const readline = require('readline'); const mongoose = require('mongoose'); -const { User } = require('@librechat/data-schemas').createModels(mongoose); +const { User, Passkey, Session } = require('@librechat/data-schemas').createModels(mongoose); require('module-alias')({ base: path.resolve(__dirname, '..', 'api') }); const { askSilentQuestion } = require('./helpers'); const connect = require('./connect'); @@ -59,11 +59,23 @@ const resetPassword = async () => { { email }, { password: hashedPassword, - passwordVersion: Date.now(), // Invalidate old sessions + /** Access tokens minted before this stamp stop verifying */ + credentialsChangedAt: new Date(), }, ); + /** + * A passkey signs in on its own, so leaving one in place would keep an attacker + * logged in after an administrator believes the account has been recovered. + */ + const { deletedCount } = await Passkey.deleteMany({ user: user._id }); + /** A refresh session outlives the stamp: refreshing mints a token issued after it. */ + await Session.deleteMany({ user: user._id }); + console.log('Password successfully reset!'); + if (deletedCount > 0) { + console.log(`Removed ${deletedCount} passkey(s); the user must enroll again.`); + } process.exit(0); } catch (err) { console.error('Error resetting password:', err); diff --git a/e2e/playwright.config.mock.ts b/e2e/playwright.config.mock.ts index 9cda6f98e1..82a72e816f 100644 --- a/e2e/playwright.config.mock.ts +++ b/e2e/playwright.config.mock.ts @@ -108,9 +108,26 @@ const enableDynamicMcp = process.env.E2E_MCP_LIST_CHANGED === 'true'; const baseURL = getE2EBaseURL(); const chromiumChannel = process.env.E2E_CHROMIUM_CHANNEL || undefined; +/** WebAuthn rejects an IP address as the relying party, so passkey ceremonies reach + * the same server through its `localhost` name. */ +const passkeyOrigin = (() => { + const url = new URL(baseURL); + url.hostname = 'localhost'; + return url.origin; +})(); + const vanillaOverrides = { TENANT_ISOLATION_STRICT: 'false', TRUST_TENANT_HEADER: 'true', + ALLOW_PASSKEY_LOGIN: 'true', + /** The password-reset scenario needs the reset routes; CI has no developer `.env`. */ + ALLOW_PASSWORD_RESET: 'true', + PASSKEY_RP_ID: 'localhost', + PASSKEY_ORIGINS: passkeyOrigin, + /** Every project reruns the reset and passkey sign-in scenarios from one IP, and each + * login page load spends a passkey request on autofill; the defaults allow 2 and 20. */ + RESET_PASSWORD_MAX: '100', + PASSKEY_MAX: '500', OPENAI_API_KEY: 'user_provided', OPENID_CLIENT_ID: '', OPENID_ISSUER: '', diff --git a/e2e/specs/mock/db.ts b/e2e/specs/mock/db.ts index 66cb5c9362..ddf3819a9b 100644 --- a/e2e/specs/mock/db.ts +++ b/e2e/specs/mock/db.ts @@ -1,6 +1,6 @@ import fs from 'fs'; import path from 'path'; -import { MongoClient } from 'mongodb'; +import { MongoClient, ObjectId } from 'mongodb'; import type { Db } from 'mongodb'; const DEFAULT_MONGO_URI = 'mongodb://127.0.0.1:27017/LibreChat-e2e'; @@ -136,3 +136,66 @@ export async function clearUserConversations(userEmail: string): Promise { await db.collection('conversations').deleteMany({ user: userId }); }); } + +export async function seedPasskey( + userEmail: string, + credentialId: string, + name: string, +): Promise { + await withMongo(async (db) => { + const userId = new ObjectId(await resolveUserId(db, userEmail)); + const now = new Date(); + await db.collection('passkeys').insertOne({ + user: userId, + credentialId, + publicKey: Buffer.from('e2e-passkey-public-key'), + counter: 0, + transports: ['internal'], + deviceType: 'singleDevice', + backedUp: false, + name, + lastUsedAt: null, + createdAt: now, + updatedAt: now, + __v: 0, + }); + }); +} + +export async function clearUserPasskeys(userEmail: string): Promise { + await withMongo(async (db) => { + const userId = new ObjectId(await resolveUserId(db, userEmail)); + await db.collection('passkeys').deleteMany({ user: userId }); + }); +} + +export async function countUserPasskeys(userId: string): Promise { + return withMongo((db) => + db.collection('passkeys').countDocuments({ user: new ObjectId(userId) }), + ); +} + +export async function enableTwoFactorFlag(userEmail: string): Promise { + await withMongo(async (db) => { + await db + .collection('users') + .updateOne({ email: userEmail }, { $set: { twoFactorEnabled: true } }); + }); +} + +/** Removes a throwaway user and the records the passkey scenarios create for it. */ +export async function deleteUserByEmail(userEmail: string): Promise { + await withMongo(async (db) => { + const user = await db.collection('users').findOne({ email: userEmail }); + if (!user) { + return; + } + await Promise.all([ + db.collection('passkeys').deleteMany({ user: user._id }), + db.collection('sessions').deleteMany({ user: user._id }), + db.collection('balances').deleteMany({ user: user._id }), + db.collection('tokens').deleteMany({ userId: user._id }), + ]); + await db.collection('users').deleteOne({ _id: user._id }); + }); +} diff --git a/e2e/specs/mock/passkeys.spec.ts b/e2e/specs/mock/passkeys.spec.ts new file mode 100644 index 0000000000..2e5bb662ae --- /dev/null +++ b/e2e/specs/mock/passkeys.spec.ts @@ -0,0 +1,146 @@ +import { expect, test } from '@playwright/test'; +import type { Response } from '@playwright/test'; +import { getPrimaryE2EUser } from '../../setup/users.mock'; +import { clearUserPasskeys, seedPasskey } from './db'; +import { NEW_CHAT_PATH } from './helpers'; + +const PASSKEY_NAME = 'Work laptop'; +const RENAMED_PASSKEY_NAME = 'Office security key'; +const CREDENTIAL_ID = 'e2e-passkey-settings-flow'; + +const responseMatches = (method: string) => (response: Response) => + response.request().method() === method && + new URL(response.url()).pathname.startsWith('/api/auth/passkey/'); + +test.describe('account settings passkeys', () => { + const user = getPrimaryE2EUser(); + + test.beforeEach(async () => { + await clearUserPasskeys(user.email); + await seedPasskey(user.email, CREDENTIAL_ID, PASSKEY_NAME); + }); + + test.afterEach(async () => { + await clearUserPasskeys(user.email); + }); + + test('keeps add and delete dialogs separate, accessible, and correctly layered', async ({ + page, + }) => { + test.setTimeout(60000); + + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + + const settingsDialog = page.getByRole('dialog', { name: /Settings/ }); + await settingsDialog.getByRole('tab', { name: 'Account' }).click(); + await settingsDialog.getByRole('button', { name: 'Passkeys', exact: true }).click(); + + const passkeysDialog = page.getByRole('dialog', { name: 'Passkeys', exact: true }); + await expect(passkeysDialog).toBeVisible(); + await expect(passkeysDialog.getByText(PASSKEY_NAME, { exact: true })).toBeVisible(); + + const addButton = passkeysDialog.getByRole('button', { name: 'Add passkey' }); + await addButton.click(); + + const addDialog = page.getByRole('dialog', { name: 'Add passkey', exact: true }); + const addPassword = addDialog.getByLabel('Confirm your password'); + await expect(addDialog).toBeVisible(); + expect( + await addDialog.evaluate( + (dialog) => dialog.parentElement?.closest('[role="dialog"]') == null, + ), + ).toBe(true); + await expect(addPassword).toBeFocused(); + await expect(addDialog.getByRole('button', { name: 'Show secret' })).toBeVisible(); + + await addDialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(addDialog).toBeHidden(); + await expect(addButton).toBeFocused(); + + const passkeyItem = passkeysDialog.getByTestId('passkey-item'); + const compactRowBox = await passkeyItem.boundingBox(); + expect(compactRowBox).not.toBeNull(); + expect(compactRowBox?.height).toBeLessThanOrEqual(60); + + const renameButton = passkeysDialog.getByRole('button', { name: 'Rename passkey' }); + await renameButton.click(); + + const nameInput = passkeysDialog.getByRole('textbox', { name: 'Passkey name' }); + const saveButton = passkeysDialog.getByRole('button', { name: 'Save' }); + const cancelButton = passkeysDialog.getByRole('button', { name: 'Cancel' }); + for (const control of [nameInput, saveButton, cancelButton]) { + const box = await control.boundingBox(); + expect(box).not.toBeNull(); + expect(box?.height).toBe(40); + } + expect((await saveButton.boundingBox())?.width).toBe(40); + expect((await cancelButton.boundingBox())?.width).toBe(40); + + await saveButton.hover(); + await expect(page.getByRole('tooltip', { name: 'Save' })).toBeVisible(); + await cancelButton.hover(); + await expect(page.getByRole('tooltip', { name: 'Cancel' })).toBeVisible(); + + await cancelButton.click(); + await expect(renameButton).toBeFocused(); + await expect(passkeysDialog.getByText(PASSKEY_NAME, { exact: true })).toBeVisible(); + + await renameButton.click(); + await nameInput.fill(RENAMED_PASSKEY_NAME); + const renameResponsePromise = page.waitForResponse(responseMatches('PATCH')); + await saveButton.click(); + expect((await renameResponsePromise).status()).toBe(200); + await expect(passkeysDialog.getByText(RENAMED_PASSKEY_NAME, { exact: true })).toBeVisible(); + + const passkeysZIndex = await passkeysDialog.evaluate((element) => + Number.parseInt(getComputedStyle(element).zIndex, 10), + ); + const removeButton = passkeysDialog.getByRole('button', { name: 'Remove passkey' }); + await removeButton.hover(); + await expect(page.getByRole('tooltip', { name: 'Remove passkey' })).toBeVisible(); + await removeButton.click(); + + const deleteDialog = page.getByRole('alertdialog', { + name: `Remove “${RENAMED_PASSKEY_NAME}”?`, + }); + const deletePassword = deleteDialog.getByLabel('Confirm your password'); + const deleteButton = deleteDialog.getByRole('button', { name: 'Delete' }); + await expect(deleteDialog).toBeVisible(); + await expect(deletePassword).toBeFocused(); + await expect(deleteDialog.getByRole('button', { name: 'Show secret' })).toBeVisible(); + await expect( + deleteDialog.getByText( + 'Removing a passkey takes away a way to sign in, so we need your password first.', + ), + ).toHaveCount(0); + await expect(deleteButton).toHaveClass(/bg-surface-destructive/); + + const deleteZIndex = await deleteDialog.evaluate((element) => + Number.parseInt(getComputedStyle(element).zIndex, 10), + ); + const deletePortalZIndex = await deleteDialog.evaluate((element) => + Number.parseInt(getComputedStyle(element.parentElement as HTMLElement).zIndex, 10), + ); + expect(deleteZIndex).toBeGreaterThan(passkeysZIndex); + expect(deletePortalZIndex).toBeGreaterThan(passkeysZIndex); + + await deletePassword.fill('wrong password'); + const rejectedDeletePromise = page.waitForResponse(responseMatches('DELETE')); + await deleteButton.click(); + expect((await rejectedDeletePromise).status()).toBe(403); + await expect(deleteDialog.getByRole('alert')).toHaveText( + 'Incorrect password. Please try again.', + ); + await expect(deletePassword).toBeFocused(); + + await deletePassword.fill(user.password); + const successfulDeletePromise = page.waitForResponse(responseMatches('DELETE')); + await deleteButton.click(); + expect((await successfulDeletePromise).status()).toBe(200); + await expect(deleteDialog).toBeHidden(); + await expect(passkeysDialog.getByTestId('passkey-item')).toHaveCount(0); + await expect(passkeysDialog.getByText('You have not added any passkeys yet')).toBeVisible(); + }); +}); diff --git a/e2e/specs/mock/scenarios/passkeys.spec.ts b/e2e/specs/mock/scenarios/passkeys.spec.ts new file mode 100644 index 0000000000..304affc772 --- /dev/null +++ b/e2e/specs/mock/scenarios/passkeys.spec.ts @@ -0,0 +1,426 @@ +import { randomUUID } from 'crypto'; +import { expect, test } from '@playwright/test'; +import type { + APIRequestContext, + Browser, + BrowserContext, + CDPSession, + Page, +} from '@playwright/test'; +import { seedPasskey, deleteUserByEmail, countUserPasskeys, enableTwoFactorFlag } from '../db'; +import { NEW_CHAT_PATH } from '../helpers'; + +/** + * Passkey sign-in and management, driven through a real WebAuthn ceremony: Chromium's + * virtual authenticator stands in for the platform authenticator, so the browser + * creates and signs with an actual credential that the server verifies. + * + * Every scenario uses its own throwaway account. Passkeys, password resets and account + * deletion all change credentials, and the shared e2e user must stay usable for the + * rest of the suite. + */ + +const PASSWORD = 'passkey-e2e-password-1'; +const DESKTOP = { width: 1280, height: 800 }; + +type FreshUser = { email: string; name: string; password: string; id: string; token: string }; + +type VirtualAuthenticator = { + cdp: CDPSession; + authenticatorId: string; + credentialCount: () => Promise; +}; + +/** Same server under its `localhost` name: WebAuthn refuses an IP address as the RP ID. */ +function passkeyBaseURL(baseURL: string | undefined): string { + const url = new URL(baseURL as string); + url.hostname = 'localhost'; + return url.origin; +} + +async function createFreshUser(request: APIRequestContext): Promise { + const email = `passkey-${randomUUID().slice(0, 8)}@example.com`; + const name = 'Passkey Scenario'; + const register = await request.post('/api/auth/register', { + data: { email, name, password: PASSWORD, confirm_password: PASSWORD }, + }); + expect(register.ok()).toBeTruthy(); + const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } }); + expect(login.ok()).toBeTruthy(); + const body = (await login.json()) as { token: string; user: { _id: string; id?: string } }; + return { email, name, password: PASSWORD, id: body.user.id ?? body.user._id, token: body.token }; +} + +async function openContextFor( + browser: Browser, + request: APIRequestContext, + baseURL: string, +): Promise { + const context = await browser.newContext({ + storageState: await request.storageState(), + baseURL, + viewport: DESKTOP, + }); + await context.addInitScript(() => { + localStorage.setItem('navVisible', 'true'); + }); + return context; +} + +async function addVirtualAuthenticator(page: Page): Promise { + const cdp = await page.context().newCDPSession(page); + await cdp.send('WebAuthn.enable'); + const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { + options: { + protocol: 'ctap2', + transport: 'internal', + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + automaticPresenceSimulation: true, + }, + }); + const credentialCount = async () => + (await cdp.send('WebAuthn.getCredentials', { authenticatorId })).credentials.length; + return { cdp, authenticatorId, credentialCount }; +} + +async function openPasskeysDialog(page: Page) { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + const settingsDialog = page.getByRole('dialog', { name: /Settings/ }); + await settingsDialog.getByRole('tab', { name: 'Account' }).click(); + await settingsDialog.getByRole('button', { name: 'Passkeys', exact: true }).click(); + const passkeysDialog = page.getByRole('dialog', { name: 'Passkeys', exact: true }); + await expect(passkeysDialog).toBeVisible(); + return passkeysDialog; +} + +async function submitAddPasskey(page: Page, password: string) { + const passkeysDialog = await openPasskeysDialog(page); + await passkeysDialog.getByRole('button', { name: 'Add passkey' }).click(); + const addDialog = page.getByRole('dialog', { name: 'Add passkey', exact: true }); + await addDialog.getByLabel('Confirm your password').fill(password); + await addDialog.getByRole('button', { name: 'Confirm' }).click(); + return { passkeysDialog, addDialog }; +} + +async function addPasskey(page: Page, password: string) { + const { passkeysDialog, addDialog } = await submitAddPasskey(page, password); + await expect(addDialog).toBeHidden(); + await expect(passkeysDialog.getByTestId('passkey-item')).toHaveCount(1); + /** A new passkey opens in rename mode, prefilled with a name derived from its transport. */ + const nameInput = passkeysDialog.getByRole('textbox', { name: 'Passkey name' }); + await expect(nameInput).toHaveValue('This device'); + await passkeysDialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(passkeysDialog.getByText('This device', { exact: true })).toBeVisible(); + return passkeysDialog; +} + +/** Nested dialogs close one per Escape, each after its exit animation. */ +async function closeDialogs(page: Page) { + const dialogs = page.getByRole('dialog'); + await expect(async () => { + if ((await dialogs.count()) > 0) { + await page.keyboard.press('Escape'); + } + await expect(dialogs).toHaveCount(0, { timeout: 1000 }); + }).toPass({ timeout: 15000 }); +} + +async function logOut(page: Page) { + await closeDialogs(page); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Log out' }).click(); + await expect(page).toHaveURL(/\/login/); +} + +/** + * The login page starts a conditional-mediation (autofill) ceremony on load, and + * Chromium's virtual authenticator answers it without a prompt, so sign-in can finish + * before the button is pressed. Pressing it otherwise starts the modal ceremony. The + * outcome the user sees is the same either way, and that is what the scenarios assert. + */ +async function signInWithPasskey(page: Page) { + const leftLogin = page + .waitForURL((url) => !url.pathname.endsWith('/login'), { timeout: 15000 }) + .catch(() => undefined); + const pressed = page + .getByRole('button', { name: 'Sign in with a passkey' }) + .click({ timeout: 15000 }) + .catch(() => undefined); + await Promise.race([leftLogin, pressed]); +} + +test.describe('passkeys', () => { + test.skip(({ browserName }) => browserName !== 'chromium', 'virtual authenticator is CDP-only'); + + let user: FreshUser | undefined; + let context: BrowserContext | undefined; + + test.afterEach(async () => { + await context?.close(); + context = undefined; + if (user) { + await deleteUserByEmail(user.email); + user = undefined; + } + }); + + test('a passkey added with the account password signs the user in @scenario:passkey-added-with-password-signs-in', 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(); + const authenticator = await addVirtualAuthenticator(page); + + await addPasskey(page, user.password); + expect(await authenticator.credentialCount()).toBe(1); + expect(await countUserPasskeys(user.id)).toBe(1); + + await logOut(page); + await signInWithPasskey(page); + + await expect(page).toHaveURL(/\/c\//, { timeout: 15000 }); + await expect(page.getByTestId('nav-user')).toBeVisible(); + }); + + test('a wrong password refuses to add a passkey @scenario:passkey-add-refused-with-wrong-password', async ({ + browser, + playwright, + baseURL, + }) => { + test.setTimeout(60000); + 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(); + const authenticator = await addVirtualAuthenticator(page); + + const { passkeysDialog, addDialog } = await submitAddPasskey(page, 'not-the-password'); + + await expect(addDialog.getByRole('alert')).toHaveText('Incorrect password. Please try again.'); + await expect(addDialog.getByLabel('Confirm your password')).toBeFocused(); + await addDialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(passkeysDialog.getByTestId('passkey-item')).toHaveCount(0); + expect(await authenticator.credentialCount()).toBe(0); + expect(await countUserPasskeys(user.id)).toBe(0); + }); + + test('a removed passkey no longer signs in @scenario:removed-passkey-no-longer-signs-in', 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(); + const authenticator = await addVirtualAuthenticator(page); + + const passkeysDialog = await addPasskey(page, user.password); + await passkeysDialog.getByRole('button', { name: 'Remove passkey' }).click(); + const deleteDialog = page.getByRole('alertdialog'); + await deleteDialog.getByLabel('Confirm your password').fill(user.password); + await deleteDialog.getByRole('button', { name: 'Delete' }).click(); + await expect(deleteDialog).toBeHidden(); + await expect(passkeysDialog.getByText('You have not added any passkeys yet')).toBeVisible(); + /** The authenticator still holds the credential; only the server forgot it. */ + expect(await authenticator.credentialCount()).toBe(1); + + await logOut(page); + await signInWithPasskey(page); + + /** Both the autofill and the button ceremony are refused, so the toast can appear twice. */ + await expect(page.getByText('Passkey sign-in failed. Please try again.').first()).toBeVisible(); + await expect(page).toHaveURL(/\/login/); + }); + + test('a renamed passkey keeps its name after a reload @scenario:renamed-passkey-keeps-its-name-after-reload', async ({ + browser, + playwright, + baseURL, + }) => { + test.setTimeout(60000); + const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) }); + user = await createFreshUser(request); + context = await openContextFor(browser, request, passkeyBaseURL(baseURL)); + await request.dispose(); + await seedPasskey(user.email, `e2e-rename-${randomUUID()}`, 'Old name'); + const page = await context.newPage(); + + let passkeysDialog = await openPasskeysDialog(page); + await passkeysDialog.getByRole('button', { name: 'Rename passkey' }).click(); + await passkeysDialog.getByRole('textbox', { name: 'Passkey name' }).fill('Clé de voyage'); + await passkeysDialog.getByRole('textbox', { name: 'Passkey name' }).press('Enter'); + await expect(passkeysDialog.getByText('Clé de voyage', { exact: true })).toBeVisible(); + + await page.reload({ timeout: 10000 }); + passkeysDialog = await openPasskeysDialog(page); + await expect(passkeysDialog.getByText('Clé de voyage', { exact: true })).toBeVisible(); + await expect(passkeysDialog.getByText('Old name', { exact: true })).toHaveCount(0); + }); + + test('passkey sign-in is offered on the login page only @scenario:passkey-sign-in-offered-only-on-login', async ({ + browser, + baseURL, + }) => { + context = await browser.newContext({ baseURL, storageState: { cookies: [], origins: [] } }); + const page = await context.newPage(); + + await page.goto('/login', { timeout: 10000 }); + await expect(page.getByRole('button', { name: 'Sign in with a passkey' })).toBeVisible(); + + await page.goto('/register', { timeout: 10000 }); + await expect(page.getByLabel('Full name')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Sign in with a passkey' })).toHaveCount(0); + }); + + test('passkey controls disappear when the deployment turns passkeys off @scenario:passkey-controls-hidden-when-disabled', async ({ + browser, + playwright, + baseURL, + }) => { + test.setTimeout(60000); + const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) }); + user = await createFreshUser(request); + context = await openContextFor(browser, request, passkeyBaseURL(baseURL)); + await request.dispose(); + await context.route('**/api/config', async (route) => { + const response = await route.fetch(); + const config = await response.json(); + await route.fulfill({ response, json: { ...config, passkeyLoginEnabled: false } }); + }); + const page = await context.newPage(); + + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + const settingsDialog = page.getByRole('dialog', { name: /Settings/ }); + await settingsDialog.getByRole('tab', { name: 'Account' }).click(); + await expect(settingsDialog.getByRole('tabpanel')).toBeVisible(); + await expect(settingsDialog.getByRole('button', { name: 'Passkeys', exact: true })).toHaveCount( + 0, + ); + + await logOut(page); + await expect(page.getByTestId('login-button')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Sign in with a passkey' })).toHaveCount(0); + }); + + test('with email login off, passkey sign-in is hidden but management stays @scenario:passkey-management-stays-when-email-login-off', async ({ + browser, + playwright, + baseURL, + }) => { + test.setTimeout(60000); + const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) }); + user = await createFreshUser(request); + context = await openContextFor(browser, request, passkeyBaseURL(baseURL)); + await request.dispose(); + await seedPasskey(user.email, `e2e-email-off-${randomUUID()}`, 'Office key'); + await context.route('**/api/config', async (route) => { + const response = await route.fetch(); + const config = await response.json(); + await route.fulfill({ response, json: { ...config, emailLoginEnabled: false } }); + }); + const page = await context.newPage(); + + const passkeysDialog = await openPasskeysDialog(page); + await expect(passkeysDialog.getByText('Office key', { exact: true })).toBeVisible(); + + await logOut(page); + await expect(page.getByRole('button', { name: 'Sign in with a passkey' })).toHaveCount(0); + }); + + test('a passkey sign-in on a 2FA account asks for the second factor @scenario:passkey-sign-in-hands-off-to-2fa', 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 enableTwoFactorFlag(user.email); + await logOut(page); + await signInWithPasskey(page); + + await expect(page).toHaveURL(/\/login\/2fa\?tempToken=/, { timeout: 15000 }); + await expect( + page.getByText('Check your preferred one-time password application for a 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, + }) => { + const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) }); + try { + user = await createFreshUser(request); + await seedPasskey(user.email, `e2e-reset-${randomUUID()}`, 'Laptop'); + const authorized = { Authorization: `Bearer ${user.token}` }; + expect((await request.get('/api/user', { headers: authorized })).status()).toBe(200); + + const resetRequest = await request.post('/api/auth/requestPasswordReset', { + data: { email: user.email }, + }); + expect(resetRequest.ok()).toBeTruthy(); + const { link } = (await resetRequest.json()) as { link?: string }; + expect(link).toBeTruthy(); + const resetUrl = new URL(link as string); + const newPassword = 'passkey-e2e-password-2'; + const reset = await request.post('/api/auth/resetPassword', { + data: { + userId: resetUrl.searchParams.get('userId'), + token: resetUrl.searchParams.get('token'), + password: newPassword, + confirm_password: newPassword, + }, + }); + expect(reset.ok()).toBeTruthy(); + + expect((await request.get('/api/user', { headers: authorized })).status()).toBe(401); + expect(await countUserPasskeys(user.id)).toBe(0); + } finally { + await request.dispose(); + } + }); + + test('deleting the account removes its passkeys @scenario:account-deletion-removes-passkeys', async ({ + playwright, + baseURL, + }) => { + const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) }); + try { + user = await createFreshUser(request); + await seedPasskey(user.email, `e2e-delete-${randomUUID()}`, 'Phone'); + expect(await countUserPasskeys(user.id)).toBe(1); + + const deletion = await request.delete('/api/user/delete', { + headers: { Authorization: `Bearer ${user.token}` }, + }); + expect(deletion.ok()).toBeTruthy(); + expect(await countUserPasskeys(user.id)).toBe(0); + } finally { + await request.dispose(); + } + }); +}); diff --git a/package-lock.json b/package-lock.json index c6fca8874b..62ffbeaa1a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -889,6 +889,7 @@ "@radix-ui/react-tabs": "^1.1.21", "@radix-ui/react-toast": "^1.2.23", "@react-spring/web": "^9.7.5", + "@simplewebauthn/browser": "^13.3.0", "@tanstack/react-query": "^4.28.0", "@tanstack/react-table": "^8.11.7", "@tanstack/react-virtual": "3.13.23", @@ -6854,6 +6855,12 @@ "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, + "node_modules/@hexagon/base64": { + "version": "1.1.28", + "resolved": "https://registry.npmjs.org/@hexagon/base64/-/base64-1.1.28.tgz", + "integrity": "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==", + "license": "MIT" + }, "node_modules/@hono/node-server": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz", @@ -9136,6 +9143,12 @@ "@opentelemetry/api": "^1.9.0" } }, + "node_modules/@levischuck/tiny-cbor": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/@levischuck/tiny-cbor/-/tiny-cbor-0.2.11.tgz", + "integrity": "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==", + "license": "MIT" + }, "node_modules/@lezer/common": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.2.1.tgz", @@ -11640,6 +11653,207 @@ "third-party-web": "latest" } }, + "node_modules/@peculiar/asn1-android": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-android/-/asn1-android-2.9.5.tgz", + "integrity": "sha512-KnNE4l033gbJ3ZzfYk7fJpSZwhd5xT+dPAnrB8bcwqylHiLN2zjZ0OyFao0LDIOI/ZdXRabV0n3Ww/KvpgZq6w==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-cms": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.5.tgz", + "integrity": "sha512-4Ivz0fsyFofe0bslNsYcGN9+iETdHX4v+BFwIPr+K/BAt61sHXECP63ff9FntU9zcfVQELJFdUG9so44OjUlBQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "@peculiar/asn1-x509-attr": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-csr": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.5.tgz", + "integrity": "sha512-9dO6PcoJeI+1xJ4rG7eINMa6f9Ix/QdRs5UGZ0D7v/R3TzmsbVr5cqAgfYw4xgS9U54ouHYqEz0bIZBbM/UY1g==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-ecc": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.5.tgz", + "integrity": "sha512-OD+HLlcV7wCL64w0rheX/C0J31DbJce0nf8ulv3UNftQ617JEZE3sQ4cMN6PotXWlJ1M5GQx90G3bywtdKOstw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pfx": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.5.tgz", + "integrity": "sha512-btcH7lbcD4410qnjHvv7F0kEuMNKbX8CFAZSs9CDPWHKzT1byLPHYeR40AnUw9z4CzsijMY0daBFYUvVx75sdA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.9.5", + "@peculiar/asn1-pkcs8": "^2.9.5", + "@peculiar/asn1-rsa": "^2.9.5", + "@peculiar/asn1-schema": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs8": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.5.tgz", + "integrity": "sha512-c7UghAGQdBfAHL9JdwcJkAc/lDJKNXfCdYXPXlf8BZdD/fVJjJnXKHxX4gyLhkFTvnGhME7caieSgc2ROtqYTQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs9": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.5.tgz", + "integrity": "sha512-4R/zMgLSHbQIZRBwP1KzX6iuNHmW3xFWwu9TS9A00N60fmQqp9DkkqnQFyd0mAYMQTrQefuzQ/yP4U8sOLGUgQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.9.5", + "@peculiar/asn1-pfx": "^2.9.5", + "@peculiar/asn1-pkcs8": "^2.9.5", + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "@peculiar/asn1-x509-attr": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-rsa": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.5.tgz", + "integrity": "sha512-kHwBLVMkm9ljlM521ovS7y4z4mr8xuHTdNyyoPlDvckBwFKSgs9HqKBryLBeqHqL2YpIgl+Vspl7kzNGG2phzA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.5.tgz", + "integrity": "sha512-Ez3wLKVjaxdsLcgeWN4OE31QkM7oBOgKuuBJxldRYAkfYw2C+8zJPcSd/SThnbhszsEOlAmoaS5kIIkN29fGKQ==", + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.5.tgz", + "integrity": "sha512-NP3ecvN6zTDlwCvogIWL7MJN9AZNuskkIbnlhrlkB97Mn2EqirBUQ8GKzsOmdAL3pRvjGu1Uk/a4DNfiZrWxhw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509-attr": { + "version": "2.9.5", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.5.tgz", + "integrity": "sha512-PlbL1a74RZiry7puPCZ5hdk/puvivxYJPbjadr2i7DBjHCJFEKCfTRPKL3DILeZFtzJjn95J5EBtSc4/TB9/6Q==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.5", + "@peculiar/asn1-x509": "^2.9.5", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/x509": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz", + "integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.6.0", + "@peculiar/asn1-csr": "^2.6.0", + "@peculiar/asn1-ecc": "^2.6.0", + "@peculiar/asn1-pkcs9": "^2.6.0", + "@peculiar/asn1-rsa": "^2.6.0", + "@peculiar/asn1-schema": "^2.6.0", + "@peculiar/asn1-x509": "^2.6.0", + "pvtsutils": "^1.3.6", + "reflect-metadata": "^0.2.2", + "tslib": "^2.8.1", + "tsyringe": "^4.10.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -15649,6 +15863,31 @@ } } }, + "node_modules/@simplewebauthn/browser": { + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-13.3.0.tgz", + "integrity": "sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ==", + "license": "MIT" + }, + "node_modules/@simplewebauthn/server": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@simplewebauthn/server/-/server-13.3.3.tgz", + "integrity": "sha512-LelX/lcy5cjc15A86i/aNxHhB5eU7dd20QsbP0VLAf9e38+SLlsnqCCyecx3xqfGofhmX05h1J9fKRYWxw+luA==", + "license": "MIT", + "dependencies": { + "@hexagon/base64": "^1.1.27", + "@levischuck/tiny-cbor": "^0.2.2", + "@peculiar/asn1-android": "^2.6.0", + "@peculiar/asn1-ecc": "^2.6.1", + "@peculiar/asn1-rsa": "^2.6.1", + "@peculiar/asn1-schema": "^2.6.0", + "@peculiar/asn1-x509": "^2.6.1", + "@peculiar/x509": "^1.14.3" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -19462,6 +19701,20 @@ "dev": true, "license": "MIT" }, + "node_modules/asn1js": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz", + "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==", + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.5", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/assert": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/assert/-/assert-2.1.0.tgz", @@ -34069,6 +34322,24 @@ "node": "^20.19.0 || ^22.12.0 || >=23" } }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/qrcode.react": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz", @@ -34900,6 +35171,12 @@ "@babel/runtime": "^7.9.2" } }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, "node_modules/reflect.getprototypeof": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", @@ -38103,6 +38380,18 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/tsyringe": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", + "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==", + "license": "MIT", + "dependencies": { + "tslib": "^1.9.3" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/tty-browserify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz", @@ -40441,6 +40730,7 @@ "dependencies": { "@langchain/langgraph-checkpoint": "^1.1.2", "@langchain/langgraph-checkpoint-mongodb": "^1.4.0", + "@simplewebauthn/server": "^13.3.2", "cluster-key-slot": "^1.1.2", "croner": "^10.0.1", "express-rate-limit": "^8.5.1", diff --git a/packages/api/package.json b/packages/api/package.json index 9e7702ef77..39924f4ba1 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -179,6 +179,7 @@ "dependencies": { "@langchain/langgraph-checkpoint": "^1.1.2", "@langchain/langgraph-checkpoint-mongodb": "^1.4.0", + "@simplewebauthn/server": "^13.3.2", "cluster-key-slot": "^1.1.2", "croner": "^10.0.1", "express-rate-limit": "^8.5.1", diff --git a/packages/api/src/admin/users.spec.ts b/packages/api/src/admin/users.spec.ts index 824dd72514..acf6a50f47 100644 --- a/packages/api/src/admin/users.spec.ts +++ b/packages/api/src/admin/users.spec.ts @@ -67,6 +67,7 @@ function createDeps(overrides: Partial = {}): AdminUsersDeps { invalidateCodeEnvironmentConfigCache: jest.fn().mockResolvedValue(undefined), deleteConfig: jest.fn().mockResolvedValue(null), deleteAclEntries: jest.fn().mockResolvedValue(undefined), + deletePasskeysByUser: jest.fn().mockResolvedValue(0), ...overrides, }; } @@ -457,6 +458,7 @@ describe('createAdminUsersHandlers', () => { principalType: PrincipalType.USER, principalId: expect.any(Types.ObjectId), }); + expect(deps.deletePasskeysByUser).toHaveBeenCalledWith(validUserId); }); it('returns success even when cascade cleanup partially fails', async () => { diff --git a/packages/api/src/admin/users.ts b/packages/api/src/admin/users.ts index 0103c72696..e612a6d71d 100644 --- a/packages/api/src/admin/users.ts +++ b/packages/api/src/admin/users.ts @@ -57,6 +57,11 @@ export interface AdminUsersDeps { principalType: PrincipalType; principalId: string | Types.ObjectId; }) => Promise; + /** + * Credential IDs are globally unique, so passkeys left behind by a deleted user + * keep authentication material and can collide with a later registration. + */ + deletePasskeysByUser: (userId: string) => Promise; } export function createAdminUsersHandlers(deps: AdminUsersDeps): { @@ -79,6 +84,7 @@ export function createAdminUsersHandlers(deps: AdminUsersDeps): { invalidateCodeEnvironmentConfigCache, deleteConfig, deleteAclEntries, + deletePasskeysByUser, } = deps; async function listUsersHandler(req: ServerRequest, res: Response) { @@ -229,6 +235,7 @@ export function createAdminUsersHandlers(deps: AdminUsersDeps): { deleteConfig(PrincipalType.USER, id), ...(codeEnvironmentCleanupSafe ? [deleteUserCodeEnvironments(objectId)] : []), deleteAclEntries({ principalType: PrincipalType.USER, principalId: objectId }), + deletePasskeysByUser(id), ]); for (const r of cleanupResults) { if (r.status === 'rejected') { diff --git a/packages/api/src/auth/credentials.spec.ts b/packages/api/src/auth/credentials.spec.ts new file mode 100644 index 0000000000..e1531b51aa --- /dev/null +++ b/packages/api/src/auth/credentials.spec.ts @@ -0,0 +1,52 @@ +import { isTokenIssuedBeforeCredentialChange } from './credentials'; + +const changedAt = new Date(1700000010500); + +describe('isTokenIssuedBeforeCredentialChange', () => { + it('revokes nothing for an account that never changed credentials', () => { + expect(isTokenIssuedBeforeCredentialChange({ iat: 1 }, {})).toBe(false); + expect(isTokenIssuedBeforeCredentialChange({ iat: 1 }, undefined)).toBe(false); + }); + + it('rejects a token minted before the change', () => { + expect( + isTokenIssuedBeforeCredentialChange({ iat: 1700000009 }, { credentialsChangedAt: changedAt }), + ).toBe(true); + }); + + it('fails closed for a token minted inside the second of the change', () => { + expect( + isTokenIssuedBeforeCredentialChange({ iat: 1700000010 }, { credentialsChangedAt: changedAt }), + ).toBe(true); + }); + + it('accepts a token minted after the change', () => { + expect( + isTokenIssuedBeforeCredentialChange({ iat: 1700000011 }, { credentialsChangedAt: changedAt }), + ).toBe(false); + }); + + it('reads string and numeric stamps the way Mongo or a cache may hand them back', () => { + const user = { credentialsChangedAt: changedAt.toISOString() }; + expect(isTokenIssuedBeforeCredentialChange({ iat: 1700000009 }, user)).toBe(true); + expect( + isTokenIssuedBeforeCredentialChange( + { iat: 1700000011 }, + { credentialsChangedAt: changedAt.getTime() }, + ), + ).toBe(false); + }); + + it('rejects a token without a usable iat once credentials have changed', () => { + const user = { credentialsChangedAt: changedAt }; + expect(isTokenIssuedBeforeCredentialChange({}, user)).toBe(true); + expect(isTokenIssuedBeforeCredentialChange(undefined, user)).toBe(true); + expect(isTokenIssuedBeforeCredentialChange({ iat: Number.NaN }, user)).toBe(true); + }); + + it('ignores an unreadable stamp rather than locking the account out', () => { + expect( + isTokenIssuedBeforeCredentialChange({ iat: 1 }, { credentialsChangedAt: 'not-a-date' }), + ).toBe(false); + }); +}); diff --git a/packages/api/src/auth/credentials.ts b/packages/api/src/auth/credentials.ts new file mode 100644 index 0000000000..7570557d62 --- /dev/null +++ b/packages/api/src/auth/credentials.ts @@ -0,0 +1,40 @@ +/** Timestamp source a user document may carry for its last credential change. */ +export type CredentialChangeStamp = Date | string | number | null; + +/** + * A password reset stamps `credentialsChangedAt` on the user. Access tokens are stateless, + * so a token minted before the reset keeps verifying on signature and `exp` alone unless the + * stamp is consulted: this predicate is what makes a reset revoke outstanding access tokens. + * + * `iat` is whole seconds, so it only identifies the second a token was minted in, not its + * position inside that second. Comparing the start of the issuing second against the + * millisecond-precision stamp fails closed: a token minted in the same second as the reset is + * rejected rather than accepted. Failing open there would let an attacker holding a live token + * refresh in a tight loop, land a mint inside the reset's second and keep a full-lifetime token, + * which is the attack the stamp exists to stop. The reset request issues no token of its own, so + * the only cost is that a login completing within the same second as the reset must be retried. + */ +export function isTokenIssuedBeforeCredentialChange( + payload: { iat?: number } | null | undefined, + user: { credentialsChangedAt?: CredentialChangeStamp } | null | undefined, +): boolean { + const changedAt = user?.credentialsChangedAt; + if (!changedAt) { + return false; + } + + const changedAtMs = + changedAt instanceof Date ? changedAt.getTime() : new Date(changedAt).getTime(); + /** An unreadable stamp revokes nothing; treating it as a cutoff would lock the account out for good */ + if (!Number.isFinite(changedAtMs)) { + return false; + } + + const issuedAt = payload?.iat; + /** Without `iat` the token cannot be shown to postdate the reset */ + if (typeof issuedAt !== 'number' || !Number.isFinite(issuedAt)) { + return true; + } + + return issuedAt * 1000 < changedAtMs; +} diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.ts index 3d0dd70279..eaf2f21b94 100644 --- a/packages/api/src/auth/index.ts +++ b/packages/api/src/auth/index.ts @@ -7,6 +7,10 @@ export * from './refresh'; export * from './googleRefresh'; export * from './agent'; export * from './password'; +export * from './passkey'; +export * from './passkey/handlers'; +export * from './credentials'; +export * from './verification'; export * from './invite'; export * from './codeapi'; export * from './openidRoleSync'; diff --git a/packages/api/src/auth/passkey.spec.ts b/packages/api/src/auth/passkey.spec.ts new file mode 100644 index 0000000000..5da2cc1865 --- /dev/null +++ b/packages/api/src/auth/passkey.spec.ts @@ -0,0 +1,526 @@ +import Keyv from 'keyv'; +import { logger } from '@librechat/data-schemas'; +import { createHash, generateKeyPairSync, sign } from 'node:crypto'; +import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server'; +import type { PasskeyChallengeStore, PasskeyConfig } from './passkey'; +import { + authenticationChallengeKey, + consumeChallenge, + createPasskeyAuthenticationOptions, + createPasskeyRegistrationOptions, + defaultPasskeyName, + getPasskeyConfig, + isPasskeyEnabled, + registrationChallengeKey, + verifyPasskeyAuthentication, + verifyPasskeyRegistration, +} from './passkey'; + +/** In-memory stand-in for the app's Keyv challenge store. */ +function createStore(): PasskeyChallengeStore & { entries: Map } { + const entries = new Map(); + return { + entries, + get: async (key) => entries.get(key), + set: async (key, value) => entries.set(key, value), + delete: async (key) => entries.delete(key), + getDel: async (key) => { + const value = entries.get(key); + entries.delete(key); + return value; + }, + }; +} + +const config: PasskeyConfig = { + enabled: true, + rpID: 'chat.example.com', + rpName: 'LibreChat', + origins: ['https://chat.example.com'], +}; + +const user = { id: '65f0000000000000000000aa', email: 'user@example.com', name: 'Ada' }; + +/** Authenticator data flags: user present, and user present plus user verified. */ +const FLAG_UP = 0x01; +const FLAG_UP_UV = 0x05; + +/** + * Builds a real ES256 authenticator so assertions are genuinely signed and the + * only thing under test is which flags the server insists on. + */ +function createAuthenticator(credentialId = 'cred-id') { + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const { x = '', y = '' } = publicKey.export({ format: 'jwk' }); + + /** COSE_Key map: kty EC2, alg ES256, crv P-256, then the 32-byte x and y. */ + const cosePublicKey = Buffer.concat([ + Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), + Buffer.from(x, 'base64url'), + Buffer.from([0x22, 0x58, 0x20]), + Buffer.from(y, 'base64url'), + ]); + + const id = Buffer.from(credentialId, 'utf8').toString('base64url'); + + const assert = ({ + challenge, + flags, + counter = 1, + origin = config.origins[0], + }: { + challenge: string; + flags: number; + counter?: number; + origin?: string; + }): AuthenticationResponseJSON => { + const clientData = Buffer.from( + JSON.stringify({ type: 'webauthn.get', challenge, origin, crossOrigin: false }), + 'utf8', + ); + + const authenticatorData = Buffer.alloc(37); + createHash('sha256').update(config.rpID).digest().copy(authenticatorData, 0); + authenticatorData[32] = flags; + authenticatorData.writeUInt32BE(counter, 33); + + const signature = sign( + 'sha256', + Buffer.concat([authenticatorData, createHash('sha256').update(clientData).digest()]), + privateKey, + ); + + return { + id, + rawId: id, + type: 'public-key', + clientExtensionResults: {}, + response: { + clientDataJSON: clientData.toString('base64url'), + authenticatorData: authenticatorData.toString('base64url'), + signature: signature.toString('base64url'), + }, + } as AuthenticationResponseJSON; + }; + + return { assert, credential: { credentialId: id, publicKey: cosePublicKey, counter: 0 } }; +} + +describe('getPasskeyConfig', () => { + it('derives the RP ID and origins from DOMAIN_CLIENT', () => { + const resolved = getPasskeyConfig({ + ALLOW_PASSKEY_LOGIN: 'true', + DOMAIN_CLIENT: 'https://chat.example.com', + DOMAIN_SERVER: 'https://chat.example.com', + APP_TITLE: 'Acme Chat', + } as NodeJS.ProcessEnv); + + expect(resolved.enabled).toBe(true); + expect(resolved.rpID).toBe('chat.example.com'); + expect(resolved.rpName).toBe('Acme Chat'); + expect(resolved.origins).toEqual(['https://chat.example.com']); + }); + + it('keeps a distinct server origin alongside the client origin', () => { + const resolved = getPasskeyConfig({ + ALLOW_PASSKEY_LOGIN: 'true', + DOMAIN_CLIENT: 'https://chat.example.com', + DOMAIN_SERVER: 'https://api.example.com', + } as NodeJS.ProcessEnv); + + expect(resolved.origins).toEqual(['https://chat.example.com', 'https://api.example.com']); + }); + + it('prefers explicit overrides and ignores unparseable origins', () => { + const resolved = getPasskeyConfig({ + ALLOW_PASSKEY_LOGIN: 'true', + DOMAIN_CLIENT: 'https://chat.example.com', + PASSKEY_RP_ID: 'example.com', + PASSKEY_RP_NAME: 'Custom', + PASSKEY_ORIGINS: 'https://a.example.com, not-a-url ,https://b.example.com', + } as NodeJS.ProcessEnv); + + expect(resolved.rpID).toBe('example.com'); + expect(resolved.rpName).toBe('Custom'); + expect(resolved.origins).toEqual(['https://a.example.com', 'https://b.example.com']); + }); + + it('is disabled unless ALLOW_PASSKEY_LOGIN is truthy', () => { + const resolved = getPasskeyConfig({ + DOMAIN_CLIENT: 'https://chat.example.com', + } as NodeJS.ProcessEnv); + + expect(resolved.enabled).toBe(false); + expect(isPasskeyEnabled(resolved)).toBe(false); + }); + + it('reports disabled when no origin can be resolved', () => { + expect(isPasskeyEnabled({ ...config, origins: [] })).toBe(false); + }); +}); + +describe('consumeChallenge', () => { + it('returns the challenge once and invalidates it', async () => { + const store = createStore(); + await store.set('key', 'challenge-value'); + + expect(await consumeChallenge(store, 'key')).toBe('challenge-value'); + expect(await consumeChallenge(store, 'key')).toBeUndefined(); + }); + + it('returns undefined for an unknown key', async () => { + expect(await consumeChallenge(createStore(), 'missing')).toBeUndefined(); + }); + + it('hands a challenge to only one of two concurrent readers without a native getDel', async () => { + const keyv = new Keyv(); + const store: PasskeyChallengeStore = { + get: (key) => keyv.get(key), + set: (key, value, ttl) => keyv.set(key, value, ttl), + delete: (key) => keyv.delete(key), + }; + await store.set('key', 'challenge-value'); + + const results = await Promise.all([ + consumeChallenge(store, 'key'), + consumeChallenge(store, 'key'), + ]); + + expect(results.filter((value) => value === 'challenge-value')).toHaveLength(1); + expect(results.filter((value) => value === undefined)).toHaveLength(1); + }); + + it('uses getDel when present so concurrent consumers cannot both win', async () => { + const store = createStore(); + await store.set('key', 'challenge-value'); + + const [first, second] = await Promise.all([ + consumeChallenge(store, 'key'), + consumeChallenge(store, 'key'), + ]); + + const values = [first, second].filter((value) => value !== undefined); + expect(values).toEqual(['challenge-value']); + expect(store.entries.has('key')).toBe(false); + }); + + it('falls back to get-then-delete when getDel is absent', async () => { + const entries = new Map([['key', 'challenge-value']]); + const store: PasskeyChallengeStore = { + get: async (key) => entries.get(key), + set: async (key, value) => entries.set(key, value), + delete: async (key) => entries.delete(key), + }; + + expect(await consumeChallenge(store, 'key')).toBe('challenge-value'); + expect(await consumeChallenge(store, 'key')).toBeUndefined(); + expect(entries.has('key')).toBe(false); + }); +}); + +describe('createPasskeyRegistrationOptions', () => { + it('stores the challenge under the user and excludes known credentials', async () => { + const store = createStore(); + const options = await createPasskeyRegistrationOptions({ + config, + store, + user, + existingCredentials: [ + { credentialId: 'abc', publicKey: Buffer.alloc(1), counter: 0, transports: ['internal'] }, + ], + }); + + expect(options.rp).toEqual({ id: config.rpID, name: config.rpName }); + expect(options.user.name).toBe(user.email); + expect(options.user.displayName).toBe('Ada'); + expect(options.excludeCredentials).toEqual([ + { id: 'abc', type: 'public-key', transports: ['internal'] }, + ]); + /** Discoverable credentials are what make usernameless sign-in possible. */ + expect(options.authenticatorSelection?.residentKey).toBe('required'); + /** UV at registration so the credential is bound to a verified user gesture. */ + expect(options.authenticatorSelection?.userVerification).toBe('required'); + expect(store.entries.get(registrationChallengeKey(user.id))).toBe(options.challenge); + }); +}); + +describe('createPasskeyAuthenticationOptions', () => { + it('omits allowCredentials so the response does not reveal account existence', async () => { + const store = createStore(); + const { options, sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + expect(options.allowCredentials).toBeUndefined(); + expect(options.rpId).toBe(config.rpID); + expect(store.entries.get(authenticationChallengeKey(sessionId))).toBe(options.challenge); + }); + + it('asks the authenticator to verify the user, since sign-in is single-factor', async () => { + const { options } = await createPasskeyAuthenticationOptions({ config, store: createStore() }); + + expect(options.userVerification).toBe('required'); + }); + + it('issues a distinct session handle per ceremony', async () => { + const store = createStore(); + const first = await createPasskeyAuthenticationOptions({ config, store }); + const second = await createPasskeyAuthenticationOptions({ config, store }); + + expect(first.sessionId).not.toBe(second.sessionId); + expect(store.entries.size).toBe(2); + }); +}); + +describe('verification without a live challenge', () => { + const registrationResponse = { + id: 'cred-id', + rawId: 'cred-id', + type: 'public-key', + clientExtensionResults: {}, + response: { clientDataJSON: '', attestationObject: '' }, + } as RegistrationResponseJSON; + + const authenticationResponse = { + id: 'cred-id', + rawId: 'cred-id', + type: 'public-key', + clientExtensionResults: {}, + response: { clientDataJSON: '', authenticatorData: '', signature: '' }, + } as AuthenticationResponseJSON; + + it('rejects a registration with no pending challenge', async () => { + const result = await verifyPasskeyRegistration({ + config, + store: createStore(), + userId: user.id, + response: registrationResponse, + }); + + expect(result).toBeNull(); + }); + + it('rejects a replayed registration challenge', async () => { + const store = createStore(); + await createPasskeyRegistrationOptions({ config, store, user }); + + /** The first attempt consumes the challenge even though the payload is bogus. */ + expect( + await verifyPasskeyRegistration({ + config, + store, + userId: user.id, + response: registrationResponse, + }), + ).toBeNull(); + expect(store.entries.has(registrationChallengeKey(user.id))).toBe(false); + }); + + it('rejects an assertion with an unknown session handle', async () => { + const result = await verifyPasskeyAuthentication({ + config, + store: createStore(), + sessionId: 'never-issued', + response: authenticationResponse, + credential: { credentialId: 'cred-id', publicKey: Buffer.alloc(1), counter: 0 }, + }); + + expect(result).toBeNull(); + }); + + it('rejects a tampered assertion and burns the challenge', async () => { + const store = createStore(); + const { sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + const result = await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: authenticationResponse, + credential: { credentialId: 'cred-id', publicKey: Buffer.alloc(1), counter: 0 }, + }); + + expect(result).toBeNull(); + expect(store.entries.has(authenticationChallengeKey(sessionId))).toBe(false); + }); +}); + +describe('verifyPasskeyAuthentication', () => { + it('accepts an assertion the authenticator user-verified', async () => { + const store = createStore(); + const { assert, credential } = createAuthenticator(); + const { options, sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + const result = await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: assert({ challenge: options.challenge, flags: FLAG_UP_UV }), + credential, + }); + + expect(result).toEqual({ newCounter: 1 }); + }); + + it('rejects an assertion carrying only the user-present flag', async () => { + const store = createStore(); + const { assert, credential } = createAuthenticator(); + const { options, sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + /** A tap on a PIN-less key is possession alone, which cannot stand in for a login. */ + const result = await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: assert({ challenge: options.challenge, flags: FLAG_UP }), + credential, + }); + + expect(result).toBeNull(); + expect(store.entries.has(authenticationChallengeKey(sessionId))).toBe(false); + }); +}); + +describe('ceremony failure logging', () => { + const credential = { credentialId: 'cred-id', publicKey: Buffer.alloc(1), counter: 0 }; + + /** Builds the base64url `clientDataJSON` an unauthenticated caller fully controls. */ + function clientDataJSON(type: string, challenge: string): string { + return Buffer.from( + JSON.stringify({ type, challenge, origin: config.origins[0], crossOrigin: false }), + 'utf8', + ).toString('base64url'); + } + + function authenticationResponseWith(challenge: string): AuthenticationResponseJSON { + return { + id: 'cred-id', + rawId: 'cred-id', + type: 'public-key', + clientExtensionResults: {}, + response: { + clientDataJSON: clientDataJSON('webauthn.get', challenge), + authenticatorData: '', + signature: '', + }, + } as AuthenticationResponseJSON; + } + + function registrationResponseWith(challenge: string): RegistrationResponseJSON { + return { + id: 'cred-id', + rawId: 'cred-id', + type: 'public-key', + clientExtensionResults: {}, + response: { + clientDataJSON: clientDataJSON('webauthn.create', challenge), + attestationObject: '', + }, + } as RegistrationResponseJSON; + } + + /** A challenge crafted to close the log line and forge a second, fake record. */ + const forgedChallenge = + 'x", expected "y\r\n2026-01-01 00:00:00 info: [FORGED] admin@example.com signed in\u001b[31m\u0007'; + + let warn: jest.SpyInstance; + + beforeEach(() => { + warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger); + }); + + it('logs the authentication failure as one line with no injected control characters', async () => { + const store = createStore(); + const { sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + const result = await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: authenticationResponseWith(forgedChallenge), + credential, + }); + + expect(result).toBeNull(); + expect(warn).toHaveBeenCalledTimes(1); + + /** A single string argument: nothing is left for winston to concatenate. */ + expect(warn.mock.calls[0]).toHaveLength(1); + const line = warn.mock.calls[0][0] as string; + expect(typeof line).toBe('string'); + // eslint-disable-next-line no-control-regex + expect(line).not.toMatch(/[\r\n\u0000-\u001f\u007f-\u009f]/); + /** The forged text stays inline as diagnostics: it can never begin its own record. */ + expect(line.indexOf('[FORGED]')).toBeGreaterThan(0); + expect(line.split('\n')).toHaveLength(1); + }); + + it('keeps the reason for an authentication failure readable', async () => { + const store = createStore(); + const { sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: authenticationResponseWith('a-mismatched-challenge'), + credential, + }); + + const line = warn.mock.calls[0][0] as string; + expect(line).toContain('[passkey] Authentication verification failed'); + expect(line).toContain('Unexpected authentication response challenge'); + expect(line).toContain('a-mismatched-challenge'); + }); + + it('logs the registration failure as one line with no injected control characters', async () => { + const store = createStore(); + await createPasskeyRegistrationOptions({ config, store, user }); + + const result = await verifyPasskeyRegistration({ + config, + store, + userId: user.id, + response: registrationResponseWith(forgedChallenge), + }); + + expect(result).toBeNull(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]).toHaveLength(1); + + const line = warn.mock.calls[0][0] as string; + expect(line).toContain('[passkey] Registration verification failed'); + expect(line).toContain('Unexpected registration response challenge'); + // eslint-disable-next-line no-control-regex + expect(line).not.toMatch(/[\r\n\u0000-\u001f\u007f-\u009f]/); + /** The forged text stays inline as diagnostics: it can never begin its own record. */ + expect(line.indexOf('[FORGED]')).toBeGreaterThan(0); + }); + + it('bounds how much attacker-supplied text reaches the log', async () => { + const store = createStore(); + const { sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: authenticationResponseWith('A'.repeat(5000)), + credential, + }); + + const line = warn.mock.calls[0][0] as string; + expect(line).toMatch(/\.\.\. \[truncated\]$/); + expect(line.length).toBeLessThan(300); + }); +}); + +describe('defaultPasskeyName', () => { + it.each([ + [['hybrid'], 'Phone or tablet'], + [['usb'], 'Security key'], + [['nfc'], 'Security key'], + [['internal'], 'This device'], + [[], 'Passkey'], + ])('labels %p as %s', (transports, expected) => { + expect(defaultPasskeyName(transports)).toBe(expected); + }); +}); diff --git a/packages/api/src/auth/passkey.ts b/packages/api/src/auth/passkey.ts new file mode 100644 index 0000000000..399b831913 --- /dev/null +++ b/packages/api/src/auth/passkey.ts @@ -0,0 +1,368 @@ +import { randomUUID } from 'node:crypto'; +import { logger } from '@librechat/data-schemas'; +import { + generateAuthenticationOptions, + generateRegistrationOptions, + verifyAuthenticationResponse, + verifyRegistrationResponse, +} from '@simplewebauthn/server'; + +import type { + AuthenticationResponseJSON, + AuthenticatorTransportFuture, + PublicKeyCredentialCreationOptionsJSON, + PublicKeyCredentialRequestOptionsJSON, + RegistrationResponseJSON, +} from '@simplewebauthn/server'; +import type { PasskeyDeviceType } from '@librechat/data-schemas'; + +import { isEnabled } from '~/utils'; + +/** How long a generated challenge stays valid, in milliseconds. */ +export const PASSKEY_CHALLENGE_TTL: number = 5 * 60 * 1000; + +/** Matches the challenge TTL so the authenticator prompt cannot outlive the challenge. */ +const CEREMONY_TIMEOUT = PASSKEY_CHALLENGE_TTL; + +export interface PasskeyConfig { + enabled: boolean; + /** Registrable domain the credential is scoped to (no scheme, no port). */ + rpID: string; + /** Human-readable name shown by the authenticator during registration. */ + rpName: string; + /** Origins a ceremony is allowed to originate from. */ + origins: string[]; +} + +/** The stored credential fields the ceremony helpers need. */ +export interface PasskeyCredential { + credentialId: string; + publicKey: Buffer | Uint8Array; + counter: number; + transports?: string[]; +} + +export interface VerifiedPasskeyRegistration { + credentialId: string; + publicKey: Buffer; + counter: number; + transports: string[]; + deviceType: PasskeyDeviceType; + backedUp: boolean; +} + +/** Minimal key/value contract satisfied by the app's Keyv cache stores. */ +export interface PasskeyChallengeStore { + get: (key: string) => Promise; + set: (key: string, value: string, ttl?: number) => Promise; + /** Resolves true only for the caller that actually removed the key. */ + delete: (key: string) => Promise; + /** Optional atomic get-and-delete (Redis GETDEL). Prefer when available. */ + getDel?: (key: string) => Promise; +} + +/** Upper bound on the ceremony error text copied into a log line. */ +const MAX_LOGGED_REASON_LENGTH = 200; + +/** Line breaks, ANSI escapes and other control characters that could forge log records. */ +// eslint-disable-next-line no-control-regex +const LOG_UNSAFE_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g; + +/** + * Ceremony errors interpolate attacker-supplied `clientDataJSON` fields into + * their message, so the text is flattened to a single bounded line before it + * reaches the logger and cannot fabricate additional log records. + */ +function logSafeReason(error: unknown): string { + const message = error instanceof Error ? error.message : String(error ?? ''); + const flattened = message.replace(LOG_UNSAFE_CHARACTERS, ' ').trim(); + if (!flattened) { + return 'unknown error'; + } + return flattened.length > MAX_LOGGED_REASON_LENGTH + ? `${flattened.slice(0, MAX_LOGGED_REASON_LENGTH)}... [truncated]` + : flattened; +} + +function hostnameOf(value?: string): string | undefined { + if (!value) { + return undefined; + } + try { + return new URL(value).hostname; + } catch { + return undefined; + } +} + +function normalizeOrigin(value: string): string | undefined { + const trimmed = value.trim(); + if (!trimmed) { + return undefined; + } + try { + return new URL(trimmed).origin; + } catch { + return undefined; + } +} + +/** + * Resolves passkey settings from the environment. + * + * `PASSKEY_RP_ID` and `PASSKEY_ORIGINS` are optional: both are derived from + * `DOMAIN_CLIENT` so a standard deployment needs only `ALLOW_PASSKEY_LOGIN=true`. + * A credential is permanently bound to the RP ID it was created under, so an + * operator changing `DOMAIN_CLIENT` later must pin `PASSKEY_RP_ID` to keep + * existing passkeys usable. + */ +export function getPasskeyConfig(env: NodeJS.ProcessEnv = process.env): PasskeyConfig { + const clientOrigin = normalizeOrigin(env.DOMAIN_CLIENT ?? ''); + const serverOrigin = normalizeOrigin(env.DOMAIN_SERVER ?? ''); + + const configuredOrigins = (env.PASSKEY_ORIGINS ?? '') + .split(',') + .map(normalizeOrigin) + .filter((origin): origin is string => !!origin); + + const origins = configuredOrigins.length + ? configuredOrigins + : [clientOrigin, serverOrigin].filter((origin): origin is string => !!origin); + + const rpID = env.PASSKEY_RP_ID?.trim() || hostnameOf(clientOrigin) || 'localhost'; + + return { + enabled: isEnabled(env.ALLOW_PASSKEY_LOGIN), + rpID, + rpName: env.PASSKEY_RP_NAME?.trim() || env.APP_TITLE?.trim() || 'LibreChat', + origins: origins.length ? Array.from(new Set(origins)) : ['http://localhost:3080'], + }; +} + +/** + * True when passkeys are switched on and the deployment has at least one origin + * to validate ceremonies against. + */ +export function isPasskeyEnabled(config: PasskeyConfig = getPasskeyConfig()): boolean { + return config.enabled && config.origins.length > 0; +} + +/** Namespaced cache key for a pending registration ceremony. */ +export const registrationChallengeKey = (userId: string): string => `passkey-reg:${userId}`; + +/** Namespaced cache key for a pending authentication ceremony. */ +export const authenticationChallengeKey = (sessionId: string): string => + `passkey-auth:${sessionId}`; + +/** + * Reads a challenge and immediately invalidates it, so a challenge can back at + * most one ceremony even if the client replays the verification request. + * + * Prefers atomic get-and-delete when the store implements `getDel` (e.g. Redis + * GETDEL). Otherwise the delete arbitrates: `DEL` and `Map#delete` report removal to + * exactly one caller, so a replayed or concurrent verification cannot share a challenge. + */ +export async function consumeChallenge( + store: PasskeyChallengeStore, + key: string, +): Promise { + if (typeof store.getDel === 'function') { + const value = await store.getDel(key); + return value ?? undefined; + } + + const challenge = await store.get(key); + if (challenge == null) { + return undefined; + } + /** Concurrent readers can all see the value; only the one whose delete removed it may use it. */ + return (await store.delete(key)) ? challenge : undefined; +} + +/** + * Builds registration options for an already-authenticated user and stores the + * challenge under that user's id. + */ +export async function createPasskeyRegistrationOptions({ + config, + store, + user, + existingCredentials = [], +}: { + config: PasskeyConfig; + store: PasskeyChallengeStore; + user: { id: string; email: string; name?: string; username?: string }; + existingCredentials?: PasskeyCredential[]; +}): Promise { + const options = await generateRegistrationOptions({ + rpID: config.rpID, + rpName: config.rpName, + userID: new Uint8Array(Buffer.from(user.id, 'utf8')), + userName: user.email, + userDisplayName: user.name || user.username || user.email, + timeout: CEREMONY_TIMEOUT, + attestationType: 'none', + excludeCredentials: existingCredentials.map((credential) => ({ + id: credential.credentialId, + transports: credential.transports as AuthenticatorTransportFuture[] | undefined, + })), + authenticatorSelection: { + residentKey: 'required', + userVerification: 'required', + }, + }); + + await store.set(registrationChallengeKey(user.id), options.challenge, PASSKEY_CHALLENGE_TTL); + return options; +} + +/** + * Verifies an attestation against the challenge issued for `userId` and returns + * the credential fields to persist. Returns `null` when verification fails. + */ +export async function verifyPasskeyRegistration({ + config, + store, + userId, + response, +}: { + config: PasskeyConfig; + store: PasskeyChallengeStore; + userId: string; + response: RegistrationResponseJSON; +}): Promise { + const expectedChallenge = await consumeChallenge(store, registrationChallengeKey(userId)); + if (!expectedChallenge) { + return null; + } + + let verification; + try { + verification = await verifyRegistrationResponse({ + response, + expectedChallenge, + expectedOrigin: config.origins, + expectedRPID: config.rpID, + requireUserVerification: true, + }); + } catch (error) { + logger.warn(`[passkey] Registration verification failed: ${logSafeReason(error)}`); + return null; + } + + if (!verification.verified) { + return null; + } + + const { credential, credentialDeviceType, credentialBackedUp } = verification.registrationInfo; + + return { + credentialId: credential.id, + publicKey: Buffer.from(credential.publicKey), + counter: credential.counter, + transports: credential.transports ?? response.response.transports ?? [], + deviceType: credentialDeviceType, + backedUp: credentialBackedUp, + }; +} + +/** + * Builds authentication options for an anonymous caller. No `allowCredentials` + * is sent, so the browser offers whichever discoverable credential the user has + * for this RP and the server never confirms whether an account exists. + * + * The returned `sessionId` is the opaque handle the client must send back with + * the assertion; it is the only thing tying the assertion to its challenge. + * + * User verification is requested as `required` so the authenticator collects the + * PIN or biometric during the ceremony, matching what verification enforces. + */ +export async function createPasskeyAuthenticationOptions({ + config, + store, +}: { + config: PasskeyConfig; + store: PasskeyChallengeStore; +}): Promise<{ options: PublicKeyCredentialRequestOptionsJSON; sessionId: string }> { + const options = await generateAuthenticationOptions({ + rpID: config.rpID, + timeout: CEREMONY_TIMEOUT, + userVerification: 'required', + }); + + const sessionId = randomUUID(); + await store.set(authenticationChallengeKey(sessionId), options.challenge, PASSKEY_CHALLENGE_TTL); + + return { options, sessionId }; +} + +/** + * Verifies an assertion against the challenge issued for `sessionId`. + * Returns the authenticator's new signature counter on success, `null` otherwise. + * + * A passkey assertion is a complete single-factor login here, so user + * verification is required: an assertion carrying only the user-present flag, + * which mere possession of the authenticator produces, is rejected. + */ +export async function verifyPasskeyAuthentication({ + config, + store, + sessionId, + response, + credential, +}: { + config: PasskeyConfig; + store: PasskeyChallengeStore; + sessionId: string; + response: AuthenticationResponseJSON; + credential: PasskeyCredential; +}): Promise<{ newCounter: number } | null> { + const expectedChallenge = await consumeChallenge(store, authenticationChallengeKey(sessionId)); + if (!expectedChallenge) { + return null; + } + + let verification; + try { + verification = await verifyAuthenticationResponse({ + response, + expectedChallenge, + expectedOrigin: config.origins, + expectedRPID: config.rpID, + requireUserVerification: true, + credential: { + id: credential.credentialId, + publicKey: new Uint8Array(credential.publicKey), + counter: credential.counter, + transports: credential.transports as AuthenticatorTransportFuture[] | undefined, + }, + }); + } catch (error) { + logger.warn(`[passkey] Authentication verification failed: ${logSafeReason(error)}`); + return null; + } + + if (!verification.verified) { + return null; + } + + return { newCounter: verification.authenticationInfo.newCounter }; +} + +/** + * Derives a default label for a new credential from the authenticator's + * transports, so the list in account settings is readable without the user + * having to name every key. + */ +export function defaultPasskeyName(transports: string[] = []): string { + if (transports.includes('hybrid')) { + return 'Phone or tablet'; + } + if (transports.includes('usb') || transports.includes('nfc')) { + return 'Security key'; + } + if (transports.includes('internal')) { + return 'This device'; + } + return 'Passkey'; +} diff --git a/packages/api/src/auth/passkey/handlers.spec.ts b/packages/api/src/auth/passkey/handlers.spec.ts new file mode 100644 index 0000000000..b1916874f4 --- /dev/null +++ b/packages/api/src/auth/passkey/handlers.spec.ts @@ -0,0 +1,949 @@ +import mongoose from 'mongoose'; +import { createHash } from 'node:crypto'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider'; +import { logger, createMethods, createModels } from '@librechat/data-schemas'; +import type { RegistrationResponseJSON } from '@simplewebauthn/server'; +import type { IUser } from '@librechat/data-schemas'; +import type { Response } from 'express'; +import type { PasskeyHandlersDeps, PasskeyRequest, AuthenticatedPasskeyRequest } from './handlers'; +import type { PasskeyChallengeStore } from '~/auth/passkey'; +import { + verifyPasskeyRegistration, + verifyPasskeyAuthentication, + createPasskeyRegistrationOptions, +} from '~/auth/passkey'; +import { createPasskeyHandlers, createPasskeyChallengeStore } from './handlers'; + +/** + * The WebAuthn ceremonies need a real authenticator to produce a signature, so only + * they are replaced. Config resolution, naming and everything behind them stay real. + */ +jest.mock('~/auth/passkey', () => ({ + ...jest.requireActual('~/auth/passkey'), + createPasskeyRegistrationOptions: jest.fn(), + verifyPasskeyRegistration: jest.fn(), + verifyPasskeyAuthentication: jest.fn(), +})); + +const mockRegistrationOptions = jest.mocked(createPasskeyRegistrationOptions); +const mockVerifyRegistration = jest.mocked(verifyPasskeyRegistration); +const mockVerifyAuthentication = jest.mocked(verifyPasskeyAuthentication); + +const PASSWORD = 'correct horse battery staple'; +/** Stands in for the caller's hash function: the gate only needs a real comparison to run. */ +const hash = (value: string): string => createHash('sha256').update(value).digest('hex'); +const compare = async (candidate: string, stored: string): Promise => + hash(candidate) === stored; +const PASSWORD_HASH = hash(PASSWORD); +const attestation = { id: 'cred-1' } as RegistrationResponseJSON; +const REQUEST_IP = '203.0.113.10'; +const ENV_KEYS = [ + 'ALLOW_PASSKEY_LOGIN', + 'ALLOW_UNVERIFIED_EMAIL_LOGIN', + 'EMAIL_SERVICE', + 'EMAIL_FROM', +] as const; + +type MockResponse = Response & { status: jest.Mock; json: jest.Mock }; +type BanCheck = PasskeyHandlersDeps['checkBan']; + +let mongoServer: MongoMemoryServer; +let methods: ReturnType; +let checkBan: jest.MockedFunction; +let savedEnv: Partial>; + +function buildRes(): MockResponse { + const res = { headersSent: false } as MockResponse; + res.status = jest.fn().mockReturnValue(res); + res.json = jest.fn().mockReturnValue(res); + return res; +} + +function memoryCache(): PasskeyChallengeStore { + const entries = new Map(); + return { + get: async (key) => entries.get(key), + set: async (key, value) => entries.set(key, value), + delete: async (key) => entries.delete(key), + }; +} + +function buildDeps(overrides: Partial = {}): PasskeyHandlersDeps { + return { + checkBan, + compare, + getChallengeCache: memoryCache, + getUserById: methods.getUserById, + updateUser: (userId, update) => methods.updateUser(userId.toString(), update), + createPasskey: methods.createPasskey, + deletePasskey: methods.deletePasskey, + renamePasskey: methods.renamePasskey, + recordPasskeyUse: methods.recordPasskeyUse, + findPasskeysByUser: methods.findPasskeysByUser, + countPasskeysByUser: methods.countPasskeysByUser, + findPasskeyByCredentialId: methods.findPasskeyByCredentialId, + ...overrides, + }; +} + +async function createUser(fields: Partial = {}): Promise { + const doc = await mongoose.models.User.create({ + email: `user-${new mongoose.Types.ObjectId().toString()}@example.com`, + provider: 'local', + password: PASSWORD_HASH, + emailVerified: true, + ...fields, + }); + return doc.toObject({ virtuals: true }) as IUser; +} + +async function createStoredPasskey(user: IUser, credentialId = 'cred-1') { + return methods.createPasskey({ + user: user._id, + credentialId, + publicKey: Buffer.from('public-key'), + counter: 0, + transports: ['internal'], + deviceType: 'singleDevice', + backedUp: false, + name: 'Laptop', + }); +} + +function authedReq( + user: IUser, + body?: TBody, + params: { passkeyId: string } = { passkeyId: '' }, +): AuthenticatedPasskeyRequest { + return { + user: { id: user._id.toString(), provider: user.provider, email: user.email }, + ip: REQUEST_IP, + body, + params, + } as AuthenticatedPasskeyRequest; +} + +const verifiedRegistration = (credentialId = 'cred-1') => ({ + credentialId, + publicKey: Buffer.from('public-key'), + counter: 0, + transports: ['internal'], + deviceType: 'singleDevice' as const, + backedUp: false, +}); + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + createModels(mongoose); + methods = createMethods(mongoose); + await mongoose.models.Passkey.syncIndexes(); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); +}); + +beforeEach(async () => { + savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); + for (const key of ENV_KEYS) { + delete process.env[key]; + } + process.env.ALLOW_PASSKEY_LOGIN = 'true'; + /** Email configured by default, so the legacy grandfather path stays out of the way. */ + process.env.EMAIL_SERVICE = 'smtp'; + process.env.EMAIL_FROM = 'noreply@example.com'; + + jest.clearAllMocks(); + jest.spyOn(logger, 'warn').mockImplementation(() => logger); + jest.spyOn(logger, 'error').mockImplementation(() => logger); + checkBan = jest.fn, Parameters>(async () => undefined); + mockRegistrationOptions.mockResolvedValue({ challenge: 'chal' } as Awaited< + ReturnType + >); + mockVerifyRegistration.mockResolvedValue(verifiedRegistration()); + mockVerifyAuthentication.mockResolvedValue({ newCounter: 1 }); + + await mongoose.models.User.deleteMany({}); + await mongoose.models.Passkey.deleteMany({}); +}); + +afterEach(() => { + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } + jest.restoreAllMocks(); +}); + +describe('feature gate', () => { + it('answers 404 on every route while passkeys are disabled', async () => { + process.env.ALLOW_PASSKEY_LOGIN = 'false'; + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.listPasskeys(authedReq(user), res); + + expect(res.status).toHaveBeenCalledWith(404); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey authentication is not enabled' }); + }); +}); + +describe('passkey registration provider enforcement', () => { + it('issues registration options for a local account', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: PASSWORD }), res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ challenge: 'chal' }); + }); + + it.each(['openid', 'google', 'ldap', 'saml', undefined])( + 'rejects registration options for provider %s', + async (provider) => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const req = authedReq(user, { password: PASSWORD }); + req.user.provider = provider as string; + const res = buildRes(); + + await handlers.registerPasskeyOptions(req, res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ + message: 'Passkeys are only available for local accounts', + }); + expect(mockRegistrationOptions).not.toHaveBeenCalled(); + }, + ); + + it('does not read the account password when the provider check already failed', async () => { + const getUserById = jest.fn(methods.getUserById); + const handlers = createPasskeyHandlers(buildDeps({ getUserById })); + const user = await createUser({ provider: 'openid' }); + const res = buildRes(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: PASSWORD }), res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(getUserById).not.toHaveBeenCalled(); + }); + + it('refuses a new challenge once the account holds the maximum number of passkeys', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await Promise.all( + Array.from({ length: MAX_PASSKEYS_PER_USER }, (_, i) => + createStoredPasskey(user, `cred-${i}`), + ), + ); + const res = buildRes(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: PASSWORD }), res); + + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey limit reached' }); + }); + + it('stores the credential when the account is local', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { + credential: attestation, + name: ' Work laptop ', + password: PASSWORD, + }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(201); + const stored = await methods.findPasskeysByUser(user._id.toString()); + expect(stored).toHaveLength(1); + expect(res.json).toHaveBeenCalledWith({ + passkey: { + id: stored[0]._id.toString(), + name: 'Work laptop', + deviceType: 'singleDevice', + backedUp: false, + transports: ['internal'], + createdAt: expect.any(Date), + lastUsedAt: null, + }, + }); + }); + + it('names an unnamed credential after its transports', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + buildRes(), + ); + + const [stored] = await methods.findPasskeysByUser(user._id.toString()); + expect(stored.name).toBeTruthy(); + }); + + it('rejects registration verification for a non-local account', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ provider: 'openid' }); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(403); + expect(mockVerifyRegistration).not.toHaveBeenCalled(); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + }); + + it('answers 400 when the credential is missing', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyVerify(authedReq(user, { password: PASSWORD }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ message: 'Missing credential' }); + }); + + it('answers 400 when the attestation does not verify', async () => { + mockVerifyRegistration.mockResolvedValue(null); + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + message: 'Passkey registration could not be verified', + }); + }); + + it('returns 409 for a credential that is already registered', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith({ message: 'This passkey is already registered' }); + }); + + it('returns 409 when create races on a duplicate credentialId', async () => { + const handlers = createPasskeyHandlers( + buildDeps({ findPasskeyByCredentialId: async () => null }), + ); + const user = await createUser(); + await createStoredPasskey(user); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith({ message: 'This passkey is already registered' }); + }); + + it('still lists passkeys for a non-local account so a stale credential can be removed', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ provider: 'openid' }); + const res = buildRes(); + + await handlers.listPasskeys(authedReq(user), res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ passkeys: [] }); + }); +}); + +describe('passkey registration password confirmation (step-up)', () => { + const rejections: Array<[string, object | undefined]> = [ + ['a missing password', undefined], + ['a missing password field', {}], + ['an empty password', { password: '' }], + ['a non-string password', { password: 12345 }], + ['an object password', { password: { $ne: null } }], + ['a wrong password', { password: 'not the password' }], + ]; + + it.each(rejections)('rejects registration options for %s', async (_label, body) => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyOptions(authedReq(user, body), res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' }); + expect(mockRegistrationOptions).not.toHaveBeenCalled(); + }); + + it.each(rejections)('rejects registration verification for %s', async (_label, body) => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, name: 'Laptop', ...body }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' }); + expect(mockVerifyRegistration).not.toHaveBeenCalled(); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + }); + + it('rejects an account that has no usable password hash', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ password: undefined }); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + }); + + it('answers 500 when the account lookup fails, without minting a credential', async () => { + const handlers = createPasskeyHandlers( + buildDeps({ getUserById: jest.fn().mockRejectedValue(new Error('mongo down')) }), + ); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: PASSWORD }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ message: 'Something went wrong' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + }); + + it('never answers 401, which the client would turn into a sign-out', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: 'wrong' }), res); + + expect(res.status).not.toHaveBeenCalledWith(401); + }); + + it('logs a warning naming the user and request IP on a failed step-up', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: 'wrong' }), buildRes()); + await handlers.registerPasskeyVerify( + authedReq(user, { credential: attestation, password: 'wrong' }), + buildRes(), + ); + + const expected = `[Passkey] [Registration step-up failed] [User: ${user._id.toString()}] [Request-IP: ${REQUEST_IP}]`; + expect(logger.warn).toHaveBeenNthCalledWith(1, expected); + expect(logger.warn).toHaveBeenNthCalledWith(2, expected); + }); + + it('reads the password field explicitly, which the schema hides by default', async () => { + const getUserById = jest.fn(methods.getUserById); + const handlers = createPasskeyHandlers(buildDeps({ getUserById })); + const user = await createUser(); + + await handlers.registerPasskeyOptions(authedReq(user, { password: PASSWORD }), buildRes()); + + expect(getUserById).toHaveBeenCalledWith(user._id.toString(), '+password'); + expect(logger.warn).not.toHaveBeenCalled(); + }); +}); + +describe('passkey rename', () => { + it('leaves rename ungated: it grants nothing and removes no login factor', async () => { + const getUserById = jest.fn(methods.getUserById); + const handlers = createPasskeyHandlers(buildDeps({ getUserById })); + const user = await createUser(); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.updatePasskey( + authedReq(user, { name: ` ${'x'.repeat(80)} ` }, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(200); + expect(getUserById).not.toHaveBeenCalled(); + expect(res.json.mock.calls[0][0].passkey.name).toBe('x'.repeat(60)); + }); + + it('requires a non-blank name', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const res = buildRes(); + + await handlers.updatePasskey(authedReq(user, { name: ' ' }, { passkeyId: 'p1' }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ message: 'Name is required' }); + }); + + it('answers 404 for a credential the caller does not own', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const owner = await createUser(); + const other = await createUser(); + const passkey = await createStoredPasskey(owner); + const res = buildRes(); + + await handlers.updatePasskey( + authedReq(other, { name: 'Mine now' }, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(404); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey not found' }); + }); +}); + +describe('passkey removal password confirmation (step-up)', () => { + const rejections: Array<[string, object | undefined]> = [ + ['a missing body', undefined], + ['a missing password field', {}], + ['an empty password', { password: '' }], + ['a non-string password', { password: 12345 }], + ['an object password', { password: { $ne: null } }], + ['a wrong password', { password: 'not the password' }], + ]; + + it.each(rejections)('refuses removal for %s', async (_label, body) => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.removePasskey(authedReq(user, body, { passkeyId: passkey._id.toString() }), res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.status).not.toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(1); + }); + + it('logs a warning naming the user and request IP on a failed step-up', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + + await handlers.removePasskey( + authedReq(user, { password: 'wrong' }, { passkeyId: 'p1' }), + buildRes(), + ); + + expect(logger.warn).toHaveBeenCalledWith( + `[Passkey] [Deletion step-up failed] [User: ${user._id.toString()}] [Request-IP: ${REQUEST_IP}]`, + ); + }); + + it('answers 500 when the account lookup fails, without deleting', async () => { + const handlers = createPasskeyHandlers( + buildDeps({ getUserById: jest.fn().mockRejectedValue(new Error('mongo down')) }), + ); + const user = await createUser(); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.removePasskey( + authedReq(user, { password: PASSWORD }, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ message: 'Something went wrong' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(1); + }); + + it('removes the credential once the password matches', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.removePasskey( + authedReq(user, { password: PASSWORD }, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey deleted' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('answers 404 for a credential the caller does not own', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const owner = await createUser(); + const other = await createUser(); + const passkey = await createStoredPasskey(owner); + const res = buildRes(); + + await handlers.removePasskey( + authedReq(other, { password: PASSWORD }, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(404); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey not found' }); + expect(await methods.countPasskeysByUser(owner._id.toString())).toBe(1); + }); + + it('removes a stranded credential from an account with no password hash', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ provider: 'openid', password: undefined }); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.removePasskey( + authedReq(user, undefined, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(200); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('gates on the password hash and not on the provider', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ provider: 'openid' }); + const passkey = await createStoredPasskey(user); + const res = buildRes(); + + await handlers.removePasskey( + authedReq(user, undefined, { passkeyId: passkey._id.toString() }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' }); + expect(await methods.countPasskeysByUser(user._id.toString())).toBe(1); + }); +}); + +describe('passkey sign-in', () => { + const loginReq = (credentialId = 'cred-1', userHandle?: string) => + ({ + body: { credential: { id: credentialId, response: { userHandle } }, sessionId: 'sess-1' }, + }) as PasskeyRequest<{ + credential: { id: string; response: { userHandle?: string } }; + sessionId: string; + }> as Parameters['authenticatePasskey']>[0]; + + it('issues an anonymous challenge that lists no credentials', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + + await handlers.loginPasskeyOptions({} as PasskeyRequest, res); + + expect(res.status).toHaveBeenCalledWith(200); + const body = res.json.mock.calls[0][0]; + expect(typeof body.sessionId).toBe('string'); + expect(body.options.allowCredentials ?? []).toEqual([]); + }); + + it('answers 400 without a session id', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + const req = loginReq(); + delete (req.body as { sessionId?: string }).sessionId; + + await handlers.authenticatePasskey(req, res, jest.fn()); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ message: 'Missing credential' }); + }); + + it('signs in a credential owned by a verified local account and advances the counter', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + const req = loginReq(); + const next = jest.fn(); + + await handlers.authenticatePasskey(req, buildRes(), next); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.user?._id.toString()).toBe(user._id.toString()); + const stored = await methods.findPasskeyByCredentialId('cred-1'); + expect(stored?.counter).toBe(1); + expect(stored?.lastUsedAt).toBeInstanceOf(Date); + }); + + it('refuses an unknown credential', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + + await handlers.authenticatePasskey(loginReq('missing'), res, jest.fn()); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ message: 'Passkey authentication failed' }); + }); + + it('refuses a user handle that does not match the credential owner', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + const res = buildRes(); + const handle = Buffer.from('someone-else').toString('base64url'); + + await handlers.authenticatePasskey(loginReq('cred-1', handle), res, jest.fn()); + + expect(res.status).toHaveBeenCalledWith(401); + expect(mockVerifyAuthentication).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith( + '[authenticatePasskey] User handle does not match the credential owner', + ); + }); + + it('refuses an assertion that does not verify', async () => { + mockVerifyAuthentication.mockResolvedValue(null); + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + const res = buildRes(); + + await handlers.authenticatePasskey( + loginReq('cred-1', Buffer.from(user._id.toString()).toString('base64url')), + res, + jest.fn(), + ); + + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('refuses a credential owned by an SSO-provisioned account', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ provider: 'openid' }); + await createStoredPasskey(user); + const res = buildRes(); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect((await methods.findPasskeyByCredentialId('cred-1'))?.counter).toBe(0); + }); + + it('rejects an unverified local account when ALLOW_UNVERIFIED_EMAIL_LOGIN is false', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ emailVerified: false }); + await createStoredPasskey(user); + const res = buildRes(); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(logger.warn).toHaveBeenCalledWith( + '[authenticatePasskey] Rejected unverified email login', + ); + expect((await methods.findPasskeyByCredentialId('cred-1'))?.counter).toBe(0); + }); + + it('allows an unverified local account when ALLOW_UNVERIFIED_EMAIL_LOGIN is true', async () => { + process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN = 'true'; + const updateUser = jest.fn(buildDeps().updateUser); + const handlers = createPasskeyHandlers(buildDeps({ updateUser })); + const expiresAt = new Date(Date.now() + 60_000); + const user = await createUser({ emailVerified: false, expiresAt }); + await createStoredPasskey(user); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), buildRes(), next); + + expect(next).toHaveBeenCalledTimes(1); + expect(updateUser).toHaveBeenCalledWith(user._id, {}); + }); + + /** + * Matches `localStrategy`: an account predating mandatory verification, on a + * deployment with no email configured, is verified as it signs in. Diverging here + * would let the password factor in and lock the passkey factor out. + */ + it('grandfathers a legacy unverified account the way the password flow does', async () => { + delete process.env.EMAIL_SERVICE; + delete process.env.EMAIL_FROM; + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser({ emailVerified: false }); + await mongoose.models.User.collection.updateOne( + { _id: user._id }, + { $set: { createdAt: new Date('2024-01-01T00:00:00.000Z') } }, + ); + await createStoredPasskey(user); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), buildRes(), next); + + expect(next).toHaveBeenCalledTimes(1); + const reloaded = await methods.getUserById(user._id.toString()); + expect(reloaded?.emailVerified).toBe(true); + }); + + it('rejects an assertion that loses the signature counter transition', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + await methods.recordPasskeyUse('cred-1', 5); + mockVerifyAuthentication.mockResolvedValue({ newCounter: 3 }); + const req = loginReq(); + const res = buildRes(); + const next = jest.fn(); + + await handlers.authenticatePasskey(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(req.user).toBeUndefined(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('answers 500 when a lookup throws', async () => { + const handlers = createPasskeyHandlers( + buildDeps({ findPasskeyByCredentialId: jest.fn().mockRejectedValue(new Error('down')) }), + ); + const res = buildRes(); + + await handlers.authenticatePasskey(loginReq(), res, jest.fn()); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ message: 'Something went wrong' }); + }); +}); + +describe('passkey sign-in ban enforcement', () => { + const loginReq = () => + ({ + body: { credential: { id: 'cred-1', response: {} }, sessionId: 'sess-1' }, + }) as Parameters['authenticatePasskey']>[0]; + + let user: IUser; + + beforeEach(async () => { + user = await createUser(); + await createStoredPasskey(user); + }); + + it('re-checks the ban with the resolved user before handing off', async () => { + let userAtCheck: IUser | undefined; + checkBan.mockImplementation(async (req) => { + userAtCheck = req.user; + }); + const handlers = createPasskeyHandlers(buildDeps()); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), buildRes(), next); + + expect(checkBan).toHaveBeenCalledTimes(1); + expect(userAtCheck?._id.toString()).toBe(user._id.toString()); + expect(next).toHaveBeenCalledTimes(1); + }); + + it('does not issue tokens for a banned user', async () => { + checkBan.mockImplementation(async (req, res) => { + req.banned = true; + return res.status(403).json({ message: 'banned' }); + }); + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.status).toHaveBeenCalledTimes(1); + }); + + /** + * `checkBan` swallows its own errors into a no-op `next`, so a failed check leaves + * `req.banned` unset. Falling through there would issue tokens to an account the + * ban list was never able to answer for. + */ + it('refuses when the ban check cannot complete', async () => { + checkBan.mockImplementation(async (_req, _res, next) => next(new Error('ban store down'))); + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + }); + + it('does not answer twice when the failed ban check already responded', async () => { + checkBan.mockImplementation(async (_req, res, next) => { + res.headersSent = true; + next(new Error('ban store down')); + }); + const handlers = createPasskeyHandlers(buildDeps()); + const res = buildRes(); + + await handlers.authenticatePasskey(loginReq(), res, jest.fn()); + + expect(res.status).not.toHaveBeenCalled(); + }); +}); + +describe('createPasskeyChallengeStore', () => { + it('leaves arbitration to delete when the cache has no native getDel', async () => { + const store = createPasskeyChallengeStore(memoryCache()); + await store.set('k', 'challenge'); + + expect(store.getDel).toBeUndefined(); + await expect(store.get('k')).resolves.toBe('challenge'); + await expect(Promise.all([store.delete('k'), store.delete('k')])).resolves.toEqual([ + true, + false, + ]); + }); + + it('prefers the cache getDel when the adapter exposes one', async () => { + const getDel = jest.fn(async () => 'atomic'); + const store = createPasskeyChallengeStore({ ...memoryCache(), getDel }); + + await expect(store.getDel?.('k')).resolves.toBe('atomic'); + expect(getDel).toHaveBeenCalledWith('k'); + }); +}); diff --git a/packages/api/src/auth/passkey/handlers.ts b/packages/api/src/auth/passkey/handlers.ts new file mode 100644 index 0000000000..5caf194ab4 --- /dev/null +++ b/packages/api/src/auth/passkey/handlers.ts @@ -0,0 +1,614 @@ +import { logger } from '@librechat/data-schemas'; +import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider'; +import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server'; +import type { IUser, IPasskey, UserMethods, PasskeyMethods } from '@librechat/data-schemas'; +import type { TPasskey } from 'librechat-data-provider'; +import type { Request, Response } from 'express'; +import type { PasskeyConfig, PasskeyChallengeStore } from '~/auth/passkey'; +import type { ComparePasswordDeps } from '~/auth/password'; +import type { UserDocumentId } from '~/auth/verification'; +import { + getPasskeyConfig, + isPasskeyEnabled, + defaultPasskeyName, + verifyPasskeyRegistration, + verifyPasskeyAuthentication, + createPasskeyRegistrationOptions, + createPasskeyAuthenticationOptions, +} from '~/auth/passkey'; +import { grandfatherLegacyEmailVerification } from '~/auth/verification'; +import { comparePassword } from '~/auth/password'; +import { isEnabled } from '~/utils'; + +const MAX_PASSKEY_NAME_LENGTH = 60; +const LOCAL_PROVIDER = 'local'; +/** Single answer for every step-up failure so the endpoint reveals nothing extra. */ +const INCORRECT_PASSWORD = 'Incorrect password'; +/** Log tags keep the two step-up sites distinguishable in the audit trail. */ +const REGISTRATION_STEP_UP = 'Registration step-up failed'; +const DELETION_STEP_UP = 'Deletion step-up failed'; + +interface StepUpBody { + password?: string; +} + +interface RegistrationBody extends StepUpBody { + credential?: RegistrationResponseJSON; + name?: string; +} + +interface RenameBody { + name?: string; +} + +interface AuthenticationBody { + credential?: AuthenticationResponseJSON; + sessionId?: string; +} + +export type PasskeyRequest = Request< + { passkeyId: string }, + object, + TBody | undefined +> & { + user?: IUser; + banned?: boolean; +}; + +/** Every management route sits behind `requireJwtAuth`, so `req.user` is always populated. */ +export type AuthenticatedPasskeyRequest = PasskeyRequest & { + user: IUser; +}; + +/** The client-facing summary, carrying dates before JSON serialization turns them into strings. */ +export type PasskeySummary = Omit & { + transports: string[]; + createdAt?: Date; + lastUsedAt: Date | null; +}; + +type PasskeyResult = Promise; +type NextCallback = (err?: Error) => void; + +export interface PasskeyHandlersDeps + extends Pick< + PasskeyMethods, + | 'createPasskey' + | 'deletePasskey' + | 'renamePasskey' + | 'recordPasskeyUse' + | 'findPasskeysByUser' + | 'countPasskeysByUser' + | 'findPasskeyByCredentialId' + > { + getUserById: UserMethods['getUserById']; + /** Receives the raw document id, exactly as the password strategy passes it. */ + updateUser: (userId: UserDocumentId, update: Partial) => Promise; + /** Resolves the cache backing pending WebAuthn ceremonies. */ + getChallengeCache: () => PasskeyChallengeStore; + compare: ComparePasswordDeps['compare']; + /** The login ban middleware; reports an internal failure through `next(err)`. */ + checkBan: ( + req: PasskeyRequest, + res: Response, + next: NextCallback, + ) => Promise; +} + +export interface PasskeyHandlers { + listPasskeys: (req: AuthenticatedPasskeyRequest, res: Response) => PasskeyResult; + registerPasskeyOptions: (req: AuthenticatedPasskeyRequest, res: Response) => PasskeyResult; + registerPasskeyVerify: ( + req: AuthenticatedPasskeyRequest, + res: Response, + ) => PasskeyResult; + updatePasskey: (req: AuthenticatedPasskeyRequest, res: Response) => PasskeyResult; + removePasskey: (req: AuthenticatedPasskeyRequest, res: Response) => PasskeyResult; + loginPasskeyOptions: (req: PasskeyRequest, res: Response) => PasskeyResult; + authenticatePasskey: ( + req: PasskeyRequest, + res: Response, + next: () => void, + ) => PasskeyResult; +} + +/** + * Challenge store handed to the ceremony helpers. `getDel` is exposed only when the + * cache has a native one; otherwise `consumeChallenge` arbitrates on `delete`, which + * reports removal to exactly one concurrent caller. + */ +export function createPasskeyChallengeStore(cache: PasskeyChallengeStore): PasskeyChallengeStore { + const nativeGetDel = cache.getDel?.bind(cache); + return { + get: (key) => cache.get(key), + set: (key, value, ttl) => cache.set(key, value, ttl), + delete: (key) => cache.delete(key), + ...(nativeGetDel ? { getDel: nativeGetDel } : {}), + }; +} + +/** + * Passkeys are a local-account credential. An account provisioned by an identity + * provider must keep authenticating through it, otherwise the passkey becomes a + * login path that bypasses IdP-side MFA, conditional access and deprovisioning. + */ +const isLocalAccount = (user: IUser | null | undefined): boolean => + user?.provider === LOCAL_PROVIDER; + +/** Shapes a stored credential into the safe summary the client renders. */ +export const serializePasskey = (passkey: IPasskey): PasskeySummary => ({ + id: passkey._id.toString(), + name: passkey.name, + deviceType: passkey.deviceType, + backedUp: passkey.backedUp, + transports: passkey.transports ?? [], + createdAt: passkey.createdAt, + lastUsedAt: passkey.lastUsedAt ?? null, +}); + +/** Base64URL-decodes the assertion's user handle so it can be matched to the credential owner. */ +const decodeUserHandle = (userHandle: string | undefined): string | null => { + if (typeof userHandle !== 'string' || !userHandle) { + return null; + } + try { + return Buffer.from(userHandle, 'base64url').toString('utf8'); + } catch { + return null; + } +}; + +type MongoWriteError = { code?: number | string } | null | undefined; + +const isDuplicateKeyError = (err: MongoWriteError): boolean => + err?.code === 11000 || err?.code === 'E11000'; + +/** Responds 403 when the authenticated account is not a local one. */ +const requireLocalAccount = (req: AuthenticatedPasskeyRequest, res: Response): boolean => { + if (isLocalAccount(req.user)) { + return true; + } + res.status(403).json({ message: 'Passkeys are only available for local accounts' }); + return false; +}; + +/** + * Guard shared by every passkey endpoint. Responds 404 when the feature is off + * so a disabled deployment does not advertise the routes. + */ +const requirePasskeysEnabled = (res: Response): PasskeyConfig | null => { + const config = getPasskeyConfig(); + if (!isPasskeyEnabled(config)) { + res.status(404).json({ message: 'Passkey authentication is not enabled' }); + return null; + } + return config; +}; + +/** + * Answers a failed step-up. The rejection is logged because these endpoints would + * otherwise be a silent password oracle for a stolen access token: they are keyed + * by user id rather than by IP, so the login ban system never sees these attempts. + */ +const denyPasswordConfirmation = ( + req: AuthenticatedPasskeyRequest, + res: Response, + tag: string, +): boolean => { + logger.warn(`[Passkey] [${tag}] [User: ${req.user?.id}] [Request-IP: ${req.ip}]`); + res.status(403).json({ message: INCORRECT_PASSWORD }); + return false; +}; + +/** Builds the passkey route handlers around the caller's data layer, cache and ban check. */ +export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandlers { + const { + compare, + checkBan, + updateUser, + getUserById, + createPasskey, + deletePasskey, + renamePasskey, + recordPasskeyUse, + getChallengeCache, + findPasskeysByUser, + countPasskeysByUser, + findPasskeyByCredentialId, + } = deps; + + const getChallengeStore = (): PasskeyChallengeStore => + createPasskeyChallengeStore(getChallengeCache()); + + /** + * Step-up gate shared by the passkey endpoints that add or remove a login factor. + * A passkey is a durable single-factor login that outlives session revocation, so + * minting one, or stripping one the account relies on, takes the account password + * and not merely a bearer token. + * + * Answers 403 rather than 401 on failure: the client turns a 401 into a token + * refresh followed by a redirect to the login page, so a mistyped password would + * sign the user out instead of showing an error. + * + * `allowPasswordless` waves through an account carrying no password hash instead + * of refusing it. Resolves true when the caller may continue. + */ + const requirePasswordConfirmation = async ( + req: AuthenticatedPasskeyRequest, + res: Response, + { tag, allowPasswordless = false }: { tag: string; allowPasswordless?: boolean }, + ): Promise => { + const password = req.body?.password; + const submitted = typeof password === 'string' && password.length > 0; + + if (!submitted && !allowPasswordless) { + return denyPasswordConfirmation(req, res, tag); + } + + let account: IUser | null; + try { + account = await getUserById(req.user.id, '+password'); + } catch (err) { + logger.error('[requirePasswordConfirmation]', err); + res.status(500).json({ message: 'Something went wrong' }); + return false; + } + + if (!account?.password) { + return allowPasswordless ? true : denyPasswordConfirmation(req, res, tag); + } + + if (!submitted) { + return denyPasswordConfirmation(req, res, tag); + } + + const isMatch = await comparePassword({ password: account.password }, password, { + compare, + }).catch((err) => { + logger.error('[requirePasswordConfirmation]', err); + return false; + }); + + if (!isMatch) { + return denyPasswordConfirmation(req, res, tag); + } + + return true; + }; + + /** Lists the authenticated user's registered passkeys. */ + const listPasskeys: PasskeyHandlers['listPasskeys'] = async (req, res) => { + if (!requirePasskeysEnabled(res)) { + return; + } + + try { + const passkeys = await findPasskeysByUser(req.user.id); + return res.status(200).json({ passkeys: passkeys.map(serializePasskey) }); + } catch (err) { + logger.error('[listPasskeys]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** Issues a registration challenge for the authenticated user. */ + const registerPasskeyOptions: PasskeyHandlers['registerPasskeyOptions'] = async (req, res) => { + const config = requirePasskeysEnabled(res); + if (!config) { + return; + } + + if (!requireLocalAccount(req, res)) { + return; + } + + if (!(await requirePasswordConfirmation(req, res, { tag: REGISTRATION_STEP_UP }))) { + return; + } + + try { + const existingCredentials = await findPasskeysByUser(req.user.id); + if (existingCredentials.length >= MAX_PASSKEYS_PER_USER) { + return res.status(409).json({ message: 'Passkey limit reached' }); + } + + const options = await createPasskeyRegistrationOptions({ + config, + store: getChallengeStore(), + user: { + id: req.user.id, + email: req.user.email, + name: req.user.name, + username: req.user.username, + }, + existingCredentials, + }); + + return res.status(200).json(options); + } catch (err) { + logger.error('[registerPasskeyOptions]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** + * Verifies an attestation and stores the credential against the authenticated user. + * + * The step-up is repeated here rather than only on the options step because + * `createPasskey` is the durable write, and gating only the challenge would leave + * the write path itself uncontrolled. + */ + const registerPasskeyVerify: PasskeyHandlers['registerPasskeyVerify'] = async (req, res) => { + const config = requirePasskeysEnabled(res); + if (!config) { + return; + } + + if (!requireLocalAccount(req, res)) { + return; + } + + if (!(await requirePasswordConfirmation(req, res, { tag: REGISTRATION_STEP_UP }))) { + return; + } + + try { + const { credential, name } = req.body ?? {}; + if (!credential || typeof credential !== 'object') { + return res.status(400).json({ message: 'Missing credential' }); + } + + if ((await countPasskeysByUser(req.user.id)) >= MAX_PASSKEYS_PER_USER) { + return res.status(409).json({ message: 'Passkey limit reached' }); + } + + const verified = await verifyPasskeyRegistration({ + config, + store: getChallengeStore(), + userId: req.user.id, + response: credential, + }); + + if (!verified) { + return res.status(400).json({ message: 'Passkey registration could not be verified' }); + } + + if (await findPasskeyByCredentialId(verified.credentialId)) { + return res.status(409).json({ message: 'This passkey is already registered' }); + } + + const trimmedName = typeof name === 'string' ? name.trim() : ''; + const passkey = await createPasskey({ + user: req.user.id, + credentialId: verified.credentialId, + publicKey: verified.publicKey, + counter: verified.counter, + transports: verified.transports, + deviceType: verified.deviceType, + backedUp: verified.backedUp, + name: + trimmedName.slice(0, MAX_PASSKEY_NAME_LENGTH) || defaultPasskeyName(verified.transports), + }); + + return res.status(201).json({ passkey: serializePasskey(passkey) }); + } catch (err) { + if (isDuplicateKeyError(err as MongoWriteError)) { + return res.status(409).json({ message: 'This passkey is already registered' }); + } + logger.error('[registerPasskeyVerify]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** Renames one of the authenticated user's passkeys. */ + const updatePasskey: PasskeyHandlers['updatePasskey'] = async (req, res) => { + if (!requirePasskeysEnabled(res)) { + return; + } + + try { + const name = typeof req.body?.name === 'string' ? req.body.name.trim() : ''; + if (!name) { + return res.status(400).json({ message: 'Name is required' }); + } + + const passkey = await renamePasskey( + req.params.passkeyId, + req.user.id, + name.slice(0, MAX_PASSKEY_NAME_LENGTH), + ); + + if (!passkey) { + return res.status(404).json({ message: 'Passkey not found' }); + } + + return res.status(200).json({ passkey: serializePasskey(passkey) }); + } catch (err) { + logger.error('[updatePasskey]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** + * Removes one of the authenticated user's passkeys. + * + * Password-confirmed for the same reason enrollment is: a stolen access token + * must not be able to strip a login factor the account still depends on. + * + * The gate is skipped for an account carrying no password hash. That looks like a + * hole and is not one. An SSO or LDAP account can never satisfy a password gate, + * and a passkey enrolled on one before the provider check existed would otherwise + * be stranded with no UI or API able to remove it. Allowing the removal grants an + * attacker nothing either: `authenticatePasskey` already refuses a credential + * whose owner is not a local account, so it is not a usable sign-in factor. + */ + const removePasskey: PasskeyHandlers['removePasskey'] = async (req, res) => { + if (!requirePasskeysEnabled(res)) { + return; + } + + if ( + !(await requirePasswordConfirmation(req, res, { + tag: DELETION_STEP_UP, + allowPasswordless: true, + })) + ) { + return; + } + + try { + const result = await deletePasskey(req.params.passkeyId, req.user.id); + if (!result?.deletedCount) { + return res.status(404).json({ message: 'Passkey not found' }); + } + return res.status(200).json({ message: 'Passkey deleted' }); + } catch (err) { + logger.error('[removePasskey]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** + * Issues an authentication challenge to an anonymous caller. No credential list + * is returned, so the response is identical whether or not an account exists. + */ + const loginPasskeyOptions: PasskeyHandlers['loginPasskeyOptions'] = async (_req, res) => { + const config = requirePasskeysEnabled(res); + if (!config) { + return; + } + + try { + const { options, sessionId } = await createPasskeyAuthenticationOptions({ + config, + store: getChallengeStore(), + }); + return res.status(200).json({ options, sessionId }); + } catch (err) { + logger.error('[loginPasskeyOptions]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + /** + * Verifies an assertion and, on success, populates `req.user` with the + * credential's owner. Handing off to the shared `loginController` keeps passkey + * sign-in identical to password sign-in for 2FA gating and token issuance. + */ + const authenticatePasskey: PasskeyHandlers['authenticatePasskey'] = async (req, res, next) => { + const config = requirePasskeysEnabled(res); + if (!config) { + return; + } + + const failure = (): Response => + res.status(401).json({ message: 'Passkey authentication failed' }); + + try { + const { credential, sessionId } = req.body ?? {}; + if (!credential || typeof credential !== 'object' || typeof sessionId !== 'string') { + return res.status(400).json({ message: 'Missing credential' }); + } + + const passkey = await findPasskeyByCredentialId(credential.id); + if (!passkey) { + return failure(); + } + + const userHandle = decodeUserHandle(credential.response?.userHandle); + if (userHandle && userHandle !== passkey.user.toString()) { + logger.warn('[authenticatePasskey] User handle does not match the credential owner'); + return failure(); + } + + const result = await verifyPasskeyAuthentication({ + config, + store: getChallengeStore(), + sessionId, + response: credential, + credential: { + credentialId: passkey.credentialId, + publicKey: passkey.publicKey, + counter: passkey.counter, + transports: passkey.transports, + }, + }); + + if (!result) { + return failure(); + } + + const user = await getUserById(passkey.user.toString()); + if (!user) { + return failure(); + } + + if (!isLocalAccount(user)) { + logger.warn( + '[authenticatePasskey] Rejected a passkey belonging to a non-local account; the identity provider must be used', + ); + return failure(); + } + + /** Shared with the password strategy so both factors apply one account policy. */ + await grandfatherLegacyEmailVerification({ updateUser }, user); + + const unverifiedAllowed = isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN); + if (user.expiresAt && unverifiedAllowed) { + await updateUser(user._id || user.id, {}); + } + if (!user.emailVerified && !unverifiedAllowed) { + logger.warn('[authenticatePasskey] Rejected unverified email login'); + return failure(); + } + + /** + * The counter write is the compare-and-swap for clone detection: losing it means + * another assertion already consumed this counter value, so this one is a replay + * or a clone even though the signature verified. + */ + const counterAdvanced = await recordPasskeyUse(passkey.credentialId, result.newCounter); + if (!counterAdvanced) { + logger.warn( + '[authenticatePasskey] Rejected an assertion that did not advance the signature counter', + ); + return failure(); + } + + req.user = user; + + /** + * `checkBan` defaults `next` to a no-op, so calling it bare would swallow an + * internal failure and leave `req.banned` unset: the request would go on to be + * issued tokens. Capture the error the middleware chain would have propagated + * and refuse instead, so a ban check that cannot complete never admits anyone. + */ + let banError: Error | undefined; + await checkBan(req, res, (err) => { + banError = err; + }); + if (banError) { + logger.error('[authenticatePasskey] Ban check failed to complete', banError); + return res.headersSent ? undefined : failure(); + } + if (req.banned) { + return; + } + + return next(); + } catch (err) { + logger.error('[authenticatePasskey]', err); + return res.status(500).json({ message: 'Something went wrong' }); + } + }; + + return { + listPasskeys, + updatePasskey, + removePasskey, + authenticatePasskey, + loginPasskeyOptions, + registerPasskeyOptions, + registerPasskeyVerify, + }; +} diff --git a/packages/api/src/auth/passwordReset.spec.ts b/packages/api/src/auth/passwordReset.spec.ts index cd137f88b9..311f56dc34 100644 --- a/packages/api/src/auth/passwordReset.spec.ts +++ b/packages/api/src/auth/passwordReset.spec.ts @@ -77,7 +77,7 @@ describe('commitPasswordReset', () => { await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); expect(deps.updateUser).toHaveBeenCalledWith( 'user-reset', - { password: 'hashed-password' }, + { password: 'hashed-password', credentialsChangedAt: expect.any(Date) }, { email: 'user@example.com' }, ); }); diff --git a/packages/api/src/auth/passwordReset.ts b/packages/api/src/auth/passwordReset.ts index 79df6c1211..d4872f6fe2 100644 --- a/packages/api/src/auth/passwordReset.ts +++ b/packages/api/src/auth/passwordReset.ts @@ -22,7 +22,7 @@ export interface PasswordResetDeps { getUserById: (userId: string, select: string) => Promise; updateUser: ( userId: string, - update: { password: string }, + update: { password: string; credentialsChangedAt: Date }, expectedState: { email: string }, ) => Promise; deleteTokens: (query: { userId: string; type: string }) => Promise; @@ -106,7 +106,8 @@ export async function commitPasswordReset( const user = await deps.updateUser( input.userId, - { password: deps.hashPassword(input.password) }, + /** Stamped with the new password so access tokens issued before the reset stop verifying */ + { password: deps.hashPassword(input.password), credentialsChangedAt: new Date() }, { email: account.email }, ); if (!user) { diff --git a/packages/api/src/auth/verification.spec.ts b/packages/api/src/auth/verification.spec.ts new file mode 100644 index 0000000000..70a5ef3443 --- /dev/null +++ b/packages/api/src/auth/verification.spec.ts @@ -0,0 +1,131 @@ +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { createMethods, createModels } from '@librechat/data-schemas'; +import type { IUser } from '@librechat/data-schemas'; +import type { LegacyVerificationDeps, UserDocumentId } from './verification'; +import { grandfatherLegacyEmailVerification, verificationEnabledTimestamp } from './verification'; + +/** Either side of the cutoff, expressed the way Mongo hands the field back. */ +const BEFORE_CUTOFF = new Date((verificationEnabledTimestamp - 86_400) * 1000); +const AFTER_CUTOFF = new Date((verificationEnabledTimestamp + 86_400) * 1000); +const EMAIL_KEYS = ['EMAIL_SERVICE', 'EMAIL_HOST', 'EMAIL_FROM', 'MAILGUN_API_KEY'] as const; + +let mongoServer: MongoMemoryServer; +let methods: ReturnType; +let deps: LegacyVerificationDeps & { updateUser: jest.Mock }; +let savedEnv: Partial>; + +async function createUser(createdAt: Date, emailVerified = false): Promise { + const doc = await mongoose.models.User.create({ + email: `user-${new mongoose.Types.ObjectId().toString()}@example.com`, + provider: 'local', + emailVerified, + }); + await mongoose.models.User.collection.updateOne({ _id: doc._id }, { $set: { createdAt } }); + return (await methods.getUserById(doc._id.toString())) as IUser; +} + +async function storedVerification(user: IUser): Promise { + return (await methods.getUserById(user._id.toString()))?.emailVerified; +} + +function configureEmail(enabled: boolean): void { + if (enabled) { + process.env.EMAIL_SERVICE = 'smtp'; + process.env.EMAIL_FROM = 'noreply@example.com'; + } +} + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + createModels(mongoose); + methods = createMethods(mongoose); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); +}); + +beforeEach(async () => { + savedEnv = Object.fromEntries(EMAIL_KEYS.map((key) => [key, process.env[key]])); + for (const key of EMAIL_KEYS) { + delete process.env[key]; + } + deps = { + updateUser: jest.fn((userId: UserDocumentId, update: { emailVerified: boolean }) => + methods.updateUser(userId.toString(), update), + ), + }; + await mongoose.models.User.deleteMany({}); +}); + +afterEach(() => { + for (const key of EMAIL_KEYS) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } +}); + +describe('grandfatherLegacyEmailVerification', () => { + it('verifies a pre-cutoff account when no email is configured', async () => { + const user = await createUser(BEFORE_CUTOFF); + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(true); + expect(deps.updateUser).toHaveBeenCalledWith(user._id, { emailVerified: true }); + expect(user.emailVerified).toBe(true); + expect(await storedVerification(user)).toBe(true); + }); + + it('leaves a post-cutoff account unverified', async () => { + const user = await createUser(AFTER_CUTOFF); + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(false); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(user.emailVerified).toBe(false); + }); + + it('leaves a pre-cutoff account alone when email is configured', async () => { + configureEmail(true); + const user = await createUser(BEFORE_CUTOFF); + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(false); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(await storedVerification(user)).toBe(false); + }); + + it('short-circuits an already verified account without writing', async () => { + const user = await createUser(BEFORE_CUTOFF, true); + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(true); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('does not verify when createdAt is unreadable', async () => { + const user = { + _id: new mongoose.Types.ObjectId(), + emailVerified: false, + createdAt: 'not-a-date', + }; + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(false); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('refuses a missing user', async () => { + await expect(grandfatherLegacyEmailVerification(deps, null)).resolves.toBe(false); + }); + + it('falls back to id when the document has no _id', async () => { + const stored = await createUser(BEFORE_CUTOFF); + const user = { id: stored._id.toString(), emailVerified: false, createdAt: BEFORE_CUTOFF }; + + await expect(grandfatherLegacyEmailVerification(deps, user)).resolves.toBe(true); + expect(deps.updateUser).toHaveBeenCalledWith(user.id, { emailVerified: true }); + expect(await storedVerification(stored)).toBe(true); + }); +}); diff --git a/packages/api/src/auth/verification.ts b/packages/api/src/auth/verification.ts new file mode 100644 index 0000000000..1551590321 --- /dev/null +++ b/packages/api/src/auth/verification.ts @@ -0,0 +1,56 @@ +import { checkEmailConfig } from '~/utils'; + +/** Unix timestamp for 2024-06-07 15:20:18 Eastern Time, when verification became mandatory. */ +export const verificationEnabledTimestamp: number = 1717788018; + +/** Identifier a user document is addressed by: `_id` on a document, `id` on a serialized one. */ +export type UserDocumentId = string | { toString(): string }; + +export interface LegacyVerificationUser { + _id?: UserDocumentId; + id?: string; + emailVerified?: boolean; + createdAt?: Date | string; +} + +export interface LegacyVerificationDeps { + updateUser: ( + userId: UserDocumentId, + update: { emailVerified: boolean }, + ) => Promise; +} + +/** + * Accounts created before verification was mandatory were never given a way to verify, + * so on a deployment with no email configured they would be locked out for good. Marking + * them verified as they sign in is the compatibility path. + * + * This has to apply to every login method: gating it per strategy means the same account + * is accepted by one factor and refused by another. + * + * Mutates `user.emailVerified` so callers can keep reading it after the await. + * Resolves whether the account counts as verified afterwards. + */ +export async function grandfatherLegacyEmailVerification( + deps: LegacyVerificationDeps, + user: LegacyVerificationUser | null | undefined, +): Promise { + if (user?.emailVerified) { + return true; + } + if (!user || checkEmailConfig()) { + return false; + } + + const createdAtMs = new Date(user.createdAt ?? NaN).getTime(); + if (!Number.isFinite(createdAtMs)) { + return false; + } + if (Math.floor(createdAtMs / 1000) >= verificationEnabledTimestamp) { + return false; + } + + await deps.updateUser((user._id ?? user.id) as UserDocumentId, { emailVerified: true }); + user.emailVerified = true; + return true; +} diff --git a/packages/client/src/components/AlertDialog.spec.tsx b/packages/client/src/components/AlertDialog.spec.tsx new file mode 100644 index 0000000000..e0e397c5e9 --- /dev/null +++ b/packages/client/src/components/AlertDialog.spec.tsx @@ -0,0 +1,40 @@ +import React from 'react'; +import '@testing-library/jest-dom'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { + AlertDialog, + AlertDialogContent, + AlertDialogDescription, + AlertDialogTitle, + AlertDialogTrigger, +} from './AlertDialog'; +import { OGDialog, OGDialogContent, OGDialogDescription, OGDialogTitle } from './OriginalDialog'; + +describe('AlertDialog dialog depth', () => { + it('renders its portal above an open OGDialog', () => { + render( + + + Passkeys + Manage passkeys + + Remove + + Remove passkey? + This cannot be undone. + + + + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Remove' })); + const alertDialog = screen.getByRole('alertdialog', { name: 'Remove passkey?' }); + const portalLayer = alertDialog.parentElement; + const overlay = alertDialog.previousElementSibling; + + expect(portalLayer).toHaveStyle({ zIndex: 190 }); + expect(overlay).toHaveStyle({ zIndex: 190 }); + expect(alertDialog).toHaveStyle({ zIndex: 200 }); + }); +}); diff --git a/packages/client/src/components/AlertDialog.tsx b/packages/client/src/components/AlertDialog.tsx index b0a2946e58..4b957750fd 100644 --- a/packages/client/src/components/AlertDialog.tsx +++ b/packages/client/src/components/AlertDialog.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import { JSX } from 'react/jsx-runtime'; import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'; +import { useDialogDepth } from './OriginalDialog'; import { cn } from '~/utils'; const AlertDialog: React.FC = AlertDialogPrimitive.Root; @@ -11,28 +12,42 @@ const AlertDialogTrigger: React.ForwardRefExoticComponent< type AlertPortalProps = AlertDialogPrimitive.AlertDialogPortalProps & { className?: string }; -const AlertDialogPortal = ({ className = '', children, ...props }: AlertPortalProps) => ( - -
- {children} -
-
-); +const AlertDialogPortal = ({ className = '', children, ...props }: AlertPortalProps) => { + const dialogDepth = useDialogDepth(); + const zIndex = dialogDepth > 0 ? 190 + (dialogDepth - 1) * 60 : 50; + + return ( + +
+ {children} +
+
+ ); +}; AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName; const AlertDialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef ->(({ className = '', ...props }, ref) => ( - -)); +>(({ className = '', style, ...props }, ref) => { + const dialogDepth = useDialogDepth(); + const zIndex = dialogDepth > 0 ? 190 + (dialogDepth - 1) * 60 : 50; + + return ( + + ); +}); AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName; const AlertDialogContent: React.ForwardRefExoticComponent< @@ -41,21 +56,27 @@ const AlertDialogContent: React.ForwardRefExoticComponent< > = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef ->(({ className = '', ...props }, ref) => ( - - - - -)); +>(({ className = '', style, ...props }, ref) => { + const dialogDepth = useDialogDepth(); + const zIndex = dialogDepth > 0 ? 200 + (dialogDepth - 1) * 60 : 50; + + return ( + + + + + ); +}); AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName; const AlertDialogHeader: { diff --git a/packages/client/src/svgs/PasskeyIcon.tsx b/packages/client/src/svgs/PasskeyIcon.tsx new file mode 100644 index 0000000000..cac833582b --- /dev/null +++ b/packages/client/src/svgs/PasskeyIcon.tsx @@ -0,0 +1,24 @@ +/** + * PasskeyIcon Component + * + * The FIDO Alliance passkey mark, used so the sign-in affordance is + * recognizable across services. + * + * Source: https://www.passkeys.com/icons, FIDO Alliance, free to use. + */ +import React from 'react'; +import { cn } from '~/utils'; + +export default function PasskeyIcon({ className }: { className?: string }): React.JSX.Element { + return ( + + ); +} diff --git a/packages/client/src/svgs/index.ts b/packages/client/src/svgs/index.ts index 7c0a8e4cee..1d1ba63de5 100644 --- a/packages/client/src/svgs/index.ts +++ b/packages/client/src/svgs/index.ts @@ -26,6 +26,7 @@ export { default as GithubIcon } from './GithubIcon'; export { default as DiscordIcon } from './DiscordIcon'; export { default as AppleIcon } from './AppleIcon'; export { default as SamlIcon } from './SamlIcon'; +export { default as PasskeyIcon } from './PasskeyIcon'; export { default as AnthropicIcon } from './AnthropicIcon'; export { default as SendIcon } from './SendIcon'; export { default as LinkIcon } from './LinkIcon'; diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts index f2c3a3bfcf..cebb40f6bd 100644 --- a/packages/data-provider/src/api-endpoints.ts +++ b/packages/data-provider/src/api-endpoints.ts @@ -582,6 +582,14 @@ export const disableTwoFactor = () => `${BASE_URL}/api/auth/2fa/disable`; export const regenerateBackupCodes = () => `${BASE_URL}/api/auth/2fa/backup/regenerate`; export const verifyTwoFactorTemp = () => `${BASE_URL}/api/auth/2fa/verify-temp`; +// Passkey (WebAuthn) Endpoints +export const passkeys = () => `${BASE_URL}/api/auth/passkey`; +export const passkey = (passkeyId: string) => `${passkeys()}/${encodeURIComponent(passkeyId)}`; +export const passkeyRegistrationOptions = () => `${passkeys()}/register/options`; +export const passkeyRegistrationVerify = () => `${passkeys()}/register/verify`; +export const passkeyLoginOptions = () => `${passkeys()}/login/options`; +export const passkeyLoginVerify = () => `${passkeys()}/login/verify`; + /* Memories */ export const memories = () => `${BASE_URL}/api/memories`; export const memory = (key: string, agentId?: string) => diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index ad77537b1b..61b529dc7c 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -2640,6 +2640,7 @@ export type TStartupConfig = { openidLoginEnabled: boolean; appleLoginEnabled: boolean; samlLoginEnabled: boolean; + passkeyLoginEnabled: boolean; openidLabel: string; openidImageUrl: string; openidAutoRedirect: boolean; @@ -3914,6 +3915,10 @@ export enum CacheKeys { * Key for admin panel OAuth exchange codes (one-time-use, short TTL). */ ADMIN_OAUTH_EXCHANGE = 'ADMIN_OAUTH_EXCHANGE', + /** + * Key for pending WebAuthn (passkey) ceremony challenges (one-time-use, short TTL). + */ + PASSKEY_CHALLENGE = 'PASSKEY_CHALLENGE', } export const AUTH_USER_DOC_BY_ID_PREFIX = 'auth-user-doc-byid'; @@ -4624,6 +4629,9 @@ export function splitToolCallName( } /** Maximum explicit subagent hops allowed from any root agent at runtime. */ +/** Upper bound on WebAuthn credentials a single user may register. */ +export const MAX_PASSKEYS_PER_USER = 20; + export const MAX_SUBAGENT_DEPTH = 5; /** Maximum unique explicit subagent targets that may be loaded at runtime. */ diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts index e143943468..ca58b92621 100644 --- a/packages/data-provider/src/data-service.ts +++ b/packages/data-provider/src/data-service.ts @@ -1603,6 +1603,47 @@ export function verifyTwoFactorTemp( return request.post(endpoints.verifyTwoFactorTemp(), payload); } +// Passkeys (WebAuthn) +export function getPasskeys(): Promise { + return request.get(endpoints.passkeys()); +} + +export function getPasskeyRegistrationOptions( + payload: t.TPasskeyRegistrationOptionsRequest, +): Promise { + return request.post(endpoints.passkeyRegistrationOptions(), payload); +} + +export function verifyPasskeyRegistration( + payload: t.TVerifyPasskeyRegistrationRequest, +): Promise { + return request.post(endpoints.passkeyRegistrationVerify(), payload); +} + +export function getPasskeyLoginOptions(): Promise { + return request.post(endpoints.passkeyLoginOptions(), {}); +} + +export function verifyPasskeyLogin( + payload: t.TVerifyPasskeyLoginRequest, +): Promise { + return request.post(endpoints.passkeyLoginVerify(), payload); +} + +export function renamePasskey({ + passkeyId, + name, +}: t.TRenamePasskeyRequest): Promise { + return request.patch(endpoints.passkey(passkeyId), { name }); +} + +export function deletePasskey({ + passkeyId, + password, +}: t.TDeletePasskeyRequest): Promise<{ message: string }> { + return request.deleteWithOptions(endpoints.passkey(passkeyId), { data: { password } }); +} + /* Memories */ export const getMemories = (): Promise => { return request.get(endpoints.memories()); diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts index 985251ef53..6856c060bf 100644 --- a/packages/data-provider/src/keys.ts +++ b/packages/data-provider/src/keys.ts @@ -15,6 +15,7 @@ export enum QueryKeys { conversationTraceRecords = 'conversationTraceRecords', conversationTraceRecord = 'conversationTraceRecord', user = 'user', + passkeys = 'passkeys', name = 'name', // user key name models = 'models', balance = 'balance', @@ -148,6 +149,10 @@ export enum MutationKeys { updateRole = 'updateRole', enableTwoFactor = 'enableTwoFactor', verifyTwoFactor = 'verifyTwoFactor', + registerPasskey = 'registerPasskey', + renamePasskey = 'renamePasskey', + deletePasskey = 'deletePasskey', + passkeyLogin = 'passkeyLogin', updateMemoryPreferences = 'updateMemoryPreferences', createProject = 'createProject', updateProject = 'updateProject', diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts index c5ee47d802..4e6d4a6926 100644 --- a/packages/data-provider/src/types.ts +++ b/packages/data-provider/src/types.ts @@ -802,6 +802,153 @@ export type TVerify2FATempResponse = { message?: string; }; +/* Passkeys (WebAuthn) */ + +/** + * WebAuthn ceremony payloads, mirroring the W3C `*JSON` dictionaries that the + * browser's `PublicKeyCredential` serializes to. They are declared here rather + * than imported so `librechat-data-provider` stays dependency-free; the client + * hands them straight to `@simplewebauthn/browser`, which validates the shape. + */ +export type TPasskeyTransport = + | 'ble' + | 'cable' + | 'hybrid' + | 'internal' + | 'nfc' + | 'smart-card' + | 'usb'; + +export type TPasskeyCredentialDescriptor = { + id: string; + type: 'public-key'; + transports?: TPasskeyTransport[]; +}; + +/** https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson */ +export type TPasskeyCreationOptions = { + rp: { id?: string; name: string }; + user: { id: string; name: string; displayName: string }; + challenge: string; + pubKeyCredParams: Array<{ alg: number; type: 'public-key' }>; + timeout?: number; + excludeCredentials?: TPasskeyCredentialDescriptor[]; + authenticatorSelection?: { + authenticatorAttachment?: 'platform' | 'cross-platform'; + residentKey?: 'discouraged' | 'preferred' | 'required'; + requireResidentKey?: boolean; + userVerification?: 'discouraged' | 'preferred' | 'required'; + }; + attestation?: 'none' | 'indirect' | 'direct' | 'enterprise'; + hints?: string[]; +}; + +/** https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson */ +export type TPasskeyRequestOptions = { + challenge: string; + timeout?: number; + rpId?: string; + allowCredentials?: TPasskeyCredentialDescriptor[]; + userVerification?: 'discouraged' | 'preferred' | 'required'; + hints?: string[]; +}; + +/** https://w3c.github.io/webauthn/#dictdef-registrationresponsejson */ +export type TPasskeyRegistrationResponse = { + id: string; + rawId: string; + type: 'public-key'; + authenticatorAttachment?: 'platform' | 'cross-platform'; + clientExtensionResults: Record; + response: { + clientDataJSON: string; + attestationObject: string; + authenticatorData?: string; + transports?: TPasskeyTransport[]; + publicKeyAlgorithm?: number; + publicKey?: string; + }; +}; + +/** https://w3c.github.io/webauthn/#dictdef-authenticationresponsejson */ +export type TPasskeyAuthenticationResponse = { + id: string; + rawId: string; + type: 'public-key'; + authenticatorAttachment?: 'platform' | 'cross-platform'; + clientExtensionResults: Record; + response: { + clientDataJSON: string; + authenticatorData: string; + signature: string; + userHandle?: string; + }; +}; + +/** + * A registered credential as exposed to the client. Deliberately excludes the + * public key and credential ID: the UI only needs to identify and label it. + */ +export type TPasskey = { + id: string; + name: string; + deviceType: 'singleDevice' | 'multiDevice'; + backedUp: boolean; + transports: TPasskeyTransport[]; + createdAt: string; + lastUsedAt: string | null; +}; + +export type TPasskeysResponse = { + passkeys: TPasskey[]; +}; + +export type TPasskeyResponse = { + passkey: TPasskey; +}; + +/** + * Enrollment is password-confirmed on both steps: a passkey is a durable + * single-factor login, so an access token alone must not be enough to mint one. + */ +export type TPasskeyRegistrationOptionsRequest = { + password: string; +}; + +export type TVerifyPasskeyRegistrationRequest = TPasskeyRegistrationOptionsRequest & { + credential: TPasskeyRegistrationResponse; + name?: string; +}; + +export type TPasskeyAuthenticationOptionsResponse = { + options: TPasskeyRequestOptions; + /** Opaque handle tying the assertion back to its server-side challenge. */ + sessionId: string; +}; + +export type TVerifyPasskeyLoginRequest = { + credential: TPasskeyAuthenticationResponse; + sessionId: string; +}; + +export type TRenamePasskeyRequest = { + passkeyId: string; + name: string; +}; + +/** + * Removal is password-confirmed too: deleting a passkey takes a login factor + * away, so a bearer token alone must not be enough. + * + * `password` is optional because an account provisioned by an identity provider + * has no local password to confirm with, and its stranded credentials must stay + * removable. The server only waives the check when no password hash exists. + */ +export type TDeletePasskeyRequest = { + passkeyId: string; + password?: string; +}; + export type TDisable2FARequest = TOTPVerificationPayload; export type TDisable2FAResponse = { diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts index 173729a9df..a8f1abcf1d 100644 --- a/packages/data-schemas/src/methods/index.ts +++ b/packages/data-schemas/src/methods/index.ts @@ -12,6 +12,7 @@ import { type RefreshTokenBridgeMethods, } from './refreshTokenBridge'; import { createSessionMethods, DEFAULT_REFRESH_TOKEN_EXPIRY, type SessionMethods } from './session'; +import { createPasskeyMethods, type PasskeyMethods } from './passkey'; import { createUserMethods, DEFAULT_SESSION_EXPIRY, type UserMethods } from './user'; import { createFileMethods, type FileMethods, type FileOwnerScope } from './file'; import { createTokenMethods, type TokenMethods } from './token'; @@ -231,6 +232,7 @@ export type AllMethods = UserMethods & TokenMethods & RefreshTokenBridgeMethods & OpenIDRefreshFlightMethods & + PasskeyMethods & RoleMethods & KeyMethods & FileMethods & @@ -461,6 +463,7 @@ export function createMethods( ...createTokenMethods(mongoose), ...createRefreshTokenBridgeMethods(mongoose), ...createOpenIDRefreshFlightMethods(mongoose), + ...createPasskeyMethods(mongoose), ...roleMethods, ...createKeyMethods(mongoose), ...createFileMethods(mongoose), @@ -513,6 +516,7 @@ export function createMethods( export type { UserMethods, + PasskeyMethods, SessionMethods, TokenMethods, RefreshTokenBridgeMethods, diff --git a/packages/data-schemas/src/methods/passkey.spec.ts b/packages/data-schemas/src/methods/passkey.spec.ts new file mode 100644 index 0000000000..7eb142f7eb --- /dev/null +++ b/packages/data-schemas/src/methods/passkey.spec.ts @@ -0,0 +1,282 @@ +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import type * as t from '~/types'; +import { createPasskeyMethods } from './passkey'; +import passkeySchema from '~/schema/passkey'; + +jest.mock('~/config/winston', () => ({ + error: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + debug: jest.fn(), +})); + +let mongoServer: MongoMemoryServer; +let methods: ReturnType; + +const userId = new mongoose.Types.ObjectId(); +const otherUserId = new mongoose.Types.ObjectId(); + +const passkeyData = (overrides: Partial = {}): t.PasskeyCreateData => ({ + user: userId, + credentialId: 'credential-one', + publicKey: Buffer.from([1, 2, 3]), + counter: 0, + transports: ['internal'], + deviceType: 'multiDevice', + backedUp: true, + name: 'This device', + ...overrides, +}); + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + if (!mongoose.models.Passkey) { + mongoose.model('Passkey', passkeySchema); + } + methods = createPasskeyMethods(mongoose); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); +}); + +beforeEach(async () => { + await mongoose.connection.dropDatabase(); + await mongoose.models.Passkey.syncIndexes(); +}); + +describe('createPasskey', () => { + it('stores the credential with its public key intact', async () => { + const created = await methods.createPasskey(passkeyData()); + + expect(created.credentialId).toBe('credential-one'); + expect(Buffer.from(created.publicKey).equals(Buffer.from([1, 2, 3]))).toBe(true); + expect(created.backedUp).toBe(true); + expect(created.lastUsedAt).toBeNull(); + expect(created.createdAt).toBeInstanceOf(Date); + }); + + it('rejects a credential ID that is already registered', async () => { + await methods.createPasskey(passkeyData()); + + await expect( + methods.createPasskey(passkeyData({ user: otherUserId, name: 'Someone else' })), + ).rejects.toThrow(); + }); + + it('builds the unique credential index itself when auto-indexing never ran', async () => { + await mongoose.connection.dropDatabase(); + const freshMethods = createPasskeyMethods(mongoose); + + await freshMethods.createPasskey(passkeyData()); + + await expect( + freshMethods.createPasskey(passkeyData({ user: otherUserId, name: 'Someone else' })), + ).rejects.toThrow(/duplicate key/); + expect(await mongoose.models.Passkey.countDocuments({ credentialId: 'credential-one' })).toBe( + 1, + ); + }); +}); + +describe('findPasskeysByUser', () => { + it('returns only the requested user credentials, newest first', async () => { + await methods.createPasskey(passkeyData({ credentialId: 'a', name: 'First' })); + await methods.createPasskey(passkeyData({ credentialId: 'b', name: 'Second' })); + await methods.createPasskey( + passkeyData({ credentialId: 'c', name: 'Other user', user: otherUserId }), + ); + + const found = await methods.findPasskeysByUser(userId.toString()); + + expect(found.map((passkey) => passkey.name)).toEqual(['Second', 'First']); + expect(await methods.countPasskeysByUser(userId.toString())).toBe(2); + }); +}); + +describe('findPasskeyByCredentialId', () => { + it('resolves the owning user without a user scope, as sign-in requires', async () => { + await methods.createPasskey(passkeyData()); + + const found = await methods.findPasskeyByCredentialId('credential-one'); + + expect(found?.user.toString()).toBe(userId.toString()); + }); + + it('returns null for an unknown credential', async () => { + expect(await methods.findPasskeyByCredentialId('nope')).toBeNull(); + }); + + /** + * `lean()` hands back a BSON `Binary`, and `new Uint8Array(binary)` yields + * zero bytes, which would make every signature verification fail. Assert on + * the read path, not the write path, since only the read path is affected. + */ + it('returns the public key as a Buffer that survives Uint8Array conversion', async () => { + const publicKey = Buffer.from([9, 8, 7, 6, 5]); + await methods.createPasskey(passkeyData({ publicKey })); + + const found = await methods.findPasskeyByCredentialId('credential-one'); + + expect(Buffer.isBuffer(found?.publicKey)).toBe(true); + expect(new Uint8Array(found!.publicKey)).toEqual(new Uint8Array(publicKey)); + }); + + it('returns Buffer public keys when listing a user credentials', async () => { + const publicKey = Buffer.from([4, 3, 2, 1]); + await methods.createPasskey(passkeyData({ publicKey })); + + const [found] = await methods.findPasskeysByUser(userId.toString()); + + expect(Buffer.isBuffer(found.publicKey)).toBe(true); + expect(new Uint8Array(found.publicKey)).toEqual(new Uint8Array(publicKey)); + }); +}); + +describe('recordPasskeyUse', () => { + it('advances the signature counter and stamps last use', async () => { + await methods.createPasskey(passkeyData()); + + await expect(methods.recordPasskeyUse('credential-one', 7)).resolves.toBe(true); + + const updated = await methods.findPasskeyByCredentialId('credential-one'); + expect(updated?.counter).toBe(7); + expect(updated?.lastUsedAt).toBeInstanceOf(Date); + }); + + it('does not regress the counter when the new value is lower', async () => { + await methods.createPasskey(passkeyData({ counter: 5 })); + + await expect(methods.recordPasskeyUse('credential-one', 3)).resolves.toBe(false); + + const updated = await methods.findPasskeyByCredentialId('credential-one'); + expect(updated?.counter).toBe(5); + expect(updated?.lastUsedAt).toBeNull(); + }); + + it('stamps last use when a counterless authenticator stays at 0', async () => { + await methods.createPasskey(passkeyData({ counter: 0 })); + + await expect(methods.recordPasskeyUse('credential-one', 0)).resolves.toBe(true); + + const updated = await methods.findPasskeyByCredentialId('credential-one'); + expect(updated?.counter).toBe(0); + expect(updated?.lastUsedAt).toBeInstanceOf(Date); + }); + + /** + * Two assertions that verified against the same stored counter must not both + * commit, otherwise a cloned authenticator is indistinguishable from the real one. + */ + it('lets only one of two assertions at the same counter win', async () => { + await methods.createPasskey(passkeyData({ counter: 5 })); + + const [first, second] = await Promise.all([ + methods.recordPasskeyUse('credential-one', 6), + methods.recordPasskeyUse('credential-one', 6), + ]); + + expect([first, second].filter(Boolean)).toHaveLength(1); + const updated = await methods.findPasskeyByCredentialId('credential-one'); + expect(updated?.counter).toBe(6); + }); + + it('reports a replay that repeats the stored counter', async () => { + await methods.createPasskey(passkeyData({ counter: 5 })); + + await expect(methods.recordPasskeyUse('credential-one', 5)).resolves.toBe(false); + }); + + it('does not throw when the credential is gone', async () => { + await expect(methods.recordPasskeyUse('missing', 1)).resolves.toBe(false); + }); + + describe('when the counter write fails', () => { + const failWrite = () => + jest.spyOn(mongoose.models.Passkey, 'updateOne').mockReturnValue({ + exec: () => Promise.reject(new Error('write failed')), + } as unknown as ReturnType); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('fails closed for a counter-capable credential', async () => { + await methods.createPasskey(passkeyData({ counter: 5 })); + failWrite(); + + await expect(methods.recordPasskeyUse('credential-one', 6)).resolves.toBe(false); + }); + + it('lets a counterless credential through, since it carries no clone signal', async () => { + await methods.createPasskey(passkeyData({ counter: 0 })); + failWrite(); + + await expect(methods.recordPasskeyUse('credential-one', 0)).resolves.toBe(true); + }); + }); +}); + +describe('renamePasskey', () => { + it('renames a credential the user owns', async () => { + const created = await methods.createPasskey(passkeyData()); + + const renamed = await methods.renamePasskey( + created._id.toString(), + userId.toString(), + 'Work laptop', + ); + + expect(renamed?.name).toBe('Work laptop'); + }); + + it('refuses to rename another user credential', async () => { + const created = await methods.createPasskey(passkeyData()); + + const renamed = await methods.renamePasskey( + created._id.toString(), + otherUserId.toString(), + 'Stolen', + ); + + expect(renamed).toBeNull(); + const untouched = await methods.findPasskeyByCredentialId('credential-one'); + expect(untouched?.name).toBe('This device'); + }); +}); + +describe('deletePasskey', () => { + it('deletes a credential the user owns', async () => { + const created = await methods.createPasskey(passkeyData()); + + const result = await methods.deletePasskey(created._id.toString(), userId.toString()); + + expect(result.deletedCount).toBe(1); + expect(await methods.findPasskeyByCredentialId('credential-one')).toBeNull(); + }); + + it('refuses to delete another user credential', async () => { + const created = await methods.createPasskey(passkeyData()); + + const result = await methods.deletePasskey(created._id.toString(), otherUserId.toString()); + + expect(result.deletedCount).toBe(0); + expect(await methods.findPasskeyByCredentialId('credential-one')).not.toBeNull(); + }); +}); + +describe('deletePasskeysByUser', () => { + it('clears every credential for the user and leaves others alone', async () => { + await methods.createPasskey(passkeyData({ credentialId: 'a' })); + await methods.createPasskey(passkeyData({ credentialId: 'b' })); + await methods.createPasskey(passkeyData({ credentialId: 'c', user: otherUserId })); + + const result = await methods.deletePasskeysByUser(userId.toString()); + + expect(result.deletedCount).toBe(2); + expect(await methods.countPasskeysByUser(otherUserId.toString())).toBe(1); + }); +}); diff --git a/packages/data-schemas/src/methods/passkey.ts b/packages/data-schemas/src/methods/passkey.ts new file mode 100644 index 0000000000..ca6891a0af --- /dev/null +++ b/packages/data-schemas/src/methods/passkey.ts @@ -0,0 +1,162 @@ +import type { DeleteResult } from 'mongoose'; +import type { IPasskey, PasskeyCreateData } from '~/types'; +import { createIndexesWithRetry } from '~/utils/retry'; +import logger from '~/config/winston'; + +export interface PasskeyMethods { + createPasskey: (data: PasskeyCreateData) => Promise; + findPasskeysByUser: (userId: string) => Promise; + findPasskeyByCredentialId: (credentialId: string) => Promise; + countPasskeysByUser: (userId: string) => Promise; + recordPasskeyUse: (credentialId: string, counter: number) => Promise; + renamePasskey: (passkeyId: string, userId: string, name: string) => Promise; + deletePasskey: (passkeyId: string, userId: string) => Promise; + deletePasskeysByUser: (userId: string) => Promise; +} + +/** The shapes a `Buffer` schema field can come back as, depending on `lean()`. */ +type StoredBinary = Buffer | Uint8Array | { buffer: Buffer }; + +/** + * `lean()` skips Mongoose casting, so a `Buffer` field arrives as the driver's + * BSON `Binary`. `new Uint8Array(binary)` silently yields zero bytes, which + * would make every signature check fail. Normalize at the data-layer boundary + * so callers can trust the declared `Buffer` type. + */ +function toBuffer(value: StoredBinary): Buffer { + if (Buffer.isBuffer(value)) { + return value; + } + if ('buffer' in value && Buffer.isBuffer(value.buffer)) { + return value.buffer; + } + return Buffer.from(value as Uint8Array); +} + +function normalizePasskey(passkey: T): T { + if (passkey?.publicKey) { + passkey.publicKey = toBuffer(passkey.publicKey as StoredBinary); + } + return passkey; +} + +export function createPasskeyMethods(mongoose: typeof import('mongoose')): PasskeyMethods { + let passkeyIndexesPromise: Promise | null = null; + + /** + * The unique `credentialId` index is what stops two concurrent registrations from + * storing the same credential. With `MONGO_AUTO_INDEX=false` the schema declaration + * alone never builds it, so it is ensured before the first write. + */ + function ensurePasskeyIndexes(): Promise { + if (!passkeyIndexesPromise) { + passkeyIndexesPromise = createIndexesWithRetry(mongoose.models.Passkey).catch((error) => { + passkeyIndexesPromise = null; + throw error; + }); + } + return passkeyIndexesPromise; + } + + /** Registers a newly verified credential for a user. */ + async function createPasskey(data: PasskeyCreateData): Promise { + await ensurePasskeyIndexes(); + const Passkey = mongoose.models.Passkey; + return (await Passkey.create(data)) as IPasskey; + } + + /** Lists a user's credentials, newest first. */ + async function findPasskeysByUser(userId: string): Promise { + const Passkey = mongoose.models.Passkey; + const passkeys = (await Passkey.find({ user: userId }) + .sort({ createdAt: -1 }) + .lean() + .exec()) as unknown as IPasskey[]; + return passkeys.map(normalizePasskey); + } + + /** + * Looks up a credential by its authenticator-supplied ID. Called before the + * caller is authenticated, so it is intentionally not scoped to a user. + */ + async function findPasskeyByCredentialId(credentialId: string): Promise { + const Passkey = mongoose.models.Passkey; + const passkey = (await Passkey.findOne({ credentialId }).lean().exec()) as IPasskey | null; + return normalizePasskey(passkey); + } + + async function countPasskeysByUser(userId: string): Promise { + const Passkey = mongoose.models.Passkey; + return await Passkey.countDocuments({ user: userId }).exec(); + } + + /** + * Persists the authenticator's signature counter after a successful assertion. + * + * For counter-capable authenticators this is the compare-and-swap that makes + * clone detection meaningful: the update only matches while the stored counter + * is still strictly below the asserted one, so of two assertions that verified + * concurrently against the same stored value exactly one can commit. The caller + * must reject the losing assertion. Authenticators that do not implement a + * counter report 0 forever and carry no clone signal, so they only restamp + * `lastUsedAt`. + * + * Returns whether this assertion won the transition. A storage error fails closed + * for counter-capable credentials: letting the sign-in through would forfeit the + * clone signal exactly when the transition cannot be proven, and a database that + * cannot take this write cannot mint the session either. A counterless credential + * has no signal to forfeit, so it is not held to the same bar. + */ + async function recordPasskeyUse(credentialId: string, counter: number): Promise { + try { + const Passkey = mongoose.models.Passkey; + const filter = + counter > 0 + ? { credentialId, counter: { $lt: counter } } + : { credentialId, counter: { $lte: 0 } }; + const result = await Passkey.updateOne(filter, { + $set: { counter, lastUsedAt: new Date() }, + }).exec(); + return result.matchedCount > 0; + } catch (error) { + logger.error('[recordPasskeyUse] Failed to persist passkey counter', error); + return counter === 0; + } + } + + async function renamePasskey( + passkeyId: string, + userId: string, + name: string, + ): Promise { + const Passkey = mongoose.models.Passkey; + return (await Passkey.findOneAndUpdate( + { _id: passkeyId, user: userId }, + { name }, + { new: true }, + ) + .lean() + .exec()) as IPasskey | null; + } + + async function deletePasskey(passkeyId: string, userId: string): Promise { + const Passkey = mongoose.models.Passkey; + return await Passkey.deleteOne({ _id: passkeyId, user: userId }).exec(); + } + + async function deletePasskeysByUser(userId: string): Promise { + const Passkey = mongoose.models.Passkey; + return await Passkey.deleteMany({ user: userId }).exec(); + } + + return { + createPasskey, + findPasskeysByUser, + findPasskeyByCredentialId, + countPasskeysByUser, + recordPasskeyUse, + renamePasskey, + deletePasskey, + deletePasskeysByUser, + }; +} diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.ts index 90c6f369d3..2fe5b49b9d 100644 --- a/packages/data-schemas/src/models/index.ts +++ b/packages/data-schemas/src/models/index.ts @@ -28,6 +28,7 @@ import { createToolCallModel } from './toolCall'; import { createAclEntryModel } from './aclEntry'; import { createAuditLogModel } from './auditLog'; import { createSessionModel } from './session'; +import { createPasskeyModel } from './passkey'; import { createBalanceModel } from './balance'; import { createMessageModel } from './message'; import { createActionModel } from './action'; @@ -53,6 +54,7 @@ export function createModels(mongoose: typeof import('mongoose')): { User: ReturnType; Token: ReturnType; Session: ReturnType; + Passkey: ReturnType; Balance: ReturnType; Conversation: ReturnType; ChatProject: ReturnType; @@ -102,6 +104,7 @@ export function createModels(mongoose: typeof import('mongoose')): { User: createUserModel(mongoose), Token: createTokenModel(mongoose), Session: createSessionModel(mongoose), + Passkey: createPasskeyModel(mongoose), Balance: createBalanceModel(mongoose), Conversation: createConversationModel(mongoose), ChatProject: createChatProjectModel(mongoose), diff --git a/packages/data-schemas/src/models/passkey.ts b/packages/data-schemas/src/models/passkey.ts new file mode 100644 index 0000000000..acdf61589f --- /dev/null +++ b/packages/data-schemas/src/models/passkey.ts @@ -0,0 +1,9 @@ +import { Model } from 'mongoose'; +import type * as t from '~/types'; +import { applyTenantIsolation } from '~/models/plugins/tenantIsolation'; +import passkeySchema from '~/schema/passkey'; + +export function createPasskeyModel(mongoose: typeof import('mongoose')): Model { + applyTenantIsolation(passkeySchema); + return mongoose.models.Passkey || mongoose.model('Passkey', passkeySchema); +} diff --git a/packages/data-schemas/src/schema/index.ts b/packages/data-schemas/src/schema/index.ts index 21f77ee052..f1d87563f9 100644 --- a/packages/data-schemas/src/schema/index.ts +++ b/packages/data-schemas/src/schema/index.ts @@ -21,6 +21,7 @@ export { default as promptGroupSchema } from './promptGroup'; export { default as openidRefreshFlightSchema } from './openidRefreshFlight'; export { default as refreshTokenBridgeSchema } from './refreshTokenBridge'; export { default as roleSchema } from './role'; +export { default as passkeySchema } from './passkey'; export { default as sessionSchema } from './session'; export { default as shareSchema } from './share'; export { default as skillSyncCredentialSchema } from './skillSyncCredential'; diff --git a/packages/data-schemas/src/schema/passkey.ts b/packages/data-schemas/src/schema/passkey.ts new file mode 100644 index 0000000000..17bce07e2d --- /dev/null +++ b/packages/data-schemas/src/schema/passkey.ts @@ -0,0 +1,57 @@ +import { Schema } from 'mongoose'; +import type { IPasskey } from '~/types'; + +const passkeySchema: Schema = new Schema( + { + user: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + credentialId: { + type: String, + required: true, + unique: true, + }, + publicKey: { + type: Buffer, + required: true, + }, + counter: { + type: Number, + required: true, + default: 0, + }, + transports: { + type: [String], + default: [], + }, + deviceType: { + type: String, + enum: ['singleDevice', 'multiDevice'], + default: 'singleDevice', + }, + backedUp: { + type: Boolean, + default: false, + }, + name: { + type: String, + required: true, + trim: true, + maxlength: 60, + }, + lastUsedAt: { + type: Date, + default: null, + }, + tenantId: { + type: String, + index: true, + }, + }, + { timestamps: true }, +); + +export default passkeySchema; diff --git a/packages/data-schemas/src/schema/user.spec.ts b/packages/data-schemas/src/schema/user.spec.ts new file mode 100644 index 0000000000..da0a20aed2 --- /dev/null +++ b/packages/data-schemas/src/schema/user.spec.ts @@ -0,0 +1,19 @@ +import userSchema from './user'; + +describe('userSchema', () => { + describe('credentialsChangedAt', () => { + it('is a Date path so a password reset can persist the access-token cutoff', () => { + const path = userSchema.path('credentialsChangedAt'); + + expect(path).toBeDefined(); + expect(path.instance).toBe('Date'); + }); + + it('is writable through a strict-mode update', () => { + const changedAt = new Date(1700000010500); + const update = userSchema.path('credentialsChangedAt').cast(changedAt); + + expect(update).toEqual(changedAt); + }); + }); +}); diff --git a/packages/data-schemas/src/schema/user.ts b/packages/data-schemas/src/schema/user.ts index 68efec7cc7..de4fbab159 100644 --- a/packages/data-schemas/src/schema/user.ts +++ b/packages/data-schemas/src/schema/user.ts @@ -121,6 +121,14 @@ const userSchema: Schema = new Schema( select: false, default: undefined, }, + /** + * Instant of the last credential change (password reset). Access tokens issued + * before it are rejected at JWT verification, so a token that outlives the reset + * cannot keep authenticating. + */ + credentialsChangedAt: { + type: Date, + }, refreshToken: { type: [SessionSchema], }, diff --git a/packages/data-schemas/src/types/index.ts b/packages/data-schemas/src/types/index.ts index 92ace38060..e8a8e9b2fa 100644 --- a/packages/data-schemas/src/types/index.ts +++ b/packages/data-schemas/src/types/index.ts @@ -11,6 +11,7 @@ export * from './openidRefreshFlight'; export * from './convo'; export * from './chatProject'; export * from './session'; +export * from './passkey'; export * from './balance'; export * from './banner'; export * from './transaction'; diff --git a/packages/data-schemas/src/types/passkey.ts b/packages/data-schemas/src/types/passkey.ts new file mode 100644 index 0000000000..6ae17da171 --- /dev/null +++ b/packages/data-schemas/src/types/passkey.ts @@ -0,0 +1,34 @@ +import type { Document, Types } from 'mongoose'; + +export type PasskeyDeviceType = 'singleDevice' | 'multiDevice'; + +export interface IPasskey extends Document { + _id: Types.ObjectId; + user: Types.ObjectId; + /** Base64URL-encoded credential ID, unique across the deployment */ + credentialId: string; + /** COSE public key bytes returned by the authenticator */ + publicKey: Buffer; + /** Signature counter, used to detect cloned authenticators */ + counter: number; + transports: string[]; + deviceType: PasskeyDeviceType; + backedUp: boolean; + /** User-supplied label shown in account settings */ + name: string; + lastUsedAt?: Date | null; + tenantId?: string; + createdAt?: Date; + updatedAt?: Date; +} + +export interface PasskeyCreateData { + user: string | Types.ObjectId; + credentialId: string; + publicKey: Buffer; + counter: number; + transports?: string[]; + deviceType: PasskeyDeviceType; + backedUp: boolean; + name: string; +} diff --git a/packages/data-schemas/src/types/user.ts b/packages/data-schemas/src/types/user.ts index 62cc0f3565..2928d227f6 100644 --- a/packages/data-schemas/src/types/user.ts +++ b/packages/data-schemas/src/types/user.ts @@ -48,6 +48,8 @@ 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; refreshToken?: Array<{ refreshToken: string; }>;