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: Strip Unresolved Header Placeholders at Final Resolution (#14595)

Danny Avila7e74f8eb8c3d
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 1b8b9d1090..28c62743c8 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -3232,11 +3232,13 @@ class AgentClient extends BaseClient {
/** Resolve request-based headers across provider-specific header locations:
* OpenAI `configuration.defaultHeaders`, Anthropic `clientOptions.defaultHeaders`
- * (preserved above), and Google `customHeaders`.
+ * (preserved above), and Google `customHeaders`. Uses the `req` captured at
+ * entry — `disposeClient` nulls `this.options.req` and can race this async
+ * title flow, which would blank the user context mid-generation.
*/
resolveConfigHeaders({
llmConfig: clientOptions,
- user: createSafeUser(this.options.req?.user),
+ user: createSafeUser(req?.user),
body: {
messageId: this.responseMessageId,
conversationId: this.conversationId,
diff --git a/api/server/services/Endpoints/azureAssistants/initialize.js b/api/server/services/Endpoints/azureAssistants/initialize.js
index fde02b1589..c170de2968 100644
--- a/api/server/services/Endpoints/azureAssistants/initialize.js
+++ b/api/server/services/Endpoints/azureAssistants/initialize.js
@@ -117,6 +117,7 @@ const initializeClient = async ({ req, res, version, endpointOption, initAppClie
'OpenAI-Beta': `assistants=${version}`,
},
user: req.user,
+ stripUnresolved: true,
});
opts.model = azureOptions.azureOpenAIApiDeploymentName;
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 4e71841e7d..240c311763 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -539,6 +539,7 @@ function resolveSummarizationProvider(
headers: customEndpointConfig.headers as Record<string, string>,
user: createSafeUser(headerContext.user),
body: headerContext.requestBody,
+ stripUnresolved: true,
})
: undefined;
/**
diff --git a/packages/api/src/endpoints/google/initialize.ts b/packages/api/src/endpoints/google/initialize.ts
index 41c2f65298..833956ad1a 100644
--- a/packages/api/src/endpoints/google/initialize.ts
+++ b/packages/api/src/endpoints/google/initialize.ts
@@ -100,7 +100,12 @@ export async function initializeGoogle({
*/
const mergedHeaders = mergeHeaders(allConfig?.headers, googleConfig?.headers);
const headers = mergedHeaders
- ? resolveHeaders({ headers: mergedHeaders, user: req.user, body: req.body })
+ ? resolveHeaders({
+ headers: mergedHeaders,
+ user: req.user,
+ body: req.body,
+ stripUnresolved: true,
+ })
: undefined;
clientOptions = {
diff --git a/packages/api/src/endpoints/models.spec.ts b/packages/api/src/endpoints/models.spec.ts
index 30e1d7546a..a354303974 100644
--- a/packages/api/src/endpoints/models.spec.ts
+++ b/packages/api/src/endpoints/models.spec.ts
@@ -199,6 +199,7 @@ describe('fetchModels', () => {
expect(resolveHeaders).toHaveBeenCalledWith({
headers: customHeaders,
user: userObject,
+ stripUnresolved: true,
});
expect(mockedAxios.get).toHaveBeenCalledWith(
expect.stringContaining('https://api.test.com/models'),
@@ -658,6 +659,7 @@ describe('fetchModels with Ollama specific logic', () => {
expect(resolveHeaders).toHaveBeenCalledWith({
headers: customHeaders,
user: userObject,
+ stripUnresolved: true,
});
expect(mockedAxios.get).toHaveBeenCalledWith('https://api.ollama.test.com/api/tags', {
headers: customHeaders,
diff --git a/packages/api/src/endpoints/models.ts b/packages/api/src/endpoints/models.ts
index 55fe926a42..b0beb1787a 100644
--- a/packages/api/src/endpoints/models.ts
+++ b/packages/api/src/endpoints/models.ts
@@ -97,6 +97,7 @@ async function fetchOllamaModels(
const resolvedHeaders = resolveHeaders({
headers: options.headers ?? undefined,
user: options.user,
+ stripUnresolved: true,
});
const requestOptions: AxiosRequestConfig & {
@@ -240,6 +241,7 @@ export async function fetchModels({
const resolvedHeaders = resolveHeaders({
headers: headers ?? undefined,
user: userObject,
+ stripUnresolved: true,
});
const options: AxiosRequestConfig & {
diff --git a/packages/api/src/utils/env.spec.ts b/packages/api/src/utils/env.spec.ts
index 9c4d7bff2b..395f5e70ed 100644
--- a/packages/api/src/utils/env.spec.ts
+++ b/packages/api/src/utils/env.spec.ts
@@ -2189,3 +2189,107 @@ describe('createSafeUser', () => {
expect(createSafeUser(user).id).toBeUndefined();
});
});
+
+describe('resolveHeaders stripUnresolved', () => {
+ const templateHeaders = {
+ 'X-OpenID-Id': '{{LIBRECHAT_USER_OPENIDID}}',
+ 'X-User-Id': '{{LIBRECHAT_USER_ID}}',
+ 'Content-Type': 'application/json',
+ };
+
+ it('strips user placeholders when user context is missing entirely', () => {
+ const result = resolveHeaders({ headers: { ...templateHeaders }, stripUnresolved: true });
+
+ expect(result).toEqual({
+ 'X-OpenID-Id': '',
+ 'X-User-Id': '',
+ 'Content-Type': 'application/json',
+ });
+ });
+
+ it('strips user placeholders when the safe user is an empty object (issue #14580)', () => {
+ const result = resolveHeaders({
+ headers: { ...templateHeaders },
+ user: createSafeUser(undefined),
+ stripUnresolved: true,
+ });
+
+ expect(result).toEqual({
+ 'X-OpenID-Id': '',
+ 'X-User-Id': '',
+ 'Content-Type': 'application/json',
+ });
+ });
+
+ it('strips placeholders for fields the user lacks while substituting present fields', () => {
+ const localUser = createSafeUser({ id: 'user-123', email: '[email protected]' } as IUser);
+
+ const result = resolveHeaders({
+ headers: { ...templateHeaders, 'X-Email': '{{LIBRECHAT_USER_EMAIL}}' },
+ user: localUser,
+ stripUnresolved: true,
+ });
+
+ expect(result).toEqual({
+ 'X-OpenID-Id': '',
+ 'X-User-Id': 'user-123',
+ 'X-Email': '[email protected]',
+ 'Content-Type': 'application/json',
+ });
+ });
+
+ it('strips only the placeholder within a composite header value', () => {
+ const result = resolveHeaders({
+ headers: { Authorization: 'Bearer {{LIBRECHAT_USER_OPENIDID}}' },
+ stripUnresolved: true,
+ });
+
+ expect(result.Authorization).toBe('Bearer ');
+ });
+
+ it('strips body placeholders when no body context is available', () => {
+ const result = resolveHeaders({
+ headers: { 'X-Convo': '{{LIBRECHAT_BODY_CONVERSATIONID}}' },
+ user: { id: 'user-123' },
+ stripUnresolved: true,
+ });
+
+ expect(result['X-Convo']).toBe('');
+ });
+
+ it('strips OpenID token placeholders when no valid token is available', () => {
+ const result = resolveHeaders({
+ headers: {
+ 'X-Access': '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
+ 'X-Token': '{{LIBRECHAT_OPENID_TOKEN}}',
+ },
+ user: { id: 'user-123' },
+ stripUnresolved: true,
+ });
+
+ expect(result['X-Access']).toBe('');
+ expect(result['X-Token']).toBe('');
+ });
+
+ it('leaves unknown and non-resolvable placeholders untouched', () => {
+ const result = resolveHeaders({
+ headers: {
+ 'X-Typo': '{{LIBRECHAT_USER_NONEXISTENT}}',
+ 'X-Graph': '{{LIBRECHAT_GRAPH_ACCESS_TOKEN}}',
+ 'X-Custom': '{{MY_CUSTOM_VAR}}',
+ },
+ stripUnresolved: true,
+ });
+
+ expect(result['X-Typo']).toBe('{{LIBRECHAT_USER_NONEXISTENT}}');
+ expect(result['X-Graph']).toBe('{{LIBRECHAT_GRAPH_ACCESS_TOKEN}}');
+ expect(result['X-Custom']).toBe('{{MY_CUSTOM_VAR}}');
+ });
+
+ it('preserves unresolved placeholders by default (staged flows resolve later)', () => {
+ const result = resolveHeaders({ headers: { ...templateHeaders } });
+
+ expect(result['X-OpenID-Id']).toBe('{{LIBRECHAT_USER_OPENIDID}}');
+ expect(result['X-User-Id']).toBe('{{LIBRECHAT_USER_ID}}');
+ });
+});
diff --git a/packages/api/src/utils/env.ts b/packages/api/src/utils/env.ts
index 20de5e36e1..9534a5a9ab 100644
--- a/packages/api/src/utils/env.ts
+++ b/packages/api/src/utils/env.ts
@@ -2,7 +2,12 @@ import { extractEnvVariable } from 'librechat-data-provider';
import type { MCPOptions } from 'librechat-data-provider';
import type { IUser } from '@librechat/data-schemas';
import type { RequestBody } from '~/types';
-import { extractOpenIDTokenInfo, processOpenIDPlaceholders, isOpenIDTokenValid } from './oidc';
+import {
+ OPENID_TOKEN_FIELDS,
+ isOpenIDTokenValid,
+ extractOpenIDTokenInfo,
+ processOpenIDPlaceholders,
+} from './oidc';
/**
* List of allowed user fields that can be used in MCP environment variables.
@@ -124,6 +129,36 @@ export function createSafeUser(
*/
const ALLOWED_BODY_FIELDS = ['conversationId', 'parentMessageId', 'messageId'] as const;
+/**
+ * Matches every placeholder this module knows how to resolve: the enumerated
+ * `{{LIBRECHAT_USER_*}}`, `{{LIBRECHAT_BODY_*}}`, and `{{LIBRECHAT_OPENID_*}}`
+ * names. Deliberately excludes unknown names (a typo'd placeholder staying
+ * literal is diagnosable) and `{{LIBRECHAT_GRAPH_ACCESS_TOKEN}}`, which is
+ * resolved asynchronously via the OBO flow outside this pipeline.
+ */
+const RESOLVABLE_PLACEHOLDER_PATTERN = new RegExp(
+ [
+ `LIBRECHAT_USER_(?:${ALLOWED_USER_FIELDS.map((field) => field.toUpperCase()).join('|')})`,
+ `LIBRECHAT_BODY_(?:${ALLOWED_BODY_FIELDS.map((field) => field.toUpperCase()).join('|')})`,
+ `LIBRECHAT_OPENID_(?:${OPENID_TOKEN_FIELDS.join('|')}|TOKEN)`,
+ ]
+ .map((names) => `\\{\\{(?:${names})\\}\\}`)
+ .join('|'),
+ 'g',
+);
+
+/**
+ * Replaces resolvable-but-unresolved placeholders with an empty string so
+ * LibreChat's internal template syntax is never sent upstream as if it were
+ * real user data (e.g. a gateway trusting a literal
+ * `{{LIBRECHAT_USER_OPENIDID}}` as an account identity would pool unrelated
+ * users under that one string). Only for final resolution passes — staged
+ * flows that resolve again later with more context must not strip.
+ */
+function stripUnresolvedPlaceholders(value: string): string {
+ return value.replace(RESOLVABLE_PLACEHOLDER_PATTERN, '');
+}
+
/**
* Processes a string value to replace user field placeholders.
* When isHeader is true, non-ASCII characters in certain fields are Base64 encoded.
@@ -520,6 +555,10 @@ export function resolveNestedObject<T = unknown>(options?: {
* @param options.user - Optional user object for replacing user field placeholders (can be partial with just id)
* @param options.body - Optional request body object for replacing body field placeholders
* @param options.customUserVars - Optional custom user variables to replace placeholders
+ * @param options.stripUnresolved - When true (final resolution passes only), replaces any
+ * remaining resolvable placeholders with an empty string so internal template syntax is
+ * never forwarded upstream. Leave unset for staged flows whose values are resolved again
+ * later with more context.
* @returns The processed headers with all placeholders replaced
*/
export function resolveHeaders(options?: {
@@ -527,21 +566,23 @@ export function resolveHeaders(options?: {
user?: Partial<IUser> | { id: string };
body?: RequestBody;
customUserVars?: Record<string, string>;
+ stripUnresolved?: boolean;
}): Record<string, string> {
- const { headers, user, body, customUserVars } = options ?? {};
+ const { headers, user, body, customUserVars, stripUnresolved = false } = options ?? {};
const inputHeaders = headers ?? {};
const resolvedHeaders: Record<string, string> = { ...inputHeaders };
if (inputHeaders && typeof inputHeaders === 'object' && !Array.isArray(inputHeaders)) {
Object.keys(inputHeaders).forEach((key) => {
- resolvedHeaders[key] = processSingleValue({
+ const processed = processSingleValue({
originalValue: inputHeaders[key],
customUserVars,
user: user as IUser,
body,
isHeader: true, // Important: Enable header encoding
});
+ resolvedHeaders[key] = stripUnresolved ? stripUnresolvedPlaceholders(processed) : processed;
});
}
diff --git a/packages/api/src/utils/headers.spec.ts b/packages/api/src/utils/headers.spec.ts
index ca5cdd8c10..4f914c07ac 100644
--- a/packages/api/src/utils/headers.spec.ts
+++ b/packages/api/src/utils/headers.spec.ts
@@ -152,4 +152,36 @@ describe('resolveConfigHeaders', () => {
expect(() => resolveConfigHeaders({ llmConfig, user, body })).not.toThrow();
expect(llmConfig.configuration).toEqual({});
});
+
+ it('never forwards unresolved user placeholders when user context is missing (issue #14580)', () => {
+ const llmConfig = {
+ configuration: {
+ defaultHeaders: {
+ 'X-LibreChat-User': '{{LIBRECHAT_USER_OPENIDID}}',
+ 'X-Conversation-Id': '{{LIBRECHAT_BODY_CONVERSATIONID}}',
+ },
+ },
+ } as unknown as RunLLMConfig;
+
+ // The empty safe user produced by createSafeUser(undefined) — e.g. a disposed
+ // req racing async title generation — must not leak literal template text.
+ resolveConfigHeaders({ llmConfig, user: {} as { id: string }, body });
+
+ expect(llmConfig.configuration?.defaultHeaders).toEqual({
+ 'X-LibreChat-User': '',
+ 'X-Conversation-Id': 'convo-abc',
+ });
+ });
+
+ it('strips placeholders for fields the resolved user lacks', () => {
+ const llmConfig = {
+ configuration: {
+ defaultHeaders: { 'X-LibreChat-User': '{{LIBRECHAT_USER_OPENIDID}}' },
+ },
+ } as unknown as RunLLMConfig;
+
+ resolveConfigHeaders({ llmConfig, user, body });
+
+ expect(llmConfig.configuration?.defaultHeaders).toEqual({ 'X-LibreChat-User': '' });
+ });
});
diff --git a/packages/api/src/utils/headers.ts b/packages/api/src/utils/headers.ts
index cb84449dfd..940e88983f 100644
--- a/packages/api/src/utils/headers.ts
+++ b/packages/api/src/utils/headers.ts
@@ -89,6 +89,11 @@ const resolvedHeaderMaps = new WeakSet<object>();
* Resolution runs at request time so request-body placeholders (e.g.
* `{{LIBRECHAT_BODY_CONVERSATIONID}}`) resolve against the live request. It is a
* no-op for header values without placeholders, and idempotent under config reuse.
+ *
+ * This is the last resolution pass before the outbound provider request, so any
+ * placeholder still unresolved here (missing user context, a user without the
+ * configured field) is stripped rather than forwarded as literal template text
+ * the upstream could mistake for real user data.
*/
export function resolveConfigHeaders({
llmConfig,
@@ -113,7 +118,7 @@ export function resolveConfigHeaders({
if (resolvedHeaderMaps.has(headers)) {
return headers;
}
- const resolved = resolveHeaders({ headers, user, body, customUserVars });
+ const resolved = resolveHeaders({ headers, user, body, customUserVars, stripUnresolved: true });
resolvedHeaderMaps.add(resolved);
return resolved;
};
diff --git a/packages/api/src/utils/oidc.ts b/packages/api/src/utils/oidc.ts
index 51056406c1..fcf2db247b 100644
--- a/packages/api/src/utils/oidc.ts
+++ b/packages/api/src/utils/oidc.ts
@@ -18,7 +18,7 @@ function isFederatedTokens(obj: unknown): obj is OIDCTokens {
return 'access_token' in obj || 'id_token' in obj || 'expires_at' in obj;
}
-const OPENID_TOKEN_FIELDS = [
+export const OPENID_TOKEN_FIELDS = [
'ACCESS_TOKEN',
'ID_TOKEN',
'USER_ID',