⚙️ feat: Make the Per-User Passkey Cap Configurable (#16259)

(cherry picked from commit 84180a87e2)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16259
This commit is contained in:
Marco Beretta 2026-09-25 11:34:06 +02:00 • committed by Lia
parent 4fb238d5fe
commit eefeb2a7f9
18 changed files with 501 additions and 11 deletions

View file

@ -948,6 +948,9 @@ APPLE_CALLBACK_URL=/oauth/apple/callback
# Passkeys (WebAuthn)
# Requires HTTPS in production; localhost is exempt.
ALLOW_PASSKEY_LOGIN=false
# Optional. Passkeys each account may enroll (1-100). A librechat.yaml
# `passkeys.perUserMax` overrides this; both default to 20.
# MAX_PASSKEYS_PER_USER=20
# Optional. Defaults to the hostname of DOMAIN_CLIENT. Pin this if DOMAIN_CLIENT
# may change: existing passkeys stop working when the RP ID changes.
# PASSKEY_RP_ID=

View file

@ -3,12 +3,14 @@ const { CacheKeys } = require('librechat-data-provider');
const { createPasskeyHandlers } = require('@librechat/api');
const { checkBan } = require('~/server/middleware');
const { getLogStores } = require('~/cache');
const { getAppConfig } = require('~/server/services/Config/app');
const db = require('~/models');
module.exports = createPasskeyHandlers({
checkBan,
compare: bcrypt.compare,
getChallengeCache: () => getLogStores(CacheKeys.PASSKEY_CHALLENGE),
getAppConfig,
getUserById: db.getUserById,
updateUser: db.updateUser,
createPasskey: db.createPasskey,

View file

@ -1,5 +1,7 @@
const mockCheckBan = jest.fn();
const mockGetLogStores = jest.fn();
const mockGetAppConfig = jest.fn();
jest.mock('~/server/services/Config/app', () => ({ getAppConfig: mockGetAppConfig }));
const mockModels = {
getUserById: jest.fn(),
updateUser: jest.fn(),
@ -69,6 +71,7 @@ describe('PasskeyController wiring', () => {
it('hands the model methods, bcrypt and the ban check to the handler factory', () => {
expect(deps.compare).toBe(bcrypt.compare);
expect(deps.getAppConfig).toBe(mockGetAppConfig);
for (const name of Object.keys(mockModels)) {
expect(deps[name]).toBe(mockModels[name]);
}

View file

@ -1082,3 +1082,22 @@ describe('GET /api/config', () => {
});
});
});
describe('passkey enrollment cap', () => {
it('publishes the cap normalized from YAML only after authentication', async () => {
const { AppService } = require('@librechat/data-schemas');
const appConfig = await AppService({ config: { passkeys: { perUserMax: 2 } } });
mockGetAppConfig.mockResolvedValue(appConfig);
const authenticated = await request(createApp(mockUser)).get('/api/config');
expect(authenticated.status).toBe(200);
expect(authenticated.body.maxPasskeysPerUser).toBe(2);
expect(mockGetAppConfig).toHaveBeenCalledWith(
expect.objectContaining({ userId: mockUser.id, role: mockUser.role }),
);
const anonymous = await request(createApp()).get('/api/config');
expect(anonymous.status).toBe(200);
expect(anonymous.body).not.toHaveProperty('maxPasskeysPerUser');
});
});

View file

@ -18,6 +18,7 @@ const {
resolveCodeEnvironmentMoveVersion,
isPasskeyEnabled,
buildPreLoginInterface,
resolveMaxPasskeysPerUser,
} = require('@librechat/api');
const {
DEFAULT_MCP_APP_CSP_LIMITS,
@ -159,6 +160,7 @@ function buildPostLoginPayload(appConfig) {
process.env.ALLOW_ACCOUNT_DELETION === undefined ||
isEnabled(process.env.ALLOW_ACCOUNT_DELETION),
allowEmailChange: resolveEmailChangeSettings(appConfig?.emailChange).enabled,
maxPasskeysPerUser: resolveMaxPasskeysPerUser(appConfig?.passkeys),
};
return payload;

View file

@ -22,6 +22,7 @@ import {
import type { PasskeyRemovalResult } from './PasskeyItem';
import {
useDeletePasskeyMutation,
useGetStartupConfig,
usePasskeysQuery,
useRenamePasskeyMutation,
} from '~/data-provider';
@ -48,13 +49,16 @@ function Passkeys() {
const renameAfterCloseRef = useRef<string | null>(null);
const { data, isLoading, isError } = usePasskeysQuery({ enabled: isDialogOpen });
const { data: startupConfig, refetch: refetchStartupConfig } = useGetStartupConfig();
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;
/** Falls back to the documented default while the startup config is still loading. */
const maxPasskeys = startupConfig?.maxPasskeysPerUser ?? MAX_PASSKEYS_PER_USER;
const atLimit = passkeys.length >= maxPasskeys;
/**
* Removing a passkey is password-confirmed, but an account provisioned by an
* identity provider has no password to confirm with. The server waives the
@ -161,6 +165,7 @@ function Passkeys() {
(open: boolean) => {
setDialogOpen(open);
if (open) {
void refetchStartupConfig();
return;
}
setPassword('');
@ -169,7 +174,7 @@ function Passkeys() {
renameAfterCloseRef.current = null;
clearPasswordError();
},
[clearPasswordError],
[clearPasswordError, refetchStartupConfig],
);
return (

View file

@ -5,8 +5,13 @@ import Passkeys from '../Passkeys';
const mockClearPasswordError = jest.fn();
const mockRegisterPasskey = jest.fn();
const mockRefetchStartupConfig = jest.fn();
jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => ({
data: { maxPasskeysPerUser: 20 },
refetch: mockRefetchStartupConfig,
}),
usePasskeysQuery: () => ({ data: { passkeys: [] }, isLoading: false, isError: false }),
useRenamePasskeyMutation: () => ({ mutate: jest.fn() }),
useDeletePasskeyMutation: () => ({ mutateAsync: jest.fn() }),
@ -44,6 +49,20 @@ describe('Passkeys enrollment dialog', () => {
jest.clearAllMocks();
});
it('refreshes startup configuration on each management dialog open', async () => {
const user = userEvent.setup();
render(<Passkeys />);
expect(mockRefetchStartupConfig).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Passkeys' }));
expect(mockRefetchStartupConfig).toHaveBeenCalledTimes(1);
await user.keyboard('{Escape}');
await waitFor(() =>
expect(screen.queryByRole('dialog', { name: 'Passkeys' })).not.toBeInTheDocument(),
);
await user.click(screen.getByRole('button', { name: 'Passkeys' }));
expect(mockRefetchStartupConfig).toHaveBeenCalledTimes(2);
});
it('opens password confirmation in a separate dialog and restores focus on cancel', async () => {
const user = userEvent.setup();
render(<Passkeys />);

View file

@ -9,6 +9,7 @@ import type {
} from '@playwright/test';
import { seedPasskey, deleteUserByEmail, countUserPasskeys, enableTwoFactorFlag } from '../db';
import { NEW_CHAT_PATH } from '../helpers';
import { getPrimaryE2EUser } from '../../../setup/users.mock';
/**
* Passkey sign-in and management, driven through a real WebAuthn ceremony: Chromium's
@ -423,4 +424,107 @@ test.describe('passkeys', () => {
await request.dispose();
}
});
test('a configured per-user cap hides the add control at that cap @scenario:passkey-cap-hides-add-control', async ({
browser,
playwright,
baseURL,
}) => {
test.setTimeout(60000);
const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) });
user = await createFreshUser(request);
await seedPasskey(user.email, `e2e-cap-${randomUUID()}`, 'Only key');
context = await openContextFor(browser, request, passkeyBaseURL(baseURL));
await request.dispose();
const page = await context.newPage();
await page.route('**/api/config', async (route) => {
const response = await route.fetch();
const config = await response.json();
await route.fulfill({ response, json: { ...config, maxPasskeysPerUser: 1 } });
});
const cappedDialog = await openPasskeysDialog(page);
const cappedAdd = cappedDialog.getByRole('button', { name: 'Add passkey' });
await expect(cappedAdd).toBeVisible();
await expect(cappedAdd).toBeDisabled();
await expect(
cappedDialog.getByText('You have reached the maximum number of passkeys'),
).toBeVisible();
await page.unroute('**/api/config');
await page.keyboard.press('Escape');
await expect(cappedDialog).toBeHidden();
await page
.getByRole('dialog', { name: /Settings/ })
.getByRole('button', { name: 'Passkeys', exact: true })
.click();
const defaultDialog = page.getByRole('dialog', { name: 'Passkeys', exact: true });
const defaultAdd = defaultDialog.getByRole('button', { name: 'Add passkey' });
await expect(defaultAdd).toBeVisible();
await expect(defaultAdd).toBeEnabled();
await expect(
defaultDialog.getByText('You have reached the maximum number of passkeys'),
).toHaveCount(0);
});
test('the effective user cap reaches startup and both enrollment routes @scenario:passkey-cap-effective-config', async ({
playwright,
baseURL,
}) => {
test.setTimeout(60000);
const request = await playwright.request.newContext({ baseURL: passkeyBaseURL(baseURL) });
user = await createFreshUser(request);
const headers = { Authorization: `Bearer ${user.token}` };
const admin = getPrimaryE2EUser();
const login = await request.post('/api/auth/login', {
data: { email: admin.email, password: admin.password },
});
expect(login.ok()).toBeTruthy();
const adminHeaders = { Authorization: `Bearer ${(await login.json()).token}` };
const overridePath = `/api/admin/config/user/${user.id}`;
try {
const baseline = await request.get('/api/config', { headers });
expect((await baseline.json()).maxPasskeysPerUser).toBe(20);
await seedPasskey(user.email, `e2e-effective-cap-${randomUUID()}`, 'Existing key');
const saved = await request.put(overridePath, {
headers: adminHeaders,
data: { overrides: { passkeys: { perUserMax: 1 } } },
});
expect(saved.ok()).toBeTruthy();
await expect
.poll(async () => {
const config = await request.get('/api/config', { headers });
return (await config.json()).maxPasskeysPerUser;
})
.toBe(1);
for (const path of ['options', 'verify']) {
const response = await request.post(`/api/auth/passkey/register/${path}`, {
headers,
data: { password: user.password, credential: { id: 'over-cap' } },
});
expect(response.status()).toBe(409);
expect(await response.json()).toEqual({ message: 'Passkey limit reached' });
}
expect(await countUserPasskeys(user.id)).toBe(1);
const restored = await request.delete(overridePath, { headers: adminHeaders });
expect(restored.ok()).toBeTruthy();
await expect
.poll(async () => {
const config = await request.get('/api/config', { headers });
return (await config.json()).maxPasskeysPerUser;
})
.toBe(20);
const allowed = await request.post('/api/auth/passkey/register/options', {
headers,
data: { password: user.password },
});
expect(allowed.status()).toBe(200);
} finally {
const cleanup = await request.delete(overridePath, { headers: adminHeaders });
expect([200, 404]).toContain(cleanup.status());
await request.dispose();
}
});
});

View file

@ -390,6 +390,11 @@ interface:
# enabled: true
# tokenTTLSeconds: 900
# Passkey (WebAuthn) enrollment limits.
# Omitted, perUserMax falls back to MAX_PASSKEYS_PER_USER, then 20.
# passkeys:
# perUserMax: 20
registration:
socialLogins: ['github', 'google', 'discord', 'openid', 'facebook', 'apple', 'saml']
# allowedDomains:

View file

@ -68,6 +68,11 @@ const defaultAgentCapabilitiesWithoutMemory = defaultAgentCapabilities.filter(
);
describe('AppService', () => {
it('preserves the YAML passkey cap in the effective configuration', async () => {
const result = await AppService({ config: { passkeys: { perUserMax: 2 } } });
expect(result?.passkeys).toEqual({ perUserMax: 2 });
});
const mockSystemTools: Record<string, FunctionTool> = {
ExampleTool: {
type: 'function',

View file

@ -1,7 +1,9 @@
import Keyv from 'keyv';
import { logger } from '@librechat/data-schemas';
import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider';
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server';
import type { TCustomConfig } from 'librechat-data-provider';
import type { PasskeyChallengeStore, PasskeyConfig } from './passkey';
import {
authenticationChallengeKey,
@ -12,6 +14,7 @@ import {
getPasskeyConfig,
isPasskeyEnabled,
registrationChallengeKey,
resolveMaxPasskeysPerUser,
verifyPasskeyAuthentication,
verifyPasskeyRegistration,
} from './passkey';
@ -107,6 +110,50 @@ function createAuthenticator(credentialId = 'cred-id') {
return { assert, credential: { credentialId: id, publicKey: cosePublicKey, counter: 0 } };
}
describe('resolveMaxPasskeysPerUser', () => {
it('prefers the yaml value over the environment and the documented default', () => {
expect(
resolveMaxPasskeysPerUser({ perUserMax: 5 }, {
MAX_PASSKEYS_PER_USER: '9',
} as NodeJS.ProcessEnv),
).toBe(5);
});
it('falls back to the environment, then the documented default', () => {
expect(
resolveMaxPasskeysPerUser(undefined, { MAX_PASSKEYS_PER_USER: '9' } as NodeJS.ProcessEnv),
).toBe(9);
expect(resolveMaxPasskeysPerUser(undefined, {} as NodeJS.ProcessEnv)).toBe(
MAX_PASSKEYS_PER_USER,
);
expect(
resolveMaxPasskeysPerUser(undefined, {
MAX_PASSKEYS_PER_USER: 'not-a-number',
} as NodeJS.ProcessEnv),
).toBe(MAX_PASSKEYS_PER_USER);
});
it('applies the schema bounds to the environment value too', () => {
const rejected = ['0', '-1', '101', '9abc', '1.5'];
for (const value of rejected) {
expect(
resolveMaxPasskeysPerUser(undefined, { MAX_PASSKEYS_PER_USER: value } as NodeJS.ProcessEnv),
).toBe(MAX_PASSKEYS_PER_USER);
}
expect(
resolveMaxPasskeysPerUser(undefined, { MAX_PASSKEYS_PER_USER: '100' } as NodeJS.ProcessEnv),
).toBe(100);
});
it('ignores an out-of-bounds cap from an unvalidated override', () => {
const env = { MAX_PASSKEYS_PER_USER: '9' } as NodeJS.ProcessEnv;
const rejected: unknown[] = [0, -1, 101, 1.5, '5', 'abc', null];
for (const perUserMax of rejected) {
expect(resolveMaxPasskeysPerUser({ perUserMax } as TCustomConfig['passkeys'], env)).toBe(9);
}
});
});
describe('getPasskeyConfig', () => {
it('derives the RP ID and origins from DOMAIN_CLIENT', () => {
const resolved = getPasskeyConfig({

View file

@ -1,12 +1,12 @@
import { randomUUID } from 'node:crypto';
import { logger } from '@librechat/data-schemas';
import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider';
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from '@simplewebauthn/server';
import type {
AuthenticationResponseJSON,
AuthenticatorTransportFuture,
@ -15,7 +15,7 @@ import type {
RegistrationResponseJSON,
} from '@simplewebauthn/server';
import type { PasskeyDeviceType } from '@librechat/data-schemas';
import type { TCustomConfig } from 'librechat-data-provider';
import { isEnabled } from '~/utils';
/** How long a generated challenge stays valid, in milliseconds. */
@ -147,6 +147,29 @@ export function isPasskeyEnabled(config: PasskeyConfig = getPasskeyConfig()): bo
return config.enabled && config.origins.length > 0;
}
/** The schema's bounds for `passkeys.perUserMax`, applied to every source of the cap. */
const isCapWithinBounds = (value: unknown): value is number =>
typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 100;
/**
* yaml wins over the environment, which wins over the documented default, so a
* deployment that sets neither keeps exactly the behavior it has today. Every
* source is held to the schema's bounds: principal-scoped database overrides
* merge in without passing through `configSchema`, and a stray value must
* neither brick enrollment nor lift the cap.
*/
export function resolveMaxPasskeysPerUser(
config?: TCustomConfig['passkeys'],
env: NodeJS.ProcessEnv = process.env,
): number {
const fromConfig: unknown = config?.perUserMax;
if (isCapWithinBounds(fromConfig)) {
return fromConfig;
}
const fromEnv = Number(env.MAX_PASSKEYS_PER_USER);
return isCapWithinBounds(fromEnv) ? fromEnv : MAX_PASSKEYS_PER_USER;
}
/** Namespaced cache key for a pending registration ceremony. */
export const registrationChallengeKey = (userId: string): string => `passkey-reg:${userId}`;

View file

@ -1,7 +1,7 @@
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 { FileSources, 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';
@ -48,6 +48,7 @@ const ENV_KEYS = [
'ALLOW_UNVERIFIED_EMAIL_LOGIN',
'EMAIL_SERVICE',
'EMAIL_FROM',
'MAX_PASSKEYS_PER_USER',
] as const;
type MockResponse = Response & { status: jest.Mock; json: jest.Mock };
@ -259,6 +260,190 @@ describe('passkey registration provider enforcement', () => {
expect(res.json).toHaveBeenCalledWith({ message: 'Passkey limit reached' });
});
it('enforces the per-account cap the deployment configures', async () => {
const handlers = createPasskeyHandlers(
buildDeps({
getAppConfig: async () => ({
config: {},
fileStrategy: FileSources.local,
imageOutputType: 'png',
passkeys: { perUserMax: 2 },
}),
}),
);
const user = await createUser();
await Promise.all([createStoredPasskey(user, 'cap-0'), createStoredPasskey(user, 'cap-1')]);
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('awaits an asynchronous cap resolver on the verify path', async () => {
const handlers = createPasskeyHandlers(
buildDeps({
getAppConfig: async () => ({
config: {},
fileStrategy: FileSources.local,
imageOutputType: 'png',
passkeys: { perUserMax: 1 },
}),
}),
);
const user = await createUser();
await createStoredPasskey(user, 'cap-verify-0');
const res = buildRes();
await handlers.registerPasskeyVerify(
authedReq(user, {
credential: attestation,
name: 'Third key',
password: PASSWORD,
}),
res,
);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.json).toHaveBeenCalledWith({ message: 'Passkey limit reached' });
});
it('resolves the authenticated principal once before writing a credential', async () => {
const getAppConfig = jest
.fn<
ReturnType<NonNullable<PasskeyHandlersDeps['getAppConfig']>>,
Parameters<NonNullable<PasskeyHandlersDeps['getAppConfig']>>
>()
.mockResolvedValueOnce({
config: {},
fileStrategy: FileSources.local,
imageOutputType: 'png',
passkeys: { perUserMax: 1 },
})
.mockRejectedValue(new Error('Config unavailable after enrollment'));
const handlers = createPasskeyHandlers(buildDeps({ getAppConfig }));
const user = await createUser();
const req = authedReq(user, { credential: attestation, password: PASSWORD });
req.user.role = 'USER';
req.user.idOnTheSource = 'source-user';
const res = buildRes();
await handlers.registerPasskeyVerify(req, res);
expect(res.status).toHaveBeenCalledWith(201);
expect(getAppConfig).toHaveBeenCalledTimes(1);
expect(getAppConfig).toHaveBeenCalledWith({
userId: user._id.toString(),
role: 'USER',
idOnTheSource: 'source-user',
tenantId: undefined,
failClosed: true,
});
expect(await methods.countPasskeysByUser(user._id.toString())).toBe(1);
});
it('reuses configuration already loaded for the request', async () => {
const getAppConfig = jest.fn().mockRejectedValue(new Error('Unnecessary config read'));
const handlers = createPasskeyHandlers(buildDeps({ getAppConfig }));
const user = await createUser();
await createStoredPasskey(user);
const req = authedReq(user, { password: PASSWORD });
req.config = {
config: {},
fileStrategy: FileSources.local,
imageOutputType: 'png',
passkeys: { perUserMax: 1 },
};
const res = buildRes();
await handlers.registerPasskeyOptions(req, res);
expect(res.status).toHaveBeenCalledWith(409);
expect(getAppConfig).not.toHaveBeenCalled();
});
it('does not enroll a credential when effective configuration cannot be loaded', async () => {
const getAppConfig = jest.fn().mockRejectedValue(new Error('Config unavailable'));
const handlers = createPasskeyHandlers(buildDeps({ getAppConfig }));
const user = await createUser();
const res = buildRes();
await handlers.registerPasskeyVerify(
authedReq(user, { credential: attestation, password: PASSWORD }),
res,
);
expect(res.status).toHaveBeenCalledWith(500);
expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0);
expect(mockVerifyRegistration).not.toHaveBeenCalled();
});
it('removes the inserted credential if the post-write count fails', async () => {
const countPasskeysByUser = jest
.fn(methods.countPasskeysByUser)
.mockResolvedValueOnce(0)
.mockRejectedValueOnce(new Error('Count unavailable'));
const handlers = createPasskeyHandlers(buildDeps({ countPasskeysByUser }));
const user = await createUser();
const res = buildRes();
await handlers.registerPasskeyVerify(
authedReq(user, { credential: attestation, password: PASSWORD }),
res,
);
expect(res.status).toHaveBeenCalledWith(500);
expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0);
});
it('rolls back a credential that wins the enrollment race past the cap', async () => {
/** Both verifies observe the pre-enrollment count, as two concurrent
* ceremonies for the same account do, so both pass the early check. */
const racedCount = jest
.fn()
.mockImplementationOnce(async () => 0)
.mockImplementationOnce(async () => 0)
.mockImplementation(methods.countPasskeysByUser);
const handlers = createPasskeyHandlers(
buildDeps({
getAppConfig: async () => ({
config: {},
fileStrategy: FileSources.local,
imageOutputType: 'png',
passkeys: { perUserMax: 1 },
}),
countPasskeysByUser: racedCount,
}),
);
let ceremony = 0;
mockVerifyRegistration.mockImplementation(async () =>
verifiedRegistration(`raced-cred-${++ceremony}`),
);
const user = await createUser();
const results = await Promise.allSettled(
[1, 2].map((index) =>
handlers.registerPasskeyVerify(
authedReq(user, {
credential: { id: `raced-cred-${index}` } as RegistrationResponseJSON,
name: `Raced ${index}`,
password: PASSWORD,
}),
buildRes(),
),
),
);
expect(
results.every(
(result) =>
result.status === 'fulfilled' ||
result.reason === undefined /** handlers return rather than throw */,
),
).toBe(true);
expect(await methods.countPasskeysByUser(user._id.toString())).toBeLessThanOrEqual(1);
});
it('stores the credential when the account is local', async () => {
const handlers = createPasskeyHandlers(buildDeps());
const user = await createUser();

View file

@ -1,9 +1,9 @@
import { logger } from '@librechat/data-schemas';
import { MAX_PASSKEYS_PER_USER } from 'librechat-data-provider';
import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server';
import type { PasskeyCreateData, PasskeyRecord } from '@librechat/data-schemas';
import type { PasskeyCreateData, PasskeyRecord, AppConfig } from '@librechat/data-schemas';
import type { TPasskey } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type { AppConfigUserLike, GetAppConfigOptions } from '~/app/service';
import type { PasskeyConfig, PasskeyChallengeStore } from '~/auth/passkey';
import type { ComparePasswordDeps } from '~/auth/password';
import type { UserDocumentId } from '~/auth/verification';
@ -11,12 +11,14 @@ import {
getPasskeyConfig,
isPasskeyEnabled,
defaultPasskeyName,
resolveMaxPasskeysPerUser,
verifyPasskeyRegistration,
verifyPasskeyAuthentication,
createPasskeyRegistrationOptions,
createPasskeyAuthenticationOptions,
} from '~/auth/passkey';
import { grandfatherLegacyEmailVerification } from '~/auth/verification';
import { resolveStrictAppConfig } from '~/app/service';
import { comparePassword } from '~/auth/password';
import { isEnabled } from '~/utils';
@ -53,7 +55,7 @@ interface AuthenticationBody {
* handoff to `loginController` and legacy-verification grandfathering, not by
* the route handlers themselves.
*/
export interface PasskeyAccount {
export interface PasskeyAccount extends AppConfigUserLike {
id?: string;
_id?: UserDocumentId;
email?: string;
@ -74,6 +76,7 @@ export type PasskeyRequest<TBody = StepUpBody> = Request<
> & {
user?: PasskeyAccount;
banned?: boolean;
config?: AppConfig;
};
/** Every management route sits behind `requireJwtAuth`, so `req.user` is always populated. */
@ -115,6 +118,8 @@ export interface PasskeyHandlersDeps {
findPasskeyByCredentialId: (credentialId: string) => Promise<PasskeyRecord | null>;
/** Resolves the cache backing pending WebAuthn ceremonies. */
getChallengeCache: () => PasskeyChallengeStore;
/** Resolves effective configuration for the authenticated principal. */
getAppConfig?: (options: GetAppConfigOptions) => Promise<AppConfig | undefined>;
compare: ComparePasswordDeps['compare'];
/** The login ban middleware; reports an internal failure through `next(err)`. */
checkBan: (
@ -242,6 +247,7 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
recordPasskeyUse,
getChallengeCache,
findPasskeysByUser,
getAppConfig,
countPasskeysByUser,
findPasskeyByCredentialId,
} = deps;
@ -249,6 +255,14 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
const getChallengeStore = (): PasskeyChallengeStore =>
createPasskeyChallengeStore(getChallengeCache());
/** Resolved per request, so a config reload changes the cap without a restart. */
const resolveMaxPasskeys = async (req: AuthenticatedPasskeyRequest): Promise<number> => {
const appConfig =
req.config ??
(getAppConfig ? await resolveStrictAppConfig(getAppConfig, req.user) : undefined);
return resolveMaxPasskeysPerUser(appConfig?.passkeys);
};
/**
* 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
@ -336,8 +350,11 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
}
try {
const existingCredentials = await findPasskeysByUser(req.user.id);
if (existingCredentials.length >= MAX_PASSKEYS_PER_USER) {
const [existingCredentials, maxPasskeys] = await Promise.all([
findPasskeysByUser(req.user.id),
resolveMaxPasskeys(req),
]);
if (existingCredentials.length >= maxPasskeys) {
return res.status(409).json({ message: 'Passkey limit reached' });
}
@ -387,7 +404,11 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
return res.status(400).json({ message: 'Missing credential' });
}
if ((await countPasskeysByUser(req.user.id)) >= MAX_PASSKEYS_PER_USER) {
const [count, maxPasskeys] = await Promise.all([
countPasskeysByUser(req.user.id),
resolveMaxPasskeys(req),
]);
if (count >= maxPasskeys) {
return res.status(409).json({ message: 'Passkey limit reached' });
}
@ -419,6 +440,24 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
trimmedName.slice(0, MAX_PASSKEY_NAME_LENGTH) || defaultPasskeyName(verified.transports),
});
/**
* The early count check races a concurrent ceremony for the same account:
* both can observe a below-cap count and both insert. Re-counting after
* the write and rolling this credential back keeps the stored set within
* the cap without a transaction, at the cost of rejecting the whole race.
*/
let countAfterWrite: number;
try {
countAfterWrite = await countPasskeysByUser(req.user.id);
} catch (error) {
await deletePasskey(passkey.id, req.user.id);
throw error;
}
if (countAfterWrite > maxPasskeys) {
await deletePasskey(passkey.id, req.user.id);
return res.status(409).json({ message: 'Passkey limit reached' });
}
return res.status(201).json({ passkey: serializePasskey(passkey) });
} catch (err) {
if (isDuplicateKeyError(err as MongoWriteError)) {

View file

@ -175,6 +175,22 @@ describe('ask user retained answers', () => {
});
});
describe('passkey enrollment config', () => {
it('ships a per-account cap a deployment can raise or lower', () => {
expect(configSchema.parse({ version: '1.0' }).passkeys).toEqual({});
expect(
configSchema.parse({ version: '1.0', passkeys: { perUserMax: 5 } }).passkeys.perUserMax,
).toBe(5);
/** A cap below one would brick enrollment; a fraction of a credential is nonsense. */
expect(configSchema.safeParse({ version: '1.0', passkeys: { perUserMax: 0 } }).success).toBe(
false,
);
expect(configSchema.safeParse({ version: '1.0', passkeys: { perUserMax: 1.5 } }).success).toBe(
false,
);
});
});
describe('retained tool-count ceiling', () => {
it('ships the exact-count budget a deployment can raise or lower', () => {
/** The save path tokenizes a stopped turn's retained tool results to add an

View file

@ -2748,6 +2748,8 @@ export type TStartupConfig = {
appleLoginEnabled: boolean;
samlLoginEnabled: boolean;
passkeyLoginEnabled: boolean;
/** Per-account passkey enrollment cap, from `passkeys.perUserMax`; post-login only. */
maxPasskeysPerUser?: number;
openidLabel: string;
openidImageUrl: string;
openidAutoRedirect: boolean;
@ -3521,6 +3523,14 @@ export const configSchema = z.object({
tokenTTLSeconds: z.number().int().min(60).max(86_400).optional(),
})
.optional(),
/** WebAuthn passkey enrollment. An unset field falls back to its env var, then the
* documented default, so an existing deployment keeps the behavior it has today. */
passkeys: z
.object({
/** `MAX_PASSKEYS_PER_USER` when unset; the documented default when neither is given. */
perUserMax: z.number().int().min(1).max(100).optional(),
})
.default({}),
balance: balanceSchema.optional(),
transactions: transactionsSchema.optional(),
speech: z

View file

@ -187,6 +187,7 @@ export const AppService = async (params?: {
fileStrategy,
registration,
emailChange,
passkeys: config.passkeys,
transactions,
filteredTools,
includedTools,

View file

@ -82,6 +82,8 @@ export interface AppConfig {
registration?: TCustomConfig['registration'];
/** Changing the registered email address */
emailChange?: TCustomConfig['emailChange'];
/** Passkey enrollment configuration */
passkeys?: TCustomConfig['passkeys'];
/** Actions configurations */
actions?: TCustomConfig['actions'];
/** Admin-filtered tools */