LibreChat/api/server/middleware/uaParser.js
Danny Avila 2e1874e596
🔧 fix: handleError import path to use '@librechat/api' (#8415)
* 🔧 fix: Update handleError import path to use '@librechat/api' in middleware files

* chore: import order

* chore: import order

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
2025-07-11 13:29:51 -04:00

31 lines
1,023 B
JavaScript

const uap = require('ua-parser-js');
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 = 'non_browser';
await logViolation(req, res, type, { type }, score);
return handleError(res, { message: 'Illegal request' });
}
next();
}
module.exports = uaParser;