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 credential redirect edge cases
Chris7e3af0b0fb64
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex ae74c0069e..1931aded0f 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -141,24 +141,42 @@ describe('cindy-bridge extension source', () => {target: ts.ScriptTarget.ES2022,},}).outputText;+ const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));const context: {realpathSync: typeof realpathSync;+ statSync: typeof statSync;+ path: typeof path;+ process: { cwd: () => string };collectResolvedCredentialPaths?: (input: unknown) => string[];bashInputReadTargets?: (input: unknown) => string[];- parseShellInputRedirections?: (command: string) => { command: string; targets: string[] };- } = { realpathSync };+ parseShellInputRedirections?: (command: string) => {+ command: string;+ targets: string[];+ targetPrefixes: string[];+ hasUnresolvedTarget: boolean;+ };+ } = { realpathSync, statSync, path, process: { cwd: () => tempRoot } };runInNewContext(compiled, context);- const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));try {const secretPath = path.join(tempRoot, 'secrets', '.env');const ordinaryPath = path.join(tempRoot, 'ordinary.txt');const secretLink = path.join(tempRoot, 'innocent.txt');const ordinaryLink = path.join(tempRoot, 'ordinary-link.txt');+ const nestedDir = path.join(tempRoot, 'nested');+ const dashDir = path.join(tempRoot, '-credential-dir');+ const nestedSecretLink = path.join(nestedDir, 'nested-innocent.txt');+ const dashSecretLink = path.join(dashDir, 'innocent.txt');+ const lateSecretLink = path.join(nestedDir, 'late-only-secret-link');mkdirSync(path.dirname(secretPath), { recursive: true });+ mkdirSync(nestedDir, { recursive: true });+ mkdirSync(dashDir, { recursive: true });writeFileSync(secretPath, 'FAKE PRIVATE KEY');writeFileSync(ordinaryPath, 'ordinary');symlinkSync(secretPath, secretLink);+ symlinkSync(secretPath, nestedSecretLink);+ symlinkSync(secretPath, dashSecretLink);+ symlinkSync(secretPath, lateSecretLink);symlinkSync(ordinaryPath, ordinaryLink);expect(context.collectResolvedCredentialPaths?.({ path: secretLink })).toEqual([@@ -176,6 +194,40 @@ describe('cindy-bridge extension source', () => {expect(context.collectResolvedCredentialPaths?.(context.bashInputReadTargets?.({ command: ordinaryCommand }),)).toEqual([]);+ const nestedCommand = `cd ${nestedDir} && cat <nested-innocent.txt`;+ expect(context.collectResolvedCredentialPaths?.(+ context.bashInputReadTargets?.({ command: nestedCommand }),+ )).toEqual([realpathSync(secretPath)]);+ const optionTerminatedCdCommand = 'cd -- -credential-dir && cat <innocent.txt';+ expect(context.collectResolvedCredentialPaths?.(+ context.bashInputReadTargets?.({ command: optionTerminatedCdCommand }),+ )).toEqual([realpathSync(secretPath)]);+ const quotedNoiseCommand = `printf '%s' '; cd a; cd b; cd c; cd d; cd e; cd f'; cd ${nestedDir}; cat <nested-innocent.txt`;+ expect(context.collectResolvedCredentialPaths?.(+ context.bashInputReadTargets?.({ command: quotedNoiseCommand }),+ )).toEqual([realpathSync(secretPath)]);+ const targetBeforeCdCommand = `cat <late-only-secret-link; cd ${nestedDir}`;+ expect(context.collectResolvedCredentialPaths?.(+ context.bashInputReadTargets?.({ command: targetBeforeCdCommand }),+ )).toEqual([]);+ const multilineCommand = `true # cat <ignored\ncd ${nestedDir}\ncat <nested-innocent.txt`;+ expect(context.collectResolvedCredentialPaths?.(+ context.bashInputReadTargets?.({ command: multilineCommand }),+ )).toEqual([realpathSync(secretPath)]);+ const dynamicCommand = 'cat <$(printf .env)';+ expect(context.parseShellInputRedirections?.(dynamicCommand)).toEqual({+ command: dynamicCommand,+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: true,+ });+ expect(context.bashInputReadTargets?.({ command: dynamicCommand })).toEqual([]);+ expect(context.parseShellInputRedirections?.('cat <>created')).toEqual({+ command: 'cat <>created',+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: false,+ });expect(source).toContain("event.toolName === 'bash' ? bashInputReadTargets(event.input) : []");expect(source).toContain('resolvedCredentialPaths: resolvedCredentialReadPaths');} finally {diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 1b5a4851ff..e1abb4eef1 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -121,7 +121,83 @@ ${SHELL_INPUT_REDIRECTION_PARSER_SOURCE}function bashInputReadTargets(input: unknown): string[] {if (!input || typeof input !== 'object') return [];const command = (input as Record<string, unknown>).command;- return typeof command === 'string' ? parseShellInputRedirections(command).targets : [];+ if (typeof command !== 'string') return [];+ const parsed = parseShellInputRedirections(command);+ return [...new Set(parsed.targets.flatMap((target, index) => {+ const cwdCandidates = bashWorkingDirectoryCandidates(parsed.targetPrefixes[index] ?? '');+ return path.isAbsolute(target)+ ? [target]+ : cwdCandidates.map((cwd) => path.resolve(cwd, target));+ }))];+}++function bashWorkingDirectoryCandidates(command: string): string[] {+ let candidates = [process.cwd()];+ const codeMask = bashShellCodeMask(command);+ const directoryChange = /(?:^|[;&|\n])\s*(?:command\s+)?(?:cd|pushd)\s+/g;+ for (const match of codeMask.matchAll(directoryChange)) {+ let cursor = (match.index ?? 0) + match[0].length;+ let parsed = readShellRedirectionTarget(command, cursor);+ let optionsEnded = false;+ while (parsed.target === '--' || /^-[LPen]+$/.test(parsed.target)) {+ if (parsed.target === '--') optionsEnded = true;+ cursor = parsed.end;+ while (/\s/.test(command[cursor] ?? '')) cursor += 1;+ parsed = readShellRedirectionTarget(command, cursor);+ }+ if (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-'))) continue;+ const operator = /^\s*(&&|\|\||[;\n|&])/.exec(command.slice(parsed.end))?.[1] ?? '';+ if (!operator || operator === '|' || operator === '&') continue;++ const changed: string[] = [];+ for (const cwd of candidates) {+ const candidate = path.resolve(cwd, parsed.target);+ try {+ if (statSync(candidate).isDirectory()) changed.push(candidate);+ } catch {+ // A failed cd leaves cwd unchanged for ;/newline, and skips the RHS of &&.+ }+ }+ if (operator === '||') {+ candidates = [...new Set([...candidates, ...changed])];+ } else if (changed.length > 0) {+ candidates = [...new Set(changed)];+ } else if (operator === '&&') {+ candidates = [];+ }+ }+ return candidates;+}++function bashShellCodeMask(command: string): string {+ let mask = '';+ let quote: "'" | '"' | null = null;+ for (let index = 0; index < command.length; index += 1) {+ const char = command[index];+ if (quote) {+ mask += /\s/.test(char) ? char : ' ';+ if (char === '\\' && quote === '"' && index + 1 < command.length) {+ index += 1;+ mask += /\s/.test(command[index]) ? command[index] : ' ';+ } else if (char === quote) {+ quote = null;+ }+ continue;+ }+ if (char === "'" || char === '"') {+ quote = char;+ mask += ' ';+ continue;+ }+ if (char === '\\' && index + 1 < command.length) {+ mask += ' ';+ index += 1;+ mask += /\s/.test(command[index]) ? command[index] : ' ';+ continue;+ }+ mask += char;+ }+ return mask;}// 递归扫全部字符串叶子(含数组 / 嵌套对象),深度上限防环/超大入参。工具入参把路径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 93595f478f..18998d5c3c 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,10 +390,17 @@ describe('对抗语料 — dotenv 凭证路径', () => {'env -- cat<.env.production','grep API_KEY<.env.test','cat<.e\\nv',+ 'cat <.e\\' + '\n' + 'nv',+ 'cat .e\\' + '\n' + 'nv','cat <".env"','cat 0<.env.local','env -- cat <./.env.production','grep API_KEY <.env.test',+ 'cat <$(printf .env)',+ 'cat <$TARGET',+ 'cat <"${TARGET}"',+ 'cat <`printf .env`',+ 'git cat-file --batch-check <$(printf .env)','cat /repo/.env && true',"cat /repo/.env | sed -n '1p'",'cat /repo/.env ',@@ -526,6 +533,15 @@ describe('对抗语料 — dotenv 凭证路径', () => {'git cat-file blob HEAD','git cat-file --batch','git cat-file --batch-command',+ 'git cat-file --batch-check <.env',+ 'git cat-file --batch-check<.env.local',+ 'git cat-file --batch-check <".env.production"',+ 'git blame --contents=.env README.md',+ 'git blame --contents .env.local README.md',+ 'git blame --contents=.env.production -- README.md',+ 'git blame --contents=.env* README.md',+ 'git blame --cont=.env README.md',+ 'git blame --cont .env.local README.md','git status -v','git status -vv','git show HEAD:.env.local',@@ -552,6 +568,14 @@ describe('对抗语料 — dotenv 凭证路径', () => {}});+ it.each([+ 'cat <>created',+ 'cat<>created',+ 'cat 3<>created',+ ])('%s 保留读写副作用审批', (command) => {+ expect(classifyShellCommand(command, roots, opts)).toBe('prompt');+ });+it('brace expansion 在全局候选预算内惰性遍历,超限时 fail-closed', () => {const explosiveOperand = Array.from({ length: 8 },@@ -569,6 +593,10 @@ describe('对抗语料 — dotenv 凭证路径', () => {["cat '<.env'", 'auto-approve'],['cat <<<.env', 'auto-approve'],['cat 0<README.md', 'auto-approve'],+ ['cat <*.txt', 'auto-approve'],+ ['cat README.md # example: cat <$TARGET', 'auto-approve'],+ ['cat README.md # example path: .env', 'auto-approve'],+ ["cat <'$TARGET'", 'auto-approve'],["grep '<.env' data.txt", 'auto-approve'],['grep KEY <data.txt', 'auto-approve'],['cat config.env.local', 'auto-approve'],@@ -632,6 +660,11 @@ describe('对抗语料 — dotenv 凭证路径', () => {['git cat-file blob HEAD:README.md', 'auto-approve'],['git cat-file -t HEAD', 'auto-approve'],['git cat-file --batch-check', 'auto-approve'],+ ['git cat-file --batch-check <README.md', 'auto-approve'],+ ['git cat-file --batch-check<ordinary.txt', 'auto-approve'],+ ['git blame --contents=README.md src/index.ts', 'auto-approve'],+ ['git blame --contents README.md src/index.ts', 'auto-approve'],+ ['git blame --cont=README.md src/index.ts', 'auto-approve'],['git status --short', 'auto-approve'],['git log --format=prefix:.env', 'auto-approve'],['git log --stat', 'auto-approve'],diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex 3d4696d10f..243bf90017 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -5109,6 +5109,24 @@ function isGitExcludePathspec(value: string): boolean {return value.startsWith(':!') || value.startsWith(':^');}+function gitBlameContentsReadDotenv(args: readonly string[]): boolean {+ for (let index = 0; index < args.length; index += 1) {+ const token = args[index];+ if (token === '--') break;+ if (!token.startsWith('--')) continue;+ const equalsIndex = token.indexOf('=');+ const name = equalsIndex >= 0 ? token.slice(0, equalsIndex) : token;+ const isContentsOption = name === '--contents'+ || (name.length >= '--cont'.length && '--contents'.startsWith(name));+ if (!isContentsOption) continue;+ const attached = equalsIndex >= 0 ? token.slice(equalsIndex + 1) : undefined;+ const value = attached ?? args[index + 1];+ if (value && shellOperandCouldMatchDotenv(value)) return true;+ if (attached === undefined) index += 1;+ }+ return false;+}+function gitArgumentsReadDotenv(args: readonly string[]): boolean {let pathspecOnly = false;for (let index = 0; index < args.length; index += 1) {@@ -5257,6 +5275,10 @@ function shellCommandReadsDotenv(): boolean {for (const segment of splitTopLevelSegments(command)) {const inputRedirections = parseShellInputRedirections(segment);+ if (inputRedirections.hasUnresolvedTarget) return true;+ const readsCredentialInput = inputRedirections.targets.some(+ (target) => shellOperandCouldMatchDotenv(target),+ );const unwrapped = unwrapCommand(stripShellControlTokens(tokenize(inputRedirections.command)),opts.cwd ?? workspaceRoots[0],@@ -5268,10 +5290,12 @@ function shellCommandReadsDotenv(if (bin === 'git') {const invocation = parseGitInvocation(tokens, workspaceRoots, opts);if (!invocation?.sub || !SAFE_GIT_SUBCOMMANDS.has(invocation.sub)) continue;+ if (readsCredentialInput) return true;if (invocation.sub === 'grep') {if (gitGrepExpandsSearchScope(invocation.args)) return true;if (readerArgumentsReadDotenv('grep', invocation.args, isGitDotenvOperand)) return true;- } else if (gitArgumentsReadDotenv(invocation.args)) {+ } else if ((invocation.sub === 'blame' && gitBlameContentsReadDotenv(invocation.args))+ || gitArgumentsReadDotenv(invocation.args)) {return true;}if (gitContentReadWithoutPath(invocation.sub, invocation.args)@@ -5280,7 +5304,7 @@ function shellCommandReadsDotenv(}if (!DOTENV_FILE_READER_BINS.has(bin)) continue;- if (inputRedirections.targets.some((target) => shellOperandCouldMatchDotenv(target))) return true;+ if (readsCredentialInput) return true;const args = tokens.slice(1);if (grepRecursesIntoPotentialDotenv(bin, args)) return true;if (bin === 'rg' && rgSearchesPotentialDotenv(args)) return true;diff --git a/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts b/packages/maker-core/src/agents/shared/shell-input-redirections.test.tsindex 40324a96f7..94178c0312 100644--- a/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts@@ -9,11 +9,68 @@ describe('parseShellInputRedirections', () => {['env -- cat 0<./.env.production', './.env.production', 'env -- cat 0'],['cat<.e"nv"', '.env', 'cat'],['cat<.e\\nv', '.env', 'cat'],- ['cat<>README.md', 'README.md', 'cat'],- ])('extracts the input target from %s', (command, target, stripped) => {+ ["cat <'$TARGET'", '$TARGET', 'cat'],+ ['cat <*.txt', '*.txt', 'cat'],+ ])('extracts the static input target from %s', (command, target, stripped) => {const parsed = parseShellInputRedirections(command);expect(parsed.command.trim()).toBe(stripped);expect(parsed.targets).toEqual([target]);+ expect(parsed.targetPrefixes).toHaveLength(1);+ expect(parsed.hasUnresolvedTarget).toBe(false);+ });++ it.each([+ 'cat <$(printf .env)',+ 'cat <$TARGET',+ 'cat <"${TARGET}"',+ 'cat <`printf .env`',+ ])('preserves dynamic input targets for fail-closed classification: %s', (command) => {+ expect(parseShellInputRedirections(command)).toEqual({+ command,+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: true,+ });+ });++ it('normalizes shell line continuations inside static targets', () => {+ const command = 'cat <.e\\' + '\n' + 'nv';+ expect(parseShellInputRedirections(command)).toEqual({+ command: 'cat ',+ targets: ['.env'],+ targetPrefixes: ['cat '],+ hasUnresolvedTarget: false,+ });+ });++ it('normalizes shell line continuations outside redirection targets', () => {+ const command = 'cat .e\\' + '\n' + 'nv';+ expect(parseShellInputRedirections(command)).toEqual({+ command: 'cat .env',+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: false,+ });+ });++ it('skips comments only through the current line and resumes target scanning', () => {+ const command = 'true # cat <$TARGET\ncat <.env';+ expect(parseShellInputRedirections(command)).toEqual({+ command: 'true \ncat ',+ targets: ['.env'],+ targetPrefixes: ['true \ncat '],+ hasUnresolvedTarget: false,+ });+ });++ it('leaves redirection-like text in comments out of the classified command', () => {+ const command = 'cat README.md # example: cat <$TARGET';+ expect(parseShellInputRedirections(command)).toEqual({+ command: 'cat README.md ',+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: false,+ });});it.each([@@ -24,7 +81,14 @@ describe('parseShellInputRedirections', () => {'cat <&0','cat <(printf x)','cat \\<.env',- ])('does not treat data or non-file input syntax as a target: %s', (command) => {- expect(parseShellInputRedirections(command)).toEqual({ command, targets: [] });+ 'cat <>created',+ 'cat 3<>created',+ ])('does not treat data or non-input-file syntax as a target: %s', (command) => {+ expect(parseShellInputRedirections(command)).toEqual({+ command,+ targets: [],+ targetPrefixes: [],+ hasUnresolvedTarget: false,+ });});});diff --git a/packages/maker-core/src/agents/shared/shell-input-redirections.ts b/packages/maker-core/src/agents/shared/shell-input-redirections.tsindex d4eb178a8d..b6f042a2ac 100644--- a/packages/maker-core/src/agents/shared/shell-input-redirections.ts+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.ts@@ -1,14 +1,17 @@export type ParsedShellInputRedirections = {command: string;targets: string[];+ targetPrefixes: string[];+ hasUnresolvedTarget: boolean;};export function readShellRedirectionTarget(command: string,start: number,-): { target: string; end: number } {+): { target: string; end: number; unresolved: boolean } {let target = '';let quote: "'" | '"' | null = null;+ let unresolved = false;let cursor = start;while (cursor < command.length) {const char = command[cursor];@@ -19,21 +22,23 @@ export function readShellRedirectionTarget(continue;}if (char === '\\' && quote === '"' && cursor + 1 < command.length) {- target += command[cursor + 1];+ if (command[cursor + 1] !== '\n') target += command[cursor + 1];cursor += 2;continue;}+ if (quote === '"' && (char === '$' || char.charCodeAt(0) === 96)) unresolved = true;target += char;cursor += 1;continue;}+ if (char === '$' || char.charCodeAt(0) === 96) unresolved = true;if (char === "'" || char === '"') {quote = char;cursor += 1;continue;}if (char === '\\' && cursor + 1 < command.length) {- target += command[cursor + 1];+ if (command[cursor + 1] !== '\n') target += command[cursor + 1];cursor += 2;continue;}@@ -41,30 +46,32 @@ export function readShellRedirectionTarget(target += char;cursor += 1;}- return { target, end: cursor };+ return { target, end: cursor, unresolved };}export function parseShellInputRedirections(command: string): ParsedShellInputRedirections {const targets: string[] = [];+ const targetPrefixes: string[] = [];let stripped = '';let quote: "'" | '"' | null = null;+ let hasUnresolvedTarget = false;for (let index = 0; index < command.length;) {const char = command[index];if (quote) {- stripped += char;if (char === '\\' && quote === '"' && index + 1 < command.length) {- stripped += command[index + 1];+ if (command[index + 1] !== '\n') stripped += char + command[index + 1];index += 2;continue;}+ stripped += char;if (char === quote) quote = null;index += 1;continue;}if (char === '\\' && index + 1 < command.length) {- stripped += char + command[index + 1];+ if (command[index + 1] !== '\n') stripped += char + command[index + 1];index += 2;continue;}@@ -74,6 +81,13 @@ export function parseShellInputRedirections(command: string): ParsedShellInputReindex += 1;continue;}+ if (char === '#' && (index === 0 || /[\s;&|()]/.test(command[index - 1] ?? ''))) {+ const newline = command.indexOf('\n', index);+ if (newline < 0) break;+ stripped += '\n';+ index = newline + 1;+ continue;+ }if (char !== '<') {stripped += char;index += 1;@@ -88,21 +102,32 @@ export function parseShellInputRedirections(command: string): ParsedShellInputReindex = end;continue;}+ if (next === '>') {+ stripped += '<>';+ index += 2;+ continue;+ }if (next === '&' || next === '(') {stripped += char + next;index += 2;continue;}- let cursor = index + (next === '>' ? 2 : 1);+ let cursor = index + 1;while (/\s/.test(command[cursor] ?? '')) cursor += 1;const parsedTarget = readShellRedirectionTarget(command, cursor);- if (parsedTarget.target) targets.push(parsedTarget.target);- stripped += ' ';+ if (!parsedTarget.target || parsedTarget.unresolved) {+ hasUnresolvedTarget = true;+ stripped += command.slice(index, parsedTarget.end);+ } else {+ targets.push(parsedTarget.target);+ targetPrefixes.push(stripped);+ stripped += ' ';+ }index = parsedTarget.end;}- return { command: stripped, targets };+ return { command: stripped, targets, targetPrefixes, hasUnresolvedTarget };}export function shellInputRedirectionParserSource(): string {