Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔁 feat: Retry OpenID Discovery After Startup Failures (#15899)

Danny Avila854645ffc0e7
diff --git a/.env.example b/.env.example
index 42b88f61bc..b310ffe2cc 100644
--- a/.env.example
+++ b/.env.example
@@ -987,6 +987,12 @@ OPENID_REUSE_TOKENS=
#is not rotated/revoked out from under downstream consumers (e.g. MCP servers that introspect the bearer).
#When OPENID_REUSE_TOKENS=true, the OpenID session cookie maxAge is extended to at least this value.
OPENID_REUSE_MAX_SESSION_AGE_MS=
+# Discovery attempts during startup (0-100, default 1). Set to 0 to use background retries only.
+# librechat.yaml `registration.openidDiscovery.startupAttempts` takes precedence.
+OPENID_DISCOVERY_RETRY_ATTEMPTS=
+# Delay in milliseconds between startup and background discovery retries (100-3600000, default 5000).
+# librechat.yaml `registration.openidDiscovery.retryDelayMs` takes precedence.
+OPENID_DISCOVERY_RETRY_DELAY_MS=
#Short recovery window for a rotated OpenID refresh token while LibreChat publishes the refreshed session. Default 60000 ms (1 min).
#Accepts arithmetic expressions. Increase only when slow session persistence or cross-replica publication needs more time.
OPENID_REFRESH_BRIDGE_GRACE_MS=
diff --git a/api/server/socialLogins.js b/api/server/socialLogins.js
index 8da813f240..138718fd2b 100644
--- a/api/server/socialLogins.js
+++ b/api/server/socialLogins.js
@@ -1,7 +1,12 @@
const passport = require('passport');
const session = require('express-session');
const { CacheKeys } = require('librechat-data-provider');
-const { math, isEnabled, shouldUseSecureCookie } = require('@librechat/api');
+const {
+ math,
+ isEnabled,
+ shouldUseSecureCookie,
+ registerOpenIdWithRetry,
+} = require('@librechat/api');
const { logger, DEFAULT_SESSION_EXPIRY } = require('@librechat/data-schemas');
const {
openIdJwtLogin,
@@ -21,7 +26,6 @@ const {
const { getLogStores } = require('~/cache');
const DEFAULT_OPENID_REUSE_MAX_SESSION_AGE_MS = 15 * 60 * 1000;
-
const getSessionExpiry = () => math(process.env.SESSION_EXPIRY, DEFAULT_SESSION_EXPIRY);
const getOpenIdSessionExpiry = () => {
@@ -40,9 +44,10 @@ const getOpenIdSessionExpiry = () => {
/**
* Configures OpenID Connect for the application.
* @param {Express.Application} app - The Express application instance.
+ * @param {AppConfig} [appConfig] - Base app config, read for OpenID discovery retry settings.
* @returns {Promise<void>}
*/
-async function configureOpenId(app) {
+async function configureOpenId(app, appConfig) {
logger.info('Configuring OpenID Connect...');
const sessionExpiry = getOpenIdSessionExpiry();
const sessionOptions = {
@@ -58,17 +63,16 @@ async function configureOpenId(app) {
app.use(session(sessionOptions));
app.use(passport.session());
- const config = await setupOpenId();
- if (!config) {
- logger.error('OpenID Connect configuration failed - strategy not registered.');
- return;
- }
-
- if (isEnabled(process.env.OPENID_REUSE_TOKENS)) {
- logger.info('OpenID token reuse is enabled.');
- passport.use('openidJwt', openIdJwtLogin(config));
- }
- logger.info('OpenID Connect configured successfully.');
+ await registerOpenIdWithRetry({
+ setupOpenId,
+ registerJwtStrategy: (config) => passport.use('openidJwt', openIdJwtLogin(config)),
+ reuseTokens: isEnabled(process.env.OPENID_REUSE_TOKENS),
+ discovery: appConfig?.registration?.openidDiscovery,
+ env: {
+ startupAttempts: process.env.OPENID_DISCOVERY_RETRY_ATTEMPTS,
+ retryDelayMs: process.env.OPENID_DISCOVERY_RETRY_DELAY_MS,
+ },
+ });
}
/**
@@ -111,7 +115,7 @@ const configureSocialLogins = async (app, appConfig) => {
process.env.OPENID_SCOPE &&
process.env.OPENID_SESSION_SECRET
) {
- await configureOpenId(app);
+ await configureOpenId(app, appConfig);
}
if (
process.env.SAML_ENTRY_POINT &&
diff --git a/api/server/socialLogins.spec.js b/api/server/socialLogins.spec.js
index c4bd4b8bd4..cbf6e19a5c 100644
--- a/api/server/socialLogins.spec.js
+++ b/api/server/socialLogins.spec.js
@@ -9,6 +9,14 @@ const mockSetupOpenId = jest.fn();
const mockSetupSaml = jest.fn();
const mockIsEnabled = jest.fn();
const mockShouldUseSecureCookie = jest.fn(() => true);
+const mockRegisterOpenIdWithRetry = jest.fn(
+ async ({ setupOpenId, registerJwtStrategy, reuseTokens }) => {
+ const config = await setupOpenId();
+ if (config && reuseTokens) {
+ registerJwtStrategy(config);
+ }
+ },
+);
const mockMath = jest.fn((value, fallback) => {
if (value == null || value === '') {
return fallback;
@@ -42,10 +50,11 @@ jest.mock('@librechat/api', () => ({
math: (...args) => mockMath(...args),
isEnabled: (...args) => mockIsEnabled(...args),
shouldUseSecureCookie: (...args) => mockShouldUseSecureCookie(...args),
+ registerOpenIdWithRetry: (...args) => mockRegisterOpenIdWithRetry(...args),
}));
jest.mock('@librechat/data-schemas', () => ({
DEFAULT_SESSION_EXPIRY: 900000,
- logger: { error: jest.fn(), info: jest.fn() },
+ logger: { error: jest.fn(), info: jest.fn(), warn: jest.fn() },
}));
jest.mock('~/cache', () => ({ getLogStores: (...args) => mockGetLogStores(...args) }));
jest.mock('~/strategies', () => ({
@@ -90,6 +99,10 @@ describe('configureSocialLogins OpenID session expiry', () => {
process.env = ORIGINAL_ENV;
});
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
it('extends the OpenID session cookie to the reuse window when token reuse is enabled', async () => {
process.env.SESSION_EXPIRY = '1000 * 60 * 15';
process.env.OPENID_REUSE_TOKENS = 'true';
@@ -140,6 +153,24 @@ describe('configureSocialLogins OpenID session expiry', () => {
);
expect(mockPassportUse).not.toHaveBeenCalled();
});
+
+ it('passes OpenID strategy wiring and both retry sources to the API package', async () => {
+ process.env.OPENID_DISCOVERY_RETRY_ATTEMPTS = '2';
+ process.env.OPENID_DISCOVERY_RETRY_DELAY_MS = '1000';
+ const discovery = { startupAttempts: 0, retryDelayMs: 250 };
+ const app = { use: jest.fn() };
+
+ await configureSocialLogins(app, { registration: { openidDiscovery: discovery } });
+
+ expect(mockRegisterOpenIdWithRetry).toHaveBeenCalledWith({
+ setupOpenId: expect.any(Function),
+ registerJwtStrategy: expect.any(Function),
+ reuseTokens: false,
+ discovery,
+ env: { startupAttempts: '2', retryDelayMs: '1000' },
+ });
+ expect(mockSetupOpenId).toHaveBeenCalledTimes(1);
+ });
});
describe('configureSocialLogins OAuth state options', () => {
diff --git a/librechat.example.yaml b/librechat.example.yaml
index c743bb6445..a114cd3057 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -346,6 +346,10 @@ registration:
# - "gmail.com"
# How long a started social login may take to return from the provider (ms, default 600000)
# oauthStateTtlMs: 600000
+ # OpenID discovery retries when the provider is unreachable (overrides OPENID_DISCOVERY_RETRY_* env vars)
+ # openidDiscovery:
+ # startupAttempts: 1 # attempts before startup continues; 0 = background retries only
+ # retryDelayMs: 5000 # delay between startup and background attempts
# Example Balance settings
# balance:
diff --git a/packages/api/src/auth/openid/index.ts b/packages/api/src/auth/openid/index.ts
index 4d5d56550b..f231be88d0 100644
--- a/packages/api/src/auth/openid/index.ts
+++ b/packages/api/src/auth/openid/index.ts
@@ -3,3 +3,4 @@ export * from './flight';
export * from './bridge';
export * from './recovery';
export * from './session';
+export * from './retry';
diff --git a/packages/api/src/auth/openid/retry.spec.ts b/packages/api/src/auth/openid/retry.spec.ts
new file mode 100644
index 0000000000..6c11dc7b8e
--- /dev/null
+++ b/packages/api/src/auth/openid/retry.spec.ts
@@ -0,0 +1,119 @@
+import { logger } from '@librechat/data-schemas';
+import { registerOpenIdWithRetry, resolveOpenIdDiscovery } from './retry';
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn() },
+}));
+
+const openIdConfig = { issuer: 'https://idp.example.com' };
+
+describe('resolveOpenIdDiscovery', () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it('defaults to one startup attempt and a 5000ms delay', () => {
+ expect(resolveOpenIdDiscovery()).toEqual({ startupAttempts: 1, retryDelayMs: 5000 });
+ expect(resolveOpenIdDiscovery(undefined, { startupAttempts: '', retryDelayMs: ' ' })).toEqual({
+ startupAttempts: 1,
+ retryDelayMs: 5000,
+ });
+ });
+
+ it('prefers librechat.yaml values over the environment, per field', () => {
+ expect(
+ resolveOpenIdDiscovery({ startupAttempts: 0 }, { startupAttempts: '4', retryDelayMs: '750' }),
+ ).toEqual({ startupAttempts: 0, retryDelayMs: 750 });
+ });
+
+ it.each([
+ ['retryDelayMs', '1'],
+ ['retryDelayMs', '99999999999'],
+ ['retryDelayMs', 'soon'],
+ ['startupAttempts', '-1'],
+ ['startupAttempts', '1.5'],
+ ] as const)('applies the schema bounds to environment %s=%s', (field, raw) => {
+ const resolved = resolveOpenIdDiscovery(undefined, { [field]: raw });
+ expect(resolved).toEqual({ startupAttempts: 1, retryDelayMs: 5000 });
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(`"${raw}"`));
+ });
+});
+
+describe('registerOpenIdWithRetry', () => {
+ beforeEach(() => jest.useFakeTimers());
+ afterEach(() => {
+ jest.clearAllMocks();
+ jest.useRealTimers();
+ });
+
+ it('makes one startup attempt by default, then recovers in the background', async () => {
+ const setupOpenId = jest.fn().mockResolvedValueOnce(null).mockResolvedValueOnce(openIdConfig);
+ const registerJwtStrategy = jest.fn();
+
+ await registerOpenIdWithRetry({ setupOpenId, registerJwtStrategy, reuseTokens: true });
+ expect(setupOpenId).toHaveBeenCalledTimes(1);
+ expect(registerJwtStrategy).not.toHaveBeenCalled();
+
+ await jest.advanceTimersByTimeAsync(5000);
+ expect(setupOpenId).toHaveBeenCalledTimes(2);
+ expect(registerJwtStrategy).toHaveBeenCalledWith(openIdConfig);
+
+ await jest.advanceTimersByTimeAsync(20000);
+ expect(setupOpenId).toHaveBeenCalledTimes(2);
+ });
+
+ it('retries during startup when more attempts are configured', async () => {
+ const setupOpenId = jest.fn().mockResolvedValueOnce(null).mockResolvedValueOnce(openIdConfig);
+
+ const done = registerOpenIdWithRetry({
+ setupOpenId,
+ registerJwtStrategy: jest.fn(),
+ reuseTokens: false,
+ discovery: { startupAttempts: 2, retryDelayMs: 1000 },
+ });
+ await jest.advanceTimersByTimeAsync(1000);
+ await done;
+
+ expect(setupOpenId).toHaveBeenCalledTimes(2);
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('skips startup attempts when set to zero', async () => {
+ const setupOpenId = jest.fn().mockResolvedValue(openIdConfig);
+ const registerJwtStrategy = jest.fn();
+
+ await registerOpenIdWithRetry({
+ setupOpenId,
+ registerJwtStrategy,
+ reuseTokens: false,
+ discovery: { startupAttempts: 0, retryDelayMs: 1000 },
+ });
+ expect(setupOpenId).not.toHaveBeenCalled();
+
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(setupOpenId).toHaveBeenCalledTimes(1);
+ expect(registerJwtStrategy).not.toHaveBeenCalled();
+ });
+
+ it('continues background retries when strategy registration throws', async () => {
+ const setupOpenId = jest.fn().mockResolvedValue(openIdConfig);
+ const registerJwtStrategy = jest
+ .fn()
+ .mockImplementationOnce(() => {
+ throw new Error('strategy registration failed');
+ })
+ .mockImplementationOnce(() => undefined);
+
+ await registerOpenIdWithRetry({
+ setupOpenId,
+ registerJwtStrategy,
+ reuseTokens: true,
+ env: { retryDelayMs: '1000' },
+ });
+ expect(logger.error).toHaveBeenCalledWith(
+ 'OpenID Connect strategy registration failed.',
+ expect.any(Error),
+ );
+
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(registerJwtStrategy).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/api/src/auth/openid/retry.ts b/packages/api/src/auth/openid/retry.ts
new file mode 100644
index 0000000000..6077bac22f
--- /dev/null
+++ b/packages/api/src/auth/openid/retry.ts
@@ -0,0 +1,118 @@
+import { logger } from '@librechat/data-schemas';
+import { openIdDiscoverySchema } from 'librechat-data-provider';
+import type { TOpenIdDiscoveryConfig } from 'librechat-data-provider';
+
+type DiscoveryField = 'startupAttempts' | 'retryDelayMs';
+
+export type OpenIdDiscoveryEnv = {
+ startupAttempts?: string;
+ retryDelayMs?: string;
+};
+
+export type OpenIdRegistrationOptions<TConfig> = {
+ /** Runs discovery and registers the `openid` strategy; resolves `null` when discovery fails. */
+ setupOpenId: () => Promise<TConfig | null>;
+ /** Registers the `openidJwt` strategy for a discovered configuration. */
+ registerJwtStrategy: (config: TConfig) => void;
+ reuseTokens: boolean;
+ /** Settings from `registration.openidDiscovery` in `librechat.yaml`. */
+ discovery?: Partial<TOpenIdDiscoveryConfig>;
+ /** Raw `OPENID_DISCOVERY_RETRY_*` values, used for fields the YAML leaves unset. */
+ env?: OpenIdDiscoveryEnv;
+};
+
+function resolveField(
+ field: DiscoveryField,
+ configured: number | undefined,
+ raw: string | undefined,
+): number {
+ const fieldSchema = openIdDiscoverySchema.shape[field];
+ if (configured != null) {
+ return configured;
+ }
+ if (raw == null || raw.trim() === '') {
+ return fieldSchema.parse(undefined);
+ }
+ const parsed = fieldSchema.safeParse(Number(raw));
+ if (parsed.success) {
+ return parsed.data;
+ }
+ const fallback = fieldSchema.parse(undefined);
+ logger.warn(`[OpenID] Ignoring invalid discovery ${field} "${raw}"; using ${fallback}.`);
+ return fallback;
+}
+
+/** Resolves discovery retry settings: YAML first, then environment, then the schema defaults. */
+export function resolveOpenIdDiscovery(
+ discovery?: Partial<TOpenIdDiscoveryConfig>,
+ env: OpenIdDiscoveryEnv = {},
+): TOpenIdDiscoveryConfig {
+ return {
+ startupAttempts: resolveField(
+ 'startupAttempts',
+ discovery?.startupAttempts,
+ env.startupAttempts,
+ ),
+ retryDelayMs: resolveField('retryDelayMs', discovery?.retryDelayMs, env.retryDelayMs),
+ };
+}
+
+const wait = (delay: number) => new Promise<void>((resolve) => setTimeout(resolve, delay));
+
+/**
+ * Registers the OpenID strategies, retrying discovery during startup and then in the
+ * background until the provider becomes reachable.
+ */
+export async function registerOpenIdWithRetry<TConfig>({
+ setupOpenId,
+ registerJwtStrategy,
+ reuseTokens,
+ discovery,
+ env,
+}: OpenIdRegistrationOptions<TConfig>): Promise<void> {
+ const { startupAttempts, retryDelayMs } = resolveOpenIdDiscovery(discovery, env);
+
+ const tryRegistration = async (): Promise<boolean> => {
+ try {
+ const config = await setupOpenId();
+ if (!config) {
+ return false;
+ }
+ if (reuseTokens) {
+ logger.info('OpenID token reuse is enabled.');
+ registerJwtStrategy(config);
+ }
+ logger.info('OpenID Connect configured successfully.');
+ return true;
+ } catch (error) {
+ logger.error('OpenID Connect strategy registration failed.', error);
+ return false;
+ }
+ };
+
+ for (let attempt = 1; attempt <= startupAttempts; attempt++) {
+ if (await tryRegistration()) {
+ return;
+ }
+ if (attempt < startupAttempts) {
+ logger.warn(
+ `OpenID Connect setup attempt ${attempt}/${startupAttempts} failed. Retrying in ${retryDelayMs}ms.`,
+ );
+ await wait(retryDelayMs);
+ }
+ }
+
+ logger.error('OpenID Connect configuration failed - strategy not registered.');
+
+ const scheduleRetry = () => {
+ logger.warn(`OpenID Connect configuration is unavailable. Retrying in ${retryDelayMs}ms.`);
+ const timer = setTimeout(async () => {
+ if (!(await tryRegistration())) {
+ scheduleRetry();
+ }
+ }, retryDelayMs);
+ timer.unref?.();
+ };
+
+ scheduleRetry();
+}
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index c2c4a40211..fcba1ab79a 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2799,6 +2799,15 @@ export const langfuseConfigSchema = z.object({
export type LangfuseConfig = z.infer<typeof langfuseConfigSchema>;
+export const openIdDiscoverySchema = z.object({
+ /** Discovery attempts made before startup continues; `0` retries only in the background. */
+ startupAttempts: z.number().int().min(0).max(100).default(1),
+ /** Milliseconds between startup and background discovery attempts. */
+ retryDelayMs: z.number().int().min(100).max(3_600_000).default(5000),
+});
+
+export type TOpenIdDiscoveryConfig = z.infer<typeof openIdDiscoverySchema>;
+
export const configSchema = z.object({
version: z.string(),
cache: z.boolean().default(true),
@@ -2891,6 +2900,8 @@ export const configSchema = z.object({
allowedDomains: z.array(z.string()).optional(),
/** Milliseconds a started social login may take to reach its callback; defaults to `DEFAULT_OAUTH_STATE_TTL_MS`. */
oauthStateTtlMs: z.number().int().min(60_000).max(3_600_000).optional(),
+ /** OpenID discovery retries; an unset field falls back to its `OPENID_DISCOVERY_RETRY_*` env var, then the schema default. */
+ openidDiscovery: openIdDiscoverySchema.partial().optional(),
})
.default({ socialLogins: defaultSocialLogins }),
balance: balanceSchema.optional(),