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(shared-task): SSH 建链期间被撤权时不再发出访客的文件修改

david030efb56ecce
diff --git a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
index 89409211f3..d2f3b67995 100644
--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
@@ -322,6 +322,38 @@ describe('file-browser device-op', () => {
expect(read.data.content).toBe('export const a = 1;\n');
});
+ it('does not send an SSH write when membership ends while the connection is being built', async () => {
+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });
+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);
+ sharedWorkdirMock.mockImplementation(async () => ({ remoteHostId: 'host-1' }));
+ const sent = vi.fn();
+ // The manager awaits getClient, then calls beforeSend right before sending.
+ sshRequestMock.mockImplementation(
+ async (_h: string, method: string, _p: unknown, options?: { beforeSend?: () => void }) => {
+ current = false;
+ options?.beforeSend?.();
+ sent(method);
+ return { size: 1, mtimeMs: 1 };
+ },
+ );
+ await expect(
+ asGuest(() =>
+ handleRemoteOp({ op: 'writeFile', workdir: '/remote/proj', relPath: 'a.ts', content: 'x' }),
+ ),
+ ).rejects.toThrow('PERMISSION_DENIED');
+ expect(sent).not.toHaveBeenCalled();
+ // Same-account controllers keep the unchanged three-argument call.
+ current = true;
+ sshRequestMock.mockResolvedValue({ size: 1, mtimeMs: 1 });
+ await handleRemoteOp({ op: 'writeFile', workdir: '/remote/proj', relPath: 'a.ts', content: 'x' });
+ expect(sshRequestMock).toHaveBeenLastCalledWith('host-1', 'writeFile', {
+ workdir: '/remote/proj',
+ relPath: 'a.ts',
+ content: 'x',
+ });
+ sshRequestMock.mockReset();
+ });
+
it('rebinds the task workdir and endpoint after the endpoint checks, before touching files', async () => {
// The owner moves the task while this write is in flight.
guardMock.mockImplementationOnce(async () => {
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
index be08da25c6..ac0cbd79bb 100644
--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
@@ -9,7 +9,7 @@
*/
import { PassThrough } from 'node:stream';
-import { mkdtemp, rm, writeFile as fsWriteFile } from 'node:fs/promises';
+import { mkdtemp, readFile, rm, writeFile as fsWriteFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -128,6 +128,28 @@ describe('RemoteFileBrowserManager', () => {
await mgr.disposeAll();
});
+ it('beforeSend runs after the connection is built and can stop the request', async () => {
+ const { deps, calls } = makeDeps({ probeResults: [READY_PROBE] });
+ const mgr = new RemoteFileBrowserManager(deps);
+ let spawnedBeforeGate = -1;
+ await expect(
+ mgr.request(
+ 'h1',
+ 'writeFile',
+ { workdir, relPath: 'hello.txt', content: 'late\n' },
+ {
+ beforeSend: () => {
+ spawnedBeforeGate = calls.spawn;
+ throw new Error('[PERMISSION_DENIED] revoked');
+ },
+ },
+ ),
+ ).rejects.toThrow('PERMISSION_DENIED');
+ expect(spawnedBeforeGate).toBe(1);
+ expect(await readFile(path.join(workdir, 'hello.txt'), 'utf8')).toBe('hi\n');
+ await mgr.disposeAll();
+ });
+
it('concurrent first requests share one connection build', async () => {
const { deps, calls } = makeDeps({ probeResults: [READY_PROBE] });
const mgr = new RemoteFileBrowserManager(deps);
diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.ts
index cc83d04a07..1fd8dc265b 100644
--- a/apps/desktop/src/main/file-browser/device-op.ts
+++ b/apps/desktop/src/main/file-browser/device-op.ts
@@ -59,6 +59,7 @@ import {
type PushOwnerStamp,
} from '@cindy/device-link';
import { WorkdirWatchManager } from '@cindy/remote-file-service';
+import type { FsRpcMethods } from '@cindy/remote-file-service/protocol';
import { createLogger } from '../logger.js';
import { getDbClient } from '../localDb/client/current.js';
@@ -483,16 +484,29 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
const sameEndpoint =
expected === sharedTaskEndpoint.remoteHostId &&
(expected ? exec.kind === 'ssh' && exec.hostId === expected : exec.kind === 'local');
- if (!sameEndpoint) throw new Error('[PERMISSION_DENIED] Shared task working directory endpoint mismatch');
+ if (!sameEndpoint)
+ throw new Error('[PERMISSION_DENIED] Shared task working directory endpoint mismatch');
}
// —— SSH 二跳:直接透传给本机的 SSH file-service 路由 ——
if (exec.kind === 'ssh') {
const mgr = getRemoteFileBrowser();
const hostId = exec.hostId;
+ // 共享访客:SSH 建链等待期间可能被撤权,尚未发出的请求在发送前复核成员资格。
+ const gate = sharedTask
+ ? {
+ beforeSend: () => {
+ if (!sharedTask.isCurrent() || !sharedTask.authorize(sharedTaskOperation!)) {
+ throw new Error('[PERMISSION_DENIED] Shared task access changed');
+ }
+ },
+ }
+ : undefined;
+ const request = <M extends keyof FsRpcMethods>(method: M, params: FsRpcMethods[M]['params']) =>
+ gate ? mgr.request(hostId, method, params, gate) : mgr.request(hostId, method, params);
switch (args.op) {
case 'listDir': {
- const { entries } = await mgr.request(hostId, 'listDir', {
+ const { entries } = await request('listDir', {
workdir,
relPath: args.relPath ?? '',
hideMetaFiles: args.hideMetaFiles ?? true,
@@ -504,7 +518,7 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
}
case 'readFile': {
try {
- const data = await mgr.request(hostId, 'readFile', {
+ const data = await request('readFile', {
workdir,
relPath: args.relPath ?? '',
});
@@ -516,9 +530,9 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
}
}
case 'stat':
- return mgr.request(hostId, 'stat', { workdir, relPath: args.relPath ?? '' });
+ return request('stat', { workdir, relPath: args.relPath ?? '' });
case 'writeFile': {
- const r = await mgr.request(hostId, 'writeFile', {
+ const r = await request('writeFile', {
workdir,
relPath: args.relPath ?? '',
content: writeContent ?? '',
@@ -528,27 +542,27 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
case 'createFile':
return {
ok: true as const,
- stat: await mgr.request(hostId, 'createFile', { workdir, relPath: args.relPath ?? '' }),
+ stat: await request('createFile', { workdir, relPath: args.relPath ?? '' }),
};
case 'createFolder':
return {
ok: true as const,
- stat: await mgr.request(hostId, 'createFolder', { workdir, relPath: args.relPath ?? '' }),
+ stat: await request('createFolder', { workdir, relPath: args.relPath ?? '' }),
};
case 'renameEntry':
return {
ok: true as const,
- stat: await mgr.request(hostId, 'renameEntry', {
+ stat: await request('renameEntry', {
workdir,
fromRel: args.fromRel ?? '',
toRel: args.toRel ?? '',
}),
};
case 'deleteEntry':
- await mgr.request(hostId, 'deleteEntry', { workdir, relPath: args.relPath ?? '' });
+ await request('deleteEntry', { workdir, relPath: args.relPath ?? '' });
return { ok: true as const };
case 'listAllFiles':
- return mgr.request(hostId, 'listAllFiles', { workdir, cap: args.cap });
+ return request('listAllFiles', { workdir, cap: args.cap });
case 'exportFileStart':
case 'exportFileStatus':
case 'fileUrl':
diff --git a/apps/desktop/src/main/file-browser/remote.ts b/apps/desktop/src/main/file-browser/remote.ts
index 4ae45960f0..41b6bcfdef 100644
--- a/apps/desktop/src/main/file-browser/remote.ts
+++ b/apps/desktop/src/main/file-browser/remote.ts
@@ -121,15 +121,19 @@ export class RemoteFileBrowserManager {
/**
* 类型安全的远程调用入口。断链自动重建一次(仅幂等读方法);其余错误原样抛
* FileServiceRpcError(caller 决定 throwIpcError 还是 {ok:false})。
+ * `beforeSend` 在建链等待之后、每次真正发出请求之前同步调用,抛错即不发送
+ * (共享任务访客用它在建链期间被撤权时拦下尚未发出的修改)。
*/
async request<M extends keyof FsRpcMethods>(
hostId: string,
method: M,
params: FsRpcMethods[M]['params'],
+ options?: { beforeSend?: () => void },
): Promise<FsRpcMethods[M]['result']> {
const generation = this.currentEndpointGeneration(hostId);
const client = await this.getClient(hostId, generation);
this.assertCurrentEndpointGeneration(hostId, generation);
+ options?.beforeSend?.();
try {
const result = await client.request(method, params);
this.assertCurrentEndpointGeneration(hostId, generation);
@@ -148,6 +152,7 @@ export class RemoteFileBrowserManager {
this.log.warn('file-service channel lost, rebuilding', { hostId, method });
this.clients.delete(hostId);
const rebuilt = await this.getClient(hostId, generation);
+ options?.beforeSend?.();
const result = await rebuilt.request(method, params);
this.assertCurrentEndpointGeneration(hostId, generation);
return result;