LibreChat/api/cache/banViolation.js
Danny Avila a2fc7d312a
🏗️ refactor: Extract DB layers to data-schemas for shared use (#7650)
* refactor: move model definitions and database-related methods to packages/data-schemas

* ci: update tests due to new DB structure

fix: disable mocking `librechat-data-provider`

feat: Add schema exports to data-schemas package

- Introduced a new schema module that exports various schemas including action, agent, and user schemas.
- Updated index.ts to include the new schema exports for better modularity and organization.

ci: fix appleStrategy tests

fix: Agent.spec.js

ci: refactor handleTools tests to use MongoMemoryServer for in-memory database

fix: getLogStores imports

ci: update banViolation tests to use MongoMemoryServer and improve session mocking

test: refactor samlStrategy tests to improve mock configurations and user handling

ci: fix crypto mock in handleText tests for improved accuracy

ci: refactor spendTokens tests to improve model imports and setup

ci: refactor Message model tests to use MongoMemoryServer and improve database interactions

* refactor: streamline IMessage interface and move feedback properties to types/message.ts

* refactor: use exported initializeRoles from `data-schemas`, remove api workspace version (this serves as an example of future migrations that still need to happen)

* refactor: update model imports to use destructuring from `~/db/models` for consistency and clarity

* refactor: remove unused mongoose imports from model files for cleaner code

* refactor: remove unused mongoose imports from Share, Prompt, and Transaction model files for cleaner code

* refactor: remove unused import in Transaction model for cleaner code

* ci: update deploy workflow to reference new Docker Dev Branch Images Build and add new workflow for building Docker images on dev branch

* chore: cleanup imports
2025-05-30 22:18:13 -04:00

76 lines
2.5 KiB
JavaScript

const { logger } = require('@librechat/data-schemas');
const { ViolationTypes } = require('librechat-data-provider');
const { isEnabled, math, removePorts } = require('~/server/utils');
const { deleteAllUserSessions } = require('~/models');
const getLogStores = require('./getLogStores');
const { BAN_VIOLATIONS, BAN_INTERVAL } = process.env ?? {};
const interval = math(BAN_INTERVAL, 20);
/**
* Bans a user based on violation criteria.
*
* If the user's violation count is a multiple of the BAN_INTERVAL, the user will be banned.
* The duration of the ban is determined by the BAN_DURATION environment variable.
* If BAN_DURATION is not set or invalid, the user will not be banned.
* Sessions will be deleted and the refreshToken cookie will be cleared even with
* an invalid or nill duration, which is a "soft" ban; the user can remain active until
* access token expiry.
*
* @async
* @param {Object} req - Express request object containing user information.
* @param {Object} res - Express response object.
* @param {Object} errorMessage - Object containing user violation details.
* @param {string} errorMessage.type - Type of the violation.
* @param {string} errorMessage.user_id - ID of the user who committed the violation.
* @param {number} errorMessage.violation_count - Number of violations committed by the user.
*
* @returns {Promise<void>}
*
*/
const banViolation = async (req, res, errorMessage) => {
if (!isEnabled(BAN_VIOLATIONS)) {
return;
}
if (!errorMessage) {
return;
}
const { type, user_id, prev_count, violation_count } = errorMessage;
const prevThreshold = Math.floor(prev_count / interval);
const currentThreshold = Math.floor(violation_count / interval);
if (prevThreshold >= currentThreshold) {
return;
}
await deleteAllUserSessions({ userId: user_id });
res.clearCookie('refreshToken');
const banLogs = getLogStores(ViolationTypes.BAN);
const duration = errorMessage.duration || banLogs.opts.ttl;
if (duration <= 0) {
return;
}
req.ip = removePorts(req);
logger.info(
`[BAN] Banning user ${user_id} ${req.ip ? `@ ${req.ip} ` : ''}for ${
duration / 1000 / 60
} minutes`,
);
const expiresAt = Date.now() + duration;
await banLogs.set(user_id, { type, violation_count, duration, expiresAt });
if (req.ip) {
await banLogs.set(req.ip, { type, user_id, violation_count, duration, expiresAt });
}
errorMessage.ban = true;
errorMessage.ban_duration = duration;
return;
};
module.exports = banViolation;