@xiangyixie/dsh-superagent 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/policy.js CHANGED
@@ -1,739 +1,739 @@
1
- /**
2
- * Permission policy for dsh-superagent runs.
3
- *
4
- * A policy is a small JSON file a person edits by hand, so every rejection has
5
- * to say *where* the problem is: a schema error without a line number turns a
6
- * typo into an afternoon of guessing. The file is parsed by a position-aware
7
- * reader instead of `JSON.parse` for exactly that reason, and `//` / `#` line
8
- * comments are stripped (with their newlines kept) so the file can explain
9
- * itself.
10
- *
11
- * The policy only ever tightens. Nothing here relaxes a deny rule; an explicit
12
- * allow entry can lift a `confirm` or a per-run `deny`, and the caller records
13
- * that as an override so the audit trail shows who permitted it.
14
- *
15
- * @module dsh-superagent/policy
16
- */
17
- import fsp from 'node:fs/promises'
18
-
19
- /** Decisions a policy can return, from loosest to strictest. */
20
- export const LEVELS = ['allow', 'confirm', 'deny']
21
-
22
- /** Action kinds a policy can talk about. `*` is accepted as a suffix wildcard. */
23
- export const ACTION_KINDS = [
24
- 'run.start',
25
- 'run.resume',
26
- 'path.read',
27
- 'path.write',
28
- 'command.exec',
29
- 'tool.call',
30
- 'network',
31
- 'attention',
32
- ]
33
-
34
- const RUN_ID_PATTERN = /^[0-9A-Za-z][0-9A-Za-z_-]{3,63}$/
35
- const MAX_ERRORS = 20
36
- const COMPOSITE_COMMAND = /(?:&&|\|\||[;|`]|\$\(|\n)/
37
-
38
- /** One invalid line of a policy file. */
39
- export class PolicyError extends Error {
40
- /**
41
- * @param {string} file - display name of the policy file.
42
- * @param {{ line: number, column: number, path: string, message: string }[]} errors - findings.
43
- * @param {string} source - file text, used for a caret line.
44
- */
45
- constructor(file, errors, source = '') {
46
- const head = `${file}: ${errors.length} problem${errors.length === 1 ? '' : 's'} in the permission policy`
47
- const body = errors.map(problem => {
48
- const caret = source ? `\n ${source.split('\n')[problem.line - 1] ?? ''}` : ''
49
- const pointer = caret ? `\n ${' '.repeat(Math.max(0, problem.column - 1))}^` : ''
50
- return ` ${file}:${problem.line}:${problem.column} [${problem.path}] ${problem.message}${caret}${pointer}`
51
- })
52
- super([head, ...body].join('\n'))
53
- this.name = 'PolicyError'
54
- this.file = file
55
- this.errors = errors
56
- }
57
- }
58
-
59
- /**
60
- * Remove comments from JSON text without moving any character: comment bytes
61
- * become spaces, newlines survive. A `//` inside a string is left alone.
62
- * @param {string} text - raw file text.
63
- * @returns {string} text with comments blanked.
64
- */
65
- export function stripComments(text) {
66
- let out = ''
67
- let index = 0
68
- let inString = false
69
- let escaped = false
70
- while (index < text.length) {
71
- const char = text[index]
72
- const next = text[index + 1]
73
- if (inString) {
74
- out += char
75
- if (escaped) escaped = false
76
- else if (char === '\\') escaped = true
77
- else if (char === '"') inString = false
78
- index++
79
- continue
80
- }
81
- if (char === '"') {
82
- inString = true
83
- out += char
84
- index++
85
- continue
86
- }
87
- if (char === '/' && next === '/') {
88
- while (index < text.length) {
89
- const current = text[index]
90
- out += current === '\n' ? '\n' : ' '
91
- index++
92
- if (current === '\n') break
93
- }
94
- continue
95
- }
96
- if (char === '/' && next === '*') {
97
- out += ' '
98
- index += 2
99
- while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) {
100
- out += text[index] === '\n' ? '\n' : ' '
101
- index++
102
- }
103
- if (index < text.length) {
104
- out += ' '
105
- index += 2
106
- }
107
- continue
108
- }
109
- if (char === '#') {
110
- while (index < text.length) {
111
- const current = text[index]
112
- out += current === '\n' ? '\n' : ' '
113
- index++
114
- if (current === '\n') break
115
- }
116
- continue
117
- }
118
- out += char
119
- index++
120
- }
121
- return out
122
- }
123
-
124
- /**
125
- * Minimal position-aware JSON reader. It is deliberately strict: trailing
126
- * commas and unquoted keys are rejected, because a policy file that only
127
- * *nearly* parses is a policy the user believes is in force but is not.
128
- */
129
- function parseTree(text) {
130
- const lineStarts = [0]
131
- for (let i = 0; i < text.length; i++) if (text[i] === '\n') lineStarts.push(i + 1)
132
-
133
- const positionOf = index => {
134
- let low = 0
135
- let high = lineStarts.length - 1
136
- while (low < high) {
137
- const mid = Math.ceil((low + high) / 2)
138
- if (lineStarts[mid] <= index) low = mid
139
- else high = mid - 1
140
- }
141
- return { line: low + 1, column: index - lineStarts[low] + 1 }
142
- }
143
-
144
- let index = 0
145
-
146
- const fail = (message, at = index) => {
147
- const { line, column } = positionOf(Math.min(at, text.length))
148
- const error = new SyntaxError(message)
149
- error.line = line
150
- error.column = column
151
- error.at = at
152
- throw error
153
- }
154
-
155
- const skipSpace = () => {
156
- while (index < text.length && /\s/.test(text[index])) index++
157
- }
158
-
159
- const parseString = () => {
160
- const start = index
161
- index++
162
- let value = ''
163
- while (index < text.length) {
164
- const char = text[index]
165
- if (char === '"') {
166
- index++
167
- const { line, column } = positionOf(start)
168
- return { kind: 'string', value, line, column }
169
- }
170
- if (char === '\\') {
171
- const escape = text[index + 1]
172
- const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }
173
- if (escape in simple) {
174
- value += simple[escape]
175
- index += 2
176
- continue
177
- }
178
- if (escape === 'u') {
179
- const hex = text.slice(index + 2, index + 6)
180
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('invalid \\u escape in a string', index)
181
- value += String.fromCharCode(parseInt(hex, 16))
182
- index += 6
183
- continue
184
- }
185
- fail('invalid escape in a string', index)
186
- }
187
- if (char === '\n') fail('a string is missing its closing quote', start)
188
- value += char
189
- index++
190
- }
191
- fail('a string is missing its closing quote', start)
192
- return null
193
- }
194
-
195
- const parseValue = () => {
196
- skipSpace()
197
- const start = index
198
- const char = text[index]
199
- if (char === '{') {
200
- const { line, column } = positionOf(start)
201
- index++
202
- const entries = []
203
- skipSpace()
204
- if (text[index] === '}') {
205
- index++
206
- return { kind: 'object', entries, line, column }
207
- }
208
- for (;;) {
209
- skipSpace()
210
- if (text[index] !== '"') fail('expected a quoted key')
211
- const keyStart = index
212
- const keyNode = parseString()
213
- skipSpace()
214
- if (text[index] !== ':') fail('expected ":" after a key')
215
- index++
216
- const node = parseValue()
217
- const { line: keyLine, column: keyColumn } = positionOf(keyStart)
218
- entries.push({ key: keyNode.value, keyLine, keyColumn, node })
219
- skipSpace()
220
- if (text[index] === ',') {
221
- index++
222
- skipSpace()
223
- if (text[index] === '}') fail('trailing commas are not allowed')
224
- continue
225
- }
226
- if (text[index] === '}') {
227
- index++
228
- return { kind: 'object', entries, line, column }
229
- }
230
- fail('expected "," or "}" in an object')
231
- }
232
- }
233
- if (char === '[') {
234
- const { line, column } = positionOf(start)
235
- index++
236
- const items = []
237
- skipSpace()
238
- if (text[index] === ']') {
239
- index++
240
- return { kind: 'array', items, line, column }
241
- }
242
- for (;;) {
243
- items.push(parseValue())
244
- skipSpace()
245
- if (text[index] === ',') {
246
- index++
247
- skipSpace()
248
- if (text[index] === ']') fail('trailing commas are not allowed')
249
- continue
250
- }
251
- if (text[index] === ']') {
252
- index++
253
- return { kind: 'array', items, line, column }
254
- }
255
- fail('expected "," or "]" in an array')
256
- }
257
- }
258
- if (char === '"') return parseString()
259
- const literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(index))
260
- if (!literal) fail(`unexpected character ${JSON.stringify(char ?? 'end of file')}`)
261
- index += literal[0].length
262
- const { line, column } = positionOf(start)
263
- if (literal[0] === 'true' || literal[0] === 'false') {
264
- return { kind: 'boolean', value: literal[0] === 'true', line, column }
265
- }
266
- if (literal[0] === 'null') return { kind: 'null', value: null, line, column }
267
- return { kind: 'number', value: Number(literal[0]), line, column }
268
- }
269
-
270
- const root = parseValue()
271
- skipSpace()
272
- if (index < text.length) fail('unexpected text after the top-level value')
273
- return { root, positionOf }
274
- }
275
-
276
- function valueOf(node) {
277
- if (node.kind === 'object') {
278
- const value = {}
279
- for (const entry of node.entries) value[entry.key] = valueOf(entry.node)
280
- return value
281
- }
282
- if (node.kind === 'array') return node.items.map(valueOf)
283
- return node.value
284
- }
285
-
286
- /**
287
- * Validate one policy tree and return the plain object a decision reads.
288
- * Every problem carries the line and column of the token that caused it.
289
- */
290
- function validate(root, file, source) {
291
- const errors = []
292
- const add = (node, path, message) => {
293
- if (errors.length >= MAX_ERRORS) return
294
- errors.push({ line: node?.line ?? 1, column: node?.column ?? 1, path, message })
295
- }
296
- const keyOf = (entry, path) => {
297
- const node = { line: entry.keyLine, column: entry.keyColumn }
298
- return { node, path }
299
- }
300
-
301
- if (root.kind !== 'object') {
302
- add(root, '$', 'the policy must be a JSON object')
303
- throw new PolicyError(file, errors, source)
304
- }
305
-
306
- const seen = new Map()
307
- for (const entry of root.entries) {
308
- if (seen.has(entry.key)) {
309
- const spot = keyOf(entry, entry.key)
310
- add(spot.node, spot.path, `duplicate key; the earlier value was already set on line ${seen.get(entry.key)}`)
311
- } else {
312
- seen.set(entry.key, entry.keyLine)
313
- }
314
- }
315
-
316
- const knownRoot = ['version', 'defaultLevel', 'paths', 'commands', 'confirm', 'runs', 'note']
317
- for (const entry of root.entries) {
318
- if (!knownRoot.includes(entry.key)) {
319
- const spot = keyOf(entry, entry.key)
320
- add(spot.node, spot.path, `unknown key; expected one of ${knownRoot.join(', ')}`)
321
- continue
322
- }
323
- const path = entry.key
324
- const node = entry.node
325
- if (entry.key === 'version') {
326
- if (node.kind !== 'number' || node.value !== 1) add(node, path, 'must be the number 1')
327
- continue
328
- }
329
- if (entry.key === 'note') {
330
- if (node.kind !== 'string') add(node, path, 'must be a string')
331
- continue
332
- }
333
- if (entry.key === 'defaultLevel') {
334
- if (node.kind !== 'string' || !LEVELS.includes(node.value)) {
335
- add(node, path, `must be one of ${LEVELS.join(' | ')}`)
336
- }
337
- continue
338
- }
339
- if (entry.key === 'paths' || entry.key === 'commands') {
340
- if (node.kind !== 'object') {
341
- add(node, path, 'must be an object with allow and/or deny arrays')
342
- continue
343
- }
344
- const known = ['allow', 'deny']
345
- for (const child of node.entries) {
346
- if (!known.includes(child.key)) {
347
- const spot = keyOf(child, `${path}.${child.key}`)
348
- add(spot.node, spot.path, `unknown key; expected ${known.join(' or ')}`)
349
- continue
350
- }
351
- const listPath = `${path}.${child.key}`
352
- if (child.node.kind !== 'array') {
353
- add(child.node, listPath, 'must be an array of strings')
354
- continue
355
- }
356
- child.node.items.forEach((item, i) => {
357
- const itemPath = `${listPath}[${i}]`
358
- if (item.kind !== 'string') {
359
- add(item, itemPath, 'must be a string')
360
- return
361
- }
362
- if (!item.value.trim()) add(item, itemPath, 'must not be empty')
363
- })
364
- }
365
- continue
366
- }
367
- if (entry.key === 'confirm') {
368
- if (node.kind !== 'object') {
369
- add(node, path, 'must be an object with an actions array')
370
- continue
371
- }
372
- for (const child of node.entries) {
373
- if (child.key !== 'actions') {
374
- const spot = keyOf(child, `${path}.${child.key}`)
375
- add(spot.node, spot.path, 'unknown key; expected actions')
376
- continue
377
- }
378
- if (child.node.kind !== 'array') {
379
- add(child.node, `${path}.actions`, 'must be an array of action kinds')
380
- continue
381
- }
382
- child.node.items.forEach((item, i) => {
383
- const itemPath = `${path}.actions[${i}]`
384
- if (item.kind !== 'string') {
385
- add(item, itemPath, 'must be a string')
386
- return
387
- }
388
- const wildcard = item.value.endsWith('*')
389
- const base = wildcard ? item.value.slice(0, -1) : item.value
390
- const known = ACTION_KINDS.includes(item.value)
391
- || (wildcard && ACTION_KINDS.some(kind => kind.startsWith(base)))
392
- if (!known) {
393
- add(item, itemPath, `unknown action kind; expected one of ${ACTION_KINDS.join(', ')} (or "path.*")`)
394
- }
395
- })
396
- }
397
- continue
398
- }
399
- if (entry.key === 'runs') {
400
- if (node.kind !== 'object') {
401
- add(node, path, 'must be an object keyed by run id')
402
- continue
403
- }
404
- for (const child of node.entries) {
405
- const runPath = `${path}.${child.key}`
406
- const spot = keyOf(child, runPath)
407
- if (!RUN_ID_PATTERN.test(child.key)) {
408
- add(spot.node, runPath, 'is not a run id (letters, digits, "-" or "_", 4-64 characters)')
409
- continue
410
- }
411
- if (child.node.kind !== 'object') {
412
- add(child.node, runPath, 'must be an object with level and/or note')
413
- continue
414
- }
415
- for (const setting of child.node.entries) {
416
- const settingPath = `${runPath}.${setting.key}`
417
- if (setting.key === 'level') {
418
- if (setting.node.kind !== 'string' || !LEVELS.includes(setting.node.value)) {
419
- add(setting.node, settingPath, `must be one of ${LEVELS.join(' | ')}`)
420
- }
421
- } else if (setting.key === 'note') {
422
- if (setting.node.kind !== 'string') add(setting.node, settingPath, 'must be a string')
423
- } else {
424
- const settingSpot = keyOf(setting, settingPath)
425
- add(settingSpot.node, settingPath, 'unknown key; expected level or note')
426
- }
427
- }
428
- }
429
- }
430
- }
431
-
432
- if (errors.length > 0) throw new PolicyError(file, errors, source)
433
-
434
- const policy = valueOf(root)
435
- return {
436
- version: policy.version ?? 1,
437
- defaultLevel: policy.defaultLevel ?? 'allow',
438
- paths: { allow: policy.paths?.allow ?? [], deny: policy.paths?.deny ?? [] },
439
- commands: { allow: policy.commands?.allow ?? [], deny: policy.commands?.deny ?? [] },
440
- confirm: { actions: policy.confirm?.actions ?? [] },
441
- runs: policy.runs ?? {},
442
- note: typeof policy.note === 'string' ? policy.note : null,
443
- source: file,
444
- }
445
- }
446
-
447
- /**
448
- * Parse and validate policy text.
449
- * @param {string} text - file contents, comments allowed.
450
- * @param {{ file?: string }} [options] - display name used in errors.
451
- * @returns {object} frozen policy.
452
- * @throws {PolicyError} with one entry per problem, each carrying line and column.
453
- */
454
- export function parsePolicy(text, { file = 'audit-policy.json' } = {}) {
455
- const stripped = stripComments(String(text ?? ''))
456
- const trimmed = stripped.trim()
457
- if (!trimmed) throw new PolicyError(file, [{ line: 1, column: 1, path: '$', message: 'the policy file is empty' }], stripped)
458
- let tree
459
- try {
460
- tree = parseTree(stripped)
461
- } catch (error) {
462
- if (error instanceof SyntaxError) {
463
- throw new PolicyError(
464
- file,
465
- [{ line: error.line ?? 1, column: error.column ?? 1, path: '$', message: `not valid JSON: ${error.message}` }],
466
- stripped,
467
- )
468
- }
469
- throw error
470
- }
471
- return Object.freeze(validate(tree.root, file, stripped))
472
- }
473
-
474
- /**
475
- * Load a policy file, re-reading it when its mtime changes so an edit takes
476
- * effect without restarting the host. A read or parse failure is returned, not
477
- * thrown: the caller must keep the *previous* behaviour of failing closed and
478
- * telling the user, which it can only do with the error in hand.
479
- */
480
- export function createPolicyLoader({ file, warn = () => {} } = {}) {
481
- let cached = null
482
- let cachedMtime = -1
483
- let lastError = null
484
- return {
485
- file,
486
- /**
487
- * @returns {Promise<{ policy: object | null, error: PolicyError | Error | null, stale: boolean }>}
488
- */
489
- async get() {
490
- if (!file) return { policy: null, error: null, stale: false }
491
- let stat
492
- try {
493
- stat = await fsp.stat(file)
494
- } catch (error) {
495
- // A missing file is the documented "no policy" state, not a problem.
496
- if (error?.code === 'ENOENT') return { policy: null, error: null, stale: false }
497
- lastError = error
498
- return { policy: null, error, stale: cached !== null }
499
- }
500
- if (cached && stat.mtimeMs === cachedMtime) return { policy: cached, error: null, stale: false }
501
- try {
502
- const text = await fsp.readFile(file, 'utf8')
503
- const policy = parsePolicy(text, { file })
504
- cached = policy
505
- cachedMtime = stat.mtimeMs
506
- lastError = null
507
- return { policy, error: null, stale: false }
508
- } catch (error) {
509
- lastError = error
510
- warn(`permission policy ${file} is invalid and stays in force as "deny": ${error?.message ?? error}`)
511
- return { policy: null, error, stale: cached !== null }
512
- }
513
- },
514
- /** Last parse error, for status output. */
515
- get error() {
516
- return lastError
517
- },
518
- }
519
- }
520
-
521
- // ---------------------------------------------------------------------------
522
- // Matching
523
- // ---------------------------------------------------------------------------
524
-
525
- /** Convert a glob into a regular expression body; `**` spans separators. */
526
- function globBody(pattern) {
527
- let body = ''
528
- for (let i = 0; i < pattern.length; i++) {
529
- const char = pattern[i]
530
- if (char === '*') {
531
- if (pattern[i + 1] === '*') {
532
- body += '.*'
533
- i++
534
- if (pattern[i + 1] === '/') i++
535
- } else {
536
- body += '[^/]*'
537
- }
538
- continue
539
- }
540
- if (char === '?') {
541
- body += '[^/]'
542
- continue
543
- }
544
- body += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
545
- }
546
- return body
547
- }
548
-
549
- const isWindows = process.platform === 'win32'
550
-
551
- function normalizePath(value) {
552
- return String(value ?? '').replace(/\\/g, '/').replace(/\/{2,}/g, '/').replace(/\/$/, '')
553
- }
554
-
555
- /**
556
- * Does one path pattern cover this target?
557
- *
558
- * A relative pattern (`src/**`) matches at any directory boundary of an
559
- * absolute target, so the same policy works no matter where the workspace is
560
- * mounted. On Windows the comparison ignores case, which is how the filesystem
561
- * itself behaves.
562
- */
563
- export function pathMatches(pattern, target) {
564
- const raw = String(pattern ?? '').trim()
565
- if (!raw) return false
566
- const normalizedPattern = normalizePath(raw)
567
- const normalizedTarget = normalizePath(target)
568
- if (!normalizedTarget) return false
569
- const flags = isWindows ? 'i' : ''
570
- const absolute = /^[A-Za-z]:\//.test(normalizedPattern) || normalizedPattern.startsWith('/')
571
- if (absolute) {
572
- try {
573
- return new RegExp(`^${globBody(normalizedPattern)}$`, flags).test(normalizedTarget)
574
- } catch {
575
- return false
576
- }
577
- }
578
- try {
579
- // `**/x`, `x`, and `a/**/x` all have to work at a boundary; anchoring with
580
- // a slash-or-start prefix is what keeps `rc/a.js` from matching `src/a.js`.
581
- return new RegExp(`(?:^|/)${globBody(normalizedPattern)}$`, flags).test(normalizedTarget)
582
- } catch {
583
- return false
584
- }
585
- }
586
-
587
- /**
588
- * Match one command against one entry of a command list.
589
- *
590
- * A bare entry is a *prefix*: `git status` allows `git status --short` but not
591
- * `git statusx`. An entry containing `*` or `?` is a glob over the whole line.
592
- * @returns {{ matched: boolean, exact: boolean }} what the entry covered.
593
- */
594
- export function commandMatches(entry, command) {
595
- const pattern = String(entry ?? '').trim()
596
- const line = String(command ?? '').trim()
597
- if (!pattern || !line) return { matched: false, exact: false }
598
- const flags = isWindows ? 'i' : ''
599
- if (pattern.includes('*') || pattern.includes('?')) {
600
- try {
601
- const regex = new RegExp(`^${globBody(pattern)}$`, flags)
602
- return { matched: regex.test(line), exact: regex.test(line) }
603
- } catch {
604
- return { matched: false, exact: false }
605
- }
606
- }
607
- const equal = flags ? pattern.toLowerCase() === line.toLowerCase() : pattern === line
608
- if (equal) return { matched: true, exact: true }
609
- const prefix = flags ? line.toLowerCase().startsWith(`${pattern.toLowerCase()} `) : line.startsWith(`${pattern} `)
610
- return { matched: prefix, exact: false }
611
- }
612
-
613
- function matchCategory(actions, kind) {
614
- for (const entry of actions) {
615
- if (entry === kind) return entry
616
- if (entry.endsWith('*') && kind.startsWith(entry.slice(0, -1))) return entry
617
- }
618
- return null
619
- }
620
-
621
- function stricter(a, b) {
622
- const rank = { allow: 0, confirm: 1, deny: 2 }
623
- return (rank[a] ?? 0) >= (rank[b] ?? 0) ? a : b
624
- }
625
-
626
- /**
627
- * Decide one action against a policy.
628
- *
629
- * Precedence, strictest first:
630
- * 1. a `deny` pattern for the target -> deny
631
- * 2. an explicit `allow` pattern -> allow, tagged with what it relaxed
632
- * 3. the action kind listed under `confirm.actions` -> confirm
633
- * 4. the run's level, else the policy default level
634
- *
635
- * @param {object | null} policy - parsed policy, or null for "no policy".
636
- * @param {{ kind: string, target?: string, runId?: string }} request - action under review.
637
- * @returns {{ decision: 'allow'|'confirm'|'deny', rule: string, reason: string, relaxedFrom: string|null, match: string|null }}
638
- */
639
- export function decide(policy, request = {}) {
640
- const kind = String(request.kind ?? '')
641
- if (!policy) {
642
- return { decision: 'allow', rule: 'no-policy', reason: 'no permission policy is configured', relaxedFrom: null, match: null }
643
- }
644
- const isPath = kind.startsWith('path.')
645
- const isCommand = kind === 'command.exec'
646
- const target = isPath ? normalizePath(request.target) : String(request.target ?? '')
647
-
648
- if (isPath && target) {
649
- for (let i = 0; i < policy.paths.deny.length; i++) {
650
- if (pathMatches(policy.paths.deny[i], target)) {
651
- return {
652
- decision: 'deny',
653
- rule: `paths.deny[${i}]`,
654
- reason: `${target} matches the deny pattern ${JSON.stringify(policy.paths.deny[i])}`,
655
- relaxedFrom: null,
656
- match: policy.paths.deny[i],
657
- }
658
- }
659
- }
660
- for (let i = 0; i < policy.paths.allow.length; i++) {
661
- if (pathMatches(policy.paths.allow[i], target)) {
662
- const base = baseLevelFor(policy, request.runId, kind)
663
- const category = matchCategory(policy.confirm.actions, kind)
664
- const relaxedFrom = stricter(base, category ? 'confirm' : 'allow')
665
- return {
666
- decision: 'allow',
667
- rule: `paths.allow[${i}]`,
668
- reason: `${target} matches the explicit allow pattern ${JSON.stringify(policy.paths.allow[i])}`,
669
- relaxedFrom: relaxedFrom === 'allow' ? null : relaxedFrom,
670
- match: policy.paths.allow[i],
671
- }
672
- }
673
- }
674
- }
675
-
676
- if (isCommand && target) {
677
- for (let i = 0; i < policy.commands.deny.length; i++) {
678
- if (commandMatches(policy.commands.deny[i], target).matched) {
679
- return {
680
- decision: 'deny',
681
- rule: `commands.deny[${i}]`,
682
- reason: `the command matches the deny pattern ${JSON.stringify(policy.commands.deny[i])}`,
683
- relaxedFrom: null,
684
- match: policy.commands.deny[i],
685
- }
686
- }
687
- }
688
- for (let i = 0; i < policy.commands.allow.length; i++) {
689
- const hit = commandMatches(policy.commands.allow[i], target)
690
- if (!hit.matched) continue
691
- const base = baseLevelFor(policy, request.runId, kind)
692
- const category = matchCategory(policy.confirm.actions, kind)
693
- // A composite line (`a && b`) that only matched a prefix is not the
694
- // command the user allowed; it may not be lifted above "confirm".
695
- const composite = COMPOSITE_COMMAND.test(target) && !hit.exact
696
- const relaxedFrom = composite
697
- ? 'confirm'
698
- : stricter(base, category ? 'confirm' : 'allow')
699
- return {
700
- decision: composite ? 'confirm' : 'allow',
701
- rule: `commands.allow[${i}]`,
702
- reason: composite
703
- ? `the command only matches the prefix of ${JSON.stringify(policy.commands.allow[i])}, so the rest of a composite line needs confirmation`
704
- : `the command matches the explicit allow entry ${JSON.stringify(policy.commands.allow[i])}`,
705
- relaxedFrom: relaxedFrom === 'allow' ? null : relaxedFrom,
706
- match: policy.commands.allow[i],
707
- }
708
- }
709
- }
710
-
711
- const category = matchCategory(policy.confirm.actions, kind)
712
- if (category) {
713
- return {
714
- decision: 'confirm',
715
- rule: `confirm.actions[${policy.confirm.actions.indexOf(category)}]`,
716
- reason: `${kind} is listed as requiring confirmation`,
717
- relaxedFrom: null,
718
- match: category,
719
- }
720
- }
721
-
722
- const level = baseLevelFor(policy, request.runId, kind)
723
- return {
724
- decision: level,
725
- rule: request.runId && policy.runs?.[request.runId]?.level ? `runs.${request.runId}.level` : 'defaultLevel',
726
- reason: level === 'allow'
727
- ? 'nothing in the policy restricts this action'
728
- : `${kind} falls back to the ${level} level`,
729
- relaxedFrom: null,
730
- match: null,
731
- }
732
- }
733
-
734
- function baseLevelFor(policy, runId) {
735
- const perRun = runId ? policy.runs?.[runId]?.level : null
736
- const level = perRun ?? policy.defaultLevel ?? 'allow'
737
- // A policy that somehow carries an unknown level must not degrade to allow.
738
- return LEVELS.includes(level) ? level : 'deny'
739
- }
1
+ /**
2
+ * Permission policy for dsh-superagent runs.
3
+ *
4
+ * A policy is a small JSON file a person edits by hand, so every rejection has
5
+ * to say *where* the problem is: a schema error without a line number turns a
6
+ * typo into an afternoon of guessing. The file is parsed by a position-aware
7
+ * reader instead of `JSON.parse` for exactly that reason, and `//` / `#` line
8
+ * comments are stripped (with their newlines kept) so the file can explain
9
+ * itself.
10
+ *
11
+ * The policy only ever tightens. Nothing here relaxes a deny rule; an explicit
12
+ * allow entry can lift a `confirm` or a per-run `deny`, and the caller records
13
+ * that as an override so the audit trail shows who permitted it.
14
+ *
15
+ * @module dsh-superagent/policy
16
+ */
17
+ import fsp from 'node:fs/promises'
18
+
19
+ /** Decisions a policy can return, from loosest to strictest. */
20
+ export const LEVELS = ['allow', 'confirm', 'deny']
21
+
22
+ /** Action kinds a policy can talk about. `*` is accepted as a suffix wildcard. */
23
+ export const ACTION_KINDS = [
24
+ 'run.start',
25
+ 'run.resume',
26
+ 'path.read',
27
+ 'path.write',
28
+ 'command.exec',
29
+ 'tool.call',
30
+ 'network',
31
+ 'attention',
32
+ ]
33
+
34
+ const RUN_ID_PATTERN = /^[0-9A-Za-z][0-9A-Za-z_-]{3,63}$/
35
+ const MAX_ERRORS = 20
36
+ const COMPOSITE_COMMAND = /(?:&&|\|\||[;|`]|\$\(|\n)/
37
+
38
+ /** One invalid line of a policy file. */
39
+ export class PolicyError extends Error {
40
+ /**
41
+ * @param {string} file - display name of the policy file.
42
+ * @param {{ line: number, column: number, path: string, message: string }[]} errors - findings.
43
+ * @param {string} source - file text, used for a caret line.
44
+ */
45
+ constructor(file, errors, source = '') {
46
+ const head = `${file}: ${errors.length} problem${errors.length === 1 ? '' : 's'} in the permission policy`
47
+ const body = errors.map(problem => {
48
+ const caret = source ? `\n ${source.split('\n')[problem.line - 1] ?? ''}` : ''
49
+ const pointer = caret ? `\n ${' '.repeat(Math.max(0, problem.column - 1))}^` : ''
50
+ return ` ${file}:${problem.line}:${problem.column} [${problem.path}] ${problem.message}${caret}${pointer}`
51
+ })
52
+ super([head, ...body].join('\n'))
53
+ this.name = 'PolicyError'
54
+ this.file = file
55
+ this.errors = errors
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Remove comments from JSON text without moving any character: comment bytes
61
+ * become spaces, newlines survive. A `//` inside a string is left alone.
62
+ * @param {string} text - raw file text.
63
+ * @returns {string} text with comments blanked.
64
+ */
65
+ export function stripComments(text) {
66
+ let out = ''
67
+ let index = 0
68
+ let inString = false
69
+ let escaped = false
70
+ while (index < text.length) {
71
+ const char = text[index]
72
+ const next = text[index + 1]
73
+ if (inString) {
74
+ out += char
75
+ if (escaped) escaped = false
76
+ else if (char === '\\') escaped = true
77
+ else if (char === '"') inString = false
78
+ index++
79
+ continue
80
+ }
81
+ if (char === '"') {
82
+ inString = true
83
+ out += char
84
+ index++
85
+ continue
86
+ }
87
+ if (char === '/' && next === '/') {
88
+ while (index < text.length) {
89
+ const current = text[index]
90
+ out += current === '\n' ? '\n' : ' '
91
+ index++
92
+ if (current === '\n') break
93
+ }
94
+ continue
95
+ }
96
+ if (char === '/' && next === '*') {
97
+ out += ' '
98
+ index += 2
99
+ while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) {
100
+ out += text[index] === '\n' ? '\n' : ' '
101
+ index++
102
+ }
103
+ if (index < text.length) {
104
+ out += ' '
105
+ index += 2
106
+ }
107
+ continue
108
+ }
109
+ if (char === '#') {
110
+ while (index < text.length) {
111
+ const current = text[index]
112
+ out += current === '\n' ? '\n' : ' '
113
+ index++
114
+ if (current === '\n') break
115
+ }
116
+ continue
117
+ }
118
+ out += char
119
+ index++
120
+ }
121
+ return out
122
+ }
123
+
124
+ /**
125
+ * Minimal position-aware JSON reader. It is deliberately strict: trailing
126
+ * commas and unquoted keys are rejected, because a policy file that only
127
+ * *nearly* parses is a policy the user believes is in force but is not.
128
+ */
129
+ function parseTree(text) {
130
+ const lineStarts = [0]
131
+ for (let i = 0; i < text.length; i++) if (text[i] === '\n') lineStarts.push(i + 1)
132
+
133
+ const positionOf = index => {
134
+ let low = 0
135
+ let high = lineStarts.length - 1
136
+ while (low < high) {
137
+ const mid = Math.ceil((low + high) / 2)
138
+ if (lineStarts[mid] <= index) low = mid
139
+ else high = mid - 1
140
+ }
141
+ return { line: low + 1, column: index - lineStarts[low] + 1 }
142
+ }
143
+
144
+ let index = 0
145
+
146
+ const fail = (message, at = index) => {
147
+ const { line, column } = positionOf(Math.min(at, text.length))
148
+ const error = new SyntaxError(message)
149
+ error.line = line
150
+ error.column = column
151
+ error.at = at
152
+ throw error
153
+ }
154
+
155
+ const skipSpace = () => {
156
+ while (index < text.length && /\s/.test(text[index])) index++
157
+ }
158
+
159
+ const parseString = () => {
160
+ const start = index
161
+ index++
162
+ let value = ''
163
+ while (index < text.length) {
164
+ const char = text[index]
165
+ if (char === '"') {
166
+ index++
167
+ const { line, column } = positionOf(start)
168
+ return { kind: 'string', value, line, column }
169
+ }
170
+ if (char === '\\') {
171
+ const escape = text[index + 1]
172
+ const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }
173
+ if (escape in simple) {
174
+ value += simple[escape]
175
+ index += 2
176
+ continue
177
+ }
178
+ if (escape === 'u') {
179
+ const hex = text.slice(index + 2, index + 6)
180
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('invalid \\u escape in a string', index)
181
+ value += String.fromCharCode(parseInt(hex, 16))
182
+ index += 6
183
+ continue
184
+ }
185
+ fail('invalid escape in a string', index)
186
+ }
187
+ if (char === '\n') fail('a string is missing its closing quote', start)
188
+ value += char
189
+ index++
190
+ }
191
+ fail('a string is missing its closing quote', start)
192
+ return null
193
+ }
194
+
195
+ const parseValue = () => {
196
+ skipSpace()
197
+ const start = index
198
+ const char = text[index]
199
+ if (char === '{') {
200
+ const { line, column } = positionOf(start)
201
+ index++
202
+ const entries = []
203
+ skipSpace()
204
+ if (text[index] === '}') {
205
+ index++
206
+ return { kind: 'object', entries, line, column }
207
+ }
208
+ for (;;) {
209
+ skipSpace()
210
+ if (text[index] !== '"') fail('expected a quoted key')
211
+ const keyStart = index
212
+ const keyNode = parseString()
213
+ skipSpace()
214
+ if (text[index] !== ':') fail('expected ":" after a key')
215
+ index++
216
+ const node = parseValue()
217
+ const { line: keyLine, column: keyColumn } = positionOf(keyStart)
218
+ entries.push({ key: keyNode.value, keyLine, keyColumn, node })
219
+ skipSpace()
220
+ if (text[index] === ',') {
221
+ index++
222
+ skipSpace()
223
+ if (text[index] === '}') fail('trailing commas are not allowed')
224
+ continue
225
+ }
226
+ if (text[index] === '}') {
227
+ index++
228
+ return { kind: 'object', entries, line, column }
229
+ }
230
+ fail('expected "," or "}" in an object')
231
+ }
232
+ }
233
+ if (char === '[') {
234
+ const { line, column } = positionOf(start)
235
+ index++
236
+ const items = []
237
+ skipSpace()
238
+ if (text[index] === ']') {
239
+ index++
240
+ return { kind: 'array', items, line, column }
241
+ }
242
+ for (;;) {
243
+ items.push(parseValue())
244
+ skipSpace()
245
+ if (text[index] === ',') {
246
+ index++
247
+ skipSpace()
248
+ if (text[index] === ']') fail('trailing commas are not allowed')
249
+ continue
250
+ }
251
+ if (text[index] === ']') {
252
+ index++
253
+ return { kind: 'array', items, line, column }
254
+ }
255
+ fail('expected "," or "]" in an array')
256
+ }
257
+ }
258
+ if (char === '"') return parseString()
259
+ const literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(index))
260
+ if (!literal) fail(`unexpected character ${JSON.stringify(char ?? 'end of file')}`)
261
+ index += literal[0].length
262
+ const { line, column } = positionOf(start)
263
+ if (literal[0] === 'true' || literal[0] === 'false') {
264
+ return { kind: 'boolean', value: literal[0] === 'true', line, column }
265
+ }
266
+ if (literal[0] === 'null') return { kind: 'null', value: null, line, column }
267
+ return { kind: 'number', value: Number(literal[0]), line, column }
268
+ }
269
+
270
+ const root = parseValue()
271
+ skipSpace()
272
+ if (index < text.length) fail('unexpected text after the top-level value')
273
+ return { root, positionOf }
274
+ }
275
+
276
+ function valueOf(node) {
277
+ if (node.kind === 'object') {
278
+ const value = {}
279
+ for (const entry of node.entries) value[entry.key] = valueOf(entry.node)
280
+ return value
281
+ }
282
+ if (node.kind === 'array') return node.items.map(valueOf)
283
+ return node.value
284
+ }
285
+
286
+ /**
287
+ * Validate one policy tree and return the plain object a decision reads.
288
+ * Every problem carries the line and column of the token that caused it.
289
+ */
290
+ function validate(root, file, source) {
291
+ const errors = []
292
+ const add = (node, path, message) => {
293
+ if (errors.length >= MAX_ERRORS) return
294
+ errors.push({ line: node?.line ?? 1, column: node?.column ?? 1, path, message })
295
+ }
296
+ const keyOf = (entry, path) => {
297
+ const node = { line: entry.keyLine, column: entry.keyColumn }
298
+ return { node, path }
299
+ }
300
+
301
+ if (root.kind !== 'object') {
302
+ add(root, '$', 'the policy must be a JSON object')
303
+ throw new PolicyError(file, errors, source)
304
+ }
305
+
306
+ const seen = new Map()
307
+ for (const entry of root.entries) {
308
+ if (seen.has(entry.key)) {
309
+ const spot = keyOf(entry, entry.key)
310
+ add(spot.node, spot.path, `duplicate key; the earlier value was already set on line ${seen.get(entry.key)}`)
311
+ } else {
312
+ seen.set(entry.key, entry.keyLine)
313
+ }
314
+ }
315
+
316
+ const knownRoot = ['version', 'defaultLevel', 'paths', 'commands', 'confirm', 'runs', 'note']
317
+ for (const entry of root.entries) {
318
+ if (!knownRoot.includes(entry.key)) {
319
+ const spot = keyOf(entry, entry.key)
320
+ add(spot.node, spot.path, `unknown key; expected one of ${knownRoot.join(', ')}`)
321
+ continue
322
+ }
323
+ const path = entry.key
324
+ const node = entry.node
325
+ if (entry.key === 'version') {
326
+ if (node.kind !== 'number' || node.value !== 1) add(node, path, 'must be the number 1')
327
+ continue
328
+ }
329
+ if (entry.key === 'note') {
330
+ if (node.kind !== 'string') add(node, path, 'must be a string')
331
+ continue
332
+ }
333
+ if (entry.key === 'defaultLevel') {
334
+ if (node.kind !== 'string' || !LEVELS.includes(node.value)) {
335
+ add(node, path, `must be one of ${LEVELS.join(' | ')}`)
336
+ }
337
+ continue
338
+ }
339
+ if (entry.key === 'paths' || entry.key === 'commands') {
340
+ if (node.kind !== 'object') {
341
+ add(node, path, 'must be an object with allow and/or deny arrays')
342
+ continue
343
+ }
344
+ const known = ['allow', 'deny']
345
+ for (const child of node.entries) {
346
+ if (!known.includes(child.key)) {
347
+ const spot = keyOf(child, `${path}.${child.key}`)
348
+ add(spot.node, spot.path, `unknown key; expected ${known.join(' or ')}`)
349
+ continue
350
+ }
351
+ const listPath = `${path}.${child.key}`
352
+ if (child.node.kind !== 'array') {
353
+ add(child.node, listPath, 'must be an array of strings')
354
+ continue
355
+ }
356
+ child.node.items.forEach((item, i) => {
357
+ const itemPath = `${listPath}[${i}]`
358
+ if (item.kind !== 'string') {
359
+ add(item, itemPath, 'must be a string')
360
+ return
361
+ }
362
+ if (!item.value.trim()) add(item, itemPath, 'must not be empty')
363
+ })
364
+ }
365
+ continue
366
+ }
367
+ if (entry.key === 'confirm') {
368
+ if (node.kind !== 'object') {
369
+ add(node, path, 'must be an object with an actions array')
370
+ continue
371
+ }
372
+ for (const child of node.entries) {
373
+ if (child.key !== 'actions') {
374
+ const spot = keyOf(child, `${path}.${child.key}`)
375
+ add(spot.node, spot.path, 'unknown key; expected actions')
376
+ continue
377
+ }
378
+ if (child.node.kind !== 'array') {
379
+ add(child.node, `${path}.actions`, 'must be an array of action kinds')
380
+ continue
381
+ }
382
+ child.node.items.forEach((item, i) => {
383
+ const itemPath = `${path}.actions[${i}]`
384
+ if (item.kind !== 'string') {
385
+ add(item, itemPath, 'must be a string')
386
+ return
387
+ }
388
+ const wildcard = item.value.endsWith('*')
389
+ const base = wildcard ? item.value.slice(0, -1) : item.value
390
+ const known = ACTION_KINDS.includes(item.value)
391
+ || (wildcard && ACTION_KINDS.some(kind => kind.startsWith(base)))
392
+ if (!known) {
393
+ add(item, itemPath, `unknown action kind; expected one of ${ACTION_KINDS.join(', ')} (or "path.*")`)
394
+ }
395
+ })
396
+ }
397
+ continue
398
+ }
399
+ if (entry.key === 'runs') {
400
+ if (node.kind !== 'object') {
401
+ add(node, path, 'must be an object keyed by run id')
402
+ continue
403
+ }
404
+ for (const child of node.entries) {
405
+ const runPath = `${path}.${child.key}`
406
+ const spot = keyOf(child, runPath)
407
+ if (!RUN_ID_PATTERN.test(child.key)) {
408
+ add(spot.node, runPath, 'is not a run id (letters, digits, "-" or "_", 4-64 characters)')
409
+ continue
410
+ }
411
+ if (child.node.kind !== 'object') {
412
+ add(child.node, runPath, 'must be an object with level and/or note')
413
+ continue
414
+ }
415
+ for (const setting of child.node.entries) {
416
+ const settingPath = `${runPath}.${setting.key}`
417
+ if (setting.key === 'level') {
418
+ if (setting.node.kind !== 'string' || !LEVELS.includes(setting.node.value)) {
419
+ add(setting.node, settingPath, `must be one of ${LEVELS.join(' | ')}`)
420
+ }
421
+ } else if (setting.key === 'note') {
422
+ if (setting.node.kind !== 'string') add(setting.node, settingPath, 'must be a string')
423
+ } else {
424
+ const settingSpot = keyOf(setting, settingPath)
425
+ add(settingSpot.node, settingPath, 'unknown key; expected level or note')
426
+ }
427
+ }
428
+ }
429
+ }
430
+ }
431
+
432
+ if (errors.length > 0) throw new PolicyError(file, errors, source)
433
+
434
+ const policy = valueOf(root)
435
+ return {
436
+ version: policy.version ?? 1,
437
+ defaultLevel: policy.defaultLevel ?? 'allow',
438
+ paths: { allow: policy.paths?.allow ?? [], deny: policy.paths?.deny ?? [] },
439
+ commands: { allow: policy.commands?.allow ?? [], deny: policy.commands?.deny ?? [] },
440
+ confirm: { actions: policy.confirm?.actions ?? [] },
441
+ runs: policy.runs ?? {},
442
+ note: typeof policy.note === 'string' ? policy.note : null,
443
+ source: file,
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Parse and validate policy text.
449
+ * @param {string} text - file contents, comments allowed.
450
+ * @param {{ file?: string }} [options] - display name used in errors.
451
+ * @returns {object} frozen policy.
452
+ * @throws {PolicyError} with one entry per problem, each carrying line and column.
453
+ */
454
+ export function parsePolicy(text, { file = 'audit-policy.json' } = {}) {
455
+ const stripped = stripComments(String(text ?? ''))
456
+ const trimmed = stripped.trim()
457
+ if (!trimmed) throw new PolicyError(file, [{ line: 1, column: 1, path: '$', message: 'the policy file is empty' }], stripped)
458
+ let tree
459
+ try {
460
+ tree = parseTree(stripped)
461
+ } catch (error) {
462
+ if (error instanceof SyntaxError) {
463
+ throw new PolicyError(
464
+ file,
465
+ [{ line: error.line ?? 1, column: error.column ?? 1, path: '$', message: `not valid JSON: ${error.message}` }],
466
+ stripped,
467
+ )
468
+ }
469
+ throw error
470
+ }
471
+ return Object.freeze(validate(tree.root, file, stripped))
472
+ }
473
+
474
+ /**
475
+ * Load a policy file, re-reading it when its mtime changes so an edit takes
476
+ * effect without restarting the host. A read or parse failure is returned, not
477
+ * thrown: the caller must keep the *previous* behaviour of failing closed and
478
+ * telling the user, which it can only do with the error in hand.
479
+ */
480
+ export function createPolicyLoader({ file, warn = () => {} } = {}) {
481
+ let cached = null
482
+ let cachedMtime = -1
483
+ let lastError = null
484
+ return {
485
+ file,
486
+ /**
487
+ * @returns {Promise<{ policy: object | null, error: PolicyError | Error | null, stale: boolean }>}
488
+ */
489
+ async get() {
490
+ if (!file) return { policy: null, error: null, stale: false }
491
+ let stat
492
+ try {
493
+ stat = await fsp.stat(file)
494
+ } catch (error) {
495
+ // A missing file is the documented "no policy" state, not a problem.
496
+ if (error?.code === 'ENOENT') return { policy: null, error: null, stale: false }
497
+ lastError = error
498
+ return { policy: null, error, stale: cached !== null }
499
+ }
500
+ if (cached && stat.mtimeMs === cachedMtime) return { policy: cached, error: null, stale: false }
501
+ try {
502
+ const text = await fsp.readFile(file, 'utf8')
503
+ const policy = parsePolicy(text, { file })
504
+ cached = policy
505
+ cachedMtime = stat.mtimeMs
506
+ lastError = null
507
+ return { policy, error: null, stale: false }
508
+ } catch (error) {
509
+ lastError = error
510
+ warn(`permission policy ${file} is invalid and stays in force as "deny": ${error?.message ?? error}`)
511
+ return { policy: null, error, stale: cached !== null }
512
+ }
513
+ },
514
+ /** Last parse error, for status output. */
515
+ get error() {
516
+ return lastError
517
+ },
518
+ }
519
+ }
520
+
521
+ // ---------------------------------------------------------------------------
522
+ // Matching
523
+ // ---------------------------------------------------------------------------
524
+
525
+ /** Convert a glob into a regular expression body; `**` spans separators. */
526
+ function globBody(pattern) {
527
+ let body = ''
528
+ for (let i = 0; i < pattern.length; i++) {
529
+ const char = pattern[i]
530
+ if (char === '*') {
531
+ if (pattern[i + 1] === '*') {
532
+ body += '.*'
533
+ i++
534
+ if (pattern[i + 1] === '/') i++
535
+ } else {
536
+ body += '[^/]*'
537
+ }
538
+ continue
539
+ }
540
+ if (char === '?') {
541
+ body += '[^/]'
542
+ continue
543
+ }
544
+ body += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
545
+ }
546
+ return body
547
+ }
548
+
549
+ const isWindows = process.platform === 'win32'
550
+
551
+ function normalizePath(value) {
552
+ return String(value ?? '').replace(/\\/g, '/').replace(/\/{2,}/g, '/').replace(/\/$/, '')
553
+ }
554
+
555
+ /**
556
+ * Does one path pattern cover this target?
557
+ *
558
+ * A relative pattern (`src/**`) matches at any directory boundary of an
559
+ * absolute target, so the same policy works no matter where the workspace is
560
+ * mounted. On Windows the comparison ignores case, which is how the filesystem
561
+ * itself behaves.
562
+ */
563
+ export function pathMatches(pattern, target) {
564
+ const raw = String(pattern ?? '').trim()
565
+ if (!raw) return false
566
+ const normalizedPattern = normalizePath(raw)
567
+ const normalizedTarget = normalizePath(target)
568
+ if (!normalizedTarget) return false
569
+ const flags = isWindows ? 'i' : ''
570
+ const absolute = /^[A-Za-z]:\//.test(normalizedPattern) || normalizedPattern.startsWith('/')
571
+ if (absolute) {
572
+ try {
573
+ return new RegExp(`^${globBody(normalizedPattern)}$`, flags).test(normalizedTarget)
574
+ } catch {
575
+ return false
576
+ }
577
+ }
578
+ try {
579
+ // `**/x`, `x`, and `a/**/x` all have to work at a boundary; anchoring with
580
+ // a slash-or-start prefix is what keeps `rc/a.js` from matching `src/a.js`.
581
+ return new RegExp(`(?:^|/)${globBody(normalizedPattern)}$`, flags).test(normalizedTarget)
582
+ } catch {
583
+ return false
584
+ }
585
+ }
586
+
587
+ /**
588
+ * Match one command against one entry of a command list.
589
+ *
590
+ * A bare entry is a *prefix*: `git status` allows `git status --short` but not
591
+ * `git statusx`. An entry containing `*` or `?` is a glob over the whole line.
592
+ * @returns {{ matched: boolean, exact: boolean }} what the entry covered.
593
+ */
594
+ export function commandMatches(entry, command) {
595
+ const pattern = String(entry ?? '').trim()
596
+ const line = String(command ?? '').trim()
597
+ if (!pattern || !line) return { matched: false, exact: false }
598
+ const flags = isWindows ? 'i' : ''
599
+ if (pattern.includes('*') || pattern.includes('?')) {
600
+ try {
601
+ const regex = new RegExp(`^${globBody(pattern)}$`, flags)
602
+ return { matched: regex.test(line), exact: regex.test(line) }
603
+ } catch {
604
+ return { matched: false, exact: false }
605
+ }
606
+ }
607
+ const equal = flags ? pattern.toLowerCase() === line.toLowerCase() : pattern === line
608
+ if (equal) return { matched: true, exact: true }
609
+ const prefix = flags ? line.toLowerCase().startsWith(`${pattern.toLowerCase()} `) : line.startsWith(`${pattern} `)
610
+ return { matched: prefix, exact: false }
611
+ }
612
+
613
+ function matchCategory(actions, kind) {
614
+ for (const entry of actions) {
615
+ if (entry === kind) return entry
616
+ if (entry.endsWith('*') && kind.startsWith(entry.slice(0, -1))) return entry
617
+ }
618
+ return null
619
+ }
620
+
621
+ function stricter(a, b) {
622
+ const rank = { allow: 0, confirm: 1, deny: 2 }
623
+ return (rank[a] ?? 0) >= (rank[b] ?? 0) ? a : b
624
+ }
625
+
626
+ /**
627
+ * Decide one action against a policy.
628
+ *
629
+ * Precedence, strictest first:
630
+ * 1. a `deny` pattern for the target -> deny
631
+ * 2. an explicit `allow` pattern -> allow, tagged with what it relaxed
632
+ * 3. the action kind listed under `confirm.actions` -> confirm
633
+ * 4. the run's level, else the policy default level
634
+ *
635
+ * @param {object | null} policy - parsed policy, or null for "no policy".
636
+ * @param {{ kind: string, target?: string, runId?: string }} request - action under review.
637
+ * @returns {{ decision: 'allow'|'confirm'|'deny', rule: string, reason: string, relaxedFrom: string|null, match: string|null }}
638
+ */
639
+ export function decide(policy, request = {}) {
640
+ const kind = String(request.kind ?? '')
641
+ if (!policy) {
642
+ return { decision: 'allow', rule: 'no-policy', reason: 'no permission policy is configured', relaxedFrom: null, match: null }
643
+ }
644
+ const isPath = kind.startsWith('path.')
645
+ const isCommand = kind === 'command.exec'
646
+ const target = isPath ? normalizePath(request.target) : String(request.target ?? '')
647
+
648
+ if (isPath && target) {
649
+ for (let i = 0; i < policy.paths.deny.length; i++) {
650
+ if (pathMatches(policy.paths.deny[i], target)) {
651
+ return {
652
+ decision: 'deny',
653
+ rule: `paths.deny[${i}]`,
654
+ reason: `${target} matches the deny pattern ${JSON.stringify(policy.paths.deny[i])}`,
655
+ relaxedFrom: null,
656
+ match: policy.paths.deny[i],
657
+ }
658
+ }
659
+ }
660
+ for (let i = 0; i < policy.paths.allow.length; i++) {
661
+ if (pathMatches(policy.paths.allow[i], target)) {
662
+ const base = baseLevelFor(policy, request.runId, kind)
663
+ const category = matchCategory(policy.confirm.actions, kind)
664
+ const relaxedFrom = stricter(base, category ? 'confirm' : 'allow')
665
+ return {
666
+ decision: 'allow',
667
+ rule: `paths.allow[${i}]`,
668
+ reason: `${target} matches the explicit allow pattern ${JSON.stringify(policy.paths.allow[i])}`,
669
+ relaxedFrom: relaxedFrom === 'allow' ? null : relaxedFrom,
670
+ match: policy.paths.allow[i],
671
+ }
672
+ }
673
+ }
674
+ }
675
+
676
+ if (isCommand && target) {
677
+ for (let i = 0; i < policy.commands.deny.length; i++) {
678
+ if (commandMatches(policy.commands.deny[i], target).matched) {
679
+ return {
680
+ decision: 'deny',
681
+ rule: `commands.deny[${i}]`,
682
+ reason: `the command matches the deny pattern ${JSON.stringify(policy.commands.deny[i])}`,
683
+ relaxedFrom: null,
684
+ match: policy.commands.deny[i],
685
+ }
686
+ }
687
+ }
688
+ for (let i = 0; i < policy.commands.allow.length; i++) {
689
+ const hit = commandMatches(policy.commands.allow[i], target)
690
+ if (!hit.matched) continue
691
+ const base = baseLevelFor(policy, request.runId, kind)
692
+ const category = matchCategory(policy.confirm.actions, kind)
693
+ // A composite line (`a && b`) that only matched a prefix is not the
694
+ // command the user allowed; it may not be lifted above "confirm".
695
+ const composite = COMPOSITE_COMMAND.test(target) && !hit.exact
696
+ const relaxedFrom = composite
697
+ ? 'confirm'
698
+ : stricter(base, category ? 'confirm' : 'allow')
699
+ return {
700
+ decision: composite ? 'confirm' : 'allow',
701
+ rule: `commands.allow[${i}]`,
702
+ reason: composite
703
+ ? `the command only matches the prefix of ${JSON.stringify(policy.commands.allow[i])}, so the rest of a composite line needs confirmation`
704
+ : `the command matches the explicit allow entry ${JSON.stringify(policy.commands.allow[i])}`,
705
+ relaxedFrom: relaxedFrom === 'allow' ? null : relaxedFrom,
706
+ match: policy.commands.allow[i],
707
+ }
708
+ }
709
+ }
710
+
711
+ const category = matchCategory(policy.confirm.actions, kind)
712
+ if (category) {
713
+ return {
714
+ decision: 'confirm',
715
+ rule: `confirm.actions[${policy.confirm.actions.indexOf(category)}]`,
716
+ reason: `${kind} is listed as requiring confirmation`,
717
+ relaxedFrom: null,
718
+ match: category,
719
+ }
720
+ }
721
+
722
+ const level = baseLevelFor(policy, request.runId, kind)
723
+ return {
724
+ decision: level,
725
+ rule: request.runId && policy.runs?.[request.runId]?.level ? `runs.${request.runId}.level` : 'defaultLevel',
726
+ reason: level === 'allow'
727
+ ? 'nothing in the policy restricts this action'
728
+ : `${kind} falls back to the ${level} level`,
729
+ relaxedFrom: null,
730
+ match: null,
731
+ }
732
+ }
733
+
734
+ function baseLevelFor(policy, runId) {
735
+ const perRun = runId ? policy.runs?.[runId]?.level : null
736
+ const level = perRun ?? policy.defaultLevel ?? 'allow'
737
+ // A policy that somehow carries an unknown level must not degrade to allow.
738
+ return LEVELS.includes(level) ? level : 'deny'
739
+ }