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(provider-sharing): guard zsh startup before Git probes

MagicLizi911298d7cf6e
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.ts
index 0a38b7e3ef..bb1dd5f469 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
@@ -4,6 +4,7 @@
*/
import { execFileSync, spawnSync } from 'node:child_process';
import fs from 'node:fs';
+import fsPromises from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -13,6 +14,7 @@ import { shareCredentialGitReads } from '../../credentials';
import { RemoteExecutor } from '../executor';
import { ExecutorGate, type ExecutorAction } from '../gate';
import { GitCredentialHistory } from '../gitCredentials';
+import * as executorShell from '../shell';
import { ExecutorWorkspace } from '../workspace';
// Windows 上每次 spawn git 要数百毫秒。
@@ -71,6 +73,7 @@ const savedEnv = Object.fromEntries(GIT_ENV_KEYS.map((key) => [key, process.env[
beforeEach(() => {
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'share-git-credentials-')));
+ vi.stubEnv('SHELL', '/bin/bash');
vi.stubEnv('PATH', (process.env.PATH ?? '').split(path.delimiter).map((entry) => path.resolve(entry)).join(path.delimiter));
// 临时目录的上层也可能是 git 仓库(比如整个用户目录):不往上找。开发机自己的全局与系统 git 配置
// 也不读,免得里面的令牌影响结果。
@@ -88,6 +91,7 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.restoreAllMocks();
vi.unstubAllEnvs();
for (const key of GIT_ENV_KEYS) {
if (savedEnv[key] === undefined) delete process.env[key];
@@ -670,6 +674,50 @@ describe('GitCredentialHistory', () => {
expect(await provesSafe(history, 'git diff')).toBe(true);
});
+ it('keeps confirmation for zsh default and compiled startup files without ZDOTDIR', async () => {
+ const history = new GitCredentialHistory();
+ const home = path.join(root, 'home');
+ const credentialFile = path.join(root, '.env');
+ const startupFile = path.join(home, '.zshenv');
+ fs.mkdirSync(home);
+ fs.writeFileSync(credentialFile, 'PRIVATE_FIXTURE=zsh-startup\n');
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('ZDOTDIR', undefined);
+ expect(await provesSafe(history, 'git diff')).toBe(true);
+ fs.writeFileSync(startupFile, 'git() { cat ' + JSON.stringify(credentialFile.split(path.sep).join('/')) + '; }\n');
+ const shell = vi.spyOn(executorShell, 'resolveExecutorShell').mockReturnValue({
+ file: '/bin/zsh', dialect: 'bash', scriptName: 'script.sh', args: ['script.sh'],
+ });
+ if (process.platform !== 'win32' && fs.existsSync('/bin/zsh')) {
+ expect(execFileSync('/bin/zsh', ['-c', 'git diff'], { cwd: repo, encoding: 'utf8' }))
+ .toContain('PRIVATE_FIXTURE=zsh-startup');
+ }
+ for (const command of ['git diff', 'git config --list']) {
+ expect(await provesSafe(history, command), command).toBe(false);
+ await requiresCredentialConfirmation(history, command);
+ }
+ fs.renameSync(startupFile, startupFile + '.zwc');
+ expect(await provesSafe(history, 'git diff')).toBe(false);
+ fs.unlinkSync(startupFile + '.zwc');
+ const globalStartups = ['/etc/zshenv', '/etc/zsh/zshenv'].flatMap((file) => [file, file + '.zwc']);
+ if (!globalStartups.some((file) => fs.existsSync(file))) {
+ expect(await provesSafe(history, 'git diff')).toBe(true);
+ }
+ const stats = vi.spyOn(fsPromises, 'lstat').mockRejectedValue(Object.assign(new Error('unavailable'), { code: 'EACCES' }));
+ expect(await provesSafe(history, 'git diff')).toBe(false);
+ stats.mockImplementation(() => new Promise<never>(() => {}));
+ const bounded = new GitCredentialHistory({ waitMs: 10 });
+ const started = Date.now();
+ expect(await provesSafe(bounded, 'git diff')).toBe(false);
+ expect(Date.now() - started).toBeLessThan(1_000);
+ await requiresCredentialConfirmation(bounded, 'git config --list');
+ stats.mockRestore();
+ shell.mockReturnValue({ file: '/custom/bin/zsh', dialect: 'bash', scriptName: 'script.sh', args: ['script.sh'] });
+ expect(await provesSafe(history, 'git diff')).toBe(false);
+ shell.mockRestore();
+ expect(await provesSafe(history, 'git diff')).toBe(true);
+ });
+
it('keeps asking where the scan does not reach', async () => {
const history = new GitCredentialHistory();
const outside = path.join(root, 'outside');
diff --git a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
index 3ec40b062f..9c58888df4 100644
--- a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
@@ -19,6 +19,7 @@ import path from 'node:path';
import type { GitRead } from '@cindy/maker-core';
import { isShareCredentialPath, textSpellsOutSecret } from '../credentials';
+import { resolveExecutorShell } from './shell';
/** 核实一条命令最多等这么久,超过就先弹卡;仓库扫描在后台继续,结果留给后面的命令。 */
const GIT_CREDENTIAL_WAIT_MS = 8_000;
@@ -501,6 +502,29 @@ async function diffHelpersCannotRun(read: GitRead, cwd: string, timeoutMs: numbe
});
}
+async function shellStartupAllowsGitProbe(waitMs: number): Promise<boolean> {
+ const shell = resolveExecutorShell();
+ if (path.basename(shell.file) !== 'zsh') return true;
+ if (!['/bin/zsh', '/usr/bin/zsh'].includes(shell.file)) return false;
+ const home = process.env.HOME;
+ if (!home || !path.isAbsolute(home)) return false;
+ const startupFiles = ['/etc/zshenv', '/etc/zsh/zshenv', path.join(home, '.zshenv')]
+ .flatMap((file) => [file, file + '.zwc']);
+ const checks = Promise.all(startupFiles.map((file) => fsp.lstat(file).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => error.code !== 'ENOENT',
+ ))).then((present) => !present.some(Boolean));
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ checks,
+ new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), Math.max(0, waitMs)); }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
export class GitCredentialHistory {
private readonly repos = new Map<string, RepoEntry>();
@@ -518,6 +542,9 @@ 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))) {
+ 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;
diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.md
index 98d5d2efe1..f4e59cb70e 100644
--- a/docs/product-rules/provider-sharing.md
+++ b/docs/product-rules/provider-sharing.md
@@ -319,6 +319,9 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):
环境变量的赋值、移除或清空(含 PATH、加载器与 Git 配置来源)都无法与探针证明一致,照旧弹卡;
宿主继承了 `BASH_ENV` / `ENV` / `ZDOTDIR` 或导出的 Bash 函数时,同样无法证明 shell 启动后仍调用
探针使用的 Git,不授予内容与配置读取豁免;
+ 实际执行器选择 zsh 时,即使没有 `ZDOTDIR`,也要核实系统级 `zshenv` 与 `HOME/.zshenv`(含各自
+ `.zwc` 缓存)均不存在;发现文件、核实文件状态失败或超时、HOME 不明确、或自定义 zsh 的启动目录
+ 无法核实,都保留确认。此核实每次执行前重做,不读取或运行启动脚本,不沿用仓库历史的缓存;
`--bare` 这类改变仓库上下文的选项、前面的命令段可能修改 Git 状态、运行环境,或写法认不出时也不能豁免。
已知会读取 Git 内容的调用遇到未识别的全局选项、或不能归为静态只读命令时(如 `--ext-diff` /
`--textconv`)也保留凭证确认,不能因为未进入核实路径就当成不读取凭证;本机默认判定仍不变。