Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): enforce plugin policy throughout authorization
zqchris95d29c13ce67
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.tsnew file mode 100644index 0000000000..2c1ff1d072--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { BotAuthorizationCard } from '../../../shared/botAuthorization';+import type { initBotAuthorizationService } from '../botAuthorizationService';++const state = vi.hoisted(() => ({+ policy: JSON.stringify({ toolsets: ['art'] }) as string | undefined,+ deps: null as unknown as Parameters<typeof initBotAuthorizationService>[0],+ execute: vi.fn(async () => ({ ok: true })),+}));+vi.mock('electron', () => ({ shell: { openExternal: vi.fn() } }));+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../botAuthorizationService.js', () => ({+ initBotAuthorizationService: (deps: typeof state.deps) => { state.deps = deps; },+}));+vi.mock('../../localDb/client/current.js', () => ({+ getDbClient: () => ({ drizzle: { select: (fields: Record<string, unknown>) => {+ const query = {+ from: () => query, innerJoin: () => query, where: () => query, orderBy: () => query,+ limit: async () => 'resolvedJson' in fields+ ? (state.policy === undefined ? [] : [{ resolvedJson: state.policy }])+ : [{ id: 'bot', workingDir: '/bot' }],+ };+ return query;+ } } }),+}));+vi.mock('../../localDb/ipc/messages.js', () => ({+ createMessage: vi.fn(), patchMessageAgentMeta: vi.fn(),+ broadcastMessageAgentMetaUpdate: vi.fn(), updateMessageContent: vi.fn(),+}));+vi.mock('../../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: () => ({}), isDataOwnerBroadcastScopeCurrent: () => true,+}));+vi.mock('../../cindy-brain/index.js', () => ({+ getGhostManager: () => ({ list: () => [] }),+ getGhostSetupAssessment: () => ({ state: 'ready', revision: 1, groups: [] }),+ executeGhostSetupAction: state.execute, executeGhostSetupInlineAction: state.execute,+ isGhostAvailableForActiveSession: () => true,+ acquireGhostMutationLeaseForMcp: () => () => {}, captureGhostMutationOwnerForMcp: () => ({}),+}));+vi.mock('../../cindy-brain/ghostVisibility.js', () => ({+ classifyGhostVisibility: () => ({ ok: true, ghost: { manifest: { id: 'art', name: 'Art' } } }),+}));+vi.mock('../../cindy-brain/ghostWorkdirPrefs.js', () => ({ isGhostDisabledForWorkdir: () => false }));+vi.mock('../../cindy-brain/ghostSetupChangeBus.js', () => ({+ getGhostSetupChangeBus: () => ({ subscribe: () => () => {}, currentRevision: () => 1 }),+}));+vi.mock('../../cindy-brain/ghostSetupCoordinator.js', () => ({ toReauthInteractionAssessment: () => null }));+vi.mock('../../cindy-brain/ghostSetupInteractionBridge.js', () => ({ sanitizeGhostSetupSnapshotForRemote: (v: unknown) => v }));+vi.mock('../../maker-host/grok-oauth-login.js', () => ({+ getGrokAccessToken: vi.fn(), hasGrokOAuthLogin: () => false, runGrokOAuthLogin: vi.fn(),+ getGrokOAuthCredentialGeneration: () => 0, cancelGrokOAuthLogin: vi.fn(),+}));+import { initializeBotAuthorizationHost } from '../botAuthorizationHost';++const target = { kind: 'plugin' as const, id: 'art' };+describe('authorization Host frozen plugin policy', () => {+ beforeEach(() => {+ state.policy = JSON.stringify({ toolsets: ['art'] });+ state.execute.mockClear();+ initializeBotAuthorizationHost(async (_card, validate) => validate());+ });++ it.each([undefined, '{', '{}', '{"toolsets":[]}'])('rejects restored cards without an applied grant: %s', async (policy) => {+ state.policy = policy;+ await expect(state.deps.adapter('session', target)).rejects.toThrow('disabled in teammate profile');+ expect(state.execute).not.toHaveBeenCalled();+ });++ it('rechecks the durable policy before assessment, credential mutation and continuation', async () => {+ const adapter = await state.deps.adapter('session', target);+ await expect(adapter.assess()).resolves.toMatchObject({ state: 'ready' });+ state.policy = JSON.stringify({ toolsets: [] });+ await expect(adapter.assess()).rejects.toThrow('disabled in teammate profile');+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).rejects.toThrow('disabled in teammate profile');+ await expect(state.deps.resume({ sessionId: 'session', target } as BotAuthorizationCard)).rejects.toThrow('disabled in teammate profile');+ expect(state.execute).not.toHaveBeenCalled();+ });++ it('permits configured plugin actions and does not apply plugin policy to Host login', async () => {+ const adapter = await state.deps.adapter('session', target);+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).resolves.toMatchObject({ ok: true });+ expect(state.execute).toHaveBeenCalledTimes(1);+ state.policy = undefined;+ await expect(state.deps.adapter('session', { kind: 'host', id: 'grok' })).resolves.toMatchObject({ identity: { id: 'grok' } });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.tsindex 86ee627a3c..e806113573 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts@@ -1,8 +1,8 @@import { shell } from 'electron';import { t } from '../i18n.js';-import { and, eq, isNull, ne, or, gt, like, desc } from 'drizzle-orm';+import { and, eq, isNull, ne, or, gt, like, desc, inArray } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current.js';-import { botSessionLinks, botProfiles, sessions, messages } from '../localDb/schema.js';+import { botSessionLinks, botProfiles, botRuntimeSnapshots, sessions, messages } from '../localDb/schema.js';import {createMessage,patchMessageAgentMeta,@@ -65,6 +65,30 @@ export function initializeBotAuthorizationHost(resume: (card: BotAuthorizationCard, validate: () => Promise<void>) => Promise<void>,) {const ownerScopes = new Map<string, ReturnType<typeof captureDataOwnerBroadcastScope>>();+ const assertPluginPolicy = async (sessionId: string, pluginId: string) => {+ // The applied snapshot survives Host restarts; never infer teammate grants+ // from global plugin visibility or from the card's display metadata.+ const [snapshot] = await getDbClient()+ .drizzle+ .select({ resolvedJson: botRuntimeSnapshots.resolvedJson })+ .from(botRuntimeSnapshots)+ .where(+ and(+ eq(botRuntimeSnapshots.sessionId, sessionId),+ inArray(botRuntimeSnapshots.status, ['applied', 'degraded']),+ ),+ )+ .orderBy(desc(botRuntimeSnapshots.preparedAt))+ .limit(1);+ let resolved: { toolsets?: unknown } | null = null;+ try {+ resolved = JSON.parse(snapshot?.resolvedJson ?? 'null');+ } catch {+ /* deny malformed policy */+ }+ if (!Array.isArray(resolved?.toolsets) || !resolved.toolsets.includes(pluginId))+ throw new Error('Plugin is disabled in teammate profile');+ };const assertSession = async (sessionId: string) => {const scope = ownerScopes.get(sessionId);if (@@ -152,6 +176,8 @@ export function initializeBotAuthorizationHost(.where(eq(sessions.id, sessionId)).limit(1);const validate = async () => {+ await assertSession(sessionId);+ await assertPluginPolicy(sessionId, target.id);await assertSession(sessionId);const result = classifyGhostVisibility(target.id, session?.workingDir ?? null, {listGhosts: () => getGhostManager().list(),@@ -312,6 +338,8 @@ export function initializeBotAuthorizationHost(async resume(card) {await resume(card, async () => {await assertSession(card.sessionId);+ if (card.target.kind === 'plugin')+ await assertPluginPolicy(card.sessionId, card.target.id);const [row] = await getDbClient().drizzle.select({ id: messages.id }).from(messages)diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 393f97eec8..e4fc3a6e2d 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -133,6 +133,12 @@ vi.mock('../../logger.js', () => ({// Claude 走建线闭包 ctx;Codex / Pi 用此 mock 模拟 HTTP bridge 的 ALS 恢复。vi.mock('@cindy/mcps', () => ({ getLiziMcpSessionContext: () => alsSessionContextMock() }));+vi.mock('../../maker-ipc/botAuthorizationHost.js', () => ({ isBotAuthorizationSession: async () => false }));+const authorizationRequestMock = vi.fn(async () => ({ ok: true as const }));+vi.mock('../../maker-ipc/botAuthorizationService.js', () => ({+ getBotAuthorizationService: () => ({ request: authorizationRequestMock }),+}));+const WORKDIR = '/proj/alpha';const listMock = vi.fn<() => unknown[]>(() => []);const activeSessionAvailableMock = vi.fn((_ghostId: string) => true);@@ -299,6 +305,7 @@ function clearAllPrefs(): void {}beforeEach(() => {+ authorizationRequestMock.mockClear();fs.mkdirSync(outsideDir, { recursive: true });listMock.mockReset();listMock.mockReturnValue([chipGhost('art'), chipGhost('other')]);@@ -740,6 +747,28 @@ describe('写路径 roundtrip(真实存储,tmp userData)', () => {});});+describe('connect_account frozen plugin policy', () => {+ it.each([+ { __cindyAllowedBuiltinPluginIds: ['other'] },+ { __cindyDisabledBuiltinPluginIds: ['art'] },+ ])('rejects a disabled plugin before creating a card: %j', async (policy) => {+ const deps = makeDeps('claude-code', 'bot-session', 'bot-instance', policy);+ await expect(deps.connectAccount!({ kind: 'plugin', id: 'art' })).resolves.toMatchObject({+ ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR',+ });+ expect(authorizationRequestMock).not.toHaveBeenCalled();+ });++ it('allows an enabled plugin and keeps Host login independent of plugin policy', async () => {+ const deps = makeDeps('claude-code', 'bot-session', 'bot-instance', {+ __cindyAllowedBuiltinPluginIds: ['art'],+ });+ await deps.connectAccount!({ kind: 'plugin', id: 'art' });+ await deps.connectAccount!({ kind: 'host', id: 'grok' });+ expect(authorizationRequestMock).toHaveBeenCalledTimes(2);+ });+});+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 293468e19c..ababc0c326 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -1359,6 +1359,8 @@ export function getCindyGhostsMcpDeps(});return {connectAccount: async (target) => {+ if (target.kind === 'plugin' && !isGhostAllowedByFrozenProfile(target.id))+ return frozenProfileDenied();const context = resolveSessionContext();const sessionId = ghostSetupInteractionSessionId(context);if (!sessionId) return { ok: false, errorCode: 'NO_SESSION_CONTEXT' };