Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Keep connector browser starts bound to their authorization flow

wytd99b5cdfcd75
diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.ts
index 0a1d1573..6de55d1c 100644
--- a/src/main/features/connectors/oauth.ts
+++ b/src/main/features/connectors/oauth.ts
@@ -52,7 +52,7 @@ const OAUTH_RETRY_BASE_DELAY_MS = 400;
interface PendingFlow {
kind: 'connector_oauth' | 'google_picker' | 'composio';
- callbackStarted?: boolean;
+ phase: 'starting' | 'authorizing' | 'exchanging';
catalogId: string;
attemptId?: string;
requiredScopes: string[];
@@ -225,29 +225,15 @@ export async function startComposioConnect(
): Promise<ComposioGrant> {
if (entry.auth_mode !== 'composio') throw new Error(`catalog entry ${entry.id} is not Composio-backed`);
_cancelPending('superseded by a new OAuth start', 'superseded');
- const headers = connectorApiKeyHeaders();
- const res = await postConnectorBridgeJson(
- 'Composio connector start',
- `${accountApiBase()}/connectors/composio/start`,
- {
- catalog_id: entry.id,
- device_id: tokenStore.getDeviceId(),
- lang: getLanguage(),
- },
- headers,
- );
- const raw = await res.text();
- const body = _parseJsonObject(raw);
- if (!res.ok || Number(body.code || 0) !== 0 || typeof body.redirect_url !== 'string') {
- throw _friendlyComposioStartError(body, `Composio start HTTP ${res.status}`);
- }
- const redirectUrl = safeExternalHttpUrl(body.redirect_url);
- if (!redirectUrl) throw _flowError('invalid Composio redirect URL', 'invalid_redirect_url');
return new Promise<ComposioGrant>((resolve, reject) => {
- const timer = setTimeout(() => _cancelPending('OAuth flow timed out', 'flow_timeout'), FLOW_TIMEOUT_MS);
+ const expire = () => {
+ if (_pending === pending) _cancelPending('OAuth flow timed out', 'flow_timeout');
+ };
+ const timer = setTimeout(expire, FLOW_TIMEOUT_MS);
timer.unref?.();
- _pending = {
+ const pending: PendingFlow = {
kind: 'composio',
+ phase: 'starting',
catalogId: entry.id,
...(opts.attemptId ? { attemptId: opts.attemptId } : {}),
requiredScopes: [],
@@ -255,8 +241,35 @@ export async function startComposioConnect(
reject,
timer,
};
- shell.openExternal(redirectUrl).catch((err) => {
- _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
+ _pending = pending;
+ void (async () => {
+ const res = await postConnectorBridgeJson(
+ 'Composio connector start',
+ `${accountApiBase()}/connectors/composio/start`,
+ { catalog_id: entry.id, device_id: tokenStore.getDeviceId(), lang: getLanguage() },
+ connectorApiKeyHeaders(),
+ );
+ if (_pending !== pending) return;
+ const body = _parseJsonObject(await res.text());
+ if (_pending !== pending) return;
+ if (!res.ok || Number(body.code || 0) !== 0 || typeof body.redirect_url !== 'string') {
+ throw _friendlyComposioStartError(body, `Composio start HTTP ${res.status}`);
+ }
+ const redirectUrl = safeExternalHttpUrl(body.redirect_url);
+ if (!redirectUrl) throw _flowError('invalid Composio redirect URL', 'invalid_redirect_url');
+ // Preserve the full consent budget after the bounded start request.
+ clearTimeout(pending.timer);
+ pending.timer = setTimeout(expire, FLOW_TIMEOUT_MS);
+ pending.timer.unref?.();
+ pending.phase = 'authorizing';
+ await shell.openExternal(redirectUrl).catch((err) => {
+ throw _flowError(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
+ });
+ })().catch((err) => {
+ if (_pending !== pending) return;
+ _pending = null;
+ clearTimeout(pending.timer);
+ pending.reject(err);
});
});
}
@@ -297,11 +310,12 @@ export async function startOAuth(
});
return new Promise<OAuthGrant>((resolve, reject) => {
const timer = setTimeout(() => {
- _cancelPending('OAuth flow timed out', 'flow_timeout');
+ if (_pending === pending) _cancelPending('OAuth flow timed out', 'flow_timeout');
}, FLOW_TIMEOUT_MS);
timer.unref?.();
- _pending = {
+ const pending: PendingFlow = {
kind: 'connector_oauth',
+ phase: 'authorizing',
catalogId: entry.id,
...(opts.attemptId ? { attemptId: opts.attemptId } : {}),
requiredScopes: Array.isArray(entry.required_oauth_scopes) ? entry.required_oauth_scopes.slice() : [],
@@ -309,8 +323,9 @@ export async function startOAuth(
reject,
timer,
};
+ _pending = pending;
shell.openExternal(startUrl.toString()).catch((err) => {
- _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
+ if (_pending === pending) _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
});
});
}
@@ -332,19 +347,21 @@ export async function startGoogleSheetsPicker(fileIds?: string[]): Promise<Googl
log.info('opening Google Sheets picker url', { file_id_count: cleanFileIds.length });
return new Promise<GooglePickerResult>((resolve, reject) => {
const timer = setTimeout(() => {
- _cancelPending('OAuth flow timed out', 'flow_timeout');
+ if (_pending === pending) _cancelPending('OAuth flow timed out', 'flow_timeout');
}, FLOW_TIMEOUT_MS);
timer.unref?.();
- _pending = {
+ const pending: PendingFlow = {
kind: 'google_picker',
+ phase: 'authorizing',
catalogId: 'gsheets',
requiredScopes: ['https://www.googleapis.com/auth/drive.file'],
resolve: resolve as PendingFlow['resolve'],
reject,
timer,
};
+ _pending = pending;
shell.openExternal(startUrl.toString()).catch((err) => {
- _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
+ if (_pending === pending) _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');
});
});
}
@@ -359,7 +376,7 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {
const pending = _pending;
// The landing page and its return link can deliver the same callback twice.
// Once exchange starts, only that exchange may settle this flow.
- if (pending.callbackStarted) return;
+ if (pending.phase !== 'authorizing') return;
let url: URL;
try { url = new URL(rawUrl); }
catch (err) {
@@ -378,7 +395,7 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {
}
const exchangeCode = url.searchParams.get('exchange_code');
if (!exchangeCode) { _cancelPending('missing exchange_code', 'missing_exchange_code'); return; }
- pending.callbackStarted = true;
+ pending.phase = 'exchanging';
if (pending.attemptId) {
broadcastOAuthConnectProgress({
attempt_id: pending.attemptId,
diff --git a/test/main/features/connectors/oauth.test.ts b/test/main/features/connectors/oauth.test.ts
index 1ed6c906..88ce17d0 100644
--- a/test/main/features/connectors/oauth.test.ts
+++ b/test/main/features/connectors/oauth.test.ts
@@ -55,6 +55,152 @@ afterEach(() => {
});
describe('features/connectors/oauth', () => {
+ it.each(['missing_key', 'interrupted_body'] as const)('releases the pending start after %s and allows a fresh flow', async (failure) => {
+ if (failure === 'missing_key') {
+ vi.doMock('../../../../src/main/features/connectors/api-key', () => ({
+ connectorApiKeyHeaders: () => { throw Object.assign(new Error('Configure an Orkas API Key.'), { code: 'orkas_api_key_required' }); },
+ }));
+ }
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 200,
+ text: async () => { throw new Error('Controlled interrupted start body'); } }));
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const catalog = await import('../../../../src/main/features/connectors/catalog');
+ const { shell } = await import('electron');
+ const error = await oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any).catch(error => error);
+ if (failure === 'missing_key') expect(error).toMatchObject({ code: 'orkas_api_key_required' });
+ else expect(error).toMatchObject({ message: 'Controlled interrupted start body' });
+ expect(fetchMock).toHaveBeenCalledTimes(failure === 'missing_key' ? 0 : 1);
+ expect(shell.openExternal).not.toHaveBeenCalled();
+ expect(oauth.cancelInFlightOAuth()).toBe(false);
+ const retry = oauth.startOAuth('u1', catalog.findCatalogEntry('bing-webmaster')!)
+ .then(value => ({ value }), error => ({ error }));
+ expect(oauth.cancelInFlightOAuth()).toBe(true);
+ await expect(retry).resolves.toMatchObject({ error: { code: 'user_cancelled' } });
+ });
+
+ it('keeps the full consent timeout after the Composio start completes and permits retry after expiry', async () => {
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const catalog = await import('../../../../src/main/features/connectors/catalog');
+ const { shell } = await import('electron');
+ let finish!: (response: Response) => void;
+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => { finish = resolve; })));
+ vi.useFakeTimers();
+ try {
+ let result: unknown;
+ void oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any)
+ .then(value => { result = { value }; }, error => { result = { error }; });
+ await vi.advanceTimersByTimeAsync(1000);
+ finish(new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/connect' })));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(shell.openExternal).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000 - 1);
+ expect(result).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(result).toMatchObject({ error: { code: 'flow_timeout' } });
+ expect(oauth.cancelInFlightOAuth()).toBe(false);
+ const retry = oauth.startOAuth('u1', catalog.findCatalogEntry('bing-webmaster')!)
+ .then(value => ({ value }), error => ({ error }));
+ expect(oauth.cancelInFlightOAuth()).toBe(true);
+ await expect(retry).resolves.toMatchObject({ error: { code: 'user_cancelled' } });
+ } finally {
+ oauth.cancelInFlightOAuth();
+ vi.useRealTimers();
+ }
+ });
+
+ it('cancels an unfinished Composio start without opening its late consent URL', async () => {
+ let finish!: (response: Response) => void;
+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => { finish = resolve; })));
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const { shell } = await import('electron');
+ const result = oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any)
+ .then(value => ({ value }), error => ({ error }));
+ const cancelled = oauth.cancelInFlightOAuth();
+ finish(new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/old' })));
+ await new Promise<void>(resolve => setImmediate(resolve));
+ const opened = vi.mocked(shell.openExternal).mock.calls.length;
+ oauth.cancelInFlightOAuth();
+ expect(await result).toMatchObject({ error: { code: 'user_cancelled' } });
+ expect(cancelled).toBe(true);
+ expect(opened).toBe(0);
+ });
+
+ it.each(['success', 'failure'] as const)('preserves the current authorization after a late Composio start %s', async (outcome) => {
+ let finish!: (response: Response) => void;
+ vi.stubGlobal('fetch', vi.fn((url: string) => String(url).endsWith('/composio/start')
+ ? new Promise<Response>(resolve => { finish = resolve; })
+ : Promise.resolve(new Response(JSON.stringify({ code: 0, access_token: 'current-access', scope: 'webmaster.read',
+ connection_id: 'old-connection', connection_token: 'a'.repeat(43), toolkit: 'gmail', auth_config_id: 'ac_public' })))));
+ const timers = vi.spyOn(globalThis, 'setTimeout');
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const catalog = await import('../../../../src/main/features/connectors/catalog');
+ const { shell } = await import('electron');
+ const outcomes: unknown[] = [];
+ try {
+ void oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any).then(
+ () => outcomes.push(['old', 'success']), error => outcomes.push(['old', error.code]));
+ void oauth.startOAuth('u1', catalog.findCatalogEntry('bing-webmaster')!).then(
+ grant => outcomes.push(['current', grant.access_token]), error => outcomes.push(['current', error.code]));
+ finish(new Response(JSON.stringify(outcome === 'success'
+ ? { code: 0, redirect_url: 'https://provider.example/old' } : { code: 1, msg: 'Controlled old start failure' }),
+ { status: outcome === 'success' ? 200 : 400 }));
+ await new Promise<void>(resolve => setImmediate(resolve));
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=current');
+ await new Promise<void>(resolve => setImmediate(resolve));
+ expect(outcomes).toEqual([['old', 'superseded'], ['current', 'current-access']]);
+ expect(shell.openExternal).toHaveBeenCalledTimes(1);
+ } finally {
+ oauth.cancelInFlightOAuth();
+ for (const result of timers.mock.results) if (result.type === 'return') clearTimeout(result.value);
+ timers.mockRestore();
+ }
+ });
+
+ it.each(['connector_oauth', 'google_picker', 'composio'] as const)(
+ 'ignores an obsolete %s browser-open failure', async (kind) => {
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => new Response(JSON.stringify(
+ String(url).endsWith('/composio/start') ? { code: 0, redirect_url: 'https://provider.example/old' }
+ : { code: 0, access_token: 'current-access', scope: 'webmaster.read' }))));
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const catalog = await import('../../../../src/main/features/connectors/catalog');
+ const { shell } = await import('electron');
+ let failOpen!: (error: Error) => void;
+ vi.mocked(shell.openExternal).mockImplementationOnce(() => new Promise((_resolve, reject) => { failOpen = reject; }));
+ const old = (kind === 'composio' ? oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any)
+ : kind === 'google_picker' ? oauth.startGoogleSheetsPicker(['sheet-1'])
+ : oauth.startOAuth('u1', catalog.findCatalogEntry('bing-webmaster')!))
+ .then(value => ({ value }), error => ({ error }));
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalledTimes(1));
+ const current = oauth.startOAuth('u1', catalog.findCatalogEntry('bing-webmaster')!)
+ .then(value => ({ value }), error => ({ error }));
+ failOpen(new Error('Controlled browser-open failure'));
+ await new Promise<void>(resolve => setImmediate(resolve));
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=current');
+ expect(await old).toMatchObject({ error: { code: 'superseded' } });
+ expect(await current).toMatchObject({ value: { access_token: 'current-access' } });
+ oauth.cancelInFlightOAuth();
+ });
+
+ it('ignores callbacks while Composio is starting and exchanges only after consent opens', async () => {
+ let finish!: (response: Response) => void;
+ const fetchMock = vi.fn((url: string) => String(url).endsWith('/composio/start')
+ ? new Promise<Response>(resolve => { finish = resolve; })
+ : Promise.resolve(new Response(JSON.stringify({ code: 0, connection_id: 'current-connection',
+ connection_token: 'a'.repeat(43), toolkit: 'gmail', auth_config_id: 'ac_public' }))));
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const { shell } = await import('electron');
+ const pending = oauth.startComposioConnect({ id: 'gmail', auth_mode: 'composio' } as any);
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=obsolete');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ finish(new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/current' })));
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalledTimes(1));
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=current');
+ await expect(pending).resolves.toMatchObject({ connection_id: 'current-connection' });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
it.each([
['connector_oauth', 'success'], ['connector_oauth', 'failure'],
['google_picker', 'success'], ['google_picker', 'failure'],