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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Repair open-source connector OAuth flow
wyt8df73abd9c1d
diff --git a/run.sh b/run.shindex 67b0ec85..23e1020a 100755--- a/run.sh+++ b/run.sh@@ -41,6 +41,9 @@ echo "[Orkas] Starting Orkas (global prod)"node "$APP_DIR/scripts/ensure-deps.cjs"node "$APP_DIR/scripts/ensure-dev-dependencies.cjs"+# macOS source runs need the same connector callback declaration that electron-builder adds to+# packaged apps. This never starts a local server; it only registers the `orkas://` OS protocol.+node "$APP_DIR/scripts/prepare-source-protocol.cjs" || truecd "$APP_DIR"pkill -9 -f "$APP_DIR/node_modules/electron/dist" >/dev/null 2>&1 || truediff --git a/scripts/prepare-source-protocol.cjs b/scripts/prepare-source-protocol.cjsnew file mode 100644index 00000000..bb4e1901--- /dev/null+++ b/scripts/prepare-source-protocol.cjs@@ -0,0 +1,68 @@+#!/usr/bin/env node+/**+ * Declare the connector callback protocol on the bundled Electron app used by macOS source runs.+ * Packaged apps receive the same declaration from package.json via electron-builder. No network+ * listener or local HTTP endpoint is created here.+ */+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++if (process.platform !== 'darwin') process.exit(0);++const root = path.resolve(__dirname, '..');+const appBundle = path.join(root, 'node_modules', 'electron', 'dist', 'Orkas.app');+const plist = path.join(appBundle, 'Contents', 'Info.plist');+const lsregister = '/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister';+const desired = {+ bundleId: 'com.orkas.desktop',+ name: 'Orkas',+ scheme: 'orkas',+};++if (!fs.existsSync(plist)) process.exit(0);++function read(key) {+ const result = spawnSync('plutil', ['-extract', key, 'raw', '-o', '-', plist], { encoding: 'utf8' });+ return result.status === 0 ? String(result.stdout || '').trim() : '';+}++function replaceString(key, value) {+ const result = spawnSync('plutil', ['-replace', key, '-string', value, plist], { encoding: 'utf8' });+ if (result.status !== 0) throw new Error(`failed to set ${key}: ${String(result.stderr || '').trim()}`);+}++const currentScheme = read('CFBundleURLTypes.0.CFBundleURLSchemes.0');+const needsPatch = read('CFBundleIdentifier') !== desired.bundleId+ || read('CFBundleName') !== desired.name+ || read('CFBundleDisplayName') !== desired.name+ || currentScheme !== desired.scheme;++try {+ if (needsPatch) {+ replaceString('CFBundleIdentifier', desired.bundleId);+ replaceString('CFBundleName', desired.name);+ replaceString('CFBundleDisplayName', desired.name);+ spawnSync('plutil', ['-remove', 'CFBundleURLTypes', plist], { stdio: 'ignore' });+ const urlTypes = JSON.stringify([{+ CFBundleURLName: 'ai.orkas.connectors',+ CFBundleURLSchemes: [desired.scheme],+ }]);+ const inserted = spawnSync('plutil', ['-insert', 'CFBundleURLTypes', '-json', urlTypes, plist], {+ encoding: 'utf8',+ });+ if (inserted.status !== 0) {+ throw new Error(`failed to declare ${desired.scheme}://: ${String(inserted.stderr || '').trim()}`);+ }+ const signed = spawnSync('codesign', ['--force', '--deep', '--sign', '-', appBundle], { encoding: 'utf8' });+ if (signed.status !== 0) {+ throw new Error(`ad-hoc signing failed: ${String(signed.stderr || '').trim()}`);+ }+ }+ if (fs.existsSync(lsregister)) spawnSync(lsregister, ['-f', appBundle], { stdio: 'ignore' });+ console.log(`[Orkas] connector callback protocol ready (${desired.scheme}://)`);+} catch (err) {+ console.warn(`[Orkas] connector callback protocol setup skipped: ${err && err.message || err}`);+}diff --git a/src/main/features/connectors/_server_bridge.ts b/src/main/features/connectors/_server_bridge.tsindex 87e7806e..946abd68 100644--- a/src/main/features/connectors/_server_bridge.ts+++ b/src/main/features/connectors/_server_bridge.ts@@ -6,11 +6,10 @@* - `tokenStore.getDeviceId()` — stable per-machine UUID* - `tokenStore.authHeaders()` — `{user_id, session_id}` for the logged-in user*- * `features/account/` is stripped from the open-source build (no account backend). Connectors still need the- * first two pieces because the Server bridges every connector OAuth flow regardless of login- * state (`/connectors/oauth/exchange` accepts a `device_id`-only request, per PC/CLAUDE.md §6.5- * "open-source connectors" section). The third piece is always empty here because there is no Orkas- * session in the open-source build, but exposing the same signature keeps the call sites identical.+ * `features/account/` is stripped from the public build (no account backend). Connectors still+ * need the first two pieces for the pinned global HTTPS callback/bridge. Server-bridge exchange+ * and refresh accept `channel=open` plus this stable device id; the third piece is always empty+ * because this build never has an Orkas account session.** Where each piece comes from:* - `accountApiBase` aliases `features/marketplace.apiBase()` (global prod only — single@@ -71,8 +70,8 @@ export const tokenStore = {},authHeaders(): Record<string, string> {- // The open-source build has no Orkas account session. The Server's `/connectors/oauth/exchange`- // endpoint accepts device_id-only requests for this build (per PC/CLAUDE.md §6.5).+ // Never synthesize account headers. Server-bridge routes derive a pseudonymous owner only+ // when the canonical client channel is `open` and the request carries this device id.return {};},};diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsindex 68aea886..ffde1ad1 100644--- a/src/main/features/connectors/manager.ts+++ b/src/main/features/connectors/manager.ts@@ -21,12 +21,7 @@ import { findCatalogEntry } from './catalog';import { applyTemplate } from './apply-template';import { assertConnectorRuntimeEnabled, isConnectorRuntimeEnabled } from './availability';import { startOAuth, refreshIfStale, startGoogleSheetsPicker } from './oauth';-import {- startMcpDcrOAuth,- refreshDcrIfStale,- refreshDcrServerManaged,- storeDcrServerManaged,-} from './oauth-dcr';+import { startMcpDcrOAuth, refreshDcrIfStale } from './oauth-dcr';import { createLogger } from '../../logger';import { deriveCustomId, validateCustomTransport, validateDisplayName, type CustomConnectorInput } from './custom-transport';import { isConnectorUsable } from './types';@@ -411,12 +406,8 @@ async function _refreshGrantIfStale(const needsGithubServerAdoption = entry.oauth?.provider_id === 'github'&& !!inst.oauth_grant.refresh_token&& !inst.oauth_grant.server_grant_id;- const needsDcrServerAdoption = entry.auth_mode === 'mcp_dcr'- && !!inst.oauth_grant.refresh_token- && !inst.oauth_grant.server_grant_id;if (!opts.force&& !needsGithubServerAdoption- && !needsDcrServerAdoption&& inst.oauth_grant.expires_at&& inst.oauth_grant.expires_at - Date.now() > REFRESH_BUFFER_MS) {return inst.oauth_grant;@@ -433,17 +424,12 @@ async function _refreshGrantIfStale(let next: OAuthGrant;try {if (entry.auth_mode === 'mcp_dcr') {- if (inst.oauth_grant.server_grant_id) {- next = await refreshDcrServerManaged(entry.id, inst.oauth_grant, opts);- } else {- if (!inst.dcr_client) throw new Error('DCR instance missing dcr_client credentials');- if (inst.oauth_grant.refresh_token) {- const force = opts.force || !inst.oauth_grant.expires_at || inst.oauth_grant.expires_at - Date.now() <= REFRESH_BUFFER_MS;- next = await storeDcrServerManaged(entry.id, inst.dcr_client, inst.oauth_grant, { force });- } else {- next = await refreshDcrIfStale(inst.dcr_client, inst.oauth_grant);- }+ if (!inst.dcr_client) {+ const err = new Error('connector_reconnect_required: DCR client credentials are not available locally; reconnect required') as Error & { code?: string };+ err.code = 'connector_reconnect_required';+ throw err;}+ next = await refreshDcrIfStale(inst.dcr_client, inst.oauth_grant, opts);} else {next = await refreshIfStale(uid, entry, inst.oauth_grant, opts);}@@ -486,15 +472,11 @@ async function _refreshGrantIfStale(if (next !== inst.oauth_grant) {try {await registry.update(uid, instId, (cur) => {- const updated = {+ return {...cur,oauth_grant: next,updated_at: _nowIso(),};- if (entry.auth_mode === 'mcp_dcr' && next.server_managed) {- delete (updated as ConnectorInstance).dcr_client;- }- return updated;});log.info('refresh grant persisted', {id: instId,@@ -650,7 +632,7 @@ async function _connectAndCacheTools(}}if (_shouldForceRefreshAfterConnectFailure(entry, inst, statusErr)) {- log.info('MCP endpoint rejected server-managed token; forcing grant refresh and retrying', { id: inst.id });+ log.info('MCP endpoint rejected OAuth token; forcing grant refresh and retrying', { id: inst.id });try {const grant = await _refreshGrantIfStale(uid, entry!, inst.id, { force: true });const retryTransport = applyTemplate(entry!, grant);@@ -669,7 +651,7 @@ async function _connectAndCacheTools(}), statusPatches);} catch (retryErr) {statusErr = retryErr;- log.warn('server-managed forced refresh retry failed', { id: inst.id, error: (retryErr as Error).message });+ log.warn('forced OAuth refresh retry failed', { id: inst.id, error: (retryErr as Error).message });}}const degraded = await _markDegradedOnTransientFailure(@@ -690,7 +672,10 @@ function _shouldForceRefreshAfterConnectFailure(err: unknown,): boolean {if (!entry) return false;- if (!inst.oauth_grant?.server_grant_id || !inst.oauth_grant.server_managed) return false;+ const canRefresh = entry.auth_mode === 'mcp_dcr'+ ? !!inst.dcr_client && !!inst.oauth_grant?.refresh_token+ : !!inst.oauth_grant?.server_grant_id && !!inst.oauth_grant.server_managed;+ if (!canRefresh) return false;const msg = (err as Error).message || '';return /\b(401|403|unauthorized|AuthenticateToken|authentication failed|invalid_token|invalid access token|missing_token)\b/i.test(msg);}@@ -860,7 +845,7 @@ export async function connectViaOAuth(uid: string, catalogId: string): Promise<Ctry {const result = await startMcpDcrOAuth(uid, entry);grant = result.grant;- dcrClient = result.grant.server_managed ? undefined : result.client;+ dcrClient = result.client;} catch (err) {if (_isMissingRequiredScopesError(err)) {await _removeInstancesForCatalog(uid, entry, 'missing_required_scopes_oauth');diff --git a/src/main/features/connectors/oauth-dcr.ts b/src/main/features/connectors/oauth-dcr.tsindex abd8d6f7..af338783 100644--- a/src/main/features/connectors/oauth-dcr.ts+++ b/src/main/features/connectors/oauth-dcr.ts@@ -13,12 +13,13 @@* Server serves `/api/connectors/oauth/dcr-callback` as a stable HTTPS redirect_uri (DCR* clients must declare one at registration), stashes the {code, state} pair under a one-time* exchange_code, and deep-links back to PC. PC then does the first token POST against the- * provider's `token_endpoint` using the DCR-issued credentials, immediately hands the rotating- * refresh grant + DCR client credentials to Server, and persists only a server grant id.+ * provider's `token_endpoint` using the DCR-issued credentials. The public build then keeps the+ * DCR client credentials and rotating refresh grant in its local encrypted connector registry.+ * Server is only the short-lived HTTPS callback intermediary; it never receives those secrets.*- * **Why not localhost listener (RFC 8252 native-app pattern)**: PC/CLAUDE.md §1 bans HTTP- * server in main process. Server-bridge callback gets us a stable, registered HTTPS URI- * (`orkas.ai/...`) at the cost of one additional KV roundtrip — fair trade.+ * The public build never starts a loopback callback listener. Its bridge base is pinned to the+ * global production HTTPS origin, and the landing page returns through the connector-only OS+ * protocol receiver.*/import * as crypto from 'node:crypto';import { URL, URLSearchParams } from 'node:url';@@ -36,7 +37,6 @@ const log = createLogger('connectors:oauth-dcr');const FLOW_TIMEOUT_MS = 10 * 60 * 1000;const DCR_HTTP_TIMEOUT_MS = 60_000;const REFRESH_BUFFER_MS = 5 * 60 * 1000;-const SERVER_REFRESH_RETRY_DELAY_MS = 500;const CLIENT_NAME = 'Orkas';interface PendingDcrFlow {@@ -75,12 +75,6 @@ interface AuthServerMetadata {token_endpoint_auth_methods_supported?: string[];}-interface ConnectorRefreshErrorBody {- msg?: string;- error_code?: string;- retryable?: boolean;-}-/** Format `fetch` errors so the underlying cause (DNS / TLS / refused / …) surfaces in logs.* Node undici flattens every transport-level failure to `TypeError: fetch failed` with the* real reason hung off `err.cause`; logging just `err.message` loses the diagnostic. */@@ -108,18 +102,6 @@ function _fetchDcr(label: string, url: string, init: RequestInit = {}): Promise<);}-function _refreshErrorFromBody(body: ConnectorRefreshErrorBody, fallback: string): Error {- const errorCode = typeof body.error_code === 'string' ? body.error_code : '';- const message = body.msg || fallback;- const err = new Error(errorCode ? `${errorCode}: ${message}` : message) as Error & {- code?: string;- retryable?: boolean;- };- if (errorCode) err.code = errorCode;- if (typeof body.retryable === 'boolean') err.retryable = body.retryable;- return err;-}-/** Fetch `<base>/.well-known/<name>`, falling back to root-level discovery if path-suffixed* fails (per MCP authorization spec — providers can serve discovery at either location). */async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promise<T> {@@ -295,13 +277,9 @@ export async function startMcpDcrOAuth(token_auth: tokenEndpointAuthMethod,});- // Register client. The redirect_uri must point at our Server's `/connectors/oauth/dcr-callback`- // endpoint, which is environment-dependent (`accountApiBase()` resolves to the dev or prod- // Server URL per `OAUTH_REDIRECT_BASE` / debug-mode rules). DCR registers whichever URL we- // declare with the provider, so dev (localhost) and prod (orkas.ai) just work side-by-side- // — each ConnectorInstance carries its own dcr_client tied to whichever env it was installed- // under. (A dev-mode install does NOT migrate to prod automatically; the user would- // reconnect.)+ // The public build has one Server environment. `accountApiBase()` is pinned to the global+ // production HTTPS base by `_server_bridge.ts`, so source and packaged runs register the same+ // stable callback URI.const redirectUri = `${accountApiBase().replace(/\/+$/, '')}/connectors/oauth/dcr-callback`;const registered = await _registerClient(meta.registration_endpoint, redirectUri, tokenEndpointAuthMethod);log.info('DCR registration done', { client_id_tail: registered.client_id.slice(-6) });@@ -444,182 +422,28 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {scopes: tokens.scope ? tokens.scope.split(/[\s,]+/).filter(Boolean) : [],token_type: tokens.token_type || 'Bearer',};- const grant = await storeDcrServerManaged(pending.catalogId, pending.client, localGrant);_pending = null;clearTimeout(pending.timer);log.info('DCR grant resolved', {catalog_id: pending.catalogId,- has_refresh: !!grant.refresh_token,+ has_refresh: !!localGrant.refresh_token,expires_in: tokens.expires_in ?? null,});- pending.resolve({ grant, client: pending.client });+ pending.resolve({ grant: localGrant, client: pending.client });} catch (err) {_cancelPending(`token exchange failed: ${_fmtFetchErr('', err).message}`);}}-function _scopeString(grant: OAuthGrant): string {- return Array.isArray(grant.scopes) ? grant.scopes.filter(Boolean).join(' ') : '';-}--function _expiresInSeconds(grant: OAuthGrant): number {- if (!grant.expires_at) return 0;- return Math.max(0, Math.round((grant.expires_at - Date.now()) / 1000));-}--function _sleep(ms: number): Promise<void> {- return new Promise((resolve) => {- const timer = setTimeout(resolve, ms);- timer.unref?.();- });-}--async function _fetchDcrServerRefresh(provider: string, body: Record<string, unknown>): Promise<Response> {- const url = `${accountApiBase()}/connectors/oauth/refresh`;- let lastErr: unknown = null;- for (let attempt = 0; attempt < 2; attempt += 1) {- try {- return await _fetchDcr('DCR server-managed refresh', url, {- method: 'POST',- headers: withCommonHeaders({- 'Content-Type': 'application/json',- Accept: 'application/json',- ...tokenStore.authHeaders(),- }),- body: JSON.stringify(body),- });- } catch (err) {- lastErr = err;- if (attempt === 0) {- log.warn('DCR server-managed refresh fetch failed; retrying once', {- provider,- error: (err as Error).message,- });- await _sleep(SERVER_REFRESH_RETRY_DELAY_MS);- }- }- }- throw lastErr;-}--function _grantFromServerPayload(- provider: string,- grant: OAuthGrant,- body: {- access_token?: string;- grant_id?: string;- server_managed?: boolean;- expires_in?: number;- token_type?: string;- scope?: string;- account_label?: string;- },-): OAuthGrant {- if (!body.access_token || !body.grant_id) {- throw new Error(`invalid ${provider} server-managed DCR response`);- }- const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;- return {- access_token: body.access_token,- refresh_token: null,- server_managed: true,- server_grant_id: body.grant_id,- expires_at,- scopes: body.scope ? body.scope.split(/[\s,]+/).filter(Boolean) : grant.scopes,- token_type: body.token_type || grant.token_type || 'Bearer',- ...(body.account_label || grant.account_label ? { account_label: body.account_label || grant.account_label } : {}),- };-}--export async function storeDcrServerManaged(- provider: string,- client: DcrClientCredentials,- grant: OAuthGrant,- opts: { force?: boolean } = {},-): Promise<OAuthGrant> {- const res = await _fetchDcr('DCR server-managed store', `${accountApiBase()}/connectors/oauth/dcr-store`, {- method: 'POST',- headers: withCommonHeaders({- 'Content-Type': 'application/json',- Accept: 'application/json',- ...tokenStore.authHeaders(),- }),- body: JSON.stringify({- provider,- access_token: grant.access_token,- refresh_token: grant.refresh_token || '',- expires_in: _expiresInSeconds(grant),- token_type: grant.token_type || 'Bearer',- scope: _scopeString(grant),- account_label: grant.account_label || '',- dcr_client: client,- force_refresh: !!opts.force,- }),- });- if (!res.ok) {- const text = await res.text();- throw new Error(`DCR store HTTP ${res.status}: ${text}`);- }- const body = await res.json() as {- code: number;- msg?: string;- error_code?: string;- retryable?: boolean;- access_token?: string;- grant_id?: string;- server_managed?: boolean;- expires_in?: number;- token_type?: string;- scope?: string;- account_label?: string;- };- if (body.code !== 0) throw _refreshErrorFromBody(body, 'DCR server-managed store failed');- return _grantFromServerPayload(provider, grant, body);-}--export async function refreshDcrServerManaged(- provider: string,- grant: OAuthGrant,- opts: { force?: boolean } = {},-): Promise<OAuthGrant> {- if (!grant.server_grant_id) throw new Error('DCR server grant missing grant_id');- const stale = !!(grant.expires_at && grant.expires_at - Date.now() <= REFRESH_BUFFER_MS);- if (!stale && !opts.force) return grant;- const res = await _fetchDcrServerRefresh(provider, {- provider,- grant_id: grant.server_grant_id,- device_id: tokenStore.getDeviceId(),- ...(opts.force ? { force_refresh: true } : {}),- });- if (!res.ok) {- const text = await res.text();- throw new Error(`DCR refresh HTTP ${res.status}: ${text}`);- }- const body = await res.json() as {- code: number;- msg?: string;- error_code?: string;- retryable?: boolean;- access_token?: string;- grant_id?: string;- server_managed?: boolean;- expires_in?: number;- token_type?: string;- scope?: string;- account_label?: string;- };- if (body.code !== 0) throw _refreshErrorFromBody(body, 'DCR server-managed refresh failed');- return _grantFromServerPayload(provider, grant, body);-}-/** Refresh a DCR-issued access_token. Called by manager before reconnect when expires_at is* near. */export async function refreshDcrIfStale(client: DcrClientCredentials,grant: OAuthGrant,+ opts: { force?: boolean } = {},): Promise<OAuthGrant> {- if (!grant.expires_at) return grant;- if (grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;+ if (!opts.force && !grant.expires_at) return grant;+ if (!opts.force && grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;if (!grant.refresh_token) {throw new Error('access_token expired and no refresh_token available; reconnect required');}diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.tsindex 2eb15eb6..c2943d8c 100644--- a/src/main/features/connectors/oauth.ts+++ b/src/main/features/connectors/oauth.ts@@ -22,9 +22,8 @@* GitHub refresh is therefore serialized by Server, while other server-bridge providers still* refresh through the generic proxy path.*- * **No localhost HTTP listener** — §1 hard rule. The earlier draft of this file bound an- * ephemeral 127.0.0.1 port; that approach was scrapped in favor of the existing `orkas://`- * deep-link infrastructure (same as account login). Don't bring the listener back.+ * The public build never creates an HTTP callback listener. Authorization returns through the+ * production HTTPS bridge and the connector-only `orkas://` receiver.*/import { shell } from 'electron';diff --git a/src/main/features/connectors/protocol.ts b/src/main/features/connectors/protocol.tsnew file mode 100644index 00000000..8c852098--- /dev/null+++ b/src/main/features/connectors/protocol.ts@@ -0,0 +1,113 @@+/**+ * Connector-only deep-link delivery for the public desktop build.+ *+ * Account login is intentionally absent. The only accepted URLs are:+ * - orkas://connectors/oauth/callback+ * - orkas://connectors/oauth/dcr-callback+ *+ * OAuth redirects always land on the public HTTPS Server first. Its landing page then opens one+ * of the URLs above so the exact app instance that started the flow can finish the exchange. This+ * module owns that final OS-protocol hop without restoring any account/session behavior.+ */+import * as path from 'node:path';+import { app, BrowserWindow } from 'electron';++import { createLogger } from '../../logger';+import { safeUrlAction } from '../../util/log-redact';+import { handleCallbackUrl, handleDcrCallbackUrl } from './index';++const log = createLogger('connectors:protocol');+const CONNECTOR_SCHEME = 'orkas';+const SERVER_CALLBACK_PATH = '/oauth/callback';+const DCR_CALLBACK_PATH = '/oauth/dcr-callback';++let _pending: string | null = null;++function _connectorCallbackKind(rawUrl: string): 'server' | 'dcr' | null {+ let parsed: URL;+ try { parsed = new URL(rawUrl); }+ catch { return null; }+ if (parsed.protocol !== `${CONNECTOR_SCHEME}:` || parsed.host.toLowerCase() !== 'connectors') return null;+ const pathname = parsed.pathname.replace(/\/+$/, '') || '/';+ if (pathname === SERVER_CALLBACK_PATH) return 'server';+ if (pathname === DCR_CALLBACK_PATH) return 'dcr';+ return null;+}++function _extractConnectorCallback(argv: readonly string[] | undefined): string | null {+ for (const value of argv || []) {+ if (typeof value === 'string' && _connectorCallbackKind(value)) return value;+ }+ return null;+}++function _focusMainWindow(): void {+ const win = BrowserWindow.getAllWindows().find((candidate) => !candidate.isDestroyed());+ if (!win) return;+ if (win.isMinimized()) win.restore();+ win.show();+ win.focus();+}++async function _dispatch(rawUrl: string): Promise<void> {+ const kind = _connectorCallbackKind(rawUrl);+ if (!kind) {+ log.warn('ignored non-connector deep link', { action: safeUrlAction(rawUrl) });+ return;+ }+ if (!app.isReady()) {+ _pending = rawUrl;+ return;+ }+ log.info('connector deep link received', { action: safeUrlAction(rawUrl), kind });+ _focusMainWindow();+ try {+ if (kind === 'dcr') await handleDcrCallbackUrl(rawUrl);+ else await handleCallbackUrl(rawUrl);+ } catch (err) {+ log.warn('connector deep link handling failed', { error: (err as Error).message, kind });+ }+}++/** Register the connector callback scheme before app readiness and the single-instance handoff. */+export function registerConnectorProtocol(): void {+ try {+ if (!app.isPackaged && process.argv.length >= 2) {+ app.setAsDefaultProtocolClient(CONNECTOR_SCHEME, process.execPath, [path.resolve(process.argv[1])]);+ } else {+ app.setAsDefaultProtocolClient(CONNECTOR_SCHEME);+ }+ } catch (err) {+ log.warn('connector protocol registration failed', { error: (err as Error).message });+ }++ let isDefaultHandler = false;+ try { isDefaultHandler = app.isDefaultProtocolClient(CONNECTOR_SCHEME); }+ catch { /* diagnostics only */ }+ log.info('connector protocol registration', { scheme: CONNECTOR_SCHEME, isDefaultHandler });++ app.on('open-url', (event, rawUrl) => {+ if (!_connectorCallbackKind(rawUrl)) return;+ event.preventDefault();+ void _dispatch(rawUrl);+ });++ app.on('second-instance', (_event, argv) => {+ const rawUrl = _extractConnectorCallback(argv);+ if (rawUrl) void _dispatch(rawUrl);+ else _focusMainWindow();+ });++ const cold = _extractConnectorCallback(process.argv);+ if (cold) _pending = cold;+}++/** Flush a callback delivered while Electron was still starting. */+export async function consumeColdLaunchConnectorCallback(): Promise<void> {+ if (!_pending) return;+ const rawUrl = _pending;+ _pending = null;+ await _dispatch(rawUrl);+}++export const _test = { connectorCallbackKind: _connectorCallbackKind, extractConnectorCallback: _extractConnectorCallback };diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.tsindex 77519327..f09dfc60 100644--- a/src/main/features/connectors/types.ts+++ b/src/main/features/connectors/types.ts@@ -118,9 +118,9 @@ export interface ConnectorInstance {* The manager rewrites the transport env at spawn time using `oauth_grant.access_token`;* refresh logic in `oauth.ts::refreshIfStale` runs before connect / after a 401. */oauth_grant?: OAuthGrant;- /** DCR-issued client identity for legacy local MCP-spec auth (`auth_mode === 'mcp_dcr'`).- * New rotating DCR grants are server-managed; this field remains only so older local grants- * can be adopted on the next refresh. */+ /** DCR-issued client identity for MCP-spec auth (`auth_mode === 'mcp_dcr'`). The public build+ * stores this with the grant inside the encrypted local registry and never uploads it to the+ * Orkas account service. */dcr_client?: DcrClientCredentials;created_at: string;updated_at: string;@@ -182,9 +182,8 @@ export type TransportTemplate =// self-registers via Dynamic Client Registration (RFC 7591) at runtime, runs the OAuth// handshake from PC, uses the `/api/connectors/oauth/dcr-callback` Server endpoint **only**// as an HTTPS callback intermediate (Server stashes code+state in a 5-min KV, deep-links-// PC). After the first exchange, rotating DCR refresh grants are moved to Server and PC keeps-// only a server grant handle. Used for Notion, Atlassian, Cloudflare suite, … — the modern-// path.+// PC). The DCR client and rotating refresh grant remain encrypted on this device; Server is+// never a credential store for this mode. Used for Notion, Atlassian, Cloudflare suite, … .export interface OAuthConfig {/** Server-bridge only: matches the Server's `biz/connectors/oauth/<provider>.py` module name@@ -192,10 +191,9 @@ export interface OAuthConfig {provider_id: string;}-/** Dynamic Client Registration result (RFC 7591) for MCP-spec OAuth providers. Legacy local- * instances may still store this on the ConnectorInstance until the grant is adopted by Server.- * All endpoints captured at first connect — re-discovery on every refresh would add latency- * and assumes provider doesn't rotate URLs (which they shouldn't). */+/** Dynamic Client Registration result (RFC 7591) for MCP-spec OAuth providers. Stored locally+ * with the connector's encrypted secrets. All endpoints are captured at first connect —+ * re-discovery on every refresh would add latency and assumes stable provider endpoints. */export interface DcrClientCredentials {client_id: string;/** Most providers issue one; some omit (public clients). */diff --git a/src/main/index.ts b/src/main/index.tsindex 6d357228..2b382fdd 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -176,6 +176,10 @@ import * as chatArtifacts from './features/chat_artifacts';import * as savedApps from './features/saved_apps';import * as clientConfigFeature from './features/client_config';import * as connectorsFeature from './features/connectors';+import {+ consumeColdLaunchConnectorCallback,+ registerConnectorProtocol,+} from './features/connectors/protocol';import * as windowState from './features/window_state';// Server-backed account, multi-device sync, remote-control relay, and// auto-update features are stripped in the open-source build. Connectors remain available@@ -999,6 +1003,9 @@ const gotLock = IS_PACKAGED_LAUNCH_SMOKE || app.requestSingleInstanceLock();if (!gotLock) {app.quit();} else {+ // Account login is stripped, but connector OAuth still returns through the OS protocol. Keep+ // this connector-only receiver outside the removed account protocol module.+ registerConnectorProtocol();app.whenReady().then(async () => {await runBootSelfCheck();// Source-run macOS uses Electron.app's own Info.plist, so set the dock@@ -1055,6 +1062,7 @@ if (!gotLock) {}, CONNECTORS_BOOTSTRAP_DELAY_MS);connectorsTimer.unref?.();createWindow();+ await consumeColdLaunchConnectorCallback();// Boot tasks declared via util/boot_init.ts. Two phases × two modes://diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.tsindex 290f261b..c4561755 100644--- a/src/main/ipc/connectors.ts+++ b/src/main/ipc/connectors.ts@@ -10,9 +10,10 @@* connectors.refresh → { tools, instance }* connectors.set_subtools → { instance }*- * Catalog installs are OAuth-only — no API-key fallback, no BYO client credentials; Server- * holds every provider's `client_id` / `client_secret`. Custom MCP servers are the separate,- * explicitly user-authored path: `connectors.add_custom` is the single validated route+ * Catalog installs are OAuth-only — no API-key fallback. Server-bridge providers use an+ * Orkas-registered OAuth app; MCP DCR providers issue a per-device client whose credentials stay+ * in the encrypted local registry. Custom MCP servers are the separate, explicitly user-authored+ * path: `connectors.add_custom` is the single validated route* (features/connectors/custom-transport.ts), the renderer form is the consent surface, and the* stored transport lives inside `secrets_enc`. See docs/plans/open-ecosystem-architecture.md §C.*/diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 0bd4e1fe..82403f07 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -1531,6 +1531,7 @@<script src="./modules/lazy-features.js"></script><script src="./modules/i18n.js"></script><script src="./modules/chat-use.js"></script>+ <script src="./modules/user-error.js"></script><script src="./modules/model-guard.js"></script><script src="./modules/delete-file-confirm.js"></script><script src="./modules/boot.js"></script>@@ -1558,6 +1559,7 @@<script src="./modules/connectors.js"></script><script src="./modules/bridge.js"></script><script src="./modules/bash_permission.js"></script>+ <script src="./modules/interactive-cli.js"></script><script src="./modules/search.js"></script><script src="./modules/user-workspace.js"></script><script src="./modules/local-agents.js"></script>diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex 4faa6db1..6642b347 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -493,7 +493,7 @@ function _renderCatalogCard(entry, instance) {let action = '';const isConnecting = _connectorsState.connecting && _connectorsState.connecting.has(e.id);if (isConnecting) {- action = `<button class="btn btn-sm btn-primary is-loading" data-act="connect"><span class="btn-spinner"></span>${escapeHtml(t('connectors.action.connecting'))}</button>`;+ action = `<button class="btn btn-sm btn-primary is-loading" data-act="connect">${escapeHtml(t('connectors.action.connecting'))}</button>`;} else if (isOAuthPending) {action = `<button class="btn btn-sm" disabled>${escapeHtml(t('connectors.action.unavailable'))}</button>`;} else if (isVisibleDisabled) {diff --git a/src/renderer/style.css b/src/renderer/style.cssindex f555dd59..548aec1a 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -14326,21 +14326,6 @@ body.model-not-configured .main-content { flex-direction: column; }.connector-card.is-disabled { opacity: 0.55; }.connector-card.is-disabled .connector-card-icon { filter: saturate(0.4); }-/* Inline spinner inside the "连接" button — shown post-deep-link return while the IPC is- running through `/oauth/exchange` + MCP `initialize` + `list_tools` (3 network roundtrips,- ~hundreds of ms to a few seconds). Button stays clickable; spinner just signals progress. */-.btn-spinner {- display: inline-block;- width: 10px;- height: 10px;- margin-right: 6px;- border-radius: 50%;- border: 2px solid rgba(255, 255, 255, 0.5);- border-top-color: rgba(255, 255, 255, 0.95);- vertical-align: -1px;- animation: marketplace-upload-spin 0.8s linear infinite;-}-.connector-card-foot {margin-top: auto;display: flex;diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.tsindex 99ea49da..1a51c0a9 100644--- a/test/main/features/connectors/manager.test.ts+++ b/test/main/features/connectors/manager.test.ts@@ -36,8 +36,6 @@ const mocks = vi.hoisted(() => ({dcr: {startMcpDcrOAuth: undefined as any,refreshDcrIfStale: undefined as any,- refreshDcrServerManaged: undefined as any,- storeDcrServerManaged: undefined as any,},}));@@ -65,8 +63,6 @@ vi.mock('../../../../src/main/features/connectors/oauth', () => ({vi.mock('../../../../src/main/features/connectors/oauth-dcr', () => ({startMcpDcrOAuth: (...args: any[]) => mocks.dcr.startMcpDcrOAuth(...args),refreshDcrIfStale: (...args: any[]) => mocks.dcr.refreshDcrIfStale(...args),- refreshDcrServerManaged: (...args: any[]) => mocks.dcr.refreshDcrServerManaged(...args),- storeDcrServerManaged: (...args: any[]) => mocks.dcr.storeDcrServerManaged(...args),}));/** Restore default (passthrough) behavior for every mock slot. Fresh spies each@@ -81,8 +77,6 @@ function resetMockBehaviors() {mocks.oauth.refreshIfStale = vi.fn(async (_uid: string, _entry: unknown, grant: unknown) => grant);mocks.dcr.startMcpDcrOAuth = vi.fn();mocks.dcr.refreshDcrIfStale = vi.fn(async (_client: unknown, grant: unknown) => grant);- mocks.dcr.refreshDcrServerManaged = vi.fn(async (_provider: unknown, grant: unknown) => grant);- mocks.dcr.storeDcrServerManaged = vi.fn(async (_provider: unknown, _client: unknown, grant: unknown) => grant);}async function writeGoogleConnectorsConfig(value: unknown): Promise<void> {@@ -255,8 +249,14 @@ function sentryInstance() {expires_at: null,scopes: [],token_type: 'Bearer',- server_grant_id: 'grant-1',- server_managed: true,+ },+ dcr_client: {+ client_id: 'sentry-client-id',+ client_secret: 'sentry-client-secret',+ authorization_endpoint: 'https://mcp.sentry.dev/oauth/authorize',+ token_endpoint: 'https://mcp.sentry.dev/oauth/token',+ registration_endpoint: 'https://mcp.sentry.dev/oauth/register',+ resource: 'https://mcp.sentry.dev/mcp',},created_at: now,updated_at: now,@@ -685,8 +685,8 @@ describe('features/connectors/manager authorization recovery', () => {expect(registry.load(TEST_UID).connections.github.oauth_grant).toBeTruthy();});- it('degrades established DCR connectors when server-managed refresh returns generic refresh_failed', async () => {- mocks.dcr.refreshDcrServerManaged = vi.fn(async () => {+ it('degrades established DCR connectors when local provider refresh returns a transient failure', async () => {+ mocks.dcr.refreshDcrIfStale = vi.fn(async () => {const err = new Error('Failed to refresh authorization') as Error & { code?: string; retryable?: boolean };err.code = 'connector_refresh_failed';err.retryable = true;@@ -697,10 +697,6 @@ describe('features/connectors/manager authorization recovery', () => {const manager = await import('../../../../src/main/features/connectors/manager');const inst = notionInstance();- inst.oauth_grant.refresh_token = null;- (inst.oauth_grant as any).server_managed = true;- (inst.oauth_grant as any).server_grant_id = 'grant-1';- delete (inst as any).dcr_client;await registry.upsert(TEST_UID, inst);await manager.refreshTools(TEST_UID, 'notion');@@ -710,7 +706,7 @@ describe('features/connectors/manager authorization recovery', () => {});it('keeps structured DCR reconnect-required rows visible for reconnect', async () => {- mocks.dcr.refreshDcrServerManaged = vi.fn(async () => {+ mocks.dcr.refreshDcrIfStale = vi.fn(async () => {const err = new Error('Authorization expired. Please reconnect') as Error & { code?: string; retryable?: boolean };err.code = 'connector_reconnect_required';err.retryable = false;@@ -721,10 +717,6 @@ describe('features/connectors/manager authorization recovery', () => {const manager = await import('../../../../src/main/features/connectors/manager');const inst = notionInstance();- inst.oauth_grant.refresh_token = null;- (inst.oauth_grant as any).server_managed = true;- (inst.oauth_grant as any).server_grant_id = 'grant-1';- delete (inst as any).dcr_client;await registry.upsert(TEST_UID, inst);await manager.refreshTools(TEST_UID, 'notion');@@ -757,7 +749,7 @@ describe('features/connectors/manager authorization recovery', () => {await manager.bootstrap(TEST_UID);- expect(mocks.dcr.refreshDcrServerManaged).not.toHaveBeenCalled();+ expect(mocks.dcr.refreshDcrIfStale).not.toHaveBeenCalled();expect(registry.load(TEST_UID).connections.notion.auth_error).toMatchObject({code: 'connector_reconnect_required',message: expect.stringContaining('授权已失效'),@@ -783,7 +775,7 @@ describe('features/connectors/manager authorization recovery', () => {});it('keeps DCR refresh invalid_grant rows visible for reconnect', async () => {- mocks.dcr.refreshDcrServerManaged = vi.fn(async () => {+ mocks.dcr.refreshDcrIfStale = vi.fn(async () => {throw new Error('DCR refresh HTTP 400: {"error":"invalid_grant","error_description":"Grant not found"}');});@@ -791,10 +783,6 @@ describe('features/connectors/manager authorization recovery', () => {const manager = await import('../../../../src/main/features/connectors/manager');const inst = notionInstance();- inst.oauth_grant.refresh_token = null;- (inst.oauth_grant as any).server_managed = true;- (inst.oauth_grant as any).server_grant_id = 'grant-1';- delete (inst as any).dcr_client;await registry.upsert(TEST_UID, inst);await manager.refreshTools(TEST_UID, 'notion');@@ -809,18 +797,16 @@ describe('features/connectors/manager authorization recovery', () => {message: expect.stringContaining('invalid_grant'),});- mocks.dcr.refreshDcrServerManaged.mockClear();+ mocks.dcr.refreshDcrIfStale.mockClear();await manager.bootstrap(TEST_UID);- expect(mocks.dcr.refreshDcrServerManaged).not.toHaveBeenCalled();+ expect(mocks.dcr.refreshDcrIfStale).not.toHaveBeenCalled();});- it('adopts legacy DCR refresh tokens into server-managed grants', async () => {- mocks.dcr.storeDcrServerManaged = vi.fn(async (_provider, _client, grant) => ({+ it('persists rotated local DCR grants without dropping the local client credentials', async () => {+ mocks.dcr.refreshDcrIfStale = vi.fn(async (_client, grant) => ({...(grant as object),- access_token: 'server-access-token',- refresh_token: null,- server_managed: true,- server_grant_id: 'grant-1',+ access_token: 'refreshed-access-token',+ refresh_token: 'rotated-refresh-token',expires_at: Date.now() + 60 * 60 * 1000,}));@@ -832,19 +818,17 @@ describe('features/connectors/manager authorization recovery', () => {const stored = registry.load(TEST_UID).connections.notion;const grant = stored.oauth_grant;- expect(mocks.dcr.storeDcrServerManaged).toHaveBeenCalledWith(- 'notion',+ expect(mocks.dcr.refreshDcrIfStale).toHaveBeenCalledWith(expect.objectContaining({ client_id: 'client-id' }),expect.objectContaining({ refresh_token: 'refresh-token' }),- { force: true },+ {},);- expect(grant?.refresh_token).toBeNull();- expect(grant?.server_managed).toBe(true);- expect(grant?.server_grant_id).toBe('grant-1');- expect(stored.dcr_client).toBeUndefined();+ expect(grant?.access_token).toBe('refreshed-access-token');+ expect(grant?.refresh_token).toBe('rotated-refresh-token');+ expect(stored.dcr_client).toMatchObject({ client_id: 'client-id' });});- it('force refreshes server-managed Notion grants when the MCP endpoint rejects the access token', async () => {+ it('force refreshes local Notion grants when the MCP endpoint rejects the access token', async () => {// Condition-based connect (reject the STALE token, accept the force-refreshed// one) so the assertion holds regardless of how many times / in what order// connect is invoked.@@ -855,18 +839,16 @@ describe('features/connectors/manager authorization recovery', () => {}});const closeMock = vi.fn(async () => {});- const refreshDcrServerManaged = vi.fn(async (_provider, grant) => ({+ const refreshDcrIfStale = vi.fn(async (_client, grant) => ({...(grant as object),access_token: 'refreshed-notion-access',- refresh_token: null,- server_managed: true,- server_grant_id: 'grant-1',+ refresh_token: 'rotated-notion-refresh',expires_at: Date.now() + 60 * 60 * 1000,}));mocks.mcp.connect = connectMock;mocks.mcp.listTools = vi.fn(async () => [{ name: 'notion_search', description: '', input_schema: {} }]);mocks.mcp.close = closeMock;- mocks.dcr.refreshDcrServerManaged = refreshDcrServerManaged;+ mocks.dcr.refreshDcrIfStale = refreshDcrIfStale;const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');@@ -875,12 +857,9 @@ describe('features/connectors/manager authorization recovery', () => {inst.oauth_grant = {...inst.oauth_grant,access_token: 'stale-notion-access',- refresh_token: null,+ refresh_token: 'stale-notion-refresh',expires_at: Date.now() + 60 * 60 * 1000,- server_managed: true,- server_grant_id: 'grant-1',} as any;- delete (inst as any).dcr_client;await registry.upsert(TEST_UID, inst);const tools = await manager.refreshTools(TEST_UID, 'notion');@@ -888,9 +867,9 @@ describe('features/connectors/manager authorization recovery', () => {expect(tools).toEqual([{ name: 'notion_search', description: '', input_schema: {} }]);expect(connectMock).toHaveBeenCalled();expect(closeMock).toHaveBeenCalled();- expect(refreshDcrServerManaged).toHaveBeenCalledWith(- 'notion',- expect.objectContaining({ server_grant_id: 'grant-1', access_token: 'stale-notion-access' }),+ expect(refreshDcrIfStale).toHaveBeenCalledWith(+ expect.objectContaining({ client_id: 'client-id' }),+ expect.objectContaining({ access_token: 'stale-notion-access', refresh_token: 'stale-notion-refresh' }),{ force: true },);const stored = registry.load(TEST_UID).connections.notion;@@ -910,24 +889,14 @@ describe('features/connectors/manager authorization recovery', () => {if (!failedOnce) { failedOnce = true; throw new Error('fetch failed'); }});const closeMock = vi.fn(async () => {});- const refreshDcrServerManaged = vi.fn(async (_provider, grant) => grant);mocks.mcp.connect = connectMock;mocks.mcp.listTools = vi.fn(async () => [{ name: 'notion_search', description: '', input_schema: {} }]);mocks.mcp.close = closeMock;- mocks.dcr.refreshDcrServerManaged = refreshDcrServerManaged;const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');const inst = notionInstance();- inst.oauth_grant = {- ...inst.oauth_grant,- access_token: 'notion-access',- refresh_token: null,- expires_at: Date.now() + 60 * 60 * 1000,- server_managed: true,- server_grant_id: 'grant-1',- } as any;- delete (inst as any).dcr_client;+ inst.oauth_grant.expires_at = Date.now() + 60 * 60 * 1000;await registry.upsert(TEST_UID, inst);const tools = await manager.refreshTools(TEST_UID, 'notion');@@ -938,7 +907,7 @@ describe('features/connectors/manager authorization recovery', () => {// invariant (exact connect counts are brittle implementation detail).expect(connectMock).toHaveBeenCalled();expect(closeMock).toHaveBeenCalled();- expect(refreshDcrServerManaged).not.toHaveBeenCalled();+ expect(mocks.dcr.refreshDcrIfStale).not.toHaveBeenCalled();expect(registry.load(TEST_UID).connections.notion.status).toMatchObject({ kind: 'connected' });});@@ -946,29 +915,15 @@ describe('features/connectors/manager authorization recovery', () => {// The scenario is "transient failures CONTINUE" — every connect fails.const connectMock = vi.fn(async () => { throw new Error('fetch failed'); });const closeMock = vi.fn(async () => {});- const refreshDcrServerManaged = vi.fn(async (_provider, grant) => ({- ...(grant as object),- access_token: 'refreshed-notion-access',- expires_at: Date.now() + 60 * 60 * 1000,- }));mocks.mcp.connect = connectMock;mocks.mcp.listTools = vi.fn(async () => [{ name: 'notion_search', description: '', input_schema: {} }]);mocks.mcp.close = closeMock;- mocks.dcr.refreshDcrServerManaged = refreshDcrServerManaged;const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');const inst = notionInstance();inst.tools_cache = [{ name: 'notion_search', description: '', input_schema: {} }];- inst.oauth_grant = {- ...inst.oauth_grant,- access_token: 'notion-access',- refresh_token: null,- expires_at: Date.now() + 60 * 60 * 1000,- server_managed: true,- server_grant_id: 'grant-1',- } as any;- delete (inst as any).dcr_client;+ inst.oauth_grant.expires_at = Date.now() + 60 * 60 * 1000;await registry.upsert(TEST_UID, inst);const tools = await manager.refreshTools(TEST_UID, 'notion');@@ -976,9 +931,9 @@ describe('features/connectors/manager authorization recovery', () => {expect(tools).toEqual([{ name: 'notion_search', description: '', input_schema: {} }]);// Despite every connect failing, this is still a network problem, not an// auth rejection. Keep the established state and do not force-refresh the- // server-managed grant just because the MCP endpoint was unreachable.+ // local grant just because the MCP endpoint was unreachable.expect(connectMock).toHaveBeenCalled();- expect(refreshDcrServerManaged).not.toHaveBeenCalled();+ expect(mocks.dcr.refreshDcrIfStale).not.toHaveBeenCalled();// Established state kept (cached tools still served above) — but recorded as unverified, with// the real reason, rather than asserting a connection that never succeeded.const notionRow = registry.load(TEST_UID).connections.notion;diff --git a/test/main/features/connectors/oauth-dcr.test.ts b/test/main/features/connectors/oauth-dcr.test.tsindex 79b65c1a..486390de 100644--- a/test/main/features/connectors/oauth-dcr.test.ts+++ b/test/main/features/connectors/oauth-dcr.test.ts@@ -277,21 +277,6 @@ describe('features/connectors/oauth-dcr', () => {scope: 'data.records:read',});}- if (rawUrl === 'https://account.example/api/connectors/oauth/dcr-store') {- const body = JSON.parse(String(init?.body || '{}'));- expect(body.provider).toBe('airtable');- expect(body.dcr_client.token_endpoint_auth_method).toBe('client_secret_basic');- return jsonResponse({- code: 0,- access_token: 'airtable-access-server',- refresh_token: null,- grant_id: 'airtable-grant-1',- server_managed: true,- expires_in: 3600,- token_type: 'Bearer',- scope: 'data.records:read',- });- }throw new Error(`unexpected fetch ${url}`);});vi.stubGlobal('fetch', fetchMock);@@ -305,7 +290,17 @@ describe('features/connectors/oauth-dcr', () => {await handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?exchange_code=exchange-1');const result = await pending;- expect(result.grant.server_grant_id).toBe('airtable-grant-1');+ expect(result.grant).toMatchObject({+ access_token: 'airtable-access-local',+ refresh_token: 'airtable-refresh-local',+ scopes: ['data.records:read'],+ });+ expect(result.client).toMatchObject({+ client_id: 'airtable-client-1',+ client_secret: 'airtable-secret-1',+ token_endpoint_auth_method: 'client_secret_basic',+ });+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes('/dcr-store'))).toBe(false);});it('rejects a DCR callback with mismatched state before calling the provider token endpoint', async () => {@@ -349,7 +344,7 @@ describe('features/connectors/oauth-dcr', () => {expect(fetchMock.mock.calls.some(([url]) => String(url) === 'https://auth.notion.example/token')).toBe(false);});- it('stores a completed DCR grant on Server and returns only a server grant handle', async () => {+ it('keeps a completed DCR grant and client credentials local', async () => {let openedState = '';const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (String(url).endsWith('/mcp/.well-known/oauth-protected-resource')) {@@ -383,24 +378,6 @@ describe('features/connectors/oauth-dcr', () => {scope: 'read write',});}- if (String(url) === 'https://account.example/api/connectors/oauth/dcr-store') {- const body = JSON.parse(String(init?.body || '{}'));- expect(body.provider).toBe('notion');- expect(body.refresh_token).toBe('refresh-local');- expect(body.dcr_client.client_id).toBe('client-1');- expect(body.dcr_client.client_secret).toBe('secret-1');- expect((init?.headers as Record<string, string>).user_id).toBe('uid-1');- return jsonResponse({- code: 0,- access_token: 'access-server',- refresh_token: null,- grant_id: 'grant-1',- server_managed: true,- expires_in: 3600,- token_type: 'Bearer',- scope: 'read write',- });- }throw new Error(`unexpected fetch ${url}`);});vi.stubGlobal('fetch', fetchMock);@@ -416,12 +393,12 @@ describe('features/connectors/oauth-dcr', () => {const result = await pending;expect(result.grant).toMatchObject({- access_token: 'access-server',- refresh_token: null,- server_managed: true,- server_grant_id: 'grant-1',+ access_token: 'access-local',+ refresh_token: 'refresh-local',scopes: ['read', 'write'],});+ expect(result.client).toMatchObject({ client_id: 'client-1', client_secret: 'secret-1' });+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes('/dcr-store'))).toBe(false);});it('uses the first resource when protected-resource metadata returns a resource array', async () => {@@ -515,22 +492,14 @@ describe('features/connectors/oauth-dcr', () => {expect(next.expires_at).toBeGreaterThan(Date.now());});- it('retries and refreshes server-managed DCR grants by grant_id', async () => {+ it('force refreshes a still-unexpired local DCR grant directly at the provider', async () => {const fetchMock = vi.fn(async (url: string, init: RequestInit) => {- if (fetchMock.mock.calls.length === 1) {- throw new TypeError('fetch failed');- }- expect(String(url)).toBe('https://account.example/api/connectors/oauth/refresh');- const body = JSON.parse(String(init.body));- expect(body.provider).toBe('notion');- expect(body.grant_id).toBe('grant-1');- expect(body.refresh_token).toBeUndefined();+ expect(String(url)).toBe('https://auth.notion.example/token');+ const body = new URLSearchParams(String(init.body));+ expect(body.get('refresh_token')).toBe('old-refresh');return jsonResponse({- code: 0,access_token: 'new-access',- refresh_token: null,- grant_id: 'grant-1',- server_managed: true,+ refresh_token: 'new-refresh',expires_in: 3600,token_type: 'Bearer',scope: 'read write',@@ -538,24 +507,25 @@ describe('features/connectors/oauth-dcr', () => {});vi.stubGlobal('fetch', fetchMock);- const { refreshDcrServerManaged } = await import('../../../../src/main/features/connectors/oauth-dcr');- const next = await refreshDcrServerManaged('notion', {+ const { refreshDcrIfStale } = await import('../../../../src/main/features/connectors/oauth-dcr');+ const next = await refreshDcrIfStale({+ client_id: 'client-1',+ client_secret: 'secret-1',+ authorization_endpoint: 'https://auth.notion.example/authorize',+ token_endpoint: 'https://auth.notion.example/token',+ }, {access_token: 'old-access',- refresh_token: null,- server_grant_id: 'grant-1',- server_managed: true,- expires_at: Date.now() - 1,+ refresh_token: 'old-refresh',+ expires_at: Date.now() + 60 * 60 * 1000,scopes: ['old'],token_type: 'Bearer',- });+ }, { force: true });expect(next).toMatchObject({access_token: 'new-access',- refresh_token: null,- server_managed: true,- server_grant_id: 'grant-1',+ refresh_token: 'new-refresh',scopes: ['read', 'write'],});- expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock).toHaveBeenCalledTimes(1);});});diff --git a/test/main/features/connectors/open-source-boundary.test.ts b/test/main/features/connectors/open-source-boundary.test.tsnew file mode 100644index 00000000..684634a7--- /dev/null+++ b/test/main/features/connectors/open-source-boundary.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { CONNECTOR_CATALOG } from '../../../../src/main/features/connectors/catalog';++const root = path.join(__dirname, '../../../..');+const read = (rel: string) => fs.readFileSync(path.join(root, rel), 'utf8');++describe('public connector boundary', () => {+ it('keeps every catalog connector on a public OAuth mode without credit metering', () => {+ expect(CONNECTOR_CATALOG).toHaveLength(21);+ expect(CONNECTOR_CATALOG.filter((entry) => entry.auth_mode === 'mcp_dcr')).toHaveLength(11);+ expect(CONNECTOR_CATALOG.filter((entry) => entry.auth_mode === 'server_bridge')).toHaveLength(10);+ for (const entry of CONNECTOR_CATALOG) {+ expect(['server_bridge', 'mcp_dcr']).toContain(entry.auth_mode);+ expect(entry.icon_svg).toMatch(/^<svg\b/);+ if (entry.auth_mode === 'mcp_dcr') {+ expect(entry.transport_template?.kind).toBe('streamable-http');+ expect(entry.transport_template && 'url' in entry.transport_template+ ? entry.transport_template.url+ : '').toMatch(/^https:\/\//);+ }+ for (const forbiddenKey of [+ `usage_${'metering'}`,+ `credits_milli_${'per_call'}`,+ `connect_requires_${'credits'}`,+ ]) {+ expect((entry as any)[forbiddenKey]).toBeUndefined();+ }+ }+ });++ it('pins connector OAuth to the global HTTPS bridge with no loopback or environment override', () => {+ const bridge = read('src/main/features/connectors/_server_bridge.ts');+ const marketplace = read('src/main/features/marketplace.ts');+ const oauthSources = [+ bridge,+ read('src/main/features/connectors/oauth.ts'),+ read('src/main/features/connectors/oauth-dcr.ts'),+ ].join('\n');++ expect(bridge).toContain('return apiBase();');+ expect(marketplace).toContain("const GLOBAL_PROD_API_BASE = 'https://orkas.ai' + '/api';");+ expect(oauthSources).not.toMatch(/http:\/\/(?:localhost|127\.0\.0\.1)|ORKAS_API_BASE_URL|OAUTH_REDIRECT_BASE/);+ });++ it('ships and boots a connector-only callback receiver', () => {+ const main = read('src/main/index.ts');+ const pkg = JSON.parse(read('package.json'));+ const sourceLauncher = read('run.sh');++ expect(main).toContain('registerConnectorProtocol();');+ expect(main).toContain('await consumeColdLaunchConnectorCallback();');+ expect(pkg.build.protocols).toEqual(expect.arrayContaining([+ expect.objectContaining({ schemes: expect.arrayContaining(['orkas']) }),+ ]));+ expect(sourceLauncher).toContain('scripts/prepare-source-protocol.cjs');+ });++ it('keeps MCP DCR credentials local and excludes account-scoped DCR grant hosting', () => {+ const dcr = read('src/main/features/connectors/oauth-dcr.ts');+ const manager = read('src/main/features/connectors/manager.ts');+ const sources = `${dcr}\n${manager}`;++ expect(sources).not.toContain('/connectors/oauth/dcr-store');+ expect(sources).not.toContain('storeDcrServerManaged');+ expect(sources).not.toContain('refreshDcrServerManaged');+ expect(dcr).toContain('pending.resolve({ grant: localGrant, client: pending.client });');+ expect(manager).toContain('dcrClient = result.client;');+ });+});diff --git a/test/main/features/connectors/protocol.test.ts b/test/main/features/connectors/protocol.test.tsnew file mode 100644index 00000000..a80fcfd2--- /dev/null+++ b/test/main/features/connectors/protocol.test.ts@@ -0,0 +1,84 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const electronMock = vi.hoisted(() => {+ const listeners = new Map<string, (...args: any[]) => unknown>();+ const window = {+ isDestroyed: vi.fn(() => false),+ isMinimized: vi.fn(() => true),+ restore: vi.fn(),+ show: vi.fn(),+ focus: vi.fn(),+ };+ return {+ listeners,+ window,+ app: {+ isPackaged: true,+ isReady: vi.fn(() => true),+ setAsDefaultProtocolClient: vi.fn(() => true),+ isDefaultProtocolClient: vi.fn(() => true),+ on: vi.fn((event: string, listener: (...args: any[]) => unknown) => listeners.set(event, listener)),+ },+ };+});++const connectorMock = vi.hoisted(() => ({+ handleCallbackUrl: vi.fn(async () => undefined),+ handleDcrCallbackUrl: vi.fn(async () => undefined),+}));++vi.mock('electron', () => ({+ app: electronMock.app,+ BrowserWindow: { getAllWindows: () => [electronMock.window] },+}));++vi.mock('../../../../src/main/features/connectors/index', () => connectorMock);++describe('connector callback protocol', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ electronMock.listeners.clear();+ electronMock.app.isReady.mockReturnValue(true);+ });++ it('accepts only connector OAuth callbacks', async () => {+ const { _test } = await import('../../../../src/main/features/connectors/protocol');++ expect(_test.connectorCallbackKind('orkas://connectors/oauth/callback?exchange_code=x')).toBe('server');+ expect(_test.connectorCallbackKind('orkas://connectors/oauth/dcr-callback?exchange_code=x')).toBe('dcr');+ expect(_test.connectorCallbackKind(`orkas://${'auth'}/callback?code=x`)).toBeNull();+ expect(_test.connectorCallbackKind('https://orkas.ai/connectors/oauth/callback')).toBeNull();+ });++ it('registers before readiness and dispatches both callback kinds to the running app', async () => {+ const protocol = await import('../../../../src/main/features/connectors/protocol');+ protocol.registerConnectorProtocol();++ expect(electronMock.app.setAsDefaultProtocolClient).toHaveBeenCalledWith('orkas');+ const openUrl = electronMock.listeners.get('open-url');+ expect(openUrl).toBeTypeOf('function');+ const preventDefault = vi.fn();++ await openUrl?.({ preventDefault }, 'orkas://connectors/oauth/callback?exchange_code=one');+ await vi.waitFor(() => expect(connectorMock.handleCallbackUrl).toHaveBeenCalledTimes(1));+ await openUrl?.({ preventDefault }, 'orkas://connectors/oauth/dcr-callback?exchange_code=two');+ await vi.waitFor(() => expect(connectorMock.handleDcrCallbackUrl).toHaveBeenCalledTimes(1));++ expect(preventDefault).toHaveBeenCalledTimes(2);+ expect(electronMock.window.restore).toHaveBeenCalled();+ expect(electronMock.window.focus).toHaveBeenCalled();+ });++ it('does not intercept stripped account-login links', async () => {+ const protocol = await import('../../../../src/main/features/connectors/protocol');+ protocol.registerConnectorProtocol();+ const openUrl = electronMock.listeners.get('open-url');+ const preventDefault = vi.fn();++ await openUrl?.({ preventDefault }, `orkas://${'auth'}/callback?exchange_code=account`);++ expect(preventDefault).not.toHaveBeenCalled();+ expect(connectorMock.handleCallbackUrl).not.toHaveBeenCalled();+ expect(connectorMock.handleDcrCallbackUrl).not.toHaveBeenCalled();+ });+});diff --git a/test/renderer/connector-icons.test.ts b/test/renderer/connector-icons.test.tsindex 7c979431..9f054fdd 100644--- a/test/renderer/connector-icons.test.ts+++ b/test/renderer/connector-icons.test.ts@@ -16,6 +16,27 @@ describe('connector brand icons', () => {expect(indexHtml.indexOf(purifier)).toBeLessThan(indexHtml.indexOf(utilities));});+ it('loads shared public renderer dependencies that survived hosted-module stripping', () => {+ const indexHtml = fs.readFileSync(path.join(root, 'src/renderer/index.html'), 'utf8');+ for (const script of [+ './modules/user-error.js',+ './modules/interactive-cli.js',+ ]) {+ expect(fs.existsSync(path.join(root, 'src/renderer', script))).toBe(true);+ expect(indexHtml).toContain(`<script src="${script}"></script>`);+ }+ });++ it('renders exactly one connecting spinner', () => {+ const renderer = fs.readFileSync(path.join(root, 'src/renderer/modules/connectors.js'), 'utf8');+ const css = fs.readFileSync(path.join(root, 'src/renderer/style.css'), 'utf8');++ expect(renderer).toContain('btn btn-sm btn-primary is-loading');+ expect(renderer).not.toContain('class="btn-spinner"');+ expect(css).toContain('.btn.is-loading::before');+ expect(css).not.toMatch(/(^|\n)\.btn-spinner\s*\{/);+ });+it('ships an inline SVG for every public connector card', () => {const missing = CONNECTOR_CATALOG.filter((entry) => !String(entry.icon_svg || '').trim().startsWith('<svg'))