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: Restore MCP OAuth Browser Binding (#16634)
Danny Avilad349120ec372
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.jsindex 59e9227d13..1c1e55fa85 100644--- a/api/server/routes/__tests__/mcp.spec.js+++ b/api/server/routes/__tests__/mcp.spec.js@@ -633,6 +633,55 @@ describe('MCP Routes', () => {});});+ describe('POST /:serverName/oauth/bind', () => {+ it.each([+ { name: 'absent', cookies: [], refresh: true },+ { name: 'invalid', cookies: ['oauth_session=invalid'], refresh: true },+ {+ name: 'UTF-8 byte-length mismatch',+ cookies: [`oauth_session=${encodeURIComponent('é'.repeat(32))}`],+ refresh: true,+ },+ {+ name: 'non-string JSON',+ cookies: ['oauth_session=j:{"userId":"test-user-id"}'],+ refresh: true,+ },+ {+ name: 'previous account',+ cookies: [`oauth_session=${generateTestCsrfToken('previous-user-id')}`],+ refresh: true,+ },+ {+ name: 'current account',+ cookies: [`oauth_session=${generateTestCsrfToken('test-user-id')}`],+ refresh: false,+ },+ ])(+ 'handles a $name session binding before issuing the flow cookie',+ async ({ cookies, refresh }) => {+ const response = await request(app)+ .post('/api/mcp/test-server/oauth/bind')+ .set('Cookie', cookies)+ .expect(200);+ const issuedCookies = response.headers['set-cookie'];+ expect(issuedCookies).toEqual(+ expect.arrayContaining([+ expect.stringContaining(+ `oauth_csrf=${generateTestCsrfToken('test-user-id:test-server')}`,+ ),+ ]),+ );+ const sessionCookie = issuedCookies.find((cookie) => cookie.startsWith('oauth_session='));+ if (refresh) {+ expect(sessionCookie).toContain(`oauth_session=${generateTestCsrfToken('test-user-id')}`);+ } else {+ expect(sessionCookie).toBeUndefined();+ }+ },+ );+ });+describe('GET /:serverName/oauth/callback', () => {const { MCPOAuthHandler, MCPTokenStorage } = require('@librechat/api');const { getLogStores } = require('~/cache');@@ -921,7 +970,7 @@ describe('MCP Routes', () => {expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();});- it('should let the current tab complete after a stale callback burned the CSRF cookie', async () => {+ 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({@@ -955,11 +1004,20 @@ describe('MCP Routes', () => {});require('~/server/services/Config/mcp').updateMCPServerTools.mockResolvedValue();+ 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')}`),+ ]),+ );+MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);- const csrfToken = generateTestCsrfToken(flowId);- const staleResponse = await request(app)+ const staleResponse = await browser.get('/api/mcp/test-server/oauth/callback')- .set('Cookie', [`oauth_csrf=${csrfToken}`]).query({ code: 'stale-auth-code', state: 'superseded-attempt-state' });const basePath = getBasePath();@@ -967,8 +1025,8 @@ describe('MCP Routes', () => {expect(staleResponse.headers.location).toBe(`${basePath}/oauth/error?error=invalid_state`);expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();- /** The stale callback consumed the CSRF cookie; the current tab recovers via the fresh PENDING flow */- const legitResponse = await request(app)+ /** 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 });@@ -977,8 +1035,54 @@ describe('MCP Routes', () => {expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledTimes(1);});- describe('CSRF fallback via active PENDING flow', () => {- it('should proceed when a fresh PENDING flow exists and no cookies are present', async () => {+ describe('browser binding for active PENDING flows', () => {+ it.each([+ { cookies: [] },+ { cookies: ['oauth_csrf=invalid'] },+ { cookies: [`oauth_csrf=${encodeURIComponent('é'.repeat(32))}`] },+ { cookies: [`oauth_session=${encodeURIComponent('é'.repeat(32))}`] },+ { cookies: ['oauth_csrf=j:{"flowId":"test-user-id:test-server"}'] },+ { cookies: ['oauth_session=j:{"userId":"test-user-id"}'] },+ { cookies: [`oauth_session=${generateTestCsrfToken('victim-user-id')}`] },+ {+ cookies: [+ 'oauth_csrf=invalid',+ `oauth_session=${generateTestCsrfToken('victim-user-id')}`,+ ],+ },+ ])(+ 'rejects an unbound pending flow with %j before exchange or mutation',+ async ({ cookies }) => {+ const flowId = 'test-user-id:test-server';+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ status: 'PENDING',+ createdAt: Date.now(),+ metadata: { state: flowId, userId: 'test-user-id', codeVerifier: 'test-verifier' },+ }),+ completeFlow: jest.fn(),+ failFlow: jest.fn(),+ deleteFlow: jest.fn(),+ };+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);+ const response = await request(app)+ .get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', cookies)+ .query({ code: 'victim-auth-code', state: flowId });++ expect(response.headers.location).toBe(+ `${getBasePath()}/oauth/error?error=csrf_validation_failed`,+ );+ expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();+ expect(MCPTokenStorage.storeTokens).not.toHaveBeenCalled();+ expect(mockFlowManager.getFlowState).not.toHaveBeenCalled();+ expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();+ expect(mockFlowManager.failFlow).not.toHaveBeenCalled();+ expect(mockFlowManager.deleteFlow).not.toHaveBeenCalled();+ },+ );++ it('should proceed when a fresh PENDING flow has a valid session binding', async () => {const flowId = 'test-user-id:test-server';const pendingCreatedAt = Date.now();const mockFlowManager = {@@ -1027,6 +1131,7 @@ describe('MCP Routes', () => {const response = await request(app).get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_session=${generateTestCsrfToken('test-user-id')}`]).query({ code: 'test-code', state: flowId });const basePath = getBasePath();@@ -1099,6 +1204,7 @@ describe('MCP Routes', () => {const response = await request(app).get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`]).query({ code: 'test-code', state: flowId });expect(response.status).toBe(302);@@ -1166,6 +1272,7 @@ describe('MCP Routes', () => {const response = await request(app).get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`]).query({ code: 'test-code', state: flowId });expect(response.status).toBe(302);@@ -1229,6 +1336,7 @@ describe('MCP Routes', () => {const response = await request(app).get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`]).query({ code: 'test-code', state: flowId });expect(response.status).toBe(302);diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.jsindex 5b06bde702..6d8976692d 100644--- a/api/server/routes/mcp.js+++ b/api/server/routes/mcp.js@@ -352,30 +352,13 @@ router.get('/:serverName/oauth/callback', async (req, res) => {const hasCsrf = validateOAuthCsrf(req, res, flowId, OAUTH_CSRF_COOKIE_PATH);const hasSession = !hasCsrf && validateOAuthSession(req, parsedFlowId.userId);- let hasActiveFlow = false;- if (!hasCsrf && !hasSession) {- const pendingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');- const pendingAge = pendingFlow?.createdAt ? Date.now() - pendingFlow.createdAt : Infinity;- hasActiveFlow = pendingFlow?.status === 'PENDING' && pendingAge < PENDING_STALE_MS;- if (hasActiveFlow) {- logger.debug(- '[MCP OAuth] CSRF/session cookies absent, validating via active PENDING flow',- {- flowId,- },- );- }- }- if (!hasCsrf && !hasSession && !hasActiveFlow) {- logger.error(- '[MCP OAuth] CSRF validation failed: no valid CSRF cookie, session cookie, or active flow',- {- flowId,- hasCsrfCookie: !!req.cookies?.[OAUTH_CSRF_COOKIE],- hasSessionCookie: !!req.cookies?.[OAUTH_SESSION_COOKIE],- },- );+ if (!hasCsrf && !hasSession) {+ logger.error('[MCP OAuth] CSRF validation failed: no valid CSRF or session cookie', {+ flowId,+ hasCsrfCookie: !!req.cookies?.[OAUTH_CSRF_COOKIE],+ hasSessionCookie: !!req.cookies?.[OAUTH_SESSION_COOKIE],+ });return res.redirect(`${basePath}/oauth/error?error=csrf_validation_failed`);}diff --git a/e2e/specs/mock/mcp-oauth-resume.spec.ts b/e2e/specs/mock/mcp-oauth-resume.spec.tsindex 79fb86bff9..f4e734aea2 100644--- a/e2e/specs/mock/mcp-oauth-resume.spec.ts+++ b/e2e/specs/mock/mcp-oauth-resume.spec.ts@@ -27,7 +27,10 @@ type GenerationStatus = {};test.describe('MCP OAuth stream resume', () => {- test('restores one actionable OAuth prompt after reloading the stream', async ({ page }) => {+ test('restores one browser-bound OAuth prompt after rejecting an unbound callback', async ({+ page,+ browser,+ }) => {test.setTimeout(120000);await page.goto(NEW_CHAT_PATH, { timeout: 10000 });@@ -78,6 +81,7 @@ test.describe('MCP OAuth stream resume', () => {const signIn = page.getByRole('button', { name: SIGN_IN_BUTTON });await expect(signIn).toBeVisible({ timeout: 30000 });await expect(signIn).toHaveCount(1);+ await expect(signIn).toBeEnabled();const status = await fetchJson<GenerationStatus>(page,@@ -93,6 +97,31 @@ test.describe('MCP OAuth stream resume', () => {}),]);+ const authorizationUrl = new URL(status.resumeState!.pendingOAuthPrompts![0].authURL);+ const callbackUrl = new URL(authorizationUrl.searchParams.get('redirect_uri')!);+ callbackUrl.searchParams.set('state', authorizationUrl.searchParams.get('state')!);+ callbackUrl.searchParams.set('code', 'unbound-provider-code');+ const unboundBrowser = await browser.newContext();+ try {+ const callback = await unboundBrowser.request.get(callbackUrl.toString(), {+ maxRedirects: 0,+ });+ expect(callback.status()).toBe(302);+ expect(callback.headers().location).toContain('/oauth/error?error=csrf_validation_failed');+ } finally {+ await unboundBrowser.close();+ }++ const afterUnboundCallback = await fetchJson<GenerationStatus>(+ page,+ `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ );+ expect(afterUnboundCallback.active).toBe(true);+ expect(afterUnboundCallback.resumeState?.pendingOAuthPrompts).toEqual(+ status.resumeState?.pendingOAuthPrompts,+ );+const resumeRequest = page.waitForRequest((request) => {const url = new URL(request.url());diff --git a/packages/api/src/mcp/__tests__/MCPOAuthCSRFFallback.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthCSRFFallback.test.tsdeleted file mode 100644index c0a861817c..0000000000--- a/packages/api/src/mcp/__tests__/MCPOAuthCSRFFallback.test.ts+++ /dev/null@@ -1,234 +0,0 @@-/**- * Tests for the OAuth callback CSRF fallback logic.- *- * The callback route validates requests via three mechanisms (in order):- * 1. CSRF cookie (HMAC-based, set during initiate)- * 2. Session cookie (bound to authenticated userId)- * 3. Active PENDING flow in FlowStateManager (fallback for SSE/chat flows)- *- * This suite tests mechanism 3 — the PENDING flow fallback — including- * staleness enforcement and rejection of non-PENDING flows.- *- * These tests exercise the validation functions directly for fast,- * focused coverage. Route-level integration tests using supertest- * are in api/server/routes/__tests__/mcp.spec.js ("CSRF fallback- * via active PENDING flow" describe block).- */--import { Keyv } from 'keyv';-import { FlowStateManager, PENDING_STALE_MS } from '~/flow/manager';-import type { Request, Response } from 'express';-import {- generateOAuthCsrfToken,- OAUTH_SESSION_COOKIE,- validateOAuthSession,- OAUTH_CSRF_COOKIE,- validateOAuthCsrf,-} from '~/oauth/csrf';-import { MockKeyv } from './helpers/oauthTestServer';--jest.mock('@librechat/data-schemas', () => ({- logger: {- info: jest.fn(),- warn: jest.fn(),- error: jest.fn(),- debug: jest.fn(),- },- getTenantId: jest.fn(),- SYSTEM_TENANT_ID: '__SYSTEM__',- encryptV2: jest.fn(async (val: string) => `enc:${val}`),- decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),-}));--const CSRF_COOKIE_PATH = '/api/mcp';--function makeReq(cookies: Record<string, string> = {}): Request {- return { cookies } as unknown as Request;-}--function makeRes(): Response {- const res = {- clearCookie: jest.fn(),- } as unknown as Response;- return res;-}--/**- * Replicate the callback route's three-tier validation logic.- * Returns which mechanism (if any) authorized the request.- */-async function validateCallback(- req: Request,- res: Response,- flowId: string,- flowManager: FlowStateManager,-): Promise<'csrf' | 'session' | 'pendingFlow' | false> {- const flowUserId = flowId.split(':')[0];-- const hasCsrf = validateOAuthCsrf(req, res, flowId, CSRF_COOKIE_PATH);- if (hasCsrf) {- return 'csrf';- }-- const hasSession = validateOAuthSession(req, flowUserId);- if (hasSession) {- return 'session';- }-- const pendingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');- const pendingAge = pendingFlow?.createdAt ? Date.now() - pendingFlow.createdAt : Infinity;- if (pendingFlow?.status === 'PENDING' && pendingAge < PENDING_STALE_MS) {- return 'pendingFlow';- }-- return false;-}--describe('OAuth Callback CSRF Fallback', () => {- let flowManager: FlowStateManager;-- beforeEach(() => {- process.env.JWT_SECRET = 'test-secret-for-csrf';- const store = new MockKeyv();- flowManager = new FlowStateManager(store as unknown as Keyv, { ttl: 300000, ci: true });- });-- afterEach(() => {- delete process.env.JWT_SECRET;- jest.clearAllMocks();- });-- describe('CSRF cookie validation (mechanism 1)', () => {- it('should accept valid CSRF cookie', async () => {- const flowId = 'user1:test-server';- const csrfToken = generateOAuthCsrfToken(flowId, 'test-secret-for-csrf');- const req = makeReq({ [OAUTH_CSRF_COOKIE]: csrfToken });- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('csrf');- });-- it('should reject invalid CSRF cookie', async () => {- const flowId = 'user1:test-server';- const req = makeReq({ [OAUTH_CSRF_COOKIE]: 'wrong-token-value' });- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe(false);- });- });-- describe('Session cookie validation (mechanism 2)', () => {- it('should accept valid session cookie when CSRF is absent', async () => {- const flowId = 'user1:test-server';- const sessionToken = generateOAuthCsrfToken('user1', 'test-secret-for-csrf');- const req = makeReq({ [OAUTH_SESSION_COOKIE]: sessionToken });- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('session');- });- });-- describe('PENDING flow fallback (mechanism 3)', () => {- it('should accept when a fresh PENDING flow exists and no cookies are present', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });-- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('pendingFlow');- });-- it('should reject when no PENDING flow, no CSRF cookie, and no session cookie', async () => {- const flowId = 'user1:test-server';- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe(false);- });-- it('should reject when only a COMPLETED flow exists (not PENDING)', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });- await flowManager.completeFlow(flowId, 'mcp_oauth', { access_token: 'tok' } as never);-- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe(false);- });-- it('should reject when only a FAILED flow exists', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', {});- await flowManager.failFlow(flowId, 'mcp_oauth', 'some error');-- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe(false);- });-- it('should reject when PENDING flow is stale (older than PENDING_STALE_MS)', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });-- // Artificially age the flow past the staleness threshold- const store = (flowManager as unknown as { keyv: { get: (k: string) => Promise<unknown> } })- .keyv;- const flowState = (await store.get(`mcp_oauth:${flowId}`)) as { createdAt: number };- flowState.createdAt = Date.now() - PENDING_STALE_MS - 1000;-- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe(false);- });-- it('should accept PENDING flow that is just under the staleness threshold', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });-- // Flow was just created, well under threshold- const req = makeReq();- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('pendingFlow');- });- });-- describe('Priority ordering', () => {- it('should prefer CSRF cookie over PENDING flow', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });-- const csrfToken = generateOAuthCsrfToken(flowId, 'test-secret-for-csrf');- const req = makeReq({ [OAUTH_CSRF_COOKIE]: csrfToken });- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('csrf');- });-- it('should prefer session cookie over PENDING flow when CSRF is absent', async () => {- const flowId = 'user1:test-server';- await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'test-server' });-- const sessionToken = generateOAuthCsrfToken('user1', 'test-secret-for-csrf');- const req = makeReq({ [OAUTH_SESSION_COOKIE]: sessionToken });- const res = makeRes();-- const result = await validateCallback(req, res, flowId, flowManager);- expect(result).toBe('session');- });- });-});diff --git a/packages/api/src/oauth/csrf.ts b/packages/api/src/oauth/csrf.tsindex 0912815dc4..4df6b1498f 100644--- a/packages/api/src/oauth/csrf.ts+++ b/packages/api/src/oauth/csrf.ts@@ -157,14 +157,19 @@ export function validateOAuthCsrf(): boolean {const cookie = (req.cookies as Record<string, string> | undefined)?.[OAUTH_CSRF_COOKIE];res.clearCookie(OAUTH_CSRF_COOKIE, { path: cookiePath });- if (!cookie) {+ if (typeof cookie !== 'string' || !cookie) {return false;}const expected = generateOAuthCsrfToken(flowId);if (cookie.length !== expected.length) {return false;}- return crypto.timingSafeEqual(Buffer.from(cookie), Buffer.from(expected));+ const cookieBuffer = Buffer.from(cookie);+ const expectedBuffer = Buffer.from(expected);+ return (+ cookieBuffer.length === expectedBuffer.length &&+ crypto.timingSafeEqual(cookieBuffer, expectedBuffer)+ );}/**@@ -173,7 +178,7 @@ export function validateOAuthCsrf(*/export function setOAuthSession(req: Request, res: Response, next: NextFunction): void {const user = (req as Request & { user?: { id?: string } }).user;- if (user?.id && !(req.cookies as Record<string, string> | undefined)?.[OAUTH_SESSION_COOKIE]) {+ if (user?.id && !validateOAuthSession(req, user.id)) {setOAuthSessionCookie(res, user.id);}next();@@ -193,12 +198,17 @@ export function setOAuthSessionCookie(res: Response, userId: string): void {/** Validates the session cookie against the expected userId using timing-safe comparison */export function validateOAuthSession(req: Request, userId: string): boolean {const cookie = (req.cookies as Record<string, string> | undefined)?.[OAUTH_SESSION_COOKIE];- if (!cookie) {+ if (typeof cookie !== 'string' || !cookie) {return false;}const expected = generateOAuthCsrfToken(userId);if (cookie.length !== expected.length) {return false;}- return crypto.timingSafeEqual(Buffer.from(cookie), Buffer.from(expected));+ const cookieBuffer = Buffer.from(cookie);+ const expectedBuffer = Buffer.from(expected);+ return (+ cookieBuffer.length === expectedBuffer.length &&+ crypto.timingSafeEqual(cookieBuffer, expectedBuffer)+ );}