Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): bound redirect glob evidence
Chrisfcabdac46845
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex 8f337562b7..2e2f01f8c7 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -4,6 +4,7 @@ import {lstatSync,mkdtempSync,mkdirSync,+ opendirSync,readFileSync,realpathSync,rmSync,@@ -217,6 +218,7 @@ describe('cindy-bridge extension source', () => {const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));const context: {globSync: typeof globSync;+ opendirSync: typeof opendirSync;realpathSync: typeof realpathSync;statSync: typeof statSync;path: typeof path;@@ -237,6 +239,7 @@ describe('cindy-bridge extension source', () => {) => string[] | null;} = {globSync,+ opendirSync,realpathSync,statSync,path,@@ -269,12 +272,38 @@ describe('cindy-bridge extension source', () => {const cwdSwitchName = 'cwd-switch-link';const rootCwdSwitchOrdinaryLink = path.join(tempRoot, cwdSwitchName);const nestedCwdSwitchSecretLink = path.join(nestedDir, cwdSwitchName);+ const ordinaryGlobDir = path.join(tempRoot, 'ordinary-glob');+ const ordinaryGlobPath = path.join(ordinaryGlobDir, 'ordinary.txt');+ const dotglobDir = path.join(tempRoot, 'dotglob-only');+ const dotglobSecretPath = path.join(dotglobDir, '.env');+ const largeGlobDir = path.join(tempRoot, 'large-glob');+ const workGlobDir = path.join(tempRoot, 'work-glob');+ const deepGlobDir = path.join(tempRoot, 'deep-glob');mkdirSync(path.dirname(secretPath), { recursive: true });mkdirSync(nestedDir, { recursive: true });mkdirSync(dashDir, { recursive: true });mkdirSync(cdPathSubDir, { recursive: true });+ mkdirSync(ordinaryGlobDir);+ mkdirSync(dotglobDir);+ mkdirSync(largeGlobDir);+ mkdirSync(workGlobDir);+ mkdirSync(deepGlobDir);writeFileSync(secretPath, 'FAKE PRIVATE KEY');writeFileSync(ordinaryPath, 'ordinary');+ writeFileSync(ordinaryGlobPath, 'ordinary glob content');+ writeFileSync(dotglobSecretPath, 'DOTGLOB_SECRET=must-not-leak');+ for (let index = 0; index <= 1_024; index += 1) {+ writeFileSync(path.join(largeGlobDir, `match-${index}.txt`), 'ordinary');+ }+ for (let index = 0; index < 4_096; index += 1) {+ writeFileSync(path.join(workGlobDir, `nonmatch-${index}.txt`), 'ordinary');+ }+ let deepCursor = deepGlobDir;+ for (let depth = 0; depth <= 64; depth += 1) {+ deepCursor = path.join(deepCursor, `level-${depth}`);+ mkdirSync(deepCursor);+ }+ writeFileSync(path.join(deepCursor, 'ordinary.txt'), 'ordinary');symlinkSync(secretPath, secretLink);symlinkSync(secretPath, nestedSecretLink);symlinkSync(secretPath, dashSecretLink);@@ -351,6 +380,26 @@ describe('cindy-bridge extension source', () => {context.bashInputReadTargets?.({ command: expandedCommand }),), expandedCommand).toEqual([realpathSync(secretPath)]);}+ expect(context.bashInputReadEvidence?.({+ command: `cd ${ordinaryGlobDir} && cat <*.txt`,+ })).toEqual({ targets: [ordinaryGlobPath], unresolved: false });+ expect(context.bashInputReadEvidence?.({+ command: `cd ${largeGlobDir} && cat <*.txt`,+ })).toEqual({ targets: [], unresolved: true });+ expect(context.bashInputReadEvidence?.({+ command: `cd ${workGlobDir} && cat <*.json`,+ })).toEqual({ targets: [], unresolved: true });+ expect(context.bashInputReadEvidence?.({+ command: `cd ${deepGlobDir} && cat <**/*`,+ })).toEqual({ targets: [], unresolved: true });+ context.process.env.BASHOPTS = 'checkwinsize:dotglob';+ expect(context.bashInputReadEvidence?.({+ command: `cd ${dotglobDir} && cat <*>`,+ })).toEqual({ targets: [], unresolved: true });+ delete context.process.env.BASHOPTS;+ expect(context.bashInputReadEvidence?.({+ command: `cd ${ordinaryGlobDir} && cat <*.txt`,+ })).toEqual({ targets: [ordinaryGlobPath], unresolved: false });expect(context.collectResolvedCredentialPaths?.(context.bashInputReadTargets?.({ command: "cat <>'innocent.*'" }),)).toEqual([]);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.tsindex d5732a7674..e5753725f1 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts@@ -2177,6 +2177,78 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa},);+ it.skipIf(process.platform === 'win32')(+ 'redirect globs fail closed on inherited Bash options while ordinary globs stay fast',+ { timeout: 60_000 },+ async () => {+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-bash-glob-options-'));+ const previousBashOptions = process.env.BASHOPTS;+ try {+ writeFileSync(path.join(workingDir, '.env'), 'FAKE_DOTGLOB_SECRET=must-not-leak');+ writeFileSync(path.join(workingDir, 'ordinary.txt'), 'ordinary-glob-content');+ process.env.BASHOPTS = 'dotglob';++ scriptedResponses.length = 0;+ scriptedResponses.push(+ anthropicToolUseBody('bash', { command: 'cat <*' }),+ anthropicStreamBody('bash dotglob turn finished'),+ );+ const autoReqBefore = seenRequests.length;+ const autoTurn = await runPermissionTurn({+ sessionId: 'perm-auto-bash-dotglob',+ workingDir,+ permissionMode: 'auto',+ resolverBehavior: 'deny',+ });+ expect(autoTurn.resolverTools).toEqual(['bash']);+ const autoFollowUp = seenRequests.slice(autoReqBefore).map((request) => request.body);+ expect(autoFollowUp.some((body) => body.includes('FAKE_DOTGLOB_SECRET'))).toBe(false);+ expect(autoFollowUp.some((body) => body.includes('User denied this tool call via Cindy.'))).toBe(true);++ scriptedResponses.length = 0;+ scriptedResponses.push(+ anthropicToolUseBody('bash', { command: 'cat <*' }),+ anthropicStreamBody('bash Full Access dotglob turn finished'),+ );+ const fullAccessReqBefore = seenRequests.length;+ const fullAccessTurn = await runPermissionTurn({+ sessionId: 'perm-full-access-bash-dotglob',+ workingDir,+ permissionMode: 'bypassPermissions',+ resolverBehavior: 'allow',+ });+ expect(fullAccessTurn.resolverTools).toEqual([]);+ const fullAccessFollowUp = seenRequests.slice(fullAccessReqBefore).map((request) => request.body);+ expect(fullAccessFollowUp.some((body) => body.includes('FAKE_DOTGLOB_SECRET'))).toBe(false);+ expect(fullAccessFollowUp.some((body) => body.includes('Cindy blocks reading credential or key paths')))+ .toBe(true);++ delete process.env.BASHOPTS;+ scriptedResponses.length = 0;+ scriptedResponses.push(+ anthropicToolUseBody('bash', { command: 'cat <ordinary*' }),+ anthropicStreamBody('bash ordinary glob turn finished'),+ );+ const ordinaryReqBefore = seenRequests.length;+ const ordinaryTurn = await runPermissionTurn({+ sessionId: 'perm-auto-bash-ordinary-glob',+ workingDir,+ permissionMode: 'auto',+ resolverBehavior: 'deny',+ });+ expect(ordinaryTurn.resolverTools).toEqual([]);+ const ordinaryFollowUp = seenRequests.slice(ordinaryReqBefore).map((request) => request.body);+ expect(ordinaryFollowUp.some((body) => body.includes('ordinary-glob-content'))).toBe(true);+ expect(ordinaryFollowUp.some((body) => body.includes('FAKE_DOTGLOB_SECRET'))).toBe(false);+ } finally {+ if (previousBashOptions === undefined) delete process.env.BASHOPTS;+ else process.env.BASHOPTS = previousBashOptions;+ rmSync(workingDir, { recursive: true, force: true });+ scriptedResponses.length = 0;+ }+ },+ );+it.skipIf(process.platform === 'win32' || !canSymlink)('auto mode fail closes inherited CDPATH while explicit relative cd keeps ordinary reads fast',{ timeout: 60_000 },diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 66560a8fee..382bbbcf43 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -52,7 +52,7 @@ export const CINDY_BRIDGE_EXTENSION_FILENAME = "cindy-bridge.ts";export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/*** cindy-bridge (generated by Cindy — do not edit; overwritten on session start)*/-import { globSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { globSync, lstatSync, opendirSync, readFileSync, realpathSync, statSync } from 'node:fs';import { stat } from 'node:fs/promises';import { spawn } from 'node:child_process';import { createInterface } from 'node:readline';@@ -136,6 +136,119 @@ ${SHELL_INPUT_REDIRECTION_PARSER_SOURCE}type BashPathCandidates = { paths: string[]; unresolved: boolean };type BashInputReadEvidence = { targets: string[]; unresolved: boolean };+type BashGlobBudget = { matchesRemaining: number; workRemaining: number };++const BASH_REDIRECT_GLOB_MAX_PATTERN_LENGTH = 4_096;+const BASH_REDIRECT_GLOB_MAX_PATTERN_TOKENS = 64;+const BASH_REDIRECT_GLOB_MAX_BRACE_PATTERNS = 256;+const BASH_REDIRECT_GLOB_MAX_MATCHES = 1_024;+const BASH_REDIRECT_GLOB_MAX_WORK = 4_096;+const BASH_REDIRECT_GLOB_MAX_DEPTH = 64;+const BASH_PATHNAME_SHOPT_OPTIONS = new Set([+ 'dotglob',+ 'extglob',+ 'failglob',+ 'globasciiranges',+ 'globskipdots',+ 'globstar',+ 'nocaseglob',+ 'nullglob',+]);++function bashGlobBudget(): BashGlobBudget {+ return {+ matchesRemaining: BASH_REDIRECT_GLOB_MAX_MATCHES,+ workRemaining: BASH_REDIRECT_GLOB_MAX_WORK,+ };+}++function bashInheritedGlobExpansionIsUncertain(): boolean {+ if (typeof process.env.BASH_ENV === 'string' && process.env.BASH_ENV.trim().length > 0) return true;+ if (typeof process.env.GLOBIGNORE === 'string' && process.env.GLOBIGNORE.length > 0) return true;+ if ((process.env.SHELLOPTS ?? '').split(':').includes('noglob')) return true;+ return (process.env.BASHOPTS ?? '').split(':')+ .some((option) => BASH_PATHNAME_SHOPT_OPTIONS.has(option));+}++function bashBoundedBracePatterns(pattern: string): string[] | null {+ const pending = [pattern];+ const expanded: string[] = [];+ while (pending.length > 0) {+ if (pending.length + expanded.length > BASH_REDIRECT_GLOB_MAX_BRACE_PATTERNS) return null;+ const candidate = pending.pop()!;+ const brace = /^(.*?)\{([^{}]+)\}(.*)$/.exec(candidate);+ if (!brace) {+ expanded.push(candidate);+ continue;+ }+ if (!brace[2].includes(',')) return null;+ for (const alternative of brace[2].split(',')) {+ pending.push(brace[1] + alternative + brace[3]);+ }+ }+ return expanded;+}++// node:fs globSync materializes its full result. Walk the broadest possible scope+// with Dir.readSync first so both traversal and the eventual result stay bounded.+function bashGlobTraversalWithinBudget(+ pattern: string,+ cwd: string,+ budget: BashGlobBudget,+): boolean {+ const magicIndex = pattern.search(/[?*\[\]{}()]/);+ if (magicIndex < 0) return true;+ const prefix = pattern.slice(0, magicIndex);+ const separator = Math.max(prefix.lastIndexOf('/'), prefix.lastIndexOf('\\'));+ const rootText = separator >= 0 ? prefix.slice(0, separator + 1) : '.';+ const root = path.isAbsolute(rootText) ? path.resolve(rootText) : path.resolve(cwd, rootText);+ const remaining = pattern.slice(separator + 1).split(/[\\/]/).filter(Boolean);+ if (remaining.length > BASH_REDIRECT_GLOB_MAX_DEPTH) return false;+ const recursive = remaining.some((segment) => segment.includes('**'));+ const maxDepth = recursive ? BASH_REDIRECT_GLOB_MAX_DEPTH : Math.max(1, remaining.length);+ const pending = [{ directory: root, depth: 0 }];++ while (pending.length > 0) {+ const current = pending.pop()!;+ if (budget.workRemaining-- <= 0) return false;+ let directory;+ try {+ directory = opendirSync(current.directory);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENOENT' || code === 'ENOTDIR') continue;+ return false;+ }+ try {+ let entry;+ while ((entry = directory.readSync()) !== null) {+ if (budget.workRemaining-- <= 0) return false;+ const entryPath = path.join(current.directory, entry.name);+ let isDirectory = entry.isDirectory();+ if (!isDirectory && entry.isSymbolicLink()) {+ if (budget.workRemaining-- <= 0) return false;+ try {+ isDirectory = statSync(entryPath).isDirectory();+ } catch {+ return false;+ }+ }+ if (!isDirectory) continue;+ const nextDepth = current.depth + 1;+ if (recursive && nextDepth >= BASH_REDIRECT_GLOB_MAX_DEPTH) return false;+ if (nextDepth >= maxDepth) continue;+ pending.push({ directory: entryPath, depth: nextDepth });+ }+ } finally {+ directory.closeSync();+ }+ }+ return true;+}++function bashPathHasGlobMagic(pattern: string): boolean {+ return /[?*\[\]{}]/.test(pattern);+}function bashTildeCandidates(target: string): BashPathCandidates {if (!target.startsWith('~')) return { paths: [target], unresolved: false };@@ -166,20 +279,45 @@ function bashExpandedPathCandidates(target: string,cwd: string,mayExpand: boolean,+ budget: BashGlobBudget,): BashPathCandidates {if (!mayExpand) {return { paths: [path.isAbsolute(target) ? target : path.resolve(cwd, target)], unresolved: false };}+ if (bashInheritedGlobExpansionIsUncertain()) return { paths: [], unresolved: true };const tilde = bashTildeCandidates(target);if (tilde.unresolved) return tilde;+ const paths: string[] = [];try {- const paths = tilde.paths.flatMap((pattern) => {- const matches = globSync(pattern, { cwd });- if (matches.length === 0) {- return [path.isAbsolute(pattern) ? pattern : path.resolve(cwd, pattern)];+ for (const pattern of tilde.paths) {+ if (pattern.length > BASH_REDIRECT_GLOB_MAX_PATTERN_LENGTH+ || (pattern.match(/[?*\[]/g)?.length ?? 0) > BASH_REDIRECT_GLOB_MAX_PATTERN_TOKENS) {+ return { paths: [], unresolved: true };}- return matches.map((match) => path.isAbsolute(match) ? match : path.resolve(cwd, match));- });+ if (!bashPathHasGlobMagic(pattern)) {+ paths.push(path.isAbsolute(pattern) ? pattern : path.resolve(cwd, pattern));+ continue;+ }+ if (/[@+?!*]\(/.test(pattern)) return { paths: [], unresolved: true };+ const patterns = bashBoundedBracePatterns(pattern);+ if (!patterns) return { paths: [], unresolved: true };+ for (const expandedPattern of patterns) {+ if (!bashGlobTraversalWithinBudget(expandedPattern, cwd, budget)) {+ return { paths: [], unresolved: true };+ }+ const matches = globSync(expandedPattern, { cwd });+ const candidateCount = Math.max(1, matches.length);+ if (candidateCount > budget.matchesRemaining) return { paths: [], unresolved: true };+ budget.matchesRemaining -= candidateCount;+ if (matches.length === 0) {+ paths.push(path.isAbsolute(expandedPattern)+ ? expandedPattern+ : path.resolve(cwd, expandedPattern));+ } else {+ paths.push(...matches.map((match) => path.isAbsolute(match) ? match : path.resolve(cwd, match)));+ }+ }+ }return { paths: [...new Set(paths)], unresolved: false };} catch {return { paths: [], unresolved: true };@@ -191,16 +329,22 @@ function bashInputReadEvidence(input: unknown): BashInputReadEvidence {const command = (input as Record<string, unknown>).command;if (typeof command !== 'string') return { targets: [], unresolved: false };const parsed = parseShellInputRedirections(command);+ const globBudget = bashGlobBudget();let unresolved = parsed.hasUnresolvedTarget;const targets = parsed.targets.flatMap((target, index) => {- const cwdEvidence = bashWorkingDirectoryCandidates(parsed.targetPrefixes[index] ?? '');+ const cwdEvidence = bashWorkingDirectoryCandidates(parsed.targetPrefixes[index] ?? '', globBudget);unresolved ||= cwdEvidence.unresolved;// POSIX allows a literal backslash in a filename, while the embedded runtime's// tool-call and execution stages have not normalized that shell input consistently.// Preserve the target and require consent unless canonical evidence settles it.unresolved ||= path.sep === '/' && target.includes('\\');return cwdEvidence.paths.flatMap((cwd) => {- const expanded = bashExpandedPathCandidates(target, cwd, parsed.targetMayExpand[index] === true);+ const expanded = bashExpandedPathCandidates(+ target,+ cwd,+ parsed.targetMayExpand[index] === true,+ globBudget,+ );unresolved ||= expanded.unresolved;return expanded.paths;});@@ -439,7 +583,7 @@ function bashDirectoryChangeHead(return { cursor: word.end, hadRedirection, unresolved };}-function bashWorkingDirectoryCandidates(command: string): BashPathCandidates {+function bashWorkingDirectoryCandidates(command: string, globBudget: BashGlobBudget): BashPathCandidates {let candidates = [process.cwd()];let unresolved = false;const codeMask = bashShellCodeMask(command);@@ -494,7 +638,7 @@ function bashWorkingDirectoryCandidates(command: string): BashPathCandidates {const changed: string[] = [];for (const cwd of candidates) {- const expanded = bashExpandedPathCandidates(parsed.target, cwd, parsed.mayExpand);+ const expanded = bashExpandedPathCandidates(parsed.target, cwd, parsed.mayExpand, globBudget);unresolved ||= expanded.unresolved;for (const candidate of expanded.paths) {try {