LibreChat/config/reset-password.js
Marco Beretta 18b6937da3
🧯 fix: Outlast Failed Auth Cache Eviction on Credential Changes (#16435)
* fix: outlast failed auth cache eviction on credential changes

A credential change committed to MongoDB could report success while a
cached auth user document without the new credentialsChangedAt stayed
readable, so an old OpenID access token kept authorizing until the
cache TTL. The Redis-backed auth cache swallowed every failure (Keyv and
KeyvRedis resolve a failed GET as a miss and a failed DEL as a no-op), and
the eviction helpers stopped at the first error.

- The AUTH_USER_DOC namespace opts into throwOnErrors so a failed read or
  delete is visible; every caller of that namespace already catches.
- evictAuthUserDocs attempts every delete even when another fails and
  reports whether a document may still be served; the data-schemas and
  packages/api invalidation paths share it.
- updateUser waits out AUTH_USER_DOC_CACHE_TTL_MS before returning a
  credential change whose eviction was incomplete, so the change is only
  confirmed once no pre-change document can be served. Other updates stay
  best effort, and later revocations are delayed, never skipped.

* fix: record the reverse index before caching an auth user document

A document written before its reverse-index entry was cached without an
index naming it when the index write failed, so eviction could not find
it. Write the index first with a TTL that outlives the documents it names,
and skip the document when the index write fails.

* test: keep real data-schemas helpers in the pinned order spec

* fix: settle the auth cache after revoking reset credentials

Waiting out the cache TTL inside updateUser held the reset before its
session and passkey revocations, so a live refresh token or passkey could
mint an access token issued after credentialsChangedAt during the wait.
updateUser is best effort again; awaitAuthUserDocEviction retries the
eviction and waits one TTL only when it is still incomplete, and both the
web reset controller and the reset CLI call it after revoking sessions and
passkeys, before confirming the reset.

* fix: settle the credential barrier with a margin and on CLI revocation errors

Timers can fire a millisecond early, so the eviction barrier now waits the
cache TTL plus a 100 ms margin. The reset CLI also settles the barrier when
revoking passkeys or sessions throws, since the password is already changed.

* fix: treat an auth cache that cannot delete as not evicted

* fix: keep the reverse index until every document it names is evicted

A failed eviction still deleted the reverse index, so the credential
barrier's retry found no index and reported the cache clear while the
documents an unreadable index or a failed delete left behind stayed
cached. The index is now deleted only after it was read and every document
it names is gone, so a retry can still find what remains.

* fix: treat a malformed auth reverse index as unreadable

* fix: treat a reverse index with a non-string entry as unreadable
2026-09-28 21:21:53 +02:00

109 lines
3.2 KiB
JavaScript

const path = require('path');
const bcrypt = require('bcryptjs');
const readline = require('readline');
const mongoose = require('mongoose');
const { createModels, createMethods } = require('@librechat/data-schemas');
const { User, Passkey, Session } = createModels(mongoose);
require('module-alias')({ base: path.resolve(__dirname, '..', 'api') });
const getLogStores = require('~/cache/getLogStores');
const { askSilentQuestion } = require('./helpers');
const connect = require('./connect');
const methods = createMethods(mongoose, { getCache: getLogStores });
const question = (query) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) =>
rl.question(query, (answer) => {
rl.close();
resolve(answer);
}),
);
};
const resetPassword = async () => {
try {
await connect();
const email = await question('Enter user email: ');
const user = await User.findOne({ email });
if (!user) {
console.error('User not found!');
process.exit(1);
}
let validPassword = false;
let newPassword;
while (!validPassword) {
newPassword = await askSilentQuestion('Enter new password: ');
if (newPassword.length < 8) {
console.log('Password must be at least 8 characters! Please try again.');
continue;
}
const confirmPassword = await askSilentQuestion('Confirm new password: ');
if (newPassword !== confirmPassword) {
console.log('Passwords do not match! Please try again.');
continue;
}
validPassword = true;
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
/**
* Routes the write through the data-schemas method so the auth user doc
* cache entry for this user is invalidated; a raw updateOne would leave a
* cached document that keeps pre-reset access tokens verifying for the
* cache TTL.
*/
const updated = await methods.updateUser(
user._id.toString(),
{
password: hashedPassword,
/** Access tokens minted before this stamp stop verifying */
credentialsChangedAt: new Date(),
},
{},
{ preserveExpiresAt: true },
);
if (!updated) {
console.error('User not found during update!');
process.exit(1);
}
/**
* 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.
*/
let deletedCount;
try {
({ 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 });
} finally {
/** The password is already changed, so the cache settles even when a revocation fails. */
await methods.awaitAuthUserDocEviction(user._id.toString());
}
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);
process.exit(1);
}
};
resetPassword();