Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): 按宿主授权复核 Worker 工作目录
Dash2de2468ddc08
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 1b5cc665f0..d7f93d8d96 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3907,6 +3907,7 @@ const r = await cindy.agent.requestSchedule({\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。+计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。暂不支持选择现有任务、远程/伙伴任务、任意更新配置、归档、队列暂停或事件订阅。旧 \`agent.errand\` 接口不变。diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.tsindex 19aec08296..7d53c8d8f4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts@@ -2738,3 +2738,16 @@ it('revalidates a plan registered during creation preflight and releases the resexpect(deps.bootstrapSession).not.toHaveBeenCalled();expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);});+it('checks the resolved creation directory before bootstrap and releases a rejected reservation', async () => {+ const resolved = path.resolve('resolved-candidate');+ const validateCreationPlan = vi.fn(async (_params, directory?: string) => {+ if (directory !== undefined) throw new Error('Directory authorization revoked');+ return undefined;+ });+ const {deps, service} = createDeps({validateCreationPlan, resolveWorkerWorkingDir: vi.fn(async () => resolved)});+ const params = {leadSessionId:'lead-1',role:'eval',agent:'codex' as const,label:'sample',workingDir:path.resolve('candidate')};+ await expect(service.createWorker(params)).rejects.toThrow('Directory authorization revoked');+ expect(validateCreationPlan).toHaveBeenLastCalledWith(expect.objectContaining(params), resolved);+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.tsnew file mode 100644index 0000000000..07ee4ad07f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.ts@@ -0,0 +1,28 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';+import path from 'node:path';+import os from 'node:os';+import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';++describe('plugin Worker directory authorization', () => {+ const roots: string[] = [];+ afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root,{recursive:true,force:true}))); });+ it('allows the task and its real children, configured or picked roots, without granting Library', async () => {+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(),'plugin-dirs-'))); roots.push(root);+ const dirs = ['task','task/child','task-other','configured','picked','library'];+ for (const dir of dirs) await mkdir(path.join(root,dir),{recursive:true});+ const input = {leadDirectory:path.join(root,'task'),configuredDirectory:path.join(root,'configured'),isPickedDirectory:(dir:string)=>dir===path.join(root,'picked'),assertCurrent:()=>{}};+ for (const dir of ['task','task/child','configured','picked']) expect(await resolvePluginWorkerDirectory({...input,requested:path.join(root,dir)})).toBe(path.join(root,dir));+ for (const dir of ['task-other','library']) await expect(resolvePluginWorkerDirectory({...input,requested:path.join(root,dir)})).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ await expect(resolvePluginWorkerDirectory({...input,requested:path.join(root,'task','..','library')})).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ await symlink(path.join(root,'library'),path.join(root,'task','escape'),'junction');+ await expect(resolvePluginWorkerDirectory({...input,requested:path.join(root,'task','escape')})).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ await expect(resolvePluginWorkerDirectory({...input,isPickedDirectory:()=>false,requested:path.join(root,'picked')})).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ });+ it('rechecks ownership after asynchronous resolution', async () => {+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(),'plugin-owner-'))); roots.push(root);+ const assertCurrent = vi.fn().mockImplementationOnce(()=>{}).mockImplementation(()=>{throw Error('Account changed');});+ await expect(resolvePluginWorkerDirectory({requested:root,leadDirectory:root,isPickedDirectory:()=>false,assertCurrent})).rejects.toThrow('Account changed');+ expect(assertCurrent).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.tsindex 52901d6a35..c21ceb3b4a 100644--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts@@ -208,7 +208,7 @@ export interface OrcaWorkerCreationDeps {getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerListSnapshot[]>;isActiveWorkerStatus(status: OrcaWorkerStatus): boolean;- validateCreationPlan?(params: OrcaWorkerCreateInTeamParams): Promise<number | null | undefined>;+ validateCreationPlan?(params: OrcaWorkerCreateInTeamParams, resolvedWorkingDir?: string): Promise<number | null | undefined>;readCollaborationSettings(): { workerSoftLimit: number; workerHardLimit: number };getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;@@ -1026,7 +1026,7 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): Otry {// Registration may race the preflight. Once a reservation exists, a new// plan cannot be registered; reread any plan that won before reservation.- const reservedPlanLimit = await deps.validateCreationPlan?.(params);+ const reservedPlanLimit = await deps.validateCreationPlan?.(params, workingDir);if (reservedPlanLimit != null && reservation.occupiedSlotsBefore >= reservedPlanLimit) {return { ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED', message: 'Registered plan concurrency reached' };}diff --git a/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.ts b/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.tsnew file mode 100644index 0000000000..dd61c84625--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.ts@@ -0,0 +1,30 @@+import { realpath, stat } from 'node:fs/promises';+import path from 'node:path';+import { isPathInsideDir } from '../cindy-brain/dirDeposit.js';+import { PluginTaskError } from './pluginTaskService.js';++/** Plans describe work; only host directory facts authorize it. */+export async function resolvePluginWorkerDirectory(input: {+ requested: string;+ leadDirectory?: string;+ configuredDirectory?: string;+ isPickedDirectory: (directory: string) => boolean;+ assertCurrent: () => void;+}): Promise<string> {+ const deny = () => new PluginTaskError('PERMISSION_DENIED', 'Worker directory is outside the plugin task scope');+ if (!path.isAbsolute(input.requested) || input.requested.includes('\0')) throw deny();+ input.assertCurrent();+ const resolved = await realpath(input.requested);+ if (!(await stat(resolved)).isDirectory()) throw deny();+ let allowed = false;+ if (input.leadDirectory) allowed = isPathInsideDir(await realpath(input.leadDirectory), resolved);+ if (!allowed && input.configuredDirectory) {+ const configured = await realpath(input.configuredDirectory);+ allowed = isPathInsideDir(configured, resolved) && isPathInsideDir(resolved, configured);+ }+ // Pick grants are exact-directory grants, not permission for an arbitrary Library root.+ if (!allowed) allowed = input.isPickedDirectory(resolved) || input.isPickedDirectory(input.requested);+ input.assertCurrent();+ if (!allowed) throw deny();+ return resolved;+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 76f4f1c647..2ca6b72a8a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,4 +1,5 @@import { createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';+import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';@@ -10326,7 +10327,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await service.get(pluginId, task.taskId);return result;}- case 'setTeamPlan': return service.setTeamPlan(pluginId, request.taskId, request.plan);+ case 'setTeamPlan': {+ const epoch = getCurrentDbClientSnapshot();+ const task = await service.get(pluginId, request.taskId);+ const cfg = readGhostErrandConfig(pluginId);+ const assertCurrent = () => {+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId) || cfg.workingDir !== readGhostErrandConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');+ };+ for (const item of request.plan.items) await resolvePluginWorkerDirectory({requested:item.workingDir,leadDirectory:task.workingDir,configuredDirectory:cfg.workingDir,isPickedDirectory:dir=>isGhostPickedDir(pluginId,dir),assertCurrent});+ const current = await service.get(pluginId, request.taskId);+ assertCurrent();+ if (current.revision !== task.revision) throw new PluginTaskError('STALE_REVISION', 'Task changed during directory validation');+ return service.setTeamPlan(pluginId, request.taskId, request.plan);+ }case 'releaseWorker': {const epoch = getCurrentDbClientSnapshot();await service.get(pluginId,request.taskId);@@ -11379,13 +11392,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)listWorkersByLead,isActiveWorkerStatus,readCollaborationSettings,- validateCreationPlan: async params => {+ validateCreationPlan: async (params, resolvedWorkingDir) => {const epoch = getCurrentDbClientSnapshot();if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);if (!receipt || receipt.operation !== 'create') return undefined;- await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);+ const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');+ const cfg = readGhostErrandConfig(receipt.pluginId);+ const directory = await resolvePluginWorkerDirectory({+ requested: params.workingDir ?? task.workingDir ?? '', leadDirectory: task.workingDir,+ configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),+ assertCurrent: () => {+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');+ },+ });+ if (resolvedWorkingDir !== undefined && directory !== await realpathWorkingDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');+ const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);+ if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');// get() waits behind plan registration in the existing receipt queue.const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);if (!currentReceipt) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex fa84ef5c67..c85edaa88a 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -117,6 +117,8 @@### 3.1 安装与自动更新+插件普通任务创建的 Worker 目录由宿主校验:允许当前任务目录及解析符号链接后仍在其中的子目录、插件 AI 配置目录、用户通过目录选择器授权的确切目录。Library 绑定本身不授予 Agent 工作目录权限,协同计划也不构成目录授权。登记计划和实际创建 Worker 均复核授权;账号、配置或任务归属发生变化时拒绝继续创建。+- 首次安装只来自明确依据:用户导入本地 `.cindy`、明确要求当前 Agent 调用`ghost_forge_install`、用户点击某个市场条目的安装、当前 Agent 按用户请求与既有操作授权调用 `ghost_market_install` 安装选定的缺失插件,或服务端为当前 owner 下发