Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-sharing): fail closed for Git objects and linked inputs
MagicLiziff14764f0b16
diff --git a/apps/desktop/src/main/remote-agent/credentials.ts b/apps/desktop/src/main/remote-agent/credentials.tsindex 5f46a84bf0..bfa8fe819d 100644--- a/apps/desktop/src/main/remote-agent/credentials.ts+++ b/apps/desktop/src/main/remote-agent/credentials.ts@@ -42,7 +42,32 @@ const LOGIN_FILE = /(?:^|[\\/])(?:auth|\.credentials)\.json$/i;const NON_SECRET_FILE_NAME =/(^|[\\/\s'"=:<>|;&(])(?:\.env\.(?:example|sample|template)|[^\\/\s'"=:<>|;&()]*\.pub)(?=$|[\s'"|;&()<>])/gi;-type ShareCommandOptions = Pick<CredentialCommandOptions, 'cwd' | 'platform'>;+type ShareCommandOptions = Pick<CredentialCommandOptions, 'cwd' | 'platform'> & {+ resolveFilePath?: (operand: string, cwd: string) => string;+};++function credentialCommandOptions(opts: ShareCommandOptions): CredentialCommandOptions {+ const { resolveFilePath, ...commandOptions } = opts;+ if (!resolveFilePath) return { ...commandOptions, sourceFileSelectors: true };+ let checkedPaths = 0;+ return {+ ...commandOptions,+ sourceFileSelectors: true,+ credentialTextTransform: shareCredentialText,+ fileReadRequiresConsent: ({ operand, cwd, priorSegmentsMayMutate }) => {+ checkedPaths += 1;+ if (!cwd || priorSegmentsMayMutate || checkedPaths > 64 || PARENT_SEGMENT.test(operand)+ || operand.includes(String.fromCharCode(92)) || /^~[^/]/.test(operand)+ || /[$\x60*?{}\[\]]/.test(operand)) return true;+ if (isShareCredentialPath(operand)) return true;+ try {+ return isShareCredentialPath(resolveFilePath(operand, cwd));+ } catch {+ return true;+ }+ },+ };+}/*** 换掉配置目录里说明类子路径的目录名,和按惯例不含密钥的文件名,让本机凭证规则不再因为它们命中;@@ -98,7 +123,7 @@ function printsStoredCredentials(read: GitRead): boolean {}/**- * 命令是否读取、打出或直接写着凭证(只看命令文本:脚本文件里读的、编码后再解开的认不出来)。会打出 git+ * 命令是否读取、打出或直接写着凭证(可由执行器核实文件目标;脚本文件里读的、编码后再解开的认不出来)。会打出 git* 配置的命令(git remote -v、git config --list 等)也算,配置里没有密钥时由执行器核实后放行。*/export function isShareCredentialCommand(@@ -107,9 +132,8 @@ export function isShareCredentialCommand(opts: ShareCommandOptions = {},): boolean {return commandSpellsOutSecret(command)- || shellCommandReadsCredentials(shareCredentialText(command), workspaceRoots, {- ...opts,- sourceFileSelectors: true,+ || shellCommandReadsCredentials(opts.resolveFilePath ? command : shareCredentialText(command), workspaceRoots, {+ ...credentialCommandOptions(opts),gitConfigRead: () => false,});}@@ -130,9 +154,8 @@ export function shareCredentialGitReads(reads.push(read);return true;};- const needsConsent = shellCommandReadsCredentials(shareCredentialText(command), workspaceRoots, {- ...opts,- sourceFileSelectors: true,+ const needsConsent = shellCommandReadsCredentials(opts.resolveFilePath ? command : shareCredentialText(command), workspaceRoots, {+ ...credentialCommandOptions(opts),gitContentRead: collect,gitConfigRead: (read) => !printsStoredCredentials(read) && collect(read),});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.tsindex 5bb48da9bb..115a665e0b 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@@ -627,6 +627,130 @@ describe('shared provider credentials', () => {expect(gate.authorize({ kind: 'read', path: path.join(project, 'cloud', 'credentials') }).ok).toBe(false);});+ it('resolves a public-file operand through a directory link before full-access authorization', async () => {+ const secretDir = path.join(outside, '.aws');+ fs.mkdirSync(secretDir);+ fs.writeFileSync(path.join(secretDir, 'example.pub'), 'PRIVATE_FIXTURE=linked-content');+ fs.symlinkSync(secretDir, path.join(project, 'public'), process.platform === 'win32' ? 'junction' : 'dir');+ const asked = vi.fn(async (): Promise<ExecutorConfirmation> => false);+ const { executor, gate } = sharedExecutor('full', asked);+ const action: ExecutorAction = { kind: 'exec', command: 'cat public/example.pub', cwd: project };+ try {+ expect(gate.authorize(action).ok).toBe(false);+ expect(await executor.confirm(action)).toBe(false);+ expect(asked).toHaveBeenCalledExactlyOnceWith(action);+ expect(gate.authorize(action).ok).toBe(false);+ } finally {+ await executor.close();+ }+ });++ it.runIf(posix)('checks an exempt operand again when its symlink target changes', async () => {+ fs.writeFileSync(path.join(project, '.env'), 'PRIVATE_FIXTURE=changed-target');+ fs.writeFileSync(path.join(project, 'ordinary.txt'), 'public fixture');+ const link = path.join(project, '.env.example');+ fs.symlinkSync('ordinary.txt', link);+ const asked = vi.fn(async (): Promise<ExecutorConfirmation> => false);+ const { executor, gate } = sharedExecutor('full', asked);+ const action: ExecutorAction = { kind: 'exec', command: 'cat .env.example', cwd: project };+ try {+ expect(gate.authorize(action).ok).toBe(true);+ expect(text(await executor.callTool('Bash', { command: action.command }))).toContain('public fixture');+ expect(asked).not.toHaveBeenCalled();+ fs.rmSync(link);+ fs.symlinkSync('.env', link);+ expect(gate.authorize(action).ok).toBe(false);+ const denied = await executor.callTool('Bash', { command: action.command });+ expect(denied.isError).toBe(true);+ expect(text(denied)).not.toContain('PRIVATE_FIXTURE=changed-target');+ expect(asked).toHaveBeenCalledExactlyOnceWith(action);+ } finally {+ await executor.close();+ }+ });++ it.runIf(posix)('does not reuse a Git exemption or ordinary approval after a template link changes', async () => {+ fs.writeFileSync(path.join(project, '.env'), 'PRIVATE_FIXTURE=changed-during-probe');+ fs.writeFileSync(path.join(project, 'ordinary.txt'), 'public fixture');+ const link = path.join(project, '.env.example');+ fs.symlinkSync('ordinary.txt', link);+ const asked = vi.fn(async () => false);+ const history = {+ provesSafe: vi.fn(async () => {+ fs.rmSync(link);+ fs.symlinkSync('.env', link);+ return true;+ }),+ } as unknown as GitCredentialHistory;+ const { gate, executor } = sharedExecutor('full', asked, history);+ const ordinary: ExecutorAction = { kind: 'exec', command: 'cat .env.example', cwd: project };+ const compound: ExecutorAction = { kind: 'exec', command: 'git diff && cat .env.example', cwd: project };+ gate.recordApproval(ordinary);+ gate.recordCredentialExemption(compound);+ try {+ expect(await executor.confirm(compound)).toBe(false);+ expect(asked).toHaveBeenCalledExactlyOnceWith(compound);+ expect(gate.authorize(compound).ok).toBe(false);+ expect(gate.authorize(ordinary).ok).toBe(false);+ } finally {+ await executor.close();+ }+ });++ it('resolves ordinary templates in the actual shell directory and keeps local tasks unchanged', () => {+ const templates = path.join(project, 'templates');+ fs.mkdirSync(templates);+ fs.writeFileSync(path.join(templates, '.env.example'), 'PUBLIC_FIXTURE=example');+ fs.writeFileSync(path.join(project, 'README.md'), 'documentation');+ const { gate, workspace } = sharedExecutor('full');+ for (const command of [+ 'cat templates/.env.example',+ 'cat < templates/.env.example',+ 'cd templates && cat .env.example',+ 'grep -f templates/.env.example README.md',+ ]) {+ expect(gate.authorize({ kind: 'exec', command, cwd: project }).ok, command).toBe(true);+ }+ for (const command of [+ 'cat missing/.env.example',+ 'cat templates/.env.*',+ 'cat templates/../templates/.env.example',+ 'cd "$DIR" && cat .env.example',+ 'ln -sf .env templates/.env.example && cat templates/.env.example',+ 'HOME=/other cat templates/.env.example',+ 'unknown-reader --input templates/.env.example',+ ]) {+ const action: ExecutorAction = { kind: 'exec', command, cwd: project };+ expect(gate.authorize(action).ok, command).toBe(false);+ expect(gate.credentialGitReads(action), command).toBeNull();+ expect(new ExecutorGate(workspace, 'full').authorize(action).ok, command).toBe(true);+ }+ });++ it.runIf(posix)('keeps consent for broken template links and linked auxiliary reader inputs', () => {+ fs.writeFileSync(path.join(project, '.env'), 'PRIVATE_FIXTURE=auxiliary-input');+ fs.writeFileSync(path.join(project, 'README.md'), 'documentation');+ fs.symlinkSync('.env', path.join(project, '.env.example'));+ fs.symlinkSync('missing', path.join(project, '.env.sample'));+ const escaped = 'literal' + String.fromCharCode(92) + '.env.example';+ fs.writeFileSync(path.join(project, escaped), 'public fixture');+ const { gate } = sharedExecutor('full');+ for (const command of [+ 'cat .env.sample',+ 'grep -f .env.example README.md',+ 'sed -f .env.example README.md',+ 'git grep -f .env.example -- README.md',+ 'git blame --contents .env.example README.md',+ 'git diff && cat < .env.example',+ 'sh -c "cat .env.example"',+ 'cat ' + escaped,+ ]) {+ const action: ExecutorAction = { kind: 'exec', command, cwd: project };+ expect(gate.authorize(action).ok, command).toBe(false);+ expect(gate.credentialGitReads(action), command).toBeNull();+ }+ });+it('asks on this computer and goes ahead only with what the user allowed', async () => {const asked: ExecutorAction[] = [];let answer = true;diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.tsindex 66ec7220c4..621f76e609 100644--- a/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts@@ -244,6 +244,66 @@ describe('GitCredentialHistory', () => {expect(await provesSafe(fullDiffHistory, 'git log -p --full-diff -- README.md')).toBe(false);});+ it('keeps confirmation for a dangling credential blob outside every scanned commit', async () => {+ const history = new GitCredentialHistory();+ expect(await provesSafe(history, 'git show HEAD')).toBe(true);+ write('.env', 'PRIVATE_FIXTURE=unreachable-content\n');+ const blob = git('hash-object', '-w', '.env').trim();+ fs.rmSync(path.join(repo, '.env'));+ expect(git('ls-files', '--', '.env')).toBe('');+ expect(git('rev-list', '--all', '--reflog', '--objects')).not.toContain(blob);+ expect(git('show', blob)).toContain('PRIVATE_FIXTURE=unreachable-content');+ for (const command of ['git show ' + blob, 'git show ' + blob + ' -- README.md']) {+ expect(await provesSafe(history, command), command).toBe(false);+ await requiresCredentialConfirmation(history, command);+ }+ });++ it('does not use replaced objects to prove the original history has no credentials', async () => {+ const history = new GitCredentialHistory();+ expect(await provesSafe(history, 'git show HEAD')).toBe(true);+ const safe = git('rev-parse', 'HEAD').trim();+ write('.env', 'PRIVATE_FIXTURE=original-history\n');+ git('add', '.env');+ git('commit', '-q', '--no-gpg-sign', '-m', 'original credentials');+ const original = git('rev-parse', 'HEAD').trim();+ git('replace', original, safe);+ git('reset', '--mixed', '-q', 'HEAD');+ expect(git('ls-files', '--', '.env')).toBe('');+ expect(git('show', 'HEAD')).not.toContain('PRIVATE_FIXTURE=original-history');+ expect(git('--no-replace-objects', 'show', 'HEAD')).toContain('PRIVATE_FIXTURE=original-history');+ for (const command of ['git --no-replace-objects show HEAD', 'git show HEAD']) {+ expect(await provesSafe(history, command), command).toBe(false);+ await requiresCredentialConfirmation(history, command);+ }+ git('replace', '-d', original);+ vi.stubEnv('GIT_REPLACE_REF_BASE', 'refs/custom-replace/');+ git('replace', original, safe);+ expect(await provesSafe(history, 'git --no-replace-objects show HEAD')).toBe(false);+ await requiresCredentialConfirmation(history, 'git --no-replace-objects show HEAD');+ });++ it.runIf(process.platform !== 'win32')('does not exempt a tracked template symlink to an ignored credential file', async () => {+ write('.gitignore', '.env\n');+ write('.env', 'PRIVATE_FIXTURE=symlink-target\n');+ fs.rmSync(path.join(repo, '.env.example'));+ fs.symlinkSync('.env', path.join(repo, '.env.example'));+ git('add', '.gitignore', '.env.example');+ git('commit', '-q', '--no-gpg-sign', '-m', 'template link');+ expect(git('ls-files', '--', '.env')).toBe('');+ expect(git('ls-files', '--stage', '--', '.env.example')).toMatch(/^120000 /);+ const history = new GitCredentialHistory();+ for (const command of [+ 'cat .env.example',+ 'cat < .env.example',+ 'git diff && cat .env.example',+ 'git grep -f .env.example -- README.md',+ 'git blame --contents .env.example README.md',+ ]) {+ await requiresCredentialConfirmation(history, command);+ }+ });+it('does not exempt a git read after an earlier shell segment may change state', async () => {const history = new GitCredentialHistory();expect(await provesSafe(history, 'git add -A && git diff --cached')).toBe(false);diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex b682fcc302..0630200713 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -187,7 +187,9 @@ export class RemoteExecutor {const history = this.opts.gitCredentials;if (!history || action.kind !== 'exec') return null;const reads = this.gate.credentialGitReads(action);- return reads ? history.provesSafe(action.command, reads, signal).catch(() => false) : null;+ return reads ? history.provesSafe(action.command, reads, signal)+ .then((safe) => safe && this.gate.credentialGitReads(action) !== null)+ .catch(() => false) : null;}/** 检查上限;凭证类操作没有批准时先在本机问一次。 */diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.tsindex 94d953a336..ea34a2a1eb 100644--- a/apps/desktop/src/main/remote-agent/executor/gate.ts+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts@@ -18,6 +18,7 @@* 批准记录只在短时间内有效;命令与抓取的批准用一次即失效,路径批准在有效期内覆盖同一路径的读写* (编辑会先读后写)。*/+import fs from 'node:fs';import path from 'node:path';import { classifyShellCommand, reviewAction, type GitRead } from '@cindy/maker-core';@@ -164,7 +165,11 @@ export class ExecutorGate {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 isShareCredentialCommand(action.command, this.workspace.allRoots(), {+ cwd: action.cwd,+ platform: process.platform,+ resolveFilePath: (operand, cwd) => fs.realpathSync.native(this.workspace.resolve(operand, cwd)),+ });}return isShareCredentialPath(path.resolve(action.path)) || isShareCredentialPath(realPathOrAncestor(action.path));}@@ -175,18 +180,22 @@ export class ExecutorGate {*/credentialGitReads(action: ExecutorAction): GitRead[] | null {if (!this.options.confirmCredentials || action.kind !== 'exec') return null;- return shareCredentialGitReads(action.command, this.workspace.allRoots(), { cwd: action.cwd, platform: process.platform });+ return shareCredentialGitReads(action.command, this.workspace.allRoots(), {+ cwd: action.cwd,+ platform: process.platform,+ resolveFilePath: (operand, cwd) => fs.realpathSync.native(this.workspace.resolve(operand, cwd)),+ });}authorize(action: ExecutorAction): ExecutorGateDecision {let credential = this.needsCredentialConsent(action);- if (credential && this.consumeCredentialExemption(action)) credential = false;+ if (credential && this.consumeCredentialExemption(action) && this.credentialGitReads(action) !== null) credential = false;if (this.mode === 'full' && !credential) return { ok: true, elevated: true };// 抓取网页:本机用户批准过这个地址就放开内网。公网样式的域名也可能解析到内网(公司内网域名),// 只看地址文本判定为不必问,但抓取时会按 DNS 结果被拦下。if (action.kind === 'fetch' && this.consume(action)) return { ok: true, elevated: true };if (!credential && !this.requiresApproval(action)) return { ok: true };- if (this.consume(action)) return { ok: true, elevated: true };+ if (this.consume(action, credential)) return { ok: true, elevated: true };return { ok: false, reason: this.deniedReason(action) };}@@ -223,10 +232,11 @@ export class ExecutorGate {return action.scope === 'tree' && !this.workspace.contains(action.path);}- private consume(action: ExecutorAction): boolean {+ private consume(action: ExecutorAction, credential = false): boolean {this.prune();const { kind, key } = approvalOf(action);- const index = this.approvals.findIndex((approval) => approval.kind === kind && approval.key === key);+ const index = this.approvals.findIndex((approval) => approval.kind === kind && approval.key === key+ && (!credential || approval.credential));if (index < 0) return false;if (kind !== 'path') this.approvals.splice(index, 1);return true;diff --git a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts b/apps/desktop/src/main/remote-agent/executor/gitCredentials.tsindex 0cd57349c6..2328974d9f 100644--- a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts+++ b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts@@ -10,7 +10,7 @@* - 还不行时(git diff、git show、git log),按原命令只列出会显示的文件,其中没有凭证类文件也算读不到。* 认不出 git 在哪个仓库里跑、仓库带子模块、比较仓库外的文件、超过等待时限,都按读得到处理,照旧弹卡。* 会打出 git 配置的命令(git remote -v、git config --list 等)按本机生效的配置核对其中没有密钥。- * 与命令文本判定一样只防误发:直接写出底层对象名(git show <blob>)、在前面的命令里改 GIT_DIR 之类的认不出。+ * 与命令文本判定一样只防误发:不能解析为提交的对象、replacement refs 与前段可能改状态时不授予豁免。*/import { spawn } from 'node:child_process';import fsp from 'node:fs/promises';@@ -107,7 +107,7 @@ function git(opts: { stdin?: string; onRecord?: (record: string) => boolean | void; timeoutMs?: number } = {},): Promise<string> {return new Promise((resolve, reject) => {- const child = spawn('git', [...args], {+ const child = spawn('git', ['--no-replace-objects', ...args], {cwd,env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' },stdio: ['pipe', 'pipe', 'ignore'],@@ -304,10 +304,33 @@ function pathspecsAvoid(read: GitRead, cwd: string, top: string, credentials: Re});}-function revisionOperands(read: GitRead): string[] {+function revisionOperands(read: GitRead): string[] | null {if (!SHOWN_FILES[read.sub] && !PATHSPEC_SUBCOMMANDS.has(read.sub)) return [];const separator = read.args.indexOf('--');const args = read.args.slice(0, separator < 0 ? read.args.length : separator);+ if (read.sub === 'grep') {+ let patternProvided = false;+ const revisions: string[] = [];+ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];+ if (arg === '-e' || arg === '--regexp') {+ if (args[index + 1] === undefined) return null;+ index += 1;+ patternProvided = true;+ } else if (/^(?:-e.+|--regexp=)/.test(arg)) {+ patternProvided = true;+ } else if (arg === '--cached' || arg === '--line-number' || /^-[nivwhHlLcoqEGFP]+$/.test(arg)) {+ continue;+ } else if (arg.startsWith('-')) {+ return null;+ } else if (!patternProvided) {+ patternProvided = true;+ } else {+ revisions.push(arg);+ }+ }+ return patternProvided ? revisions : null;+ }return args.flatMap((arg) => {if (arg.startsWith('-')) return [];return arg.split(/\.\.\.?/).filter(Boolean);@@ -320,12 +343,14 @@ async function revisionsAreCovered(tips: ReadonlySet<string>,deadline: number,): Promise<boolean> {- for (const revision of revisionOperands(read)) {+ const revisions = revisionOperands(read);+ if (!revisions) return false;+ for (const revision of revisions) {const remaining = deadline - Date.now();if (remaining <= 0) return false;const commit = await git(['rev-parse', '--verify', '--quiet', revision + '^{commit}'], cwd, { timeoutMs: remaining }).then((output) => output.trim(), () => '');- if (!commit) continue;+ if (!commit) return false;if (tips.has(commit)) continue;let covered = false;for (const tip of tips) {@@ -471,6 +496,13 @@ export class GitCredentialHistory {if (!topLine || !commonLine) return false;const top = path.resolve(topLine);const commonDir = path.resolve(cwd, commonLine);+ if (process.env.GIT_REPLACE_REF_BASE !== undefined) return false;+ const replacementTimeout = deadline - Date.now();+ if (replacementTimeout <= 0) return false;+ const replacements = await git(['for-each-ref', '--format=%(refname)', 'refs/replace'], top, {+ timeoutMs: replacementTimeout,+ });+ if (replacements.trim()) return false;// 指向仓库外的文件时 git diff 不经仓库、直接比较文件。if (read.sub === 'diff' && read.args.some((arg) => !arg.startsWith('-') && isOutside(top, path.resolve(cwd, arg)))) {return false;diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex e4a561d0bd..b0178f3c46 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -285,7 +285,10 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):- 减少误弹(2026-10-12 用户裁决)。**以下几条只用于这张分享任务的确认卡**,本机任务、同账号远程供应商与自动审查的判定都不变:- `.env.example` / `.env.sample` / `.env.template` 与公钥 `*.pub` 按惯例不含密钥,不算凭证类文件- (读取、启动时同步都照普通文件);放在凭证目录里(如 `~/.ssh/id_rsa.pub`)时仍算;+ (读取、启动时同步都照普通文件);放在凭证目录里(如 `~/.ssh/id_rsa.pub`)时仍算。命令中读取+ 文件时,执行前按该命令段的实际目录核对原始路径与链接的真实目标;模板、公钥与配置目录里的说明+ 路径不能借链接指向凭证。目标不存在、链接断开、目录或展开认不出、前段可能改动链接或环境时,+ 都保留确认,不用改写后的文件名或上次核实的链接目标放行;- 按扩展名缩小范围的搜索不算读取凭证:rg 的 `-g '*.ts'`、grep 的 `--include='*.md'` 这类只选中源码与文档文件的写法,字面上能选中 `.env.ts`、`id_rsa.ts`,但这类名字是代码模块。直接写出像凭证的文件名、`*.json` / `*.txt` / `*.sh` 这类可能存放凭证的格式、扩展名不确定的写法(`*.ts*`)仍要确认;@@ -294,7 +297,10 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):stash 与 reflog 的历史和暂存区里从没有凭证类文件;或命令用 `--` 限定的路径碰不到这些文件;或(`git diff` / `git show` / `git log`)按原命令只列出会显示的文件,其中没有凭证类文件。认不出 git在哪个仓库里跑、仓库带子模块、比较仓库外的文件、核实超过 8 秒,都照旧弹卡;仓库的扫描结果留在- 内存里给后面的命令用。直接写出底层对象名(如 `git show <文件对象>`)之类的写法同样认不出;+ 内存里给后面的命令用。指定的对象必须能解析为提交且已在扫描范围内,否则改按实际显示的文件+ 核对;无法证明为提交的底层对象(如 `git show <blob-id>`)保留确认,不能按干净历史放行。所有+ 历史与内容探针禁用 replacement refs;仓库有 `refs/replace` 或宿主设置了 `GIT_REPLACE_REF_BASE`+ 时不授予内容豁免,避免探针与实际命令使用不同对象;- 打出 git 配置的命令(`git remote -v` / `get-url` / `show`、读 `git config`、`git var -l`)按受邀者电脑上生效的 git 配置核实:要打出的那些项里没有密钥(地址里嵌的令牌或密码、`http.extraHeader`、密码与令牌类配置项)就不弹卡,有才确认;@@ -337,7 +343,7 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):明确提示,同区域分享不受影响。10. 受邀者任务启动时不带凭证类文件;任务中读写凭证类文件或执行读取凭证的命令,即使在完全访问下也要受邀者在本机确认后才执行(§9 第 7 条)。`rg -g '*.ts'` 这类只按源码扩展名缩小范围的搜索、读- `.env.example` 与 `*.pub`、在没有凭证类文件的仓库里(或只涉及普通文件时)跑 `git diff` / `git log -p`、+ 实际目标已核实为非凭证的 `.env.example` 与 `*.pub`、在没有凭证类文件的仓库里(或只涉及普通文件时)跑 `git diff` / `git log -p`、配置里没有密钥时跑 `git remote -v` 都不弹确认卡;命令里直接写着密钥、`git credential fill` 要确认;本机任务与同账号远程供应商的确认不受影响。11. Light 与 Dark 两种模式都已实现。diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.tsindex 00725b4f0b..e66316172b 100644--- a/packages/maker-core/src/agents/shared/auto-review.test.ts+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts@@ -4722,6 +4722,46 @@ describe('shellCommandReadsCredentials — 只认凭证那一部分红线', () =// 两个附加选项只供供应商分享的受邀者任务用(apps/desktop/src/main/remote-agent/credentials.ts)。describe('shellCommandReadsCredentials — 分享任务的附加选项', () => {+ it('passes original reader operands, redirects and auxiliary files to the sharing path check', () => {+ for (const command of ['cat .env.example', 'cat < .env.example', 'grep -f .env.example README.md']) {+ const checked: string[] = [];+ expect(shellCommandReadsCredentials(command, roots, {+ cwd: '/repo',+ platform: 'linux',+ credentialTextTransform: (text) => text.replaceAll('.env.example', 'example'),+ fileReadRequiresConsent: (read) => {+ checked.push(read.operand);+ return read.operand === '.env.example';+ },+ }), command).toBe(true);+ expect(checked, command).toContain('.env.example');+ }+ expect(shellCommandReadsCredentials('cat .env.example', roots, {+ credentialTextTransform: (text) => text.replaceAll('.env.example', 'example'),+ fileReadRequiresConsent: () => false,+ })).toBe(false);+ expect(shellCommandReadsCredentials('cat .env.example', roots)).toBe(true);+ });++ it('binds sharing file checks to the segment directory and invalidates preceding mutations', () => {+ for (const [command, expected] of [+ ['cd /repo/examples && cat example.pub', { cwd: '/repo/examples', priorSegmentsMayMutate: false }],+ ['ln -sf .env example.pub && cat example.pub', { cwd: '/repo', priorSegmentsMayMutate: true }],+ ['HOME=/other cat example.pub', { cwd: '/repo', priorSegmentsMayMutate: true }],+ ['cd "$DIR" && cat example.pub', { cwd: undefined }],+ ] as const) {+ const checked: unknown[] = [];+ shellCommandReadsCredentials(command, roots, {+ cwd: '/repo',+ platform: 'linux',+ fileReadRequiresConsent: (read) => {+ checked.push(read);+ return true;+ },+ });+ expect(checked, command).toEqual([expect.objectContaining({ operand: 'example.pub', ...expected })]);+ }+ });const sourceSearches = ["rg -n 'API_KEY' --glob '*.ts'","rg -g '*.{ts,tsx}' token src",diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex 8b44232247..897c7451a8 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -3252,6 +3252,12 @@ export type GitRead = {* (apps/desktop/src/main/remote-agent/credentials.ts)。本机任务的自动审查不传,判定不变。*/export type CredentialCommandOptions = ShellReviewOptions & {+ credentialTextTransform?: (text: string) => string;+ fileReadRequiresConsent?: (read: {+ operand: string;+ cwd?: string;+ priorSegmentsMayMutate: boolean;+ }) => boolean;/** rg -g、grep --include 这类搜索范围只选中源码与文档扩展名时不算读取凭证。 */sourceFileSelectors?: boolean;/**@@ -5437,12 +5443,14 @@ function readerOptionValueIsSensitive(value: string | undefined,isSensitiveOperand: (value: string) => boolean,selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,+ fileReadRequiresConsent?: (value: string) => boolean,): boolean {if (kind === 'selector') return selectorCouldMatch(value ?? '');if (!value || (kind !== 'data-file' && kind !== 'aux-file' && kind !== 'aux-file-list')) return false;const operands = kind === 'aux-file-list' ? value.split(/[:;]/) : [value];- return operands.some((operand) =>- isSensitiveOperand(operand) || selectorCouldMatchCredential(operand));+ return operands.some((operand) => fileReadRequiresConsent+ ? fileReadRequiresConsent(operand)+ : isSensitiveOperand(operand) || selectorCouldMatchCredential(operand));}function readerArgumentsReadDotenv(@@ -5451,6 +5459,8 @@ function readerArgumentsReadDotenv(isSensitiveOperand: (value: string) => boolean = isDotenvCredentialPath,platform: NodeJS.Platform = process.platform,selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,+ fileReadRequiresConsent?: (value: string) => boolean,+ checkPositionalFiles = true,): boolean {let dataArgumentProvided = !FIRST_DATA_ARGUMENT_BINS.has(bin);let optionsEnded = false;@@ -5473,12 +5483,14 @@ function readerArgumentsReadDotenv(const secondValue = attached === undefined ? args[index + 2] : args[index + 1];if (nameValue === undefined || secondValue === undefined) return true;if (kind === 'named-file'- && readerOptionValueIsSensitive('data-file', secondValue, isSensitiveOperand)) return true;+ && readerOptionValueIsSensitive('data-file', secondValue, isSensitiveOperand,+ selectorCouldMatch, fileReadRequiresConsent)) return true;index += attached === undefined ? 2 : 1;continue;}const value = attached ?? args[index + 1];- const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand, selectorCouldMatch);+ const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand,+ selectorCouldMatch, fileReadRequiresConsent);if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -5493,7 +5505,8 @@ function readerArgumentsReadDotenv(if (!kind) continue;const attached = token.slice(optionIndex + 1) || undefined;const value = attached ?? args[index + 1];- const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand, selectorCouldMatch);+ const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand,+ selectorCouldMatch, fileReadRequiresConsent);if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -5508,7 +5521,9 @@ function readerArgumentsReadDotenv(dataArgumentProvided = true;continue;}- if (shellOperandCouldMatchDotenv(token, isSensitiveOperand)) return true;+ if (fileReadRequiresConsent && checkPositionalFiles+ ? fileReadRequiresConsent(token)+ : shellOperandCouldMatchDotenv(token, isSensitiveOperand)) return true;}return false;}@@ -5842,7 +5857,10 @@ function isGitExcludePathspec(value: string): boolean {return value.startsWith(':!') || value.startsWith(':^');}-function gitBlameContentsReadDotenv(args: readonly string[]): boolean {+function gitBlameContentsReadDotenv(+ args: readonly string[],+ fileReadRequiresConsent: (value: string) => boolean = shellOperandCouldMatchDotenv,+): boolean {for (let index = 0; index < args.length; index += 1) {const token = args[index];if (token === '--') break;@@ -5854,7 +5872,7 @@ function gitBlameContentsReadDotenv(args: readonly string[]): boolean {if (!isContentsOption) continue;const attached = equalsIndex >= 0 ? token.slice(equalsIndex + 1) : undefined;const value = attached ?? args[index + 1];- if (value && shellOperandCouldMatchDotenv(value)) return true;+ if (value && fileReadRequiresConsent(value)) return true;if (attached === undefined) index += 1;}return false;@@ -6211,6 +6229,7 @@ function priorShellSegmentsMayMutate(workspaceRoots: string[],opts: ShellReviewOptions,segmentCwds: readonly (string | undefined)[],+ allowResolvedDirectoryChanges = false,): boolean {for (let index = 0; index < segmentIndex; index += 1) {const segmentCwd = segmentCwds[index];@@ -6223,6 +6242,10 @@ function priorShellSegmentsMayMutate(// for a later credential exemption even though its output is otherwise read-only.const tokens = stripShellControlTokens(tokenize(segments[index].text));const unwrapped = unwrapCommand(tokens, segmentOpts.cwd ?? workspaceRoots[0], segmentOpts.cwdUnknown === true);+ if (allowResolvedDirectoryChanges && !process.env.CDPATH+ && tokens[0] === 'cd' && tokens.length === 2 && !tokens[1].startsWith('-')+ && segments[index].separatorAfter === 'and' && segmentCwds[index + 1] !== undefined+ && !segmentHasSideEffectRedirectOrSubstitution(segments[index].text)) continue;const invocation = unwrapped.tokens[0] && executableName(unwrapped.tokens[0]) === 'git'? parseGitInvocation(unwrapped.tokens, workspaceRoots, segmentOpts): undefined;@@ -6252,16 +6275,16 @@ function shellCommandReadsDotenv(depth = 0,): boolean {if (depth >= MAX_EXEC_REVIEW_DEPTH) return true;- const selectorCouldMatch = opts.sourceFileSelectors ? shareSelectorCouldMatchCredential : selectorCouldMatchCredential;+ const credentialText = opts.credentialTextTransform ?? ((text: string) => text);+ const selectorMatcher = opts.sourceFileSelectors ? shareSelectorCouldMatchCredential : selectorCouldMatchCredential;+ const selectorCouldMatch = (value: string) => selectorMatcher(credentialText(value));const segments = splitExecutableSegments(command);- // 只有调用方要核实 git 调用时才需要各段的目录。- const segmentCwds = opts.gitContentRead || opts.gitConfigRead ? segmentWorkingDirs(segments, workspaceRoots, opts) : [];+ // 调用方核实 Git 或文件读取时需要各段的实际目录。+ const segmentCwds = opts.gitContentRead || opts.gitConfigRead || opts.fileReadRequiresConsent+ ? segmentWorkingDirs(segments, workspaceRoots, opts) : [];for (const [segmentIndex, { text: segment }] of segments.entries()) {const inputRedirections = parseShellInputRedirections(segment);if (inputRedirections.hasUnresolvedTarget) return true;- const readsCredentialInput = inputRedirections.targets.some(- (target) => shellOperandCouldMatchDotenv(target),- );const inspectionCommand = inputRedirections.targets.length > 0? parseShellInputRedirections(segment, true).command: inputRedirections.command;@@ -6275,11 +6298,26 @@ function shellCommandReadsDotenv(const bin = executableName(tokens[0] ?? '');const sharesGitCredentialChecks = opts.gitContentRead !== undefined || opts.gitConfigRead !== undefined;const configOverride = bin === 'git' && gitUsesConfigOverride(tokens);- const priorMutation = sharesGitCredentialChecks+ const priorMutation = sharesGitCredentialChecks || opts.fileReadRequiresConsent? priorShellSegmentsMayMutate(segments, segmentIndex, workspaceRoots, opts, segmentCwds)|| segmentHasSideEffectRedirectOrSubstitution(segment)|| configOverride: false;+ const priorFileMutation = opts.fileReadRequiresConsent+ ? priorShellSegmentsMayMutate(segments, segmentIndex, workspaceRoots, opts, segmentCwds, true)+ || segmentHasSideEffectRedirectOrSubstitution(segment)+ || rawTokens[0] !== tokens[0]+ : false;+ const fileReadRequiresConsent = opts.fileReadRequiresConsent+ ? (operand: string) => opts.fileReadRequiresConsent!({+ operand,+ cwd: depth === 0 ? segmentCwds[segmentIndex] : undefined,+ priorSegmentsMayMutate: priorFileMutation,+ }) : undefined;+ const readsCredentialInput = inputRedirections.targets.some((target) => fileReadRequiresConsent+ ? fileReadRequiresConsent(target)+ : shellOperandCouldMatchDotenv(credentialText(target)));+ if (fileReadRequiresConsent && readsCredentialInput) return true;// xargs and parallel construct the real argv from stdin. The command that eventually reads// a repository or credential file is therefore outside this static scan; shared-provider@@ -6331,7 +6369,7 @@ function shellCommandReadsDotenv(// Inline programs are not shell argv, so a Python/Node reader such as// `open(".env")` never reaches the reader-specific path parser. Keep// credential path patterns visible in these payloads before recursing.- if (inlinePayloadMentionsCredentialPath(payload)) return true;+ if (inlinePayloadMentionsCredentialPath(opts.fileReadRequiresConsent ? payload : credentialText(payload))) return true;if (shellCommandReadsCredentials(payload, workspaceRoots, opts, depth + 1)) return true;}@@ -6347,14 +6385,18 @@ function shellCommandReadsDotenv(if (bin === 'git') {const invocation = parseGitInvocation(tokens, workspaceRoots, opts);if (!invocation?.sub || !SAFE_GIT_SUBCOMMANDS.has(invocation.sub)) continue;+ const credentialArgs = invocation.args.map(credentialText);if (readsCredentialInput) return true;if (invocation.sub === 'grep') {if (gitGrepExpandsSearchScope(invocation.args)) return true;- if (readerArgumentsReadDotenv('grep', invocation.args, isGitDotenvOperand)) return true;- } else if ((invocation.sub === 'blame' && gitBlameContentsReadDotenv(invocation.args))+ if (readerArgumentsReadDotenv('grep', fileReadRequiresConsent ? invocation.args : credentialArgs,+ (operand) => isGitDotenvOperand(credentialText(operand)), opts.platform ?? process.platform,+ selectorCouldMatch, fileReadRequiresConsent, false)) return true;+ } else if ((invocation.sub === 'blame' && gitBlameContentsReadDotenv(invocation.args,+ fileReadRequiresConsent ?? ((operand) => shellOperandCouldMatchDotenv(credentialText(operand)))))|| ((invocation.sub === 'log' || invocation.sub === 'whatchanged' || invocation.sub === 'show')- && gitLineRangeReadsDotenv(invocation.args))- || gitArgumentsReadDotenv(invocation.args)) {+ && gitLineRangeReadsDotenv(credentialArgs))+ || gitArgumentsReadDotenv(credentialArgs)) {return true;}if (gitContentReadWithoutPath(invocation.sub, invocation.args)@@ -6369,14 +6411,18 @@ function shellCommandReadsDotenv(continue;}- if (!DOTENV_FILE_READER_BINS.has(bin)) continue;+ if (!DOTENV_FILE_READER_BINS.has(bin)) {+ if (fileReadRequiresConsent && credentialText(segment) !== segment) return true;+ continue;+ }if (readsCredentialInput) return true;const args = tokens.slice(1);if (grepRecursesIntoPotentialDotenv(bin, args, selectorCouldMatch)) return true;if (bin === 'ag' && agSearchesPotentialCredential(args)) return true;if (bin === 'rg' && rgSearchesPotentialDotenv(args, selectorCouldMatch)) return true;if (readerArgumentsReadDotenv(- bin, args, isDotenvCredentialPath, opts.platform ?? process.platform, selectorCouldMatch)) return true;+ bin, args, isDotenvCredentialPath, opts.platform ?? process.platform,+ selectorCouldMatch, fileReadRequiresConsent)) return true;}return false;}@@ -6441,7 +6487,7 @@ export function shellCommandReadsCredentials(// 超长命令解析器不展开扫描,按需要确认处理(与 classifyShellCommand 同样不放过)。if (command.length > MAX_AUTO_REVIEW_ACTION_TEXT_CHARS) return true;if (shellCommandReadsDotenv(command, workspaceRoots, opts, depth)) return true;- const variants = deterministicScanVariants(command);+ const variants = deterministicScanVariants(opts.credentialTextTransform?.(command) ?? command);return matchesAnyVariant(CREDENTIAL_ALWAYS_ASK_PATTERNS, variants) || fetchesCloudMetadata(variants.quotesOnly);}