Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(provider-sharing): 分享任务里少弹凭证确认,命令里写着密钥时照样确认
MagicLizic23698200b1d
diff --git a/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.tsindex 6e23550b1e..8bc275967a 100644--- a/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/credentials.test.ts@@ -1,10 +1,12 @@/*** 供应商分享的受邀者任务里「凭证类」的判定:沿用本机凭证规则,但配置目录里的说明类内容(Skill、- * 子代理、命令、规则、个人说明)不算凭证。+ * 子代理、命令、规则、个人说明)、.env 模板与公钥不算凭证,只按源码扩展名缩小范围的搜索不算读取凭证,+ * git 查看内容交给执行器在本机核实。*/+import { isSensitiveCredentialPath, shellCommandReadsCredentials } from '@cindy/maker-core';import { describe, expect, it } from 'vitest';-import { isShareCredentialCommand, isShareCredentialPath } from '../credentials';+import { isShareCredentialCommand, isShareCredentialPath, shareCredentialGitReads } from '../credentials';describe('isShareCredentialPath', () => {it('keeps the credential rules of local tasks', () => {@@ -76,4 +78,124 @@ describe('isShareCredentialCommand', () => {// 含 `..` 时不放宽。expect(isShareCredentialCommand('cat ~/.claude/skills/../settings.json', roots)).toBe(true);});++ it('lets searches narrowed to source and doc extensions run', () => {+ for (const command of [+ "rg -n 'API_KEY' --glob '*.ts'",+ "rg -g '*.{ts,tsx}' token src",+ "grep -rn --include='*.md' token .",+ ]) {+ expect(isShareCredentialCommand(command, roots), command).toBe(false);+ }+ for (const command of ["rg -g '*.json' KEY", "rg -g '.env.ts' KEY", 'grep -rn KEY .']) {+ expect(isShareCredentialCommand(command, roots), command).toBe(true);+ }+ });+});++describe('templates and public keys', () => {+ const roots = ['/repo'];++ it('are not credentials, unless they sit in a credential folder', () => {+ for (const target of [+ '/repo/.env.example',+ '/repo/apps/web/.env.sample',+ '/repo/.ENV.TEMPLATE',+ '/repo/deploy/id_rsa.pub',+ '/repo/keys/server.key.pub',+ 'C:\\repo\\id_ed25519.pub',+ ]) {+ expect(isShareCredentialPath(target), target).toBe(false);+ // 本机规则不变。+ expect(isSensitiveCredentialPath(target), target).toBe(true);+ }+ for (const target of [+ '/home/me/.ssh/id_rsa.pub',+ 'C:\\Users\\me\\.ssh\\id_rsa.pub',+ '/repo/.env.example.local',+ '/repo/deploy/id_rsa.pub.bak',+ '/repo/.env',+ '/repo/deploy/id_rsa',+ ]) {+ expect(isShareCredentialPath(target), target).toBe(true);+ }+ });++ it('can be read by commands', () => {+ for (const command of ['cat .env.example', 'head -5 apps/web/.env.sample', 'cat deploy/id_rsa.pub', "rg -g '.env.example' KEY"]) {+ expect(isShareCredentialCommand(command, roots), command).toBe(false);+ expect(shellCommandReadsCredentials(command, roots), command).toBe(true);+ }+ for (const command of ['cat ~/.ssh/id_rsa.pub', 'cat .env.example .env', 'cat id_rsa.pub id_rsa']) {+ expect(isShareCredentialCommand(command, roots), command).toBe(true);+ }+ });+});++describe('shareCredentialGitReads', () => {+ const roots = ['/repo'];++ it('hands over git commands that need confirmation only because they show content', () => {+ expect(shareCredentialGitReads('git log -p -- src/app.ts', roots, { cwd: '/repo' })).toMatchObject([+ { sub: 'log', args: ['-p', '--', 'src/app.ts'] },+ ]);+ expect(shareCredentialGitReads('git diff && git show HEAD', roots, { cwd: '/repo' })).toHaveLength(2);+ // 还有别的理由,或本来就不用确认:不交给核实。+ 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();+ });++ it('hands over git commands that print the git config, but not ones that print saved logins', () => {+ for (const command of ['git remote -v', 'git config --list', 'git config --get remote.origin.url']) {+ expect(isShareCredentialCommand(command, roots, { cwd: '/repo' }), command).toBe(true);+ expect(shareCredentialGitReads(command, roots, { cwd: '/repo' }), command).toHaveLength(1);+ }+ for (const command of ['git credential fill', 'git credential-osxkeychain get', 'git remote -v && cat .env']) {+ expect(isShareCredentialCommand(command, roots, { cwd: '/repo' }), command).toBe(true);+ expect(shareCredentialGitReads(command, roots, { cwd: '/repo' }), command).toBeNull();+ }+ });+});++describe('secrets written in the command', () => {+ const roots = ['/repo'];+ const token = 'ghp_0123456789abcdefghijABCDEFGHIJ012345';++ it('need confirmation, only in shared provider tasks', () => {+ for (const command of [+ `git remote set-url origin https://me:${token}@github.com/a/b.git`,+ 'git clone https://oauth2:[email protected]/a/b.git',+ `git push https://${token}@github.com/a/b.git`,+ `git -c http.extraHeader="Authorization: Bearer ${token}" pull`,+ 'git log -S AKIAIOSFODNN7EXAMPLE',+ `curl -H "Authorization: token ${token}" https://api.github.com/user`,+ 'psql postgres://app:[email protected]/app',+ // <提交>:<路径> 写出以点开头的凭证类文件,scp 式地址同理。+ 'git show HEAD:.aws/credentials',+ 'git show main:.npmrc',+ 'scp build-host:.npmrc .',+ ]) {+ expect(isShareCredentialCommand(command, roots), command).toBe(true);+ expect(shareCredentialGitReads(command, roots), command).toBeNull();+ // 本机规则不变。+ expect(shellCommandReadsCredentials(command, roots), command).toBe(false);+ }+ });++ it('leave ordinary addresses and words alone', () => {+ for (const command of [+ 'git clone [email protected]:a/b.git',+ '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);+ }+ });});diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex c7bfed7517..8030243d37 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -22,6 +22,7 @@ import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/provimport { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';import type { PdfTextExtractor } from '../executor/files';import { ExecutorGate, executorGateModeFor, type ExecutorAction } from '../executor/gate';+import { GitCredentialHistory } from '../executor/gitCredentials';import type { GuardedFetch } from '../executor/webFetch';import { ExecutorWorkspace } from '../executor/workspace';import type {@@ -181,6 +182,9 @@ export function shadowAliases(return aliases;}+/** 供应商分享的受邀者任务共用:同一个仓库的扫描结果留给后面的命令与任务。 */+const sharedGitCredentials = new GitCredentialHistory();+/** 凭证类操作的确认卡:用与 Agent 自带工具同名的工具显示本机路径或命令。 */export function credentialConfirmation(action: ExecutorAction, description: string): LocalConfirmation {const base = {@@ -236,6 +240,7 @@ export async function startRemoteAgentSession(? {confirm: async (action: ExecutorAction) =>controller?.confirm(credentialConfirmation(action, credentialConsent.description)) ?? false,+ gitCredentials: sharedGitCredentials,}: {}),});diff --git a/apps/desktop/src/main/remote-agent/credentials.ts b/apps/desktop/src/main/remote-agent/credentials.tsindex 95dd6bb825..5f46a84bf0 100644--- a/apps/desktop/src/main/remote-agent/credentials.ts+++ b/apps/desktop/src/main/remote-agent/credentials.ts@@ -6,11 +6,24 @@* 可明确允许当前任务后续的凭证操作;关闭、重新打开任务或切换权限档后恢复确认* (docs/product-rules/provider-sharing.md §9 第 7 条)。*- * 规则沿用本机任务的凭证规则(isSensitiveCredentialPath),只有一处不同:Claude Code / Codex 配置目录里- * 的说明类内容(Skill、子代理、命令、规则、个人说明)不算凭证。本机规则把整个配置目录算作敏感,是为了- * 保护里面的登录与设置,不是这些说明文字;不放开的话,个人 Skill 的每个参考文件都要确认。+ * 规则沿用本机任务的凭证规则(isSensitiveCredentialPath),以下几处不同,都只在这里生效,本机任务不变:+ * - Claude Code / Codex 配置目录里的说明类内容(Skill、子代理、命令、规则、个人说明)不算凭证。本机规则+ * 把整个配置目录算作敏感,是为了保护里面的登录与设置,不是这些说明文字;不放开的话,个人 Skill 的+ * 每个参考文件都要确认;+ * - 按惯例不含密钥的 .env 模板(.env.example / .env.sample / .env.template)与公钥(*.pub)不算凭证,+ * 所在目录本身是凭证目录(~/.ssh 等)时照旧算;+ * - rg -g、grep --include 这类只选中源码与文档扩展名的搜索不算读取凭证;+ * - git 查看内容又没有限定到具体文件的命令、会打出 git 配置的命令交给执行器在本机核实+ * (executor/gitCredentials.ts);+ * - 再收紧:命令里直接写着密钥(带密码的地址、令牌、私钥)、用 `<提交>:<路径>` 写出凭证类文件、+ * git credential fill 这类打出保存的凭证的命令也要确认。*/-import { isSensitiveCredentialPath, shellCommandReadsCredentials } from '@cindy/maker-core';+import {+ isSensitiveCredentialPath,+ shellCommandReadsCredentials,+ type CredentialCommandOptions,+ type GitRead,+} from '@cindy/maker-core';/** 配置目录里的说明类子路径:`/.claude/skills/…`、`/.codex/AGENTS.md` 等(两种分隔符都认)。 */const CONFIG_INSTRUCTION_SEGMENT =@@ -22,23 +35,106 @@ 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');+/**+ * 按惯例不含密钥的文件名(整个文件名):.env 模板与公钥。前面是开头、路径分隔符或 shell 分隔符,后面是+ * 结尾或 shell 分隔符;`.env.example.local`、`id_rsa.pub.bak` 这类不算。+ */+const NON_SECRET_FILE_NAME =+ /(^|[\\/\s'"=:<>|;&(])(?:\.env\.(?:example|sample|template)|[^\\/\s'"=:<>|;&()]*\.pub)(?=$|[\s'"|;&()<>])/gi;++type ShareCommandOptions = Pick<CredentialCommandOptions, 'cwd' | 'platform'>;++/**+ * 换掉配置目录里说明类子路径的目录名,和按惯例不含密钥的文件名,让本机凭证规则不再因为它们命中;+ * 所在目录的名字不动(~/.ssh/id_rsa.pub 照旧因为 .ssh 命中)。+ */+function shareCredentialText(text: string): string {+ const withoutInstructionDirs = PARENT_SEGMENT.test(text) ? text : text.replace(CONFIG_INSTRUCTION_SEGMENT, '$1_$2');+ return withoutInstructionDirs.replace(NON_SECRET_FILE_NAME, '$1_');+}++/**+ * 命令里直接写着的密钥:带密码的地址(`https://用户:密码@`)、当用户名放进 http 地址的长令牌、Authorization+ * 头的取值、常见服务的令牌格式与私钥。用 `$变量` 写的已按令牌类环境变量算。+ */+const LITERAL_SECRET_PATTERNS: readonly RegExp[] = [+ /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@'"$]+:[^\s/@'"$]+@/i,+ /\bhttps?:\/\/[A-Za-z0-9_-]{20,}@/i,+ /\bauthorization:\s*(?:bearer|basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/i,+ /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|xox[abposr]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{36}|AIza[0-9A-Za-z_-]{35}|(?:AKIA|ASIA)[0-9A-Z]{16})\b/,+ /\bsk-(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{32,}/,+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,+];++/**+ * git 的 `<提交>:<路径>` 写法(含 scp 式地址 `host:路径`):路径紧跟冒号,本机规则认不出 `HEAD:.aws/credentials`、+ * `HEAD:.npmrc` 这类以点开头的名字,单独取出路径再判。+ */+const COLON_PATH = /[\w.@{}~^/-]:([^\s'"|;&<>()]+)/g;++/** 文本里直接写着密钥(命令、git 配置项等)。 */+export function textSpellsOutSecret(text: string): boolean {+ return LITERAL_SECRET_PATTERNS.some((pattern) => pattern.test(text));+}++/** 命令文本里直接写着密钥,或用 `<提交>:<路径>` 写出了凭证类文件。 */+function commandSpellsOutSecret(command: string): boolean {+ if (textSpellsOutSecret(command)) return true;+ for (const match of command.matchAll(COLON_PATH)) {+ if (isShareCredentialPath(`/${match[1]}`)) return true;+ }+ return false;}/** 路径是否为凭证类文件(调用方对链接目标的真实路径也要各判一次)。 */export function isShareCredentialPath(target: string): boolean {if (typeof target !== 'string' || !target) return false;- return isSensitiveCredentialPath(withoutConfigInstructionDirs(target)) || LOGIN_FILE.test(target);+ return isSensitiveCredentialPath(shareCredentialText(target)) || LOGIN_FILE.test(target);}-/** 命令是否读取或打出凭证(只看命令文本:脚本文件里读的、编码后再解开的认不出来)。 */+/** 打出保存的登录凭证(git credential fill 与 credential-* 助手):一律要确认,不交给核实。 */+function printsStoredCredentials(read: GitRead): boolean {+ return read.sub === 'credential' || read.sub.startsWith('credential-');+}++/**+ * 命令是否读取、打出或直接写着凭证(只看命令文本:脚本文件里读的、编码后再解开的认不出来)。会打出 git+ * 配置的命令(git remote -v、git config --list 等)也算,配置里没有密钥时由执行器核实后放行。+ */export function isShareCredentialCommand(command: string,workspaceRoots: string[],- opts: { cwd?: string; platform?: NodeJS.Platform } = {},+ opts: ShareCommandOptions = {},): boolean {- return shellCommandReadsCredentials(withoutConfigInstructionDirs(command), workspaceRoots, opts);+ return commandSpellsOutSecret(command)+ || shellCommandReadsCredentials(shareCredentialText(command), workspaceRoots, {+ ...opts,+ sourceFileSelectors: true,+ gitConfigRead: () => false,+ });+}++/**+ * 命令要按凭证确认、但只是因为 git 查看内容又没有限定到具体文件(git diff、git log -p 等),或会打出 git+ * 配置(git remote -v、git config --list 等)时,返回这些 git 调用,由执行器在本机核实;还有别的原因+ * (包括 git credential fill 这类直接打出保存的凭证)、或本来就不用确认时返回 null。+ */+export function shareCredentialGitReads(+ command: string,+ workspaceRoots: string[],+ opts: ShareCommandOptions = {},+): GitRead[] | null {+ if (commandSpellsOutSecret(command)) return null;+ const reads: GitRead[] = [];+ const collect = (read: GitRead) => {+ reads.push(read);+ return true;+ };+ const needsConsent = shellCommandReadsCredentials(shareCredentialText(command), workspaceRoots, {+ ...opts,+ sourceFileSelectors: true,+ gitContentRead: collect,+ gitConfigRead: (read) => !printsStoredCredentials(read) && collect(read),+ });+ return needsConsent || reads.length === 0 ? null : reads;}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 70e700c448..a42a050cc0 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@@ -8,6 +8,7 @@ import { handleExecMcpRequest } from '../ccMcp';import { RemoteExecutor, type ExecutorConfirmation } from '../executor';import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor, type ExecutorAction } from '../gate';import type { PdfTextExtractor } from '../files';+import type { GitCredentialHistory } from '../gitCredentials';import { findWindowsGitBash, truncateOutput } from '../shell';import type { GuardedFetch } from '../webFetch';import { ExecutorWorkspace } from '../workspace';@@ -581,6 +582,7 @@ describe('shared provider credentials', () => {function sharedExecutor(mode: ReturnType<typeof executorGateModeFor>,confirm?: (action: ExecutorAction) => Promise<ExecutorConfirmation>,+ gitCredentials?: GitCredentialHistory,) {const workspace = new ExecutorWorkspace({ workingDir: project });const gate = new ExecutorGate(workspace, mode, Date.now, { confirmCredentials: true });@@ -590,6 +592,7 @@ describe('shared provider credentials', () => {rgPath: RG,tempDir: path.join(root, 'tmp'),...(confirm ? { confirm } : {}),+ ...(gitCredentials ? { gitCredentials } : {}),});return { executor, gate, workspace };}@@ -780,6 +783,37 @@ describe('shared provider credentials', () => {}});+ it('lets git commands run without asking once this computer has checked they cannot show credentials', async () => {+ const asked: ExecutorAction[] = [];+ const checked: string[] = [];+ let safe = true;+ const gitCredentials = {+ provesSafe: async (command: string) => {+ checked.push(command);+ return safe;+ },+ } as unknown as GitCredentialHistory;+ const { executor, gate } = sharedExecutor('full', async (action) => {+ asked.push(action);+ return false;+ }, gitCredentials);+ const log: ExecutorAction = { kind: 'exec', command: 'git log -p', cwd: project };+ expect(gate.authorize(log).ok).toBe(false);+ expect(await executor.confirm(log)).toBe(true);+ expect(gate.authorize(log).ok).toBe(true);+ expect(asked).toEqual([]);+ // 核实不了时照旧问;命令还读别的凭证、或打出保存的凭证时不交给核实。+ safe = false;+ expect(await executor.confirm(log)).toBe(false);+ expect(asked).toEqual([log]);+ const withEnv: ExecutorAction = { kind: 'exec', command: 'git log -p && cat .env', cwd: project };+ const fill: ExecutorAction = { kind: 'exec', command: 'git credential fill', cwd: project };+ expect(await executor.confirm(withEnv)).toBe(false);+ expect(await executor.confirm(fill)).toBe(false);+ expect(asked).toEqual([log, withEnv, fill]);+ expect(checked).toEqual(['git log -p', 'git log -p']);+ });+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');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.tsnew file mode 100644index 0000000000..6b83b2ed7e--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts@@ -0,0 +1,251 @@+/**+ * 供应商分享的受邀者任务:git 查看内容的命令在本机核实仓库读不到凭证类文件时不弹卡(gitCredentials.ts)。+ * 用真实的 git 仓库验证扫描范围(历史、reflog、stash、暂存区)与各种照旧弹卡的情况。+ */+import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { shareCredentialGitReads } from '../../credentials';+import { GitCredentialHistory } from '../gitCredentials';++// Windows 上每次 spawn git 要数百毫秒。+vi.setConfig({ testTimeout: process.platform === 'win32' ? 120_000 : 60_000 });++let root: string;+let repo: string;++function git(...args: string[]): string {+ return execFileSync('git', args, { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });+}++function write(file: string, content = 'x\n'): void {+ fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true });+ fs.writeFileSync(path.join(repo, file), content);+}++function commit(message: string, ...files: string[]): void {+ for (const file of files) write(file);+ git('add', '-A');+ git('commit', '-q', '--no-gpg-sign', '-m', message);+}++/** 按分享任务的判定取出要核实的 git 调用,再交给本机核实。 */+async function provesSafe(history: GitCredentialHistory, command: string, cwd = repo): Promise<boolean> {+ const reads = shareCredentialGitReads(command, [repo], { cwd, platform: process.platform });+ expect(reads, command).not.toBeNull();+ return history.provesSafe(command, reads ?? []);+}++const GIT_ENV_KEYS = ['GIT_CEILING_DIRECTORIES', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM'] as const;+const savedEnv = Object.fromEntries(GIT_ENV_KEYS.map((key) => [key, process.env[key]]));++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'share-git-credentials-')));+ // 临时目录的上层也可能是 git 仓库(比如整个用户目录):不往上找。开发机自己的全局与系统 git 配置+ // 也不读,免得里面的令牌影响结果。+ process.env.GIT_CEILING_DIRECTORIES = root;+ process.env.GIT_CONFIG_GLOBAL = path.join(root, 'gitconfig');+ process.env.GIT_CONFIG_NOSYSTEM = '1';+ fs.writeFileSync(process.env.GIT_CONFIG_GLOBAL, '');+ repo = path.join(root, 'repo');+ fs.mkdirSync(repo);+ git('init', '-q');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 'XDT Test');+ git('config', 'core.autocrlf', 'false');+ commit('init', 'src/app.ts', 'README.md', '.env.example', 'deploy/id_rsa.pub');+});++afterEach(() => {+ for (const key of GIT_ENV_KEYS) {+ if (savedEnv[key] === undefined) delete process.env[key];+ else process.env[key] = savedEnv[key];+ }+ fs.rmSync(root, { recursive: true, force: true });+});++describe('GitCredentialHistory', () => {+ it('lets content commands run in a repository that never had credential files', async () => {+ const history = new GitCredentialHistory();+ commit('more', 'src/util.ts');+ write('src/app.ts', 'changed\n');+ for (const command of ['git diff', 'git log -p', 'git show HEAD', 'git grep -n x', 'git diff --cached', 'git log -p --all | head -50']) {+ expect(await provesSafe(history, command), command).toBe(true);+ }+ // 子目录里跑也是同一个仓库。+ expect(await provesSafe(history, 'git log -p', path.join(repo, 'src'))).toBe(true);+ });++ // git grep 只看扫描结果(不按会显示的文件再核对),用它验证扫描范围。+ it('finds credential files anywhere in history: deleted, only in the reflog, in a stash or staged', async () => {+ // 提交过又删掉。+ let history = new GitCredentialHistory();+ commit('add env', '.env');+ git('rm', '-q', '.env');+ git('commit', '-q', '--no-gpg-sign', '-m', 'drop env');+ expect(await provesSafe(history, 'git grep -n x')).toBe(false);++ // 只剩在 reflog 里。+ fs.rmSync(path.join(root, 'repo'), { recursive: true, force: true });+ fs.mkdirSync(repo);+ git('init', '-q');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 'XDT Test');+ commit('init', 'src/app.ts');+ history = new GitCredentialHistory();+ expect(await provesSafe(history, 'git grep -n x')).toBe(true);+ commit('key', 'certs/server.key');+ git('reset', '-q', '--hard', 'HEAD~1');+ expect(await provesSafe(history, 'git grep -n x')).toBe(false);++ // 在 stash 里。+ history = new GitCredentialHistory();+ git('reflog', 'expire', '--expire=now', '--all');+ git('gc', '-q', '--prune=now');+ expect(await provesSafe(history, 'git grep -n x')).toBe(true);+ write('.npmrc');+ git('add', '.npmrc');+ git('stash', '-q');+ expect(await provesSafe(history, 'git grep -n x')).toBe(false);++ // 只在暂存区。+ history = new GitCredentialHistory();+ git('stash', 'drop', '-q');+ git('reflog', 'expire', '--expire=now', '--all');+ git('gc', '-q', '--prune=now');+ expect(await provesSafe(history, 'git diff --cached')).toBe(true);+ write('.env.local');+ git('add', '.env.local');+ expect(await provesSafe(history, 'git diff --cached')).toBe(false);+ });++ it('lets commands limited to paths that never held credential files run', async () => {+ const history = new GitCredentialHistory();+ commit('fixtures', 'test/fixtures/server.key', 'src/lib/index.ts');+ for (const command of [+ 'git log -p -- src/app.ts',+ 'git log -p -- src',+ 'git diff HEAD~1 -- src/lib README.md',+ "git grep -n x -- '*.ts'",+ 'git show HEAD -- src',+ // 没写 `--` 时按会显示的文件核对。+ 'git log -p src/app.ts',+ ]) {+ expect(await provesSafe(history, command), command).toBe(true);+ }+ for (const command of [+ 'git log -p',+ 'git log -p -- .',+ 'git log -p -- test',+ "git grep -n x -- '*'",+ "git grep -n x -- 't*/fixtures'",+ 'git show HEAD:src/app.ts -- src',+ ]) {+ expect(await provesSafe(history, command), command).toBe(false);+ }+ // 在子目录里跑时,路径按子目录解释。+ expect(await provesSafe(history, 'git log -p -- lib', path.join(repo, 'src'))).toBe(true);+ expect(await provesSafe(history, 'git log -p -- fixtures', path.join(repo, 'test'))).toBe(false);+ });++ it('checks the files a command would show when the repository has credential files', async () => {+ const history = new GitCredentialHistory();+ // 像多数 pnpm / npm 项目一样提交了 .npmrc。+ commit('npmrc', '.npmrc');+ commit('code', 'src/util.ts');+ write('src/app.ts', 'changed\n');+ for (const command of [+ 'git diff',+ 'git diff HEAD',+ 'git diff HEAD~1 HEAD',+ 'git show HEAD',+ 'git log -p -1',+ 'git log -p src/app.ts',+ 'git log -p -n 1 src/app.ts',+ 'git log -p --author=XDT -- src',+ ]) {+ expect(await provesSafe(history, command), command).toBe(true);+ }+ for (const command of [+ 'git show HEAD~1',+ 'git log -p -2',+ 'git log -p',+ 'git log -p --graph -1',+ 'git diff --stat -p',+ // 选项的取值恰好是个文件名:插入的选项可能被它当成取值,不这样核对。+ 'git log -p -S README.md',+ ]) {+ expect(await provesSafe(history, command), command).toBe(false);+ }+ write('.npmrc', 'changed\n');+ expect(await provesSafe(history, 'git diff')).toBe(false);+ // 直接写出文件对象时显示的是内容本身。+ git('tag', '-a', 'blob-tag', '-m', 't', git('rev-parse', 'HEAD:src/util.ts').trim());+ expect(await provesSafe(history, 'git show blob-tag')).toBe(false);+ expect(await provesSafe(history, 'git show blob-tag -- src')).toBe(false);+ });++ it('lets commands that print the git config run only while the config holds no secrets', async () => {+ const history = new GitCredentialHistory();+ const token = 'ghp_0123456789abcdefghijABCDEFGHIJ012345';+ const printing = ['git remote -v', 'git remote get-url origin', 'git config --list', 'git config --get remote.origin.url'];+ git('remote', 'add', 'origin', 'https://github.com/a/b.git');+ for (const command of [...printing, 'git config user.name']) {+ expect(await provesSafe(history, command), command).toBe(true);+ }+ // 远程地址里嵌着令牌:打出地址与整份配置的要问,只读别的键的不用。+ git('remote', 'set-url', 'origin', `https://me:${token}@github.com/a/b.git`);+ for (const command of printing) {+ expect(await provesSafe(history, command), command).toBe(false);+ }+ expect(await provesSafe(history, 'git config user.name')).toBe(true);+ // 令牌藏在地址改写规则的键名里、或在 http 头里。+ git('remote', 'set-url', 'origin', 'https://github.com/a/b.git');+ git('config', `url.https://${token}@github.com/.insteadOf`, 'https://github.com/');+ expect(await provesSafe(history, 'git remote -v')).toBe(false);+ git('config', '--unset', `url.https://${token}@github.com/.insteadOf`);+ git('config', 'http.https://github.com/.extraheader', 'AUTHORIZATION: basic eDp5');+ expect(await provesSafe(history, 'git remote -v')).toBe(true);+ expect(await provesSafe(history, 'git config --list')).toBe(false);+ // 全局配置也算。+ git('config', '--unset', 'http.https://github.com/.extraheader');+ expect(await provesSafe(history, 'git config --list')).toBe(true);+ git('config', '--global', 'sendemail.smtppass', 'hunter2');+ expect(await provesSafe(history, 'git config --list')).toBe(false);+ });++ it('keeps asking where the scan does not reach', async () => {+ const history = new GitCredentialHistory();+ const outside = path.join(root, 'outside');+ fs.mkdirSync(outside);+ fs.writeFileSync(path.join(outside, 'a.txt'), 'a');+ for (const command of [+ 'GIT_DIR=/other/.git git log -p',+ 'git diff --no-index a b',+ `git diff ${path.join(outside, 'a.txt')} src/app.ts`,+ 'git log -p ORIG_HEAD',+ 'git grep --recurse-submodules x',+ 'git log -p $(cat revs)',+ ]) {+ expect(await provesSafe(history, command), command).toBe(false);+ }+ // 不在 git 仓库里。+ expect(await provesSafe(history, 'git log -p', outside)).toBe(false);+ // 认不出目录。+ expect(await history.provesSafe('git log -p', [{ sub: 'log', args: ['-p'] }])).toBe(false);+ // 带子模块。+ git('update-index', '--add', '--cacheinfo', `160000,${git('rev-parse', 'HEAD').trim()},vendor/lib`);+ expect(await provesSafe(history, 'git log -p')).toBe(false);+ });++ it('does not keep the command waiting past the limit', async () => {+ const history = new GitCredentialHistory({ waitMs: 0 });+ expect(await provesSafe(history, 'git log -p')).toBe(false);+ // 扫描在后台继续;等它结束再清理(Windows 上 git 进程占着目录时删不掉)。+ await vi.waitFor(() => fs.rmSync(root, { recursive: true, force: true }), { timeout: 30_000, interval: 200 });+ });+});diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex 6d0fcece34..55b7ab3ab1 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -33,6 +33,7 @@ import {type ToolResult,} from './files';import type { ExecutorAction, ExecutorGate, ExecutorGateDecision, ExecutorGateMode } from './gate';+import type { GitCredentialHistory } from './gitCredentials';import { piGrep, type PiGrepInput } from './search';import { resolveExecutorShell, runOnce, ShellSession } from './shell';import { fetchWebPage, WEB_FETCH_PAGE_CHARS, type GuardedFetch } from './webFetch';@@ -65,6 +66,8 @@ export interface RemoteExecutorOptions {* 默认只放行这一个操作;用户明确选择会话级允许后免除后续的分享凭证确认。缺省时直接拒绝。*/confirm?(action: ExecutorAction): Promise<ExecutorConfirmation>;+ /** 与 confirm 一起提供:git 查看内容、打出 git 配置的命令先在本机核实,读不到凭证时不弹卡。 */+ gitCredentials?: GitCredentialHistory;}export class ExecutorRequestError extends Error {@@ -153,11 +156,20 @@ export class RemoteExecutor {/*** 凭证类操作在本机补问一次(供应商分享的受邀者任务);本机用户允许后登记批准,调用方再检查一次即可- * 放行。不是凭证类、没有确认通道或任务已结束时返回 false。+ * 放行。git 查看内容、打出 git 配置的命令在本机核实过读不到凭证时不弹卡,直接登记批准。不是凭证类、+ * 没有确认通道或任务已结束时返回 false。*/async confirm(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> {if (this.closed || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;const permissionGeneration = this.permissionGeneration;+ // 只有要核实的 git 命令才在弹卡前等核实结果,其余操作照旧立即弹卡。+ const gitCheck = this.gitReadsCheck(action, signal);+ if (gitCheck && await gitCheck) {+ // 核实期间任务结束、请求被取消或权限已切换:同样不放行。+ if (this.closed || signal?.aborted || permissionGeneration !== this.permissionGeneration) return false;+ this.gate.recordApproval(action);+ return true;+ }const allowed = await this.opts.confirm(action).catch(() => false);// 等确认期间任务结束、请求被取消或权限已切换:不接受旧确认。if ((allowed !== true && allowed !== 'session') || this.closed || signal?.aborted@@ -170,6 +182,14 @@ export class RemoteExecutor {return true;}+ /** 要在本机核实的 git 命令返回核实结果(true = 读不到凭证);不需要核实的返回 null。 */+ private gitReadsCheck(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> | null {+ 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;+ }+/** 检查上限;凭证类操作没有批准时先在本机问一次。 */private async decide(action: ExecutorAction, signal?: AbortSignal): Promise<ExecutorGateDecision> {const decision = this.gate.authorize(action);diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.tsindex 2ebb32c4b2..25eb934ea1 100644--- a/apps/desktop/src/main/remote-agent/executor/gate.ts+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts@@ -20,9 +20,9 @@*/import path from 'node:path';-import { classifyShellCommand, reviewAction } from '@cindy/maker-core';+import { classifyShellCommand, reviewAction, type GitRead } from '@cindy/maker-core';-import { isShareCredentialCommand, isShareCredentialPath } from '../credentials';+import { isShareCredentialCommand, isShareCredentialPath, shareCredentialGitReads } from '../credentials';import { realPathOrAncestor, type ExecutorWorkspace } from './workspace';/**@@ -154,6 +154,15 @@ export class ExecutorGate {return isShareCredentialPath(path.resolve(action.path)) || isShareCredentialPath(realPathOrAncestor(action.path));}+ /**+ * 命令要按凭证确认、但只是因为 git 查看内容或打出 git 配置时,返回这些 git 调用(执行器在本机核实读不到+ * 凭证后可以不问);其余情况返回 null。+ */+ 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 });+ }+authorize(action: ExecutorAction): ExecutorGateDecision {const credential = this.needsCredentialConsent(action);if (this.mode === 'full' && !credential) return { ok: true, elevated: true };diff --git a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts b/apps/desktop/src/main/remote-agent/executor/gitCredentials.tsnew file mode 100644index 0000000000..4af36aec8d--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts@@ -0,0 +1,447 @@+/**+ * 供应商分享的受邀者任务:git 查看内容的命令在本机核实读不到凭证类文件时不弹确认卡+ * (docs/product-rules/provider-sharing.md §9 第 7 条)。+ *+ * 只看命令文本时,git diff、git log -p、git show、git grep 这类命令按可能读到提交进仓库的凭证处理+ * (credentials.ts)。这里在本机扫一遍仓库:所有分支、标签、stash 与 reflog 可达的提交里出现过的路径,+ * 加上暂存区,记下其中的凭证类路径(扫描结果按仓库缓存,提交变化后只补扫新增的部分):+ * - 一个都没有:这个仓库里查看内容的命令读不到凭证;+ * - 有:命令用 `--` 限定的路径都碰不到这些文件时算读不到;+ * - 还不行时(git diff、git show、git log),按原命令只列出会显示的文件,其中没有凭证类文件也算读不到。+ * 认不出 git 在哪个仓库里跑、仓库带子模块、比较仓库外的文件、超过等待时限,都按读得到处理,照旧弹卡。+ * 会打出 git 配置的命令(git remote -v、git config --list 等)按本机生效的配置核对其中没有密钥。+ * 与命令文本判定一样只防误发:直接写出底层对象名(git show <blob>)、在前面的命令里改 GIT_DIR 之类的认不出。+ */+import { spawn } from 'node:child_process';+import fsp from 'node:fs/promises';+import path from 'node:path';++import type { GitRead } from '@cindy/maker-core';++import { isShareCredentialPath, textSpellsOutSecret } from '../credentials';++/** 核实一条命令最多等这么久,超过就先弹卡;仓库扫描在后台继续,结果留给后面的命令。 */+const GIT_CREDENTIAL_WAIT_MS = 8_000;+const SCAN_TIMEOUT_MS = 120_000;+const QUERY_TIMEOUT_MS = 15_000;+/** 记下的凭证类路径上限:超过时不再逐个比对限定路径,按读得到处理。 */+const MAX_CREDENTIAL_PATHS = 4_096;+const MAX_REPOS = 16;++/** 交给这里核实的查看内容的子命令;git cat-file 直接读对象,不在内。 */+const CONTENT_SUBCOMMANDS: ReadonlySet<string> = new Set(['diff', 'show', 'log', 'whatchanged', 'grep', 'status']);+/** 会打出 git 配置的子命令(git credential 一律要确认,不交给这里)。 */+const CONFIG_SUBCOMMANDS: ReadonlySet<string> = new Set(['remote', 'config', 'var']);+/** 密码、令牌、http 头这类配置项:有取值就按密钥处理。 */+const SECRET_CONFIG_KEY = /(?:^|\.)(?:password|passwd|pass|token|secret|smtppass|apikey|api-key|extraheader)$/i;+/**+ * 这些子命令只按提交与文件显示内容,输出受 `--` 后的路径限定。git diff / git show 可以直接写出文件对象+ * (不受路径限定),交给按会显示的文件核对。+ */+const PATHSPEC_SUBCOMMANDS: ReadonlySet<string> = new Set(['log', 'whatchanged', 'grep']);+/** 扫描覆盖不到:不经仓库比较文件(--no-index)、子模块、别的仓库的对象、从输入读提交。 */+const UNCOVERED_OPTION = /^--(?:no-i|rec|sub|alt|std)/;+/** 不在分支、标签与 reflog 里的特殊引用。 */+const PSEUDO_REF = /(?:ORIG|FETCH|MERGE|CHERRY_PICK|REVERT|REBASE|BISECT)_HEAD|AUTO_MERGE/;+/** 命令里改 git 的仓库、暂存区或对象位置的环境变量。 */+const GIT_ENV_ASSIGNMENT = /\bGIT_[A-Z0-9_]*\s*=/i;+/** 列出历史里每个路径(每个路径至少在某次提交里以新增出现)。 */+const HISTORY_PATHS = ['log', '-m', '--root', '--no-renames', '--diff-filter=A', '--name-only', '--format=', '-z', '--no-show-signature'];+/**+ * 按原命令只列出会显示的文件(插在原有选项之后,后出现的输出格式生效,见 shownFilesArgs)。合并提交按+ * 每个父提交分别列、不认改名,只会多列。git grep 的选项不能放在搜索词之后,不在内。+ */+const SHOWN_FILES: Readonly<Record<string, { sub: string; args: readonly string[] }>> = {+ diff: { sub: 'diff', args: ['--name-only', '--no-renames', '--no-relative', '--no-color', '-z'] },+ show: { sub: 'show', args: ['--name-only', '--format=', '-m', '--no-renames', '--no-relative', '--no-color', '-z'] },+ log: { sub: 'log', args: ['--name-only', '--format=', '-m', '--root', '--no-renames', '--no-relative', '--no-color', '-z'] },+ whatchanged: { sub: 'log', args: ['--name-only', '--format=', '-m', '--root', '--no-renames', '--no-relative', '--no-color', '-z'] },+};+/** 会在文件名列表里夹进别的内容的输出选项:碰到就不这样核对。 */+const MIXED_OUTPUT_OPTION = /^--(?:graph|stat|numstat|shortstat|dirstat|summary|raw|name-|check|compact-summary|patch-with|line-prefix)/;+/**+ * 确定不会把后一个参数当作取值的选项。列文件的选项插在某个参数之后时,前一个参数必须是这类选项、+ * `--名称=值`、带数字的短选项或提交;否则插进去的选项可能被它当成取值(`git log -S <文件名>`)。+ */+const VALUELESS_OPTIONS: ReadonlySet<string> = new Set([+ '-p', '-u', '--patch', '-W', '--function-context', '--cached', '--staged', '--merge-base', '-R',+ '-a', '--text', '-w', '-b', '--ignore-all-space', '--ignore-space-change', '--ignore-blank-lines',+ '--minimal', '--patience', '--histogram', '--word-diff', '--color-words', '--color', '--no-color',+ '--no-ext-diff', '--no-prefix', '--full-index', '--binary', '-M', '-C', '-B', '--find-renames', '--no-renames',+ '-m', '-c', '--cc', '--root', '--follow', '--full-diff', '--all', '--branches', '--tags', '--remotes',+ '--no-merges', '--merges', '--first-parent', '--reverse', '--oneline', '--decorate', '--no-decorate',+ '--abbrev-commit', '--source', '--left-right', '--date-order', '--topo-order', '-g', '--walk-reflogs',+]);++function cannotTakeNextAsValue(token: string | undefined): boolean {+ return token === undefined+ || !token.startsWith('-')+ || /^--[\w-]+=/.test(token)+ || /^-(?:\d+|[nUMCBl]\d+)$/.test(token)+ || VALUELESS_OPTIONS.has(token);+}++interface RepoHistory {+ /** 扫描时的提交端点(分支、标签、stash 与 reflog):变化后只扫新增的部分。 */+ tips: Set<string>;+ /** 历史里出现过的凭证类路径(相对仓库根,`/` 分隔)。 */+ credentials: Set<string>;+}++interface RepoEntry {+ history: RepoHistory | null;+ refreshing: Promise<RepoHistory | null> | null;+ /** 扫描失败或超时:本次运行里不再核实这个仓库。 */+ unavailable: boolean;+}++/**+ * 跑一条 git。onRecord 逐个收到以 NUL 分隔的输出(-z),返回 true 表示已有结论:提前结束 git,照常返回。+ */+function git(+ args: readonly string[],+ cwd: string,+ opts: { stdin?: string; onRecord?: (record: string) => boolean | void; timeoutMs?: number } = {},+): Promise<string> {+ return new Promise((resolve, reject) => {+ const child = spawn('git', [...args], {+ cwd,+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' },+ stdio: ['pipe', 'pipe', 'ignore'],+ windowsHide: true,+ });+ const timer = setTimeout(() => child.kill(), opts.timeoutMs ?? QUERY_TIMEOUT_MS);+ let output = '';+ let pending = '';+ let stopped = false;+ child.stdout.setEncoding('utf8');+ child.stdout.on('data', (chunk: string) => {+ if (!opts.onRecord) {+ output += chunk;+ return;+ }+ if (stopped) return;+ const records = (pending + chunk).split('\0');+ pending = records.pop() ?? '';+ for (const record of records) {+ if (opts.onRecord(record) !== true) continue;+ stopped = true;+ child.kill();+ return;+ }+ });+ child.on('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ child.on('close', (code) => {+ clearTimeout(timer);+ if (stopped) {+ resolve(output);+ return;+ }+ if (code !== 0) {+ reject(new Error(`git ${args[0]} exited with ${code ?? 'a signal'}`));+ return;+ }+ if (pending) opts.onRecord?.(pending);+ resolve(output);+ });+ child.stdin.on('error', () => {});+ child.stdin.end(opts.stdin ?? '');+ });+}++/** 收集凭证类路径;超过上限时返回 null。 */+function credentialCollector(top: string): { add(file: string): void; result(): Set<string> | null } {+ const credentials = new Set<string>();+ return {+ add(file) {+ if (file && credentials.size <= MAX_CREDENTIAL_PATHS && isShareCredentialPath(path.join(top, file))) credentials.add(file);+ },+ result: () => (credentials.size > MAX_CREDENTIAL_PATHS ? null : credentials),+ };+}++async function scanHistory(top: string, extraArgs: readonly string[], stdin?: string): Promise<Set<string> | null> {+ const collector = credentialCollector(top);+ await git([...HISTORY_PATHS, ...extraArgs], top, { stdin, timeoutMs: SCAN_TIMEOUT_MS, onRecord: collector.add });+ return collector.result();+}++/** 暂存区里的凭证类路径;带子模块或超过上限时返回 null。 */+async function indexCredentials(top: string): Promise<Set<string> | null> {+ const collector = credentialCollector(top);+ let submodule = false;+ await git(['ls-files', '--stage', '-z'], top, {+ onRecord: (record) => {+ const tab = record.indexOf('\t');+ if (tab < 0) return;+ if (record.startsWith('160000 ')) submodule = true;+ collector.add(record.slice(tab + 1));+ },+ });+ return submodule ? null : collector.result();+}++async function currentTips(top: string): Promise<Set<string>> {+ const output = await git(['rev-list', '--all', '--reflog', '--no-walk'], top);+ return new Set(output.split(/\r?\n/).filter(Boolean));+}++function sameSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {+ return a.size === b.size && [...a].every((item) => b.has(item));+}++function isOutside(root: string, target: string): boolean {+ const relative = path.relative(root, target);+ return relative.startsWith('..') || path.isAbsolute(relative);+}++async function exists(target: string): Promise<boolean> {+ return fsp.stat(target).then(() => true, () => false);+}++/**+ * git 路径限定是否可能选中 file(都已转小写,相对仓库根):不含通配符时是这个路径本身或它下面的文件;+ * 含通配符时 `*` 可跨目录,方括号放宽为任意一个字符,上层目录被选中也算(只会多判、不会漏判)。+ */+function pathspecCouldSelect(spec: string): (file: string) => boolean {+ if (!/[*?[]/.test(spec)) return (file) => spec === '' || file === spec || file.startsWith(`${spec}/`);+ let source = '';+ for (let index = 0; index < spec.length; index += 1) {+ const char = spec.charAt(index);+ if (char === '*') source += '.*';+ else if (char === '?') source += '.';+ else if (char === '[') {+ source += '.';+ const close = spec.indexOf(']', index + 2);+ if (close > 0) index = close;+ } else source += char.replace(/[.+^${}()|\\/-]/g, '\\$&');+ }+ const pattern = new RegExp(`^${source}$`, 's');+ return (file) => {+ for (let end = file.length; end > 0; end = file.lastIndexOf('/', end - 1)) {+ if (pattern.test(file.slice(0, end))) return true;+ }+ return false;+ };+}++/** 命令用 `--` 限定的路径都碰不到这些凭证类路径。 */+function pathspecsAvoid(read: GitRead, cwd: string, top: string, credentials: ReadonlySet<string>): boolean {+ if (!PATHSPEC_SUBCOMMANDS.has(read.sub)) return false;+ const separator = read.args.indexOf('--');+ if (separator < 0 || separator === read.args.length - 1) return false;+ // `--` 前带 `:` 的是 <提交>:<路径> 这类直接指定的对象,不受后面的路径限定。+ if (read.args.slice(0, separator).some((arg) => !arg.startsWith('-') && arg.includes(':'))) return false;+ const files = [...credentials].map((file) => file.toLowerCase());+ return read.args.slice(separator + 1).every((spec) => {+ if (!spec || spec.startsWith(':') || spec.includes('\\')) return false;+ const target = path.resolve(cwd, spec);+ if (isOutside(top, target)) return false;+ const selects = pathspecCouldSelect(path.relative(top, target).split(path.sep).join('/').toLowerCase());+ return !files.some(selects);+ });+}++/**+ * 按原命令只列出会显示的文件的完整参数;不能这样核对时返回 null。+ * - git diff / git show 写出的对象都得是提交(或提交区间):直接写出文件对象(<提交>:<路径>、指向文件的+ * 标签)时显示的是内容本身,列不出文件名;+ * - 列文件的选项放在原有选项之后,后出现的输出格式生效:有 `--` 时放在它前面,没有时放在第一个路径前+ * (git 不接受路径之后的选项)。+ */+async function shownFilesArgs(read: GitRead, cwd: string): Promise<string[] | null> {+ const listing = SHOWN_FILES[read.sub];+ if (!listing || read.args.some((arg) => MIXED_OUTPUT_OPTION.test(arg))) return null;+ const objectsMustBeCommits = read.sub === 'diff' || read.sub === 'show';+ const resolves = (spec: string) => git(['rev-parse', '--verify', '--quiet', spec], cwd).then(() => true, () => false);+ const separator = read.args.indexOf('--');+ let insertAt = separator < 0 ? read.args.length : separator;+ for (let index = 0; index < insertAt; index += 1) {+ const arg = read.args[index];+ if (arg.startsWith('-')) continue;+ const range = arg.split(/\.\.\.?/);+ if (range.length > 1) {+ for (const side of objectsMustBeCommits ? range.filter(Boolean) : []) {+ if (!(await resolves(`${side}^{commit}`))) return null;+ }+ continue;+ }+ if (await resolves(`${arg}^{commit}`)) continue;+ if (await resolves(arg)) {+ if (objectsMustBeCommits) return null;+ continue;+ }+ // 既不是提交也不是别的对象、又是存在的路径:git 从这里起都按路径处理。+ if (await exists(path.resolve(cwd, arg))) insertAt = index;+ }+ if (!cannotTakeNextAsValue(read.args[insertAt - 1])) return null;+ return [listing.sub, ...read.args.slice(0, insertAt), ...listing.args, ...read.args.slice(insertAt)];+}++/**+ * 输出的一行可能指向凭证类文件。正常是一个文件名;原命令的输出格式盖过了只列文件名时(比如选项值+ * 被认错)是补丁之类的整行,按空白拆开、去掉引号与 a/ b/ 前缀后每一段也比对,只会多判。+ */+function lineMentionsCredential(top: string, line: string): boolean {+ if (!line) return false;+ const parts = line.split(/\s+/).map((part) => part.replace(/^"|"$/g, '').replace(/^[ab]\//, ''));+ return [line, ...parts].some((candidate) => Boolean(candidate) && isShareCredentialPath(path.join(top, candidate)));+}++/** 按原命令列出会显示的文件,其中没有凭证类文件。 */+async function shownFilesAvoidCredentials(read: GitRead, cwd: string, top: string, timeoutMs: number): Promise<boolean> {+ const args = await shownFilesArgs(read, cwd);+ if (!args) return false;+ let credential = false;+ await git(args, cwd, {+ timeoutMs,+ onRecord: (record) => {+ credential = record.split('\n').some((line) => lineMentionsCredential(top, line));+ return credential;+ },+ });+ return !credential;+}++/** 读这一项要打出的 git config 键名(小写);列出全部或认不准键名时为 undefined。 */+function requestedConfigKey(read: GitRead): string | undefined {+ if (read.sub !== 'config' || read.args.some((arg) => /^(?:--list|-l|list|--get-regexp|--get-urlmatch)$/.test(arg))) {+ return undefined;+ }+ // `--type bool core.x` 这类带取值的选项会让位置参数对不上:多于一个就按全部处理。+ const keys = read.args.filter((arg) => !arg.startsWith('-') && arg !== 'get');+ return keys.length === 1 ? keys[0].toLowerCase() : undefined;+}++/** 配置项里有密钥:键名或取值里直接写着(带令牌的地址、Authorization 头),或是密码、令牌、http 头这类项。 */+function configEntryHoldsSecret(key: string, value: string): boolean {+ return textSpellsOutSecret(`${key}=${value}`) || (SECRET_CONFIG_KEY.test(key) && value.trim() !== '');+}++/**+ * 打出 git 配置的命令(git remote -v / get-url / show、读 git config、git var -l):按这个目录生效的 git 配置+ * (系统、全局、仓库,含 include)核对它会打出的那些项里没有密钥。读别的配置文件(-f / --blob)的不核对。+ */+async function configReadProvesSafe(read: GitRead): Promise<boolean> {+ if (!read.cwd || read.args.some((arg) => /[$`]/.test(arg) || /^(?:-f|--file|--blob)(?:=|$)/.test(arg))) return false;+ const cwd = await fsp.realpath(read.cwd);+ const key = requestedConfigKey(read);+ const entries = (await git(['config', '--list', '-z'], cwd)).split('\0').filter(Boolean);+ return !entries.some((entry) => {+ const newline = entry.indexOf('\n');+ const name = newline < 0 ? entry : entry.slice(0, newline);+ const lowered = name.toLowerCase();+ const shown = read.sub === 'remote'+ ? lowered.startsWith('remote.') || lowered.startsWith('url.')+ : key === undefined || lowered === key;+ return shown && configEntryHoldsSecret(name, newline < 0 ? '' : entry.slice(newline + 1));+ });+}++export class GitCredentialHistory {+ private readonly repos = new Map<string, RepoEntry>();++ constructor(private readonly opts: { waitMs?: number } = {}) {}++ /** 这些 git 调用(credentials.ts shareCredentialGitReads 的结果)在本机核实后都读不到、打不出凭证。 */+ async provesSafe(command: string, reads: readonly GitRead[], signal?: AbortSignal): Promise<boolean> {+ if (reads.length === 0 || GIT_ENV_ASSIGNMENT.test(command)) 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;+ }+ 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;+ if (read.args.some((arg) => /[$`]/.test(arg) || UNCOVERED_OPTION.test(arg) || PSEUDO_REF.test(arg))) return false;+ const cwd = await fsp.realpath(read.cwd);+ const [topLine, commonLine] = (await git(['rev-parse', '--show-toplevel', '--git-common-dir'], cwd)).split(/\r?\n/);+ if (!topLine || !commonLine) return false;+ const top = path.resolve(topLine);+ const commonDir = path.resolve(cwd, commonLine);+ // 指向仓库外的文件时 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);+ if (!index) return false;+ const history = await this.waitForHistory(top, commonDir, deadline, signal);+ if (history) {+ const credentials = new Set([...history.credentials, ...index]);+ if (credentials.size === 0 || pathspecsAvoid(read, cwd, top, credentials)) return true;+ }+ // 仓库里有凭证类文件(或还没扫完):按这条命令实际会显示的文件再核对一次,与等扫描共用同一个时限。+ const remaining = deadline - Date.now();+ if (signal?.aborted || remaining <= 0) return false;+ return shownFilesAvoidCredentials(read, cwd, top, remaining);+ }++ private async waitForHistory(+ top: string,+ commonDir: string,+ deadline: number,+ signal?: AbortSignal,+ ): Promise<RepoHistory | null> {+ let timer: NodeJS.Timeout | undefined;+ let onAbort: (() => void) | undefined;+ const timeout = new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), Math.max(0, deadline - Date.now()));+ onAbort = () => resolve(null);+ signal?.addEventListener('abort', onAbort, { once: true });+ });+ try {+ return await Promise.race([this.history(top, commonDir), timeout]);+ } finally {+ clearTimeout(timer);+ if (onAbort) signal?.removeEventListener('abort', onAbort);+ }+ }++ private history(top: string, commonDir: string): Promise<RepoHistory | null> {+ let entry = this.repos.get(commonDir);+ if (!entry) {+ entry = { history: null, refreshing: null, unavailable: false };+ this.repos.set(commonDir, entry);+ if (this.repos.size > MAX_REPOS) this.repos.delete(this.repos.keys().next().value as string);+ }+ if (entry.unavailable) return Promise.resolve(null);+ const current = entry;+ current.refreshing ??= this.refresh(current, top).finally(() => {+ current.refreshing = null;+ });+ return current.refreshing;+ }++ private async refresh(entry: RepoEntry, top: string): Promise<RepoHistory | null> {+ try {+ const tips = await currentTips(top);+ const previous = entry.history;+ if (previous && sameSet(previous.tips, tips)) return previous;+ // undefined = 还没扫;null = 凭证类路径太多。+ let credentials: Set<string> | null | undefined;+ if (previous) {+ // 只扫上次之后新增的提交;上次的端点已被清理掉时 git 会报错,改为整个重扫。+ const stdin = [...previous.tips].map((tip) => `^${tip}\n`).join('');+ const added = await scanHistory(top, ['--stdin', '--all', '--reflog'], stdin).catch(() => undefined);+ if (added !== undefined) credentials = added && new Set([...previous.credentials, ...added]);+ }+ if (credentials === undefined) credentials = await scanHistory(top, ['--all', '--reflog']);+ if (!credentials || credentials.size > MAX_CREDENTIAL_PATHS) {+ entry.unavailable = true;+ return null;+ }+ entry.history = { tips, credentials };+ return entry.history;+ } catch {+ entry.unavailable = true;+ return null;+ }+ }+}diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex 4f91328ae3..1cdb604c33 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -281,9 +281,30 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):关闭、重新打开任务或切换权限档后恢复确认,不扩展到其他任务或供应商分享。原权限档的其他限制仍然生效,启动同步仍排除凭证文件。确认卡说明内容会经过分享者或其安排的电脑,以及这项授权的范围与失效时机。确认卡与 Agent 的确认走同一通道,手机远控与 IM 也能处理;- - 命令只能按命令文本识别(脚本里读的、编码后再解开的认不出来),是防误发,不是防恶意。+ - 命令只能按命令文本识别(脚本里读的、编码后再解开的认不出来),是防误发,不是防恶意;+ - 减少误弹(2026-10-12 用户裁决)。**以下几条只用于这张分享任务的确认卡**,本机任务、同账号远程供应商与+ 自动审查的判定都不变:+ - `.env.example` / `.env.sample` / `.env.template` 与公钥 `*.pub` 按惯例不含密钥,不算凭证类文件+ (读取、启动时同步都照普通文件);放在凭证目录里(如 `~/.ssh/id_rsa.pub`)时仍算;+ - 按扩展名缩小范围的搜索不算读取凭证:rg 的 `-g '*.ts'`、grep 的 `--include='*.md'` 这类只选中源码+ 与文档文件的写法,字面上能选中 `.env.ts`、`id_rsa.ts`,但这类名字是代码模块。直接写出像凭证的+ 文件名、`*.json` / `*.txt` / `*.sh` 这类可能存放凭证的格式、扩展名不确定的写法(`*.ts*`)仍要确认;+ - git 查看内容的命令(`git diff`、`git show`、`git log -p`、`git grep`)只看命令文本时按可能读到+ 提交进仓库的凭证处理,执行前先在受邀者电脑上核实,读不到凭证类文件就不弹卡:仓库所有分支、标签、+ stash 与 reflog 的历史和暂存区里从没有凭证类文件;或命令用 `--` 限定的路径碰不到这些文件;或+ (`git diff` / `git show` / `git log`)按原命令只列出会显示的文件,其中没有凭证类文件。认不出 git+ 在哪个仓库里跑、仓库带子模块、比较仓库外的文件、核实超过 8 秒,都照旧弹卡;仓库的扫描结果留在+ 内存里给后面的命令用。直接写出底层对象名(如 `git show <文件对象>`)之类的写法同样认不出;+ - 打出 git 配置的命令(`git remote -v` / `get-url` / `show`、读 `git config`、`git var -l`)按受邀者+ 电脑上生效的 git 配置核实:要打出的那些项里没有密钥(地址里嵌的令牌或密码、`http.extraHeader`、+ 密码与令牌类配置项)就不弹卡,有才确认;+ - 再收紧(2026-10-12 用户裁决),同样只用于分享任务:命令里直接写着密钥(`https://用户:密码@`、+ 地址里的令牌、`Authorization` 头的取值、常见服务的令牌格式与私钥)、用 `<提交>:<路径>` 写出凭证类文件+ (`git show HEAD:.aws/credentials`)、`git credential fill` 这类打出保存的登录凭证的命令都要确认。同账号远程供应商不受影响:与本机一致,项目与个人配置里的符号链接一律跟随,不额外确认。- 实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,controller/projectFiles.ts}`。+ 实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,executor/executor.ts,executor/gitCredentials.ts,controller/projectFiles.ts}`;+ 命令判定复用 `packages/maker-core/src/agents/shared/auto-review.ts` 的 `shellCommandReadsCredentials`,+ 上面的命令放宽与 git 核实通过它只有分享任务才传的选项(`CredentialCommandOptions`)实现,不传时判定不变。## 10. 与现有规则的关系@@ -311,7 +332,10 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):9. 中国大陆版与 Global 账号之间能完成同样的申请、审批、使用与撤销;合规开关关闭时跨区链接给出明确提示,同区域分享不受影响。10. 受邀者任务启动时不带凭证类文件;任务中读写凭证类文件或执行读取凭证的命令,即使在完全访问下也- 要受邀者在本机确认后才执行(§9 第 7 条)。+ 要受邀者在本机确认后才执行(§9 第 7 条)。`rg -g '*.ts'` 这类只按源码扩展名缩小范围的搜索、读+ `.env.example` 与 `*.pub`、在没有凭证类文件的仓库里(或只涉及普通文件时)跑 `git diff` / `git log -p`、+ 配置里没有密钥时跑 `git remote -v` 都不弹确认卡;命令里直接写着密钥、`git credential fill` 要确认;+ 本机任务与同账号远程供应商的确认不受影响。11. Light 与 Dark 两种模式都已实现。## 12. 后续可选diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.tsindex bedd5ebace..ed222b18fa 100644--- a/packages/maker-core/src/agents/index.ts+++ b/packages/maker-core/src/agents/index.ts@@ -123,7 +123,7 @@ export {} from './shared/auto-review-decision.js';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 type { CredentialCommandOptions, GitRead, ReviewableAction } from './shared/auto-review.js';export { classifyShellCommand, reviewAction, shellCommandReadsCredentials } from './shared/auto-review.js';export type {ToolLoopReviewDecision,diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.tsindex d8496e8510..1e28825c68 100644--- a/packages/maker-core/src/agents/shared/auto-review.test.ts+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts@@ -17,9 +17,11 @@ import {isProtectedSystemPath,reviewAction,shellCommandReadsCredentials,+ type GitRead,} from './auto-review.js';const roots = ['/repo', '/extra'];+const toForwardSlashes = (value: string) => value.replace(/\\/g, '/');describe('reviewAction — 非 shell 动作', () => {it('read / session-state → auto-approve', () => {@@ -4717,3 +4719,102 @@ describe('shellCommandReadsCredentials — 只认凭证那一部分红线', () =expect(shellCommandReadsCredentials('', roots)).toBe(false);});});++// 两个附加选项只供供应商分享的受邀者任务用(apps/desktop/src/main/remote-agent/credentials.ts)。+describe('shellCommandReadsCredentials — 分享任务的附加选项', () => {+ const sourceSearches = [+ "rg -n 'API_KEY' --glob '*.ts'",+ "rg -g '*.{ts,tsx}' token src",+ "rg -g '*.tsx' -g '!*.test.tsx' secret",+ "grep -rn --include='*.md' token .",+ ];++ it('不传选项时判定不变:按扩展名缩小范围的搜索与 git 查看内容照旧必问(本机自动审查同此)', () => {+ for (const command of [...sourceSearches, 'git diff', 'git log -p', 'git grep -n token']) {+ expect(shellCommandReadsCredentials(command, roots), command).toBe(true);+ expect(classifyShellCommand(command, roots), command).toBe('prompt-each-time');+ }+ });++ it('sourceFileSelectors:只选中源码与文档扩展名的搜索不算读取凭证', () => {+ for (const command of sourceSearches) {+ expect(shellCommandReadsCredentials(command, roots, { sourceFileSelectors: true }), command).toBe(false);+ }+ for (const command of [+ // 文件名本身像凭证、可能存放凭证的格式、扩展名不确定、搜索目标就是凭证。+ "rg -g '.env.ts' KEY",+ "rg -g 'server.key.ts' KEY",+ "rg -g '.ssh/**/*.ts' KEY",+ "rg -g '*.json' KEY",+ "grep -rn --include='*.sh' KEY .",+ "rg -g '*.ts*' KEY",+ "rg -g '*.t[s]' KEY",+ "rg -g '*.ts' KEY .env",+ 'grep -rn KEY .',+ 'rg --hidden KEY',+ ]) {+ expect(shellCommandReadsCredentials(command, roots, { sourceFileSelectors: true }), command).toBe(true);+ }+ });++ it('gitContentRead:git 查看内容先问调用方,并带上 git 实际运行的目录', () => {+ const reads: GitRead[] = [];+ const record = (read: GitRead) => {+ reads.push(read);+ return true;+ };+ expect(shellCommandReadsCredentials('git log -p -- src/app.ts', roots, { gitContentRead: record })).toBe(false);+ expect(shellCommandReadsCredentials('cd /repo/packages/a && git diff', roots, { gitContentRead: record })).toBe(false);+ expect(shellCommandReadsCredentials('cd "$DIR" && git diff', roots, { gitContentRead: record })).toBe(false);+ expect(shellCommandReadsCredentials('(cd /repo/a && ls); git diff', roots, { gitContentRead: record })).toBe(false);+ expect(reads.map(({ sub, args }) => ({ sub, args }))).toEqual([+ { sub: 'log', args: ['-p', '--', 'src/app.ts'] },+ { sub: 'diff', args: [] },+ { sub: 'diff', args: [] },+ { sub: 'diff', args: [] },+ ]);+ expect(reads.map(({ cwd }) => cwd && toForwardSlashes(cwd))).toEqual(['/repo', '/repo/packages/a', undefined, undefined]);+ // 调用方没核实时照旧算;还有别的理由时不受影响。+ expect(shellCommandReadsCredentials('git diff', roots, { gitContentRead: () => false })).toBe(true);+ expect(shellCommandReadsCredentials('git diff && cat .env', roots, { gitContentRead: () => true })).toBe(true);+ expect(shellCommandReadsCredentials('git diff -- .env', roots, { gitContentRead: () => true })).toBe(true);+ });++ it('gitConfigRead:会打出 git 配置或保存的凭证的调用交给调用方', () => {+ const printing = [+ 'git remote -v',+ 'git remote get-url origin',+ 'git remote show origin',+ 'git config --list',+ 'git config --get remote.origin.url',+ 'git config user.name',+ 'git var -l',+ 'printf "protocol=https\\nhost=github.com\\n" | git credential fill',+ 'git-credential-store get',+ 'git -c credential.helper=store credential fill',+ ];+ // 不传选项时判定不变(本机自动审查同此)。+ for (const command of printing.slice(0, 7)) {+ expect(shellCommandReadsCredentials(command, roots), command).toBe(false);+ }+ expect(classifyShellCommand('git remote -v', roots)).toBe('auto-approve');+ const reads: GitRead[] = [];+ for (const command of printing) {+ expect(shellCommandReadsCredentials(command, roots, {+ gitConfigRead: (read) => {+ reads.push(read);+ return false;+ },+ }), command).toBe(true);+ }+ expect(reads.map(({ sub }) => sub)).toEqual([+ 'remote', 'remote', 'remote', 'config', 'config', 'config', 'var', 'credential', 'credential', 'credential',+ ]);+ // 全局选项认不出时只粗找子命令,目录按认不出。+ expect(reads[9]?.cwd).toBeUndefined();+ expect(reads[0]?.cwd && toForwardSlashes(reads[0].cwd)).toBe('/repo');+ for (const command of ['git remote', 'git remote add origin https://github.com/a/b.git', 'git config user.name Me', 'git status']) {+ expect(shellCommandReadsCredentials(command, roots, { gitConfigRead: () => false }), command).toBe(false);+ }+ });+});diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex 716f3102d8..a943cab7bc 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -3223,6 +3223,37 @@ type ShellReviewOptions = {destructivePathResolution?: 'host' | 'unavailable' | 'lexical';};+/**+ * 交给调用方核实的一次 git 调用:查看内容又没有静态限定到具体文件(git diff、git log -p、git grep 等),+ * 或会打出 git 配置与保存的凭证(git remote -v、git config --list、git credential fill 等)。+ */+export type GitRead = {+ sub: string;+ /** 子命令之后的参数(已去引号)。 */+ args: readonly string[];+ /** git 实际运行的目录(已跟随前面各段的 cd 与 -C);认不出时为 undefined。 */+ cwd?: string;+};++/**+ * shellCommandReadsCredentials 的附加选项:只供供应商分享的受邀者任务确认凭证用+ * (apps/desktop/src/main/remote-agent/credentials.ts)。本机任务的自动审查不传,判定不变。+ */+export type CredentialCommandOptions = ShellReviewOptions & {+ /** rg -g、grep --include 这类搜索范围只选中源码与文档扩展名时不算读取凭证。 */+ sourceFileSelectors?: boolean;+ /**+ * git 查看内容又没有限定到具体文件时默认按可能读到提交进仓库的凭证处理;提供时先问调用方,+ * 返回 true 表示调用方已核实这次调用读不到凭证类文件。+ */+ gitContentRead?: (read: GitRead) => boolean;+ /**+ * 会打出 git 配置(远程地址、http 头等)或保存的凭证的调用默认不算;提供时交给调用方,返回 false 表示+ * 这次调用要按读取凭证处理。认不出子命令所在目录时 cwd 为 undefined。+ */+ gitConfigRead?: (read: GitRead) => boolean;+};+function resolveWritableRoots(workspaceRoots: readonly string[],explicit?: readonly string[],@@ -5345,12 +5376,45 @@ function shellOperandCouldMatchDotenv(});}+/**+ * 分享任务确认凭证用(CredentialCommandOptions.sourceFileSelectors):只选中这些扩展名的搜索范围不算+ * 读取凭证。都是代码与文档;`.json`、`.yaml`、`.txt`、`.sh`、`.sql` 这类可能直接存放凭证的格式不在内。+ */+const SOURCE_FILE_SELECTOR_EXTENSIONS: ReadonlySet<string> = new Set([+ 'ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs', 'vue', 'svelte', 'astro',+ 'py', 'pyi', 'rb', 'go', 'rs', 'java', 'kt', 'kts', 'scala', 'swift', 'm', 'mm',+ 'c', 'h', 'cc', 'cpp', 'cxx', 'hpp', 'hh', 'cs', 'fs', 'php', 'lua', 'dart',+ 'ex', 'exs', 'erl', 'hs', 'ml', 'clj', 'r', 'jl', 'zig', 'sol', 'proto', 'graphql', 'gql',+ 'css', 'scss', 'sass', 'less', 'html', 'htm', 'md', 'mdx', 'rst', 'adoc',+]);++/**+ * 选择器的每个展开都以固定的源码 / 文档扩展名结尾,且扩展名前的部分去掉通配符后不像凭证:+ * `*.ts`、`src/**\/*.{ts,tsx}` 算;`.env.ts`、`server.key.ts`、`.ssh/**\/*.ts`、`*.ts*`、`*.t[s]` 不算。+ * 字面上 `*.ts` 也能选中 `.env.ts`、`id_rsa.ts`,这类名字按代码模块处理(provider-sharing.md §9 第 7 条)。+ */+function selectorOnlyMatchesSourceFiles(value: string): boolean {+ return !braceExpansionCouldMatch(value, (alternative) => {+ const normalized = alternative.replace(/\\/g, '/');+ const slash = normalized.lastIndexOf('/');+ const match = /^(.*)\.([A-Za-z0-9]+)$/.exec(normalized.slice(slash + 1));+ if (!match || !SOURCE_FILE_SELECTOR_EXTENSIONS.has(match[2].toLowerCase())) return true;+ const literal = (normalized.slice(0, slash + 1) + match[1]).replace(/[*?[\]!]/g, '');+ return isSensitiveCredentialPath(literal) || isSensitiveCredentialPath(`${literal}/`);+ });+}++function shareSelectorCouldMatchCredential(value: string): boolean {+ return selectorCouldMatchCredential(value) && !selectorOnlyMatchesSourceFiles(value);+}+function readerOptionValueIsSensitive(kind: ReaderOptionKind,value: string | undefined,isSensitiveOperand: (value: string) => boolean,+ selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,): boolean {- if (kind === 'selector') return selectorCouldMatchCredential(value ?? '');+ 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) =>@@ -5362,6 +5426,7 @@ function readerArgumentsReadDotenv(args: readonly string[],isSensitiveOperand: (value: string) => boolean = isDotenvCredentialPath,platform: NodeJS.Platform = process.platform,+ selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,): boolean {let dataArgumentProvided = !FIRST_DATA_ARGUMENT_BINS.has(bin);let optionsEnded = false;@@ -5389,7 +5454,7 @@ function readerArgumentsReadDotenv(continue;}const value = attached ?? args[index + 1];- const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand);+ const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand, selectorCouldMatch);if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -5404,7 +5469,7 @@ function readerArgumentsReadDotenv(if (!kind) continue;const attached = token.slice(optionIndex + 1) || undefined;const value = attached ?? args[index + 1];- const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand);+ const isSensitive = readerOptionValueIsSensitive(kind, value, isSensitiveOperand, selectorCouldMatch);if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -5424,7 +5489,11 @@ function readerArgumentsReadDotenv(return false;}-function grepRecursesIntoPotentialDotenv(bin: string, args: readonly string[]): boolean {+function grepRecursesIntoPotentialDotenv(+ bin: string,+ args: readonly string[],+ selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,+): boolean {if (bin !== 'grep' && bin !== 'egrep' && bin !== 'fgrep') return false;const longOptionNames = [@@ -5482,7 +5551,7 @@ function grepRecursesIntoPotentialDotenv(bin: string, args: readonly string[]):}}- return recursive && (includes.length === 0 || includes.some(selectorCouldMatchCredential));+ return recursive && (includes.length === 0 || includes.some(selectorCouldMatch));}type RgTypeDefinition = { globs: string[]; includes: string[] };@@ -5509,15 +5578,16 @@ function parseRgTypeSpec(value: string): ParsedRgTypeSpec | null {function rgCustomTypeCouldMatchCredential(name: string,definitions: ReadonlyMap<string, RgTypeDefinition>,+ selectorCouldMatch: (value: string) => boolean,visiting = new Set<string>(),): boolean {if (visiting.has(name)) return true;const definition = definitions.get(name);if (!definition) return true;- if (definition.globs.some(selectorCouldMatchCredential)) return true;+ if (definition.globs.some(selectorCouldMatch)) return true;const nextVisiting = new Set(visiting).add(name);return definition.includes.some((included) =>- rgCustomTypeCouldMatchCredential(included, definitions, nextVisiting));+ rgCustomTypeCouldMatchCredential(included, definitions, selectorCouldMatch, nextVisiting));}type AgScopeOptionKind =@@ -5602,7 +5672,10 @@ function agSearchesPotentialCredential(args: readonly string[]): boolean {return hidden && recursive && !filenameOnly;}-function rgSearchesPotentialDotenv(args: readonly string[]): boolean {+function rgSearchesPotentialDotenv(+ args: readonly string[],+ selectorCouldMatch: (value: string) => boolean = selectorCouldMatchCredential,+): boolean {let hidden = false;let unrestricted = 0;let typeParsingUnresolved = false;@@ -5681,10 +5754,10 @@ function rgSearchesPotentialDotenv(args: readonly string[]): boolean {const selectedCustomTypes = [...definitions.keys()].filter((name) =>typeSelections.get(name) ?? allTypesIncluded);if (selectedCustomTypes.some((name) =>- rgCustomTypeCouldMatchCredential(name, definitions))) return true;+ rgCustomTypeCouldMatchCredential(name, definitions, selectorCouldMatch))) return true;const positive = globs.filter((glob) => !glob.startsWith('!'));- const positiveCouldMatchCredential = positive.some(selectorCouldMatchCredential);+ const positiveCouldMatchCredential = positive.some(selectorCouldMatch);const positiveIsSafe = positive.length > 0 && !positiveCouldMatchCredential;return hidden && !positiveIsSafe;}@@ -5976,12 +6049,124 @@ function gitContentReadWithoutPath(sub: string, args: readonly string[]): booleareturn false;}+/**+ * 各段命令实际运行的目录(认不出时为 undefined):跟随前面各段的 cd / pushd,规则同 scopedDestructionNeedsConsent。+ * 出现括号(子 shell、命令组)后,后续各段的目录按认不出处理。+ */+function segmentWorkingDirs(+ segments: readonly ExecutableSegment[],+ workspaceRoots: string[],+ opts: ShellReviewOptions,+): Array<string | undefined> {+ let cwd: string | undefined = opts.cwd ?? workspaceRoots[0];+ let cwdUnknown = opts.cwdUnknown === true;+ return segments.map(({ text, separatorAfter }) => {+ const unwrapped = unwrapCommand(stripShellControlTokens(tokenize(text)), cwd, cwdUnknown);+ const here = unwrapped.cwdUnknown ? undefined : unwrapped.cwd;+ const change = directoryChangeTarget(unwrapped.tokens);+ if (/[(){}]/.test(text) || (change.changesDirectory && separatorAfter === 'or')) {+ cwd = undefined;+ cwdUnknown = true;+ } else if (change.changesDirectory && separatorAfter !== 'pipe' && separatorAfter !== 'background') {+ const next = resolveCwdTarget(change.target, unwrapped.cwd, unwrapped.cwdUnknown);+ cwd = next.cwd;+ cwdUnknown = next.cwdUnknown;+ }+ return here;+ });+}++/** git 的 -C 叠加在所在目录上(parseGitInvocation 已核对过全局选项)。 */+function gitInvocationCwd(tokens: readonly string[], cwd: string | undefined): string | undefined {+ for (let index = 1; index < tokens.length && cwd !== undefined; index += 1) {+ const token = tokens[index];+ if (token === '--' || !token.startsWith('-')) break;+ if (token === '--namespace') {+ index += 1;+ continue;+ }+ const attached = /^-C=?(.+)$/.exec(token);+ if (token !== '-C' && !attached) continue;+ const target = attached ? attached[1] : tokens[index + 1];+ if (!attached) index += 1;+ const next = resolveCwdTarget(target, cwd);+ cwd = next.cwdUnknown ? undefined : next.cwd;+ }+ return cwd;+}++/** 带独立取值的 git 全局选项(只用于在 parseGitInvocation 认不出时粗找子命令)。 */+const GIT_GLOBAL_VALUE_OPTIONS: ReadonlySet<string> = new Set([+ '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--super-prefix',+]);+/** 读取 git config 的选项与子命令;其余写配置的选项与子命令见 GIT_CONFIG_WRITES。 */+const GIT_CONFIG_READS = /^(?:--get(?:-all|-regexp|-urlmatch)?|--list|-l|list|get)$/;+const GIT_CONFIG_WRITES: ReadonlySet<string> = new Set([+ '--unset', '--unset-all', '--add', '--replace-all', '--rename-section', '--remove-section', '-e', '--edit',+ 'set', 'unset', 'rename-section', 'remove-section', 'edit',+]);++/**+ * 会打出 git 配置(远程地址、http 头等)或保存的凭证:git credential 与 credential-* 助手、git remote -v /+ * get-url / show、读 git config、git var -l。+ */+function gitPrintsConfig(sub: string, args: readonly string[]): boolean {+ if (sub === 'credential' || sub.startsWith('credential-')) return true;+ if (sub === 'var') return args.includes('-l');+ if (sub === 'remote') {+ const action = args.find((arg) => !arg.startsWith('-'));+ return action === 'get-url' || action === 'show'+ || (action === undefined && args.some((arg) => arg === '-v' || arg === '--verbose'));+ }+ if (sub !== 'config') return false;+ if (args.some((arg) => GIT_CONFIG_READS.test(arg))) return true;+ if (args.some((arg) => GIT_CONFIG_WRITES.has(arg))) return false;+ // 只写了键名的是读取(`git config user.name`),键名加取值是写入;-f / --blob 的取值不算。+ const positionals = args.filter((arg) => !arg.startsWith('-')).length;+ const fileValues = args.filter((arg) => arg === '-f' || arg === '--file' || arg === '--blob').length;+ return positionals - fileValues <= 1;+}++/**+ * 一段命令里会打出 git 配置或保存的凭证的调用(gitPrintsConfig)。全局选项超出已知范围时+ * parseGitInvocation 认不出子命令,这里退一步粗找子命令名,目录按认不出(调用方据此按读取凭证处理)。+ */+function gitConfigReadOf(+ tokens: string[],+ workspaceRoots: string[],+ opts: ShellReviewOptions,+ segmentCwd: string | undefined,+): GitRead | null {+ if (executableName(tokens[0] ?? '') !== 'git') return { sub: 'credential', args: tokens.slice(1), cwd: segmentCwd };+ const invocation = parseGitInvocation(tokens, workspaceRoots, opts);+ if (invocation?.sub) {+ return gitPrintsConfig(invocation.sub, invocation.args)+ ? { sub: invocation.sub, args: invocation.args, cwd: gitInvocationCwd(tokens, segmentCwd) }+ : null;+ }+ for (let index = 1; index < tokens.length; index += 1) {+ const token = tokens[index];+ if (GIT_GLOBAL_VALUE_OPTIONS.has(token)) {+ index += 1;+ continue;+ }+ if (token.startsWith('-')) continue;+ const args = tokens.slice(index + 1);+ return gitPrintsConfig(token, args) ? { sub: token, args } : null;+ }+ return null;+}+function shellCommandReadsDotenv(command: string,workspaceRoots: string[],- opts: ShellReviewOptions,+ opts: CredentialCommandOptions,): boolean {- for (const segment of splitTopLevelSegments(command)) {+ const selectorCouldMatch = opts.sourceFileSelectors ? shareSelectorCouldMatchCredential : selectorCouldMatchCredential;+ const segments = splitExecutableSegments(command);+ // 只有调用方要核实 git 调用时才需要各段的目录。+ const segmentCwds = opts.gitContentRead || opts.gitConfigRead ? 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(@@ -5998,6 +6183,11 @@ function shellCommandReadsDotenv(const tokens = unwrapped.tokens;const bin = executableName(tokens[0] ?? '');+ if (opts.gitConfigRead && (bin === 'git' || bin.startsWith('git-credential'))) {+ const read = gitConfigReadOf(tokens, workspaceRoots, opts, segmentCwds[segmentIndex]);+ if (read && !opts.gitConfigRead(read)) return true;+ }+if (bin === 'git') {const invocation = parseGitInvocation(tokens, workspaceRoots, opts);if (!invocation?.sub || !SAFE_GIT_SUBCOMMANDS.has(invocation.sub)) continue;@@ -6012,17 +6202,23 @@ function shellCommandReadsDotenv(return true;}if (gitContentReadWithoutPath(invocation.sub, invocation.args)- && classifyGit(tokens, segment, workspaceRoots, opts) === 'auto-approve') return true;+ && classifyGit(tokens, segment, workspaceRoots, opts) === 'auto-approve'+ && !opts.gitContentRead?.({+ sub: invocation.sub,+ args: invocation.args,+ cwd: gitInvocationCwd(tokens, segmentCwds[segmentIndex]),+ })) return true;continue;}if (!DOTENV_FILE_READER_BINS.has(bin)) continue;if (readsCredentialInput) return true;const args = tokens.slice(1);- if (grepRecursesIntoPotentialDotenv(bin, args)) return true;+ if (grepRecursesIntoPotentialDotenv(bin, args, selectorCouldMatch)) return true;if (bin === 'ag' && agSearchesPotentialCredential(args)) return true;- if (bin === 'rg' && rgSearchesPotentialDotenv(args)) return true;- if (readerArgumentsReadDotenv(bin, args, isDotenvCredentialPath, opts.platform ?? process.platform)) return true;+ if (bin === 'rg' && rgSearchesPotentialDotenv(args, selectorCouldMatch)) return true;+ if (readerArgumentsReadDotenv(+ bin, args, isDotenvCredentialPath, opts.platform ?? process.platform, selectorCouldMatch)) return true;}return false;}@@ -6080,7 +6276,7 @@ function matchesAnyVariant(patterns: readonly RegExp[], variants: ReturnType<typexport function shellCommandReadsCredentials(command: string,workspaceRoots: string[],- opts: ShellReviewOptions = {},+ opts: CredentialCommandOptions = {},): boolean {if (typeof command !== 'string' || command.trim().length === 0) return false;// 超长命令解析器不展开扫描,按需要确认处理(与 classifyShellCommand 同样不放过)。