LibreChat/packages/api/src/auth/userDocCache.ts
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

212 lines
5.8 KiB
TypeScript

import { createHash } from 'crypto';
import { logger, evictAuthUserDocs } from '@librechat/data-schemas';
import {
CacheKeys,
AUTH_USER_DOC_BY_ID_PREFIX,
AUTH_USER_DOC_CACHE_TTL_MS,
} from 'librechat-data-provider';
import type { IUser } from '@librechat/data-schemas';
import { cacheConfig } from '~/cache/cacheConfig';
const AUTH_USER_DOC_CACHE_VERSION = 2;
export { AUTH_USER_DOC_CACHE_TTL_MS };
export type AuthUserDocCacheMode = 'off' | 'on';
export interface AuthUserDocCacheStore {
get: <T = unknown>(key: string) => Promise<T | undefined>;
set: (key: string, value: unknown, ttl?: number) => Promise<unknown>;
delete: (key: string) => Promise<unknown>;
}
export interface AuthUserDocCacheKeyInput {
strategy: string;
subject?: string;
issuer?: string;
tenantId?: string;
userId?: string;
scope?: string;
}
interface CachedAuthUserDoc {
version: number;
cachedAt: number;
user: CachedAuthUser;
}
type CachedAuthUser = Omit<Partial<IUser>, '_id'> & {
_id?: string;
id?: string;
};
type UserIdInput = {
_id?: string | { toString(): string };
id?: string;
};
let warnedAuthUserDocCacheRequiresRedis = false;
export function getAuthUserDocCacheTtlMs(): number {
return AUTH_USER_DOC_CACHE_TTL_MS;
}
function isAuthUserDocCacheRedisBacked(): boolean {
return (
cacheConfig.USE_REDIS &&
!cacheConfig.FORCED_IN_MEMORY_CACHE_NAMESPACES?.includes(CacheKeys.AUTH_USER_DOC)
);
}
export function getAuthUserDocCacheMode(): AuthUserDocCacheMode {
if (process.env.AUTH_USER_CACHE_MODE !== 'on') {
return 'off';
}
if (!isAuthUserDocCacheRedisBacked()) {
if (!warnedAuthUserDocCacheRequiresRedis) {
warnedAuthUserDocCacheRequiresRedis = true;
logger.warn(
'[authUserDocCache] User request burst caching requires Redis; disabling auth user cache',
);
}
return 'off';
}
return 'on';
}
function normalizeKeyPart(value: string | undefined): string {
return (value ?? '').trim().toLowerCase().replace(/\/+$/, '');
}
function normalizeExactKeyPart(value: string | undefined): string {
return (value ?? '').trim();
}
export function buildAuthUserDocCacheKey(input: AuthUserDocCacheKeyInput): string | undefined {
const strategy = input.strategy.trim();
const subject = input.subject?.trim();
if (!strategy || !subject) {
return undefined;
}
const digest = createHash('sha256')
.update(
[
normalizeKeyPart(strategy),
subject,
normalizeKeyPart(input.issuer),
normalizeExactKeyPart(input.tenantId),
normalizeExactKeyPart(input.userId),
normalizeKeyPart(input.scope),
].join('\0'),
)
.digest('base64url');
return `auth-user-doc:v${AUTH_USER_DOC_CACHE_VERSION}:${digest}`;
}
function getUserId(user: UserIdInput): string | undefined {
const id = user._id ?? user.id;
if (id == null) {
return undefined;
}
return typeof id === 'string' ? id : id.toString();
}
export function buildAuthUserDocReverseIndexKey(userId: string): string {
return `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;
}
function sanitizeUserForCache(user: Partial<IUser>): CachedAuthUser {
const id = getUserId(user);
const { _id: _ignored, ...rest } = user;
const sanitized: CachedAuthUser = { ...rest };
if (id) {
sanitized._id = id;
sanitized.id = id;
}
delete sanitized.password;
delete sanitized.refreshToken;
delete sanitized.totpSecret;
delete sanitized.pendingTotpSecret;
delete sanitized.backupCodes;
delete sanitized.pendingBackupCodes;
delete sanitized.twoFactorAcknowledgementNonceHash;
delete sanitized.twoFactorFinalizationNonceHash;
delete sanitized.federatedTokens;
delete sanitized.openidTokens;
return sanitized;
}
async function rememberUserCacheKey(
store: AuthUserDocCacheStore,
userId: string,
cacheKey: string,
ttlMs: number,
): Promise<void> {
const indexKey = buildAuthUserDocReverseIndexKey(userId);
const existing = await store.get<string[]>(indexKey);
const keys = Array.isArray(existing) ? existing.filter((value) => value !== cacheKey) : [];
keys.push(cacheKey);
await store.set(indexKey, keys.slice(-20), ttlMs);
}
export async function getCachedAuthUserDoc(
store: AuthUserDocCacheStore,
cacheKey: string,
): Promise<CachedAuthUser | undefined> {
try {
const cached = await store.get<CachedAuthUserDoc>(cacheKey);
if (!cached || cached.version !== AUTH_USER_DOC_CACHE_VERSION || !cached.user) {
return undefined;
}
return cached.user;
} catch (error) {
logger.warn('[authUserDocCache] Cache read failed; falling back to user lookup', {
error: error instanceof Error ? error.message : String(error),
});
return undefined;
}
}
/**
* The reverse index is written first and outlives every document it names, so eviction can
* always find a cached document: when the index write fails, the document is not cached.
*/
export async function setCachedAuthUserDoc(
store: AuthUserDocCacheStore,
cacheKey: string,
user: Partial<IUser>,
): Promise<void> {
try {
const sanitized = sanitizeUserForCache(user);
const userId = getUserId(sanitized);
if (userId) {
await rememberUserCacheKey(store, userId, cacheKey, AUTH_USER_DOC_CACHE_TTL_MS * 2);
}
await store.set(
cacheKey,
{
version: AUTH_USER_DOC_CACHE_VERSION,
cachedAt: Date.now(),
user: sanitized,
} satisfies CachedAuthUserDoc,
AUTH_USER_DOC_CACHE_TTL_MS,
);
} catch (error) {
logger.warn('[authUserDocCache] Cache write failed', {
error: error instanceof Error ? error.message : String(error),
});
}
}
export async function invalidateCachedAuthUserDoc(
store: AuthUserDocCacheStore | undefined,
input: { userId?: string; cacheKey?: string },
): Promise<void> {
if (!store) {
return;
}
await evictAuthUserDocs(store, input);
}