-
- {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')}
+
+
+
+
+
+
+ );
+}
+
+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')}
+
+
+
+
+
+
+
+ );
+}
+
+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