Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mcp): 统一项目移动与登记的真实路径校验

Dashae5b5783e5c8
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
index d98174b9fb..1ac78e2c0b 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
@@ -38,12 +38,14 @@ vi.mock('../../localDb/client/current.js', () => {
};
return { tryGetDbClient: () => (h.ready ? client : null) };
});
-vi.mock('../../localDb/ipc/recentWorkdirs.js', () => ({
- normalizeRecentWorkdirPath: (value: string) =>
- value.includes('.cindy-worktrees') ? null : value.replaceAll('\\', '/'),
- upsertRecentWorkdir: h.upsert,
- listRecentWorkdirs: h.list,
-}));
+vi.mock('../../localDb/ipc/recentWorkdirs.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../localDb/ipc/recentWorkdirs.js')>();
+ return {
+ normalizeRecentWorkdirPath: actual.normalizeRecentWorkdirPath,
+ upsertRecentWorkdir: h.upsert,
+ listRecentWorkdirs: h.list,
+ };
+});
vi.mock('../../localDb/ipc/projectAliases.js', () => ({
listProjectAliases: h.aliases,
upsertProjectAlias: h.rename,
@@ -110,15 +112,30 @@ describe('createProject', () => {
});
expect(h.upsert).not.toHaveBeenCalled();
});
- it('rejects symlink and junction aliases of managed worktrees before registration', async () => {
- const managed = path.join(directory, '.cindy-worktrees', 'task');
- await mkdir(managed, { recursive: true });
- const alias = path.join(directory, 'alias');
- await symlink(managed, alias, process.platform === 'win32' ? 'junction' : 'dir');
- expect(await run(alias)).toMatchObject({ errorCode: 'INVALID_ARGS' });
- expect(h.upsert).not.toHaveBeenCalled();
- expect(h.restore).not.toHaveBeenCalled();
- });
+ it.for(['.cindy-worktrees', '.xdt-worktrees'])(
+ 'rejects %s aliases before registration',
+ async (managedName, ctx) => {
+ const managed = path.join(directory, managedName, 'task');
+ await mkdir(managed, { recursive: true });
+ const alias = path.join(directory, 'alias');
+ try {
+ await symlink(managed, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch (error) {
+ if (['EPERM', 'EACCES', 'ENOSYS'].includes((error as NodeJS.ErrnoException).code ?? '')) {
+ ctx.skip();
+ return;
+ }
+ throw error;
+ }
+ expect(await run(alias)).toMatchObject({ errorCode: 'INVALID_ARGS' });
+ expect(h.upsert).not.toHaveBeenCalled();
+ expect(h.restore).not.toHaveBeenCalled();
+ await rm(alias);
+ await symlink(directory, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ // Preserve the logical alias identity, not the physical target path.
+ expect(await run(alias)).toMatchObject({ ok: true, workingDir: alias.replaceAll('\\', '/') });
+ },
+ );
it('rejects files, relative paths and managed task worktrees', async () => {
const file = path.join(directory, 'file');
await writeFile(file, 'contents');
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
index 7d70972202..4bbfe26f74 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
@@ -1,4 +1,4 @@
-import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -31,10 +31,13 @@ vi.mock('../../localDb/client/current.js', () => {
};
return { tryGetDbClient: () => client };
});
-vi.mock('../../localDb/ipc/recentWorkdirs.js', () => ({
- normalizeRecentWorkdirPath: (p: string) => p,
- upsertRecentWorkdir: vi.fn(),
-}));
+vi.mock('../../localDb/ipc/recentWorkdirs.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../localDb/ipc/recentWorkdirs.js')>();
+ return {
+ normalizeRecentWorkdirPath: actual.normalizeRecentWorkdirPath,
+ upsertRecentWorkdir: vi.fn(),
+ };
+});
vi.mock('../../sidebarSettingsStore.js', () => ({ restoreLocalProjectVisibility: vi.fn() }));
vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
vi.mock('../../im/binding.js', () => ({
@@ -58,7 +61,7 @@ describe('moveSession host', () => {
{ id: 'target', status: 'active', remoteHostId: null, source: null, orcaRole: null },
]);
h.update.mockImplementation(async (id, patch, _opts, guard) => {
- h.enterLock();
+ await h.enterLock();
guard.assertCurrent();
await guard.beforeUpdate();
guard.assertCurrent();
@@ -79,6 +82,7 @@ describe('moveSession host', () => {
});
it('uses the shared update path for moving projects and preserves cwd when removing grouping', async () => {
+ // recent_workdirs stores logical project identities with forward slashes on all platforms.
expect(await run(directory)).toMatchObject({
ok: true,
workingDir: directory.replaceAll('\\', '/'),
@@ -99,12 +103,16 @@ describe('moveSession host', () => {
'rechecks running state after acquiring the route lock (%s)',
async (target) => {
h.enterLock.mockImplementation(() => h.running.add('target'));
- expect(await run(target ? directory : null)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });
+ expect(await run(target ? directory : null)).toMatchObject({
+ errorCode: 'PRECONDITION_FAILED',
+ });
expect(h.saved).not.toHaveBeenCalled();
},
);
it('does not report a committed move as rejected when IM attaches after the write', async () => {
- h.saved.mockImplementationOnce(() => { h.attached = true; });
+ h.saved.mockImplementationOnce(() => {
+ h.attached = true;
+ });
expect(await run(null)).toMatchObject({ ok: true, workspaceKind: 'dialogue' });
});
@@ -143,4 +151,32 @@ describe('moveSession host', () => {
expect(await run('relative')).toMatchObject({ errorCode: 'INVALID_ARGS' });
expect(h.saved).not.toHaveBeenCalled();
});
+ it.for(['.cindy-worktrees', '.xdt-worktrees'])(
+ 'rejects a %s alias retargeted while waiting for the route lock',
+ async (managedName, ctx) => {
+ const ordinary = path.join(directory, 'ordinary');
+ const managed = path.join(directory, managedName, 'task');
+ const alias = path.join(directory, 'alias');
+ await mkdir(ordinary);
+ await mkdir(managed, { recursive: true });
+ try {
+ await symlink(ordinary, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch (error) {
+ if (['EPERM', 'EACCES', 'ENOSYS'].includes((error as NodeJS.ErrnoException).code ?? '')) {
+ ctx.skip();
+ return;
+ }
+ throw error;
+ }
+ expect(await run(alias)).toMatchObject({ ok: true, workingDir: alias.replaceAll('\\', '/') });
+ h.saved.mockClear();
+ h.enterLock.mockImplementationOnce(async () => {
+ await rm(alias);
+ await symlink(managed, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ });
+ expect(await run(alias)).toMatchObject({ errorCode: 'INVALID_PARAMS' });
+ expect(h.saved).not.toHaveBeenCalled();
+ expect(await run(null)).toMatchObject({ ok: true, workingDir: '/old' });
+ },
+ );
});
diff --git a/apps/desktop/src/main/mcp-integrations/createProject.ts b/apps/desktop/src/main/mcp-integrations/createProject.ts
index ddb55f6de7..11e8557b85 100644
--- a/apps/desktop/src/main/mcp-integrations/createProject.ts
+++ b/apps/desktop/src/main/mcp-integrations/createProject.ts
@@ -91,6 +91,14 @@ export function validateLocalProjectDirectory(
: fail('INVALID_ARGS', 'Managed task worktrees cannot be registered as separate projects.');
}
+/** Check physical targets without changing the caller's normalized project identity. */
+export async function validateExistingLocalProjectDirectory(workingDir: string) {
+ if (!(await stat(workingDir)).isDirectory())
+ return fail('NOT_A_DIRECTORY', 'working_dir is not a directory.');
+ // Both registration and task moves must reject disguised managed worktrees.
+ return validateLocalProjectDirectory(await realpath(workingDir));
+}
+
/** Register only: filesystem creation and task execution remain separate agent actions. */
export async function createProject({
callerSessionId,
@@ -102,10 +110,7 @@ export async function createProject({
const directory = validateLocalProjectDirectory(workingDir);
if (!directory.ok) return directory;
return withLocalProjectContext(callerSessionId, async ({ client, owner, assertCurrent }) => {
- if (!(await stat(directory.workingDir)).isDirectory())
- return fail('NOT_A_DIRECTORY', 'working_dir is not a directory.');
- // Symlinks/junctions must not disguise a managed task worktree as a project.
- const physicalDirectory = validateLocalProjectDirectory(await realpath(directory.workingDir));
+ const physicalDirectory = await validateExistingLocalProjectDirectory(directory.workingDir);
if (!physicalDirectory.ok) return physicalDirectory;
assertCurrent();
if (!(await upsertRecentWorkdir(directory.workingDir, Date.now(), process.platform, client))) {
diff --git a/apps/desktop/src/main/mcp-integrations/moveSession.ts b/apps/desktop/src/main/mcp-integrations/moveSession.ts
index b8728524b9..d89c6d70d9 100644
--- a/apps/desktop/src/main/mcp-integrations/moveSession.ts
+++ b/apps/desktop/src/main/mcp-integrations/moveSession.ts
@@ -1,11 +1,14 @@
-import { stat } from 'node:fs/promises';
import { and, eq } from 'drizzle-orm';
import type { XdtHelperMcpDeps } from '@cindy/mcps';
import { sessions, orcaTeams, orcaWorkers } from '../localDb/schema.js';
import { updateSessionInDb } from '../localDb/ipc/sessions.js';
import { bindingStore } from '../im/binding.js';
import { throwIpcError } from '../utils/ipcValidate.js';
-import { validateLocalProjectDirectory, withLocalProjectContext } from './createProject.js';
+import {
+ validateExistingLocalProjectDirectory,
+ validateLocalProjectDirectory,
+ withLocalProjectContext,
+} from './createProject.js';
/** The caller supplies the same live running-state projection used by the sidebar. */
export function createMoveSession(
@@ -64,8 +67,10 @@ export function createMoveSession(
.innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))
.where(and(eq(orcaTeams.leadSessionId, sessionId), eq(orcaTeams.status, 'active')))
: [];
- if (targetDir && !(await stat(targetDir)).isDirectory())
- throwIpcError('INVALID_PARAMS', 'working_dir is not a directory.');
+ if (targetDir) {
+ const physicalDirectory = await validateExistingLocalProjectDirectory(targetDir);
+ if (!physicalDirectory.ok) throwIpcError('INVALID_PARAMS', physicalDirectory.message);
+ }
assertMoveAllowed();
};
const patch =