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.

fix(connectors): persist one-time connection credentials locally

wyt90def5780c53
diff --git a/bin/composio-mcp-server.cjs b/bin/composio-mcp-server.cjs
index 1ad6425d..0e714fb8 100644
--- a/bin/composio-mcp-server.cjs
+++ b/bin/composio-mcp-server.cjs
@@ -8,6 +8,7 @@ const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontext
const API_BASE = (process.env.ORKAS_API_BASE || '').replace(/\/+$/, '');
const API_KEY = process.env.ORKAS_API_KEY || '';
const CONNECTION_ID = process.env.COMPOSIO_CONNECTION_ID || '';
+const CONNECTION_TOKEN = process.env.COMPOSIO_CONNECTION_TOKEN || '';
const CONNECTOR_ID = process.env.COMPOSIO_CONNECTOR_ID || '';
const TOOLS_REQUEST_TIMEOUT_MS = 25000;
const EXECUTE_REQUEST_TIMEOUT_MS = 100000;
@@ -56,6 +57,7 @@ function clientHeaders() {
function assertConfigured() {
if (!API_BASE) throw new Error('ORKAS_API_BASE env var not set');
if (!API_KEY) throw new Error('ORKAS_API_KEY env var not set');
+ if (!CONNECTION_TOKEN) throw new OrkasProxyResponseError('Reconnect this connector to authorize access', 403, 'connector_reconnect_required');
if (!CONNECTION_ID || !CONNECTOR_ID) throw new Error('Composio connector env vars not set');
}
@@ -83,6 +85,7 @@ async function orkasRequest(path, body, timeoutMs) {
'Content-Type': 'application/json',
...clientHeaders(),
Authorization: `Bearer ${API_KEY}`,
+ 'X-Orkas-Connection-Token': CONNECTION_TOKEN,
},
body: JSON.stringify({
connection_id: CONNECTION_ID,
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.ts
index 616bcb26..4ef4a916 100644
--- a/src/main/features/connectors/manager.ts
+++ b/src/main/features/connectors/manager.ts
@@ -165,6 +165,9 @@ function _pcDirForChild(): string {
function _composioTransport(inst: ConnectorInstance): Transport {
if (!inst.composio_grant?.connection_id) throw new Error('no composio_grant');
+ if (!inst.composio_grant.connection_token) {
+ throw Object.assign(new Error('connector_reconnect_required'), { code: 'connector_reconnect_required' });
+ }
const nodeRuntime = resolveBackgroundNodeRuntime();
return {
kind: 'stdio',
@@ -176,6 +179,7 @@ function _composioTransport(inst: ConnectorInstance): Transport {
ORKAS_API_KEY: connectorApiKeyHeaders().Authorization.slice('Bearer '.length),
ORKAS_CLIENT_HEADERS_JSON: JSON.stringify(commonHeaders()),
COMPOSIO_CONNECTION_ID: inst.composio_grant.connection_id,
+ COMPOSIO_CONNECTION_TOKEN: inst.composio_grant.connection_token,
COMPOSIO_CONNECTOR_ID: inst.id,
}, nodeRuntime),
};
@@ -204,8 +208,10 @@ function _composioInstanceDraft(entry: CatalogEntry, grant: ComposioGrant): Conn
return draft;
}
-async function _deleteComposioConnectionOnServer(id: string): Promise<void> {
+async function _deleteComposioConnectionOnServer(id: string, grant?: ComposioGrant): Promise<void> {
if (findCatalogEntry(id)?.auth_mode !== 'composio') return;
+ // Legacy/lost credentials can only be removed locally; reconnect obtains a new one.
+ if (!grant?.connection_token) return;
try {
const response = await fetchWithTimeout(`${accountApiBase()}/connectors/composio/disconnect`, {
method: 'POST',
@@ -213,6 +219,7 @@ async function _deleteComposioConnectionOnServer(id: string): Promise<void> {
'Content-Type': 'application/json',
Accept: 'application/json',
...connectorApiKeyHeaders(),
+ 'X-Orkas-Connection-Token': grant.connection_token,
}),
body: JSON.stringify({ connector_id: id }),
}, 60_000, undefined, 'Composio disconnect timed out after 60s');
@@ -233,6 +240,9 @@ function _missingRequiredScopes(entry: CatalogEntry, grant: OAuthGrant | undefin
function _storedAuthorizationProblem(inst: ConnectorInstance): { message: string; reason: string } | null {
const entry = findCatalogEntry(inst.id);
if (!entry) return null;
+ if (entry.auth_mode === 'composio' && !inst.composio_grant?.connection_token) {
+ return { message: 'connector_reconnect_required', reason: 'missing_connection_credential' };
+ }
if (inst.auth_error?.message) {
return {
message: inst.auth_error.message,
@@ -1339,7 +1349,9 @@ export async function removeInstance(
try { await conn.close(); } catch { /* swallow */ }
_conns.delete(runtimeKey);
}
- if (options.disconnectRemote !== false) await _deleteComposioConnectionOnServer(id);
+ if (options.disconnectRemote !== false) {
+ await _deleteComposioConnectionOnServer(id, registry.load(uid).connections[id]?.composio_grant);
+ }
return registry.remove(uid, id);
}
diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.ts
index 24c18ad0..bafb55b8 100644
--- a/src/main/features/connectors/oauth.ts
+++ b/src/main/features/connectors/oauth.ts
@@ -49,6 +49,7 @@ const OAUTH_RETRY_BASE_DELAY_MS = 400;
interface PendingFlow {
kind: 'connector_oauth' | 'google_picker' | 'composio';
+ callbackStarted?: boolean;
catalogId: string;
attemptId?: string;
requiredScopes: string[];
@@ -167,9 +168,10 @@ async function postConnectorBridgeJson(
url: string,
body: Record<string, unknown>,
extraHeaders: Record<string, string> = {},
+ maxAttempts = OAUTH_RETRY_MAX_ATTEMPTS,
): Promise<Response> {
- for (let attempt = 1; attempt <= OAUTH_RETRY_MAX_ATTEMPTS; attempt += 1) {
- const last = attempt === OAUTH_RETRY_MAX_ATTEMPTS;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ const last = attempt === maxAttempts;
let res: Response;
try {
res = await fetchOAuthJson(label, url, {
@@ -371,13 +373,17 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {
try {
if (pending.kind === 'composio') {
+ if (pending.callbackStarted) return;
+ pending.callbackStarted = true;
const res = await postConnectorBridgeJson(
'Composio connector exchange',
`${accountApiBase()}/connectors/composio/exchange`,
{ exchange_code: exchangeCode, device_id: tokenStore.getDeviceId() },
connectorApiKeyHeaders(),
+ 1, // A lost one-time credential response requires reconnect, never a retrieval retry.
);
const raw = await res.text();
+ if (_pending !== pending) return;
const body = _parseJsonObject(raw);
if (!res.ok || Number(body.code || 0) !== 0) {
throw _flowError(
@@ -386,13 +392,18 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {
);
}
const connectionId = String(body.connection_id || '');
+ const connectionToken = typeof body.connection_token === 'string' ? body.connection_token : '';
const toolkit = String(body.toolkit || '');
const authConfigId = String(body.auth_config_id || '');
if (!connectionId || !toolkit || !authConfigId) {
throw _flowError('invalid Composio exchange response', 'invalid_exchange_response');
}
+ if (!/^[A-Za-z0-9_-]{43}$/.test(connectionToken)) {
+ throw _flowError('connector_reconnect_required', 'connector_reconnect_required');
+ }
const grant: ComposioGrant = {
connection_id: connectionId,
+ connection_token: connectionToken,
toolkit,
auth_config_id: authConfigId,
...(body.account_label ? { account_label: String(body.account_label) } : {}),
@@ -475,6 +486,7 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {
pending.resolve(grant);
}
} catch (err) {
+ if (pending.kind === 'composio' && _pending !== pending) return;
log.warn('connector OAuth exchange failed', { error: (err as Error).message });
const code = (err as { code?: unknown }).code;
// A thrown network/timeout error carries no code of its own — still tag the stage so these do
diff --git a/src/main/features/connectors/registry.ts b/src/main/features/connectors/registry.ts
index cd93eef4..ab8a0029 100644
--- a/src/main/features/connectors/registry.ts
+++ b/src/main/features/connectors/registry.ts
@@ -36,7 +36,7 @@ import { Mutex } from 'async-mutex';
import { userConnectorsConfigFile } from '../../paths';
import { createLogger } from '../../logger';
import * as localSecrets from '../../util/local-secret-store';
-import type { ConnectorInstance, ConnectorsFile, OAuthGrant, DcrClientCredentials, Transport } from './types';
+import type { ConnectorInstance, ConnectorsFile, OAuthGrant, DcrClientCredentials, ComposioGrant, Transport } from './types';
const log = createLogger('connectors:registry');
const _writeMutex = new Mutex();
@@ -54,12 +54,12 @@ const _readCache = new Map<string, { file: string; mtimeMs: number; size: number
// re-runs `applyTemplate` from the catalog template + fresh `oauth_grant` on every connect, so
// the persisted transport is purely vestigial at runtime — sealing it has zero runtime cost.
// Only this module is aware of the disk form.
-type InstanceOnDisk = Omit<ConnectorInstance, 'oauth_grant' | 'dcr_client' | 'transport'> & {
+type InstanceOnDisk = Omit<ConnectorInstance, 'oauth_grant' | 'dcr_client' | 'composio_grant' | 'transport'> & {
secrets_enc?: string;
// Kept optional in the disk type so a hydrate failure can still surface a row (with `transport`
// unset and oauth_grant unset) — manager will mark it `status:error` and the user re-OAuths.
};
-interface SecretsBlob { oauth_grant?: OAuthGrant; dcr_client?: DcrClientCredentials; transport?: Transport }
+interface SecretsBlob { oauth_grant?: OAuthGrant; dcr_client?: DcrClientCredentials; composio_grant?: ComposioGrant; transport?: Transport }
const PRESERVED_SECRETS = Symbol('preservedConnectorSecrets');
const UNAVAILABLE_SECRETS = Symbol('unavailableConnectorSecrets');
@@ -205,6 +205,7 @@ function _hydrateSecrets(uid: string, disk: InstanceOnDisk): { instance: Connect
const blob = JSON.parse(dec.json) as SecretsBlob;
if (blob.oauth_grant) out.oauth_grant = blob.oauth_grant;
if (blob.dcr_client) out.dcr_client = blob.dcr_client;
+ if (blob.composio_grant) out.composio_grant = blob.composio_grant;
if (blob.transport) out.transport = blob.transport;
// Metadata-only writes dominate connector startup. Keep the exact sealed
// value when its plaintext is unchanged so status/tool-cache updates do
@@ -227,14 +228,15 @@ function _hydrateSecrets(uid: string, disk: InstanceOnDisk): { instance: Connect
}
function _dehydrateSecrets(uid: string, inst: ConnectorInstance): InstanceOnDisk {
- const { oauth_grant, dcr_client, transport, ...rest } = inst;
+ const { oauth_grant, dcr_client, composio_grant, transport, ...rest } = inst;
const onDisk = { ...rest } as InstanceOnDisk;
const unavailable = (inst as ConnectorInstanceWithLocalSecretState)[UNAVAILABLE_SECRETS];
if (unavailable) onDisk.status = _cloneJson(unavailable.persistedStatus);
- if (oauth_grant || dcr_client || transport) {
+ if (oauth_grant || dcr_client || composio_grant || transport) {
const blob: SecretsBlob = {};
if (oauth_grant) blob.oauth_grant = oauth_grant;
if (dcr_client) blob.dcr_client = dcr_client;
+ if (composio_grant) blob.composio_grant = composio_grant;
if (transport) blob.transport = transport;
const plaintext = JSON.stringify(blob);
const preserved = (inst as ConnectorInstanceWithLocalSecretState)[PRESERVED_SECRETS];
diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.ts
index 8ba6c7b8..94e3b27c 100644
--- a/src/main/features/connectors/types.ts
+++ b/src/main/features/connectors/types.ts
@@ -237,6 +237,8 @@ export interface OAuthGrant {
export interface ComposioGrant {
connection_id: string;
+ /** One-time-issued local credential; absent on legacy connections that must reconnect. */
+ connection_token?: string;
toolkit: string;
auth_config_id: string;
account_label?: string;
diff --git a/test/main/features/connectors/composio-stdio-adapter.test.ts b/test/main/features/connectors/composio-stdio-adapter.test.ts
index a2570ada..2dcc0637 100644
--- a/test/main/features/connectors/composio-stdio-adapter.test.ts
+++ b/test/main/features/connectors/composio-stdio-adapter.test.ts
@@ -25,6 +25,7 @@ const ORIGINAL_ENV = {
ORKAS_API_KEY: process.env.ORKAS_API_KEY,
ORKAS_CLIENT_HEADERS_JSON: process.env.ORKAS_CLIENT_HEADERS_JSON,
COMPOSIO_CONNECTION_ID: process.env.COMPOSIO_CONNECTION_ID,
+ COMPOSIO_CONNECTION_TOKEN: process.env.COMPOSIO_CONNECTION_TOKEN,
COMPOSIO_CONNECTOR_ID: process.env.COMPOSIO_CONNECTOR_ID,
};
@@ -38,6 +39,7 @@ function configureAdapterEnv(): void {
session_id: 'must-not-forward',
});
process.env.COMPOSIO_CONNECTION_ID = 'connection-1';
+ process.env.COMPOSIO_CONNECTION_TOKEN = 'a'.repeat(43);
process.env.COMPOSIO_CONNECTOR_ID = 'gmail';
}
@@ -148,7 +150,7 @@ describe('Composio stdio proxy adapter', () => {
]);
});
- it('calls the reused connector API with Bearer auth and no account-session headers', async () => {
+ it('calls the reused connector API with both credentials outside provider arguments', async () => {
configureAdapterEnv();
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
code: 0,
@@ -162,12 +164,15 @@ describe('Composio stdio proxy adapter', () => {
const init = fetchMock.mock.calls[0][1];
expect(init.headers).toMatchObject({
Authorization: 'Bearer orkas-user-key',
+ 'X-Orkas-Connection-Token': 'a'.repeat(43),
'Orkas-Channel': 'open',
'Orkas-App-Version': '2026.9.7',
});
expect(init.headers).not.toHaveProperty('session_id');
expect(init.headers).not.toHaveProperty('user_id');
expect(init.headers).not.toHaveProperty('Accept-Language');
+ expect(init.body).not.toContain('a'.repeat(43));
+ expect(init.body).not.toContain('orkas-user-key');
});
it('returns a completed Server failure as an MCP tool error with a stable safe code', async () => {
@@ -192,6 +197,17 @@ describe('Composio stdio proxy adapter', () => {
});
});
+ it('blocks a legacy connection before any network call and asks to reconnect', async () => {
+ configureAdapterEnv();
+ delete process.env.COMPOSIO_CONNECTION_TOKEN;
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const result = await loadAdapter().callComposioTool('GMAIL_FETCH_EMAILS', {});
+ expect(result).toMatchObject({ isError: true });
+ expect(JSON.stringify(result)).toContain('connector_reconnect_required');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('still throws when no Server response exists so the transport circuit can react', async () => {
configureAdapterEnv();
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('fetch failed'); }));
diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.ts
index c3416269..f2bef3e5 100644
--- a/test/main/features/connectors/manager.test.ts
+++ b/test/main/features/connectors/manager.test.ts
@@ -387,6 +387,7 @@ describe('features/connectors/manager authorization recovery', () => {
await writeComposioCatalog();
mocks.oauth.startComposioConnect.mockResolvedValue({
connection_id: 'connection-1',
+ connection_token: 'a'.repeat(43),
toolkit: 'gmail',
auth_config_id: 'ac_public_123',
account_label: '[email protected]',
@@ -405,6 +406,7 @@ describe('features/connectors/manager authorization recovery', () => {
env: {
ORKAS_API_KEY: 'orkas-connector-key',
COMPOSIO_CONNECTION_ID: 'connection-1',
+ COMPOSIO_CONNECTION_TOKEN: 'a'.repeat(43),
COMPOSIO_CONNECTOR_ID: 'composio-mail',
},
},
@@ -416,6 +418,65 @@ describe('features/connectors/manager authorization recovery', () => {
expect(mocks.oauth.startComposioConnect).toHaveBeenCalledOnce();
});
+ it('marks a legacy paid connection for reconnect without fetching a replacement credential', async () => {
+ await writeComposioCatalog();
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const now = new Date().toISOString();
+ await registry.upsert(TEST_UID, {
+ id: 'composio-mail', display_name: 'Mail',
+ transport: { kind: 'stdio', command: 'node', args: [] },
+ composio_grant: { connection_id: 'legacy', toolkit: 'gmail', auth_config_id: 'ac_public_123' },
+ enabled_subtools: null, tools_cache: [], tools_cached_at: Date.now(),
+ status: { kind: 'connected', since: Date.now() }, created_at: now, updated_at: now,
+ });
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ expect(manager.listInstances(TEST_UID)[0].status).toMatchObject({ kind: 'error', message: 'connector_reconnect_required' });
+ await manager.bootstrap(TEST_UID);
+ expect(mocks.mcp.connect).not.toHaveBeenCalled();
+ expect(mocks.oauth.startComposioConnect).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ await manager.removeInstance(TEST_UID, 'composio-mail');
+ expect(fetchMock).not.toHaveBeenCalled();
+ } finally { vi.unstubAllGlobals(); }
+ });
+
+ it('sends the connection credential on explicit remote disconnect', async () => {
+ await writeComposioCatalog();
+ mocks.oauth.startComposioConnect.mockResolvedValue({
+ connection_id: 'connection-1', connection_token: 'a'.repeat(43), toolkit: 'gmail', auth_config_id: 'ac_public_123',
+ });
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ await manager.connectViaOAuth(TEST_UID, 'composio-mail');
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ code: 0, removed: true })));
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ expect(await manager.removeInstance(TEST_UID, 'composio-mail')).toBe(true);
+ expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/composio/disconnect'), expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer orkas-connector-key', 'X-Orkas-Connection-Token': 'a'.repeat(43) }),
+ }));
+ expect(manager.listInstances(TEST_UID)).toEqual([]);
+ } finally { vi.unstubAllGlobals(); }
+ });
+
+ it('does not start a connector or recover the credential remotely when local persistence fails', async () => {
+ await writeComposioCatalog();
+ mocks.oauth.startComposioConnect.mockResolvedValue({
+ connection_id: 'connection-1', connection_token: 'a'.repeat(43), toolkit: 'gmail', auth_config_id: 'ac_public_123',
+ });
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const save = vi.spyOn(registry, 'upsert').mockRejectedValueOnce(new Error('local write failed'));
+ try {
+ await expect(manager.connectViaOAuth(TEST_UID, 'composio-mail')).rejects.toThrow('local write failed');
+ expect(mocks.mcp.connect).not.toHaveBeenCalled();
+ expect(manager.listInstances(TEST_UID)).toEqual([]);
+ expect(mocks.oauth.startComposioConnect).toHaveBeenCalledOnce();
+ } finally { save.mockRestore(); }
+ });
+
it('keeps persisted server-bridge auth error rows visible for reconnect', async () => {
const registry = await import('../../../../src/main/features/connectors/registry');
const manager = await import('../../../../src/main/features/connectors/manager');
diff --git a/test/main/features/connectors/oauth.test.ts b/test/main/features/connectors/oauth.test.ts
index c2bbe668..fe2a8f89 100644
--- a/test/main/features/connectors/oauth.test.ts
+++ b/test/main/features/connectors/oauth.test.ts
@@ -63,6 +63,7 @@ describe('features/connectors/oauth', () => {
.mockResolvedValueOnce(new Response(JSON.stringify({
code: 0,
connection_id: 'conn-1',
+ connection_token: 'a'.repeat(43),
toolkit: 'gmail',
auth_config_id: 'auth-config-public-id',
account_label: '[email protected]',
@@ -82,6 +83,7 @@ describe('features/connectors/oauth', () => {
await expect(pending).resolves.toMatchObject({
connection_id: 'conn-1',
+ connection_token: 'a'.repeat(43),
toolkit: 'gmail',
auth_config_id: 'auth-config-public-id',
account_label: '[email protected]',
@@ -89,6 +91,75 @@ describe('features/connectors/oauth', () => {
for (const [, init] of fetchMock.mock.calls) {
expect(init.headers).toMatchObject({ Authorization: 'Bearer orkas-connector-key' });
}
+ expect(JSON.stringify(logInfo.mock.calls)).not.toContain('a'.repeat(43));
+ });
+
+ it('requires reconnect when a consumed exchange has no connection credential', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/connect' })))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ code: 0, connection_id: 'legacy', 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);
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'connector_reconnect_required' });
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalled());
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=consumed-code');
+ await rejected;
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not retry a lost credential exchange response or duplicate callback', async () => {
+ let failExchange!: (error: Error) => void;
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/connect' })))
+ .mockImplementationOnce(() => new Promise((_resolve, reject) => { failExchange = reject; }));
+ 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);
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'exchange_failed' });
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalled());
+ const callback = oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=lost-response');
+ await vi.waitFor(() => expect(failExchange).toBeTypeOf('function'));
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=lost-response');
+ failExchange(new Error('response lost'));
+ await callback;
+ await rejected;
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['success', 'failure'])('ignores a cancelled exchange completing with %s while reconnecting', async (outcome) => {
+ let finishOld!: (value: Response) => void;
+ let failOld!: (error: Error) => void;
+ const startResponse = () => new Response(JSON.stringify({ code: 0, redirect_url: 'https://provider.example/connect' }));
+ const grantResponse = (token: string) => new Response(JSON.stringify({
+ code: 0, connection_id: 'conn-1', connection_token: token, toolkit: 'gmail', auth_config_id: 'ac_public',
+ }));
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(startResponse)
+ .mockImplementationOnce(() => new Promise<Response>((resolve, reject) => { finishOld = resolve; failOld = reject; }))
+ .mockImplementationOnce(startResponse)
+ .mockImplementationOnce(() => grantResponse('b'.repeat(43)));
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth');
+ const { shell } = await import('electron');
+ const entry = { id: 'gmail', auth_mode: 'composio' } as any;
+ const first = oauth.startComposioConnect(entry);
+ const cancelled = expect(first).rejects.toMatchObject({ code: 'user_cancelled' });
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalledTimes(1));
+ const oldCallback = oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=old');
+ await vi.waitFor(() => expect(finishOld).toBeTypeOf('function'));
+ expect(oauth.cancelInFlightOAuth()).toBe(true);
+ await cancelled;
+ const replacement = oauth.startComposioConnect(entry);
+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalledTimes(2));
+ if (outcome === 'success') finishOld(grantResponse('a'.repeat(43)));
+ else failOld(new Error('old response lost'));
+ await oldCallback;
+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=new');
+ await expect(replacement).resolves.toMatchObject({ connection_token: 'b'.repeat(43) });
+ expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('rejects a server-bridge connector grant when the user unchecked a required scope', async () => {
diff --git a/test/main/features/connectors/registry-secret-store.test.ts b/test/main/features/connectors/registry-secret-store.test.ts
index b0366d47..3a6623ea 100644
--- a/test/main/features/connectors/registry-secret-store.test.ts
+++ b/test/main/features/connectors/registry-secret-store.test.ts
@@ -48,6 +48,25 @@ function sampleInstance() {
}
describe('connectors registry secret storage', () => {
+ it('keeps the one-time Composio credential encrypted across restart and metadata updates', async () => {
+ let registry = await import('../../../../src/main/features/connectors/registry');
+ const paths = await import('../../../../src/main/paths');
+ const inst = { ...sampleInstance(), id: 'paid-mail', composio_grant: {
+ connection_id: 'connection-1', toolkit: 'gmail', auth_config_id: 'ac_public', connection_token: 'a'.repeat(43),
+ } };
+ await registry.upsert(TEST_UID, inst);
+ const file = paths.userConnectorsConfigFile(TEST_UID);
+ const raw = fs.readFileSync(file, 'utf8');
+ expect(raw).not.toContain(inst.composio_grant.connection_token);
+ expect(JSON.parse(raw).connections['paid-mail'].composio_grant).toBeUndefined();
+ vi.resetModules();
+ registry = await import('../../../../src/main/features/connectors/registry');
+ expect(registry.load(TEST_UID).connections['paid-mail'].composio_grant).toEqual(inst.composio_grant);
+ await registry.update(TEST_UID, 'paid-mail', (value) => ({ ...value, tools_cached_at: 42 }));
+ expect(fs.readFileSync(file, 'utf8')).not.toContain(inst.composio_grant.connection_token);
+ expect(registry.load(TEST_UID).connections['paid-mail'].composio_grant).toEqual(inst.composio_grant);
+ });
+
it('writes token-bearing fields as local-secret ciphertext', async () => {
const registry = await import('../../../../src/main/features/connectors/registry');
const paths = await import('../../../../src/main/paths');
diff --git a/test/main/ipc/connectors.test.ts b/test/main/ipc/connectors.test.ts
index 82192989..1ca86568 100644
--- a/test/main/ipc/connectors.test.ts
+++ b/test/main/ipc/connectors.test.ts
@@ -39,6 +39,7 @@ function baseInstance(transport: any): any {
access_token: 'oauth-access-secret',
refresh_token: 'oauth-refresh-secret',
},
+ composio_grant: { connection_id: 'conn-1', connection_token: 'connection-private-secret', toolkit: 'gmail', auth_config_id: 'ac_public' },
created_at: now,
updated_at: now,
};
@@ -147,6 +148,8 @@ describe('ipc/connectors renderer DTO', () => {
expect(json).not.toContain('env-secret');
expect(json).not.toContain('oauth-access-secret');
expect(json).not.toContain('oauth-refresh-secret');
+ expect(json).not.toContain('connection-private-secret');
+ expect(dto).not.toHaveProperty('composio_grant');
});
it('strips credentials, query, and fragment from streamable-http URLs', async () => {