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

157 lines
5 KiB
TypeScript

import jwt from 'jsonwebtoken';
import { createHash } from 'node:crypto';
import { rateLimit } from 'express-rate-limit';
import { ViolationTypes } from 'librechat-data-provider';
import type { NextFunction, Request, Response } from 'express';
import type { Store } from 'express-rate-limit';
import type { TwoFactorTempRequest } from './tempuser';
type ViolationMessage = {
type: ViolationTypes;
max: string | number;
limiter: string;
windowInMinutes: number;
};
export interface TwoFactorLimiterDependencies {
env: NodeJS.ProcessEnv;
limiterCache: (prefix: string) => Store | undefined;
removePorts: (req: Request) => string | undefined;
logViolation: (
req: Request,
res: Response,
type: ViolationTypes,
message: ViolationMessage,
score: string | number | undefined,
) => Promise<void>;
}
interface TwoFactorLimiterPolicy {
namespace: string;
windowMinutes: string | number;
max: string | number;
score: string | number | undefined;
describeAttempts: string;
}
export function createTwoFactorLimiter(
deps: TwoFactorLimiterDependencies,
policy: TwoFactorLimiterPolicy,
) {
const { namespace, max, score, describeAttempts } = policy;
const windowMs = Number(policy.windowMinutes) * 60 * 1000;
const windowInMinutes = windowMs / 60000;
const message = `Too many ${describeAttempts}, please try again after ${windowInMinutes} minutes.`;
const getEnrollmentToken = (req: TwoFactorTempRequest): string | undefined =>
req.body?.[req.twoFactorTokenField ?? 'tempToken'];
const getUserLimiterKey = (req: Request): string => {
const tempReq = req as TwoFactorTempRequest;
const userId = tempReq.user?.id ?? tempReq.user?._id;
if (userId) {
return `user:${userId.toString()}`;
}
const token = getEnrollmentToken(tempReq);
if (typeof token === 'string' && token) {
return `temp:${createHash('sha256').update(token).digest('hex')}`;
}
const ip = deps.removePorts(req);
return ip ? `ip:${ip}` : 'ip:unknown';
};
const getTempTokenUserId = (token: string | undefined): string | null => {
if (!token) {
return null;
}
try {
const payload = jwt.verify(token, deps.env.JWT_SECRET ?? '');
return typeof payload === 'object' && typeof payload.userId === 'string'
? payload.userId
: null;
} catch {
return null;
}
};
const createHandler =
(limiter: string) =>
async (req: Request, res: Response): Promise<Response> => {
const type = ViolationTypes.LOGINS;
const errorMessage = { type, max, limiter, windowInMinutes };
const tempReq = req as TwoFactorTempRequest;
const userId = getTempTokenUserId(getEnrollmentToken(tempReq));
if (userId && !tempReq.user) {
tempReq.user = { id: userId };
} else if (userId && tempReq.user && !tempReq.user.id && !tempReq.user._id) {
tempReq.user.id = userId;
}
await deps.logViolation(req, res, type, errorMessage, score);
return res.status(429).json({ message });
};
const ipLimiter = rateLimit({
windowMs,
max: Number(max),
skip: (req) =>
namespace === 'two_factor_setup' &&
Boolean((req as TwoFactorTempRequest).user?.id ?? (req as TwoFactorTempRequest).user?._id),
handler: createHandler('ip'),
keyGenerator: deps.removePorts as (req: Request) => string,
store: deps.limiterCache(`${namespace}_limiter`),
});
const userLimiter = rateLimit({
windowMs,
max: Number(max),
handler: createHandler('user'),
keyGenerator: getUserLimiterKey,
store: deps.limiterCache(`${namespace}_user_limiter`),
});
return (req: Request, res: Response, next: NextFunction): void => {
ipLimiter(req, res, (error) => {
if (error) {
next(error);
return;
}
userLimiter(req, res, next);
});
};
}
export function createTwoFactorLimiters(deps: TwoFactorLimiterDependencies): {
twoFactorTempLimiter: (req: Request, res: Response, next: NextFunction) => void;
twoFactorSetupLimiter: (req: Request, res: Response, next: NextFunction) => void;
} {
const {
LOGIN_WINDOW = 5,
LOGIN_MAX = 7,
LOGIN_VIOLATION_SCORE,
TWO_FACTOR_TEMP_WINDOW = LOGIN_WINDOW,
TWO_FACTOR_TEMP_MAX = LOGIN_MAX,
TWO_FACTOR_TEMP_VIOLATION_SCORE,
TWO_FACTOR_SETUP_WINDOW = TWO_FACTOR_TEMP_WINDOW,
TWO_FACTOR_SETUP_MAX = 20,
TWO_FACTOR_SETUP_VIOLATION_SCORE,
} = deps.env;
return {
twoFactorTempLimiter: createTwoFactorLimiter(deps, {
namespace: 'two_factor_temp',
windowMinutes: TWO_FACTOR_TEMP_WINDOW,
max: TWO_FACTOR_TEMP_MAX,
score: TWO_FACTOR_TEMP_VIOLATION_SCORE ?? LOGIN_VIOLATION_SCORE,
describeAttempts: 'verification attempts',
}),
twoFactorSetupLimiter: createTwoFactorLimiter(deps, {
namespace: 'two_factor_setup',
windowMinutes: TWO_FACTOR_SETUP_WINDOW,
max: TWO_FACTOR_SETUP_MAX,
score:
TWO_FACTOR_SETUP_VIOLATION_SCORE ??
TWO_FACTOR_TEMP_VIOLATION_SCORE ??
LOGIN_VIOLATION_SCORE,
describeAttempts: 'two-factor setup requests',
}),
};
}