Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): add remote authorization and private setup cards (#4813)
Siriusb8b90eb536e6
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex b754683073..6955ad680e 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -48,6 +48,11 @@ import {} from '../device-link/invoke-context';import * as subscriptions from '../device-link/subscriptions';import { createDesktopOnlyConfirmationRequestId } from '../cindy-brain/desktopOnlyConfirmationProjection';+import { PLUGIN_OAUTH_CHANNEL } from '@cindy/device-link';+import { initializePluginOauthHost, invalidatePluginOauth, publishedPluginOauthIdentity } from '../plugin-oauth/runtime';+import { OauthBox } from '../plugin-oauth/box';+import { testOauthSigningKey } from '../plugin-oauth/__tests__/fixtures';+import { authenticateOauthController } from '../plugin-oauth/authentication';beforeEach(() => {remoteControlEnabled = true;@@ -63,6 +68,31 @@ beforeEach(() => {});describe('runInvoke 双层校验', () => {+ it('routes OAuth with the authenticated src and applies revocation before its private handler', async () => {+ initializePluginOauthHost({+ owner: () => 'member:g1', available: () => true,+ bind: async () => ({ ghostId: 'p', current: () => true }), run: () => true,+ }, () => ({deviceId:'cloud',membershipId:'member',realm:'global'}), testOauthSigningKey);+ try {+ const now=Date.now(), action={requestId:'card',actionId:'oauth_connect:x',expectedRevision:1};+ let last: unknown;+ const exchange=await authenticateOauthController({+ target:{...(await publishedPluginOauthIdentity())!,realm:'global',deviceId:'cloud',membershipId:'member',observedAtMs:now,expiresAtMs:now+60000},+ peer:'ctrl-a',action,ghostId:'p',assertCurrent:()=>{},trustIdentity:async()=>{},+ invoke:async raw=>{last=raw;const reply=await runInvoke('ctrl-a',{channel:PLUGIN_OAUTH_CHANNEL,args:[raw]});+ if(!reply.ok)throw Error('rejected');return reply.result;},+ });+ const started=await exchange({op:'start',...action,publicKey:new OauthBox().publicKey}) as {id:string};+ const id=started.id;expect(id).toBeTruthy();+ expect((await runInvoke('ctrl-b',{channel:PLUGIN_OAUTH_CHANNEL,args:[last]})).ok).toBe(false);+ expect((await runInvoke('ctrl-a',{channel:'device-link:plugin-oauth:v1',args:[{op:'capabilities'}]}))).toMatchObject({ok:false,error:{code:'CHANNEL_NOT_ALLOWED'}});+ revokedControllers = ['ctrl-a'];+ await expect(runInvoke('ctrl-a', { channel: PLUGIN_OAUTH_CHANNEL, args: [{ op: 'status', id }] })).resolves.toMatchObject({+ ok: false, error: { code: 'ACCESS_REVOKED' },+ });+ expect((await runInvoke('ctrl-b', { channel: PLUGIN_OAUTH_CHANNEL, args: [{ op: 'capabilities', src: 'ctrl-a' }] })).ok).toBe(false);+ } finally { invalidatePluginOauth(); }+ });it('开关关闭 → REMOTE_DISABLED', async () => {remoteControlEnabled = false;const r = await runInvoke('ctrl', { channel: 'maker:list-active', args: [] });diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex e76ab21258..ed0d5d3fd7 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -104,7 +104,7 @@ import {retryUnsubscribeAfterWindowGone,type DeviceLinkIpcDeps,} from '../device-link/ipc';-import { DeviceLinkError } from '@cindy/device-link';+import { DeviceLinkError, PLUGIN_OAUTH_CHANNEL, PLUGIN_SECRET_LOCAL_CHANNEL } from '@cindy/device-link';import { invokeWithClosedLinkRecovery } from '../device-link/linkRecovery';import { ServerApiError } from '../serverApiClient';import {@@ -165,6 +165,11 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {}describe('device-link IPC handlers', () => {+ it.each([PLUGIN_OAUTH_CHANNEL, PLUGIN_SECRET_LOCAL_CHANNEL])('never forwards %s from the generic Renderer tunnel', async channel => {+ const deps = makeDeps();+ await expect(handleInvoke(deps, 'cloud', channel, [{ op: 'capabilities' }])).rejects.toThrow('PERMISSION_DENIED');+ expect(deps.invoke).not.toHaveBeenCalled();+ });beforeEach(() => {refcountTesting.reset(); // 多窗口订阅引用计数:每个用例独立capabilities.canUseDeviceLink = true;diff --git a/apps/desktop/src/main/__tests__/oauthResultPageGlossary.test.ts b/apps/desktop/src/main/__tests__/oauthResultPageGlossary.test.tsindex 7b015dbb0b..0a15af8413 100644--- a/apps/desktop/src/main/__tests__/oauthResultPageGlossary.test.ts+++ b/apps/desktop/src/main/__tests__/oauthResultPageGlossary.test.ts@@ -37,6 +37,7 @@ import {import {buildOAuthReturnAction,getGhostOAuthResultCopy,+ getRemoteOAuthCallbackCopy,getOAuthNeutralResultCopy,getProviderOAuthResultCopy,type OAuthResultPageLang,@@ -76,6 +77,7 @@ function collectEntries(): { locale: string; key: string; value: string }[] {};for (const lang of LANGS) {+ for (const [key, value] of Object.entries(getRemoteOAuthCallbackCopy(lang))) push(lang, `remote.${key}`, value);const provider = getProviderOAuthResultCopy(lang, PROVIDER, BRAND);for (const [k, v] of Object.entries(provider)) {if (typeof v === 'string') push(lang, `provider.${k}`, v);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.tsindex 168972d132..719d0f4366 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts@@ -243,6 +243,81 @@ function harness(initial: GhostSetupAssessment) {}describe('GhostSetupCoordinator', () => {+ it('completes local reconfiguration only after opening settings and a committed write to that connection', async () => {+ const action = { id: 'manage_connection:connection:service', kind: 'manage_connection' as const };+ const assessment: GhostSetupAssessment = { state: 'ready', revision: 1, groups: [{ id: 'connection', mode: 'any_of',+ items: [{ ref: 'connection:service', kind: 'connection', label: 'Service', state: 'satisfied', actions: [action] }] }] };+ const h = harness(assessment);+ h.executeAction.mockResolvedValue({ ok: true, waitingExternal: true });+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'gmail', reauthorize: true });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ const card = h.bridge.pendingSnapshots()[0].request;+ expect(h.bridge.resolve(card.requestId, { kind: 'plugin_setup', action: 'run_action', actionId: action.id, expectedRevision: card.revision })).toBe(true);+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()[0].request.steps[0].phase).toBe('waiting_external'));+ h.changeBus.wake('gmail', { source: 'connection', ref: 'service' });+ h.changeBus.emit('gmail', { source: 'connection', ref: 'different' });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()[0].request.steps[0].phase).toBe('waiting_external'));+ h.changeBus.emit('gmail', { source: 'connection', ref: 'service' });+ await expect(waiting).resolves.toMatchObject({ ok: true });+ });+ it('does not treat another connection write or a forged Renderer receipt as completing reconfiguration', async () => {+ const action = { id: 'manage_connection:connection:service', kind: 'manage_connection' as const };+ const assessment: GhostSetupAssessment = { state: 'ready', revision: 1, groups: [{ id: 'connection', mode: 'any_of',+ items: [{ ref: 'connection:service', kind: 'connection', label: 'Service', state: 'satisfied', actions: [action] }] }] };+ const h = harness(assessment), abort = new AbortController();+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'gmail', reauthorize: true, signal: abort.signal });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ const original = h.bridge.pendingSnapshots()[0].request;+ h.changeBus.emit('gmail', { source: 'connection', ref: 'service' });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()[0].request.revision).toBeGreaterThan(original.revision));+ const card = h.bridge.pendingSnapshots()[0].request;+ expect(h.bridge.resolve(card.requestId, { kind: 'plugin_setup', action: 'connection_committed', actionId: action.id, expectedRevision: card.revision })).toBe(false);+ expect(h.bridge.connectionCommitted(card.requestId, action.id, original.revision)).toBe(false);+ expect(h.bridge.connectionCommitted(card.requestId, 'manage_connection:connection:other', card.revision)).toBe(false);+ expect(h.bridge.pendingSnapshots()).toHaveLength(1);+ abort.abort();+ await expect(waiting).resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ expect(h.bridge.connectionCommitted(card.requestId, action.id, card.revision)).toBe(false);+ });+ it('cancels a connection waiter and rejects a replay of its card', async () => {+ const h = harness(required());+ const controller = new AbortController();+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'gmail', signal: controller.signal });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ const card = h.bridge.pendingSnapshots()[0].request;+ controller.abort();+ await expect(waiting).resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);+ expect(h.bridge.resolve(card.requestId, {+ kind: 'plugin_setup', action: 'run_action', expectedRevision: card.revision,+ actionId: 'oauth_connect:secret:google',+ })).toBe(false);+ expect(h.executeAction).not.toHaveBeenCalled();+ });++ it('does not open a card after its MCP request was already cancelled', async () => {+ const h = harness(required());+ const controller = new AbortController(); controller.abort();+ await expect(h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'gmail', signal: controller.signal }))+ .resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);+ });++ it('explicit reconnect waits for its actual OAuth action, not an unrelated settings event', async () => {+ const configured = ready();+ configured.groups[0].items[0].actions = required().groups[0].items[0].actions;+ const h = harness(configured);+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'gmail', reauthorize: true });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ h.changeBus.emit('gmail', { source: 'secret' });+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()[0].request.steps[0].phase).toBe('pending'));+ const card = h.bridge.pendingSnapshots()[0].request;+ await h.bridge.resolve(card.requestId, { kind: 'plugin_setup', action: 'run_action',+ expectedRevision: card.revision, actionId: 'oauth_connect:secret:google' });+ await expect(waiting).resolves.toMatchObject({ ok: true });+ expect(h.executeAction).toHaveBeenCalledTimes(1);+ });+it('ready path does not create an interaction', async () => {const h = harness(ready());await expect(diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupSecretReauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupSecretReauth.test.tsnew file mode 100644index 0000000000..e9acbc7ecb--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupSecretReauth.test.ts@@ -0,0 +1,153 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { validateGhostManifest } from '../../../shared/ghost.js';+import { GhostSetupChangeBus } from '../ghostSetupChangeBus.js';+import { GhostSetupCoordinator, type GhostSetupInlineActionInput } from '../ghostSetupCoordinator.js';+import { GhostSetupInteractionBridge } from '../ghostSetupInteractionBridge.js';+import { executeGhostSetupInlineSubmission } from '../ghostSetupInlineExecutor.js';+import { evaluateGhostSetupAssessment } from '../ghostSetupStatus.js';++const cleanups: Array<() => void> = [];+afterEach(() => cleanups.splice(0).forEach(close => close()));++function harness(options: { saved?: boolean; hold?: boolean; fail?: boolean } = {}) {+ const parsed = validateGhostManifest({+ schemaVersion: 2, id: 'demo', name: 'Demo', version: '1.0.0',+ entry: 'main.js', settingsHtml: 'settings.html', slots: ['tool', 'network'],+ tools: [{ name: 'check', description: 'Check' }],+ network: { hosts: ['service.example.test'], secrets: [+ { key: 'api_key', label: 'API Key', source: 'user',+ inject: { header: 'Authorization', format: 'Bearer {value}' } },+ ] },+ });+ if (!parsed.ok) throw new Error('Invalid test manifest');+ let manifest = parsed.manifest;+ const values = new Map(options.saved ? [['api_key', 'synthetic-old']] : []);+ const changes = new GhostSetupChangeBus();+ const broadcast = vi.fn();+ const bridge = new GhostSetupInteractionBridge({ broadcast });+ const assess = () => evaluateGhostSetupAssessment(manifest, {+ secretSaved: key => values.has(key),+ oauthStatus: () => ({ clientConfigured: false, connected: 0, expired: 0 }),+ connectionCount: () => 0, kvValue: () => undefined,+ }, { revision: changes.currentRevision('demo') });+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let fail = options.fail ?? false, available = true;+ let submitted: GhostSetupInlineActionInput | undefined;+ const storeSecret = vi.fn((_ghost: string, key: string, value: string) => {+ if (fail) return false;+ values.set(key, value);+ return true;+ });+ const execute = (args: GhostSetupInlineActionInput) => executeGhostSetupInlineSubmission({+ getAssessment: assess, getManifest: () => manifest, storeSecret,+ emitChange: () => changes.emit('demo', { source: 'secret', ref: 'api_key' }),+ }, args);+ const coordinator = new GhostSetupCoordinator({+ bridge, changeBus: changes, assess,+ validateTarget: () => available ? { ok: true } :+ { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: 'Unavailable' },+ getGhostIdentity: () => ({ id: 'demo', name: 'Demo' }),+ executeAction: async () => ({ ok: false, errorCode: 'ACTION_STALE' }),+ executeInlineAction: async args => {+ submitted = args;+ if (options.hold) await gate;+ return execute(args);+ },+ terminalGraceMs: 0,+ });+ const abort = new AbortController();+ cleanups.push(() => { abort.abort(); release(); });+ const start = (reauthorize = true) => coordinator.ensureReady({+ sessionId: 'task', ghostId: 'demo', workingDir: '/fixture',+ reauthorize, signal: abort.signal,+ });+ const card = () => bridge.pendingSnapshots()[0].request;+ const submit = (overrides: Record<string, unknown> = {}) => bridge.submitInline(card().requestId, {+ actionId: card().steps[0].action!.id, expectedRevision: card().revision,+ value: 'synthetic-new', ...overrides,+ });+ return { start, card, submit, bridge, values, storeSecret, changes, execute,+ submitted: () => submitted, broadcast, abort, release,+ fail: (value: boolean) => { fail = value; },+ disable: () => { available = false; },+ changeDeclaration: () => { manifest = { ...manifest, network: { ...manifest.network!, secrets: [] } }; },+ };+}++describe('saved user Secret reconfiguration', () => {+ it.each([false, true])('stores the current card once (previous value: %s)', async saved => {+ const h = harness({ saved });+ const ready = h.start();+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ const original = h.card();+ // Even a settings event for this key is not this card's commit receipt.+ h.changes.emit('demo', { source: 'secret', ref: 'api_key' });+ await vi.waitFor(() => expect(h.card().revision).toBeGreaterThan(original.revision));+ expect(h.values.get('api_key')).toBe(saved ? 'synthetic-old' : undefined);+ h.submit();+ await expect(ready).resolves.toMatchObject({ ok: true });+ expect(h.values.get('api_key')).toBe('synthetic-new');+ expect(h.storeSecret).toHaveBeenCalledTimes(1);+ expect(h.bridge.submitInline(original.requestId, {+ actionId: original.steps[0].action!.id, expectedRevision: original.revision, value: 'replay',+ })).toBe(false);+ expect(JSON.stringify(h.broadcast.mock.calls)).not.toContain('synthetic-');+ });++ it('keeps ordinary ready checks noninteractive', async () => {+ const h = harness({ saved: true });+ await expect(h.start(false)).resolves.toMatchObject({ ok: true });+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);+ expect(h.storeSecret).not.toHaveBeenCalled();+ });++ it('retains the previous value on failure and accepts a retry on the new revision', async () => {+ const h = harness({ saved: true, fail: true });+ const ready = h.start();+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ h.submit();+ await vi.waitFor(() => expect(h.card().steps[0].errorCode).toBe('SAVE_FAILED'));+ expect(h.values.get('api_key')).toBe('synthetic-old');+ h.fail(false);+ h.submit();+ await expect(ready).resolves.toMatchObject({ ok: true });+ expect(h.values.get('api_key')).toBe('synthetic-new');+ });++ it.each(['cancel', 'workdir', 'declaration'] as const)('rejects a delayed local write after %s', async reason => {+ const h = harness({ saved: true, hold: true });+ const ready = h.start();+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ h.submit();+ await vi.waitFor(() => expect(h.submitted()).toBeDefined());+ if (reason === 'cancel') h.abort.abort();+ if (reason === 'workdir') h.disable();+ if (reason === 'declaration') h.changeDeclaration();+ h.release();+ if (reason === 'cancel') await expect(ready).resolves.toMatchObject({ errorCode: 'SETUP_CANCELLED' });+ else await vi.waitFor(() => expect(h.card().steps[0].phase).toBe('failed'));+ expect(h.values.get('api_key')).toBe('synthetic-old');+ expect(h.storeSecret).not.toHaveBeenCalled();+ });++ it('rejects stale revisions, another action and reuse of the Main-only commit capability', async () => {+ const h = harness({ saved: true, hold: true });+ const ready = h.start();+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));+ h.submit({ expectedRevision: -1 });+ h.submit({ actionId: 'inline_form:another-key' });+ await vi.waitFor(() => expect(h.card().steps[0].phase).toBe('pending'));+ expect(h.submitted()).toBeUndefined();+ h.submit();+ await vi.waitFor(() => expect(h.submitted()).toBeDefined());+ const args = h.submitted()!;+ expect(() => h.execute({ ...args, ghostId: 'another-plugin' })).toThrow('PLUGIN_SETUP_INLINE_STALE');+ expect(() => args.commit!.assertCurrent('demo', args.action.id, 'secret:another-key')).toThrow();+ expect(h.storeSecret).not.toHaveBeenCalled();+ h.release();+ await expect(ready).resolves.toMatchObject({ ok: true });+ expect(() => h.execute(args)).toThrow('PLUGIN_SETUP_INLINE_STALE');+ expect(h.storeSecret).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeAuthorizationClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeAuthorizationClient.test.tsnew file mode 100644index 0000000000..d67961c74a--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeAuthorizationClient.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from 'vitest';+import { NodeAuthorizationClient } from '../nodeAuthorizationClient.js';+import { NodeRequestScopes } from '../nodeRequestScope.js';+import { parseGhostNodeChildToHostMessage } from '../../../shared/ghost.js';++function harness() {+ const scopes = new NodeRequestScopes(),+ sent: Record<string, unknown>[] = [];+ const client = new NodeAuthorizationClient(scopes, (raw) =>+ sent.push(raw as Record<string, unknown>),+ );+ let authorize!: NonNullable<ReturnType<NodeAuthorizationClient['bind']>>;+ scopes.feed('{"id":"1","cindy":{"cancelWithCall":true}}', () => {+ authorize = client.bind()!;+ });+ return { scopes, sent, client, authorize };+}+describe('generic private Node authorization', () => {+ it('binds the originating RPC and accepts a user code without exposing it through stdout', async () => {+ const h = harness();+ const request = {+ kind: 'device' as const,+ url: 'https://provider.example/activate',+ userCode: '123456789',+ };+ const waiting = h.authorize(request);+ expect(h.sent[0]).toEqual({ type: 'plugin-authorize', reqId: 'auth1', rpcId: '1', request });+ expect(parseGhostNodeChildToHostMessage(h.sent[0])).toEqual(h.sent[0]);+ h.client.reply({ reqId: 'auth1', ok: true, result: { kind: 'opened' } });+ await expect(waiting).resolves.toEqual({ kind: 'opened' });+ await expect(h.authorize(request)).rejects.toThrow();+ });+ it('rejects late callback and a callback injected into a device request', async () => {+ const h = harness();+ const waiting = h.authorize({ kind: 'device', url: 'https://provider.example/activate' });+ h.client.reply({+ reqId: 'auth1',+ ok: true,+ result: { kind: 'callback', state: 's'.repeat(43), code: 'synthetic' },+ });+ await expect(waiting).rejects.toThrow();+ const late = harness();+ const pending = late.authorize({ kind: 'browser', url: 'https://provider.example/qr' });+ late.scopes.finish('1');+ late.client.reply({ reqId: 'auth1', ok: true, result: { kind: 'opened' } });+ await expect(pending).rejects.toThrow();+ });+ it('denies background calls, forged task IDs, URLs and commands in the control frame', () => {+ const h = harness();+ expect(h.client.bind()).toBeUndefined();+ const valid = {+ type: 'plugin-authorize',+ reqId: 'a',+ rpcId: '1',+ request: { kind: 'browser', url: 'https://provider.example' },+ };+ for (const raw of [+ { ...valid, sessionId: 'forged' },+ { ...valid, rpcId: 'call-a' },+ { ...valid, request: { ...valid.request, command: 'anything' } },+ { ...valid, request: { kind: 'browser', url: 'http://provider.example' } },+ ])+ expect(parseGhostNodeChildToHostMessage(raw)).toBeNull();+ });+ it('cancels pending work when its RPC ends', async () => {+ const h = harness(),+ waiting = h.authorize({ kind: 'browser', url: 'https://provider.example/qr' });+ h.client.finish('1');+ await expect(waiting).rejects.toThrow();+ h.client.reply({ reqId: 'auth1', ok: true, result: { kind: 'opened' } });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeDeviceAuthorizationClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeDeviceAuthorizationClient.test.tsnew file mode 100644index 0000000000..4f332b613d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeDeviceAuthorizationClient.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';+import { NodeDeviceAuthorizationClient } from '../nodeDeviceAuthorizationClient';+import { NodeRequestScopes } from '../nodeRequestScope';++describe('bound Node device authorization transport', () => {+ it('captures the request before a stream callback loses context and cannot bind a sibling or expired call', async () => {+ const scopes = new NodeRequestScopes();+ const sent: Array<Record<string, unknown>> = [];+ const client = new NodeDeviceAuthorizationClient(scopes, (m) =>+ sent.push(m as Record<string, unknown>),+ );+ expect(client.bind()).toBeUndefined();+ let authorize!: (url: string) => Promise<void>;+ scopes.feed('{"id":"1","cindy":{"cancelWithCall":true}}', () => {+ authorize = client.bind()!;+ });+ let opening!: Promise<void>;+ scopes.feed('{"id":"2","cindy":{"cancelWithCall":true}}', () => {+ opening = authorize('https://provider.example/device?code=synthetic');+ });+ expect(sent[0]).toMatchObject({ type: 'device-authorize', rpcId: '1' });+ client.reply({ reqId: sent[0].reqId, ok: true });+ await opening;+ await expect(authorize('https://provider.example/again')).rejects.toThrow();+ let late!: (url: string) => Promise<void>;+ scopes.feed('{"id":"3","cindy":{"cancelWithCall":true}}', () => {+ late = client.bind()!;+ });+ scopes.finish('3');+ await expect(late('https://provider.example/late')).rejects.toThrow();+ expect(sent).toHaveLength(1);+ });+ it('rejects the captured request when the Host settles it and ignores a late opened reply', async () => {+ const scopes = new NodeRequestScopes();+ const sent: Array<Record<string, unknown>> = [];+ const client = new NodeDeviceAuthorizationClient(scopes, (m) =>+ sent.push(m as Record<string, unknown>),+ );+ let opening!: Promise<void>;+ scopes.feed('{"id":"1","cindy":{"cancelWithCall":true}}', () => {+ opening = client.bind()!('https://provider.example/device');+ });+ const rejected = expect(opening).rejects.toThrow('DEVICE_AUTHORIZATION_UNAVAILABLE');+ scopes.finish('1');+ client.finish('1');+ client.reply({ reqId: sent[0].reqId, ok: true });+ await rejected;+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRequestScope.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRequestScope.test.tsnew file mode 100644index 0000000000..a367d6e88e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRequestScope.test.ts@@ -0,0 +1,48 @@+import { createInterface } from 'node:readline';+import { PassThrough } from 'node:stream';+import { describe, expect, it } from 'vitest';+import { NodeRequestScopes } from '../nodeRequestScope';++describe('call-bound Node async context', () => {+ it('keeps interleaved readline requests separate and rejects late work after cancellation', async () => {+ const scopes = new NodeRequestScopes();+ const stream = new PassThrough();+ const lines = createInterface({ input: stream });+ const release: Array<() => void> = [];+ const work: Promise<string | undefined>[] = [];+ lines.on('line', () => {+ work.push(+ (async () => {+ await new Promise<void>((resolve) => release.push(resolve));+ return scopes.currentRpcId();+ })(),+ );+ });+ try {+ for (const id of ['1', '2'])+ scopes.feed(JSON.stringify({ id, cindy: { cancelWithCall: true } }) + '\n', (x) =>+ stream.write(x),+ );+ scopes.finish('1');+ const cancelled = expect(work[0]).rejects.toThrow('has ended');+ release[1]();+ expect(await work[1]).toBe('2');+ release[0]();+ await cancelled;+ scopes.finish('2');+ expect(scopes.currentRpcId()).toBeUndefined();+ } finally {+ lines.close();+ stream.destroy();+ }+ });++ it('preserves unbound legacy and background stdin behavior', async () => {+ const scopes = new NodeRequestScopes();+ let result: Promise<string | undefined>;+ scopes.feed('{"id":"3","method":"tools/call"}\n', () => {+ result = Promise.resolve().then(() => scopes.currentRpcId());+ });+ expect(await result!).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex d6017c648f..618b193ee1 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -285,6 +285,110 @@ function makeAutoReplyProcess(methods?: string[], emitSpawn = true) {return process;}+describe('nodeRuntimeBroker protected manual input', () => {+ function manualHarness() {+ const ghost = fakeGhost();+ ghost.manifest.node!.entries = ['node/account.cjs'];+ ghost.manifest.node!.secretBindings = [{ key: 'manual_token', label: 'Manual Token',+ entry: 'node/account.cjs', methods: ['account/import'] }];+ const abort = new AbortController();+ let saved: string | null = null;+ let sessionId: string | null = 'task';+ let child: FakeNodeProcess;+ const spawnProcess = vi.fn(() => { child = makeAutoReplyProcess(); return child; });+ const readSecret = vi.fn(() => saved);+ const openSecretInput = vi.fn(async (input: import('../nodeSecretSetup').NodeSecretSetupInput) => {+ input.assertCurrent(); saved = 'synthetic-manual-secret'; return true;+ });+ const log = { info: vi.fn(), warn: vi.fn() };+ const secretSaved = vi.fn(() => saved !== null);+ const broker = new GhostNodeRuntimeBroker({ getGhost: () => ghost, spawnProcess,+ getCallSignal: (_, id) => id === 'live-call' ? abort.signal : null,+ getCallSessionId: () => sessionId, readSecret, secretSaved,+ openSecretInput, log });+ const request = { type: 'node-request', entry: 'node/account.cjs', method: 'account/import',+ params: {}, callId: 'live-call', cancelWithCall: true, promptSecrets: true };+ return { ghost, broker, get child() { return child; }, request, abort, readSecret, secretSaved, openSecretInput, spawnProcess, log,+ changeSession: () => { sessionId = 'another-task'; } };+ }++ it.each([false, true])('leaves legacy manual credentials unchanged (saved: %s)', async saved => {+ const h = manualHarness();+ h.secretSaved.mockImplementation(() => { throw new Error('New card state must not be probed'); });+ h.readSecret.mockReturnValue(saved ? 'synthetic-existing' : null);+ try {+ const result = await h.broker.handleRequest('node-ghost', {+ ...h.request, callId: 'old-metadata', cancelWithCall: undefined, promptSecrets: undefined,+ });+ expect(result).toMatchObject(saved ? { ok: true } : { ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(h.secretSaved).not.toHaveBeenCalled();+ expect(h.openSecretInput).not.toHaveBeenCalled();+ if (saved) expect(h.child.received[0]).toMatchObject({ cindy: { secrets: { manual_token: 'synthetic-existing' } } });+ } finally { h.broker.destroyAll(); }+ });++ it('waits for the card before spawning and privately injects its saved value', async () => {+ const h = manualHarness();+ h.openSecretInput.mockImplementationOnce(async input => {+ expect(h.spawnProcess).not.toHaveBeenCalled();+ expect(h.readSecret).not.toHaveBeenCalled();+ expect(input).toMatchObject({ entry: 'node/account.cjs', method: 'account/import', force: true });+ h.readSecret.mockReturnValue('synthetic-manual-secret');+ return true;+ });+ try {+ const result = await h.broker.handleRequest('node-ghost', h.request);+ expect(result).toMatchObject({ ok: true });+ expect(h.child.received[0]).toMatchObject({ params: {},+ cindy: { secretInputCompleted: true, secrets: { manual_token: 'synthetic-manual-secret' } } });+ expect(JSON.stringify(result)).not.toContain('synthetic-manual-secret');+ expect(JSON.stringify(h.log)).not.toContain('synthetic-manual-secret');+ } finally { h.broker.destroyAll(); }+ });++ it('can collect a missing optional binding without changing global plugin setup', async () => {+ const h = manualHarness(); h.ghost.manifest.setup = { requires: [] };+ try {+ expect(await h.broker.handleRequest('node-ghost', { ...h.request, promptSecrets: false }))+ .toMatchObject({ ok: true });+ expect(h.openSecretInput).toHaveBeenCalledWith(expect.objectContaining({ force: false }));+ expect(h.ghost.manifest.setup).toEqual({ requires: [] });+ } finally { h.broker.destroyAll(); }+ });++ it('allows only one pending password card per call and releases it after cancellation', async () => {+ const h = manualHarness();+ let release!: (value: boolean) => void;+ h.openSecretInput.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));+ try {+ const pending = h.broker.handleRequest('node-ghost', h.request);+ await vi.waitFor(() => expect(h.openSecretInput).toHaveBeenCalledTimes(1));+ expect(await h.broker.handleRequest('node-ghost', h.request)).toMatchObject({ ok: false, errorCode: 'RATE_LIMITED' });+ release(false);+ expect(await pending).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ expect(await h.broker.handleRequest('node-ghost', h.request)).toMatchObject({ ok: true });+ } finally { h.broker.destroyAll(); }+ });++ it.each(['cancel', 'owner', 'package', 'missing-method', 'background'])('refuses %s before Node dispatch', async failure => {+ const h = manualHarness();+ h.openSecretInput.mockImplementationOnce(async input => {+ if (failure === 'cancel') return false;+ if (failure === 'owner') h.changeSession();+ if (failure === 'package') h.ghost.manifest.version = '2.0.0';+ input.assertCurrent(); return true;+ });+ const request = { ...h.request,+ ...(failure === 'missing-method' ? { method: 'account/status' } : {}),+ ...(failure === 'background' ? { callId: undefined } : {}) };+ try {+ expect(await h.broker.handleRequest('node-ghost', request)).toMatchObject({ ok: false });+ expect(h.spawnProcess).not.toHaveBeenCalled();+ expect(h.readSecret).not.toHaveBeenCalled();+ } finally { h.broker.destroyAll(); }+ });+});+afterEach(() => {vi.useRealTimers();vi.unstubAllEnvs();@@ -1971,7 +2075,7 @@ describe('nodeRuntimeBroker · 权限与协议', () => {method: 'mail/action',params: { action: 'search' },// main.js 自报的同名字段不可信;broker 必须忽略并重铸。- cindy: { secrets: { mail_code: 'attacker-value' } },+ cindy: { secretInputCompleted: true, secrets: { mail_code: 'attacker-value' } },});expect(result).toMatchObject({ ok: true });expect(readSecret).toHaveBeenCalledWith('node-ghost', 'mail_code');@@ -1980,6 +2084,7 @@ describe('nodeRuntimeBroker · 权限与协议', () => {params: { action: 'search' },cindy: { secrets: { mail_code: 'fake-secret-value' } },});+ expect(child.received[0].cindy).not.toHaveProperty('secretInputCompleted');await broker.handleRequest('node-ghost', rpcRequest('account/status', {}));expect(readSecret).toHaveBeenCalledTimes(1);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.tsnew file mode 100644index 0000000000..7b37fd49b3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts@@ -0,0 +1,408 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { InstalledGhost } from '../../../shared/ghost';+import {+ GhostNodeRuntimeBroker,+ type NodeWorkerProcess,+ type GhostNodeRuntimeBrokerDeps,+} from '../nodeRuntimeBroker';++class Worker extends EventEmitter {+ stdin = new PassThrough();+ stdout = new PassThrough();+ stderr = new PassThrough();+ killed = false;+ pid = 42;+ requests: Array<{ id: string; method: string; cindy?: unknown }> = [];+ controls: Array<Record<string, unknown>> = [];+ listener?: (value: unknown) => void;+ constructor(autoSpawn = true) {+ super();+ this.stdin.on('data', (chunk) => this.requests.push(JSON.parse(String(chunk))));+ if (autoSpawn) queueMicrotask(() => this.emit('spawn'));+ }+ onControl(listener: (value: unknown) => void) {+ this.listener = listener;+ }+ sendControl(value: unknown) {+ this.controls.push(value as Record<string, unknown>);+ return true;+ }+ kill(signal = 'SIGTERM') {+ this.killed = true;+ queueMicrotask(() => this.emit('exit', null, signal));+ return true;+ }+}++const brokers: GhostNodeRuntimeBroker[] = [];+afterEach(() => {+ for (const b of brokers.splice(0)) b.destroyAll();+});++function harness(autoSpawn = true, extra: Partial<GhostNodeRuntimeBrokerDeps> = {}) {+ const worker = new Worker();+ const children: Worker[] = [];+ const calls = new Map([+ ['call-a', new AbortController()],+ ['call-b', new AbortController()],+ ]);+ const ghost = {+ manifest: {+ id: 'test-plugin',+ name: 'Test',+ version: '1.0.0',+ network: { hosts: ['provider.example'] },+ node: {+ entry: 'worker.cjs',+ entries: ['child.cjs'],+ protocol: 'json-rpc-stdio',+ childSpawn: true,+ },+ },+ dir: path.resolve('test-plugin'),+ enabled: true,+ } as InstalledGhost;+ const broker = new GhostNodeRuntimeBroker({+ ...extra,+ getGhost: () => ghost,+ getCallSignal: (id, callId) =>+ id === 'test-plugin' ? (calls.get(callId)?.signal ?? null) : null,+ spawnProcess: () => {+ queueMicrotask(() => worker.emit('spawn'));+ return worker as NodeWorkerProcess;+ },+ spawnChildProcess: () => {+ const child = new Worker(autoSpawn);+ children.push(child);+ return child as NodeWorkerProcess;+ },+ });+ brokers.push(broker);+ const request = (callId?: string) =>+ broker.handleRequest('test-plugin', {+ type: 'node-request',+ method: 'tools/call',+ params: { name: 'login' },+ ...(callId ? { callId, cancelWithCall: true } : {}),+ });+ const spawn = (rpcId: string | undefined, reqId: string) =>+ worker.listener?.({+ type: 'spawn-child',+ reqId,+ entry: 'child.cjs',+ args: [],+ ...(rpcId ? { rpcId } : {}),+ });+ return { worker, children, calls, broker, request, spawn };+}++async function until(check: () => boolean) {+ for (let i = 0; i < 50; i++) {+ if (check()) return;+ await new Promise<void>((r) => setImmediate(r));+ }+ throw new Error('Expected lifecycle transition did not occur');+}++describe('Node cancellation boundaries', () => {+ it('stops a child cancelled before its ready handshake', async () => {+ const h = harness(false);+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ h.spawn(h.worker.requests[0].id, 'starting');+ await until(() => h.children.length === 1);+ h.calls.get('call-a')!.abort();+ expect(await result).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ await until(() => h.worker.controls.some((x) => x.reqId === 'starting'));+ expect(h.children[0].killed).toBe(true);+ expect(h.worker.controls.find((x) => x.reqId === 'starting')).toMatchObject({ ok: false });+ expect(h.worker.killed).toBe(false);+ });++ it('kills the cancelled request child and preserves another request in the same worker', async () => {+ const h = harness();+ const first = h.request('call-a');+ const second = h.request('call-b');+ await until(() => h.worker.requests.length === 2);+ const [a, b] = h.worker.requests;+ expect(a.cindy).toEqual({ cancelWithCall: true });+ h.spawn(a.id, 'spawn-a');+ h.spawn(b.id, 'spawn-b');+ await until(+ () => h.worker.controls.filter((x) => x.type === 'spawn-child-result').length === 2,+ );+ h.calls.get('call-a')!.abort();+ expect(await first).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ expect(h.children[0].killed).toBe(true);+ expect(h.children[1].killed).toBe(false);+ expect(h.worker.killed).toBe(false);+ h.spawn(a.id, 'late-spawn');+ await until(() => h.worker.controls.some((x) => x.reqId === 'late-spawn'));+ expect(h.children.length).toBe(2);+ expect(h.worker.controls.find((x) => x.reqId === 'late-spawn')).toMatchObject({ ok: false });+ h.worker.stdout.write(+ JSON.stringify({ jsonrpc: '2.0', id: b.id, result: { kept: true } }) + '\n',+ );+ expect(await second).toEqual({ ok: true, result: { kept: true } });+ expect(h.children[1].killed).toBe(true);+ });++ it('rejects stale bindings before starting a worker', async () => {+ const h = harness();+ expect(await h.request('missing')).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ h.calls.get('call-a')!.abort();+ expect(await h.request('call-a')).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ expect(h.worker.requests).toEqual([]);+ });++ it.each([undefined, false])('keeps legacy callId metadata nonbinding (opt-in: %s)', async cancelWithCall => {+ const h = harness();+ const result = h.broker.handleRequest('test-plugin', {+ type: 'node-request', method: 'background/start', callId: 'obsolete-call', cancelWithCall,+ });+ await until(() => h.worker.requests.length === 1);+ expect(h.worker.requests[0].cindy).toBeUndefined();+ h.spawn(undefined, 'background');+ await until(() => h.children.length === 1);+ h.worker.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: h.worker.requests[0].id, result: true }) + '\n');+ expect(await result).toEqual({ ok: true, result: true });+ expect(h.children[0].killed).toBe(false);+ });++ it('does not stop legacy autonomous children when an unbound RPC returns', async () => {+ const h = harness();+ const result = h.request();+ await until(() => h.worker.requests.length === 1);+ h.spawn(undefined, 'background');+ await until(() => h.worker.controls.some((x) => x.reqId === 'background'));+ const id = h.worker.requests[0].id;+ expect(h.worker.requests[0].cindy).toBeUndefined();+ h.worker.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result: true }) + '\n');+ expect(await result).toEqual({ ok: true, result: true });+ expect(h.children[0].killed).toBe(false);+ });+});++describe('Node private authorization bridge', () => {+ it('cannot promote legacy callId metadata into an authorization capability', async () => {+ const open = vi.fn(), session = vi.fn(() => 'trusted-session');+ const h = harness(true, { getCallSessionId: session, openAuthorization: open });+ const result = h.broker.handleRequest('test-plugin', {+ type: 'node-request', method: 'legacy', callId: 'call-a',+ });+ await until(() => h.worker.requests.length === 1);+ const id = h.worker.requests[0].id;+ h.worker.listener?.({+ type: 'plugin-authorize', reqId: 'forged-opt-in', rpcId: id,+ request: { kind: 'browser', url: 'https://provider.example/activate' },+ });+ expect(h.worker.controls.find(x => x.reqId === 'forged-opt-in')).toMatchObject({ ok: false });+ expect(session).not.toHaveBeenCalled();+ expect(open).not.toHaveBeenCalled();+ h.worker.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result: 'original-completion' }) + '\n');+ expect(await result).toEqual({ ok: true, result: 'original-completion' });+ });++ it('routes generic device codes privately and keeps setup completion tied to the Node result', async () => {+ const finish = vi.fn(),+ dispose = vi.fn();+ const open = vi.fn(+ (input: Parameters<NonNullable<GhostNodeRuntimeBrokerDeps['openAuthorization']>>[0]) => {+ expect(input.sessionId).toBe('trusted-session');+ expect(input.request).toEqual({+ kind: 'device',+ url: 'https://provider.example/activate',+ userCode: '123456789',+ });+ return {+ opened: Promise.resolve(),+ result: Promise.resolve({ kind: 'opened' as const }),+ finish,+ dispose,+ };+ },+ );+ const h = harness(true, { getCallSessionId: () => 'trusted-session', openAuthorization: open });+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ const id = h.worker.requests[0].id;+ h.worker.listener?.({+ type: 'plugin-authorize',+ reqId: 'generic',+ rpcId: id,+ request: { kind: 'device', url: 'https://provider.example/activate', userCode: '123456789' },+ });+ await until(() => h.worker.controls.some((x) => x.reqId === 'generic'));+ expect(h.worker.controls.find((x) => x.reqId === 'generic')).toEqual({+ type: 'plugin-authorize-result',+ reqId: 'generic',+ ok: true,+ result: { kind: 'opened' },+ });+ expect(finish).not.toHaveBeenCalled();+ h.worker.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result: { ok: true } }) + '\n');+ expect(await result).toEqual({ ok: true, result: { ok: true } });+ expect(finish).toHaveBeenCalledWith(true);+ expect(JSON.stringify(h.worker.requests)).not.toContain('123456789');+ });++ it('does not revive a cancelled generic request when its private callback arrives late', async () => {+ let receive!: (value: { kind: 'opened' }) => void;+ const waiting = new Promise<{ kind: 'opened' }>((r) => {+ receive = r;+ });+ const finish = vi.fn(),+ dispose = vi.fn();+ const h = harness(true, {+ getCallSessionId: () => 'trusted-session',+ openAuthorization: () => ({ opened: Promise.resolve(), result: waiting, finish, dispose }),+ });+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ const id = h.worker.requests[0].id;+ h.worker.listener?.({+ type: 'plugin-authorize',+ reqId: 'generic',+ rpcId: id,+ request: { kind: 'browser', url: 'https://provider.example/qr' },+ });+ h.calls.get('call-a')!.abort();+ expect(await result).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ receive({ kind: 'opened' });+ await until(() => h.worker.controls.some((x) => x.reqId === 'generic'));+ expect(h.worker.controls.find((x) => x.reqId === 'generic')).toMatchObject({ ok: false });+ expect(dispose).toHaveBeenCalled();+ expect(finish).not.toHaveBeenCalled();+ });++ it('applies the same declared target check to generic browser requests', async () => {+ const open = vi.fn();+ const h = harness(true, { getCallSessionId: () => 'trusted-session', openAuthorization: open });+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ h.worker.listener?.({+ type: 'plugin-authorize',+ reqId: 'generic',+ rpcId: h.worker.requests[0].id,+ request: { kind: 'browser', url: 'https://untrusted.example/qr' },+ });+ expect(open).not.toHaveBeenCalled();+ expect(await result).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ });++ it('rejects an undeclared browser target and cancels the bound request', async () => {+ const open = vi.fn();+ const h = harness(true, {+ getCallSessionId: () => 'trusted-session',+ openDeviceAuthorization: open,+ });+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ h.worker.listener?.({+ type: 'device-authorize',+ reqId: 'untrusted-target',+ rpcId: h.worker.requests[0].id,+ url: 'https://untrusted.example/device',+ });+ expect(h.worker.controls.find((x) => x.reqId === 'untrusted-target')).toMatchObject({+ ok: false,+ });+ expect(open).not.toHaveBeenCalled();+ expect(await result).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ });++ it('binds to Main task identity, rejects unbound/duplicate control frames, and cancels only its child after opened', async () => {+ let input!: Parameters<NonNullable<GhostNodeRuntimeBrokerDeps['openDeviceAuthorization']>>[0];+ const dispose = vi.fn();+ const finish = vi.fn();+ const open = vi.fn((value: typeof input) => {+ input = value;+ return { opened: Promise.resolve(), finish, dispose };+ });+ const h = harness(true, {+ getCallSessionId: (g, id) =>+ g === 'test-plugin' && id === 'call-a' ? 'trusted-session' : null,+ openDeviceAuthorization: open,+ });+ const first = h.request('call-a');+ const second = h.request('call-b');+ await until(() => h.worker.requests.length === 2);+ const [a, b] = h.worker.requests;+ h.spawn(a.id, 'spawn-a');+ h.spawn(b.id, 'spawn-b');+ await until(+ () => h.worker.controls.filter((x) => x.type === 'spawn-child-result').length === 2,+ );+ const frame = {+ type: 'device-authorize',+ reqId: 'authorize-a',+ rpcId: a.id,+ url: 'https://provider.example/device?code=synthetic',+ };+ h.worker.listener?.({ ...frame, reqId: 'forged', rpcId: b.id });+ expect(open).not.toHaveBeenCalled();+ h.worker.listener?.(frame);+ await until(() => h.worker.controls.some((x) => x.reqId === 'authorize-a'));+ expect(h.worker.controls.find((x) => x.reqId === 'authorize-a')).toMatchObject({ ok: true });+ expect(input.sessionId).toBe('trusted-session');+ expect(input.ghost.id).toBe('test-plugin');+ input.assertCurrent();+ h.worker.listener?.({ ...frame, reqId: 'duplicate' });+ expect(open).toHaveBeenCalledTimes(1);+ expect(h.worker.controls.find((x) => x.reqId === 'duplicate')).toMatchObject({ ok: false });+ input.cancel();+ expect(await first).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ expect(dispose).toHaveBeenCalled();+ expect(() => input.assertCurrent()).toThrow();+ expect(h.children[0].killed).toBe(true);+ expect(h.children[1].killed).toBe(false);+ h.worker.stdout.write(+ JSON.stringify({ jsonrpc: '2.0', id: a.id, result: { ok: true } }) + '\n',+ );+ expect(finish).not.toHaveBeenCalled();+ h.worker.stdout.write(+ JSON.stringify({ jsonrpc: '2.0', id: b.id, result: { ok: true } }) + '\n',+ );+ await second;+ });+ it.each([true, false])(+ 'finishes the authorization before invalidating its binding (CLI ok=%s)',+ async (ok) => {+ let assertCurrent!: () => void;+ const finish = vi.fn((value: boolean) => {+ assertCurrent();+ expect(value).toBe(ok);+ });+ const h = harness(true, {+ getCallSessionId: () => 'trusted-session',+ openDeviceAuthorization: (input) => {+ assertCurrent = input.assertCurrent;+ return { opened: Promise.resolve(), finish, dispose: () => {} };+ },+ });+ const result = h.request('call-a');+ await until(() => h.worker.requests.length === 1);+ const id = h.worker.requests[0].id;+ h.worker.listener?.({+ type: 'device-authorize',+ reqId: 'a',+ rpcId: id,+ url: 'https://provider.example/device',+ });+ await until(() => h.worker.controls.some((x) => x.reqId === 'a'));+ h.worker.stdout.write(+ JSON.stringify({+ jsonrpc: '2.0',+ id,+ result: { structuredContent: { ok }, isError: !ok },+ }) + '\n',+ );+ await result;+ expect(finish).toHaveBeenCalledWith(ok);+ expect(() => assertCurrent()).toThrow();+ },+ );+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.tsindex 8e515c0d03..93f4490cb7 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts@@ -121,7 +121,10 @@ describe('Node runtime packaging contract', () => {);// 窄接口冻结挂载,原样模式伪装 argv,不引 child_process 自己生进程。expect(worker).toContain('__CINDY_NODE__');- expect(worker).toContain('Object.freeze({ spawnEntry })');+ // Pin the complete public surface, allowing only formatting differences.+ expect(worker).toMatch(+ /Object\.freeze\(\{\s*spawnEntry,\s*bindDeviceAuthorization: \(\) => deviceAuthorization\.bind\(\),\s*bindAuthorization: \(\) => authorization\.bind\(\)\s*\}\)/,+ );expect(worker).toContain('GHOST_NODE_CHILD_MODE_FLAG');expect(worker).not.toContain("require('node:child_process')");expect(worker).not.toContain("from 'node:child_process'");diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeSecretSetup.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeSecretSetup.test.tsnew file mode 100644index 0000000000..c017d31765--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeSecretSetup.test.ts@@ -0,0 +1,211 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { GhostManifest } from '../../../shared/ghost.js';+import { GhostSetupChangeBus } from '../ghostSetupChangeBus.js';+import { GhostSetupInteractionBridge } from '../ghostSetupInteractionBridge.js';+import { requestNodeSecretSetup } from '../nodeSecretSetup.js';++const aborts: AbortController[] = [];+afterEach(() => {+ aborts.splice(0).forEach((controller) => controller.abort());+});++function harness(force = false, saved?: string) {+ const values = new Map<string, string>(saved ? [['manual_token', saved]] : []);+ const broadcast = vi.fn();+ const bridge = new GhostSetupInteractionBridge({ broadcast });+ const changeBus = new GhostSetupChangeBus();+ const abort = new AbortController();+ aborts.push(abort);+ let current = true;+ const manifest: GhostManifest = {+ schemaVersion: 3,+ kind: 'chip',+ id: 'demo',+ name: 'Demo',+ version: '1.0.0',+ entry: 'main.js',+ settingsHtml: 'settings.html',+ setup: { requires: [] },+ node: {+ entry: 'node/main.cjs',+ entries: ['node/account.cjs'],+ protocol: 'json-rpc-stdio',+ secretBindings: [+ {+ key: 'manual_token',+ label: 'Manual Token',+ entry: 'node/account.cjs',+ methods: ['account/import'],+ hint: 'Create a Token on the website, then fill this protected field.',+ url: 'https://accounts.example.com/tokens',+ },+ { key: 'unrelated', label: 'Other key', methods: ['other/action'] },+ ],+ },+ };+ const store = vi.fn((_: string, key: string, value: string) => {+ values.set(key, value);+ return true;+ });+ const deps = {+ bridge,+ changeBus,+ getManifest: () => manifest,+ secretSaved: (_: string, key: string) => values.has(key),+ storeSecret: store,+ };+ const input = {+ ghostId: 'demo',+ entry: 'node/account.cjs',+ method: 'account/import',+ sessionId: 'task',+ signal: abort.signal,+ force,+ assertCurrent: () => {+ if (!current) throw new Error('STALE');+ },+ };+ const start = () => requestNodeSecretSetup(deps, input);+ const pending = async () => {+ await vi.waitFor(() => expect(bridge.pendingSnapshots()).toHaveLength(1));+ return bridge.pendingSnapshots()[0].request;+ };+ const submit = async (value: string) => {+ const p = await pending();+ return bridge.submitInline(p.requestId, {+ expectedRevision: p.revision,+ actionId: p.steps[0].action!.id,+ value,+ });+ };+ return {+ values,+ bridge,+ broadcast,+ changeBus,+ abort,+ store,+ manifest,+ input,+ start,+ pending,+ submit,+ invalidate: () => {+ current = false;+ },+ };+}++describe('on-demand Node credential card', () => {+ it('uses the exact method/entry declaration while keeping ordinary setup and history unchanged', async () => {+ const h = harness();+ const waiting = h.start();+ const p = await h.pending();+ expect(p.remoteSecret).toBe(true);+ expect(p.steps).toHaveLength(1);+ expect(p.steps[0].action).toMatchObject({+ kind: 'inline_form',+ form: {+ fields: [+ {+ type: 'secret',+ label: 'Manual Token',+ externalLink: { url: 'https://accounts.example.com/tokens' },+ },+ ],+ },+ });+ await h.submit('synthetic-private-token');+ await expect(waiting).resolves.toBe(true);+ expect(h.store).toHaveBeenCalledWith('demo', 'manual_token', 'synthetic-private-token');+ expect(h.manifest.setup).toEqual({ requires: [] });+ expect(JSON.stringify(h.broadcast.mock.calls)).not.toContain('synthetic-private-token');+ expect(JSON.stringify(h.broadcast.mock.calls)).not.toContain('unrelated');+ });++ it('reuses a saved credential without a card unless replacement is explicit', async () => {+ const h = harness(false, 'existing-secret');+ await expect(h.start()).resolves.toBe(true);+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);+ expect(h.store).not.toHaveBeenCalled();+ });++ it('can replace a saved value, including submitting the same value again', async () => {+ const h = harness(true, 'existing-secret');+ const waiting = h.start();+ await h.submit('existing-secret');+ await expect(waiting).resolves.toBe(true);+ expect(h.store).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(h.broadcast.mock.calls)).not.toContain('existing-secret');+ });++ it('cancels without clearing the previous value or committing a late input', async () => {+ const h = harness(true, 'old-secret');+ const waiting = h.start();+ const p = await h.pending();+ h.abort.abort();+ await expect(waiting).resolves.toBe(false);+ expect(+ h.bridge.submitInline(p.requestId, {+ expectedRevision: p.revision,+ actionId: p.steps[0].action!.id,+ value: 'late-secret',+ }),+ ).toBe(false);+ expect(h.values.get('manual_token')).toBe('old-secret');+ expect(h.store).not.toHaveBeenCalled();+ });++ it('rejects another call owner at commit time', async () => {+ const h = harness();+ const waiting = h.start();+ await h.pending();+ h.invalidate();+ await h.submit('must-not-be-written');+ await expect(waiting).resolves.toBe(false);+ expect(h.store).not.toHaveBeenCalled();+ });++ it('rejects an action after its declaration changes instead of writing a different key', async () => {+ const h = harness();+ const waiting = h.start();+ const p = await h.pending();+ h.manifest.node!.secretBindings![0].key = 'replacement';+ h.bridge.submitInline(p.requestId, {+ expectedRevision: p.revision,+ actionId: p.steps[0].action!.id,+ value: 'rejected-secret',+ });+ await vi.waitFor(() =>+ expect(h.bridge.pendingSnapshots()[0].request.steps[0].phase).toBe('failed'),+ );+ expect(h.store).not.toHaveBeenCalled();+ h.abort.abort();+ await waiting;+ });++ it.each(['other/action', 'initialize'])(+ 'does not request a key for unbound method %s',+ async (method) => {+ const h = harness();+ h.input.method = method;+ await expect(h.start()).resolves.toBe(false);+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);+ expect(h.store).not.toHaveBeenCalled();+ },+ );++ it('leaves a failed write retryable and retains the previous credential', async () => {+ const h = harness(true, 'old-secret');+ h.store.mockImplementationOnce(() => false);+ const waiting = h.start();+ await h.submit('new-secret');+ await vi.waitFor(() =>+ expect(h.bridge.pendingSnapshots()[0].request.steps[0].phase).toBe('failed'),+ );+ expect(h.values.get('manual_token')).toBe('old-secret');+ await h.submit('new-secret');+ await expect(waiting).resolves.toBe(true);+ expect(h.values.get('manual_token')).toBe('new-secret');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex 962570041e..f09005bece 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -80,6 +80,93 @@ function makeHarness(opts: {const CALL = { ghostId: 'art', tool: 'gen_image', args: { prompt: '一只猫' } };+describe('caller cancellation', () => {+ it('Host Stop affects only opted-in calls in that session, preserving legacy calls', async () => {+ const h = makeHarness();+ const stopped = h.dispatcher.callGhostTool({ ...CALL, callId: 'stopped', sessionId: 'session-a' });+ const kept = h.dispatcher.callGhostTool({ ...CALL, callId: 'kept', sessionId: 'session-b' });+ const legacy = h.dispatcher.callGhostTool({ ...CALL, callId: 'legacy', sessionId: 'session-a' });+ expect(h.dispatcher.getPendingCallSessionId('art', 'legacy')).toBeNull();+ h.dispatcher.getPendingCallSignal('art', 'stopped');+ const keptSignal = h.dispatcher.getPendingCallSignal('art', 'kept')!;+ h.dispatcher.cancelSessionCalls('session-a');+ expect(await stopped).toMatchObject({ ok: false, message: 'Plugin tool call cancelled' });+ expect(keptSignal.aborted).toBe(false);+ expect(h.dispatcher.pendingCount()).toBe(2);+ h.dispatcher.handleToolResult('art', { callId: 'legacy', ok: true, result: 'legacy-kept' });+ expect(await legacy).toEqual({ ok: true, result: 'legacy-kept' });+ h.dispatcher.cancelSessionCalls('session-b');+ expect(await kept).toMatchObject({ ok: false });+ expect(h.dispatcher.pendingCount()).toBe(0);+ });++ it('cancels one call without ending another call to the same plugin', async () => {+ const h = makeHarness();+ const a = new AbortController();+ const first = h.dispatcher.callGhostTool({ ...CALL, callId: 'call-1', signal: a.signal });+ const second = h.dispatcher.callGhostTool({ ...CALL, callId: 'call-2' });+ const firstLifetime = h.dispatcher.getPendingCallSignal('art', 'call-1')!;+ const secondLifetime = h.dispatcher.getPendingCallSignal('art', 'call-2')!;+ expect(h.dispatcher.getPendingCallSignal('other-plugin', 'call-1')).toBeNull();+ expect(h.dispatcher.getPendingCallSessionId('other-plugin', 'call-1')).toBeNull();+ expect(h.dispatcher.getPendingCallSessionId('art', 'missing')).toBeNull();+ a.abort();+ expect(await first).toMatchObject({ ok: false, message: 'Plugin tool call cancelled' });+ expect(firstLifetime.aborted).toBe(true);+ expect(secondLifetime.aborted).toBe(false);+ expect(h.dispatcher.pendingCount()).toBe(1);+ expect(h.dispatcher.handleToolResult('art', { callId: 'call-1', ok: true, result: 'late' }).accepted).toBe(false);+ h.dispatcher.handleToolResult('art', { callId: 'call-2', ok: true, result: 'kept' });+ expect(await second).toEqual({ ok: true, result: 'kept' });+ expect(secondLifetime.aborted).toBe(true);+ });++ it.each(['before', 'during'] as const)('preserves legacy dispatch when MCP aborts %s startup', async when => {+ const h = makeHarness({ state: 'stopped' as GhostRuntimeState });+ const abort = new AbortController(), gate = deferred();+ if (when === 'before') abort.abort();+ h.deps.spawn.mockImplementation(async () => { await gate.promise; return { ok: true }; });+ const pending = h.dispatcher.callGhostTool({ ...CALL, callId: 'legacy', signal: abort.signal, sessionId: 'task' });+ abort.abort();+ h.dispatcher.cancelSessionCalls('task');+ gate.resolve();+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));+ h.dispatcher.handleToolResult('art', { callId: 'legacy', ok: true, result: 'kept' });+ expect(await pending).toEqual({ ok: true, result: 'kept' });+ });++ it('rejects late opt-in after Host Stop while the sandbox was starting', async () => {+ const h = makeHarness();+ h.deps.runtimeStateOf.mockReturnValue('off');+ let started!: () => void;+ h.deps.spawn.mockImplementation(() => new Promise(resolve => {+ started = () => resolve({ ok: true });+ }));+ const pending = h.dispatcher.callGhostTool({ ...CALL, callId: 'stopped-before-binding', sessionId: 'stopped' });+ h.dispatcher.cancelSessionCalls('stopped');+ started();+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));+ expect(h.dispatcher.getPendingCallSignal('art', 'stopped-before-binding')).toBeNull();+ await expect(pending).resolves.toMatchObject({ ok: false, message: 'Plugin tool call cancelled' });++ // Stop belongs to that invocation, not future turns reusing the session.+ h.deps.runtimeStateOf.mockReturnValue('running');+ const next = h.dispatcher.callGhostTool({ ...CALL, callId: 'new-turn', sessionId: 'stopped' });+ expect(h.dispatcher.getPendingCallSignal('art', 'new-turn')?.aborted).toBe(false);+ h.dispatcher.handleToolResult('art', { callId: 'new-turn', ok: true, result: 'done' });+ await expect(next).resolves.toMatchObject({ ok: true });+ });++ it('rejects a new cancellation binding if its original MCP call was already aborted', async () => {+ const h = makeHarness(), abort = new AbortController();+ const pending = h.dispatcher.callGhostTool({ ...CALL, callId: 'late-bind', signal: abort.signal });+ abort.abort();+ expect(h.dispatcher.getPendingCallSignal('art', 'late-bind')).toBeNull();+ expect(await pending).toMatchObject({ ok: false, message: 'Plugin tool call cancelled' });+ expect(h.dispatcher.pendingCount()).toBe(0);+ });+});+describe('资格审(结构化错误分类)', () => {it('未装入 → GHOST_NOT_FOUND', async () => {const h = makeHarness({ ghost: null });diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 02f0a08a41..54afdfd0b7 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3915,6 +3915,8 @@ readline.createInterface({ input: process.stdin }).on('line', async (line) => {\`\`\`jsconst response = await cindy.node.request({method: 'taptap/connect',+ callId: msg.callId, // tool-call 内透传+ cancelWithCall: true, // 显式启用授权卡和随调用结束的生命周期params: { projectId: 'demo' },timeoutMs: 30000 // 可选 1000–120000,缺省 30000});@@ -3922,6 +3924,12 @@ if (!response.ok) throw new Error(response.message);const result = response.result;\`\`\`+当前工具触发的登录等前台请求应同时传入 \`cancelWithCall: true\` 和主机下发的+\`callId\`。显式启用后,主机只接受当前插件的在途调用;取消、超时或交卷后,该+Node 请求及其子进程一并结束,晚到的授权或子进程启动会被拒绝。只传旧 \`callId\`+或不启用开关都保持既有独立 RPC 生命周期,不自动弹授权卡、不回收后台进程;+设置页等无 tool-call 的入口不能伪造或复用调用编号。+#### Node Worker 的持久化凭证绑定本地 IMAP/SMTP 等协议确实需要 Worker 使用凭证明文时,在@@ -3957,8 +3965,17 @@ const authorizationCode = request.cindy.secrets.mail_code;- \`secretBindings\` 最多 4 条,每条 \`methods\` 1–16 个;省略 \`entry\`只绑定主入口,不能借同名方法把凭证送去其它入口;-- 未保存凭证时宿主在请求进入 Worker 前返回 \`PERMISSION_DENIED\`,设置页可用- \`GET /secrets\` 的 saved 状态引导用户;+- 在途工具调用显式携带 \`cancelWithCall: true\` 和 \`callId\` 时,缺少本次方法/入口声明的手动凭证会先显示既有保密输入卡,+ 远程任务复用签名加密输入桥;用户提交后才进入 Worker。显式登录或更换 Token 可带+ \`promptSecrets: true\`(要求上述显式生命周期开关),即使已保存也重新显示卡片;取消不清除原凭证。+ 没有在途调用或旧 Host 不支持此接线时仍返回 \`PERMISSION_DENIED\`,不会回退到聊天收取+ Token。设置页继续使用 \`/secrets\`,不要把输入放入业务 RPC 或 BroadcastChannel;+ 完成本次卡片提交后,Host 在 Worker 私有 \`request.cindy.secretInputCompleted\` 标记+ \`true\`。要求本次人工填写的登录方法必须检查该标记;旧 Host 缺标记时拒绝执行,不能+ 因其忽略新请求字段而静默复用旧 Token;标记不能由插件 main.js 自报;+- 若手动凭证只用于登录方法,可用 \`setup: { requires: [] }\` 保留既有 CLI 登录及其它工具,+ 由具体绑定方法触发卡片。此配置就绪仅表示凭证已保存;插件还需执行最小只读权限验证。+ 这个增量只涉及插件→本机 Host 的 Node 请求;远程卡片和输入协议不增加字段;- 宿主不会直接把明文交给 \`main.js\`、Agent 参数或写入宿主日志;但 Worker收到明文后可以主动回传、落盘或写日志,浏览器侧代码和 Agent 也可能因此间接获得它。插件详情的能力清单会逐条披露此风险,只安装可信来源插件;@@ -4101,6 +4118,59 @@ const maker = require('@taptap/maker'); // 之后它的自启动全部走了正但**只适合文本/协议流**,别拿它传大文件;- 级联生死:worker 退出/被停/插件停用,子进程一并收掉,不留孤儿。+### 4.12.5 随包 CLI 的登录授权卡片++优先调用通用 \`globalThis.__CINDY_NODE__.bindAuthorization()\`。在**当前 JSON-RPC 请求处理函数内**+同步捕获返回的 authorize 函数,再交给 CLI 输出/浏览器启动回调。调用方必须以+\`cancelWithCall: true\` 显式启用;它只绑定这一次仍在途的 \`callId\`,不允许后台启动或复用。可传入的请求为:++\`\`\`ts+type AuthorizationRequest =+ | { kind: 'device'; url: string; userCode?: string; expiresAt?: number }+ | { kind: 'browser'; url: string; expiresAt?: number }+ | { kind: 'loopback'; url: string; callbackUrl: string; state: string };+// device/browser 只表示页面已打开;之后原 CLI 继续轮询、保存、校验。+// loopback 远程回 {kind:'callback', state, code} 或 {kind:'callback', state, error};+// 本机回 {kind:'opened'},原 CLI 自有 localhost listener 接受浏览器回调。+const authorize = globalThis.__CINDY_NODE__?.bindAuthorization();+if (!authorize) throw new Error('Authorization cards unavailable');+const result = await authorize({ kind: 'device', url: verificationUri,+ userCode, expiresAt: Date.now() + expiresInSeconds * 1000 });+// 由现有 provider SDK/CLI 完成后续操作;RPC 成功必须晚于实际领取/保存/校验。+\`\`\`++\`browser\` 用于上游提供 HTTPS 确认页的扫码或浏览器确认,不传二维码图片、Cookie、+账号密码或任意 CLI 命令。\`device\` 的 userCode 原样保留(1–32 位字母/数字/空格/连字符),+不把私有 device_code 当用户码。expiresAt 是绝对毫秒时间且不能延长宿主五分钟上限。+目标必须命中已安装插件的 OAuth origin / network hosts;GitHub/TapTap 继续用已审查的精确规则。++\`loopback\` 只支持原 CLI 的 Authorization Code + PKCE S256:url 内唯一 state、redirect_uri、+response_type=code、client_id、code_challenge 与 code_challenge_method=S256 必须完整;+callbackUrl 必须与 redirect_uri 精确相等,且为 localhost、127.0.0.1 或 [::1] 的显式非特权+端口 HTTP URL。不能改写上游登记的 redirect、降低 PKCE 或抢占别人端口。verifier 留在源 CLI;+远程 callback 只经 bootstrap 私有 Promise 交给这一次可信 Node 调用,用原 provider SDK+交换,不经 stdout/main.js/Agent。既有 CLI 若仅有固定监听器,需要在其受审查适配器内消费+此私有结果;Host 不代发任意 HTTP。不要把 callback code 放到 argv、日志或 RPC 结果。++普通 API Key/PAT 不走这个 Node 接口:沿用 \`network.secrets\` / \`node.secretBindings\`+声明,由 Host 原密码卡收集,远程端支持时经签名输入桥直接写对应 vault key。插件不读取输入,+不要求用户把密钥发给模型。保存只证明配置已落地,上游权限由实际业务调用核验。++兼容入口继续保留:++当第三方 CLI 使用「浏览器授权、发起端轮询」时,Node worker 可在**当前请求处理函数内**+捕获 \`globalThis.__CINDY_NODE__.bindDeviceAuthorization()\` 返回的函数,再在 CLI 输出回调+里调用 \`await authorize(httpsUrl)\`。同一请求只接受一个链接。Node 请求必须带来自当前+\`tool-call\` 的 \`callId\`,并显式设置 \`cancelWithCall: true\`;宿主反查插件、任务和 owner,插件不能自选任务。无绑定时返回+undefined;不支持时明确报错,远程流程不能回退到在执行设备开浏览器或把链接交给模型。++宿主创建含真实授权域名的卡片,用户点击后由当前设备的可信 Host 打开链接。远程链接只走既有+加密授权事务;这个 Promise 只代表浏览器已打开,**不代表登录完成**。CLI 仍在原设备轮询,+凭据由原 CLI 保存;Node RPC 只有在真实领取/保存和检查完成后才返回成功。取消卡片/任务、+断开控制端或事务到期会取消该 Node RPC 及其绑定子进程。不要把 URL、轮询码或 token 放进+stdout 的 RPC 结果、通知、模型回复或错误;业务状态返回固定摘要。此卡片不改变 Host 的+network setup/readiness,不能拿 CLI 的登录结果冒充宿主凭据配置已完成。+## 4.13 会话上下文(sessionContext 能力)围着用户项目干活的插件(构建/检查/同步类)需要知道"现在是哪个会话、项目在哪个diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.tsindex a16119eee4..925fe503e3 100644--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts@@ -873,6 +873,7 @@ export class GhostOauthAccountManager {deliveryHosts?: readonly string[];/** Main-only handoff for reopening the current authorization page. */onAuthorizationUrl?: (url: string) => void;+ remote?: import('../plugin-oauth/context.js').RemoteOauthContext;/** Main-only caller boundary, checked inside the credential mutation lock. */assertCurrent?: () => void;beforeCommit?: () => Promise<void>;@@ -923,6 +924,7 @@ export class GhostOauthAccountManager {const flow = await startGhostOauthFlow({config,+ remote: opts?.remote,openExternal: (url) => { opts?.onAuthorizationUrl?.(url); return this.deps.openExternal(url); },fetchImpl: this.deps.fetchImpl,broker: this.deps.broker,@@ -935,6 +937,7 @@ export class GhostOauthAccountManager {reclaimPort: isFirstPartyHostPrivilegeGhostId(ghostId) ? this.deps.reclaimPort : undefined,});if (!flow.ok) return { ok: false, error: flow.error, detail: flow.detail };+ opts?.remote?.assertCurrent();if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) {return {ok: false,@@ -977,6 +980,7 @@ export class GhostOauthAccountManager {return this.withMutationLock(ghostId, async () => {await opts?.beforeCommit?.();opts?.assertCurrent?.();+ opts?.remote?.assertCurrent();// Identity/avatar fetches are asynchronous as well. Recheck inside the// same strict mutation lock as the first vault read/write so a package// update cannot replace the declaration between validation and commit.@@ -1067,6 +1071,7 @@ export class GhostOauthAccountManager {secretKey,accountId: existing.id,});+ opts?.remote?.finish(true);this.notifyConnected(ghostId, secretKey, existing.displayLabel ?? existing.label);return {ok: true,@@ -1131,6 +1136,7 @@ export class GhostOauthAccountManager {secretKey,accountId: account.id,});+ opts?.remote?.finish(true);this.notifyConnected(ghostId, secretKey, account.displayLabel ?? account.label);return {ok: true,diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.tsindex 343d724b47..16fc3ebbe7 100644--- a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts+++ b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts@@ -235,6 +235,8 @@ export interface GhostOauthLogger {}export interface StartGhostOauthFlowOptions {+ /** Main-only transaction, never a plugin/Renderer-supplied URL. */+ remote?: import('../plugin-oauth/context.js').RemoteOauthContext;config: GhostOauthClientConfig;/** 拉起系统浏览器(生产注入 shell.openExternal)。 */openExternal(url: string): void | Promise<void>;@@ -393,6 +395,9 @@ function isInvalidGrant(text: string | null): boolean {/** 在途单作废钩子:同一时刻只允许一单,后来者顶掉前一单(CANCELLED 收场)。 */let activeAbort: (() => void) | null = null;+// Remote transactions have their own cancellation boundary. A second controller+// must never supersede another controller's authorization.+const remoteAborts = new Set<() => void>();/*** 前一单**完整收尾**(含 loopback 监听真正关闭)的信号。close 是异步的,@@ -404,6 +409,7 @@ let activeSettled: Promise<void> | null = null;/** 外部主动取消当前在途授权(用户关设置页 / 换意识时调用;无在途时是空操作)。 */export function cancelActiveGhostOauthFlow(): void {activeAbort?.();+ for (const abort of remoteAborts) abort();}/**@@ -451,18 +457,22 @@ export async function startGhostOauthFlow(const cancelledPromise = new Promise<'cancelled'>((resolve) => {signalCancelled = () => {cancelledFlag = true;+ opts.remote?.finish(false);resolve('cancelled');};});- activeAbort?.();- activeAbort = signalCancelled;+ if (opts.remote) remoteAborts.add(signalCancelled);+ else {+ activeAbort?.();+ activeAbort = signalCancelled;+ }const cancellation: FlowCancellation = {cancelledPromise,isCancelled: () => cancelledFlag,myAbort: signalCancelled,};- const prior = activeSettled;+ const prior = opts.remote ? null : activeSettled;const run = (async (): Promise<GhostOauthFlowResult> => {// 等前一单**完整**收尾(含监听真正关闭)再起本单;排队期间被顶掉/取消// 就直接收场,不去抢端口。@@ -472,6 +482,22 @@ export async function startGhostOauthFlow(})();// 同步挂链:第三单在本单尚未真正跑起来时进场,也严格排到本单之后——// 任意时刻至多一单持有监听,不存在两单并发抢同一钉死端口的窗口。+ if (opts.remote) {+ try {+ const result = await run;+ if (!result.ok) {+ opts.remote.finish(false);+ // Provider errors may echo a code/token. Never publish their detail.+ return { ok: false, error: result.error };+ }+ return result;+ } catch {+ opts.remote.finish(false);+ return { ok: false, error: 'CANCELLED' };+ } finally {+ remoteAborts.delete(signalCancelled);+ }+ }activeSettled = run.then(() => undefined,() => undefined,@@ -492,7 +518,12 @@ async function runGhostOauthFlow(opts: StartGhostOauthFlowOptions,cancellation: FlowCancellation,): Promise<GhostOauthFlowResult> {- const { config, openExternal, fetchImpl, logger } = opts;+ const { config, openExternal, fetchImpl } = opts;+ // Remote metadata must not echo provider-controlled responses into logs.+ const logger: GhostOauthLogger | undefined = opts.remote && opts.logger ? {+ info: message => opts.logger!.info(message),+ warn: message => opts.logger!.warn(message),+ } : opts.logger;const timeoutMs = opts.timeoutMs ?? FLOW_TIMEOUT_DEFAULT_MS;const brandName = opts.brandName ?? 'Cindy';@@ -530,7 +561,7 @@ async function runGhostOauthFlow(} catch (err) {listenErr = err;}- if (!listener && config.redirectPort && opts.reclaimPort) {+ if (!listener && config.redirectPort && opts.reclaimPort && !opts.remote) {logger?.warn('ghost oauth 钉死端口被占,尝试自动回收', { port: config.redirectPort });const reclaimed = await opts.reclaimPort(config.redirectPort).catch(() => false);if (reclaimed) {@@ -602,6 +633,7 @@ async function runGhostOauthFlow(};const corsAllowlist = ghostCallbackCorsAllowlist(config);server.on('request', (req, res) => {+ if (opts.remote) { res.writeHead(404); res.end(); return; }// 页面语言按浏览器 Accept-Language 就近命中(zh/ja/ko, 缺省英文)const lang = pickOAuthResultPageLang(typeof req.headers['accept-language'] === 'string'@@ -678,18 +710,37 @@ async function runGhostOauthFlow(timeoutHandle = setTimeout(() => resolve('timeout'), timeoutMs);});+ const remoteAbort = new AbortController();+ let callbackReceived = false;try {// listen / 回收期间已被顶掉或取消:别再拉浏览器弹无主的授权页。if (cancellation.isCancelled()) return { ok: false, error: 'CANCELLED' };- await openExternal(authorizeUrl.toString());- logger?.info('ghost oauth 授权页已拉起', { host: authorizeUrl.hostname, port });+ opts.remote?.assertCurrent();+ if (opts.remote) await new Promise<void>(resolve => server.close(() => resolve()));+ // Reserve the same redirect port on both hosts. The controller never kills a port owner.+ const remoteCallback = opts.remote?.authorize({+ authorizeUrl: authorizeUrl.toString(), callbackUrl: `http://127.0.0.1:${port}${callbackPath}`,+ state, corsOrigins: [...ghostCallbackCorsAllowlist(config).origins],+ corsHosts: [...(config.corsDeliveryHosts ?? [])],+ }, remoteAbort.signal).then(value => {+ opts.remote?.assertCurrent();+ if (value.state !== state) return { kind: 'invalid' as const, detail: 'remote callback rejected' };+ return 'code' in value ? { kind: 'code' as const, code: value.code } :+ { kind: 'invalid' as const, detail: 'remote authorization denied' };+ });+ if (!opts.remote) await openExternal(authorizeUrl.toString());+ logger?.info(opts.remote ? 'ghost oauth 等待控制端授权' : 'ghost oauth 授权页已拉起', {+ host: authorizeUrl.hostname, port,+ });- const outcome = await Promise.race([callback, timeout, cancellation.cancelledPromise]);+ const outcome = await Promise.race([remoteCallback ?? callback, timeout, cancellation.cancelledPromise]);if (outcome === 'timeout') return { ok: false, error: 'TIMEOUT' };if (outcome === 'cancelled') return { ok: false, error: 'CANCELLED' };if (outcome.kind === 'invalid')return { ok: false, error: 'CALLBACK_INVALID', detail: outcome.detail };+ callbackReceived = true;+ opts.remote?.assertCurrent();// broker 模式:code 交换交给 XDT server(secret 在服务端),不直连 tokenUrl。if (config.tokenBroker && opts.broker) {@@ -698,6 +749,7 @@ async function runGhostOauthFlow(redirectUri,...(verifier !== null ? { codeVerifier: verifier } : {}),});+ opts.remote?.assertCurrent();if (!brokered.ok) {logger?.warn('ghost oauth broker 交换失败', {slug: config.tokenBroker,@@ -745,6 +797,7 @@ async function runGhostOauthFlow(}const text = await readBoundedText(res);+ opts.remote?.assertCurrent();if (!res.ok) {const detail = summarizeTokenError(res.status, text);logger?.warn('ghost oauth token 交换被拒', {@@ -768,6 +821,7 @@ async function runGhostOauthFlow(});return { ok: true, bundle };} finally {+ if (!callbackReceived) remoteAbort.abort();if (timeoutHandle !== undefined) clearTimeout(timeoutHandle);// 只清自己那单的取消钩子:单 A 被单 B 顶掉后,A 的 finally 晚到,不能把// B 刚注册的 activeAbort 抹成 null(否则 B 变成"取消不掉的孤儿单")。diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupConnectionExecutor.ts b/apps/desktop/src/main/cindy-brain/ghostSetupConnectionExecutor.tsnew file mode 100644index 0000000000..db8f3ec51d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostSetupConnectionExecutor.ts@@ -0,0 +1,58 @@+import { parsePluginConnectionInput, type PluginConnectionInput } from '@cindy/device-link';+import type { GhostManifest, GhostSetupAssessment } from '../../shared/ghost.js';+import type { GhostConnectionManager } from './ghostConnections.js';+import { getRemoteOauthContext } from '../plugin-oauth/context.js';++export interface GhostSetupConnectionExecutorDeps {+ getManifest(ghostId: string): GhostManifest | null;+ getAssessment(ghostId: string): GhostSetupAssessment;+ manager: Pick<GhostConnectionManager, 'upsert'>;+ emitChange(ghostId: string, key: string): void;+}+/** Dedicated authenticated form. Never accepts a caller-selected vault key or inject header. */+export function executeGhostSetupConnectionSubmission(+ deps: GhostSetupConnectionExecutorDeps,+ args: {+ ghostId: string;+ actionId: string;+ expectedManifest: string;+ value: PluginConnectionInput;+ /** Main-only callback bound to the still-current card, before revision broadcasts. */+ onCommitted?(): void;+ },+): boolean {+ const remote = getRemoteOauthContext();+ if (!remote?.submitConnection) return false;+ remote.assertCurrent();+ const value = parsePluginConnectionInput(args.value);+ const manifest = deps.getManifest(args.ghostId);+ if (!manifest || JSON.stringify(manifest) !== args.expectedManifest) return false;+ const assessment = deps.getAssessment(args.ghostId);+ // The signed bridge already requires a live exact-revision action card. Its+ // explicit reconnect may legitimately target an existing connection.+ const item = assessment.groups+ .flatMap((g) => g.items)+ .find(+ (i) =>+ i.kind === 'connection' &&+ i.actions.some((a) => a.kind === 'manage_connection' && a.id === args.actionId),+ );+ if (!item?.ref.startsWith('connection:')) return false;+ const key = item.ref.slice('connection:'.length);+ const decl = manifest.network?.connections?.find((c) => c.key === key);+ if (!decl || args.actionId !== `manage_connection:connection:${key}`) return false;+ // User typed this exact host in the trusted Desktop form. The plugin iframe+ // cannot submit this channel. Its existing settings confirmation stays intact.+ remote.assertCurrent();+ const result = deps.manager.upsert(args.ghostId, key, {+ ...value,+ max: decl.maxConnections ?? 8,+ });+ if (!result.ok) return false;+ // Synchronous vault write completed under the same owner/card fence. Mark only+ // configuration saved; a subsequent real provider call proves account access.+ remote.finish(true);+ args.onCommitted?.();+ deps.emitChange(args.ghostId, key);+ return true;+}diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.tsindex cc0371a50e..39220c60cc 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts@@ -8,6 +8,7 @@import { randomUUID } from 'node:crypto';+import { getRemoteOauthContext } from '../plugin-oauth/context.js';import type {GhostSetupAllowedAction,GhostSetupAssessment,@@ -63,7 +64,24 @@ export type GhostSetupActionResult =message?: string;};+/** Main-only capability for one card submission; never serialized to an IPC or model. */+export interface GhostSetupInlineCommit {+ readonly replaceExisting: boolean;+ assertCurrent(ghostId: string, actionId: string, requirementRef: string): void;+ /** Called only after the vault write, before readiness/change broadcasts. */+ onCommitted(): void;+}++export interface GhostSetupInlineActionInput {+ sessionId: string;+ ghostId: string;+ action: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }>;+ value: string;+ commit?: GhostSetupInlineCommit;+}+export interface GhostSetupCoordinatorDeps {+ remoteConnection?: true;changeBus: GhostSetupChangeBus;bridge: GhostSetupInteractionBridge;assess: (ghostId: string) => Promise<GhostSetupAssessment> | GhostSetupAssessment;@@ -83,12 +101,7 @@ export interface GhostSetupCoordinatorDeps {action: GhostSetupAllowedAction;responseTarget?: GhostSetupInteractionResponseTarget;}) => Promise<GhostSetupActionResult>;- executeInlineAction?: (args: {- sessionId: string;- ghostId: string;- action: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }>;- value: string;- }) => Promise<GhostSetupActionResult>;+ executeInlineAction?: (args: GhostSetupInlineActionInput) => Promise<GhostSetupActionResult>;timeoutMs?: number;terminalGraceMs?: number;timeoutMessage?: () => string;@@ -106,6 +119,10 @@ export interface GhostSetupEnsureRequest {/** Captured call scope; revalidated after every setup/policy change. */workingDir?: string | null;plan?: GhostSetupPlan;+ /** Explicit credential reconfiguration; never removes the existing value first. */+ reauthorize?: boolean;+ /** The original MCP call owns this waiter, including while its card is open. */+ signal?: AbortSignal;}const DEFAULT_SETUP_TIMEOUT_MS = 10 * 60 * 1000;@@ -131,15 +148,25 @@ export class GhostSetupCoordinator {}async ensureReady(request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> {+ const cancelled = (): GhostSetupEnsureResult => ({+ ok: false, errorCode: 'SETUP_CANCELLED', message: 'Plugin setup was cancelled; no plugin operation was executed.',+ });+ if (request.signal?.aborted) return cancelled();let assessment: GhostSetupAssessment;let unsubscribe = () => {};let wakeVerify: (() => void) | null = null;let assessmentDirty = false;+ const reconnectedActions = new Set<string>();+ let localConnectionAction: { id: string; ref: string; revision: number } | undefined;// Subscribe before the initial read. A committed settings write racing the// first assessment will then keep the read loop running until one complete// assessment observes a quiet revision.- unsubscribe = this.deps.changeBus.subscribe(request.ghostId, () => {+ unsubscribe = this.deps.changeBus.subscribe(request.ghostId, event => {+ if (localConnectionAction && event.source === 'connection' && event.ref === localConnectionAction.ref &&+ event.revision > localConnectionAction.revision) {+ reconnectedActions.add(localConnectionAction.id);+ }assessmentDirty = true;if (wakeVerify) wakeVerify();});@@ -177,8 +204,15 @@ export class GhostSetupCoordinator {// ready 态的重连建议是非阻塞的:仅 Agent 主动带 plan 且本回合有交互面时才进// 卡流程;无 sessionId 的回合(IM/定时任务)丢弃 plan 直接放行,绝不把 ready// 插件拦成 SETUP_REQUIRED。+ if (request.signal?.aborted) {+ unsubscribe();+ return cancelled();+ }+ const requestedReauth = (next: GhostSetupAssessment): GhostSetupAssessment | null =>+ toReauthInteractionAssessment(next) ??+ (request.reauthorize ? toExplicitReauthInteractionAssessment(next, reconnectedActions) : null);const reauthAssessment =- request.plan && request.sessionId ? toReauthInteractionAssessment(assessment) : null;+ (request.plan || request.reauthorize) && request.sessionId ? requestedReauth(assessment) : null;const reauthMode = reauthAssessment !== null;if (assessment.state === 'ready' && !reauthMode) {unsubscribe();@@ -212,6 +246,8 @@ export class GhostSetupCoordinator {? validateReauthPlan(request.plan, assessment): validatePlan(request.plan, assessment)) ?? defaultPlan(assessment);let snapshot = toSnapshot(requestId, identity, assessment, plan);+ if (this.deps.executeInlineAction) snapshot.remoteSecret = true;+ if (this.deps.remoteConnection) snapshot.remoteConnection = true;let settled = false;let verifying: Promise<void> | null = null;let timeoutId: ReturnType<typeof setTimeout> | null = null;@@ -226,6 +262,7 @@ export class GhostSetupCoordinator {): void => {if (settled) return;settled = true;+ request.signal?.removeEventListener('abort', onAbort);unsubscribe();if (timeoutId) clearTimeout(timeoutId);// The terminal card may remain visible for a short grace period, but@@ -271,6 +308,8 @@ export class GhostSetupCoordinator {activeActionId,allPendingSteps,});+ if (this.deps.executeInlineAction) snapshot.remoteSecret = true;+ if (this.deps.remoteConnection) snapshot.remoteConnection = true;this.deps.bridge.update(snapshot);};@@ -321,7 +360,7 @@ export class GhostSetupCoordinator {return;}const next = current.assessment;- const nextReauthAssessment = reauthMode ? toReauthInteractionAssessment(next) : null;+ const nextReauthAssessment = reauthMode ? requestedReauth(next) : null;if (next.state === 'ready' && !nextReauthAssessment) {publishSatisfied(next);settle({ ok: true, assessment: next }, 'ready');@@ -344,64 +383,80 @@ export class GhostSetupCoordinator {expectedRevision: number,responseTarget?: GhostSetupInteractionResponseTarget,): Promise<void> => {- if (settled) return;- if (expectedRevision !== snapshot.revision) {- await verify();- return;- }- const target = this.deps.validateTarget(request.ghostId, request.tool, request.workingDir);- if (!target.ok) {- settleTargetFailure(target);- return;- }- const action = findAllowedAction(assessment, actionId);- if (!action) {- await verify();- return;- }- activeActionId = action.id;- publish(assessment, 'action_running');- // OAuth is a Host-global flow and remains shared. Navigation actions- // belong to a session + responding window: two sessions displayed in- // one window must each receive a route carrying its own sessionId.- const flightScope =- action.kind === 'oauth_connect'- ? 'shared'- : responseTarget- ? `session:${sessionId}:target:${responseTarget.id}`- : `session:${sessionId}`;- const flightKey = `${request.ghostId}\u0000${action.id}\u0000${flightScope}`;- let flight = this.actionFlights.get(flightKey);- if (!flight) {- flight = this.trackAction(- this.deps- .executeAction({- sessionId,- ghostId: request.ghostId,- action,- ...(responseTarget ? { responseTarget } : {}),- })- .finally(() => this.actionFlights.delete(flightKey)),- );- this.actionFlights.set(flightKey, flight);- }- let result: GhostSetupActionResult;+ const remoteOauth = getRemoteOauthContext();try {- result = await flight;- } catch (error) {- result = {- ok: false,- errorCode: 'ACTION_FAILED',- message: error instanceof Error ? error.message : '插件设置操作失败',- };- }- if (settled) return;- if (!result.ok) {- publish(assessment, 'failed', result.errorCode ?? 'ACTION_FAILED');- return;+ if (settled) return;+ if (expectedRevision !== snapshot.revision) {+ await verify();+ return;+ }+ const target = this.deps.validateTarget(request.ghostId, request.tool, request.workingDir);+ if (!target.ok) {+ settleTargetFailure(target);+ return;+ }+ const action = findAllowedAction(assessment, actionId);+ if (!action) {+ await verify();+ return;+ }+ activeActionId = action.id;+ if (action.kind === 'manage_connection' && !remoteOauth) {+ localConnectionAction = { id: action.id, ref: action.id.slice('manage_connection:connection:'.length),+ revision: this.deps.changeBus.currentRevision(request.ghostId) };+ }+ publish(assessment, 'action_running');+ // Local OAuth actions remain shared; remote ones belong to their transaction. Navigation actions+ // belong to a session + responding window: two sessions displayed in+ // one window must each receive a route carrying its own sessionId.+ const flightScope =+ action.kind === 'oauth_connect'+ ? (getRemoteOauthContext()?.scope ?? 'shared')+ : responseTarget+ ? `session:${sessionId}:target:${responseTarget.id}`+ : `session:${sessionId}`;+ const flightKey = `${request.ghostId}\u0000${action.id}\u0000${flightScope}`;+ let flight = this.actionFlights.get(flightKey);+ if (!flight) {+ flight = this.trackAction(+ this.deps+ .executeAction({+ sessionId,+ ghostId: request.ghostId,+ action,+ ...(responseTarget ? { responseTarget } : {}),+ })+ .finally(() => this.actionFlights.delete(flightKey)),+ );+ this.actionFlights.set(flightKey, flight);+ }+ let result: GhostSetupActionResult;+ try {+ result = await flight;+ } catch (error) {+ result = {+ ok: false,+ errorCode: 'ACTION_FAILED',+ message: error instanceof Error ? error.message : '插件设置操作失败',+ };+ }+ if (settled) return;+ if (!result.ok) {+ if (localConnectionAction?.id === action.id) localConnectionAction = undefined;+ publish(assessment, 'failed', result.errorCode ?? 'ACTION_FAILED');+ return;+ }+ if (action.kind === 'oauth_connect') {+ reconnectedActions.add(action.id);+ assessmentDirty = true;+ }+ if (result.waitingExternal) publish(assessment, 'waiting_external');+ await verify(result.waitingExternal ? 'waiting_external' : undefined);+ } finally {+ // Success is sealed at credential commit, before readiness broadcasts.+ // Early validation/action failures must also settle the remote request.+ remoteOauth?.finish(false);}- if (result.waitingExternal) publish(assessment, 'waiting_external');- await verify(result.waitingExternal ? 'waiting_external' : undefined);};const onCommand = async (@@ -428,7 +483,7 @@ export class GhostSetupCoordinator {await runAction(command.actionId, command.expectedRevision, responseTarget);};- const submitInline = async (submit: {+ const submitInlineCurrent = async (submit: {actionId: string;expectedRevision: number;value: string;@@ -454,9 +509,29 @@ export class GhostSetupCoordinator {await verify();return;}+ const boundItem = assessment.groups.flatMap(group => group.items)+ .find(item => item.actions.some(candidate => candidate.id === action.id));+ if (!boundItem) return;inlineSubmitting = true;activeActionId = action.id;publish(assessment, 'action_running');+ let committed = false;+ const commit: GhostSetupInlineCommit = {+ replaceExisting: request.reauthorize === true && reauthMode,+ assertCurrent: (ghostId, actionId, requirementRef) => {+ if (settled || committed || request.signal?.aborted || !inlineSubmitting ||+ activeActionId !== action.id || ghostId !== request.ghostId ||+ actionId !== action.id || requirementRef !== boundItem.ref ||+ !this.deps.validateTarget(request.ghostId, request.tool, request.workingDir).ok) {+ throw new Error('PLUGIN_SETUP_INLINE_STALE');+ }+ },+ onCommitted: () => {+ committed = true;+ reconnectedActions.add(action.id);+ assessmentDirty = true;+ },+ };let result: GhostSetupActionResult;try {result = this.deps.executeInlineAction@@ -466,6 +541,7 @@ export class GhostSetupCoordinator {ghostId: request.ghostId,action,value: submit.value,+ commit,}),): {@@ -490,12 +566,32 @@ export class GhostSetupCoordinator {await verify();};+ const submitInline = async (submit: Parameters<typeof submitInlineCurrent>[0]): Promise<void> => {+ const remote = getRemoteOauthContext();+ try { remote?.assertCurrent(); await submitInlineCurrent(submit); }+ finally { remote?.finish(false); }+ };++ const onAbort = (): void => {+ publish(assessment, 'cancelled', undefined, true);+ settle(cancelled(), 'cancelled', 0);+ };try {- this.deps.bridge.open(sessionId, snapshot, onCommand, submitInline);+ this.deps.bridge.open(sessionId, snapshot, onCommand, submitInline, actionId => {+ if (settled) return;+ reconnectedActions.add(actionId);+ assessmentDirty = true;+ void verify();+ });} catch (error) {settle(this.internalFailure('插件设置卡片打开失败', error), 'open-failed', 0);return;}+ request.signal?.addEventListener('abort', onAbort, { once: true });+ if (request.signal?.aborted) {+ onAbort();+ return;+ }timeoutId = setTimeout(() => {publish(assessment, 'failed', 'TIMEOUT', true);settle(@@ -637,6 +733,26 @@ export function toReauthInteractionAssessment(};}+/** Reopen current credential actions without deleting the previously stored values. */+function toExplicitReauthInteractionAssessment(+ assessment: GhostSetupAssessment,+ completedActions: ReadonlySet<string>,+): GhostSetupAssessment | null {+ if (assessment.state !== 'ready') return null;+ const groups = assessment.groups.flatMap((group) => {+ if (group.items.some(item => item.actions.some(action => completedActions.has(action.id)))) return [];+ const items = group.items.flatMap(item => {+ const actions = item.actions.filter(action => !completedActions.has(action.id) &&+ ((item.kind === 'oauth' && action.kind === 'oauth_connect') ||+ (item.kind === 'connection' && action.kind === 'manage_connection') ||+ (item.kind === 'secret' && action.kind === 'inline_form')));+ return actions.length ? [{ ...item, state: 'expired' as const, actions }] : [];+ });+ return items.length ? [{ ...group, items }] : [];+ });+ return groups.length ? { ...assessment, state: 'required', groups } : null;+}+export function defaultPlan(assessment: GhostSetupAssessment): GhostSetupPlan {const steps = assessment.groups.flatMap((group, index) => {if (group.items.some((item) => item.state === 'satisfied')) return [];diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.tsindex e8dd47db7d..06e3736c2e 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts@@ -4,8 +4,9 @@ import type {GhostSetupAssessment,} from '../../shared/ghost.js';import { GHOST_SECRET_VALUE_MAX_CHARS } from '../../shared/ghost.js';-import type { GhostSetupActionResult } from './ghostSetupCoordinator.js';+import type { GhostSetupActionResult, GhostSetupInlineCommit } from './ghostSetupCoordinator.js';import { t } from '../i18n.js';+import { getRemoteOauthContext } from '../plugin-oauth/context.js';export interface GhostSetupInlineExecutorDeps {getAssessment: (ghostId: string) => GhostSetupAssessment;@@ -28,8 +29,11 @@ export function executeGhostSetupInlineSubmission(ghostId: string;action: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }>;value: string;+ commit?: GhostSetupInlineCommit;},): GhostSetupActionResult {+ const remote = getRemoteOauthContext();+ remote?.assertCurrent();const trimmed = args.value.trim();if (trimmed.length === 0 || trimmed.length > GHOST_SECRET_VALUE_MAX_CHARS) {return { ok: false, errorCode: 'INLINE_INVALID', message: t('newChat.pluginSetup.inlineSecretInvalid') };@@ -47,10 +51,11 @@ export function executeGhostSetupInlineSubmission(const assessment = deps.getAssessment(args.ghostId);let boundRef: string | null = null;for (const group of assessment.groups) {- if (group.items.some((item) => item.state === 'satisfied')) continue;+ if (!args.commit?.replaceExisting && group.items.some((item) => item.state === 'satisfied')) continue;for (const item of group.items) {if (- item.state !== 'satisfied' &&+ item.kind === 'secret' &&+ (item.state !== 'satisfied' || args.commit?.replaceExisting) &&item.actions.some((action) => action.id === args.action.id && action.kind === 'inline_form',)@@ -87,9 +92,15 @@ export function executeGhostSetupInlineSubmission(message: t('newChat.pluginSetup.inlineSecretDeclChanged'),};}+ args.commit?.assertCurrent(args.ghostId, args.action.id, boundRef);+ remote?.assertCurrent();if (!deps.storeSecret(args.ghostId, secretKey, trimmed)) {return { ok: false, errorCode: 'SAVE_FAILED', message: t('newChat.pluginSetup.inlineSecretStoreFailed') };}+ // The current target is now stored. Seal before synchronous change listeners+ // can retire the card. This promises configuration, not provider account access.+ args.commit?.onCommitted();+ remote?.finish(true);deps.emitChange(args.ghostId, secretKey);try {deps.onSaved?.(args.ghostId, decl.label);diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.tsindex 976a17e910..af91b96523 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts@@ -1,4 +1,6 @@import { readBotAuthorizationCard } from '../../shared/botAuthorization.js';+import { notifyOauthCardClosed } from '../plugin-oauth/context.js';+import { supportsRemotePluginOauth } from '../plugin-oauth/runtime.js';/*** Desktop interaction bridge for Host-owned plugin setup cards.*@@ -36,6 +38,12 @@ export interface GhostSetupInteractionStep {}export interface GhostSetupInteractionSnapshot {+ /** Presentation hint; only the dedicated Main bridge may execute OAuth remotely. */+ remoteOauth?: true;+ /** Only the ordinary Host-owned inline setup executor supports the signed input bridge. */+ remoteSecret?: true;+ /** Dedicated exact-host connection form; never generic remote settings access. */+ remoteConnection?: true;kind: 'plugin_setup';requestId: string;revision: number;@@ -106,6 +114,7 @@ interface PendingSetupInteraction {responseTarget?: GhostSetupInteractionResponseTarget,) => Promise<void> | void;onInlineSubmit?: (submit: GhostSetupInlineSubmit) => Promise<void> | void;+ onConnectionCommitted?: (actionId: string) => void;}export class GhostSetupInteractionBridge {@@ -118,6 +127,7 @@ export class GhostSetupInteractionBridge {snapshot: GhostSetupInteractionSnapshot,onCommand: PendingSetupInteraction['onCommand'],onInlineSubmit?: PendingSetupInteraction['onInlineSubmit'],+ onConnectionCommitted?: PendingSetupInteraction['onConnectionCommitted'],): void {if (this.pending.has(snapshot.requestId)) {throw new Error(`plugin setup interaction already exists: ${snapshot.requestId}`);@@ -128,6 +138,7 @@ export class GhostSetupInteractionBridge {completed: false,onCommand,...(onInlineSubmit ? { onInlineSubmit } : {}),+ ...(onConnectionCommitted ? { onConnectionCommitted } : {}),});try {this.broadcastSnapshot(sessionId, snapshot);@@ -192,14 +203,25 @@ export class GhostSetupInteractionBridge {return true;}- /**- * Retire a settled request from pending/actionable semantics while keeping- * its last snapshot addressable for a delayed visual dismissal.- */+ /** Main-only receipt after the exact connection card has committed its vault write. */+ connectionCommitted(requestId: string, actionId: string, expectedRevision: number): boolean {+ const entry = this.pending.get(requestId);+ if (!entry || entry.completed || entry.snapshot.terminal ||+ entry.snapshot.revision !== expectedRevision || !entry.onConnectionCommitted) return false;+ const step = entry.snapshot.steps.find(step => step.action?.id === actionId &&+ step.action.kind === 'manage_connection' && (step.phase === 'pending' || step.phase === 'failed'));+ if (!step) return false;+ // Main-only commit receipt. Never exposed through resolve or a Renderer command.+ entry.onConnectionCommitted(actionId);+ return true;+ }++ /** Retire a settled request while retaining its snapshot for delayed dismissal. */complete(requestId: string): boolean {const entry = this.pending.get(requestId);if (!entry || entry.completed) return false;entry.completed = true;+ notifyOauthCardClosed(requestId);return true;}@@ -207,6 +229,7 @@ export class GhostSetupInteractionBridge {const entry = this.pending.get(requestId);if (!entry) return false;this.pending.delete(requestId);+ notifyOauthCardClosed(requestId);try {this.deps.broadcast(MAKER_PUSH.INTERACTION_DISMISSED, {sessionId: entry.sessionId,@@ -326,6 +349,9 @@ export function sanitizeGhostSetupSnapshotForRemote(): GhostSetupInteractionSnapshot {return {kind: snapshot.kind,+ ...(supportsRemotePluginOauth() ? { remoteOauth: true as const } : {}),+ ...(supportsRemotePluginOauth() && snapshot.remoteSecret ? { remoteSecret: true as const } : {}),+ ...(supportsRemotePluginOauth() && snapshot.remoteConnection ? { remoteConnection: true as const } : {}),requestId: snapshot.requestId,revision: snapshot.revision,...(snapshot.terminal ? { terminal: true as const } : {}),diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex adb4fd5178..29ed3e9dd4 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,4 +1,6 @@import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';+import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';+import { t as authorizationText } from '../i18n.js';import { getBotAuthorizationService } from '../maker-ipc/botAuthorizationService.js';import { isResidentBrowserGhost, spawnResidentGhost } from './residentGhost.js';import { handleRoutineRequest } from './routineSlot.js';@@ -74,6 +76,7 @@ import {type GhostLibraryOverview,} from '../../shared/ghost.js';import { getAppCapabilities } from '../appCapabilities.js';+import { getRemoteOauthContext } from '../plugin-oauth/context.js';import { withGhostSkillProjectionReconcile } from '../authBoundaryQuarantine.js';import {activeOwnerScopeKey,@@ -155,12 +158,15 @@ import { GhostSetupManifestTracker } from './ghostSetupManifestTracker.js';import {getGhostSetupCoordinator,type GhostSetupActionResult,+ type GhostSetupInlineActionInput,} from './ghostSetupCoordinator.js';import {getGhostSetupInteractionBridge,type GhostSetupInteractionResponseTarget,} from './ghostSetupInteractionBridge.js';import { executeGhostSetupInlineSubmission } from './ghostSetupInlineExecutor.js';+import { requestNodeSecretSetup } from './nodeSecretSetup.js';+import { executeGhostSetupConnectionSubmission } from './ghostSetupConnectionExecutor.js';import { handleGhostSecretsRequest } from './runtime/ghostSecretsEndpoint.js';import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';@@ -391,6 +397,7 @@ import { isCatalogMediaModelVisible } from './mediaDisplayVisibility.js';import { readProviderOrder } from '../maker-host/provider-order-store.js';import { guardedOutboundFetch, outboundFetch } from '../maker-host/outbound-fetch.js';import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';+import { copyPrivateDeviceCode } from '../plugin-oauth/deviceCodeClipboard.js';import { hasCodexOAuthLoginReadOnly } from '../maker-host/codex-oauth-readiness.js';import {formatAuxiliaryModelRefLabel,@@ -1748,8 +1755,45 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {if (!nodeRuntimeBrokerSingleton) {nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({getGhost: findAvailableGhost,+ getCallSignal: (ghostId, callId) => getGhostPipeDispatcher().getPendingCallSignal(ghostId, callId),+ getCallSessionId: (ghostId, callId) =>+ getGhostPipeDispatcher().getPendingCallSessionId(ghostId, callId),+ openSecretInput: input => {+ const bridge = getGhostSetupInteractionBridge();+ if (!bridge) throw new Error('NODE_SECRET_INPUT_UNAVAILABLE');+ return requestNodeSecretSetup({+ bridge,+ changeBus: getGhostSetupChangeBus(),+ getManifest: ghostId => findAvailableGhost(ghostId)?.manifest ?? null,+ secretSaved: ghostSecretSaved,+ storeSecret: storeGhostSecret,+ }, input);+ },+ openDeviceAuthorization: (input) => {+ const bridge = getGhostSetupInteractionBridge();+ if (!bridge) throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ return openDeviceAuthorizationCard(input, {+ bridge,+ openExternal: (url) => shell.openExternal(url),+ copy: {+ title: authorizationText('pluginDeviceAuthorization.title'),+ description: authorizationText('pluginDeviceAuthorization.description'),+ },+ });+ },+ openAuthorization: input => {+ const bridge = getGhostSetupInteractionBridge();+ if (!bridge) throw new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');+ return openPluginAuthorizationCard(input, {+ bridge, openExternal: url => shell.openExternal(url),+ copyDeviceCode: code => copyPrivateDeviceCode(clipboard, code),+ copy: { title: authorizationText('pluginDeviceAuthorization.title'),+ description: authorizationText('pluginDeviceAuthorization.description') },+ });+ },ownerScope: ghostOwnerScope,readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),+ secretSaved: ghostSecretSaved,resolveOauthSecret: async (ghostId, secretKey, accountId) => {const ghost = findAvailableGhost(ghostId);const source = ghost@@ -5042,21 +5086,30 @@ export async function executeGhostSetupAction(args: {message: '当前安装来源或组织身份无权使用授权 broker',};}- const connected = await getGhostOauthAccountManager().connectAccount(- args.ghostId,- secretKey,- decl,- { deliveryHosts: runtimeManifest.network?.hosts, onAuthorizationUrl: args.onAuthorizationUrl, assertCurrent: args.assertCurrent, beforeCommit: args.beforeCommit },- );- return connected.ok- ? { ok: true }- : {- ok: false,- errorCode: mapGhostOauthConnectError(connected.error),- // interaction snapshot 只传稳定 errorCode;detail 可能含服务路径或- // 上游诊断,留在 Main,不下放 Renderer。- message: connected.detail ?? connected.error,- };+ const remote = getRemoteOauthContext();+ try {+ remote?.assertCurrent();+ const connected = await getGhostOauthAccountManager().connectAccount(+ args.ghostId,+ secretKey,+ decl,+ { deliveryHosts: runtimeManifest.network?.hosts, remote, onAuthorizationUrl: remote ? undefined : args.onAuthorizationUrl, assertCurrent: args.assertCurrent, beforeCommit: args.beforeCommit },+ );+ remote?.finish(connected.ok);+ return connected.ok+ ? { ok: true }+ : {+ ok: false,+ errorCode: mapGhostOauthConnectError(connected.error),+ // interaction snapshot 只传稳定 errorCode;detail 可能含服务路径或+ // 上游诊断,留在 Main,不下放 Renderer。+ message: connected.detail ?? connected.error,+ };+ } catch (error) {+ remote?.finish(false);+ if (remote) return { ok: false, errorCode: 'AUTH_FAILED', message: 'Remote authorization unavailable' };+ throw error;+ }}const navigation = ghostSetupNavigationForAction(args.ghostId, args.action);@@ -5086,12 +5139,7 @@ export async function executeGhostSetupAction(args: {* 仅供 trusted Desktop inline-setup IPC 调用。Secret 值不经过通用* InteractionDecision,也不进入 assessment、snapshot 或日志。*/-export async function executeGhostSetupInlineAction(args: {- sessionId: string;- ghostId: string;- action: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }>;- value: string;-}): Promise<GhostSetupActionResult> {+export async function executeGhostSetupInlineAction(args: GhostSetupInlineActionInput): Promise<GhostSetupActionResult> {return executeGhostSetupInlineSubmission({getAssessment: getGhostSetupAssessment,@@ -5118,6 +5166,22 @@ export async function executeGhostSetupInlineAction(args: {);}+/** Only called under the authenticated remote connection-card context. */+export function bindGhostSetupConnectionAction(args: { ghostId: string; actionId: string; onCommitted(): void }):+ ((value: import('@cindy/device-link').PluginConnectionInput) => boolean) | null {+ const manifest = findAvailableGhost(args.ghostId)?.manifest;+ if (!manifest) return null;+ const expectedManifest = JSON.stringify(manifest);+ return value => executeGhostSetupConnectionSubmission({+ getAssessment: getGhostSetupAssessment,+ getManifest: ghostId => findAvailableGhost(ghostId)?.manifest ?? null,+ manager: getGhostConnectionManager(),+ emitChange: (ghostId, key) => {+ getGhostSetupChangeBus().emit(ghostId, { source: 'connection', ref: key });+ },+ }, { ...args, value, expectedManifest });+}+/*** network 槽单例:deps 全部懒取现查——意识清单实扫、凭证保险库现读,* 用户填/改 key 后下一单即生效,无需任何重启。diff --git a/apps/desktop/src/main/cindy-brain/nodeAuthorizationClient.ts b/apps/desktop/src/main/cindy-brain/nodeAuthorizationClient.tsnew file mode 100644index 0000000000..0459507cc9--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/nodeAuthorizationClient.ts@@ -0,0 +1,89 @@+import {+ PLUGIN_OAUTH_TTL_MS,+ parsePluginAuthorizationRequest,+ parsePluginAuthorizationResult,+ type PluginAuthorizationRequest,+ type PluginAuthorizationResult,+} from '@cindy/device-link';+import type { NodeRequestScopes } from './nodeRequestScope.js';++/** Bootstrap-private replies; callback codes never travel through JSON-RPC stdout. */+export class NodeAuthorizationClient {+ private nextId = 1;+ private readonly pending = new Map<+ string,+ {+ rpcId: string;+ request: PluginAuthorizationRequest;+ assertCurrent(): void;+ resolve(result: PluginAuthorizationResult): void;+ reject(error: Error): void;+ timer: NodeJS.Timeout;+ }+ >();+ constructor(+ private readonly scopes: NodeRequestScopes,+ private readonly send: (message: unknown) => void,+ ) {}++ bind():+ ((request: PluginAuthorizationRequest) => Promise<PluginAuthorizationResult>) | undefined {+ const bound = this.scopes.capture();+ if (!bound) return undefined;+ let used = false;+ return async (raw) => {+ bound.assertCurrent();+ if (used) throw new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');+ const request = parsePluginAuthorizationRequest(raw);+ const ttl = Math.min(+ PLUGIN_OAUTH_TTL_MS,+ request.kind === 'loopback' ? Infinity : (request.expiresAt ?? Infinity) - Date.now(),+ );+ if (ttl <= 0) throw new Error('PLUGIN_AUTHORIZATION_EXPIRED');+ used = true;+ const reqId = 'auth' + this.nextId++;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => this.settle(reqId), ttl);+ timer.unref?.();+ this.pending.set(reqId, {+ rpcId: bound.rpcId,+ request,+ assertCurrent: bound.assertCurrent,+ resolve,+ reject,+ timer,+ });+ try {+ this.send({ type: 'plugin-authorize', reqId, rpcId: bound.rpcId, request });+ } catch {+ this.settle(reqId);+ }+ });+ };+ }+ private settle(reqId: string, raw?: unknown): void {+ const pending = this.pending.get(reqId);+ if (!pending) return;+ this.pending.delete(reqId);+ clearTimeout(pending.timer);+ try {+ pending.assertCurrent();+ const result = parsePluginAuthorizationResult(raw);+ if (+ result.kind === 'callback' &&+ (pending.request.kind !== 'loopback' || pending.request.state !== result.state)+ )+ throw new Error('stale');+ pending.resolve(result);+ } catch {+ pending.reject(new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE'));+ }+ }+ reply(value: Record<string, unknown>): void {+ if (typeof value.reqId === 'string')+ this.settle(value.reqId, value.ok === true ? value.result : undefined);+ }+ finish(rpcId: string): void {+ for (const [id, pending] of this.pending) if (pending.rpcId === rpcId) this.settle(id);+ }+}diff --git a/apps/desktop/src/main/cindy-brain/nodeDeviceAuthorizationClient.ts b/apps/desktop/src/main/cindy-brain/nodeDeviceAuthorizationClient.tsnew file mode 100644index 0000000000..8168227fb1--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/nodeDeviceAuthorizationClient.ts@@ -0,0 +1,60 @@+import { PLUGIN_OAUTH_TTL_MS, parseDeviceAuthorizationUrl } from '@cindy/device-link';+import type { NodeRequestScopes } from './nodeRequestScope.js';++/** Bootstrap-private transport. The captured scope survives stream callback context loss. */+export class NodeDeviceAuthorizationClient {+ private nextId = 1;+ private readonly pending = new Map<+ string,+ {+ rpcId: string;+ resolve(): void;+ reject(error: Error): void;+ timer: NodeJS.Timeout;+ }+ >();+ constructor(+ private readonly scopes: NodeRequestScopes,+ private readonly send: (message: unknown) => void,+ ) {}++ bind(): ((url: string) => Promise<void>) | undefined {+ const bound = this.scopes.capture();+ if (!bound) return undefined;+ let used = false;+ return async (rawUrl) => {+ bound.assertCurrent();+ if (used) throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ used = true;+ const url = parseDeviceAuthorizationUrl(rawUrl);+ const reqId = `a${this.nextId++}`;+ return new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(reqId);+ reject(new Error('DEVICE_AUTHORIZATION_UNAVAILABLE'));+ }, PLUGIN_OAUTH_TTL_MS);+ timer.unref?.();+ this.pending.set(reqId, { rpcId: bound.rpcId, resolve, reject, timer });+ try {+ this.send({ type: 'device-authorize', reqId, rpcId: bound.rpcId, url });+ } catch {+ this.settle(reqId, false);+ }+ });+ };+ }+ private settle(reqId: string, ok: boolean): void {+ const pending = this.pending.get(reqId);+ if (!pending) return;+ this.pending.delete(reqId);+ clearTimeout(pending.timer);+ if (ok) pending.resolve();+ else pending.reject(new Error('DEVICE_AUTHORIZATION_UNAVAILABLE'));+ }+ reply(value: Record<string, unknown>): void {+ if (typeof value.reqId === 'string') this.settle(value.reqId, value.ok === true);+ }+ finish(rpcId: string): void {+ for (const [id, pending] of this.pending) if (pending.rpcId === rpcId) this.settle(id, false);+ }+}diff --git a/apps/desktop/src/main/cindy-brain/nodeRequestScope.ts b/apps/desktop/src/main/cindy-brain/nodeRequestScope.tsnew file mode 100644index 0000000000..a0a5732beb--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/nodeRequestScope.ts@@ -0,0 +1,55 @@+import { AsyncLocalStorage } from 'node:async_hooks';++interface RequestScope {+ rpcId: string;+ active: boolean;+}++/** Keeps async child spawns attached to the exact call-bound stdin request. */+export class NodeRequestScopes {+ private readonly current = new AsyncLocalStorage<RequestScope>();+ private readonly scopes = new Map<string, RequestScope>();++ feed(chunk: string, deliver: (chunk: string) => void): void {+ let value: { id?: unknown; cindy?: { cancelWithCall?: unknown } } | undefined;+ try {+ value = JSON.parse(chunk);+ } catch {+ /* Existing stdio validation owns malformed input. */+ }+ if (+ value?.cindy?.cancelWithCall !== true ||+ typeof value.id !== 'string' ||+ !/^\d{1,16}$/.test(value.id)+ ) {+ this.current.exit(() => deliver(chunk));+ return;+ }+ const scope = { rpcId: value.id, active: true };+ this.scopes.set(scope.rpcId, scope);+ this.current.run(scope, () => deliver(chunk));+ }++ finish(rpcId: string): void {+ const scope = this.scopes.get(rpcId);+ if (scope) scope.active = false;+ this.scopes.delete(rpcId);+ }++ capture(): { rpcId: string; assertCurrent(): void } | undefined {+ const scope = this.current.getStore();+ if (!scope) return undefined;+ const assertCurrent = () => {+ if (!scope.active || this.scopes.get(scope.rpcId) !== scope)+ throw new Error('The originating Node request has ended');+ };+ assertCurrent();+ return { rpcId: scope.rpcId, assertCurrent };+ }++ currentRpcId(): string | undefined {+ const scope = this.current.getStore();+ if (scope && !scope.active) throw new Error('The originating Node request has ended');+ return scope?.rpcId;+ }+}diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 3c03e7421f..f8befca744 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -1,3 +1,11 @@+import type {+ DeviceAuthorizationHandle,+ DeviceAuthorizationInput,+ PluginAuthorizationHandle,+ PluginAuthorizationInput,+} from '../plugin-oauth/deviceCard.js';+import { parseDeviceAuthorizationUrl } from '@cindy/device-link';+import { bindDeviceAuthorizationTarget, bindPluginAuthorizationTarget } from '../plugin-oauth/targetPolicy.js';/*** nodeRuntimeBroker — 随意识安装的本地 Node 工作进程守门与 stdio 中继。*@@ -139,12 +147,19 @@ export interface NodeRuntimeStartAttemptContext {export interface GhostNodeRuntimeBrokerDeps {getGhost(id: string): InstalledGhost | null;+ openSecretInput?: (input: import('./nodeSecretSetup.js').NodeSecretSetupInput) => Promise<boolean>;+ /** Main's exact live tool-call lookup; a plugin cannot select another call's owner. */+ getCallSignal?: (ghostId: string, callId: string) => AbortSignal | null;+ getCallSessionId?: (ghostId: string, callId: string) => string | null;+ openDeviceAuthorization?: (input: DeviceAuthorizationInput) => DeviceAuthorizationHandle;+ openAuthorization?: (input: PluginAuthorizationInput) => PluginAuthorizationHandle;ownerScope?: GhostOwnerScope;/*** 读取当前插件自己声明的 Node 凭证。生产接 safeStorage;返回 null =* 未保存或保险库不可用。调用方不得记录返回值。*/readSecret?: (ghostId: string, secretKey: string) => string | null;+ secretSaved?: (ghostId: string, secretKey: string) => boolean;/** 只解析本插件显式引用的 OAuth 槽;不交付 refresh token。 */resolveOauthSecret?: (ghostId: string, secretKey: string, accountId?: string) => Promise<{ ok: true; accessToken: string } | { ok: false; error: string }@@ -274,11 +289,18 @@ interface PendingRpc {/** 超时收尾(初臂/续命共用同一段收尾逻辑)。 */expire(): void;ownerScopeSnapshot: unknown;+ signal?: AbortSignal;+ callId?: string;+ authorization?: DeviceAuthorizationHandle;+ authorizationStarted?: boolean;+ cancel(): void;+ cleanup(): void;}/** 宿主代启的原样 stdio 子进程(childSpawn;挂在某个 worker 名下)。 */interface ChildProcEntry {childId: string;+ rpcId?: string;entryRel: string;proc: NodeWorkerProcess;hardKillTimer: NodeJS.Timeout | null;@@ -344,7 +366,7 @@ interface WorkerEntry {class NodeRpcError extends Error {constructor(- readonly kind: 'exit' | 'protocol' | 'timeout' | 'remote',+ readonly kind: 'exit' | 'protocol' | 'timeout' | 'remote' | 'cancelled',message: string,readonly data?: unknown,) {@@ -684,6 +706,7 @@ function clearHostSecrets(secrets: Record<string, string> | undefined): void {* 任意命令执行。stop(ghostId) 收掉该意识全部进程。*/export class GhostNodeRuntimeBroker {+ private readonly secretInputCalls = new Set<string>();/*** key = `ghostId::entryRel`(entryRel = 主入口或申报的额外入口;ghostId 与* 安全相对路径的字符集都不含 ":",拼接无歧义)。@@ -801,9 +824,11 @@ export class GhostNodeRuntimeBroker {this.stoppedGhosts.delete(ghostId);const requestGeneration = this.stopGeneration.get(ghostId) ?? 0;const requestManifest = JSON.stringify(ghost.manifest);+ const requestDirectory = ghost.dir;const requestStillCurrent = (): boolean => {const current = this.deps.getGhost(ghostId);return !this.destroyed && current?.enabled === true+ && current.dir === requestDirectory&& (this.stopGeneration.get(ghostId) ?? 0) === requestGeneration&& JSON.stringify(current.manifest) === requestManifest;};@@ -811,6 +836,15 @@ export class GhostNodeRuntimeBroker {return errorResult('INVALID_REQUEST', 'node-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.cancelWithCall !== undefined && typeof request.cancelWithCall !== 'boolean') {+ return errorResult('INVALID_REQUEST', 'cancelWithCall must be a boolean');+ }+ if (request.promptSecrets !== undefined && typeof request.promptSecrets !== 'boolean') {+ return errorResult('INVALID_REQUEST', 'promptSecrets must be a boolean');+ }+ if (request.promptSecrets === true && request.cancelWithCall !== true) {+ return errorResult('INVALID_REQUEST', 'Protected credential input requires cancelWithCall');+ }if (request.authAccount !== undefined &&(typeof request.authAccount !== 'string' || request.authAccount.length === 0 || request.authAccount.length > 64)) {return errorResult('INVALID_REQUEST', 'authAccount 必须是 1–64 字符的账号 id');@@ -818,6 +852,17 @@ export class GhostNodeRuntimeBroker {if (request.type !== 'node-request') {return errorResult('INVALID_REQUEST', '请求类型必须是 node-request');}+ let signal: AbortSignal | undefined;+ // callId alone was ignored by older Hosts. Only the new explicit contract+ // changes a legacy RPC's lifetime or grants access to authorization cards.+ if (request.cancelWithCall === true) {+ if (typeof request.callId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(request.callId)) {+ return errorResult('INVALID_REQUEST', 'callId must identify the current tool call');+ }+ const current = this.deps.getCallSignal?.(ghostId, request.callId);+ if (!current || current.aborted) return errorResult('CANCELLED', 'The tool call is no longer active');+ signal = current;+ }if (typeof request.method !== 'string' ||!/^[A-Za-z0-9_./:-]{1,128}$/.test(request.method)@@ -893,6 +938,56 @@ export class GhostNodeRuntimeBroker {}let hostSecrets: Record<string, string> | undefined;+ let secretInputCompleted = false;+ const manualBindings = secretBindings.filter(binding => !binding.oauthSecret);+ if (request.promptSecrets === true && manualBindings.length === 0) {+ return errorResult('INVALID_REQUEST', 'This Node method has no manual credential binding');+ }+ // A missing optional credential can prompt only inside the exact live tool+ // call. No account, key or URL can be selected by the plugin's params.+ let needsSecretInput = request.promptSecrets === true;+ try {+ if (signal && !needsSecretInput && this.deps.openSecretInput && this.deps.secretSaved) {+ needsSecretInput = manualBindings.some(binding => !this.deps.secretSaved!(ghostId, binding.key));+ }+ } catch {+ return errorResult('INTERNAL', 'Plugin credential status is unavailable');+ }+ if (manualBindings.length > 0 && needsSecretInput) {+ const callId = typeof request.callId === 'string' ? request.callId : null;+ const sessionId = callId ? this.deps.getCallSessionId?.(ghostId, callId) : null;+ if (signal && callId && sessionId && this.deps.openSecretInput) {+ const inputKey = `${ghostId}\0${callId}`;+ if (this.secretInputCalls.has(inputKey) || this.secretInputCalls.size >= MAX_PENDING_REQUESTS) {+ return errorResult('RATE_LIMITED', 'A protected credential input is already pending');+ }+ const assertCurrent = () => {+ if (signal.aborted || !requestStillCurrent() ||+ !this.ownerScopeUsable(ghostId, ownerScopeSnapshot) ||+ this.deps.getCallSignal?.(ghostId, callId) !== signal ||+ this.deps.getCallSessionId?.(ghostId, callId) !== sessionId) {+ throw new Error('NODE_SECRET_INPUT_UNAVAILABLE');+ }+ };+ this.secretInputCalls.add(inputKey);+ try {+ assertCurrent();+ const saved = await this.deps.openSecretInput({+ ghostId, entry: entryRel, method: request.method as string,+ sessionId, signal, force: request.promptSecrets === true, assertCurrent,+ });+ assertCurrent();+ if (!saved) return errorResult('CANCELLED', 'Plugin credential input was not completed');+ secretInputCompleted = true;+ } catch {+ return errorResult('CANCELLED', 'Plugin credential input is no longer active');+ } finally {+ this.secretInputCalls.delete(inputKey);+ }+ } else if (request.promptSecrets === true) {+ return errorResult('PERMISSION_DENIED', 'Protected credential input requires a live task');+ }+ }if (secretBindings.length > 0) {hostSecrets = Object.create(null) as Record<string, string>;try {@@ -944,6 +1039,10 @@ export class GhostNodeRuntimeBroker {let entry: WorkerEntry;try {+ if (signal?.aborted) {+ clearHostSecrets(hostSecrets);+ return errorResult('CANCELLED', 'The tool call was cancelled');+ }entry = await this.ensureWorker(ghost, entryRel, ownerScopeSnapshot);this.assertOwnerScopeUsable(ghostId, ownerScopeSnapshot);if (!requestStillCurrent()) {@@ -987,6 +1086,9 @@ export class GhostNodeRuntimeBroker {request.maxTotalMs as number | undefined,hostSecrets,ownerScopeSnapshot,+ signal,+ signal ? request.callId as string : undefined,+ secretInputCompleted,);// writeLine/JSON.stringify 在 sendRpc 内同步完成;随即抹掉本次临时对象,// 不让凭证明文跟随 Promise 生命周期常驻在 broker 闭包里。@@ -998,6 +1100,7 @@ export class GhostNodeRuntimeBroker {return { ok: true, result };} catch (error) {if (error instanceof NodeRpcError) {+ if (error.kind === 'cancelled') return errorResult('CANCELLED', error.message);if (error.kind === 'timeout') return errorResult('TIMEOUT', error.message);if (error.kind === 'exit') return errorResult('PROCESS_EXITED', error.message);return errorResult('PROTOCOL_ERROR', error.message, error.data);@@ -1016,6 +1119,10 @@ export class GhostNodeRuntimeBroker {if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;const message = parseGhostNodeChildToHostMessage(raw);if (!message) return;+ if (message.type === 'device-authorize' || message.type === 'plugin-authorize') {+ this.authorizePlugin(entry, message);+ return;+ }if (message.type === 'spawn-child') {void this.spawnChildForWorker(entry, message);return;@@ -1031,6 +1138,90 @@ export class GhostNodeRuntimeBroker {}}+ private authorizePlugin(+ entry: WorkerEntry,+ message: Extract<GhostNodeChildToHostMessage, { type: 'device-authorize' | 'plugin-authorize' }>,+ ): void {+ const ghostId = entry.ghost.manifest.id;+ const pending = entry.pending.get(message.rpcId);+ const reply = (ok: boolean, result?: Awaited<PluginAuthorizationHandle['result']>) =>+ this.replyToWorker(entry, message.type === 'device-authorize'+ ? { type: 'device-authorize-result', reqId: message.reqId, ok }+ : { type: 'plugin-authorize-result', reqId: message.reqId, ok, ...(result ? { result } : {}) });+ const sessionId = pending?.signal && pending.callId+ ? this.deps.getCallSessionId?.(ghostId, pending.callId)+ : null;+ if (+ !pending?.signal ||+ !sessionId ||+ !this.isLiveBoundRpc(entry, message.rpcId) ||+ !(message.type === 'device-authorize' ? this.deps.openDeviceAuthorization : this.deps.openAuthorization) ||+ pending.authorizationStarted+ ) {+ reply(false);+ return;+ }+ pending.authorizationStarted = true;+ try {+ const request = message.type === 'device-authorize'+ ? { kind: 'device' as const, url: parseDeviceAuthorizationUrl(message.url) } : message.request;+ const checkTarget = message.type === 'device-authorize'+ ? bindDeviceAuthorizationTarget(entry.ghost.manifest, request.url)+ : bindPluginAuthorizationTarget(entry.ghost.manifest, request);+ const assertCurrent = () => {+ const currentGhost = this.deps.getGhost(ghostId);+ if (!currentGhost || !currentGhost.enabled || currentGhost.dir !== entry.ghost.dir)+ throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ checkTarget(currentGhost.manifest);+ if (+ entry.pending.get(message.rpcId) !== pending ||+ !this.isLiveBoundRpc(entry, message.rpcId) ||+ !this.ownerScopeUsable(ghostId, pending.ownerScopeSnapshot) ||+ this.deps.getCallSessionId?.(ghostId, pending.callId!) !== sessionId ||+ this.workers.get(GhostNodeRuntimeBroker.keyOf(ghostId, entry.entryRel)) !== entry+ )+ throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ };+ assertCurrent();+ const input = {+ ghost: { id: ghostId, name: entry.ghost.manifest.name },+ sessionId,+ signal: pending.signal,+ assertCurrent,+ cancel: () => pending.cancel(),+ };+ let handle: DeviceAuthorizationHandle;+ let result: Promise<Awaited<PluginAuthorizationHandle['result']> | undefined>;+ if (message.type === 'device-authorize') {+ handle = this.deps.openDeviceAuthorization!({ ...input, url: request.url });+ result = handle.opened.then(() => undefined);+ } else {+ const authorization = this.deps.openAuthorization!({ ...input, request });+ handle = authorization;+ result = authorization.result;+ }+ pending.authorization = handle;+ void result+ .then(+ value => {+ assertCurrent();+ reply(true, value);+ },+ () => {+ reply(false);+ pending.cancel();+ },+ )+ .catch(() => {+ reply(false);+ pending.cancel();+ });+ } catch {+ reply(false);+ pending.cancel();+ }+ }+/** 某插件当前在世的代启子进程总数(跨该插件全部 worker)。 */private childCountOf(ghostId: string): number {let count = 0;@@ -1081,6 +1272,10 @@ export class GhostNodeRuntimeBroker {fail('插件正在停止,不能再启动子进程');return;}+ if (message.rpcId !== undefined && !this.isLiveBoundRpc(entry, message.rpcId)) {+ fail('The originating Node request is no longer active');+ return;+ }if (!this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)) {fail('Plugin owner boundary changed before child process dispatch');return;@@ -1149,6 +1344,10 @@ export class GhostNodeRuntimeBroker {// entry.children。原位更新不能漏掉这段空窗,否则 Windows rename 仍可能// 撞上子进程持有的插件文件句柄。const startingChild = this.trackStartingChild(ghostId, proc);+ const signal = message.rpcId === undefined ? undefined : entry.pending.get(message.rpcId)?.signal;+ const abortStarting = () => this.stopStartingChild(startingChild, true);+ signal?.addEventListener('abort', abortStarting, { once: true });+ if (signal?.aborted) abortStarting();try {await new Promise<void>((resolve, reject) => {let settled = false;@@ -1174,12 +1373,15 @@ export class GhostNodeRuntimeBroker {this.stopStartingChild(startingChild, true);fail(error instanceof Error ? error.message : '子进程启动失败');return;+ } finally {+ signal?.removeEventListener('abort', abortStarting);}// worker 在等待答复期间死了/被停:孩子不能变孤儿,就地收掉。if (this.workers.get(GhostNodeRuntimeBroker.keyOf(ghostId, entry.entryRel)) !== entry|| !this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)+ || (message.rpcId !== undefined && !this.isLiveBoundRpc(entry, message.rpcId))) {try {proc.kill('SIGKILL');@@ -1193,6 +1395,7 @@ export class GhostNodeRuntimeBroker {this.forgetStartingChild(startingChild);const child: ChildProcEntry = {childId: randomUUID(),+ ...(message.rpcId !== undefined ? { rpcId: message.rpcId } : {}),entryRel: message.entry,proc,hardKillTimer: null,@@ -1403,6 +1606,7 @@ export class GhostNodeRuntimeBroker {// 级联:先收孩子再收本体,不留孤儿进程。for (const child of [...entry.children.values()]) this.stopChild(entry, child, true);for (const pending of entry.pending.values()) {+ pending.cleanup();this.clearTimer(pending.timer);pending.reject(new NodeRpcError('exit', 'Node 工作进程已停止'));}@@ -1887,8 +2091,12 @@ export class GhostNodeRuntimeBroker {maxTotalMs?: number,hostSecrets?: Readonly<Record<string, string>>,ownerScopeSnapshot: unknown = entry.ownerScopeSnapshot,+ signal?: AbortSignal,+ callId?: string,+ secretInputCompleted = false,): Promise<unknown> {this.assertOwnerScopeUsable(entry.ghost.manifest.id, ownerScopeSnapshot);+ if (signal?.aborted) return Promise.reject(new NodeRpcError('cancelled', 'The tool call was cancelled'));this.clearIdleTimer(entry);const id = String(entry.nextId++);return new Promise((resolve, reject) => {@@ -1901,31 +2109,66 @@ export class GhostNodeRuntimeBroker {deadlineAt: maxTotalMs !== undefined ? this.now() + maxTotalMs : null,expire: () => {entry.pending.delete(id);+ pending.cleanup();reject(new NodeRpcError('timeout', `Node 请求 ${method} 等待超时`));this.scheduleIdleStop(entry);},ownerScopeSnapshot,+ signal,+ callId,+ cancel: () => abort(),+ cleanup: () => {+ pending.authorization?.dispose();+ signal?.removeEventListener('abort', abort);+ if (!signal) return;+ // Only explicitly call-bound work ends here; autonomous/background work is unchanged.+ try { entry.child.sendControl?.({ type: 'request-settled', rpcId: id }); }+ catch { /* A closed worker pipe must not prevent child cleanup or settlement. */ }+ for (const child of entry.children.values()) {+ if (child.rpcId === id) this.stopChild(entry, child, false);+ }+ },+ };+ const abort = () => {+ if (entry.pending.get(id) !== pending) return;+ entry.pending.delete(id);+ this.clearTimer(pending.timer);+ pending.cleanup();+ reject(new NodeRpcError('cancelled', 'The tool call was cancelled'));+ this.scheduleIdleStop(entry);};entry.pending.set(id, pending);this.armPendingTimer(pending);+ signal?.addEventListener('abort', abort, { once: true });+ if (signal?.aborted) { abort(); return; }try {this.writeLine(entry, {jsonrpc: '2.0',id,method,params,- ...(hostSecrets && Object.keys(hostSecrets).length > 0- ? { cindy: { secrets: hostSecrets } }+ ...(signal || (hostSecrets && Object.keys(hostSecrets).length > 0)+ ? { cindy: {+ ...(signal ? { cancelWithCall: true } : {}),+ ...(secretInputCompleted ? { secretInputCompleted: true } : {}),+ ...(hostSecrets && Object.keys(hostSecrets).length > 0 ? { secrets: hostSecrets } : {}),+ } }: {}),});} catch (error) {entry.pending.delete(id);this.clearTimer(pending.timer);+ pending.cleanup();reject(error);}});}+ private isLiveBoundRpc(entry: WorkerEntry, id: string): boolean {+ const signal = entry.pending.get(id)?.signal;+ return signal !== undefined && !signal.aborted;+ }+/** 初臂/续命共用:按沉默窗口与绝对截止的较小者上闹钟。 */private armPendingTimer(pending: PendingRpc): void {const delay =@@ -2006,8 +2249,23 @@ export class GhostNodeRuntimeBroker {if (msg.id !== undefined && typeof msg.method !== 'string') {const pending = entry.pending.get(String(msg.id));if (!pending) return; // 迟到或未知 response,静默丢弃。+ const value = msg.result as {+ isError?: unknown;+ ok?: unknown;+ structuredContent?: { ok?: unknown };+ } | null;+ const authorizationOk =+ !msg.error &&+ 'result' in msg &&+ !!value &&+ typeof value === 'object' &&+ value.isError !== true &&+ value.ok !== false &&+ value.structuredContent?.ok !== false;+ pending.authorization?.finish(authorizationOk);entry.pending.delete(String(msg.id));this.clearTimer(pending.timer);+ pending.cleanup();if (!this.ownerScopeUsable(entry.ghost.manifest.id, pending.ownerScopeSnapshot)) {pending.reject(new NodeRpcError('exit', 'Plugin owner boundary changed before response'));return;@@ -2054,6 +2312,7 @@ export class GhostNodeRuntimeBroker {private failProtocol(entry: WorkerEntry, message: string): void {for (const pending of entry.pending.values()) {+ pending.cleanup();this.clearTimer(pending.timer);pending.reject(new NodeRpcError('protocol', message));}@@ -2198,6 +2457,7 @@ export class GhostNodeRuntimeBroker {exitHint ? `:${exitHint}` : ''}`;for (const pending of entry.pending.values()) {+ pending.cleanup();this.clearTimer(pending.timer);pending.reject(new NodeRpcError('exit', `Node 工作进程已退出(${detail})`));}diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.tsindex 092380b171..ddbd5b607f 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts@@ -28,6 +28,9 @@ import { PassThrough } from 'node:stream';import type { GhostNodeChildToWorkerMessage } from '../../shared/ghost.js';import { GHOST_NODE_CHILD_MODE_FLAG } from '../../shared/ghost.js';import { installVirtualStdin } from './nodeRuntimeVirtualStdin.js';+import { NodeRequestScopes } from './nodeRequestScope.js';+import { NodeDeviceAuthorizationClient } from './nodeDeviceAuthorizationClient.js';+import { NodeAuthorizationClient } from './nodeAuthorizationClient.js';interface ParentPortLike {postMessage(message: unknown): void;@@ -55,6 +58,11 @@ if (// Windows 上 Electron 把 process.stdin 钉成不可配置 getter,不能整体替换;// 替换或原地复活的分支收敛在 installVirtualStdin 里。const virtualStdin = installVirtualStdin(process);+const requestScopes = new NodeRequestScopes();+const deviceAuthorization = new NodeDeviceAuthorizationClient(requestScopes, (message) =>+ parentPort.postMessage(message),+);+const authorization = new NodeAuthorizationClient(requestScopes, message => parentPort.postMessage(message));/* ── spawnEntry 窄接口(仅普通 worker 模式;子进程模式不给,树深恒为 1)── */@@ -136,6 +144,7 @@ function handleChildControlMessage(m: GhostNodeChildToWorkerMessage): void {pending.resolve(handle);return;}+ if (m.type === 'device-authorize-result' || m.type === 'plugin-authorize-result') return;const internal = childHandles.get(m.childId);if (!internal) return;if (m.type === 'child-stdout') {@@ -159,6 +168,7 @@ function handleChildControlMessage(m: GhostNodeChildToWorkerMessage): void {*/function spawnEntry(entry: string, args?: string[]): Promise<unknown> {return new Promise((resolve, reject) => {+ const rpcId = requestScopes.currentRpcId();const reqId = `r${nextSpawnReq++}`;const timer = setTimeout(() => {pendingSpawns.delete(reqId);@@ -170,6 +180,7 @@ function spawnEntry(entry: string, args?: string[]): Promise<unknown> {type: 'spawn-child',reqId,entry,+ ...(rpcId !== undefined ? { rpcId } : {}),...(args !== undefined ? { args } : {}),});});@@ -181,7 +192,23 @@ parentPort.on('message', (event) => {const data = event.data;if (!isRecord(data)) return;if (data.type === 'stdin' && typeof data.chunk === 'string') {- if (Buffer.byteLength(data.chunk, 'utf8') <= 1024 * 1024) virtualStdin.feed(data.chunk);+ if (Buffer.byteLength(data.chunk, 'utf8') <= 1024 * 1024) {+ requestScopes.feed(data.chunk, (chunk) => virtualStdin.feed(chunk));+ }+ return;+ }+ if (!childMode && data.type === 'request-settled' && typeof data.rpcId === 'string') {+ requestScopes.finish(data.rpcId);+ deviceAuthorization.finish(data.rpcId);+ authorization.finish(data.rpcId);+ return;+ }+ if (!childMode && data.type === 'device-authorize-result') {+ deviceAuthorization.reply(data);+ return;+ }+ if (!childMode && data.type === 'plugin-authorize-result') {+ authorization.reply(data);return;}// 子进程原样模式的字节口(base64,防多字节字符被 chunk 边界切坏)。@@ -225,7 +252,8 @@ if (childMode) {configurable: false,enumerable: false,writable: false,- value: Object.freeze({ spawnEntry }),+ value: Object.freeze({ spawnEntry, bindDeviceAuthorization: () => deviceAuthorization.bind(),+ bindAuthorization: () => authorization.bind() }),});}diff --git a/apps/desktop/src/main/cindy-brain/nodeSecretSetup.ts b/apps/desktop/src/main/cindy-brain/nodeSecretSetup.tsnew file mode 100644index 0000000000..043ba3cfc7--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/nodeSecretSetup.ts@@ -0,0 +1,123 @@+import type { GhostManifest } from '../../shared/ghost.js';+import { GhostSetupCoordinator } from './ghostSetupCoordinator.js';+import type { GhostSetupChangeBus } from './ghostSetupChangeBus.js';+import type { GhostSetupInteractionBridge } from './ghostSetupInteractionBridge.js';+import { executeGhostSetupInlineSubmission } from './ghostSetupInlineExecutor.js';+import { evaluateGhostSetupAssessment } from './ghostSetupStatus.js';++export interface NodeSecretSetupInput {+ ghostId: string;+ entry: string;+ method: string;+ sessionId: string;+ signal: AbortSignal;+ force: boolean;+ /** Captures the exact live call, owner, package and runtime generation. */+ assertCurrent(): void;+}++export interface NodeSecretSetupDeps {+ bridge: GhostSetupInteractionBridge;+ changeBus: GhostSetupChangeBus;+ getManifest(ghostId: string): GhostManifest | null;+ secretSaved(ghostId: string, key: string): boolean;+ storeSecret(ghostId: string, key: string, value: string): boolean;+}++/**+ * On-demand configuration of the exact Node RPC's declared manual credentials.+ * Reuses the existing password card, signed remote bridge and vault executor.+ * The temporary assessment never changes the plugin's ordinary setup policy;+ * existing CLI logins and unrelated tools therefore remain usable.+ */+export async function requestNodeSecretSetup(+ deps: NodeSecretSetupDeps,+ input: NodeSecretSetupInput,+): Promise<boolean> {+ const submitted = new Set<string>();+ const currentManifest = (): GhostManifest => {+ input.assertCurrent();+ if (input.signal.aborted) throw new Error('NODE_SECRET_INPUT_CANCELLED');+ const manifest = deps.getManifest(input.ghostId);+ if (!manifest?.node) throw new Error('NODE_SECRET_TARGET_UNAVAILABLE');+ return manifest;+ };+ const assess = () => {+ const manifest = currentManifest();+ const bindings =+ manifest.node!.secretBindings?.filter(+ (binding) =>+ !binding.oauthSecret &&+ binding.methods.includes(input.method) &&+ (binding.entry ?? manifest.node!.entry) === input.entry,+ ) ?? [];+ if (bindings.length === 0) throw new Error('NODE_SECRET_BINDING_UNAVAILABLE');+ return evaluateGhostSetupAssessment(+ {+ ...manifest,+ setup: {+ requires: bindings.map((binding) => ({+ anyOf: [{ kind: 'secret' as const, key: binding.key }],+ })),+ },+ },+ {+ secretSaved: (key) =>+ (!input.force || submitted.has(key)) && deps.secretSaved(input.ghostId, key),+ oauthStatus: () => ({ clientConfigured: false, connected: 0, expired: 0 }),+ connectionCount: () => 0,+ kvValue: () => undefined,+ },+ { revision: deps.changeBus.currentRevision(input.ghostId), strict: true },+ );+ };+ const coordinator = new GhostSetupCoordinator({+ bridge: deps.bridge,+ changeBus: deps.changeBus,+ assess,+ validateTarget: () => {+ try {+ currentManifest();+ return { ok: true };+ } catch {+ return {+ ok: false,+ errorCode: 'GHOST_NOT_FOUND',+ message: 'Plugin credential input is no longer active',+ };+ }+ },+ getGhostIdentity: () => {+ const manifest = currentManifest();+ return { id: manifest.id, name: manifest.name };+ },+ executeAction: async () => ({ ok: false, errorCode: 'ACTION_STALE' }),+ executeInlineAction: async (args) =>+ executeGhostSetupInlineSubmission(+ {+ getManifest: currentManifest,+ getAssessment: assess,+ storeSecret: (ghostId, key, value) => {+ currentManifest();+ const saved = deps.storeSecret(ghostId, key, value);+ // Seal a forced replacement before synchronous change listeners run.+ // Cancellation / failed writes keep the previous credential untouched.+ if (saved) submitted.add(key);+ return saved;+ },+ emitChange: (ghostId, key) => {+ deps.changeBus.emit(ghostId, { source: 'secret', ref: key });+ },+ },+ args,+ ),+ });+ const result = await coordinator.ensureReady({+ sessionId: input.sessionId,+ ghostId: input.ghostId,+ signal: input.signal,+ });+ if (!result.ok) return false;+ currentManifest();+ return true;+}diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.tsindex 0f41fbd640..70cf845b6e 100644--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts@@ -59,6 +59,7 @@ interface PendingBindingClaim {}interface PendingCall {+ sessionId?: string;ghostId: string;tool: string;ownerScopeSnapshot: unknown;@@ -76,6 +77,10 @@ interface PendingCall {deadlineAt: number;/** 在途代办 hold 计数(同一卷可并发多单代办,全部收工才收窗)。 */holds: number;+ lifetime: AbortController;+ sourceSignal?: AbortSignal;+ cancellationBound?: boolean;+ detachAbort?: () => void;}/**@@ -120,6 +125,7 @@ export function toolNotFoundMessage(export class GhostPipeDispatcher {private readonly pending = new Map<string, PendingCall>();+ private readonly sessionCalls = new Map<string, Set<AbortController>>();constructor(private readonly deps: PipeDispatcherDeps) {}@@ -139,7 +145,32 @@ export class GhostPipeDispatcher {* 派活主入口(ghost 总机的 callGhostTool 回调)。* 永不 reject——一切失败都折叠成结构化 GhostToolCallResult。*/- async callGhostTool(request: {+ async callGhostTool(request: Parameters<GhostPipeDispatcher['dispatchCall']>[0]): Promise<GhostToolCallResult> {+ // Remember Stop even while a sandbox starts, without changing legacy RPC+ // completion. Only an explicit Node opt-in consumes this cancellation gate.+ const controller = new AbortController();+ const abort = () => controller.abort();+ request.signal?.addEventListener('abort', abort, { once: true });+ if (request.signal?.aborted) abort();+ const sessionId = request.sessionId;+ if (sessionId) {+ const calls = this.sessionCalls.get(sessionId) ?? new Set<AbortController>();+ calls.add(controller);+ this.sessionCalls.set(sessionId, calls);+ }+ try {+ return await this.dispatchCall({ ...request, signal: controller.signal });+ } finally {+ request.signal?.removeEventListener('abort', abort);+ if (sessionId) {+ const calls = this.sessionCalls.get(sessionId);+ calls?.delete(controller);+ if (calls?.size === 0) this.sessionCalls.delete(sessionId);+ }+ }+ }++ private async dispatchCall(request: {ghostId: string;tool: string;args: Record<string, unknown>;@@ -150,6 +181,10 @@ export class GhostPipeDispatcher {callId?: string;/** 仅供可信宿主内部调用方收短等待时间;插件不能控制该值。 */timeoutMs?: number;+ /** Trusted caller's MCP cancellation; not a plugin-controlled field. */+ signal?: AbortSignal;+ /** Trusted Host session attribution, never accepted from plugin input. */+ sessionId?: string;}): Promise<GhostToolCallResult> {const { ghostId, tool, args } = request;@@ -194,6 +229,7 @@ export class GhostPipeDispatcher {const startedAt = Date.now();const baseTimeoutMs = this.baseTimeoutMs(request.timeoutMs);const entry: PendingCall = {+ sessionId: request.sessionId,ghostId,tool,ownerScopeSnapshot,@@ -205,6 +241,8 @@ export class GhostPipeDispatcher {timeoutExtensionsAllowed: request.timeoutMs === undefined,deadlineAt: startedAt + baseTimeoutMs,holds: 0,+ lifetime: new AbortController(),+ sourceSignal: request.signal,};this.pending.set(callId, entry);this.armTimer(callId, entry);@@ -220,6 +258,40 @@ export class GhostPipeDispatcher {});}+ /** Cancel opt-in work and deny late opt-in; legacy completion remains unchanged. */+ cancelSessionCalls(sessionId: string): void {+ for (const controller of this.sessionCalls.get(sessionId) ?? []) controller.abort();+ }++ private cancelBoundCall(callId: string): void {+ this.settle(callId, { ok: false, errorCode: 'INTERNAL', message: 'Plugin tool call cancelled' });+ }++ /** Called only for an explicit cancelWithCall Node request. Legacy tools keep their lifetime. */+ getPendingCallSignal(ghostId: string, callId: string): AbortSignal | null {+ const entry = this.pending.get(callId);+ if (!entry || entry.ghostId !== ghostId || !this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)) return null;+ if (!entry.cancellationBound) {+ entry.cancellationBound = true;+ const abort = () => this.cancelBoundCall(callId);+ entry.sourceSignal?.addEventListener('abort', abort, { once: true });+ entry.detachAbort = () => entry.sourceSignal?.removeEventListener('abort', abort);+ }+ if (entry.sourceSignal?.aborted) {+ this.cancelBoundCall(callId);+ return null;+ }+ return entry.lifetime.signal;+ }++ getPendingCallSessionId(ghostId: string, callId: string): string | null {+ const entry = this.pending.get(callId);+ if (!entry?.cancellationBound || entry.ghostId !== ghostId || entry.lifetime.signal.aborted ||+ entry.sourceSignal?.aborted || !this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)) return null;+ return entry.sessionId ?? null;+ }++/*** 认领真实在途 tool-call 的宿主能力绑定。*@@ -301,6 +373,8 @@ export class GhostPipeDispatcher {const setT = this.deps.setTimeoutFn ?? setTimeout;entry.timer = setT(() => {if (this.pending.delete(callId)) {+ entry.detachAbort?.();+ entry.lifetime.abort();this.deps.log?.warn('ghost tool call timed out', {ghostId: entry.ghostId,tool: entry.tool,@@ -462,6 +536,8 @@ export class GhostPipeDispatcher {if (!entry) return;this.pending.delete(callId);(this.deps.clearTimeoutFn ?? clearTimeout)(entry.timer);+ entry.detachAbort?.();+ entry.lifetime.abort();this.deps.log?.info('ghost tool call completed', {ghostId: entry.ghostId,tool: entry.tool,diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 03b95fed2c..0e02ad9260 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -74,6 +74,17 @@ vi.mock('../../serverApiClient', () => ({serverApiFetch: vi.fn(),ServerApiError: class ServerApiError extends Error {},}));+// Authorization bridge dependencies are outside the mirror-cache IPC boundary.+// Keep registration in memory without loading the real credential/runtime stack.+vi.mock('../../authManager.js', () => ({+ getAccessToken: vi.fn(),+ getCurrentUserId: vi.fn(),+ getDeviceId: vi.fn(),+ getActiveAuthRealm: vi.fn(),+}));+vi.mock('../../clientEndpointsService.js', () => ({+ getClientEndpoint: vi.fn(),+}));vi.mock('../index', () => ({getDeviceLinkStatus: () => 'online',getDeviceLinkConnectionIssue: () => null,diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.tsindex a19cc25510..ba205573a6 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts@@ -1,6 +1,6 @@import { sharedTaskGuestPeer } from '@cindy/device-link';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { PROTOCOL_VERSION, SHARED_TASK_CAPABILITY, type SharedTaskDetail } from '@cindy/device-link';+import { PLUGIN_OAUTH_CHANNEL, PROTOCOL_VERSION, SHARED_TASK_CAPABILITY, type SharedTaskDetail } from '@cindy/device-link';vi.mock('electron', () => ({app: { getAppPath: () => '/tmp/cindy-test/app', getPath: () => '/tmp/cindy-test', getVersion: () => 'test' },@@ -16,6 +16,7 @@ import { __testing as registry } from '../invoke-registry';import { SharedTaskHost } from '../sharedTaskHost';import { setSharedTaskDispatchHost } from '../sharedTaskDispatch';import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks';+import * as pluginOauthRuntime from '../../plugin-oauth/runtime';const peer = sharedTaskGuestPeer('sharedTask', 'member', 'phone');const read = { channel: 'local-db:messages:list', args: ['task'] };@@ -63,6 +64,29 @@ afterEach(() => {});describe('shared task temporary authority fences preserve membership', () => {+ it('keeps plugin authorization owner-only without blocking guest task history', async () => {+ const request = { op: 'hello' };+ const reply = { accepted: true };+ const authorize = vi.spyOn(pluginOauthRuntime, 'requestPluginOauth').mockResolvedValue(reply);+ try {+ expect(host.capturePeer(peer)?.isCurrent()).toBe(true);+ for (const args of [[request], ['task', request]]) {+ await expect(runInvoke(peer, { channel: PLUGIN_OAUTH_CHANNEL, args })).resolves.toMatchObject({+ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('PERMISSION_DENIED') },+ });+ }+ expect(authorize).not.toHaveBeenCalled();+ expect(host.peerStatus(peer)).toBe('available');+ registry.register(read.channel, () => []);+ await expect(runInvoke(peer, read)).resolves.toEqual({ ok: true, result: [] });+ await expect(runInvoke('owner-phone', { channel: PLUGIN_OAUTH_CHANNEL, args: [request] }))+ .resolves.toEqual({ ok: true, result: reply });+ expect(authorize).toHaveBeenCalledExactlyOnceWith('owner-phone', request);+ } finally {+ authorize.mockRestore();+ }+ });+it.each(['suspended', 'revoked'] as const)('gates admission, subscription, link-open and final send while %s', async (state) => {let rejectRemove!: (error: Error) => void;let removal: Promise<void> | undefined;diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 3ed87c2fc1..6cb317f826 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -89,6 +89,8 @@ import { createLogger } from '../logger';import { projectMobileMessagePage, projectMobileToolPush } from './mobileToolProjection';import { normalizeSessionProviderId } from '../maker-host/session-provider-store.js';import { readDeviceLinkSettings } from './settings-store';+import { PLUGIN_OAUTH_CHANNEL } from '@cindy/device-link';+import { requestPluginOauth, invalidatePluginOauth } from '../plugin-oauth/runtime.js';import { dispatchLocalInvoke } from './invoke-registry';import {assertRemoteBotInvocationAllowed, projectRemoteSessionResult, projectRemoteBotPush,@@ -2278,6 +2280,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi}clearRemoteInvokeStateFor(src);stopFilePeers(src);+ invalidatePluginOauth(src);remoteDesktop.stop(src);void remoteCredentialHost.close(src).catch(() => remoteCredentialHost.dispose());offlinePushQueue.clear(src);@@ -3704,6 +3707,11 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefintry { return { ok: true, result: await requestFilePeer(src, payload.args?.[0]) }; }catch { return { ok: false, error: { code: 'IPC_ERROR', message: 'FILE_PEER_UNAVAILABLE' } }; }}+ if (payload.channel === PLUGIN_OAUTH_CHANNEL) {+ if (payload.args?.length !== 1) return { ok: false, error: { code: 'IPC_ERROR', message: '[INVALID_PARAMS] Invalid OAuth transaction' } };+ try { return { ok: true, result: await requestPluginOauth(src, payload.args[0]) }; }+ catch { return { ok: false, error: { code: 'IPC_ERROR', message: '[PRECONDITION_FAILED] Remote authorization unavailable' } }; }+ }if (payload.channel === REMOTE_DESKTOP_CHANNEL) {try { return { ok: true, result: await requestRemoteDesktop(src, payload.args?.[0]) }; }catch (error) { return { ok: false, error: { code: 'IPC_ERROR', message: error instanceof Error ? error.message : 'DESKTOP_UNAVAILABLE' } }; }diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 9fd94d5405..ae59743afe 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -153,6 +153,7 @@ import {setContactsDeviceLinkOwnerActive,} from '../contacts-sync/driver';import { invokeWithClosedLinkRecovery, requiresSessionLink } from './linkRecovery';+import { invalidatePluginOauth } from '../plugin-oauth/runtime.js';import {createResponsivenessTracker,isDeviceResponsivenessProbeEligible,@@ -772,10 +773,12 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vclient.onPeerRouteStateChanged((change) => {if (change.state === 'offline') {+ invalidatePluginOauth(change.deviceId);handleControllerOffline(change.deviceId, change);}});client.onPeerTransportReset(({ deviceId }) => {+ invalidatePluginOauth(deviceId);// Mutual control shares one peer link: a locally exhausted inbound stream// also invalidates this Desktop's remote view, without reopening other peers.broadcast(DEVICE_LINK_PUSH.PEER_LINK_RESET, { deviceId });@@ -783,6 +786,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vclient.onStatusChange((status) => {if (status !== 'online') {+ invalidatePluginOauth();// The shared relay connection is a larger fault domain than one peer:// release every active controller projection, but keep remembered topics// so reconnect recovery can still replay them explicitly.@@ -1296,6 +1300,7 @@ export function getMobileNotifyGeneration(): number {* 同进程换账号登录还会把上一账号的控制端串到新账号。*/function teardownActiveLink(): void {+ invalidatePluginOauth();void stopSharedTaskRuntime().catch((error) => log.warn('sharedTask runtime teardown failed', error));remoteCredentialHost.dispose();stopNetworkWatch?.();@@ -1439,6 +1444,7 @@ export function disconnectAllControllers(): void {* 直到 restoreController 恢复。*/export async function revokeController(deviceId: string): Promise<void> {+ invalidatePluginOauth(deviceId);// 先消化并 enforce 盘上的外部变化,避免快照刷新吞掉别的实例刚写入的撤销(见 setRemoteControlEnabled)pollExternalSettingsChange();// updater 在写锁内基于盘上最新名单追加,不能锁外算好整数组再整值写@@ -1686,13 +1692,15 @@ export async function openRemoteLink(/** 控制端:解除控制链路 */export function closeRemoteLink(deviceId: string): void {+ invalidatePluginOauth(deviceId);// 取消义务清单(不变量 6):用户显式断开必须终止该设备**全部** per-device// 恢复机制,漏一个就是「刚关又被自动建回」。当前全量:// 1. transportTimeoutReopen 重开循环;// 2. pendingPeerLinkReopens 重开队列;// 3. 订阅重放收敛循环(翻代 + 清定时器);// 4. 在途建链(登记删除 + closeEpochs 翻代拦 park 中的等待);- // 5. remoteInvoke / remoteSubscribe 在途调用(经 4 的代次在发送/重开前自败)。+ // 5. remoteInvoke / remoteSubscribe 在途调用(经 4 的代次在发送/重开前自败);+ // 6. OAuth 授权事务与本机回调监听(翻代后在后续操作前自败)。// 新增任何 per-device 重试/恢复机制时必须同步登记到本清单。transportTimeoutReopen.cancel(deviceId);cancelSubscriptionReplay(deviceId);diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 3dd726b928..23bcf9884c 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -6,7 +6,16 @@*/import { createHash, randomBytes } from 'node:crypto';-import { ipcMain } from 'electron';+import { ipcMain, shell, clipboard } from 'electron';+import { currentOauthIdentityScope, trustOauthPeer } from '../plugin-oauth/desktopIdentity.js';+import { RemotePluginOauthUnsupportedError, resolveOauthPeerIdentity } from '../plugin-oauth/identityResolver.js';+import { getDeviceId } from '../authManager.js';+import { copyPrivateDeviceCode } from '../plugin-oauth/deviceCodeClipboard.js';+import { PLUGIN_OAUTH_CHANNEL, PLUGIN_OAUTH_LOCAL_CHANNEL, PLUGIN_SECRET_LOCAL_CHANNEL, PLUGIN_CONNECTION_LOCAL_CHANNEL } from '@cindy/device-link';+import { handleAssistPluginOauth, handleSubmitPluginSecret, handleSubmitPluginConnection } from '../plugin-oauth/localIpc.js';+import { LocalDeviceCodeSessions } from '../plugin-oauth/deviceCodeSessions.js';+import { PLUGIN_OAUTH_DEVICE_CODE_CHANNEL } from '../../shared/pluginOauthDeviceCode.js';+import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import {DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,DeviceLinkError,@@ -576,6 +585,8 @@ export async function handleInvoke(if (typeof channel !== 'string' || !channel.trim()) {throwIpcError('INVALID_PARAMS', 'channel is required');}+ if (channel === PLUGIN_OAUTH_CHANNEL || channel === PLUGIN_SECRET_LOCAL_CHANNEL || channel === PLUGIN_CONNECTION_LOCAL_CHANNEL)+ throwIpcError('PERMISSION_DENIED', 'Authorization transport is Host-only');let callArgs = Array.isArray(args) ? args : [];// Resolve controller-relative references first. If the source session is@@ -1268,6 +1279,56 @@ export async function retryUnsubscribeAfterWindowGone(// ─── 注册(Electron adapter)──────────────────────────────────────────────────export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()): void {+ const deviceCodes = new LocalDeviceCodeSessions();+ const deviceCodeScope = (event: import('electron').IpcMainInvokeEvent): string => {+ assertTrustedAppRendererEvent(event);+ requireDeviceLinkCapability();+ if (isAppSessionBoundaryPending() || getActiveAppSession().mode !== 'cloud' || event.sender.isDestroyed())+ throwIpcError('PRECONDITION_FAILED', 'Remote authorization unavailable');+ const frame = event.senderFrame!;+ return JSON.stringify([activeOwnerScopeKey(), event.sender.id, frame.processId, frame.routingId]);+ };+ // Local-only reads from the initiating frame; never a broadcast, mirror or remote invoke.+ ipcMain.handle(PLUGIN_OAUTH_DEVICE_CODE_CHANNEL, async (event, raw: unknown) => {+ const scope = deviceCodeScope(event);+ try { return await deviceCodes.handle(scope, raw); }+ catch { throwIpcError('PRECONDITION_FAILED', 'Authorization code unavailable; retry from the current card'); }+ });+ const authorizationHandler = (mode: 'oauth' | 'secret' | 'connection') => async (event: import('electron').IpcMainInvokeEvent, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ requireDeviceLinkCapability();+ try {+ return await (mode === 'connection' ? handleSubmitPluginConnection : mode === 'secret' ? handleSubmitPluginSecret : handleAssistPluginOauth)({+ owner: () => !isAppSessionBoundaryPending() && getActiveAppSession().mode === 'cloud' ? activeOwnerScopeKey() : null,+ assertTarget: deviceId => {+ if (event.sender.isDestroyed()) throw new Error('OAUTH_BRIDGE_UNAVAILABLE');+ assertTrustedAppRendererEvent(event);+ assertControlTargetEnabled(deps, deviceId);+ },+ invoke: deps.invoke,+ localDeviceId: getDeviceId,+ identity: (deviceId, assertCurrent) => resolveOauthPeerIdentity({scope: currentOauthIdentityScope, invoke: deps.invoke}, deviceId, assertCurrent),+ trustIdentity: trustOauthPeer,+ openExternal: url => shell.openExternal(url),+ copyDeviceCode: code => copyPrivateDeviceCode(clipboard, code),+ presentBrowserAuthorization: (target, expiresAt, assertCurrent, reopen) =>+ deviceCodes.presentBrowser(deviceCodeScope(event), target, expiresAt, assertCurrent, reopen),+ presentDeviceCode: (target, prompt, assertCurrent, clearClipboard) => deviceCodes.present(deviceCodeScope(event), target, prompt, {+ assertCurrent,+ clearClipboard,+ copy: code => { copyPrivateDeviceCode(clipboard, code); },+ openExternal: url => shell.openExternal(url),+ }),+ }, raw);+ } catch (error) {+ if (error instanceof RemotePluginOauthUnsupportedError)+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Update Cindy on the remote device to use remote plugin authorization');+ throwIpcError('PRECONDITION_FAILED', 'Remote authorization unavailable; retry from the current card');+ }+ };+ ipcMain.handle(PLUGIN_OAUTH_LOCAL_CHANNEL, authorizationHandler('oauth'));+ ipcMain.handle(PLUGIN_SECRET_LOCAL_CHANNEL, authorizationHandler('secret'));+ ipcMain.handle(PLUGIN_CONNECTION_LOCAL_CHANNEL, authorizationHandler('connection'));const gated =<T extends unknown[]>(handler: (...args: T) => unknown) =>(...args: T) => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.tsindex c06fb23c54..5606999ed6 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts@@ -7,6 +7,7 @@ import {type BotAuthorizationAdapter,} from '../botAuthorizationService';import type { BotAuthorizationCard } from '../../../shared/botAuthorization';+import { getRemoteOauthContext, withRemoteOauthContext, type RemoteOauthContext } from '../../plugin-oauth/context';function harness() {let ready = false;@@ -104,6 +105,34 @@ async function flush() {beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());describe('Bot authorization transcript lifecycle (Grok parity)', () => {+ it('dedicates the bridge to current plugin OAuth cards, without a fake Renderer sender', async () => {+ const h = harness();+ const context: RemoteOauthContext = { scope: 'tx', assertCurrent: vi.fn(), authorize: vi.fn(), finish: vi.fn() };+ try {+ await h.service.request('s', { kind: 'plugin', id: 'p' });+ const action = { requestId: h.card().snapshot.requestId, actionId: 'connect', expectedRevision: h.card().snapshot.revision };+ expect(await h.service.bindRemoteOauth({ ...action, expectedRevision: -1 })).toBeNull();+ expect(await h.service.bindRemoteOauth({ ...action, actionId: 'open-settings' })).toBeNull();+ expect(await h.service.resolveRemoteOauth(action)).toBe(false);+ h.adapter.execute = vi.fn(async () => {+ expect(getRemoteOauthContext()).toBe(context);+ return { ok: false as const, errorCode: 'ACTION_FAILED' as const };+ });+ expect(await withRemoteOauthContext(context, () => h.service.resolveRemoteOauth(action))).toBe(true);+ await flush();+ expect(h.adapter.execute).toHaveBeenCalledOnce();+ expect(context.finish).toHaveBeenCalledWith(false);+ expect(h.deps.openExternal).not.toHaveBeenCalled();+ } finally { await h.service.dispose(); }+ const local = harness();+ try {+ await local.service.request('s', { kind: 'host', id: 'grok' });+ const action = { requestId: local.card().snapshot.requestId, actionId: 'connect', expectedRevision: local.card().snapshot.revision };+ expect(await local.service.bindRemoteOauth(action)).toBeNull();+ expect(await withRemoteOauthContext(context, () => local.service.resolveRemoteOauth(action))).toBe(false);+ expect(local.adapter.execute).not.toHaveBeenCalled();+ } finally { await local.service.dispose(); }+ });it('returns the card without opening a browser or holding the model turn; duplicate requests reuse it', async () => {const h = harness();const result = await h.service.request('s', { kind: 'host', id: 'grok' });diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationService.tsindex 49d62f8046..aa056ef0ce 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts@@ -1,4 +1,7 @@import { randomUUID } from 'node:crypto';+import { getRemoteOauthContext, notifyOauthCardClosed } from '../plugin-oauth/context.js';+import type { PluginOauthAction } from '@cindy/device-link';+import type { OauthCardBinding } from '../plugin-oauth/transactions.js';import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';import type {GhostSetupAllowedAction,@@ -333,6 +336,25 @@ export class BotAuthorizationService {return true;}+ /** Separate remote entry: plugin OAuth only; host login, navigation and secrets stay local. */+ async bindRemoteOauth(action: PluginOauthAction): Promise<OauthCardBinding | null> {+ const entry = await this.get(action.requestId);+ if (!entry || entry.closed || entry.cancelled || entry.action || entry.card.target.kind !== 'plugin' ||+ entry.card.snapshot.terminal || entry.card.snapshot.revision !== action.expectedRevision ||+ !entry.card.snapshot.steps.some(s => s.action?.id === action.actionId && s.action.kind === 'oauth_connect')) return null;+ return { ghostId: entry.card.target.id, current: () => !entry.closed && !entry.cancelled && !entry.card.snapshot.terminal };+ }+ async resolveRemoteOauth(action: PluginOauthAction): Promise<boolean> {+ const binding = await this.bindRemoteOauth(action);+ const context = getRemoteOauthContext();+ if (!binding || !context) return false;+ context.assertCurrent();+ const entry = this.entries.get(action.requestId);+ if (!entry) return false;+ this.start(entry, action.actionId);+ return true;+ }+async submit(requestId: string, raw: unknown): Promise<boolean> {const submit = parseGhostSetupInlineSubmit(raw);if (!submit) return false;@@ -353,6 +375,7 @@ export class BotAuthorizationService {value?: string,) {if (entry.action) return;+ const remoteOauth = getRemoteOauthContext();const assertBoundary = this.deps.captureRequestGuard?.(entry.card.sessionId);const assertCurrent = () => {if (entry.closed || entry.cancelled) throw new Error('Authorization action is no longer active');@@ -412,6 +435,7 @@ export class BotAuthorizationService {}).finally(() => {entry.action = undefined;+ remoteOauth?.finish(false); // No-op after commit; settle stale/early-return actions too.});}private async execute(@@ -432,7 +456,7 @@ export class BotAuthorizationService {assertCurrent();},};- const key = `${entry.card.target.kind}:${entry.card.target.id}:${action.id}`;+ const key = `${entry.card.target.kind}:${entry.card.target.id}:${action.id}:${getRemoteOauthContext()?.scope ?? 'local'}`;let flight = this.oauthFlights.get(key);if (!flight) {const listeners = new Set<(url: string) => void>([onUrl]);@@ -605,6 +629,7 @@ export class BotAuthorizationService {}private close(entry: Entry) {entry.closed = true;+ notifyOauthCardClosed(entry.card.snapshot.requestId);entry.unsubscribe();this.stopPoll(entry);if (entry.expiry) clearTimeout(entry.expiry);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9b0091b229..ee21a13af4 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -100,6 +100,10 @@ import {} from '../appSessionState.js';import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';import { isRetainableProjectSession } from '../../shared/sessionSource.js';+import { initializePluginOauthCards } from '../plugin-oauth/cards.js';+import { currentOauthIdentityScope, loadOauthSigningKey } from '../plugin-oauth/desktopIdentity.js';+import { readDeviceLinkSettings } from '../device-link/settings-store.js';+import { getDeviceLinkStatus } from '../device-link/index.js';import type { AgentMeta, Session as RendererSession } from '../../renderer/lib/ccAgent.types';import {deriveAutoTitleSeed,@@ -155,7 +159,9 @@ import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';import {executeGhostSetupAction,executeGhostSetupInlineAction,+ bindGhostSetupConnectionAction,getGhostManager,+ getGhostPipeDispatcher,getGhostSetupAssessment,getIOSSimulatorPluginAccessDecision,isGhostAvailableForActiveSession,@@ -2424,6 +2430,7 @@ const ghostSetupInteractionBridge = initGhostSetupInteractionBridge({});initGhostSetupCoordinator({+ remoteConnection: true,changeBus: getGhostSetupChangeBus(),bridge: ghostSetupInteractionBridge,assess: (ghostId) => getGhostSetupAssessment(ghostId),@@ -2465,12 +2472,24 @@ initGhostSetupCoordinator({action,...(responseTarget ? { responseTarget } : {}),}),- executeInlineAction: ({ sessionId, ghostId, action, value }) =>- executeGhostSetupInlineAction({ sessionId, ghostId, action, value }),+ executeInlineAction: executeGhostSetupInlineAction,timeoutMessage: () => t('newChat.pluginSetup.timeout'),logger: log,});+initializePluginOauthCards({+ bindConnection: bindGhostSetupConnectionAction,+ identity: currentOauthIdentityScope,+ loadKey: loadOauthSigningKey,+ bridge: ghostSetupInteractionBridge,+ bots: getBotAuthorizationService,+ owner: () => currentOauthIdentityScope() ? activeOwnerScopeKey() : null,+ available: peer => {+ const settings = readDeviceLinkSettings();+ return getDeviceLinkStatus() === 'online' && settings.remoteControlEnabled && !settings.revokedControllers.includes(peer);+ },+});+function clearPendingInteraction(requestId: string): PendingInteractionEntry | null {const entry = pendingInteractionResolvers.get(requestId);if (!entry) return null;@@ -15286,6 +15305,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Main 是本机窗口与 Device Link 控制端的 Stop 汇合点;先记账再触发 abort,// 任何 renderer 后续请求推荐都会从同一 ledger fail-closed。notePromptPredictionSessionStopped(sid);+ getGhostPipeDispatcher().cancelSessionCalls(sid);// 这三类续跑撤销都是同步操作,必须早于 goal/DB await;// 否则退避 timer 能在用户已点 Stop 后抢先发出下一轮。resetAutomaticRecoveryForExplicitStop(sid);diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 1b0171acb8..b266980dec 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -24,7 +24,7 @@ import type {} from '../../cindy-brain/ghostSetupCoordinator';import { t } from '../../i18n';import type { CindyGhostsHostDeps } from '../ghost';-import type { InstalledGhost } from '../../../shared/ghost';+import type { InstalledGhost, GhostSetupAssessment } from '../../../shared/ghost';const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-workdir-gate-'));const prefsFile = () => path.join(tmpUserData, 'ghost-workdir-prefs.json');@@ -149,7 +149,7 @@ const WORKDIR = '/proj/alpha';const listMock = vi.fn<() => unknown[]>(() => []);const activeSessionAvailableMock = vi.fn<(ghostId: string) => boolean>(() => true);const dispatchMock = vi.fn(async () => ({ ok: true as const, result: 'done' }));-const setupAssessmentMock = vi.fn((_ghostId: string) => {+const setupAssessmentMock = vi.fn((_ghostId: string): GhostSetupAssessment => {void _ghostId;return {state: 'ready' as const,@@ -1171,6 +1171,7 @@ describe('写路径 roundtrip(真实存储,tmp userData)', () => {describe('connect_account shares Host live plugin policy', () => {it('passes dynamically discovered plugins to Host without treating builtin toolsets as plugin grants', async () => {+ isAuthorizationSessionMock.mockResolvedValueOnce(true);const deps = makeDeps('claude-code', 'bot-session', 'bot-instance', {__cindyAllowedBuiltinPluginIds: ['memory', 'xdt_helper'],});@@ -1181,6 +1182,88 @@ describe('connect_account shares Host live plugin policy', () => {});});+describe('connect_account ordinary task entry', () => {+ it('keeps Host-derived GitHub login on its existing path without a cloud-only adapter', async () => {+ listMock.mockReturnValue([chipGhost('cindy-github')]);+ const signal = new AbortController().signal;+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'cindy-github', reauthorize: true }, signal))+ .toMatchObject({ ok: false, errorCode: 'PLUGIN_CONNECTION_METHOD_REQUIRED' });+ expect(ensureReadyMock).not.toHaveBeenCalled();+ expect(dispatchMock).not.toHaveBeenCalled();+ expect(grantAttachmentsMock).not.toHaveBeenCalled();+ });+ it('blocks disabled GitHub before offering its existing connection method', async () => {+ listMock.mockReturnValue([chipGhost('cindy-github')]);+ setGhostDisabledForWorkdir(WORKDIR, 'cindy-github', true);+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'cindy-github' }))+ .toMatchObject({ ok: false });+ setGhostDisabledForWorkdir(WORKDIR, 'cindy-github', false);+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'cindy-github' }))+ .toMatchObject({ ok: false, errorCode: 'PLUGIN_CONNECTION_METHOD_REQUIRED' });+ expect(dispatchMock).not.toHaveBeenCalled();+ });++ const configured = {+ state: 'ready' as const, revision: 1,+ groups: [{ id: 'account', mode: 'any_of' as const, items: [{+ ref: 'secret:account', kind: 'oauth' as const, label: 'Account', state: 'satisfied' as const,+ actions: [{ id: 'oauth_connect:secret:account', kind: 'oauth_connect' as const }],+ }] }],+ };++ it('uses the normal setup card without a teammate, business call, or attachment grant', async () => {+ setupAssessmentMock.mockReturnValue(configured);+ const signal = new AbortController().signal;+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }, signal))+ .resolves.toMatchObject({ ok: true, status: 'ready', ghostId: 'art' });+ expect(ensureReadyMock).toHaveBeenCalledWith(expect.objectContaining({+ ghostId: 'art', workingDir: WORKDIR, signal,+ }));+ expect(ensureReadyMock.mock.calls[0][0].tool).toBeUndefined();+ expect(authorizationRequestMock).not.toHaveBeenCalled();+ expect(dispatchMock).not.toHaveBeenCalled();+ expect(grantAttachmentsMock).not.toHaveBeenCalled();+ });++ it('passes explicit reconnect and cancellation through the normal waiter', async () => {+ setupAssessmentMock.mockReturnValue(configured);+ ensureReadyMock.mockResolvedValueOnce({ ok: false, errorCode: 'SETUP_CANCELLED', message: 'Cancelled' });+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art', reauthorize: true }))+ .resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ expect(ensureReadyMock.mock.calls[0][0].reauthorize).toBe(true);+ });++ it('rejects an already aborted request before opening a card', async () => {+ const controller = new AbortController(); controller.abort();+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }, controller.signal))+ .resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ expect(ensureReadyMock).not.toHaveBeenCalled();+ });++ it('keeps unavailable plugins outside the connection entry', async () => {+ setGhostDisabledForWorkdir(WORKDIR, 'art', true);+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }))+ .resolves.toMatchObject({ ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR' });+ expect(ensureReadyMock).not.toHaveBeenCalled();+ });++ it('rechecks visibility after the user completes setup', async () => {+ setupAssessmentMock.mockReturnValue(configured);+ ensureReadyMock.mockImplementationOnce(async () => {+ setGhostDisabledForWorkdir(WORKDIR, 'art', true);+ return { ok: true, assessment: configured };+ });+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }))+ .resolves.toMatchObject({ ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR' });+ });++ it('does not claim Host-managed platform login from an empty ready assessment', async () => {+ await expect(makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }))+ .resolves.toMatchObject({ ok: false, errorCode: 'PLUGIN_CONNECTION_METHOD_REQUIRED' });+ expect(ensureReadyMock).not.toHaveBeenCalled();+ });+});+describe('花名册 / ghost_list 过滤', () => {it('被禁用的意识不进花名册与现查清单;其余照常', async () => {setGhostDisabledForWorkdir(WORKDIR, 'art', true);diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex 75399c5828..70e4165ef5 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -1693,13 +1693,49 @@ export function getCindyGhostsMcpDeps(searchMarket: (query: string) => marketTools.search(query),installMarket: (request: { pluginId: string; releaseId: string }, signal?: AbortSignal) => marketTools.install(request, signal),} : {}),- connectAccount: async (target) => {+ connectAccount: async (target, signal) => {const context = resolveSessionContext();const sessionId = ghostSetupInteractionSessionId(context);if (!sessionId) return { ok: false, errorCode: 'NO_SESSION_CONTEXT' };- const service = getBotAuthorizationService();- if (!service) return { ok: false, errorCode: 'HOST_NOT_READY' };- return service.request(sessionId, target);+ if (signal?.aborted) return { ok: false, errorCode: 'SETUP_CANCELLED' };+ // The persistent teammate service retains its own session/policy checks.+ // Ordinary tasks use the same setup gate as ghost_call, without dispatching+ // a business tool or granting files merely to obtain a connection card.+ if (target.kind === 'host' || await isBotAuthorizationSession(sessionId)) {+ if (signal?.aborted) return { ok: false, errorCode: 'SETUP_CANCELLED' };+ const service = getBotAuthorizationService();+ if (!service) return { ok: false, errorCode: 'HOST_NOT_READY' };+ return service.request(sessionId, target);+ }+ const workingDir = context?.workingDir ?? null;+ const visible = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps);+ if (!visible.ok) return visible;+ const assessment = getGhostSetupAssessment(target.id);+ if (assessment.state === 'ready' && assessment.groups.length === 0) {+ // gh-cli and other Host-derived sources deliberately have no synchronous+ // setup requirement. An empty assessment is not proof of platform login.+ return {+ ok: false,+ errorCode: 'PLUGIN_CONNECTION_METHOD_REQUIRED',+ ghostId: target.id,+ settingsAvailable: Boolean(visible.ghost.manifest.settingsHtml),+ message: 'This plugin has no Host setup action. Use its existing plugin settings or documented login tool on the machine running this task. Do not request or copy tokens in chat; setup readiness does not verify platform access.',+ };+ }+ const coordinator = getGhostSetupCoordinator();+ if (!coordinator) return { ok: false, errorCode: 'HOST_NOT_READY' };+ const result = await coordinator.ensureReady({+ sessionId, ghostId: target.id, workingDir, signal,+ ...(target.reauthorize ? { reauthorize: true } : {}),+ });+ if (!result.ok) return result;+ if (signal?.aborted) return { ok: false, errorCode: 'SETUP_CANCELLED' };+ const current = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps);+ if (!current.ok) return current;+ const final = getGhostSetupAssessment(target.id);+ if (final.state !== 'ready') return { ok: false, errorCode: 'SETUP_REQUIRED' };+ return { ok: true, status: 'ready', ghostId: target.id,+ message: 'Host setup is ready. No plugin business operation was executed. Platform permissions are verified only by the requested operation.' };},callMedia: async (request) => {const sessionContext = resolveSessionContext();@@ -1843,6 +1879,7 @@ export function getCindyGhostsMcpDeps(agentToolUseId,grantOnly,setupPlan,+ signal,}) {const sessionContext = resolveSessionContext();const sessionIdForConfirm = sessionContext?.sessionId ?? null;@@ -2221,6 +2258,8 @@ export function getCindyGhostsMcpDeps(tool,args: mergedArgs,callId,+ signal,+ sessionId: callSessionContext?.sessionId,});// 收口取账(ghostMediaLedger):本次调用期间主机实际入库的媒体地址。// 失败也 drain(清账防泄漏),但只在成功结果上附带——cindy-tools 层diff --git a/apps/desktop/src/main/oauthResultPage.ts b/apps/desktop/src/main/oauthResultPage.tsindex 511b880259..794e423e4c 100644--- a/apps/desktop/src/main/oauthResultPage.ts+++ b/apps/desktop/src/main/oauthResultPage.ts@@ -8,6 +8,17 @@ import { DEEP_LINK_URL_PREFIX } from '../shared/deepLinkSchemes';import { LOGIN_CALLBACK_CHIBI } from './assets/loginCallbackAssets';export type OAuthResultPageLang = 'zh' | 'zh-TW' | 'en' | 'ja' | 'ko';++/** Receipt is not token-exchange success. The authoritative result stays in the cloud card. */+export function getRemoteOAuthCallbackCopy(lang: OAuthResultPageLang): { title: string; body: string } {+ return {+ zh: { title: '已收到授权回调', body: '请返回 Cindy,查看远程设备的授权结果。' },+ 'zh-TW': { title: '已收到授權回呼', body: '請返回 Cindy,查看遠端裝置的授權結果。' },+ en: { title: 'Authorization callback received', body: 'Return to Cindy to check the authorization result on the remote device.' },+ ja: { title: '認証コールバックを受信しました', body: 'Cindy に戻り、リモートデバイスの認証結果を確認してください。' },+ ko: { title: '인증 콜백을 받았습니다', body: 'Cindy로 돌아가 원격 기기의 인증 결과를 확인하세요.' },+ }[lang];+}export type OAuthResultPageVariant = 'success' | 'warning' | 'error';export type OAuthResultPageTheme = 'light' | 'dark';diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.tsnew file mode 100644index 0000000000..7785726e31--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts@@ -0,0 +1,252 @@+import { describe, expect, it, vi } from 'vitest';+import { randomBytes } from 'node:crypto';+import {+ AuthenticatedOauthHost,+ authenticateOauthController,+ OauthHostIdentity,+} from '../authentication.js';+import { OauthBox } from '../box.js';+import { parsePluginOauthHelloReply, type PluginOauthAction, type PluginOauthPeerIdentity } from '@cindy/device-link';++const action: PluginOauthAction = {+ requestId: 'card-1',+ actionId: 'oauth_connect:account',+ expectedRevision: 1,+};+function fixture() {+ let now = Date.now(),+ owner: string | null = 'membership:g1';+ const identity = {+ key: new OauthHostIdentity(),+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ };+ const request = vi.fn(async (_peer: string, raw: unknown) => {+ const r = raw as { op: string };+ if (r.op === 'start') return { id: 'inner-transaction', publicKey: new OauthBox().publicKey };+ return { phase: 'starting', marker: 'synthetic-private-result' };+ });+ const host = new AuthenticatedOauthHost({+ identity: () => identity,+ owner: () => owner,+ available: () => true,+ bind: async () => ({ ghostId: 'test-plugin', current: () => true }),+ request,+ now: () => now,+ });+ const target: PluginOauthPeerIdentity = {+ ...identity.key.descriptor,+ deviceId: identity.deviceId,+ realm: 'global' as const,+ membershipId: identity.membershipId,+ observedAtMs: now,+ expiresAtMs: now + 60_000,+ };+ const invoke = vi.fn((raw: unknown) => host.request('desktop', raw));+ const options = {+ trustIdentity: vi.fn(async () => {}),+ target,+ peer: 'desktop',+ action,+ ghostId: 'test-plugin',+ invoke,+ assertCurrent: () => {},+ now: () => now,+ };+ return {+ host,+ target,+ options,+ request,+ invoke,+ now: (v: number) => {+ now = v;+ },+ owner: (v: string | null) => {+ owner = v;+ },+ };+}++describe('signed OAuth transport with explicit peer trust', () => {+ it('authenticates before any side effect and encrypts all subsequent request/reply bodies', async () => {+ const f = fixture(),+ call = await authenticateOauthController(f.options);+ expect(f.request).not.toHaveBeenCalled();+ await expect(call({ op: 'capabilities' })).resolves.toMatchObject({+ marker: 'synthetic-private-result',+ });+ expect(JSON.stringify(f.invoke.mock.calls)).not.toContain('capabilities');+ const frame = f.invoke.mock.calls[1][0];+ expect(JSON.stringify(await f.host.request('desktop', frame))).not.toContain(+ 'synthetic-private-result',+ );+ expect(f.request).toHaveBeenCalledTimes(1); // identical retry returns the cached ciphertext, without replaying work+ });+ it('rejects the former raw v1 transport', async () => {+ const f = fixture();+ await expect(+ f.host.request('desktop', { op: 'start', ...action, publicKey: new OauthBox().publicKey }),+ ).rejects.toThrow();+ await expect(f.host.request('desktop', { op: 'capabilities' })).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('rejects reuse of an authenticated nonce with a different ciphertext before dispatch', async () => {+ const f = fixture(), key = new OauthBox();+ const reply = parsePluginOauthHelloReply(await f.host.request('desktop', {+ op: 'hello', version: 3, nonce: randomBytes(32).toString('base64url'),+ publicKey: key.publicKey, action,+ }));+ const payload = { nonce: randomBytes(32).toString('base64url'), request: { op: 'capabilities' } };+ const frame = () => ({+ op: 'exchange', id: reply.id,+ box: key.seal(reply.publicKey, `authenticated-plugin-oauth-v3:${reply.id}`, 'callback', payload),+ });+ const first = frame();+ const result = await f.host.request('desktop', first);+ expect(await f.host.request('desktop', first)).toEqual(result);+ await expect(f.host.request('desktop', frame())).rejects.toThrow();+ expect(f.request).toHaveBeenCalledTimes(1);+ });++ it('rejects a mutated authenticated envelope without invoking the transaction', async () => {+ const f = fixture(), call = await authenticateOauthController(f.options);+ await call({ op: 'capabilities' });+ const frame = f.invoke.mock.calls[1][0] as { op: string; id: string; box: string };+ const ciphertext = Buffer.from(frame.box, 'base64url');+ ciphertext[16] ^= 1;+ await expect(f.host.request('desktop', { ...frame, box: ciphertext.toString('base64url') })).rejects.toThrow();+ expect(f.request).toHaveBeenCalledTimes(1);+ });+ it('rejects relay substitution of the client ephemeral key, before provider or browser work', async () => {+ const f = fixture(),+ attacker = new OauthBox();+ await expect(+ authenticateOauthController({+ ...f.options,+ invoke: (raw) =>+ f.host.request('desktop', { ...(raw as object), publicKey: attacker.publicKey }),+ }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it.each(['publicKey', 'deviceId', 'membershipId', 'realm', 'bootId'] as const)(+ 'rejects a substituted trusted %s',+ async (field) => {+ const f = fixture();+ const target = {+ ...f.target,+ [field]:+ field === 'publicKey'+ ? new OauthHostIdentity().descriptor.publicKey+ : 'different-identity',+ };+ await expect(authenticateOauthController({ ...f.options, target })).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ },+ );+ it.each(['peer', 'ghostId'] as const)('rejects a different %s binding', async (field) => {+ const f = fixture();+ await expect(+ authenticateOauthController({ ...f.options, [field]: 'wrong-target' }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('binds the exact card action and prevents a relay from changing it', async () => {+ const f = fixture();+ await expect(+ authenticateOauthController({+ ...f.options,+ invoke: (raw) =>+ f.host.request('desktop', {+ ...(raw as object),+ action: { ...action, actionId: 'different' },+ }),+ }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('rejects stale identity responses and an expired connection', async () => {+ const f = fixture();+ await expect(+ authenticateOauthController({+ ...f.options,+ target: { ...f.target, expiresAtMs: Date.now() - 1 },+ }),+ ).rejects.toThrow();+ expect(f.invoke).not.toHaveBeenCalled();+ const call = await authenticateOauthController(f.options);+ f.now(Date.now() + 6 * 60_000);+ await expect(call({ op: 'capabilities' })).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('rejects other peers and changed owners even with an authentic ciphertext', async () => {+ const f = fixture(),+ call = await authenticateOauthController(f.options);+ await call({ op: 'capabilities' });+ const frame = f.invoke.mock.calls[1][0];+ await expect(f.host.request('other-desktop', frame)).rejects.toThrow();+ f.owner('membership:g2');+ await expect(f.host.request('desktop', frame)).rejects.toThrow();+ expect(f.request).toHaveBeenCalledTimes(1);+ });+ it('prevents a connection from starting another card', async () => {+ const f = fixture(),+ call = await authenticateOauthController(f.options);+ await expect(+ call({+ op: 'start',+ ...action,+ requestId: 'different-card',+ publicKey: new OauthBox().publicKey,+ }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('rejects forged plaintext success and previously valid replies to a new request', async () => {+ const f = fixture();+ let prior: unknown,+ forged = false;+ const call = await authenticateOauthController({+ ...f.options,+ invoke: async (raw) => {+ if (forged) return prior;+ const v = await f.invoke(raw);+ if ((raw as { op: string }).op === 'exchange') prior = v;+ return v;+ },+ });+ await call({ op: 'capabilities' });+ forged = true;+ await expect(call({ op: 'capabilities' })).rejects.toThrow();+ prior = { phase: 'succeeded' };+ await expect(call({ op: 'capabilities' })).rejects.toThrow();+ });+ it('limits peer invalidation to that peer', async () => {+ const f = fixture(),+ a = await authenticateOauthController(f.options);+ const b = await authenticateOauthController({+ ...f.options,+ peer: 'desktop-b',+ invoke: (raw) => f.host.request('desktop-b', raw),+ });+ f.host.invalidate('desktop');+ await expect(a({ op: 'capabilities' })).rejects.toThrow();+ await expect(b({ op: 'capabilities' })).resolves.toMatchObject({ phase: 'starting' });+ });+ it('rejects extra handshake fields including caller-supplied authority/token', async () => {+ const f = fixture();+ await expect(+ f.host.request('desktop', {+ op: 'hello',+ version: 3,+ nonce: randomBytes(32).toString('base64url'),+ publicKey: new OauthBox().publicKey,+ action,+ authority: 'https://attacker.example',+ }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/authorizationAdapters.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/authorizationAdapters.test.tsnew file mode 100644index 0000000000..d0e3d6ce42--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authorizationAdapters.test.ts@@ -0,0 +1,414 @@+import http from 'node:http';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { PluginAuthorizationRequest } from '@cindy/device-link';+import { openPluginAuthorizationCard } from '../deviceCard.js';+import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';+import { OauthTransactions } from '../transactions.js';+import { assistPluginOauth } from '../controller.js';+import { openAuthorizationOffer } from '../authorizationAdapters.js';+import {+ authenticateOauthController,+ AuthenticatedOauthHost,+ OauthHostIdentity,+} from '../authentication.js';++const cleanups: Array<() => void> = [];+afterEach(() => cleanups.splice(0).forEach((close) => close()));+async function unusedPort() {+ const server = http.createServer();+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));+ const port = (server.address() as { port: number }).port;+ await new Promise<void>((r) => server.close(() => r()));+ return port;+}+async function loopback() {+ const callbackUrl = 'http://127.0.0.1:' + (await unusedPort()) + '/cli/callback';+ const state = 'cli_state_0123456789';+ const url = new URL('https://provider.example/authorize');+ url.search = new URLSearchParams({+ client_id: 'fixture',+ response_type: 'code',+ state,+ redirect_uri: callbackUrl,+ code_challenge: 'p'.repeat(43),+ code_challenge_method: 'S256',+ }).toString();+ return { kind: 'loopback' as const, url: url.toString(), callbackUrl, state };+}+function harness(request: PluginAuthorizationRequest) {+ let current = true;+ const events: unknown[] = [],+ wire: unknown[] = [];+ const bridge = new GhostSetupInteractionBridge({ broadcast: (...args) => events.push(args) });+ const abort = new AbortController(),+ cancel = vi.fn(() => abort.abort());+ const card = openPluginAuthorizationCard(+ {+ ghost: { id: 'fixture-plugin', name: 'Fixture' },+ sessionId: 'task',+ request,+ signal: abort.signal,+ cancel,+ assertCurrent: () => {+ if (!current) throw new Error('stale');+ },+ },+ {+ bridge,+ openExternal: async () => {+ throw new Error('source browser forbidden');+ },+ copy: { title: 'Authorize', description: 'Continue on {{host}}' },+ },+ );+ const snapshot = bridge.pendingSnapshots()[0].request;+ const action = {+ requestId: snapshot.requestId,+ actionId: snapshot.steps[0].action!.id,+ expectedRevision: 0,+ };+ const owner = () => (current ? 'membership' : null);+ const bind = async () => ({+ ghostId: 'fixture-plugin',+ current: () => bridge.pendingSnapshots().length === 1,+ });+ const tx = new OauthTransactions({+ owner,+ available: () => true,+ bind,+ run: (a) => bridge.resolve(a.requestId, { kind: 'plugin_setup', action: 'run_action', ...a }),+ });+ const identity = {+ key: new OauthHostIdentity(),+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ };+ const authenticated = new AuthenticatedOauthHost({+ identity: () => identity,+ owner,+ available: () => true,+ bind,+ request: (peer, raw) => tx.request(peer, raw),+ });+ const target = {+ ...identity.key.descriptor,+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ observedAtMs: Date.now(),+ expiresAtMs: Date.now() + 60_000,+ };+ const invoke = async (raw: unknown) => {+ const reply = await authenticated.request('desktop', raw);+ wire.push(raw, reply);+ return reply;+ };+ const assist = async (+ openExternal: (url: string) => Promise<void>,+ extra: Partial<Parameters<typeof assistPluginOauth>[0]> = {},+ ) => {+ const call = await authenticateOauthController({+ trustIdentity: async () => {},+ target,+ peer: 'desktop',+ action,+ ghostId: 'fixture-plugin',+ invoke,+ assertCurrent() {},+ });+ return assistPluginOauth(+ {+ invoke: call,+ openExternal,+ assertCurrent() {},+ pause: () => new Promise((r) => setTimeout(r, 1)),+ ...extra,+ },+ action,+ );+ };+ cleanups.push(() => {+ card.dispose();+ tx.cancelPeer();+ authenticated.invalidate();+ });+ return {+ card,+ bridge,+ events,+ wire,+ tx,+ action,+ cancel,+ assist,+ abort,+ stale: () => {+ current = false;+ },+ };+}++describe('generic authorization through the signed Host bridge', () => {+ it.each(['browser', 'loopback'] as const)(+ 'reopens the current generic %s transaction and closes its presentation',+ async (kind) => {+ const request =+ kind === 'loopback'+ ? await loopback()+ : {+ kind,+ url: 'https://provider.example/authorize?state=synthetic',+ };+ let current = true;+ const open = vi.fn(async () => {}),+ dismiss = vi.fn();+ let reopen!: () => Promise<void>;+ const handle = await openAuthorizationOffer(+ {+ kind: 'authorization',+ state: 's'.repeat(43),+ request,+ },+ {+ openExternal: open,+ deadline: Date.now() + 60_000,+ assertCurrent() {+ if (!current) throw new Error('stale');+ },+ deliver: async () => {},+ failed() {},+ presentBrowserAuthorization: (_expiresAt, callback) => {+ reopen = callback;+ return dismiss;+ },+ },+ );+ cleanups.push(() => handle.close());+ await reopen();+ expect(open).toHaveBeenCalledTimes(2);+ expect(open).toHaveBeenLastCalledWith(request.url);+ current = false;+ await expect(reopen()).rejects.toThrow('stale');+ expect(open).toHaveBeenCalledTimes(2);+ handle.close('completed');+ expect(dismiss).toHaveBeenCalledWith('completed');+ },+ );++ it('rejects an expired challenge before a browser or callback listener is opened', async () => {+ const openExternal = vi.fn(),+ deliver = vi.fn();+ await expect(+ openAuthorizationOffer(+ {+ kind: 'authorization',+ state: 's'.repeat(43),+ request: { kind: 'device', url: 'https://provider.example/activate', expiresAt: 1000 },+ },+ { openExternal, deliver, deadline: 5000, now: () => 1000, assertCurrent() {}, failed() {} },+ ),+ ).rejects.toThrow();+ expect(openExternal).not.toHaveBeenCalled();+ expect(deliver).not.toHaveBeenCalled();+ });++ it('does not take a callback port already owned by another local process', async () => {+ const request = await loopback(),+ h = harness(request);+ const server = http.createServer((_req, res) => res.end('existing-listener'));+ await new Promise<void>((r) =>+ server.listen(Number(new URL(request.callbackUrl).port), '127.0.0.1', r),+ );+ cleanups.push(() => {+ server.close();+ server.closeAllConnections();+ });+ const open = vi.fn();+ await expect(h.assist(open)).rejects.toThrow();+ expect(open).not.toHaveBeenCalled();+ expect(await (await fetch(request.callbackUrl)).text()).toBe('existing-listener');+ });++ it.each(['device', 'browser'] as const)(+ 'opens %s on the controller but waits for actual source verification',+ async (kind) => {+ const request =+ kind === 'device'+ ? {+ kind,+ url: 'https://provider.example/activate',+ userCode: 'abcdef123',+ expiresAt: Date.now() + 60_000,+ }+ : { kind, url: 'https://provider.example/qr?request=synthetic-challenge' };+ const h = harness(request);+ const clear = vi.fn(),+ dismiss = vi.fn(),+ copy = vi.fn(() => clear),+ present = vi.fn(() => dismiss);+ let finished = false;+ const assisting = h+ .assist(+ async (url) => {+ expect(url).toBe(request.url);+ },+ { copyDeviceCode: copy, presentDeviceCode: present },+ )+ .then((result) => {+ finished = true;+ return result;+ });+ await expect(h.card.result).resolves.toEqual({ kind: 'opened' });+ expect(finished).toBe(false);+ if (kind === 'device') {+ expect(copy).toHaveBeenCalledWith('abcdef123');+ expect(present).toHaveBeenCalledWith(+ expect.objectContaining({ expiresAt: request.expiresAt }),+ clear,+ );+ }+ h.card.finish(true);+ await expect(assisting).resolves.toEqual({ accepted: true });+ if (kind === 'device') {+ expect(clear).toHaveBeenCalled();+ expect(dismiss).toHaveBeenCalledWith('completed');+ }+ for (const secret of ['abcdef123', 'synthetic-challenge', request.url])+ expect(JSON.stringify([h.wire, h.events])).not.toContain(secret);+ },+ );++ it('delivers a real loopback callback privately with the CLI state, and consumes it once', async () => {+ const request = await loopback(),+ h = harness(request);+ let browserDone!: () => void;+ const browser = new Promise<void>((r) => {+ browserDone = r;+ });+ const assisting = h.assist(async () => {+ const bad = await fetch(request.callbackUrl + '?state=wrong&code=synthetic');+ expect(bad.status).toBe(400);+ const result = await fetch(+ request.callbackUrl + '?state=' + request.state + '&code=synthetic-callback',+ );+ expect(result.status).toBe(200);+ expect(await result.text()).not.toContain('synthetic-callback');+ const repeated = await fetch(+ request.callbackUrl + '?state=' + request.state + '&code=synthetic-callback',+ );+ expect(repeated.status).toBe(409);+ browserDone();+ });+ await expect(h.card.result).resolves.toEqual({+ kind: 'callback',+ state: request.state,+ code: 'synthetic-callback',+ });+ await browser;+ h.card.finish(true); // CLI exchange/store/probe has completed.+ await expect(assisting).resolves.toEqual({ accepted: true });+ for (const secret of ['synthetic-callback', request.state, request.url, request.callbackUrl])+ expect(JSON.stringify([h.wire, h.events])).not.toContain(secret);+ await expect(fetch(request.callbackUrl)).rejects.toThrow();+ });++ it('cannot turn a provider denial into a successful card even if the CLI misreports success', async () => {+ const request = await loopback(),+ h = harness(request);+ const assisting = h.assist(async () => {+ await fetch(request.callbackUrl + '?state=' + request.state + '&error=access_denied');+ });+ const rejection = expect(assisting).rejects.toThrow();+ await expect(h.card.result).resolves.toEqual({+ kind: 'callback',+ state: request.state,+ error: 'access_denied',+ });+ h.card.finish(true);+ await rejection;+ expect(JSON.stringify(h.events)).not.toContain('"phase":"satisfied"');+ });++ it.each(['call', 'card', 'peer', 'owner'] as const)(+ 'rejects a late completion after %s invalidation',+ async (reason) => {+ const h = harness({ kind: 'browser', url: 'https://provider.example/confirm' });+ const assisting = h.assist(async () => {});+ const rejection = expect(assisting).rejects.toThrow();+ await h.card.result;+ if (reason === 'call') h.abort.abort();+ if (reason === 'card') h.bridge.cleanupForSession('task', 'session_closed');+ if (reason === 'peer') h.tx.cancelPeer('desktop');+ if (reason === 'owner') h.stale();+ h.card.finish(true);+ await rejection;+ expect(JSON.stringify(h.events)).not.toContain('"phase":"satisfied"');+ },+ );++ it('rejects unsupported old controllers before opening a browser', async () => {+ const h = harness({ kind: 'browser', url: 'https://provider.example/confirm' });+ const open = vi.fn();+ const assisting = assistPluginOauth(+ {+ invoke: async (request) => {+ const result = await h.tx.request('desktop', request);+ if (request.op === 'capabilities')+ return { ...(result as object), authorizationV1: undefined };+ return result;+ },+ openExternal: open,+ assertCurrent() {},+ pause: () => new Promise((r) => setTimeout(r, 1)),+ },+ h.action,+ );+ await expect(assisting).rejects.toThrow();+ await expect(h.card.result).rejects.toThrow();+ expect(open).not.toHaveBeenCalled();+ });++ it('keeps local CLI listeners in control of their own callback port', async () => {+ const request = await loopback();+ const server = http.createServer((_req, res) => res.end('CLI callback'));+ await new Promise<void>((r) =>+ server.listen(Number(new URL(request.callbackUrl).port), '127.0.0.1', r),+ );+ cleanups.push(() => {+ server.close();+ server.closeAllConnections();+ });+ const bridge = new GhostSetupInteractionBridge({ broadcast() {} });+ const abort = new AbortController();+ const open = vi.fn(async () => {+ expect(await (await fetch(request.callbackUrl)).text()).toBe('CLI callback');+ });+ const card = openPluginAuthorizationCard(+ {+ request,+ ghost: { id: 'p', name: 'P' },+ sessionId: 't',+ signal: abort.signal,+ assertCurrent() {},+ cancel: () => abort.abort(),+ },+ { bridge, openExternal: open, copy: { title: 'Authorize', description: '{{host}}' } },+ );+ cleanups.push(card.dispose);+ const snapshot = bridge.pendingSnapshots()[0].request;+ bridge.resolve(+ snapshot.requestId,+ {+ kind: 'plugin_setup',+ action: 'run_action',+ actionId: snapshot.steps[0].action!.id,+ expectedRevision: 0,+ },+ { isDestroyed: () => false } as never,+ );+ await expect(card.result).resolves.toEqual({ kind: 'opened' });+ card.finish(true);+ expect(open).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/bridge.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/bridge.test.tsnew file mode 100644index 0000000000..5975e0377a--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/bridge.test.ts@@ -0,0 +1,471 @@+import http from 'node:http';+import { createHash } from 'node:crypto';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ parsePluginOauthRequest,+ type PluginOauthOffer,+ type PluginOauthRequest,+} from '@cindy/device-link';+import { OauthBox } from '../box.js';+import { OauthTransactions } from '../transactions.js';+import { getRemoteOauthContext, type RemoteOauthContext } from '../context.js';+import { assistPluginOauth, listenForOauthCallback, parseOauthOffer } from '../controller.js';+import { GhostOauthAccountManager } from '../../cindy-brain/ghostOauthAccounts.js';+import { cancelActiveGhostOauthFlow } from '../../cindy-brain/ghostOauthFlow.js';++const action = {+ requestId: 'request-1',+ actionId: 'oauth_connect:secret:account',+ expectedRevision: 1,+};+const state = 's'.repeat(43);+const offer: PluginOauthOffer = {+ authorizeUrl: `https://provider.example/authorize?response_type=code&state=${state}`,+ callbackUrl: 'http://127.0.0.1:12345/callback',+ state,+ corsOrigins: ['https://provider.example'],+ corsHosts: ['*.delivery.example'],+};+const hosts: OauthTransactions[] = [];+afterEach(() => {+ for (const h of hosts.splice(0)) h.cancelPeer();+ cancelActiveGhostOauthFlow();+});++function harness() {+ let owner = 'member:g1';+ let live = true;+ let now = 100;+ const contexts = new Map<string, RemoteOauthContext>();+ const host = new OauthTransactions({+ owner: () => owner,+ available: () => live,+ now: () => now,+ bind: async (a) => ({ ghostId: 'test-plugin', current: () => a.expectedRevision === 1 }),+ run: (a) => {+ contexts.set(a.requestId, getRemoteOauthContext()!);+ return true;+ },+ });+ hosts.push(host);+ const controller = new OauthBox();+ const start = async (+ peer = 'desktop-1',+ requestId = action.requestId,+ capabilities: Partial<+ Pick<+ Extract<PluginOauthRequest, { op: 'start' }>,+ 'authorizationV1' | 'deviceUserCode' | 'secretSubmission'+ >+ > = {},+ ) =>+ (await host.request(peer, {+ op: 'start',+ ...action,+ requestId,+ publicKey: controller.publicKey,+ ...capabilities,+ })) as { id: string; publicKey: string };+ return {+ host,+ controller,+ contexts,+ start,+ owner: (v: string) => {+ owner = v;+ },+ live: (v: boolean) => {+ live = v;+ },+ now: (v: number) => {+ now = v;+ },+ };+}++describe('remote OAuth transactions', () => {+ it('encrypts offers and callbacks with transaction and direction binding', () => {+ const a = new OauthBox();+ const b = new OauthBox();+ const c = new OauthBox();+ const sealed = a.seal(b.publicKey, 'tx1', 'offer', offer);+ expect(sealed).not.toContain('provider');+ expect(sealed).not.toContain(state);+ expect(b.open(a.publicKey, 'tx1', 'offer', sealed)).toEqual(offer);+ for (const bad of [+ () => b.open(a.publicKey, 'tx2', 'offer', sealed),+ () => b.open(a.publicKey, 'tx1', 'callback', sealed),+ () => c.open(a.publicKey, 'tx1', 'offer', sealed),+ () => b.open(a.publicKey, 'tx1', 'offer', sealed.slice(1)),+ ])+ expect(bad).toThrow('OAUTH_BRIDGE_INVALID');+ });+ it('rejects plaintext callbacks, unknown fields and arbitrary transport commands', () => {+ for (const v of [+ { op: 'callback', id: 'tx', code: 'synthetic-code' },+ { op: 'status', id: 'tx', url: 'http://localhost' },+ { op: 'start', ...action, publicKey: new OauthBox().publicKey, scopes: ['extra'] },+ { op: 'fetch', url: 'http://localhost' },+ ])+ expect(parsePluginOauthRequest(v)).toBeNull();+ });+ it('requires the opening peer and matching state and consumes a callback once', async () => {+ const h = harness();+ const tx = await h.start();+ const context = h.contexts.get(action.requestId)!;+ const waiting = context.authorize(offer, new AbortController().signal);+ const status = (await h.host.request('desktop-1', { op: 'status', id: tx.id })) as {+ offer: string;+ };+ expect(h.controller.open(tx.publicKey, tx.id, 'offer', status.offer)).toEqual(offer);+ await expect(h.host.request('desktop-2', { op: 'status', id: tx.id })).rejects.toThrow();+ const box = (s: string) =>+ h.controller.seal(tx.publicKey, tx.id, 'callback', { state: s, code: 'synthetic-code' });+ await expect(+ h.host.request('desktop-1', { op: 'callback', id: tx.id, box: box('x'.repeat(43)) }),+ ).rejects.toThrow();+ const valid = box(state);+ await h.host.request('desktop-1', { op: 'callback', id: tx.id, box: valid });+ await expect(waiting).resolves.toEqual({ state, code: 'synthetic-code' });+ await expect(+ h.host.request('desktop-1', { op: 'callback', id: tx.id, box: valid }),+ ).resolves.toEqual({ accepted: true });+ await expect(+ h.host.request('desktop-1', { op: 'callback', id: tx.id, box: box(state) }),+ ).rejects.toThrow();+ context.finish(true);+ await expect(h.host.request('desktop-1', { op: 'status', id: tx.id })).resolves.toEqual({+ phase: 'succeeded',+ });+ await expect(+ h.host.request('desktop-1', { op: 'callback', id: tx.id, box: valid }),+ ).rejects.toThrow();+ });+ it.each(['owner', 'expiry', 'cancel', 'card', 'disconnect'] as const)(+ 'invalidates in-flight work on %s',+ async (cause) => {+ const h = harness();+ const tx = await h.start();+ const context = h.contexts.get(action.requestId)!;+ const pending = context.authorize(offer, new AbortController().signal);+ const rejected = expect(pending).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ if (cause === 'owner') h.owner('other:g2');+ if (cause === 'expiry') h.now(300_101);+ if (cause === 'disconnect') h.host.cancelPeer('desktop-1');+ if (cause === 'card') h.host.cancelRequest(action.requestId);+ if (cause === 'cancel') await h.host.request('desktop-1', { op: 'cancel', id: tx.id });+ expect(() => context.assertCurrent()).toThrow();+ await rejected;+ },+ );+ it('limits disconnect to its peer, including starts still awaiting card lookup', async () => {+ const h = harness();+ await h.start('desktop-1', 'card-a');+ await h.start('desktop-2', 'card-b');+ h.host.cancelPeer('desktop-1');+ expect(() => h.contexts.get('card-a')!.assertCurrent()).toThrow();+ expect(() => h.contexts.get('card-b')!.assertCurrent()).not.toThrow();+ let release!: () => void;+ const run = vi.fn(() => true);+ const slow = new OauthTransactions({+ owner: () => 'owner',+ available: () => true,+ bind: () =>+ new Promise((resolve) => {+ release = () => resolve({ ghostId: 'p', current: () => true });+ }),+ run,+ });+ hosts.push(slow);+ const pending = slow.request('desktop-1', {+ op: 'start',+ ...action,+ publicKey: h.controller.publicKey,+ });+ slow.cancelPeer('desktop-1');+ release();+ await expect(pending).rejects.toThrow();+ expect(run).not.toHaveBeenCalled();+ });+ it('rejects concurrent starts of the same card', async () => {+ const h = harness();+ await h.start();+ await expect(h.start()).rejects.toThrow();+ });+});++describe('shared authorization transaction lifecycle', () => {+ const modes = ['oauth', 'legacy-device', 'device', 'browser', 'loopback', 'secret'] as const;+ const presentation = {+ ghostName: 'Fixture',+ title: 'API Key',+ description: '',+ intro: '',+ fieldLabel: 'API Key',+ fieldDescription: '',+ maxLength: 200,+ };+ function begin(mode: (typeof modes)[number], context: RemoteOauthContext, signal: AbortSignal) {+ if (mode === 'oauth') return context.authorize(offer, signal);+ if (mode === 'legacy-device')+ return context.authorizeDevice!(+ {+ kind: 'device',+ authorizeUrl: 'https://provider.example/device',+ state,+ },+ signal,+ );+ if (mode === 'secret')+ return context.submitSecret!({ kind: 'secret-entry', state, presentation });+ const callbackUrl = 'http://127.0.0.1:12345/cli/callback';+ const cliState = 'cli_state_0123456789';+ const params = new URLSearchParams({+ client_id: 'fixture',+ response_type: 'code',+ state: cliState,+ redirect_uri: callbackUrl,+ code_challenge: 'c'.repeat(43),+ code_challenge_method: 'S256',+ });+ return context.authorizePlugin!(+ {+ kind: 'authorization',+ state,+ request:+ mode === 'loopback'+ ? {+ kind: 'loopback',+ url: `https://provider.example/authorize?${params}`,+ callbackUrl,+ state: cliState,+ }+ : { kind: mode, url: 'https://provider.example/activate' },+ },+ signal,+ );+ }++ it.each(modes)('cancels a pending %s offer and rejects a later success', async (mode) => {+ const h = harness();+ const tx = await h.start('desktop-1', action.requestId, {+ authorizationV1: true,+ secretSubmission: true,+ });+ const context = h.contexts.get(action.requestId)!;+ const signal = new AbortController().signal;+ const waiting = begin(mode, context, signal);+ const rejected = expect(waiting).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ expect(() => begin(mode, context, signal)).toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ h.host.cancelRequest(action.requestId);+ await rejected;+ context.finish(true);+ await expect(h.host.request('desktop-1', { op: 'status', id: tx.id })).resolves.toEqual({+ phase: 'cancelled',+ });+ });++ it.each(modes)(+ 'keeps %s bound to its reply type and source lifetime after exchange',+ async (mode) => {+ const h = harness();+ const tx = await h.start('desktop-1', action.requestId, {+ authorizationV1: true,+ secretSubmission: true,+ });+ const context = h.contexts.get(action.requestId)!;+ const source = new AbortController();+ const waiting = begin(mode, context, source.signal);+ const reply =+ mode === 'secret'+ ? { kind: 'secret-value', state, value: 'synthetic-pat' }+ : mode === 'oauth' || mode === 'loopback'+ ? { state, code: 'synthetic-code' }+ : { kind: 'device-opened', state };+ const wrong =+ mode === 'secret'+ ? { kind: 'device-opened', state }+ : { kind: 'secret-value', state, value: 'synthetic-pat' };+ const callback = (value: unknown) =>+ h.host.request('desktop-1', {+ op: 'callback',+ id: tx.id,+ box: h.controller.seal(tx.publicKey, tx.id, 'callback', value),+ });+ await expect(callback(wrong)).rejects.toThrow();+ await callback(reply);+ await waiting;+ await expect(h.host.request('desktop-1', { op: 'status', id: tx.id })).resolves.toEqual({+ phase: 'exchanging',+ });+ if (mode === 'secret') h.host.cancelRequest(action.requestId);+ else source.abort();+ context.finish(true);+ await expect(h.host.request('desktop-1', { op: 'status', id: tx.id })).resolves.toEqual({+ phase: 'cancelled',+ });+ },+ );+});++describe('real local loopback callback and cloud-owned account exchange', () => {+ it('stores only on the cloud Host; callback state/PKCE and redirect remain the original transaction', async () => {+ const vault = new Map<string, string>();+ const wire: unknown[] = [];+ let challenge = '';+ let exchangeCount = 0;+ const manager = new GhostOauthAccountManager({+ vault: {+ read: (g, k) => vault.get(`${g}/${k}`) ?? null,+ store: (g, k, v) => {+ vault.set(`${g}/${k}`, v);+ return true;+ },+ remove: (g, k) => {+ vault.delete(`${g}/${k}`);+ },+ },+ openExternal: () => {+ throw new Error('Cloud browser must not open');+ },+ fetchImpl: vi.fn(async (_url, init) => {+ const form = new URLSearchParams(String(init?.body));+ exchangeCount++;+ expect(form.get('code')).toBe('synthetic-code');+ expect(createHash('sha256').update(form.get('code_verifier')!).digest('base64url')).toBe(+ challenge,+ );+ return new Response(+ JSON.stringify({+ access_token: 'synthetic-access',+ refresh_token: 'synthetic-refresh',+ expires_in: 3600,+ }),+ );+ }),+ });+ let accountRun: Promise<unknown> | undefined;+ const host = new OauthTransactions({+ owner: () => 'owner',+ available: () => true,+ bind: async () => ({ ghostId: 'test-plugin', current: () => true }),+ run: () => {+ const remote = getRemoteOauthContext()!;+ accountRun = manager+ .connectAccount(+ 'test-plugin',+ 'account',+ {+ authorizeUrl: 'https://provider.example/authorize',+ tokenUrl: 'https://provider.example/token',+ clientId: 'synthetic-client',+ scopes: ['read'],+ },+ { remote },+ )+ .then(+ (result) => {+ remote.finish(result.ok);+ return result;+ },+ (error) => {+ remote.finish(false);+ throw error;+ },+ );+ return true;+ },+ });+ hosts.push(host);+ const result = await assistPluginOauth(+ {+ invoke: async (request) => {+ wire.push(request);+ const reply = await host.request('desktop-1', request);+ wire.push(reply);+ return reply;+ },+ assertCurrent: () => {},+ pause: () => new Promise((resolve) => setTimeout(resolve, 5)),+ openExternal: async (raw) => {+ const authorize = new URL(raw);+ challenge = authorize.searchParams.get('code_challenge')!;+ const url = new URL(authorize.searchParams.get('redirect_uri')!);+ url.searchParams.set('state', authorize.searchParams.get('state')!);+ url.searchParams.set('code', 'synthetic-code');+ const response = await fetch(url);+ expect(response.status).toBe(200);+ expect(await response.text()).toContain('callback received');+ },+ },+ action,+ );+ expect(result).toEqual({ accepted: true });+ await accountRun;+ expect(exchangeCount).toBe(1);+ expect([...vault.values()]).toContain('synthetic-refresh');+ const serialized = JSON.stringify(wire);+ for (const value of [+ 'synthetic-code',+ 'synthetic-access',+ 'synthetic-refresh',+ 'provider.example',+ challenge,+ ])+ expect(serialized).not.toContain(value);+ });+ it('binds exact path, method, state and CORS without consuming malformed requests', async () => {+ const probe = http.createServer();+ await new Promise<void>((r) => probe.listen(0, '127.0.0.1', r));+ const port = (probe.address() as { port: number }).port;+ await new Promise<void>((r) => probe.close(() => r()));+ const specific = { ...offer, callbackUrl: `http://127.0.0.1:${port}/callback` };+ const deliver = vi.fn(async () => {});+ const listener = await listenForOauthCallback(specific, deliver, () => {});+ try {+ const request = async (query: string, init?: RequestInit) => {+ const response = await fetch(specific.callbackUrl + query, init);+ await response.text();+ return response.status;+ };+ expect(await request('?state=wrong&code=synthetic-code')).toBe(400);+ expect(await request('?state=' + state + '&code=synthetic-code', { method: 'POST' })).toBe(+ 405,+ );+ expect(+ await request('?state=' + state + '&code=synthetic-code', {+ headers: { Origin: 'https://evil.example' },+ }),+ ).toBe(403);+ expect(await request('?state=' + state + '&state=' + state + '&code=synthetic-code')).toBe(+ 400,+ );+ expect(+ await request('', {+ method: 'OPTIONS',+ headers: { Origin: 'https://sub.delivery.example' },+ }),+ ).toBe(204);+ expect(deliver).not.toHaveBeenCalled();+ expect(await request('?state=' + state + '&code=synthetic-code')).toBe(200);+ expect(await request('?state=' + state + '&code=synthetic-code')).toBe(409);+ expect(deliver).toHaveBeenCalledOnce();+ await expect(listenForOauthCallback(specific, deliver, () => {})).rejects.toThrow();+ } finally {+ listener.close();+ }+ });+ it('never interprets a remote address, credential or command as a callback destination', () => {+ for (const callbackUrl of [+ 'http://localhost:123/cb',+ 'http://127.0.0.1.evil.example:123/cb',+ 'https://127.0.0.1:123/cb',+ 'http://127.0.0.1:123/cb?q=x',+ ])+ expect(() => parseOauthOffer({ ...offer, callbackUrl })).toThrow();+ expect(() => parseOauthOffer({ ...offer, command: 'execute' })).toThrow();+ expect(() =>+ parseOauthOffer({ ...offer, authorizeUrl: 'https://user:[email protected]' }),+ ).toThrow();+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.tsnew file mode 100644index 0000000000..09fb452a60--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts@@ -0,0 +1,308 @@+import { testOauthSigningKey } from './fixtures.js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { GhostManifest, GhostSetupAssessment } from '../../../shared/ghost.js';+import { createPluginConnectionPresentation } from '../../../shared/pluginOauth.js';+import { GhostSetupChangeBus } from '../../cindy-brain/ghostSetupChangeBus.js';+import { GhostSetupCoordinator } from '../../cindy-brain/ghostSetupCoordinator.js';+import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';+import { GhostConnectionManager } from '../../cindy-brain/ghostConnections.js';+import { executeGhostSetupConnectionSubmission } from '../../cindy-brain/ghostSetupConnectionExecutor.js';+import { initializePluginOauthCards } from '../cards.js';+import { assistPluginOauth, type OauthControllerDeps } from '../controller.js';+import {+ handleAssistPluginOauth,+ handleSubmitPluginConnection,+ type LocalOauthDeps,+} from '../localIpc.js';+import {+ invalidatePluginOauth,+ publishedPluginOauthIdentity,+ requestPluginOauth,+} from '../runtime.js';++const cleanups: Array<() => void> = [];+afterEach(() => {+ cleanups.splice(0).forEach((f) => f());+ invalidatePluginOauth();+});+const input = { host: 'https://git.example.test/', token: 'synthetic-connection-token' };+async function harness(fault?: 'vault' | 'owner' | 'manifest' | 'stale', configured = false) {+ let owner = 'membership';+ const values = new Map<string, string>(),+ wire: unknown[] = [],+ messages: unknown[] = [];+ const store = vi.fn((ghost: string, key: string, value: string) => {+ if (fault === 'vault') return false;+ values.set(`${ghost}:${key}`, value);+ return true;+ });+ const manager = new GhostConnectionManager({+ vault: {+ store,+ read: (ghost, key) => values.get(`${ghost}:${key}`) ?? null,+ remove: (ghost, key) => {+ values.delete(`${ghost}:${key}`);+ },+ readTail: () => null,+ },+ });+ if (configured) {+ manager.upsert('demo', 'service', {+ host: 'git.example.test',+ token: 'synthetic-old-token',+ max: 2,+ });+ manager.upsert('demo', 'service', {+ host: 'other.example.test',+ token: 'synthetic-other-token',+ max: 2,+ });+ store.mockClear();+ }+ const changes = new GhostSetupChangeBus();+ const bridge = new GhostSetupInteractionBridge({ broadcast: (...args) => messages.push(args) });+ const action = { id: 'manage_connection:connection:service', kind: 'manage_connection' as const };+ const manifest: GhostManifest = {+ schemaVersion: 2,+ id: 'demo',+ name: 'Demo',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ tools: [],+ network: {+ hosts: [],+ connections: [+ {+ key: 'service',+ label: 'Service',+ maxConnections: 2,+ inject: { header: 'PRIVATE-TOKEN', format: '{value}' },+ },+ ],+ },+ };+ const assess = (): GhostSetupAssessment => ({+ state: values.size ? 'ready' : 'required',+ revision: changes.currentRevision('demo'),+ groups: [+ {+ id: 'connection',+ mode: 'any_of',+ items: [+ {+ ref: 'connection:service',+ kind: 'connection',+ label: 'Service',+ state: values.size ? 'satisfied' : 'missing',+ actions: [action],+ },+ ],+ },+ ],+ });+ const coordinator = new GhostSetupCoordinator({+ bridge,+ changeBus: changes,+ assess,+ remoteConnection: true,+ validateTarget: () => ({ ok: true }),+ getGhostIdentity: () => ({ id: 'demo', name: 'Demo' }),+ executeAction: async () => ({ ok: true }),+ terminalGraceMs: 0,+ });+ const save = vi.fn((args) => {+ if (fault === 'owner') owner = 'different-owner';+ return executeGhostSetupConnectionSubmission(+ {+ manager,+ getAssessment: () =>+ fault === 'stale' ? { state: 'ready', revision: 2, groups: [] } : assess(),+ getManifest: () =>+ fault === 'manifest' ? { ...manifest, network: { hosts: [] } } : manifest,+ emitChange: () => changes.emit('demo', { source: 'connection', ref: 'service' }),+ },+ { ...args, expectedManifest: JSON.stringify(manifest) },+ );+ });+ initializePluginOauthCards({+ loadKey: testOauthSigningKey,+ bridge,+ bots: () => null,+ owner: () => owner,+ available: () => true,+ identity: () => ({+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ }),+ bindConnection: (args) => (value) => save({ ...args, value }),+ });+ const abort = new AbortController();+ const ready = coordinator.ensureReady({+ sessionId: 'task',+ ghostId: 'demo',+ signal: abort.signal,+ reauthorize: configured,+ });+ cleanups.push(() => abort.abort());+ await vi.waitFor(() => expect(bridge.pendingSnapshots()).toHaveLength(1));+ const snapshot = bridge.pendingSnapshots()[0].request;+ const target = {+ deviceId: 'cloud-device',+ ghostId: 'demo',+ requestId: snapshot.requestId,+ actionId: action.id,+ expectedRevision: snapshot.revision,+ };+ const presentation = createPluginConnectionPresentation(snapshot, snapshot.steps[0]);+ const openExternal = vi.fn(async () => {+ throw new Error('No browser for a connection form');+ });+ const deps: LocalOauthDeps = {+ owner: () => owner,+ assertTarget: (device) => {+ if (device !== 'cloud-device') throw new Error('target');+ },+ localDeviceId: () => 'desktop',+ openExternal,+ trustIdentity: async () => {},+ identity: async () => ({+ ...(await publishedPluginOauthIdentity())!,+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ observedAtMs: Date.now(),+ expiresAtMs: Date.now() + 60_000,+ }),+ invoke: async (_device, _channel, args) => {+ const result = await requestPluginOauth('desktop', args[0]);+ wire.push({ request: args[0], result });+ return { ok: true, result };+ },+ };+ return {+ ready,+ values,+ store,+ save,+ wire,+ messages,+ openExternal,+ manager,+ target,+ presentation,+ deps,+ abort,+ bridge,+ submit: (override: Record<string, unknown> = {}) =>+ handleSubmitPluginConnection(deps, {+ ...target,+ presentation,+ value: input,+ ...override,+ }),+ };+}++describe('authenticated exact-host connection form', () => {+ it('reopens an existing connection and replaces only its token after the signed submission commits', async () => {+ const h = await harness(undefined, true);+ const before = h.manager.list('demo', 'service');+ const receipt = vi.spyOn(h.bridge, 'connectionCommitted');+ expect(h.store).not.toHaveBeenCalled();+ expect(h.bridge.pendingSnapshots()).toHaveLength(1);+ await expect(h.submit()).resolves.toEqual({ accepted: true });+ expect(receipt).toHaveReturnedWith(true);+ await expect(h.ready).resolves.toMatchObject({ ok: true });+ expect(h.manager.list('demo', 'service')).toEqual(before);+ expect(h.manager.resolveTokenByHost('demo', 'service', 'git.example.test')).toBe(input.token);+ expect(h.manager.resolveTokenByHost('demo', 'service', 'other.example.test')).toBe(+ 'synthetic-other-token',+ );+ expect(h.save).toHaveBeenCalledTimes(1);+ expect(JSON.stringify([h.wire, h.messages])).not.toContain(input.token);+ expect(JSON.stringify([h.wire, h.messages])).not.toContain('synthetic-old-token');+ });+ it('cancelled reconfiguration keeps existing credentials and refuses the stale card', async () => {+ const h = await harness(undefined, true);+ h.abort.abort();+ await expect(h.ready).resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });+ await expect(h.submit()).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ expect(h.manager.resolveTokenByHost('demo', 'service', 'git.example.test')).toBe(+ 'synthetic-old-token',+ );+ });+ it('rejects an old reader before creating a transaction and drops private input', async () => {+ const invoke = vi.fn(async () => ({+ version: 1,+ callback: 'desktop-loopback',+ encrypted: true,+ secretSubmission: true,+ }));+ const deps: OauthControllerDeps = {+ invoke,+ assertCurrent: vi.fn(),+ openExternal: vi.fn(),+ connectionValue: input,+ };+ await expect(+ assistPluginOauth(deps, { requestId: 'card', actionId: 'connection', expectedRevision: 1 }),+ ).rejects.toThrow();+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(deps.connectionValue).toBeUndefined();+ });+ it('writes through the existing connection manager and resumes the card without plaintext in transport/history', async () => {+ const h = await harness();+ await expect(h.submit()).resolves.toEqual({ accepted: true });+ await expect(h.ready).resolves.toMatchObject({ ok: true });+ expect(h.manager.resolveTokenByHost('demo', 'service', 'git.example.test')).toBe(input.token);+ expect(h.manager.resolveTokenByHost('demo', 'service', 'other.example.test')).toBeNull();+ expect(h.manager.resolveTokenByHost('other-plugin', 'service', 'git.example.test')).toBeNull();+ expect(h.manager.list('demo', 'service')).toHaveLength(1);+ expect(h.openExternal).not.toHaveBeenCalled();+ expect(JSON.stringify([h.wire, h.messages])).not.toContain(input.token);+ for (const entry of h.wire as Array<{ request: { op: string }; result: unknown }>) {+ if (entry.request.op === 'exchange')+ await expect(requestPluginOauth('desktop', entry.request)).resolves.toEqual(entry.result);+ }+ expect(h.save).toHaveBeenCalledTimes(1);+ });+ it.each(['ghostName', 'title', 'description', 'intro', 'connectionKey'])(+ 'rejects changed displayed %s',+ async (field) => {+ const h = await harness();+ await expect(+ h.submit({ presentation: { ...h.presentation, [field]: 'changed' } }),+ ).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ },+ );+ it.each(['vault', 'owner', 'manifest', 'stale'] as const)(+ 'does not report saved when %s changes',+ async (fault) => {+ const h = await harness(fault);+ await expect(h.submit()).rejects.toThrow();+ expect(h.values.size).toBe(0);+ if (fault !== 'vault') expect(h.store).not.toHaveBeenCalled();+ },+ );+ it.each([+ { deviceId: 'other-device' },+ { ghostId: 'other-plugin' },+ { expectedRevision: 99 },+ { actionId: 'manage_connection:connection:another' },+ { storageKey: 'forged' },+ { value: { host: 'https://git.example.test/malicious', token: input.token } },+ ])('rejects cross-target/invalid input %#', async (override) => {+ const h = await harness();+ await expect(h.submit(override)).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ });+ it('does not grant input capability to ordinary assist', async () => {+ const h = await harness();+ await expect(handleAssistPluginOauth(h.deps, h.target)).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/deviceAuthorization.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/deviceAuthorization.test.tsnew file mode 100644index 0000000000..eeb168872f--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/deviceAuthorization.test.ts@@ -0,0 +1,349 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ parseDeviceAuthorizationUrl,+ parsePluginDeviceOffer,+ parsePluginOauthRequest,+} from '@cindy/device-link';+import { OauthTransactions } from '../transactions.js';+import { OauthBox } from '../box.js';+import { openDeviceAuthorizationCard } from '../deviceCard.js';+import { assistPluginOauth } from '../controller.js';+import { copyPrivateDeviceCode } from '../deviceCodeClipboard.js';+import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';++const url = 'https://provider.example/device?code=synthetic-private-code';+const cleanup: Array<() => void> = [];+afterEach(() => {+ cleanup.splice(0).forEach((f) => f());+});+function setup(userCode?: string) {+ let current = true;+ const events: unknown[] = [];+ const bridge = new GhostSetupInteractionBridge({+ broadcast: (...args) => {+ events.push(args);+ },+ });+ const controller = new AbortController();+ const cancel = vi.fn(() => controller.abort());+ const card = openDeviceAuthorizationCard(+ {+ ghost: { id: 'plugin-a', name: 'Plugin A' },+ sessionId: 'session-a',+ url: userCode ? 'https://github.com/login/device' : url,+ ...(userCode ? { userCode } : {}),+ signal: controller.signal,+ cancel,+ assertCurrent: () => {+ if (!current) throw new Error('stale');+ },+ },+ {+ bridge,+ openExternal: async () => {+ throw new Error('cloud browser forbidden');+ },+ copy: { title: 'Authorize Plugin Login', description: 'Authorize at {{host}}' },+ },+ );+ const snapshot = bridge.pendingSnapshots()[0].request;+ const action = {+ requestId: snapshot.requestId,+ actionId: snapshot.steps[0].action!.id,+ expectedRevision: 0,+ };+ const host = new OauthTransactions({+ owner: () => (current ? 'member-a' : 'member-b'),+ available: () => true,+ bind: async (a) =>+ a.requestId === action.requestId && a.expectedRevision === 0+ ? { ghostId: 'plugin-a', current: () => bridge.pendingSnapshots().length === 1 }+ : null,+ run: (a) => bridge.resolve(a.requestId, { kind: 'plugin_setup', action: 'run_action', ...a }),+ });+ cleanup.push(() => {+ card.dispose();+ host.cancelPeer();+ });+ return {+ bridge,+ events,+ controller,+ card,+ host,+ cancel,+ action,+ stale: () => {+ current = false;+ },+ };+}++describe('private device authorization', () => {+ it.each(['abcDEF123', 'AB CD EF', '123456'])(+ 'copies the exact generic provider code %s without erasing newer clipboard content',+ (code) => {+ let value = '';+ const clipboard = {+ writeText: (text: string) => {+ value = text;+ },+ readText: () => value,+ clear: () => {+ value = '';+ },+ };+ const clear = copyPrivateDeviceCode(clipboard, code);+ expect(value).toBe(code);+ clear();+ expect(value).toBe('');+ copyPrivateDeviceCode(clipboard, code);+ value = 'user clipboard';+ clear();+ expect(value).toBe('user clipboard');+ },+ );+ it.each([+ 'http://provider.example/login',+ 'https://user:[email protected]/login',+ 'https://127.0.0.1/login',+ 'https://[::1]/login',+ 'https://foo.localhost/login',+ 'https://provider.example/login#secret',+ 'https://provider.example/ bad',+ 'file:///tmp/login',+ 'https://provider.example\\@evil.example/login',+ ])('rejects unsafe URL %s', (bad) => {+ expect(() => parseDeviceAuthorizationUrl(bad)).toThrow();+ });+ it('keeps the device offer distinct from loopback and rejects extra fields', () => {+ expect(() =>+ parsePluginDeviceOffer({+ kind: 'device',+ authorizeUrl: url,+ state: 'a'.repeat(43),+ callbackUrl: 'http://127.0.0.1:4/',+ }),+ ).toThrow();+ });+ it('opens on the controller and waits for the cloud operation, exposing no private URL on the wire/card', async () => {+ const h = setup();+ const wire: unknown[] = [];+ let opened = false;+ let finished = false;+ const assisting = assistPluginOauth(+ {+ invoke: async (req) => {+ const res = await h.host.request('desktop-a', req);+ wire.push(req, res);+ return res;+ },+ assertCurrent: () => {},+ openExternal: async (value) => {+ expect(value).toBe(url);+ opened = true;+ },+ pause: () => new Promise((resolve) => setTimeout(resolve, 1)),+ },+ h.action,+ ).then((value) => {+ finished = true;+ return value;+ });+ await h.card.opened;+ expect(opened).toBe(true);+ expect(finished).toBe(false);+ expect(h.cancel).not.toHaveBeenCalled();+ expect(JSON.stringify([wire, h.events])).not.toContain('synthetic-private-code');+ h.card.finish(true); // The bound Node RPC has now verified its credential use.+ await expect(assisting).resolves.toEqual({ accepted: true });+ expect(h.cancel).not.toHaveBeenCalled();+ expect(h.bridge.pendingSnapshots()).toEqual([]);+ });+ it.each(['peer', 'card', 'call', 'owner'] as const)(+ 'cancels after browser open on %s and rejects late success',+ async (cause) => {+ const h = setup();+ const assisting = assistPluginOauth(+ {+ invoke: (req) => h.host.request('desktop-a', req),+ assertCurrent: () => {},+ openExternal: async () => {},+ pause: () => new Promise((r) => setTimeout(r, 1)),+ },+ h.action,+ );+ const rejection = expect(assisting).rejects.toThrow();+ await h.card.opened;+ if (cause === 'peer') h.host.cancelPeer('desktop-a');+ if (cause === 'card') h.bridge.cleanupForSession('session-a', 'session_closed');+ if (cause === 'call') h.controller.abort();+ if (cause === 'owner') {+ h.stale();+ await h.host.request('desktop-a', { op: 'capabilities' });+ }+ await rejection;+ expect(h.cancel).toHaveBeenCalled();+ h.card.finish(true);+ expect(JSON.stringify(h.events)).not.toContain('"phase":"satisfied"');+ expect(JSON.stringify(h.events)).not.toContain('synthetic-private-code');+ },+ );+ it('requires peer/state/mode binding and only acknowledges the identical opened retry', async () => {+ const h = setup();+ const key = new OauthBox();+ const start = (await h.host.request('desktop-a', {+ op: 'start',+ ...h.action,+ publicKey: key.publicKey,+ })) as { id: string; publicKey: string };+ const status = (await h.host.request('desktop-a', { op: 'status', id: start.id })) as {+ offer: string;+ };+ const offer = parsePluginDeviceOffer(+ key.open(start.publicKey, start.id, 'offer', status.offer),+ );+ const box = (value: unknown) => key.seal(start.publicKey, start.id, 'callback', value);+ for (const value of [+ { state: offer.state, code: 'fake-code' },+ { kind: 'device-opened', state: 'x'.repeat(43) },+ ]) {+ await expect(+ h.host.request('desktop-a', { op: 'callback', id: start.id, box: box(value) }),+ ).rejects.toThrow();+ }+ const valid = box({ kind: 'device-opened', state: offer.state });+ await expect(+ h.host.request('desktop-b', { op: 'callback', id: start.id, box: valid }),+ ).rejects.toThrow();+ await h.host.request('desktop-a', { op: 'callback', id: start.id, box: valid });+ await h.card.opened;+ await expect(+ h.host.request('desktop-a', { op: 'callback', id: start.id, box: valid }),+ ).resolves.toEqual({ accepted: true });+ await expect(+ h.host.request('desktop-a', {+ op: 'callback',+ id: start.id,+ box: box({ kind: 'device-opened', state: offer.state }),+ }),+ ).rejects.toThrow();+ await expect(h.host.request('desktop-a', { op: 'status', id: start.id })).resolves.toEqual({+ phase: 'exchanging',+ });+ h.card.finish(true);+ });+ it('does not open a cloud browser through generic remote run_action or stale revision', async () => {+ const h = setup();+ const rejected = expect(h.card.opened).rejects.toThrow();+ h.bridge.resolve(h.action.requestId, {+ kind: 'plugin_setup',+ action: 'run_action',+ actionId: h.action.actionId,+ expectedRevision: 0,+ });+ await Promise.resolve();+ expect(h.bridge.pendingSnapshots()[0].request.revision).toBe(0);+ h.controller.abort();+ await rejected;+ });+});++describe('private GitHub user code', () => {+ it('negotiates code support without changing old start requests', () => {+ const base = {+ op: 'start',+ requestId: 'request',+ actionId: 'action',+ expectedRevision: 0,+ publicKey: 'a'.repeat(59),+ };+ expect(parsePluginOauthRequest(base)).toEqual(base);+ expect(parsePluginOauthRequest({ ...base, deviceUserCode: true })).toEqual({+ ...base,+ deviceUserCode: true,+ });+ expect(parsePluginOauthRequest({ ...base, deviceUserCode: false })).toBeNull();+ expect(parsePluginOauthRequest({ ...base, userCode: 'ABCD-EFGH' })).toBeNull();+ });+ it('copies only inside local Main and never includes the code in card/model/relay metadata', async () => {+ const h = setup('ABCD-EFGH');+ const wire: unknown[] = [];+ const clear = vi.fn();+ const copy = vi.fn(() => clear);+ const closeView = vi.fn();+ const present = vi.fn(() => closeView);+ const assisting = assistPluginOauth(+ {+ invoke: async (req) => {+ const res = await h.host.request('desktop-a', req);+ wire.push(req, res);+ return res;+ },+ assertCurrent: () => {},+ copyDeviceCode: copy,+ presentDeviceCode: present,+ openExternal: async (value) => {+ expect(copy).toHaveBeenCalledWith('ABCD-EFGH');+ expect(value).toBe('https://github.com/login/device');+ },+ pause: () => new Promise((r) => setTimeout(r, 1)),+ },+ h.action,+ );+ await h.card.opened;+ expect(JSON.stringify([wire, h.events])).not.toContain('ABCD-EFGH');+ expect(clear).not.toHaveBeenCalled();+ expect(present).toHaveBeenCalledExactlyOnceWith(+ {+ userCode: 'ABCD-EFGH',+ authorizeUrl: 'https://github.com/login/device',+ expiresAt: expect.any(Number),+ },+ clear,+ );+ h.card.finish(true);+ expect(await assisting).toEqual({ accepted: true });+ expect(clear).toHaveBeenCalledOnce();+ expect(closeView).toHaveBeenCalledExactlyOnceWith('completed');+ });+ it('rejects an old controller before opening or delivering a code', async () => {+ const h = setup('ABCD-EFGH');+ const rejected = expect(h.card.opened).rejects.toThrow();+ const openExternal = vi.fn();+ await expect(+ assistPluginOauth(+ {+ invoke: (req) => h.host.request('desktop-a', req),+ assertCurrent: () => {},+ openExternal,+ pause: () => new Promise((r) => setTimeout(r, 1)),+ },+ h.action,+ ),+ ).rejects.toThrow();+ await rejected;+ expect(openExternal).not.toHaveBeenCalled();+ expect(h.cancel).toHaveBeenCalled();+ });+ it('clears only the device code it owns, preserving later user copies', () => {+ let value = '';+ const clipboard = {+ readText: () => value,+ writeText: (v: string) => {+ value = v;+ },+ clear: () => {+ value = '';+ },+ };+ const clear = copyPrivateDeviceCode(clipboard, 'ABCD-EFGH');+ expect(value).toBe('ABCD-EFGH');+ value = 'user content';+ clear();+ expect(value).toBe('user content');+ const clearNext = copyPrivateDeviceCode(clipboard, 'IJKL-MNOP');+ clearNext();+ expect(value).toBe('');+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.tsnew file mode 100644index 0000000000..89afe141fe--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts@@ -0,0 +1,203 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';+import { LocalDeviceCodeSessions } from '../deviceCodeSessions';+import { copyPrivateDeviceCode } from '../deviceCodeClipboard';+import { PLUGIN_OAUTH_DEVICE_CODE_CHANNEL } from '../../../shared/pluginOauthDeviceCode';++const target = {+ deviceId: 'device-a',+ ghostId: 'cindy-github',+ requestId: 'card-a',+ actionId: 'connect',+};+const scope = 'owner-a:window-a:frame-a';+beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(1000);+});+afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+});++function setup() {+ const registry = new LocalDeviceCodeSessions();+ let clipboard = '';+ let current = true;+ const board = {+ readText: () => clipboard,+ writeText: (code: string) => {+ clipboard = code;+ },+ clear: () => {+ clipboard = '';+ },+ };+ const clear = copyPrivateDeviceCode(board, 'TEST-CODE');+ const copy = vi.fn((code: string) => {+ copyPrivateDeviceCode(board, code);+ });+ const openExternal = vi.fn(async (_url: string) => {});+ const close = registry.present(+ scope,+ target,+ { userCode: 'TEST-CODE', authorizeUrl: 'https://github.com/login/device', expiresAt: 61_000 },+ {+ assertCurrent: () => {+ if (!current) throw new Error('stale');+ },+ copy,+ openExternal,+ clearClipboard: clear,+ },+ );+ return {+ registry,+ copy,+ openExternal,+ close,+ clear,+ clipboard: () => clipboard,+ overwrite: () => {+ clipboard = 'unrelated text';+ },+ stale: () => {+ current = false;+ },+ read: () => registry.handle(scope, { ...target, operation: 'read' }),+ };+}++it('returns only the display projection and supports repeated copy and exact reopen without restarting authorization', async () => {+ const h = setup();+ expect(await h.read()).toEqual({+ phase: 'ready',+ userCode: 'TEST-CODE',+ verificationHost: 'github.com',+ expiresAt: 61_000,+ copiedAt: 1000,+ });+ for (let i = 0; i < 2; i++) {+ h.overwrite();+ await h.registry.handle(scope, { ...target, operation: 'copy' });+ expect(h.clipboard()).toBe('TEST-CODE');+ }+ await h.registry.handle(scope, { ...target, operation: 'reopen' });+ expect(h.openExternal).toHaveBeenCalledExactlyOnceWith('https://github.com/login/device');+ expect(h.copy).toHaveBeenCalledTimes(2);+ h.close('completed');+ h.clear();+ expect(await h.read()).toEqual({ phase: 'completed' });+ expect(h.clipboard()).toBe('');+});++it.each(['deviceId', 'ghostId', 'requestId', 'actionId'] as const)(+ 'does not disclose another %s or accept its copy request',+ async (field) => {+ const h = setup();+ const other = { ...target, [field]: 'other' };+ expect(await h.registry.handle(scope, { ...other, operation: 'read' })).toBeNull();+ await expect(h.registry.handle(scope, { ...other, operation: 'copy' })).rejects.toThrow(+ 'OAUTH_BRIDGE_UNAVAILABLE',+ );+ expect(h.copy).not.toHaveBeenCalled();+ },+);++it.each(['owner-b:window-a:frame-a', 'owner-a:window-b:frame-a', 'owner-a:window-a:frame-b'])(+ 'does not disclose across scope %s',+ async (other) => {+ const h = setup();+ expect(await h.registry.handle(other, { ...target, operation: 'read' })).toBeNull();+ await expect(h.registry.handle(other, { ...target, operation: 'reopen' })).rejects.toThrow();+ expect(h.openExternal).not.toHaveBeenCalled();+ },+);++it.each([+ { userCode: 'TEST-CODE' },+ { url: 'https://evil.example/' },+ { operation: 'execute' },+ { operation: 4 },+])('rejects untrusted additions/operations %j', async (extra) => {+ const h = setup();+ await expect(+ h.registry.handle(scope, { ...target, operation: 'copy', ...extra }),+ ).rejects.toThrow();+ expect(h.copy).not.toHaveBeenCalled();+});++it('expires without a reader, removes the code and clipboard, and cannot become completed later', async () => {+ const h = setup();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await h.read()).toEqual({ phase: 'expired' });+ expect(h.clipboard()).toBe('');+ await expect(h.registry.handle(scope, { ...target, operation: 'copy' })).rejects.toThrow();+ h.close('completed');+ expect(await h.read()).toEqual({ phase: 'expired' });+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await h.read()).toBeNull();+});++it('rechecks owner/peer/frame validity on read, copy, and after opening the browser', async () => {+ const h = setup();+ h.openExternal.mockImplementation(async () => {+ h.stale();+ });+ await expect(h.registry.handle(scope, { ...target, operation: 'reopen' })).rejects.toThrow();+ await expect(h.read()).rejects.toThrow();+ await expect(h.registry.handle(scope, { ...target, operation: 'copy' })).rejects.toThrow();+ expect(h.copy).not.toHaveBeenCalled();+});++it('preserves newer clipboard content on completion and disallows remote invocation', () => {+ const h = setup();+ h.overwrite();+ h.close('ended');+ h.clear();+ expect(h.clipboard()).toBe('unrelated text');+ expect(REMOTE_INVOKE_ALLOWLIST.has(PLUGIN_OAUTH_DEVICE_CODE_CHANNEL)).toBe(false);+});++it('reopens a browser authorization without exposing its URL, copying a code, or creating another transaction', async () => {+ const registry = new LocalDeviceCodeSessions();+ const url = 'https://accounts.example.com/authorize?state=private-state';+ const open = vi.fn(async (_url: string) => {});+ const close = registry.presentBrowser(+ scope,+ target,+ 61_000,+ () => {},+ () => open(url),+ );+ const read = () => registry.handle(scope, { ...target, operation: 'read' });+ expect(await read()).toEqual({ phase: 'browser', expiresAt: 61_000 });+ await registry.handle(scope, { ...target, operation: 'reopen' });+ expect(open).toHaveBeenCalledExactlyOnceWith(url);+ await expect(registry.handle(scope, { ...target, operation: 'copy' })).rejects.toThrow();+ expect(await registry.handle('different-frame', { ...target, operation: 'read' })).toBeNull();+ close('ended');+ expect(await read()).toEqual({ phase: 'ended' });+ await expect(registry.handle(scope, { ...target, operation: 'reopen' })).rejects.toThrow();+});++it('expires browser-only authorizations and revalidates the initiating frame after reopen', async () => {+ const registry = new LocalDeviceCodeSessions();+ let current = true;+ const assertCurrent = () => {+ if (!current) throw new Error('stale');+ };+ registry.presentBrowser(scope, target, 61_000, assertCurrent, async () => {+ current = false;+ });+ await expect(registry.handle(scope, { ...target, operation: 'reopen' })).rejects.toThrow();+ current = true;+ expect(await registry.handle(scope, { ...target, operation: 'read' })).toEqual({+ phase: 'ended',+ });+ registry.presentBrowser(scope, target, 61_000, assertCurrent, async () => {});+ await vi.advanceTimersByTimeAsync(60_001);+ expect(await registry.handle(scope, { ...target, operation: 'read' })).toEqual({+ phase: 'expired',+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/fixtures.ts b/apps/desktop/src/main/plugin-oauth/__tests__/fixtures.tsnew file mode 100644index 0000000000..1988b32f1e--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/fixtures.ts@@ -0,0 +1,40 @@+import { createCipheriv, createDecipheriv, generateKeyPairSync, randomBytes } from 'node:crypto';+import path from 'node:path';+import {+ OauthIdentityStore,+ oauthIdentityScopeKey,+ type OauthSigningKey,+} from '../identityStore.js';++/** Synthetic, process-local keys. Product wiring must always use its secure identity store. */+export async function testOauthSigningKey(): Promise<OauthSigningKey> {+ const pair = generateKeyPairSync('ed25519');+ return {+ publicKey: pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64url'),+ privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64url'),+ };+}++/** OS secure storage stand-in for unit tests; callers own and clean their temporary directory. */+export function testOauthIdentityStore(directory: string) {+ const encryptionKey = randomBytes(32);+ const deps = {+ filePath: (scope: Parameters<typeof oauthIdentityScopeKey>[0]) =>+ path.join(directory, `${oauthIdentityScopeKey(scope)}.enc`),+ available: () => true,+ encrypt: (plaintext: string) => {+ const iv = randomBytes(12),+ cipher = createCipheriv('aes-256-gcm', encryptionKey, iv);+ const body = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);+ return Buffer.concat([iv, cipher.getAuthTag(), body]);+ },+ decrypt: (value: Buffer) => {+ const decipher = createDecipheriv('aes-256-gcm', encryptionKey, value.subarray(0, 12));+ decipher.setAuthTag(value.subarray(12, 28));+ return Buffer.concat([decipher.update(value.subarray(28)), decipher.final()]).toString(+ 'utf8',+ );+ },+ };+ return { store: new OauthIdentityStore(deps), restart: () => new OauthIdentityStore(deps), deps };+}diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/identityIntegration.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/identityIntegration.test.tsnew file mode 100644index 0000000000..5ea4c3eea5--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/identityIntegration.test.ts@@ -0,0 +1,274 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { PLUGIN_OAUTH_CHANNEL, type InvokeResultPayload } from '@cindy/device-link';+import {+ authenticateOauthController,+ AuthenticatedOauthHost,+ OauthHostIdentity,+} from '../authentication.js';+import { RemotePluginOauthUnsupportedError, resolveOauthPeerIdentity } from '../identityResolver.js';+import { oauthSecureStorageAvailable, type OauthIdentityScope } from '../identityStore.js';+import {+ initializePluginOauthHost,+ invalidatePluginOauth,+ publishedPluginOauthIdentity,+ requestPluginOauth,+ supportsRemotePluginOauth,+} from '../runtime.js';+import { testOauthIdentityStore, testOauthSigningKey } from './fixtures.js';++const scope: OauthIdentityScope = {+ realm: 'global',+ membershipId: 'synthetic-member',+ deviceId: 'controller',+};+const remote = { ...scope, deviceId: 'remote-desktop' };+const action = { requestId: 'card', actionId: 'oauth_connect:account', expectedRevision: 1 };+const dirs: string[] = [];+afterEach(() => {+ invalidatePluginOauth();+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });+});+const directory = () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-oauth-peer-'));+ dirs.push(dir);+ return dir;+};++async function fixture(now?: () => number) {+ const local = testOauthIdentityStore(directory()),+ target = testOauthIdentityStore(directory());+ const signingKey = await target.store.load(remote, () => {});+ let identity = { ...remote, key: new OauthHostIdentity(signingKey) };+ const operation = vi.fn(async () => ({ phase: 'starting' }));+ const host = new AuthenticatedOauthHost({+ owner: () => 'owner:1',+ available: () => true,+ identity: () => identity,+ bind: async () => ({ ghostId: 'test-plugin', current: () => true }),+ request: operation,+ now,+ });+ const invoke = vi.fn(+ async (device: string, channel: string, args: unknown[]): Promise<InvokeResultPayload> => {+ expect(device).toBe(remote.deviceId);+ expect(channel).toBe(PLUGIN_OAUTH_CHANNEL);+ return { ok: true, result: await host.request(scope.deviceId, args[0]) };+ },+ );+ const resolve = () =>+ resolveOauthPeerIdentity({ scope: () => scope, invoke, now }, remote.deviceId, () => {});+ const connect = async (store = local.store) =>+ authenticateOauthController({+ target: await resolve(),+ peer: scope.deviceId,+ action,+ ghostId: 'test-plugin',+ assertCurrent: () => {},+ trustIdentity: (id, check) => store.trustPeer(scope, id.deviceId, id.publicKey, check),+ invoke: (raw) => host.request(scope.deviceId, raw),+ });+ return {+ local,+ target,+ resolve,+ connect,+ invoke,+ operation,+ host,+ restart: async () => {+ host.invalidate();+ identity = {+ ...remote,+ key: new OauthHostIdentity(await target.restart().load(remote, () => {})),+ };+ },+ replace: async () => {+ host.invalidate();+ identity = { ...remote, key: new OauthHostIdentity(await testOauthSigningKey()) };+ },+ };+}++describe('ordinary Desktop identity admission without CIS', () => {+ it('accepts a fresh descriptor when the clock advances between individual reads', async () => {+ let clock = Date.now();+ const f = await fixture(() => clock++);+ const identity = await f.resolve();+ expect(identity.expiresAtMs - identity.observedAtMs).toBe(60_000);+ expect(identity.deviceId).toBe(remote.deviceId);+ expect(f.operation).not.toHaveBeenCalled();+ });+ it('resolves on the authorized channel, verifies possession and persists continuity across both restarts', async () => {+ const f = await fixture(),+ first = await f.resolve();+ expect(f.invoke.mock.calls[0][2]).toEqual([{ op: 'identity', version: 3 }]);+ expect(fs.readdirSync(path.dirname(f.local.deps.filePath(scope)))).toEqual([]);+ await (+ await f.connect()+ )({ op: 'capabilities' });+ await f.restart();+ const second = await f.resolve();+ expect(second.publicKey).toBe(first.publicKey);+ expect(second.bootId).not.toBe(first.bootId);+ await (+ await f.connect(f.local.restart())+ )({ op: 'capabilities' });+ expect(f.operation).toHaveBeenCalledTimes(2);+ await f.replace();+ await expect(f.connect(f.local.restart())).rejects.toThrow();+ expect(f.operation).toHaveBeenCalledTimes(2);+ });+ it('does not write a pin for a forged handshake or continue after a cancelled trust operation', async () => {+ const f = await fixture(),+ target = await f.resolve();+ const trustIdentity = vi.fn((id, check) =>+ f.local.store.trustPeer(scope, id.deviceId, id.publicKey, check),+ );+ const options = {+ target,+ trustIdentity,+ peer: scope.deviceId,+ action,+ ghostId: 'test-plugin',+ assertCurrent: () => {},+ invoke: (raw: unknown) => f.host.request(scope.deviceId, raw),+ };+ await expect(+ authenticateOauthController({+ ...options,+ invoke: async (raw) => ({+ ...((await options.invoke(raw)) as object),+ signature: 'A'.repeat(86),+ }),+ }),+ ).rejects.toThrow();+ expect(trustIdentity).not.toHaveBeenCalled();+ expect(fs.existsSync(f.local.deps.filePath(scope))).toBe(false);+ let current = true;+ await expect(+ authenticateOauthController({+ ...options,+ assertCurrent: () => {+ if (!current) throw Error('cancelled');+ },+ trustIdentity: async (_id, check) => {+ current = false;+ check();+ },+ }),+ ).rejects.toThrow();+ expect(f.operation).not.toHaveBeenCalled();+ });+ it.each([+ { realm: 'cn' },+ { membershipId: 'other-member' },+ { deviceId: 'other-device' },+ { observedAtMs: 0 },+ { expiresAtMs: 0 },+ { version: 2 },+ { instanceId: 'old-instance' },+ ])(+ 'rejects a mismatched/stale/legacy descriptor %j without invoking authorization',+ async (override) => {+ const f = await fixture(),+ valid = await f.resolve();+ await expect(+ resolveOauthPeerIdentity(+ {+ scope: () => scope,+ invoke: async () => ({ ok: true, result: { ...valid, ...override } }),+ },+ remote.deviceId,+ () => {},+ ),+ ).rejects.toThrow();+ expect(f.operation).not.toHaveBeenCalled();+ },+ );+ it('rejects an owner change during discovery and an old peer without falling back', async () => {+ const f = await fixture();+ let current = scope;+ await expect(+ resolveOauthPeerIdentity(+ {+ scope: () => current,+ invoke: async (...args) => {+ const result = await f.invoke(...args);+ current = { ...scope, membershipId: 'other-member' };+ return result;+ },+ },+ remote.deviceId,+ () => {},+ ),+ ).rejects.toThrow();+ const invoke = vi.fn(+ async (+ _device: string,+ _channel: string,+ _args: unknown[],+ ): Promise<InvokeResultPayload> => ({+ ok: false,+ error: { code: 'CHANNEL_NOT_ALLOWED', message: 'unsupported' },+ }),+ );+ await expect(+ resolveOauthPeerIdentity({ scope: () => scope, invoke }, remote.deviceId, () => {}),+ ).rejects.toBeInstanceOf(RemotePluginOauthUnsupportedError);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(invoke.mock.calls[0]?.[1]).toBe(PLUGIN_OAUTH_CHANNEL);+ });+});++describe('lazy secure identity lifecycle', () => {+ it('projects capability without accessing secure storage and rejects a cancelled async load', async () => {+ let release!: (key: Awaited<ReturnType<typeof testOauthSigningKey>>) => void;+ const load = vi.fn(+ () =>+ new Promise<Awaited<ReturnType<typeof testOauthSigningKey>>>((resolve) => {+ release = resolve;+ }),+ );+ initializePluginOauthHost(+ { owner: () => 'owner', available: () => true, bind: async () => null, run: () => false },+ () => remote,+ load,+ );+ expect(supportsRemotePluginOauth()).toBe(true);+ expect(load).not.toHaveBeenCalled();+ const pending = publishedPluginOauthIdentity();+ invalidatePluginOauth();+ release(await testOauthSigningKey());+ await expect(pending).rejects.toThrow();+ });+ it('checks remote permission before reading secure storage', async () => {+ const load = vi.fn(testOauthSigningKey);+ initializePluginOauthHost(+ { owner: () => 'owner', available: () => false, bind: async () => null, run: () => false },+ () => remote,+ load,+ );+ await expect(+ requestPluginOauth('controller', { op: 'identity', version: 3 }),+ ).rejects.toThrow();+ expect(load).not.toHaveBeenCalled();+ });+ it.each([undefined, 'unknown', 'basic_text'])('rejects insecure Linux backend %s', (backend) => {+ expect(oauthSecureStorageAvailable({ platform: 'linux', available: true, backend })).toBe(+ false,+ );+ });+ it('requires secure storage on all platforms', () => {+ for (const platform of ['darwin', 'win32', 'linux'] as const) {+ expect(+ oauthSecureStorageAvailable({ platform, available: false, backend: 'gnome_libsecret' }),+ ).toBe(false);+ expect(+ oauthSecureStorageAvailable({ platform, available: true, backend: 'gnome_libsecret' }),+ ).toBe(true);+ }+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/identityStore.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/identityStore.test.tsnew file mode 100644index 0000000000..1f0c498fc3--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/identityStore.test.ts@@ -0,0 +1,163 @@+import { afterEach, describe, expect, it } from 'vitest';+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {+ OauthIdentityStore,+ oauthIdentityScopeKey,+ type OauthIdentityScope,+} from '../identityStore.js';+import { testOauthSigningKey } from './fixtures.js';++const directories: string[] = [];+afterEach(() => {+ for (const dir of directories.splice(0)) fs.rmSync(dir, { recursive: true, force: true });+});+const scope: OauthIdentityScope = {+ realm: 'global',+ membershipId: 'synthetic-member',+ deviceId: 'local-device',+};+function fixture() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-oauth-identity-'));+ directories.push(dir);+ const encryptionKey = randomBytes(32);+ let available = true;+ let current = true;+ const filePath = (s: OauthIdentityScope) => path.join(dir, oauthIdentityScopeKey(s) + '.enc');+ const encrypt = (plaintext: string) => {+ const iv = randomBytes(12),+ cipher = createCipheriv('aes-256-gcm', encryptionKey, iv);+ const body = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);+ return Buffer.concat([iv, cipher.getAuthTag(), body]);+ };+ const decrypt = (value: Buffer) => {+ const decipher = createDecipheriv('aes-256-gcm', encryptionKey, value.subarray(0, 12));+ decipher.setAuthTag(value.subarray(12, 28));+ return Buffer.concat([decipher.update(value.subarray(28)), decipher.final()]).toString('utf8');+ };+ const deps = { filePath, available: () => available, encrypt, decrypt };+ const assertCurrent = () => {+ if (!current) throw new Error('cancelled');+ };+ return {+ dir,+ deps,+ filePath,+ assertCurrent,+ store: new OauthIdentityStore(deps),+ lock: () => {+ available = false;+ },+ cancel: () => {+ current = false;+ },+ };+}++describe('persistent authorization identity and peer continuity', () => {+ it('does no startup I/O, stores encrypted keys, and survives a fresh store instance', async () => {+ const f = fixture();+ expect(fs.readdirSync(f.dir)).toEqual([]);+ const identity = await f.store.load(scope, f.assertCurrent);+ const saved = fs.readFileSync(f.filePath(scope));+ expect(saved.includes(identity.privateKey)).toBe(false);+ expect(saved.includes(scope.membershipId)).toBe(false);+ expect(await new OauthIdentityStore(f.deps).load(scope, f.assertCurrent)).toEqual(identity);+ expect(fs.readFileSync(f.filePath(scope))).toEqual(saved);+ });+ it('pins only the first key and refuses substitution across process restarts', async () => {+ const f = fixture(),+ peer = await testOauthSigningKey(),+ replacement = await testOauthSigningKey();+ await f.store.trustPeer(scope, 'peer-device', peer.publicKey, f.assertCurrent);+ const saved = fs.readFileSync(f.filePath(scope));+ const restarted = new OauthIdentityStore(f.deps);+ await restarted.trustPeer(scope, 'peer-device', peer.publicKey, f.assertCurrent);+ await expect(+ restarted.trustPeer(scope, 'peer-device', replacement.publicKey, f.assertCurrent),+ ).rejects.toThrow();+ expect(fs.readFileSync(f.filePath(scope))).toEqual(saved);+ });+ it('isolates realm, membership and controller device without erasing existing pins', async () => {+ const f = fixture();+ const first = await f.store.load(scope, f.assertCurrent);+ for (const other of [+ { ...scope, realm: 'cn' as const },+ { ...scope, membershipId: 'other-member' },+ { ...scope, deviceId: 'other-device' },+ ]) {+ expect((await f.store.load(other, f.assertCurrent)).publicKey).not.toBe(first.publicKey);+ }+ expect(await f.store.load(scope, f.assertCurrent)).toEqual(first);+ });+ it('does not regenerate a corrupted or transplanted encrypted identity', async () => {+ const f = fixture();+ await f.store.load(scope, f.assertCurrent);+ const other = { ...scope, deviceId: 'other-device' };+ const encrypted = fs.readFileSync(f.filePath(scope));+ fs.writeFileSync(f.filePath(other), encrypted);+ await expect(f.store.load(other, f.assertCurrent)).rejects.toThrow();+ expect(fs.readFileSync(f.filePath(other))).toEqual(encrypted);+ fs.writeFileSync(f.filePath(scope), 'invalid-synthetic-ciphertext');+ await expect(f.store.load(scope, f.assertCurrent)).rejects.toThrow();+ expect(fs.readFileSync(f.filePath(scope), 'utf8')).toBe('invalid-synthetic-ciphertext');+ });+ it('fails while secure storage is unavailable without creating plaintext or replacing existing data', async () => {+ const f = fixture();+ f.lock();+ await expect(f.store.load(scope, f.assertCurrent)).rejects.toThrow();+ expect(fs.readdirSync(f.dir)).toEqual([]);+ });+ it('rechecks cancellation after encryption, before committing a key or pin', async () => {+ const f = fixture();+ const store = new OauthIdentityStore({+ ...f.deps,+ encrypt: (value) => {+ const result = f.deps.encrypt(value);+ f.cancel();+ return result;+ },+ });+ await expect(store.load(scope, f.assertCurrent)).rejects.toThrow();+ expect(fs.existsSync(f.filePath(scope))).toBe(false);+ });+ it('serializes competing first admissions and never replaces the winner', async () => {+ const f = fixture(),+ a = await testOauthSigningKey(),+ b = await testOauthSigningKey();+ const stores = [new OauthIdentityStore(f.deps), new OauthIdentityStore(f.deps)];+ const result = await Promise.allSettled(+ stores.map((store, i) =>+ store.trustPeer(scope, 'peer-device', [a, b][i].publicKey, f.assertCurrent),+ ),+ );+ expect(result.filter((r) => r.status === 'fulfilled')).toHaveLength(1);+ expect(result.filter((r) => r.status === 'rejected')).toHaveLength(1);+ const winner = result[0].status === 'fulfilled' ? a : b;+ await new OauthIdentityStore(f.deps).trustPeer(+ scope,+ 'peer-device',+ winner.publicKey,+ f.assertCurrent,+ );+ expect(await stores[0].load(scope, f.assertCurrent)).toEqual(+ await stores[1].load(scope, f.assertCurrent),+ );+ });+ it('rejects malformed and self device identities', async () => {+ const f = fixture(),+ peer = await testOauthSigningKey();+ await expect(+ f.store.trustPeer(scope, scope.deviceId, peer.publicKey, f.assertCurrent),+ ).rejects.toThrow();+ await expect(+ f.store.trustPeer(scope, '../other', peer.publicKey, f.assertCurrent),+ ).rejects.toThrow();+ await expect(+ f.store.trustPeer(scope, 'peer-device', 'not-a-key', f.assertCurrent),+ ).rejects.toThrow();+ expect(fs.readdirSync(f.dir)).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/lifecycle.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/lifecycle.test.tsnew file mode 100644index 0000000000..217cf666b7--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/lifecycle.test.ts@@ -0,0 +1,358 @@+import { createHash } from 'node:crypto';+import { afterEach, expect, it, vi } from 'vitest';+import type { PluginOauthOffer } from '@cindy/device-link';+import { GhostOauthAccountManager } from '../../cindy-brain/ghostOauthAccounts.js';+import {+ cancelActiveGhostOauthFlow,+ startGhostOauthFlow,+} from '../../cindy-brain/ghostOauthFlow.js';+import { OauthBox } from '../box.js';+import { assistPluginOauth } from '../controller.js';+import { getRemoteOauthContext } from '../context.js';+import { OauthTransactions } from '../transactions.js';+import { AuthenticatedOauthHost, OauthHostIdentity } from '../authentication.js';+import { handleAssistPluginOauth } from '../localIpc.js';++const instances: OauthTransactions[] = [];+afterEach(() => {+ for (const h of instances.splice(0)) h.cancelPeer();+ cancelActiveGhostOauthFlow();+});+const decl = {+ clientId: 'synthetic-client',+ authorizeUrl: 'https://provider.example/authorize',+ tokenUrl: 'https://provider.example/token',+ scopes: ['read'],+};+function managed(fetchImpl: typeof fetch) {+ let owner = 'member:g1';+ const vault = new Map<string, string>();+ const manager = new GhostOauthAccountManager({+ vault: {+ read: (g, k) => vault.get(`${g}/${k}`) ?? null,+ store: (g, k, v) => {+ vault.set(`${g}/${k}`, v);+ return true;+ },+ remove: (g, k) => {+ vault.delete(`${g}/${k}`);+ },+ },+ openExternal: () => {+ throw new Error('cloud browser forbidden');+ },+ fetchImpl,+ });+ const running = new Map<string, Promise<unknown>>();+ const host = new OauthTransactions({+ owner: () => owner,+ available: () => true,+ bind: async () => ({ ghostId: 'test-plugin', current: () => true }),+ run: (action) => {+ const remote = getRemoteOauthContext()!;+ const promise = manager.connectAccount('test-plugin', action.requestId, decl, { remote });+ running.set(+ action.requestId,+ promise.then(+ (r) => {+ remote.finish(r.ok);+ return r;+ },+ () => {+ remote.finish(false);+ return { ok: false };+ },+ ),+ );+ return true;+ },+ });+ instances.push(host);+ const start = async (peer: string, card: string) => {+ const key = new OauthBox();+ const tx = (await host.request(peer, {+ op: 'start',+ requestId: card,+ actionId: 'oauth_connect:account',+ expectedRevision: 1,+ publicKey: key.publicKey,+ })) as { id: string; publicKey: string };+ let offer!: PluginOauthOffer;+ await vi.waitFor(async () => {+ const status = (await host.request(peer, { op: 'status', id: tx.id })) as { offer?: string };+ expect(status.offer).toBeTruthy();+ offer = key.open(tx.publicKey, tx.id, 'offer', status.offer!) as PluginOauthOffer;+ });+ return {+ offer,+ tx,+ callback: () =>+ host.request(peer, {+ op: 'callback',+ id: tx.id,+ box: key.seal(tx.publicKey, tx.id, 'callback', {+ state: offer.state,+ code: 'synthetic-code',+ }),+ }),+ };+ };+ return {+ host,+ vault,+ running,+ start,+ switchOwner: () => {+ owner = 'other:g2';+ },+ };+}++it.each(['owner', 'card', 'peer', 'account-boundary'] as const)(+ 'never commits credentials after %s changes during token exchange',+ async (cause) => {+ let respond!: (r: Response) => void;+ const fetchImpl = vi.fn(+ () =>+ new Promise<Response>((resolve) => {+ respond = resolve;+ }),+ );+ const h = managed(fetchImpl);+ const tx = await h.start('desktop-a', 'card-a');+ await tx.callback();+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());+ if (cause === 'owner') h.switchOwner();+ if (cause === 'card') h.host.cancelRequest('card-a');+ if (cause === 'peer') h.host.cancelPeer('desktop-a');+ if (cause === 'account-boundary') cancelActiveGhostOauthFlow();+ respond(+ new Response(+ JSON.stringify({ access_token: 'synthetic-access', refresh_token: 'synthetic-refresh' }),+ ),+ );+ await expect(h.running.get('card-a')).resolves.toMatchObject({ ok: false });+ expect(h.vault.size).toBe(0);+ },+);++it('runs two real OAuth flows independently and keeps the second after the first peer disconnects', async () => {+ const h = managed(+ vi.fn(+ async () =>+ new Response(+ JSON.stringify({ access_token: 'synthetic-access', refresh_token: 'synthetic-refresh' }),+ ),+ ),+ );+ await h.start('desktop-a', 'card-a');+ const b = await h.start('desktop-b', 'card-b');+ h.host.cancelPeer('desktop-a');+ await b.callback();+ await expect(h.running.get('card-a')).resolves.toMatchObject({ ok: false });+ await expect(h.running.get('card-b')).resolves.toMatchObject({ ok: true });+ await expect(h.host.request('desktop-b', { op: 'status', id: b.tx.id })).resolves.toEqual({+ phase: 'succeeded',+ });+ expect([...h.vault.keys()].every((k) => !k.includes('card-a'))).toBe(true);+});++it('closes the local listener and cancels the cloud transaction when its window is gone', async () => {+ const fetchImpl = vi.fn();+ const h = managed(fetchImpl);+ let visible = true;+ let callback = '';+ const identity = {+ key: new OauthHostIdentity(),+ deviceId: 'cloud',+ realm: 'global' as const,+ membershipId: 'member',+ };+ const authenticated = new AuthenticatedOauthHost({+ owner: () => 'member:g1',+ available: () => true,+ identity: () => identity,+ bind: async () => ({ ghostId: 'test-plugin', current: () => true }),+ request: (peer, raw) => h.host.request(peer, raw),+ });+ const promise = handleAssistPluginOauth(+ {+ owner: () => 'member:g1',+ localDeviceId: () => 'desktop',+ trustIdentity: async () => {},+ identity: async () => ({+ ...identity.key.descriptor,+ deviceId: 'cloud',+ realm: 'global' as const,+ membershipId: 'member',+ observedAtMs: Date.now(),+ expiresAtMs: Date.now() + 59_000,+ }),+ assertTarget: () => {+ if (!visible) throw new Error('window gone');+ },+ invoke: async (_device, _channel, args) => ({+ ok: true,+ result: await authenticated.request('desktop', args[0]),+ }),+ openExternal: async (raw) => {+ callback = new URL(raw).searchParams.get('redirect_uri')!;+ const response = await fetch(callback);+ expect(response.status).toBe(400);+ await response.text();+ visible = false;+ },+ },+ {+ deviceId: 'cloud',+ ghostId: 'test-plugin',+ requestId: 'card',+ actionId: 'oauth_connect:account',+ expectedRevision: 1,+ },+ );+ await expect(promise).rejects.toThrow();+ await expect(h.running.get('card')).resolves.toMatchObject({ ok: false });+ await expect(fetch(callback)).rejects.toThrow();+ expect(fetchImpl).not.toHaveBeenCalled();+ expect(h.vault.size).toBe(0);+});++it('preserves a registered public bounce redirect and PKCE at the existing broker exchange', async () => {+ let challenge = '';+ let result: Promise<unknown> | undefined;+ const exchange = vi.fn(+ async (_slug: string, params: { code: string; redirectUri: string; codeVerifier?: string }) => {+ expect(params.code).toBe('synthetic-code');+ expect(params.redirectUri).toBe('https://broker.example/provider/bounce');+ expect(createHash('sha256').update(params.codeVerifier!).digest('base64url')).toBe(challenge);+ return {+ ok: true as const,+ bundle: {+ accessToken: 'synthetic-access',+ refreshToken: 'synthetic-refresh',+ expiresAt: null,+ grantedScope: null,+ },+ };+ },+ );+ const host = new OauthTransactions({+ owner: () => 'member:g1',+ available: () => true,+ bind: async () => ({ ghostId: 'p', current: () => true }),+ run: () => {+ const remote = getRemoteOauthContext()!;+ result = startGhostOauthFlow({+ remote,+ config: {+ ...decl,+ tokenBroker: 'provider',+ publicRedirectUri: 'https://broker.example/provider/bounce',+ callbackPath: '/provider/callback',+ },+ openExternal: () => {+ throw new Error('forbidden');+ },+ fetchImpl: vi.fn(),+ broker: { exchange, refresh: vi.fn() },+ }).then((r) => {+ remote.finish(r.ok);+ return r;+ });+ return true;+ },+ });+ instances.push(host);+ const key = new OauthBox();+ const tx = (await host.request('desktop', {+ op: 'start',+ requestId: 'card',+ actionId: 'oauth_connect:x',+ expectedRevision: 1,+ publicKey: key.publicKey,+ })) as { id: string; publicKey: string };+ let offer!: PluginOauthOffer;+ await vi.waitFor(async () => {+ const status = (await host.request('desktop', { op: 'status', id: tx.id })) as {+ offer?: string;+ };+ expect(status.offer).toBeTruthy();+ offer = key.open(tx.publicKey, tx.id, 'offer', status.offer!) as PluginOauthOffer;+ });+ const url = new URL(offer.authorizeUrl);+ expect(url.searchParams.get('redirect_uri')).toBe('https://broker.example/provider/bounce');+ expect(new URL(offer.callbackUrl).pathname).toBe('/provider/callback');+ challenge = url.searchParams.get('code_challenge')!;+ await host.request('desktop', {+ op: 'callback',+ id: tx.id,+ box: key.seal(tx.publicKey, tx.id, 'callback', { state: offer.state, code: 'synthetic-code' }),+ });+ await expect(result).resolves.toMatchObject({ ok: true });+ expect(exchange).toHaveBeenCalledOnce();+});++it('does not echo a provider exception into remote logs or structured errors', async () => {+ const log = { info: vi.fn(), warn: vi.fn() };+ const remote = {+ scope: 'test',+ assertCurrent: () => {},+ finish: vi.fn(),+ authorize: async (offer: PluginOauthOffer) => ({ state: offer.state, code: 'synthetic-code' }),+ };+ const result = await startGhostOauthFlow({+ config: decl,+ remote,+ openExternal: vi.fn(),+ logger: log,+ fetchImpl: async () => {+ throw new Error('synthetic-code synthetic-refresh');+ },+ });+ expect(result).toEqual({ ok: false, error: 'NETWORK' });+ expect(JSON.stringify([log.info.mock.calls, log.warn.mock.calls, result])).not.toContain(+ 'synthetic-code',+ );+ expect(JSON.stringify([log.info.mock.calls, log.warn.mock.calls, result])).not.toContain(+ 'synthetic-refresh',+ );+});++it('fails closed before browser opening on an old Host and settles rejected card dispatch immediately', async () => {+ const openExternal = vi.fn();+ const invoke = vi.fn(async () => ({ version: 0 }));+ await expect(+ assistPluginOauth(+ { invoke, openExternal, assertCurrent: () => {} },+ {+ requestId: 'card',+ actionId: 'oauth_connect:x',+ expectedRevision: 1,+ },+ ),+ ).rejects.toThrow();+ expect(invoke).toHaveBeenCalledOnce();+ expect(openExternal).not.toHaveBeenCalled();+ let fails = true;+ const h = new OauthTransactions({+ owner: () => 'member:g1',+ available: () => true,+ bind: async () => ({ ghostId: 'p', current: () => true }),+ run: () => {+ if (fails) throw new Error('synthetic private detail');+ return true;+ },+ });+ instances.push(h);+ const input = {+ op: 'start',+ requestId: 'card',+ actionId: 'oauth_connect:x',+ expectedRevision: 1,+ publicKey: new OauthBox().publicKey,+ };+ await expect(h.request('desktop', input)).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ fails = false;+ await expect(h.request('desktop', input)).resolves.toHaveProperty('id');+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.tsnew file mode 100644index 0000000000..6bc2f5ef43--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts@@ -0,0 +1,195 @@+import http from 'node:http';+import type { ListenOptions } from 'node:net';+import { afterEach, expect, it, vi } from 'vitest';+import type { PluginOauthOffer } from '@cindy/device-link';+import { listenForOauthCallback } from '../loopbackListener.js';++const state = 's'.repeat(43);+const resources: Array<{ close(): unknown }> = [];+afterEach(() => {+ for (const resource of resources.splice(0)) resource.close();+ vi.restoreAllMocks();+});++async function bind(host: string, port = 0) {+ const server = http.createServer((_req, res) => {+ res.writeHead(204);+ res.end();+ });+ resources.push(server);+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen({ host, port, ipv6Only: host === '::1' }, () => {+ server.removeListener('error', reject);+ resolve();+ });+ });+ return { server, port: (server.address() as { port: number }).port };+}++async function unusedPort() {+ const { server, port } = await bind('127.0.0.1');+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ return port;+}++function offer(port: number, hostname = 'localhost'): PluginOauthOffer {+ return {+ authorizeUrl: 'https://provider.example/authorize',+ callbackUrl: `http://${hostname}:${port}/callback`,+ state,+ corsOrigins: [],+ corsHosts: [],+ };+}++function request(host: string, port: number, options: { path?: string; authority?: string } = {}) {+ return new Promise<number>((resolve, reject) => {+ const req = http.get(+ {+ host,+ port,+ agent: false,+ path: options.path ?? `/callback?state=${state}&error=access_denied`,+ headers: { Host: options.authority ?? `localhost:${port}` },+ },+ (res) => {+ res.resume();+ res.once('end', () => resolve(res.statusCode!));+ },+ );+ req.setTimeout(2_000, () => req.destroy(new Error('request timed out')));+ req.once('error', reject);+ });+}++it.each(['127.0.0.1', '::1'])(+ 'accepts localhost callbacks via %s and consumes once across families',+ async (first) => {+ const port = await unusedPort();+ const deliver = vi.fn(async () => {});+ const listener = await listenForOauthCallback(offer(port), deliver, () => {});+ resources.push(listener);+ for (const host of ['127.0.0.1', '::1']) {+ expect(await request(host, port, { authority: `evil.example:${port}` })).toBe(400);+ expect(await request(host, port, { path: '/callback?state=wrong&code=synthetic' })).toBe(400);+ expect(await request(host, port, { path: '/wrong-path' })).toBe(404);+ }+ expect(deliver).not.toHaveBeenCalled();+ expect(await request(first, port)).toBe(200);+ const other = first === '::1' ? '127.0.0.1' : '::1';+ expect(await request(other, port)).toBe(409);+ expect(deliver).toHaveBeenCalledExactlyOnceWith({ state, error: 'access_denied' });+ listener.close();+ listener.close();+ // Both ports are released, including on an idempotent cancellation.+ await bind('127.0.0.1', port);+ await bind('::1', port);+ },+);++it('shares consumption while delivery through the other family is still pending', async () => {+ const port = await unusedPort();+ let finish!: () => void;+ let started!: () => void;+ const entered = new Promise<void>((resolve) => {+ started = resolve;+ });+ const delivered = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const deliver = vi.fn(() => {+ started();+ return delivered;+ });+ resources.push(await listenForOauthCallback(offer(port), deliver, () => {}));+ const first = request('::1', port);+ try {+ await entered;+ expect(await request('127.0.0.1', port)).toBe(409);+ } finally {+ finish();+ await first;+ }+ expect(deliver).toHaveBeenCalledOnce();+});++it.each([+ ['127.0.0.1', '127.0.0.1', '::1'],+ ['[::1]', '::1', '127.0.0.1'],+])('keeps a literal %s callback confined to that interface', async (hostname, host, other) => {+ const port = await unusedPort();+ resources.push(+ await listenForOauthCallback(+ offer(port, hostname),+ async () => {},+ () => {},+ ),+ );+ expect(await request(host, port, { authority: `${hostname}:${port}` })).toBe(200);+ await bind(other, port);+});++it('fails the whole localhost setup on a port conflict and leaves its owner alone', async () => {+ const { port } = await bind('::1');+ const deliver = vi.fn(async () => {});+ await expect(listenForOauthCallback(offer(port), deliver, () => {})).rejects.toThrow(+ 'OAUTH_BRIDGE_UNAVAILABLE',+ );+ // The first family must be released when the second cannot bind.+ await bind('127.0.0.1', port);+ expect(await request('::1', port)).toBe(204);+ expect(deliver).not.toHaveBeenCalled();+});++it('releases both listeners if the card is no longer current after binding', async () => {+ const port = await unusedPort();+ await expect(+ listenForOauthCallback(+ offer(port),+ async () => {},+ () => {+ throw new Error('stale');+ },+ ),+ ).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ await bind('127.0.0.1', port);+ await bind('::1', port);+});++it.each(['EAFNOSUPPORT', 'EADDRNOTAVAIL'])(+ 'supports an OS with IPv6 disabled (%s), but never a port conflict fallback',+ async (code) => {+ const port = await unusedPort();+ const original = http.Server.prototype.listen;+ vi.spyOn(http.Server.prototype, 'listen').mockImplementation(function (+ this: http.Server,+ ...args: unknown[]+ ) {+ if ((args[0] as ListenOptions).host === '::1') {+ queueMicrotask(() =>+ this.emit('error', Object.assign(new Error('unavailable family'), { code })),+ );+ return this;+ }+ return Reflect.apply(original, this, args);+ });+ resources.push(+ await listenForOauthCallback(+ offer(port),+ async () => {},+ () => {},+ ),+ );+ expect(await request('127.0.0.1', port)).toBe(200);+ await expect(+ listenForOauthCallback(+ offer(port, '[::1]'),+ async () => {},+ () => {},+ ),+ ).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');+ },+);diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.tsnew file mode 100644index 0000000000..3552c770c8--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts@@ -0,0 +1,18 @@+import { expect, it } from 'vitest';+import { buildDesktopClaudeRuntimeConfig, desktopCodexRuntimeConfig } from '../../maker-host/runtime-configs.js';+import hostPrompt from '../../maker-host/host-system-prompt.md?raw';+import precedence from '../../maker-host/skill-source-precedence-prompt.md?raw';+import claudePrompt from '../../maker-host/claude-system-prompt.md?raw';+import codexPrompt from '../../maker-host/codex-system-prompt.md?raw';++it('keeps the upstream Desktop system prompt unchanged by remote authorization', () => {+ const cases = [+ [buildDesktopClaudeRuntimeConfig(() => 'https://model.example'), claudePrompt],+ [desktopCodexRuntimeConfig, codexPrompt],+ ] as const;+ for (const [config, harnessPrompt] of cases) {+ expect(config.systemPrompt).toBe([hostPrompt, precedence, harnessPrompt]+ .map(section => section.trim()).filter(Boolean).join('\n\n'));+ expect(config.systemPrompt).not.toContain('Plugin accounts and remote authorization');+ }+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/secretSubmission.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/secretSubmission.test.tsnew file mode 100644index 0000000000..dd1eb58401--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/secretSubmission.test.ts@@ -0,0 +1,315 @@+import { testOauthSigningKey } from './fixtures.js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type {+ GhostManifest,+ GhostSetupAllowedAction,+ GhostSetupAssessment,+} from '../../../shared/ghost.js';+import { GhostSetupChangeBus } from '../../cindy-brain/ghostSetupChangeBus.js';+import { GhostSetupCoordinator } from '../../cindy-brain/ghostSetupCoordinator.js';+import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';+import { executeGhostSetupInlineSubmission } from '../../cindy-brain/ghostSetupInlineExecutor.js';+import { initializePluginOauthCards } from '../cards.js';+import { assistPluginOauth } from '../controller.js';+import {+ handleAssistPluginOauth,+ handleSubmitPluginSecret,+ type LocalOauthDeps,+} from '../localIpc.js';+import {+ invalidatePluginOauth,+ publishedPluginOauthIdentity,+ requestPluginOauth,+} from '../runtime.js';++const cleanups: Array<() => void> = [];+afterEach(() => {+ cleanups.splice(0).forEach((close) => close());+ invalidatePluginOauth();+});+const input = 'synthetic-pat-never-in-messages';+const inline: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }> = {+ id: 'inline_form:bound-key',+ kind: 'inline_form',+ form: {+ fields: [{ id: 'value', type: 'secret', label: 'API Key', required: true, maxLength: 200 }],+ },+};++async function harness(options: { failStore?: boolean; holdStore?: boolean; saved?: boolean } = {}) {+ let owner: string | null = 'membership';+ let source: 'user' | 'oauth' = 'user';+ const values = new Map<string, string>(options.saved ? [['demo:api_key', 'synthetic-old']] : []);+ const messages: unknown[] = [],+ wire: Array<{ request: unknown; response: unknown }> = [];+ const changes = new GhostSetupChangeBus();+ const bridge = new GhostSetupInteractionBridge({ broadcast: (...args) => messages.push(args) });+ const manifest = (): GhostManifest => ({+ schemaVersion: 2,+ id: 'demo',+ name: 'Demo',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ tools: [],+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'api_key',+ label: 'API Key',+ source,+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],+ },+ });+ const assess = (): GhostSetupAssessment => ({+ state: values.size ? 'ready' : 'required',+ revision: changes.currentRevision('demo'),+ groups: values.size && !options.saved+ ? []+ : [+ {+ id: 'credential',+ mode: 'any_of',+ items: [+ {+ ref: 'secret:api_key',+ kind: 'secret',+ label: 'API Key',+ state: values.size ? 'satisfied' : 'missing',+ actions: [inline],+ },+ ],+ },+ ],+ });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let attempted = false;+ const store = vi.fn((ghost: string, key: string, value: string) => {+ if (options.failStore) return false;+ values.set(ghost + ':' + key, value);+ return true;+ });+ const coordinator = new GhostSetupCoordinator({+ bridge,+ changeBus: changes,+ assess,+ validateTarget: () => ({ ok: true }),+ getGhostIdentity: () => ({ id: 'demo', name: 'Demo' }),+ executeAction: async () => ({ ok: true }),+ executeInlineAction: async (args) => {+ attempted = true;+ if (options.holdStore) await gate;+ return executeGhostSetupInlineSubmission(+ {+ getAssessment: assess,+ getManifest: manifest,+ storeSecret: store,+ emitChange: () => {+ changes.emit('demo', { source: 'secret', ref: 'secret:api_key' });+ },+ },+ args,+ );+ },+ terminalGraceMs: 0,+ });+ initializePluginOauthCards({+ loadKey: testOauthSigningKey,+ bridge,+ bots: () => null,+ owner: () => owner,+ available: () => true,+ identity: () => ({+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ }),+ });+ const abort = new AbortController();+ const ready = coordinator.ensureReady({+ sessionId: 'task',+ ghostId: 'demo',+ signal: abort.signal,+ reauthorize: options.saved,+ });+ cleanups.push(() => {+ abort.abort();+ release();+ });+ await vi.waitFor(() => expect(bridge.pendingSnapshots()).toHaveLength(1));+ const snapshot = bridge.pendingSnapshots()[0].request;+ const step = snapshot.steps[0];+ const action = {+ deviceId: 'cloud-device',+ ghostId: 'demo',+ requestId: snapshot.requestId,+ actionId: inline.id,+ expectedRevision: snapshot.revision,+ };+ const presentation = {+ ghostName: snapshot.ghost.name,+ title: step.title,+ description: step.description,+ intro: snapshot.intro ?? '',+ fieldLabel: 'API Key',+ fieldDescription: '',+ maxLength: 200,+ };+ const openExternal = vi.fn(async () => {+ throw new Error('input must not open a browser');+ });+ const deps: LocalOauthDeps = {+ owner: () => owner,+ assertTarget: (deviceId) => {+ if (deviceId !== 'cloud-device') throw new Error('target');+ },+ localDeviceId: () => 'desktop',+ openExternal,+ trustIdentity: async () => {},+ identity: async () => ({+ ...(await publishedPluginOauthIdentity())!,+ deviceId: 'cloud-device',+ realm: 'global' as const,+ membershipId: 'membership',+ observedAtMs: Date.now(),+ expiresAtMs: Date.now() + 60_000,+ }),+ invoke: async (_device, _channel, args) => {+ const response = await requestPluginOauth('desktop', args[0]);+ wire.push({ request: args[0], response });+ return { ok: true, result: response };+ },+ };+ return {+ deps,+ action,+ presentation,+ bridge,+ ready,+ store,+ values,+ wire,+ messages,+ openExternal,+ release,+ attempted: () => attempted,+ abort,+ changeOwner: () => {+ owner = 'someone-else';+ },+ changeSource: () => {+ source = 'oauth';+ },+ submit: (override: Record<string, unknown> = {}) =>+ handleSubmitPluginSecret(deps, { ...action, value: input, presentation, ...override }),+ };+}++describe('signed remote inline setup through the actual Host executor', () => {+ it.each([false, true])('stores only the bound plugin key without exposing plaintext (reconfigure: %s)', async saved => {+ const h = await harness({ saved });+ await expect(h.submit()).resolves.toEqual({ accepted: true });+ await expect(h.ready).resolves.toMatchObject({ ok: true });+ expect(h.values).toEqual(new Map([['demo:api_key', input]]));+ expect(h.openExternal).not.toHaveBeenCalled();+ expect(JSON.stringify([h.wire, h.messages])).not.toContain(input);+ // Replaying the same authenticated packet returns its old reply, never a second write.+ const exchanges = h.wire.filter((e) => (e.request as { op: string }).op === 'exchange');+ for (const entry of exchanges)+ await expect(requestPluginOauth('desktop', entry.request)).resolves.toEqual(entry.response);+ expect(h.store).toHaveBeenCalledTimes(1);+ await expect(requestPluginOauth('other-desktop', exchanges.at(-1)!.request)).rejects.toThrow();+ });++ it.each([+ 'ghostName',+ 'title',+ 'description',+ 'intro',+ 'fieldLabel',+ 'fieldDescription',+ 'maxLength',+ ] as const)('refuses a changed displayed %s before transmitting the value', async (field) => {+ const h = await harness();+ await expect(+ h.submit({+ presentation: { ...h.presentation, [field]: field === 'maxLength' ? 199 : 'changed' },+ }),+ ).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ expect(h.attempted()).toBe(false);+ expect(JSON.stringify([h.wire, h.messages])).not.toContain(input);+ });++ it.each([+ { ghostId: 'another-plugin' },+ { deviceId: 'other-device' },+ { expectedRevision: 100 },+ { actionId: 'another-field' },+ { value: 'x'.repeat(201) },+ { storageKey: 'forged' },+ { value: '' },+ { value: 'line\u0000break' },+ ])('rejects invalid or cross-target input %j', async (override) => {+ const h = await harness();+ await expect(h.submit(override)).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ });++ it('does not turn ordinary assist into a secret request or open browser', async () => {+ const h = await harness();+ await expect(handleAssistPluginOauth(h.deps, h.action)).rejects.toThrow();+ expect(h.store).not.toHaveBeenCalled();+ expect(h.openExternal).not.toHaveBeenCalled();+ });++ it('refuses an old Host before sending input and clears the local pending value', async () => {+ const invoke = vi.fn(async () => ({+ version: 1,+ callback: 'desktop-loopback',+ encrypted: true,+ }));+ const deps = { invoke, secretValue: input, assertCurrent() {}, openExternal: vi.fn() };+ await expect(+ assistPluginOauth(deps, { requestId: 'card', actionId: 'action', expectedRevision: 0 }),+ ).rejects.toThrow();+ expect(invoke).toHaveBeenCalledExactlyOnceWith({ op: 'capabilities' });+ expect(deps.secretValue).toBeUndefined();+ expect(deps.openExternal).not.toHaveBeenCalled();+ });++ it.each(['session', 'peer', 'owner', 'declaration'] as const)(+ 'rejects a late store after %s changes',+ async (reason) => {+ const h = await harness({ holdStore: true, saved: true });+ const submitting = h.submit();+ const rejected = expect(submitting).rejects.toThrow();+ await vi.waitFor(() => expect(h.attempted()).toBe(true));+ if (reason === 'session') h.abort.abort();+ if (reason === 'peer') invalidatePluginOauth('desktop');+ if (reason === 'owner') h.changeOwner();+ if (reason === 'declaration') h.changeSource();+ h.release();+ await rejected;+ expect(h.store).not.toHaveBeenCalled();+ expect(h.values.get('demo:api_key')).toBe('synthetic-old');+ },+ );++ it('reports a vault write failure and leaves the card retryable', async () => {+ const h = await harness({ failStore: true, saved: true });+ await expect(h.submit()).rejects.toThrow();+ expect(h.values.get('demo:api_key')).toBe('synthetic-old');+ expect(h.bridge.pendingSnapshots()[0].request.steps[0]).toMatchObject({+ phase: 'failed',+ errorCode: 'SAVE_FAILED',+ });+ expect(JSON.stringify(h.messages)).not.toContain(input);+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/targetPolicy.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/targetPolicy.test.tsnew file mode 100644index 0000000000..af5315d0c8--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/targetPolicy.test.ts@@ -0,0 +1,67 @@+import { expect, it } from 'vitest';+import type { GhostManifest } from '../../../shared/ghost.js';+import { bindDeviceAuthorizationTarget } from '../targetPolicy.js';++const manifest = {+ id: 'test-plugin',+ version: '1.0.0',+ network: { hosts: ['provider.example'] },+} as GhostManifest;+it('rejects unrelated domains, alternate ports, credentials and insecure schemes', () => {+ for (const url of [+ 'https://attacker.example/device',+ 'https://provider.example.attacker.example/device',+ 'https://provider.example:8443/device',+ 'https://[email protected]/device',+ 'http://provider.example/device',+ ]) {+ expect(() => bindDeviceAuthorizationTarget(manifest, url)).toThrow();+ }+});+it('pins the current plugin declaration throughout the live authorization', () => {+ const check = bindDeviceAuthorizationTarget(manifest, 'https://provider.example/device');+ expect(() => check(manifest)).not.toThrow();+ expect(() => check({ ...manifest, network: { hosts: ['attacker.example'] } })).toThrow();+ expect(() => check({ ...manifest, id: 'other-plugin' })).toThrow();+ expect(() => check({ ...manifest, version: '2.0.0' })).toThrow();+});+it('rejects a generic CLI target when no trusted declaration exists', () => {+ expect(() =>+ bindDeviceAuthorizationTarget(+ { ...manifest, network: undefined },+ 'https://provider.example/device',+ ),+ ).toThrow();+});+it('binds the existing GitHub device adapter to its exact provider endpoint', () => {+ const github = { ...manifest, id: 'cindy-github', network: undefined };+ expect(() =>+ bindDeviceAuthorizationTarget(github, 'https://github.com/login/device'),+ ).not.toThrow();+ for (const url of [+ 'https://github.com/other',+ 'https://github.com/login/device?next=https://attacker.example',+ 'https://github.com/login/device#fragment',+ 'https://github.com.attacker.example/login/device',+ ]) {+ expect(() => bindDeviceAuthorizationTarget(github, url)).toThrow();+ }+});+it('binds the reviewed TapTap CLI adapter to its exact PAT route and one private code', () => {+ const maker = { ...manifest, id: 'taptap-maker', network: undefined };+ const url = 'https://maker.taptap.cn/pat-tokens?code=' + 'a'.repeat(32);+ const check = bindDeviceAuthorizationTarget(maker, url);+ expect(() => check(maker)).not.toThrow();+ for (const bad of [+ url + '&redirect=https://attacker.example',+ url + '&code=' + 'a'.repeat(32),+ url.replace('/pat-tokens', '/other'),+ url.replace('maker.taptap.cn', 'attacker.example'),+ url.replace('?code=', '?token='),+ url + '#fragment',+ url.slice(0, -1),+ ]) {+ expect(() => bindDeviceAuthorizationTarget(maker, bad)).toThrow();+ }+ expect(() => check({ ...maker, version: 'changed' })).toThrow();+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.tsnew file mode 100644index 0000000000..9e7bfa2869--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts@@ -0,0 +1,291 @@+import { testOauthIdentityStore } from './fixtures.js';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { resolveOauthPeerIdentity } from '../identityResolver.js';+import { createHash } from 'node:crypto';+import { WebSocket, WebSocketServer } from 'ws';+import { expect, it, vi } from 'vitest';+import { DeviceLinkClient, PLUGIN_OAUTH_CHANNEL, type Envelope } from '@cindy/device-link';+import type { GhostSetupAssessment } from '../../../shared/ghost.js';+import { GhostOauthAccountManager } from '../../cindy-brain/ghostOauthAccounts.js';+import { GhostSetupChangeBus } from '../../cindy-brain/ghostSetupChangeBus.js';+import { GhostSetupCoordinator } from '../../cindy-brain/ghostSetupCoordinator.js';+import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';+import { getRemoteOauthContext } from '../context.js';+import { initializePluginOauthCards } from '../cards.js';+import { handleAssistPluginOauth } from '../localIpc.js';+import { invalidatePluginOauth, requestPluginOauth } from '../runtime.js';++it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and cloud vault commit', async ({+ onTestFinished,+}) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-oauth-transport-'));+ onTestFinished(() => fs.rmSync(directory, { recursive: true, force: true }));+ const identityStore = testOauthIdentityStore(directory);+ const controllerScope = {+ realm: 'global' as const,+ deviceId: 'desktop',+ membershipId: 'synthetic-member',+ };+ // Real transport clients and sockets; only relay identity and provider HTTP are synthetic.+ const relay = new WebSocketServer({ host: '127.0.0.1', port: 0 });+ await new Promise<void>((resolve) => relay.once('listening', resolve));+ const port = (relay.address() as { port: number }).port;+ const sockets = new Map<string, WebSocket>();+ const frames: unknown[] = [];+ relay.on('connection', (socket, req) => {+ const peer = req.url!.slice(1);+ sockets.set(peer, socket);+ socket.on('message', (bytes) => {+ const env = JSON.parse(bytes.toString()) as Envelope;+ frames.push(env);+ if (env.kind === 'hello') {+ socket.send(+ JSON.stringify({+ v: 1,+ kind: 'hello-ack',+ payload: {+ serverProtocolVersion: 1,+ deviceId: peer,+ userId: 'synthetic-member',+ },+ }),+ );+ } else if (env.kind === 'ping') {+ socket.send(JSON.stringify({ v: 1, kind: 'pong', id: env.id }));+ } else if (env.dst) {+ const routed = { ...env, src: peer };+ frames.push(routed);+ sockets.get(env.dst)?.send(JSON.stringify(routed));+ }+ });+ });+ const clients: DeviceLinkClient[] = [];+ function client(peer: string) {+ const c = new DeviceLinkClient({+ getWsUrl: () => `ws://127.0.0.1:${port}/${peer}`,+ getToken: async () => 'synthetic-relay-identity',+ getHello: () => ({+ deviceName: peer,+ platform: 'test',+ appVersion: '1',+ remoteControlEnabled: true,+ busy: false,+ }),+ createWebSocket: (url, headers) => new WebSocket(url, { headers }),+ logger: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ });+ clients.push(c);+ return c;+ }+ const cloud = client('cloud');+ const desktop = client('desktop');+ const other = client('other-desktop');+ const vault = new Map<string, string>();+ const broadcasts: unknown[] = [];+ const bus = new GhostSetupChangeBus();+ const bridge = new GhostSetupInteractionBridge({+ broadcast: (...args) => {+ broadcasts.push(args);+ },+ });+ let connected = false;+ let challenge = '';+ let codeState = '';+ let verifier = '';+ let exchangeCount = 0;+ let transactionId = '';+ const account = new GhostOauthAccountManager({+ vault: {+ read: (g, k) => vault.get(`${g}/${k}`) ?? null,+ store: (g, k, value) => {+ vault.set(`${g}/${k}`, value);+ return true;+ },+ remove: (g, k) => {+ vault.delete(`${g}/${k}`);+ },+ },+ openExternal: () => {+ throw new Error('Cloud browser forbidden');+ },+ fetchImpl: async (_url, init) => {+ const body = new URLSearchParams(String(init?.body));+ expect(body.get('code')).toBe('synthetic-provider-code');+ verifier = body.get('code_verifier')!;+ expect(createHash('sha256').update(verifier).digest('base64url')).toBe(challenge);+ exchangeCount++;+ return new Response(+ JSON.stringify({+ access_token: 'synthetic-access',+ refresh_token: 'synthetic-refresh',+ expires_in: 3600,+ }),+ );+ },+ onAccountConnected: () => {+ connected = true;+ // Exercises card close/readiness racing with the controller's next status poll.+ bus.emit('test-plugin', { source: 'oauth', ref: 'account' });+ },+ });+ const assessment = (): GhostSetupAssessment => ({+ revision: connected ? 2 : 1,+ state: connected ? 'ready' : 'required',+ groups: connected+ ? []+ : [+ {+ id: 'account',+ mode: 'any_of',+ items: [+ {+ ref: 'secret:account',+ kind: 'oauth',+ label: 'Provider',+ state: 'missing',+ actions: [{ id: 'oauth_connect:secret:account', kind: 'oauth_connect' }],+ },+ ],+ },+ ],+ });+ const coordinator = new GhostSetupCoordinator({+ bridge,+ changeBus: bus,+ assess: assessment,+ validateTarget: () => ({ ok: true }),+ getGhostIdentity: () => ({ id: 'test-plugin', name: 'Provider' }),+ executeAction: async () => {+ const result = await account.connectAccount(+ 'test-plugin',+ 'account',+ {+ authorizeUrl: 'https://provider.example/authorize',+ tokenUrl: 'https://provider.example/token',+ clientId: 'synthetic-client',+ scopes: ['read'],+ },+ { remote: getRemoteOauthContext() },+ );+ return result.ok ? { ok: true } : { ok: false, errorCode: 'ACTION_FAILED' };+ },+ terminalGraceMs: 0,+ });+ initializePluginOauthCards({+ loadKey: (scope, check) => identityStore.store.load(scope, check),+ identity: () => ({+ deviceId: 'cloud',+ realm: 'global' as const,+ membershipId: 'synthetic-member',+ }),+ bridge,+ bots: () => null,+ owner: () => 'synthetic-member:g1',+ available: (peer) => ['desktop', 'other-desktop'].includes(peer),+ });+ cloud.onFrame(async (env) => {+ if (env.kind === 'link-open')+ cloud.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'synthetic' });+ if (env.kind === 'invoke') {+ const payload = env.payload as { channel: string; args: unknown[] };+ try {+ if (payload.channel !== PLUGIN_OAUTH_CHANNEL || payload.args.length !== 1)+ throw new Error('denied');+ const result = await requestPluginOauth(env.src!, payload.args[0]);+ if ((payload.args[0] as { op: string }).op === 'hello')+ transactionId = (result as { id: string }).id;+ cloud.sendInvokeResult(env.src!, env.id!, { ok: true, result });+ } catch {+ cloud.sendInvokeResult(env.src!, env.id!, {+ ok: false,+ error: { code: 'IPC_ERROR', message: 'unavailable' },+ });+ }+ }+ });+ const setup = coordinator.ensureReady({+ sessionId: 'cloud-session',+ ghostId: 'test-plugin',+ tool: 'read',+ });+ try {+ for (const c of clients) c.start();+ await vi.waitFor(() => expect(clients.every((c) => c.getSelfDeviceId())).toBe(true));+ for (const c of [desktop, other])+ await c.openLink('cloud', { controllerName: 'test', appVersion: '1', protocolVersion: 1 });+ await vi.waitFor(() => expect(bridge.pendingSnapshots()).toHaveLength(1));+ const snapshot = bridge.pendingSnapshots()[0].request;+ const callbackResponses: number[] = [];+ const result = await handleAssistPluginOauth(+ {+ owner: () => 'synthetic-member:g1',+ localDeviceId: () => 'desktop',+ trustIdentity: (id, check) =>+ identityStore.store.trustPeer(controllerScope, id.deviceId, id.publicKey, check),+ identity: (id, check) =>+ resolveOauthPeerIdentity(+ {+ scope: () => controllerScope,+ invoke: (dst, channel, args) => desktop.invoke(dst, { channel, args }),+ },+ id,+ check,+ ),+ assertTarget: (id) => {+ expect(id).toBe('cloud');+ },+ invoke: (dst, channel, args) => desktop.invoke(dst, { channel, args }),+ openExternal: async (raw) => {+ const url = new URL(raw);+ challenge = url.searchParams.get('code_challenge')!;+ codeState = url.searchParams.get('state')!;+ const stolen = await other.invoke('cloud', {+ channel: PLUGIN_OAUTH_CHANNEL,+ args: [{ op: 'status', id: transactionId }],+ });+ expect(stolen.ok).toBe(false);+ const callback = new URL(url.searchParams.get('redirect_uri')!);+ callback.searchParams.set('state', codeState);+ callback.searchParams.set('code', 'synthetic-provider-code');+ const response = await fetch(callback);+ callbackResponses.push(response.status);+ expect(await response.text()).toContain('callback received');+ },+ },+ {+ deviceId: 'cloud',+ ghostId: 'test-plugin',+ requestId: snapshot.requestId,+ actionId: snapshot.steps[0].action!.id,+ expectedRevision: snapshot.revision,+ },+ );+ expect(result).toEqual({ accepted: true });+ expect(callbackResponses).toEqual([200]);+ await expect(setup).resolves.toMatchObject({ ok: true });+ expect(exchangeCount).toBe(1);+ expect([...vault.values()]).toContain('synthetic-refresh');+ const projected = JSON.stringify({ frames, broadcasts, result });+ for (const secret of [+ codeState,+ verifier,+ challenge,+ 'synthetic-provider-code',+ 'synthetic-access',+ 'synthetic-refresh',+ 'provider.example',+ ]) {+ expect(projected).not.toContain(secret);+ }+ } finally {+ invalidatePluginOauth();+ bridge.cleanupAll('session_aborted');+ await setup;+ await coordinator.waitForActionsIdle();+ for (const c of clients) c.stop();+ for (const socket of relay.clients) socket.terminate();+ await new Promise<void>((resolve) => relay.close(() => resolve()));+ }+}, 10_000);diff --git a/apps/desktop/src/main/plugin-oauth/authentication.ts b/apps/desktop/src/main/plugin-oauth/authentication.tsnew file mode 100644index 0000000000..8744121f56--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/authentication.ts@@ -0,0 +1,374 @@+import {+ createPrivateKey,+ createPublicKey,+ generateKeyPairSync,+ randomBytes,+ randomUUID,+ sign,+ verify,+} from 'node:crypto';+import {+ PLUGIN_OAUTH_TTL_MS,+ oauthExact,+ oauthNonce,+ parsePluginOauthHello,+ parsePluginOauthHelloReply,+ parsePluginOauthRequest,+ type PluginOauthAction,+ type PluginOauthHello,+ type PluginOauthHelloReply,+ type PluginOauthPublicIdentity,+ type PluginOauthPeerIdentity,+ type PluginOauthRequest,+} from '@cindy/device-link';+import { OauthBox } from './box.js';+import type { OauthCardBinding } from './transactions.js';+import type { OauthIdentityScope, OauthSigningKey } from './identityStore.js';++const fail = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');+const nonce = () => randomBytes(32).toString('base64url');+const sameAction = (a: PluginOauthAction, b: PluginOauthAction) =>+ a.requestId === b.requestId &&+ a.actionId === b.actionId &&+ a.expectedRevision === b.expectedRevision;+const domain = (id: string) => `authenticated-plugin-oauth-v3:${id}`;++/** Persistent signing key with a new boot identifier; ephemeral keys remain per handshake. */+export class OauthHostIdentity {+ private readonly pair;+ readonly descriptor: PluginOauthPublicIdentity;+ constructor(stored?: OauthSigningKey) {+ // Production supplies the secure store key. In-memory identities are useful to protocol tests.+ this.pair = stored+ ? {+ privateKey: createPrivateKey({+ key: Buffer.from(stored.privateKey, 'base64url'),+ type: 'pkcs8',+ format: 'der',+ }),+ publicKey: createPublicKey({+ key: Buffer.from(stored.publicKey, 'base64url'),+ type: 'spki',+ format: 'der',+ }),+ }+ : generateKeyPairSync('ed25519');+ this.descriptor = {+ version: 1,+ bootId: randomUUID(),+ publicKey: this.pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64url'),+ };+ }+ sign(transcript: Buffer): string {+ return sign(null, transcript, this.pair.privateKey).toString('base64url');+ }+}+function transcript(+ hello: PluginOauthHello,+ reply: Omit<PluginOauthHelloReply, 'signature'>,+ target: OauthIdentityScope & { publicKey: string },+ peer: string,+): Buffer {+ return Buffer.from(+ JSON.stringify([+ 'cindy-plugin-oauth-authentication-v3',+ target.realm,+ target.membershipId,+ target.deviceId,+ peer,+ target.publicKey,+ reply.bootId,+ hello.nonce,+ hello.publicKey,+ reply.publicKey,+ reply.id,+ reply.expiresAtMs,+ hello.action.requestId,+ hello.action.actionId,+ hello.action.expectedRevision,+ reply.ghostId,+ ]),+ );+}+interface Connection {+ id: string;+ peer: string;+ owner: string;+ hello: PluginOauthHello;+ key: OauthBox;+ expiresAtMs: number;+ binding: OauthCardBinding;+ started: boolean;+ finished: boolean;+ innerId?: string;+ messages: Map<string, { box: string; promise: Promise<unknown> }>;+}+export class AuthenticatedOauthHost {+ private readonly connections = new Map<string, Connection>();+ private generation = 0;+ private readonly peerGenerations = new Map<string, number>();+ constructor(+ private readonly deps: {+ owner(): string | null;+ available(peer: string): boolean;+ identity():+ | (OauthIdentityScope & { key: OauthHostIdentity })+ | null+ | Promise<(OauthIdentityScope & { key: OauthHostIdentity }) | null>;+ bind(action: PluginOauthAction): Promise<OauthCardBinding | null>;+ request(peer: string, raw: unknown): Promise<unknown>;+ now?: () => number;+ },+ ) {}+ invalidate(peer?: string): void {+ if (peer) this.peerGenerations.set(peer, (this.peerGenerations.get(peer) ?? 0) + 1);+ else {+ this.generation++;+ this.peerGenerations.clear();+ }+ for (const [id, c] of this.connections)+ if (!peer || c.peer === peer) this.connections.delete(id);+ }+ private now() {+ return this.deps.now?.() ?? Date.now();+ }+ private assertCurrent(c: Connection): void {+ if (+ this.connections.get(c.id) !== c ||+ c.owner !== this.deps.owner() ||+ !this.deps.available(c.peer) ||+ this.now() >= c.expiresAtMs+ )+ throw fail();+ }+ async request(peer: string, raw: unknown): Promise<unknown> {+ const owner = this.deps.owner(),+ startGeneration = this.generation,+ startPeer = this.peerGenerations.get(peer) ?? 0;+ if (!owner || !this.deps.available(peer)) throw fail();+ const identity = await this.deps.identity();+ if (+ !owner ||+ !identity ||+ this.deps.owner() !== owner ||+ !this.deps.available(peer) ||+ startGeneration !== this.generation ||+ startPeer !== (this.peerGenerations.get(peer) ?? 0)+ )+ throw fail();+ if ((raw as { op?: unknown })?.op === 'identity') {+ const request = oauthExact(raw, ['op', 'version']);+ if (request.version !== 3) throw fail();+ const observedAtMs = this.now();+ return {+ ...identity.key.descriptor,+ realm: identity.realm,+ deviceId: identity.deviceId,+ membershipId: identity.membershipId,+ observedAtMs,+ expiresAtMs: observedAtMs + 60_000,+ };+ }+ for (const [id, c] of this.connections)+ if (this.now() >= c.expiresAtMs || c.owner !== owner) this.connections.delete(id);+ if ((raw as { op?: unknown })?.op === 'hello') {+ const hello = parsePluginOauthHello(raw);+ for (const [id, c] of this.connections) if (c.finished) this.connections.delete(id);+ if (+ this.connections.size >= 16 ||+ [...this.connections.values()].filter((c) => c.peer === peer).length >= 4+ )+ throw fail();+ const generation = this.generation,+ peerGeneration = this.peerGenerations.get(peer) ?? 0;+ const binding = await this.deps.bind(hello.action);+ const currentIdentity = await this.deps.identity();+ if (+ !binding?.current() ||+ this.deps.owner() !== owner ||+ !this.deps.available(peer) ||+ generation !== this.generation ||+ peerGeneration !== (this.peerGenerations.get(peer) ?? 0) ||+ currentIdentity?.key !== identity.key ||+ this.connections.size >= 16 ||+ [...this.connections.values()].filter((c) => c.peer === peer).length >= 4+ )+ throw fail();+ const key = new OauthBox(),+ id = randomUUID(),+ expiresAtMs = this.now() + PLUGIN_OAUTH_TTL_MS;+ key.seal(hello.publicKey, domain(id), 'offer', {}); // validate X25519 before any authorization side effect+ const reply = {+ version: 3 as const,+ id,+ publicKey: key.publicKey,+ bootId: identity.key.descriptor.bootId,+ ghostId: binding.ghostId,+ expiresAtMs,+ };+ this.connections.set(id, {+ id,+ peer,+ owner,+ hello,+ key,+ expiresAtMs,+ binding,+ started: false,+ finished: false,+ messages: new Map(),+ });+ return {+ ...reply,+ signature: identity.key.sign(+ transcript(+ hello,+ reply,+ { ...identity, publicKey: identity.key.descriptor.publicKey },+ peer,+ ),+ ),+ };+ }+ const v = oauthExact(raw, ['op', 'id', 'box']);+ if (v.op !== 'exchange' || typeof v.id !== 'string' || typeof v.box !== 'string') throw fail();+ const c = this.connections.get(v.id);+ if (!c || c.peer !== peer) throw fail();+ this.assertCurrent(c);+ const payload = oauthExact(c.key.open(c.hello.publicKey, domain(c.id), 'callback', v.box), [+ 'nonce',+ 'request',+ ]);+ const request = parsePluginOauthRequest(payload.request);+ if (!oauthNonce(payload.nonce) || !request) throw fail();+ const prior = c.messages.get(payload.nonce);+ if (prior) {+ if (prior.box !== v.box) throw fail();+ return prior.promise;+ }+ if (c.messages.size >= 1024) throw fail();+ if (request.op === 'start') {+ if (c.started || !sameAction(request, c.hello.action) || !c.binding.current()) throw fail();+ c.started = true;+ } else if (request.op !== 'capabilities' && (!c.innerId || request.id !== c.innerId))+ throw fail();+ const requestNonce = payload.nonce;+ const promise = (async () => {+ try {+ this.assertCurrent(c);+ const result = await this.deps.request(peer, request);+ this.assertCurrent(c);+ if (request.op === 'start') {+ const id = (result as { id?: unknown })?.id;+ if (typeof id !== 'string') throw fail();+ c.innerId = id;+ }+ if (+ request.op === 'cancel' ||+ ['succeeded', 'failed', 'cancelled', 'expired'].includes(+ String((result as { phase?: unknown })?.phase),+ )+ )+ c.finished = true;+ return {+ box: c.key.seal(c.hello.publicKey, domain(c.id), 'offer', {+ nonce: requestNonce,+ ok: true,+ result,+ }),+ };+ } catch {+ this.assertCurrent(c);+ return {+ box: c.key.seal(c.hello.publicKey, domain(c.id), 'offer', {+ nonce: requestNonce,+ ok: false,+ }),+ };+ }+ })();+ c.messages.set(requestNonce, { box: v.box, promise });+ return promise;+ }+}++/** Verify the signed handshake before sending start or opening any authorization page. No legacy identity/channel fallback. */+export async function authenticateOauthController(deps: {+ target: PluginOauthPeerIdentity;+ trustIdentity(target: PluginOauthPeerIdentity, assertCurrent: () => void): Promise<void>;+ peer: string;+ action: PluginOauthAction;+ ghostId: string;+ invoke(raw: unknown): Promise<unknown>;+ assertCurrent(): void;+ now?: () => number;+}): Promise<(request: PluginOauthRequest) => Promise<unknown>> {+ const now = deps.now ?? Date.now;+ deps.assertCurrent();+ if (+ deps.target.observedAtMs > now() + 1000 ||+ now() - deps.target.observedAtMs > 60_000 ||+ deps.target.expiresAtMs <= now() ||+ deps.target.expiresAtMs > deps.target.observedAtMs + 60_000+ )+ throw fail();+ const key = new OauthBox();+ const hello: PluginOauthHello = {+ op: 'hello',+ version: 3,+ nonce: nonce(),+ publicKey: key.publicKey,+ action: deps.action,+ };+ const reply = parsePluginOauthHelloReply(await deps.invoke(hello));+ deps.assertCurrent();+ const pub = createPublicKey({+ key: Buffer.from(deps.target.publicKey, 'base64url'),+ type: 'spki',+ format: 'der',+ });+ if (+ deps.target.expiresAtMs <= now() ||+ pub.asymmetricKeyType !== 'ed25519' ||+ reply.bootId !== deps.target.bootId ||+ reply.ghostId !== deps.ghostId ||+ reply.expiresAtMs <= now() ||+ reply.expiresAtMs > now() + PLUGIN_OAUTH_TTL_MS + 1000 ||+ !verify(+ null,+ transcript(hello, reply, deps.target, deps.peer),+ pub,+ Buffer.from(reply.signature, 'base64url'),+ )+ )+ throw fail();+ await deps.trustIdentity(deps.target, deps.assertCurrent);+ deps.assertCurrent();+ return async (request) => {+ if (request.op !== 'cancel') deps.assertCurrent();+ if (now() >= reply.expiresAtMs) throw fail();+ const requestNonce = nonce();+ const response = oauthExact(+ await deps.invoke({+ op: 'exchange',+ id: reply.id,+ box: key.seal(reply.publicKey, domain(reply.id), 'callback', {+ nonce: requestNonce,+ request,+ }),+ }),+ ['box'],+ );+ if (request.op !== 'cancel') deps.assertCurrent();+ if (typeof response.box !== 'string') throw fail();+ const opened = key.open(reply.publicKey, domain(reply.id), 'offer', response.box) as {+ ok?: unknown;+ };+ const value = oauthExact(+ opened,+ opened?.ok === true ? ['nonce', 'ok', 'result'] : ['nonce', 'ok'],+ );+ if (value.nonce !== requestNonce || value.ok !== true) throw fail();+ return value.result;+ };+}diff --git a/apps/desktop/src/main/plugin-oauth/authorizationAdapters.ts b/apps/desktop/src/main/plugin-oauth/authorizationAdapters.tsnew file mode 100644index 0000000000..fea8cf8e56--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/authorizationAdapters.ts@@ -0,0 +1,165 @@+import {+ parsePluginAuthorizationOffer,+ PLUGIN_OAUTH_TTL_MS,+ type PluginAuthorizationOffer,+ type PluginAuthorizationRequest,+ type PluginOauthCallback,+ type PluginDeviceOpened,+} from '@cindy/device-link';+import type {+ PluginOauthDeviceCodeClose,+ PluginOauthDeviceCodePrompt,+} from '../../shared/pluginOauthDeviceCode.js';+import { listenForOauthCallback } from './loopbackListener.js';++/** Transport-independent UI adapters. Only a validated Host transaction supplies an offer. */+export interface AuthorizationAdapterDeps {+ openExternal(url: string): Promise<void>;+ copyDeviceCode?(code: string): () => void;+ presentBrowserAuthorization?(+ expiresAt: number,+ reopen: () => Promise<void>,+ ): PluginOauthDeviceCodeClose;+ presentDeviceCode?(+ prompt: PluginOauthDeviceCodePrompt,+ clear: () => void,+ ): PluginOauthDeviceCodeClose;+ deliver(callback: PluginOauthCallback | PluginDeviceOpened): Promise<void>;+ assertCurrent(): void;+ failed(): void;+ deadline: number;+ now?: () => number;+ signal?: AbortSignal;+}+export interface AuthorizationAdapterHandle {+ close(phase?: 'completed' | 'expired' | 'ended'): void;+}+type Adapter = (+ offer: PluginAuthorizationOffer,+ deps: AuthorizationAdapterDeps,+) => Promise<AuthorizationAdapterHandle>;+const fail = () => new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');++async function openBrowser(+ offer: PluginAuthorizationOffer,+ deps: AuthorizationAdapterDeps,+): Promise<AuthorizationAdapterHandle> {+ const request = offer.request;+ let clear: (() => void) | undefined;+ let dismiss: PluginOauthDeviceCodeClose | undefined;+ const close = (phase: 'completed' | 'expired' | 'ended' = 'ended') => {+ clear?.();+ dismiss?.(phase);+ };+ try {+ if (request.kind === 'device' && request.userCode !== undefined) {+ if (!deps.copyDeviceCode) throw fail();+ clear = deps.copyDeviceCode(request.userCode);+ dismiss = deps.presentDeviceCode?.(+ {+ userCode: request.userCode,+ authorizeUrl: request.url,+ expiresAt: Math.min(deps.deadline, request.expiresAt ?? deps.deadline),+ },+ clear,+ );+ }+ if (!dismiss) {+ dismiss = deps.presentBrowserAuthorization?.(deps.deadline, async () => {+ deps.assertCurrent();+ await deps.openExternal(request.url);+ deps.assertCurrent();+ });+ }+ await deps.openExternal(request.url);+ deps.assertCurrent();+ await deps.deliver({ kind: 'device-opened', state: offer.state });+ return { close };+ } catch {+ close();+ throw fail();+ }+}++async function openLoopback(+ offer: PluginAuthorizationOffer,+ deps: AuthorizationAdapterDeps,+): Promise<AuthorizationAdapterHandle> {+ const request = offer.request;+ if (request.kind !== 'loopback') throw fail();+ // The provider state can use the CLI's own encoding. The private wire callback+ // uses the independently generated bridge state; neither is rendered or logged.+ const listener = await listenForOauthCallback(+ {+ authorizeUrl: request.url,+ callbackUrl: request.callbackUrl,+ state: offer.state,+ corsOrigins: [new URL(request.url).origin],+ corsHosts: [],+ },+ async (callback) => {+ try {+ deps.assertCurrent();+ await deps.deliver(callback);+ } catch {+ deps.failed();+ throw fail();+ }+ },+ deps.assertCurrent,+ request.state,+ );+ let dismiss: PluginOauthDeviceCodeClose | undefined;+ try {+ deps.signal?.addEventListener('abort', listener.close, { once: true });+ deps.assertCurrent();+ dismiss = deps.presentBrowserAuthorization?.(deps.deadline, async () => {+ deps.assertCurrent();+ await deps.openExternal(request.url);+ deps.assertCurrent();+ });+ await deps.openExternal(request.url);+ deps.assertCurrent();+ return {+ close: (phase = 'ended') => {+ dismiss?.(phase);+ deps.signal?.removeEventListener('abort', listener.close);+ listener.close();+ },+ };+ } catch {+ dismiss?.('ended');+ deps.signal?.removeEventListener('abort', listener.close);+ listener.close();+ throw fail();+ }+}++/**+ * Adding a transport mode means adding one parser/adapter and negotiated support,+ * never another provider branch in card, IPC, broker or Agent dispatch.+ */+const adapters: Readonly<Record<PluginAuthorizationRequest['kind'], Adapter>> = Object.freeze({+ device: openBrowser,+ browser: openBrowser,+ loopback: openLoopback,+});++export async function openAuthorizationOffer(+ raw: unknown,+ deps: AuthorizationAdapterDeps,+): Promise<AuthorizationAdapterHandle> {+ const offer = parsePluginAuthorizationOffer(raw);+ const now = deps.now ?? Date.now;+ const expiresAt = Math.min(+ deps.deadline,+ now() + PLUGIN_OAUTH_TTL_MS,+ offer.request.kind === 'loopback' ? Infinity : (offer.request.expiresAt ?? Infinity),+ );+ const assertCurrent = () => {+ deps.assertCurrent();+ if (deps.signal?.aborted || now() >= expiresAt) throw fail();+ };+ assertCurrent();+ return adapters[offer.request.kind](offer, { ...deps, assertCurrent, deadline: expiresAt });+}diff --git a/apps/desktop/src/main/plugin-oauth/box.ts b/apps/desktop/src/main/plugin-oauth/box.tsnew file mode 100644index 0000000000..047a21dfd1--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/box.ts@@ -0,0 +1,72 @@+import {+ createCipheriv,+ createDecipheriv,+ createPublicKey,+ diffieHellman,+ generateKeyPairSync,+ hkdfSync,+ randomBytes,+ type KeyObject,+} from 'node:crypto';++/** Ephemeral X25519 + HKDF/AES-GCM. Relay identity routing remains a trust root. */+export class OauthBox {+ private readonly privateKey: KeyObject;+ readonly publicKey: string;+ constructor() {+ const pair = generateKeyPairSync('x25519');+ this.privateKey = pair.privateKey;+ this.publicKey = pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64url');+ }+ private key(peer: string, id: string, direction: 'offer' | 'callback'): Buffer {+ if (!/^[A-Za-z0-9_-]{59}$/.test(peer)) throw new Error('OAUTH_BRIDGE_INVALID');+ const key = createPublicKey({+ key: Buffer.from(peer, 'base64url'),+ type: 'spki',+ format: 'der',+ });+ if (key.asymmetricKeyType !== 'x25519') throw new Error('OAUTH_BRIDGE_INVALID');+ const shared = diffieHellman({ privateKey: this.privateKey, publicKey: key });+ try {+ return Buffer.from(hkdfSync('sha256', shared, id, `cindy-plugin-oauth-v1:${direction}`, 32));+ } finally {+ shared.fill(0);+ }+ }+ seal(peer: string, id: string, direction: 'offer' | 'callback', value: unknown): string {+ const key = this.key(peer, id, direction);+ const iv = randomBytes(12);+ try {+ const cipher = createCipheriv('aes-256-gcm', key, iv);+ cipher.setAAD(Buffer.from(`cindy-plugin-oauth-v1:${id}:${direction}`));+ const body = Buffer.from(JSON.stringify(value));+ if (body.length > 32_000) throw new Error('OAUTH_BRIDGE_INVALID');+ return Buffer.concat([iv, cipher.update(body), cipher.final(), cipher.getAuthTag()]).toString(+ 'base64url',+ );+ } finally {+ key.fill(0);+ }+ }+ open(peer: string, id: string, direction: 'offer' | 'callback', box: string): unknown {+ try {+ if (!/^[A-Za-z0-9_-]{40,48000}$/.test(box)) throw 0;+ const data = Buffer.from(box, 'base64url');+ const key = this.key(peer, id, direction);+ try {+ const decipher = createDecipheriv('aes-256-gcm', key, data.subarray(0, 12));+ decipher.setAAD(Buffer.from(`cindy-plugin-oauth-v1:${id}:${direction}`));+ decipher.setAuthTag(data.subarray(-16));+ return JSON.parse(+ Buffer.concat([decipher.update(data.subarray(12, -16)), decipher.final()]).toString(+ 'utf8',+ ),+ );+ } finally {+ key.fill(0);+ }+ } catch {+ throw new Error('OAUTH_BRIDGE_INVALID');+ }+ }+}diff --git a/apps/desktop/src/main/plugin-oauth/builtinAuthorizationTargets.ts b/apps/desktop/src/main/plugin-oauth/builtinAuthorizationTargets.tsnew file mode 100644index 0000000000..e912fdf738--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/builtinAuthorizationTargets.ts@@ -0,0 +1,18 @@+/**+ * Narrow legacy provider contracts. New generic integrations use their installed+ * declaration; these restrictions cannot be overridden by plugin/CLI output.+ */+export const builtinAuthorizationTargets: Readonly<Record<string, (url: URL) => boolean>> =+ Object.freeze({+ 'cindy-github': (url) =>+ url.origin === 'https://github.com' &&+ url.pathname === '/login/device' &&+ !url.search &&+ !url.hash,+ 'taptap-maker': (url) =>+ url.origin === 'https://maker.taptap.cn' &&+ url.pathname === '/pat-tokens' &&+ !url.hash &&+ [...url.searchParams.keys()].join(',') === 'code' &&+ /^[A-Za-z0-9_-]{32}$/.test(url.searchParams.get('code') ?? ''),+ });diff --git a/apps/desktop/src/main/plugin-oauth/cards.ts b/apps/desktop/src/main/plugin-oauth/cards.tsnew file mode 100644index 0000000000..8731bc939f--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/cards.ts@@ -0,0 +1,142 @@+import type { PluginOauthAction, PluginConnectionInput } from '@cindy/device-link';+import { randomBytes } from 'node:crypto';+import {+ createPluginSecretPresentation,+ createPluginConnectionPresentation,+} from '../../shared/pluginOauth.js';+import { getRemoteOauthContext } from './context.js';+import type { GhostSetupInteractionBridge } from '../cindy-brain/ghostSetupInteractionBridge.js';+import type { BotAuthorizationService } from '../maker-ipc/botAuthorizationService.js';+import { initializePluginOauthHost, type OauthKeyLoader } from './runtime.js';+import type { OauthIdentityScope } from './identityStore.js';+import type { OauthCardBinding } from './transactions.js';++/** Bind existing Host cards; no new plugin manifest or generic setup permission. */+export function initializePluginOauthCards(deps: {+ bridge: GhostSetupInteractionBridge;+ bots(): BotAuthorizationService | null;+ owner(): string | null;+ available(peer: string): boolean;+ identity: () => OauthIdentityScope | null;+ loadKey: OauthKeyLoader;+ bindConnection?(args: {+ ghostId: string;+ actionId: string;+ onCommitted(): void;+ }): ((value: PluginConnectionInput) => boolean) | null;+}): void {+ const findCardAction = (action: PluginOauthAction) => {+ const found = deps.bridge+ .pendingSnapshots()+ .find((e) => e.request.requestId === action.requestId);+ if (!found || found.request.terminal || found.request.revision !== action.expectedRevision)+ return null;+ const step = found.request.steps.find(+ (s) =>+ s.action?.id === action.actionId &&+ (s.action.kind === 'oauth_connect' ||+ (found.request.remoteSecret === true && s.action.kind === 'inline_form') ||+ (found.request.remoteConnection === true &&+ !!deps.bindConnection &&+ s.action.kind === 'manage_connection')) &&+ (s.phase === 'pending' || s.phase === 'failed'),+ );+ if (!step) return null;+ const binding: OauthCardBinding = {+ ghostId: found.request.ghost.id,+ current: () =>+ deps.bridge+ .pendingSnapshots(found.sessionId)+ .some((e) => e.request.requestId === action.requestId && !e.request.terminal),+ };+ return { snapshot: found.request, step, binding };+ };+ initializePluginOauthHost(+ {+ owner: deps.owner,+ available: deps.available,+ bind: async (action) =>+ findCardAction(action)?.binding ?? (await deps.bots()?.bindRemoteOauth(action)) ?? null,+ run: async (action) => {+ const card = findCardAction(action);+ if (card) {+ const { snapshot, step } = card;+ if (step.action?.kind === 'manage_connection') {+ const remote = getRemoteOauthContext();+ if (!remote?.submitConnection || !deps.bindConnection) return false;+ const save = deps.bindConnection({+ ghostId: snapshot.ghost.id,+ actionId: action.actionId,+ onCommitted: () => {+ deps.bridge.connectionCommitted(+ action.requestId,+ action.actionId,+ action.expectedRevision,+ );+ },+ });+ if (!save) return false;+ const presentation = createPluginConnectionPresentation(snapshot, step);+ void (async () => {+ let value: PluginConnectionInput | undefined;+ try {+ value = await remote.submitConnection!({+ kind: 'connection-entry',+ state: randomBytes(32).toString('base64url'),+ presentation,+ });+ remote.assertCurrent();+ if (!findCardAction(action) || !save(value))+ throw new Error('PLUGIN_CONNECTION_UNAVAILABLE');+ } catch {+ remote.finish(false);+ } finally {+ value = undefined;+ }+ })();+ return true;+ }+ if (step.action?.kind === 'inline_form') {+ const remote = getRemoteOauthContext();+ const submitSecret = remote?.submitSecret;+ if (!remote || !submitSecret) return false;+ const field = step.action.form.fields[0];+ const presentation = createPluginSecretPresentation(snapshot, step, field);+ void (async () => {+ try {+ let value = await submitSecret({+ kind: 'secret-entry',+ state: randomBytes(32).toString('base64url'),+ presentation,+ });+ remote.assertCurrent();+ // No optimistic write: the same card/revision/action must still be+ // pending, then the ordinary executor re-resolves its actual vault key.+ if (!findCardAction(action)) throw new Error('PLUGIN_SECRET_UNAVAILABLE');+ const accepted = deps.bridge.submitInline(action.requestId, {+ actionId: action.actionId,+ expectedRevision: action.expectedRevision,+ value,+ });+ value = '';+ if (!accepted) throw new Error('PLUGIN_SECRET_UNAVAILABLE');+ } catch {+ remote.finish(false);+ }+ })();+ return true;+ }+ return deps.bridge.resolve(action.requestId, {+ kind: 'plugin_setup',+ action: 'run_action',+ actionId: action.actionId,+ expectedRevision: action.expectedRevision,+ });+ }+ return (await deps.bots()?.resolveRemoteOauth(action)) ?? false;+ },+ },+ deps.identity,+ deps.loadKey,+ );+}diff --git a/apps/desktop/src/main/plugin-oauth/context.ts b/apps/desktop/src/main/plugin-oauth/context.tsnew file mode 100644index 0000000000..584008402b--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/context.ts@@ -0,0 +1,43 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import type {+ PluginSecretOffer,+ PluginConnectionOffer,+ PluginConnectionInput,+ PluginOauthCallback,+ PluginOauthOffer,+ PluginDeviceOffer,+ PluginAuthorizationOffer,+ PluginDeviceOpened,+} from '@cindy/device-link';++/** Captured by a validated card action, never from model/Renderer URL parameters. */+export interface RemoteOauthContext {+ scope: string;+ assertCurrent(): void;+ authorize(offer: PluginOauthOffer, signal: AbortSignal): Promise<PluginOauthCallback>;+ /** Optional additive capability; old loopback callers stay unchanged. */+ authorizeDevice?(offer: PluginDeviceOffer, signal: AbortSignal): Promise<void>;+ authorizePlugin?(+ offer: PluginAuthorizationOffer,+ signal: AbortSignal,+ ): Promise<PluginOauthCallback | PluginDeviceOpened>;+ submitSecret?(offer: PluginSecretOffer): Promise<string>;+ submitConnection?(offer: PluginConnectionOffer): Promise<PluginConnectionInput>;+ cancelled?: AbortSignal;+ finish(ok: boolean): void;+}+const storage = new AsyncLocalStorage<RemoteOauthContext>();+export const getRemoteOauthContext = () => storage.getStore();+export function withRemoteOauthContext<T>(context: RemoteOauthContext, action: () => T): T {+ return storage.run(context, action);+}+const closedListeners = new Set<(requestId: string) => void>();+export function onOauthCardClosed(listener: (requestId: string) => void): () => void {+ closedListeners.add(listener);+ return () => {+ closedListeners.delete(listener);+ };+}+export function notifyOauthCardClosed(requestId: string): void {+ for (const listener of closedListeners) listener(requestId);+}diff --git a/apps/desktop/src/main/plugin-oauth/controller.ts b/apps/desktop/src/main/plugin-oauth/controller.tsnew file mode 100644index 0000000000..9bc25e10a1--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/controller.ts@@ -0,0 +1,315 @@+import {+ PLUGIN_OAUTH_TTL_MS,+ parsePluginDeviceOffer,+ parsePluginSecretOffer,+ parsePluginSecretValue,+ parsePluginSecretPresentation,+ type PluginSecretPresentation,+ parsePluginConnectionOffer,+ parsePluginConnectionValue,+ parsePluginConnectionPresentation,+ type PluginConnectionInput,+ type PluginConnectionPresentation,+ oauthId,+ type PluginOauthAction,+ type PluginOauthCallback,+ type PluginDeviceOpened,+ type PluginOauthOffer,+ type PluginOauthRequest,+} from '@cindy/device-link';+import { OauthBox } from './box.js';+import {+ openAuthorizationOffer,+ type AuthorizationAdapterHandle,+} from './authorizationAdapters.js';+import type {+ PluginOauthDeviceCodePrompt,+ PluginOauthDeviceCodeClose,+} from '../../shared/pluginOauthDeviceCode.js';+import { listenForOauthCallback } from './loopbackListener.js';+export { listenForOauthCallback } from './loopbackListener.js';++const fail = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');+function object(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail();+ return value as Record<string, unknown>;+}+/** These URLs come only from the encrypted, registered Host transaction. */+export function parseOauthOffer(raw: unknown): PluginOauthOffer {+ const v = object(raw);+ if (+ Object.keys(v).sort().join(',') !== 'authorizeUrl,callbackUrl,corsHosts,corsOrigins,state' ||+ typeof v.authorizeUrl !== 'string' ||+ v.authorizeUrl.length > 16_384 ||+ typeof v.callbackUrl !== 'string' ||+ v.callbackUrl.length > 2048 ||+ typeof v.state !== 'string' ||+ !/^[A-Za-z0-9_-]{43}$/.test(v.state) ||+ !Array.isArray(v.corsOrigins) ||+ v.corsOrigins.length > 64 ||+ !Array.isArray(v.corsHosts) ||+ v.corsHosts.length > 128 ||+ v.corsHosts.some((h) => typeof h !== 'string' || !/^(?:\*\.)?[A-Za-z0-9.-]{1,253}$/.test(h))+ )+ throw fail();+ const authorize = new URL(v.authorizeUrl);+ const callback = new URL(v.callbackUrl);+ if (+ authorize.protocol !== 'https:' ||+ authorize.username ||+ authorize.password ||+ authorize.hash ||+ authorize.searchParams.getAll('state').length !== 1 ||+ authorize.searchParams.get('state') !== v.state ||+ authorize.searchParams.get('response_type') !== 'code' ||+ callback.protocol !== 'http:' ||+ callback.hostname !== '127.0.0.1' ||+ !callback.port ||+ Number(callback.port) < 1 ||+ callback.username ||+ callback.password ||+ callback.hash ||+ callback.search ||+ /[\x00-\x20]/.test(v.callbackUrl)+ )+ throw fail();+ const corsOrigins = v.corsOrigins.map((origin) => {+ if (typeof origin !== 'string' || origin.length > 1024) throw fail();+ const parsed = new URL(origin);+ if (+ parsed.protocol !== 'https:' ||+ parsed.origin !== origin ||+ parsed.username ||+ parsed.password+ )+ throw fail();+ return origin;+ });+ return {+ authorizeUrl: authorize.toString(),+ callbackUrl: callback.toString(),+ state: v.state,+ corsOrigins,+ corsHosts: v.corsHosts as string[],+ };+}++export interface OauthControllerDeps {+ /** Supplied only by the dedicated local input IPC, never generic assist or a Node adapter. */+ secretValue?: string;+ secretPresentation?: PluginSecretPresentation;+ connectionValue?: PluginConnectionInput;+ connectionPresentation?: PluginConnectionPresentation;+ invoke(request: PluginOauthRequest): Promise<unknown>;+ openExternal(url: string): Promise<void>;+ copyDeviceCode?(code: string): () => void;+ presentBrowserAuthorization?(+ expiresAt: number,+ reopen: () => Promise<void>,+ ): PluginOauthDeviceCodeClose;+ presentDeviceCode?(+ prompt: PluginOauthDeviceCodePrompt,+ clearClipboard: () => void,+ ): PluginOauthDeviceCodeClose;+ assertCurrent(): void;+ now?: () => number;+ pause?: () => Promise<void>;+}+/** Runs only behind the trusted Desktop click IPC. Returns status, never URL/code/token. */+export async function assistPluginOauth(+ deps: OauthControllerDeps,+ action: PluginOauthAction,+): Promise<{ accepted: true }> {+ try {+ return await runAuthorization(deps, action);+ } finally {+ // Capability/handshake failures happen before a transaction exists too.+ deps.secretValue = undefined;+ deps.connectionValue = undefined;+ }+}++async function runAuthorization(+ deps: OauthControllerDeps,+ action: PluginOauthAction,+): Promise<{ accepted: true }> {+ const now = deps.now ?? Date.now;+ const deadline = now() + PLUGIN_OAUTH_TTL_MS;+ deps.assertCurrent();+ const caps = object(await deps.invoke({ op: 'capabilities' }));+ if (caps.version !== 1 || caps.callback !== 'desktop-loopback' || caps.encrypted !== true)+ throw fail();+ if (deps.secretValue !== undefined && caps.secretSubmission !== true) throw fail();+ if (+ deps.connectionValue !== undefined &&+ (caps.connectionSubmission !== true || deps.secretValue !== undefined)+ )+ throw fail();+ deps.assertCurrent();+ const key = new OauthBox();+ const deviceUserCode = caps.deviceUserCode === true && !!deps.copyDeviceCode;+ const start = object(+ await deps.invoke({+ op: 'start',+ ...action,+ publicKey: key.publicKey,+ ...(deviceUserCode ? { deviceUserCode: true } : {}),+ ...(caps.authorizationV1 === true ? { authorizationV1: true } : {}),+ ...(deps.secretValue !== undefined ? { secretSubmission: true } : {}),+ ...(deps.connectionValue !== undefined ? { connectionSubmission: true } : {}),+ }),+ );+ if (+ !oauthId(start.id) ||+ typeof start.publicKey !== 'string' ||+ !/^[A-Za-z0-9_-]{59}$/.test(start.publicKey)+ )+ throw fail();+ const id = start.id;+ const peerKey = start.publicKey;+ const deliverSealedCallback = async (box: string) => {+ deps.assertCurrent();+ const result = object(await deps.invoke({ op: 'callback', id, box }));+ if (result.accepted !== true) throw fail();+ };+ const deliverCallback = async (callback: PluginOauthCallback | PluginDeviceOpened) => {+ deps.assertCurrent();+ await deliverSealedCallback(key.seal(peerKey, id, 'callback', callback));+ };+ let listener: { close(): void } | undefined;+ let adapter: AuthorizationAdapterHandle | undefined;+ let opened = false;+ let finished = false;+ let callbackFailed = false;+ let clearDeviceCode: (() => void) | undefined;+ let closeDeviceCode: PluginOauthDeviceCodeClose | undefined;+ try {+ while (now() < deadline) {+ deps.assertCurrent();+ if (callbackFailed) throw fail();+ const status = object(await deps.invoke({ op: 'status', id }));+ deps.assertCurrent();+ if (status.phase === 'succeeded') {+ finished = true;+ return { accepted: true };+ }+ if (status.phase === 'failed' || status.phase === 'cancelled') throw fail();+ if (!['starting', 'authorizing', 'exchanging'].includes(String(status.phase))) throw fail();+ if (status.phase === 'authorizing' && !opened) {+ if (typeof status.offer !== 'string') throw fail();+ const rawOffer = object(key.open(peerKey, id, 'offer', status.offer));+ if (rawOffer.kind === 'connection-entry') {+ if (caps.connectionSubmission !== true || deps.connectionValue === undefined)+ throw fail();+ const offer = parsePluginConnectionOffer(rawOffer);+ if (+ JSON.stringify(offer.presentation) !==+ JSON.stringify(parsePluginConnectionPresentation(deps.connectionPresentation))+ )+ throw fail();+ const payload = parsePluginConnectionValue({+ kind: 'connection-value',+ state: offer.state,+ value: deps.connectionValue,+ });+ deps.assertCurrent();+ const sealed = key.seal(peerKey, id, 'callback', payload);+ deps.connectionValue = undefined;+ await deliverSealedCallback(sealed);+ opened = true;+ continue;+ }+ // A connection form cannot be reinterpreted as a free-form secret or OAuth action.+ if (deps.connectionValue !== undefined) throw fail();+ if (rawOffer.kind === 'secret-entry') {+ if (caps.secretSubmission !== true || deps.secretValue === undefined) throw fail();+ const offer = parsePluginSecretOffer(rawOffer);+ if (+ JSON.stringify(offer.presentation) !==+ JSON.stringify(parsePluginSecretPresentation(deps.secretPresentation))+ )+ throw fail();+ const payload = parsePluginSecretValue({+ kind: 'secret-value',+ state: offer.state,+ value: deps.secretValue,+ });+ if (payload.value.length > offer.presentation.maxLength) throw fail();+ deps.assertCurrent();+ const sealed = key.seal(peerKey, id, 'callback', payload);+ deps.secretValue = undefined;+ await deliverSealedCallback(sealed);+ opened = true;+ continue;+ }+ // Never send an input secret to a transaction that asks for another mode.+ if (deps.secretValue !== undefined) throw fail();+ if (rawOffer.kind === 'authorization') {+ if (caps.authorizationV1 !== true) throw fail();+ adapter = await openAuthorizationOffer(rawOffer, {+ ...deps,+ deadline,+ failed: () => {+ callbackFailed = true;+ },+ copyDeviceCode: deviceUserCode ? deps.copyDeviceCode : undefined,+ deliver: deliverCallback,+ });+ opened = true;+ continue;+ }+ if (rawOffer.kind === 'device') {+ if (caps.deviceAuthorization !== true) throw fail();+ const offer = parsePluginDeviceOffer(rawOffer);+ deps.assertCurrent();+ if (offer.userCode !== undefined) {+ if (!deviceUserCode || !deps.copyDeviceCode) throw fail();+ clearDeviceCode = deps.copyDeviceCode(offer.userCode);+ closeDeviceCode = deps.presentDeviceCode?.(+ { userCode: offer.userCode, authorizeUrl: offer.authorizeUrl, expiresAt: deadline },+ clearDeviceCode,+ );+ }+ if (!closeDeviceCode)+ closeDeviceCode = deps.presentBrowserAuthorization?.(deadline, () =>+ deps.openExternal(offer.authorizeUrl),+ );+ await deps.openExternal(offer.authorizeUrl);+ deps.assertCurrent();+ await deliverCallback({ kind: 'device-opened', state: offer.state });+ opened = true;+ continue; // Browser open is not authorization completion. Keep observing the cloud operation.+ }+ const offer = parseOauthOffer(rawOffer);+ listener = await listenForOauthCallback(+ offer,+ async (callback) => {+ try {+ await deliverCallback(callback);+ } catch {+ callbackFailed = true;+ throw fail();+ }+ },+ deps.assertCurrent,+ );+ deps.assertCurrent();+ closeDeviceCode = deps.presentBrowserAuthorization?.(deadline, () =>+ deps.openExternal(offer.authorizeUrl),+ );+ await deps.openExternal(offer.authorizeUrl);+ opened = true;+ }+ await (deps.pause?.() ?? new Promise((resolve) => setTimeout(resolve, 500)));+ }+ throw fail();+ } finally {+ deps.secretValue = undefined;+ deps.connectionValue = undefined;+ listener?.close();+ adapter?.close(finished ? 'completed' : now() >= deadline ? 'expired' : 'ended');+ clearDeviceCode?.();+ closeDeviceCode?.(finished ? 'completed' : now() >= deadline ? 'expired' : 'ended');+ if (!finished) await deps.invoke({ op: 'cancel', id }).catch(() => {});+ }+}diff --git a/apps/desktop/src/main/plugin-oauth/desktopIdentity.ts b/apps/desktop/src/main/plugin-oauth/desktopIdentity.tsnew file mode 100644index 0000000000..6dce74a682--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/desktopIdentity.ts@@ -0,0 +1,76 @@+import { safeStorage } from 'electron';+import { getCurrentUserId, getDeviceId, getActiveAuthRealm } from '../authManager.js';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+ ownerScopedUserDataPath,+} from '../appSessionState.js';+import {+ OauthIdentityStore,+ oauthIdentityScopeKey,+ oauthSecureStorageAvailable,+ type OauthIdentityScope,+} from './identityStore.js';+import type { PluginOauthPeerIdentity } from '@cindy/device-link';++/** The normal authenticated Desktop owner, independent of distribution or instance configuration. */+export function currentOauthIdentityScope(): OauthIdentityScope | null {+ const session = getActiveAppSession();+ const membershipId = getCurrentUserId();+ if (+ isAppSessionBoundaryPending() ||+ session.mode !== 'cloud' ||+ !membershipId ||+ session.dataOwnerId !== membershipId+ )+ return null;+ return { realm: getActiveAuthRealm(), membershipId, deviceId: getDeviceId() };+}++const store = new OauthIdentityStore({+ filePath: (scope) =>+ ownerScopedUserDataPath('plugin-oauth', `${oauthIdentityScopeKey(scope)}.v1.enc`),+ available: () => {+ try {+ return oauthSecureStorageAvailable({+ platform: process.platform,+ available: safeStorage.isEncryptionAvailable(),+ backend: process.platform === 'linux' ? safeStorage.getSelectedStorageBackend() : undefined,+ });+ } catch {+ return false;+ }+ },+ encrypt: (value) => safeStorage.encryptString(value),+ decrypt: (value) => safeStorage.decryptString(value),+});++function scopedCheck(scope: OauthIdentityScope, assertCurrent: () => void): () => void {+ const expected = oauthIdentityScopeKey(scope);+ return () => {+ assertCurrent();+ const current = currentOauthIdentityScope();+ if (!current || oauthIdentityScopeKey(current) !== expected)+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ };+}++export function loadOauthSigningKey(scope: OauthIdentityScope, assertCurrent: () => void) {+ return store.load(scope, scopedCheck(scope, assertCurrent));+}++/** Called after signed proof of possession, before any browser/secret operation. */+export async function trustOauthPeer(+ identity: PluginOauthPeerIdentity,+ assertCurrent: () => void,+): Promise<void> {+ const scope = currentOauthIdentityScope();+ if (!scope || identity.realm !== scope.realm || identity.membershipId !== scope.membershipId)+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ await store.trustPeer(+ scope,+ identity.deviceId,+ identity.publicKey,+ scopedCheck(scope, assertCurrent),+ );+}diff --git a/apps/desktop/src/main/plugin-oauth/deviceCard.ts b/apps/desktop/src/main/plugin-oauth/deviceCard.tsnew file mode 100644index 0000000000..a662d92118--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/deviceCard.ts@@ -0,0 +1,286 @@+import { randomBytes, randomUUID } from 'node:crypto';+import {+ PLUGIN_OAUTH_TTL_MS,+ parsePluginAuthorizationRequest,+ type PluginAuthorizationRequest,+ type PluginAuthorizationResult,+ type PluginOauthCallback,+ type PluginDeviceOpened,+} from '@cindy/device-link';+import {+ openAuthorizationOffer,+ type AuthorizationAdapterHandle,+} from './authorizationAdapters.js';+import type {+ GhostSetupInteractionBridge,+ GhostSetupInteractionSnapshot,+} from '../cindy-brain/ghostSetupInteractionBridge.js';+import { getRemoteOauthContext, type RemoteOauthContext } from './context.js';++export interface DeviceAuthorizationHandle {+ opened: Promise<void>;+ finish(ok: boolean): void;+ dispose(): void;+}+export interface DeviceAuthorizationInput {+ ghost: { id: string; name: string };+ sessionId: string;+ url: string;+ userCode?: string;+ signal: AbortSignal;+ assertCurrent(): void;+ cancel(): void;+}++export interface PluginAuthorizationHandle extends DeviceAuthorizationHandle {+ result: Promise<PluginAuthorizationResult>;+}+export interface PluginAuthorizationInput extends Omit<+ DeviceAuthorizationInput,+ 'url' | 'userCode'+> {+ request: PluginAuthorizationRequest;+}+export interface AuthorizationCardDeps {+ bridge: GhostSetupInteractionBridge;+ openExternal(url: string): Promise<void>;+ copyDeviceCode?(code: string): () => void;+ copy: { title: string; description: string };+}++/** Legacy URL-only callers retain their existing negotiated device offer. */+export function openDeviceAuthorizationCard(+ input: DeviceAuthorizationInput,+ deps: AuthorizationCardDeps,+): DeviceAuthorizationHandle {+ return openCard(+ {+ ...input,+ request: {+ kind: 'device',+ url: input.url,+ ...(input.userCode === undefined ? {} : { userCode: input.userCode }),+ },+ },+ deps,+ true,+ );+}++/** One lifecycle for device codes, browser/QR confirmation and CLI PKCE callbacks. */+export function openPluginAuthorizationCard(+ input: PluginAuthorizationInput,+ deps: AuthorizationCardDeps,+): PluginAuthorizationHandle {+ return openCard(input, deps, false);+}++function openCard(+ input: PluginAuthorizationInput,+ deps: AuthorizationCardDeps,+ legacy: boolean,+): PluginAuthorizationHandle {+ input.assertCurrent();+ const request = parsePluginAuthorizationRequest(input.request);+ const url = request.url;+ const expiresAt = Math.min(+ Date.now() + PLUGIN_OAUTH_TTL_MS,+ request.kind === 'loopback' ? Infinity : (request.expiresAt ?? Infinity),+ );+ if (expiresAt <= Date.now()) throw new Error('PLUGIN_AUTHORIZATION_EXPIRED');+ const requestId = randomUUID();+ const actionId = 'device-authorization';+ const lifetime = new AbortController();+ let context: RemoteOauthContext | undefined;+ let begun = false;+ let opened = false;+ let settled = false;+ let providerRejected = false;+ let clearDeviceCode: (() => void) | undefined;+ let localAdapter: AuthorizationAdapterHandle | undefined;+ let resolveResult!: (result: PluginAuthorizationResult) => void;+ let rejectResult!: (error: Error) => void;+ const result = new Promise<PluginAuthorizationResult>((yes, no) => {+ resolveResult = yes;+ rejectResult = no;+ });+ void result.catch(() => {});+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const openedPromise = new Promise<void>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ void openedPromise.catch(() => {});+ let snapshot: GhostSetupInteractionSnapshot = {+ kind: 'plugin_setup',+ requestId,+ revision: 0,+ ghost: input.ghost,+ steps: [+ {+ id: actionId,+ groupId: actionId,+ groupMode: 'any_of',+ title: deps.copy.title,+ description: deps.copy.description.replace('{{host}}', new URL(url).hostname),+ phase: 'pending',+ action: { id: actionId, kind: 'oauth_connect' },+ },+ ],+ };+ const assertCurrent = () => {+ if (settled || input.signal.aborted || lifetime.signal.aborted || Date.now() >= expiresAt)+ throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ input.assertCurrent();+ context?.assertCurrent();+ };+ const update = (phase: 'waiting_external' | 'satisfied' | 'failed', terminal = false) => {+ snapshot = {+ ...snapshot,+ revision: snapshot.revision + 1,+ ...(terminal ? { terminal: true } : {}),+ steps: snapshot.steps.map((step) => ({+ ...step,+ phase,+ ...(phase === 'failed' ? { errorCode: 'AUTH_FAILED' as const } : {}),+ })),+ };+ deps.bridge.update(snapshot);+ };+ const finish = (ok: boolean) => {+ if (settled) return;+ let valid = false;+ try {+ assertCurrent();+ valid = true;+ } catch {+ /* Stale completions cannot become success. */+ }+ const success = ok && opened && valid && !providerRejected;+ settled = true;+ // Finish the transaction before the card becomes terminal and closes its binding.+ context?.cancelled?.removeEventListener('abort', cancel);+ context?.finish(success);+ lifetime.abort();+ input.signal.removeEventListener('abort', cancel);+ clearTimeout(timer);+ clearDeviceCode?.();+ localAdapter?.close(success ? 'completed' : 'ended');+ if (!opened) rejectResult(new Error('DEVICE_AUTHORIZATION_UNAVAILABLE'));+ if (!opened) reject(new Error('DEVICE_AUTHORIZATION_UNAVAILABLE'));+ update(success ? 'satisfied' : 'failed', true);+ deps.bridge.complete(requestId);+ const dismiss = setTimeout(+ () => deps.bridge.close(requestId, success ? 'completed' : 'cancelled'),+ 1500,+ );+ dismiss.unref?.();+ };+ const cancel = () => {+ finish(false);+ input.cancel();+ };+ const timer = setTimeout(cancel, Math.max(1, expiresAt - Date.now()));+ timer.unref?.();+ input.signal.addEventListener('abort', cancel, { once: true });+ try {+ deps.bridge.open(input.sessionId, snapshot, (command, responseTarget) => {+ if (command.action === 'cancel') {+ if (command.cleanupReason || command.expectedRevision === snapshot.revision) cancel();+ return;+ }+ if (begun || command.expectedRevision !== snapshot.revision || command.actionId !== actionId)+ return;+ assertCurrent();+ const remote = getRemoteOauthContext();+ // Generic remote run_action cannot fall through to opening a cloud browser.+ if (!remote && (!responseTarget || responseTarget.isDestroyed())) return;+ begun = true;+ context = remote;+ context?.cancelled?.addEventListener('abort', cancel, { once: true });+ update('waiting_external');+ void (async () => {+ assertCurrent();+ let response: PluginAuthorizationResult = { kind: 'opened' };+ if (!legacy) {+ const offer = {+ kind: 'authorization' as const,+ state: randomBytes(32).toString('base64url'),+ request,+ };+ let callback: PluginOauthCallback | PluginDeviceOpened;+ if (remote) {+ if (!remote.authorizePlugin || !remote.cancelled)+ throw new Error('PLUGIN_AUTHORIZATION_UNSUPPORTED');+ callback = await remote.authorizePlugin(offer, lifetime.signal);+ } else if (request.kind === 'loopback') {+ // The source CLI already owns its local callback listener. A local+ // browser delivers directly; never bind its port or forward HTTP.+ await deps.openExternal(request.url);+ assertCurrent();+ callback = { kind: 'device-opened', state: offer.state };+ } else {+ let receive!: (value: PluginOauthCallback | PluginDeviceOpened) => void;+ let fail!: (error: Error) => void;+ const waiting = new Promise<PluginOauthCallback | PluginDeviceOpened>((yes, no) => {+ receive = yes;+ fail = no;+ });+ void waiting.catch(() => {});+ const abort = () => fail(new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE'));+ lifetime.signal.addEventListener('abort', abort, { once: true });+ try {+ localAdapter = await openAuthorizationOffer(offer, {+ ...deps,+ deadline: expiresAt,+ signal: lifetime.signal,+ assertCurrent,+ failed: cancel,+ deliver: async (value) => {+ assertCurrent();+ receive(value);+ },+ });+ callback = await waiting;+ } finally {+ lifetime.signal.removeEventListener('abort', abort);+ }+ }+ if (request.kind === 'loopback' && remote) {+ if ('kind' in callback) throw new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');+ providerRejected = 'error' in callback;+ response = { ...callback, kind: 'callback', state: request.state };+ } else if (!('kind' in callback)) throw new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');+ } else if (remote) {+ if (!remote.authorizeDevice || !remote.cancelled || request.kind !== 'device')+ throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ await remote.authorizeDevice(+ {+ kind: 'device',+ authorizeUrl: url,+ state: randomBytes(32).toString('base64url'),+ ...(request.userCode !== undefined ? { userCode: request.userCode } : {}),+ },+ lifetime.signal,+ );+ } else {+ if (request.kind === 'device' && request.userCode !== undefined) {+ if (!deps.copyDeviceCode) throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ clearDeviceCode = deps.copyDeviceCode(request.userCode);+ }+ await deps.openExternal(url);+ if (responseTarget!.isDestroyed()) throw new Error('DEVICE_AUTHORIZATION_UNAVAILABLE');+ }+ assertCurrent();+ opened = true;+ resolve();+ resolveResult(response);+ })().catch(cancel);+ });+ if (input.signal.aborted) cancel();+ } catch {+ cancel();+ }+ return { opened: openedPromise, result, finish, dispose: () => finish(false) };+}diff --git a/apps/desktop/src/main/plugin-oauth/deviceCodeClipboard.ts b/apps/desktop/src/main/plugin-oauth/deviceCodeClipboard.tsnew file mode 100644index 0000000000..1b4e3652f4--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/deviceCodeClipboard.ts@@ -0,0 +1,17 @@+import { parseAuthorizationUserCode } from '@cindy/device-link';++/** Own only this temporary code; never erase newer user clipboard content. */+export function copyPrivateDeviceCode(+ clipboard: { writeText(value: string): void; readText(): string; clear(): void },+ code: string,+): () => void {+ parseAuthorizationUserCode(code);+ clipboard.writeText(code);+ return () => {+ try {+ if (clipboard.readText() === code) clipboard.clear();+ } catch {+ /* clipboard service closed */+ }+ };+}diff --git a/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts b/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.tsnew file mode 100644index 0000000000..ab079ab260--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts@@ -0,0 +1,210 @@+import {+ oauthId,+ PLUGIN_OAUTH_TTL_MS,+ parseDeviceAuthorizationUrl,+ parseAuthorizationUserCode,+} from '@cindy/device-link';+import type {+ PluginOauthDeviceCodeTarget,+ PluginOauthDeviceCodePrompt,+ PluginOauthDeviceCodeView,+ PluginOauthDeviceCodeRequest,+ PluginOauthDeviceCodeClose,+} from '../../shared/pluginOauthDeviceCode.js';++interface Entry {+ view: PluginOauthDeviceCodeView;+ assertCurrent(): void;+ copy(): void;+ reopen(): Promise<void>;+ close: PluginOauthDeviceCodeClose;+}++const isActive = (+ view: PluginOauthDeviceCodeView,+): view is Extract<PluginOauthDeviceCodeView, { phase: 'ready' | 'browser' }> =>+ view.phase === 'ready' || view.phase === 'browser';++const fail = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');+function parseRequest(raw: unknown): PluginOauthDeviceCodeRequest {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw fail();+ const v = raw as Record<string, unknown>;+ if (+ Object.keys(v).sort().join(',') !== 'actionId,deviceId,ghostId,operation,requestId' ||+ !oauthId(v.deviceId) ||+ !oauthId(v.ghostId) ||+ !oauthId(v.requestId) ||+ typeof v.actionId !== 'string' ||+ !v.actionId ||+ v.actionId.length > 256 ||+ [...v.actionId].some((char) => char.charCodeAt(0) < 32) ||+ typeof v.operation !== 'string' ||+ !['read', 'copy', 'reopen'].includes(v.operation)+ )+ throw fail();+ return v as unknown as PluginOauthDeviceCodeRequest;+}++/** Bounded, in-memory display leases belonging to the exact initiating owner and renderer frame. */+export class LocalDeviceCodeSessions {+ private readonly entries = new Map<string, Entry>();+ constructor(private readonly now: () => number = Date.now) {}++ private key(scope: string, target: PluginOauthDeviceCodeTarget): string {+ return JSON.stringify([+ scope,+ target.deviceId,+ target.ghostId,+ target.requestId,+ target.actionId,+ ]);+ }++ present(+ scope: string,+ target: PluginOauthDeviceCodeTarget,+ prompt: PluginOauthDeviceCodePrompt,+ deps: {+ assertCurrent(): void;+ copy(code: string): void;+ openExternal(url: string): Promise<void>;+ clearClipboard(): void;+ },+ ): PluginOauthDeviceCodeClose {+ deps.assertCurrent();+ const authorizeUrl = parseDeviceAuthorizationUrl(prompt.authorizeUrl);+ parseAuthorizationUserCode(prompt.userCode);+ if (+ !Number.isSafeInteger(prompt.expiresAt) ||+ prompt.expiresAt <= this.now() ||+ prompt.expiresAt - this.now() > PLUGIN_OAUTH_TTL_MS+ )+ throw fail();+ return this.register(+ scope,+ target,+ {+ phase: 'ready',+ userCode: prompt.userCode,+ verificationHost: new URL(authorizeUrl).hostname,+ expiresAt: prompt.expiresAt,+ copiedAt: this.now(),+ },+ deps.assertCurrent,+ (code) => deps.copy(code),+ () => deps.openExternal(authorizeUrl),+ deps.clearClipboard,+ );+ }++ /** The controller supplies a closure over an already validated URL; no URL reaches Renderer. */+ presentBrowser(+ scope: string,+ target: PluginOauthDeviceCodeTarget,+ expiresAt: number,+ assertCurrent: () => void,+ reopen: () => Promise<void>,+ ): PluginOauthDeviceCodeClose {+ assertCurrent();+ if (+ !Number.isSafeInteger(expiresAt) ||+ expiresAt <= this.now() ||+ expiresAt - this.now() > PLUGIN_OAUTH_TTL_MS+ )+ throw fail();+ return this.register(+ scope,+ target,+ { phase: 'browser', expiresAt },+ assertCurrent,+ () => {+ throw fail();+ },+ reopen,+ () => {},+ );+ }++ private register(+ scope: string,+ target: PluginOauthDeviceCodeTarget,+ view: Extract<PluginOauthDeviceCodeView, { phase: 'ready' | 'browser' }>,+ assertCurrent: () => void,+ copy: (code: string) => void,+ reopen: () => Promise<void>,+ clearClipboard: () => void,+ ): PluginOauthDeviceCodeClose {+ const key = this.key(scope, target);+ this.entries.get(key)?.close('ended');+ if (this.entries.size >= 64) {+ for (const [oldKey, entry] of this.entries) {+ if (!isActive(entry.view)) this.entries.delete(oldKey);+ }+ if (this.entries.size >= 64) throw fail();+ }+ const close: PluginOauthDeviceCodeClose = (phase) => {+ if (!isActive(entry.view)) return;+ clearTimeout(expiry);+ clearClipboard();+ // Remove all closures that capture authorization material, retaining only a brief status.+ entry.view = { phase };+ entry.copy = () => {+ throw fail();+ };+ entry.reopen = async () => {+ throw fail();+ };+ const forget = setTimeout(() => {+ if (this.entries.get(key) === entry) this.entries.delete(key);+ }, 60_000);+ forget.unref?.();+ };+ const entry: Entry = {+ view,+ assertCurrent,+ reopen,+ close,+ copy: () => {+ if (entry.view.phase !== 'ready') throw fail();+ copy(entry.view.userCode);+ entry.view = { ...entry.view, copiedAt: this.now() };+ },+ };+ this.entries.set(key, entry);+ const expiry = setTimeout(() => close('expired'), view.expiresAt - this.now());+ expiry.unref?.();+ return close;+ }++ async handle(scope: string, raw: unknown): Promise<PluginOauthDeviceCodeView | null> {+ const request = parseRequest(raw);+ const entry = this.entries.get(this.key(scope, request));+ if (!entry) {+ if (request.operation === 'read') return null;+ throw fail();+ }+ try {+ entry.assertCurrent();+ } catch {+ entry.close('ended');+ throw fail();+ }+ if (isActive(entry.view) && this.now() >= entry.view.expiresAt) entry.close('expired');+ if (request.operation !== 'read') {+ if (!isActive(entry.view)) throw fail();+ if (request.operation === 'copy') entry.copy();+ else await entry.reopen();+ try {+ entry.assertCurrent();+ } catch {+ entry.close('ended');+ throw fail();+ }+ if (!isActive(entry.view) || this.now() >= entry.view.expiresAt) {+ entry.close('expired');+ throw fail();+ }+ }+ return { ...entry.view };+ }+}diff --git a/apps/desktop/src/main/plugin-oauth/identityResolver.ts b/apps/desktop/src/main/plugin-oauth/identityResolver.tsnew file mode 100644index 0000000000..77bbc59434--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/identityResolver.ts@@ -0,0 +1,59 @@+import {+ PLUGIN_OAUTH_CHANNEL,+ parsePluginOauthPeerIdentity,+ type InvokeResultPayload,+} from '@cindy/device-link';+import type { OauthIdentityScope } from './identityStore.js';++/** A peer that has not implemented this bridge must never trigger a weaker fallback. */+export class RemotePluginOauthUnsupportedError extends Error {+ constructor() {+ super('REMOTE_PLUGIN_OAUTH_UNSUPPORTED');+ this.name = 'RemotePluginOauthUnsupportedError';+ }+}++/** Descriptor comes only from the authorized account route; it is pinned after signature verification. */+export async function resolveOauthPeerIdentity(+ deps: {+ scope(): OauthIdentityScope | null;+ invoke(deviceId: string, channel: string, args: unknown[]): Promise<InvokeResultPayload>;+ now?: () => number;+ },+ deviceId: string,+ assertCurrent: () => void,+) {+ assertCurrent();+ const scope = deps.scope();+ if (!scope || scope.deviceId === deviceId) throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ const response = await deps.invoke(deviceId, PLUGIN_OAUTH_CHANNEL, [+ { op: 'identity', version: 3 },+ ]);+ assertCurrent();+ const current = deps.scope();+ if (+ !current ||+ current.realm !== scope.realm ||+ current.membershipId !== scope.membershipId ||+ current.deviceId !== scope.deviceId+ )+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ if (!response.ok) {+ if (response.error.code === 'CHANNEL_NOT_ALLOWED')+ throw new RemotePluginOauthUnsupportedError();+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ }+ const value = parsePluginOauthPeerIdentity(response.result);+ const now = deps.now?.() ?? Date.now();+ if (+ value.deviceId !== deviceId ||+ value.membershipId !== scope.membershipId ||+ value.realm !== scope.realm ||+ value.observedAtMs > now + 1000 ||+ now - value.observedAtMs > 60_000 ||+ value.expiresAtMs <= now ||+ value.expiresAtMs > value.observedAtMs + 60_000+ )+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ return value;+}diff --git a/apps/desktop/src/main/plugin-oauth/identityStore.ts b/apps/desktop/src/main/plugin-oauth/identityStore.tsnew file mode 100644index 0000000000..a8e69842ed--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/identityStore.ts@@ -0,0 +1,203 @@+import {+ createHash,+ createPrivateKey,+ createPublicKey,+ generateKeyPairSync,+ randomUUID,+} from 'node:crypto';+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import path from 'node:path';+import { oauthExact, oauthId, oauthPublicKey } from '@cindy/device-link';+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';++export interface OauthIdentityScope {+ realm: 'cn' | 'global';+ membershipId: string;+ deviceId: string;+}+export interface OauthSigningKey {+ publicKey: string;+ privateKey: string;+}+interface StoredIdentity extends OauthSigningKey {+ version: 1;+ scope: OauthIdentityScope;+ peers: Record<string, string>;+}+export interface OauthIdentityStoreDeps {+ filePath(scope: OauthIdentityScope): string;+ available(): boolean;+ encrypt(plaintext: string): Buffer;+ decrypt(ciphertext: Buffer): string;+}+const fail = () => new Error('OAUTH_IDENTITY_UNAVAILABLE');+const MAX_PEERS = 1000;+const MAX_BYTES = 256 * 1024;++export function oauthSecureStorageAvailable(input: {+ platform: NodeJS.Platform;+ available: boolean;+ backend?: string;+}): boolean {+ return (+ input.available &&+ (input.platform !== 'linux' ||+ (!!input.backend && input.backend !== 'basic_text' && input.backend !== 'unknown'))+ );+}++export function oauthIdentityScopeKey(scope: OauthIdentityScope): string {+ if (+ !['cn', 'global'].includes(scope.realm) ||+ !oauthId(scope.membershipId) ||+ !oauthId(scope.deviceId)+ )+ throw fail();+ return createHash('sha256')+ .update(JSON.stringify([scope.realm, scope.membershipId, scope.deviceId]))+ .digest('hex');+}++/** Separate-purpose keys and pins. Called only by an explicit authorization operation, never at startup. */+export class OauthIdentityStore {+ constructor(private readonly deps: OauthIdentityStoreDeps) {}++ async load(scope: OauthIdentityScope, assertCurrent: () => void): Promise<OauthSigningKey> {+ return this.locked(scope, assertCurrent, (data) => ({+ publicKey: data.publicKey,+ privateKey: data.privateKey,+ }));+ }++ /** First use trusts the authenticated account route; changed keys are never silently replaced. */+ async trustPeer(+ scope: OauthIdentityScope,+ deviceId: string,+ publicKey: string,+ assertCurrent: () => void,+ ): Promise<void> {+ if (!oauthId(deviceId) || deviceId === scope.deviceId || !oauthPublicKey(publicKey))+ throw fail();+ if (+ createPublicKey({ key: Buffer.from(publicKey, 'base64url'), type: 'spki', format: 'der' })+ .asymmetricKeyType !== 'ed25519'+ )+ throw fail();+ await this.locked(scope, assertCurrent, (data, save) => {+ const pin = data.peers[deviceId];+ if (pin === publicKey) return;+ if (pin || Object.keys(data.peers).length >= MAX_PEERS) throw fail();+ save({ ...data, peers: { ...data.peers, [deviceId]: publicKey } });+ });+ }++ private async locked<T>(+ scope: OauthIdentityScope,+ assertCurrent: () => void,+ operation: (data: StoredIdentity, save: (data: StoredIdentity) => void) => T,+ ): Promise<T> {+ oauthIdentityScopeKey(scope);+ const file = this.deps.filePath(scope);+ const check = () => {+ assertCurrent();+ if (this.deps.filePath(scope) !== file || !this.deps.available()) throw fail();+ };+ check();+ await fsp.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });+ return withCrossProcessLock(+ `${file}.lock`,+ { label: 'plugin-oauth-identity', waitMs: 12_000 },+ async (status) => {+ check();+ if (!status.held) throw fail();+ const save = (data: StoredIdentity) => {+ check();+ const temp = `${file}.${randomUUID()}.tmp`;+ try {+ const encrypted = this.deps.encrypt(JSON.stringify(data));+ check();+ const fd = fs.openSync(temp, 'wx', 0o600);+ try {+ fs.writeFileSync(fd, encrypted);+ fs.fsyncSync(fd);+ } finally {+ fs.closeSync(fd);+ }+ check();+ fs.renameSync(temp, file);+ } finally {+ fs.rmSync(temp, { force: true });+ }+ };+ let data: StoredIdentity;+ let fd: number | undefined;+ try {+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw fail();+ }+ if (fd === undefined) {+ const pair = generateKeyPairSync('ed25519');+ data = {+ version: 1,+ scope: { ...scope },+ peers: {},+ publicKey: pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64url'),+ privateKey: pair.privateKey+ .export({ type: 'pkcs8', format: 'der' })+ .toString('base64url'),+ };+ save(data);+ } else {+ try {+ const stat = fs.fstatSync(fd);+ if (!stat.isFile() || stat.size > MAX_BYTES || stat.size === 0) throw fail();+ data = parseStoredIdentity(JSON.parse(this.deps.decrypt(fs.readFileSync(fd))), scope);+ } catch {+ throw fail();+ } finally {+ fs.closeSync(fd);+ }+ }+ check();+ const result = operation(data, save);+ check();+ return result;+ },+ );+ }+}++function parseStoredIdentity(raw: unknown, scope: OauthIdentityScope): StoredIdentity {+ const value = oauthExact(raw, ['version', 'scope', 'publicKey', 'privateKey', 'peers']);+ const storedScope = oauthExact(value.scope, ['realm', 'membershipId', 'deviceId']);+ if (+ value.version !== 1 ||+ storedScope.realm !== scope.realm ||+ storedScope.membershipId !== scope.membershipId ||+ storedScope.deviceId !== scope.deviceId ||+ !oauthPublicKey(value.publicKey) ||+ typeof value.privateKey !== 'string' ||+ value.privateKey.length > 256 ||+ !value.peers ||+ typeof value.peers !== 'object' ||+ Array.isArray(value.peers)+ )+ throw fail();+ const key = createPrivateKey({+ key: Buffer.from(value.privateKey, 'base64url'),+ type: 'pkcs8',+ format: 'der',+ });+ if (+ key.asymmetricKeyType !== 'ed25519' ||+ createPublicKey(key).export({ type: 'spki', format: 'der' }).toString('base64url') !==+ value.publicKey+ )+ throw fail();+ const peers = Object.entries(value.peers);+ if (peers.length > MAX_PEERS || peers.some(([id, pin]) => !oauthId(id) || !oauthPublicKey(pin)))+ throw fail();+ return value as unknown as StoredIdentity;+}diff --git a/apps/desktop/src/main/plugin-oauth/localIpc.ts b/apps/desktop/src/main/plugin-oauth/localIpc.tsnew file mode 100644index 0000000000..2d739e021a--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/localIpc.ts@@ -0,0 +1,166 @@+import {+ PLUGIN_OAUTH_CHANNEL,+ oauthId,+ parsePluginOauthAction,+ parsePluginSecretInput,+ parsePluginSecretPresentation,+ parsePluginConnectionInput,+ parsePluginConnectionPresentation,+ type InvokeResultPayload,+ type PluginOauthPeerIdentity,+} from '@cindy/device-link';+import { assistPluginOauth } from './controller.js';+import { capturePluginOauthPeer } from './runtime.js';+import { authenticateOauthController } from './authentication.js';+import type {+ LocalPluginSecretRequest,+ LocalPluginConnectionRequest,+} from '../../shared/pluginOauth.js';+import type {+ PluginOauthDeviceCodePrompt,+ PluginOauthDeviceCodeClose,+ PluginOauthDeviceCodeTarget,+} from '../../shared/pluginOauthDeviceCode.js';++const active = new Set<string>();+export interface LocalOauthDeps {+ owner(): string | null;+ assertTarget(deviceId: string): void;+ invoke(deviceId: string, channel: string, args: unknown[]): Promise<InvokeResultPayload>;+ openExternal(url: string): Promise<void>;+ copyDeviceCode?(code: string): () => void;+ presentBrowserAuthorization?(+ target: PluginOauthDeviceCodeTarget,+ expiresAt: number,+ assertCurrent: () => void,+ reopen: () => Promise<void>,+ ): PluginOauthDeviceCodeClose;+ presentDeviceCode?(+ target: PluginOauthDeviceCodeTarget,+ prompt: PluginOauthDeviceCodePrompt,+ assertCurrent: () => void,+ clearClipboard: () => void,+ ): PluginOauthDeviceCodeClose;+ localDeviceId(): string;+ trustIdentity(target: PluginOauthPeerIdentity, assertCurrent: () => void): Promise<void>;+ identity(deviceId: string, assertCurrent: () => void): Promise<PluginOauthPeerIdentity>;+}+/** Renderer supplies only an opaque card action and its target. No caller-supplied URL/key. */+export async function handleAssistPluginOauth(+ deps: LocalOauthDeps,+ raw: unknown,+): Promise<{ accepted: true }> {+ return handleAuthorization(deps, raw);+}++async function handleAuthorization(+ deps: LocalOauthDeps,+ raw: unknown,+ secret?: Pick<LocalPluginSecretRequest, 'value' | 'presentation'>,+ connection?: Pick<LocalPluginConnectionRequest, 'value' | 'presentation'>,+): Promise<{ accepted: true }> {+ const fail = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw fail();+ const { deviceId, ghostId, ...rest } = raw as Record<string, unknown>;+ const action = parsePluginOauthAction(rest);+ const owner = deps.owner();+ if (!oauthId(deviceId) || !oauthId(ghostId) || !action || !owner) throw fail();+ const slot = `${deviceId}:${action.requestId}`;+ if (active.has(slot) || active.size >= 8) throw fail();+ const peerCurrent = capturePluginOauthPeer(deviceId);+ const assertCurrent = () => {+ peerCurrent();+ if (owner !== deps.owner()) throw fail();+ deps.assertTarget(deviceId);+ };+ assertCurrent();+ active.add(slot);+ try {+ const target = await deps.identity(deviceId, assertCurrent);+ assertCurrent();+ if (target.deviceId !== deviceId) throw fail();+ const exchange = await authenticateOauthController({+ target,+ trustIdentity: deps.trustIdentity,+ peer: deps.localDeviceId(),+ action,+ ghostId,+ assertCurrent,+ invoke: async (raw) => {+ // A vanished window may send an encrypted cancellation, but never under a new owner/peer generation.+ peerCurrent();+ if (owner !== deps.owner()) throw fail();+ const result = await deps.invoke(deviceId, PLUGIN_OAUTH_CHANNEL, [raw]);+ peerCurrent();+ if (owner !== deps.owner() || !result.ok) throw fail();+ return result.result;+ },+ });+ return await assistPluginOauth(+ {+ ...(secret ? { secretValue: secret.value, secretPresentation: secret.presentation } : {}),+ ...(connection+ ? { connectionValue: connection.value, connectionPresentation: connection.presentation }+ : {}),+ assertCurrent,+ openExternal: deps.openExternal,+ copyDeviceCode: deps.copyDeviceCode,+ presentBrowserAuthorization: (expiresAt, reopen) =>+ deps.presentBrowserAuthorization?.(+ { deviceId, ghostId, requestId: action.requestId, actionId: action.actionId },+ expiresAt,+ assertCurrent,+ reopen,+ ) ?? (() => {}),+ presentDeviceCode: (prompt, clearClipboard) =>+ deps.presentDeviceCode?.(+ { deviceId, ghostId, requestId: action.requestId, actionId: action.actionId },+ prompt,+ assertCurrent,+ clearClipboard,+ ) ?? (() => {}),+ invoke: async (request) => {+ // A closed/navigated window must still cancel its existing transaction.+ // Never send cancellation under a new owner or re-established peer.+ if (request.op === 'cancel') {+ peerCurrent();+ if (owner !== deps.owner()) throw fail();+ } else assertCurrent();+ const result = await exchange(request);+ if (request.op !== 'cancel') assertCurrent();+ return result;+ },+ },+ action,+ );+ } finally {+ active.delete(slot);+ }+}++/** One-shot local input IPC. The value cannot name a storage path, key or another action. */+export async function handleSubmitPluginSecret(+ deps: LocalOauthDeps,+ raw: unknown,+): Promise<{ accepted: true }> {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))+ throw new Error('PLUGIN_SECRET_UNAVAILABLE');+ const { value, presentation, ...target } = raw as Record<string, unknown>;+ return handleAuthorization(deps, target, {+ value: parsePluginSecretInput(value),+ presentation: parsePluginSecretPresentation(presentation),+ });+}++export async function handleSubmitPluginConnection(+ deps: LocalOauthDeps,+ raw: unknown,+): Promise<{ accepted: true }> {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))+ throw new Error('PLUGIN_CONNECTION_UNAVAILABLE');+ const { value, presentation, ...target } = raw as Record<string, unknown>;+ return handleAuthorization(deps, target, undefined, {+ value: parsePluginConnectionInput(value),+ presentation: parsePluginConnectionPresentation(presentation),+ });+}diff --git a/apps/desktop/src/main/plugin-oauth/loopbackListener.ts b/apps/desktop/src/main/plugin-oauth/loopbackListener.tsnew file mode 100644index 0000000000..5e6b1d7646--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/loopbackListener.ts@@ -0,0 +1,179 @@+import http from 'node:http';+import {+ parsePluginOauthCallback,+ type PluginOauthOffer,+ type PluginOauthCallback,+} from '@cindy/device-link';+import { ghostNetworkHostMatches } from '../../shared/ghost.js';+import {+ getGhostOAuthResultCopy,+ getRemoteOAuthCallbackCopy,+ OAUTH_RESULT_HTML_LANG,+ pickOAuthResultPageLang,+ renderOAuthResultPage,+} from '../oauthResultPage.js';+const fail = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');++/** Fixed listener, no arbitrary URL fetch/port tunnelling or port-owner termination. */+export async function listenForOauthCallback(+ offer: PluginOauthOffer,+ deliver: (value: PluginOauthCallback) => Promise<void>,+ assertCurrent: () => void,+ expectedState: string = offer.state,+): Promise<{ close(): void }> {+ const endpoint = new URL(offer.callbackUrl);+ let consumed = false;+ let closed = false;+ let ready = false;+ const servers: http.Server[] = [];+ // localhost can resolve to either family. Both listeners share one transaction;+ // literal addresses continue to bind only the requested loopback interface.+ const hosts =+ endpoint.hostname === 'localhost'+ ? ['127.0.0.1', '::1']+ : [endpoint.hostname === '[::1]' ? '::1' : '127.0.0.1'];+ const handle: http.RequestListener = (req, res) => {+ res.setHeader('Cache-Control', 'no-store');+ res.setHeader('Referrer-Policy', 'no-referrer');+ res.setHeader('X-Content-Type-Options', 'nosniff');+ const reply = (status: number) => {+ if (res.destroyed || res.writableEnded) return;+ res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });+ // No provider text, URL or code in the browser result.+ const lang = pickOAuthResultPageLang(req.headers['accept-language']);+ const copy = getRemoteOAuthCallbackCopy(lang);+ const errors = getGhostOAuthResultCopy(lang);+ res.end(+ renderOAuthResultPage({+ htmlLang: OAUTH_RESULT_HTML_LANG[lang],+ variant: status === 200 ? 'warning' : 'error',+ title: status === 200 ? copy.title : errors.errorTitle,+ body:+ status === 200+ ? copy.body+ : errors.errors['invalid-callback'].replace('{brand}', 'Cindy'),+ pageKind: 'ghost-oauth',+ }),+ );+ };+ try {+ assertCurrent();+ if (+ !ready ||+ closed ||+ req.headers.host !== endpoint.host ||+ !req.url?.startsWith('/') ||+ req.url.startsWith('//') ||+ req.url.length > 12_288+ ) {+ reply(400);+ return;+ }+ const url = new URL(req.url, endpoint.origin);+ if (url.pathname !== endpoint.pathname) {+ reply(404);+ return;+ }+ const origin = req.headers.origin;+ if (typeof origin === 'string') {+ const parsed = new URL(origin);+ if (+ parsed.origin !== origin ||+ parsed.protocol !== 'https:' ||+ (!offer.corsOrigins.includes(origin) &&+ !offer.corsHosts.some((h) => ghostNetworkHostMatches(h, parsed.hostname)))+ ) {+ reply(403);+ return;+ }+ res.setHeader('Access-Control-Allow-Origin', origin);+ res.setHeader('Vary', 'Origin');+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');+ res.setHeader('Access-Control-Allow-Private-Network', 'true');+ }+ if (req.method === 'OPTIONS') {+ res.writeHead(204);+ res.end();+ return;+ }+ if (req.method !== 'GET') {+ reply(405);+ return;+ }+ if (consumed) {+ reply(409);+ return;+ }+ if (+ url.searchParams.getAll('state').length !== 1 ||+ url.searchParams.get('state') !== expectedState ||+ url.searchParams.getAll('code').length + url.searchParams.getAll('error').length !== 1+ ) {+ reply(400);+ return;+ }+ const callback = parsePluginOauthCallback({+ state: offer.state,+ ...(url.searchParams.has('error')+ ? { error: url.searchParams.get('error') }+ : { code: url.searchParams.get('code') }),+ });+ if (!callback) {+ reply(400);+ return;+ }+ consumed = true;+ void deliver(callback).then(+ () => reply(200),+ () => reply(502),+ );+ } catch {+ reply(410);+ }+ };+ const close = () => {+ if (closed) return;+ closed = true;+ for (const server of servers) {+ server.close();+ server.closeAllConnections();+ }+ };+ try {+ for (const host of hosts) {+ if (closed) throw fail();+ const server = http.createServer(+ { maxHeaderSize: 16_384, requestTimeout: 10_000, headersTimeout: 10_000 },+ handle,+ );+ server.maxConnections = 8;+ servers.push(server);+ try {+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen({ port: Number(endpoint.port), host, ipv6Only: host === '::1' }, () => {+ server.removeListener('error', reject);+ server.on('error', close);+ resolve();+ });+ });+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ // An OS may disable a family. An occupied/forbidden port is not that case:+ // fail the entire setup so another process cannot intercept localhost.+ if (+ endpoint.hostname !== 'localhost' ||+ (code !== 'EAFNOSUPPORT' && code !== 'EADDRNOTAVAIL')+ )+ throw error;+ }+ }+ if (closed || !servers.some((server) => server.listening)) throw fail();+ assertCurrent();+ ready = true;+ return { close };+ } catch {+ close();+ throw fail();+ }+}diff --git a/apps/desktop/src/main/plugin-oauth/runtime.ts b/apps/desktop/src/main/plugin-oauth/runtime.tsnew file mode 100644index 0000000000..6ee313efc9--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/runtime.ts@@ -0,0 +1,118 @@+import { OauthTransactions, type OauthTransactionDeps } from './transactions.js';+import { onOauthCardClosed } from './context.js';+import { AuthenticatedOauthHost, OauthHostIdentity } from './authentication.js';+import {+ oauthIdentityScopeKey,+ type OauthIdentityScope,+ type OauthSigningKey,+} from './identityStore.js';++export type OauthKeyLoader = (+ scope: OauthIdentityScope,+ assertCurrent: () => void,+) => Promise<OauthSigningKey>;+let host: OauthTransactions | undefined;+let authenticated: AuthenticatedOauthHost | undefined;+let identity: (OauthIdentityScope & { key: OauthHostIdentity; owner: string }) | null = null;+let identityFlight: { scope: string; promise: ReturnType<typeof currentIdentity> } | null = null;+let identityTarget: () => OauthIdentityScope | null = () => null;+let loadKey: OauthKeyLoader | undefined;+let currentOwner: (() => string | null) | undefined;+let unsubscribe: (() => void) | undefined;+let epoch = 0;+const peers = new Map<string, number>();++async function currentIdentity(): Promise<+ (OauthIdentityScope & { key: OauthHostIdentity }) | null+> {+ const owner = currentOwner?.();+ const target = owner ? identityTarget() : null;+ const loader = loadKey;+ if (!owner || !target || !loader) return null;+ const scope = JSON.stringify([owner, oauthIdentityScopeKey(target)]);+ if (+ identity &&+ identity.owner === owner &&+ oauthIdentityScopeKey(identity) === oauthIdentityScopeKey(target)+ )+ return identity;+ if (identityFlight?.scope === scope) return identityFlight.promise;+ const startEpoch = epoch;+ const assertCurrent = () => {+ const now = identityTarget();+ if (+ epoch !== startEpoch ||+ loader !== loadKey ||+ owner !== currentOwner?.() ||+ !now ||+ oauthIdentityScopeKey(now) !== oauthIdentityScopeKey(target)+ )+ throw new Error('OAUTH_IDENTITY_UNAVAILABLE');+ };+ const promise = (async () => {+ const stored = await loader(target, assertCurrent);+ assertCurrent();+ identity = { ...target, key: new OauthHostIdentity(stored), owner };+ return identity;+ })();+ identityFlight = { scope, promise };+ try {+ return await promise;+ } finally {+ if (identityFlight?.promise === promise) identityFlight = null;+ }+}++export function initializePluginOauthHost(+ deps: OauthTransactionDeps,+ target: () => OauthIdentityScope | null,+ keyLoader: OauthKeyLoader,+): void {+ invalidatePluginOauth();+ unsubscribe?.();+ host = new OauthTransactions(deps);+ identity = null;+ identityFlight = null;+ identityTarget = target;+ loadKey = keyLoader;+ currentOwner = deps.owner;+ const transactions = host;+ authenticated = new AuthenticatedOauthHost({+ ...deps,+ identity: currentIdentity,+ request: (peer, raw) => transactions.request(peer, raw),+ });+ unsubscribe = onOauthCardClosed((id) => host?.cancelRequest(id));+}++/** Capability projection must not access the keychain or generate a key at startup. */+export function supportsRemotePluginOauth(): boolean {+ return !!loadKey && !!currentOwner?.() && !!identityTarget();+}+export async function publishedPluginOauthIdentity() {+ return (await currentIdentity())?.key.descriptor;+}+export function requestPluginOauth(peer: string, raw: unknown): Promise<unknown> {+ if (!authenticated) return Promise.reject(new Error('OAUTH_BRIDGE_UNAVAILABLE'));+ return authenticated.request(peer, raw);+}+/** A peer failure cancels only that peer. Shared relay/account teardown cancels all transactions. */+export function invalidatePluginOauth(peer?: string): void {+ host?.cancelPeer(peer);+ authenticated?.invalidate(peer);+ if (peer) peers.set(peer, (peers.get(peer) ?? 0) + 1);+ else {+ epoch++;+ peers.clear();+ identity = null;+ identityFlight = null;+ }+}+export function capturePluginOauthPeer(peer: string): () => void {+ const startEpoch = epoch;+ const peerEpoch = peers.get(peer) ?? 0;+ return () => {+ if (startEpoch !== epoch || peerEpoch !== (peers.get(peer) ?? 0))+ throw new Error('OAUTH_BRIDGE_UNAVAILABLE');+ };+}diff --git a/apps/desktop/src/main/plugin-oauth/targetPolicy.ts b/apps/desktop/src/main/plugin-oauth/targetPolicy.tsnew file mode 100644index 0000000000..a361ffd7d3--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/targetPolicy.ts@@ -0,0 +1,61 @@+import {+ parseDeviceAuthorizationUrl,+ parsePluginAuthorizationRequest,+ type PluginAuthorizationRequest,+} from '@cindy/device-link';+import { ghostNetworkHostMatches, type GhostManifest } from '../../shared/ghost.js';+import { builtinAuthorizationTargets } from './builtinAuthorizationTargets.js';++/** Narrow only browser authorization delegation; ordinary in-flight plugin network capabilities are unchanged. */+export function bindDeviceAuthorizationTarget(+ manifest: GhostManifest,+ raw: string,+): (current: GhostManifest) => void {+ const url = new URL(parseDeviceAuthorizationUrl(raw));+ const snapshot = JSON.stringify({+ id: manifest.id,+ version: manifest.version,+ network: manifest.network ?? null,+ });+ const allowed = (m: GhostManifest) => {+ if (url.port) return false; // HTTPS default only; no alternate local/private service on a permitted hostname.+ const builtin = Object.hasOwn(builtinAuthorizationTargets, m.id)+ ? builtinAuthorizationTargets[m.id]+ : undefined;+ if (builtin) return builtin(url);+ const declaration = m.network;+ const oauthOrigins = (declaration?.secrets ?? []).flatMap((s) =>+ s.oauth ? [new URL(s.oauth.authorizeUrl).origin] : [],+ );+ const hosts = declaration?.hosts ?? [];+ // Undeclared targets fail closed. An extra confirmation is not a substitute for a trusted target.+ return (+ oauthOrigins.includes(url.origin) ||+ hosts.some((h) => ghostNetworkHostMatches(h, url.hostname))+ );+ };+ if (!allowed(manifest)) throw new Error('DEVICE_AUTHORIZATION_TARGET_REJECTED');+ return (current) => {+ if (+ snapshot !==+ JSON.stringify({+ id: current.id,+ version: current.version,+ network: current.network ?? null,+ }) ||+ !allowed(current)+ )+ throw new Error('DEVICE_AUTHORIZATION_TARGET_REJECTED');+ };+}++/** Typed mode selection does not relax the current provider/manifest target binding. */+export function bindPluginAuthorizationTarget(+ manifest: GhostManifest,+ raw: PluginAuthorizationRequest,+): (current: GhostManifest) => void {+ const request = parsePluginAuthorizationRequest(raw);+ if (request.kind === 'loopback' && Object.hasOwn(builtinAuthorizationTargets, manifest.id))+ throw new Error('PLUGIN_AUTHORIZATION_TARGET_REJECTED');+ return bindDeviceAuthorizationTarget(manifest, request.url);+}diff --git a/apps/desktop/src/main/plugin-oauth/transactions.ts b/apps/desktop/src/main/plugin-oauth/transactions.tsnew file mode 100644index 0000000000..45e7fd1645--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/transactions.ts@@ -0,0 +1,337 @@+import { randomUUID } from 'node:crypto';+import {+ PLUGIN_OAUTH_TTL_MS,+ parsePluginOauthCallback,+ parsePluginDeviceOpened,+ parsePluginDeviceOffer,+ parsePluginAuthorizationOffer,+ parsePluginSecretOffer,+ parsePluginSecretValue,+ type PluginSecretValue,+ parsePluginConnectionOffer,+ parsePluginConnectionValue,+ type PluginConnectionValue,+ type PluginDeviceOpened,+ type PluginOauthCallback,+ parsePluginOauthRequest,+ type PluginOauthAction,+ type PluginOauthPhase,+ type PluginOauthRequest,+} from '@cindy/device-link';+import { OauthBox } from './box.js';+import { withRemoteOauthContext, type RemoteOauthContext } from './context.js';++export interface OauthCardBinding {+ ghostId: string;+ /** Must become false on card cancellation, session close/rewind or replacement. */+ current(): boolean;+}+export interface OauthTransactionDeps {+ owner(): string | null;+ available(peer: string): boolean;+ bind(action: PluginOauthAction): Promise<OauthCardBinding | null>;+ run(action: PluginOauthAction): Promise<boolean> | boolean;+ now?: () => number;+}+type TransactionReply =+ PluginOauthCallback | PluginDeviceOpened | PluginSecretValue | PluginConnectionValue;+type ReplyMode = 'loopback' | 'device' | 'secret' | 'connection';+interface OfferExchange<T> {+ offer: { state: string };+ mode: ReplyMode;+ parse(value: unknown): T | null;+ signal?: AbortSignal;+ expiresAt?: number;+ maxSecretLength?: number;+}+interface Transaction {+ id: string;+ peer: string;+ owner: string;+ action: PluginOauthAction;+ binding: OauthCardBinding;+ expiresAt: number;+ phase: PluginOauthPhase;+ key?: OauthBox;+ publicKey: string;+ offer?: string;+ state?: string;+ mode?: ReplyMode;+ maxSecretLength?: number;+ lifetime: AbortController;+ resolve?: (value: TransactionReply) => void;+ reject?: (error: Error) => void;+ callbackBox?: string;+ cleanup?: () => void;+}+const terminal = (phase: PluginOauthPhase) => ['succeeded', 'failed', 'cancelled'].includes(phase);+const failure = () => new Error('OAUTH_BRIDGE_UNAVAILABLE');++/** Process-local, peer/owner/card-bound transactions. Restart requires a fresh human action. */+export class OauthTransactions {+ private readonly entries = new Map<string, Transaction>();+ private readonly starts = new Set<string>();+ private readonly peerEpochs = new Map<string, number>();+ private epoch = 0;+ constructor(private readonly deps: OauthTransactionDeps) {}+ private now() {+ return this.deps.now?.() ?? Date.now();+ }+ private current(t: Transaction): boolean {+ return (+ t.owner === this.deps.owner() &&+ this.deps.available(t.peer) &&+ this.now() < t.expiresAt &&+ t.binding.current()+ );+ }+ private assertCurrent(t: Transaction) {+ if (terminal(t.phase) || !this.current(t)) {+ if (!terminal(t.phase)) this.finish(t, 'cancelled');+ throw failure();+ }+ }+ private finish(t: Transaction, phase: PluginOauthPhase) {+ if (terminal(t.phase)) return;+ t.phase = phase;+ if (phase !== 'succeeded') t.lifetime.abort();+ t.reject?.(failure());+ t.cleanup?.();+ delete t.resolve;+ delete t.reject;+ delete t.cleanup;+ delete t.offer;+ delete t.state;+ delete t.key;+ delete t.callbackBox;+ }+ /** All offer modes share the same lifetime and single-use exchange. */+ private waitForReply<T>(t: Transaction, exchange: OfferExchange<T>): Promise<T> {+ this.assertCurrent(t);+ const { offer, signal } = exchange;+ if (t.phase !== 'starting' || signal?.aborted || !t.key) throw failure();+ if (exchange.expiresAt !== undefined) {+ if (exchange.expiresAt <= this.now()) throw failure();+ t.expiresAt = Math.min(t.expiresAt, exchange.expiresAt);+ }+ t.mode = exchange.mode;+ t.maxSecretLength = exchange.maxSecretLength;+ t.state = offer.state;+ t.offer = t.key.seal(t.publicKey, t.id, 'offer', offer);+ t.phase = 'authorizing';+ return new Promise<T>((resolve, reject) => {+ t.resolve = (value) => {+ try {+ const reply = exchange.parse(value);+ if (reply === null) throw failure();+ resolve(reply);+ } catch {+ reject(failure());+ }+ };+ t.reject = reject;+ if (signal) {+ const abort = () => this.finish(t, 'cancelled');+ signal.addEventListener('abort', abort, { once: true });+ const cleanup = t.cleanup;+ t.cleanup = () => {+ cleanup?.();+ signal.removeEventListener('abort', abort);+ };+ }+ });+ }+ private createContext(+ t: Transaction,+ request: Extract<PluginOauthRequest, { op: 'start' }>,+ ): RemoteOauthContext {+ return {+ scope: t.id,+ cancelled: t.lifetime.signal,+ assertCurrent: () => this.assertCurrent(t),+ authorize: (offer, signal) =>+ this.waitForReply(t, {+ offer,+ signal,+ mode: 'loopback',+ parse: parsePluginOauthCallback,+ }),+ authorizeDevice: (rawOffer, signal) => {+ const offer = parsePluginDeviceOffer(rawOffer);+ if (offer.userCode !== undefined && request.deviceUserCode !== true) throw failure();+ return this.waitForReply(t, {+ offer,+ signal,+ mode: 'device',+ parse: parsePluginDeviceOpened,+ }).then(() => undefined);+ },+ authorizePlugin: (rawOffer, signal) => {+ if (request.authorizationV1 !== true) throw failure();+ const offer = parsePluginAuthorizationOffer(rawOffer);+ if (+ offer.request.kind === 'device' &&+ offer.request.userCode !== undefined &&+ request.deviceUserCode !== true+ )+ throw failure();+ const mode = offer.request.kind === 'loopback' ? 'loopback' : 'device';+ return this.waitForReply<PluginOauthCallback | PluginDeviceOpened>(t, {+ offer,+ signal,+ mode,+ expiresAt: offer.request.kind === 'loopback' ? undefined : offer.request.expiresAt,+ parse: mode === 'loopback' ? parsePluginOauthCallback : parsePluginDeviceOpened,+ });+ },+ submitSecret: (rawOffer) => {+ if (request.secretSubmission !== true) throw failure();+ const offer = parsePluginSecretOffer(rawOffer);+ return this.waitForReply(t, {+ offer,+ mode: 'secret',+ parse: parsePluginSecretValue,+ maxSecretLength: offer.presentation.maxLength,+ }).then((reply) => reply.value);+ },+ submitConnection: (rawOffer) => {+ if (request.connectionSubmission !== true) throw failure();+ const offer = parsePluginConnectionOffer(rawOffer);+ return this.waitForReply(t, {+ offer,+ mode: 'connection',+ parse: parsePluginConnectionValue,+ }).then((reply) => reply.value);+ },+ finish: (ok) => {+ if (!terminal(t.phase)) this.finish(t, ok && this.current(t) ? 'succeeded' : 'failed');+ },+ };+ }+ /** Called by link/owner teardown; one peer failing does not cancel other peers. */+ cancelPeer(peer?: string) {+ if (peer) this.peerEpochs.set(peer, (this.peerEpochs.get(peer) ?? 0) + 1);+ else {+ this.epoch++;+ this.peerEpochs.clear();+ }+ for (const t of this.entries.values())+ if (!peer || t.peer === peer) this.finish(t, 'cancelled');+ }+ cancelRequest(requestId: string) {+ for (const t of this.entries.values())+ if (t.action.requestId === requestId) this.finish(t, 'cancelled');+ }+ async request(peer: string, raw: unknown): Promise<unknown> {+ const request = parsePluginOauthRequest(raw);+ if (!request || !this.deps.owner() || !this.deps.available(peer)) throw failure();+ for (const t of this.entries.values()) {+ if (!terminal(t.phase) && !this.current(t)) this.finish(t, 'cancelled');+ if (this.now() >= t.expiresAt) this.entries.delete(t.id);+ }+ if (request.op === 'capabilities')+ return {+ version: 1,+ callback: 'desktop-loopback',+ encrypted: true,+ deviceAuthorization: true,+ deviceUserCode: true,+ authorizationV1: true,+ secretSubmission: true,+ connectionSubmission: true,+ };+ if (request.op === 'start') {+ const owner = this.deps.owner()!;+ const epoch = this.epoch;+ const peerEpoch = this.peerEpochs.get(peer) ?? 0;+ if (+ this.starts.has(request.requestId) ||+ this.starts.size >= 16 ||+ this.entries.size >= 64 ||+ [...this.entries.values()].some(+ (t) => !terminal(t.phase) && t.action.requestId === request.requestId,+ )+ )+ throw failure();+ this.starts.add(request.requestId);+ try {+ const binding = await this.deps.bind(request);+ if (+ !binding ||+ !binding.current() ||+ owner !== this.deps.owner() ||+ !this.deps.available(peer) ||+ epoch !== this.epoch ||+ peerEpoch !== (this.peerEpochs.get(peer) ?? 0)+ )+ throw failure();+ const key = new OauthBox();+ const id = randomUUID();+ // Validate the offered public key before starting any OAuth side effects.+ key.seal(request.publicKey, id, 'offer', {});+ const t: Transaction = {+ id,+ peer,+ owner,+ action: request,+ binding,+ key,+ publicKey: request.publicKey,+ expiresAt: this.now() + PLUGIN_OAUTH_TTL_MS,+ phase: 'starting',+ lifetime: new AbortController(),+ };+ this.entries.set(id, t);+ const timer = setTimeout(() => this.finish(t, 'cancelled'), PLUGIN_OAUTH_TTL_MS);+ timer.unref?.();+ t.cleanup = () => clearTimeout(timer);+ const context = this.createContext(t, request);+ try {+ const accepted = await withRemoteOauthContext(context, () => this.deps.run(request));+ if (!accepted) throw failure();+ } catch {+ this.finish(t, 'failed');+ throw failure();+ }+ return { id, publicKey: key.publicKey, expiresAt: t.expiresAt };+ } finally {+ this.starts.delete(request.requestId);+ }+ }+ const t = this.entries.get(request.id);+ if (!t || t.peer !== peer || t.owner !== this.deps.owner()) throw failure();+ if (request.op === 'cancel') {+ this.finish(t, 'cancelled');+ return { accepted: true };+ }+ if (request.op === 'status') return { phase: t.phase, ...(t.offer ? { offer: t.offer } : {}) };+ this.assertCurrent(t);+ // An identical retry can acknowledge an in-flight exchange, never exchange again.+ if (t.phase === 'exchanging' && request.box === t.callbackBox) return { accepted: true };+ if (t.phase !== 'authorizing' || !t.key) throw failure();+ const rawCallback = t.key.open(t.publicKey, t.id, 'callback', request.box);+ const callback =+ t.mode === 'connection'+ ? parsePluginConnectionValue(rawCallback)+ : t.mode === 'secret'+ ? parsePluginSecretValue(rawCallback)+ : t.mode === 'device'+ ? parsePluginDeviceOpened(rawCallback)+ : parsePluginOauthCallback(rawCallback);+ if (!callback || callback.state !== t.state) throw failure();+ if (+ 'kind' in callback &&+ callback.kind === 'secret-value' &&+ callback.value.length > (t.maxSecretLength ?? 0)+ )+ throw failure();+ t.phase = 'exchanging';+ t.callbackBox = request.box;+ delete t.offer;+ delete t.state;+ t.resolve?.(callback);+ delete t.resolve;+ delete t.reject;+ return { accepted: true };+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 4f47a45502..f1972d0b84 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2,6 +2,7 @@ import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/worimport { FAVORITE_HOST_READY, FAVORITE_HOST_REQUEST, FAVORITE_HOST_REPLY, FAVORITE_HOST_CHANGED, type ModelFavoritesHostApi } from '../shared/modelFavoritesSync';import { invokeOpenPath } from './openPath';import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';+import type { LocalPluginOauthRequest, LocalPluginSecretRequest } from '../shared/pluginOauth';import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';import type { RoutineInput } from '@cindy/maker-scheduler';import {@@ -6554,6 +6555,19 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ accepted: boolean }> =>ipcRenderer.invoke('maker:resolve-interaction', requestId, decision),+ /** Opens a remote Host's registered OAuth transaction. Returns no authorization material. */+ assistPluginOauth: (request: LocalPluginOauthRequest): Promise<{ accepted: boolean }> =>+ ipcRenderer.invoke('plugin-oauth:assist', request),+ /** Dedicated signed input transport; never uses the ordinary remote invoke API. */+ submitRemotePluginSecret: (request: LocalPluginSecretRequest): Promise<{ accepted: boolean }> =>+ ipcRenderer.invoke('plugin-oauth:submit-secret', request),+ submitRemotePluginConnection: (request: import('../shared/pluginOauth').LocalPluginConnectionRequest): Promise<{ accepted: boolean }> =>+ ipcRenderer.invoke('plugin-oauth:submit-connection', request),++ /** Ephemeral user-entered device code for this frame's active card; no callback code or token. */+ pluginOauthDeviceCode: (request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest): Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null> =>+ ipcRenderer.invoke('plugin-oauth:device-code', request),+/** Local-only Secret handoff; Main verifies this is Cindy's trusted top-level frame. */submitPluginSetupInline: (request: {requestId: string;diff --git a/apps/desktop/src/renderer/__tests__/PluginConnectionForm.test.tsx b/apps/desktop/src/renderer/__tests__/PluginConnectionForm.test.tsxnew file mode 100644index 0000000000..4ef2794572--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/PluginConnectionForm.test.tsx@@ -0,0 +1,170 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import '@/i18n';+import i18n from '@/i18n';+import { PluginSetupPrompt } from '@/components/new-chat/PluginSetupPrompt';+import type { PendingPluginSetup } from '@/lib/makerChatStore';++const pending: PendingPluginSetup = {+ requestId: 'connection-card',+ revision: 1,+ remoteConnection: true,+ ghost: { id: 'demo', name: 'Demo' },+ steps: [+ {+ id: 'connection',+ groupId: 'service',+ groupMode: 'any_of',+ title: 'Connect service',+ description: 'Use your service account',+ phase: 'pending',+ action: { kind: 'manage_connection', id: 'manage_connection:connection:service' },+ },+ ],+};+beforeEach(async () => {+ await i18n.changeLanguage('en');+});+afterEach(cleanup);+function form(p = pending, device = 'cloud-a') {+ const onCommand = vi.fn();+ const element = (next = p, target = device) => (+ <PluginSetupPrompt+ pending={next}+ remote+ remoteDeviceId={target}+ viewerState="expanded"+ commandInFlight={null}+ onCommand={onCommand}+ onViewerStateChange={vi.fn()}+ />+ );+ return { ...render(element()), element, onCommand };+}+describe('cloud connection card', () => {+ it.each([false, true])(+ 'keeps Save beside Cancel and outside the scrolling body (compact=%s)',+ (compact) => {+ const onCommand = vi.fn();+ render(+ <PluginSetupPrompt+ pending={pending}+ remote+ remoteDeviceId="cloud-a"+ compact={compact}+ viewerState="expanded"+ commandInFlight={null}+ onCommand={onCommand}+ onViewerStateChange={vi.fn()}+ />,+ );+ const save = screen.getByRole('button', { name: 'Save Configuration' }) as HTMLButtonElement;+ const cancel = screen.getByRole('button', { name: 'Cancel' });+ const host = screen.getByLabelText('Instance address');+ const token = screen.getByLabelText('Access token');+ const scrollRegion = screen.queryByTestId('interaction-prompt-scroll-region');+ expect(save.closest('form')).toBeNull();+ expect(save.form).toBe(host.closest('form'));+ expect(save.parentElement?.parentElement).toBe(cancel.parentElement);+ if (!compact) {+ expect(scrollRegion?.contains(host)).toBe(true);+ expect(scrollRegion?.contains(save)).toBe(false);+ }+ expect(save.disabled).toBe(true);+ fireEvent.change(host, { target: { value: 'https://git.example.test/' } });+ fireEvent.change(token, { target: { value: 'synthetic-pat' } });+ fireEvent.click(save);+ fireEvent.click(save);+ expect(onCommand).toHaveBeenCalledTimes(1);+ expect((token as HTMLInputElement).value).toBe('');+ },+ );+ it('associates each footer with only its own card form', () => {+ const first = form(),+ second = form({ ...pending, requestId: 'other-card' }, 'cloud-b');+ const cards = screen+ .getAllByRole('button', { name: 'Cancel' })+ .map((cancel) => cancel.parentElement!);+ const saves = cards.map(+ (card) =>+ within(card).getByRole('button', { name: 'Save Configuration' }) as HTMLButtonElement,+ );+ expect(saves[0].form).not.toBe(saves[1].form);+ const fill = (save: HTMLButtonElement, host: string) => {+ fireEvent.change(within(save.form!).getByLabelText('Instance address'), {+ target: { value: host },+ });+ fireEvent.change(within(save.form!).getByLabelText('Access token'), {+ target: { value: 'synthetic-pat' },+ });+ };+ fill(saves[0], 'https://first.example.test');+ fill(saves[1], 'https://second.example.test');+ fireEvent.click(saves[1]);+ expect(first.onCommand).not.toHaveBeenCalled();+ expect(second.onCommand).toHaveBeenCalledWith(+ 'other-card',+ 'submit_form',+ 'manage_connection:connection:service',+ { host: 'https://second.example.test', value: 'synthetic-pat' },+ );+ });+ it('renders a protected connection form, sends one private submission and clears input', () => {+ const h = form();+ const host = screen.getByLabelText('Instance address'),+ token = screen.getByLabelText('Access token');+ expect(+ screen.queryByText(+ 'Complete this setup on the controlled desktop. This card will update automatically.',+ ),+ ).toBeNull();+ expect(token.getAttribute('type')).toBe('password');+ fireEvent.change(host, { target: { value: 'https://git.example.test/' } });+ fireEvent.change(token, { target: { value: 'synthetic-pat' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));+ expect(h.onCommand).toHaveBeenCalledWith(+ 'connection-card',+ 'submit_form',+ 'manage_connection:connection:service',+ { host: 'https://git.example.test/', value: 'synthetic-pat' },+ );+ expect((token as HTMLInputElement).value).toBe('');+ expect((host as HTMLInputElement).value).toBe('');+ expect(document.body.textContent).not.toContain('synthetic-pat');+ });+ it('rejects a path target and focuses the address without submitting', () => {+ const h = form();+ const host = screen.getByLabelText('Instance address');+ fireEvent.change(host, { target: { value: 'https://git.example.test/path' } });+ fireEvent.change(screen.getByLabelText('Access token'), { target: { value: 'synthetic-pat' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));+ expect(h.onCommand).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(host);+ });+ it.each(['revision', 'target', 'cancel'] as const)(+ 'drops private input on %s change',+ (change) => {+ const h = form();+ fireEvent.change(screen.getByLabelText('Access token'), {+ target: { value: 'synthetic-pat' },+ });+ if (change === 'cancel') {+ h.rerender(h.element({ ...pending, terminal: true }));+ expect(screen.queryByLabelText('Access token')).toBeNull();+ } else {+ h.rerender(+ h.element(+ change === 'revision' ? { ...pending, revision: 2 } : pending,+ change === 'target' ? 'cloud-b' : 'cloud-a',+ ),+ );+ expect((screen.getByLabelText('Access token') as HTMLInputElement).value).toBe('');+ }+ },+ );+ it('does not show an input form for an older Host without connection capability', () => {+ form({ ...pending, remoteConnection: undefined });+ expect(screen.queryByLabelText('Access token')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/PluginOauthDeviceCode.test.tsx b/apps/desktop/src/renderer/__tests__/PluginOauthDeviceCode.test.tsxnew file mode 100644index 0000000000..9516b6a370--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/PluginOauthDeviceCode.test.tsx@@ -0,0 +1,135 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { PluginOauthDeviceCode } from '../components/new-chat/PluginOauthDeviceCode';+import type { PluginOauthDeviceCodeView } from '../../shared/pluginOauthDeviceCode';++const mocks = vi.hoisted(() => ({+ api: vi.fn(),+ toast: vi.fn(),+ t: (key: string, args?: Record<string, string>) => key + (args?.time ?? ''),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: mocks.t }) }));+vi.mock('@/lib/toast', () => ({ toast: { success: mocks.toast } }));+const prefix = 'newChat.pluginSetup.deviceCode.';+const target = {+ deviceId: 'device-test',+ ghostId: 'cindy-github',+ requestId: 'card-test',+ actionId: 'connect',+};+const ready = (): PluginOauthDeviceCodeView => ({+ phase: 'ready',+ userCode: 'TEST-CODE',+ verificationHost: 'github.com',+ copiedAt: Date.now(),+ expiresAt: Date.now() + 30_000,+});+beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(10_000);+ vi.clearAllMocks();+ mocks.api.mockResolvedValue(ready());+ window.electronAPI = {+ maker: { pluginOauthDeviceCode: mocks.api },+ } as unknown as typeof window.electronAPI;+});+afterEach(() => {+ cleanup();+ vi.clearAllTimers();+ vi.useRealTimers();+});+const settle = () =>+ act(async () => {+ await Promise.resolve();+ });++it('shows the ephemeral code, copy reminder and repeat actions without submitting material to any API', async () => {+ render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ expect(screen.getByText('TEST-CODE')).toBeTruthy();+ expect(screen.getByText(prefix + 'copiedHint')).toBeTruthy();+ expect(mocks.toast).toHaveBeenCalledWith(prefix + 'copiedHint', { duration: 5000 });+ for (let i = 0; i < 2; i++) {+ fireEvent.click(screen.getByRole('button', { name: prefix + 'copyAgain' }));+ await settle();+ }+ fireEvent.click(screen.getByRole('button', { name: prefix + 'reopen' }));+ await settle();+ expect(mocks.api.mock.calls.map((c) => c[0])).toEqual([+ { ...target, operation: 'read' },+ { ...target, operation: 'copy' },+ { ...target, operation: 'copy' },+ { ...target, operation: 'reopen' },+ ]);+ expect(JSON.stringify(mocks.api.mock.calls)).not.toContain('TEST-CODE');+ expect(JSON.stringify(mocks.toast.mock.calls)).not.toContain('TEST-CODE');+ expect(localStorage.length).toBe(0);+});++it('clears at expiry even while the next read is stalled and does not leave copy/reopen enabled', async () => {+ render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ mocks.api.mockImplementation(() => new Promise(() => {}));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30_001);+ });+ expect(screen.queryByText('TEST-CODE')).toBeNull();+ expect(screen.getByText(prefix + 'expired')).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+});++it.each(['completed', 'expired', 'ended'] as const)(+ 'clears the code after Main reports %s',+ async (phase) => {+ render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ mocks.api.mockResolvedValue({ phase });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(750);+ });+ expect(screen.queryByText('TEST-CODE')).toBeNull();+ expect(screen.getByText(prefix + phase)).toBeTruthy();+ },+);++it('removes the old code immediately on card replacement and ignores its late copy response', async () => {+ const view = render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ let resolve!: (v: PluginOauthDeviceCodeView) => void;+ mocks.api.mockImplementationOnce(+ () =>+ new Promise((r) => {+ resolve = r;+ }),+ );+ fireEvent.click(screen.getByRole('button', { name: prefix + 'copyAgain' }));+ mocks.api.mockResolvedValue(null);+ view.rerender(<PluginOauthDeviceCode target={{ ...target, requestId: 'new-card' }} active />);+ expect(screen.queryByText('TEST-CODE')).toBeNull();+ await act(async () => {+ resolve(ready());+ });+ expect(screen.queryByText('TEST-CODE')).toBeNull();+});++it('hides the code immediately when cancelled, without persisting it for a later mount', async () => {+ const view = render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ view.rerender(<PluginOauthDeviceCode target={target} active={false} />);+ expect(screen.queryByText('TEST-CODE')).toBeNull();+ expect(localStorage.length).toBe(0);+});++it('keeps the code visible after a clipboard error and allows another attempt', async () => {+ render(<PluginOauthDeviceCode target={target} active />);+ await settle();+ mocks.api.mockRejectedValueOnce(new Error('unavailable'));+ fireEvent.click(screen.getByRole('button', { name: prefix + 'copyAgain' }));+ await settle();+ expect(screen.getByRole('alert').textContent).toBe(prefix + 'actionFailed');+ expect(screen.getByText('TEST-CODE')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: prefix + 'copyAgain' }));+ await settle();+ expect(screen.queryByRole('alert')).toBeNull();+});diff --git a/apps/desktop/src/renderer/__tests__/PluginSetupPrompt.test.tsx b/apps/desktop/src/renderer/__tests__/PluginSetupPrompt.test.tsxindex 1915fae13b..90b9323268 100644--- a/apps/desktop/src/renderer/__tests__/PluginSetupPrompt.test.tsx+++ b/apps/desktop/src/renderer/__tests__/PluginSetupPrompt.test.tsx@@ -250,6 +250,47 @@ describe('PluginSetupPrompt', () => {);});+ it('enables only OAuth actions advertised by the cloud Host', () => {+ const onCommand = vi.fn();+ render(<PluginSetupPrompt pending={{ ...pending, remoteOauth: true }} viewerState="expanded"+ commandInFlight={null} remote onViewerStateChange={vi.fn()} onCommand={onCommand} />);+ const authorize = screen.getByRole('button', { name: pending.steps[0].title }) as HTMLButtonElement;+ expect(authorize.disabled).toBe(false);+ fireEvent.click(authorize);+ expect(onCommand).toHaveBeenCalledWith(pending.requestId, 'run_action', pending.steps[0].action!.id);+ expect(screen.getByText(/this computer’s browser/)).toBeTruthy();+ expect(parsePendingPluginSetup({ ...pending, remoteOauth: true })?.remoteOauth).toBe(true);+ });++ it('keeps inline secrets blocked even when remote OAuth is supported', () => {+ render(<PluginSetupPrompt pending={{ ...inlinePending, remoteOauth: true }} viewerState="expanded"+ commandInFlight={null} remote onViewerStateChange={vi.fn()} onCommand={vi.fn()} />);+ expect((screen.getByPlaceholderText('Enter API Key') as HTMLInputElement).disabled).toBe(true);+ });++ it('uses the existing password card for an explicitly supported cloud input and clears the value on handoff', () => {+ const onCommand = vi.fn();+ const p = { ...inlinePending, remoteSecret: true as const };+ const { rerender } = render(<PluginSetupPrompt pending={p} viewerState="expanded"+ commandInFlight={null} remote onViewerStateChange={vi.fn()} onCommand={onCommand} />);+ const input = screen.getByPlaceholderText('Enter API Key') as HTMLInputElement;+ expect(input.disabled).toBe(false);+ expect(input.type).toBe('password');+ expect(screen.getByText(/current remote device/)).toBeTruthy();+ fireEvent.change(input, {target: {value: 'synthetic-input'}});+ fireEvent.click(screen.getByRole('button', {name: 'Save Configuration'}));+ expect(onCommand).toHaveBeenCalledWith('setup-1', 'submit_form', 'inline:api-key', {value: 'synthetic-input'});+ expect(input.value).toBe('');+ expect(parsePendingPluginSetup(p)?.remoteSecret).toBe(true);+ rerender(<PluginSetupPrompt pending={p} viewerState="expanded"+ commandInFlight={{requestId: p.requestId, action: 'submit_form', actionId: 'inline:api-key'}}+ remote onViewerStateChange={vi.fn()} onCommand={onCommand} />);+ const cancel = screen.getByRole('button', {name: 'Cancel'}) as HTMLButtonElement;+ expect(cancel.disabled).toBe(false);+ fireEvent.click(cancel);+ expect(onCommand).toHaveBeenLastCalledWith('setup-1', 'cancel');+ });+it('disables duplicate commands while Main owns an in-flight action', () => {render(<PluginSetupPrompt@@ -591,6 +632,14 @@ describe('PluginSetupPrompt', () => {});describe('teammate authorization card presentation', () => {+ it('allows cancellation while the local Host is awaiting a remote OAuth callback', () => {+ const command = vi.fn();+ render(<PluginSetupPrompt pending={{ ...pending, remoteOauth: true }} viewerState="expanded"+ commandInFlight={{ requestId: pending.requestId, action: 'run_action', actionId: pending.steps[0].action!.id }}+ remote onViewerStateChange={() => {}} onCommand={command} />);+ fireEvent.click(screen.getByRole('button', { name: i18n.t('newChat.pluginSetup.cancel') }));+ expect(command).toHaveBeenCalledWith('setup-1', 'cancel');+ });it('omits a missing brand icon and uses the service name directly', () => {const { container } = render(<PluginSetupPrompt compact pending={pending} viewerState="expanded"commandInFlight={null} remote={false} onViewerStateChange={() => {}} onCommand={() => {}} />);diff --git a/apps/desktop/src/renderer/__tests__/RemoteOauthSetupCard.test.tsx b/apps/desktop/src/renderer/__tests__/RemoteOauthSetupCard.test.tsxnew file mode 100644index 0000000000..3f8c45100d--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/RemoteOauthSetupCard.test.tsx@@ -0,0 +1,204 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import '@/i18n';+import i18n from '@/i18n';+import { PluginSetupPrompt } from '../components/new-chat/PluginSetupPrompt';+import type { PendingPluginSetup } from '../lib/makerChatStore';++const api = vi.fn();+const command = vi.fn();+const pending: PendingPluginSetup = {+ requestId: 'card-test',+ revision: 1,+ remoteOauth: true,+ ghost: { id: 'test-plugin', name: 'Example plugin' },+ steps: [+ {+ id: 'account',+ groupId: 'account',+ groupMode: 'any_of',+ title: 'Connect account',+ description: '',+ phase: 'waiting_external',+ action: { id: 'connect', kind: 'oauth_connect' },+ },+ ],+};+const target = {+ deviceId: 'remote-test',+ ghostId: 'test-plugin',+ requestId: 'card-test',+ actionId: 'connect',+};+const props = {+ pending,+ remote: true,+ remoteDeviceId: target.deviceId,+ viewerState: 'expanded' as const,+ onViewerStateChange: vi.fn(),+ onCommand: command,+ commandInFlight: {+ requestId: pending.requestId,+ action: 'run_action' as const,+ actionId: 'connect',+ },+};+const settle = () =>+ act(async () => {+ await Promise.resolve();+ });+beforeEach(async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1000);+ vi.clearAllMocks();+ await i18n.changeLanguage('en');+ window.electronAPI = {+ maker: { pluginOauthDeviceCode: api },+ } as unknown as typeof window.electronAPI;+ api.mockResolvedValue({ phase: 'browser', expiresAt: 61_000 });+});+afterEach(() => {+ cleanup();+ vi.clearAllTimers();+ vi.useRealTimers();+});++it.each([false, true])(+ 'reopens the same authorization and allows cancellation while the bridge is pending (compact=%s)',+ async (compact) => {+ render(<PluginSetupPrompt {...props} compact={compact} />);+ await settle();+ expect(screen.getByRole('heading', { name: 'Waiting for browser authorization' })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Reopen Authorization Page' }));+ await settle();+ expect(api).toHaveBeenCalledWith({ ...target, operation: 'reopen' });+ expect(command).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(command).toHaveBeenCalledExactlyOnceWith('card-test', 'cancel');+ },+);++it('adds only the code content and keeps the same heading and footer for device authorization', async () => {+ api.mockResolvedValue({+ phase: 'ready',+ userCode: 'TEST-CODE',+ verificationHost: 'example.com',+ expiresAt: 61_000,+ copiedAt: 1000,+ });+ render(<PluginSetupPrompt {...props} />);+ await settle();+ expect(screen.getByRole('heading', { name: 'Waiting for browser authorization' })).toBeTruthy();+ expect(screen.getByText('TEST-CODE')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /copy/i }));+ await settle();+ expect(api).toHaveBeenCalledWith({ ...target, operation: 'copy' });+ expect(JSON.stringify(api.mock.calls)).not.toContain('TEST-CODE');+ expect(screen.getAllByRole('button', { name: 'Reopen Authorization Page' })).toHaveLength(1);+});++it('keeps ended, expired and cancelled distinct and never retries until the previous command finishes', async () => {+ api.mockResolvedValue({ phase: 'ended' });+ const r = render(<PluginSetupPrompt {...props} />);+ await settle();+ expect(screen.getByRole('heading', { name: 'Authorization ended' })).toBeTruthy();+ expect((screen.getByRole('button', { name: 'Reconnect' }) as HTMLButtonElement).disabled).toBe(+ true,+ );+ r.rerender(<PluginSetupPrompt {...props} commandInFlight={null} />);+ expect((screen.getByRole('button', { name: 'Reconnect' }) as HTMLButtonElement).disabled).toBe(+ true,+ );+ r.rerender(+ <PluginSetupPrompt+ {...props}+ commandInFlight={null}+ pending={{ ...pending, steps: [{ ...pending.steps[0], phase: 'failed' }] }}+ />,+ );+ await settle();+ fireEvent.click(screen.getByRole('button', { name: 'Reconnect' }));+ expect(command).toHaveBeenCalledWith('card-test', 'run_action', 'connect');+ api.mockResolvedValue({ phase: 'expired' });+ r.rerender(<PluginSetupPrompt {...props} />);+ await settle();+ expect(screen.getByRole('heading', { name: 'Authorization expired' })).toBeTruthy();+ r.rerender(+ <PluginSetupPrompt+ {...props}+ commandInFlight={null}+ pending={{ ...pending, steps: [{ ...pending.steps[0], phase: 'cancelled' }] }}+ />,+ );+ expect(screen.getByRole('heading', { name: 'Connection cancelled' })).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+});++it('removes private code as soon as cancellation starts and ignores a late response', async () => {+ const ready = {+ phase: 'ready',+ userCode: 'TEST-CODE',+ verificationHost: 'example.com',+ expiresAt: 61_000,+ copiedAt: 1000,+ };+ api.mockResolvedValue(ready);+ const r = render(<PluginSetupPrompt {...props} />);+ await settle();+ let finish!: (value: unknown) => void;+ api.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ fireEvent.click(screen.getByRole('button', { name: /copy/i }));+ r.rerender(+ <PluginSetupPrompt {...props} commandInFlight={{ requestId: 'card-test', action: 'cancel' }} />,+ );+ expect(screen.queryByText('TEST-CODE')).toBeNull();+ await act(async () => {+ finish(ready);+ });+ expect(screen.queryByText('TEST-CODE')).toBeNull();+});++it('distinguishes opening the browser from verifying an authorization result', async () => {+ api.mockResolvedValue(null);+ const r = render(+ <PluginSetupPrompt+ {...props}+ pending={{ ...pending, steps: [{ ...pending.steps[0], phase: 'pending' }] }}+ />,+ );+ await settle();+ expect(screen.getByRole('heading', { name: 'Opening authorization page' })).toBeTruthy();+ r.rerender(+ <PluginSetupPrompt+ {...props}+ pending={{ ...pending, steps: [{ ...pending.steps[0], phase: 'verifying' }] }}+ />,+ );+ expect(screen.getByRole('heading', { name: 'Confirming authorization' })).toBeTruthy();+});+++it.each([false, true])('shows a persistent failure only for the current remote card (compact=%s)', async (compact) => {+ api.mockResolvedValue(null);+ const current = { ...pending, steps: [{ ...pending.steps[0], phase: 'pending' as const }] };+ const error = { requestId: pending.requestId, revision: pending.revision, code: 'REMOTE_UNSUPPORTED' as const };+ const r = render(<PluginSetupPrompt {...props} compact={compact} pending={current} commandInFlight={null} commandError={error} />);+ await settle();+ expect(screen.getByRole('alert').textContent).toContain('Update it and try again');+ fireEvent.click(screen.getByRole('button', { name: 'Connect account' }));+ expect(command).toHaveBeenCalledWith('card-test', 'run_action', 'connect');+ r.rerender(<PluginSetupPrompt {...props} compact={compact} pending={current} commandError={error} />);+ expect(screen.queryByRole('alert')).toBeNull();+ r.rerender(<PluginSetupPrompt {...props} pending={{ ...current, revision: 2 }} commandInFlight={null} commandError={error} />);+ expect(screen.queryByRole('alert')).toBeNull();+ r.rerender(<PluginSetupPrompt {...props} pending={{ ...current, requestId: 'another-card' }} commandInFlight={null} commandError={error} />);+ expect(screen.queryByRole('alert')).toBeNull();+ r.rerender(<PluginSetupPrompt {...props} pending={current} remote={false} commandInFlight={null} commandError={error} />);+ expect(screen.queryByRole('alert')).toBeNull();+});diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 56897fc279..5ef3b512cf 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -300,6 +300,8 @@ function installElectronBridge(): void {send: vi.fn(async () => ({ accepted: true })),resolveInteraction: vi.fn(async () => ({ accepted: true })),submitPluginSetupInline: vi.fn(async () => {}),+ assistPluginOauth: vi.fn(async () => ({ accepted: true })),+ submitRemotePluginSecret: vi.fn(async () => ({ accepted: true })),getPendingInteractions,steer: vi.fn(async () => true),generateTitle: vi.fn(async () => ({ title: 't' })),@@ -1614,6 +1616,68 @@ describe('makerChatStore text delta batching', () => {await flushPromises();});+ it.each([+ ['UNSUPPORTED_CAPABILITY', 'REMOTE_UNSUPPORTED'],+ ['PRECONDITION_FAILED', 'REMOTE_FAILED'],+ ])('keeps %s visible on the current remote card without retaining private error details', async (code, expected) => {+ deviceLinkInvoke.mockResolvedValue(null);+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ emitInteractionRequest({ ...pluginSetupRequest(1), remoteOauth: true });+ const api = vi.mocked(window.electronAPI.maker.assistPluginOauth);+ api.mockRejectedValueOnce(new Error(`Error invoking remote method: Error: [${code}] private-provider-payload`));+ makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'run_action', 'oauth:google-account');+ await flushPromises();+ let state = makerChatStore.getSnapshot(SESSION_ID);+ expect(api).toHaveBeenCalledOnce();+ expect(state.pluginSetupCommandInFlight).toBeNull();+ expect(state.pluginSetupCommandError).toEqual({ requestId: 'plugin-setup-1', revision: 1, code: expected });+ expect(state.pendingPluginSetup?.steps[0].phase).toBe('pending');+ expect(JSON.stringify(state)).not.toContain('private-provider-payload');+ let finish!: (result: { accepted: boolean }) => void;+ api.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'run_action', 'oauth:google-account');+ makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'run_action', 'oauth:google-account');+ state = makerChatStore.getSnapshot(SESSION_ID);+ expect(api).toHaveBeenCalledTimes(2);+ expect(state.pluginSetupCommandError).toBeNull();+ expect(state.pluginSetupCommandInFlight?.action).toBe('run_action');+ finish({ accepted: true });+ await flushPromises();+ });++ it.each(['cancel', 'revision', 'owner'])('discards a remote authorization failure after %s changes', async (change) => {+ deviceLinkInvoke.mockResolvedValue(null);+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ emitInteractionRequest({ ...pluginSetupRequest(1), remoteOauth: true });+ let reject!: (error: Error) => void;+ vi.mocked(window.electronAPI.maker.assistPluginOauth).mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; }));+ makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'run_action', 'oauth:google-account');+ if (change === 'cancel') makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'cancel');+ if (change === 'revision') emitInteractionRequest({ ...pluginSetupRequest(2), remoteOauth: true });+ if (change === 'owner') setDataOwnerGeneration('owner-b');+ const before = makerChatStore.getSnapshot(SESSION_ID).pluginSetupCommandInFlight;+ reject(new Error('[UNSUPPORTED_CAPABILITY] private-provider-payload'));+ await flushPromises();+ const state = makerChatStore.getSnapshot(SESSION_ID);+ expect(state.pluginSetupCommandError).toBeNull();+ expect(state.pluginSetupCommandInFlight).toBe(before);+ });++ it('reports remote secret submission failure without retaining the input or provider payload', async () => {+ deviceLinkInvoke.mockResolvedValue(null);+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ emitInteractionRequest({ ...inlinePluginSetupRequest(1), remoteSecret: true });+ const api = vi.mocked(window.electronAPI.maker.submitRemotePluginSecret);+ api.mockRejectedValueOnce(new Error('[UNSUPPORTED_CAPABILITY] synthetic-private-token'));+ makerChatStore.respondToPluginSetup(SESSION_ID, 'plugin-setup-1', 'submit_form', 'inline:api-key', { value: 'synthetic-private-token' });+ await flushPromises();+ const state = makerChatStore.getSnapshot(SESSION_ID);+ expect(api).toHaveBeenCalledOnce();+ expect(state.pluginSetupCommandError?.code).toBe('REMOTE_UNSUPPORTED');+ expect(state.pluginSetupCommandInFlight).toBeNull();+ expect(JSON.stringify(state)).not.toContain('synthetic-private-token');+ });+it('submits an inline Secret only through the local narrow API without retaining it', async () => {emitInteractionRequest(inlinePluginSetupRequest(1));diff --git a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts b/apps/desktop/src/renderer/__tests__/makerQueueState.test.tsindex 49a02f8727..db6b72bbcd 100644--- a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts@@ -99,6 +99,7 @@ const state = (overrides: Partial<SessionChatState> = {}): SessionChatState => (pendingPluginSetupQueue: [],pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,pendingPlanReview: null,pendingIssueConfirm: null,pendingRenameSessionsConfirm: null,diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.tsindex c679658348..eec37eb487 100644--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts@@ -13,6 +13,8 @@ beforeEach(() => {function stubElectron() {const makerSpies = {+ submitRemotePluginSecret: vi.fn().mockResolvedValue({accepted: true}),+ submitRemotePluginConnection: vi.fn().mockResolvedValue({accepted: true}),setModel: vi.fn(),setEffort: vi.fn(),fork: vi.fn(),@@ -64,6 +66,33 @@ function stubElectron() {const sess = (id: string): Session => ({ id }) as unknown as Session;describe('makerApiFor 路由(完整对等会话级操作)', () => {+ it('routes connection input only through the dedicated local Main bridge', async () => {+ const {makerSpies, invoke} = stubElectron();+ const {submitRemotePluginConnection} = await import('@/lib/makerTransport');+ const {remoteProjectsStore} = await import('@/features/device-link/remoteProjectsStore');+ remoteProjectsStore.setDeviceSessions('cloud', 'Cloud', [sess('connection-task')]);+ const request = { ghostId: 'plugin', requestId: 'card', actionId: 'manage_connection:connection:service', expectedRevision: 0,+ value: { host: 'git.example.test', token: 'synthetic-pat' },+ presentation: { ghostName: 'Plugin', title: 'Connect', description: '', intro: '', connectionKey: 'service' } };+ await expect(submitRemotePluginConnection('connection-task', request)).resolves.toEqual({accepted: true});+ expect(makerSpies.submitRemotePluginConnection).toHaveBeenCalledWith({deviceId: 'cloud', ...request});+ expect(invoke).not.toHaveBeenCalled();+ await expect(submitRemotePluginConnection('unknown-local-task', request)).rejects.toThrow();+ });+ it('routes cloud key input only through the dedicated local Main bridge, never generic invoke', async () => {+ const {makerSpies, invoke} = stubElectron();+ const {submitRemotePluginSecret} = await import('@/lib/makerTransport');+ const {remoteProjectsStore} = await import('@/features/device-link/remoteProjectsStore');+ remoteProjectsStore.setDeviceSessions('cloud', 'Cloud', [sess('remote-task')]);+ const request = {ghostId: 'plugin', requestId: 'card', actionId: 'action', expectedRevision: 0,+ value: 'synthetic-pat', presentation: {ghostName: 'Plugin', title: 'Key', description: '', intro: '',+ fieldLabel: 'API key', fieldDescription: '', maxLength: 200}};+ await expect(submitRemotePluginSecret('remote-task', request)).resolves.toEqual({accepted: true});+ expect(makerSpies.submitRemotePluginSecret).toHaveBeenCalledWith({deviceId: 'cloud', ...request});+ expect(invoke).not.toHaveBeenCalled();+ await expect(submitRemotePluginSecret('unknown-local-task', request)).rejects.toThrow();+ expect(makerSpies.submitRemotePluginSecret).toHaveBeenCalledTimes(1);+ });it('远程 device-link 会话:每个任务级操作命中对应隧道 channel + 原样转发 args', async () => {const { invoke } = stubElectron();const { makerApiFor } = await import('@/lib/makerTransport');diff --git a/apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx b/apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsxnew file mode 100644index 0000000000..85a91aad31--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx@@ -0,0 +1,130 @@+import { useEffect, useId, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';+import { normalizePluginConnectionHost, parsePluginConnectionInput } from '@cindy/device-link';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { FormField } from '@/components/ui/form-field';++/** Input is ephemeral and local to the current target/card/revision. Never a chat draft. */+export function PluginConnectionForm({+ busy,+ disabled,+ actionsContainer,+ onSubmit,+}: {+ busy: boolean;+ disabled: boolean;+ onSubmit(host: string, token: string): void;+ /** Keep the submit action beside Cancel, outside the card's scrolling body. */+ actionsContainer?: HTMLElement | null;+}) {+ const { t } = useTranslation();+ const formId = useId();+ const [host, setHost] = useState(''),+ [token, setToken] = useState('');+ const [error, setError] = useState<'host' | 'token' | null>(null);+ const hostRef = useRef<HTMLInputElement>(null),+ tokenRef = useRef<HTMLInputElement>(null);+ const submitted = useRef(false);+ useEffect(() => {+ if (!busy) submitted.current = false;+ }, [busy]);+ const submit = () => {+ if (disabled || busy || submitted.current) return;+ try {+ normalizePluginConnectionHost(host);+ } catch {+ setError('host');+ hostRef.current?.focus();+ return;+ }+ try {+ parsePluginConnectionInput({ host, token });+ } catch {+ setError('token');+ tokenRef.current?.focus();+ return;+ }+ submitted.current = true;+ onSubmit(host, token);+ setToken('');+ setHost('');+ setError(null);+ };+ const submitButton = (+ <Button+ type="submit"+ form={formId}+ size="lg"+ loading={busy}+ disabled={disabled || !host.trim() || !token.trim()}+ >+ {t('newChat.pluginSetup.saveConfiguration')}+ </Button>+ );+ return (+ <form+ id={formId}+ className="mt-3 flex min-w-0 flex-col gap-3"+ autoComplete="off"+ onSubmit={(e) => {+ e.preventDefault();+ submit();+ }}+ >+ <FormField+ label={t('newChat.pluginSetup.connection.host')}+ required+ reserveFeedback+ hint={t('newChat.pluginSetup.connection.hostHint')}+ error={error === 'host' ? t('newChat.pluginSetup.connection.hostInvalid') : undefined}+ >+ {(control) => (+ <Input+ {...control}+ size="md"+ inputRef={hostRef}+ value={host}+ onChange={setHost}+ disabled={disabled || busy}+ maxLength={512}+ autoCapitalize="none"+ spellCheck={false}+ autoComplete="off"+ />+ )}+ </FormField>+ <FormField+ label={t('newChat.pluginSetup.connection.token')}+ required+ reserveFeedback+ error={error === 'token' ? t('newChat.pluginSetup.connection.tokenInvalid') : undefined}+ >+ {(control) => (+ <Input+ {...control}+ size="md"+ inputRef={tokenRef}+ secret+ value={token}+ onChange={setToken}+ disabled={disabled || busy}+ maxLength={4096}+ autoCapitalize="none"+ spellCheck={false}+ autoComplete="new-password"+ />+ )}+ </FormField>+ <p className="text-12 leading-5 text-[var(--text-secondary)]">+ {t('newChat.pluginSetup.connection.hint')}+ </p>+ {actionsContainer === undefined ? (+ <div>{submitButton}</div>+ ) : actionsContainer ? (+ createPortal(submitButton, actionsContainer)+ ) : null}+ </form>+ );+}diff --git a/apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx b/apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsxnew file mode 100644index 0000000000..eeacd5c162--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx@@ -0,0 +1,215 @@+import { Copy, ExternalLink } from 'lucide-react';+import { useEffect, useRef, useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { toast } from '@/lib/toast';+import type {+ PluginOauthDeviceCodeTarget,+ PluginOauthDeviceCodeView,+} from '../../../shared/pluginOauthDeviceCode';++// Notification deduplication contains only card IDs/deadlines, never authorization material.+const notified = new Map<string, number>();++export interface PluginOauthPresentation {+ view: PluginOauthDeviceCodeView | null;+ now: number;+ working: 'copy' | 'reopen' | null;+ failed: boolean;+ operate: (operation: 'copy' | 'reopen') => Promise<void>;+}++/** Ephemeral view; it never writes to the chat store, messages, localStorage or remote transport. */+export function PluginOauthDeviceCode({+ target,+ active,+ children,+ running = false,+}: {+ target: PluginOauthDeviceCodeTarget;+ active: boolean;+ running?: boolean;+ children?: (state: PluginOauthPresentation) => ReactNode;+}) {+ return (+ <DeviceCodeView+ key={JSON.stringify(target)}+ target={target}+ active={active}+ running={running}+ children={children}+ />+ );+}++function DeviceCodeView({+ target,+ active,+ children,+ running,+}: {+ target: PluginOauthDeviceCodeTarget;+ active: boolean;+ running: boolean;+ children?: (state: PluginOauthPresentation) => ReactNode;+}) {+ const { t } = useTranslation();+ const [view, setView] = useState<PluginOauthDeviceCodeView | null>(null);+ const [now, setNow] = useState(Date.now);+ const [working, setWorking] = useState<'copy' | 'reopen' | null>(null);+ const [failed, setFailed] = useState(false);+ const current = useRef(false);+ const command = useRef(false);+ const epoch = useRef(0);+ const key = JSON.stringify([target.deviceId, target.ghostId, target.requestId, target.actionId]);++ useEffect(() => {+ current.current = true;+ return () => {+ current.current = false;+ };+ }, []);++ useEffect(() => {+ const generation = ++epoch.current;+ command.current = false;+ setWorking(null);+ setFailed(false);+ let alive = true;+ let timer: ReturnType<typeof setTimeout> | undefined;+ if (!active || !window.electronAPI.maker.pluginOauthDeviceCode) {+ setView(null);+ return;+ }+ const read = async () => {+ try {+ const next = await window.electronAPI.maker.pluginOauthDeviceCode({+ ...target,+ operation: 'read',+ });+ if (!alive || generation !== epoch.current) return;+ setNow(Date.now());+ setView(+ next &&+ (next.phase === 'ready' || next.phase === 'browser') &&+ next.expiresAt <= Date.now()+ ? { phase: 'expired' }+ : next,+ );+ if (next?.phase === 'ready' && next.expiresAt > Date.now()) {+ for (const [id, expiry] of notified) if (expiry <= Date.now()) notified.delete(id);+ const notice = `${key}:${next.expiresAt}`;+ if (!notified.has(notice)) {+ if (notified.size >= 64) notified.delete(notified.keys().next().value!);+ notified.set(notice, next.expiresAt);+ toast.success(t('newChat.pluginSetup.deviceCode.copiedHint'), { duration: 5000 });+ }+ }+ if (!next || next.phase === 'ready' || next.phase === 'browser' || running)+ timer = setTimeout(() => void read(), 750);+ } catch {+ if (alive) setView((previous) => (previous ? { phase: 'ended' } : null));+ }+ };+ void read();+ return () => {+ alive = false;+ ++epoch.current;+ clearTimeout(timer);+ };+ }, [key, active, running, t]);++ useEffect(() => {+ if (view?.phase !== 'ready' && view?.phase !== 'browser') return;+ const timer = setTimeout(+ () => setView({ phase: 'expired' }),+ Math.max(0, view.expiresAt - Date.now()),+ );+ return () => clearTimeout(timer);+ }, [view?.phase, view?.phase === 'ready' || view?.phase === 'browser' ? view.expiresAt : null]);++ const ready = active && view?.phase === 'ready' && view.expiresAt > now ? view : null;+ const operate = async (operation: 'copy' | 'reopen') => {+ const available =+ active &&+ (view?.phase === 'ready' || view?.phase === 'browser') &&+ view.expiresAt > Date.now();+ if (!available || (operation === 'copy' && !ready) || command.current) return;+ command.current = true;+ const generation = epoch.current;+ setWorking(operation);+ setFailed(false);+ try {+ const next = await window.electronAPI.maker.pluginOauthDeviceCode({ ...target, operation });+ if (!current.current || generation !== epoch.current) return;+ setView(next);+ setNow(Date.now());+ if (operation === 'copy' && next?.phase === 'ready')+ toast.success(t('newChat.pluginSetup.deviceCode.copied'));+ } catch {+ if (current.current && generation === epoch.current) setFailed(true);+ } finally {+ if (generation === epoch.current) command.current = false;+ if (current.current && generation === epoch.current) setWorking(null);+ }+ };+ if (children) return children({ view: active ? view : null, now, working, failed, operate });+ if (!active || !view || view.phase === 'browser') return null;+ const seconds = ready ? Math.max(0, Math.ceil((ready.expiresAt - now) / 1000)) : 0;+ const time = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;+ return (+ <div+ className="flex flex-col gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"+ data-plugin-oauth-device-code+ >+ {ready ? (+ <>+ <p className="text-13 text-[var(--text-secondary)]" role="status">+ {t('newChat.pluginSetup.deviceCode.copiedHint')}+ </p>+ <code+ className="select-all whitespace-pre-wrap break-all text-20 font-medium tracking-wider text-[var(--text-primary)]"+ aria-label={t('newChat.pluginSetup.deviceCode.label')}+ >+ {ready.userCode}+ </code>+ <p className="text-13 leading-5 text-[var(--text-secondary)]">+ {t('newChat.pluginSetup.deviceCode.instructions', { host: ready.verificationHost })}+ </p>+ <div className="flex flex-wrap gap-2">+ <Button+ variant="secondary"+ onClick={() => void operate('copy')}+ disabled={!!working}+ className="gap-2"+ >+ <Copy size={14} aria-hidden="true" />+ {t('newChat.pluginSetup.deviceCode.copyAgain')}+ </Button>+ <Button+ variant="secondary"+ onClick={() => void operate('reopen')}+ disabled={!!working}+ className="gap-2"+ >+ <ExternalLink size={14} aria-hidden="true" />+ {t('newChat.pluginSetup.deviceCode.reopen')}+ </Button>+ </div>+ <p className="text-12 text-[var(--text-secondary)]">+ {t('newChat.pluginSetup.deviceCode.remaining', { time })}+ </p>+ {failed ? (+ <p role="alert" className="text-13 text-[var(--error-fg)]">+ {t('newChat.pluginSetup.deviceCode.actionFailed')}+ </p>+ ) : null}+ </>+ ) : (+ <p role="status" className="text-13 text-[var(--text-secondary)]">+ {t(`newChat.pluginSetup.deviceCode.${view.phase === 'ready' ? 'expired' : view.phase}`)}+ </p>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsxindex eab07e0e8b..db5749ccf9 100644--- a/apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx+++ b/apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx@@ -8,16 +8,22 @@ import { cn } from '@/lib/utils';import type {PendingPluginSetup,PluginSetupCommandInFlight,+ PluginSetupCommandError,PluginSetupInlineFormValues,PluginSetupViewerState,} from '@/lib/makerChatStore';import type { GhostSetupStepPhase } from '../../../shared/ghost';+import { RemoteOauthSetupCard } from './RemoteOauthSetupCard';+import { PluginOauthDeviceCode } from './PluginOauthDeviceCode';+import { PluginConnectionForm } from './PluginConnectionForm';interface PluginSetupPromptProps {+ remoteDeviceId?: string;compact?: boolean;pending: PendingPluginSetup;viewerState: PluginSetupViewerState;commandInFlight: PluginSetupCommandInFlight | null;+ commandError?: PluginSetupCommandError | null;remote: boolean;onViewerStateChange: (next: PluginSetupViewerState) => void;onCommand: (@@ -44,7 +50,7 @@ function normalizedCopy(value: string | undefined): string {export function PluginSetupPrompt({ pending, ...props }: PluginSetupPromptProps) {return (<PluginSetupPromptStateful- key={`${pending.requestId}:${pending.revision}`}+ key={`${props.remoteDeviceId ?? 'local'}:${pending.requestId}:${pending.revision}`}pending={pending}{...props}/>@@ -56,13 +62,16 @@ function PluginSetupPromptStateful({compact = false,viewerState,commandInFlight,+ commandError,remote,+ remoteDeviceId,onViewerStateChange,onCommand,}: PluginSetupPromptProps) {const { t } = useTranslation();const inputId = useId();const [iconFailed, setIconFailed] = useState(false);+ const [connectionActions, setConnectionActions] = useState<HTMLDivElement | null>(null);const [formValues, setFormValues] = useState<Record<string, string>>({});const [formTouched, setFormTouched] = useState<Record<string, boolean>>({});const [linkOpenFailed, setLinkOpenFailed] = useState<Record<string, boolean>>({});@@ -93,7 +102,18 @@ function PluginSetupPromptStateful({pending.steps.some((step) => step.phase === 'cancelled') &&pending.steps.every((step) => isTerminalPhase(step.phase));const terminal = pending.terminal === true || allSatisfied || cancelledTerminal;+ const commandErrorMessage = remote && !terminal && !commandInFlight &&+ commandError?.requestId === pending.requestId && commandError.revision === pending.revision+ ? t(`newChat.pluginSetup.error.${commandError.code}`) : undefined;const busy = !!commandInFlight || (!compact && !!currentStep && RUNNING_PHASES.has(currentStep.phase));+ const blockedRemoteAction = (step = currentStep): boolean =>+ remote && !((pending.remoteOauth && step?.action?.kind === 'oauth_connect') ||+ (pending.remoteSecret && step?.action?.kind === 'inline_form') ||+ (pending.remoteConnection && step?.action?.kind === 'manage_connection'));+ const cancelBlocked = !!commandInFlight && !(remote &&+ ((pending.remoteOauth && commandInFlight.action === 'run_action') ||+ ((pending.remoteSecret || pending.remoteConnection) && commandInFlight.action === 'submit_form')));+ const connectionForm = (step = currentStep) => remote && pending.remoteConnection && step?.action?.kind === 'manage_connection';const title = compact ? pending.ghost.name : t('newChat.pluginSetup.title', { name: pending.ghost.name });const inlineFormAction = currentStep?.action?.kind === 'inline_form' ? currentStep.action : null;const inlineFormField = inlineFormAction?.form.fields[0];@@ -213,7 +233,7 @@ function PluginSetupPromptStateful({};const submitStepAction = (step: PendingPluginSetup['steps'][number]) => {- if (!step.action || remote || busy || terminal) return;+ if (!step.action || blockedRemoteAction(step) || busy || terminal) return;if (step.action.kind !== 'inline_form') {onCommand(pending.requestId, 'run_action', step.action.id);return;@@ -280,10 +300,10 @@ function PluginSetupPromptStateful({type="password"autoComplete="new-password"spellCheck={false}- autoFocus={!hasCurrentGroupAlternatives && !remote && !busy && !terminal}+ autoFocus={!hasCurrentGroupAlternatives && !blockedRemoteAction(step) && !busy && !terminal}value={context.value}maxLength={field.maxLength}- disabled={remote || busy || terminal}+ disabled={blockedRemoteAction(step) || busy || terminal}placeholder={field.placeholder ||t('newChat.pluginSetup.form.placeholder', {@@ -320,18 +340,18 @@ function PluginSetupPromptStateful({'text-14 text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)]','outline-none transition-colors focus-visible:border-[var(--focus-ring)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',context.error ? 'border-[var(--error-border)]' : 'border-[var(--border-default)]',- (remote || busy || terminal) &&+ (blockedRemoteAction(step) || busy || terminal) &&'cursor-not-allowed bg-[var(--surface-elevated-soft)] text-[var(--text-disabled)]',)}/>{showSubmit ? (<buttontype="button"- disabled={remote || busy || context.missing || context.tooLong}+ disabled={blockedRemoteAction(step) || busy || terminal || context.missing || context.tooLong}onClick={() => submitStepAction(step)}className={cn('h-9 shrink-0 rounded-[9999px] px-4 text-13 font-medium transition-colors',- remote || busy || context.missing || context.tooLong+ blockedRemoteAction(step) || busy || terminal || context.missing || context.tooLong? 'cursor-not-allowed border border-[var(--border-default)] bg-transparent text-[var(--text-disabled-tertiary)] opacity-60': 'border border-transparent bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',)}@@ -395,21 +415,23 @@ function PluginSetupPromptStateful({const footer = (<div className="flex flex-wrap items-center gap-2">+ {connectionForm() && !hasCurrentGroupAlternatives && !terminal && commandInFlight?.action !== 'cancel'+ ? <div ref={setConnectionActions} /> : null}{compact && pending.reopenActionId && !terminal && !remote ? <button type="button"disabled={!!commandInFlight} onClick={() => onCommand(pending.requestId, 'run_action', pending.reopenActionId)}className="h-9 rounded-[9999px] border border-[var(--border-default)] px-4 text-13 text-[var(--text-primary)] disabled:opacity-50">{t('newChat.pluginSetup.reopen')}</button> : null}- {currentStep?.action && !terminal && !hasCurrentGroupAlternatives ? (+ {currentStep?.action && !terminal && !hasCurrentGroupAlternatives && !connectionForm() ? (<buttontype="button"disabled={- remote || busy || (!!inlineFormAction && (formValueMissing || formValueTooLong))+ blockedRemoteAction() || busy || (!!inlineFormAction && (formValueMissing || formValueTooLong))}onClick={submitCurrentAction}className={cn('h-9 rounded-[9999px] px-[18px] text-13 font-medium transition-colors',- remote || busy || (!!inlineFormAction && (formValueMissing || formValueTooLong))+ blockedRemoteAction() || busy || (!!inlineFormAction && (formValueMissing || formValueTooLong))? 'cursor-not-allowed border border-[var(--border-default)] bg-transparent text-[var(--text-disabled-tertiary)] opacity-60': 'border border-transparent bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',)}@@ -427,11 +449,11 @@ function PluginSetupPromptStateful({{!terminal ? (<buttontype="button"- disabled={!!commandInFlight}+ disabled={cancelBlocked}onClick={cancelSetup}className={cn('h-9 rounded-[9999px] border border-[var(--confirm-btn-secondary-border)] bg-transparent px-[18px] text-13 font-medium text-[var(--confirm-btn-secondary-text)] transition-colors',- commandInFlight+ cancelBlocked? 'cursor-not-allowed opacity-50': 'hover:bg-[var(--confirm-btn-secondary-hover)]',)}@@ -442,6 +464,12 @@ function PluginSetupPromptStateful({</div>);+ if (remote && pending.remoteOauth && pending.steps.length === 1 &&+ (currentStep?.action?.kind === 'oauth_connect' || (terminal && !currentStep?.action))) {+ return <RemoteOauthSetupCard pending={pending} compact={compact} remoteDeviceId={remoteDeviceId}+ commandInFlight={commandInFlight} errorMessage={commandErrorMessage} onCommand={onCommand} />;+ }+const Shell = compact ? AuthorizationShell : InteractionPromptCardShell;return (<Shell@@ -471,16 +499,29 @@ function PluginSetupPromptStateful({footer={terminal ? undefined : footer}><div className="flex flex-col gap-[10px]" role="status" aria-live="polite" aria-label={title}>+ {commandErrorMessage ? <p role="alert" className="text-13 text-[var(--error-fg)]">{commandErrorMessage}</p> : null}{!compactInlineForm && pending.intro ? (<p className="text-14 leading-5 text-[var(--ask-option-desc)]">{pending.intro}</p>) : null}- {remote && !terminal ? (+ {remote && !terminal && !connectionForm() ? (<div className="rounded-[12px] border border-[var(--ask-option-border)] bg-[var(--ask-option-list-bg)] px-3 py-2.5 text-13 text-[var(--ask-option-desc)]">- {t('newChat.pluginSetup.completeOnDesktop')}+ {t(pending.remoteSecret && currentStep?.action?.kind === 'inline_form'+ ? 'newChat.pluginSetup.remoteSecretHint' : pending.remoteOauth && pending.steps.some(s => s.action?.kind === 'oauth_connect')+ ? 'newChat.pluginSetup.remoteOauthHint' : 'newChat.pluginSetup.completeOnDesktop')}</div>) : null}+ {remote && remoteDeviceId && pending.remoteOauth && !terminal &&+ currentStep?.action?.kind === 'oauth_connect' ? (+ <PluginOauthDeviceCode+ key={`${remoteDeviceId}:${pending.requestId}:${currentStep.action.id}`}+ target={{ deviceId: remoteDeviceId, ghostId: pending.ghost.id, requestId: pending.requestId, actionId: currentStep.action.id }}+ active={commandInFlight?.action !== 'cancel' && (commandInFlight?.action === 'run_action' ||+ ['action_running', 'waiting_external', 'verifying'].includes(currentStep.phase))}+ />+ ) : null}+{compact && terminal ? null : compactInlineForm && currentStep && inlineFormField ? (<div className="flex flex-col gap-2">{inlineLead ? (@@ -531,6 +572,7 @@ function PluginSetupPromptStateful({hasCurrentGroupAlternatives &&step.action &&step.action.kind !== 'inline_form' &&+ !connectionForm(step) &&(step.phase === 'pending' || step.phase === 'failed');return (<li@@ -587,14 +629,19 @@ function PluginSetupPromptStateful({{renderInlineFormControl(step, false, hasCurrentGroupAlternatives)}</div>) : null}+ {currentGroupOption && connectionForm(step) && !terminal && commandInFlight?.action !== 'cancel' ? <PluginConnectionForm+ key={step.action!.id} busy={busy} disabled={blockedRemoteAction(step)}+ actionsContainer={hasCurrentGroupAlternatives ? undefined : connectionActions}+ onSubmit={(host, token) => onCommand(pending.requestId, 'submit_form', step.action!.id, { host, value: token })}+ /> : null}{directActionOption ? (<buttontype="button"- disabled={remote || busy || terminal}+ disabled={blockedRemoteAction(step) || busy || terminal}onClick={() => submitStepAction(step)}className={cn('mt-2 h-9 rounded-[9999px] px-4 text-13 font-medium transition-colors',- remote || busy || terminal+ blockedRemoteAction(step) || busy || terminal? 'cursor-not-allowed border border-[var(--border-default)] bg-transparent text-[var(--text-disabled-tertiary)] opacity-60': 'border border-transparent bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',)}diff --git a/apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx b/apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsxnew file mode 100644index 0000000000..5cc2c0d32f--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx@@ -0,0 +1,257 @@+import { AlertCircle, Check, Copy, ExternalLink, LoaderCircle } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';+import type { PendingPluginSetup, PluginSetupCommandInFlight } from '@/lib/makerChatStore';+import { PluginOauthDeviceCode, type PluginOauthPresentation } from './PluginOauthDeviceCode';++interface Props {+ pending: PendingPluginSetup;+ compact: boolean;+ remoteDeviceId?: string;+ commandInFlight: PluginSetupCommandInFlight | null;+ errorMessage?: string;+ onCommand: (requestId: string, action: 'run_action' | 'cancel', actionId?: string) => void;+}++/** One remote account action, shared by the composer and Bot transcript. */+export function RemoteOauthSetupCard(props: Props) {+ const { pending, remoteDeviceId, commandInFlight } = props;+ const step = pending.steps[0];+ const active =+ !pending.terminal &&+ step.phase !== 'satisfied' &&+ step.phase !== 'cancelled' &&+ commandInFlight?.action !== 'cancel' &&+ (commandInFlight?.action === 'run_action' ||+ ['action_running', 'waiting_external', 'verifying', 'failed'].includes(step.phase));+ if (remoteDeviceId && step.action) {+ return (+ <PluginOauthDeviceCode+ target={{+ deviceId: remoteDeviceId,+ ghostId: pending.ghost.id,+ requestId: pending.requestId,+ actionId: step.action.id,+ }}+ active={active}+ running={commandInFlight?.action === 'run_action'}+ >+ {(presentation) => <AccountCard {...props} presentation={presentation} />}+ </PluginOauthDeviceCode>+ );+ }+ return <AccountCard {...props} />;+}++function AccountCard({+ pending,+ compact,+ commandInFlight,+ onCommand,+ presentation,+ errorMessage,+}: Props & { presentation?: PluginOauthPresentation }) {+ const { t } = useTranslation();+ const step = pending.steps[0];+ const view = presentation?.view;+ const cancelled = step.phase === 'cancelled';+ const complete = step.phase === 'satisfied';+ const expired = !complete && !cancelled && view?.phase === 'expired';+ const ended = !complete && !cancelled && view?.phase === 'ended';+ const failed = step.phase === 'failed';+ const waiting =+ !complete &&+ !cancelled &&+ !expired &&+ !ended &&+ !failed &&+ step.phase !== 'verifying' &&+ (step.phase === 'waiting_external' || view?.phase === 'ready' || view?.phase === 'browser');+ const loading =+ !waiting &&+ !complete &&+ !cancelled &&+ !expired &&+ !ended &&+ (step.phase === 'action_running' || step.phase === 'verifying' || !!commandInFlight);+ const terminal = pending.terminal === true || complete || cancelled;+ const canReopen = waiting && (view?.phase === 'ready' || view?.phase === 'browser');+ const code = waiting && view?.phase === 'ready' ? view : null;+ const title = complete+ ? t('newChat.pluginSetup.account.connected')+ : cancelled+ ? t('newChat.pluginSetup.account.cancelled')+ : expired+ ? t('newChat.pluginSetup.account.expired')+ : ended+ ? t('newChat.pluginSetup.account.ended')+ : failed+ ? t('newChat.pluginSetup.account.failed')+ : waiting+ ? t('newChat.pluginSetup.account.waiting')+ : loading+ ? t(+ step.phase === 'verifying'+ ? 'newChat.pluginSetup.account.verifying'+ : 'newChat.pluginSetup.account.opening',+ )+ : step.title;+ const description = complete+ ? t('newChat.pluginSetup.account.continue')+ : cancelled+ ? ''+ : expired || ended+ ? t('newChat.pluginSetup.account.reconnectHint')+ : failed+ ? step.errorCode+ ? t(`newChat.pluginSetup.error.${step.errorCode}`)+ : step.errorMessage+ : waiting+ ? t('newChat.pluginSetup.account.waitingHint')+ : loading+ ? ''+ : t('newChat.pluginSetup.account.remoteHint');+ const instructions =+ !terminal && !waiting && !loading+ ? [...new Set([pending.intro?.trim(), step.description.trim()])]+ .filter((text): text is string => !!text && text !== step.title && text !== description)+ .join(' ')+ : '';+ const seconds = code+ ? Math.max(0, Math.ceil((code.expiresAt - (presentation?.now ?? Date.now())) / 1000))+ : 0;+ const cancelBlocked = !!commandInFlight && commandInFlight.action !== 'run_action';+ const canStart =+ !terminal &&+ !!step.action &&+ !commandInFlight &&+ !waiting &&+ !loading &&+ (step.phase === 'pending' || step.phase === 'failed');+ return (+ <section+ aria-label={step.title}+ className={`w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] ${compact ? 'p-4' : 'p-5'}`}+ >+ <div className="flex items-center gap-2 text-13 text-[var(--text-secondary)]">+ <span className="h-5 w-5 shrink-0">+ <GhostPluginIcon+ iconId={pending.ghost.id}+ iconName={pending.ghost.name}+ iconDataUrl={pending.ghost.iconDataUrl}+ size="mini"+ />+ </span>+ <span>{pending.ghost.name}</span>+ </div>+ <div+ className={`${compact ? 'mt-3' : 'mt-4'} flex items-center gap-2`}+ role="status"+ aria-live="polite"+ >+ {complete ? (+ <Check size={18} aria-hidden />+ ) : failed || expired || ended ? (+ <AlertCircle size={18} aria-hidden />+ ) : waiting || loading ? (+ <span className="inline-flex animate-spin motion-reduce:animate-none text-[var(--text-secondary)]">+ <LoaderCircle size={17} aria-hidden />+ </span>+ ) : null}+ <h2 className="text-16 font-semibold text-[var(--text-primary)]">{title}</h2>+ </div>+ {description ? (+ <p+ className={`mt-2 text-13 leading-5 ${failed ? 'text-[var(--error-fg)]' : 'text-[var(--text-secondary)]'}`}+ >+ {description}+ </p>+ ) : null}+ {instructions ? (+ <p className="mt-2 text-13 leading-5 text-[var(--text-secondary)]">{instructions}</p>+ ) : null}+ {code ? (+ <div+ className="mt-4 rounded-lg bg-[var(--surface)] px-4 py-3"+ data-plugin-oauth-device-code+ >+ <div className="flex flex-wrap items-center justify-between gap-2 text-13 text-[var(--text-secondary)]">+ <span>+ {t('newChat.pluginSetup.account.codeInstructions', { host: code.verificationHost })}+ </span>+ <span>+ {t('newChat.pluginSetup.account.remaining', {+ time: `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`,+ })}+ </span>+ </div>+ <div className="mt-2 flex items-center justify-between gap-3">+ <code+ className="min-w-0 select-all whitespace-pre-wrap break-all text-20 font-medium tracking-wider text-[var(--text-primary)]"+ aria-label={t('newChat.pluginSetup.deviceCode.label')}+ >+ {code.userCode}+ </code>+ <Button+ variant="secondary"+ className="gap-2"+ aria-label={t('newChat.pluginSetup.deviceCode.copyAgain')}+ title={t('newChat.pluginSetup.deviceCode.copyAgain')}+ disabled={!!presentation?.working}+ onClick={() => void presentation?.operate('copy')}+ >+ <Copy size={16} aria-hidden />+ {t('newChat.pluginSetup.deviceCode.copyAgain')}+ </Button>+ </div>+ </div>+ ) : null}+ {!terminal && errorMessage ? (+ <p role="alert" className="mt-3 text-13 text-[var(--error-fg)]">{errorMessage}</p>+ ) : null}+ {!terminal ? (+ <div className={`${compact ? 'mt-4' : 'mt-5'} flex flex-wrap items-center gap-2`}>+ {canReopen ? (+ <Button+ variant="secondary"+ disabled={!!presentation?.working}+ onClick={() => void presentation?.operate('reopen')}+ >+ <ExternalLink size={14} aria-hidden className="mr-2" />+ {t('newChat.pluginSetup.deviceCode.reopen')}+ </Button>+ ) : !waiting && !loading && step.action ? (+ <Button+ variant="cta"+ disabled={!canStart}+ onClick={() => onCommand(pending.requestId, 'run_action', step.action!.id)}+ >+ {expired || ended+ ? t('newChat.pluginSetup.account.reconnect')+ : failed+ ? t('newChat.pluginSetup.retry')+ : step.title}+ </Button>+ ) : null}+ <Button+ variant="secondary"+ disabled={cancelBlocked}+ onClick={() => onCommand(pending.requestId, 'cancel')}+ >+ {t(+ commandInFlight?.action === 'cancel'+ ? 'newChat.pluginSetup.cancelling'+ : 'newChat.pluginSetup.cancel',+ )}+ </Button>+ </div>+ ) : null}+ {presentation?.failed ? (+ <p role="alert" className="mt-2 text-13 text-[var(--error-fg)]">+ {t('newChat.pluginSetup.deviceCode.actionFailed')}+ </p>+ ) : null}+ </section>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx b/apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsxindex 2185f4300e..98551d86e9 100644--- a/apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx@@ -2,8 +2,13 @@ import { useState } from 'react';import { useTranslation } from 'react-i18next';import { PluginSetupPrompt } from '@/components/new-chat/PluginSetupPrompt';import { readBotAuthorizationCard } from '../../../shared/botAuthorization';-import { isRemoteSessionSticky, makerApiForSticky } from '@/lib/makerTransport';+import {+ assistRemotePluginOauth,+ isRemoteSessionSticky,+ makerApiForSticky,+} from '@/lib/makerTransport';import type { PluginSetupCommandInFlight } from '@/lib/makerChatStore';+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';/** Same composable form for Host and plugin accounts, rendered in the transcript. */export function BotAuthorizationCardView({@@ -31,36 +36,68 @@ function AuthorizationBody({return (<div className="my-2 max-w-xl"><PluginSetupPrompt- pending={card.snapshot}+ // Bot cards bind only the OAuth bridge. Do not expose private forms even+ // if a retained/newer snapshot advertises the regular setup capabilities.+ pending={+ remote+ ? { ...card.snapshot, remoteSecret: undefined, remoteConnection: undefined }+ : card.snapshot+ }compactviewerState="expanded"onViewerStateChange={() => {}}remote={remote}+ remoteDeviceId={getStickySessionDeviceId(card.sessionId) ?? undefined}commandInFlight={busy}onCommand={(requestId, action, actionId, values) => {- if (busy || (isRemoteSessionSticky(card.sessionId) && action !== 'cancel')) return;+ const remoteOauth =+ remote &&+ card.snapshot.remoteOauth &&+ action === 'run_action' &&+ actionId &&+ card.snapshot.steps.some(+ (s) => s.action?.id === actionId && s.action.kind === 'oauth_connect',+ );+ const cancelRemoteOauth =+ action === 'cancel' &&+ remote &&+ card.snapshot.remoteOauth &&+ busy?.action === 'run_action';+ if (busy && !cancelRemoteOauth) return;+ if (remote && action !== 'cancel' && !remoteOauth) {+ setFailed(true);+ return;+ }setFailed(false);- setBusy({ requestId, action, actionId });+ const pending = { requestId, action, actionId };+ setBusy(pending);const command =- action === 'submit_form' && actionId && values && !remote- ? window.electronAPI.maker.submitPluginSetupInline({+ remoteOauth && actionId+ ? assistRemotePluginOauth(card.sessionId, {+ ghostId: card.snapshot.ghost.id,requestId,actionId,expectedRevision: card.snapshot.revision,- value: values.value,})- : makerApiForSticky(card.sessionId).resolveInteraction(requestId, {- kind: 'plugin_setup',- action: action === 'cancel' ? 'cancel' : 'run_action',- ...(actionId ? { actionId } : {}),- expectedRevision: card.snapshot.revision,- });+ : action === 'submit_form' && actionId && values && !remote+ ? window.electronAPI.maker.submitPluginSetupInline({+ requestId,+ actionId,+ expectedRevision: card.snapshot.revision,+ value: values.value,+ })+ : makerApiForSticky(card.sessionId).resolveInteraction(requestId, {+ kind: 'plugin_setup',+ action: action === 'cancel' ? 'cancel' : 'run_action',+ ...(actionId ? { actionId } : {}),+ expectedRevision: card.snapshot.revision,+ });void command.then((result) => {if (result && 'accepted' in result && !result.accepted) setFailed(true);}).catch(() => setFailed(true))- .finally(() => setBusy(null));+ .finally(() => setBusy((current) => (current === pending ? null : current)));}}/>{failed ? (diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.forms.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.forms.test.tsxnew file mode 100644index 0000000000..1d4514292f--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.forms.test.tsx@@ -0,0 +1,194 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ BotAuthorizationService,+ type BotAuthorizationAdapter,+} from '../../../../main/maker-ipc/botAuthorizationService';+import { sanitizeBotAuthorizationMetaForRemote } from '../../../../main/cindy-brain/ghostSetupInteractionBridge';+import {+ readBotAuthorizationCard,+ type BotAuthorizationCard,+} from '../../../../shared/botAuthorization';+import type { GhostSetupAllowedAction } from '../../../../shared/ghost';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { __resetStickySessionOriginForTest } from '@/features/device-link/stickySessionOrigin';+import { BotAuthorizationCardView } from '../BotAuthorizationCard';++// Keep the actual Host snapshot/projection, card, shared form and transport routing.+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../../../../main/plugin-oauth/runtime', () => ({ supportsRemotePluginOauth: () => true }));+const invoke = vi.fn(async () => ({ accepted: true }));+const submit = vi.fn(async () => ({ accepted: true }));+const resolve = vi.fn(async () => ({ accepted: true }));+const assist = vi.fn(async () => ({ accepted: true }));+const services: BotAuthorizationService[] = [];+const secret: GhostSetupAllowedAction = {+ id: 'key',+ kind: 'inline_form',+ form: {+ fields: [+ {+ id: 'value',+ type: 'secret',+ label: 'API key',+ placeholder: 'API key',+ required: true,+ maxLength: 100,+ },+ ],+ },+};+const connection: GhostSetupAllowedAction = { id: 'connection', kind: 'manage_connection' };++beforeEach(() => {+ vi.clearAllMocks();+ remoteProjectsStore.clear();+ remoteProjectsStore.__resetPinnedOriginsForTest();+ __resetStickySessionOriginForTest();+ window.electronAPI = {+ maker: {+ resolveInteraction: resolve,+ submitPluginSetupInline: submit,+ assistPluginOauth: assist,+ },+ deviceLink: { invoke },+ } as unknown as typeof window.electronAPI;+});+afterEach(async () => {+ cleanup();+ for (const service of services.splice(0)) await service.dispose();+});++async function hostCard(action: GhostSetupAllowedAction, remote: boolean) {+ const stored = new Map<string, BotAuthorizationCard>();+ const adapter: BotAuthorizationAdapter = {+ identity: { id: 'plugin', name: 'Plugin' },+ assess: async () => ({+ state: 'required',+ revision: 1,+ groups: [+ {+ id: 'account',+ mode: 'any_of',+ items: [+ {+ ref: 'account',+ kind:+ action.kind === 'inline_form'+ ? 'secret'+ : action.kind === 'manage_connection'+ ? 'connection'+ : 'oauth',+ label: 'Account',+ state: 'missing',+ actions: [action],+ },+ ],+ },+ ],+ }),+ subscribe: () => () => {},+ execute: vi.fn(async () => ({ ok: true as const })),+ };+ const service = new BotAuthorizationService({+ adapter: async () => adapter,+ save: async (card) => {+ stored.set(card.snapshot.requestId, structuredClone(card));+ },+ load: async (id) => stored.get(id) ?? null,+ findPending: async () => null,+ resume: async () => {},+ warn: vi.fn(),+ openExternal: vi.fn(async () => {}),+ });+ services.push(service);+ await service.request('session', { kind: 'plugin', id: 'plugin' });+ const card = [...stored.values()][0]!;+ if (!remote) return card;+ remoteProjectsStore.pinSessionOrigin('owner-device', 'session');+ return readBotAuthorizationCard(+ sanitizeBotAuthorizationMetaForRemote({ botAuthorization: card }).botAuthorization,+ )!;+}++it.each([false, true])(+ 'does not accept secret input on remote Bot cards (unexpected capability=%s)',+ async (extra) => {+ const card = await hostCard(secret, true);+ expect(card.snapshot).not.toHaveProperty('remoteSecret');+ const snapshot = { ...card.snapshot, ...(extra ? { remoteSecret: true } : {}) };+ render(<BotAuthorizationCardView sessionId="session" data={{ ...card, snapshot }} />);+ expect((screen.getByPlaceholderText('API key') as HTMLInputElement).disabled).toBe(true);+ const save = screen.getByRole('button', { name: 'newChat.pluginSetup.saveConfiguration' });+ expect((save as HTMLButtonElement).disabled).toBe(true);+ expect(screen.getByText('newChat.pluginSetup.completeOnDesktop')).toBeTruthy();+ fireEvent.click(save);+ expect(submit).not.toHaveBeenCalled();+ expect(invoke).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ },+);++it.each([false, true])(+ 'does not expose an unwired remote Bot connection form (unexpected capability=%s)',+ async (extra) => {+ const card = await hostCard(connection, true);+ expect(card.snapshot).not.toHaveProperty('remoteConnection');+ const snapshot = { ...card.snapshot, ...(extra ? { remoteConnection: true } : {}) };+ const { container } = render(+ <BotAuthorizationCardView sessionId="session" data={{ ...card, snapshot }} />,+ );+ expect(container.querySelector('input')).toBeNull();+ const configure = screen.getByRole('button', {+ name: 'newChat.pluginSetup.action.manage_connection',+ });+ expect((configure as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(configure);+ expect(invoke).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'newChat.pluginSetup.cancel' }));+ await waitFor(() =>+ expect(invoke).toHaveBeenCalledWith('owner-device', 'maker:resolve-interaction', [+ card.snapshot.requestId,+ { kind: 'plugin_setup', action: 'cancel', expectedRevision: card.snapshot.revision },+ ]),+ );+ },+);++it('keeps local Bot secrets on the private local submit path', async () => {+ const card = await hostCard(secret, false);+ render(<BotAuthorizationCardView sessionId="session" data={{ ...card }} />);+ const input = screen.getByPlaceholderText('API key') as HTMLInputElement;+ expect(input.disabled).toBe(false);+ fireEvent.change(input, { target: { value: 'synthetic-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'newChat.pluginSetup.saveConfiguration' }));+ await waitFor(() =>+ expect(submit).toHaveBeenCalledWith({+ requestId: card.snapshot.requestId,+ actionId: 'key',+ expectedRevision: card.snapshot.revision,+ value: 'synthetic-key',+ }),+ );+ expect(invoke).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+});++it('keeps the remote OAuth action on the dedicated bridge', async () => {+ const card = await hostCard({ id: 'connect', kind: 'oauth_connect' }, true);+ expect(card.snapshot.remoteOauth).toBe(true);+ render(<BotAuthorizationCardView sessionId="session" data={{ ...card }} />);+ fireEvent.click(screen.getByRole('button', { name: card.snapshot.steps[0].title }));+ await waitFor(() =>+ expect(assist).toHaveBeenCalledWith({+ deviceId: 'owner-device',+ ghostId: 'plugin',+ requestId: card.snapshot.requestId,+ actionId: 'connect',+ expectedRevision: card.snapshot.revision,+ }),+ );+ expect(invoke).not.toHaveBeenCalled();+ expect(submit).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.test.tsxindex e697fe2426..62b27ff0ad 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotAuthorizationCard.test.tsx@@ -10,13 +10,15 @@ import type { PluginSetupPrompt } from '@/components/new-chat/PluginSetupPrompt'vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/components/new-chat/PluginSetupPrompt', () => ({PluginSetupPrompt: ({ onCommand, commandInFlight }: ComponentProps<typeof PluginSetupPrompt>) => <>- <button disabled={!!commandInFlight} onClick={() => onCommand('request', 'cancel')}>Cancel</button>+ <button disabled={commandInFlight?.action === 'cancel'} onClick={() => onCommand('request', 'cancel')}>Cancel</button>+ <button disabled={!!commandInFlight} onClick={() => onCommand('request', 'run_action', 'connect')}>Connect</button><button disabled={!!commandInFlight} onClick={() => onCommand('request', 'submit_form', 'key', { value: 'fake-secret' })}>Submit</button></>,}));const local = vi.fn(async () => ({ accepted: true }));const submit = vi.fn(async () => ({ accepted: true }));const invoke = vi.fn(async () => ({ accepted: true }));+const assist = vi.fn(async () => ({ accepted: true }));const card = { v: 1, sessionId: 'session', createdAt: 1, target: { kind: 'plugin', id: 'p' },snapshot: { kind: 'plugin_setup', requestId: 'request', revision: 3, ghost: { id: 'p', name: 'Plugin' }, steps: [] } };beforeEach(() => {@@ -24,11 +26,35 @@ beforeEach(() => {remoteProjectsStore.__resetPinnedOriginsForTest();__resetStickySessionOriginForTest();vi.clearAllMocks();- window.electronAPI = { maker: { resolveInteraction: local, submitPluginSetupInline: submit },+ window.electronAPI = { maker: { resolveInteraction: local, submitPluginSetupInline: submit, assistPluginOauth: assist },deviceLink: { invoke } } as unknown as typeof window.electronAPI;});afterEach(cleanup);+it('sends only card/target IDs to local Main and can cancel while its bridge is pending', async () => {+ remoteProjectsStore.pinSessionOrigin('owner-device', 'session');+ let finish!: (value: { accepted: boolean }) => void;+ assist.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ render(<BotAuthorizationCardView sessionId="session" data={{ ...card, snapshot: {+ ...card.snapshot, remoteOauth: true, steps: [{+ id: 'account', groupId: 'account', groupMode: 'any_of', title: 'Connect', description: '', phase: 'pending',+ action: { id: 'connect', kind: 'oauth_connect' },+ }],+ } }} />);+ fireEvent.click(screen.getByText('Connect'));+ await waitFor(() => expect(assist).toHaveBeenCalledWith({+ deviceId: 'owner-device', ghostId: 'p', requestId: 'request', actionId: 'connect', expectedRevision: 3,+ }));+ expect(invoke).not.toHaveBeenCalled();+ fireEvent.click(screen.getByText('Cancel'));+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('owner-device', 'maker:resolve-interaction', [+ 'request', { kind: 'plugin_setup', action: 'cancel', expectedRevision: 3 },+ ]));+ finish({ accepted: false });+ await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());+ expect(submit).not.toHaveBeenCalled();+});+it.each([false, true])('routes remote cancellation to its owner, including reconnect=%s', async (reconnect) => {remoteProjectsStore.pinSessionOrigin('owner-device', 'session');render(<BotAuthorizationCardView sessionId="session" data={card} />);@@ -50,6 +76,7 @@ it('rejects remote secret submissions at the callback boundary', () => {expect(submit).not.toHaveBeenCalled();expect(local).not.toHaveBeenCalled();expect(invoke).not.toHaveBeenCalled();+ expect(screen.getByRole('alert').textContent).toBe('newChat.pluginSetup.error.ACTION_FAILED');});it('keeps local cancellation and secret submission on the local maker', async () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 38fe74ae65..4ab8b2a420 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -1740,6 +1740,7 @@ export function CCAgentSessionView({pendingPluginSetup,pluginSetupViewerState,pluginSetupCommandInFlight,+ pluginSetupCommandError,setPluginSetupViewerState,respondToPluginSetup,askUserViewerState,@@ -5186,8 +5187,10 @@ export function CCAgentSessionView({) : pendingPluginSetup ? (<PluginSetupPromptpending={pendingPluginSetup}+ remoteDeviceId={remoteDeviceId ?? undefined}viewerState={pluginSetupViewerState}commandInFlight={pluginSetupCommandInFlight}+ commandError={pluginSetupCommandError}remote={!!remoteDeviceId}onViewerStateChange={setPluginSetupViewerState}onCommand={respondToPluginSetup}diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.tsindex a218615259..c6f2d25181 100644--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts@@ -40,6 +40,7 @@ import {type PendingAskUser,type PendingPluginSetup,type PluginSetupCommandInFlight,+ type PluginSetupCommandError,type PluginSetupInlineFormValues,type PluginSetupViewerState,type PendingIssueConfirm,@@ -219,6 +220,7 @@ interface UseCCAgentChatReturn {pendingPluginSetup: PendingPluginSetup | null;pluginSetupViewerState: PluginSetupViewerState;pluginSetupCommandInFlight: PluginSetupCommandInFlight | null;+ pluginSetupCommandError: PluginSetupCommandError | null;setPluginSetupViewerState: (next: PluginSetupViewerState) => void;respondToPluginSetup: (requestId: string,@@ -884,6 +886,7 @@ export function useCCAgentChat(pendingPluginSetup: lightState.pendingPluginSetup,pluginSetupViewerState: lightState.pluginSetupViewerState,pluginSetupCommandInFlight: lightState.pluginSetupCommandInFlight,+ pluginSetupCommandError: lightState.pluginSetupCommandError,setPluginSetupViewerState,respondToPluginSetup,askUserViewerState: lightState.askUserViewerState,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a9a4486fc3..9fc21a1e72 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8025,6 +8025,23 @@"stop": "Stop generating"},"pluginSetup": {+ "account": {+ "opening": "Opening authorization page",+ "connected": "Account connected",+ "cancelled": "Connection cancelled",+ "expired": "Authorization expired",+ "ended": "Authorization ended",+ "failed": "Could not connect account",+ "waiting": "Waiting for browser authorization",+ "verifying": "Confirming authorization",+ "continue": "The task will continue.",+ "reconnectHint": "Reconnect to continue authorization.",+ "waitingHint": "Complete authorization in your browser. The task will then continue automatically.",+ "remoteHint": "Authorize in this computer’s browser to let Cindy on the remote device use this account.",+ "codeInstructions": "Enter the code at {{host}}",+ "remaining": "Expires in {{time}}",+ "reconnect": "Reconnect"+ },"reopen": "Reopen","title": "{{name}} Settings","assessmentReadFailed": "Couldn't read the plugin setup status.",@@ -8033,6 +8050,16 @@"chooseOne": "Choose one setup method","restoreAria": "Restore {{name}} settings","minimizeAria": "Minimize {{name}} settings",+ "remoteOauthHint": "Authorize in this computer’s browser to connect the account on the current remote device. Complete other settings on the remote device.",+ "connection": {+ "host": "Instance address",+ "hostHint": "Enter the service’s HTTPS address, using its default port.",+ "hostInvalid": "Enter one HTTPS domain without a path, query, or custom port.",+ "token": "Access token",+ "tokenInvalid": "Enter a valid access token (up to 4096 characters).",+ "hint": "Saved only for this plugin on the current remote device. The token is sent only to the address you enter and is not included in chat history."+ },+ "remoteSecretHint": "Enter the key here to save it only for this plugin on the current remote device. It will not appear in chat history.","completeOnDesktop": "Complete this setup on the controlled desktop. This card will update automatically.","cancel": "Cancel","cancelling": "Cancelling…",@@ -8040,6 +8067,8 @@"saveConfiguration": "Save Configuration","saving": "Saving…","error": {+ "REMOTE_UNSUPPORTED": "Cindy on the remote device does not support this authorization method yet. Update it and try again.",+ "REMOTE_FAILED": "Could not start remote authorization. Check that both devices are online and try again.","ACTION_FAILED": "Couldn't complete this setup action. Try again.","ACTION_STALE": "This setup changed. Choose the setup action again.","AUTH_CANCELLED": "Authorization was cancelled. Authorize the account again when ready.",@@ -8093,7 +8122,20 @@"inlineSecretStoreFailed": "Failed to save credential","targetNotFound": "The target plugin was uninstalled or is currently unavailable","targetDisabled": "The target plugin has been disabled",- "targetDisabledInWorkdir": "The user has disabled this plugin in the current working directory; do not retry."+ "targetDisabledInWorkdir": "The user has disabled this plugin in the current working directory; do not retry.",+ "deviceCode": {+ "label": "Device Code",+ "copied": "Device code copied",+ "copiedHint": "Device code copied automatically. You can copy it again here.",+ "instructions": "After choosing your account on {{host}}, paste this code into the code field and continue authorizing.",+ "copyAgain": "Copy Code Again",+ "reopen": "Reopen Authorization Page",+ "remaining": "Waiting for authorization · {{time}} remaining for this attempt",+ "completed": "Account connected. Device code cleared.",+ "expired": "This authorization attempt expired. Start a new connection in the task to get a new code.",+ "ended": "This authorization attempt ended. Start a new connection in the task.",+ "actionFailed": "The action did not complete. Retry, or start a new connection if authorization has ended."+ }},"createAgent": {"quickStart": "Quick start",@@ -13515,5 +13557,9 @@"presetLife": "Life","presetIdeas": "Ideas","presetReference": "Reference"+ },+ "pluginDeviceAuthorization": {+ "title": "Authorize Plugin Login",+ "description": "Open {{host}} on this device to authorize the plugin running this task. Its credentials stay on the originating device."}}diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2e0c6e2fdf..a2166eb83a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8023,6 +8023,23 @@"stop": "生成を停止"},"pluginSetup": {+ "account": {+ "opening": "認証ページを開いています",+ "connected": "アカウント接続済み",+ "cancelled": "接続をキャンセルしました",+ "expired": "認証の有効期限が切れました",+ "ended": "認証が終了しました",+ "failed": "アカウントに接続できませんでした",+ "waiting": "ブラウザーでの認証を待っています",+ "verifying": "認証結果を確認中",+ "continue": "タスクを続行します。",+ "reconnectHint": "再接続して認証を続けてください。",+ "waitingHint": "ブラウザーで認証を完了すると、タスクが自動的に再開します。",+ "remoteHint": "このコンピューターのブラウザーで認証し、リモートデバイスの Cindy にアカウントの使用を許可します。",+ "codeInstructions": "{{host}} でコードを入力",+ "remaining": "有効期限まで {{time}}",+ "reconnect": "再接続"+ },"reopen": "もう一度開く","title": "{{name}} の設定","assessmentReadFailed": "プラグインの設定状態を読み取れませんでした。",@@ -8031,6 +8048,16 @@"chooseOne": "設定方法を1つ選択してください","restoreAria": "{{name}} の設定を展開","minimizeAria": "{{name}} の設定を折りたたむ",+ "remoteOauthHint": "このコンピューターのブラウザーで認証すると、現在のリモートデバイスにアカウントが接続されます。その他の設定はリモートデバイスで行ってください。",+ "connection": {+ "host": "インスタンスのアドレス",+ "hostHint": "サービスの HTTPS アドレスを標準ポートで入力してください。",+ "hostInvalid": "パス、クエリ、独自ポートを含まない HTTPS ドメインを入力してください。",+ "token": "アクセストークン",+ "tokenInvalid": "有効なアクセストークンを入力してください(4096文字以内)。",+ "hint": "現在のリモートデバイスのこのプラグインにのみ保存します。トークンは入力したアドレスにのみ送信され、チャット履歴には残りません。"+ },+ "remoteSecretHint": "ここに入力したキーは、現在のリモートデバイスのこのプラグインにのみ保存されます。チャット履歴には残りません。","completeOnDesktop": "リモートのパソコンで設定を完了してください。このカードは自動的に更新されます。","cancel": "キャンセル","cancelling": "キャンセル中…",@@ -8038,6 +8065,8 @@"saveConfiguration": "設定を保存","saving": "保存中…","error": {+ "REMOTE_UNSUPPORTED": "リモートデバイスの Cindy はこの認証方法にまだ対応していません。そのデバイスの Cindy を更新して再試行してください。",+ "REMOTE_FAILED": "リモート認証を開始できませんでした。両方のデバイスがオンラインであることを確認して再試行してください。","ACTION_FAILED": "設定操作を完了できませんでした。もう一度お試しください。","ACTION_STALE": "設定内容が更新されました。設定操作を選び直してください。","AUTH_CANCELLED": "認証がキャンセルされました。必要に応じてもう一度認証してください。",@@ -8091,7 +8120,20 @@"inlineSecretStoreFailed": "認証情報の保存に失敗しました","targetNotFound": "対象プラグインがアンインストールされたか現在利用不可です","targetDisabled": "対象プラグインが無効化されています",- "targetDisabledInWorkdir": "ユーザーが現在のワーキングディレクトリでこのプラグインを無効にしています。リトライしないでください。"+ "targetDisabledInWorkdir": "ユーザーが現在のワーキングディレクトリでこのプラグインを無効にしています。リトライしないでください。",+ "deviceCode": {+ "label": "デバイスコード",+ "copied": "デバイスコードをコピーしました",+ "copiedHint": "デバイスコードを自動でコピーしました。ここから再度コピーできます。",+ "instructions": "{{host}} でアカウントを選択した後、このコードを入力欄に貼り付けて認証を続けてください。",+ "copyAgain": "コードを再度コピー",+ "reopen": "認証ページを再度開く",+ "remaining": "認証を待っています… この操作の残り時間 {{time}}",+ "completed": "アカウントを接続し、デバイスコードを消去しました",+ "expired": "認証の有効期限が切れました。タスクから再度接続を開始して新しいコードを取得してください。",+ "ended": "今回の認証は終了しました。タスクから再度接続を開始してください。",+ "actionFailed": "操作を完了できませんでした。再試行してください。認証が終了している場合は、再度接続を開始してください。"+ }},"createAgent": {"quickStart": "クイックスタート",@@ -13496,5 +13538,9 @@"presetLife": "生活","presetIdeas": "アイデア","presetReference": "資料"+ },+ "pluginDeviceAuthorization": {+ "title": "プラグインのログインを認証",+ "description": "このデバイスで {{host}} を開き、このタスクを実行するプラグインを認証します。認証情報は認証を開始したデバイスに保存されます。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b03416a1a9..d185e21e6c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8023,6 +8023,23 @@"stop": "생성 중지"},"pluginSetup": {+ "account": {+ "opening": "인증 페이지 여는 중",+ "connected": "계정 연결됨",+ "cancelled": "연결 취소됨",+ "expired": "인증 시간이 만료되었습니다",+ "ended": "인증이 종료되었습니다",+ "failed": "계정에 연결하지 못했습니다",+ "waiting": "브라우저 인증 대기 중",+ "verifying": "인증 결과 확인 중",+ "continue": "작업이 계속됩니다.",+ "reconnectHint": "다시 연결하여 인증을 계속하세요.",+ "waitingHint": "브라우저에서 인증을 완료하면 작업이 자동으로 계속됩니다.",+ "remoteHint": "이 컴퓨터의 브라우저에서 인증하여 원격 기기의 Cindy가 이 계정을 사용하도록 허용합니다.",+ "codeInstructions": "{{host}}에서 코드 입력",+ "remaining": "{{time}} 후 만료",+ "reconnect": "다시 연결"+ },"reopen": "다시 열기","title": "{{name}} 설정","assessmentReadFailed": "플러그인 설정 상태를 읽을 수 없습니다.",@@ -8031,6 +8048,16 @@"chooseOne": "설정 방법을 하나 선택하세요","restoreAria": "{{name}} 설정 펼치기","minimizeAria": "{{name}} 설정 접기",+ "remoteOauthHint": "이 컴퓨터의 브라우저에서 인증하면 현재 원격 기기에 계정이 연결됩니다. 다른 설정은 원격 기기에서 완료하세요.",+ "connection": {+ "host": "인스턴스 주소",+ "hostHint": "서비스의 HTTPS 주소를 기본 포트로 입력하세요.",+ "hostInvalid": "경로, 쿼리 또는 사용자 지정 포트가 없는 HTTPS 도메인을 입력하세요.",+ "token": "액세스 토큰",+ "tokenInvalid": "올바른 액세스 토큰을 입력하세요(최대 4096자).",+ "hint": "현재 원격 기기의 이 플러그인에만 저장됩니다. 토큰은 입력한 주소에만 전송되며 채팅 기록에 남지 않습니다."+ },+ "remoteSecretHint": "여기에 입력한 키는 현재 원격 기기의 이 플러그인에만 저장됩니다. 채팅 기록에는 남지 않습니다.","completeOnDesktop": "원격 컴퓨터에서 설정을 완료하세요. 이 카드는 자동으로 업데이트됩니다.","cancel": "취소","cancelling": "취소 중…",@@ -8038,6 +8065,8 @@"saveConfiguration": "설정 저장","saving": "저장 중…","error": {+ "REMOTE_UNSUPPORTED": "원격 기기의 Cindy가 아직 이 인증 방식을 지원하지 않습니다. 해당 기기의 Cindy를 업데이트한 후 다시 시도하세요.",+ "REMOTE_FAILED": "원격 인증을 시작하지 못했습니다. 두 기기가 모두 온라인인지 확인한 후 다시 시도하세요.","ACTION_FAILED": "설정 작업을 완료할 수 없습니다. 다시 시도하세요.","ACTION_STALE": "설정 내용이 변경되었습니다. 설정 작업을 다시 선택하세요.","AUTH_CANCELLED": "인증이 취소되었습니다. 필요한 경우 다시 인증하세요.",@@ -8091,7 +8120,20 @@"inlineSecretStoreFailed": "자격 증명 저장에 실패했습니다","targetNotFound": "대상 플러그인이 제거되었거나 현재 사용할 수 없습니다","targetDisabled": "대상 플러그인이 비활성화되었습니다",- "targetDisabledInWorkdir": "사용자가 현재 작업 디렉토리에서 이 플러그인을 비활성화했습니다. 재시도하지 마세요."+ "targetDisabledInWorkdir": "사용자가 현재 작업 디렉토리에서 이 플러그인을 비활성화했습니다. 재시도하지 마세요.",+ "deviceCode": {+ "label": "기기 코드",+ "copied": "기기 코드를 복사했습니다",+ "copiedHint": "기기 코드를 자동으로 복사했습니다. 여기에서 다시 복사할 수 있습니다.",+ "instructions": "{{host}}에서 계정을 선택한 후 이 코드를 입력란에 붙여넣고 인증을 계속하세요.",+ "copyAgain": "코드 다시 복사",+ "reopen": "인증 페이지 다시 열기",+ "remaining": "인증을 기다리는 중… 이번 시도 남은 시간 {{time}}",+ "completed": "계정이 연결되어 기기 코드를 지웠습니다",+ "expired": "이번 인증이 만료되었습니다. 작업에서 연결을 다시 시작하여 새 코드를 받으세요.",+ "ended": "이번 인증이 종료되었습니다. 작업에서 연결을 다시 시작하세요.",+ "actionFailed": "작업을 완료하지 못했습니다. 다시 시도하세요. 인증이 종료되었다면 연결을 다시 시작하세요."+ }},"createAgent": {"quickStart": "빠른 시작",@@ -13496,5 +13538,9 @@"presetLife": "생활","presetIdeas": "아이디어","presetReference": "자료"+ },+ "pluginDeviceAuthorization": {+ "title": "플러그인 로그인 인증",+ "description": "이 기기에서 {{host}}를 열어 이 작업을 실행하는 플러그인을 인증하세요. 인증 정보는 인증을 시작한 기기에 저장됩니다."}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 6e54c3ab01..e569b96690 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8023,6 +8023,23 @@"stop": "停止生成"},"pluginSetup": {+ "account": {+ "opening": "正在打开授权页",+ "connected": "账号已连接",+ "cancelled": "已取消连接",+ "expired": "本次授权已过期",+ "ended": "本次授权已结束",+ "failed": "未能连接账号",+ "waiting": "等待浏览器授权",+ "verifying": "正在确认授权结果",+ "continue": "任务将继续。",+ "reconnectHint": "重新连接以继续授权。",+ "waitingHint": "请在浏览器中完成授权,完成后任务会自动继续。",+ "remoteHint": "在本机浏览器中授权,账号将供远程设备上的 Cindy 使用。",+ "codeInstructions": "在 {{host}} 输入验证码",+ "remaining": "{{time}} 后过期",+ "reconnect": "重新连接"+ },"reopen": "重新打开","title": "{{name}} 设置","assessmentReadFailed": "无法读取插件配置状态。",@@ -8031,6 +8048,16 @@"chooseOne": "选择一种配置方式","restoreAria": "展开 {{name}} 设置","minimizeAria": "收起 {{name}} 设置",+ "remoteOauthHint": "在这台电脑的浏览器中授权,账号将连接到当前远程设备。其他设置仍需在远程设备上完成。",+ "connection": {+ "host": "实例地址",+ "hostHint": "填写服务的 HTTPS 地址,使用默认端口。",+ "hostInvalid": "请填写单个 HTTPS 域名,不带路径、查询参数或自定义端口。",+ "token": "访问令牌",+ "tokenInvalid": "请填写有效的访问令牌,最多 4096 个字符。",+ "hint": "仅保存到当前远程设备的这个插件。令牌只用于你填写的地址,不进入对话记录。"+ },+ "remoteSecretHint": "在此填写,仅保存到当前远程设备的这个插件。内容不会进入对话记录。","completeOnDesktop": "请在远程电脑完成设置,本卡片会自动更新状态。","cancel": "取消","cancelling": "正在取消…",@@ -8038,6 +8065,8 @@"saveConfiguration": "保存配置","saving": "保存中…","error": {+ "REMOTE_UNSUPPORTED": "远程设备上的 Cindy 尚不支持此授权方式,请更新该设备的 Cindy 后重试",+ "REMOTE_FAILED": "未能发起远程授权,请确认两端在线后重试","ACTION_FAILED": "设置操作未完成,请重试。","ACTION_STALE": "设置已更新,请重新选择配置操作。","AUTH_CANCELLED": "授权已取消,您可以重新授权。",@@ -8091,7 +8120,20 @@"inlineSecretStoreFailed": "凭证保存失败","targetNotFound": "目标插件已卸载或当前不可用","targetDisabled": "目标插件已被停用",- "targetDisabledInWorkdir": "用户已在当前工作目录停用该插件;不要重试。"+ "targetDisabledInWorkdir": "用户已在当前工作目录停用该插件;不要重试。",+ "deviceCode": {+ "label": "设备验证码",+ "copied": "验证码已复制",+ "copiedHint": "验证码已自动复制,也可在这里再次复制",+ "instructions": "在 {{host}} 选择账号后,将此 验证码粘贴到输入框,再继续授权。",+ "copyAgain": "再次复制验证码",+ "reopen": "重新打开授权页",+ "remaining": "等待授权,本次操作剩余 {{time}}",+ "completed": "账号已连接,验证码已清除",+ "expired": "本次授权已过期,请在任务中重新发起连接获取新码",+ "ended": "本次授权已结束,请在任务中重新发起连接",+ "actionFailed": "操作未完成,请重试;若授权已结束,请重新发起连接"+ }},"createAgent": {"quickStart": "快速开始",@@ -13496,5 +13538,9 @@"presetLife": "生活","presetIdeas": "灵感","presetReference": "资料"+ },+ "pluginDeviceAuthorization": {+ "title": "授权插件登录",+ "description": "在这台设备打开 {{host}},为执行此任务的插件授权。凭据保存在发起授权的设备上。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex bf71ee846e..ae6193083b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8023,6 +8023,23 @@"stop": "停止生成"},"pluginSetup": {+ "account": {+ "opening": "正在開啟授權頁",+ "connected": "帳號已連接",+ "cancelled": "已取消連接",+ "expired": "本次授權已過期",+ "ended": "本次授權已結束",+ "failed": "無法連接帳號",+ "waiting": "等待瀏覽器授權",+ "verifying": "正在確認授權結果",+ "continue": "任務將繼續。",+ "reconnectHint": "重新連接以繼續授權。",+ "waitingHint": "請在瀏覽器中完成授權,完成後任務會自動繼續。",+ "remoteHint": "在本機瀏覽器中授權,帳號將供遠端裝置上的 Cindy 使用。",+ "codeInstructions": "在 {{host}} 輸入驗證碼",+ "remaining": "{{time}} 後過期",+ "reconnect": "重新連接"+ },"reopen": "重新開啟","title": "{{name}} 設定","assessmentReadFailed": "無法讀取插件配置狀態。",@@ -8031,6 +8048,16 @@"chooseOne": "選擇一種配置方式","restoreAria": "展開 {{name}} 設定","minimizeAria": "收起 {{name}} 設定",+ "remoteOauthHint": "在這台電腦的瀏覽器中授權,帳號將連接到目前的遠端裝置。其他設定仍需在遠端裝置上完成。",+ "connection": {+ "host": "執行個體地址",+ "hostHint": "填寫服務的 HTTPS 地址,使用預設連接埠。",+ "hostInvalid": "請填寫單個 HTTPS 網域,不含路徑、查詢參數或自訂連接埠。",+ "token": "存取權杖",+ "tokenInvalid": "請填寫有效的存取權杖,最多 4096 個字元。",+ "hint": "僅儲存到目前遠端裝置的這個插件。權杖僅用於你填寫的地址,不會進入對話記錄。"+ },+ "remoteSecretHint": "在此填寫,僅儲存到目前遠端裝置的這個插件。內容不會進入對話記錄。","completeOnDesktop": "請在遠端電腦完成設定,本卡片會自動更新狀態。","cancel": "取消","cancelling": "正在取消…",@@ -8038,6 +8065,8 @@"saveConfiguration": "儲存配置","saving": "儲存中…","error": {+ "REMOTE_UNSUPPORTED": "遠端裝置上的 Cindy 尚不支援此授權方式,請更新該裝置的 Cindy 後重試",+ "REMOTE_FAILED": "未能發起遠端授權,請確認兩端上線後重試","ACTION_FAILED": "設定操作未完成,請重試。","ACTION_STALE": "設定已更新,請重新選擇配置操作。","AUTH_CANCELLED": "授權已取消,您可以重新授權。",@@ -8091,7 +8120,20 @@"inlineSecretStoreFailed": "憑證儲存失敗","targetNotFound": "目標插件已解除安裝或當前不可用","targetDisabled": "目標插件已被停用",- "targetDisabledInWorkdir": "使用者已在當前工作目錄停用該插件;不要重試。"+ "targetDisabledInWorkdir": "使用者已在當前工作目錄停用該插件;不要重試。",+ "deviceCode": {+ "label": "裝置驗證碼",+ "copied": "驗證碼已複製",+ "copiedHint": "驗證碼已自動複製,也可在這裡再次複製",+ "instructions": "在 {{host}} 選擇帳號後,將此 驗證碼貼到輸入框,再繼續授權。",+ "copyAgain": "再次複製驗證碼",+ "reopen": "重新開啟授權頁",+ "remaining": "等待授權,本次操作剩餘 {{time}}",+ "completed": "帳號已連接,驗證碼已清除",+ "expired": "本次授權已過期,請在任務中重新發起連接以取得新碼",+ "ended": "本次授權已結束,請在任務中重新發起連接",+ "actionFailed": "操作未完成,請重試;若授權已結束,請重新發起連接"+ }},"createAgent": {"quickStart": "快速開始",@@ -13496,5 +13538,9 @@"presetLife": "生活","presetIdeas": "靈感","presetReference": "資料"+ },+ "pluginDeviceAuthorization": {+ "title": "授權插件登入",+ "description": "在這台裝置開啟 {{host}},為執行此任務的插件授權。憑證保存在發起授權的裝置上。"}}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 0e1091904b..827e486a0d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,3 +1,5 @@+import { remotePluginSetupErrorCode, type PluginSetupCommandError } from './pluginSetupCommandError';+export type { PluginSetupCommandError } from './pluginSetupCommandError';import { emitTaskTagCatalog } from '@/features/task-tags/taskTagEvents';import { normalizeTaskTags } from '@cindy/maker-shared';import type { ImMessageSource } from '../../shared/imMessageSource';@@ -6,6 +8,8 @@ import { readBotAuthorizationCard } from '../../shared/botAuthorization';import { applyCindyMakeCardAttention } from './cindyMakeAttention';import { confirmRemoteUsers, reserveRemoteUser } from './remoteUserHandoff';import { readRemoteHistoryCache, remoteHistoryCacheWriter } from './remoteHistoryCache';+import { createPluginSecretPresentation, createPluginConnectionPresentation } from '../../shared/pluginOauth';+import { parsePluginConnectionInput } from '@cindy/device-link';/*** makerChatStore — Module-level store for Maker chat (Claude / Codex), sharded by sessionId.* ---------------------------------------------------------------------------@@ -112,6 +116,9 @@ import * as sessionService from '@/lib/sessionService';// device-link 透明传输:远程(被控设备)会话的操作/读取走隧道,本地会话零变化。import {makerApiFor,+ assistRemotePluginOauth,+ submitRemotePluginSecret,+ submitRemotePluginConnection,makerApiForDevice,getSessionFor,listMessagesFor,@@ -728,6 +735,9 @@ export type PluginSetupAction = GhostSetupAllowedAction;type PluginSetupInlineFormAction = Extract<GhostSetupAllowedAction, { kind: 'inline_form' }>;export interface PendingPluginSetup {+ remoteOauth?: true;+ remoteSecret?: true;+ remoteConnection?: true;reopenActionId?: string;requestId: string;revision: number;@@ -778,6 +788,7 @@ export interface PluginSetupCommandInFlight {export interface PluginSetupInlineFormValues {value: string;+ host?: string;}/**@@ -2545,6 +2556,7 @@ export interface SessionChatState {pluginSetupViewerState: PluginSetupViewerState;/** Prevents duplicate commands until Main publishes a newer snapshot/dismissal. */pluginSetupCommandInFlight: PluginSetupCommandInFlight | null;+ pluginSetupCommandError: PluginSetupCommandError | null;/*** F-AUQ-MIN-1: AskUserQuestion viewer display state. Only meaningful while* pendingAskUser != null. Reset to 'expanded' every time a new@@ -2770,6 +2782,7 @@ export type SessionChatLightState = Pick<| 'pendingPluginSetup'| 'pluginSetupViewerState'| 'pluginSetupCommandInFlight'+ | 'pluginSetupCommandError'| 'askUserViewerState'| 'askUserDraft'| 'pendingPlanReview'@@ -2841,6 +2854,7 @@ function createInitialState(): SessionChatState {pendingPluginSetupQueue: [],pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,askUserViewerState: 'expanded',askUserDraft: null,pendingPlanReview: null,@@ -2923,6 +2937,7 @@ export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({pendingPluginSetupQueue: [],pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,askUserViewerState: 'expanded',askUserDraft: null,pendingPlanReview: null,@@ -6301,6 +6316,7 @@ export function handleStreamEvent(pendingPluginSetupQueue: remainingSetups,pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,};}const queuedSetupIndex = state.pendingPluginSetupQueue.findIndex(@@ -6710,6 +6726,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatStatependingPluginSetupQueue: [],pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,askUserViewerState: 'expanded',askUserDraft: null,pendingPlanReview: null,@@ -7434,6 +7451,9 @@ function parsePluginSetupInlineFormAction(/** Strict renderer boundary parser: unknown push data never reaches the card. */export function parsePendingPluginSetup(request: {+ remoteOauth?: unknown;+ remoteSecret?: unknown;+ remoteConnection?: unknown;requestId?: unknown;revision?: unknown;terminal?: unknown;@@ -7549,6 +7569,9 @@ export function parsePendingPluginSetup(request: {return {requestId: request.requestId,revision: request.revision,+ ...(request.remoteOauth === true ? { remoteOauth: true as const } : {}),+ ...(request.remoteSecret === true ? { remoteSecret: true as const } : {}),+ ...(request.remoteConnection === true ? { remoteConnection: true as const } : {}),...(request.terminal === true ? { terminal: true as const } : {}),ghost: {id: ghost.id,@@ -8126,6 +8149,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {pendingPluginSetup: parsed,pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,};}if (current.requestId === parsed.requestId) {@@ -8135,6 +8159,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {...s,pendingPluginSetup: parsed,pluginSetupCommandInFlight: advanced ? null : s.pluginSetupCommandInFlight,+ pluginSetupCommandError: advanced ? null : s.pluginSetupCommandError,};}@@ -9344,6 +9369,7 @@ function selectLightState(state: SessionChatState): SessionChatLightState {pendingPluginSetup: state.pendingPluginSetup,pluginSetupViewerState: state.pluginSetupViewerState,pluginSetupCommandInFlight: state.pluginSetupCommandInFlight,+ pluginSetupCommandError: state.pluginSetupCommandError,askUserViewerState: state.askUserViewerState,askUserDraft: state.askUserDraft,pendingPlanReview: state.pendingPlanReview,@@ -9392,6 +9418,7 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): ba.pendingPluginSetup === b.pendingPluginSetup &&a.pluginSetupViewerState === b.pluginSetupViewerState &&a.pluginSetupCommandInFlight === b.pluginSetupCommandInFlight &&+ a.pluginSetupCommandError === b.pluginSetupCommandError &&a.askUserViewerState === b.askUserViewerState &&a.askUserDraft === b.askUserDraft &&a.pendingPlanReview === b.pendingPlanReview &&@@ -9943,6 +9970,7 @@ function reconcilePendingInteractions(pendingPluginSetupQueue: survivingQueue,pluginSetupViewerState: currentChanged ? 'expanded' : state.pluginSetupViewerState,pluginSetupCommandInFlight: nextCommand,+ pluginSetupCommandError: currentChanged ? null : state.pluginSetupCommandError,pendingRemoteDesktopConfirmation: promotedRemoteDesktopConfirmation,pendingRemoteDesktopConfirmationQueue: remainingRemoteConfirmations,};@@ -15038,6 +15066,7 @@ async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string):pendingPluginSetupQueue: [],pluginSetupViewerState: 'expanded',pluginSetupCommandInFlight: null,+ pluginSetupCommandError: null,// F-AUQ-MIN-5: Clear session — wipe viewer state too.askUserViewerState: 'expanded',// F-AUQ-DRAFT: Clear session also wipes any in-progress draft.@@ -15337,16 +15366,52 @@ function respondToPluginSetup(if (!sessionId) return;const state = getOrCreateState(sessionId);const pending = state.pendingPluginSetup;- if (!pending || pending.requestId !== requestId || state.pluginSetupCommandInFlight) return;+ if (!pending || pending.requestId !== requestId) return;+ if (state.pluginSetupCommandInFlight && !(action === 'cancel' && isRemoteSession(sessionId) &&+ ((pending.remoteOauth && state.pluginSetupCommandInFlight.action === 'run_action') ||+ ((pending.remoteSecret || pending.remoteConnection) && state.pluginSetupCommandInFlight.action === 'submit_form')))) return;++ const owner = getDataOwnerGeneration();+ const recordRemoteFailure = (command: PluginSetupCommandInFlight, error: unknown) => {+ if (!isDataOwnerGenerationCurrent(owner)) return;+ setState(sessionId, (current) => {+ if (current.pluginSetupCommandInFlight !== command ||+ current.pendingPluginSetup?.requestId !== requestId ||+ current.pendingPluginSetup.revision !== pending.revision) return current;+ return {+ ...current,+ pluginSetupCommandInFlight: null,+ pluginSetupCommandError: { requestId, revision: pending.revision, code: remotePluginSetupErrorCode(error) },+ };+ });+ };const selectedAction = actionId? pending.steps.find((step) => step.action?.id === actionId)?.action: undefined;if (action === 'run_action') {if (!selectedAction || selectedAction.kind === 'inline_form') return;+ if (isRemoteSession(sessionId) && (!pending.remoteOauth || selectedAction.kind !== 'oauth_connect')) return;} else if (action === 'submit_form') {+ if (selectedAction?.kind === 'manage_connection' && isRemoteSession(sessionId) && pending.remoteConnection) {+ let value: import('@cindy/device-link').PluginConnectionInput;+ try { value = parsePluginConnectionInput({ host: values?.host, token: values?.value }); }+ catch { return; }+ const step = pending.steps.find(s => s.action?.id === selectedAction.id)!;+ if (pending.terminal || !['pending', 'failed'].includes(step.phase)) return;+ bumpInteractionReconcileEpoch(sessionId);+ const command: PluginSetupCommandInFlight = { requestId, action, actionId: selectedAction.id };+ setState(sessionId, s => ({ ...s, pluginSetupCommandInFlight: command, pluginSetupCommandError: null }));+ void submitRemotePluginConnection(sessionId, { requestId, actionId: selectedAction.id,+ expectedRevision: pending.revision, ghostId: pending.ghost.id, value,+ presentation: createPluginConnectionPresentation(pending, step) }).catch((error) => {+ // Never log the request, provider reply or IPC details from credential input.+ recordRemoteFailure(command, error);+ });+ return;+ }if (- isRemoteSession(sessionId) ||+ (isRemoteSession(sessionId) && !pending.remoteSecret) ||!selectedAction ||selectedAction.kind !== 'inline_form' ||typeof values?.value !== 'string'@@ -15363,17 +15428,28 @@ function respondToPluginSetup(action,actionId: selectedAction.id,};- setState(sessionId, (s) => ({ ...s, pluginSetupCommandInFlight: command }));- window.electronAPI.maker- .submitPluginSetupInline({- requestId,- actionId: selectedAction.id,- expectedRevision: pending.revision,- value,- })- .catch(() => {+ setState(sessionId, (s) => ({ ...s, pluginSetupCommandInFlight: command, pluginSetupCommandError: null }));+ const step = pending.steps.find((s) => s.action?.id === selectedAction.id)!;+ const submission = {+ requestId,+ actionId: selectedAction.id,+ expectedRevision: pending.revision,+ value,+ };+ const operation = isRemoteSession(sessionId)+ ? submitRemotePluginSecret(sessionId, {+ ...submission,+ ghostId: pending.ghost.id,+ presentation: createPluginSecretPresentation(pending, step, field),+ })+ : window.electronAPI.maker.submitPluginSetupInline(submission);+ operation+ .catch((error) => {+ if (isRemoteSession(sessionId)) { recordRemoteFailure(command, error); return; }// Do not attach IPC error details here: this path carries a secret.log.error('Failed to submit plugin setup form');+ if (sessions.get(sessionId)?.pluginSetupCommandInFlight !== command) return;+ toast.warning(i18n.t('newChat.pluginSetup.error.ACTION_FAILED'));setState(sessionId, (s) =>s.pluginSetupCommandInFlight === command ? { ...s, pluginSetupCommandInFlight: null } : s,);@@ -15387,16 +15463,20 @@ function respondToPluginSetup(action,...(actionId ? { actionId } : {}),};- setState(sessionId, (s) => ({ ...s, pluginSetupCommandInFlight: command }));+ setState(sessionId, (s) => ({ ...s, pluginSetupCommandInFlight: command, pluginSetupCommandError: null }));- makerApiFor(sessionId)- .resolveInteraction(requestId, {+ const remoteOauth = isRemoteSession(sessionId) && action === 'run_action' && actionId;+ const operation = remoteOauth+ ? assistRemotePluginOauth(sessionId, { ghostId: pending.ghost.id, requestId, actionId, expectedRevision: pending.revision })+ : makerApiFor(sessionId).resolveInteraction(requestId, {kind: 'plugin_setup',action,...(actionId ? { actionId } : {}),expectedRevision: pending.revision,- })+ });+ operation.catch((err) => {+ if (remoteOauth) { recordRemoteFailure(command, err); return; }log.error('Failed to respond to plugin setup:', err);setState(sessionId, (s) =>s.pluginSetupCommandInFlight === command ? { ...s, pluginSetupCommandInFlight: null } : s,diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.tsindex d953d3b72a..81547cb40d 100644--- a/apps/desktop/src/renderer/lib/makerTransport.ts+++ b/apps/desktop/src/renderer/lib/makerTransport.ts@@ -33,9 +33,36 @@ import * as messageService from '@/lib/messageService';import * as sessionService from '@/lib/sessionService';import { extractIpcError } from '@/utils/ipcError';import type { TurnChangeSetUpdatedPayload } from '../../shared/turnChangeSet';+import type { LocalPluginOauthRequest, LocalPluginSecretRequest, LocalPluginConnectionRequest } from '../../shared/pluginOauth';type FullMaker = typeof window.electronAPI.maker;+/** The dedicated local Main API owns the browser and encrypted callback; Renderer sees status only. */+export function assistRemotePluginOauth(+ sessionId: string,+ request: Omit<LocalPluginOauthRequest, 'deviceId'>,+): Promise<{ accepted: boolean }> {+ const deviceId = getStickySessionDeviceId(sessionId);+ if (!deviceId) return Promise.reject(new Error('Remote authorization unavailable'));+ return window.electronAPI.maker.assistPluginOauth({ deviceId, ...request });+}++/** This local call goes straight to Main's signed bridge, never makerApiFor/device-link invoke. */+export function submitRemotePluginSecret(+ sessionId: string,+ request: Omit<LocalPluginSecretRequest, 'deviceId'>,+): Promise<{ accepted: boolean }> {+ const deviceId = getStickySessionDeviceId(sessionId);+ if (!deviceId) return Promise.reject(new Error('Remote authorization unavailable'));+ return window.electronAPI.maker.submitRemotePluginSecret({ deviceId, ...request });+}++export function submitRemotePluginConnection(sessionId: string, request: Omit<LocalPluginConnectionRequest, 'deviceId'>): Promise<{ accepted: boolean }> {+ const deviceId = getStickySessionDeviceId(sessionId);+ if (!deviceId) return Promise.reject(new Error('Remote authorization unavailable'));+ return window.electronAPI.maker.submitRemotePluginConnection({ deviceId, ...request });+}+/*** makerChatStore / ChatInput 经传输层调用的会话操作子集。本地直接复用* window.electronAPI.maker;远程转 deviceLink.invoke。所有 channel 均在diff --git a/apps/desktop/src/renderer/lib/pluginSetupCommandError.ts b/apps/desktop/src/renderer/lib/pluginSetupCommandError.tsnew file mode 100644index 0000000000..35d8f141b5--- /dev/null+++ b/apps/desktop/src/renderer/lib/pluginSetupCommandError.ts@@ -0,0 +1,14 @@+import { extractIpcError } from '@/utils/ipcError';++/** Local presentation only; never sent to the Host or persisted in task history. */+export interface PluginSetupCommandError {+ requestId: string;+ revision: number;+ code: 'REMOTE_UNSUPPORTED' | 'REMOTE_FAILED';+}++export function remotePluginSetupErrorCode(error: unknown): PluginSetupCommandError['code'] {+ return extractIpcError(error)?.code === 'UNSUPPORTED_CAPABILITY'+ ? 'REMOTE_UNSUPPORTED'+ : 'REMOTE_FAILED';+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8c16b69d6b..2001486fac 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -6003,6 +6003,11 @@ interface ElectronAPI {decision: Record<string, unknown>,) => Promise<{ accepted: boolean }>;+ assistPluginOauth: (request: import('../shared/pluginOauth').LocalPluginOauthRequest) => Promise<{ accepted: boolean }>;+ submitRemotePluginSecret: (request: import('../shared/pluginOauth').LocalPluginSecretRequest) => Promise<{ accepted: boolean }>;+ submitRemotePluginConnection: (request: import('../shared/pluginOauth').LocalPluginConnectionRequest) => Promise<{ accepted: boolean }>;+ pluginOauthDeviceCode: (request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest) => Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null>;+/** Submit one inline plugin Secret through the local trusted-frame-only IPC. */submitPluginSetupInline: (request: {requestId: string;diff --git a/apps/desktop/src/shared/botAuthorization.ts b/apps/desktop/src/shared/botAuthorization.tsindex 0e40d96474..e4ef4adf36 100644--- a/apps/desktop/src/shared/botAuthorization.ts+++ b/apps/desktop/src/shared/botAuthorization.ts@@ -1,5 +1,6 @@import type { GhostSetupAllowedAction, GhostSetupStepPhase, GhostSetupErrorCode } from './ghost.js';export interface AuthorizationSnapshot {+ remoteOauth?: true;reopenActionId?: string;kind: 'plugin_setup';requestId: string;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex bd0ad02730..36dc2c338c 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1,4 +1,5 @@import { parseGhostRoutineEvents, type GhostRoutineEvents } from '@cindy/plugin-protocol';+import { parsePluginAuthorizationRequest, type PluginAuthorizationRequest, type PluginAuthorizationResult } from '@cindy/device-link';import {type GhostRecommendation,GHOST_LOCALES,@@ -335,13 +336,17 @@ export const GHOST_NODE_CHILD_MODE_FLAG = '__cindy-node-child__';/** worker → 主机:代启/喂 stdin/收 stdin/杀进程。 */export type GhostNodeChildToHostMessage =- | { type: 'spawn-child'; reqId: string; entry: string; args?: string[] }+ | { type: 'plugin-authorize'; reqId: string; rpcId: string; request: PluginAuthorizationRequest }+ | { type: 'device-authorize'; reqId: string; rpcId: string; url: string }+ | { type: 'spawn-child'; reqId: string; entry: string; args?: string[]; rpcId?: string }| { type: 'child-stdin'; childId: string; b64: string }| { type: 'child-stdin-end'; childId: string }| { type: 'child-kill'; childId: string };/** 主机 → worker:代启结果/子进程输出/退出。 */export type GhostNodeChildToWorkerMessage =+ | { type: 'plugin-authorize-result'; reqId: string; ok: boolean; result?: PluginAuthorizationResult }+ | { type: 'device-authorize-result'; reqId: string; ok: boolean }| { type: 'spawn-child-result'; reqId: string; ok: true; childId: string; pid?: number }| { type: 'spawn-child-result'; reqId: string; ok: false; message: string }| { type: 'child-stdout'; childId: string; b64: string }@@ -356,8 +361,27 @@ function isChildId(v: unknown): v is string {export function parseGhostNodeChildToHostMessage(raw: unknown): GhostNodeChildToHostMessage | null {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;const m = raw as Record<string, unknown>;+ if (m.type === 'plugin-authorize') {+ if (Object.keys(m).sort().join(',') !== 'reqId,request,rpcId,type'+ || !isChildId(m.reqId) || typeof m.rpcId !== 'string' || !/^\d{1,16}$/.test(m.rpcId)) return null;+ try { return { type: m.type, reqId: m.reqId, rpcId: m.rpcId, request: parsePluginAuthorizationRequest(m.request) }; }+ catch { return null; }+ }+ if (m.type === 'device-authorize') {+ if (+ Object.keys(m).sort().join(',') !== 'reqId,rpcId,type,url' ||+ !isChildId(m.reqId) ||+ typeof m.rpcId !== 'string' ||+ !/^\d{1,16}$/.test(m.rpcId) ||+ typeof m.url !== 'string' ||+ m.url.length > 8192+ )+ return null;+ return { type: 'device-authorize', reqId: m.reqId, rpcId: m.rpcId, url: m.url };+ }if (m.type === 'spawn-child') {if (!isChildId(m.reqId) || typeof m.entry !== 'string') return null;+ if (m.rpcId !== undefined && (typeof m.rpcId !== 'string' || !/^\d{1,16}$/.test(m.rpcId))) return null;if (m.args !== undefined) {if (!Array.isArray(m.args) || m.args.length > GHOST_NODE_CHILD_MAX_ARGS) return null;for (const arg of m.args) {@@ -368,6 +392,7 @@ export function parseGhostNodeChildToHostMessage(raw: unknown): GhostNodeChildTotype: 'spawn-child',reqId: m.reqId,entry: m.entry,+ ...(typeof m.rpcId === 'string' ? { rpcId: m.rpcId } : {}),...(m.args !== undefined ? { args: m.args as string[] } : {}),};}@@ -6342,8 +6367,14 @@ export interface GhostPipeNodeRequest {type: 'node-request';/** OAuth 注入的本插件账号 id;缺省使用对应 OAuth 槽的默认账号。 */authAccount?: string;+ /** Live tool-call identity; only cancelWithCall opts in to the new lifecycle. */+ callId?: string;+ /** Explicit opt-in: cancellation/completion stops this RPC and its children. */+ cancelWithCall?: boolean;/** JSON-RPC 方法名;mcp-stdio 时使用 tools/list、tools/call 等 MCP 方法。 */method: string;+ /** Live call only: show the existing protected card for this RPC's manual Node bindings. */+ promptSecrets?: boolean;params?: unknown;/*** 单次等待上限,缺省 30 秒;允许 1–120 秒。声明了 maxTotalMs 时语义变为@@ -6369,6 +6400,7 @@ export type GhostPipeNodeResult =| {ok: false;errorCode:+ | 'CANCELLED'| 'INVALID_REQUEST'| 'PERMISSION_DENIED'| 'PROCESS_START_FAILED'diff --git a/apps/desktop/src/shared/pluginOauth.ts b/apps/desktop/src/shared/pluginOauth.tsnew file mode 100644index 0000000000..7f28c2b611--- /dev/null+++ b/apps/desktop/src/shared/pluginOauth.ts@@ -0,0 +1,55 @@+import type {+ PluginOauthAction,+ PluginSecretPresentation,+ PluginConnectionPresentation,+ PluginConnectionInput,+} from '@cindy/device-link';+import type { GhostSetupInlineSecretField } from './ghost.js';++/** Trusted Desktop IPC only; these requests must never use generic device-link invoke. */+export interface LocalPluginOauthRequest extends PluginOauthAction {+ deviceId: string;+ ghostId: string;+}++export interface LocalPluginSecretRequest extends LocalPluginOauthRequest {+ value: string;+ presentation: PluginSecretPresentation;+}++export interface LocalPluginConnectionRequest extends LocalPluginOauthRequest {+ value: PluginConnectionInput;+ presentation: PluginConnectionPresentation;+}++export function createPluginConnectionPresentation(+ card: { ghost: { name: string }; intro?: string },+ step: { title: string; description: string; action?: { id: string } },+): PluginConnectionPresentation {+ const prefix = 'manage_connection:connection:';+ if (!step.action?.id.startsWith(prefix)) throw new Error('PLUGIN_CONNECTION_UNAVAILABLE');+ return {+ ghostName: card.ghost.name,+ title: step.title,+ description: step.description,+ intro: card.intro ?? '',+ connectionKey: step.action.id.slice(prefix.length),+ };+}++/** Both Hosts bind the same displayed fields; neither side may choose a vault key. */+export function createPluginSecretPresentation(+ card: { ghost: { name: string }; intro?: string },+ step: Pick<PluginSecretPresentation, 'title' | 'description'>,+ field: Pick<GhostSetupInlineSecretField, 'label' | 'description' | 'maxLength'>,+): PluginSecretPresentation {+ return {+ ghostName: card.ghost.name,+ title: step.title,+ description: step.description,+ intro: card.intro ?? '',+ fieldLabel: field.label,+ fieldDescription: field.description ?? '',+ maxLength: field.maxLength,+ };+}diff --git a/apps/desktop/src/shared/pluginOauthDeviceCode.ts b/apps/desktop/src/shared/pluginOauthDeviceCode.tsnew file mode 100644index 0000000000..d6076402b1--- /dev/null+++ b/apps/desktop/src/shared/pluginOauthDeviceCode.ts@@ -0,0 +1,33 @@+/** Local Desktop presentation only. Never add this channel to device-link or chat snapshots. */+export const PLUGIN_OAUTH_DEVICE_CODE_CHANNEL = 'plugin-oauth:device-code';++export interface PluginOauthDeviceCodeTarget {+ deviceId: string;+ ghostId: string;+ requestId: string;+ actionId: string;+}++export type PluginOauthDeviceCodeRequest = PluginOauthDeviceCodeTarget & {+ operation: 'read' | 'copy' | 'reopen';+};++/** Only the short user-entered device code is displayable, never OAuth callback codes or tokens. */+export type PluginOauthDeviceCodeView =+ | {+ phase: 'ready';+ userCode: string;+ verificationHost: string;+ expiresAt: number;+ copiedAt: number;+ }+ | { phase: 'browser'; expiresAt: number }+ | { phase: 'completed' | 'expired' | 'ended' };++export interface PluginOauthDeviceCodePrompt {+ userCode: string;+ authorizeUrl: string;+ expiresAt: number;+}++export type PluginOauthDeviceCodeClose = (phase: 'completed' | 'expired' | 'ended') => void;diff --git a/docs/README.md b/docs/README.mdindex e99bdcfc6c..6257d9043a 100644--- a/docs/README.md+++ b/docs/README.md@@ -38,6 +38,7 @@| [remote-and-mobile-adaptation.md](./dev-rules/remote-and-mobile-adaptation.md) | 远程/手机版门禁 | authoritative | SSH 远程工作区、device-link allowlist、`apps/mobile` 入口与功能类 PR 三选一门禁 | — || [development-workflow.md](./dev-rules/development-workflow.md) | 开发工作流 | authoritative | worktree dogfooding 契约、提 PR/直推 main 门禁、Review P0/P1/P2 口径 | — || [plugin-setup-runtime.md](./plugin-setup-runtime.md) | 技术设计 | 参考 | `ghost_list` / `ghost_info` / `ghost_call` 插件配置前置检查、Ask-shell Setup 卡片、配置变更回调与原调用恢复 | — |+| [remote-plugin-oauth.md](./remote-plugin-oauth.md) | 客户端契约 | 参考 | 远程设备插件 OAuth 事务、Desktop 回调桥、任务授权指引及兼容边界 | — || [desktop-login-hosted-callback.md](./desktop-login-hosted-callback.md) | 跨仓契约 | 参考 | Desktop 系统浏览器登录的托管回调链路:auth-server 路由契约、结果页模板交付、灰度开关与回滚 | — || [auth-realm-routing.md](./auth-realm-routing.md) | 跨仓契约 | 参考 | 组织 SSO 双区域发现、会话区域持久化与 token 消费端点路由 | — || [client-log-upload-requirements.md](./client-log-upload-requirements.md) | 需求文档 | 参考 | Desktop 客户端日志上报(手动 + 崩溃自动)的目标、数据边界、同意闸与可靠性要求 | — |diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 966438029f..6c702284c9 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -18,12 +18,12 @@| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 || `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 || `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 288 | 43 | 490 |+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 288 | 43 | 493 || `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 22 | 7 | 64 || `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 2 |-| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 269 | 43 | 389 |+| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 269 | 43 | 392 || `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts, apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts | 44 | 0 | 109 |-| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 269 | 43 | 388 |+| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 269 | 43 | 391 || `desktop.dev.maker-experimental` | desktop | Maker 实验诊断页 | hash `/maker-experimental`(MakerExperimentalView;EXPERIMENTAL_FEATURES 现为空,仍是生产路由) | MakerExperimentalView | apps/desktop/src/renderer/features/maker-experimental/MakerExperimentalView.tsx | 10 | 0 | 11 || `desktop.issues.guide` | desktop | Issue 引导页 | hash `/issues`(IssueTrackerFeatureLayout,已迁 GitHub 后的引导页) | IssueTrackerFeatureLayout | apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx, apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx, apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts, apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts, apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts | 0 | 0 | 8 || `desktop.native.app-menu` | desktop | 应用菜单 | Menu.setApplicationMenu(用户可见出口,不展开业务逻辑) | applicationMenuLabels | apps/desktop/src/main/applicationMenuLabels.ts | 0 | 0 | 0 |diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex a9e2111725..f65a02b136 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -32,6 +32,11 @@- 插件自定义的账号昵称、展示偏好和业务配置属于插件数据,使用现有隔离 `/kv`,不扩充 Host OAuth 账号模型、凭证库或专用接口。插件按账号 ID 合并这些数据用于展示和选择账号;传给 Host 的授权身份仍是账号 ID,不能用昵称替代。+- 远程声明式 API Key/PAT 可通过 [签名输入桥](../remote-plugin-oauth.md) 的密码卡一次性+ 提交;专用本机 IPC 验证设备、插件、卡片、完整字段展示后加密交给目标 Host 原 executor。+ 只写已声明的单个 user Secret,不读回、不批量同步、不开放账号 vault。值只短暂存在于+ 输入组件/Main 调用中,不进入 Renderer store、Agent、普通远控、日志或历史。CLI PKCE+ 的私有回调也只交给发起的可信 Node RPC,不能返回沙箱 main.js 或业务 stdout。- access token 等只需短期使用的秘密优先保留在内存中。日志、错误、遥测和调试输出不得包含凭证明文、完整鉴权头或可直接复用的授权材料。- 测试只使用明显无效的假凭证,不读取或复制开发者真实的 `HOME`、Agent home、diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 9d460fb168..dd3549d2cc 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -278,8 +278,29 @@`ghost_call` 恢复均由 Host 掌控。Secret、Token、OAuth code 和连接凭证不得进入Agent、Ghost、interaction / pending snapshot、会话历史、日志或分析事件。内联 Secret只允许短暂存在于本地 Desktop 输入组件和一次性的 trusted Renderer → Main 专用 IPC;- 不得走通用 interaction response、device-link 或其它远程通道,也不得写入 Renderer- store。提交成功、取消、request / revision 替换和组件卸载时必须清空。+ 不得走通用 interaction response、通用 device-link invoke,也不得写入 Renderer+ store。提交成功、取消、request / revision 替换和组件卸载时必须清空。远程普通 user+ Secret 的窄例外仅为下述签名输入桥,不提供保险库读取或同步。+- 远程设备插件 OAuth 的 [Desktop 回调桥](../remote-plugin-oauth.md) 是独立的 Host 对 Host+ 授权事务,只承接当前卡片的已声明 OAuth action。URL/code 必须在两个 Main 间加密,+ 不能暴露给 Renderer、Agent、插件或通用 invoke;token 仍由目标 Host 现有账号管理器交换保存。+ 通用设备码、浏览器确认和 CLI PKCE 回调由同一类型化适配层承接,仍须精确任务/插件/目标+ 绑定;可信 Node 的私有 CLI callback 只回 bootstrap Promise,不经 stdout、沙箱或模型。+ Node 本来拥有系统用户权限,这不是隔离恶意 Node 的保证;不放开任意端口/URL 转发。+ 新 Node 授权卡须以 `cancelWithCall:true` 和当前 `callId` 显式启用;只带旧调用编号+ 不取得授权能力,也不改变旧 RPC/后台子进程生命周期。任务 Stop 后不得迟到启用,+ 取消只回收该调用所属子进程,不停止同一 Worker 中其它调用。+ 普通 user Secret 可由 `remoteSecret:true` 卡片通过专用本机 `plugin-oauth:submit-secret`+ 加密送到目标 Host;必须先签名握手,并比较原 Host 的完整字段展示与用户看到的字段,绑定+ 设备/插件/action/revision,在最新声明与写入边界复验。只允许写既有 executor 解析出的+ 单个 Secret;OAuth、gh-cli、oidc-token 和账号 vault 不接受此输入。Bot/旧卡片无此标记,+ 不自动获得能力。原始值不进通用 invoke、事件、会话历史、日志或 store;不增加确认窗口。+ 用户要求的设备码卡片展示是窄例外:加密 device offer 中供用户手工输入的短时+ `userCode` 可通过本机专用 `plugin-oauth:device-code` 接口投影到发起授权的自有顶层+ Renderer。只在当前卡片组件内存显示;按 owner、窗口/frame、设备、插件、request/action+ 绑定,支持再次复制与重新打开 Main 保管的同一授权页。过期、终态或身份失效后清除。+ 它不包含 OAuth callback code、device_code、Token、完整 URL 或 state,不进入聊天+ snapshot、模型、持久化或通用远控;不改变原授权卡片或新增确认窗口。- Host 必须把每个未满足 `any_of` 组的全部可执行 item 投影到卡片,Agent plan不能隐藏合法配置路径。Renderer 统一按组展示选项并复用 Ask 卡片的正文限高与纵向滚动,不得为 Brave、Tavily、Gmail 等具体插件增加分支。diff --git a/docs/ghost-progressive-discovery.md b/docs/ghost-progressive-discovery.mdindex 80276381aa..bff179ffed 100644--- a/docs/ghost-progressive-discovery.md+++ b/docs/ghost-progressive-discovery.md@@ -70,6 +70,12 @@ frontmatter `name + description` 的召回作用;`manual.items` 只是插件## 3. 花名册(roster)+普通任务可调用 `connect_account({kind:"plugin", id:ghost_id})`,由 Host 复用配置卡等待连接,+不必先触发插件业务调用。等待受当前任务取消、插件可见性及原配置卡版本校验约束。+伙伴继续使用原持久授权卡与配置策略;Host 账号入口仍只用于伙伴。显式 `reauthorize`+只呈现已声明的 OAuth、Secret 或连接配置动作,不删除现存账号。没有 Host 配置动作的插件应使用其+设置页或手册中的登录工具;空的配置就绪状态不能作为平台账号已登录的证据。+### 3.1 内容与口径- 每条 = `{id, name, command, recall}`;`recall = whenToUse ?? description`。@@ -228,3 +234,11 @@ frontmatter `name + description` 的召回作用;`manual.items` 只是插件`--append-system-prompt`);Pi 的 host 侧装配在`apps/desktop/src/main/maker-host/pi-host.ts`(buildPiAgent /composePiSystemPrompt)++### 任务内授权指引++Desktop 的 Claude/Codex/Pi Host 追加同一静态授权指引,复用现有发现及市场安装工具,+不改安装权限或来源策略。已有登录态时,用户明确要求更新授权仍调用 `reauthorize:true`;+私密值只填原卡片,不进入工具参数或对话。先等待 Host 完成,再以最小只读调用验证平台权限。+提示词保持原 system 前缀,无设备 ID、凭据、时间戳或动态账号状态;详见+[远程授权契约](remote-plugin-oauth.md) 的兼容性与缓存影响。diff --git a/docs/product-rules/bot-authorization-cards.md b/docs/product-rules/bot-authorization-cards.mdindex 86c680d4ca..51efd4875e 100644--- a/docs/product-rules/bot-authorization-cards.md+++ b/docs/product-rules/bot-authorization-cards.md@@ -44,7 +44,9 @@ Grok 的 MCP 后端 state TTL 不能直接套给 Grok 订阅登录或所有插- SSH Agent 不因该工具获得本机凭证;请求要求可交互的本机伙伴主任务。远端 Pi 仍可发现和调用实际可用插件,但缺配置时不承诺聊天授权卡或完成通知;指向可信 Desktop 的插件连接页,用户确认配置完成后再重试。手机控制本机伙伴仍保留原授权卡与自动续接。-- 没有修改 device-link 重试、relay 或断链恢复;故障范围是单张卡。+- 远程设备的插件 OAuth 可通过 [Desktop 回调桥](../remote-plugin-oauth.md) 完成;使用专用+ Host 事务,普通远程 setup/Secret 提交仍拒绝。先探测能力,旧端不回退通用 invoke。+ relay 路由及重试机制不变;断链取消对应 peer 的在途授权,不影响其它 peer。## 完成提交边界diff --git a/docs/remote-plugin-oauth.md b/docs/remote-plugin-oauth.mdnew file mode 100644index 0000000000..04a150caa3--- /dev/null+++ b/docs/remote-plugin-oauth.md@@ -0,0 +1,219 @@+# 远程插件授权与配置++本功能连接两台已登录同账号、已允许 Device Link 控制的 Desktop。执行任务的 Host+拥有插件及凭据,控制端 Desktop 提供浏览器和保密卡片。协议及实现正本为+`packages/device-link/src/plugin*.ts` 与 `apps/desktop/src/main/plugin-oauth/`。+它不依赖 CIS、云实例配置、定制发行包或新的服务端接口。++## 用户流程++1. Agent 按现有花名册及 `ghost_info` 发现插件;缺少当前请求必需的插件时,复用市场+ 搜索/安装工具及既有权限策略。安装成功不表示账号已授权。+2. setup 检查或 `connect_account({kind:"plugin",id})` 在执行设备创建现有配置卡。+ 用户明确要求换 Token、更新授权或重新配置时使用 `reauthorize:true`,即使已有连接。+3. 用户在连接该设备的 Desktop 点击卡片。Main 验证目标、握手、卡片版本及授权来源,+ 再打开本机浏览器或发送保密表单;没有额外确认窗口。+4. OAuth 回调在本机接收,加密回到原 Host;原 Host 保管 PKCE verifier,并用原始+ redirect URI 交换、保存账号。Device Flow 由原插件/CLI 继续轮询。+5. Host 收到本卡片的实际提交回执并复验后才继续任务。浏览器打开、回调到达、配置+ 已保存都不能单独证明平台权限;后续用最小只读操作检查实际可用性。++```mermaid+sequenceDiagram+ participant U as 用户的 Desktop+ participant C as 控制端 Main+ participant R as 执行端 Host+ participant P as 第三方平台+ R->>U: 配置卡(不含凭据)+ U->>C: 点击卡片 / 一次性保密输入+ C->>R: v3 identity + hello(同账号控制链路)+ R-->>C: 绑定卡片、双方设备与临时密钥的签名+ C->>C: 验签并登记/核对持久公钥+ C->>R: 加密 start,协商当前动作+ R-->>C: 加密 offer(授权目标或完整表单展示)+ C->>C: 核对目标、卡片与展示+ C->>P: 打开授权网页(需要浏览器时)+ P-->>C: 本机回调 / 用户按平台要求确认+ C->>R: 加密 callback 或保密输入+ R->>P: 原 OAuth 交换 / 原 CLI 验证+ R->>R: 当前 owner 与卡片复验、保存+ R-->>U: 完成状态,继续原任务+```++## 身份与信任边界++- 使用上游同账号 Device Link 准入,执行端仍检查远程控制开关和 controller 撤权。+ **首次公钥登记信任账号服务与 relay**;验签证明持有对应私钥,但首次登记时不能防止+ 恶意 relay 同时替换描述符及握手。不得称为独立身份认证、双向设备证明或 CIS 验证。+ 执行端对控制端的身份和准入仍依赖既有 Device Link 链路;持久 pin 保护控制端所认的+ 执行设备,不把它解释成可抵御账号服务或 relay 冒充控制端的双向独立认证。+- 执行端使用独立用途的持久 Ed25519 密钥;控制端验签成功后才固定对端公钥。两端+ 按 realm/membership/local device 分域,使用 Electron safeStorage 加密落盘,原子写入+ 和跨进程锁;不复用通讯录密钥,不在启动/能力投影时访问钥匙串。+- 文件在 `ownerScopedUserDataPath('plugin-oauth', <scope-sha256>.v1.enc)`,含本机签名+ 密钥及该域的 peer pins。Linux 无安全后端、`unknown`、`basic_text` 均拒绝。+ 损坏或跨身份移植的文件不得重新生成后放行。重启沿用密钥,生成新的 bootId。+- 已登记 peer 换钥直接拒绝;没有自动清 pin、信任新钥或删除凭据的恢复入口。+ 重装丢失密钥时需先核实并重新登记设备身份;本 PR 不提供绕过 pin 的恢复按钮。+- 两端 Main、OS、安全存储、执行插件/CLI 与既有账号服务仍在可信基座内。Node 插件+ 拥有系统用户权限;本桥不是同 UID 进程隔离,也不能阻止有权插件使用已授予的能力。+ relay 后续仍能拒绝服务、观察路由元数据;普通控制通道的信任模型不变。++## v3 机器契约++私有外层通道为 `device-link:plugin-oauth:v3`。独立于实验云分支的 v2,不降级回它。++控制端和执行端都必须实现 v3;设备已连接、可创建任务或能投影旧授权卡片,不代表授权桥兼容。+执行端返回 `CHANNEL_NOT_ALLOWED` 时,本机授权 IPC 以 `UNSUPPORTED_CAPABILITY` 拒绝,+卡片明确提示更新远程设备上的 Cindy。其它前置失败只显示受控的失败提示,不展示原始异常、+provider 响应或凭据。提示仅保存在控制端内存,并绑定账号代次、当前请求与 revision;重试、+取消或新卡片不能被迟到的旧失败覆盖。它不改变 Host 的权威卡片 phase,也不进入任务历史。+++```ts+type IdentityRequest = { op: 'identity'; version: 3 };+type PeerIdentity = {+ version: 1; // 描述符结构版本,不是外层通道版本+ realm: 'cn' | 'global'; membershipId: string; deviceId: string;+ publicKey: string; // Ed25519 SPKI DER, base64url+ bootId: string; observedAtMs: number; expiresAtMs: number;+};+type Action = { requestId: string; actionId: string; expectedRevision: number };+type Hello = { op: 'hello'; version: 3; nonce: string; publicKey: string; action: Action };+type HelloReply = {+ version: 3; id: string; publicKey: string; bootId: string;+ ghostId: string; expiresAtMs: number; signature: string;+};+type Exchange = { op: 'exchange'; id: string; box: string };+// 解密请求:{ nonce, request: InnerRequest }+// 解密响应:{ nonce, ok: true, result } | { nonce, ok: false }+```++描述符必须精确匹配当前 realm、membership、目标 device,最长 60 秒。+身份查询与 hello 必须走同一已授权通道。签名绑定上述身份、控制端设备、签名公钥、+bootId、双方临时 X25519 公钥、nonce、事务 ID/期限、卡片/action/revision 和插件。+先验签并持久核对 pin,再发 start/打开网页。X25519、HKDF-SHA256、AES-256-GCM+保护之后的请求和响应,方向/事务纳入密钥派生;回包需匹配请求 nonce。++内层保留事务 `version:1`,只接受 capabilities/start/status/callback/cancel。+`deviceUserCode`、`authorizationV1`、`secretSubmission`、`connectionSubmission`+逐项协商,缺字段即不支持;不得改走通用 invoke 或让用户把秘密贴到对话。+解析器拒绝未知字段;请求不能指定命令、存储路径、密钥名、身份 authority 或 bearer。++## 支持方式与扩展++| 方式 | 接入点 | 完成的事实来源 |+| --- | --- | --- |+| 声明式 OAuth / broker | 既有 `network.secrets[].source=oauth` | 原 Host 交换/保存/复验 |+| 设备码 | Node `bindAuthorization` 的 `kind:'device'` | 原插件/CLI 领取并验证 |+| 浏览器确认页 | `kind:'browser'` | 原插件/CLI 轮询/确认 |+| CLI PKCE loopback | `kind:'loopback'` | 原可信 Node 保管 verifier 并交换 |+| API Key/PAT | 既有 user Secret `inline_form` | 原 executor 保存指定 Secret |+| 服务地址 + Token | 既有 `network.connections` 的 `manage_connection` | 原 ConnectionManager 保存 |++声明式 OAuth 和连接表单沿用已装插件格式,不要求重装/重新批准/更换凭据。+CLI 特殊登录需主动调用类型化接口,不能自动解析任意 stdout。通用适配器在+`authorizationAdapters.ts`;Node 接线在 `nodeAuthorizationClient.ts`、+`nodeDeviceAuthorizationClient.ts`、`nodeSecretSetup.ts`。`forge.ts` 记录其作者契约。+不允许插件提供 Host 可执行命令或加载任意适配器模块。++GitHub 的 Linux 专用登录 helper、云镜像和 gh-cli 凭据源改动不在本分支;上游原有+GitHub 登录来源与设置保持可用。通用设备码框架及已审查 URL 限制保留,但不能据此+声称任意平台的 GitHub CLI 登录已自动接入。TapTap 等 CLI 插件也须实际使用上述接口。++标准 OAuth 目标由当前已批准的 manifest 与 broker 配置约束;设备/浏览器授权只允许+HTTPS 默认端口,专用 provider 目标由 `builtinAuthorizationTargets.ts` 精确校验。+卡片绑定 manifest 快照,提交时再次检查。CLI loopback 限显式非特权端口、固定路径、+唯一 state/redirect_uri/client_id/response_type=code/S256 challenge;不提供任意 HTTP+转发。端口占用时失败,不抢端口、不杀进程、不改注册地址。++CLI 的 `localhost` 回调在同一端口监听 `127.0.0.1` 和 `::1`,共用 state、卡片校验和+一次性消费状态;显式 IP 回调只监听该地址,不监听通配接口。任一可用地址的端口冲突+会关闭本次全部监听器;只有 OS 明确不支持某地址族或该回环地址不可用时才使用另一族。+回归见 `plugin-oauth/__tests__/loopbackListener.test.ts`。++## 保密输入与设备码++专用本机 IPC:++- `plugin-oauth:assist`:deviceId、ghostId、requestId、actionId、expectedRevision。+- `plugin-oauth:submit-secret`:相同绑定 + value + 完整 presentation。+- `plugin-oauth:submit-connection`:相同绑定 + `{host,token}` + 完整 presentation。+- `plugin-oauth:device-code`:设备/插件/request/action + read/copy/reopen。++这些接口仅接受可信自有顶层 Renderer,不进入通用远控 allowlist。+输入只在原组件及一次性 Main 调用短暂存在;签名握手后比较目标 Host 的完整字段展示,+再加密发送。存储 key 由最新声明解析,不能由请求选定。user Secret 不接受 OAuth、+gh-cli、oidc-token 或账号 vault 写入;临时 Node Secret 卡只允许其已声明方法/入口。+连接地址只接受 HTTPS 默认端口 DNS 主机/根 URL,无路径/query/自定义端口/IP。++伙伴消息内的 Bot 授权卡目前只接通远程插件 OAuth 和取消,不支持远程 Secret/连接表单。+即使旧消息或较新 Host 的快照携带这些表单能力标记,也禁用输入并提示在执行设备完成,+不会先收取再丢弃凭据;本地伙伴卡片的保密输入保持原路径。Host 发卡、远程投影及真实+表单组件的连通测试见 `BotAuthorizationCard.forms.test.tsx`。++重新配置必须收到**本卡片/action/revision 的实际保存回执**,普通 change event 或旧值+不能让新卡片提前结束。同地址保留原连接 ID/默认选择;提交前取消保留旧凭据。保存成功+表示配置写入,第三方验证失败不会自动恢复被替换的 Token,也不能宣称已登录。++已保存的 user Secret/API Key/PAT 同样支持显式重配。协调器只为当前提交创建 Main 内+的写入能力,绑定插件、卡片动作及声明的 Secret;最终 executor 重新检查当前声明、+任务取消与工作目录准入,再覆盖该值。保存失败保留旧值,成功回执先于 change 事件,+才能解除本卡片的重填要求。该能力不进入 wire DTO,Renderer 不能提交 force 标记或+自行选择存储 key;一般 readiness 检查仍复用已有值,不重复要求用户授权。++输入在提交、取消、换卡/设备及卸载时清空。设备用户码仅在发起授权的本机卡片显示,+可重复复制/重开 Main 保管的页面;不包含 callback code、device_code、token、state 或+完整 URL。它不进入聊天 store、历史、镜像、日志或模型。结束/过期清内存,剪贴板仍为+同一码时才清除;复开不新建事务,也不恢复已消费的码。++## 生命周期、兼容及降级++- owner、peer 代际、卡片、期限和权限在异步边界及写入前复验。账号/连接失效、取消、+ 超时后的晚到结果不得写入;本机窗口消失也收口监听器。取消不承诺撤销平台已完成的 consent。+- 事务最长五分钟,只在内存;每 Host 最多 16 个握手、每 peer 最多 4 个。相同 nonce/+ 密文重试复用回执,不重复交换,复用 nonce 搭配不同密文拒绝。+- 单 peer 断链仅取消该 peer;共享 relay/账号退出取消全部。不开全局重连、不动别的+ peer。Node 请求显式传入 `cancelWithCall:true` 和当前 `callId`,才启用授权卡及+ 随 task stop/abort 回收所属进程的生命周期。单独携带旧 `callId` 或省略开关都+ 保持上游独立 RPC 行为,不自动弹卡或结束后台进程。已停止的调用不能迟到启用新授权。+- 两端 Desktop 必须支持 v3。旧版仍可使用原本的远控及执行设备本地设置;新授权动作+ 不走旧通道/明文降级,不会替用户清空已有凭据。+- Mobile 当前只可查看/取消既有卡片,未实现本机回调与保密输入;在连接该设备的新版+ Desktop 完成。网站 Cookie/全量 vault 同步不在范围。+- Auth、relay、CIS、Model Access 不需要本功能的新服务接口或部署;双方客户端需升级。++### 各端范围与后续门禁++| 场景 | 本 PR 的处理 |+| --- | --- |+| Desktop → Desktop Device Link | 已适配:新私有通道经同账号授权、卡片绑定及签名握手;原有 invoke/push 规则不放宽。 |+| Mobile → Desktop Device Link | 保留既有只读配置状态、取消和完成状态。手机侧保密输入、设备码操作与浏览器回调尚未适配,必须在 PR 链接专门的跟踪 issue 后才能满足上游延期要求,不能把这三项写成已支持。 |+| SSH 工作区 | 本 PR 不新增 SSH 凭据转发或远端插件安装。SSH 的 Agent/workdir 仍经 maker-remote-ssh、cc-manager 与 remote-file-service;插件由提供 MCP 的 Desktop Host 管理,授权仅改变该 Host 的连接。SSH 主机没有本桥的 Desktop 身份、OS 密钥存储和 Device Link peer,不能把它当作另一个被控 Desktop,也不向其 HOME/workdir 复制本机凭据。原有远端文件、网络与 Forge 限制保留。 |++故障范围:单卡片取消/超时只收口该事务;单 peer 失效只取消该 peer 的事务;账号退出+或整条 relay 失效才取消全部。桥不强拆或重建全局 relay。自动化多 peer 用例见+`plugin-oauth/__tests__/lifecycle.test.ts` 与 `transport.test.ts`:两个控制端同时授权,+其中一个断链后另一个仍能完成;这些是本地传输测试,不是生产 relay 验收。++## Agent 指引与验证++普通 Desktop 的 Claude/Codex/Pi system prompt 与上游一致,不注入全局授权提示词。+本 PR 只在相关工具的 schema/description 中说明发现、必要安装、发起卡片和显式重配;+原有工具批准策略不变。工具描述有增量,不能声称整个模型请求或缓存键完全不变。+云实例的全局指引保留在独立云分支,由云运行环境启用,不属于此 PR,也不加入普通+Desktop 的 system 段。++可用显式 opt-in 的 `scripts/eval-plugin-authorization.mts` 对比上游基线:两组均使用三种 Host+原有提示词片段,只切换真实 MCP schema/handler,通过真实模型覆盖必要安装、首次授权、已保存+Secret 重配、取消、无关任务及相同前缀重复请求,记录行为、usage/cache、首事件与总耗时。+插件安装/账号结果为合成数据,不操作真实账户;现有模型登录仅在内存只读使用,不刷新或+复制授权文件,结果写系统临时目录。该脚本评估 Host prompt profiles,不启动原生+Claude/Codex/Pi 二进制,也不能证明 Anthropic 原生缓存、真实双 Desktop 或第三方登录+通过。PR 必须附实际结果及此范围说明,不用字符串单测替代指标实测。++自动测试以虚构身份/凭据及临时目录覆盖持久密钥/peer pin、跨身份拒绝、签名绑定、旧端+拒绝、加密重放、真实本地 WebSocket/TCP 回调、Host coordinator/executor 写入、取消及+Node 回收、设备码/保密表单和重配回执。OS secureStorage、relay 准入及第三方 HTTP 可为+测试替身,不能将这些结果报告为真实平台登录或线上部署完成。+发布前应另行验证各目标平台安全存储、双 Desktop 实际登录、provider 风控/MFA/回调策略。diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.tsindex 0c7517f2a9..adb202f47b 100644--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts@@ -1980,6 +1980,55 @@ describe("cindy · 卡槽③(xdt_card_id 提升 + agentToolUseId 提取)", () =>});describe('connect_account transport', () => {+ it('exposes cloud market discovery/install only when the Host supplies them', async () => {+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');+ const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');+ const searchMarket = vi.fn(async () => ({ ok: true, plugins: [] }));+ const installMarket = vi.fn(async () => ({ ok: true, ghostId: 'example-plugin', installed: true }));+ const server = createCindyGhostsMcpServer(fakeDeps({ searchMarket, installMarket }));+ const client = new Client({ name: 'market-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair(); await server.connect(st); await client.connect(ct);+ try {+ expect((await client.listTools()).tools.map(t => t.name)).toEqual(expect.arrayContaining(['ghost_market_search', 'ghost_market_install']));+ await client.callTool({ name: 'ghost_market_search', arguments: { query: 'calendar' } });+ expect(searchMarket).toHaveBeenCalledWith('calendar');+ await client.callTool({ name: 'ghost_market_install', arguments: { plugin_id: 'catalog-plugin', release_id: 'release-1' } });+ expect(installMarket).toHaveBeenCalledWith({ pluginId: 'catalog-plugin', releaseId: 'release-1' }, expect.any(AbortSignal));+ const rejected = await client.callTool({ name: 'ghost_market_install', arguments: { plugin_id: 'catalog-plugin' } });+ expect(rejected.isError).toBe(true); expect(installMarket).toHaveBeenCalledTimes(1);+ } finally { await client.close(); await server.close(); }+ });+ it('propagates MCP cancellation to the exact Host tool call', async () => {+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');+ const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');+ let started!: () => void;+ const ready = new Promise<void>((resolve) => { started = resolve; });+ let aborted!: () => void;+ const cancelled = new Promise<void>((resolve) => { aborted = resolve; });+ const server = createCindyGhostsMcpServer(fakeDeps({+ callGhostTool: async ({ signal }) => {+ expect(signal).toBeInstanceOf(AbortSignal);+ started();+ await new Promise<void>((resolve) => signal!.addEventListener('abort', () => {+ aborted(); resolve();+ }, { once: true }));+ return { ok: false, errorCode: 'INTERNAL', message: 'cancelled' };+ },+ }));+ const client = new Client({ name: 'cancel-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await server.connect(st); await client.connect(ct);+ try {+ const controller = new AbortController();+ const call = client.callTool({ name: 'ghost_call', arguments: {+ ghost_id: 'art', tool: 'gen_image',+ } }, undefined, { signal: controller.signal });+ const rejected = expect(call).rejects.toBeDefined();+ await ready; controller.abort();+ await rejected; await cancelled;+ } finally { await client.close(); await server.close(); }+ });+it('exposes a Host connection without requiring an installed plugin', async () => {const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');@@ -1992,12 +2041,36 @@ describe('connect_account transport', () => {const tools = await client.listTools();expect(tools.tools.some(tool => tool.name === 'connect_account')).toBe(true);await client.callTool({ name: 'connect_account', arguments: { kind: 'host', id: 'grok' } });- expect(connectAccount).toHaveBeenCalledWith({ kind: 'host', id: 'grok', reauthorize: undefined });+ expect(connectAccount).toHaveBeenCalledWith({ kind: 'host', id: 'grok', reauthorize: undefined }, expect.any(AbortSignal));const rejected = await client.callTool({ name: 'connect_account', arguments: { kind: 'host', id: 'invented' } });expect(rejected.isError).toBe(true);expect(connectAccount).toHaveBeenCalledTimes(1);} finally { await client.close(); await server.close(); }});++ it('forwards MCP cancellation to the ordinary connection waiter', async () => {+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');+ const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');+ let started!: () => void, cancelled!: () => void;+ const ready = new Promise<void>(resolve => { started = resolve; });+ const aborted = new Promise<void>(resolve => { cancelled = resolve; });+ const server = createCindyGhostsMcpServer(fakeDeps({ connectAccount: async (_target, signal) => {+ expect(signal).toBeInstanceOf(AbortSignal); started();+ return new Promise(resolve => signal!.addEventListener('abort', () => {+ cancelled(); resolve({ ok: false, errorCode: 'SETUP_CANCELLED' });+ }, { once: true }));+ } }));+ const client = new Client({ name: 'connection-cancel', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await server.connect(st); await client.connect(ct);+ try {+ const controller = new AbortController();+ const result = client.callTool({ name: 'connect_account', arguments: { kind: 'plugin', id: 'calendar' } },+ undefined, { signal: controller.signal });+ const rejected = expect(result).rejects.toBeDefined();+ await ready; controller.abort(); await rejected; await aborted;+ } finally { await client.close(); await server.close(); }+ });});describe('Cindy market MCP transport', () => {@@ -2027,7 +2100,7 @@ describe('Cindy market MCP transport', () => {expect(callGhostTool).not.toHaveBeenCalled();await client.callTool({ name: 'ghost_info', arguments: { ghost_id: 'art' } });await client.callTool({ name: 'connect_account', arguments: { kind: 'plugin', id: 'art' } });- expect(connectAccount).toHaveBeenCalledWith({ kind: 'plugin', id: 'art', reauthorize: undefined });+ expect(connectAccount).toHaveBeenCalledWith({ kind: 'plugin', id: 'art', reauthorize: undefined }, expect.any(AbortSignal));expect(callGhostTool).not.toHaveBeenCalled();// Host authorization continuation retries the original work through the same gateway.await client.callTool({ name: 'ghost_call', arguments: { ghost_id: 'art', tool: 'gen_image', args: {} } });diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex cd2c9240ea..1d430798a8 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -899,12 +899,14 @@ export async function handleGhostCall(setup_plan?: GhostSetupPlanInput;},agentToolUseId?: string,+ signal?: AbortSignal,): Promise<McpTextResult> {try {const result = await deps.callGhostTool({ghostId: input.ghost_id,tool: input.tool,args: input.args ?? {},+ ...(signal ? { signal } : {}),...(input.grant_only === true ? { grantOnly: true } : {}),...(input.attachments && input.attachments.length > 0? { attachments: input.attachments }@@ -1243,12 +1245,12 @@ export function createCindyGhostsMcpServer(if (deps.connectAccount) server.tool("connect_account",- "Request an account connection card in a teammate conversation. For a built-in Grok account use kind=host, id=grok; for an installed plugin use kind=plugin and its real ghost_id. Do not invent connectors, URLs or credentials. The card returns immediately; finish unrelated work and end the turn. The Host resumes you after authorization succeeds. Grok login does not authorize X or change your model.",- { kind: z.enum(["host", "plugin"]), id: z.string().min(1).max(256), reauthorize: z.boolean().optional().describe("Only for an explicit reconnect request or a known authorization/scope failure") },- async ({ kind, id, reauthorize }) => {+ "Request an account connection for an installed plugin in the current conversation: kind=plugin and its real ghost_id. The Host presents its supported setup card, including protected manual connection forms, without calling a plugin business tool. Use reauthorize=true when the user asks to reconnect, replace a token, update authorization, or reconfigure an existing connection; saved configuration must not skip that request. Ordinary tasks wait until setup completes or is cancelled; teammate tasks may return a pending card immediately, then the Host resumes them after authorization. Follow the returned status and do not infer provider access from setup readiness. Only if the Host reports no supported setup action, follow the installed plugin's documented login method on the machine running the task. Never request credentials in chat or tool arguments. Built-in Grok login (kind=host, id=grok) remains available only in teammate conversations and does not authorize X or change your model. Do not invent connectors, URLs or credentials.",+ { kind: z.enum(["host", "plugin"]), id: z.string().min(1).max(256), reauthorize: z.boolean().optional().describe("Reopen supported setup for an explicit reconnect, token replacement, authorization update or reconfiguration request, or a known authorization/scope failure") },+ async ({ kind, id, reauthorize }, extra) => {if (kind === "host" && id !== "grok") return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, errorCode: "UNSUPPORTED_CONNECTION" }) }], isError: true };try {- const result = await deps.connectAccount!(kind === "host" ? { kind, id: "grok", reauthorize } : { kind, id, reauthorize });+ const result = await deps.connectAccount!(kind === "host" ? { kind, id: "grok", reauthorize } : { kind, id, reauthorize }, extra.signal);return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };} catch {return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, errorCode: "CONNECTION_UNAVAILABLE" }) }], isError: true };@@ -1327,7 +1329,7 @@ export function createCindyGhostsMcpServer(),},async (input, extra) =>- handleGhostCall(deps, input, extractAgentToolUseId(extra)),+ handleGhostCall(deps, input, extractAgentToolUseId(extra), extra.signal),);server.tool(diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.tsindex 7988172265..9d52e0706d 100644--- a/packages/cindy-tools/src/types.ts+++ b/packages/cindy-tools/src/types.ts@@ -353,7 +353,7 @@ export interface CindyGhostsMcpDeps {searchMarket?(query: string): Promise<Record<string, unknown>>;installMarket?(request: { pluginId: string; releaseId: string }, signal?: AbortSignal): Promise<Record<string, unknown>>;/** Host-owned connection card. No URLs or credentials may be supplied by the model. */- connectAccount?(target: { kind: 'plugin'; id: string; reauthorize?: boolean } | { kind: 'host'; id: 'grok'; reauthorize?: boolean }): Promise<Record<string, unknown>>;+ connectAccount?(target: { kind: 'plugin'; id: string; reauthorize?: boolean } | { kind: 'host'; id: 'grok'; reauthorize?: boolean }, signal?: AbortSignal): Promise<Record<string, unknown>>;/** Cindy Core 原生媒体调用器;能力本身不依赖任何插件。 */callMedia?(request: CindyMediaToolRequest): Promise<Record<string, unknown>>;/**@@ -381,6 +381,8 @@ export interface CindyGhostsMcpDeps {ghostId: string;tool: string;args: Record<string, unknown>;+ /** Host-only cancellation from the MCP request; never enters plugin args. */+ signal?: AbortSignal;/*** 媒体过户(可选):会话里用户媒体或当前 Agent / Core 工具生成结果的* 地址(xdt-image:// / cindy-media://blobs/ / 本机绝对路径,主机归一化并验归属)。diff --git a/packages/device-link/README.md b/packages/device-link/README.mdindex 4fe7f77032..59a4cd0bdf 100644--- a/packages/device-link/README.md+++ b/packages/device-link/README.md@@ -161,3 +161,13 @@| server 中继(presence / 路由 / pub-sub) | `apps/server/src/device-link/*` || 被控端 dispatch(双层校验 + 合成 event) | `apps/desktop/src/main/device-link/dispatch.ts` || 桌面控制端传输路由(本地/远程按 session 切换) | `apps/desktop/src/renderer/lib/makerTransport.ts` |++## Remote plugin authorization transport v3++`device-link:plugin-oauth:v3` is a Host-only signed/encrypted channel carried by the existing authorized account route. It does not require CIS or an instance identity endpoint. Both Desktops must support v3; older peers fail without falling back to raw setup, plaintext input, v1 or the separate cloud v2 protocol.++A Host lazily persists a separate Ed25519 signing key in OS secure storage. The controller resolves the exact realm/membership/device descriptor over Device Link, verifies the signed card/nonce/ephemeral-key transcript, then pins the peer public key in its own encrypted owner-scoped store. Restarts retain the key and change the boot identifier; changed peer keys are rejected. **First admission trusts account services and the relay**, like upstream same-account key registration; this does not protect first contact against a malicious relay and is not mutual attestation.++All inner offers, callbacks, codes and private form values use authenticated encryption. Local Renderer supplies card IDs or one-shot protected input to dedicated local IPC; it cannot invoke this channel directly. A short-lived user code can be displayed/copied only on its initiating local card. Tokens, callback codes, full URLs and state stay out of card snapshots, logs, history and the model. Capability flags are additive and must be explicitly negotiated.++See [remote-plugin-oauth.md](../../docs/remote-plugin-oauth.md) for exact shapes, target validation, supported adapters, lifecycle and trust limits. No relay/Auth/Model Access deployment is introduced.diff --git a/packages/device-link/src/__tests__/pluginAuthorization.test.ts b/packages/device-link/src/__tests__/pluginAuthorization.test.tsnew file mode 100644index 0000000000..0fa4f33ff4--- /dev/null+++ b/packages/device-link/src/__tests__/pluginAuthorization.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from "vitest";+import {+ parsePluginAuthorizationRequest,+ parsePluginAuthorizationOffer,+ parsePluginAuthorizationResult,+} from "../pluginAuthorization.js";+import { parsePluginOauthRequest } from "../pluginOauth.js";++function loopback() {+ const callbackUrl = "http://127.0.0.1:45678/callback";+ const state = "cli_state_0123456789";+ const url = new URL("https://provider.example/authorize");+ url.search = new URLSearchParams({+ client_id: "fixture-client",+ response_type: "code",+ state,+ redirect_uri: callbackUrl,+ code_challenge: "s".repeat(43),+ code_challenge_method: "S256",+ }).toString();+ return { kind: "loopback" as const, url: url.toString(), callbackUrl, state };+}++describe("private extensible authorization schema", () => {+ it.each(["ABCD-EFGH", "abcDEF123", "123456", "AB CD EF"])(+ "preserves a provider user code %s",+ (userCode) => {+ const request = {+ kind: "device",+ url: "https://provider.example/activate",+ userCode,+ };+ expect(parsePluginAuthorizationRequest(request)).toEqual(request);+ },+ );+ it.each(["", "a".repeat(33), "code\n", "<script>", "token=secret", "A\tB"])(+ "rejects non-display code %j",+ (userCode) => {+ expect(() =>+ parsePluginAuthorizationRequest({+ kind: "device",+ url: "https://provider.example",+ userCode,+ }),+ ).toThrow();+ },+ );+ it("accepts browser confirmation without claiming access to its cookies", () => {+ expect(+ parsePluginAuthorizationRequest({+ kind: "browser",+ url: "https://provider.example/qr?request=fixture",+ }),+ ).toMatchObject({ kind: "browser" });+ expect(() =>+ parsePluginAuthorizationRequest({+ kind: "browser",+ url: "https://provider.example",+ cookies: [],+ }),+ ).toThrow();+ });+ it.each(["command", "token", "device_code", "secret", "callbackUrl"])(+ "rejects extra device parameter %s",+ (key) => {+ expect(() =>+ parsePluginAuthorizationRequest({+ kind: "device",+ url: "https://provider.example",+ [key]: "private",+ }),+ ).toThrow();+ },+ );+ it.each([+ "http://provider.example",+ "file:///tmp",+ "https://127.0.0.1",+ "https://[::1]",+ "https://provider.example:8443",+ ])("rejects authorization URL %s", (url) => {+ expect(() =>+ parsePluginAuthorizationRequest({ kind: "browser", url }),+ ).toThrow();+ });+ it("requires exact redirect, state and S256, never implicit grants", () => {+ const valid = loopback();+ expect(parsePluginAuthorizationRequest(valid)).toEqual(valid);+ for (const [key, value] of Object.entries({+ state: "different_state_fixture",+ redirect_uri: "http://127.0.0.1:45678/other",+ response_type: "token",+ code_challenge_method: "plain",+ code_challenge: "invalid",+ client_id: "",+ })) {+ const url = new URL(valid.url);+ url.searchParams.set(key, value);+ expect(() =>+ parsePluginAuthorizationRequest({ ...valid, url: url.toString() }),+ ).toThrow();+ }+ const url = new URL(valid.url);+ url.searchParams.append("state", valid.state);+ expect(() =>+ parsePluginAuthorizationRequest({ ...valid, url: url.toString() }),+ ).toThrow();+ });+ it.each(["http://localhost:45678/cb", "http://[::1]:45678/cb"])(+ "supports literal loopback %s",+ (callbackUrl) => {+ const valid = loopback(),+ url = new URL(valid.url);+ url.searchParams.set("redirect_uri", callbackUrl);+ expect(+ parsePluginAuthorizationRequest({+ ...valid,+ url: url.toString(),+ callbackUrl,+ }),+ ).toMatchObject({ callbackUrl });+ },+ );+ it.each([+ "http://127.0.0.2:45678/cb",+ "http://internal.example:45678/cb",+ "http://127.0.0.1:80/cb",+ "http://[email protected]:45678/cb",+ "http://127.0.0.1:45678/cb?next=x",+ ])("rejects callback target %s", (callbackUrl) => {+ const valid = loopback(),+ url = new URL(valid.url);+ url.searchParams.set("redirect_uri", callbackUrl);+ expect(() =>+ parsePluginAuthorizationRequest({+ ...valid,+ url: url.toString(),+ callbackUrl,+ }),+ ).toThrow();+ });+ it("keeps bridge state separate and validates private results", () => {+ const offer = {+ kind: "authorization",+ state: "b".repeat(43),+ request: loopback(),+ };+ expect(parsePluginAuthorizationOffer(offer)).toEqual(offer);+ expect(+ parsePluginAuthorizationResult({+ kind: "callback",+ state: loopback().state,+ code: "synthetic-code",+ }),+ ).toMatchObject({ kind: "callback" });+ for (const raw of [+ { kind: "callback", state: "bad", code: "x" },+ { kind: "opened", token: "x" },+ { kind: "callback", state: loopback().state, code: "x", error: "denied" },+ ])+ expect(() => parsePluginAuthorizationResult(raw)).toThrow();+ });+ it("negotiates additively without accepting false flags or unrecognized capabilities", () => {+ const start = {+ op: "start",+ requestId: "card",+ actionId: "action",+ expectedRevision: 0,+ publicKey: "a".repeat(59),+ };+ expect(parsePluginOauthRequest(start)).toEqual(start);+ expect(+ parsePluginOauthRequest({ ...start, authorizationV1: true }),+ ).toMatchObject({ authorizationV1: true });+ expect(+ parsePluginOauthRequest({ ...start, authorizationV1: false }),+ ).toBeNull();+ expect(+ parsePluginOauthRequest({ ...start, arbitraryAdapter: true }),+ ).toBeNull();+ });+});diff --git a/packages/device-link/src/__tests__/pluginConnectionSubmission.test.ts b/packages/device-link/src/__tests__/pluginConnectionSubmission.test.tsnew file mode 100644index 0000000000..203df284ea--- /dev/null+++ b/packages/device-link/src/__tests__/pluginConnectionSubmission.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import {+ normalizePluginConnectionHost,+ parsePluginConnectionInput,+ parsePluginConnectionValue,+ PLUGIN_CONNECTION_LOCAL_CHANNEL,+} from "../pluginConnectionSubmission.js";+import { parsePluginOauthRequest } from "../pluginOauth.js";+import { REMOTE_INVOKE_ALLOWLIST } from "../allowlist.js";++describe("connection input wire contract", () => {+ it.each([+ "git.example.test",+ "https://GIT.example.test/",+ "https://git.example.test:443/",+ ])("accepts an exact HTTPS host: %s", (host) => {+ expect(normalizePluginConnectionHost(host)).toBe("git.example.test");+ });+ it.each([+ "http://git.example.test",+ "https://git.example.test:8443",+ "*.example.test",+ "https://git.example.test/path",+ "https://git.example.test/?token=x",+ "https://u:[email protected]",+ "https://git.example.test/path/..",+ "https://%67it.example.test/",+ "https://git.example.test/#fragment",+ "https://127.0.0.1",+ "https://[::1]",+ "git.example.test:443",+ "https://git.example.test\\@evil.test",+ "localhost",+ ])("rejects ambiguous target %s", (host) => {+ expect(() => normalizePluginConnectionHost(host)).toThrow();+ });+ it.each([+ "",+ "x".repeat(4097),+ "a\r\nINJECTED: header",+ "a\u0000b",+ "with space",+ ])("rejects invalid token %#", (token) => {+ expect(() =>+ parsePluginConnectionInput({ host: "git.example.test", token }),+ ).toThrow();+ });+ it("rejects unknown fields and a secret-value disguised as a connection", () => {+ expect(() =>+ parsePluginConnectionInput({+ host: "git.example.test",+ token: "synthetic",+ path: "/vault",+ }),+ ).toThrow();+ expect(() =>+ parsePluginConnectionValue({+ kind: "secret-value",+ state: "a".repeat(43),+ value: "synthetic",+ }),+ ).toThrow();+ });+ it("requires explicit additive capability and keeps the local input off the remote allowlist", () => {+ const base = {+ op: "start",+ requestId: "request",+ actionId: "connection",+ expectedRevision: 1,+ publicKey: "a".repeat(59),+ };+ expect(+ parsePluginOauthRequest({ ...base, connectionSubmission: true }),+ ).toMatchObject({ connectionSubmission: true });+ expect(+ parsePluginOauthRequest({ ...base, connectionSubmission: false }),+ ).toBeNull();+ expect(REMOTE_INVOKE_ALLOWLIST.has(PLUGIN_CONNECTION_LOCAL_CHANNEL)).toBe(+ false,+ );+ });+});diff --git a/packages/device-link/src/__tests__/pluginSecretSubmission.test.ts b/packages/device-link/src/__tests__/pluginSecretSubmission.test.tsnew file mode 100644index 0000000000..71ca8a63d6--- /dev/null+++ b/packages/device-link/src/__tests__/pluginSecretSubmission.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";+import { REMOTE_INVOKE_ALLOWLIST } from "../allowlist.js";+import { parsePluginOauthRequest } from "../pluginOauth.js";+import {+ PLUGIN_SECRET_LOCAL_CHANNEL,+ parsePluginSecretOffer,+ parsePluginSecretPresentation,+ parsePluginSecretInput,+ parsePluginSecretValue,+} from "../pluginSecretSubmission.js";++const presentation = {+ ghostName: "Demo",+ title: "Configure",+ description: "Enter API key",+ intro: "",+ fieldLabel: "API key",+ fieldDescription: "",+ maxLength: 200,+};+const state = "s".repeat(43);+describe("dedicated private secret input schema", () => {+ it("is not a generic remotely invokable channel and requires explicit capability negotiation", () => {+ expect(REMOTE_INVOKE_ALLOWLIST.has(PLUGIN_SECRET_LOCAL_CHANNEL)).toBe(+ false,+ );+ const start = {+ op: "start",+ requestId: "card",+ actionId: "action",+ expectedRevision: 0,+ publicKey: "k".repeat(59),+ };+ expect(+ parsePluginOauthRequest({ ...start, secretSubmission: true }),+ ).toMatchObject({ secretSubmission: true });+ expect(+ parsePluginOauthRequest({ ...start, secretSubmission: false }),+ ).toBeNull();+ });+ it("binds the full displayed field but never accepts a caller-supplied storage key or path", () => {+ expect(+ parsePluginSecretOffer({ kind: "secret-entry", state, presentation }),+ ).toEqual({ kind: "secret-entry", state, presentation });+ for (const extra of [+ { storageKey: "another" },+ { path: "/tmp/other" },+ { token: "synthetic" },+ ]) {+ expect(() =>+ parsePluginSecretOffer({+ kind: "secret-entry",+ state,+ presentation,+ ...extra,+ }),+ ).toThrow();+ expect(() =>+ parsePluginSecretValue({+ kind: "secret-value",+ state,+ value: "synthetic",+ ...extra,+ }),+ ).toThrow();+ }+ for (const invalid of [+ { ...presentation, title: undefined },+ { ...presentation, maxLength: 4097 },+ { ...presentation, fieldLabel: "" },+ { ...presentation, maxLength: 0 },+ { ...presentation, command: "ignored" },+ ])+ expect(() => parsePluginSecretPresentation(invalid)).toThrow();+ });+ it.each(["", " ", "x".repeat(4097), "null\u0000byte"])(+ "rejects malformed values without echoing input",+ (value) => {+ expect(() => parsePluginSecretInput(value)).toThrow(+ "PLUGIN_SECRET_UNAVAILABLE",+ );+ try {+ parsePluginSecretValue({ kind: "secret-value", state, value });+ throw new Error("accepted");+ } catch (error) {+ expect((error as Error).message).toBe("PLUGIN_SECRET_UNAVAILABLE");+ }+ },+ );+ it("preserves accepted input exactly and validates it without a transaction state", () => {+ const value = " synthetic-pat\twith whitespace ";+ expect(parsePluginSecretInput(value)).toBe(value);+ expect(+ parsePluginSecretValue({ kind: "secret-value", state, value }).value,+ ).toBe(value);+ for (const invalid of [null, undefined, 1, {}, []])+ expect(() => parsePluginSecretInput(invalid)).toThrow(+ "PLUGIN_SECRET_UNAVAILABLE",+ );+ });+});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 5103279a92..e73ec7e309 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -601,6 +601,8 @@ export const REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS: ReadonlySet<string> = new Seexport const REMOTE_INVOKE_ALLOWLIST: ReadonlySet<string> = new Set([// Same-account owner controls only; guest task dispatch has its own deny-by-default gate.'maker:shared-task',+ // Dedicated Host-only OAuth transaction. Args/replies are never forwarded to Renderer.+ 'device-link:plugin-oauth:v3','device-link:remote-desktop:v1',...CORE_INVOKE_CHANNELS,...EXTENDED_INVOKE_CHANNELS,diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 35bf406b6a..623923715e 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -41,3 +41,10 @@ export * from "./sessionListTransport.js";export * from "./clipboardSync.js";export * from "./clipboardSyncFailure.js";export * from "./clipboardTransfer.js";++export * from "./pluginOauth.js";+export * from "./pluginAuthorization.js";+export * from "./pluginSecretSubmission.js";+export * from "./pluginConnectionSubmission.js";+export * from "./pluginDeviceAuthorization.js";+export * from "./pluginOauthAuthentication.js";diff --git a/packages/device-link/src/pluginAuthorization.ts b/packages/device-link/src/pluginAuthorization.tsnew file mode 100644index 0000000000..e2c2f45eda--- /dev/null+++ b/packages/device-link/src/pluginAuthorization.ts@@ -0,0 +1,183 @@+import { parseDeviceAuthorizationUrl } from "./pluginDeviceAuthorization.js";++/**+ * Private Host/Node authorization requests. These values never belong in tool+ * results, card snapshots or ordinary device-link invokes.+ */+export type PluginAuthorizationRequest =+ | { kind: "device"; url: string; userCode?: string; expiresAt?: number }+ | { kind: "browser"; url: string; expiresAt?: number }+ | { kind: "loopback"; url: string; callbackUrl: string; state: string };++/** Additive offer, used only after both Hosts negotiate authorizationV1. */+export interface PluginAuthorizationOffer {+ kind: "authorization";+ state: string;+ request: PluginAuthorizationRequest;+}++/** Private bootstrap return, never a JSON-RPC tool result. Opened is not connected. */+export type PluginAuthorizationResult =+ | { kind: "opened" }+ | { kind: "callback"; state: string; code: string }+ | { kind: "callback"; state: string; error: string };++const fail = () => new Error("PLUGIN_AUTHORIZATION_INVALID");+const object = (v: unknown): Record<string, unknown> => {+ if (!v || typeof v !== "object" || Array.isArray(v)) throw fail();+ return v as Record<string, unknown>;+};+function exact(v: Record<string, unknown>, keys: string[]): void {+ if (+ Object.keys(v).length !== keys.length ||+ keys.some((k) => !Object.hasOwn(v, k))+ )+ throw fail();+}++/** Human-entered code, not device_code or an access token. Never normalize it. */+export function parseAuthorizationUserCode(value: unknown): string {+ if (+ typeof value !== "string" ||+ !/^[A-Za-z0-9](?:[A-Za-z0-9 -]{0,30}[A-Za-z0-9])?$/.test(value)+ )+ throw fail();+ return value;+}++function publicUrl(raw: unknown): string {+ const url = new URL(parseDeviceAuthorizationUrl(raw));+ if (url.port) throw fail();+ return url.toString();+}++/** A listener address, never an address the Host may fetch or forward a port to. */+export function parseAuthorizationCallbackUrl(raw: unknown): string {+ if (typeof raw !== "string" || raw.length > 2048 || /[\x00-\x20\\]/.test(raw))+ throw fail();+ const url = new URL(raw);+ if (+ url.protocol !== "http:" ||+ !["127.0.0.1", "[::1]", "localhost"].includes(url.hostname) ||+ !url.port ||+ Number(url.port) < 1024 ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ )+ throw fail();+ return url.toString();+}++export function parsePluginAuthorizationRequest(+ raw: unknown,+): PluginAuthorizationRequest {+ const v = object(raw);+ const url = publicUrl(v.url);+ if (v.kind === "device" || v.kind === "browser") {+ exact(v, [+ "kind",+ "url",+ ...(v.userCode === undefined ? [] : ["userCode"]),+ ...(v.expiresAt === undefined ? [] : ["expiresAt"]),+ ]);+ if (v.kind === "browser" && v.userCode !== undefined) throw fail();+ if (+ v.expiresAt !== undefined &&+ (!Number.isSafeInteger(v.expiresAt) || (v.expiresAt as number) <= 0)+ )+ throw fail();+ return {+ kind: v.kind,+ url,+ ...(v.userCode === undefined+ ? {}+ : { userCode: parseAuthorizationUserCode(v.userCode) }),+ ...(v.expiresAt === undefined+ ? {}+ : { expiresAt: v.expiresAt as number }),+ };+ }+ if (v.kind === "loopback") {+ exact(v, ["kind", "url", "callbackUrl", "state"]);+ if (+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9._~-]{16,512}$/.test(v.state)+ )+ throw fail();+ const callbackUrl = parseAuthorizationCallbackUrl(v.callbackUrl);+ const params = new URL(url).searchParams;+ for (const key of [+ "state",+ "redirect_uri",+ "response_type",+ "client_id",+ "code_challenge",+ "code_challenge_method",+ ])+ if (params.getAll(key).length !== 1) throw fail();+ // The CLI owns the PKCE verifier and token exchange. The bridge only delivers+ // one callback; it cannot turn itself into an implicit grant or open proxy.+ if (+ params.get("state") !== v.state ||+ params.get("redirect_uri") !== callbackUrl ||+ params.get("response_type") !== "code" ||+ !params.get("client_id") ||+ params.get("code_challenge_method") !== "S256" ||+ !/^[A-Za-z0-9_-]{43}$/.test(params.get("code_challenge") ?? "")+ )+ throw fail();+ return { kind: v.kind, url, callbackUrl, state: v.state };+ }+ throw fail();+}++export function parsePluginAuthorizationOffer(+ raw: unknown,+): PluginAuthorizationOffer {+ const v = object(raw);+ exact(v, ["kind", "state", "request"]);+ if (+ v.kind !== "authorization" ||+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9_-]{43}$/.test(v.state)+ )+ throw fail();+ return {+ kind: v.kind,+ state: v.state,+ request: parsePluginAuthorizationRequest(v.request),+ };+}++export function parsePluginAuthorizationResult(+ raw: unknown,+): PluginAuthorizationResult {+ const v = object(raw);+ if (v.kind === "opened") {+ exact(v, ["kind"]);+ return { kind: "opened" };+ }+ if (+ v.kind !== "callback" ||+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9._~-]{16,512}$/.test(v.state)+ )+ throw fail();+ if (v.code !== undefined) {+ exact(v, ["kind", "state", "code"]);+ if (+ typeof v.code !== "string" ||+ !v.code ||+ v.code.length > 8192 ||+ /[\x00-\x1f]/.test(v.code)+ )+ throw fail();+ return { kind: v.kind, state: v.state, code: v.code };+ }+ exact(v, ["kind", "state", "error"]);+ if (typeof v.error !== "string" || !/^[a-zA-Z0-9_.-]{1,128}$/.test(v.error))+ throw fail();+ return { kind: v.kind, state: v.state, error: v.error };+}diff --git a/packages/device-link/src/pluginConnectionSubmission.ts b/packages/device-link/src/pluginConnectionSubmission.tsnew file mode 100644index 0000000000..0a431f55d1--- /dev/null+++ b/packages/device-link/src/pluginConnectionSubmission.ts@@ -0,0 +1,129 @@+/** Local trusted form only. Never expose this IPC through the remote allowlist. */+export const PLUGIN_CONNECTION_LOCAL_CHANNEL = "plugin-oauth:submit-connection";+export interface PluginConnectionInput {+ host: string;+ token: string;+}+export interface PluginConnectionPresentation {+ ghostName: string;+ title: string;+ description: string;+ intro: string;+ connectionKey: string;+}+export interface PluginConnectionOffer {+ kind: "connection-entry";+ state: string;+ presentation: PluginConnectionPresentation;+}+export interface PluginConnectionValue {+ kind: "connection-value";+ state: string;+ value: PluginConnectionInput;+}+const fail = () => new Error("PLUGIN_CONNECTION_UNAVAILABLE");+function exact(raw: unknown, keys: string): Record<string, unknown> {+ if (+ !raw ||+ typeof raw !== "object" ||+ Array.isArray(raw) ||+ Object.keys(raw).sort().join(",") !== keys.split(" ").sort().join(",")+ )+ throw fail();+ return raw as Record<string, unknown>;+}+/** HTTPS default port and a single exact DNS host. Never a wildcard, path or IP. */+export function normalizePluginConnectionHost(raw: unknown): string {+ if (typeof raw !== "string" || raw.length > 512) throw fail();+ const text = raw.trim();+ if (!text || /[\s\\]/u.test(text)) throw fail();+ let host = text.toLowerCase();+ if (text.includes("://")) {+ // Validate before URL normalizes dot-segments or escaped host characters.+ if (!/^https:\/\/[a-z0-9.-]+(?::443)?\/?$/iu.test(text)) throw fail();+ let url: URL;+ try {+ url = new URL(text);+ } catch {+ throw fail();+ }+ if (+ url.protocol !== "https:" ||+ url.port ||+ url.username ||+ url.password ||+ url.pathname !== "/" ||+ url.search ||+ url.hash+ )+ throw fail();+ host = url.hostname;+ }+ if (+ host.length > 253 ||+ !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/u.test(+ host,+ ) ||+ /^[0-9.]+$/u.test(host)+ )+ throw fail();+ return host;+}+export function parsePluginConnectionInput(+ raw: unknown,+): PluginConnectionInput {+ const value = exact(raw, "host token");+ if (typeof value.token !== "string") throw fail();+ const token = value.token.trim();+ if (!token || token.length > 4096 || /[\x00-\x20\x7f]/u.test(token))+ throw fail();+ return { host: normalizePluginConnectionHost(value.host), token };+}+export function parsePluginConnectionPresentation(+ raw: unknown,+): PluginConnectionPresentation {+ const value = exact(raw, "ghostName title description intro connectionKey");+ if (+ Object.values(value).some(+ (v) => typeof v !== "string" || v.length > 4096,+ ) ||+ !value.ghostName ||+ typeof value.connectionKey !== "string" ||+ !/^[a-zA-Z0-9_-]{1,128}$/u.test(value.connectionKey)+ )+ throw fail();+ return {+ ghostName: value.ghostName as string,+ title: value.title as string,+ description: value.description as string,+ intro: value.intro as string,+ connectionKey: value.connectionKey,+ };+}+function state(raw: unknown): string {+ if (typeof raw !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(raw))+ throw fail();+ return raw;+}+export function parsePluginConnectionOffer(+ raw: unknown,+): PluginConnectionOffer {+ const value = exact(raw, "kind state presentation");+ if (value.kind !== "connection-entry") throw fail();+ return {+ kind: value.kind,+ state: state(value.state),+ presentation: parsePluginConnectionPresentation(value.presentation),+ };+}+export function parsePluginConnectionValue(+ raw: unknown,+): PluginConnectionValue {+ const value = exact(raw, "kind state value");+ if (value.kind !== "connection-value") throw fail();+ return {+ kind: value.kind,+ state: state(value.state),+ value: parsePluginConnectionInput(value.value),+ };+}diff --git a/packages/device-link/src/pluginDeviceAuthorization.ts b/packages/device-link/src/pluginDeviceAuthorization.tsnew file mode 100644index 0000000000..0af239177a--- /dev/null+++ b/packages/device-link/src/pluginDeviceAuthorization.ts@@ -0,0 +1,70 @@+/** Device/CLI authorization: the initiating Host polls; the controller only opens a URL. */+export interface PluginDeviceOffer {+ kind: "device";+ authorizeUrl: string;+ state: string;+ /** Private offer only; never card/message metadata. Requires deviceUserCode capability. */+ userCode?: string;+}+export interface PluginDeviceOpened {+ kind: "device-opened";+ state: string;+}+const fail = () => new Error("OAUTH_BRIDGE_UNAVAILABLE");++export function parseDeviceAuthorizationUrl(value: unknown): string {+ if (+ typeof value !== "string" ||+ value.length > 8192 ||+ /[\x00-\x20\\]/.test(value)+ )+ throw fail();+ const url = new URL(value);+ if (+ url.protocol !== "https:" ||+ url.username ||+ url.password ||+ url.hash ||+ !/^[a-z0-9.-]+$/i.test(url.hostname) ||+ !url.hostname.includes(".") ||+ /^(?:\d+\.)+\d+$/.test(url.hostname) ||+ url.hostname.endsWith(".localhost")+ )+ throw fail();+ return url.toString();+}+export function parsePluginDeviceOffer(value: unknown): PluginDeviceOffer {+ if (!value || typeof value !== "object" || Array.isArray(value)) throw fail();+ const v = value as Record<string, unknown>;+ if (+ Object.keys(v).sort().join(",") !==+ (v.userCode === undefined+ ? "authorizeUrl,kind,state"+ : "authorizeUrl,kind,state,userCode") ||+ (v.userCode !== undefined &&+ (typeof v.userCode !== "string" ||+ !/^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(v.userCode))) ||+ v.kind !== "device" ||+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9_-]{43}$/.test(v.state)+ )+ throw fail();+ return {+ kind: "device",+ authorizeUrl: parseDeviceAuthorizationUrl(v.authorizeUrl),+ state: v.state,+ ...(v.userCode !== undefined ? { userCode: v.userCode as string } : {}),+ };+}+export function parsePluginDeviceOpened(+ value: unknown,+): PluginDeviceOpened | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const v = value as Record<string, unknown>;+ return Object.keys(v).sort().join(",") === "kind,state" &&+ v.kind === "device-opened" &&+ typeof v.state === "string" &&+ /^[A-Za-z0-9_-]{43}$/.test(v.state)+ ? { kind: "device-opened", state: v.state }+ : null;+}diff --git a/packages/device-link/src/pluginOauth.ts b/packages/device-link/src/pluginOauth.tsnew file mode 100644index 0000000000..2dcd95d986--- /dev/null+++ b/packages/device-link/src/pluginOauth.ts@@ -0,0 +1,158 @@+/** Host-to-Host OAuth control only. Never expose its replies to a Renderer. */+export const PLUGIN_OAUTH_CHANNEL = "device-link:plugin-oauth:v3";+export const PLUGIN_OAUTH_LOCAL_CHANNEL = "plugin-oauth:assist";+export const PLUGIN_OAUTH_TTL_MS = 5 * 60_000;++export interface PluginOauthAction {+ requestId: string;+ actionId: string;+ expectedRevision: number;+}++export type PluginOauthRequest =+ | { op: "capabilities" }+ | ({+ op: "start";+ publicKey: string;+ deviceUserCode?: true;+ authorizationV1?: true;+ secretSubmission?: true;+ connectionSubmission?: true;+ } & PluginOauthAction)+ | { op: "status"; id: string }+ | { op: "cancel"; id: string }+ | { op: "callback"; id: string; box: string };++export type PluginOauthPhase =+ | "starting"+ | "authorizing"+ | "exchanging"+ | "succeeded"+ | "failed"+ | "cancelled";+export interface PluginOauthOffer {+ authorizeUrl: string;+ callbackUrl: string;+ state: string;+ corsOrigins: string[];+ corsHosts: string[];+}+export type PluginOauthCallback =+ { state: string; code: string } | { state: string; error: string };++function record(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}+function exact(v: Record<string, unknown>, keys: string[]) {+ return (+ Object.keys(v).length === keys.length &&+ keys.every((k) => Object.hasOwn(v, k))+ );+}+export function oauthId(v: unknown): v is string {+ return typeof v === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(v);+}+export function parsePluginOauthAction(+ value: unknown,+): PluginOauthAction | null {+ if (+ !record(value) ||+ !exact(value, ["requestId", "actionId", "expectedRevision"]) ||+ !oauthId(value.requestId) ||+ typeof value.actionId !== "string" ||+ !value.actionId ||+ value.actionId.length > 256 ||+ /[\x00-\x1f]/.test(value.actionId) ||+ !Number.isSafeInteger(value.expectedRevision) ||+ (value.expectedRevision as number) < 0+ )+ return null;+ return {+ requestId: value.requestId,+ actionId: value.actionId,+ expectedRevision: value.expectedRevision as number,+ };+}+export function parsePluginOauthRequest(+ value: unknown,+): PluginOauthRequest | null {+ if (!record(value)) return null;+ if (value.op === "capabilities" && exact(value, ["op"]))+ return { op: value.op };+ if (+ value.op === "start" &&+ exact(value, [+ "op",+ "publicKey",+ "requestId",+ "actionId",+ "expectedRevision",+ ...(value.deviceUserCode === true ? ["deviceUserCode"] : []),+ ...(value.authorizationV1 === true ? ["authorizationV1"] : []),+ ...(value.secretSubmission === true ? ["secretSubmission"] : []),+ ...(value.connectionSubmission === true ? ["connectionSubmission"] : []),+ ])+ ) {+ const action = parsePluginOauthAction({+ requestId: value.requestId,+ actionId: value.actionId,+ expectedRevision: value.expectedRevision,+ });+ if (+ action &&+ typeof value.publicKey === "string" &&+ /^[A-Za-z0-9_-]{59}$/.test(value.publicKey)+ )+ return {+ op: "start",+ publicKey: value.publicKey,+ ...action,+ ...(value.deviceUserCode === true ? { deviceUserCode: true } : {}),+ ...(value.authorizationV1 === true ? { authorizationV1: true } : {}),+ ...(value.secretSubmission === true ? { secretSubmission: true } : {}),+ ...(value.connectionSubmission === true+ ? { connectionSubmission: true }+ : {}),+ };+ }+ if (+ (value.op === "status" || value.op === "cancel") &&+ exact(value, ["op", "id"]) &&+ oauthId(value.id)+ )+ return { op: value.op, id: value.id };+ if (+ value.op === "callback" &&+ exact(value, ["op", "id", "box"]) &&+ oauthId(value.id) &&+ typeof value.box === "string" &&+ /^[A-Za-z0-9_-]{40,48000}$/.test(value.box)+ )+ return { op: value.op, id: value.id, box: value.box };+ return null;+}+export function parsePluginOauthCallback(+ value: unknown,+): PluginOauthCallback | null {+ if (+ !record(value) ||+ typeof value.state !== "string" ||+ !/^[A-Za-z0-9_-]{43}$/.test(value.state)+ )+ return null;+ if (+ exact(value, ["state", "code"]) &&+ typeof value.code === "string" &&+ value.code.length > 0 &&+ value.code.length <= 8192 &&+ !/[\x00-\x1f]/.test(value.code)+ )+ return { state: value.state, code: value.code };+ if (+ exact(value, ["state", "error"]) &&+ typeof value.error === "string" &&+ /^[a-zA-Z0-9_.-]{1,128}$/.test(value.error)+ )+ return { state: value.state, error: value.error };+ return null;+}diff --git a/packages/device-link/src/pluginOauthAuthentication.ts b/packages/device-link/src/pluginOauthAuthentication.tsnew file mode 100644index 0000000000..ed12af8580--- /dev/null+++ b/packages/device-link/src/pluginOauthAuthentication.ts@@ -0,0 +1,129 @@+import {+ oauthId,+ parsePluginOauthAction,+ type PluginOauthAction,+} from "./pluginOauth.js";++/** Host-only protocol. First keys use the authenticated account route; controllers persist pins after verifying the signed handshake. */+export interface PluginOauthPublicIdentity {+ version: 1;+ publicKey: string;+ bootId: string;+}+export interface PluginOauthPeerIdentity extends PluginOauthPublicIdentity {+ realm: "cn" | "global";+ deviceId: string;+ membershipId: string;+ observedAtMs: number;+ expiresAtMs: number;+}+export interface PluginOauthHello {+ op: "hello";+ version: 3;+ nonce: string;+ publicKey: string;+ action: PluginOauthAction;+}+export interface PluginOauthHelloReply {+ version: 3;+ id: string;+ publicKey: string;+ bootId: string;+ ghostId: string;+ expiresAtMs: number;+ signature: string;+}+export function oauthExact(+ value: unknown,+ fields: readonly string[],+): Record<string, unknown> {+ if (+ !value ||+ typeof value !== "object" ||+ Array.isArray(value) ||+ Object.keys(value).sort().join(",") !== [...fields].sort().join(",")+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return value as Record<string, unknown>;+}+export const oauthNonce = (v: unknown): v is string =>+ typeof v === "string" && /^[A-Za-z0-9_-]{43}$/.test(v);+export const oauthPublicKey = (v: unknown): v is string =>+ typeof v === "string" && /^[A-Za-z0-9_-]{59}$/.test(v);+export function parsePluginOauthPublicIdentity(+ value: unknown,+): PluginOauthPublicIdentity {+ const v = oauthExact(value, ["version", "publicKey", "bootId"]);+ if (v.version !== 1 || !oauthPublicKey(v.publicKey) || !oauthId(v.bootId))+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return v as unknown as PluginOauthPublicIdentity;+}+export function parsePluginOauthPeerIdentity(+ value: unknown,+): PluginOauthPeerIdentity {+ const v = oauthExact(value, [+ "version",+ "publicKey",+ "bootId",+ "realm",+ "deviceId",+ "membershipId",+ "observedAtMs",+ "expiresAtMs",+ ]);+ parsePluginOauthPublicIdentity({+ version: v.version,+ publicKey: v.publicKey,+ bootId: v.bootId,+ });+ if (+ ![v.deviceId, v.membershipId].every(oauthId) ||+ !["cn", "global"].includes(String(v.realm)) ||+ !Number.isSafeInteger(v.observedAtMs) ||+ !Number.isSafeInteger(v.expiresAtMs)+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return v as unknown as PluginOauthPeerIdentity;+}+export function parsePluginOauthHello(value: unknown): PluginOauthHello {+ const v = oauthExact(value, [+ "op",+ "version",+ "nonce",+ "publicKey",+ "action",+ ]);+ const action = parsePluginOauthAction(v.action);+ if (+ v.op !== "hello" ||+ v.version !== 3 ||+ !oauthNonce(v.nonce) ||+ !oauthPublicKey(v.publicKey) ||+ !action+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return { ...v, action } as unknown as PluginOauthHello;+}+export function parsePluginOauthHelloReply(+ value: unknown,+): PluginOauthHelloReply {+ const v = oauthExact(value, [+ "version",+ "id",+ "publicKey",+ "bootId",+ "ghostId",+ "expiresAtMs",+ "signature",+ ]);+ if (+ v.version !== 3 ||+ ![v.id, v.bootId, v.ghostId].every(oauthId) ||+ !oauthPublicKey(v.publicKey) ||+ !Number.isSafeInteger(v.expiresAtMs) ||+ typeof v.signature !== "string" ||+ !/^[A-Za-z0-9_-]{86}$/.test(v.signature)+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return v as unknown as PluginOauthHelloReply;+}diff --git a/packages/device-link/src/pluginSecretSubmission.ts b/packages/device-link/src/pluginSecretSubmission.tsnew file mode 100644index 0000000000..d9a38c4233--- /dev/null+++ b/packages/device-link/src/pluginSecretSubmission.ts@@ -0,0 +1,105 @@+/** Dedicated trusted Desktop input only; never add this channel to the remote allowlist. */+export const PLUGIN_SECRET_LOCAL_CHANNEL = "plugin-oauth:submit-secret";+export const PLUGIN_SECRET_MAX_CHARS = 4096;+/** What the user saw before typing. Main compares it with the authenticated Host offer. */+export interface PluginSecretPresentation {+ ghostName: string;+ title: string;+ description: string;+ intro: string;+ fieldLabel: string;+ fieldDescription: string;+ maxLength: number;+}+export interface PluginSecretOffer {+ kind: "secret-entry";+ state: string;+ presentation: PluginSecretPresentation;+}+export interface PluginSecretValue {+ kind: "secret-value";+ state: string;+ value: string;+}+const fail = () => new Error("PLUGIN_SECRET_UNAVAILABLE");+function object(raw: unknown): Record<string, unknown> {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw fail();+ return raw as Record<string, unknown>;+}+export function parsePluginSecretOffer(raw: unknown): PluginSecretOffer {+ const v = object(raw);+ if (+ Object.keys(v).sort().join(",") !== "kind,presentation,state" ||+ v.kind !== "secret-entry" ||+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9_-]{43}$/.test(v.state)+ )+ throw fail();+ return {+ kind: v.kind,+ state: v.state,+ presentation: parsePluginSecretPresentation(v.presentation),+ };+}+export function parsePluginSecretPresentation(+ raw: unknown,+): PluginSecretPresentation {+ const v = object(raw);+ const keys = [+ "ghostName",+ "title",+ "description",+ "intro",+ "fieldLabel",+ "fieldDescription",+ ];+ if (+ Object.keys(v).length !== keys.length + 1 ||+ keys.some((k) => !Object.hasOwn(v, k)) ||+ keys.some(+ (k) => typeof v[k] !== "string" || (v[k] as string).length > 4096,+ ) ||+ !v.ghostName ||+ !v.fieldLabel ||+ !Number.isSafeInteger(v.maxLength) ||+ (v.maxLength as number) < 1 ||+ (v.maxLength as number) > PLUGIN_SECRET_MAX_CHARS+ )+ throw fail();+ return {+ ghostName: v.ghostName as string,+ title: v.title as string,+ description: v.description as string,+ intro: v.intro as string,+ fieldLabel: v.fieldLabel as string,+ fieldDescription: v.fieldDescription as string,+ maxLength: v.maxLength as number,+ };+}+export function parsePluginSecretValue(raw: unknown): PluginSecretValue {+ const v = object(raw);+ if (+ Object.keys(v).sort().join(",") !== "kind,state,value" ||+ v.kind !== "secret-value" ||+ typeof v.state !== "string" ||+ !/^[A-Za-z0-9_-]{43}$/.test(v.state)+ )+ throw fail();+ return {+ kind: v.kind,+ state: v.state,+ value: parsePluginSecretInput(v.value),+ };+}++/** Validate local input before a transaction exists, without inventing a bridge state. */+export function parsePluginSecretInput(value: unknown): string {+ if (+ typeof value !== "string" ||+ !value.trim() ||+ value.length > PLUGIN_SECRET_MAX_CHARS ||+ /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value)+ )+ throw fail();+ return value;+}diff --git a/scripts/eval-plugin-authorization.mts b/scripts/eval-plugin-authorization.mtsnew file mode 100644index 0000000000..0d31cfe54d--- /dev/null+++ b/scripts/eval-plugin-authorization.mts@@ -0,0 +1,198 @@+/**+ * Opt-in live model evaluation of the three Desktop Host prompt profiles and+ * actual MCP tool schemas/handlers. Plugin/provider results are synthetic: this+ * never installs a plugin, stores a credential or authorizes a real account.+ * It does NOT launch the native harness binaries or test Anthropic caching.+ * pnpm exec tsx scripts/eval-plugin-authorization.mts --live --codex-home /path/to/codex --base <commit>+ */+import { readFile, writeFile, mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { parseArgs } from 'node:util';+import { build } from 'esbuild';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { createCindyGhostsMcpServer } from '../packages/cindy-tools/src/ghost/mcpServer.js';+import type { CindyGhostsMcpDeps, CindyGhostInfo } from '../packages/cindy-tools/src/types.js';++const { values } = parseArgs({ options: {+ live: { type: 'boolean' }, 'codex-home': { type: 'string' }, base: { type: 'string' },+ model: { type: 'string', default: 'gpt-5.6-luna' },+} });+if (!values.live || !values['codex-home'] || !/^[a-f0-9]{40}$/.test(values.base ?? '')) {+ throw new Error('Explicit --live, --codex-home and full --base commit are required');+}+const repo = fileURLToPath(new URL('..', import.meta.url));+const output = await mkdtemp(path.join(tmpdir(), 'cindy-plugin-authorization-live-'));+const sha = (text: string) => createHash('sha256').update(text).digest('hex');+const baseToolFile = 'packages/cindy-tools/src/ghost/mcpServer.ts';+const baselineTools = path.join(output, 'baseline-tools.mjs');+await build({+ stdin: { contents: execFileSync('git', ['show', `${values.base}:${baseToolFile}`], { cwd: repo, encoding: 'utf8' }),+ resolveDir: path.join(repo, path.dirname(baseToolFile)), loader: 'ts' },+ outfile: baselineTools, bundle: true, platform: 'node', format: 'esm',+ banner: { js: 'import {createRequire} from "node:module"; const require=createRequire(import.meta.url);' },+});+const baselineFactory = (await import(pathToFileURL(baselineTools).href)).createCindyGhostsMcpServer as typeof createCindyGhostsMcpServer;+// Read only, in memory. No refresh/logout and no auth.json copied to the fixture.+const auth = JSON.parse(await readFile(path.join(values['codex-home'], 'auth.json'), 'utf8'));+if (!auth.tokens?.access_token || !auth.tokens?.account_id) throw new Error('An existing OpenAI session is required');+const headers = { authorization: `Bearer ${auth.tokens.access_token}`, 'chatgpt-account-id': auth.tokens.account_id,+ 'OpenAI-Beta': 'responses=experimental', originator: 'codex_cli_rs', accept: 'text/event-stream',+ 'content-type': 'application/json' };++const cases = [+ { id: 'install', prompt: '请用 Demo Reports 查询我的报告数。当前没有安装插件,需要的话请安装相关插件并连接账号。' },+ { id: 'first-login', prompt: '请连接当前任务执行设备上的 demo-reports 插件账号,然后只读检查报告数。' },+ { id: 'reconfigure', prompt: '请更换 demo-reports 已保存的 API Key,重新打开配置卡。保存后只读检查报告数。' },+ { id: 'cancel', prompt: '请连接 demo-reports 插件,然后查询报告数。' },+ { id: 'unrelated', prompt: '计算 17 × 19。只回答数字。' },+ { id: 'unrelated-repeat', prompt: '计算 17 × 19。只回答数字。' },+];+const results: Record<string, any>[] = [];+const manifests: Record<string, any>[] = [];+let failedRequests = 0;+for (const profile of ['claude', 'codex', 'pi']) {+ const hostRoot = path.join(repo, 'apps/desktop/src/main/maker-host');+ const sections = ['host-system-prompt.md', ...(profile === 'pi' ? [] : ['skill-source-precedence-prompt.md']), `${profile}-system-prompt.md`];+ const original = (await Promise.all(sections.map(file => readFile(path.join(hostRoot, file), 'utf8'))))+ .map(section => section.trim()).filter(Boolean).join('\n\n');+ for (const variant of ['before', 'after'] as const) {+ // Normal Desktop system instructions stay byte-identical; compare tool guidance only.+ const instructions = original;+ manifests.push({ profile, variant, bytes: Buffer.byteLength(instructions), sha256: sha(instructions),+ preservesPrefix: instructions.startsWith(original) });+ for (const sample of cases) {+ let installed = sample.id !== 'install', configured = sample.id === 'reconfigure', cancelled = false;+ let setupAttempts = 0, successfulReads = 0;+ const completeSetup = async () => {+ setupAttempts++;+ if (sample.id === 'cancel') {+ cancelled = true;+ return { ok: false, errorCode: 'SETUP_CANCELLED', message: 'User cancelled the card. Do not retry or run the plugin.' };+ }+ configured = true;+ return { ok: true, status: 'ready', message: 'The card was submitted. Provider access still needs a read-only check.' };+ };+ const calls: Array<{ name: string; arguments: Record<string, any> }> = [];+ const ghost = (): CindyGhostInfo => ({ id: 'demo-reports', name: 'Demo Reports', command: 'demo-reports',+ recall: 'Read report counts', tools: [{ name: 'count', description: 'Read the number of reports', parameters: { type: 'object', properties: {} } }],+ setup: { state: configured ? 'ready' : 'required', revision: 1, groups: [{ id: 'account', mode: 'any_of',+ items: [{ ref: 'secret:api_key', kind: 'secret', label: 'API Key', state: configured ? 'satisfied' : 'missing',+ actions: [{ id: 'inline_form:fixture', kind: 'inline_form', form: { fields: [{ id: 'value', type: 'secret', label: 'API Key', required: true, maxLength: 4096 }] } }] }] }] } });+ const deps = {+ listAwakeGhosts: async () => installed ? [ghost()] : [],+ getAwakeGhost: async (id: string) => installed && id === 'demo-reports' ? { ok: true, ghost: ghost() } :+ { ok: false, errorCode: 'GHOST_NOT_FOUND', message: 'Plugin not installed' },+ readGhostManual: async () => ({ ok: false, errorCode: 'MANUAL_UNAVAILABLE', message: 'No manual' }),+ searchMarket: async () => ({ ok: true, matches: [{ plugin_id: 'fixture-catalog/demo-reports', release_id: 'fixture-release-1', ghost_id: 'demo-reports', name: 'Demo Reports' }] }),+ installMarket: async ({ pluginId, releaseId }: { pluginId: string; releaseId: string }) => {+ if (pluginId !== 'fixture-catalog/demo-reports' || releaseId !== 'fixture-release-1') return { ok: false };+ installed = true; return { ok: true, ghost_id: 'demo-reports', status: 'installed' };+ },+ connectAccount: completeSetup,+ callGhostTool: async () => {+ if (cancelled) return { ok: false, errorCode: 'SETUP_CANCELLED', message: 'User cancelled' };+ // The existing Host also opens setup before a business tool. This+ // fixture must not falsely require a separate connect_account call.+ if (!configured) {+ const setup = await completeSetup();+ if (!setup.ok) return setup;+ }+ successfulReads++;+ return { ok: true, result: { count: 7 } };+ },+ } as CindyGhostsMcpDeps;+ const server = (variant === 'before' ? baselineFactory : createCindyGhostsMcpServer)(deps);+ const client = new Client({ name: 'plugin-authorization-eval', version: '1' });+ const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);+ const listed = await client.listTools();+ const tools = listed.tools.map(tool => ({ type: 'function', name: tool.name, description: tool.description,+ parameters: tool.inputSchema, strict: false }));+ const input: any[] = [{ role: 'user', content: sample.prompt }];+ const requests: any[] = [];+ let answer = '', error: string | undefined, complete = false;+ const turnStart = performance.now();+ try {+ for (let step = 0; step < 9; step++) {+ const started = performance.now();+ const response = await fetch('https://chatgpt.com/backend-api/codex/responses', {+ method: 'POST', headers, signal: AbortSignal.timeout(45_000),+ body: JSON.stringify({ model: values.model, instructions, input, tools, tool_choice: 'auto',+ store: false, stream: true, parallel_tool_calls: false, reasoning: { effort: 'low' },+ prompt_cache_key: `cindy-plugin-auth-${profile}-${variant}` }),+ });+ if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);+ const reader = response.body.getReader(), decoder = new TextDecoder();+ let pending = '', doneResponse: any, firstEventMs: number | undefined;+ const eventTypes: string[] = [];+ const completedItems: any[] = [];+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ pending += decoder.decode(value, { stream: true });+ let end: number;+ while ((end = pending.indexOf('\n')) >= 0) {+ const line = pending.slice(0, end).trim(); pending = pending.slice(end + 1);+ if (!line.startsWith('data: ') || line === 'data: [DONE]') continue;+ const event = JSON.parse(line.slice(6));+ firstEventMs ??= performance.now() - started;+ if (eventTypes.at(-1) !== event.type) eventTypes.push(event.type);+ if (event.type === 'response.output_item.done') completedItems.push(event.item);+ if (event.type === 'response.completed') doneResponse = event.response;+ if (event.type === 'error' || event.type === 'response.failed') throw new Error('Provider stream failed');+ }+ }+ if (!doneResponse) throw new Error('Missing completed event');+ const usage = doneResponse.usage;+ requests.push({ durationMs: performance.now() - started, firstEventMs, eventTypes,+ inputTokens: usage?.input_tokens, cachedTokens: usage?.input_tokens_details?.cached_tokens ?? 0,+ outputTokens: usage?.output_tokens });+ // The subscription endpoint can omit output from its terminal summary.+ // Item events are authoritative; never discard the streamed tool calls.+ const items = (completedItems.length ? completedItems : doneResponse.output)+ .filter((item: any) => item.type !== 'reasoning');+ input.push(...items);+ const toolCalls = items.filter((item: any) => item.type === 'function_call');+ answer += items.filter((item: any) => item.type === 'message').flatMap((item: any) => item.content)+ .filter((item: any) => item.type === 'output_text').map((item: any) => item.text).join('');+ if (!toolCalls.length) { complete = true; break; }+ for (const call of toolCalls) {+ const args = JSON.parse(call.arguments);+ calls.push({ name: call.name, arguments: args });+ const result = await client.callTool({ name: call.name, arguments: args });+ input.push({ type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(result) });+ }+ }+ } catch (failure) {+ // Do not persist arbitrary fetch/SDK errors: they can contain headers.+ error = failure instanceof Error && /^HTTP \d+$/.test(failure.message) ? failure.message : 'Evaluation request failed';+ } finally { await client.close(); await server.close(); }+ const connections = calls.filter(call => call.name === 'connect_account');+ const countRead = successfulReads > 0;+ const cancelIndex = calls.findIndex(call => call.name === 'connect_account' || call.name === 'ghost_call');+ const retriedAfterCancel = calls.slice(cancelIndex + 1)+ .some(call => call.name === 'connect_account' || call.name === 'ghost_call');+ const pass = !error && complete && (sample.id.startsWith('unrelated') ? calls.length === 0 && answer.trim() === '323' :+ sample.id === 'cancel' ? setupAttempts === 1 && cancelled && !countRead && !retriedAfterCancel :+ sample.id === 'reconfigure' ? connections.some(call => call.arguments.reauthorize === true) && countRead :+ sample.id === 'install' ? calls.some(call => call.name === 'ghost_market_install') && setupAttempts === 1 && countRead :+ setupAttempts === 1 && countRead);+ results.push({ profile, variant, case: sample.id, pass, error, calls, answer, requests, setupAttempts, successfulReads,+ toolsSha256: sha(JSON.stringify(tools)), durationMs: performance.now() - turnStart });+ await writeFile(path.join(output, 'results.json'), JSON.stringify({ base: values.base, model: values.model,+ environment: 'Live OpenAI model, actual MCP schemas/handlers, synthetic plugin state; Host prompt profiles, not native CLI sessions',+ manifests, results }, null, 2));+ console.log(JSON.stringify({ profile, variant, case: sample.id, pass, error, requests: requests.length }));+ failedRequests = error ? failedRequests + 1 : 0;+ if (error === 'HTTP 429' || failedRequests >= 3) throw new Error(`Live evaluation stopped; evidence: ${output}`);+ }+ }+}+console.log(JSON.stringify({ output, afterPassed: results.filter(row => row.variant === 'after' && row.pass).length,+ afterTotal: results.filter(row => row.variant === 'after').length }));+process.exitCode = results.some(row => row.variant === 'after' && !row.pass) ? 1 : 0;