Skip to content

🤯 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.

🐛 fix(connector): relay OAuth callback status without an opener (#19865)

AmAzing-e7801aefc932
diff --git a/apps/desktop/src/common/connectorOAuth.ts b/apps/desktop/src/common/connectorOAuth.ts
new file mode 100644
index 00000000000..d5fca6bf697
--- /dev/null
+++ b/apps/desktop/src/common/connectorOAuth.ts
@@ -0,0 +1,3 @@
+export const CONNECTOR_OAUTH_RESULT_CHANNEL = 'desktop:connector-oauth-result';
+
+export type ConnectorOAuthResult = 'success' | 'dismissed' | 'failed' | 'timeout';
diff --git a/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts
new file mode 100644
index 00000000000..a7e6adcb0e4
--- /dev/null
+++ b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts
@@ -0,0 +1,109 @@
+import path from 'node:path';
+
+import { OFFICIAL_CLOUD_URL, OFFICIAL_URL } from '@lobechat/const/url';
+import { BrowserWindow } from 'electron';
+
+import { preloadDir } from '@/const/dir';
+import { createLogger } from '@/utils/logger';
+import { CONNECTOR_OAUTH_RESULT_CHANNEL, type ConnectorOAuthResult } from '~common/connectorOAuth';
+
+import { ControllerModule, IpcMethod } from './index';
+import RemoteServerConfigCtr from './RemoteServerConfigCtr';
+
+const logger = createLogger('controllers:ConnectorOAuthCtr');
+
+export default class ConnectorOAuthCtr extends ControllerModule {
+ static override readonly groupName = 'connectorOAuth';
+
+ @IpcMethod()
+ async authorize(params: {
+ authorizationUrl: string;
+ connectorId: string;
+ }): Promise<ConnectorOAuthResult> {
+ const authorizationUrl = new URL(params.authorizationUrl);
+ const remoteUrl = await this.app.getController(RemoteServerConfigCtr).getRemoteServerUrl();
+ const remoteOrigin = new URL(remoteUrl).origin;
+ // Official API and app origins differ; self-hosted servers trust only their own origin.
+ const callbackOrigins = [OFFICIAL_CLOUD_URL, OFFICIAL_URL].includes(remoteOrigin)
+ ? [OFFICIAL_CLOUD_URL, OFFICIAL_URL]
+ : [remoteOrigin];
+ const callbackUrl = callbackOrigins
+ .map((origin) => new URL('/oauth/connector/callback', origin))
+ .find((url) => url.href === authorizationUrl.searchParams.get('redirect_uri'));
+ const state = authorizationUrl.searchParams.get('state');
+ if (!['https:', 'http:'].includes(authorizationUrl.protocol) || !callbackUrl || !state) {
+ return 'failed';
+ }
+
+ const parent = this.app.browserManager.getMainWindow().browserWindow;
+ const popup = new BrowserWindow({
+ autoHideMenuBar: true,
+ height: 720,
+ parent,
+ title: 'Connector authorization',
+ webPreferences: {
+ contextIsolation: true,
+ nodeIntegration: false,
+ partition: 'connector-oauth',
+ preload: path.join(preloadDir, 'connectorOAuth.js'),
+ sandbox: true,
+ webviewTag: false,
+ },
+ width: 600,
+ });
+
+ // Keep third-party content out of the desktop's authenticated session and
+ // deny local navigation, nested windows, and device permission requests.
+ popup.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) =>
+ callback(false),
+ );
+ popup.webContents.session.setPermissionCheckHandler(() => false);
+ popup.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ const guardNavigation = (event: Electron.Event, url: string) => {
+ if (!['https:', 'http:'].includes(new URL(url).protocol)) event.preventDefault();
+ };
+ popup.webContents.on('will-navigate', guardNavigation);
+ popup.webContents.on('will-redirect', guardNavigation);
+
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (result: ConnectorOAuthResult) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ parent.removeListener('closed', onParentClosed);
+ if (!popup.isDestroyed()) popup.destroy();
+ resolve(result);
+ };
+ const onParentClosed = () => finish('dismissed');
+ const timer = setTimeout(() => finish('timeout'), 5 * 60_000);
+ parent.once('closed', onParentClosed);
+ popup.once('closed', () => finish('dismissed'));
+ popup.webContents.on('render-process-gone', () => finish('failed'));
+ popup.webContents.on('did-fail-load', (_event, code, _description, _url, isMainFrame) => {
+ if (isMainFrame && code !== -3) finish('failed'); // ERR_ABORTED is normal on redirects.
+ });
+ popup.webContents.ipc.on(CONNECTOR_OAUTH_RESULT_CHANNEL, (event, data) => {
+ if (event.senderFrame !== popup.webContents.mainFrame) return;
+ const url = new URL(event.senderFrame.url);
+ if (
+ url.origin !== callbackUrl.origin ||
+ url.pathname !== callbackUrl.pathname ||
+ url.searchParams.get('state') !== state ||
+ data?.type !== 'lobe-connector-oauth' ||
+ (data.connectorId && data.connectorId !== params.connectorId)
+ )
+ return;
+
+ if (data.success === true && data.connectorId === params.connectorId) finish('success');
+ else if (data.success === false) finish('failed');
+ });
+ // Never log this URL: it contains the user's OAuth state and PKCE challenge.
+ popup.loadURL(authorizationUrl.href).catch((error: { code?: string }) => {
+ if (error.code === 'ERR_ABORTED') return; // The provider navigated before loading finished.
+ logger.error('Failed to load connector authorization page');
+ finish('failed');
+ });
+ });
+ }
+}
diff --git a/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts
new file mode 100644
index 00000000000..d79e7f77189
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts
@@ -0,0 +1,220 @@
+import { EventEmitter } from 'node:events';
+
+import { BrowserWindow } from 'electron';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+import { CONNECTOR_OAUTH_RESULT_CHANNEL } from '~common/connectorOAuth';
+
+import ConnectorOAuthCtr from '../ConnectorOAuthCtr';
+
+vi.mock('electron', () => ({ BrowserWindow: vi.fn(), ipcMain: { handle: vi.fn() } }));
+vi.mock('@/const/dir', () => ({ preloadDir: '/preload' }));
+vi.mock('../RemoteServerConfigCtr', () => ({ default: class {} }));
+
+const callback = 'https://server.example/oauth/connector/callback';
+const authorizationUrl = `https://provider.example/authorize?state=expected-state&redirect_uri=${encodeURIComponent(callback)}`;
+const params = { authorizationUrl, connectorId: 'connector-1' };
+
+const makePopup = () => {
+ const popup = Object.assign(new EventEmitter(), {
+ destroy: vi.fn(),
+ isDestroyed: vi.fn(() => false),
+ loadURL: vi.fn().mockResolvedValue(undefined),
+ webContents: Object.assign(new EventEmitter(), {
+ ipc: new EventEmitter(),
+ mainFrame: { url: `${callback}?state=expected-state&code=code` },
+ session: {
+ setPermissionCheckHandler: vi.fn(),
+ setPermissionRequestHandler: vi.fn(),
+ },
+ setWindowOpenHandler: vi.fn(),
+ }),
+ });
+ popup.destroy.mockImplementation(() => {
+ popup.isDestroyed.mockReturnValue(true);
+ popup.emit('closed');
+ });
+ return popup;
+};
+
+describe('ConnectorOAuthCtr', () => {
+ let popup: ReturnType<typeof makePopup>;
+ let parent: EventEmitter;
+ let controller: ConnectorOAuthCtr;
+ let remoteUrl: string;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ popup = makePopup();
+ parent = new EventEmitter();
+ remoteUrl = 'https://server.example';
+ vi.mocked(BrowserWindow).mockImplementation(function () {
+ return popup as unknown as BrowserWindow;
+ });
+ controller = new ConnectorOAuthCtr({
+ browserManager: { getMainWindow: () => ({ browserWindow: parent }) },
+ getController: () => ({ getRemoteServerUrl: async () => remoteUrl }),
+ } as unknown as App);
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ });
+
+ const success = { connectorId: 'connector-1', success: true, type: 'lobe-connector-oauth' };
+ const send = (data = success, senderFrame = popup.webContents.mainFrame) =>
+ popup.webContents.ipc.emit(CONNECTOR_OAUTH_RESULT_CHANNEL, { senderFrame }, data);
+
+ it('opens an isolated native window and completes without window.opener', async () => {
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ expect(BrowserWindow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ webPreferences: {
+ contextIsolation: true,
+ nodeIntegration: false,
+ partition: 'connector-oauth',
+ preload: '/preload/connectorOAuth.js',
+ sandbox: true,
+ webviewTag: false,
+ },
+ }),
+ );
+ expect(popup.loadURL).toHaveBeenCalledWith(authorizationUrl);
+ send();
+ await expect(result).resolves.toBe('success');
+ expect(popup.destroy).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(parent.listenerCount('closed')).toBe(0);
+ });
+
+ it.each([
+ ['https://lobehub.com', 'https://app.lobehub.com/oauth/connector/callback'],
+ ['https://app.lobehub.com/', 'https://lobehub.com/oauth/connector/callback'],
+ ])(
+ 'accepts the official callback alias for %s and binds completion to it',
+ async (server, redirectUri) => {
+ remoteUrl = server;
+ const url = new URL(authorizationUrl);
+ url.searchParams.set('redirect_uri', redirectUri);
+ const result = controller.authorize({ ...params, authorizationUrl: url.href });
+ await Promise.resolve();
+ expect(popup.loadURL).toHaveBeenCalledWith(url.href);
+
+ // Even the other trusted official origin cannot complete this attempt.
+ popup.webContents.mainFrame.url = new URL(
+ '/oauth/connector/callback?state=expected-state',
+ server,
+ ).href;
+ send();
+ expect(popup.destroy).not.toHaveBeenCalled();
+ popup.webContents.mainFrame.url = `${redirectUri}?state=expected-state`;
+ send();
+ await expect(result).resolves.toBe('success');
+ expect(vi.getTimerCount()).toBe(0);
+ },
+ );
+
+ it.each([
+ ['https://lobehub.com', 'https://other.lobehub.com/oauth/connector/callback'],
+ ['https://lobehub.com', 'https://app.lobehub.com.evil.example/oauth/connector/callback'],
+ ['https://lobehub.com', 'http://app.lobehub.com/oauth/connector/callback'],
+ ['https://lobehub.com', 'https://app.lobehub.com:8443/oauth/connector/callback'],
+ ['https://lobehub.com', 'https://app.lobehub.com/other'],
+ ['https://server.example', 'https://app.lobehub.com/oauth/connector/callback'],
+ ])('rejects an untrusted redirect from %s to %s', async (server, redirectUri) => {
+ remoteUrl = server;
+ const url = new URL(authorizationUrl);
+ url.searchParams.set('redirect_uri', redirectUri);
+ await expect(controller.authorize({ ...params, authorizationUrl: url.href })).resolves.toBe(
+ 'failed',
+ );
+ expect(BrowserWindow).not.toHaveBeenCalled();
+ });
+
+ it('keeps waiting after an aborted load caused by navigation', async () => {
+ popup.loadURL.mockRejectedValue(Object.assign(new Error('aborted'), { code: 'ERR_ABORTED' }));
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ await Promise.resolve();
+ popup.webContents.emit('did-fail-load', {}, -3, '', '', true);
+ expect(popup.destroy).not.toHaveBeenCalled();
+ send();
+ await expect(result).resolves.toBe('success');
+ });
+
+ it('rejects a different callback origin, path, state, connector or subframe', async () => {
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ for (const url of [
+ 'https://evil.example/oauth/connector/callback?state=expected-state',
+ 'https://server.example/other?state=expected-state',
+ `${callback}?state=wrong-state`,
+ ]) {
+ popup.webContents.mainFrame.url = url;
+ send();
+ }
+ popup.webContents.mainFrame.url = `${callback}?state=expected-state`;
+ send({ ...success, connectorId: 'other' });
+ send(success, { url: popup.webContents.mainFrame.url });
+ expect(popup.destroy).not.toHaveBeenCalled();
+ send();
+ await expect(result).resolves.toBe('success');
+ });
+
+ it.each([
+ 'file:///etc/passwd',
+ 'https://evil.example/authorize?state=x&redirect_uri=https://evil.example/callback',
+ ])('rejects unsafe input %s', async (url) => {
+ await expect(controller.authorize({ ...params, authorizationUrl: url })).resolves.toBe(
+ 'failed',
+ );
+ expect(BrowserWindow).not.toHaveBeenCalled();
+ });
+
+ it.each(['closed', 'denied', 'timeout', 'load-failure', 'parent-closed'])(
+ 'settles %s and cleans up',
+ async (scenario) => {
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ if (scenario === 'closed') popup.emit('closed');
+ if (scenario === 'parent-closed') parent.emit('closed');
+ if (scenario === 'denied') send({ ...success, success: false });
+ if (scenario === 'timeout') vi.advanceTimersByTime(5 * 60_000);
+ if (scenario === 'load-failure')
+ popup.webContents.emit('did-fail-load', {}, -105, '', '', true);
+ await expect(result).resolves.toBe(
+ scenario === 'closed' || scenario === 'parent-closed'
+ ? 'dismissed'
+ : scenario === 'timeout'
+ ? 'timeout'
+ : 'failed',
+ );
+ expect(vi.getTimerCount()).toBe(0);
+ expect(parent.listenerCount('closed')).toBe(0);
+ },
+ );
+
+ it('blocks nested windows and local navigation but permits provider redirects', async () => {
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ expect(popup.webContents.setWindowOpenHandler.mock.calls[0][0]()).toEqual({ action: 'deny' });
+ const appNavigation = { preventDefault: vi.fn() };
+ const fileRedirect = { preventDefault: vi.fn() };
+ const providerRedirect = { preventDefault: vi.fn() };
+ popup.webContents.emit('will-navigate', appNavigation, 'app://renderer');
+ popup.webContents.emit('will-redirect', fileRedirect, 'file:///etc/passwd');
+ popup.webContents.emit('will-redirect', providerRedirect, 'https://login.example/authorize');
+ expect(appNavigation.preventDefault).toHaveBeenCalledOnce();
+ expect(fileRedirect.preventDefault).toHaveBeenCalledOnce();
+ expect(providerRedirect.preventDefault).not.toHaveBeenCalled();
+ expect(popup.destroy).not.toHaveBeenCalled();
+ popup.emit('closed');
+ await expect(result).resolves.toBe('dismissed');
+ expect(vi.getTimerCount()).toBe(0);
+ expect(parent.listenerCount('closed')).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index 8596b857ef9..3ddeb7dca97 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -8,6 +8,7 @@ import BrowserSidebarCtr from './BrowserSidebarCtr';
import BrowserWindowsCtr from './BrowserWindowsCtr';
import CliCtr from './CliCtr';
import CompletionSoundCtr from './CompletionSoundCtr';
+import ConnectorOAuthCtr from './ConnectorOAuthCtr';
import DevtoolsCtr from './DevtoolsCtr';
import GatewayConnectionCtr from './GatewayConnectionCtr';
import GitCtr from './GitCtr';
@@ -43,6 +44,7 @@ export const controllerIpcConstructors = [
BrowserWindowsCtr,
CliCtr,
CompletionSoundCtr,
+ ConnectorOAuthCtr,
DevtoolsCtr,
GatewayConnectionCtr,
GitCtr,
diff --git a/apps/desktop/src/preload/connectorOAuth.ts b/apps/desktop/src/preload/connectorOAuth.ts
new file mode 100644
index 00000000000..a2143097933
--- /dev/null
+++ b/apps/desktop/src/preload/connectorOAuth.ts
@@ -0,0 +1,10 @@
+import { ipcRenderer } from 'electron';
+
+import { CONNECTOR_OAUTH_RESULT_CHANNEL } from '../common/connectorOAuth';
+
+// This preload exposes no desktop APIs. The main process verifies the sending
+// frame, callback URL and OAuth state before accepting a status message.
+window.addEventListener('message', (event) => {
+ if (event.source !== window || event.data?.type !== 'lobe-connector-oauth') return;
+ ipcRenderer.send(CONNECTOR_OAUTH_RESULT_CHANNEL, event.data);
+});
diff --git a/apps/desktop/vite.preload.config.ts b/apps/desktop/vite.preload.config.ts
index 33db9bf1e23..9006dfce3af 100644
--- a/apps/desktop/vite.preload.config.ts
+++ b/apps/desktop/vite.preload.config.ts
@@ -24,7 +24,11 @@ export default defineConfig(async (env) => {
copyPublicDir: false,
emptyOutDir: true,
lib: {
- entry: path.resolve(__dirname, 'src/preload/index.ts'),
+ entry: {
+ connectorOAuth: path.resolve(__dirname, 'src/preload/connectorOAuth.ts'),
+ index: path.resolve(__dirname, 'src/preload/index.ts'),
+ },
+ fileName: (_format, entryName) => `${entryName}.js`,
formats: ['cjs'],
},
minify: !isDev,
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 8ab4c65fffe..51d1ed1992c 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -341,12 +341,12 @@
"share.settings.link.title": "Share link",
"share.settings.link.viewCount": "{{views}} views",
"share.settings.link.workspaceDesc": "Anyone signed in who has the link can chat with this Agent. Runs execute in the Workspace and are charged to its budget.",
- "share.settings.notice.workspaceDesc": "Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.",
- "share.settings.notice.workspaceTitle": "Visitors run this Agent on the Workspace budget",
"share.settings.modelRestriction.description": "To choose a model from another provider, turn off sharing first.",
"share.settings.modelRestriction.title": "Sharing is on: models are limited to the LobeHub provider",
"share.settings.notice.desc": "Visitors can use the tools and data you allow below. Review permissions and the monthly spend cap before sharing.",
"share.settings.notice.title": "You pay for visitor usage.",
+ "share.settings.notice.workspaceDesc": "Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.",
+ "share.settings.notice.workspaceTitle": "Visitors run this Agent on the Workspace budget",
"share.settings.permissions.allowCreatorViewSessions": "Let me read visitor conversations",
"share.settings.permissions.allowCreatorViewSessionsHint": "Off by default: visitor conversations stay private to the visitor.",
"share.settings.permissions.allowReadMemory": "Allow reading my memory",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 02851a04e45..880023cdc92 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -703,6 +703,10 @@
"dev.meta.title.placeholder": "Search engine",
"dev.metaConfig": "Meta config",
"dev.modalDesc": "Custom Skills can be used for development or directly in conversations. See <1>docs↗</1>",
+ "dev.oauthError.blocked": "The authorization window could not open. Allow popups, or update the desktop app, then try again.",
+ "dev.oauthError.dismissed": "Authorization was canceled. Click Authorize & Connect to try again.",
+ "dev.oauthError.failed": "Authorization failed. Check your OAuth settings and try again.",
+ "dev.oauthError.timeout": "Authorization timed out. Click Authorize & Connect to try again.",
"dev.openai.importUrl": "Import from URL",
"dev.openai.schema": "Schema",
"dev.permissionDenied": "You are not allowed to modify this connector — only the creator or a workspace owner can",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 6ffb5fd8116..886b515537b 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -341,12 +341,12 @@
"share.settings.link.title": "分享链接",
"share.settings.link.viewCount": "被浏览 {{views}} 次",
"share.settings.link.workspaceDesc": "任何拿到链接并已登录的人都能和这个助手对话,运行发生在工作区内,并从工作区预算扣费。",
- "share.settings.notice.workspaceDesc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都在工作区内生成并从工作区共享预算扣费,不占用创建者或其他成员的个人额度。助手只会使用你在下面授予访客的权限。",
- "share.settings.notice.workspaceTitle": "访客将使用工作区预算运行此助手",
"share.settings.modelRestriction.description": "如需选择其他服务商提供的模型,请先关闭分享。",
"share.settings.modelRestriction.title": "分享已开启,模型服务商限定为 LobeHub",
"share.settings.notice.desc": "访客可使用你在下方授权的工具和数据。开启分享前,请确认权限与每月消耗上限。",
"share.settings.notice.title": "访客使用产生的费用由你承担。",
+ "share.settings.notice.workspaceDesc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都在工作区内生成并从工作区共享预算扣费,不占用创建者或其他成员的个人额度。助手只会使用你在下面授予访客的权限。",
+ "share.settings.notice.workspaceTitle": "访客将使用工作区预算运行此助手",
"share.settings.permissions.allowCreatorViewSessions": "允许我查看访客会话",
"share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的会话内容只有访客自己能看到。",
"share.settings.permissions.allowReadMemory": "允许读取我的记忆",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index b5be5f23fcb..ef2684e6b70 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -703,6 +703,10 @@
"dev.meta.title.placeholder": "搜索引擎",
"dev.metaConfig": "技能元信息配置",
"dev.modalDesc": "添加自定义技能后,可用于技能开发验证,也可直接在会话中使用。技能开发请参考<1>开发文档↗</>",
+ "dev.oauthError.blocked": "无法打开授权窗口。请允许弹出窗口,或更新桌面客户端后重试。",
+ "dev.oauthError.dismissed": "授权已取消。点击「授权并连接」可重试。",
+ "dev.oauthError.failed": "授权失败。请检查 OAuth 配置后重试。",
+ "dev.oauthError.timeout": "授权已超时。点击「授权并连接」可重试。",
"dev.openai.importUrl": "从 URL 链接导入",
"dev.openai.schema": "Schema",
"dev.permissionDenied": "你无权修改此连接器——仅创建者或工作区 Owner 可以操作",
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 3501dc87cc2..6407d6336b5 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -713,6 +713,11 @@ export default {
'dev.metaConfig': 'Meta config',
'dev.modalDesc':
'Custom Skills can be used for development or directly in conversations. See <1>docs↗</1>',
+ 'dev.oauthError.blocked':
+ 'The authorization window could not open. Allow popups, or update the desktop app, then try again.',
+ 'dev.oauthError.dismissed': 'Authorization was canceled. Click Authorize & Connect to try again.',
+ 'dev.oauthError.failed': 'Authorization failed. Check your OAuth settings and try again.',
+ 'dev.oauthError.timeout': 'Authorization timed out. Click Authorize & Connect to try again.',
'dev.openai.importUrl': 'Import from URL',
'dev.openai.schema': 'Schema',
'dev.preview.api.noParams': 'No parameters',
diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.ts
index 4b77609f778..a0497bdf98b 100644
--- a/src/app/(backend)/oauth/connector/callback/route.test.ts
+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts
@@ -1,3 +1,5 @@
+import { runInNewContext } from 'node:vm';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { GET } from './route';
@@ -63,6 +65,38 @@ beforeEach(() => {
});
describe('connector OAuth callback', () => {
+ it.each([true, false])(
+ 'delivers status with or without an opener (opener=%s)',
+ async (hasOpener) => {
+ mockSync.mockResolvedValue({ toolCount: 5 });
+ const body = await (await GET(makeReq())).text();
+ const postMessage = vi.fn();
+ const openerPostMessage = vi.fn();
+ const script = new DOMParser().parseFromString(body, 'text/html').querySelector('script');
+ if (!script?.textContent) throw new Error('Missing callback status script');
+
+ runInNewContext(script.textContent, {
+ setTimeout: vi.fn(),
+ window: {
+ location: { origin: 'https://app.example.com' },
+ opener: hasOpener ? { postMessage: openerPostMessage } : null,
+ postMessage,
+ },
+ });
+
+ const expected = {
+ connectorId: 'c1',
+ success: true,
+ synced: true,
+ type: 'lobe-connector-oauth',
+ };
+ expect(postMessage.mock.calls).toEqual([[expected, 'https://app.example.com']]);
+ expect(openerPostMessage.mock.calls).toEqual(
+ hasOpener ? [[expected, 'https://app.example.com']] : [],
+ );
+ },
+ );
+
it('reports synced:false when auth succeeds but tool sync fails', async () => {
mockSync.mockRejectedValue(new Error('mcp down'));
diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.ts
index ddc47bfebb4..08dfa5c7bba 100644
--- a/src/app/(backend)/oauth/connector/callback/route.ts
+++ b/src/app/(backend)/oauth/connector/callback/route.ts
@@ -53,6 +53,9 @@ const renderResultPage = (result: {
<script>
(function () {
try {
+ // The isolated desktop preload relays status to the native window
+ // owner even when a provider's COOP policy severs window.opener.
+ window.postMessage(${payload}, window.location.origin);
if (window.opener) {
window.opener.postMessage(${payload}, ${jsonForScript(targetOrigin())});
}
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index 4f752716e19..eca8a54361a 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -6,6 +6,7 @@ import { ConnectorSourceType } from '@/database/schemas';
import DevModal from '@/features/PluginDevModal';
import { useToolStore } from '@/store/tool';
import { connectorSelectors } from '@/store/tool/slices/connector';
+import { waitForConnectorOAuth } from '@/utils/connectorOAuth';
import { executeLegacyMigrationSave } from './legacyPluginMigration';
@@ -27,49 +28,6 @@ interface CustomConnectorModalProps {
open: boolean;
}
-interface OAuthPopupResult {
- error?: string;
- status: 'success' | 'error' | 'dismissed';
- synced?: boolean;
-}
-
-/**
- * Wait for an already-opened popup to report the OAuth result. The popup MUST be
- * opened synchronously from the user's click (see DevModal) and then navigated
- * to the authorize URL. The callback page posts a message before attempting
- * `window.close()`, so the message signal is reliable even when the browser
- * refuses to close a cross-origin-navigated popup.
- */
-const waitForOAuthPopup = (popup: Window, connectorId: string): Promise<OAuthPopupResult> =>
- new Promise((resolve) => {
- const cleanup = () => {
- window.removeEventListener('message', onMessage);
- clearInterval(timer);
- };
-
- const onMessage = (event: MessageEvent) => {
- if (event.origin !== window.location.origin) return;
- const data = event.data;
- if (!data || data.type !== 'lobe-connector-oauth') return;
- if (data.connectorId && data.connectorId !== connectorId) return;
- cleanup();
- resolve(
- data.success
- ? { status: 'success', synced: data.synced }
- : { error: data.error, status: 'error' },
- );
- };
-
- window.addEventListener('message', onMessage);
-
- const timer = setInterval(() => {
- if (popup.closed) {
- cleanup();
- resolve({ status: 'dismissed' });
- }
- }, 800);
- });
-
/** Drop empty key/value pairs a user may have left behind in an editor. */
const cleanRecord = (record?: Record<string, string>): Record<string, string> | undefined => {
if (!record) return undefined;
@@ -309,19 +267,13 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
await updateConnector(connectorId, patch);
if (authType === 'oauth2' && isHttp) {
- const popup = ctx?.oauthPopup ?? null;
- if (!popup) throw new Error('OAuth popup was blocked');
+ const popup = ctx?.oauthPopup;
try {
const authorizationUrl = await startConnectorOAuth(connectorId);
- popup.location.href = authorizationUrl;
- const result = await waitForOAuthPopup(popup, connectorId);
+ await waitForConnectorOAuth(popup, connectorId, authorizationUrl);
+ } finally {
+ popup?.close();
await fetchConnectors();
- if (result.status !== 'success') {
- throw new Error(result.error || 'Authorization was not completed');
- }
- } catch (e) {
- if (!popup.closed) popup.close();
- throw e;
}
}
@@ -346,10 +298,9 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
};
// OAuth: create with the OIDC config, then drive the authorize popup that
- // DevModal already opened synchronously for us.
+ // DevModal opened for web, or the native desktop authorization window.
if (isHttp && authType === 'oauth2') {
- const popup = ctx?.oauthPopup ?? null;
- if (!popup) throw new Error('OAuth popup was blocked');
+ const popup = ctx?.oauthPopup;
const clientId = mcp.auth?.clientId?.trim();
try {
@@ -364,17 +315,11 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
});
const authorizationUrl = await startConnectorOAuth(newConnectorId);
- popup.location.href = authorizationUrl;
- const result = await waitForOAuthPopup(popup, newConnectorId);
- await fetchConnectors();
- if (result.status !== 'success') {
- throw new Error(result.error || 'Authorization was not completed');
- }
- } catch (e) {
+ await waitForConnectorOAuth(popup, newConnectorId, authorizationUrl);
+ } finally {
// Close the blank/in-flight popup we opened so it isn't left dangling.
- // On success the OAuth callback page closes it itself.
- if (!popup.closed) popup.close();
- throw e;
+ popup?.close();
+ await fetchConnectors();
}
return;
}
diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsx
index 95716082448..b1a2c54e328 100644
--- a/src/features/PluginDevModal/index.tsx
+++ b/src/features/PluginDevModal/index.tsx
@@ -8,6 +8,8 @@ import { useResponsive } from 'antd-style';
import { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { ConnectorOAuthError, openConnectorOAuthPopup } from '@/utils/connectorOAuth';
+
import MCPManifestForm from './MCPManifestForm';
import PluginPreview from './PluginPreview';
@@ -80,19 +82,29 @@ const DevModal = memo<DevModalProps>(
'dev.permissionDenied',
'You are not allowed to modify this connector — only the creator or a workspace owner can',
)
- : t('dev.saveError'),
+ : error instanceof ConnectorOAuthError
+ ? t(`dev.oauthError.${error.reason}`)
+ : ctx
+ ? t('dev.oauthError.failed')
+ : t('dev.saveError'),
);
} finally {
+ ctx?.oauthPopup?.close();
setSubmitting(false);
}
};
- // OAuth needs window.open within the user-gesture tick (browsers block it
+ // Web OAuth needs window.open within the user-gesture tick (browsers block it
// after an async boundary). Open a blank popup synchronously here, validate,
- // then hand it to onSave which navigates it to the authorize URL. Shared by
+ // then hand it to onSave. Desktop opens a native window via IPC instead. Shared by
// the footer save button and the in-form "Authorize" button.
const runOAuthFlow = async () => {
- const popup = window.open('about:blank', 'lobe-connector-oauth', 'width=600,height=720');
+ if (submitting) return;
+ const popup = openConnectorOAuthPopup();
+ if (popup === null) {
+ toast.error(t('dev.oauthError.blocked'));
+ return;
+ }
try {
const values = (await form.validateFields()) as LobeToolCustomPlugin;
await doSave(values, { oauthPopup: popup });
diff --git a/src/utils/connectorOAuth.test.ts b/src/utils/connectorOAuth.test.ts
new file mode 100644
index 00000000000..74e575e3dd3
--- /dev/null
+++ b/src/utils/connectorOAuth.test.ts
@@ -0,0 +1,154 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { openConnectorOAuthPopup, waitForConnectorOAuth } from './connectorOAuth';
+
+const platform = vi.hoisted(() => ({ isDesktop: false }));
+const authorize = vi.hoisted(() => vi.fn());
+vi.mock('@lobechat/const', () => platform);
+vi.mock('@/utils/electron/ipc', () => ({
+ ensureElectronIpc: () => ({ connectorOAuth: { authorize } }),
+}));
+
+const authorizationUrl =
+ 'https://provider.example/authorize?redirect_uri=https%3A%2F%2Fserver.example%2Foauth%2Fconnector%2Fcallback';
+
+describe('connector OAuth popup', () => {
+ let popup: Window;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ authorize.mockReset();
+ platform.isDesktop = false;
+ popup = { close: vi.fn(), closed: false, location: { href: '' } } as unknown as Window;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ const send = (source: Window, origin: string, data: Record<string, unknown>) => {
+ window.dispatchEvent(new MessageEvent('message', { data, origin, source }));
+ };
+
+ it('keeps the synchronous blank popup on web', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(popup);
+ expect(openConnectorOAuthPopup()).toBe(popup);
+ expect(open).toHaveBeenCalledWith(
+ 'about:blank',
+ 'lobe-connector-oauth',
+ 'width=600,height=720',
+ );
+ });
+
+ it('uses native authorization on desktop without opening a renderer popup', async () => {
+ platform.isDesktop = true;
+ const open = vi.spyOn(window, 'open');
+ authorize.mockResolvedValue('success');
+ const placeholder = openConnectorOAuthPopup();
+ expect(placeholder).toBeUndefined();
+ await expect(
+ waitForConnectorOAuth(placeholder, 'connector-1', authorizationUrl),
+ ).resolves.toBeUndefined();
+ expect(open).not.toHaveBeenCalled();
+ expect(authorize).toHaveBeenCalledWith({ authorizationUrl, connectorId: 'connector-1' });
+ });
+
+ it.each(['dismissed', 'failed', 'timeout'])(
+ 'reports native %s without a success result',
+ async (reason) => {
+ platform.isDesktop = true;
+ authorize.mockResolvedValue(reason);
+ await expect(
+ waitForConnectorOAuth(undefined, 'connector-1', authorizationUrl),
+ ).rejects.toMatchObject({ reason });
+ },
+ );
+
+ it('accepts the remote callback rather than the desktop opener origin and cleans up', async () => {
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl);
+ expect(popup.location.href).toBe(authorizationUrl);
+ send(popup, 'https://server.example', {
+ connectorId: 'connector-1',
+ success: true,
+ type: 'lobe-connector-oauth',
+ });
+ await expect(result).resolves.toBeUndefined();
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reports navigation failure and cleans up without accepting a later callback', async () => {
+ Object.defineProperty(popup.location, 'href', {
+ set: () => {
+ throw new Error('Navigation blocked');
+ },
+ });
+
+ await expect(
+ waitForConnectorOAuth(popup, 'connector-1', authorizationUrl),
+ ).rejects.toMatchObject({ reason: 'failed' });
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+
+ send(popup, 'https://server.example', {
+ connectorId: 'connector-1',
+ success: true,
+ type: 'lobe-connector-oauth',
+ });
+ expect(popup.close).toHaveBeenCalledOnce();
+ });
+
+ it('ignores other origins, windows, connectors and malformed success messages', async () => {
+ const settled = vi.fn();
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl).then(settled);
+ const success = { connectorId: 'connector-1', success: true, type: 'lobe-connector-oauth' };
+ send(popup, 'https://provider.example', success);
+ send(window, 'https://server.example', success);
+ send(popup, 'https://server.example', { ...success, connectorId: 'connector-2' });
+ send(popup, 'https://server.example', { ...success, connectorId: undefined });
+ send(popup, 'https://server.example', { ...success, success: 'true' });
+ await Promise.resolve();
+ expect(settled).not.toHaveBeenCalled();
+ expect(popup.close).not.toHaveBeenCalled();
+
+ send(popup, 'https://server.example', success);
+ await result;
+ expect(settled).toHaveBeenCalledOnce();
+ });
+
+ it('handles provider denial without a connector ID', async () => {
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl);
+ send(popup, 'https://server.example', {
+ error: 'access_denied',
+ success: false,
+ type: 'lobe-connector-oauth',
+ });
+ await expect(result).rejects.toMatchObject({ reason: 'failed' });
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it.each([true, false])('settles when closed (already closed=%s)', async (alreadyClosed) => {
+ Object.defineProperty(popup, 'closed', { configurable: true, value: alreadyClosed });
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl);
+ Object.defineProperty(popup, 'closed', { value: true });
+ vi.advanceTimersByTime(800);
+ await expect(result).rejects.toMatchObject({ reason: 'dismissed' });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('times out a callback that never arrives and removes the message listener', async () => {
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl);
+ vi.advanceTimersByTime(5 * 60_000);
+ await expect(result).rejects.toMatchObject({ reason: 'timeout' });
+ expect(popup.close).toHaveBeenCalledOnce();
+ send(popup, 'https://server.example', {
+ connectorId: 'connector-1',
+ success: true,
+ type: 'lobe-connector-oauth',
+ });
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/src/utils/connectorOAuth.ts b/src/utils/connectorOAuth.ts
new file mode 100644
index 00000000000..36319cc8f73
--- /dev/null
+++ b/src/utils/connectorOAuth.ts
@@ -0,0 +1,74 @@
+import { isDesktop } from '@lobechat/const';
+
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+export class ConnectorOAuthError extends Error {
+ constructor(public readonly reason: 'blocked' | 'dismissed' | 'failed' | 'timeout') {
+ super(`Connector OAuth ${reason}`);
+ }
+}
+
+/** Must be called synchronously from the click, before validation or network IO. */
+export const openConnectorOAuthPopup = () =>
+ isDesktop
+ ? undefined
+ : window.open('about:blank', 'lobe-connector-oauth', 'width=600,height=720');
+
+/** Navigate and wait for the server callback, not messages from the provider. */
+export const waitForConnectorOAuth = async (
+ popup: Window | null | undefined,
+ connectorId: string,
+ authorizationUrl: string,
+): Promise<void> => {
+ if (isDesktop) {
+ // Native ownership survives provider COOP headers that sever window.opener.
+ const result = await ensureElectronIpc().connectorOAuth.authorize({
+ authorizationUrl,
+ connectorId,
+ });
+ if (result !== 'success') throw new ConnectorOAuthError(result);
+ return;
+ }
+ if (!popup) throw new ConnectorOAuthError('blocked');
+
+ // The server supplies redirect_uri; only its callback may settle the flow.
+ const redirectUri = new URL(authorizationUrl).searchParams.get('redirect_uri');
+ const callbackOrigin = redirectUri ? new URL(redirectUri).origin : window.location.origin;
+
+ return new Promise((resolve, reject) => {
+ const finish = (error?: ConnectorOAuthError) => {
+ window.removeEventListener('message', onMessage);
+ clearInterval(timer);
+ clearTimeout(timeout);
+ if (!popup.closed) popup.close();
+ if (error) reject(error);
+ else resolve();
+ };
+
+ const onMessage = (event: MessageEvent) => {
+ if (event.origin !== callbackOrigin || event.source !== popup) return;
+ const data = event.data;
+ if (!data || data.type !== 'lobe-connector-oauth') return;
+ // Early callback failures (e.g. access_denied) have no connector ID.
+ if (data.connectorId && data.connectorId !== connectorId) return;
+ if (data.success === true && data.connectorId === connectorId) finish();
+ else if (data.success === false) finish(new ConnectorOAuthError('failed'));
+ };
+
+ window.addEventListener('message', onMessage);
+ const timer = setInterval(() => {
+ if (popup.closed) finish(new ConnectorOAuthError('dismissed'));
+ }, 800);
+ const timeout = setTimeout(() => finish(new ConnectorOAuthError('timeout')), 5 * 60_000);
+
+ if (popup.closed) {
+ finish(new ConnectorOAuthError('dismissed'));
+ return;
+ }
+ try {
+ popup.location.href = authorizationUrl;
+ } catch {
+ finish(new ConnectorOAuthError('failed'));
+ }
+ });
+};