LibreChat/api/server/routes/oauth.js
Peter bf80cf30b3
*️⃣ feat: Reuse OpenID Auth Tokens (#7397)
* feat: integrate OpenID Connect support with token reuse

- Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality.
- Implemented OpenID token refresh logic in `AuthController`.
- Enhanced `LogoutController` to handle OpenID logout and session termination.
- Updated JWT authentication middleware to support OpenID token provider.
- Modified OAuth routes to accommodate OpenID authentication and token management.
- Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies.
- Upgraded OpenID strategy with user info fetching and token exchange protocol.
- Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens.
- Added caching mechanism for exchanged OpenID tokens.
- Updated configuration to include OpenID exchanged tokens cache key.
- updated .env.example to include the new env variables needed for the feature.

* fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables

* fix: update Jest configuration and tests for OpenID strategy integration

* fix: update OpenID strategy to include callback URL in setup

* fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront)

* fix: fixed code formatting

* Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests

* fix eslint errors: Format mock file openid-client.

*  feat: Add PKCE support for OpenID and default handling in strategy setup

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-23 17:40:40 -04:00

191 lines
3.9 KiB
JavaScript

// file deepcode ignore NoRateLimitingForLogin: Rate limiting is handled by the `loginLimiter` middleware
const express = require('express');
const passport = require('passport');
const {
checkBan,
logHeaders,
loginLimiter,
setBalanceConfig,
checkDomainAllowed,
} = require('~/server/middleware');
const { setAuthTokens, setOpenIDAuthTokens } = require('~/server/services/AuthService');
const { logger } = require('~/config');
const { isEnabled } = require('~/server/utils');
const router = express.Router();
const domains = {
client: process.env.DOMAIN_CLIENT,
server: process.env.DOMAIN_SERVER,
};
router.use(logHeaders);
router.use(loginLimiter);
const oauthHandler = async (req, res) => {
try {
await checkDomainAllowed(req, res);
await checkBan(req, res);
if (req.banned) {
return;
}
if (
req.user &&
req.user.provider == 'openid' &&
isEnabled(process.env.OPENID_REUSE_TOKENS) === true
) {
setOpenIDAuthTokens(req.user.tokenset, res);
} else {
await setAuthTokens(req.user._id, res);
}
res.redirect(domains.client);
} catch (err) {
logger.error('Error in setting authentication tokens:', err);
}
};
router.get('/error', (req, res) => {
// A single error message is pushed by passport when authentication fails.
logger.error('Error in OAuth authentication:', { message: req.session.messages.pop() });
// Redirect to login page with auth_failed parameter to prevent infinite redirect loops
res.redirect(`${domains.client}/login?redirect=false`);
});
/**
* Google Routes
*/
router.get(
'/google',
passport.authenticate('google', {
scope: ['openid', 'profile', 'email'],
session: false,
}),
);
router.get(
'/google/callback',
passport.authenticate('google', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
scope: ['openid', 'profile', 'email'],
}),
setBalanceConfig,
oauthHandler,
);
/**
* Facebook Routes
*/
router.get(
'/facebook',
passport.authenticate('facebook', {
scope: ['public_profile'],
profileFields: ['id', 'email', 'name'],
session: false,
}),
);
router.get(
'/facebook/callback',
passport.authenticate('facebook', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
scope: ['public_profile'],
profileFields: ['id', 'email', 'name'],
}),
setBalanceConfig,
oauthHandler,
);
/**
* OpenID Routes
*/
router.get(
'/openid',
passport.authenticate('openid', {
session: false,
}),
);
router.get(
'/openid/callback',
passport.authenticate('openid', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
}),
setBalanceConfig,
oauthHandler,
);
/**
* GitHub Routes
*/
router.get(
'/github',
passport.authenticate('github', {
scope: ['user:email', 'read:user'],
session: false,
}),
);
router.get(
'/github/callback',
passport.authenticate('github', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
scope: ['user:email', 'read:user'],
}),
setBalanceConfig,
oauthHandler,
);
/**
* Discord Routes
*/
router.get(
'/discord',
passport.authenticate('discord', {
scope: ['identify', 'email'],
session: false,
}),
);
router.get(
'/discord/callback',
passport.authenticate('discord', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
scope: ['identify', 'email'],
}),
setBalanceConfig,
oauthHandler,
);
/**
* Apple Routes
*/
router.get(
'/apple',
passport.authenticate('apple', {
session: false,
}),
);
router.post(
'/apple/callback',
passport.authenticate('apple', {
failureRedirect: `${domains.client}/oauth/error`,
failureMessage: true,
session: false,
}),
setBalanceConfig,
oauthHandler,
);
module.exports = router;