|
| 1 | +/** |
| 2 | + * Clean up and deduplicate permissions array |
| 3 | + * Removes invalid and redundant permissions based on template |
| 4 | + */ |
| 5 | + |
| 6 | +/** |
| 7 | + * Clean up permissions array by removing invalid and redundant entries |
| 8 | + * @param templatePermissions - Permissions from template (source of truth) |
| 9 | + * @param userPermissions - User's existing permissions |
| 10 | + * @returns Cleaned permissions array |
| 11 | + */ |
| 12 | +export function cleanupPermissions(templatePermissions: string[], userPermissions: string[]): string[] { |
| 13 | + // Create a set for template permissions for O(1) lookup |
| 14 | + const templateSet = new Set(templatePermissions); |
| 15 | + |
| 16 | + // Filter user permissions |
| 17 | + const cleanedPermissions = userPermissions.filter((permission) => { |
| 18 | + // Remove literal "mcp__.*" (invalid wildcard from v2.0 and earlier) |
| 19 | + if (['mcp__.*', 'mcp__*', 'mcp__(*)'].includes(permission)) { |
| 20 | + return false; |
| 21 | + } |
| 22 | + |
| 23 | + // Check if this permission is redundant (covered by a template permission) |
| 24 | + // For example, if template has "Bash", remove "Bash(*)", "Bash(mkdir:*)", etc. |
| 25 | + for (const templatePerm of templatePermissions) { |
| 26 | + // Skip if it's the exact same permission (will be handled by mergeArraysUnique) |
| 27 | + if (permission === templatePerm) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + |
| 31 | + // Check if user permission starts with template permission followed by "(" |
| 32 | + // This catches patterns like "Bash(*)", "Bash(mkdir:*)" when template has "Bash" |
| 33 | + if (permission.startsWith(templatePerm)) { |
| 34 | + return false; // Remove this redundant permission |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Keep all other permissions |
| 39 | + return true; |
| 40 | + }); |
| 41 | + |
| 42 | + // Merge template and cleaned user permissions, removing duplicates |
| 43 | + const merged = [...templateSet]; |
| 44 | + |
| 45 | + for (const permission of cleanedPermissions) { |
| 46 | + if (!templateSet.has(permission)) { |
| 47 | + merged.push(permission); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return merged; |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Merge and clean permissions arrays |
| 56 | + * Combines template and user permissions while removing invalid/redundant entries |
| 57 | + * @param templatePermissions - Permissions from template |
| 58 | + * @param userPermissions - User's existing permissions |
| 59 | + * @returns Merged and cleaned permissions array |
| 60 | + */ |
| 61 | +export function mergeAndCleanPermissions( |
| 62 | + templatePermissions: string[] | undefined, |
| 63 | + userPermissions: string[] | undefined |
| 64 | +): string[] { |
| 65 | + const template = templatePermissions || []; |
| 66 | + const user = userPermissions || []; |
| 67 | + |
| 68 | + return cleanupPermissions(template, user); |
| 69 | +} |
0 commit comments