Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔑 fix: Invalidate the Auth User Cache After a CLI Password Reset (#16257)
Marco Berettab0783e8085f9
diff --git a/config/reset-password.js b/config/reset-password.jsindex 548cd8ab45..1d239f58b1 100644--- a/config/reset-password.js+++ b/config/reset-password.js@@ -2,11 +2,15 @@ const path = require('path');const bcrypt = require('bcryptjs');const readline = require('readline');const mongoose = require('mongoose');-const { User, Passkey, Session } = require('@librechat/data-schemas').createModels(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,@@ -55,15 +59,28 @@ const resetPassword = async () => {const salt = await bcrypt.genSalt(10);const hashedPassword = await bcrypt.hash(newPassword, salt);- await User.updateOne(- { email },+ /**+ * 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.diff --git a/e2e/playwright.config.redis.ts b/e2e/playwright.config.redis.tsindex f7706811a6..6b99afe50b 100644--- a/e2e/playwright.config.redis.ts+++ b/e2e/playwright.config.redis.ts@@ -1,7 +1,7 @@import { defineConfig } from '@playwright/test';import mockConfig from './playwright.config.mock';-/** Browser scenarios whose behavior crosses the generation stream-store boundary. */+/** Scenarios that exercise Redis-backed streams or shared cache invalidation. */export default defineConfig({...mockConfig,/**@@ -26,5 +26,6 @@ export default defineConfig({/tool-approvals\.spec\.ts/,/usage\.spec\.ts/,/scenarios\/redis-stream\.spec\.ts/,+ /scenarios\/reset-password\.spec\.ts/,],});diff --git a/e2e/specs/mock/scenarios/no-auto-index.cjs b/e2e/specs/mock/scenarios/no-auto-index.cjsnew file mode 100644index 0000000000..472a306789--- /dev/null+++ b/e2e/specs/mock/scenarios/no-auto-index.cjs@@ -0,0 +1 @@+require('mongoose').set('autoIndex', false);diff --git a/e2e/specs/mock/scenarios/reset-password.spec.ts b/e2e/specs/mock/scenarios/reset-password.spec.tsnew file mode 100644index 0000000000..fc14e00759--- /dev/null+++ b/e2e/specs/mock/scenarios/reset-password.spec.ts@@ -0,0 +1,233 @@+import fs from 'fs';+import path from 'path';+import os from 'os';+import { Keyv } from 'keyv';+import KeyvRedis from '@keyv/redis';+import { expect, test } from '@playwright/test';+import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider';+import { spawn } from 'node:child_process';+import { randomInt, randomUUID } from 'node:crypto';+import { withMongo, seedPasskey, deleteUserByEmail } from '../db';++const PASSWORD = 'test1234!';+const NEW_PASSWORD = 'fresh-password-1';+const REPO_ROOT = path.resolve(__dirname, '../../../..');+const NO_AUTO_INDEX = path.join(__dirname, 'no-auto-index.cjs');++type RuntimeEnv = { MONGO_URI?: string };++function getMongoUri(): string {+ const runtimeEnvPath =+ process.env.E2E_RUNTIME_ENV_PATH ??+ path.resolve(__dirname, '../../.test-results/runtime-env.json');+ try {+ const env = JSON.parse(fs.readFileSync(runtimeEnvPath, 'utf8')) as RuntimeEnv;+ if (env.MONGO_URI) {+ return env.MONGO_URI;+ }+ } catch {+ /* fall through to env */+ }+ return process.env.MONGO_URI ?? 'mongodb://127.0.0.1:27017/LibreChat-e2e';+}++/**+ * Drives the interactive reset CLI the way an administrator would, answering+ * each prompt as it appears rather than pre-loading stdin, which the prompt+ * loop would consume as one burst.+ */+function runResetCli(+ email: string,+ cwd: string,+ env: NodeJS.ProcessEnv,+): Promise<{ code: number | null; stdout: string; stderr: string }> {+ const child = spawn(process.execPath, [path.join(REPO_ROOT, 'config/reset-password.js')], {+ cwd,+ env: {+ ...env,+ MONGO_URI: getMongoUri(),+ /** The harness server already built the indexes; skip the module-scope rebuild. */+ NODE_OPTIONS: process.env.NODE_OPTIONS+ ? `${process.env.NODE_OPTIONS} --require ${NO_AUTO_INDEX}`+ : `--require ${NO_AUTO_INDEX}`,+ },+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ const answers: Array<[string, string] | null> = [+ ['Enter user email: ', email],+ ['Enter new password: ', NEW_PASSWORD],+ ['Confirm new password: ', NEW_PASSWORD],+ ];+ let stdout = '';+ child.stdout?.on('data', (chunk: Buffer) => {+ stdout += chunk.toString();+ answers.forEach((answer, index) => {+ if (answer !== null && stdout.includes(answer[0])) {+ child.stdin?.write(`${answer[1]}\n`);+ answers[index] = null;+ }+ });+ });+ let stderr = '';+ child.stderr?.on('data', (chunk: Buffer) => (stderr += chunk.toString()));+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ reject(new Error(`reset CLI timed out; stdout: ${stdout.slice(-400)}`));+ }, 60_000);+ child.on('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ child.on('close', (code) => {+ clearTimeout(timer);+ child.stdin?.end();+ resolve({ code, stdout, stderr });+ });+ });+}++test.describe('CLI password reset', () => {+ test.skip(process.env.E2E_STREAM_STORE !== 'redis', 'Runs in the Redis integration lane');+ for (const [source, scenario] of [+ ['environment', '@scenario:cli-reset-revokes-old-tokens'],+ ['dotenv', '@scenario:cli-reset-loads-cache-env'],+ ]) {+ test(`evicts cached credentials with ${source} configuration ${scenario}`, async ({+ playwright,+ baseURL,+ }) => {+ test.setTimeout(90_000);+ // The harness trusts one proxy; isolate each scenario's login rate-limit budget.+ const request = await playwright.request.newContext({+ baseURL,+ extraHTTPHeaders: {+ 'X-Forwarded-For': `127.${randomInt(1, 255)}.${randomInt(1, 255)}.${randomInt(1, 255)}`,+ },+ });+ const email = `cli-reset-${randomUUID().slice(0, 8)}@example.com`;+ const expiresAt = source === 'dotenv' ? new Date(Date.now() + 604800_000) : undefined;+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lc-reset-'));+ const redisUri = process.env.REDIS_URI ?? 'redis://127.0.0.1:6379';+ const prefix = `cli-reset-${randomUUID()}`;+ const adapter = new KeyvRedis(redisUri, { throwOnErrors: true, connectionTimeout: 5000 });+ // Match standardCache's namespace layering without initializing app singletons in this worker.+ const cache = new Keyv(adapter, { namespace: CacheKeys.AUTH_USER_DOC });+ adapter.namespace = prefix;+ adapter.keyPrefixSeparator = '::';+ const keys: string[] = [];+ try {+ const register = await request.post('/api/auth/register', {+ data: { email, name: 'CLI Reset', password: PASSWORD, confirm_password: PASSWORD },+ });+ expect(register.ok()).toBeTruthy();+ const login = await request.post('/api/auth/login', {+ data: { email, password: PASSWORD },+ });+ expect(login.ok()).toBeTruthy();+ const { token, user } = (await login.json()) as { token: string; user: { _id: string } };+ const authorized = await request.get('/api/user', {+ headers: { Authorization: `Bearer ${token}` },+ });+ expect(authorized.ok()).toBeTruthy();+ await seedPasskey(email, randomUUID(), 'Reset regression');+ await withMongo(async (db) => {+ if (expiresAt) {+ await db+ .collection('users')+ .updateOne({ email }, { $set: { expiresAt, emailVerified: false } });+ }+ const resetUser = await db.collection('users').findOne({ email });+ expect(await db.collection('passkeys').countDocuments({ user: resetUser!._id })).toBe(1);+ expect(+ await db.collection('sessions').countDocuments({ user: resetUser!._id }),+ ).toBeGreaterThan(0);+ });+ const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id}`;+ const documentKeys = ['first', 'second'].map((suffix) => `auth-user-doc:${suffix}`);+ const controlKey = 'auth-user-doc:another-user';+ keys.push(indexKey, ...documentKeys, controlKey);+ // Keep fixtures alive beyond the test deadline so expiry cannot masquerade as eviction.+ await cache.set(indexKey, documentKeys, 120_000);+ for (const key of [...documentKeys, controlKey]) {+ await cache.set(key, { credentialsChangedAt: null }, 120_000);+ expect(await cache.get(key)).toEqual({ credentialsChangedAt: null });+ }+ expect(await cache.get(indexKey)).toEqual(documentKeys);++ const config = {+ USE_REDIS: 'true',+ USE_REDIS_CLUSTER: 'false',+ REDIS_URI: redisUri,+ REDIS_KEY_PREFIX: prefix,+ REDIS_KEY_PREFIX_VAR: '',+ AUTH_USER_CACHE_MODE: 'on',+ FORCED_IN_MEMORY_CACHE_NAMESPACES: '',+ };+ const env = { ...process.env };+ for (const key of Object.keys(config)) {+ delete env[key];+ }+ if (source === 'dotenv') {+ fs.writeFileSync(+ path.join(cwd, '.env'),+ Object.entries(config)+ .map(([key, value]) => `${key}=${JSON.stringify(value)}`)+ .join('\n'),+ { mode: 0o600 },+ );+ } else {+ Object.assign(env, config);+ }++ const cli = await runResetCli(email, cwd, env);+ expect(cli.code, cli.stderr.slice(-400)).toBe(0);+ expect(cli.stdout, `reset CLI stderr: ${cli.stderr.slice(-400)}`).toContain(+ 'Password successfully reset!',+ );+ expect(await cache.get(indexKey)).toBeUndefined();+ for (const key of documentKeys) {+ expect(await cache.get(key), `stale auth cache entry: ${key}`).toBeUndefined();+ }+ expect(await cache.get(controlKey)).toEqual({ credentialsChangedAt: null });+ await withMongo(async (db) => {+ const resetUser = await db.collection('users').findOne({ email });+ expect(resetUser?.credentialsChangedAt).toBeTruthy();+ expect(resetUser?.expiresAt).toEqual(expiresAt);+ if (expiresAt) {+ expect(resetUser?.emailVerified).toBe(false);+ }+ expect(await db.collection('passkeys').countDocuments({ user: resetUser!._id })).toBe(0);+ expect(await db.collection('sessions').countDocuments({ user: resetUser!._id })).toBe(0);+ });++ const rejected = await request.get('/api/user', {+ headers: { Authorization: `Bearer ${token}` },+ });+ expect(rejected.status()).toBe(401);+ const oldLogin = await request.post('/api/auth/login', {+ data: { email, password: PASSWORD },+ });+ expect(oldLogin.status()).toBe(404);+ const newLogin = await request.post('/api/auth/login', {+ data: { email, password: NEW_PASSWORD },+ });+ if (expiresAt) {+ expect(newLogin.status()).toBe(422);+ expect(await newLogin.json()).toEqual({ message: 'Email not verified.' });+ } else {+ expect(newLogin.ok()).toBeTruthy();+ }+ } finally {+ try {+ await Promise.all(keys.map((key) => cache.delete(key)));+ } finally {+ await cache.disconnect();+ await request.dispose();+ fs.rmSync(cwd, { recursive: true, force: true });+ await deleteUserByEmail(email);+ }+ }+ });+ }+});diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.tsindex 6ef431153f..44df9b4cd4 100644--- a/packages/data-schemas/src/methods/user.methods.spec.ts+++ b/packages/data-schemas/src/methods/user.methods.spec.ts@@ -393,6 +393,44 @@ describe('User Methods - Database Tests', () => {expect(updated?.expiresAt).toBeUndefined();});+ test.each([new Date(Date.now() + 604800 * 1000), undefined])(+ 'should preserve expiresAt %s and invalidate auth cache when requested',+ async (expiresAt) => {+ enableAuthUserDocCache();+ const user = await User.create({+ name: 'Pending User',+ email: '[email protected]',+ provider: 'local',+ emailVerified: false,+ expiresAt,+ });+ const userId = user._id?.toString() ?? '';+ const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;+ const cache = {+ get: jest.fn().mockResolvedValue(['auth-cache-key']),+ set: jest.fn().mockResolvedValue(true),+ delete: jest.fn().mockResolvedValue(true),+ };+ const methodsWithCache = createUserMethods(mongoose, { getCache: () => cache });++ const updated = await methodsWithCache.updateUser(+ userId,+ { password: 'new-password-hash', credentialsChangedAt: new Date() },+ {},+ { preserveExpiresAt: true },+ );++ const stored = await User.findById(userId).select('+password').lean();+ expect(stored?.password).toBe('new-password-hash');+ expect(updated?.credentialsChangedAt).toBeInstanceOf(Date);+ expect(updated?.emailVerified).toBe(false);+ expect(updated?.expiresAt).toEqual(expiresAt);+ expect(cache.get).toHaveBeenCalledWith(indexKey);+ expect(cache.delete).toHaveBeenCalledWith('auth-cache-key');+ expect(cache.delete).toHaveBeenCalledWith(indexKey);+ },+ );+test('should update only when the expected account state still matches', async () => {const user = await User.create({name: 'Conditional User',diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.tsindex 5e59490ed5..07de2ded81 100644--- a/packages/data-schemas/src/methods/user.ts+++ b/packages/data-schemas/src/methods/user.ts@@ -53,6 +53,7 @@ export function createUserMethods(userId: string,updateData: Partial<IUser>,expectedState?: FilterQuery<IUser>,+ options?: { preserveExpiresAt?: boolean },) => Promise<IUser | null>;claimSamlIdentity: (userId: string,@@ -307,16 +308,18 @@ export function createUserMethods(/*** Update a user with new data without overwriting existing properties.+ * Removes pending-account expiry unless preserveExpiresAt is requested.*/async function updateUser(userId: string,updateData: Partial<IUser>,expectedState: FilterQuery<IUser> = {},+ options: { preserveExpiresAt?: boolean } = {},): Promise<IUser | null> {const User = mongoose.models.User;const updateOperation = {$set: updateData,- $unset: { expiresAt: '' }, // Remove the expiresAt field to prevent TTL+ ...(options.preserveExpiresAt ? {} : { $unset: { expiresAt: '' } }),};const updated = await User.findOneAndUpdate({ ...expectedState, _id: userId },