File size: 11,912 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | import { posix } from 'path'
import type { ToolPermissionContext } from '../../Tool.js'
// Types extracted to src/types/permissions.ts to break import cycles
import type {
AdditionalWorkingDirectory,
WorkingDirectorySource,
} from '../../types/permissions.js'
import { logForDebugging } from '../debug.js'
import type { EditableSettingSource } from '../settings/constants.js'
import {
getSettingsForSource,
updateSettingsForSource,
} from '../settings/settings.js'
import { jsonStringify } from '../slowOperations.js'
import { toPosixPath } from './filesystem.js'
import type { PermissionRuleValue } from './PermissionRule.js'
import type {
PermissionUpdate,
PermissionUpdateDestination,
} from './PermissionUpdateSchema.js'
import {
permissionRuleValueFromString,
permissionRuleValueToString,
} from './permissionRuleParser.js'
import { addPermissionRulesToSettings } from './permissionsLoader.js'
// Re-export for backwards compatibility
export type { AdditionalWorkingDirectory, WorkingDirectorySource }
export function extractRules(
updates: PermissionUpdate[] | undefined,
): PermissionRuleValue[] {
if (!updates) return []
return updates.flatMap(update => {
switch (update.type) {
case 'addRules':
return update.rules
default:
return []
}
})
}
export function hasRules(updates: PermissionUpdate[] | undefined): boolean {
return extractRules(updates).length > 0
}
/**
* Applies a single permission update to the context and returns the updated context
* @param context The current permission context
* @param update The permission update to apply
* @returns The updated permission context
*/
export function applyPermissionUpdate(
context: ToolPermissionContext,
update: PermissionUpdate,
): ToolPermissionContext {
switch (update.type) {
case 'setMode':
logForDebugging(
`Applying permission update: Setting mode to '${update.mode}'`,
)
return {
...context,
mode: update.mode,
}
case 'addRules': {
const ruleStrings = update.rules.map(rule =>
permissionRuleValueToString(rule),
)
logForDebugging(
`Applying permission update: Adding ${update.rules.length} ${update.behavior} rule(s) to destination '${update.destination}': ${jsonStringify(ruleStrings)}`,
)
// Determine which collection to update based on behavior
const ruleKind =
update.behavior === 'allow'
? 'alwaysAllowRules'
: update.behavior === 'deny'
? 'alwaysDenyRules'
: 'alwaysAskRules'
return {
...context,
[ruleKind]: {
...context[ruleKind],
[update.destination]: [
...(context[ruleKind][update.destination] || []),
...ruleStrings,
],
},
}
}
case 'replaceRules': {
const ruleStrings = update.rules.map(rule =>
permissionRuleValueToString(rule),
)
logForDebugging(
`Replacing all ${update.behavior} rules for destination '${update.destination}' with ${update.rules.length} rule(s): ${jsonStringify(ruleStrings)}`,
)
// Determine which collection to update based on behavior
const ruleKind =
update.behavior === 'allow'
? 'alwaysAllowRules'
: update.behavior === 'deny'
? 'alwaysDenyRules'
: 'alwaysAskRules'
return {
...context,
[ruleKind]: {
...context[ruleKind],
[update.destination]: ruleStrings, // Replace all rules for this source
},
}
}
case 'addDirectories': {
logForDebugging(
`Applying permission update: Adding ${update.directories.length} director${update.directories.length === 1 ? 'y' : 'ies'} with destination '${update.destination}': ${jsonStringify(update.directories)}`,
)
const newAdditionalDirs = new Map(context.additionalWorkingDirectories)
for (const directory of update.directories) {
newAdditionalDirs.set(directory, {
path: directory,
source: update.destination,
})
}
return {
...context,
additionalWorkingDirectories: newAdditionalDirs,
}
}
case 'removeRules': {
const ruleStrings = update.rules.map(rule =>
permissionRuleValueToString(rule),
)
logForDebugging(
`Applying permission update: Removing ${update.rules.length} ${update.behavior} rule(s) from source '${update.destination}': ${jsonStringify(ruleStrings)}`,
)
// Determine which collection to update based on behavior
const ruleKind =
update.behavior === 'allow'
? 'alwaysAllowRules'
: update.behavior === 'deny'
? 'alwaysDenyRules'
: 'alwaysAskRules'
// Filter out the rules to be removed
const existingRules = context[ruleKind][update.destination] || []
const rulesToRemove = new Set(ruleStrings)
const filteredRules = existingRules.filter(
rule => !rulesToRemove.has(rule),
)
return {
...context,
[ruleKind]: {
...context[ruleKind],
[update.destination]: filteredRules,
},
}
}
case 'removeDirectories': {
logForDebugging(
`Applying permission update: Removing ${update.directories.length} director${update.directories.length === 1 ? 'y' : 'ies'}: ${jsonStringify(update.directories)}`,
)
const newAdditionalDirs = new Map(context.additionalWorkingDirectories)
for (const directory of update.directories) {
newAdditionalDirs.delete(directory)
}
return {
...context,
additionalWorkingDirectories: newAdditionalDirs,
}
}
default:
return context
}
}
/**
* Applies multiple permission updates to the context and returns the updated context
* @param context The current permission context
* @param updates The permission updates to apply
* @returns The updated permission context
*/
export function applyPermissionUpdates(
context: ToolPermissionContext,
updates: PermissionUpdate[],
): ToolPermissionContext {
let updatedContext = context
for (const update of updates) {
updatedContext = applyPermissionUpdate(updatedContext, update)
}
return updatedContext
}
export function supportsPersistence(
destination: PermissionUpdateDestination,
): destination is EditableSettingSource {
return (
destination === 'localSettings' ||
destination === 'userSettings' ||
destination === 'projectSettings'
)
}
/**
* Persists a permission update to the appropriate settings source
* @param update The permission update to persist
*/
export function persistPermissionUpdate(update: PermissionUpdate): void {
if (!supportsPersistence(update.destination)) return
logForDebugging(
`Persisting permission update: ${update.type} to source '${update.destination}'`,
)
switch (update.type) {
case 'addRules': {
logForDebugging(
`Persisting ${update.rules.length} ${update.behavior} rule(s) to ${update.destination}`,
)
addPermissionRulesToSettings(
{
ruleValues: update.rules,
ruleBehavior: update.behavior,
},
update.destination,
)
break
}
case 'addDirectories': {
logForDebugging(
`Persisting ${update.directories.length} director${update.directories.length === 1 ? 'y' : 'ies'} to ${update.destination}`,
)
const existingSettings = getSettingsForSource(update.destination)
const existingDirs =
existingSettings?.permissions?.additionalDirectories || []
// Add new directories, avoiding duplicates
const dirsToAdd = update.directories.filter(
dir => !existingDirs.includes(dir),
)
if (dirsToAdd.length > 0) {
const updatedDirs = [...existingDirs, ...dirsToAdd]
updateSettingsForSource(update.destination, {
permissions: {
additionalDirectories: updatedDirs,
},
})
}
break
}
case 'removeRules': {
// Handle rule removal
logForDebugging(
`Removing ${update.rules.length} ${update.behavior} rule(s) from ${update.destination}`,
)
const existingSettings = getSettingsForSource(update.destination)
const existingPermissions = existingSettings?.permissions || {}
const existingRules = existingPermissions[update.behavior] || []
// Convert rules to normalized strings for comparison
// Normalize via parse→serialize roundtrip so "Bash(*)" and "Bash" match
const rulesToRemove = new Set(
update.rules.map(permissionRuleValueToString),
)
const filteredRules = existingRules.filter(rule => {
const normalized = permissionRuleValueToString(
permissionRuleValueFromString(rule),
)
return !rulesToRemove.has(normalized)
})
updateSettingsForSource(update.destination, {
permissions: {
[update.behavior]: filteredRules,
},
})
break
}
case 'removeDirectories': {
logForDebugging(
`Removing ${update.directories.length} director${update.directories.length === 1 ? 'y' : 'ies'} from ${update.destination}`,
)
const existingSettings = getSettingsForSource(update.destination)
const existingDirs =
existingSettings?.permissions?.additionalDirectories || []
// Remove specified directories
const dirsToRemove = new Set(update.directories)
const filteredDirs = existingDirs.filter(dir => !dirsToRemove.has(dir))
updateSettingsForSource(update.destination, {
permissions: {
additionalDirectories: filteredDirs,
},
})
break
}
case 'setMode': {
logForDebugging(
`Persisting mode '${update.mode}' to ${update.destination}`,
)
updateSettingsForSource(update.destination, {
permissions: {
defaultMode: update.mode,
},
})
break
}
case 'replaceRules': {
logForDebugging(
`Replacing all ${update.behavior} rules in ${update.destination} with ${update.rules.length} rule(s)`,
)
const ruleStrings = update.rules.map(permissionRuleValueToString)
updateSettingsForSource(update.destination, {
permissions: {
[update.behavior]: ruleStrings,
},
})
break
}
}
}
/**
* Persists multiple permission updates to the appropriate settings sources
* Only persists updates with persistable sources
* @param updates The permission updates to persist
*/
export function persistPermissionUpdates(updates: PermissionUpdate[]): void {
for (const update of updates) {
persistPermissionUpdate(update)
}
}
/**
* Creates a Read rule suggestion for a directory.
* @param dirPath The directory path to create a rule for
* @param destination The destination for the permission rule (defaults to 'session')
* @returns A PermissionUpdate for a Read rule, or undefined for the root directory
*/
export function createReadRuleSuggestion(
dirPath: string,
destination: PermissionUpdateDestination = 'session',
): PermissionUpdate | undefined {
// Convert to POSIX format for pattern matching (handles Windows internally)
const pathForPattern = toPosixPath(dirPath)
// Root directory is too broad to be a reasonable permission target
if (pathForPattern === '/') {
return undefined
}
// For absolute paths, prepend an extra / to create //path/** pattern
const ruleContent = posix.isAbsolute(pathForPattern)
? `/${pathForPattern}/**`
: `${pathForPattern}/**`
return {
type: 'addRules',
rules: [
{
toolName: 'Read',
ruleContent,
},
],
behavior: 'allow',
destination,
}
}
|