LibreChat/api/cache/banViolation.js
Jón Levy dc89e00039
🪙 refactor: Distinguish ID Tokens from Access Tokens in OIDC Federated Auth (#11711)
* fix(openid): distinguish ID tokens from access tokens in federated auth

Fix OpenID Connect token handling to properly distinguish ID tokens from access tokens. ID tokens and access tokens are now stored and propagated separately, preventing token placeholders from resolving to identical values.

- AuthService.js: Added idToken field to session storage
- openIdJwtStrategy.js: Updated to read idToken from session
- openidStrategy.js: Explicitly included id_token in federatedTokens
- Test suites: Added comprehensive test coverage for token distinction

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(openid): add separate openid_id_token cookie for ID token storage

Store the OIDC ID token in its own cookie rather than relying solely on
the access token, ensuring correct token type is used for identity
verification vs API authorization.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test(openid): add JWT strategy cookie fallback tests

Cover the token source resolution logic in openIdJwtStrategy:
session-only, cookie-only, partial session fallback, raw Bearer
fallback, and distinct id_token/access_token from cookies.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 11:07:39 -05:00

87 lines
2.8 KiB
JavaScript

const { logger } = require('@librechat/data-schemas');
const { isEnabled, math } = require('@librechat/api');
const { ViolationTypes } = require('librechat-data-provider');
const { deleteAllUserSessions } = require('~/models');
const { removePorts } = require('~/server/utils');
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 });
/** Clear OpenID session tokens if present */
if (req.session?.openidTokens) {
delete req.session.openidTokens;
}
res.clearCookie('refreshToken');
res.clearCookie('openid_access_token');
res.clearCookie('openid_id_token');
res.clearCookie('openid_user_id');
res.clearCookie('token_provider');
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;