π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(connector): finish MCP OAuth installs inside workspaces (#20400)
Rdmclin25c8179cd658d
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 53500e4648a..3d86505a673 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -629,6 +629,7 @@ export const connectorRouter = router({connectorId: input.id,lobeUserId: ctx.userId,returnTo: input.returnTo,+ workspaceId: ctx.workspaceId ?? undefined,});return { authorizationUrl };diff --git a/apps/server/src/services/connector/stateStore.ts b/apps/server/src/services/connector/stateStore.tsindex a3187cf481e..a190272c6ed 100644--- a/apps/server/src/services/connector/stateStore.ts+++ b/apps/server/src/services/connector/stateStore.ts@@ -25,6 +25,11 @@ export interface ConnectorOAuthStatePayload {returnTo?: string;/** Issuance timestamp (ms epoch) for diagnostics. */ts: number;+ /**+ * Workspace the connector belongs to. The callback has no request context of+ * its own, so it must reuse this to find workspace-scoped connectors.+ */+ workspaceId?: string;}/** Generate an opaque, single-use state value to embed in the authorize URL. */diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.tsindex a0497bdf98b..8d3bc879870 100644--- a/src/app/(backend)/oauth/connector/callback/route.test.ts+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts@@ -2,6 +2,9 @@ import { runInNewContext } from 'node:vm';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { GET } from './route';const { mockConsume, mockFindById, mockSync, mockUpdate } = vi.hoisted(() => ({@@ -42,8 +45,8 @@ vi.mock('@/database/models/connectorTool', () => ({}));vi.mock('@/server/services/connector/sync', () => ({ syncConnectorToolsById: mockSync }));-const makeReq = () =>- ({ nextUrl: { searchParams: new URLSearchParams('code=abc&state=xyz') } }) as any;+const makeReq = (query = 'code=abc&state=xyz') =>+ ({ nextUrl: { searchParams: new URLSearchParams(query) } }) as any;beforeEach(() => {vi.clearAllMocks();@@ -62,6 +65,7 @@ beforeEach(() => {},});mockUpdate.mockResolvedValue(undefined);+ vi.spyOn(console, 'error').mockImplementation(() => {});});describe('connector OAuth callback', () => {@@ -114,4 +118,42 @@ describe('connector OAuth callback', () => {expect(body).toContain('"success":true');expect(body).toContain('"synced":true');});++ it('looks the connector up in the workspace it was started from', async () => {+ mockSync.mockResolvedValue({ toolCount: 5 });+ mockConsume.mockResolvedValue({+ authorizationServerUrl: 'https://as',+ codeVerifier: 'v',+ connectorId: 'c1',+ lobeUserId: 'u1',+ workspaceId: 'ws1',+ });++ const body = await (await GET(makeReq())).text();++ expect(body).toContain('"success":true');+ expect(ConnectorModel).toHaveBeenCalledWith({}, 'u1', 'ws1', {});+ expect(ConnectorToolModel).toHaveBeenCalledWith({}, 'u1', 'ws1');+ });++ it('keeps the failure page open and shows the escaped reason', async () => {+ mockFindById.mockResolvedValue(undefined);++ const body = await (await GET(makeReq())).text();++ expect(body).toContain('Authorization failed.');+ expect(body).toContain('>connector_not_found</p>');+ expect(body).not.toContain('window.close');+ expect(console.error).toHaveBeenCalled();+ });++ it('shows the provider error description without injecting markup', async () => {+ const body = await (+ await GET(makeReq('error=access_denied&error_description=%3Cimg%20src%3Dx%3E'))+ ).text();++ expect(body).toContain('access_denied: <img src=x>');+ expect(body).not.toContain('<img');+ expect(mockConsume).not.toHaveBeenCalled();+ });});diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.tsindex 08dfa5c7bba..64b88be8456 100644--- a/src/app/(backend)/oauth/connector/callback/route.ts+++ b/src/app/(backend)/oauth/connector/callback/route.ts@@ -36,7 +36,17 @@ const jsonForScript = (value: unknown): string =>(c) => '\\u' + c.codePointAt(0)!.toString(16).padStart(4, '0'),);-/** Auto-closing popup page that reports the result back to the opener window. */+const escapeHtml = (value: string): string =>+ value.replaceAll(+ /[&<>"']/g,+ (c) => ({ '"': '"', '&': '&', "'": ''', '<': '<', '>': '>' })[c]!,+ );++/**+ * Popup page that reports the result back to the opener window. Success closes+ * itself; failure stays open with the reason, because providers whose COOP+ * policy severs `window.opener` leave the page as the only place to see it.+ */const renderResultPage = (result: {connectorId?: string;error?: string;@@ -50,6 +60,7 @@ const renderResultPage = (result: {<head><meta charset="utf-8" /><title>Connector authorization</title></head><body style="font-family: system-ui, sans-serif; padding: 24px; text-align: center;"><p>${result.success ? 'Authorization complete. You can close this window.' : 'Authorization failed.'}</p>+ ${result.error ? `<p style="color: #888; font-size: 13px; word-break: break-word;">${escapeHtml(result.error)}</p>` : ''}<script>(function () {try {@@ -60,7 +71,7 @@ const renderResultPage = (result: {window.opener.postMessage(${payload}, ${jsonForScript(targetOrigin())});}} catch (e) {}- setTimeout(function () { window.close(); }, 300);+ ${result.success ? 'setTimeout(function () { window.close(); }, 300);' : ''}})();</script></body>@@ -70,6 +81,11 @@ const renderResultPage = (result: {});};+const renderFailure = (error: string, cause?: unknown): NextResponse => {+ console.error('[connector OAuth callback] failed: %s', error, cause ?? '');+ return renderResultPage({ error, success: false });+};+export const GET = async (req: NextRequest) => {const searchParams = req.nextUrl.searchParams;const code = searchParams.get('code');@@ -77,36 +93,43 @@ export const GET = async (req: NextRequest) => {const oauthError = searchParams.get('error');if (oauthError) {- log('authorization server returned error: %s', oauthError);- return renderResultPage({ error: oauthError, success: false });+ const description = searchParams.get('error_description');+ return renderFailure(description ? `${oauthError}: ${description}` : oauthError);}if (!code || !state) {- return renderResultPage({ error: 'missing_code_or_state', success: false });+ return renderFailure('missing_code_or_state');}try {const payload = await consumeConnectorOAuthState(state);if (!payload) {- return renderResultPage({ error: 'invalid_or_expired_state', success: false });+ return renderFailure('invalid_or_expired_state');}const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const connectorModel = new ConnectorModel(serverDB, payload.lobeUserId, undefined, gateKeeper);+ // Same scope the connector was created in; otherwise a workspace connector+ // is looked up as a personal one and never found.+ const connectorModel = new ConnectorModel(+ serverDB,+ payload.lobeUserId,+ payload.workspaceId,+ gateKeeper,+ );const connector = await connectorModel.findById(payload.connectorId);if (!connector) {- return renderResultPage({ error: 'connector_not_found', success: false });+ return renderFailure('connector_not_found');}const oidc = connector.oidcConfig;if (!oidc?.clientId) {- return renderResultPage({ error: 'connector_missing_client', success: false });+ return renderFailure('connector_missing_client');}const metadata = await discoverAuthorizationServerMetadata(payload.authorizationServerUrl);if (!metadata) {- return renderResultPage({ error: 'metadata_discovery_failed', success: false });+ return renderFailure('metadata_discovery_failed');}const tokens = await exchangeConnectorCode({@@ -131,7 +154,11 @@ export const GET = async (req: NextRequest) => {// Sync the tool list server-side so the connector is immediately usable β// no dependency on the popup/postMessage round-trip. This also sets the// connector status (connected on success, error on failure).- const connectorToolModel = new ConnectorToolModel(serverDB, payload.lobeUserId);+ const connectorToolModel = new ConnectorToolModel(+ serverDB,+ payload.lobeUserId,+ payload.workspaceId,+ );let synced = false;try {const { toolCount } = await syncConnectorToolsById(payload.connectorId, {@@ -149,8 +176,7 @@ export const GET = async (req: NextRequest) => {return renderResultPage({ connectorId: payload.connectorId, success: true, synced });} catch (err) {- log('connector OAuth callback error: %O', err);const message = err instanceof Error ? err.message : 'internal_error';- return renderResultPage({ error: message, success: false });+ return renderFailure(message, err);}};diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex 3c341075da0..b2193803ec6 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -316,7 +316,17 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(},},popup,- { createConnector, deleteConnector, startConnectorOAuth, waitForConnectorOAuth },+ {+ createConnector,+ deleteConnector,+ isConnectorConnected: async (id) => {+ await fetchConnectors();+ const latest = connectorSelectors.connectorById(id)(useToolStore.getState());+ return latest?.status === 'connected';+ },+ startConnectorOAuth,+ waitForConnectorOAuth,+ },);} finally {// Close the blank/in-flight popup we opened so it isn't left dangling.diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts b/src/features/Connectors/CustomConnectorModal/oauthCreate.test.tsindex 37a0e072e7b..c4e2c3136c9 100644--- a/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts+++ b/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts@@ -1,10 +1,13 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { ConnectorOAuthError } from '@/utils/connectorOAuth';+import { executeOAuthCreate } from './oauthCreate';const deps = {createConnector: vi.fn(),deleteConnector: vi.fn(),+ isConnectorConnected: vi.fn(),startConnectorOAuth: vi.fn(),waitForConnectorOAuth: vi.fn(),};@@ -14,6 +17,7 @@ describe('executeOAuthCreate', () => {beforeEach(() => {vi.clearAllMocks();deps.deleteConnector.mockResolvedValue(undefined);+ deps.isConnectorConnected.mockResolvedValue(false);});it('opens the authorize URL for the created connector', async () => {@@ -70,4 +74,49 @@ describe('executeOAuthCreate', () => {expect(deps.deleteConnector).not.toHaveBeenCalled();});++ describe('when the popup closes without reporting a result', () => {+ beforeEach(() => {+ deps.startConnectorOAuth.mockResolvedValue('https://auth.example.com/authorize');+ deps.waitForConnectorOAuth.mockRejectedValue(new ConnectorOAuthError('dismissed'));+ });++ it('succeeds when the callback already connected the new connector', async () => {+ // Regression: a COOP provider severed window.opener, so a successful+ // authorization was reported to the user as "canceled".+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.isConnectorConnected.mockResolvedValue(true);++ await expect(executeOAuthCreate({}, popup, deps)).resolves.toBeUndefined();++ expect(deps.isConnectorConnected).toHaveBeenCalledWith('c1');+ });++ it('stays canceled when the new connector is still not connected', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toMatchObject({+ reason: 'dismissed',+ });+ });++ it('stays canceled when the status check itself fails', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.isConnectorConnected.mockRejectedValue(new Error('network'));++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toMatchObject({+ reason: 'dismissed',+ });+ });++ it('does not trust the status of a connector that existed before', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: false });+ deps.isConnectorConnected.mockResolvedValue(true);++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toMatchObject({+ reason: 'dismissed',+ });+ expect(deps.isConnectorConnected).not.toHaveBeenCalled();+ });+ });});diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.ts b/src/features/Connectors/CustomConnectorModal/oauthCreate.tsindex 88f69bd3ba6..e57db828325 100644--- a/src/features/Connectors/CustomConnectorModal/oauthCreate.ts+++ b/src/features/Connectors/CustomConnectorModal/oauthCreate.ts@@ -1,6 +1,10 @@+import { ConnectorOAuthError } from '@/utils/connectorOAuth';+export interface OAuthCreateDeps<TPayload> {createConnector: (payload: TPayload) => Promise<{ id: string; isNew: boolean }>;deleteConnector: (id: string) => Promise<void>;+ /** Re-read the connector from the server and report whether it is connected. */+ isConnectorConnected: (id: string) => Promise<boolean>;startConnectorOAuth: (id: string) => Promise<string>;waitForConnectorOAuth: (popup: Window | null | undefined,@@ -18,7 +22,10 @@ export interface OAuthCreateDeps<TPayload> {* back instead of leaving a disconnected, tool-less connector behind β the same* `isNew` guard as the non-OAuth path, so a pre-existing connector is never* deleted. Once the popup is navigated the row is kept: a "dismissed" result may- * still hide a successful callback whose status message was lost.+ * still hide a successful callback whose status message was lost β providers+ * whose COOP policy severs `window.opener` (e.g. Stripe) always lose it. For a+ * fresh row only the callback can mark it connected, so the server state+ * decides between success and a real cancel.*/export const executeOAuthCreate = async <TPayload>(payload: TPayload,@@ -35,5 +42,11 @@ export const executeOAuthCreate = async <TPayload>(throw error;}- await deps.waitForConnectorOAuth(popup, id, authorizationUrl);+ try {+ await deps.waitForConnectorOAuth(popup, id, authorizationUrl);+ } catch (error) {+ const dismissed = error instanceof ConnectorOAuthError && error.reason === 'dismissed';+ if (!dismissed || !isNew) throw error;+ if (!(await deps.isConnectorConnected(id).catch(() => false))) throw error;+ }};