Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close plugin publisher IPC gaps
fmfsaisai67aa529de7a6
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.tsindex a4276132e6..d22b06271d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts@@ -57,12 +57,16 @@ describe('consumeForgePackForPublish', () => {).toBe('accepted');});- it('rejects owner mismatch and deletes staging bytes', () => {+ it.each([+ { field: 'mode', currentOwner: { ...owner, mode: 'local' as const } },+ { field: 'dataOwnerId', currentOwner: { ...owner, dataOwnerId: 'member-2' } },+ { field: 'generation', currentOwner: { ...owner, generation: owner.generation + 1 } },+ ])('rejects $field owner mismatch and deletes staging bytes', ({ currentOwner }) => {const { controller, staged } = harness();expect(consumeForgePackForPublish(controller, {token: staged.ticket,- currentOwner: { ...owner, generation: owner.generation + 1 },+ currentOwner,boundaryPending: false,}),).toEqual({ kind: 'rejected', reason: 'owner-mismatch' });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.tsindex a244e39581..6a3b4c0e72 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts@@ -12,6 +12,9 @@* 「零窗口」这个具体场景把两者的绑定钉死。*/+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, it, expect, vi, beforeEach } from 'vitest';const windows: { isDestroyed: () => boolean; webContents: { send: (ch: string) => void } }[] = [];@@ -34,7 +37,7 @@ const AGENT_ORIGIN = {};/** 用本文件自身当"存在且可读的普通文件",避免造临时目录。 */-const REAL_FILE = new URL(import.meta.url).pathname;+const REAL_FILE = fileURLToPath(import.meta.url);beforeEach(() => {windows.length = 0;@@ -86,7 +89,10 @@ describe('openFileInstall · origin 与路径同存同取', () => {it('路径不存在:不写缓冲、不广播(容错口径与 open-folder 一致)', async () => {addWindow();- await handleIncomingCindyFile('/definitely/not/here.cindy', 'open-file');+ await handleIncomingCindyFile(+ path.join(path.dirname(REAL_FILE), 'definitely-not-here.cindy'),+ 'open-file',+ );expect(sent).toEqual([]);expect(takePendingCindyInstall()).toBeNull();});diff --git a/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts b/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.tsindex c578f6ea34..2747ab114a 100644--- a/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts+++ b/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts@@ -15,7 +15,10 @@ export type ForgePackPublishConsume =reason: 'session-boundary-pending' | 'ticket-invalid' | 'owner-mismatch';};-function sameOwner(a: ActiveAppSession, b: ActiveAppSession): boolean {+export function sameActiveAppSessionOwner(+ a: ActiveAppSession,+ b: ActiveAppSession,+): boolean {return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;}@@ -32,7 +35,7 @@ export function consumeForgePackForPublish(}const ticket = controller.consume(input.token);if (!ticket) return { kind: 'rejected', reason: 'ticket-invalid' };- if (!sameOwner(ticket.owner, input.currentOwner)) {+ if (!sameActiveAppSessionOwner(ticket.owner, input.currentOwner)) {controller.releaseStaging(ticket.stagingPath);return { kind: 'rejected', reason: 'owner-mismatch' };}diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.tsindex 2d4904517b..13a420509f 100644--- a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts+++ b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts@@ -66,6 +66,37 @@ const prepared = {};describe('PluginPublisherOrchestrator', () => {+ it('hides status and cancel from a different active-session owner', async () => {+ const filePath = await packagePath();+ const owner = { mode: 'cloud' as const, dataOwnerId: 'member-1', generation: 7 };+ let resolveConfirm!: (confirmed: boolean) => void;+ const confirm = new Promise<boolean>((resolve) => {+ resolveConfirm = resolve;+ });+ const orch = createPluginPublisherOrchestrator({+ api: { prepare: vi.fn(), commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),+ confirm: () => confirm,+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),+ owner: () => owner,+ });+ const started = orch.start(filePath);+ const differentOwner = { ...owner, generation: owner.generation + 1 };++ // Excludes leaking whether a transferId exists after an owner switch.+ expect(orch.snapshotForOwner(started.transferId, differentOwner)).toBeNull();+ expect(orch.cancelForOwner(started.transferId, differentOwner)).toEqual({+ cancelled: false,+ });+ expect(orch.snapshotForOwner(started.transferId, owner)?.stage).toBe('confirming');+ expect(orch.cancelForOwner(started.transferId, owner)).toEqual({ cancelled: true });++ resolveConfirm(false);+ await vi.waitFor(() =>+ expect(orch.snapshotForOwner(started.transferId, owner)?.stage).toBe('cancelled'),+ );+ });+it('returns immediately while confirmation and transfer continue in the background', async () => {const filePath = await packagePath();let resolveConfirm!: (confirmed: boolean) => void;diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.tsnew file mode 100644index 0000000000..6fb830aca9--- /dev/null+++ b/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts@@ -0,0 +1,121 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++type Handler = (event: { sender: { id: number } }, payload: unknown) => unknown;++const {+ handlers,+ boundaryPendingMock,+ getActiveAppSessionMock,+ snapshotForOwnerMock,+ cancelForOwnerMock,+ trustedRendererMock,+} = vi.hoisted(() => ({+ handlers: new Map<string, Handler>(),+ boundaryPendingMock: vi.fn(() => false),+ getActiveAppSessionMock: vi.fn(() => ({+ mode: 'cloud' as const,+ dataOwnerId: 'member-1',+ generation: 7,+ })),+ snapshotForOwnerMock: vi.fn(() => ({ transferId: 'transfer-1', stage: 'confirming' })),+ cancelForOwnerMock: vi.fn(() => ({ cancelled: true })),+ trustedRendererMock: vi.fn(),+}));++vi.mock('electron', () => ({+ ipcMain: {+ handle: (channel: string, handler: Handler) => handlers.set(channel, handler),+ },+}));+vi.mock('../../appSessionState.js', () => ({+ getActiveAppSession: getActiveAppSessionMock,+ isAppSessionBoundaryPending: boundaryPendingMock,+}));+vi.mock('../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: trustedRendererMock,+}));+vi.mock('../host.js', () => ({+ currentPublisherIdentity: vi.fn(() => ({+ membershipId: 'member-1',+ orgSlug: 'acme',+ orgName: 'Acme',+ })),+ getPluginPublisherConfirmBridge: vi.fn(() => ({ resolve: vi.fn() })),+ getPluginPublisherOrchestrator: vi.fn(() => ({+ snapshotForOwner: snapshotForOwnerMock,+ cancelForOwner: cancelForOwnerMock,+ })),+ publisherAudience: vi.fn((orgSlug: string) => `${orgSlug}:publisher`),+ trackPublisherConfirmRequester: vi.fn(),+}));+vi.mock('../api.js', () => ({+ PluginPublisherApi: class {},+ PluginPublisherApiError: class extends Error {},+}));+vi.mock('../../cindy-brain/index.js', () => ({+ getConnectionTokenProvider: vi.fn(() => ({+ getToken: vi.fn(),+ invalidate: vi.fn(),+ })),+}));++const { registerPluginPublisherIpc } = await import('../registerIpc.js');++function handler(channel: string): Handler {+ const registered = handlers.get(channel);+ if (!registered) throw new Error(`${channel} handler 未注册`);+ return registered;+}++const event = { sender: { id: 9 } };++beforeAll(() => registerPluginPublisherIpc());++beforeEach(() => {+ boundaryPendingMock.mockReset();+ boundaryPendingMock.mockReturnValue(false);+ getActiveAppSessionMock.mockClear();+ snapshotForOwnerMock.mockClear();+ cancelForOwnerMock.mockClear();+ trustedRendererMock.mockClear();+});++describe('plugin-publisher IPC owner boundary', () => {+ it('fails closed when an untrusted Renderer submits a publish file path', async () => {+ let caught: unknown;+ try {+ await handler('plugin-publisher:start')(event, 'C:\\Users\\demo\\plugin.cindy');+ } catch (error) {+ caught = error;+ }+ // Excludes restoring the path-taking Renderer IPC before a Main-minted grant exists.+ expect(caught).toMatchObject({ code: 'INVALID_PARAMS' });+ });++ it('passes same-owner status and cancel through the owner-aware lookup', () => {+ const owner = getActiveAppSessionMock();++ expect(handler('plugin-publisher:status')(event, 'transfer-1')).toEqual({+ progress: { transferId: 'transfer-1', stage: 'confirming' },+ });+ expect(snapshotForOwnerMock).toHaveBeenCalledWith('transfer-1', owner);+ expect(handler('plugin-publisher:cancel')(event, 'transfer-1')).toEqual({+ cancelled: true,+ });+ expect(cancelForOwnerMock).toHaveBeenCalledWith('transfer-1', owner);+ });++ it('hides status and cancel while the app-session boundary is pending', () => {+ boundaryPendingMock.mockReturnValue(true);++ expect(handler('plugin-publisher:status')(event, 'transfer-1')).toEqual({+ progress: null,+ });+ expect(handler('plugin-publisher:cancel')(event, 'transfer-1')).toEqual({+ cancelled: false,+ });+ // Excludes checking a transfer before the account boundary settles.+ expect(snapshotForOwnerMock).not.toHaveBeenCalled();+ expect(cancelForOwnerMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/plugin-publisher/orchestrator.ts b/apps/desktop/src/main/plugin-publisher/orchestrator.tsindex b2e09840f8..3f5aee6bf5 100644--- a/apps/desktop/src/main/plugin-publisher/orchestrator.ts+++ b/apps/desktop/src/main/plugin-publisher/orchestrator.ts@@ -16,6 +16,11 @@ import {type PluginMemberUploadStatusResponse,} from '@cindy/plugin-protocol';+import {+ getActiveAppSession,+ type ActiveAppSession,+} from '../appSessionState.js';+import { sameActiveAppSessionOwner } from '../cindy-brain/forgePackPublishConsume.js';import { PluginPublisherApi, PluginPublisherApiError } from './api.js';import { hashLocalFile, PluginPublisherHashCancelledError } from './hashFile.js';import { PluginPublisherPutError, putLocalFile } from './putObject.js';@@ -48,6 +53,7 @@ export interface PluginPublisherOrchestratorDeps {sizeBytes: number;}): Promise<boolean>;identity(): { membershipId: string; orgSlug: string; orgName: string | null } | null;+ owner?: () => ActiveAppSession;now?: () => number;sleep?: (ms: number, signal: AbortSignal) => Promise<void>;onProgress?: (progress: PluginPublisherProgress) => void;@@ -66,6 +72,7 @@ interface TransferRecord {transferId: string;uploadId: string | null;filePath: string;+ owner: ActiveAppSession;controller: AbortController;progress: PluginPublisherProgress;run: Promise<void>;@@ -134,11 +141,13 @@ export class PluginPublisherOrchestrator {private readonly now: () => number;private readonly sleep: (ms: number, signal: AbortSignal) => Promise<void>;private readonly inspectGate: { acquire(signal: AbortSignal): Promise<void>; release(): void };+ private readonly owner: () => ActiveAppSession;constructor(private readonly deps: PluginPublisherOrchestratorDeps) {this.now = deps.now ?? Date.now;this.sleep = deps.sleep ?? defaultSleep;this.inspectGate = deps.inspectGate ?? new SerialGate();+ this.owner = deps.owner ?? getActiveAppSession;}start(@@ -159,6 +168,7 @@ export class PluginPublisherOrchestrator {transferId,uploadId: null,filePath,+ owner: this.owner(),controller,progress,run: Promise.resolve(),@@ -177,6 +187,16 @@ export class PluginPublisherOrchestrator {return this.transfers.get(transferId)?.progress ?? null;}+ snapshotForOwner(+ transferId: string,+ owner: ActiveAppSession,+ ): PluginPublisherProgress | null {+ const record = this.transfers.get(transferId);+ return record && sameActiveAppSessionOwner(record.owner, owner)+ ? record.progress+ : null;+ }+listActive(): PluginPublisherProgress[] {return [...this.transfers.values()].map((record) => record.progress)@@ -190,6 +210,17 @@ export class PluginPublisherOrchestrator {return { cancelled: true };}+ cancelForOwner(+ transferId: string,+ owner: ActiveAppSession,+ ): { cancelled: boolean } {+ const record = this.transfers.get(transferId);+ if (!record || !sameActiveAppSessionOwner(record.owner, owner)) {+ return { cancelled: false };+ }+ return this.cancel(transferId);+ }+abortAll(): void {for (const record of this.transfers.values()) {if (!isTerminalStage(record.progress.stage)) record.controller.abort();diff --git a/apps/desktop/src/main/plugin-publisher/registerIpc.ts b/apps/desktop/src/main/plugin-publisher/registerIpc.tsindex ef5371b5da..01eb0457fb 100644--- a/apps/desktop/src/main/plugin-publisher/registerIpc.ts+++ b/apps/desktop/src/main/plugin-publisher/registerIpc.ts@@ -1,5 +1,9 @@import { ipcMain } from 'electron';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+} from '../appSessionState.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';import { PluginPublisherApi, PluginPublisherApiError } from './api.js';@@ -8,7 +12,6 @@ import {getPluginPublisherConfirmBridge,getPluginPublisherOrchestrator,publisherAudience,- startPluginPublish,trackPublisherConfirmRequester,} from './host.js';import { getConnectionTokenProvider } from '../cindy-brain/index.js';@@ -50,28 +53,34 @@ export function registerPluginPublisherIpc(): void {if (registered) return;registered = true;- ipcMain.handle('plugin-publisher:start', async (event, filePath: unknown) => {+ ipcMain.handle('plugin-publisher:start', (event, _filePath: unknown) => {assertTrustedAppRendererEvent(event);- if (typeof filePath !== 'string' || filePath.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'filePath must be a non-empty string');- }- if (!currentPublisherIdentity()) {- throwIpcError('PERMISSION_DENIED', '需要组织身份才能发布插件');- }- trackPublisherConfirmRequester(event.sender);- return startPluginPublish(filePath, event.sender);+ // 临时 fail closed:Renderer 自报绝对路径不构成用户授权(XSS 可伪造)。下期重新+ // 开放“我的发布”前,必须先由 Main 文件选择器签发一次性 grant,再由 start 消费;+ // 在 grant 落地前这个 IPC 入口不得恢复。+ throwIpcError('INVALID_PARAMS', 'Renderer file path publishing is disabled');});ipcMain.handle('plugin-publisher:status', (event, transferId: unknown) => {assertTrustedAppRendererEvent(event);const id = requireString(transferId, 'transferId');- return { progress: getPluginPublisherOrchestrator().snapshot(id) };+ if (isAppSessionBoundaryPending()) return { progress: null };+ return {+ progress: getPluginPublisherOrchestrator().snapshotForOwner(+ id,+ getActiveAppSession(),+ ),+ };});ipcMain.handle('plugin-publisher:cancel', (event, transferId: unknown) => {assertTrustedAppRendererEvent(event);const id = requireString(transferId, 'transferId');- return getPluginPublisherOrchestrator().cancel(id);+ if (isAppSessionBoundaryPending()) return { cancelled: false };+ return getPluginPublisherOrchestrator().cancelForOwner(+ id,+ getActiveAppSession(),+ );});ipcMain.handle('plugin-publisher:list-mine', async (event, raw: unknown) => {