This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtask-permissions.ts
More file actions
302 lines (273 loc) · 9.06 KB
/
Copy pathtask-permissions.ts
File metadata and controls
302 lines (273 loc) · 9.06 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
297
298
299
300
301
302
import { z } from "zod"
/**
* TaskPermissions defines permission boundaries that a parent task can impose
* on a subtask created via the `new_task` tool.
*
* When nested subtasks are created, permissions are merged using
* "most-restrictive-wins" semantics: a child can never grant itself
* more access than its parent.
*/
/**
* Maximum allowed length for a regex pattern string.
* Keeps patterns short to limit the surface area for ReDoS.
*/
const MAX_REGEX_LENGTH = 500
/**
* Heuristic check for ReDoS-prone regex patterns.
*
* Detects common dangerous constructs:
* - Nested quantifiers: `(a+)+`, `(a*)*`, `(a+)*`, `(a{1,})+` etc.
* - Overlapping alternation with quantifiers that can cause exponential backtracking
*
* This is a conservative heuristic -- it may reject some safe patterns,
* but it will catch the most common ReDoS vectors.
*
* @returns `true` if the pattern appears safe, `false` if it looks dangerous.
*/
export function isSafeRegex(pattern: string): boolean {
if (pattern.length > MAX_REGEX_LENGTH) {
return false
}
// Detect nested quantifiers: a group/char-class followed by a quantifier,
// itself followed by another quantifier.
// e.g., (a+)+ (\w+)* [a-z]+* (.+){2,}+
// Pattern: something quantified inside a group, then the group is quantified again.
// We look for `)` followed by a quantifier, preceded by content that also has a quantifier.
const nestedQuantifierRe = /(\+|\*|\?|\{[0-9,]+\})\s*\)(\+|\*|\?|\{[0-9,]+\})/
if (nestedQuantifierRe.test(pattern)) {
return false
}
// Detect star-height > 1 patterns like (.+)+ (.*)* (.+)*
const starHeightRe = /\(([^)]*(\+|\*|\{[0-9,]+\})[^)]*)\)(\+|\*|\{[0-9,]+\})/
if (starHeightRe.test(pattern)) {
return false
}
return true
}
/** Zod refinement that rejects strings which are not valid regular expressions
* or that contain potentially dangerous ReDoS patterns. */
const regexString = z
.string()
.refine(
(val) => {
try {
new RegExp(val)
return true
} catch {
return false
}
},
{ message: "Invalid regular expression" },
)
.refine((val) => isSafeRegex(val), {
message:
"Regex pattern is potentially unsafe (nested quantifiers or excessive length). Simplify the pattern to avoid ReDoS risk.",
})
export const taskPermissionsSchema = z.object({
/**
* Regex patterns for allowed file paths.
* When set, file operations (read/write) are restricted to paths matching
* at least one of these patterns. Patterns are automatically anchored
* (wrapped in `^(?:...)$`) at runtime so they match the full path.
*/
filePatterns: z.array(regexString).optional(),
/**
* Regex patterns for allowed shell commands.
* When set, command execution is restricted to commands matching
* at least one of these patterns. Patterns are automatically anchored.
*/
commandPatterns: z.array(regexString).optional(),
/**
* Explicit tool allowlist. When set, only these tools may be used
* by the subtask (in addition to always-available tools like
* attempt_completion and ask_followup_question).
*/
allowedTools: z.array(z.string()).optional(),
/**
* Explicit tool blocklist. These tools are denied regardless of
* mode configuration.
*/
deniedTools: z.array(z.string()).optional(),
})
/** The shape accepted as input from the model via the new_task tool. */
export type TaskPermissionsInput = z.infer<typeof taskPermissionsSchema>
/**
* Internal representation of task permissions. Extends the input shape with
* layered pattern fields that accumulate across nested delegation so that
* each ancestor's constraints are enforced independently (AND semantics
* between layers, OR semantics within a layer).
*/
export interface TaskPermissions extends TaskPermissionsInput {
/**
* Accumulated file-pattern layers from ancestor tasks.
* Each inner array is an OR-group; all layers must match (AND between layers).
* Populated only by `mergeTaskPermissions` -- never set from model input.
*/
_filePatternLayers?: string[][]
/**
* Accumulated command-pattern layers from ancestor tasks.
* Same semantics as `_filePatternLayers`.
*/
_commandPatternLayers?: string[][]
}
/**
* Convert a validated input object (flat arrays) into the internal
* `TaskPermissions` representation, wrapping patterns into single layers.
*/
export function toTaskPermissions(input: TaskPermissionsInput): TaskPermissions {
return {
...input,
_filePatternLayers: input.filePatterns ? [input.filePatterns] : undefined,
_commandPatternLayers: input.commandPatterns ? [input.commandPatterns] : undefined,
}
}
/**
* Merge two TaskPermissions using most-restrictive-wins semantics.
*
* - filePatterns / commandPatterns: accumulated as independent layers so that
* a value must match at least one pattern from EACH ancestor's layer.
* - allowedTools: intersection of both lists (if both defined).
* - deniedTools: union of both lists (most restrictive).
*
* @returns merged permissions, or undefined if both inputs are undefined.
*/
export function mergeTaskPermissions(
parent: TaskPermissions | undefined,
child: TaskPermissions | undefined,
): TaskPermissions | undefined {
if (!parent && !child) {
return undefined
}
if (!parent) {
return child
}
if (!child) {
return parent
}
// Collect pattern layers from both sides. Each side may already carry
// accumulated layers from earlier merges (_*PatternLayers) as well as
// its own top-level patterns (filePatterns / commandPatterns).
const filePatternLayers = collectPatternLayers(
parent._filePatternLayers,
parent.filePatterns,
child._filePatternLayers,
child.filePatterns,
)
const commandPatternLayers = collectPatternLayers(
parent._commandPatternLayers,
parent.commandPatterns,
child._commandPatternLayers,
child.commandPatterns,
)
return {
// The top-level field stores the child's own patterns (used for display /
// serialization); runtime enforcement uses the layers.
filePatterns: child.filePatterns ?? parent.filePatterns,
commandPatterns: child.commandPatterns ?? parent.commandPatterns,
_filePatternLayers: filePatternLayers.length > 0 ? filePatternLayers : undefined,
_commandPatternLayers: commandPatternLayers.length > 0 ? commandPatternLayers : undefined,
allowedTools: intersectOptionalArrays(parent.allowedTools, child.allowedTools),
deniedTools: unionOptionalArrays(parent.deniedTools, child.deniedTools),
}
}
/**
* Collect pattern layers from parent and child, deduplicating identical layers.
*/
function collectPatternLayers(
parentLayers: string[][] | undefined,
parentPatterns: string[] | undefined,
childLayers: string[][] | undefined,
childPatterns: string[] | undefined,
): string[][] {
const layers: string[][] = []
const seen = new Set<string>()
const addLayer = (layer: string[]) => {
if (layer.length === 0) return
const key = JSON.stringify(layer)
if (!seen.has(key)) {
seen.add(key)
layers.push(layer)
}
}
// Add accumulated parent layers
if (parentLayers) {
for (const layer of parentLayers) {
addLayer(layer)
}
} else if (parentPatterns && parentPatterns.length > 0) {
addLayer(parentPatterns)
}
// Add accumulated child layers
if (childLayers) {
for (const layer of childLayers) {
addLayer(layer)
}
} else if (childPatterns && childPatterns.length > 0) {
addLayer(childPatterns)
}
return layers
}
/**
* Check if a value matches at least one pattern in a list of regex patterns.
*/
export function matchesAnyPattern(value: string, patterns: string[]): boolean {
return patterns.some((pattern) => {
try {
// Skip patterns that fail the safety heuristic at runtime
// (belt-and-suspenders: Zod schema also checks at parse time)
if (!isSafeRegex(pattern)) {
return false
}
// Anchor patterns so they must match the entire value, not a substring.
// This prevents "src/.*" from matching "evil/src/foo".
const anchored = pattern.startsWith("^") ? pattern : `^(?:${pattern})$`
return new RegExp(anchored).test(value)
} catch {
// Invalid regex -- treat as non-match
return false
}
})
}
/**
* Check if a value matches ALL pattern layers (AND between layers, OR within each layer).
* Returns true if there are no layers.
*/
export function matchesAllPatternLayers(value: string, layers: string[][] | undefined): boolean {
if (!layers || layers.length === 0) {
return true
}
return layers.every((layer) => matchesAnyPattern(value, layer))
}
/**
* Intersect two optional arrays. If both are defined, return elements present
* in both. If only one is defined, return that one. If neither, return undefined.
*/
function intersectOptionalArrays(a: string[] | undefined, b: string[] | undefined): string[] | undefined {
if (!a && !b) {
return undefined
}
if (!a) {
return b
}
if (!b) {
return a
}
const setB = new Set(b)
const result = a.filter((item) => setB.has(item))
return result.length > 0 ? result : []
}
/**
* Union two optional arrays, deduplicating entries.
*/
function unionOptionalArrays(a: string[] | undefined, b: string[] | undefined): string[] | undefined {
if (!a && !b) {
return undefined
}
if (!a) {
return b
}
if (!b) {
return a
}
return [...new Set([...a, ...b])]
}