Elffuss BraidHub

kikocis/continue public

main · 6.4 KiBRawPermalink
1import type { ToolPolicy } from "@continuedev/terminal-security";
2
3import { getServiceSync } from "../services/index.js";
4import type { ToolPermissionServiceState } from "../services/types.js";
5import { SERVICE_NAMES } from "../services/types.js";
6import { getAllBuiltinTools } from "../tools/index.js";
7
8import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
9import {
10 PermissionCheckResult,
11 PermissionPolicy,
12 ToolCallRequest,
13 ToolPermissions,
14} from "./types.js";
15
16/**
17 * Checks if a tool name matches a pattern.
18 * Supports wildcards (*) for pattern matching.
19 * Also handles special Bash command patterns like "Bash(ls*)"
20 */
21export function matchesToolPattern(
22 toolName: string,
23 pattern: string,
24 toolArguments?: Record<string, any>,
25): boolean {
26 if (pattern === "*") return true;
27 if (pattern === toolName) return true;
28
29 // Handle special Bash command patterns like "Bash(ls*)"
30 const bashCommandMatch = pattern.match(/^Bash\((.+)\)$/);
31 if (bashCommandMatch) {
32 // Check if this is a bash/terminal tool
33 const isBashTool = toolName === "Bash";
34 if (isBashTool && toolArguments?.command) {
35 const commandPattern = bashCommandMatch[1];
36 const command = toolArguments.command;
37
38 // Handle command patterns with wildcards
39 if (commandPattern.includes("*") || commandPattern.includes("?")) {
40 // Escape all regex metacharacters except * and ?
41 const escaped = commandPattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
42 // Convert * and ? to their regex equivalents
43 const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
44 const regex = new RegExp(`^${regexPattern}$`);
45 return regex.test(command);
46 }
47
48 // Exact command match
49 return command === commandPattern;
50 }
51 return false;
52 }
53
54 // Handle regular wildcard patterns like "mcp__*"
55 if (pattern.includes("*") || pattern.includes("?")) {
56 // Escape all regex metacharacters except * and ?
57 const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
58 // Convert * and ? to their regex equivalents
59 const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
60 const regex = new RegExp(`^${regexPattern}$`);
61 return regex.test(toolName);
62 }
63
64 return false;
65}
66
67/**
68 * Checks if tool call arguments match the specified patterns.
69 * Supports glob patterns with * and ? wildcards.
70 */
71export function matchesArguments(
72 args: Record<string, any>,
73 patterns?: Record<string, any>,
74): boolean {
75 if (!patterns) return true;
76
77 for (const [key, pattern] of Object.entries(patterns)) {
78 const argValue = args[key];
79
80 if (pattern === "*") continue; // Wildcard matches anything
81
82 // Handle glob patterns with wildcards (only for string patterns)
83 if (
84 typeof pattern === "string" &&
85 (pattern.includes("*") || pattern.includes("?"))
86 ) {
87 // Convert argValue to string for pattern matching
88 const stringValue = String(argValue ?? "");
89
90 // Escape all regex metacharacters except * and ?
91 const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
92 // Convert * and ? to their regex equivalents
93 const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
94 const regex = new RegExp(`^${regexPattern}$`);
95
96 if (!regex.test(stringValue)) {
97 return false;
98 }
99 } else {
100 // Exact match for non-glob patterns (preserve original behavior)
101 if (argValue !== pattern) {
102 return false;
103 }
104 }
105 }
106
107 return true;
108}
109
110/**
111 * Converts CLI's PermissionPolicy to core's ToolPolicy
112 */
113function permissionPolicyToToolPolicy(
114 permission: PermissionPolicy,
115): ToolPolicy {
116 switch (permission) {
117 case "allow":
118 return "allowedWithoutPermission";
119 case "ask":
120 return "allowedWithPermission";
121 case "exclude":
122 return "disabled";
123 default:
124 return "allowedWithPermission";
125 }
126}
127
128/**
129 * Evaluates a tool call request against a set of permission policies.
130 * Returns the permission for the first matching policy.
131 */
132export function checkToolPermission(
133 toolCall: ToolCallRequest,
134 permissions?: ToolPermissions,
135): PermissionCheckResult {
136 // Get permissions from service if not provided
137 let policies = permissions?.policies;
138
139 if (!policies) {
140 const serviceResult = getServiceSync<ToolPermissionServiceState>(
141 SERVICE_NAMES.TOOL_PERMISSIONS,
142 );
143
144 // Only use defaults if service is not ready, not registered, or has no value
145 // This allows critical runtime errors to propagate properly
146 if (serviceResult.state !== "ready" || !serviceResult.value) {
147 policies = DEFAULT_TOOL_POLICIES;
148 } else {
149 policies =
150 serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
151 }
152 }
153
154 // First, get the base permission from static policies
155 let basePermission: PermissionPolicy = "ask";
156 let matchedPolicy = undefined;
157
158 for (const policy of policies) {
159 if (
160 matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) &&
161 matchesArguments(toolCall.arguments, policy.argumentMatches)
162 ) {
163 basePermission = policy.permission;
164 matchedPolicy = policy;
165 break;
166 }
167 }
168
169 // Check if tool has dynamic policy evaluation
170 const builtinTools = getAllBuiltinTools();
171 const tool = builtinTools.find((t) => t.name === toolCall.name);
172
173 if (tool?.evaluateToolCallPolicy) {
174 // Convert CLI permission to core policy
175 const basePolicy = permissionPolicyToToolPolicy(basePermission);
176
177 // Evaluate the dynamic policy
178 const evaluatedPolicy = tool.evaluateToolCallPolicy(
179 basePolicy,
180 toolCall.arguments,
181 );
182
183 // If dynamic evaluation says disabled, that ALWAYS takes precedence
184 if (evaluatedPolicy === "disabled") {
185 return {
186 permission: "exclude",
187 matchedPolicy,
188 };
189 }
190
191 // Otherwise, user preference wins - return the original base permission
192 return {
193 permission: basePermission,
194 matchedPolicy,
195 };
196 }
197
198 // No dynamic evaluation, return static result
199 return {
200 permission: basePermission,
201 matchedPolicy,
202 };
203}
204
205/**
206 * Filters out tools that have "exclude" permission from a list of tool names.
207 */
208export function filterExcludedTools(
209 toolNames: string[],
210 permissions?: ToolPermissions,
211): string[] {
212 return toolNames.filter((toolName) => {
213 const result = checkToolPermission(
214 { name: toolName, arguments: {} },
215 permissions,
216 );
217 return result.permission !== "exclude";
218 });
219}