🔐 fix: Revoke Password Reset Credentials Independently (#16320)

This commit is contained in:
Marco Beretta 2026-09-24 18:41:18 +02:00 • committed by GitHub
parent 7402197317
commit c59fb60341
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 146 additions and 19 deletions

View file

@ -5,6 +5,7 @@ const { logger, runAsSystem, tenantStorage } = require('@librechat/data-schemas'
const {
math,
isEnabled,
createResetPasswordController,
createAuthIdentityContext,
createOpenIDRefreshOwnershipError,
isOpenIDRefreshOwnershipError,
@ -321,25 +322,11 @@ const resetPasswordRequestController = async (req, res) => {
}
};
const resetPasswordController = async (req, res) => {
try {
const resetPasswordService = await resetPassword(
req.body.userId,
req.body.token,
req.body.password,
);
if (resetPasswordService instanceof Error) {
return res.status(400).json(resetPasswordService);
} else {
await deleteAllUserSessions({ userId: req.body.userId });
await deletePasskeysByUser(req.body.userId);
return res.status(200).json(resetPasswordService);
}
} catch (e) {
logger.error('[resetPasswordController]', e);
return res.status(400).json({ message: e.message });
}
};
const resetPasswordController = createResetPasswordController({
resetPassword,
deleteAllUserSessions,
deletePasskeysByUser,
});
const refreshController = async (req, res) => {
const parsedCookies = req.headers.cookie ? cookies.parse(req.headers.cookie) : {};

View file

@ -2476,9 +2476,13 @@ describe('registrationController - invite consumption', () => {
describe('resetPasswordController', () => {
let req, res;
const serviceResult = { message: 'Password reset successful' };
beforeEach(() => {
jest.clearAllMocks();
resetPassword.mockReset().mockResolvedValue(serviceResult);
deleteAllUserSessions.mockReset().mockResolvedValue(undefined);
deletePasskeysByUser.mockReset().mockResolvedValue(undefined);
req = {
body: {
userId: 'user-123',
@ -2518,4 +2522,92 @@ describe('resetPasswordController', () => {
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(resetError);
});
it.each([
['sessions', true, false],
['passkeys', false, true],
['sessions and passkeys', true, true],
])('reports a committed reset when revoking %s fails', async (_, failSessions, failPasskeys) => {
const sessionError = new Error('Session store unavailable');
const passkeyError = new Error('Passkey store unavailable');
if (failSessions) {
deleteAllUserSessions.mockRejectedValue(sessionError);
}
if (failPasskeys) {
deletePasskeysByUser.mockRejectedValue(passkeyError);
}
await resetPasswordController(req, res);
expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-123' });
expect(deletePasskeysByUser).toHaveBeenCalledWith('user-123');
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(serviceResult);
expect(logger.error).toHaveBeenCalledTimes(Number(failSessions) + Number(failPasskeys));
if (failSessions) {
expect(logger.error).toHaveBeenCalledWith(
'[resetPasswordController] Failed to revoke sessions for user user-123',
sessionError,
);
}
if (failPasskeys) {
expect(logger.error).toHaveBeenCalledWith(
'[resetPasswordController] Failed to revoke passkeys for user user-123',
passkeyError,
);
}
});
it('starts passkey revocation while session revocation is still pending', async () => {
let finishSessions;
deleteAllUserSessions.mockReturnValue(
new Promise((resolve) => {
finishSessions = resolve;
}),
);
const reset = resetPasswordController(req, res);
await new Promise((resolve) => setImmediate(resolve));
const passkeyCalls = deletePasskeysByUser.mock.calls.length;
const responseCalls = res.status.mock.calls.length;
finishSessions();
await reset;
expect(passkeyCalls).toBe(1);
expect(responseCalls).toBe(0);
expect(res.status).toHaveBeenCalledWith(200);
});
it.each(['sessions', 'passkeys'])('handles a synchronous %s revocation failure', async (kind) => {
const error = new Error('Revocation failed');
const revoke = kind === 'sessions' ? deleteAllUserSessions : deletePasskeysByUser;
revoke.mockImplementation(() => {
throw error;
});
await resetPasswordController(req, res);
expect(deleteAllUserSessions).toHaveBeenCalledWith({ userId: 'user-123' });
expect(deletePasskeysByUser).toHaveBeenCalledWith('user-123');
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(serviceResult);
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith(
`[resetPasswordController] Failed to revoke ${kind} for user user-123`,
error,
);
});
it('does not revoke sessions or passkeys when the reset service throws', async () => {
const resetError = new Error('Password update failed');
resetPassword.mockRejectedValue(resetError);
await resetPasswordController(req, res);
expect(deleteAllUserSessions).not.toHaveBeenCalled();
expect(deletePasskeysByUser).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith({ message: resetError.message });
expect(logger.error).toHaveBeenCalledWith('[resetPasswordController]', resetError);
});
});

View file

@ -1,4 +1,5 @@
import { logger } from '@librechat/data-schemas';
import type { Request, Response } from 'express';
import { EMAIL_CHANGE_TOKEN_TYPE } from './email';
/** The stored reset token, in both the typed shape and the untyped legacy one. */
@ -36,12 +37,59 @@ export interface PasswordResetInput {
password: string;
}
export interface PasswordResetControllerDeps {
resetPassword: (
userId: string,
token: string,
password: string,
) => Promise<{ message: string } | Error>;
deleteAllUserSessions: (query: { userId: string }) => Promise<{ deletedCount?: number }>;
deletePasskeysByUser: (userId: string) => Promise<{ deletedCount?: number }>;
}
export type PasswordResetOutcome =
| { ok: true; user: PasswordResetUser; resetToken: PasswordResetToken }
| { ok: false };
export const PASSWORD_RESET_USER_FIELDS: string = 'email _id name username emailChangedAt';
export function createResetPasswordController(deps: PasswordResetControllerDeps) {
return async (
req: Request<Record<string, string>, object, PasswordResetInput>,
res: Response,
): Promise<Response> => {
try {
const { userId, token, password } = req.body;
const result = await deps.resetPassword(userId, token, password);
if (result instanceof Error) {
return res.status(400).json(result);
}
const [sessions, passkeys] = await Promise.allSettled([
Promise.resolve().then(() => deps.deleteAllUserSessions({ userId })),
Promise.resolve().then(() => deps.deletePasskeysByUser(userId)),
]);
if (sessions.status === 'rejected') {
logger.error(
`[resetPasswordController] Failed to revoke sessions for user ${userId}`,
sessions.reason,
);
}
if (passkeys.status === 'rejected') {
logger.error(
`[resetPasswordController] Failed to revoke passkeys for user ${userId}`,
passkeys.reason,
);
}
return res.status(200).json(result);
} catch (error) {
logger.error('[resetPasswordController]', error);
return res.status(400).json({ message: error instanceof Error ? error.message : undefined });
}
};
}
/**
* Keyed on the token's address binding rather than its type, so the untyped legacy shape
* a fallback lookup returns is covered too. Address-less tokens stay usable so links from