Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): close implicit dotenv read gaps
Chris78bb31f88a8d
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.tsindex 8b40de3e53..02c78ac2ef 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts@@ -165,7 +165,7 @@ describe('classifyBuiltinToolForAutoReview — Bash 只读命令放行', () => {}});it('git 只读子命令 auto-approve', () => {- for (const c of ['git status', 'git log --oneline', 'git diff HEAD', 'git show abc', 'git branch', 'git config --get user.name']) {+ for (const c of ['git status', 'git log --oneline', 'git diff HEAD -- README.md', 'git show abc', 'git branch', 'git config --get user.name']) {expect(verdict('Bash', { command: c })).toBe('auto-approve');}});diff --git a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.tsindex 0ce9545c74..e877409463 100644--- a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts+++ b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts@@ -390,6 +390,11 @@ describe('对抗语料 — dotenv 凭证路径', () => {'cat /repo/.env # inspect configuration','cat "/repo/.env.local"; true','cat ./.env.production.local',+ 'cat .env* && true',+ 'cat .env{,.local}',+ 'cat .e{n..n}v',+ 'head ./.env* | tail -1',+ 'env -- cat .env*','grep KEY .env.local && true','sed -n 1p .env.test','grep -f .env data.txt',@@ -429,11 +434,30 @@ describe('对抗语料 — dotenv 凭证路径', () => {'command grep --recursive API_KEY .','printf x | grep -r API_KEY .',"rg --hidden -g '.env*' API_KEY .",+ "rg --hidden -g '!.env*' -g '.env' API_KEY .",+ 'rg --hidden --no-ignore API_KEY .',+ 'rg -uu API_KEY .',+ 'rg -uuu API_KEY .',+ 'env -- rg --hidden --no-ignore API_KEY .',+ 'command rg -uuu API_KEY .',+ 'rg --no-ignore --hidden API_KEY . && true','grep -r --exclude-from=.env API_KEY .','rg --ignore-file=.env API_KEY .','grep --fil=.env.local data.txt','sed --fil=.env.production data.txt','git --no-pager diff --no-index /dev/null .env',+ 'git diff',+ 'git diff HEAD',+ 'git diff --stat -U0',+ 'git diff --stat --word-diff',+ 'git diff --stat --binary',+ 'git diff -- .env*',+ 'env -- git diff',+ 'git status --short && git diff',+ 'git grep API_KEY',+ 'git grep -- API_KEY',+ 'git grep -e-l',+ 'command git grep API_KEY','git diff -- .env.local | head','git show HEAD:.env','git show HEAD:.env.local',@@ -452,13 +476,18 @@ describe('对抗语料 — dotenv 凭证路径', () => {'command git grep --no-index .','git status --short && git grep --untracked .',]) {- expect(classifyShellCommand(command, roots, opts)).toBe('prompt-each-time');+ expect(classifyShellCommand(command, roots, opts), command).toBe('prompt-each-time');}});it.each([['cat .environment', 'auto-approve'],['cat config.env.local', 'auto-approve'],+ ['cat *', 'auto-approve'],+ ['cat *.env', 'auto-approve'],+ ['cat .environment*', 'auto-approve'],+ ['cat .env{1..3}', 'auto-approve'],+ ['cat config.env*', 'auto-approve'],['echo .env', 'auto-approve'],['jq .env data.json', 'auto-approve'],['grep .env data.json', 'auto-approve'],@@ -473,6 +502,12 @@ describe('对抗语料 — dotenv 凭证路径', () => {["rg -g '[!.]*.ts' KEY .", 'auto-approve'],["grep -r --include='[!.]*.json' KEY .", 'auto-approve'],["rg --hidden -g '[!.]*.ts' KEY .", 'auto-approve'],+ ['rg --no-ignore KEY .', 'auto-approve'],+ ['rg -u KEY .', 'auto-approve'],+ ['rg --hidden --no-hidden KEY .', 'auto-approve'],+ ['rg -uu --no-hidden KEY .', 'auto-approve'],+ ['rg -e --hidden data.txt', 'auto-approve'],+ ['rg -- --hidden data.txt', 'auto-approve'],["grep -r --include='[!.]*.ts' KEY .", 'auto-approve'],["grep -r --include='config.env*' KEY .", 'auto-approve'],['grep -e -r data.txt', 'auto-approve'],@@ -489,7 +524,16 @@ describe('对抗语料 — dotenv 凭证路径', () => {['env -- grep -e -r data.txt', 'auto-approve'],["rg --hidden -g '!.env*' KEY .", 'auto-approve'],['git --no-pager diff --no-index /dev/null README.md', 'auto-approve'],- ['git grep .env data.json', 'auto-approve'],+ ['git diff --stat', 'auto-approve'],+ ['git diff --name-only', 'auto-approve'],+ ['git diff -- README.md', 'auto-approve'],+ ['git diff HEAD -- README.md', 'auto-approve'],+ ['git grep .env -- data.json', 'auto-approve'],+ ['git grep -- .env data.json', 'auto-approve'],+ ['git grep -e API_KEY -- README.md', 'auto-approve'],+ ['git grep -l API_KEY', 'auto-approve'],+ ['git grep -L API_KEY', 'auto-approve'],+ ['git grep --files-with-matches API_KEY', 'auto-approve'],['git show HEAD:README.md', 'auto-approve'],['git cat-file -p HEAD:README.md', 'auto-approve'],['git log --format=prefix:.env', 'auto-approve'],diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.tsindex b16af1dcad..11adc3fb0b 100644--- a/packages/maker-core/src/agents/shared/auto-review.test.ts+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts@@ -89,13 +89,13 @@ describe('classifyShellCommand — 只读放行', () => {'git -C /repo status','git -C /repo show HEAD','git -C/repo log --oneline',- 'git --namespace=review -C /repo diff HEAD',+ 'git --namespace=review -C /repo diff HEAD -- README.md',]) {expect(classifyShellCommand(c, roots), c).toBe('auto-approve');}});it('子命令自身的 -c 参数不被当作危险全局选项', () => {- for (const c of ['git diff -c', 'git show -c']) {+ for (const c of ['git diff -c -- README.md', 'git show -c']) {expect(classifyShellCommand(c, roots), c).toBe('auto-approve');}});@@ -526,10 +526,10 @@ describe('reviewAction / classifyShellCommand — agent OAuth 凭证文件', ()});describe('classifyShellCommand — git --output 写文件 / curl SSRF 改路由 / wget 一律升级', () => {- it('git diff --output 写文件(无 shell >)→ prompt;普通 git diff 仍放行', () => {+ it('git diff --output 写文件(无 shell >)→ prompt;显式普通 path 的 git diff 仍放行', () => {expect(classifyShellCommand('git diff --output ~/.bashrc HEAD^ HEAD', roots)).toBe('prompt');expect(classifyShellCommand('git diff --output=/tmp/x HEAD', roots)).toBe('prompt');- expect(classifyShellCommand('git diff HEAD', roots)).toBe('auto-approve');+ expect(classifyShellCommand('git diff HEAD -- README.md', roots)).toBe('auto-approve');});it('curl 改路由 flag(--resolve/--connect-to/--unix-socket/-x/--proxy)→ prompt(SSRF 绕过)', () => {for (const c of [@@ -575,11 +575,11 @@ describe('classifyShellCommand — procfs / 短选项绕过 / 反斜杠 / git RCit('反斜杠转义拆分 flag(find -ex\\ec)去转义后命中', () => {expect(classifyShellCommand("find . -ex\\ec sh -c 'x' {} +", roots)).toBe('prompt');});- it('git --ext-diff / 内联 -c(core.pager/diff.external)→ prompt(RCE);普通 git diff 仍放行', () => {+ it('git --ext-diff / 内联 -c(core.pager/diff.external)→ prompt(RCE);显式普通 path 的 git diff 仍放行', () => {expect(classifyShellCommand('git diff --ext-diff', roots)).toBe('prompt');expect(classifyShellCommand('git -c core.pager=evil show HEAD', roots)).toBe('prompt');expect(classifyShellCommand('git -c diff.external=evil diff', roots)).toBe('prompt');- expect(classifyShellCommand('git diff HEAD', roots)).toBe('auto-approve');+ expect(classifyShellCommand('git diff HEAD -- README.md', roots)).toBe('auto-approve');});});@@ -860,8 +860,8 @@ describe('classifyShellCommand — 第三轮 bot 审查回归护栏', () => {for (const c of ['git grep --open-files-in-pager=./payload pattern', 'git grep -O./payload pattern']) {expect(classifyShellCommand(c, roots)).toBe('prompt');}- // 反例:普通 git grep 仍放行。- expect(classifyShellCommand('git grep pattern', roots)).toBe('auto-approve');+ // 反例:显式普通 path 的 git grep 仍放行。+ expect(classifyShellCommand('git grep pattern -- README.md', roots)).toBe('auto-approve');});it('git 子命令前内联 config 的等号形式(--config-env=…)升级 —— 防 core.pager RCE', () => {diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex a18f739322..1aa994fa1e 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -1794,7 +1794,7 @@ function stripShellControlTokens(tokens: string[]): string[] {if (out[0]) out[0] = out[0].replace(/^[({]+/, '');while (out[0] === '') out.shift();const last = out.length - 1;- if (last >= 0 && !/[$<]\(/.test(out[last])) {+ if (last >= 0 && !/[$<]\(/.test(out[last]) && !out[last].includes('{')) {out[last] = out[last].replace(/[)}]+$/, '');if (out[last] === '') out.pop();}@@ -4802,16 +4802,38 @@ function selectorAlternativeCannotMatchDotenv(value: string): boolean {if (!/[*?\[]/.test(basename)) return !isDotenvCredentialPath(value);if (/^\[(?:!|\^)\.\]/.test(basename)) return true;const literalPrefix = basename.slice(0, basename.search(/[*?\[]/));- return Boolean(literalPrefix)- && !'.env'.startsWith(literalPrefix)- && !literalPrefix.startsWith('.env');+ const couldStartDotenv = '.env'.startsWith(literalPrefix) || literalPrefix.startsWith('.env.');+ return Boolean(literalPrefix) && !couldStartDotenv;+}++function expandBraceSequence(value: string): string[] | null {+ const match = /^(-?\d+|[A-Za-z])\.\.(-?\d+|[A-Za-z])(?:\.\.(-?\d+))?$/.exec(value);+ if (!match) return null;+ const numeric = /^-?\d+$/.test(match[1]) && /^-?\d+$/.test(match[2]);+ const alphabetic = /^[A-Za-z]$/.test(match[1]) && /^[A-Za-z]$/.test(match[2]);+ if (!numeric && !alphabetic) return ['*'];+ const start = numeric ? Number(match[1]) : match[1].charCodeAt(0);+ const end = numeric ? Number(match[2]) : match[2].charCodeAt(0);+ const step = match[3] ? Math.abs(Number(match[3])) : 1;+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || !Number.isSafeInteger(step) || step === 0) return ['*'];+ const count = Math.floor(Math.abs(end - start) / step) + 1;+ if (count > 64) return ['*'];+ const direction = start <= end ? 1 : -1;+ return Array.from({ length: count }, (_, index) => {+ const item = start + (index * step * direction);+ return numeric ? String(item) : String.fromCharCode(item);+ });}function expandBraceAlternatives(value: string, depth = 0): string[] {if (depth >= 8) return ['*'];- const match = /^(.*?)\{([^{}]*,[^{}]*)\}(.*)$/.exec(value);+ const match = /^(.*?)\{([^{}]+)\}(.*)$/.exec(value);if (!match) return [value];- return match[2].split(',').flatMap((alternative) =>+ const alternatives = match[2].includes(',')+ ? match[2].split(',')+ : expandBraceSequence(match[2]);+ if (!alternatives) return [value];+ return alternatives.flatMap((alternative) =>expandBraceAlternatives(`${match[1]}${alternative}${match[3]}`, depth + 1));}@@ -4820,6 +4842,17 @@ function selectorCouldMatchDotenv(value: string): boolean {.some((alternative) => !selectorAlternativeCannotMatchDotenv(alternative));}+function shellOperandCouldMatchDotenv(+ value: string,+ exactMatcher: (candidate: string) => boolean = isDotenvCredentialPath,+): boolean {+ if (exactMatcher(value)) return true;+ return expandBraceAlternatives(value).some((alternative) => {+ const basename = alternative.replace(/\\/g, '/').split('/').pop() ?? '';+ return basename.startsWith('.') && !selectorAlternativeCannotMatchDotenv(alternative);+ });+}+function readerArgumentsReadDotenv(bin: string,args: readonly string[],@@ -4845,7 +4878,7 @@ function readerArgumentsReadDotenv(const isSensitive = kind === 'selector'? selectorCouldMatchDotenv(value ?? ''): (kind === 'data-file' || kind === 'aux-file')- && Boolean(value && isSensitiveOperand(value));+ && Boolean(value && shellOperandCouldMatchDotenv(value, isSensitiveOperand));if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -4863,7 +4896,7 @@ function readerArgumentsReadDotenv(const isSensitive = kind === 'selector'? selectorCouldMatchDotenv(value ?? ''): (kind === 'data-file' || kind === 'aux-file')- && Boolean(value && isSensitiveOperand(value));+ && Boolean(value && shellOperandCouldMatchDotenv(value, isSensitiveOperand));if (kind !== 'data' && isSensitive) return true;if (attached === undefined) index += 1;if (kind === 'data' || kind === 'data-file') dataArgumentProvided = true;@@ -4878,7 +4911,7 @@ function readerArgumentsReadDotenv(dataArgumentProvided = true;continue;}- if (isSensitiveOperand(token)) return true;+ if (shellOperandCouldMatchDotenv(token, isSensitiveOperand)) return true;}return false;}@@ -4944,6 +4977,47 @@ function grepRecursesIntoPotentialDotenv(bin: string, args: readonly string[]):return recursive && (includes.length === 0 || includes.some(selectorCouldMatchDotenv));}+function rgSearchesPotentialDotenv(args: readonly string[]): boolean {+ let hidden = false;+ let unrestricted = 0;+ const globs: string[] = [];+ for (let index = 0; index < args.length; index += 1) {+ const token = args[index];+ if (token === '--') break;+ if (token === '--hidden') { hidden = true; continue; }+ if (token === '--no-hidden') { hidden = false; continue; }+ if (token.startsWith('--')) {+ const equalsIndex = token.indexOf('=');+ const name = equalsIndex >= 0 ? token.slice(0, equalsIndex) : token;+ const kind = resolveReaderLongOption('rg', name);+ if (!kind) continue;+ const attached = equalsIndex >= 0 ? token.slice(equalsIndex + 1) : undefined;+ const value = attached ?? args[index + 1];+ if (attached === undefined) index += 1;+ if (kind === 'selector' && value) globs.push(value);+ continue;+ }+ if (!/^-[^-]/.test(token)) continue;+ for (let optionIndex = 1; optionIndex < token.length; optionIndex += 1) {+ const option = token.charAt(optionIndex);+ if (option === 'u') { unrestricted += 1; if (unrestricted >= 2) hidden = true; continue; }+ const kind = readerShortOptionKind('rg', option);+ if (!kind) continue;+ const attached = token.slice(optionIndex + 1) || undefined;+ const value = attached ?? args[index + 1];+ if (attached === undefined) index += 1;+ if (kind === 'selector' && value) globs.push(value);+ break;+ }+ }+ const positive = globs.filter((glob) => !glob.startsWith('!'));+ const positiveCouldMatchDotenv = positive.some(selectorCouldMatchDotenv);+ const excludesDotenv = !positiveCouldMatchDotenv+ && globs.some((glob) => glob === '!.env*' || glob === '!**/.env*');+ const positiveIsSafe = positive.length > 0 && !positiveCouldMatchDotenv;+ return hidden && !excludesDotenv && !positiveIsSafe;+}+function gitGrepExpandsSearchScope(args: readonly string[]): boolean {for (let index = 0; index < args.length; index += 1) {const token = args[index];@@ -5006,12 +5080,61 @@ function gitArgumentsReadDotenv(args: readonly string[]): boolean {index += 1;continue;}- if (isGitDotenvOperand(token)) return true;+ if (shellOperandCouldMatchDotenv(token, isGitDotenvOperand)) return true;if (!pathspecOnly && isGitRevisionDotenvOperand(token)) return true;}return false;}+function gitGrepHasExplicitPathspec(args: readonly string[]): boolean {+ const separator = args.indexOf('--');+ if (separator < 0) return false;+ let patternProvided = false;+ for (let index = 0; index < separator; index += 1) {+ const token = args[index];+ if (token.startsWith('-')) {+ const equalsIndex = token.indexOf('=');+ const name = equalsIndex >= 0 ? token.slice(0, equalsIndex) : token;+ const kind = token.startsWith('--')+ ? resolveReaderLongOption('grep', name)+ : [...token.slice(1)].map((option) => readerShortOptionKind('grep', option)).find(Boolean);+ if (kind && equalsIndex < 0 && !/^-[^-].+/.test(token)) index += 1;+ if (kind === 'data' || kind === 'data-file') patternProvided = true;+ continue;+ }+ patternProvided = true;+ }+ return args.length - separator - 1 >= (patternProvided ? 1 : 2);+}++function gitGrepListsOnly(args: readonly string[]): boolean {+ for (const token of args) {+ if (token === '--') break;+ if (token === '--files-with-matches' || token === '--files-without-match' || token === '--name-only') return true;+ if (!/^-[^-]/.test(token)) continue;+ for (let index = 1; index < token.length; index += 1) {+ const option = token.charAt(index);+ if (option === 'e' || option === 'f') break;+ if (option === 'l' || option === 'L') return true;+ }+ }+ return false;+}++function gitContentReadWithoutPath(sub: string, args: readonly string[]): boolean {+ if (sub === 'grep') return !gitGrepListsOnly(args) && !gitGrepHasExplicitPathspec(args);+ if (sub !== 'diff') return false;+ const separator = args.indexOf('--');+ if (separator >= 0 && separator < args.length - 1) return false;+ if (args.includes('--no-index') && args.filter((arg) => !arg.startsWith('-')).length >= 2) return false;+ const metadataOnly = args.some((arg) => [+ '--stat', '--shortstat', '--numstat', '--name-only', '--name-status', '--summary', '--check', '--raw',+ ].includes(arg));+ const patchRequested = args.some((arg) =>+ /^(?:-p|--patch|-u|-U\d*|--unified(?:=.*)?|-W|--function-context|--word-diff(?:=.*)?|--word-diff-regex(?:=.*)?|--color-words(?:=.*)?|--patch-with-stat|--patch-with-raw|--binary|--inter-hunk-context(?:=.*)?)$/.test(arg));+ return !metadataOnly || patchRequested;+}+function shellCommandReadsDotenv(command: string,workspaceRoots: string[],@@ -5035,12 +5158,15 @@ function shellCommandReadsDotenv(} else if (gitArgumentsReadDotenv(invocation.args)) {return true;}+ if (gitContentReadWithoutPath(invocation.sub, invocation.args)+ && classifyGit(tokens, segment, workspaceRoots, opts) === 'auto-approve') return true;continue;}if (!DOTENV_FILE_READER_BINS.has(bin)) continue;const args = tokens.slice(1);if (grepRecursesIntoPotentialDotenv(bin, args)) return true;+ if (bin === 'rg' && rgSearchesPotentialDotenv(args)) return true;if (readerArgumentsReadDotenv(bin, args)) return true;}return false;