Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): enforce current task authority at admission
Dash85e5bdac4597
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex f598bf2fa5..a167ba9b62 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest';import {createPluginTaskService,+ isPluginTaskPermissionAllowed,type PluginTaskReceipt,type PluginTaskStore,type PluginTaskServiceDeps,@@ -54,6 +55,7 @@ function fixture() {const execution = { instanceId: 'native', generation: 1 };const deps: PluginTaskServiceDeps = {store,+ readPermissionMode: () => 'auto',assertAuthorized: () => {if (!current) throw new Error('Owner changed');},@@ -64,7 +66,7 @@ function fixture() {now: () => 1,resolveRoute: vi.fn(async (_, r) => r ?? route),createSession: vi.fn(async (_, taskId, title, resolvedConfig) => {- tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active' });+ tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active', permissionMode: 'plan' });}),readSession: async (id) => copy(tasks.get(id) ?? null),dispatch: vi.fn(async () => ({ ok: true })),@@ -377,3 +379,45 @@ it('a rejected operation does not poison subsequent drain', async () => {await expect(f.service.cancel('p', run.runId)).resolves.toMatchObject({status:'cancelled'});await f.service.drain();});+++describe('current plugin dispatch authority', () => {+ it.each(['plan', 'acceptEdits', 'auto'])('allows only authority within %s configuration', configured => {+ const modes = ['plan', 'acceptEdits', 'auto'];+ for (const mode of [...modes, 'bypassPermissions', 'unknown', undefined]) {+ expect(isPluginTaskPermissionAllowed(mode, configured)).toBe(modes.includes(mode!) && modes.indexOf(mode!) <= modes.indexOf(configured));+ }+ expect(isPluginTaskPermissionAllowed('auto', undefined)).toBe(false);+ });+ it.each(['before', 'route', 'insert'])('blocks a new dispatch after revocation at %s', async point => {+ const f = fixture(), task = await f.create();+ f.tasks.get(task.taskId)!.permissionMode = 'auto';+ let mode = 'auto'; f.deps.readPermissionMode = () => mode;+ if (point === 'before') mode = 'plan';+ if (point === 'route') f.deps.resolveRoute = async () => { mode = 'plan'; return f.route; };+ if (point === 'insert') {+ const insert = f.deps.store.insert;+ f.deps.store.insert = async row => { await insert(row); mode = 'plan'; };+ }+ const attempt = f.service.send('p', {taskId:task.taskId,expectedRevision:task.revision,requestKey:'new',text:'input'});+ if (point === 'insert') await expect(attempt).resolves.toMatchObject({status:'reconciling'});+ else await expect(attempt).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ expect(f.deps.dispatch).not.toHaveBeenCalled();+ });+ it.each(['before', 'route', 'save'])('blocks queued acceptance after revocation at %s and keeps cancel available', async point => {+ const f = fixture(), run = await f.send();+ f.tasks.get(run.taskId)!.permissionMode = 'auto';+ let mode = 'auto'; f.deps.readPermissionMode = () => mode;+ if (point === 'before') mode = 'plan';+ if (point === 'route') f.deps.resolveRoute = async () => { mode = 'plan'; return f.route; };+ if (point === 'save') {+ const save = f.deps.store.save;+ f.deps.store.save = async row => { await save(row); mode = 'plan'; };+ }+ await expect(f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution)).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ // Same-key retries observe the existing receipt; they never reopen dispatch.+ const calls = vi.mocked(f.deps.dispatch).mock.calls.length;+ await f.send(); expect(f.deps.dispatch).toHaveBeenCalledTimes(calls);+ await expect(f.service.cancel('p',run.runId)).resolves.toMatchObject({status:'cancelled'});+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.tsindex 3fd662ddb1..3f1d155220 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectory.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';+import { mkdtemp, mkdir, realpath, rename, rm, symlink } from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';@@ -39,3 +39,19 @@ describe('plugin Worker directory authorization', () => {expect(assertCurrent).toHaveBeenCalledTimes(2);});});+++it.each(['configuredDirectory', 'leadDirectory'] as const)('does not retarget a stored %s grant through a replacement link', async key => {+ const root=await realpath(await mkdtemp(path.join(os.tmpdir(),'plugin-root-identity-')));+ try {+ const selected=path.join(root,'selected'), other=path.join(root,'other');+ await mkdir(selected);await mkdir(other);+ const input={requested:selected,[key]:selected,isPickedDirectory:()=>false,assertCurrent:()=>{}};+ expect(await resolvePluginWorkerDirectory(input)).toBe(selected);+ await rename(selected,path.join(root,'old'));await symlink(other,selected,'junction');+ await expect(resolvePluginWorkerDirectory(input)).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ await expect(resolvePluginWorkerDirectory({...input,requested:other})).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ // An independent exact pick can still authorize that real target.+ expect(await resolvePluginWorkerDirectory({...input,isPickedDirectory:dir=>dir===other})).toBe(other);+ } finally {await rm(root,{recursive:true,force:true});}+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 80e901e4c5..176de88da5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';import { describe, expect, it, vi } from 'vitest';import ts from 'typescript';import { withSessionRestartLock, withSendToSessionLock, sendToSessionLocks } from '../sendToSessionLock.js';-import { PluginTaskError } from '../pluginTaskService.js';+import { isPluginTaskPermissionAllowed, PluginTaskError } from '../pluginTaskService.js';// Execute the real switch branch with controlled Host boundaries.const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');@@ -21,7 +21,7 @@ function fixture() {const slots = new Set<string>();const dialog = { showMessageBox: vi.fn(async () => ({ response: 0 })) };const write = vi.fn((_id: string, value: Record<string, unknown>) => { cfg = value; });- const deps = { withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => epoch, readGhostErrandConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => live }, inputCoordinator: { getQueueControlSnapshot: () => ({ pendingQueue: [] }) }, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };+ const deps = { isPluginTaskPermissionAllowed, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => epoch, readGhostErrandConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => live }, inputCoordinator: { getQueueControlSnapshot: () => ({ pendingQueue: [] }) }, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };const run = new Function(...Object.keys(deps), js)(...Object.values(deps));return { run: (mode = 'acceptEdits') => run('plugin', { kind: 'requestWriteAccess', taskId: 'task', mode }), service, live, epoch, dialog, slots, write, history, drain, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };}@@ -122,3 +122,18 @@ describe('first plugin write approval checks actual task history', () => {release(); await result;await withSendToSessionLock('task', send); expect(send).toHaveBeenCalledOnce();});+++it.each(['bypassPermissions', 'auto', 'acceptEdits'])('does not report %s as granted after plugin authority is lowered', async permissionMode => {+ const f = fixture();+ f.service.get.mockImplementation(async () => ({taskId:'task',revision:1,permissionMode}));+ f.dialog.showMessageBox.mockResolvedValue({response:1});+ await expect(f.run()).resolves.toMatchObject({granted:false});+ expect(f.dialog.showMessageBox).toHaveBeenCalledOnce();+ expect(f.live.setPermissionMode).not.toHaveBeenCalled();+});+it.each(['acceptEdits', 'auto'])('reuses an effective %s grant without another confirmation',async permissionMode=>{+ const f=fixture();f.change({permissionMode});+ f.service.get.mockImplementation(async()=>({taskId:'task',revision:1,permissionMode}));+ await expect(f.run()).resolves.toMatchObject({granted:true});expect(f.dialog.showMessageBox).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex b79dd1a2ce..4c2324efbe 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -51,6 +51,12 @@ export class PluginTaskError extends Error {export function assertPluginTaskResult(result: { ok: boolean; errorCode?: string }, message: string): void {if (!result.ok) throw new PluginTaskError(result.errorCode || 'HOST_NOT_READY', message);}+/** A live task cannot exercise more authority than the plugin's current setting. */+export function isPluginTaskPermissionAllowed(taskMode: unknown, configuredMode: unknown): boolean {+ const rank = (mode: unknown) => mode === 'plan' ? 0 : mode === 'acceptEdits' ? 1 : mode === 'auto' ? 2 : -1;+ const task = rank(taskMode);+ return task >= 0 && task <= Math.max(0, rank(configuredMode));+}const fail = (code: string, message: string): never => {throw new PluginTaskError(code, message);};@@ -64,6 +70,7 @@ export interface PluginTaskServiceDeps {/** Bound to the captured account/database epoch and plugin availability. */assertCurrent(): void;assertAuthorized(pluginId: string): void;+ readPermissionMode(pluginId: string): unknown;resolveRoute(pluginId: string, route?: PluginTaskRoute): Promise<PluginTaskRoute>;createSession(pluginId: string,@@ -115,6 +122,14 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {operations = Promise.all([operations, result.catch(() => undefined)]).then(() => undefined);return result;};+ const assertDispatch = async (pluginId: string, taskId: string) => {+ const view = await ownTask(pluginId, taskId);+ deps.assertAuthorized(pluginId);+ if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');+ if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId)))+ return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ return view;+ };const save = async (row: PluginTaskReceipt, payload: unknown) => {deps.assertCurrent();row.payload = JSON.stringify(payload);@@ -238,6 +253,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {if (!data.teamPlan?.items.some((x: {label:string})=>x.label===label)) return fail('INVALID_REQUEST','Worker is not in team plan');await save(row,{...data,settledLabels:[...new Set([...(data.settledLabels||[]),label])]});}),+ assertDispatch,get: (pluginId: string, taskId: string) => exclusive(() => ownTask(pluginId, taskId)),list: (pluginId: string, after = '', limit = 50) =>exclusive(async () => {@@ -263,12 +279,13 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {);if (previous)return { run: JSON.parse(previous.payload) as PluginTaskRun, dispatch: false };- if (view.permissionMode === 'bypassPermissions') return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId))) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');if (view.status !== 'active')return fail('TASK_BUSY', 'Archived tasks cannot accept input');if (view.revision !== request.expectedRevision)return fail('REVISION_CONFLICT', 'Task configuration changed');await deps.resolveRoute(pluginId, view.resolvedConfig);+ await assertDispatch(pluginId, view.taskId);const runId = id();const run: PluginTaskRun = {runId,@@ -290,7 +307,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {// Never hold the receipt lock while entering Session dispatch/control. The// coordinator awaits accept() before vendor dispatch under its own lock.try {- deps.assertAuthorized(pluginId);+ await assertDispatch(pluginId, prepared.run.taskId);const outcome = await deps.dispatch(pluginId,prepared.run.taskId,@@ -372,14 +389,16 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {}const view = await ownTask(row.pluginId, taskId);if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');- if (view.permissionMode === 'bypassPermissions') return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(row.pluginId))) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');if (hash(view.resolvedConfig) !== hash(run.acceptedConfig))return fail('ROUTE_UNAVAILABLE', 'Accepted route changed before dispatch');await deps.resolveRoute(row.pluginId, run.acceptedConfig);+ await assertDispatch(row.pluginId, taskId);run.inputClientIds = [...new Set([...(run.inputClientIds ?? []), item.clientId])];run.execution = execution;run.status = 'running';await save(row, run);+ await assertDispatch(row.pluginId, taskId);}}),settle: (diff --git a/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.ts b/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.tsindex fcc21488e5..3031935240 100644--- a/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.ts+++ b/apps/desktop/src/main/maker-ipc/pluginWorkerDirectory.ts@@ -16,11 +16,20 @@ export async function resolvePluginWorkerDirectory(input: {input.assertCurrent();const resolved = await realpath(input.requested);if (!(await stat(resolved)).isDirectory()) throw deny();+ // Stored Host roots are canonical identities, not aliases to resolve into new grants.+ const sameDirectory = (a: string, b: string) => isPathInsideDir(a, b) && isPathInsideDir(b, a);+ const unchangedRoot = async (stored: string) => {+ const current = await realpath(stored);+ return sameDirectory(stored, current) ? current : null;+ };let allowed = false;- if (input.leadDirectory) allowed = isPathInsideDir(await realpath(input.leadDirectory), resolved);+ if (input.leadDirectory) {+ const lead = await unchangedRoot(input.leadDirectory);+ allowed = lead !== null && isPathInsideDir(lead, resolved);+ }if (!allowed && input.configuredDirectory) {- const configured = await realpath(input.configuredDirectory);- allowed = isPathInsideDir(configured, resolved) && isPathInsideDir(resolved, configured);+ const configured = await unchangedRoot(input.configuredDirectory);+ allowed = configured !== null && sameDirectory(configured, resolved);}// Pick grants are exact-directory grants, not permission for an arbitrary Library root.if (!allowed) allowed = input.isPickedDirectory(resolved);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 1a15ea685a..7bfad15587 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,4 +1,4 @@-import { assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';+import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';@@ -10161,6 +10161,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)pluginTaskEpoch = snapshot;pluginTasks = createPluginTaskService({store: createPluginTaskStore(snapshot.client), assertCurrent, assertAuthorized: assertPlugin, resolveRoute,+ readPermissionMode: pluginId => readGhostErrandConfig(pluginId).permissionMode,assertTeamPlanUnstarted: async taskId => {assertCurrent();const workers = await snapshot.client.drizzle.select({id:orcaWorkers.id}).from(orcaWorkers).innerJoin(orcaTeams,eq(orcaWorkers.teamId,orcaTeams.id)).where(eq(orcaTeams.leadSessionId,taskId)).limit(1);@@ -10193,7 +10194,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},dispatch: async (pluginId, taskId, clientId, text) => {assertPlugin(pluginId);- const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, forceQueue: true, onAccepted: () => assertPlugin(pluginId) });+ const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, forceQueue: true, onAccepted: async () => { assertPlugin(pluginId); await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId); assertPlugin(pluginId); } });await awaitAgentInputQueueSnapshotPersistence(taskId);assertCurrent();return outcome;@@ -10275,7 +10276,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const task = await service.get(pluginId, request.taskId);const mode = request.mode ?? 'acceptEdits';const cfg = readGhostErrandConfig(pluginId);- if (mode === 'acceptEdits' ? task.permissionMode !== 'plan' : task.permissionMode === 'auto' && cfg.permissionMode === 'auto') return { granted: true, task };+ if (isPluginTaskPermissionAllowed(task.permissionMode, cfg.permissionMode) && (mode === 'acceptEdits' ? task.permissionMode === 'acceptEdits' || task.permissionMode === 'auto' : task.permissionMode === 'auto')) return { granted: true, task };if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');const before = JSON.stringify(cfg);const assertIdle = async () => {