🧹 refactor: Keep Mongoose Types Out of the Passkey Handler Contract (#16263)

This commit is contained in:
Marco Beretta 2026-09-24 13:17:52 +02:00 • committed by GitHub
parent 1c54ffa411
commit fea7c17a56
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 173 additions and 84 deletions

View file

@ -6,7 +6,12 @@ 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 {
PasskeyAccount,
PasskeyHandlersDeps,
PasskeyRequest,
AuthenticatedPasskeyRequest,
} from './handlers';
import type { PasskeyChallengeStore } from '~/auth/passkey';
import {
verifyPasskeyRegistration,
@ -75,7 +80,7 @@ function buildDeps(overrides: Partial<PasskeyHandlersDeps> = {}): PasskeyHandler
compare,
getChallengeCache: memoryCache,
getUserById: methods.getUserById,
updateUser: (userId, update) => methods.updateUser(userId.toString(), update),
updateUser: (userId, update) => methods.updateUser(userId.toString(), update as Partial<IUser>),
createPasskey: methods.createPasskey,
deletePasskey: methods.deletePasskey,
renamePasskey: methods.renamePasskey,
@ -100,7 +105,7 @@ async function createUser(fields: Partial<IUser> = {}): Promise<IUser> {
async function createStoredPasskey(user: IUser, credentialId = 'cred-1') {
return methods.createPasskey({
user: user._id,
user: user._id.toString(),
credentialId,
publicKey: Buffer.from('public-key'),
counter: 0,
@ -273,7 +278,7 @@ describe('passkey registration provider enforcement', () => {
expect(stored).toHaveLength(1);
expect(res.json).toHaveBeenCalledWith({
passkey: {
id: stored[0]._id.toString(),
id: stored[0].id,
name: 'Work laptop',
deviceType: 'singleDevice',
backedUp: false,
@ -500,7 +505,7 @@ describe('passkey rename', () => {
const res = buildRes();
await handlers.updatePasskey(
authedReq(user, { name: ` ${'x'.repeat(80)} ` }, { passkeyId: passkey._id.toString() }),
authedReq(user, { name: ` ${'x'.repeat(80)} ` }, { passkeyId: passkey.id }),
res,
);
@ -528,7 +533,7 @@ describe('passkey rename', () => {
const res = buildRes();
await handlers.updatePasskey(
authedReq(other, { name: 'Mine now' }, { passkeyId: passkey._id.toString() }),
authedReq(other, { name: 'Mine now' }, { passkeyId: passkey.id }),
res,
);
@ -553,7 +558,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const passkey = await createStoredPasskey(user);
const res = buildRes();
await handlers.removePasskey(authedReq(user, body, { passkeyId: passkey._id.toString() }), res);
await handlers.removePasskey(authedReq(user, body, { passkeyId: passkey.id }), res);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.status).not.toHaveBeenCalledWith(401);
@ -584,7 +589,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const res = buildRes();
await handlers.removePasskey(
authedReq(user, { password: PASSWORD }, { passkeyId: passkey._id.toString() }),
authedReq(user, { password: PASSWORD }, { passkeyId: passkey.id }),
res,
);
@ -600,7 +605,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const res = buildRes();
await handlers.removePasskey(
authedReq(user, { password: PASSWORD }, { passkeyId: passkey._id.toString() }),
authedReq(user, { password: PASSWORD }, { passkeyId: passkey.id }),
res,
);
@ -618,7 +623,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const res = buildRes();
await handlers.removePasskey(
authedReq(other, { password: PASSWORD }, { passkeyId: passkey._id.toString() }),
authedReq(other, { password: PASSWORD }, { passkeyId: passkey.id }),
res,
);
@ -633,10 +638,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const passkey = await createStoredPasskey(user);
const res = buildRes();
await handlers.removePasskey(
authedReq(user, undefined, { passkeyId: passkey._id.toString() }),
res,
);
await handlers.removePasskey(authedReq(user, undefined, { passkeyId: passkey.id }), res);
expect(res.status).toHaveBeenCalledWith(200);
expect(await methods.countPasskeysByUser(user._id.toString())).toBe(0);
@ -649,10 +651,7 @@ describe('passkey removal password confirmation (step-up)', () => {
const passkey = await createStoredPasskey(user);
const res = buildRes();
await handlers.removePasskey(
authedReq(user, undefined, { passkeyId: passkey._id.toString() }),
res,
);
await handlers.removePasskey(authedReq(user, undefined, { passkeyId: passkey.id }), res);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith({ message: 'Incorrect password' });
@ -703,7 +702,7 @@ describe('passkey sign-in', () => {
await handlers.authenticatePasskey(req, buildRes(), next);
expect(next).toHaveBeenCalledTimes(1);
expect(req.user?._id.toString()).toBe(user._id.toString());
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);
@ -879,7 +878,7 @@ describe('passkey sign-in ban enforcement', () => {
});
it('re-checks the ban with the resolved user before handing off', async () => {
let userAtCheck: IUser | undefined;
let userAtCheck: PasskeyAccount | undefined;
checkBan.mockImplementation(async (req) => {
userAtCheck = req.user;
});
@ -889,7 +888,7 @@ describe('passkey sign-in ban enforcement', () => {
await handlers.authenticatePasskey(loginReq(), buildRes(), next);
expect(checkBan).toHaveBeenCalledTimes(1);
expect(userAtCheck?._id.toString()).toBe(user._id.toString());
expect(userAtCheck?._id?.toString()).toBe(user._id.toString());
expect(next).toHaveBeenCalledTimes(1);
});

View file

@ -1,7 +1,7 @@
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 { PasskeyCreateData, PasskeyRecord } from '@librechat/data-schemas';
import type { TPasskey } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type { PasskeyConfig, PasskeyChallengeStore } from '~/auth/passkey';
@ -46,18 +46,39 @@ interface AuthenticationBody {
sessionId?: string;
}
/**
* The account fields the passkey routes read, as a plain shape: neither the
* request's user nor the data-layer results carry Mongoose types across the
* package boundary. `twoFactorEnabled` and `createdAt` are read after the
* handoff to `loginController` and legacy-verification grandfathering, not by
* the route handlers themselves.
*/
export interface PasskeyAccount {
id?: string;
_id?: UserDocumentId;
email?: string;
name?: string;
username?: string;
emailVerified?: boolean;
expiresAt?: Date | null;
provider?: string;
password?: string;
twoFactorEnabled?: boolean;
createdAt?: Date | string;
}
export type PasskeyRequest<TBody = StepUpBody> = Request<
{ passkeyId: string },
object,
TBody | undefined
> & {
user?: IUser;
user?: PasskeyAccount;
banned?: boolean;
};
/** Every management route sits behind `requireJwtAuth`, so `req.user` is always populated. */
export type AuthenticatedPasskeyRequest<TBody = StepUpBody> = PasskeyRequest<TBody> & {
user: IUser;
user: PasskeyAccount & { id: string; email: string };
};
/** The client-facing summary, carrying dates before JSON serialization turns them into strings. */
@ -70,20 +91,28 @@ export type PasskeySummary = Omit<TPasskey, 'transports' | 'createdAt' | 'lastUs
type PasskeyResult = Promise<Response | void>;
type NextCallback = (err?: Error) => void;
export interface PasskeyHandlersDeps
extends Pick<
PasskeyMethods,
| 'createPasskey'
| 'deletePasskey'
| 'renamePasskey'
| 'recordPasskeyUse'
| 'findPasskeysByUser'
| 'countPasskeysByUser'
| 'findPasskeyByCredentialId'
> {
getUserById: UserMethods['getUserById'];
/**
* The handlers' data layer, in plain shapes. The data-schemas methods satisfy
* these signatures structurally, so the wiring stays unchanged while Mongoose
* types stay inside data-schemas.
*/
export interface PasskeyHandlersDeps {
getUserById: (
userId: string,
fieldsToSelect?: string | string[] | null,
) => Promise<(PasskeyAccount & { _id: UserDocumentId }) | null>;
/** Receives the raw document id, exactly as the password strategy passes it. */
updateUser: (userId: UserDocumentId, update: Partial<IUser>) => Promise<IUser | null>;
updateUser: (
userId: UserDocumentId,
update: Partial<PasskeyAccount>,
) => Promise<PasskeyAccount | null>;
createPasskey: (data: PasskeyCreateData) => Promise<PasskeyRecord>;
deletePasskey: (passkeyId: string, userId: string) => Promise<{ deletedCount: number }>;
renamePasskey: (passkeyId: string, userId: string, name: string) => Promise<PasskeyRecord | null>;
recordPasskeyUse: (credentialId: string, counter: number, backedUp?: boolean) => Promise<boolean>;
findPasskeysByUser: (userId: string) => Promise<PasskeyRecord[]>;
countPasskeysByUser: (userId: string) => Promise<number>;
findPasskeyByCredentialId: (credentialId: string) => Promise<PasskeyRecord | null>;
/** Resolves the cache backing pending WebAuthn ceremonies. */
getChallengeCache: () => PasskeyChallengeStore;
compare: ComparePasswordDeps['compare'];
@ -132,12 +161,12 @@ export function createPasskeyChallengeStore(cache: PasskeyChallengeStore): Passk
* 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 =>
const isLocalAccount = (user: PasskeyAccount | 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(),
export const serializePasskey = (passkey: PasskeyRecord): PasskeySummary => ({
id: passkey.id,
name: passkey.name,
deviceType: passkey.deviceType,
backedUp: passkey.backedUp,
@ -245,7 +274,7 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
return denyPasswordConfirmation(req, res, tag);
}
let account: IUser | null;
let account: PasskeyAccount | null;
try {
account = await getUserById(req.user.id, '+password');
} catch (err) {
@ -516,7 +545,7 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
}
const userHandle = decodeUserHandle(credential.response?.userHandle);
if (userHandle && userHandle !== passkey.user.toString()) {
if (userHandle && userHandle !== passkey.userId) {
logger.warn('[authenticatePasskey] User handle does not match the credential owner');
return failure();
}
@ -538,7 +567,7 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
return failure();
}
const user = await getUserById(passkey.user.toString());
const user = await getUserById(passkey.userId);
if (!user) {
return failure();
}
@ -555,7 +584,7 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler
const unverifiedAllowed = isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN);
if (user.expiresAt && unverifiedAllowed) {
await updateUser(user._id || user.id, {});
await updateUser(user._id, {});
}
if (!user.emailVerified && !unverifiedAllowed) {
logger.warn('[authenticatePasskey] Rejected unverified email login');

View file

@ -18,7 +18,7 @@ const userId = new mongoose.Types.ObjectId();
const otherUserId = new mongoose.Types.ObjectId();
const passkeyData = (overrides: Partial<t.PasskeyCreateData> = {}): t.PasskeyCreateData => ({
user: userId,
user: userId.toString(),
credentialId: 'credential-one',
publicKey: Buffer.from([1, 2, 3]),
counter: 0,
@ -59,11 +59,22 @@ describe('createPasskey', () => {
expect(created.createdAt).toBeInstanceOf(Date);
});
it('returns a plain record, not a Mongoose document', async () => {
await methods.createPasskey(passkeyData());
const found = await methods.findPasskeyByCredentialId('credential-one');
expect(found).not.toHaveProperty('$__');
expect(found).not.toHaveProperty('_doc');
expect(found?.id).toMatch(/^[a-f\d]{24}$/);
expect(found?.userId).toBe(userId.toString());
});
it('rejects a credential ID that is already registered', async () => {
await methods.createPasskey(passkeyData());
await expect(
methods.createPasskey(passkeyData({ user: otherUserId, name: 'Someone else' })),
methods.createPasskey(passkeyData({ user: otherUserId.toString(), name: 'Someone else' })),
).rejects.toThrow();
});
@ -74,7 +85,9 @@ describe('createPasskey', () => {
await freshMethods.createPasskey(passkeyData());
await expect(
freshMethods.createPasskey(passkeyData({ user: otherUserId, name: 'Someone else' })),
freshMethods.createPasskey(
passkeyData({ user: otherUserId.toString(), name: 'Someone else' }),
),
).rejects.toThrow(/duplicate key/);
expect(await mongoose.models.Passkey.countDocuments({ credentialId: 'credential-one' })).toBe(
1,
@ -87,7 +100,7 @@ describe('findPasskeysByUser', () => {
await methods.createPasskey(passkeyData({ credentialId: 'a', name: 'First' }));
await methods.createPasskey(passkeyData({ credentialId: 'b', name: 'Second' }));
await methods.createPasskey(
passkeyData({ credentialId: 'c', name: 'Other user', user: otherUserId }),
passkeyData({ credentialId: 'c', name: 'Other user', user: otherUserId.toString() }),
);
const found = await methods.findPasskeysByUser(userId.toString());
@ -103,7 +116,7 @@ describe('findPasskeyByCredentialId', () => {
const found = await methods.findPasskeyByCredentialId('credential-one');
expect(found?.user.toString()).toBe(userId.toString());
expect(found?.userId).toBe(userId.toString());
});
it('returns null for an unknown credential', async () => {
@ -241,11 +254,7 @@ describe('renamePasskey', () => {
it('renames a credential the user owns', async () => {
const created = await methods.createPasskey(passkeyData());
const renamed = await methods.renamePasskey(
created._id.toString(),
userId.toString(),
'Work laptop',
);
const renamed = await methods.renamePasskey(created.id, userId.toString(), 'Work laptop');
expect(renamed?.name).toBe('Work laptop');
});
@ -253,11 +262,7 @@ describe('renamePasskey', () => {
it('refuses to rename another user credential', async () => {
const created = await methods.createPasskey(passkeyData());
const renamed = await methods.renamePasskey(
created._id.toString(),
otherUserId.toString(),
'Stolen',
);
const renamed = await methods.renamePasskey(created.id, otherUserId.toString(), 'Stolen');
expect(renamed).toBeNull();
const untouched = await methods.findPasskeyByCredentialId('credential-one');
@ -269,7 +274,7 @@ describe('deletePasskey', () => {
it('deletes a credential the user owns', async () => {
const created = await methods.createPasskey(passkeyData());
const result = await methods.deletePasskey(created._id.toString(), userId.toString());
const result = await methods.deletePasskey(created.id, userId.toString());
expect(result.deletedCount).toBe(1);
expect(await methods.findPasskeyByCredentialId('credential-one')).toBeNull();
@ -278,7 +283,7 @@ describe('deletePasskey', () => {
it('refuses to delete another user credential', async () => {
const created = await methods.createPasskey(passkeyData());
const result = await methods.deletePasskey(created._id.toString(), otherUserId.toString());
const result = await methods.deletePasskey(created.id, otherUserId.toString());
expect(result.deletedCount).toBe(0);
expect(await methods.findPasskeyByCredentialId('credential-one')).not.toBeNull();
@ -289,7 +294,7 @@ describe('deletePasskeysByUser', () => {
it('clears every credential for the user and leaves others alone', async () => {
await methods.createPasskey(passkeyData({ credentialId: 'a' }));
await methods.createPasskey(passkeyData({ credentialId: 'b' }));
await methods.createPasskey(passkeyData({ credentialId: 'c', user: otherUserId }));
await methods.createPasskey(passkeyData({ credentialId: 'c', user: otherUserId.toString() }));
const result = await methods.deletePasskeysByUser(userId.toString());

View file

@ -1,15 +1,15 @@
import type { DeleteResult } from 'mongoose';
import type { IPasskey, PasskeyCreateData } from '~/types';
import type { IPasskey, PasskeyCreateData, PasskeyRecord } from '~/types';
import { createIndexesWithRetry } from '~/utils/retry';
import logger from '~/config/winston';
export interface PasskeyMethods {
createPasskey: (data: PasskeyCreateData) => Promise<IPasskey>;
findPasskeysByUser: (userId: string) => Promise<IPasskey[]>;
findPasskeyByCredentialId: (credentialId: string) => Promise<IPasskey | null>;
createPasskey: (data: PasskeyCreateData) => Promise<PasskeyRecord>;
findPasskeysByUser: (userId: string) => Promise<PasskeyRecord[]>;
findPasskeyByCredentialId: (credentialId: string) => Promise<PasskeyRecord | null>;
countPasskeysByUser: (userId: string) => Promise<number>;
recordPasskeyUse: (credentialId: string, counter: number, backedUp?: boolean) => Promise<boolean>;
renamePasskey: (passkeyId: string, userId: string, name: string) => Promise<IPasskey | null>;
renamePasskey: (passkeyId: string, userId: string, name: string) => Promise<PasskeyRecord | null>;
deletePasskey: (passkeyId: string, userId: string) => Promise<DeleteResult>;
deletePasskeysByUser: (userId: string) => Promise<DeleteResult>;
}
@ -17,6 +17,24 @@ export interface PasskeyMethods {
/** The shapes a `Buffer` schema field can come back as, depending on `lean()`. */
type StoredBinary = Buffer | Uint8Array | { buffer: Buffer };
/** What the driver hands back for a stored passkey: `lean()` rows or saved documents. */
type StoredPasskey = Pick<
IPasskey,
| 'credentialId'
| 'publicKey'
| 'counter'
| 'transports'
| 'deviceType'
| 'backedUp'
| 'name'
| 'lastUsedAt'
| 'tenantId'
| 'createdAt'
> & {
_id: { toString(): string };
user: { toString(): string };
};
/**
* `lean()` skips Mongoose casting, so a `Buffer` field arrives as the driver's
* BSON `Binary`. `new Uint8Array(binary)` silently yields zero bytes, which
@ -33,11 +51,22 @@ function toBuffer(value: StoredBinary): Buffer {
return Buffer.from(value as Uint8Array);
}
function normalizePasskey<T extends IPasskey | null>(passkey: T): T {
if (passkey?.publicKey) {
passkey.publicKey = toBuffer(passkey.publicKey as StoredBinary);
}
return passkey;
/** Maps a stored row to the plain record the methods expose. */
function toPasskeyRecord(passkey: StoredPasskey): PasskeyRecord {
return {
id: passkey._id.toString(),
userId: passkey.user.toString(),
credentialId: passkey.credentialId,
publicKey: toBuffer(passkey.publicKey as StoredBinary),
counter: passkey.counter,
transports: passkey.transports ?? [],
deviceType: passkey.deviceType,
backedUp: passkey.backedUp,
name: passkey.name,
lastUsedAt: passkey.lastUsedAt ?? null,
tenantId: passkey.tenantId,
createdAt: passkey.createdAt,
};
}
export function createPasskeyMethods(mongoose: typeof import('mongoose')): PasskeyMethods {
@ -59,30 +88,33 @@ export function createPasskeyMethods(mongoose: typeof import('mongoose')): Passk
}
/** Registers a newly verified credential for a user. */
async function createPasskey(data: PasskeyCreateData): Promise<IPasskey> {
async function createPasskey(data: PasskeyCreateData): Promise<PasskeyRecord> {
await ensurePasskeyIndexes();
const Passkey = mongoose.models.Passkey;
return (await Passkey.create(data)) as IPasskey;
const stored = (await Passkey.create(data)) as unknown as StoredPasskey;
return toPasskeyRecord(stored);
}
/** Lists a user's credentials, newest first. */
async function findPasskeysByUser(userId: string): Promise<IPasskey[]> {
async function findPasskeysByUser(userId: string): Promise<PasskeyRecord[]> {
const Passkey = mongoose.models.Passkey;
const passkeys = (await Passkey.find({ user: userId })
.sort({ createdAt: -1 })
.lean()
.exec()) as unknown as IPasskey[];
return passkeys.map(normalizePasskey);
.exec()) as unknown as StoredPasskey[];
return passkeys.map(toPasskeyRecord);
}
/**
* Looks up a credential by its authenticator-supplied ID. Called before the
* caller is authenticated, so it is intentionally not scoped to a user.
*/
async function findPasskeyByCredentialId(credentialId: string): Promise<IPasskey | null> {
async function findPasskeyByCredentialId(credentialId: string): Promise<PasskeyRecord | null> {
const Passkey = mongoose.models.Passkey;
const passkey = (await Passkey.findOne({ credentialId }).lean().exec()) as IPasskey | null;
return normalizePasskey(passkey);
const passkey = (await Passkey.findOne({ credentialId })
.lean()
.exec()) as unknown as StoredPasskey | null;
return passkey ? toPasskeyRecord(passkey) : null;
}
async function countPasskeysByUser(userId: string): Promise<number> {
@ -136,15 +168,16 @@ export function createPasskeyMethods(mongoose: typeof import('mongoose')): Passk
passkeyId: string,
userId: string,
name: string,
): Promise<IPasskey | null> {
): Promise<PasskeyRecord | null> {
const Passkey = mongoose.models.Passkey;
return (await Passkey.findOneAndUpdate(
const renamed = (await Passkey.findOneAndUpdate(
{ _id: passkeyId, user: userId },
{ name },
{ new: true },
)
.lean()
.exec()) as IPasskey | null;
.exec()) as unknown as StoredPasskey | null;
return renamed ? toPasskeyRecord(renamed) : null;
}
async function deletePasskey(passkeyId: string, userId: string): Promise<DeleteResult> {

View file

@ -23,7 +23,7 @@ export interface IPasskey extends Document {
}
export interface PasskeyCreateData {
user: string | Types.ObjectId;
user: string;
credentialId: string;
publicKey: Buffer;
counter: number;
@ -32,3 +32,26 @@ export interface PasskeyCreateData {
backedUp: boolean;
name: string;
}
/**
* A stored passkey as a plain record. The data-schemas methods return this
* shape so Mongoose documents stay inside this package; `id` and `userId` are
* strings rather than ObjectIds, and `publicKey` is a real `Buffer`.
*/
export interface PasskeyRecord {
id: string;
userId: string;
credentialId: string;
/** COSE public key bytes returned by the authenticator */
publicKey: Buffer;
/** Signature counter, used to detect cloned authenticators */
counter: number;
transports: string[];
deviceType: PasskeyDeviceType;
backedUp: boolean;
/** User-supplied label shown in account settings */
name: string;
lastUsedAt: Date | null;
tenantId?: string;
createdAt?: Date;
}