forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermissionsLoader.ts
More file actions
296 lines (263 loc) · 8.54 KB
/
Copy pathpermissionsLoader.ts
File metadata and controls
296 lines (263 loc) · 8.54 KB
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
import { readFileSync } from '../fileRead.js'
import { getFsImplementation, safeResolvePath } from '../fsOperations.js'
import { safeParseJSON } from '../json.js'
import { logError } from '../log.js'
import {
type EditableSettingSource,
getEnabledSettingSources,
type SettingSource,
} from '../settings/constants.js'
import {
getSettingsFilePathForSource,
getSettingsForSource,
updateSettingsForSource,
} from '../settings/settings.js'
import type { SettingsJson } from '../settings/types.js'
import type {
PermissionBehavior,
PermissionRule,
PermissionRuleSource,
PermissionRuleValue,
} from './PermissionRule.js'
import {
permissionRuleValueFromString,
permissionRuleValueToString,
} from './permissionRuleParser.js'
/**
* Returns true if allowManagedPermissionRulesOnly is enabled in managed settings (policySettings).
* When enabled, only permission rules from managed settings are respected.
*/
export function shouldAllowManagedPermissionRulesOnly(): boolean {
return (
getSettingsForSource('policySettings')?.allowManagedPermissionRulesOnly ===
true
)
}
/**
* Returns true if "always allow" options should be shown in permission prompts.
* When allowManagedPermissionRulesOnly is enabled, these options are hidden.
*/
export function shouldShowAlwaysAllowOptions(): boolean {
return !shouldAllowManagedPermissionRulesOnly()
}
const SUPPORTED_RULE_BEHAVIORS = [
'allow',
'deny',
'ask',
] as const satisfies PermissionBehavior[]
/**
* Lenient version of getSettingsForSource that doesn't fail on ANY validation errors.
* Simply parses the JSON and returns it as-is without schema validation.
*
* Used when loading settings to append new rules (avoids losing existing rules
* due to validation failures in unrelated fields like hooks).
*
* FOR EDITING ONLY - do not use this for reading settings for execution.
*/
function getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READING(
source: SettingSource,
): SettingsJson | null {
const filePath = getSettingsFilePathForSource(source)
if (!filePath) {
return null
}
try {
const { resolvedPath } = safeResolvePath(getFsImplementation(), filePath)
const content = readFileSync(resolvedPath)
if (content.trim() === '') {
return {}
}
const data = safeParseJSON(content, false)
// Return raw parsed JSON without validation to preserve all existing settings
// This is safe because we're only using this for reading/appending, not for execution
return data && typeof data === 'object' ? (data as SettingsJson) : null
} catch {
return null
}
}
/**
* Converts permissions JSON to an array of PermissionRule objects
* @param data The parsed permissions data
* @param source The source of these rules
* @returns Array of PermissionRule objects
*/
function settingsJsonToRules(
data: SettingsJson | null,
source: PermissionRuleSource,
): PermissionRule[] {
if (!data || !data.permissions) {
return []
}
const { permissions } = data
const rules: PermissionRule[] = []
for (const behavior of SUPPORTED_RULE_BEHAVIORS) {
const behaviorArray = permissions[behavior]
if (behaviorArray) {
for (const ruleString of behaviorArray) {
rules.push({
source,
ruleBehavior: behavior,
ruleValue: permissionRuleValueFromString(ruleString),
})
}
}
}
return rules
}
/**
* Loads all permission rules from all relevant sources (managed and project settings)
* @returns Array of all permission rules
*/
export function loadAllPermissionRulesFromDisk(): PermissionRule[] {
// If allowManagedPermissionRulesOnly is set, only use managed permission rules
if (shouldAllowManagedPermissionRulesOnly()) {
return getPermissionRulesForSource('policySettings')
}
// Otherwise, load from all enabled sources (backwards compatible)
const rules: PermissionRule[] = []
for (const source of getEnabledSettingSources()) {
rules.push(...getPermissionRulesForSource(source))
}
return rules
}
/**
* Loads permission rules from a specific source
* @param source The source to load from
* @returns Array of permission rules from that source
*/
export function getPermissionRulesForSource(
source: SettingSource,
): PermissionRule[] {
const settingsData = getSettingsForSource(source)
return settingsJsonToRules(settingsData, source)
}
export type PermissionRuleFromEditableSettings = PermissionRule & {
source: EditableSettingSource
}
// Editable sources that can be modified (excludes policySettings and flagSettings)
const EDITABLE_SOURCES: EditableSettingSource[] = [
'userSettings',
'projectSettings',
'localSettings',
]
/**
* Deletes a rule from the project permissions file
* @param rule The rule to delete
* @returns Promise resolving to a boolean indicating success
*/
export function deletePermissionRuleFromSettings(
rule: PermissionRuleFromEditableSettings,
): boolean {
// Runtime check to ensure source is actually editable
if (!EDITABLE_SOURCES.includes(rule.source as EditableSettingSource)) {
return false
}
const ruleString = permissionRuleValueToString(rule.ruleValue)
const settingsData = getSettingsForSource(rule.source)
// If there's no settings data or permissions, nothing to do
if (!settingsData || !settingsData.permissions) {
return false
}
const behaviorArray = settingsData.permissions[rule.ruleBehavior]
if (!behaviorArray) {
return false
}
// Normalize raw settings entries via roundtrip parse→serialize so legacy
// names (e.g. "KillShell") match their canonical form ("TaskStop").
const normalizeEntry = (raw: string): string =>
permissionRuleValueToString(permissionRuleValueFromString(raw))
if (!behaviorArray.some(raw => normalizeEntry(raw) === ruleString)) {
return false
}
try {
// Keep a copy of the original permissions data to preserve unrecognized keys
const updatedSettingsData = {
...settingsData,
permissions: {
...settingsData.permissions,
[rule.ruleBehavior]: behaviorArray.filter(
raw => normalizeEntry(raw) !== ruleString,
),
},
}
const { error } = updateSettingsForSource(rule.source, updatedSettingsData)
if (error) {
// Error already logged inside updateSettingsForSource
return false
}
return true
} catch (error) {
logError(error)
return false
}
}
function getEmptyPermissionSettingsJson(): SettingsJson {
return {
permissions: {},
}
}
/**
* Adds rules to the project permissions file
* @param ruleValues The rule values to add
* @returns Promise resolving to a boolean indicating success
*/
export function addPermissionRulesToSettings(
{
ruleValues,
ruleBehavior,
}: {
ruleValues: PermissionRuleValue[]
ruleBehavior: PermissionBehavior
},
source: EditableSettingSource,
): boolean {
// When allowManagedPermissionRulesOnly is enabled, don't persist new permission rules
if (shouldAllowManagedPermissionRulesOnly()) {
return false
}
if (ruleValues.length < 1) {
// No rules to add
return true
}
const ruleStrings = ruleValues.map(permissionRuleValueToString)
// First try the normal settings loader which validates the schema
// If validation fails, fall back to lenient loading to preserve existing rules
// even if some fields (like hooks) have validation errors
const settingsData =
getSettingsForSource(source) ||
getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READING(source) ||
getEmptyPermissionSettingsJson()
try {
// Ensure permissions object exists
const existingPermissions = settingsData.permissions || {}
const existingRules = existingPermissions[ruleBehavior] || []
// Filter out duplicates - normalize existing entries via roundtrip
// parse→serialize so legacy names match their canonical form.
const existingRulesSet = new Set(
existingRules.map(raw =>
permissionRuleValueToString(permissionRuleValueFromString(raw)),
),
)
const newRules = ruleStrings.filter(rule => !existingRulesSet.has(rule))
// If no new rules to add, return success
if (newRules.length === 0) {
return true
}
// Keep a copy of the original settings data to preserve unrecognized keys
const updatedSettingsData = {
...settingsData,
permissions: {
...existingPermissions,
[ruleBehavior]: [...existingRules, ...newRules],
},
}
const result = updateSettingsForSource(source, updatedSettingsData)
if (result.error) {
throw result.error
}
return true
} catch (error) {
logError(error)
return false
}
}