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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🛖 fix: Scope OAuth Binding Cookies to the Public API Path (#16649)
lia-by-librechat[bot]19a337da4691
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.jsindex 1c1e55fa85..1590813635 100644--- a/api/server/routes/__tests__/mcp.spec.js+++ b/api/server/routes/__tests__/mcp.spec.js@@ -970,70 +970,105 @@ describe('MCP Routes', () => {expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();});- it('refreshes a previous account binding and recovers after a stale callback consumes CSRF', async () => {- const flowId = 'test-user-id:test-server';- const mockFlowManager = {- getFlowState: jest.fn().mockResolvedValue({- status: 'PENDING',- createdAt: Date.now(),- }),- completeFlow: jest.fn().mockResolvedValue(true),- deleteFlow: jest.fn().mockResolvedValue(true),- };-- getLogStores.mockReturnValue({});- require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);- MCPOAuthHandler.getFlowState.mockResolvedValue({- state: flowId,- serverName: 'test-server',- userId: 'test-user-id',- metadata: {},- clientInfo: {},- codeVerifier: 'current-verifier',- });- mockOAuthCompletion({ access_token: 'test-token' });- mockTokenStorageCommit();- mockRegistryInstance.getServerConfig.mockResolvedValue({});+ describe.each(['', '/chat', '/apps/librechat'])(+ 'browser binding at public path %p',+ (publicPath) => {+ let originalEnv;+ beforeEach(() => {+ originalEnv = process.env;+ process.env = {+ ...originalEnv,+ DOMAIN_CLIENT: `http://localhost${publicPath}`,+ DOMAIN_SERVER: `http://localhost${publicPath}`,+ SESSION_COOKIE_SECURE: 'false',+ };+ });+ afterEach(() => {+ process.env = originalEnv;+ });- const mockMcpManager = createLeasedMcpManager({- fetchToolsSnapshot: jest.fn().mockResolvedValue({ tools: [], complete: true }),- });- require('~/config').getMCPManager.mockReturnValue(mockMcpManager);- require('~/config').getOAuthReconnectionManager.mockReturnValue({- clearReconnection: jest.fn(),- });- require('~/server/services/Config/mcp').updateMCPServerTools.mockResolvedValue();+ it('refreshes a previous account binding and recovers after a stale callback consumes CSRF', async () => {+ const flowId = 'test-user-id:test-server';+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ status: 'PENDING',+ createdAt: Date.now(),+ }),+ completeFlow: jest.fn().mockResolvedValue(true),+ deleteFlow: jest.fn().mockResolvedValue(true),+ };- const browser = request.agent(app);- const binding = await browser- .post('/api/mcp/test-server/oauth/bind')- .set('Cookie', [`oauth_session=${generateTestCsrfToken('previous-user-id')}`])- .expect(200);- expect(binding.headers['set-cookie']).toEqual(- expect.arrayContaining([- expect.stringContaining(`oauth_session=${generateTestCsrfToken('test-user-id')}`),- ]),- );+ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);+ MCPOAuthHandler.getFlowState.mockResolvedValue({+ state: flowId,+ serverName: 'test-server',+ userId: 'test-user-id',+ metadata: {},+ clientInfo: {},+ codeVerifier: 'current-verifier',+ });+ mockOAuthCompletion({ access_token: 'test-token' });+ mockTokenStorageCommit();+ mockRegistryInstance.getServerConfig.mockResolvedValue({});- MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);- const staleResponse = await browser- .get('/api/mcp/test-server/oauth/callback')- .query({ code: 'stale-auth-code', state: 'superseded-attempt-state' });+ const mockMcpManager = createLeasedMcpManager({+ fetchToolsSnapshot: jest.fn().mockResolvedValue({ tools: [], complete: true }),+ });+ require('~/config').getMCPManager.mockReturnValue(mockMcpManager);+ require('~/config').getOAuthReconnectionManager.mockReturnValue({+ clearReconnection: jest.fn(),+ });+ require('~/server/services/Config/mcp').updateMCPServerTools.mockResolvedValue();- const basePath = getBasePath();- expect(staleResponse.status).toBe(302);- expect(staleResponse.headers.location).toBe(`${basePath}/oauth/error?error=invalid_state`);- expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();+ const publicApp = express();+ publicApp.use(cookieParser());+ publicApp.use((req, _res, next) => {+ req.user = { id: 'test-user-id' };+ next();+ });+ publicApp.use(`${publicPath}/api/mcp`, mcpRouter);+ const browser = request.agent(publicApp);+ const binding = await browser+ .post(`${publicPath}/api/mcp/test-server/oauth/bind`)+ .set('Cookie', [`oauth_session=${generateTestCsrfToken('previous-user-id')}`])+ .expect(200);+ expect(binding.headers['set-cookie']).toEqual(+ expect.arrayContaining([+ expect.stringContaining(`oauth_session=${generateTestCsrfToken('test-user-id')}`),+ expect.stringContaining(`Path=${publicPath}/api/mcp;`),+ expect.stringContaining(`Path=${publicPath}/api;`),+ ]),+ );- /** The stale callback consumed the CSRF cookie; the initiating browser retains its session binding. */- const legitResponse = await browser- .get('/api/mcp/test-server/oauth/callback')- .query({ code: 'current-auth-code', state: flowId });+ MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);+ const staleResponse = await browser+ .get(`${publicPath}/api/mcp/test-server/oauth/callback`)+ .query({ code: 'stale-auth-code', state: 'superseded-attempt-state' });- expect(legitResponse.status).toBe(302);- expect(legitResponse.headers.location).toContain(`${basePath}/oauth/success`);- expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledTimes(1);- });+ const basePath = getBasePath();+ expect(staleResponse.status).toBe(302);+ expect(staleResponse.headers.location).toBe(+ `${basePath}/oauth/error?error=invalid_state`,+ );+ expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();+ expect(MCPTokenStorage.storeTokens).not.toHaveBeenCalled();+ expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();+ expect(staleResponse.headers['set-cookie']).toEqual([+ expect.stringContaining(`Path=${publicPath}/api/mcp;`),+ ]);++ /** The stale callback consumed the CSRF cookie; the initiating browser retains its session binding. */+ const legitResponse = await browser+ .get(`${publicPath}/api/mcp/test-server/oauth/callback`)+ .query({ code: 'current-auth-code', state: flowId });++ expect(legitResponse.status).toBe(302);+ expect(legitResponse.headers.location).toContain(`${basePath}/oauth/success`);+ expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledTimes(1);+ });+ },+ );describe('browser binding for active PENDING flows', () => {it.each([diff --git a/api/server/services/ActionService.js b/api/server/services/ActionService.jsindex 9f5e7f9942..6fcdb641c6 100644--- a/api/server/services/ActionService.js+++ b/api/server/services/ActionService.js@@ -9,6 +9,7 @@ const {logAxiosError,detachOnAbort,getTokenExpiresAt,+ getOAuthCallbackUrl,refreshAccessToken,GenerationJobManager,createSSRFSafeAgents,@@ -225,7 +226,10 @@ async function createActionTool({const stateToken = jwt.sign(statePayload, JWT_SECRET, { expiresIn: '10m' });try {- const redirectUri = `${process.env.DOMAIN_CLIENT}/api/actions/${action_id}/oauth/callback`;+ const redirectUri = getOAuthCallbackUrl(+ process.env.DOMAIN_SERVER || 'http://localhost:3080',+ `/api/actions/${action_id}/oauth/callback`,+ );const params = new URLSearchParams({client_id: metadata.oauth_client_id,scope: metadata.auth.scope,@@ -280,7 +284,7 @@ async function createActionTool({state: stateToken,userId: userId,client_url: metadata.auth.client_url,- redirect_uri: `${process.env.DOMAIN_SERVER}/api/actions/${action_id}/oauth/callback`,+ redirect_uri: redirectUri,token_exchange_method: metadata.auth.token_exchange_method,allowedAddresses,/** Encrypted values */diff --git a/api/server/services/ActionService.spec.js b/api/server/services/ActionService.spec.jsindex cd6b8935af..08260b99bd 100644--- a/api/server/services/ActionService.spec.js+++ b/api/server/services/ActionService.spec.js@@ -246,75 +246,108 @@ describe('legacyDomainEncode', () => {});describe('createActionTool OAuth events', () => {- it('fences resumable login and completion deltas to the owning job epoch', async () => {- const streamId = 'action-oauth-stream';- const jobCreatedAt = 1234;- const preparedExecutor = {- setAuth: jest.fn().mockResolvedValue(undefined),- execute: jest.fn().mockResolvedValue({ data: { ok: true } }),- };- const requestBuilder = {- createExecutor: jest.fn(() => ({- setParams: jest.fn(() => preparedExecutor),- })),- };- mockFindToken.mockResolvedValue(null);- mockActionFlowManager.createFlowWithHandler.mockImplementation(- async (_flowId, _type, handler) => handler(),- );- mockActionFlowManager.createFlow.mockResolvedValue({- access_token: 'access-token',- refresh_token: 'refresh-token',- expires_in: 3600,- });+ const originalEnv = process.env;+ beforeEach(() => {+ process.env = { ...originalEnv, DOMAIN_CLIENT: 'https://client.example/ui/' };+ });+ afterEach(() => {+ process.env = originalEnv;+ });- const actionTool = await createActionTool({- userId: 'action-user',- res: {},- action: {- action_id: 'action-1',- metadata: {- domain: 'https://api.example.com',- oauth_client_id: 'client-id',- auth: {- type: 'oauth',- authorization_url: 'https://auth.example.com/authorize',- client_url: 'https://auth.example.com/token',- scope: 'read',+ it.each([+ [undefined, 'http://localhost:3080'],+ ['https://server.example', 'https://server.example'],+ ['https://server.example/', 'https://server.example'],+ ['https://server.example///', 'https://server.example'],+ ['https://server.example/chat', 'https://server.example/chat'],+ ['https://server.example/chat/', 'https://server.example/chat'],+ ['https://server.example/chat///', 'https://server.example/chat'],+ ['https://server.example/apps/librechat/', 'https://server.example/apps/librechat'],+ ])(+ 'fences OAuth events and uses one canonical callback for %s',+ async (domainServer, baseUrl) => {+ if (domainServer === undefined) {+ delete process.env.DOMAIN_SERVER;+ } else {+ process.env.DOMAIN_SERVER = domainServer;+ }+ const streamId = 'action-oauth-stream';+ const jobCreatedAt = 1234;+ const preparedExecutor = {+ setAuth: jest.fn().mockResolvedValue(undefined),+ execute: jest.fn().mockResolvedValue({ data: { ok: true } }),+ };+ const requestBuilder = {+ createExecutor: jest.fn(() => ({+ setParams: jest.fn(() => preparedExecutor),+ })),+ };+ let authorizationUrl;+ mockEmitChunk.mockImplementation(async (_streamId, event) => {+ authorizationUrl ??= event.data?.delta?.auth;+ });+ mockFindToken.mockResolvedValue(null);+ mockActionFlowManager.createFlowWithHandler.mockImplementation(+ async (_flowId, _type, handler) => handler(),+ );+ mockActionFlowManager.createFlow.mockResolvedValue({+ access_token: 'access-token',+ refresh_token: 'refresh-token',+ expires_in: 3600,+ });++ const actionTool = await createActionTool({+ userId: 'action-user',+ res: {},+ action: {+ action_id: 'action-1',+ metadata: {+ domain: 'https://api.example.com',+ oauth_client_id: 'client-id',+ auth: {+ type: 'oauth',+ authorization_url: 'https://auth.example.com/authorize',+ client_url: 'https://auth.example.com/token',+ scope: 'read',+ },},},- },- requestBuilder,- encrypted: {- oauth_client_id: 'encrypted-client-id',- oauth_client_secret: 'encrypted-client-secret',- },- streamId,- jobCreatedAt,- });-- await actionTool._call(- {},- {- metadata: {- thread_id: 'thread-1',- run_id: 'run-1',+ requestBuilder,+ encrypted: {+ oauth_client_id: 'encrypted-client-id',+ oauth_client_secret: 'encrypted-client-secret',},- toolCall: {- id: 'tool-call-1',- stepId: 'step-1',- name: 'action-tool',- type: 'tool_call',+ streamId,+ jobCreatedAt,+ });++ await actionTool._call(+ {},+ {+ metadata: {+ thread_id: 'thread-1',+ run_id: 'run-1',+ },+ toolCall: {+ id: 'tool-call-1',+ stepId: 'step-1',+ name: 'action-tool',+ type: 'tool_call',+ },},- },- );-- expect(mockEmitChunk).toHaveBeenCalledTimes(2);- for (const [emittedStreamId, , options] of mockEmitChunk.mock.calls) {- expect(emittedStreamId).toBe(streamId);- expect(options).toEqual({ expectedCreatedAt: jobCreatedAt });- }- });+ );++ const expectedRedirectUri = `${baseUrl}/api/actions/action-1/oauth/callback`;+ const [, , flowMetadata] = mockActionFlowManager.createFlow.mock.calls[0];+ expect(flowMetadata.redirect_uri).toBe(expectedRedirectUri);+ expect(new URL(authorizationUrl).searchParams.get('redirect_uri')).toBe(expectedRedirectUri);+ expect(mockEmitChunk).toHaveBeenCalledTimes(2);+ for (const [emittedStreamId, , options] of mockEmitChunk.mock.calls) {+ expect(emittedStreamId).toBe(streamId);+ expect(options).toEqual({ expectedCreatedAt: jobCreatedAt });+ }+ },+ );});describe('createActionTool OAuth flow cancellation', () => {diff --git a/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.tsindex 0911c81975..ed84738356 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts@@ -209,27 +209,60 @@ describe('MCP OAuth SSRF protection', () => {});describe('MCP OAuth redirect_uri enforcement', () => {- it('should ignore attacker-supplied redirect_uri and use the server default', async () => {- const attackerRedirectUri = 'https://attacker.example.com/steal-code';+ const originalEnv = process.env;+ let oauthServer: OAuthTestServer;- const result = await MCPOAuthHandler.initiateOAuthFlow(- 'victim-server',- 'https://mcp.example.com/',- 'victim-user-id',- {},- {- authorization_url: 'https://auth.example.com/authorize',- token_url: 'https://auth.example.com/token',- client_id: 'attacker-client',- client_secret: 'attacker-secret',- redirect_uri: attackerRedirectUri,- },- );+ beforeAll(async () => {+ oauthServer = await createOAuthMCPServer({ tokenTTLMs: 60000 });+ });+ afterAll(async () => {+ await oauthServer.close();+ });+ beforeEach(() => {+ process.env = { ...originalEnv, DOMAIN_CLIENT: 'https://client.example/ui/' };+ });+ afterEach(() => {+ process.env = originalEnv;+ });- const authUrl = new URL(result.authorizationUrl);- const expectedRedirectUri = `${process.env.DOMAIN_SERVER || 'http://localhost:3080'}/api/mcp/victim-server/oauth/callback`;- expect(authUrl.searchParams.get('redirect_uri')).toBe(expectedRedirectUri);- expect(authUrl.searchParams.get('redirect_uri')).not.toBe(attackerRedirectUri);+ it.each([+ [undefined, 'http://localhost:3080'],+ ['https://server.example', 'https://server.example'],+ ['https://server.example/', 'https://server.example'],+ ['https://server.example///', 'https://server.example'],+ ['https://server.example/chat', 'https://server.example/chat'],+ ['https://server.example/chat/', 'https://server.example/chat'],+ ['https://server.example/chat///', 'https://server.example/chat'],+ ['https://server.example/apps/librechat/', 'https://server.example/apps/librechat'],+ ])('ignores attacker redirects and canonicalizes %s', async (domainServer, baseUrl) => {+ if (domainServer === undefined) {+ delete process.env.DOMAIN_SERVER;+ } else {+ process.env.DOMAIN_SERVER = domainServer;+ }+ const attackerRedirectUri = 'https://attacker.example.com/steal-code';+ for (const preconfigured of [true, false]) {+ const result = await MCPOAuthHandler.initiateOAuthFlow(+ 'victim-server',+ oauthServer.url,+ 'victim-user-id',+ {},+ preconfigured+ ? {+ authorization_url: `${oauthServer.url}authorize`,+ token_url: `${oauthServer.url}token`,+ client_id: 'test-client',+ redirect_uri: attackerRedirectUri,+ }+ : { redirect_uri: attackerRedirectUri },+ ['127.0.0.1'],+ );+ const authUrl = new URL(result.authorizationUrl);+ const expectedRedirectUri = `${baseUrl}/api/mcp/victim-server/oauth/callback`;+ expect(authUrl.searchParams.get('redirect_uri')).toBe(expectedRedirectUri);+ expect(result.flowMetadata.clientInfo?.redirect_uris).toEqual([expectedRedirectUri]);+ expect(authUrl.searchParams.get('redirect_uri')).not.toBe(attackerRedirectUri);+ }});});diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.tsindex 3123163cdf..be77d0045d 100644--- a/packages/api/src/mcp/oauth/handler.ts+++ b/packages/api/src/mcp/oauth/handler.ts@@ -37,6 +37,7 @@ import { MCPTokenStorage, MCPTokenRefreshUnavailableError } from './tokens';import { probeResourceMetadataHint } from './resourceHint';import { createHardenedOAuthFetch } from './hardenedFetch';import { sanitizeUrlForLogging } from '~/mcp/utils';+import { getOAuthCallbackUrl } from '~/oauth/url';import { getOAuthUrlPort } from './url';/** Type for the OAuth metadata from the SDK */@@ -1680,9 +1681,10 @@ export class MCPOAuthHandler {*/private static getDefaultRedirectUri(serverName?: string): string {const baseUrl = process.env.DOMAIN_SERVER || 'http://localhost:3080';- return serverName- ? `${baseUrl}/api/mcp/${serverName}/oauth/callback`- : `${baseUrl}/api/mcp/oauth/callback`;+ const callbackPath = serverName+ ? `/api/mcp/${serverName}/oauth/callback`+ : '/api/mcp/oauth/callback';+ return getOAuthCallbackUrl(baseUrl, callbackPath);}/**diff --git a/packages/api/src/oauth/csrf.spec.ts b/packages/api/src/oauth/csrf.spec.tsindex b512ff4735..548d7288cb 100644--- a/packages/api/src/oauth/csrf.spec.ts+++ b/packages/api/src/oauth/csrf.spec.ts@@ -1,5 +1,6 @@import crypto from 'crypto';import jwt from 'jsonwebtoken';+import type { Request, Response } from 'express';import {shouldUseSecureCookie,setRefreshTokenCookie,@@ -7,8 +8,78 @@ import {REFRESH_TOKEN_COOKIE,TOKEN_PROVIDER_COOKIE,OPENID_USER_ID_COOKIE,+ setOAuthCsrfCookie,+ setOAuthSessionCookie,+ validateOAuthCsrf,+ generateOAuthCsrfToken,} from './csrf';+describe('OAuth browser binding cookie paths', () => {+ const originalEnv = process.env;++ beforeEach(() => {+ process.env = {+ ...originalEnv,+ DOMAIN_CLIENT: 'https://client.example/ui',+ JWT_SECRET: 'cookie-path-test-secret',+ SESSION_COOKIE_SECURE: 'false',+ };+ });++ afterEach(() => {+ process.env = originalEnv;+ });++ it.each([+ { domainServer: undefined, basePath: '' },+ { domainServer: '', basePath: '' },+ { domainServer: 'invalid', basePath: '' },+ { domainServer: 'https://server.example', basePath: '' },+ { domainServer: 'https://server.example/', basePath: '' },+ { domainServer: 'https://server.example/chat', basePath: '/chat' },+ { domainServer: 'https://server.example/chat/', basePath: '/chat' },+ { domainServer: 'https://server.example/chat///', basePath: '/chat' },+ { domainServer: 'https://server.example/apps/librechat', basePath: '/apps/librechat' },+ ])(+ 'issues and clears cookies under $basePath for $domainServer',+ async ({ domainServer, basePath }) => {+ if (domainServer === undefined) {+ delete process.env.DOMAIN_SERVER;+ } else {+ process.env.DOMAIN_SERVER = domainServer;+ }++ const res = { cookie: jest.fn(), clearCookie: jest.fn() } as unknown as Response;+ setOAuthSessionCookie(res, 'user-123');+ expect(res.cookie).toHaveBeenCalledWith(+ 'oauth_session',+ generateOAuthCsrfToken('user-123'),+ expect.objectContaining({ path: `${basePath}/api`, httpOnly: true, sameSite: 'lax' }),+ );+ for (const route of ['mcp', 'actions']) {+ const cookiePath = `/api/${route}`;+ const flowId = `user-123:${route}`;+ const token = generateOAuthCsrfToken(flowId);+ setOAuthCsrfCookie(res, flowId, cookiePath);+ expect(res.cookie).toHaveBeenCalledWith(+ 'oauth_csrf',+ token,+ expect.objectContaining({+ path: `${basePath}${cookiePath}`,+ httpOnly: true,+ sameSite: 'lax',+ }),+ );+ const req = { cookies: { oauth_csrf: token } } as Request;+ expect(validateOAuthCsrf(req, res, flowId, cookiePath)).toBe(true);+ expect(res.clearCookie).toHaveBeenCalledWith('oauth_csrf', {+ path: `${basePath}${cookiePath}`,+ });+ }+ },+ );+});+describe('shouldUseSecureCookie', () => {const originalEnv = process.env;diff --git a/packages/api/src/oauth/csrf.ts b/packages/api/src/oauth/csrf.tsindex 08dd0bdf2e..1ad1ad6443 100644--- a/packages/api/src/oauth/csrf.ts+++ b/packages/api/src/oauth/csrf.ts@@ -1,6 +1,7 @@import crypto from 'crypto';import jwt from 'jsonwebtoken';import type { Request, Response, NextFunction } from 'express';+import { getOAuthCallbackUrl } from './url';import { isEnabled } from '~/utils/common';export const OAUTH_CSRF_COOKIE = 'oauth_csrf';@@ -134,6 +135,19 @@ export function generateOAuthCsrfToken(flowId: string, secret?: string): stringreturn crypto.createHmac('sha256', key).update(flowId).digest('hex').slice(0, 32);}+/** Cookie paths must match the public callback URL, not a proxy-stripped request path. */+function getOAuthCookiePath(cookiePath: string): string {+ const domainServer = process.env.DOMAIN_SERVER;+ if (!domainServer) {+ return cookiePath;+ }+ try {+ return new URL(getOAuthCallbackUrl(domainServer, cookiePath)).pathname;+ } catch {+ return cookiePath;+ }+}+/** Sets a SameSite=Lax CSRF cookie bound to a specific OAuth flow */export function setOAuthCsrfCookie(res: Response, flowId: string, cookiePath: string): void {res.cookie(OAUTH_CSRF_COOKIE, generateOAuthCsrfToken(flowId), {@@ -141,7 +155,7 @@ export function setOAuthCsrfCookie(res: Response, flowId: string, cookiePath: stsecure: shouldUseSecureCookie(),sameSite: 'lax',maxAge: OAUTH_CSRF_MAX_AGE,- path: cookiePath,+ path: getOAuthCookiePath(cookiePath),});}@@ -156,7 +170,7 @@ export function validateOAuthCsrf(cookiePath: string,): boolean {const cookie = (req.cookies as Record<string, string> | undefined)?.[OAUTH_CSRF_COOKIE];- res.clearCookie(OAUTH_CSRF_COOKIE, { path: cookiePath });+ res.clearCookie(OAUTH_CSRF_COOKIE, { path: getOAuthCookiePath(cookiePath) });if (typeof cookie !== 'string' || !cookie) {return false;}@@ -191,7 +205,7 @@ export function setOAuthSessionCookie(res: Response, userId: string): void {secure: shouldUseSecureCookie(),sameSite: 'lax',maxAge: OAUTH_SESSION_MAX_AGE,- path: OAUTH_SESSION_COOKIE_PATH,+ path: getOAuthCookiePath(OAUTH_SESSION_COOKIE_PATH),});}diff --git a/packages/api/src/oauth/index.ts b/packages/api/src/oauth/index.tsindex 1101b5cde4..ba390f01ac 100644--- a/packages/api/src/oauth/index.ts+++ b/packages/api/src/oauth/index.ts@@ -1,3 +1,4 @@+export * from './url';export * from './csrf';export * from './state';export * from './expiry';diff --git a/packages/api/src/oauth/url.spec.ts b/packages/api/src/oauth/url.spec.tsnew file mode 100644index 0000000000..52e15f876b--- /dev/null+++ b/packages/api/src/oauth/url.spec.ts@@ -0,0 +1,21 @@+import { getOAuthCallbackUrl } from './url';++describe('getOAuthCallbackUrl', () => {+ it.each([+ ['https://server.example', 'https://server.example'],+ ['https://server.example/', 'https://server.example'],+ ['https://server.example///', 'https://server.example'],+ ['https://server.example/chat', 'https://server.example/chat'],+ ['https://server.example/chat/', 'https://server.example/chat'],+ ['https://server.example/chat///', 'https://server.example/chat'],+ ['https://server.example/apps/librechat/', 'https://server.example/apps/librechat'],+ ])('joins %s to callback paths without duplicate slashes', (baseUrl, expected) => {+ for (const callbackPath of [+ '/api/mcp/test-server/oauth/callback',+ '/api/mcp/oauth/callback',+ '/api/actions/test-action/oauth/callback',+ ]) {+ expect(getOAuthCallbackUrl(baseUrl, callbackPath)).toBe(`${expected}${callbackPath}`);+ }+ });+});diff --git a/packages/api/src/oauth/url.ts b/packages/api/src/oauth/url.tsnew file mode 100644index 0000000000..bf7670f453--- /dev/null+++ b/packages/api/src/oauth/url.ts@@ -0,0 +1,4 @@+/** Join the public API domain and callback path without a duplicate slash. */+export function getOAuthCallbackUrl(baseUrl: string, callbackPath: string): string {+ return `${baseUrl.replace(/\/+$/, '')}${callbackPath}`;+}