LibreChat/api/strategies/openIdJwtStrategy.js

53 lines
1.9 KiB
JavaScript
Raw Normal View History

*️⃣ 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-22 14:19:24 +02:00
const { SystemRoles } = require('librechat-data-provider');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const { updateUser, findUser } = require('~/models');
const { logger } = require('~/config');
const jwksRsa = require('jwks-rsa');
const { isEnabled } = require('~/server/utils');
/**
* @function openIdJwtLogin
* @param {import('openid-client').Configuration} openIdConfig - Configuration object for the JWT strategy.
* @returns {JwtStrategy}
* @description This function creates a JWT strategy for OpenID authentication.
* It uses the jwks-rsa library to retrieve the signing key from a JWKS endpoint.
* The strategy extracts the JWT from the Authorization header as a Bearer token.
* The JWT is then verified using the signing key, and the user is retrieved from the database.
*/
const openIdJwtLogin = (openIdConfig) =>
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: jwksRsa.passportJwtSecret({
cache: isEnabled(process.env.OPENID_JWKS_URL_CACHE_ENABLED) || true,
cacheMaxAge: process.env.OPENID_JWKS_URL_CACHE_TIME
? eval(process.env.OPENID_JWKS_URL_CACHE_TIME)
: 60000,
jwksUri: openIdConfig.serverMetadata().jwks_uri,
}),
},
async (payload, done) => {
try {
const user = await findUser({ openidId: payload?.sub });
if (user) {
user.id = user._id.toString();
if (!user.role) {
user.role = SystemRoles.USER;
await updateUser(user.id, { role: user.role });
}
done(null, user);
} else {
logger.warn(
'[openIdJwtLogin] openId JwtStrategy => no user found with the sub claims: ' +
payload?.sub,
);
done(null, false);
}
} catch (err) {
done(err, false);
}
},
);
module.exports = openIdJwtLogin;