LibreChat/config/reset-password.js
Marco Beretta 92432e95d5
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
🔐 feat: Enforce Required Two-Factor Authentication (#14731)
* feat: enforce required two-factor authentication

Require local and LDAP accounts to enroll in TOTP before they can use the
app when ENFORCE_TWO_FACTOR_AUTHENTICATION is set. Sign-in, refresh, bearer
verification, optional share auth and image authorization all route an
unenrolled account into a staged setup flow, and every bearer credential
minted before enrollment or a password reset is retired.

Password reset retirement uses the existing credentialsChangedAt stamp, and
commitPasswordReset clears any staged enrollment in the same write. Passkey
sign-in follows the same enrollment gate as password sign-in.

* test: cover passkey sign-in handing off to required enrollment

* refactor: keep Mongoose user types out of two-factor auth contracts

* fix: withdraw a minted session when its retirement recheck fails

* fix: hold Agent API keys and the reset CLI to the required two-factor policy

* fix: adopt a setup token handed off after the setup screen mounted

* fix: move every tab that receives an enrollment hand-off into setup

* fix: read the enrollment gate's retirement cutoff in system scope

* fix: clear minted session cookies before the fallible session deletion

* fix: adopt a setup token persisted before the setup screen subscribed
2026-10-01 23:39:51 +02:00

107 lines
3.3 KiB
JavaScript

const path = require('path');
const bcrypt = require('bcryptjs');
const readline = require('readline');
const mongoose = require('mongoose');
const { createPasswordResetUpdate } = require('@librechat/api');
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(),
/** Stamps credentialsChangedAt and drops any staged enrollment, as the web reset does. */
createPasswordResetUpdate(hashedPassword),
{},
{ 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();