mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-09-22 06:00:56 +02:00

* refactor: use keyv for search caching with 1 min expirations * feat: keyvRedis; chore: bump keyv, bun.lockb, add jsconfig for vscode file resolution * feat: api/search redis support * refactor(redis) use ioredis cluster for keyv fix(OpenID): when redis is configured, use redis memory store for express-session * fix: revert using uri for keyvredis * fix(SearchBar): properly debounce search queries, fix weird render behaviors * refactor: add authentication to search endpoint and show error messages in results * feat: redis support for violation logs * fix(logViolation): ensure a number is always being stored in cache * feat(concurrentLimiter): uses clearPendingReq, clears pendingReq on abort, redis support * fix(api/search/enable): query only when authenticated * feat(ModelService): redis support * feat(checkBan): redis support * refactor(api/search): consolidate keyv logic * fix(ci): add default empty value for REDIS_URI * refactor(keyvRedis): use condition to initialize keyvRedis assignment * refactor(connectDb): handle disconnected state (should create a new conn) * fix(ci/e2e): handle case where cleanUp did not successfully run * fix(getDefaultEndpoint): return endpoint from localStorage if defined and endpointsConfig is default * ci(e2e): remove afterAll messages as startup/cleanUp will clear messages * ci(e2e): remove teardown for CI until further notice * chore: bump playwright/test * ci(e2e): reinstate teardown as CI issue is specific to github env * fix(ci): click settings menu trigger by testid
97 lines
3.1 KiB
JavaScript
97 lines
3.1 KiB
JavaScript
const Keyv = require('keyv');
|
|
const uap = require('ua-parser-js');
|
|
const { getLogStores } = require('../../cache');
|
|
const denyRequest = require('./denyRequest');
|
|
const { isEnabled, removePorts } = require('../utils');
|
|
const keyvRedis = require('../../cache/keyvRedis');
|
|
|
|
const banCache = isEnabled(process.env.USE_REDIS)
|
|
? new Keyv({ store: keyvRedis })
|
|
: new Keyv({ namespace: 'bans', 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.
|
|
* @param {String} errorMessage - Error message to be displayed in case of /api/ask or /api/edit request.
|
|
*
|
|
* @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/ask or api/edit types. If it is, calls `denyRequest()` function.
|
|
*/
|
|
const banResponse = async (req, res) => {
|
|
const ua = uap(req.headers['user-agent']);
|
|
const { baseUrl } = req;
|
|
if (!ua.browser.name) {
|
|
return res.status(403).json({ message });
|
|
} else if (baseUrl === '/api/ask' || baseUrl === '/api/edit') {
|
|
return await denyRequest(req, res, { type: '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 {Function} 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 = () => {}) => {
|
|
const { BAN_VIOLATIONS } = process.env ?? {};
|
|
|
|
if (!isEnabled(BAN_VIOLATIONS)) {
|
|
return next();
|
|
}
|
|
|
|
req.ip = removePorts(req);
|
|
const userId = req.user?.id ?? req.user?._id ?? null;
|
|
const ipKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:ip:${req.ip}` : req.ip;
|
|
const userKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:user:${userId}` : userId;
|
|
|
|
const cachedIPBan = await banCache.get(ipKey);
|
|
const cachedUserBan = await banCache.get(userKey);
|
|
const cachedBan = cachedIPBan || cachedUserBan;
|
|
|
|
if (cachedBan) {
|
|
req.banned = true;
|
|
return await banResponse(req, res);
|
|
}
|
|
|
|
const banLogs = getLogStores('ban');
|
|
const duration = banLogs.opts.ttl;
|
|
|
|
if (duration <= 0) {
|
|
return next();
|
|
}
|
|
|
|
const ipBan = await banLogs.get(req.ip);
|
|
const userBan = await banLogs.get(userId);
|
|
const isBanned = ipBan || userBan;
|
|
|
|
if (!isBanned) {
|
|
return next();
|
|
}
|
|
|
|
const timeLeft = Number(isBanned.expiresAt) - Date.now();
|
|
|
|
if (timeLeft <= 0) {
|
|
await banLogs.delete(ipKey);
|
|
await banLogs.delete(userKey);
|
|
return next();
|
|
}
|
|
|
|
banCache.set(ipKey, isBanned, timeLeft);
|
|
banCache.set(userKey, isBanned, timeLeft);
|
|
req.banned = true;
|
|
return await banResponse(req, res);
|
|
};
|
|
|
|
module.exports = checkBan;
|