LibreChat/api/server/middleware/uaParser.js
Theo N. Truong 01b012a8fa
🏦 refactor: Centralize Caching & Redis Key Prefixing (#8457)
* 🔧 Overhauled caching feature:
- Refactored caching logic.
- Fixed redis prefix, namespace, tls, ttl, and cluster.
- Added REDIS_KEY_PREFIX_VAR

* # refactor: Rename redisCache to standardCache

* # Add Redis pinging mechanism to maintain connection.

* # docs: Add warning about Keyv Redis client prefix support
2025-07-15 18:24:31 -04:00

32 lines
1.1 KiB
JavaScript

const uap = require('ua-parser-js');
const { ViolationTypes } = require('librechat-data-provider');
const { handleError } = require('@librechat/api');
const { logViolation } = require('../../cache');
/**
* Middleware to parse User-Agent header and check if it's from a recognized browser.
* If the User-Agent is not recognized as a browser, logs a violation and sends an error response.
*
* @function
* @async
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @param {Function} next - Express next middleware function.
* @returns {void} Sends an error response if the User-Agent is not recognized as a browser.
*
* @example
* app.use(uaParser);
*/
async function uaParser(req, res, next) {
const { NON_BROWSER_VIOLATION_SCORE: score = 20 } = process.env;
const ua = uap(req.headers['user-agent']);
if (!ua.browser.name) {
const type = ViolationTypes.NON_BROWSER;
await logViolation(req, res, type, { type }, score);
return handleError(res, { message: 'Illegal request' });
}
next();
}
module.exports = uaParser;