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): bound Git probes and block fsmonitor hooks
MagicLizi0d9fef500560
diff --git a/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.tsindex 88c1751c0b..09ee2cfaf1 100644--- a/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts@@ -6,7 +6,7 @@import { isSensitiveCredentialPath, shellCommandReadsCredentials } from '@cindy/maker-core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { isShareCredentialCommand, isShareCredentialPath, shareCredentialGitReads } from '../credentials';+import { isShareCredentialCommand, isShareCredentialPath, shareCredentialGitReads, textSpellsOutSecret } from '../credentials';beforeEach(() => vi.stubEnv('RIPGREP_CONFIG_PATH', undefined));afterEach(() => vi.unstubAllEnvs());@@ -159,10 +159,13 @@ describe('shareCredentialGitReads', () => {{ sub: 'log', args: ['-p', '--', 'src/app.ts'] },]);expect(shareCredentialGitReads('git diff && git show HEAD', roots, { cwd: '/repo' })).toHaveLength(2);+ expect(shareCredentialGitReads('git status', roots, { cwd: '/repo' })).toMatchObject([+ { sub: 'status', metadataOnly: true },+ ]);+ expect(shellCommandReadsCredentials('git status', roots)).toBe(false);// 还有别的理由,或本来就不用确认:不交给核实。expect(shareCredentialGitReads('git diff && cat .env', roots, { cwd: '/repo' })).toBeNull();expect(shareCredentialGitReads('git show HEAD:.env', roots, { cwd: '/repo' })).toBeNull();- expect(shareCredentialGitReads('git status', roots, { cwd: '/repo' })).toBeNull();expect(shareCredentialGitReads('pnpm test', roots, { cwd: '/repo' })).toBeNull();});@@ -250,12 +253,16 @@ describe('secrets written in the command', () => {'git clone https://github.com/a/b.git','git push origin main','git commit -m "fix sk-learn import"',- "git log --format='%h: %s' -5",'curl http://localhost:3000/api',- 'git show HEAD:src/app.ts',- 'git show HEAD:.env.example',]) {expect(isShareCredentialCommand(command, roots), command).toBe(false);}+ for (const command of ["git log --format='%h: %s' -5", 'git show HEAD:src/app.ts', 'git show HEAD:.env.example']) {+ expect(textSpellsOutSecret(command), command).toBe(false);+ expect(shellCommandReadsCredentials(command, roots), command).toBe(command === 'git show HEAD:.env.example');+ expect(shareCredentialGitReads(command, roots, { cwd: '/repo' }), command).toMatchObject([+ { metadataOnly: 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 1c84c158dd..932ec8986f 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@@ -491,6 +491,75 @@ describe('GitCredentialHistory', () => {expect(fs.existsSync(invokedFile)).toBe(false);});+ it('keeps consent for fsmonitor hooks before any index probe can run them', async () => {+ const history = new GitCredentialHistory();+ const credentialFile = path.join(root, '.env');+ const hookFile = path.join(root, 'fsmonitor-hook.cjs');+ const invokedFile = path.join(root, 'fsmonitor-invoked');+ fs.writeFileSync(credentialFile, 'PRIVATE_FIXTURE=fsmonitor-hook\n');+ fs.writeFileSync(hookFile, 'const fs = require("node:fs");\n'+ + 'fs.writeFileSync(' + JSON.stringify(invokedFile) + ', "called");\n'+ + 'process.stderr.write(fs.readFileSync(' + JSON.stringify(credentialFile) + '));\n'+ + 'process.stdout.write("fixture-token\\0");\n');+ const hook = [process.execPath, hookFile].map((file) => JSON.stringify(file.split(path.sep).join('/'))).join(' ');+ expect(await provesSafe(history, 'git diff')).toBe(true);+ git('config', 'core.fsmonitor', hook);+ for (const subcommand of ['diff', 'status']) {+ const output = spawnSync('git', [subcommand], { cwd: repo, encoding: 'utf8' });+ expect(output.stderr, subcommand).toContain('PRIVATE_FIXTURE=fsmonitor-hook');+ expect(output.status, subcommand).toBe(0);+ }+ fs.unlinkSync(invokedFile);+ for (const command of ['git diff', 'git diff --no-ext-diff --no-textconv', 'git diff --cached', 'git show HEAD',+ 'git diff --name-only', 'git status', 'git ls-files', 'git show -s HEAD:src/app.ts']) {+ expect(await provesSafe(history, command), command).toBe(false);+ await requiresCredentialConfirmation(history, command);+ expect(fs.existsSync(invokedFile), command).toBe(false);+ }+ expect(await provesSafe(history, 'git config --get core.autocrlf')).toBe(true);+ for (const value of ['true', 'false']) {+ git('config', 'core.fsmonitor', value);+ expect(await provesSafe(history, 'git diff'), value).toBe(false);+ }+ git('config', '--unset', 'core.fsmonitor');+ expect(await provesSafe(history, 'git diff')).toBe(true);+ expect(await provesSafe(history, 'git diff --cached')).toBe(true);+ expect(await provesSafe(history, 'git status')).toBe(true);+ expect(await provesSafe(history, 'git ls-files')).toBe(true);+ expect(fs.existsSync(invokedFile)).toBe(false);+ });++ it('uses one budget for all Git segments including configuration reads', async () => {+ vi.spyOn(fsPromises, 'realpath').mockImplementation(async () => {+ await new Promise((resolve) => setTimeout(resolve, 75));+ return repo;+ });+ const history = new GitCredentialHistory({ waitMs: 100 });+ const started = Date.now();+ expect(await provesSafe(history, 'git config --get core.autocrlf && git config --get core.autocrlf')).toBe(false);+ expect(Date.now() - started).toBeLessThan(process.platform === 'win32' ? 5_000 : 1_000);+ const contentStarted = Date.now();+ expect(await provesSafe(history, 'git diff && git show HEAD')).toBe(false);+ expect(Date.now() - contentStarted).toBeLessThan(process.platform === 'win32' ? 5_000 : 1_000);+ });++ it('stops a stalled configuration filesystem check and cancelled command within the same budget', async () => {+ vi.spyOn(fsPromises, 'realpath').mockImplementation(() => new Promise<string>(() => {}));+ const history = new GitCredentialHistory({ waitMs: 30 });+ const started = Date.now();+ expect(await provesSafe(history, 'git config --list')).toBe(false);+ expect(Date.now() - started).toBeLessThan(1_000);+ const abort = new AbortController();+ const reads = shareCredentialGitReads('git config --list', [repo], { cwd: repo, platform: process.platform });+ const cancelled = new GitCredentialHistory({ waitMs: 5_000 });+ const cancelledStarted = Date.now();+ const pending = cancelled.provesSafe('git config --list', reads ?? [], abort.signal);+ abort.abort();+ expect(await pending).toBe(false);+ expect(Date.now() - cancelledStarted).toBeLessThan(1_000);+ expect(await history.provesSafe('git config --list', reads ?? [], abort.signal)).toBe(false);+ });+it('keeps consent for configured textconv and external diff helpers', async () => {const history = new GitCredentialHistory();const credentialFile = path.join(root, '.env');diff --git a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts b/apps/desktop/src/main/remote-agent/executor/gitCredentials.tsindex 846dd4edf8..d5c0775fb5 100644--- a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts+++ b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts@@ -174,10 +174,11 @@ async function scanHistory(top: string, extraArgs: readonly string[], stdin?: st}/** 暂存区里的凭证类路径;带子模块或超过上限时返回 null。 */-async function indexCredentials(top: string): Promise<Set<string> | null> {+async function indexCredentials(top: string, timeoutMs: number): Promise<Set<string> | null> {const collector = credentialCollector(top);let submodule = false;await git(['ls-files', '--stage', '-z'], top, {+ timeoutMs,onRecord: (record) => {const tab = record.indexOf('\t');if (tab < 0) return;@@ -456,7 +457,7 @@ function configEntryHoldsSecret(key: string, value: string): boolean {* 打出 git 配置的命令(git remote -v / get-url / show、读 git config、git var -l):按这个目录生效的 git 配置* (系统、全局、仓库,含 include)核对它会打出的那些项里没有密钥。读别的配置文件(-f / --blob)的不核对。*/-async function configReadProvesSafe(read: GitRead): Promise<boolean> {+async function configReadProvesSafe(read: GitRead, deadline: number): Promise<boolean> {if (read.sub === 'remote') {const actionIndex = read.args.findIndex((arg) => !arg.startsWith('-'));if (read.args[actionIndex] === 'show' && read.args[actionIndex + 1] !== '-n') return false;@@ -468,8 +469,10 @@ async function configReadProvesSafe(read: GitRead): Promise<boolean> {return name.startsWith('--') && name.length > 2 && configSources.some((option) => option.startsWith(name));})) return false;const cwd = await fsp.realpath(read.cwd);+ const remaining = deadline - Date.now();+ if (remaining <= 0) return false;const key = requestedConfigKey(read);- const entries = (await git(['config', '--list', '-z'], cwd)).split('\0').filter(Boolean);+ const entries = (await git(['config', '--list', '-z'], cwd, { timeoutMs: remaining })).split('\0').filter(Boolean);return !entries.some((entry) => {const newline = entry.indexOf('\n');const name = newline < 0 ? entry : entry.slice(0, newline);@@ -482,7 +485,7 @@ async function configReadProvesSafe(read: GitRead): Promise<boolean> {}async function diffHelpersCannotRun(read: GitRead, cwd: string, timeoutMs: number): Promise<boolean> {- if (!CONTENT_SUBCOMMANDS.has(read.sub)) return true;+ if (!CONTENT_SUBCOMMANDS.has(read.sub) && !read.metadataOnly) return true;const disabled = new Set<string>();for (const arg of read.args) {if (arg !== '--no-textconv' && arg !== '--no-ext-diff') break;@@ -494,8 +497,9 @@ async function diffHelpersCannotRun(read: GitRead, cwd: string, timeoutMs: numbeconst entries = (await git(['config', '--list', '-z'], cwd, { timeoutMs })).split('\0');return !entries.some((entry) => {const newline = entry.indexOf('\n');+ const key = newline < 0 ? entry : entry.slice(0, newline);+ if (key.toLowerCase() === 'core.fsmonitor') return true;if (newline < 0 || !entry.slice(newline + 1).trim()) return false;- const key = entry.slice(0, newline);return /^filter\..+\.(?:clean|process)$/i.test(key)|| (textconvEnabled && /^diff\..+\.textconv$/i.test(key))|| (externalDiffEnabled && (/^diff\..+\.command$/i.test(key) || key.toLowerCase() === 'diff.external'));@@ -532,6 +536,7 @@ export class GitCredentialHistory {/** 这些 git 调用(credentials.ts shareCredentialGitReads 的结果)在本机核实后都读不到、打不出凭证。 */async provesSafe(command: string, reads: readonly GitRead[], signal?: AbortSignal): Promise<boolean> {+ const deadline = Date.now() + Math.max(0, this.opts.waitMs ?? GIT_CREDENTIAL_WAIT_MS);if (reads.length === 0 || GIT_ENV_ASSIGNMENT.test(command) || GIT_CONFIG_ENV_ASSIGNMENT.test(command)) return false;if (['BASH_ENV', 'ENV', 'ZDOTDIR'].some((key) => process.env[key] !== undefined)|| Object.keys(process.env).some((key) => key.startsWith('BASH_FUNC_'))) return false;@@ -542,23 +547,47 @@ export class GitCredentialHistory {// segment may change Git state, its result can become stale before the later read;// keep the credential confirmation in that case instead of granting an exemption.if (reads.some((read) => read.priorSegmentsMayMutate)) return false;- if (signal?.aborted || !(await shellStartupAllowsGitProbe(this.opts.waitMs ?? GIT_CREDENTIAL_WAIT_MS).catch(() => false))) {+ if (signal?.aborted || deadline <= Date.now()) return false;+ let timer: NodeJS.Timeout | undefined;+ let onAbort: (() => void) | undefined;+ const stopped = new Promise<boolean>((resolve) => {+ timer = setTimeout(() => resolve(false), Math.max(0, deadline - Date.now()));+ onAbort = () => resolve(false);+ signal?.addEventListener('abort', onAbort, { once: true });+ });+ try {+ return await Promise.race([this.readsProveSafe(reads, deadline, signal).catch(() => false), stopped]);+ } finally {+ if (timer) clearTimeout(timer);+ if (onAbort) signal?.removeEventListener('abort', onAbort);+ }+ }++ private async readsProveSafe(reads: readonly GitRead[], deadline: number, signal?: AbortSignal): Promise<boolean> {+ if (signal?.aborted || deadline <= Date.now()+ || !(await shellStartupAllowsGitProbe(deadline - Date.now()).catch(() => false))) {return false;}for (const read of reads) {- const check = CONFIG_SUBCOMMANDS.has(read.sub) ? configReadProvesSafe(read) : this.readProvesSafe(read, signal);- if (signal?.aborted || !(await check.catch(() => false))) return false;+ if (signal?.aborted || deadline <= Date.now()) return false;+ const check = CONFIG_SUBCOMMANDS.has(read.sub)+ ? configReadProvesSafe(read, deadline) : this.readProvesSafe(read, deadline, signal);+ const safe = await check.catch(() => false);+ if (signal?.aborted || deadline <= Date.now() || !safe) return false;}return true;}- private async readProvesSafe(read: GitRead, signal?: AbortSignal): Promise<boolean> {- const deadline = Date.now() + (this.opts.waitMs ?? GIT_CREDENTIAL_WAIT_MS);- if (!read.cwd || !CONTENT_SUBCOMMANDS.has(read.sub)) return false;+ private async readProvesSafe(read: GitRead, deadline: number, signal?: AbortSignal): Promise<boolean> {+ if (!read.cwd || (!CONTENT_SUBCOMMANDS.has(read.sub) && !read.metadataOnly)) return false;if (read.args.some((arg) => /[$`]/.test(arg) || UNCOVERED_OPTION.test(arg) || PSEUDO_REF.test(arg))) return false;const cwd = await fsp.realpath(read.cwd);if (pathspecIsTooComplexForRead(read)) return false;- const [topLine, commonLine] = (await git(['rev-parse', '--show-toplevel', '--git-common-dir'], cwd)).split(/\r?\n/);+ const rootTimeout = deadline - Date.now();+ if (rootTimeout <= 0 || signal?.aborted) return false;+ const [topLine, commonLine] = (await git(['rev-parse', '--show-toplevel', '--git-common-dir'], cwd, {+ timeoutMs: rootTimeout,+ })).split(/\r?\n/);if (!topLine || !commonLine) return false;const top = path.resolve(topLine);const commonDir = path.resolve(cwd, commonLine);@@ -571,12 +600,15 @@ export class GitCredentialHistory {if (replacements.trim()) return false;const helperTimeout = deadline - Date.now();if (helperTimeout <= 0 || !(await diffHelpersCannotRun(read, cwd, helperTimeout))) return false;+ if (read.metadataOnly) return true;// 指向仓库外的文件时 git diff 不经仓库、直接比较文件。if (read.sub === 'diff' && read.args.some((arg) => !arg.startsWith('-') && isOutside(top, path.resolve(cwd, arg)))) {return false;}if (await exists(path.join(commonDir, 'modules'))) return false;- const index = await indexCredentials(top);+ const indexTimeout = deadline - Date.now();+ if (indexTimeout <= 0 || signal?.aborted) return false;+ const index = await indexCredentials(top, indexTimeout);if (!index) return false;const history = await this.waitForHistory(top, commonDir, deadline, signal);if (history) {diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex fd3992057d..48c3d68799 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -302,7 +302,11 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):stash 与 reflog 的历史和暂存区里从没有凭证类文件;或命令用 `--` 限定的路径碰不到这些文件;或(`git diff` / `git show` / `git log`)按原命令只列出会显示的文件,其中没有凭证类文件。认不出 git在哪个仓库里跑、仓库带子模块、比较仓库外的文件、核实超过 8 秒,都照旧弹卡;仓库的扫描结果留在- 内存里给后面的命令用。指定的对象必须能解析为提交且已在扫描范围内,否则改按实际显示的文件+ 内存里给后面的命令用。+ 核实预算由整条命令共用:shell 启动状态、目录、所有内容与配置命令段共享同一 8 秒期限,+ 本次查询子进程只使用剩余时间;文件状态检查不返回、取消或超过总期限时失败关闭,先弹确认。+ 已开始的历史后台扫描仍按既有缓存流程继续,不影响确认卡及时出现;+ 指定的对象必须能解析为提交且已在扫描范围内,否则改按实际显示的文件核对;无法证明为提交的底层对象(如 `git show <blob-id>`,含 `-s` / `--name-only` 等输出选项及隐式`HEAD`)保留确认,不能按干净历史放行。所有历史与内容探针禁用 replacement refs;仓库有 `refs/replace` 或宿主设置了 `GIT_REPLACE_REF_BASE`@@ -328,6 +332,9 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):Git 内容读取前还要按当次生效的配置核实 `filter.<driver>.clean` / `.process` 均无非空命令;即使指定 `--no-textconv` / `--no-ext-diff` 也不能略过过滤器核实。发现配置就保留凭证确认,探针不运行这些过滤器;移除过滤器后仍可按原有路径核实豁免,不沿用旧配置结论;+ 配置中出现 `core.fsmonitor` 时同样保留确认(不假设不同 Git 版本对布尔取值的解释一致),+ 在读取 index 前拦下它,避免 hook 经 stderr 带出凭证。`git status`、`git ls-files`、只列文件名的+ diff 等静态只读调用也要核实运行期 helper;无 helper 时仍可豁免,不改变本机任务默认判定;`--bare` 这类改变仓库上下文的选项、前面的命令段可能修改 Git 状态、运行环境,或写法认不出时也不能豁免。已知会读取 Git 内容的调用遇到未识别的全局选项、或不能归为静态只读命令时(如 `--ext-diff` /`--textconv`)也保留凭证确认,不能因为未进入核实路径就当成不读取凭证;本机默认判定仍不变。diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.tsindex 1e3a873fdc..56cd3e5e2b 100644--- a/packages/maker-core/src/agents/shared/auto-review.test.ts+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts@@ -4888,6 +4888,16 @@ describe('shellCommandReadsCredentials — 分享任务的附加选项', () => {})).toBe(true);});+ it('checks runtime helpers for sharing Git metadata without changing local decisions', () => {+ for (const command of ['git status', 'git ls-files', 'git diff --name-only', 'git log --oneline']) {+ expect(shellCommandReadsCredentials(command, roots), command).toBe(false);+ const collect = vi.fn(() => true);+ expect(shellCommandReadsCredentials(command, roots, { gitContentRead: collect }), command).toBe(false);+ expect(collect, command).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ metadataOnly: true }));+ expect(shellCommandReadsCredentials(command, roots, { gitContentRead: () => false }), command).toBe(true);+ }+ });+it('marks sharing Git probes unsafe when --bare changes the repository context', () => {for (const subcommand of ['show HEAD', 'config --list']) {const command = 'git --bare ' + subcommand;@@ -4940,8 +4950,10 @@ describe('shellCommandReadsCredentials — 分享任务的附加选项', () => {expect(collect, command).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sub: 'show' }));}const collect = vi.fn(() => false);- expect(shellCommandReadsCredentials('git show -s HEAD:src/app.ts', roots, { gitContentRead: collect })).toBe(false);- expect(collect).not.toHaveBeenCalled();+ expect(shellCommandReadsCredentials('git show -s HEAD:src/app.ts', roots, { gitContentRead: collect })).toBe(true);+ expect(collect).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ metadataOnly: true }));+ expect(shellCommandReadsCredentials('git show -s HEAD:src/app.ts', roots, { gitContentRead: () => true })).toBe(false);+ expect(shellCommandReadsCredentials('git show -s HEAD:src/app.ts', roots)).toBe(false);});it('gitContentRead:git 查看内容先问调用方,并带上 git 实际运行的目录', () => {diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex 49100f7f15..1e99246df2 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -3240,6 +3240,7 @@ export type GitRead = {/** git 实际运行的目录(已跟随前面各段的 cd 与 -C);认不出时为 undefined。 */cwd?: string;usesInheritedGitRuntime?: boolean;+ metadataOnly?: boolean;/*** 当前 git 读取前是否有无法证明只读的 shell 段。前置段可能先修改工作区或索引,* 因而使执行器在命令运行前取得的凭证扫描结果过时;调用方应拒绝凭证豁免。@@ -6421,16 +6422,19 @@ function shellCommandReadsDotenv(const probesShowObject = opts.gitContentRead !== undefined && invocation.sub === 'show'&& !gitShowHasOnlySafeObjectPaths(invocation.args);const readsContent = gitContentReadWithoutPath(invocation.sub, invocation.args) || probesShowObject;- const checksContent = readsContent || (sharesGitCredentialChecks+ const probesRuntime = opts.gitContentRead !== undefined+ && /^(?:diff|show|log|whatchanged|grep|cat-file|status|blame|ls-files|check-ignore)$/.test(invocation.sub);+ const checksContent = readsContent || probesRuntime || (sharesGitCredentialChecks&& /^(?:diff|show|log|whatchanged|grep|cat-file|status|blame)$/.test(invocation.sub));const canProbe = checksContent && classifyGit(tokens, segment, workspaceRoots, opts) === 'auto-approve';if (checksContent && sharesGitCredentialChecks && !canProbe) return true;- if (readsContent && canProbe && !opts.gitContentRead?.({+ if ((readsContent || probesRuntime) && canProbe && !opts.gitContentRead?.({sub: invocation.sub,args: invocation.args,cwd: configOverride ? undefined : gitInvocationCwd(tokens, segmentCwds[segmentIndex]),priorSegmentsMayMutate: priorMutation,usesInheritedGitRuntime: rawTokens[0] === 'git',+ ...(!readsContent ? { metadataOnly: true } : {}),})) return true;continue;}