LibreChat/api/server/middleware/checkBan.js
Danny Avila 656e1abaea
🪦 refactor: Remove Legacy Code (#10533)
* 🗑️ chore: Remove unused Legacy Provider clients and related helpers

* Deleted OpenAIClient and GoogleClient files along with their associated tests.
* Removed references to these clients in the clients index file.
* Cleaned up typedefs by removing the OpenAISpecClient export.
* Updated chat controllers to use the OpenAI SDK directly instead of the removed client classes.

* chore/remove-openapi-specs

* 🗑️ chore: Remove unused mergeSort and misc utility functions

* Deleted mergeSort.js and misc.js files as they are no longer needed.
* Removed references to cleanUpPrimaryKeyValue in messages.js and adjusted related logic.
* Updated mongoMeili.ts to eliminate local implementations of removed functions.

* chore: remove legacy endpoints

* chore: remove all plugins endpoint related code

* chore: remove unused prompt handling code and clean up imports

* Deleted handleInputs.js and instructions.js files as they are no longer needed.
* Removed references to these files in the prompts index.js.
* Updated docker-compose.yml to simplify reverse proxy configuration.

* chore: remove unused LightningIcon import from Icons.tsx

* chore: clean up translation.json by removing deprecated and unused keys

* chore: update Jest configuration and remove unused mock file

    * Simplified the setupFiles array in jest.config.js by removing the fetchEventSource mock.
    * Deleted the fetchEventSource.js mock file as it is no longer needed.

* fix: simplify endpoint type check in Landing and ConversationStarters components

    * Updated the endpoint type check to use strict equality for better clarity and performance.
    * Ensured consistency in the handling of the azureOpenAI endpoint across both components.

* chore: remove unused dependencies from package.json and package-lock.json

* chore: remove legacy EditController, associated routes and imports

* chore: update banResponse logic to refine request handling for banned users

* chore: remove unused validateEndpoint middleware and its references

* chore: remove unused 'res' parameter from initializeClient in multiple endpoint files

* chore: remove unused 'isSmallScreen' prop from BookmarkNav and NewChat components; clean up imports in ArchivedChatsTable and useSetIndexOptions hooks; enhance localization in PromptVersions

* chore: remove unused import of Constants and TMessage from MobileNav; retain only necessary QueryKeys import

* chore: remove unused TResPlugin type and related references; clean up imports in types and schemas
2025-12-11 16:36:12 -05:00

141 lines
3.8 KiB
JavaScript

const { Keyv } = require('keyv');
const uap = require('ua-parser-js');
const { logger } = require('@librechat/data-schemas');
const { isEnabled, keyvMongo } = require('@librechat/api');
const { ViolationTypes } = require('librechat-data-provider');
const { removePorts } = require('~/server/utils');
const denyRequest = require('./denyRequest');
const { getLogStores } = require('~/cache');
const { findUser } = require('~/models');
const banCache = new Keyv({ store: keyvMongo, namespace: ViolationTypes.BAN, ttl: 0 });
const message = 'Your account has been temporarily banned due to violations of our service.';
/**
* Respond to the request if the user is banned.
*
* @async
* @function
* @param {Object} req - Express Request object.
* @param {Object} res - Express Response object.
*
* @returns {Promise<Object>} - Returns a Promise which when resolved sends a response status of 403 with a specific message if request is not of api/agents/chat. If it is, calls `denyRequest()` function.
*/
const banResponse = async (req, res) => {
const ua = uap(req.headers['user-agent']);
const { baseUrl, originalUrl } = req;
if (!ua.browser.name) {
return res.status(403).json({ message });
} else if (baseUrl === '/api/agents' && originalUrl.startsWith('/api/agents/chat')) {
return await denyRequest(req, res, { type: ViolationTypes.BAN });
}
return res.status(403).json({ message });
};
/**
* Checks if the source IP or user is banned or not.
*
* @async
* @function
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @param {import('express').NextFunction} next - Next middleware function.
*
* @returns {Promise<function|Object>} - Returns a Promise which when resolved calls next middleware if user or source IP is not banned. Otherwise calls `banResponse()` and sets ban details in `banCache`.
*/
const checkBan = async (req, res, next = () => {}) => {
try {
const { BAN_VIOLATIONS } = process.env ?? {};
if (!isEnabled(BAN_VIOLATIONS)) {
return next();
}
req.ip = removePorts(req);
let userId = req.user?.id ?? req.user?._id ?? null;
if (!userId && req?.body?.email) {
const user = await findUser({ email: req.body.email }, '_id');
userId = user?._id ? user._id.toString() : userId;
}
if (!userId && !req.ip) {
return next();
}
let cachedIPBan;
let cachedUserBan;
let ipKey = '';
let userKey = '';
if (req.ip) {
ipKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:ip:${req.ip}` : req.ip;
cachedIPBan = await banCache.get(ipKey);
}
if (userId) {
userKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:user:${userId}` : userId;
cachedUserBan = await banCache.get(userKey);
}
const cachedBan = cachedIPBan || cachedUserBan;
if (cachedBan) {
req.banned = true;
return await banResponse(req, res);
}
const banLogs = getLogStores(ViolationTypes.BAN);
const duration = banLogs.opts.ttl;
if (duration <= 0) {
return next();
}
let ipBan;
let userBan;
if (req.ip) {
ipBan = await banLogs.get(req.ip);
}
if (userId) {
userBan = await banLogs.get(userId);
}
const isBanned = !!(ipBan || userBan);
if (!isBanned) {
return next();
}
const timeLeft = Number(isBanned.expiresAt) - Date.now();
if (timeLeft <= 0 && ipKey) {
await banLogs.delete(ipKey);
}
if (timeLeft <= 0 && userKey) {
await banLogs.delete(userKey);
return next();
}
if (ipKey) {
banCache.set(ipKey, isBanned, timeLeft);
}
if (userKey) {
banCache.set(userKey, isBanned, timeLeft);
}
req.banned = true;
return await banResponse(req, res);
} catch (error) {
logger.error('Error in checkBan middleware:', error);
return next(error);
}
};
module.exports = checkBan;