LibreChat/api/server/middleware/optionalJwtAuth.js
Danny Avila c67e2b54dc
🔐 feat: Mint Code API Auth Tokens (#13028)
* feat: Mint CodeAPI auth tokens

* style: Format CodeAPI download route

* fix: Prune CodeAPI token cache

* fix: Propagate CodeAPI managed auth

* test: Mock CodeAPI auth in traversal suite

* fix: Pass auth context to invoked skill cache

* feat: Mint CodeAPI plan context

* chore: Refresh CodeAPI auth guidance

* fix: Guard OpenID JWT fallback

* fix: Default CodeAPI JWT tenant in single-tenant mode

* chore: Update @librechat/agents to version 3.1.84 in package-lock.json and package.json files

* chore: Standardize references to Code API in comments and tests
2026-05-09 16:09:10 -04:00

35 lines
1.2 KiB
JavaScript

const cookies = require('cookie');
const passport = require('passport');
const { isEnabled, tenantContextMiddleware } = require('@librechat/api');
const hasPassportStrategy = (strategy) =>
typeof passport._strategy === 'function' && passport._strategy(strategy) != null;
// This middleware does not require authentication,
// but if the user is authenticated, it will set the user object
// and establish tenant ALS context.
const optionalJwtAuth = (req, res, next) => {
const cookieHeader = req.headers.cookie;
const tokenProvider = cookieHeader ? cookies.parse(cookieHeader).token_provider : null;
const useOpenIdJwt =
tokenProvider === 'openid' &&
isEnabled(process.env.OPENID_REUSE_TOKENS) &&
hasPassportStrategy('openidJwt');
const callback = (err, user) => {
if (err) {
return next(err);
}
if (user) {
req.user = user;
req.authStrategy = useOpenIdJwt ? 'openidJwt' : 'jwt';
return tenantContextMiddleware(req, res, next);
}
next();
};
if (useOpenIdJwt) {
return passport.authenticate('openidJwt', { session: false }, callback)(req, res, next);
}
passport.authenticate('jwt', { session: false }, callback)(req, res, next);
};
module.exports = optionalJwtAuth;