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

🕰️ fix: Guard `expires_in` So a Token Response Cannot Outlive Its Credential (#15321)

Danny Avila01f5391ee304
diff --git a/api/server/services/ActionService.js b/api/server/services/ActionService.js
index c39533fa7e..2c877c515e 100644
--- a/api/server/services/ActionService.js
+++ b/api/server/services/ActionService.js
@@ -6,6 +6,7 @@ const { logger, encryptV2, decryptV2 } = require('@librechat/data-schemas');
const {
sendEvent,
logAxiosError,
+ getTokenExpiresAt,
refreshAccessToken,
GenerationJobManager,
createSSRFSafeAgents,
@@ -294,8 +295,8 @@ async function createActionTool({
await sleep(3000);
metadata.oauth_access_token = result.access_token;
metadata.oauth_refresh_token = result.refresh_token;
- const expiresAt = new Date(Date.now() + result.expires_in * 1000);
- metadata.oauth_token_expires_at = expiresAt.toISOString();
+ const expiresAt = getTokenExpiresAt(result.expires_in);
+ metadata.oauth_token_expires_at = expiresAt?.toISOString();
} catch (error) {
const errorMessage = 'Failed to authenticate OAuth tool';
logger.error(errorMessage, error);
@@ -358,8 +359,8 @@ async function createActionTool({
if (refreshData.refresh_token) {
metadata.oauth_refresh_token = refreshData.refresh_token;
}
- const expiresAt = new Date(Date.now() + refreshData.expires_in * 1000);
- metadata.oauth_token_expires_at = expiresAt.toISOString();
+ const expiresAt = getTokenExpiresAt(refreshData.expires_in);
+ metadata.oauth_token_expires_at = expiresAt?.toISOString();
} catch (error) {
logger.error('Failed to refresh token, requesting new login:', error);
await requestLogin();
diff --git a/api/server/services/GraphApiService.js b/api/server/services/GraphApiService.js
index aca7e4a168..d9a6fa99fc 100644
--- a/api/server/services/GraphApiService.js
+++ b/api/server/services/GraphApiService.js
@@ -1,5 +1,9 @@
const client = require('openid-client');
-const { isEnabled } = require('@librechat/api');
+const {
+ isEnabled,
+ getTokenCacheTtlMs,
+ DEFAULT_OAUTH_TOKEN_TTL_SECONDS,
+} = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const { CacheKeys } = require('librechat-data-provider');
const { Client } = require('@microsoft/microsoft-graph-client');
@@ -90,7 +94,7 @@ const exchangeTokenForGraphAccess = async (config, accessToken, sub) => {
{
access_token: grantResponse.access_token,
},
- grantResponse.expires_in * 1000,
+ getTokenCacheTtlMs(grantResponse.expires_in, DEFAULT_OAUTH_TOKEN_TTL_SECONDS),
);
return grantResponse.access_token;
diff --git a/api/server/services/OboTokenService.js b/api/server/services/OboTokenService.js
index be269be993..86edf15b5a 100644
--- a/api/server/services/OboTokenService.js
+++ b/api/server/services/OboTokenService.js
@@ -1,6 +1,11 @@
const client = require('openid-client');
const { logger } = require('@librechat/data-schemas');
const { CacheKeys } = require('librechat-data-provider');
+const {
+ normalizeExpiresIn,
+ getTokenCacheTtlMs,
+ DEFAULT_OAUTH_TOKEN_TTL_SECONDS,
+} = require('@librechat/api');
const { getOpenIdConfig } = require('~/strategies/openidStrategy');
const getLogStores = require('~/cache/getLogStores');
@@ -96,11 +101,15 @@ async function performOboExchange({ user, accessToken, scopes, config, tokensCac
const tokenResponse = {
access_token: grantResponse.access_token,
token_type: 'Bearer',
- expires_in: grantResponse.expires_in || 3600,
+ expires_in: normalizeExpiresIn(grantResponse.expires_in) ?? DEFAULT_OAUTH_TOKEN_TTL_SECONDS,
scope: scopes,
};
- await tokensCache.set(cacheKey, tokenResponse, (grantResponse.expires_in || 3600) * 1000);
+ await tokensCache.set(
+ cacheKey,
+ tokenResponse,
+ getTokenCacheTtlMs(grantResponse.expires_in, DEFAULT_OAUTH_TOKEN_TTL_SECONDS),
+ );
logger.debug(
`[OboTokenService] Successfully obtained and cached OBO token for user: ${user.openidId}`,
diff --git a/api/strategies/openidStrategy.js b/api/strategies/openidStrategy.js
index d9c2684314..5eda5c4514 100644
--- a/api/strategies/openidStrategy.js
+++ b/api/strategies/openidStrategy.js
@@ -15,6 +15,7 @@ const {
getOpenIdIssuer,
getBalanceConfig,
selectOpenIdRole,
+ getTokenCacheTtlMs,
getAvatarSaveParams,
isEmailDomainAllowed,
getAvatarFileStrategy,
@@ -23,6 +24,7 @@ const {
getOpenIdRoleSyncOptions,
getOpenIdRolesForOpenIdSync,
getLibreChatRolesForOpenIdSync,
+ DEFAULT_OAUTH_TOKEN_TTL_SECONDS,
} = require('@librechat/api');
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
const { resizeAvatar } = require('~/server/services/Files/images/avatar');
@@ -188,7 +190,7 @@ const exchangeAccessTokenIfNeeded = async (config, accessToken, sub, fromCache =
{
access_token: grantResponse.access_token,
},
- grantResponse.expires_in * 1000,
+ getTokenCacheTtlMs(grantResponse.expires_in, DEFAULT_OAUTH_TOKEN_TTL_SECONDS),
);
return grantResponse.access_token;
}
@@ -370,12 +372,11 @@ async function exchangeTokenForOverage(accessToken, sub) {
);
}
- const ttlMs =
- Number.isFinite(grantResponse.expires_in) && grantResponse.expires_in > 0
- ? grantResponse.expires_in * 1000
- : 3600 * 1000;
-
- await tokensCache.set(cacheKey, { access_token: grantResponse.access_token }, ttlMs);
+ await tokensCache.set(
+ cacheKey,
+ { access_token: grantResponse.access_token },
+ getTokenCacheTtlMs(grantResponse.expires_in, DEFAULT_OAUTH_TOKEN_TTL_SECONDS),
+ );
return grantResponse.access_token;
}
diff --git a/packages/api/src/oauth/expiry.spec.ts b/packages/api/src/oauth/expiry.spec.ts
new file mode 100644
index 0000000000..3a489bfe8f
--- /dev/null
+++ b/packages/api/src/oauth/expiry.spec.ts
@@ -0,0 +1,149 @@
+import {
+ DEFAULT_OAUTH_TOKEN_TTL_SECONDS,
+ getTokenCacheTtlMs,
+ getTokenExpiresAt,
+ normalizeExpiresIn,
+} from './expiry';
+
+describe('normalizeExpiresIn', () => {
+ it('accepts a positive finite number of seconds', () => {
+ expect(normalizeExpiresIn(3599)).toBe(3599);
+ expect(normalizeExpiresIn(1)).toBe(1);
+ });
+
+ it('accepts a numeric string, as some providers send', () => {
+ expect(normalizeExpiresIn('3599')).toBe(3599);
+ });
+
+ it('rejects an omitted lifetime', () => {
+ expect(normalizeExpiresIn(undefined)).toBeUndefined();
+ expect(normalizeExpiresIn(null)).toBeUndefined();
+ });
+
+ it('rejects NaN, which `undefined * 1000` produces and every naive guard admits', () => {
+ expect(normalizeExpiresIn(NaN)).toBeUndefined();
+ expect(normalizeExpiresIn('not-a-number')).toBeUndefined();
+ });
+
+ it('rejects a non-finite lifetime', () => {
+ expect(normalizeExpiresIn(Infinity)).toBeUndefined();
+ expect(normalizeExpiresIn(-Infinity)).toBeUndefined();
+ });
+
+ /**
+ * Parsing the complete string is what makes this reachable — `parseInt('1e13', 10)` was `1` and
+ * masked it. `1e13` seconds overruns the ECMAScript time range, so every derived timestamp would
+ * be an Invalid Date whose `toISOString()` throws: the very failure this module removes.
+ */
+ it('rejects a lifetime that would overflow the Date range', () => {
+ expect(normalizeExpiresIn('1e13')).toBeUndefined();
+ expect(normalizeExpiresIn(1e13)).toBeUndefined();
+ expect(normalizeExpiresIn(-1e13)).toBeUndefined();
+ expect(normalizeExpiresIn(Number.MAX_SAFE_INTEGER)).toBeUndefined();
+ });
+
+ it('still accepts lifetimes far longer than any real credential', () => {
+ const oneYear = 365 * 24 * 60 * 60;
+ expect(normalizeExpiresIn(oneYear)).toBe(oneYear);
+ expect(normalizeExpiresIn(oneYear * 100)).toBe(oneYear * 100);
+ });
+
+ /** An explicit non-positive value is the provider saying the credential is already dead, which is
+ * information — collapsing it into "unknown" would hand it the fallback lifetime and revive it. */
+ it('preserves an explicitly elapsed lifetime rather than calling it unknown', () => {
+ expect(normalizeExpiresIn(0)).toBe(0);
+ expect(normalizeExpiresIn(-60)).toBe(-60);
+ expect(normalizeExpiresIn('0')).toBe(0);
+ });
+
+ it('parses a complete numeric string, which parseInt would truncate', () => {
+ expect(normalizeExpiresIn('3.6e3')).toBe(3600);
+ expect(normalizeExpiresIn(' 3600 ')).toBe(3600);
+ });
+
+ it('rejects an empty or blank string rather than reading it as zero', () => {
+ expect(normalizeExpiresIn('')).toBeUndefined();
+ expect(normalizeExpiresIn(' ')).toBeUndefined();
+ });
+
+ it('rejects shapes that are neither number nor string', () => {
+ expect(normalizeExpiresIn({})).toBeUndefined();
+ expect(normalizeExpiresIn([3600])).toBeUndefined();
+ expect(normalizeExpiresIn(true)).toBeUndefined();
+ });
+});
+
+describe('getTokenCacheTtlMs', () => {
+ it('converts a declared lifetime to milliseconds', () => {
+ expect(getTokenCacheTtlMs(1800, DEFAULT_OAUTH_TOKEN_TTL_SECONDS)).toBe(1_800_000);
+ });
+
+ it('falls back rather than returning NaN when the provider omits `expires_in`', () => {
+ expect(getTokenCacheTtlMs(undefined, DEFAULT_OAUTH_TOKEN_TTL_SECONDS)).toBe(3_600_000);
+ expect(getTokenCacheTtlMs(NaN, 60)).toBe(60_000);
+ });
+
+ /** Keyv reads a TTL of exactly 0 as "no expiry", so an elapsed lifetime must not pass through raw */
+ it('floors an elapsed lifetime to the shortest positive TTL, never 0', () => {
+ expect(getTokenCacheTtlMs(0, DEFAULT_OAUTH_TOKEN_TTL_SECONDS)).toBe(1);
+ expect(getTokenCacheTtlMs(-60, DEFAULT_OAUTH_TOKEN_TTL_SECONDS)).toBe(1);
+ });
+
+ it('does not hand an elapsed lifetime the fallback, which would revive a dead credential', () => {
+ expect(getTokenCacheTtlMs(0, DEFAULT_OAUTH_TOKEN_TTL_SECONDS)).not.toBe(3_600_000);
+ });
+
+ it('never returns 0, which Keyv would store as no expiry', () => {
+ for (const value of [undefined, null, NaN, Infinity, 0, -1, '0', 'abc', {}, '1e13', 1e300]) {
+ const ttl = getTokenCacheTtlMs(value, DEFAULT_OAUTH_TOKEN_TTL_SECONDS);
+ expect(ttl).toBeGreaterThan(0);
+ expect(Number.isFinite(ttl)).toBe(true);
+ }
+ });
+
+ /**
+ * A NaN TTL is not a short TTL: `@keyv/redis` skips its `PX` branch because NaN is falsy, and
+ * Keyv's own expiry checks compare with `>`, always false against NaN. The result is an entry
+ * that outlives the credential it holds.
+ */
+ it('never returns NaN, whatever the provider sent', () => {
+ for (const value of [undefined, null, NaN, Infinity, 0, -1, 'abc', {}]) {
+ expect(Number.isFinite(getTokenCacheTtlMs(value, DEFAULT_OAUTH_TOKEN_TTL_SECONDS))).toBe(
+ true,
+ );
+ }
+ });
+});
+
+describe('getTokenExpiresAt', () => {
+ it('returns an absolute expiry for a declared lifetime', () => {
+ const before = Date.now();
+ const expiresAt = getTokenExpiresAt(600);
+
+ expect(expiresAt).toBeInstanceOf(Date);
+ expect(expiresAt!.getTime()).toBeGreaterThanOrEqual(before + 600_000);
+ expect(expiresAt!.getTime()).toBeLessThanOrEqual(Date.now() + 600_000);
+ });
+
+ it('returns undefined rather than an Invalid Date when the lifetime is unknown', () => {
+ for (const value of [undefined, null, NaN, Infinity, 'abc', '']) {
+ expect(getTokenExpiresAt(value)).toBeUndefined();
+ }
+ });
+
+ /** An elapsed lifetime must stay elapsed, so callers refresh instead of treating it as unknown */
+ it('returns a past timestamp for an explicitly elapsed lifetime', () => {
+ const expiresAt = getTokenExpiresAt(0);
+
+ expect(expiresAt).toBeInstanceOf(Date);
+ expect(expiresAt!.getTime()).toBeLessThanOrEqual(Date.now());
+ expect(getTokenExpiresAt(-60)!.getTime()).toBeLessThan(Date.now());
+ });
+
+ /** `new Date(NaN).toISOString()` throws `RangeError: Invalid time value`, which is the ActionService failure */
+ it('never yields a value whose toISOString throws', () => {
+ for (const value of [undefined, null, NaN, Infinity, 'abc', '', 0, -60, 3600, '1e13', 1e300]) {
+ expect(() => getTokenExpiresAt(value)?.toISOString()).not.toThrow();
+ }
+ });
+});
diff --git a/packages/api/src/oauth/expiry.ts b/packages/api/src/oauth/expiry.ts
new file mode 100644
index 0000000000..9aaec7aa86
--- /dev/null
+++ b/packages/api/src/oauth/expiry.ts
@@ -0,0 +1,88 @@
+/**
+ * RFC 6749 §5.1 makes `expires_in` only RECOMMENDED, so a token response may legally omit it, and
+ * providers have been observed sending it as a string. Deriving a lifetime from the raw field is
+ * therefore unsafe: `undefined * 1000` is `NaN`, and `NaN` is neither an error nor a default.
+ *
+ * A `NaN` cache TTL means an entry that never expires. `@keyv/redis` writes the key without `PX`
+ * because `NaN` is falsy, and Keyv's own expiry checks compare with `>`, which is always false
+ * against `NaN`. The namespace default does not stand in either, since Keyv applies it with `??=`
+ * and `NaN` is neither `null` nor `undefined`. A `NaN` timestamp is just as sharp: `new Date(NaN)`
+ * is an Invalid Date and `toISOString()` on it throws `RangeError`.
+ *
+ * Every lifetime derived from a token response goes through here so the rule has one home.
+ */
+
+/**
+ * Fallback lifetime for a token response that declares none. One hour matches every hand-written
+ * default this helper replaces, and is short enough that a wrongly-guessed lifetime self-corrects.
+ */
+export const DEFAULT_OAUTH_TOKEN_TTL_SECONDS = 3600;
+
+/**
+ * Floor for a cache TTL derived from an already-elapsed lifetime. Keyv reads a TTL of exactly `0`
+ * as "no expiry" (`data.ttl === 0` becomes `undefined`), so a credential the provider declared
+ * expired must never be written as `0` — that is the very failure this module exists to prevent.
+ */
+const EXPIRED_CACHE_TTL_MS = 1;
+
+/**
+ * Longest lifetime that can still produce a valid `Date`. The ECMAScript time value range ends at
+ * ±8.64e15 ms, and every derived timestamp adds `Date.now()`, so the bound is halved to leave room
+ * for it. A provider sending something beyond this — `"1e13"` seconds is roughly 317,000 years — is
+ * not describing a credential lifetime, and accepting it would yield the Invalid Date this module
+ * exists to prevent. Such a value is reported as unusable so callers take their fallback.
+ */
+const MAX_EXPIRES_IN_SECONDS = 4_320_000_000_000;
+
+function parseExpiresIn(expiresIn: unknown): number | undefined {
+ if (typeof expiresIn === 'number') {
+ return expiresIn;
+ }
+
+ if (typeof expiresIn !== 'string') {
+ return undefined;
+ }
+
+ /** `Number` over `parseInt`, which truncates a complete numeric string such as `"3.6e3"` to `3` */
+ const trimmed = expiresIn.trim();
+ return trimmed.length === 0 ? undefined : Number(trimmed);
+}
+
+/**
+ * The lifetime a token response declares, in seconds, or `undefined` when it declares none usable.
+ *
+ * A non-positive value is preserved rather than discarded: the provider is stating the credential
+ * is already expired, which is information, and collapsing it into "unknown" would hand it the
+ * fallback lifetime and keep a dead credential alive.
+ */
+export function normalizeExpiresIn(expiresIn: unknown): number | undefined {
+ const parsed = parseExpiresIn(expiresIn);
+ if (parsed == null || !Number.isFinite(parsed)) {
+ return undefined;
+ }
+
+ return Math.abs(parsed) <= MAX_EXPIRES_IN_SECONDS ? parsed : undefined;
+}
+
+/**
+ * Cache TTL in milliseconds for a token response. A provider that omits `expires_in` gets
+ * `fallbackSeconds` rather than an entry that outlives the credential it holds; one that declares
+ * an elapsed lifetime gets the shortest positive TTL rather than `0`, which Keyv reads as no expiry.
+ */
+export function getTokenCacheTtlMs(expiresIn: unknown, fallbackSeconds: number): number {
+ const seconds = normalizeExpiresIn(expiresIn);
+ if (seconds == null) {
+ return fallbackSeconds * 1000;
+ }
+ return Math.max(seconds * 1000, EXPIRED_CACHE_TTL_MS);
+}
+
+/**
+ * Absolute expiry for a token response, or `undefined` when its lifetime is unknown. Callers store
+ * nothing rather than an Invalid Date, so an unknown expiry stays distinguishable from an elapsed
+ * one — an elapsed lifetime still yields a past timestamp, so callers refresh instead of guessing.
+ */
+export function getTokenExpiresAt(expiresIn: unknown): Date | undefined {
+ const seconds = normalizeExpiresIn(expiresIn);
+ return seconds == null ? undefined : new Date(Date.now() + seconds * 1000);
+}
diff --git a/packages/api/src/oauth/index.ts b/packages/api/src/oauth/index.ts
index 4c3fea9ea4..40d1a18850 100644
--- a/packages/api/src/oauth/index.ts
+++ b/packages/api/src/oauth/index.ts
@@ -1,4 +1,5 @@
export * from './csrf';
+export * from './expiry';
export * from './callback';
export * from './failure';
export * from './tokens';
diff --git a/packages/api/src/oauth/tokens.ts b/packages/api/src/oauth/tokens.ts
index dfdac87bb2..02fb80e287 100644
--- a/packages/api/src/oauth/tokens.ts
+++ b/packages/api/src/oauth/tokens.ts
@@ -3,6 +3,7 @@ import { TokenExchangeMethodEnum } from 'librechat-data-provider';
import { logger, encryptV2, decryptV2 } from '@librechat/data-schemas';
import type { IToken, TokenMethods } from '@librechat/data-schemas';
import type { AxiosError } from 'axios';
+import { DEFAULT_OAUTH_TOKEN_TTL_SECONDS, normalizeExpiresIn } from './expiry';
import { validateActionOAuthEndpoint } from './validation';
import { createSSRFSafeAgents } from '~/auth';
import { logAxiosError } from '~/utils';
@@ -61,12 +62,7 @@ export function createHandleOAuthToken({
type?: string;
}): Promise<IToken | null> {
const encrypedToken = await encryptV2(token);
- let expiresInNumber = 3600;
- if (typeof expiresIn === 'number') {
- expiresInNumber = expiresIn;
- } else if (expiresIn != null) {
- expiresInNumber = parseInt(expiresIn, 10) || 3600;
- }
+ const expiresInNumber = normalizeExpiresIn(expiresIn) ?? DEFAULT_OAUTH_TOKEN_TTL_SECONDS;
const tokenData = {
type,
userId,