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(remote-agent): 同步跟随软链;分享的供应商读凭证不论权限档都要本机确认

Lizi17065774d954
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 6c0fc33603..1185703a40 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -122,6 +122,7 @@ import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';
import { remoteBackgroundInvoke, remoteInvoke } from '../device-link/index.js';
import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
import { parseProviderShareAgentDeviceId } from '../device-link/providerShareGuest.js';
+import { t } from '../i18n.js';
import { createHistoryRemoteDeps } from '../mcp-integrations/historyDevices.js';
import { WorktreePool } from '../worktree/index.js';
import { getReadyBinaryPath, getCachedBinaryStatus } from '../agent-binaries/index.js';
@@ -2722,6 +2723,8 @@ export function getMaker(): Maker {
// 供应商分享的受邀者任务:WebFetch 用本机网络抓取(系统代理、单跳、内网要本机批准)。
isSharedProviderDevice: (deviceId) => parseProviderShareAgentDeviceId(deviceId) !== null,
webFetch: guardedOutboundFetch,
+ // 受邀者任务读写凭证类文件时,本机确认卡上的说明(provider-sharing.md §9 第 7 条)。
+ sharedProviderCredentialNotice: () => t('newChat.sharedProviderCredential.description'),
logger: desktopMakerLogger,
}),
makerMemory: makerMemoryManager,
diff --git a/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts
new file mode 100644
index 0000000000..6e23550b1e
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts
@@ -0,0 +1,79 @@
+/**
+ * 供应商分享的受邀者任务里「凭证类」的判定:沿用本机凭证规则,但配置目录里的说明类内容(Skill、
+ * 子代理、命令、规则、个人说明)不算凭证。
+ */
+import { describe, expect, it } from 'vitest';
+
+import { isShareCredentialCommand, isShareCredentialPath } from '../credentials';
+
+describe('isShareCredentialPath', () => {
+ it('keeps the credential rules of local tasks', () => {
+ for (const target of [
+ '/home/me/.ssh/id_ed25519',
+ '/home/me/.aws/credentials',
+ '/repo/.env',
+ '/repo/.env.production',
+ '/repo/certs/server.key',
+ '/home/me/.config/gh/hosts.yml',
+ 'C:\\Users\\me\\.ssh\\id_rsa',
+ ]) {
+ expect(isShareCredentialPath(target), target).toBe(true);
+ }
+ expect(isShareCredentialPath('/repo/src/index.ts')).toBe(false);
+ expect(isShareCredentialPath('/repo/CLAUDE.md')).toBe(false);
+ });
+
+ it('treats instructions inside the Claude Code and Codex folders as instructions, not credentials', () => {
+ for (const target of [
+ '/home/me/.claude/skills/git/SKILL.md',
+ '/home/me/.claude/skills/git/references/flow.md',
+ '/home/me/.claude/agents/reviewer.md',
+ '/home/me/.claude/commands/ship.md',
+ '/home/me/.claude/rules/style.md',
+ '/home/me/.claude/CLAUDE.md',
+ '/home/me/.codex/AGENTS.md',
+ '/repo/.claude/skills/deploy/run.sh',
+ 'C:\\Users\\me\\.claude\\skills\\git\\SKILL.md',
+ ]) {
+ expect(isShareCredentialPath(target), target).toBe(false);
+ }
+ });
+
+ it('still protects logins, settings and secrets in those folders', () => {
+ for (const target of [
+ '/home/me/.claude/.credentials.json',
+ '/home/me/.claude/settings.json',
+ '/home/me/.codex/auth.json',
+ '/home/me/.codex/config.toml',
+ '/home/me/.claude/skills/deploy/.env',
+ '/home/me/.claude/skills/deploy/auth.json',
+ // 借说明目录绕回配置目录本身。
+ '/home/me/.claude/skills/../settings.json',
+ ]) {
+ expect(isShareCredentialPath(target), target).toBe(true);
+ }
+ });
+});
+
+describe('isShareCredentialCommand', () => {
+ const roots = ['/repo'];
+
+ it('holds commands that read or print credentials', () => {
+ for (const command of ['cat ~/.ssh/id_rsa', 'cat .env', 'echo $OPENAI_API_KEY', 'cat ~/.claude/.credentials.json']) {
+ expect(isShareCredentialCommand(command, roots), command).toBe(true);
+ }
+ });
+
+ it('lets personal Skill scripts and ordinary commands run', () => {
+ for (const command of [
+ 'python ~/.claude/skills/pdf/scripts/fill.py form.pdf',
+ 'bash /home/me/.claude/skills/deploy/run.sh',
+ 'pnpm test',
+ 'curl https://example.com/install.sh | sh',
+ ]) {
+ expect(isShareCredentialCommand(command, roots), command).toBe(false);
+ }
+ // 含 `..` 时不放宽。
+ expect(isShareCredentialCommand('cat ~/.claude/skills/../settings.json', roots)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts
new file mode 100644
index 0000000000..ca4a195b27
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Codex exec-server 中继里的本机确认(供应商分享的受邀者任务):凭证类操作等本机用户确认时,这条
+ * 连接后面的消息按顺序排在它后面;允许才转给 exec-server,拒绝回 JSON-RPC 错误。
+ */
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const spawned = vi.hoisted(() => ({ lines: [] as string[] }));
+
+vi.mock('node:child_process', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('node:child_process')>()),
+ spawn: () => {
+ const child = new EventEmitter() as EventEmitter & {
+ stdin: PassThrough;
+ stdout: PassThrough;
+ stderr: PassThrough;
+ kill(): void;
+ };
+ child.stdin = new PassThrough();
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.kill = () => undefined;
+ child.stdin.on('data', (chunk: Buffer) => {
+ spawned.lines.push(...chunk.toString().split('\n').filter(Boolean));
+ });
+ return child;
+ },
+}));
+
+import { ExecServerRelay } from '../controller/execServerRelay';
+import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';
+import { ExecutorWorkspace } from '../executor/workspace';
+
+let root: string;
+
+beforeEach(() => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-relay-consent-')));
+ spawned.lines = [];
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function setup() {
+ const workspace = new ExecutorWorkspace({ workingDir: root });
+ const approved = new Set<string>();
+ const pending: Array<{ action: ExecutorAction; answer(allowed: boolean): void }> = [];
+ const replies: Array<Record<string, unknown>> = [];
+ const isSecret = (action: ExecutorAction) => action.kind !== 'fetch' && action.kind !== 'exec' && action.path.endsWith('.env');
+ const relay = new ExecServerRelay({
+ codexPath: 'codex',
+ cwd: root,
+ workspace,
+ authorize: (action): ExecutorGateDecision => {
+ if (!isSecret(action)) return { ok: true };
+ const key = action.kind === 'exec' || action.kind === 'fetch' ? '' : action.path;
+ return approved.delete(key) ? { ok: true, elevated: true } : { ok: false, reason: 'needs confirmation' };
+ },
+ confirm: (action) => new Promise<boolean>((resolve) => {
+ pending.push({
+ action,
+ answer: (allowed) => {
+ if (allowed && action.kind !== 'exec' && action.kind !== 'fetch') approved.add(action.path);
+ resolve(allowed);
+ },
+ });
+ }),
+ push: async (frames) => {
+ for (const frame of frames) if (frame.kind === 'message' && frame.data) replies.push(JSON.parse(frame.data));
+ },
+ });
+ relay.handle({ t: 'ws', connId: 'c1', kind: 'open', path: '/ws/exec-server' });
+ const send = (message: Record<string, unknown>) =>
+ relay.handle({ t: 'ws', connId: 'c1', kind: 'message', data: JSON.stringify(message) });
+ const sentIds = () => spawned.lines.map((line) => (JSON.parse(line) as { id?: unknown }).id);
+ return { relay, pending, replies, send, sentIds };
+}
+
+describe('exec-server relay with confirmation on this computer', () => {
+ it('passes ordinary messages straight through', () => {
+ const { send, sentIds, pending } = setup();
+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, 'a.txt') } });
+ send({ method: 'initialized', params: {} });
+ expect(sentIds()).toEqual([1, undefined]);
+ expect(pending).toEqual([]);
+ });
+
+ it('keeps later messages behind one that waits for the user, then forwards them in order', async () => {
+ const { send, sentIds, pending } = setup();
+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, '.env') } });
+ send({ id: 2, method: 'fs/readFile', params: { path: path.join(root, 'a.txt') } });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ expect(sentIds()).toEqual([]);
+ pending[0].answer(true);
+ await vi.waitFor(() => expect(sentIds()).toEqual([1, 2]));
+ });
+
+ it('answers with an error when the user declines and carries on with the rest', async () => {
+ const { send, sentIds, pending, replies } = setup();
+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, '.env') } });
+ send({ id: 2, method: 'fs/readFile', params: { path: path.join(root, 'a.txt') } });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ pending[0].answer(false);
+ await vi.waitFor(() => expect(sentIds()).toEqual([2]));
+ expect(replies).toEqual([{ id: 1, error: { code: -32001, message: 'needs confirmation' } }]);
+ });
+
+ it('drops what is still waiting when the connection closes', async () => {
+ const { relay, send, sentIds, pending } = setup();
+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, '.env') } });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ relay.handle({ t: 'ws', connId: 'c1', kind: 'close' });
+ pending[0].answer(true);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(sentIds()).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
index 75ccf2f895..3632b1d81c 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
@@ -103,42 +103,83 @@ describe('collectAncestorInstructionFiles', () => {
});
});
+/** 目录链接:Windows 用 junction(不需要管理员权限)。 */
+function linkDir(target: string, link: string): void {
+ fs.mkdirSync(path.dirname(link), { recursive: true });
+ fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');
+}
+
+/** 文件链接:没有权限创建时返回 false(没开开发者模式的 Windows)。 */
+function linkFile(target: string, link: string): boolean {
+ try {
+ fs.symlinkSync(target, link, 'file');
+ return true;
+ } catch (error) {
+ if (['EPERM', 'EACCES', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? '')) return false;
+ throw error;
+ }
+}
+
+function decode(files: Array<{ path: string; data: string }>): Record<string, string> {
+ return Object.fromEntries(files.map((file) => [file.path, Buffer.from(file.data, 'base64').toString()]));
+}
+
describe('collectProjectInstructionFiles', () => {
- it('rejects directory links so a checkout cannot smuggle files from outside the project', async () => {
+ it('follows directory links the way the Agent does on this computer', async () => {
const project = path.join(root, 'proj');
- const outside = path.join(root, 'outside');
+ const shared = path.join(root, 'shared-skills', 'deploy');
write(path.join(project, 'CLAUDE.md'), 'real rules');
- write(path.join(outside, 'SKILL.md'), 'secret leak');
- fs.mkdirSync(path.join(project, '.claude', 'skills'), { recursive: true });
- // Windows junction 不需要文件 symlink 的管理员权限,目录越界检查仍实跑。
- fs.symlinkSync(outside, path.join(project, '.claude', 'skills', 'leak'), process.platform === 'win32' ? 'junction' : 'dir');
- const files = await collectProjectInstructionFiles(project);
- expect(files.map((file) => file.path)).toEqual(['CLAUDE.md']);
- expect(files.map((file) => Buffer.from(file.data, 'base64').toString())).toEqual(['real rules']);
+ write(path.join(shared, 'SKILL.md'), 'deploy skill');
+ write(path.join(shared, 'scripts', 'run.sh'), 'echo deploy');
+ linkDir(shared, path.join(project, '.claude', 'skills', 'deploy'));
+ expect(decode(await collectProjectInstructionFiles(project))).toEqual({
+ 'CLAUDE.md': 'real rules',
+ '.claude/skills/deploy/SKILL.md': 'deploy skill',
+ '.claude/skills/deploy/scripts/run.sh': 'echo deploy',
+ });
});
- it('rejects file symlinks when the filesystem supports creating them', async (context) => {
+ it('follows file links when the filesystem supports creating them', async (context) => {
const project = path.join(root, 'proj');
- const outside = path.join(root, 'outside');
- write(path.join(project, 'CLAUDE.md'), 'real rules');
- write(path.join(outside, 'leak.md'), 'secret leak');
- write(path.join(outside, '.env'), 'SECRET=1');
- fs.mkdirSync(path.join(project, '.claude', 'skills'), { recursive: true });
- // 实际探测文件 symlink 能力;有权限的 Windows 与 macOS/Linux 均保留真实覆盖。
- try {
- fs.symlinkSync(path.join(outside, '.env'), path.join(project, 'CLAUDE.local.md'), 'file');
- } catch (error) {
- if (['EPERM', 'EACCES', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? '')) {
- context.skip();
- return;
- }
- throw error;
+ write(path.join(project, 'AGENTS.md'), 'shared rules');
+ if (!linkFile(path.join(project, 'AGENTS.md'), path.join(project, 'CLAUDE.md'))) {
+ context.skip();
+ return;
}
- fs.symlinkSync(path.join(outside, 'leak.md'), path.join(project, '.claude', 'skills', 'leak.md'));
- const files = await collectProjectInstructionFiles(project);
- expect(files.map((file) => file.path)).toEqual(['CLAUDE.md']);
- const decoded = files.map((file) => Buffer.from(file.data, 'base64').toString());
- expect(decoded).toEqual(['real rules']);
+ expect(decode(await collectProjectInstructionFiles(project))).toEqual({
+ 'CLAUDE.md': 'shared rules',
+ 'AGENTS.md': 'shared rules',
+ });
+ });
+
+ it('stops at a link back to its own parent and keeps a folder that two links share', async () => {
+ const project = path.join(root, 'proj');
+ const skills = path.join(project, '.claude', 'skills');
+ write(path.join(skills, 'a', 'SKILL.md'), 'a');
+ linkDir(skills, path.join(skills, 'loop'));
+ write(path.join(root, 'common', 'SKILL.md'), 'common');
+ linkDir(path.join(root, 'common'), path.join(skills, 'one'));
+ linkDir(path.join(root, 'common'), path.join(skills, 'two'));
+ expect(decode(await collectProjectInstructionFiles(project))).toEqual({
+ '.claude/skills/a/SKILL.md': 'a',
+ '.claude/skills/one/SKILL.md': 'common',
+ '.claude/skills/two/SKILL.md': 'common',
+ });
+ });
+
+ it('leaves credential files for later on a shared provider, judging links by their real target', async () => {
+ const project = path.join(root, 'proj');
+ write(path.join(project, 'CLAUDE.md'), 'rules');
+ write(path.join(project, '.claude', 'skills', 'deploy', 'SKILL.md'), 'deploy');
+ write(path.join(project, '.claude', 'skills', 'deploy', '.env'), 'TOKEN=1');
+ write(path.join(project, '.claude', 'settings.json'), JSON.stringify({ permissions: { allow: ['Bash(ls)'] } }));
+ write(path.join(root, 'outside', '.aws', 'credentials'), 'aws secret');
+ linkDir(path.join(root, 'outside', '.aws'), path.join(project, '.claude', 'skills', 'cloud'));
+ const own = decode(await collectProjectInstructionFiles(project));
+ expect(own['.claude/skills/deploy/.env']).toBe('TOKEN=1');
+ expect(own['.claude/skills/cloud/credentials']).toBe('aws secret');
+ const shared = decode(await collectProjectInstructionFiles(project, { skipCredentials: true }));
+ expect(Object.keys(shared).sort()).toEqual(['.claude/settings.json', '.claude/skills/deploy/SKILL.md', 'CLAUDE.md']);
});
});
@@ -169,6 +210,35 @@ describe('collectPersonalConfig', () => {
expect(roots).toContainEqual({ relative: '.claude/skills/mine', local: path.join(home, '.claude', 'skills', 'mine') });
});
+ it('follows personal Skills that are links, and a skills folder that is itself a link', async () => {
+ const home = path.join(root, 'home');
+ const dotfiles = path.join(root, 'dotfiles');
+ write(path.join(dotfiles, 'skills', 'git', 'SKILL.md'), 'git skill');
+ write(path.join(dotfiles, 'skills', 'git', 'reference.md'), 'git reference');
+ linkDir(path.join(dotfiles, 'skills', 'git'), path.join(home, '.claude', 'skills', 'git'));
+ const linked = await collectPersonalConfig('claude-code', [], { env: {}, home });
+ expect(decode(linked.personal.files)).toEqual({
+ '.claude/skills/git/SKILL.md': 'git skill',
+ '.claude/skills/git/reference.md': 'git reference',
+ });
+ expect(linked.roots).toEqual([{ relative: '.claude/skills/git', local: path.join(home, '.claude', 'skills', 'git') }]);
+
+ const stowed = path.join(root, 'stowed');
+ write(path.join(stowed, '.claude', 'CLAUDE.md'), 'personal memory');
+ linkDir(path.join(dotfiles, 'skills'), path.join(stowed, '.claude', 'skills'));
+ const whole = await collectPersonalConfig('claude-code', [], { env: {}, home: stowed });
+ expect(whole.personal.memory).toBe('personal memory');
+ expect(Object.keys(decode(whole.personal.files)).sort()).toEqual(['.claude/skills/git/SKILL.md', '.claude/skills/git/reference.md']);
+ });
+
+ it('leaves credential files in personal Skills for later on a shared provider', async () => {
+ const home = path.join(root, 'home');
+ write(path.join(home, '.claude', 'skills', 'deploy', 'SKILL.md'), 'deploy');
+ write(path.join(home, '.claude', 'skills', 'deploy', '.env'), 'TOKEN=1');
+ const { personal } = await collectPersonalConfig('claude-code', [], { env: {}, home, skipCredentials: true });
+ expect(decode(personal.files)).toEqual({ '.claude/skills/deploy/SKILL.md': 'deploy' });
+ });
+
it('honours CLAUDE_CONFIG_DIR and syncs nothing when there is no personal config', async () => {
const configDir = path.join(root, 'custom-claude');
write(path.join(configDir, 'CLAUDE.md'), 'from custom dir');
diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts
index e21da6e8a0..99d23ff1f3 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts
@@ -9,8 +9,9 @@ import WebSocket from 'ws';
import { mapClaudeHostedEvent } from '../controller/eventMap';
import { execServerActions, execServerCommand } from '../controller/execServerRelay';
import { collectProjectInstructionFiles } from '../controller/projectFiles';
-import { approvalActionsFor, innerShellScript } from '../controller/proxyHandle';
-import { takeGroupSwitchState } from '../controller/startRemote';
+import { approvalActionsFor, createRemoteAgentHandle, innerShellScript } from '../controller/proxyHandle';
+import type { RemoteAgentRunClient } from '../controller/runClient';
+import { credentialConfirmation, takeGroupSwitchState } from '../controller/startRemote';
import { EventLog, LineSplitter } from '../eventLog';
import { ExecutorWorkspace } from '../executor/workspace';
import { createRunTunnel } from '../host/tunnel';
@@ -114,6 +115,45 @@ describe('tunnel', () => {
});
});
+describe('confirmations raised on this computer', () => {
+ it('use the Agent confirmation channel and accept only a one-time allow', async () => {
+ let next = 0;
+ const controller = createRemoteAgentHandle({
+ client: {} as RemoteAgentRunClient,
+ started: { id: 'sdk-1', agentKind: 'claude-code', model: 'm', shadowDir: '', methods: [], state: {} },
+ workspace: new ExecutorWorkspace({ workingDir: root }),
+ recordApproval: () => undefined,
+ newId: () => `req-${(next += 1)}`,
+ dispose: async () => undefined,
+ });
+ const env = path.join(root, '.env');
+ const request = credentialConfirmation({ kind: 'read', path: env }, 'goes through the sharer');
+ // 交互还没接上:按拒绝处理。
+ expect(await controller.confirm(request)).toBe(false);
+ const seen: unknown[] = [];
+ let behavior: 'allow' | 'deny' = 'allow';
+ controller.handle.setInteractionResolver(async (incoming) => {
+ seen.push(incoming);
+ return { kind: 'permission', behavior };
+ });
+ expect(await controller.confirm(request)).toBe(true);
+ expect(seen).toEqual([{
+ kind: 'permission',
+ requestId: 'req-1',
+ toolName: 'Read',
+ input: { file_path: env },
+ description: 'goes through the sharer',
+ metadata: { hostOwnedConfirmation: 'shared_provider_credential' },
+ }]);
+ behavior = 'deny';
+ expect(await controller.confirm(request)).toBe(false);
+ expect(credentialConfirmation({ kind: 'exec', command: 'cat .env', cwd: root }, 'x')).toMatchObject({
+ toolName: 'Bash',
+ input: { command: 'cat .env' },
+ });
+ });
+});
+
describe('exec-server relay gate', () => {
it('maps exec-server requests to the actions checked on this computer', () => {
expect(execServerCommand(['/bin/zsh', '-lc', 'echo hi'])).toBe('echo hi');
diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
index b0d56cb110..7a1633842d 100644
--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
@@ -6,7 +6,8 @@
* `codex exec-server --listen stdio://`,命令、读写文件、补丁都在本机执行。
*
* 每个请求转给 exec-server 之前先过本机权限上限(与 Claude Code / Pi 同一个闸门):
- * 凭证类路径与高危命令只认本机用户批准过的同一操作;不通过就直接回 JSON-RPC 错误。
+ * 凭证类路径与高危命令只认本机用户批准过的同一操作;不通过就直接回 JSON-RPC 错误。供应商分享的
+ * 受邀者任务里,凭证类操作没有批准时先在本机弹确认卡,等待期间这条连接后面的消息排在它后面。
*/
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import path from 'node:path';
@@ -35,6 +36,8 @@ export interface ExecServerRelayDeps {
cwd: string;
workspace: ExecutorWorkspace;
authorize(action: ExecutorAction): ExecutorGateDecision;
+ /** 凭证类操作在本机补问(供应商分享的受邀者任务);允许后再 authorize 一次即放行。 */
+ confirm?(action: ExecutorAction): Promise<boolean>;
push(frames: RemoteAgentPushFrame[]): Promise<void>;
env?: NodeJS.ProcessEnv;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
@@ -44,6 +47,8 @@ interface Connection {
child: ChildProcessWithoutNullStreams;
buffer: string;
closed: boolean;
+ /** 有消息在等本机确认时,后面的消息按顺序排在它后面。 */
+ queue?: Promise<void>;
}
/** `["/bin/zsh","-lc","cmd"]` → `cmd`;其它形态按空格拼接。 */
@@ -226,21 +231,61 @@ export class ExecServerRelay {
} catch {
message = null;
}
+ let actions: ExecutorAction[] = [];
if (message && typeof message.method === 'string' && message.id !== undefined) {
message.params = mapExecServerParams(message.params, this.deps.workspace, message.method);
data = JSON.stringify(message);
- for (const action of execServerActions(message.method, message.params, this.deps.cwd)) {
- const decision = this.deps.authorize(action);
- if (!decision.ok) {
- this.sendMessage(connId, JSON.stringify({
- id: message.id,
- error: { code: -32001, message: this.deps.workspace.mapTextForAgent(decision.reason ?? 'Not allowed in this workspace.') },
- }));
- return;
- }
+ actions = execServerActions(message.method, message.params, this.deps.cwd);
+ }
+ const id = message?.id;
+ const line = `${data}\n`;
+ if (connection.queue) {
+ this.enqueue(connection, () => this.deliver(connId, connection, id, line, actions));
+ return;
+ }
+ for (const [index, action] of actions.entries()) {
+ const decision = this.deps.authorize(action);
+ if (decision.ok) continue;
+ if (!this.deps.confirm) {
+ this.reject(connId, id, decision);
+ return;
}
+ // 等本机用户确认(凭证类):这一条与之后的消息都按顺序等它。已放行的操作不再检查(批准只能用一次)。
+ const rest = actions.slice(index);
+ this.enqueue(connection, () => this.deliver(connId, connection, id, line, rest));
+ return;
}
- connection.child.stdin.write(`${data}\n`);
+ connection.child.stdin.write(line);
+ }
+
+ private enqueue(connection: Connection, task: () => Promise<void>): void {
+ const next = (connection.queue ?? Promise.resolve()).then(task).catch((error: unknown) => {
+ this.deps.log?.warn('remote agent: exec-server message failed', { error: String(error) });
+ });
+ connection.queue = next;
+ void next.then(() => {
+ if (connection.queue === next) connection.queue = undefined;
+ });
+ }
+
+ private async deliver(connId: string, connection: Connection, id: unknown, line: string, actions: ExecutorAction[]): Promise<void> {
+ for (const action of actions) {
+ let decision = this.deps.authorize(action);
+ if (!decision.ok && this.deps.confirm && await this.deps.confirm(action)) decision = this.deps.authorize(action);
+ if (connection.closed) return;
+ if (!decision.ok) {
+ this.reject(connId, id, decision);
+ return;
+ }
+ }
+ if (!connection.closed) connection.child.stdin.write(line);
+ }
+
+ private reject(connId: string, id: unknown, decision: ExecutorGateDecision): void {
+ this.sendMessage(connId, JSON.stringify({
+ id,
+ error: { code: -32001, message: this.deps.workspace.mapTextForAgent(decision.reason ?? 'Not allowed in this workspace.') },
+ }));
}
private projectOutbound(line: string): string {
diff --git a/apps/desktop/src/main/remote-agent/controller/projectFiles.ts b/apps/desktop/src/main/remote-agent/controller/projectFiles.ts
index d644b94bde..eac2948194 100644
--- a/apps/desktop/src/main/remote-agent/controller/projectFiles.ts
+++ b/apps/desktop/src/main/remote-agent/controller/projectFiles.ts
@@ -9,6 +9,11 @@
* - 项目上级目录里的说明文件:本机任务里 Agent 会沿目录向上加载它们;
* - 你这台的个人配置(用户级说明、Skill、子代理、命令与权限规则):个人配置以你这台为准,
* 那台电脑只提供登录、供应商与网络。
+ *
+ * 符号链接一律跟随,与本机 Agent 加载时一致(CLAUDE.md -> AGENTS.md、链到 dotfiles 的个人 Skill 等)。
+ * 供应商分享的受邀者任务(skipCredentials):内容会经过分享者的电脑,凭证类文件(按链接目标的真实路径
+ * 再判一次)不在启动时带过去;Agent 用到时经工具回到这台读取,由受邀者在确认卡上允许
+ * (docs/product-rules/provider-sharing.md §9 第 7 条)。
*/
import fs from 'node:fs/promises';
import os from 'node:os';
@@ -16,6 +21,7 @@ import path from 'node:path';
import type { RemoteAgentKind } from '@cindy/device-link';
+import { isShareCredentialPath } from '../credentials';
import {
ANCESTOR_INSTRUCTION_FILES,
MAX_ANCESTOR_LEVELS,
@@ -32,21 +38,32 @@ const MAX_FILE_BYTES = 512 * 1024;
const MAX_TOTAL_BYTES = 4 * 1024 * 1024;
const MAX_DEPTH = 6;
+export interface CollectOptions {
+ /** 供应商分享的受邀者任务:凭证类文件不在启动时带过去。 */
+ skipCredentials?: boolean;
+}
+
interface Budget {
files: number;
bytes: number;
+ skipCredentials: boolean;
}
-async function readLimited(file: string, budget: Budget, root: string): Promise<Buffer | null> {
+function newBudget(options: CollectOptions = {}): Budget {
+ return { files: 0, bytes: 0, skipCredentials: options.skipCredentials === true };
+}
+
+/**
+ * 读一个文件(跟随链接)。超出数量与大小上限、不是普通文件,或受邀者任务里的凭证类文件返回 null。
+ * `sanitized`:内容随后只保留权限规则(项目设置),不按凭证类跳过。
+ */
+async function readLimited(file: string, budget: Budget, sanitized = false): Promise<Buffer | null> {
if (budget.files >= MAX_FILES) return null;
try {
- // 不跟随符号链接:项目里的链接可能指向工作目录外(如 ~/.ssh、.env),一旦跟随,
- // 越界字节会被序列化后带到运行 Agent 的那台电脑上。用 lstat 先拒掉链接本身。
- const stat = await fs.lstat(file);
- if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_FILE_BYTES || budget.bytes + stat.size > MAX_TOTAL_BYTES) return null;
- // 规范路径仍须落在真实根目录内(防 `..` 与目录链接借道)。
- const [realFile, realRoot] = await Promise.all([fs.realpath(file), fs.realpath(root)]);
- if (realFile !== realRoot && !realFile.startsWith(`${realRoot}${path.sep}`)) return null;
+ const stat = await fs.stat(file);
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES || budget.bytes + stat.size > MAX_TOTAL_BYTES) return null;
+ if (budget.skipCredentials && !sanitized
+ && (isShareCredentialPath(file) || isShareCredentialPath(await fs.realpath(file)))) return null;
const data = await fs.readFile(file);
budget.files += 1;
budget.bytes += data.length;
@@ -56,6 +73,14 @@ async function readLimited(file: string, budget: Budget, root: string): Promise<
}
}
+/** 目录链接不能把整个磁盘或用户目录带进来:指向文件系统根、用户目录或其上级时不走。 */
+function isTooBroad(realDir: string): boolean {
+ if (path.dirname(realDir) === realDir) return true;
+ const home = path.resolve(os.homedir());
+ const relative = path.relative(realDir, home);
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+}
+
async function walk(
root: string,
relative: string,
@@ -63,26 +88,40 @@ async function walk(
budget: Budget,
out: RemoteAgentWireFile[],
rename: (relative: string) => string = (value) => value,
+ ancestors: ReadonlySet<string> = new Set(),
): Promise<void> {
if (depth > MAX_DEPTH || budget.files >= MAX_FILES) return;
+ const dir = path.join(root, relative);
+ let realDir: string;
let entries: import('node:fs').Dirent[];
try {
- entries = await fs.readdir(path.join(root, relative), { withFileTypes: true });
+ realDir = await fs.realpath(dir);
+ entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
+ // 链接绕回自己的上级目录会无限展开;只看这条路径上的上级,同一个目录被两个链接引用时都照常带上。
+ if (ancestors.has(realDir) || isTooBroad(realDir)) return;
+ const inside = new Set(ancestors).add(realDir);
for (const entry of entries) {
if (entry.name === '.git' || entry.name === 'node_modules') continue;
- // 目录与文件的符号链接都不跟随:目标可能落在项目外,readLimited 的根内校验拦不住
- // “整棵目录是链接”的借道,这里直接跳过。
- if (entry.isSymbolicLink()) continue;
const child = `${relative}/${entry.name}`;
const full = path.join(root, child);
- const isDir = entry.isDirectory();
- const isFile = entry.isFile();
- if (isDir) await walk(root, child, depth + 1, budget, out, rename);
+ let isDir = entry.isDirectory();
+ let isFile = entry.isFile();
+ if (entry.isSymbolicLink()) {
+ // 链接按指向的目标处理(与本机 Agent 加载时一致);目标不存在的跳过。
+ try {
+ const target = await fs.stat(full);
+ isDir = target.isDirectory();
+ isFile = target.isFile();
+ } catch {
+ continue;
+ }
+ }
+ if (isDir) await walk(root, child, depth + 1, budget, out, rename, inside);
else if (isFile && isSafeProjectFilePath(rename(child))) {
- const data = await readLimited(full, budget, root);
+ const data = await readLimited(full, budget);
if (data) out.push({ path: rename(child), data: data.toString('base64') });
}
}
@@ -100,15 +139,19 @@ function sanitizeClaudeSettings(raw: Buffer): Buffer | null {
}
}
-export async function collectProjectInstructionFiles(workingDir: string): Promise<RemoteAgentWireFile[]> {
- const budget: Budget = { files: 0, bytes: 0 };
+export async function collectProjectInstructionFiles(
+ workingDir: string,
+ options: CollectOptions = {},
+): Promise<RemoteAgentWireFile[]> {
+ const budget = newBudget(options);
const out: RemoteAgentWireFile[] = [];
for (const name of TOP_LEVEL_FILES) {
- const data = await readLimited(path.join(workingDir, name), budget, workingDir);
+ const data = await readLimited(path.join(workingDir, name), budget);
if (data) out.push({ path: name, data: data.toString('base64') });
}
for (const name of SETTINGS_FILES) {
- const data = await readLimited(path.join(workingDir, name), budget, workingDir);
+ // 项目设置只带权限规则,受邀者任务也照常同步。
+ const data = await readLimited(path.join(workingDir, name), budget, true);
const sanitized = data ? sanitizeClaudeSettings(data) : null;
if (sanitized) out.push({ path: name, data: sanitized.toString('base64') });
}
@@ -120,8 +163,11 @@ export async function collectProjectInstructionFiles(workingDir: string): Promis
* 项目上级目录里的说明文件(不含文件系统根):本机任务里 Claude Code 与 Pi 会沿目录向上加载。
* Codex 经执行环境在你这台直接读取,不需要同步。
*/
-export async function collectAncestorInstructionFiles(workingDir: string): Promise<RemoteAgentWireAncestorFile[]> {
- const budget: Budget = { files: 0, bytes: 0 };
+export async function collectAncestorInstructionFiles(
+ workingDir: string,
+ options: CollectOptions = {},
+): Promise<RemoteAgentWireAncestorFile[]> {
+ const budget = newBudget(options);
const out: RemoteAgentWireAncestorFile[] = [];
let dir = path.resolve(workingDir);
for (let up = 1; up <= MAX_ANCESTOR_LEVELS; up += 1) {
@@ -129,7 +175,7 @@ export async function collectAncestorInstructionFiles(workingDir: string): Promi
if (parent === dir || path.dirname(parent) === parent) break;
dir = parent;
for (const name of ANCESTOR_INSTRUCTION_FILES) {
- const data = await readLimited(path.join(dir, name), budget, dir);
+ const data = await readLimited(path.join(dir, name), budget);
if (data) out.push({ up, name, data: data.toString('base64') });
}
}
@@ -164,16 +210,16 @@ export interface CollectedPersonalConfig {
export async function collectPersonalConfig(
kind: RemoteAgentKind,
projectFiles: readonly RemoteAgentWireFile[],
- options: { env?: NodeJS.ProcessEnv; home?: string } = {},
+ options: CollectOptions & { env?: NodeJS.ProcessEnv; home?: string } = {},
): Promise<CollectedPersonalConfig> {
const env = options.env ?? process.env;
const home = options.home ?? os.homedir();
- const budget: Budget = { files: 0, bytes: 0 };
+ const budget = newBudget(options);
const personal: RemoteAgentWirePersonal = { files: [] };
const roots: CollectedPersonalConfig['roots'] = [];
if (kind === 'claude-code') {
const configDir = claudeConfigDir(env, home);
- const memory = await readLimited(path.join(configDir, 'CLAUDE.md'), budget, configDir);
+ const memory = await readLimited(path.join(configDir, 'CLAUDE.md'), budget);
if (memory) personal.memory = memory.toString('utf8');
const projectEntries = new Set(projectFiles.map((file) => file.path.split('/').slice(0, 3).join('/')));
for (const dir of PERSONAL_CLAUDE_DIRECTORIES) {
@@ -197,7 +243,7 @@ export async function collectPersonalConfig(
if (stat.isDirectory()) {
await walk(configDir, `${dir}/${entry.name}`, 1, budget, personal.files, (value) => `.claude/${value}`);
} else if (stat.isFile()) {
- const data = await readLimited(local, budget, configDir);
+ const data = await readLimited(local, budget);
if (data) personal.files.push({ path: relative, data: data.toString('base64') });
}
if (personal.files.length > before) roots.push({ relative, local });
@@ -218,7 +264,7 @@ export async function collectPersonalConfig(
const codexHome = codexHomeDir(env, home);
// 与 Codex 的读取顺序一致:AGENTS.override.md 优先于 AGENTS.md。
for (const name of ['AGENTS.override.md', 'AGENTS.md']) {
- const data = await readLimited(path.join(codexHome, name), budget, codexHome);
+ const data = await readLimited(path.join(codexHome, name), budget);
if (data && data.toString('utf8').trim()) {
personal.instructions = data.toString('utf8');
break;
diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
index 254c9e8a00..a4434b957d 100644
--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
@@ -195,12 +195,20 @@ export interface RemoteHandleDeps {
takeGroupNewRound?(): boolean;
}
+/** 本机自己发起的确认的内容(确认卡上显示的工具、参数与说明)。 */
+export type LocalConfirmation = Omit<Extract<InteractionRequest, { kind: 'permission' }>, 'kind' | 'requestId'>;
+
export interface RemoteAgentHandleController {
handle: AgentSessionHandle;
onEvent(event: unknown): void;
onState(state: Record<string, unknown>): void;
onRequest(request: RemoteAgentReverseRequest): Promise<RemoteAgentReply> | null;
onClosed(reason: string, message?: string): void;
+ /**
+ * 本机自己发起的确认(不是 Agent 发来的):走与 Agent 确认同一个确认卡通道,桌面、手机远控与 IM 都能
+ * 处理。只认这一次「允许」,不接受「总是允许」;交互还没接上或任务已结束时按拒绝处理。
+ */
+ confirm(request: LocalConfirmation): Promise<boolean>;
}
export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandleController {
@@ -432,6 +440,11 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
}
return null;
},
+ async confirm(request) {
+ if (!resolver || disposed) return false;
+ const decision = await resolver({ ...request, kind: 'permission', requestId: deps.newId() });
+ return !disposed && decision.kind === 'permission' && decision.behavior === 'allow';
+ },
onClosed(reason, message) {
// 'superseded':同一任务被重新打开、旧实例让位给新实例,不是错误,静默收起。
if (reason !== 'closed' && reason !== 'detached' && reason !== 'ended' && reason !== 'superseded') {
diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.ts
index a06702c53c..6836c33d6c 100644
--- a/apps/desktop/src/main/remote-agent/controller/service.ts
+++ b/apps/desktop/src/main/remote-agent/controller/service.ts
@@ -72,9 +72,16 @@ export interface DeviceAgentServiceDeps {
isSharedProviderDevice?(deviceId: string): boolean;
/** 受邀者任务在本机抓取网页的出站通道(WebFetch)。 */
webFetch?: GuardedFetch;
+ /** 受邀者任务里凭证类操作确认卡上的说明(按界面语言)。 */
+ sharedProviderCredentialNotice?(): string;
logger: Logger;
}
+/** 没有提供界面语言的说明时用的英文说明。 */
+const SHARED_PROVIDER_CREDENTIAL_NOTICE =
+ "This task uses a provider shared with you, so what the agent reads passes through the sharer's computer. "
+ + 'This involves a credential file, so it needs your confirmation.';
+
function mcpTargets(extra: PiExtraSpawnConfig | null): Map<string, LocalMcpTarget> {
const targets = new Map<string, LocalMcpTarget>();
const bridge = extra?.mcpBridge;
@@ -158,8 +165,13 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
const sessionId = opts.sessionId;
const groupSwitch = sessionId && deps.groupSwitch ? deps.groupSwitch : null;
const switchToken = groupSwitch && sessionId ? groupSwitch.takeForOpen(sessionId) : undefined;
- // 受邀者任务:Agent 自带的 WebFetch 在分享者电脑上已关闭,改由本机抓取。同账号任务不提供。
- const webFetch = deps.webFetch && deps.isSharedProviderDevice?.(input.deviceId) ? deps.webFetch : undefined;
+ // 受邀者任务(分享来的供应商):内容会经过分享者的电脑。
+ // - Agent 自带的 WebFetch 在分享者电脑上已关闭,改由本机抓取;
+ // - 凭证类文件不随启动同步,任务中读写凭证类文件、执行读取凭证的命令不论权限档都要本机确认。
+ // 同账号任务都不提供。
+ const shared = deps.isSharedProviderDevice?.(input.deviceId) === true;
+ const webFetch = deps.webFetch && shared ? deps.webFetch : undefined;
+ const collect = { skipCredentials: shared };
return startRemoteAgentSession(input.agentKind, opts, {
invoke: poller.invoke,
poller,
@@ -176,6 +188,9 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
}
: {}),
...(webFetch ? { webFetch } : {}),
+ ...(shared
+ ? { credentialConsent: { description: deps.sharedProviderCredentialNotice?.() ?? SHARED_PROVIDER_CREDENTIAL_NOTICE } }
+ : {}),
prepareMcp: async ({ kind, opts: startOpts, vendorOptions }): Promise<PreparedRemoteMcp> => {
const extra = await deps.prepareMcpBridge(deps.mcpProviders(), deps.logger, {
agentKind: kind,
@@ -204,10 +219,12 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
noteOpaqueWrite: () => deps.noteOpaqueTurnChange({ sessionId, provider, cwd: startOpts.workingDir }),
};
},
- collectProjectFiles: collectProjectInstructionFiles,
+ collectProjectFiles: (workingDir) => collectProjectInstructionFiles(workingDir, collect),
// Codex 经执行环境在本机直接读取项目与上级目录的说明,不必同步。
- collectAncestorFiles: input.agentKind === 'codex' ? undefined : collectAncestorInstructionFiles,
- collectPersonal: (kind, projectFiles) => collectPersonalConfig(kind, projectFiles),
+ collectAncestorFiles: input.agentKind === 'codex'
+ ? undefined
+ : (workingDir) => collectAncestorInstructionFiles(workingDir, collect),
+ collectPersonal: (kind, projectFiles) => collectPersonalConfig(kind, projectFiles, collect),
isGitRepo,
...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),
mapEvent: deps.mapEvent ?? remoteAgentEventMapper,
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index a5ff4bbb7b..ae18a7bb03 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -20,7 +20,7 @@ import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindy
import { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';
import type { PdfTextExtractor } from '../executor/files';
-import { ExecutorGate, executorGateModeFor } from '../executor/gate';
+import { ExecutorGate, executorGateModeFor, type ExecutorAction } from '../executor/gate';
import type { GuardedFetch } from '../executor/webFetch';
import { ExecutorWorkspace } from '../executor/workspace';
import type {
@@ -34,6 +34,7 @@ import {
createRemoteAgentHandle,
localizeRemoteError,
parseStartedInfo,
+ type LocalConfirmation,
type RemoteAgentHandleController,
} from './proxyHandle';
import { ExecServerRelay } from './execServerRelay';
@@ -76,6 +77,12 @@ export interface StartRemoteAgentDeps {
* WebFetch 在对方电脑上已关闭)。缺省时不提供。
*/
webFetch?: GuardedFetch;
+ /**
+ * 供应商分享的受邀者任务(docs/product-rules/provider-sharing.md §9 第 7 条):读写凭证类文件、执行读取
+ * 凭证的命令不论权限档都要本机用户确认,没有批准时在本机弹确认卡;`description` 是卡上的说明。
+ * 同账号任务不提供。
+ */
+ credentialConsent?: { description: string };
/** 改写来自对方的事件(如工具名)。 */
mapEvent?: (kind: RemoteAgentKind) => ((event: AgentEvent) => AgentEvent) | undefined;
/** 本机 Codex 程序(给对方的 Codex 提供 exec-server 执行环境);缺省时不提供。 */
@@ -163,6 +170,23 @@ export function shadowAliases(
return aliases;
}
+/** 凭证类操作的确认卡:用与 Agent 自带工具同名的工具显示本机路径或命令。 */
+export function credentialConfirmation(action: ExecutorAction, description: string): LocalConfirmation {
+ const base = { description, metadata: { hostOwnedConfirmation: 'shared_provider_credential' } };
+ switch (action.kind) {
+ case 'exec':
+ return { ...base, toolName: 'Bash', input: { command: action.command } };
+ case 'write':
+ return { ...base, toolName: 'Write', input: { file_path: action.path } };
+ case 'fetch':
+ return { ...base, toolName: 'WebFetch', input: { url: action.url } };
+ default:
+ return action.scope === 'tree'
+ ? { ...base, toolName: 'Grep', input: { path: action.path } }
+ : { ...base, toolName: 'Read', input: { file_path: action.path } };
+ }
+}
+
function shellName(): string {
if (process.platform === 'win32') return 'bash';
return (process.env.SHELL ?? '/bin/bash').split('/').pop() || 'bash';
@@ -180,7 +204,11 @@ export async function startRemoteAgentSession(
let writableDirs = [...new Set(opts.writableDirs ?? [])];
const workspace = new ExecutorWorkspace({ workingDir: opts.workingDir, extraDirs: [...extraDirs, ...writableDirs] });
const applyDirs = () => workspace.setExtraDirs([...new Set([...extraDirs, ...writableDirs])]);
- const gate = new ExecutorGate(workspace, executorGateModeFor(opts.permissionMode, opts.planMode === true));
+ const credentialConsent = deps.credentialConsent;
+ const gate = new ExecutorGate(workspace, executorGateModeFor(opts.permissionMode, opts.planMode === true), Date.now, {
+ confirmCredentials: credentialConsent !== undefined,
+ });
+ let controller: RemoteAgentHandleController | null = null;
const executor = new RemoteExecutor({
workspace,
gate,
@@ -189,6 +217,12 @@ export async function startRemoteAgentSession(
...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),
// 只有 Claude Code 经 cindy_exec 使用这组工具。
...(kind === 'claude-code' && deps.webFetch ? { webFetch: deps.webFetch } : {}),
+ ...(credentialConsent
+ ? {
+ confirm: async (action: ExecutorAction) =>
+ controller?.confirm(credentialConfirmation(action, credentialConsent.description)) ?? false,
+ }
+ : {}),
});
let permissionMode = opts.permissionMode;
let planMode = opts.planMode === true;
@@ -199,7 +233,6 @@ export async function startRemoteAgentSession(
});
const router = createReverseHttpRouter({ executor, mcpTarget: (name) => mcp.servers.get(name) });
- let controller: RemoteAgentHandleController | null = null;
let personalRoots: Array<{ relative: string; local: string }> = [];
let projectionReady = false;
const early: Array<{ type: 'event' | 'state'; value: unknown }> = [];
@@ -213,6 +246,7 @@ export async function startRemoteAgentSession(
cwd: workspace.workingDir,
workspace,
authorize: (action) => executor.check(action),
+ ...(credentialConsent ? { confirm: (action: ExecutorAction) => executor.confirm(action) } : {}),
push: async (frames) => {
await pushFrames?.(frames);
},
diff --git a/apps/desktop/src/main/remote-agent/credentials.ts b/apps/desktop/src/main/remote-agent/credentials.ts
new file mode 100644
index 0000000000..52320236aa
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/credentials.ts
@@ -0,0 +1,43 @@
+/**
+ * 供应商分享的受邀者任务里「凭证类」的判定(控制端)。
+ *
+ * 受邀者任务的对话与 Agent 读到的文件内容会经过分享者的电脑。凭证类文件(密钥、.env、云与工具的
+ * 登录凭证)不论权限档,都要受邀者在本机确认后才发出:启动时不随项目说明同步,任务中读取时弹确认卡
+ * (docs/product-rules/provider-sharing.md §9 第 7 条)。
+ *
+ * 规则沿用本机任务的凭证规则(isSensitiveCredentialPath),只有一处不同:Claude Code / Codex 配置目录里
+ * 的说明类内容(Skill、子代理、命令、规则、个人说明)不算凭证。本机规则把整个配置目录算作敏感,是为了
+ * 保护里面的登录与设置,不是这些说明文字;不放开的话,个人 Skill 的每个参考文件都要确认。
+ */
+import { isSensitiveCredentialPath, shellCommandReadsCredentials } from '@cindy/maker-core';
+
+/** 配置目录里的说明类子路径:`/.claude/skills/…`、`/.codex/AGENTS.md` 等(两种分隔符都认)。 */
+const CONFIG_INSTRUCTION_SEGMENT =
+ /([\\/])\.(claude|codex)(?=[\\/](?:(?:skills|agents|commands|rules|prompts)(?:[\\/]|$|[^\w.-])|(?:CLAUDE|AGENTS)(?:\.override)?\.md(?![\w.-])))/gi;
+
+/** 路径或命令里的 `..` 段:可能借说明目录绕回配置目录本身(`~/.claude/skills/../settings.json`)。 */
+const PARENT_SEGMENT = /(^|[\\/\s'"=])\.\.(?=[\\/\s'"]|$)/;
+
+/** 本机规则只在特定目录下认的登录文件,放开配置目录后在说明目录里也要认。 */
+const LOGIN_FILE = /(?:^|[\\/])(?:auth|\.credentials)\.json$/i;
+
+/** 把配置目录里说明类子路径的目录名换掉,让本机凭证规则不再因为「在配置目录里」命中。 */
+function withoutConfigInstructionDirs(text: string): string {
+ if (PARENT_SEGMENT.test(text)) return text;
+ return text.replace(CONFIG_INSTRUCTION_SEGMENT, '$1_$2');
+}
+
+/** 路径是否为凭证类文件(调用方对链接目标的真实路径也要各判一次)。 */
+export function isShareCredentialPath(target: string): boolean {
+ if (typeof target !== 'string' || !target) return false;
+ return isSensitiveCredentialPath(withoutConfigInstructionDirs(target)) || LOGIN_FILE.test(target);
+}
+
+/** 命令是否读取或打出凭证(只看命令文本:脚本文件里读的、编码后再解开的认不出来)。 */
+export function isShareCredentialCommand(
+ command: string,
+ workspaceRoots: string[],
+ opts: { cwd?: string; platform?: NodeJS.Platform } = {},
+): boolean {
+ return shellCommandReadsCredentials(withoutConfigInstructionDirs(command), workspaceRoots, opts);
+}
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
index 3d377bbbe6..251757ef6a 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { handleExecMcpRequest } from '../ccMcp';
import { RemoteExecutor } from '../executor';
-import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor } from '../gate';
+import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor, type ExecutorAction } from '../gate';
import type { PdfTextExtractor } from '../files';
import { findWindowsGitBash, truncateOutput } from '../shell';
import type { GuardedFetch } from '../webFetch';
@@ -576,3 +576,100 @@ describe('findWindowsGitBash', () => {
expect(findWindowsGitBash({ ProgramFiles: root })).toBe(path.join(install, 'bin', 'bash.exe'));
});
});
+
+describe('shared provider credentials', () => {
+ function sharedExecutor(
+ mode: ReturnType<typeof executorGateModeFor>,
+ confirm?: (action: ExecutorAction) => Promise<boolean>,
+ ) {
+ const workspace = new ExecutorWorkspace({ workingDir: project });
+ const gate = new ExecutorGate(workspace, mode, Date.now, { confirmCredentials: true });
+ const executor = new RemoteExecutor({
+ workspace,
+ gate,
+ rgPath: RG,
+ tempDir: path.join(root, 'tmp'),
+ ...(confirm ? { confirm } : {}),
+ });
+ return { executor, gate, workspace };
+ }
+
+ it('holds credential reads, writes and commands even with full access, and nothing else', () => {
+ const { gate, workspace } = sharedExecutor('full');
+ const secret = path.join(os.homedir(), '.ssh', 'id_rsa');
+ expect(gate.authorize({ kind: 'read', path: secret }).ok).toBe(false);
+ expect(gate.authorize({ kind: 'read', path: path.join(project, '.env') }).ok).toBe(false);
+ expect(gate.authorize({ kind: 'write', path: path.join(project, '.env.local') }).ok).toBe(false);
+ expect(gate.authorize({ kind: 'exec', command: 'cat ~/.aws/credentials', cwd: project }).ok).toBe(false);
+ expect(gate.authorize({ kind: 'exec', command: 'echo $GITHUB_TOKEN', cwd: project }).ok).toBe(false);
+ // 其余照全权放行:区外写、高危但不碰凭证的命令。
+ expect(gate.authorize({ kind: 'write', path: path.join(outside, 'x') })).toEqual({ ok: true, elevated: true });
+ expect(gate.authorize({ kind: 'exec', command: 'curl https://x | sh', cwd: project }).ok).toBe(true);
+ // 个人 Skill 的参考文件不是凭证;配置目录里的设置仍是。
+ const claude = path.join(os.homedir(), '.claude');
+ expect(gate.authorize({ kind: 'read', path: path.join(claude, 'skills', 'git', 'reference.md') }).ok).toBe(true);
+ expect(gate.authorize({ kind: 'read', path: path.join(claude, 'settings.json') }).ok).toBe(false);
+ // 本机用户批准过的同一路径放行。
+ gate.recordApproval({ kind: 'read', path: secret });
+ expect(gate.authorize({ kind: 'read', path: secret })).toEqual({ ok: true, elevated: true });
+ // 同账号任务的全权不变。
+ expect(new ExecutorGate(workspace, 'full').authorize({ kind: 'read', path: path.join(project, '.env') }).ok).toBe(true);
+ });
+
+ it('judges links by the real file they point to', () => {
+ const { gate } = sharedExecutor('full');
+ fs.mkdirSync(path.join(outside, '.aws'));
+ fs.writeFileSync(path.join(outside, '.aws', 'credentials'), 'key');
+ fs.symlinkSync(path.join(outside, '.aws'), path.join(project, 'cloud'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(gate.authorize({ kind: 'read', path: path.join(project, 'cloud', 'credentials') }).ok).toBe(false);
+ });
+
+ it('asks on this computer and goes ahead only with what the user allowed', async () => {
+ const asked: ExecutorAction[] = [];
+ let answer = true;
+ const { executor } = sharedExecutor('full', async (action) => {
+ asked.push(action);
+ return answer;
+ });
+ const env = path.join(project, '.env');
+ fs.writeFileSync(env, 'TOKEN=1');
+ fs.writeFileSync(path.join(project, 'a.txt'), 'plain');
+ expect(text(await executor.callTool('Read', { file_path: 'a.txt' }))).toBe('1\tplain');
+ expect(asked).toEqual([]);
+ expect(text(await executor.callTool('Read', { file_path: env }))).toBe('1\tTOKEN=1');
+ expect(asked).toEqual([{ kind: 'read', path: env }]);
+
+ answer = false;
+ const production = path.join(project, '.env.production');
+ fs.writeFileSync(production, 'TOKEN=2');
+ const denied = await executor.callTool('Read', { file_path: production });
+ expect(denied.isError).toBe(true);
+ expect(text(denied)).toContain('needs the user\'s confirmation');
+ await expect(executor.handle('fs.read', { path: production })).rejects.toMatchObject({ code: 'EACCES' });
+ expect(asked).toHaveLength(3);
+ });
+
+ it('does not ask about operations that are not credentials', async () => {
+ const asked: ExecutorAction[] = [];
+ const { executor } = sharedExecutor('normal', async (action) => {
+ asked.push(action);
+ return true;
+ });
+ // 区外写在普通档要本机批准,但不是凭证类:不在这里补问,照旧拒绝。
+ const result = await executor.callTool('Write', { file_path: path.join(outside, 'x.txt'), content: 'x' });
+ expect(result.isError).toBe(true);
+ expect(asked).toEqual([]);
+ });
+
+ it('leaves credential files out of Pi searches unless the searched path itself was allowed', async () => {
+ const { executor } = sharedExecutor('full', async () => true);
+ fs.writeFileSync(path.join(project, '.env'), 'API_KEY=secret\n');
+ fs.writeFileSync(path.join(project, 'config.ts'), 'const key = process.env.API_KEY;\n');
+ const grep = (await executor.handle('pi.grep', { params: { pattern: 'API_KEY' } })) as { text: string };
+ expect(grep.text).toContain('config.ts:1:');
+ expect(grep.text).not.toContain('secret');
+ expect(grep.text).toContain('1 credential file(s) left out');
+ const direct = (await executor.handle('pi.grep', { params: { pattern: 'API_KEY', path: '.env' } })) as { text: string };
+ expect(direct.text).toContain('secret');
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index 4eb81fda4c..32c9a85127 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -7,6 +7,7 @@
* NotebookEdit(Claude Code 的自带文件与命令工具关掉后由它顶替);供应商分享的受邀者任务另有
* WebFetch(自带的 WebFetch 对受邀者关闭,改在本机抓取)。
* 写文件前通知「每轮改动对比」抓取改前内容;命令执行后登记一次无法预知范围的改动。
+ * 供应商分享的受邀者任务里,凭证类操作没有本机批准时由这里直接在本机弹确认卡(confirm)。
*/
import path from 'node:path';
@@ -56,6 +57,11 @@ export interface RemoteExecutorOptions {
extractPdfText?: PdfTextExtractor;
/** 提供 WebFetch(在本机抓取网页)所用的出站通道;缺省时不提供这个工具。 */
webFetch?: GuardedFetch;
+ /**
+ * 在本机弹确认卡问本机用户(供应商分享的受邀者任务):凭证类操作没有本机批准时用它补问,允许后
+ * 只放行这一个操作。缺省时这类操作直接拒绝。
+ */
+ confirm?(action: ExecutorAction): Promise<boolean>;
}
export class ExecutorRequestError extends Error {
@@ -140,6 +146,26 @@ export class RemoteExecutor {
return this.gate.authorize(action);
}
+ /**
+ * 凭证类操作在本机补问一次(供应商分享的受邀者任务);本机用户允许后登记批准,调用方再检查一次即可
+ * 放行。不是凭证类、没有确认通道或任务已结束时返回 false。
+ */
+ async confirm(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> {
+ if (this.closed || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;
+ const allowed = await this.opts.confirm(action).catch(() => false);
+ // 等确认期间任务结束或请求被取消:不再执行。
+ if (!allowed || this.closed || signal?.aborted) return false;
+ this.gate.recordApproval(action);
+ return true;
+ }
+
+ /** 检查上限;凭证类操作没有批准时先在本机问一次。 */
+ private async decide(action: ExecutorAction, signal?: AbortSignal): Promise<ExecutorGateDecision> {
+ const decision = this.gate.authorize(action);
+ if (decision.ok || !(await this.confirm(action, signal))) return decision;
+ return this.gate.authorize(action);
+ }
+
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
@@ -164,8 +190,8 @@ export class RemoteExecutor {
}
}
- private authorize(action: ExecutorAction): void {
- const decision = this.gate.authorize(action);
+ private async authorize(action: ExecutorAction, signal?: AbortSignal): Promise<void> {
+ const decision = await this.decide(action, signal);
if (!decision.ok) throw new ExecutorRequestError('EACCES', decision.reason ?? 'Not allowed.');
}
@@ -178,19 +204,19 @@ export class RemoteExecutor {
switch (op) {
case 'fs.read': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'read', path: target });
+ await this.authorize({ kind: 'read', path: target }, signal);
return { data: this.workspace.mapOutputForAgent(await rawReadFile(target)).toString('base64') };
}
case 'fs.access': {
const target = this.resolvePath(str(body, 'path'));
const mode = body.mode === 'write' ? 'write' : 'read';
- this.authorize({ kind: mode, path: target });
+ await this.authorize({ kind: mode, path: target }, signal);
await rawAccess(target, mode);
return {};
}
case 'fs.write': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'write', path: target });
+ await this.authorize({ kind: 'write', path: target }, signal);
if (typeof body.data !== 'string') throw new ExecutorRequestError('INVALID', 'data must be a base64 string');
const data = this.workspace.mapInputFromAgent(Buffer.from(body.data, 'base64'));
await this.writeHooks.beforeWrite(target);
@@ -199,44 +225,49 @@ export class RemoteExecutor {
}
case 'fs.mkdir': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'write', path: target });
+ await this.authorize({ kind: 'write', path: target }, signal);
await rawMkdir(target);
return {};
}
case 'fs.stat': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'read', path: target });
+ await this.authorize({ kind: 'read', path: target }, signal);
return await rawStat(target);
}
case 'fs.readdir': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'read', path: target, scope: 'tree' });
+ await this.authorize({ kind: 'read', path: target, scope: 'tree' }, signal);
return { entries: await rawReaddir(target) };
}
case 'fs.glob': {
const cwd = this.resolvePath(str(body, 'cwd'));
- this.authorize({ kind: 'read', path: cwd, scope: 'tree' });
+ await this.authorize({ kind: 'read', path: cwd, scope: 'tree' }, signal);
const limit = Math.max(1, Math.floor(optionalNumber(body, 'limit') ?? 1000));
return { paths: (await rawGlob(this.rg, str(body, 'pattern'), cwd, limit, signal)).map((item) => this.workspace.toAgentPath(item)) };
}
case 'fs.mime': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'read', path: target });
+ await this.authorize({ kind: 'read', path: target }, signal);
return { mime: await detectImageMime(target) };
}
case 'pi.grep': {
const params = record(body.params) as unknown as PiGrepInput;
if (typeof params.pattern !== 'string' || !params.pattern) throw new ExecutorRequestError('INVALID', 'pattern is required');
const root = this.resolvePath(typeof params.path === 'string' && params.path ? params.path : '.');
- this.authorize({ kind: 'read', path: root, scope: 'tree' });
- const result = await piGrep(this.opts.rgPath, root, params, signal);
+ await this.authorize({ kind: 'read', path: root, scope: 'tree' }, signal);
+ // 供应商分享的受邀者任务:凭证类文件的内容不进搜索结果(要看须单独读取并经本机确认)。
+ // 本机用户刚批准过搜索的就是凭证目录或文件时不再过滤。
+ const skipFile = this.opts.confirm && !this.gate.needsCredentialConsent({ kind: 'read', path: root })
+ ? (file: string) => this.gate.needsCredentialConsent({ kind: 'read', path: file })
+ : undefined;
+ const result = await piGrep(this.opts.rgPath, root, params, signal, skipFile);
return { ...result, text: this.workspace.mapTextForAgent(result.text) };
}
case 'exec.run': {
this.workspace.virtualizeDirs([this.shell.getTempDir()]);
const command = this.workspace.mapCommand(str(body, 'command'), resolveExecutorShell().dialect);
const cwd = this.resolvePath(optionalString(body, 'cwd') ?? this.workspace.workingDir);
- this.authorize({ kind: 'exec', command, cwd });
+ await this.authorize({ kind: 'exec', command, cwd }, signal);
const timeoutSeconds = optionalNumber(body, 'timeout');
const timeoutMs = timeoutSeconds && timeoutSeconds > 0
? Math.min(timeoutSeconds, PI_BASH_MAX_TIMEOUT_SECONDS) * 1000
@@ -291,7 +322,7 @@ export class RemoteExecutor {
}
case 'Read': {
const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());
- this.authorizeTool({ kind: 'read', path: target });
+ await this.authorizeTool({ kind: 'read', path: target }, signal);
return this.mapToolResult(await ccRead(target, {
file_path: target,
offset: optionalNumber(args, 'offset'),
@@ -303,7 +334,7 @@ export class RemoteExecutor {
const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());
const content = args.content;
if (typeof content !== 'string') return textResult('content must be a string.', true);
- this.authorizeTool({ kind: 'write', path: target });
+ await this.authorizeTool({ kind: 'write', path: target }, signal);
return this.mapToolResult(await ccWrite(target, this.workspace.mapTextFromAgent(content), this.readState, this.writeHooks, this.workspace.toAgentPath(target)));
}
case 'Edit': {
@@ -311,7 +342,7 @@ export class RemoteExecutor {
if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') {
return textResult('old_string and new_string must be strings.', true);
}
- this.authorizeTool({ kind: 'write', path: target });
+ await this.authorizeTool({ kind: 'write', path: target }, signal);
return this.mapToolResult(await ccEdit(target, {
old_string: this.workspace.mapTextFromAgent(args.old_string),
new_string: this.workspace.mapTextFromAgent(args.new_string),
@@ -324,7 +355,7 @@ export class RemoteExecutor {
const cellType = args.cell_type === 'markdown' || args.cell_type === 'code' ? args.cell_type : undefined;
const editMode = args.edit_mode === 'insert' || args.edit_mode === 'delete' || args.edit_mode === 'replace'
? args.edit_mode : undefined;
- this.authorizeTool({ kind: 'write', path: target });
+ await this.authorizeTool({ kind: 'write', path: target }, signal);
return this.mapToolResult(await ccNotebookEdit(target, {
cell_id: optionalString(args, 'cell_id'),
new_source: this.workspace.mapTextFromAgent(args.new_source),
@@ -347,8 +378,8 @@ export class RemoteExecutor {
}
}
- private authorizeTool(action: ExecutorAction): void {
- const decision = this.gate.authorize(action);
+ private async authorizeTool(action: ExecutorAction, signal?: AbortSignal): Promise<void> {
+ const decision = await this.decide(action, signal);
if (!decision.ok) throw new ExecutorDenied(decision.reason ?? 'Not allowed.');
}
@@ -382,7 +413,7 @@ export class RemoteExecutor {
const rawCommand = args.command;
if (typeof rawCommand !== 'string' || !rawCommand.trim()) return textResult('command is required.', true);
const command = this.workspace.mapCommand(rawCommand, resolveExecutorShell().dialect);
- this.authorizeTool({ kind: 'exec', command, cwd: this.shell.getCwd() });
+ await this.authorizeTool({ kind: 'exec', command, cwd: this.shell.getCwd() }, signal);
const timeout = optionalNumber(args, 'timeout');
try {
const result = args.run_in_background === true
diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.ts
index 9c337f0ab7..df8f74d200 100644
--- a/apps/desktop/src/main/remote-agent/executor/gate.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts
@@ -12,7 +12,9 @@
* 电脑不可信时也不能绕过本机用户的目录授权;
* - 抓取网页:本机地址、内网与云 metadata 这类地址(与本机任务里 WebFetch / curl 同一判定)
* 只认本机用户刚批准过的同一地址;批准过的地址抓取时放开内网(域名也可能解析到内网);
- * - 计划模式:只允许读取、抓取网页和静态可证只读的命令,其余同样要本机用户批准过。
+ * - 计划模式:只允许读取、抓取网页和静态可证只读的命令,其余同样要本机用户批准过;
+ * - 供应商分享的受邀者任务:内容会经过分享者的电脑,凭证类的读写与读取凭证的命令即使在全权下
+ * 也只认本机用户批准过的同一操作(credentials.ts)。
* 批准记录只在短时间内有效;命令与抓取的批准用一次即失效,路径批准在有效期内覆盖同一路径的读写
* (编辑会先读后写)。
*/
@@ -20,7 +22,8 @@ import path from 'node:path';
import { classifyShellCommand, reviewAction } from '@cindy/maker-core';
-import type { ExecutorWorkspace } from './workspace';
+import { isShareCredentialCommand, isShareCredentialPath } from '../credentials';
+import { realPathOrAncestor, type ExecutorWorkspace } from './workspace';
/**
* 与本机任务权限对应的上限档位:`full` = 全权;`plan` = 计划模式;其余权限档统一为 `normal`
@@ -87,6 +90,11 @@ function approvalOf(action: ExecutorAction): { kind: Approval['kind']; key: stri
}
}
+export interface ExecutorGateOptions {
+ /** 供应商分享的受邀者任务:凭证类操作不论权限档都要本机用户确认。 */
+ confirmCredentials?: boolean;
+}
+
export class ExecutorGate {
private mode: ExecutorGateMode;
private approvals: Approval[] = [];
@@ -95,6 +103,7 @@ export class ExecutorGate {
private readonly workspace: ExecutorWorkspace,
mode: ExecutorGateMode = 'normal',
private readonly now: () => number = Date.now,
+ private readonly options: ExecutorGateOptions = {},
) {
this.mode = mode;
}
@@ -114,21 +123,36 @@ export class ExecutorGate {
if (this.approvals.length > MAX_APPROVALS) this.approvals.splice(0, this.approvals.length - MAX_APPROVALS);
}
+ /**
+ * 这个操作是否要按「凭证类」由本机用户确认(只在供应商分享的受邀者任务里):读写凭证类路径(链接按
+ * 真实目标再判一次)、目录级读取的根本身是凭证目录,或命令读取 / 打出凭证。
+ */
+ needsCredentialConsent(action: ExecutorAction): boolean {
+ if (!this.options.confirmCredentials) return false;
+ if (action.kind === 'fetch') return false;
+ if (action.kind === 'exec') {
+ return isShareCredentialCommand(action.command, this.workspace.allRoots(), { cwd: action.cwd, platform: process.platform });
+ }
+ return isShareCredentialPath(path.resolve(action.path)) || isShareCredentialPath(realPathOrAncestor(action.path));
+ }
+
authorize(action: ExecutorAction): ExecutorGateDecision {
- if (this.mode === 'full') return { ok: true, elevated: true };
+ const credential = this.needsCredentialConsent(action);
+ if (this.mode === 'full' && !credential) return { ok: true, elevated: true };
// 抓取网页:本机用户批准过这个地址就放开内网。公网样式的域名也可能解析到内网(公司内网域名),
// 只看地址文本判定为不必问,但抓取时会按 DNS 结果被拦下。
if (action.kind === 'fetch' && this.consume(action)) return { ok: true, elevated: true };
- if (!this.requiresApproval(action)) return { ok: true };
+ if (!credential && !this.requiresApproval(action)) return { ok: true };
if (this.consume(action)) return { ok: true, elevated: true };
- return {
- ok: false,
- reason: action.kind === 'exec'
- ? 'This command needs the user\'s confirmation on the computer where the task runs, and it was not confirmed.'
- : action.kind === 'fetch'
- ? `Fetching ${action.url} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`
- : `Access to ${action.path} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`,
- };
+ return { ok: false, reason: this.deniedReason(action) };
+ }
+
+ private deniedReason(action: ExecutorAction): string {
+ return action.kind === 'exec'
+ ? 'This command needs the user\'s confirmation on the computer where the task runs, and it was not confirmed.'
+ : action.kind === 'fetch'
+ ? `Fetching ${action.url} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`
+ : `Access to ${action.path} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`;
}
private requiresApproval(action: ExecutorAction): boolean {
diff --git a/apps/desktop/src/main/remote-agent/executor/search.ts b/apps/desktop/src/main/remote-agent/executor/search.ts
index 77711cd31f..68e03f3171 100644
--- a/apps/desktop/src/main/remote-agent/executor/search.ts
+++ b/apps/desktop/src/main/remote-agent/executor/search.ts
@@ -50,11 +50,16 @@ interface RgEvent {
};
}
+/**
+ * `skipFile`:不输出其中内容的文件(供应商分享的受邀者任务里的凭证类文件:搜索结果会经过分享者的
+ * 电脑,要看内容须单独读取并经本机确认)。
+ */
export async function piGrep(
rgPath: string,
root: string,
input: PiGrepInput,
signal?: AbortSignal,
+ skipFile?: (absolutePath: string) => boolean,
): Promise<PiGrepResult> {
const stat = await fsp.stat(root);
const rootIsDirectory = stat.isDirectory();
@@ -75,6 +80,7 @@ export async function piGrep(
let stderr = '';
let lastPath: string | undefined;
let lastLine = -1;
+ const skipped = new Map<string, boolean>();
await new Promise<void>((resolve, reject) => {
const child = spawn(rgPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], signal });
@@ -92,6 +98,14 @@ export async function piGrep(
const file = event.data?.path?.text;
const lineNumber = event.data?.line_number;
if (!file || typeof lineNumber !== 'number') return;
+ if (skipFile) {
+ let skip = skipped.get(file);
+ if (skip === undefined) {
+ skip = skipFile(path.resolve(cwd, file));
+ skipped.set(file, skip);
+ }
+ if (skip) return;
+ }
// rg 的路径在 Windows 上是 `.` 开头的反斜杠形式(`.\src\a.ts`),统一剥掉前缀并转正斜杠。
const display = rootIsDirectory ? file.replace(/^\.[\\/]/, '').split(/[\\/]/).join('/') : path.basename(root);
if (lastPath !== undefined && (display !== lastPath || lineNumber > lastLine + 1) && context > 0) {
@@ -130,7 +144,11 @@ export async function piGrep(
});
});
- if (matches === 0) return { text: 'No matches found' };
+ const skippedFiles = [...skipped.values()].filter(Boolean).length;
+ const skippedNotice = skippedFiles > 0
+ ? `matches in ${skippedFiles} credential file(s) left out; reading such a file directly asks the user for confirmation`
+ : null;
+ if (matches === 0) return { text: skippedNotice ? `No matches found\n\n[${skippedNotice}]` : 'No matches found' };
// 上下文模式下最后一条可能是命中后的上下文,按出现顺序保留。
let output = outputLines.join('\n');
let truncated = false;
@@ -160,6 +178,7 @@ export async function piGrep(
notices.push(`${formatSize(MAX_OUTPUT_BYTES)} limit reached`);
details.truncated = true;
}
+ if (skippedNotice) notices.push(skippedNotice);
if (notices.length > 0) output += `\n\n[${notices.join('. ')}]`;
return { text: output, ...(Object.keys(details).length > 0 ? { details } : {}) };
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 98408587dc..fc12faa42f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9774,6 +9774,9 @@
"cancelEdit": "Cancel Editing",
"saveEdit": "Save Text"
},
+ "sharedProviderCredential": {
+ "description": "This task uses a provider shared with you, so what the Agent reads passes through the sharer's computer. This step involves a credential file (such as a key or .env), so it continues only after you confirm."
+ },
"mediaDownload": {
"title": "Download the generated media?",
"description": "The media has been generated and needs to be downloaded from the address below.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index bb8a01a662..5a6f46a6b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9752,6 +9752,9 @@
"cancelEdit": "編集をキャンセル",
"saveEdit": "テキストを保存"
},
+ "sharedProviderCredential": {
+ "description": "このタスクは共有されたプロバイダーを使っているため、Agent が読み取った内容は共有元のパソコンを経由します。この操作は認証情報のファイル(鍵や .env など)に関わるため、確認してから続行します。"
+ },
"mediaDownload": {
"title": "生成されたメディアをダウンロードしますか?",
"description": "メディアが生成されました。以下のアドレスからダウンロードする必要があります。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8b1aefa316..d3fd4a6592 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9752,6 +9752,9 @@
"cancelEdit": "편집 취소",
"saveEdit": "텍스트 저장"
},
+ "sharedProviderCredential": {
+ "description": "이 작업은 공유받은 제공자를 사용하므로 Agent가 읽은 내용이 공유한 사람의 컴퓨터를 거칩니다. 이 단계는 자격 증명 파일(키, .env 등)과 관련되어 있어 확인한 후에 계속됩니다."
+ },
"mediaDownload": {
"title": "생성된 미디어를 다운로드할까요?",
"description": "미디어가 생성되었습니다. 아래 주소에서 다운로드해야 합니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index f524d4bd17..f5dc2e2873 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9752,6 +9752,9 @@
"cancelEdit": "取消编辑",
"saveEdit": "保存文本"
},
+ "sharedProviderCredential": {
+ "description": "这个任务用的是分享来的供应商,Agent 读到的内容会经过分享者的电脑。这一步涉及凭证类文件(如密钥、.env),需要你确认后才继续。"
+ },
"mediaDownload": {
"title": "允许下载生成的媒体?",
"description": "媒体已生成,需要从下方地址下载。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 18079603c2..be24a9ac6e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9752,6 +9752,9 @@
"cancelEdit": "取消編輯",
"saveEdit": "儲存文字"
},
+ "sharedProviderCredential": {
+ "description": "這個任務用的是分享來的供應商,Agent 讀到的內容會經過分享者的電腦。這一步涉及憑證類檔案(如金鑰、.env),需要你確認後才繼續。"
+ },
"mediaDownload": {
"title": "允許下載產生的媒體?",
"description": "媒體已產生,需要從下方位址下載。",
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index dd9abbf1f8..3619ede52b 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -587,7 +587,9 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
`personal`(A 的个人配置:Claude Code 的 `~/.claude/CLAUDE.md`、`skills/agents/commands`、`settings.json`
里的权限规则;Codex 的 `AGENTS(.override).md`;不含 hooks / env)。两者缺省按空处理。B 把影子目录按
A 的真实路径逐级镜像在 `<runs>/workspaces/<控制端>/<任务>/fs/` 下,`open` 回包的 `mirrorRoot` 告诉 A
- 镜像根,A 据此把影子路径逐级映射回真实路径;项目里已有的同名文件以项目为准。
+ 镜像根,A 据此把影子路径逐级映射回真实路径;项目里已有的同名文件以项目为准。A 收集这些文件时跟随
+ 符号链接(与本机 Agent 加载一致,只防链接绕回上级目录与指向整个用户目录);供应商分享的受邀者任务不把
+ 凭证类文件放进载荷(`provider-sharing.md` §9 第 7 条)。载荷格式不变。
- **本机虚拟工作区**:A 在 open 前先调用 caps,只有 B 回包声明
virtualWorkspace: true 才发送 open;旧 B 或未声明能力的 B 直接提示升级,不能静默降级到
暴露 A 真实路径的合同。支持时,B 使用不含 A 真实目录名的固定短父级层级,继续承载最多 24
diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.md
index 33f5871322..feee1a7447 100644
--- a/docs/product-rules/provider-sharing.md
+++ b/docs/product-rules/provider-sharing.md
@@ -262,6 +262,15 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):
会话记录与镜像文件,并请接过它任务的组内电脑清理([供应商组](provider-groups.md) §4)。
7. **受邀者自己的权限**:受邀者电脑上的文件与命令操作仍由受邀者自己的任务权限档把关,分享不放宽
受邀者本机的任何限制。
+ **凭证类再收紧一档**(2026-10-10 裁决):对话与 Agent 读到的内容会经过分享者的电脑,因此
+ - 凭证类文件(密钥、`.env`、云与工具的登录凭证,规则同本机任务;Claude Code / Codex 配置目录里的
+ Skill、子代理、命令与说明文字不算)不随项目说明与个人配置在启动时同步,链接按真实目标判断;
+ - 任务中读写凭证类文件、执行读取或打出凭证的命令,不论权限档(含完全访问)都要受邀者在本机确认卡上
+ 允许,只放行这一次,与本机任务读凭证「每次都问」一致;Pi 的搜索结果不含凭证类文件的内容。确认卡与
+ Agent 的确认走同一通道,手机远控与 IM 也能处理;
+ - 命令只能按命令文本识别(脚本里读的、编码后再解开的认不出来),是防误发,不是防恶意。
+ 同账号远程供应商不受影响:与本机一致,项目与个人配置里的符号链接一律跟随,不额外确认。
+ 实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,controller/projectFiles.ts}`。
## 10. 与现有规则的关系
@@ -288,7 +297,9 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):
分享者电脑上执行;Agent 自带工具里作用于分享者电脑、其他会话或分享者账号的都不可用(§9 第 5 条)。
9. 中国大陆版与 Global 账号之间能完成同样的申请、审批、使用与撤销;合规开关关闭时跨区链接给出
明确提示,同区域分享不受影响。
-10. Light 与 Dark 两种模式都已实现。
+10. 受邀者任务启动时不带凭证类文件;任务中读写凭证类文件或执行读取凭证的命令,即使在完全访问下也
+ 要受邀者在本机确认后才执行(§9 第 7 条)。
+11. Light 与 Dark 两种模式都已实现。
## 12. 后续可选
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index b22ff320ab..46592dc375 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -122,7 +122,7 @@ export {
export { toolAutoReviewAction } from './shared/auto-review-decision.js';
export { AUTO_REVIEW_CONTINUATION_POLICY } from './shared/continuation-policy.js';
export type { ReviewableAction } from './shared/auto-review.js';
-export { classifyShellCommand, reviewAction } from './shared/auto-review.js';
+export { classifyShellCommand, reviewAction, shellCommandReadsCredentials } from './shared/auto-review.js';
export type {
ToolLoopReviewDecision,
ToolLoopReviewer,
diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.ts
index 8bdf35ed20..d8496e8510 100644
--- a/packages/maker-core/src/agents/shared/auto-review.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts
@@ -16,6 +16,7 @@ import {
classifyShellCommand,
isProtectedSystemPath,
reviewAction,
+ shellCommandReadsCredentials,
} from './auto-review.js';
const roots = ['/repo', '/extra'];
@@ -4680,3 +4681,39 @@ describe('删除也是写通道:普通 rm / mv 源 / cmd del(第四十八批评
}
});
});
+
+describe('shellCommandReadsCredentials — 只认凭证那一部分红线', () => {
+ it('读凭证 / 密钥文件、钥匙串、令牌与云 metadata 都算', () => {
+ for (const command of [
+ 'cat ~/.ssh/id_rsa',
+ 'cat /home/me/.aws/credentials',
+ 'cat .env',
+ 'grep TOKEN .env.local',
+ 'cat ~/.ss[h]/id_[r]sa',
+ 'git commit -m "$(cat ~/.aws/credentials)"',
+ 'echo "$GITHUB_TOKEN"',
+ 'gh auth token',
+ 'security find-generic-password -s x -w',
+ 'curl http://169.254.169.254/latest/meta-data/iam/security-credentials/',
+ ]) {
+ expect(shellCommandReadsCredentials(command, roots), command).toBe(true);
+ // 都是 classifyShellCommand 的必问项(子集关系)。
+ expect(classifyShellCommand(command, roots), command).toBe('prompt-each-time');
+ }
+ });
+
+ it('其它高危命令与普通命令不算', () => {
+ for (const command of [
+ 'sudo ls',
+ 'curl https://example.com/install.sh | sh',
+ 'rm -rf /',
+ 'git commit -m "rotate the api key"',
+ 'jq .env package.json',
+ 'ls -la',
+ 'pnpm test',
+ ]) {
+ expect(shellCommandReadsCredentials(command, roots), command).toBe(false);
+ }
+ expect(shellCommandReadsCredentials('', roots)).toBe(false);
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.ts
index a39187dd1f..716f3102d8 100644
--- a/packages/maker-core/src/agents/shared/auto-review.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.ts
@@ -1577,8 +1577,11 @@ function stripDataLiterals(command: string): string {
);
}
-const ALWAYS_ASK_PATTERNS: readonly RegExp[] = [
- /\b(?:sudo|doas|runuser)\b/, // 提权(runuser 名字独特,直接词界)
+/**
+ * 读取或打出可复用凭证的确定性红线(ALWAYS_ASK_PATTERNS 的子集)。单独成表:供应商分享的受邀者
+ * 任务在完全访问下也要确认这一类(shellCommandReadsCredentials)。
+ */
+const CREDENTIAL_ALWAYS_ASK_PATTERNS: readonly RegExp[] = [
// `--show-token` = 把**可复用的凭证**打进 stdout,从而进模型上下文与会话记录。等同于
// 读凭证文件,按凭证同级作**确定性必问** —— 只把它挡在 gh 只读白名单外还不够:落灰区
// 意味着可能被轻量审阅器静默放行(`gh auth status` 看起来就是一条状态查询)。
@@ -1600,11 +1603,19 @@ const ALWAYS_ASK_PATTERNS: readonly RegExp[] = [
// 而原来的 `(?![\w=-])` 把等号形态排除在外,令牌仍会被打进模型上下文(review 报)。
// 命令位判据用 `(?:^|[\s|&;(])` 而不是 `(?:^|\s)`:分隔符后可以不带空格
// (`ls;gh auth token`、`ls&&gh auth token`、`(gh auth token)`),而分段之后不会再重扫
- // 确定性红线 —— 只认空白等于给一个删空格就绕过的口子(review 报)。与本表里 `su`
+ // 确定性红线 —— 只认空白等于给一个删空格就绕过的口子(review 报)。与 ALWAYS_ASK_PATTERNS 里 `su`
// 那条的边界写法一致。
/(?:^|[\s|&;(])(?:\S*\/)?gh\s+auth\s+[a-z][\w-]*[^|;&\n]*?\s-[a-zA-Z]*t[a-zA-Z]*(?:=[^\s|;&]*)?(?![\w-])/,
// `gh auth token` 直接把令牌打到 stdout,与 `--show-token` 同级(同族一次收完)。
/(?:^|[\s|&;(])(?:\S*\/)?gh\s+auth\s+token\b/,
+ ...SENSITIVE_CREDENTIAL_PATH_PATTERNS, // 凭证/密钥路径(见上)
+ /\bsecurity\s+(?:find|dump|export|add)-/, // macOS keychain
+ /\$\{?[A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|APIKEY|_PAT)[A-Za-z0-9_]*\}?/i, // 敏感环境变量展开(echo "$API_KEY" 等)
+];
+
+const ALWAYS_ASK_PATTERNS: readonly RegExp[] = [
+ /\b(?:sudo|doas|runuser)\b/, // 提权(runuser 名字独特,直接词界)
+ ...CREDENTIAL_ALWAYS_ASK_PATTERNS, // 凭证文件、钥匙串、令牌(见上)
// 裸 `su`(切换到其它用户/root)同属提权,但 "su" 常出现在无关文本里 → 只在命令位(段首/分隔符后,或
// 已知启动器后)匹配,避免 `git commit -m "su"` 之类误升(自审补:sudo/doas 已红线,漏了同级的 su)。
/(?:^|[\n|&;(]\s*|\b(?:sudo|doas|xargs|nohup|setsid|env|command|exec|time|timeout|nice|ionice|stdbuf|chrt|builtin|watch|flock)\s+(?:-\S+\s+)*)su\b(?![\w.-])/,
@@ -1626,9 +1637,6 @@ const ALWAYS_ASK_PATTERNS: readonly RegExp[] = [
/:\s*\(\s*\)\s*\{.*\|.*&.*\}/, // fork bomb :(){ :|:& };:
/\bchmod\b[^|;&]*\s(?:-R\s+)?[0-7]*7{2,3}\b/, // chmod 777 之类数字放宽权限
/\bchmod\b[^|;&]*\s[ugoa]*[oa][ugoa]*[-+=][^\s]*w/, // chmod 符号型对 other/all 开放写(a+w / o+w / a+rwx)
- ...SENSITIVE_CREDENTIAL_PATH_PATTERNS, // 凭证/密钥路径(见上)
- /\bsecurity\s+(?:find|dump|export|add)-/, // macOS keychain
- /\$\{?[A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|APIKEY|_PAT)[A-Za-z0-9_]*\}?/i, // 敏感环境变量展开(echo "$API_KEY" 等)
];
/**
@@ -6019,6 +6027,69 @@ function shellCommandReadsDotenv(
return false;
}
+/**
+ * 确定性红线的扫描面:结构上确定是数据的引号字面量先换成占位符(stripDataLiterals),再生成防拆词
+ * 绕过的各个变体(各变体的用途见 classifyShellCommand 里的说明)。
+ */
+function deterministicScanVariants(command: string): {
+ deEscaped: string;
+ quotesOnly: string;
+ deGlobbed: string;
+ deExpanded: string;
+ deExpandedGlob: string;
+ deSubstituted: string;
+} {
+ const scannable = stripDataLiterals(command);
+ const deEscaped = scannable.replace(/['"\\]/g, '');
+ const quotesOnly = scannable.replace(/['"]/g, '');
+ const deGlobbed = deEscaped.replace(/[[\]{}*?]/g, '');
+ // deExpanded:抹掉参数展开(见 stripExpansions)—— 防 `s${X}udo`/`rm -r${X}f /` 这类把关键词拆开、
+ // bash 展开成空后才成形的绕过。**必须从 deEscaped 派生**(保留 `${...}` 完整):若先去 glob 会把
+ // `${X}` 的 `{}` 抹成 `$X`,再 stripExpansions 会把 `$Xudo` 整词吞掉、反而复原不出 `sudo`。
+ // deExpandedGlob:再叠加去 glob,覆盖 `${X}` 与 `[h]` 混用的组合变形。
+ const deExpanded = stripExpansions(deEscaped);
+ const deExpandedGlob = deExpanded.replace(/[[\]{}*?]/g, '');
+ // deSubstituted:把 `${X:-sudo}` 等默认值代入,让藏在展开默认值里的危险关键词现形(codex 报)。
+ const deSubstituted = substituteDefaults(deEscaped);
+ return { deEscaped, quotesOnly, deGlobbed, deExpanded, deExpandedGlob, deSubstituted };
+}
+
+/** curl / wget 抓云 metadata(读实例临时云凭证)。 */
+function fetchesCloudMetadata(quotesOnly: string): boolean {
+ for (const { text } of splitExecutableSegments(quotesOnly)) {
+ const tokens = unwrapWrappers(tokenize(text));
+ const bin = executableName(tokens[0] ?? '');
+ if (bin !== 'curl' && bin !== 'wget') continue;
+ if (tokens.slice(1).some((t) => isFetchTargetToken(t) && isCloudMetadataFetchTarget(t))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function matchesAnyVariant(patterns: readonly RegExp[], variants: ReturnType<typeof deterministicScanVariants>): boolean {
+ const texts = Object.values(variants);
+ return patterns.some((re) => texts.some((text) => re.test(text)));
+}
+
+/**
+ * 命令是否静态可证地读取或打出可复用凭证:读凭证 / 密钥文件(含 .env)、钥匙串、令牌类环境变量、
+ * `gh auth token`、抓云 metadata。是 classifyShellCommand「必问」判据里凭证的那一部分,供应商分享的
+ * 受邀者任务在完全访问下也要确认这一类。只看命令文本:脚本文件里读的、编码后再解开的认不出来。
+ */
+export function shellCommandReadsCredentials(
+ command: string,
+ workspaceRoots: string[],
+ opts: ShellReviewOptions = {},
+): boolean {
+ if (typeof command !== 'string' || command.trim().length === 0) return false;
+ // 超长命令解析器不展开扫描,按需要确认处理(与 classifyShellCommand 同样不放过)。
+ if (command.length > MAX_AUTO_REVIEW_ACTION_TEXT_CHARS) return true;
+ if (shellCommandReadsDotenv(command, workspaceRoots, opts)) return true;
+ const variants = deterministicScanVariants(command);
+ return matchesAnyVariant(CREDENTIAL_ALWAYS_ASK_PATTERNS, variants) || fetchesCloudMetadata(variants.quotesOnly);
+}
+
export function classifyShellCommand(
command: string,
workspaceRoots: string[],
@@ -6046,18 +6117,7 @@ export function classifyShellCommand(
// grep 搜索模式)先换成占位符,否则中文提交说明与 PR 回复正文会被当命令扫(见
// stripDataLiterals)。执行面判定不用这份 —— highImpactExecutionNeedsConsent 已在上面
// 按引号外的真实结构判过。
- const scannable = stripDataLiterals(command);
- const deEscaped = scannable.replace(/['"\\]/g, '');
- const quotesOnly = scannable.replace(/['"]/g, '');
- const deGlobbed = deEscaped.replace(/[[\]{}*?]/g, '');
- // deExpanded:抹掉参数展开(见 stripExpansions)—— 防 `s${X}udo`/`rm -r${X}f /` 这类把关键词拆开、
- // bash 展开成空后才成形的绕过。**必须从 deEscaped 派生**(保留 `${...}` 完整):若先去 glob 会把
- // `${X}` 的 `{}` 抹成 `$X`,再 stripExpansions 会把 `$Xudo` 整词吞掉、反而复原不出 `sudo`。
- // deExpandedGlob:再叠加去 glob,覆盖 `${X}` 与 `[h]` 混用的组合变形。
- const deExpanded = stripExpansions(deEscaped);
- const deExpandedGlob = deExpanded.replace(/[[\]{}*?]/g, '');
- // deSubstituted:把 `${X:-sudo}` 等默认值代入,让藏在展开默认值里的危险关键词现形(codex 报)。
- const deSubstituted = substituteDefaults(deEscaped);
+ const { deEscaped, quotesOnly, deGlobbed, deExpanded, deExpandedGlob, deSubstituted } = deterministicScanVariants(command);
// 仅按引号外的真实执行结构识别 pipe→解释器 / eval / 下载即执行,避免把打印示例文本误升级。
if ([command, stripExpansions(command), substituteDefaults(command)]
.some((variant) => highImpactExecutionNeedsConsent(variant))) return 'prompt-each-time';
@@ -6067,14 +6127,7 @@ export function classifyShellCommand(
// 抓云 metadata = 读实例临时云凭证,静态可证的高危 → 与内置 WebFetch(reviewAction network)一致地
// 确定性必问,不能一边硬问一边只给 shell curl 灰区(自审发现的两通道不一致)。
// 只认 metadata,不含 localhost/私网 —— `curl localhost:3000` 是开发日常,硬弹窗会违反"尽量不打扰"。
- for (const { text } of splitExecutableSegments(quotesOnly)) {
- const tokens = unwrapWrappers(tokenize(text));
- const bin = executableName(tokens[0] ?? '');
- if (bin !== 'curl' && bin !== 'wget') continue;
- if (tokens.slice(1).some((t) => isFetchTargetToken(t) && isCloudMetadataFetchTarget(t))) {
- return 'prompt-each-time';
- }
- }
+ if (fetchesCloudMetadata(quotesOnly)) return 'prompt-each-time';
// 写系统/受保护目录(重定向 `cat x > /etc/hosts` 与参数写通道 `cp payload /etc/hosts`、
// `| tee /etc/hosts`、`truncate -s 0 /etc/passwd`、`tar -C /etc` 等)= 高影响系统写,复用
// file-write 的系统红线。**判定放在 scopedDestructionNeedsConsent 的分段循环里**,因为那里已经