@xiangyixie/dsh-superagent 0.11.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/guard.js ADDED
@@ -0,0 +1,841 @@
1
+ /**
2
+ * The worker safety guard: a path and command policy enforced on the host's
3
+ * tool-call pipeline for superagent children only.
4
+ *
5
+ * The host runs every tool call through `tools/pre-execute` and its monotonic
6
+ * `ctx.tools.guard()` layer. A child agent inherits the session's filesystem and
7
+ * credentials, so this module is the one place that decides whether a worker may
8
+ * touch a path or run a command. It is deliberately a separate file with no
9
+ * host imports: `lib/index.js` registers the hook and `lib/orchestrator.js`
10
+ * only records the outcome on the run.
11
+ *
12
+ * Design notes that are not obvious from the code:
13
+ * - Deny rules win over allow roots. Allowing a broader workspace never opens
14
+ * `~/.ssh`, `.git/config`, or a system directory for writing.
15
+ * - A path is checked twice: lexically (so a target that does not exist yet is
16
+ * still caught) and through `realpath` on its deepest existing ancestor (so a
17
+ * symlink inside the workspace cannot smuggle a write outside it).
18
+ * - Commands are parsed, not pattern-blocked wholesale. `rm -rf build` stays a
19
+ * normal build step; `rm -rf /`, `rm -rf ~`, and `rm -rf .` do not.
20
+ * - An explicit `guard.allowCommands` entry is the only way through a denial,
21
+ * and every use of one is recorded on the run.
22
+ *
23
+ * @module dsh-superagent/guard
24
+ */
25
+ import fs from 'node:fs'
26
+ import os from 'node:os'
27
+ import path from 'node:path'
28
+
29
+ /** Credential locations that are never readable or writable by a worker. */
30
+ const CREDENTIAL_NAMES = [
31
+ '.ssh',
32
+ '.aws',
33
+ '.gnupg',
34
+ '.netrc',
35
+ '.npmrc',
36
+ '.yarnrc',
37
+ '.pypirc',
38
+ '.git-credentials',
39
+ '.docker/config.json',
40
+ '.kube/config',
41
+ '.config/gcloud',
42
+ '.config/gh/hosts.yml',
43
+ '.azure',
44
+ ]
45
+
46
+ /** System locations that a worker may read but never write. */
47
+ const WINDOWS_SYSTEM_WRITE = [
48
+ 'C:\\Windows',
49
+ 'C:\\Program Files',
50
+ 'C:\\Program Files (x86)',
51
+ 'C:\\ProgramData',
52
+ ]
53
+
54
+ const POSIX_SYSTEM_WRITE = [
55
+ '/etc',
56
+ '/usr',
57
+ '/bin',
58
+ '/sbin',
59
+ '/boot',
60
+ '/dev',
61
+ '/proc',
62
+ '/sys',
63
+ '/System',
64
+ '/Library',
65
+ '/Applications',
66
+ ]
67
+
68
+ /**
69
+ * Commands that are destructive regardless of their target. Each rule is a
70
+ * named policy decision so a report can say which rule stopped the call.
71
+ */
72
+ const HARD_COMMAND_RULES = [
73
+ {
74
+ id: 'cmd/disk-format',
75
+ reason: 'formats or repartitions a disk or volume',
76
+ test: text => /\b(mkfs(\.\w+)?|wipefs|diskpart|clear-disk|format-volume)\b/i.test(text)
77
+ || /\bformat(\.com)?\s+[a-z]:/i.test(text)
78
+ || /\bdd\b[^|;&]*\bof=\/dev\/(sd|hd|nvme|disk|mmcblk)\w*/i.test(text),
79
+ },
80
+ {
81
+ id: 'cmd/system-scheduler',
82
+ reason: 'changes a system-wide scheduled task, service, or login item',
83
+ test: text => /\bschtasks(\.exe)?\s+\/(create|change|delete|run)\b/i.test(text)
84
+ || /\b(register|set|new|unregister)-scheduledtask\b/i.test(text)
85
+ || /\bcrontab\s+[^|;&]*-r\b/i.test(text)
86
+ || /\bsystemctl\s+(enable|disable|mask|unmask)\b/i.test(text)
87
+ || /\blaunchctl\s+(load|unload|bootstrap|bootout|enable|disable)\b/i.test(text)
88
+ || /\bsc(\.exe)?\s+(create|delete|config)\b/i.test(text),
89
+ },
90
+ {
91
+ id: 'cmd/system-registry',
92
+ reason: 'writes a machine-wide registry or boot configuration key',
93
+ test: text => /\breg(\.exe)?\s+(add|delete|import)\b[^|;&]*\bHK(LM|EY_LOCAL_MACHINE|CR|EY_CLASSES_ROOT)\b/i.test(text)
94
+ || /\breg(\.exe)?\s+(add|delete|import)\b[^|;&]*\\Run\b/i.test(text)
95
+ || /\b(set|new|remove)-itemproperty\b[^|;&]*\bHK(LM|EY_LOCAL_MACHINE|CR|EY_CLASSES_ROOT)\b/i.test(text),
96
+ },
97
+ {
98
+ id: 'cmd/permission-nuke',
99
+ reason: 'grants world-writable access or replaces ownership of a system path',
100
+ test: text => /\bchmod\s+(-[a-z]*r[a-z]*\s+)?(777|a\+rwx)\s+\/(\s|$)/i.test(text)
101
+ || /\bchown\s+-[a-z]*r[a-z]*\s+\S+\s+\/(\s|$)/i.test(text)
102
+ || /\bicacls\b[^|;&]*\/(grant|setowner)\b[^|;&]*\b(everyone|users)\b[^|;&]*\/t\b/i.test(text),
103
+ },
104
+ ]
105
+
106
+ /** Absolute system locations used to stop a command that writes through a variable. */
107
+ const SYSTEM_WRITE_MARKERS = [
108
+ /[a-z]:[\\/]windows[\\/]/i,
109
+ /[a-z]:[\\/]program files( \(x86\))?[\\/]/i,
110
+ /[a-z]:[\\/]programdata[\\/]/i,
111
+ /%systemroot%/i,
112
+ /%programfiles%/i,
113
+ /%windir%/i,
114
+ /\$env:(systemroot|windir|programfiles)\b/i,
115
+ /(^|[\s"'])\/etc\//,
116
+ /(^|[\s"'])\/usr\//,
117
+ /(^|[\s"'])\/bin\//,
118
+ /(^|[\s"'])\/sbin\//,
119
+ /(^|[\s"'])\/boot\//,
120
+ /(^|[\s"'])\/System\//,
121
+ /(^|[\s"'])\/Library\//,
122
+ ]
123
+
124
+ /** Credential fragments that make a command an obvious credential read. */
125
+ const CREDENTIAL_MARKERS = [
126
+ /(^|[\s"'/\\])\.ssh[\\/]/i,
127
+ /(^|[\s"'/\\])\.aws[\\/]/i,
128
+ /(^|[\s"'/\\])\.gnupg[\\/]/i,
129
+ /(^|[\s"'/\\])\.npmrc\b/i,
130
+ /(^|[\s"'/\\])\.netrc\b/i,
131
+ /(^|[\s"'/\\])\.git-credentials\b/i,
132
+ /(^|[\s"'/\\])\.kube[\\/]config\b/i,
133
+ /(^|[\s"'/\\])\.docker[\\/]config\.json\b/i,
134
+ /(^|[\s"'/\\])\.config[\\/]gcloud\b/i,
135
+ /\bid_(rsa|dsa|ecdsa|ed25519)\b/i,
136
+ ]
137
+
138
+ /** `.git/config` and `.git/hooks` can run code on the next git command. */
139
+ const GIT_CONTROL_SEGMENTS = new Set(['config', 'hooks'])
140
+
141
+ const MAX_DETAIL = 240
142
+
143
+ /** True when `target` is `root` or lies below it. */
144
+ function contained(root, target, platform) {
145
+ const P = platform === 'win32' ? path.win32 : path.posix
146
+ const normalize = value => {
147
+ const normalized = P.normalize(value)
148
+ return platform === 'win32' ? normalized.toLowerCase() : normalized
149
+ }
150
+ const r = normalize(root)
151
+ const t = normalize(target)
152
+ if (r === t) return true
153
+ const relative = P.relative(r, t)
154
+ return relative !== '' && !relative.startsWith('..') && !P.isAbsolute(relative)
155
+ }
156
+
157
+ /** True when the path is a filesystem root (`C:\` or `/`). */
158
+ function isFilesystemRoot(target, platform) {
159
+ const P = platform === 'win32' ? path.win32 : path.posix
160
+ return P.parse(target).root === target
161
+ }
162
+
163
+ /** Expand `~`, `%VAR%`, and `$VAR` without treating an unknown variable as a path. */
164
+ function expandPath(value, { platform, homedir, env }) {
165
+ const P = platform === 'win32' ? path.win32 : path.posix
166
+ let expanded = value
167
+ if (expanded === '~' || /^~[\\/]/.test(expanded)) expanded = P.join(homedir, expanded.slice(1))
168
+ if (platform === 'win32') {
169
+ expanded = expanded.replace(/%([^%]+)%/g, (match, name) => {
170
+ const key = Object.keys(env ?? {}).find(candidate => candidate.toLowerCase() === name.toLowerCase())
171
+ return key === undefined ? match : env[key]
172
+ })
173
+ } else {
174
+ expanded = expanded.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, braced, bare) => {
175
+ const name = braced ?? bare
176
+ return env?.[name] ?? match
177
+ })
178
+ }
179
+ return expanded
180
+ }
181
+
182
+ /**
183
+ * Resolve a path from a tool argument against the child's workspace.
184
+ * @returns {string | null} an absolute normalized path, or null when the value
185
+ * is not a path at all (a flag, a URL, a null device, or empty).
186
+ */
187
+ function resolveTarget(raw, { cwd, platform, homedir, env }) {
188
+ const P = platform === 'win32' ? path.win32 : path.posix
189
+ let value = String(raw ?? '').trim()
190
+ if (!value) return null
191
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
192
+ value = value.slice(1, -1).trim()
193
+ }
194
+ if (!value || value === '-' || /^(nul|\/dev\/null)$/i.test(value)) return null
195
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return null
196
+ value = expandPath(value, { platform, homedir, env })
197
+ // An unresolved variable is not a literal path. Treating it as one would
198
+ // resolve it inside the workspace and silently allow a write elsewhere.
199
+ if (/%[^%]+%|\$\{?[A-Za-z_]/.test(value)) return null
200
+ // `path.win32.isAbsolute('/x')` is true but means "on the current drive".
201
+ // Resolve it against the child workspace so the compared path is real.
202
+ const driveRelative = platform === 'win32' && /^[\\/]/.test(value) && !/^[\\/]{2}/.test(value)
203
+ if (driveRelative || !P.isAbsolute(value)) {
204
+ if (!cwd) return null
205
+ value = P.resolve(cwd, value)
206
+ }
207
+ const normalized = P.normalize(value)
208
+ if (isFilesystemRoot(normalized, platform)) return normalized
209
+ return normalized.replace(/[\\/]+$/, '') || normalized
210
+ }
211
+
212
+ /**
213
+ * Resolve the deepest existing ancestor so a symlink cannot hide a target.
214
+ * A path that does not exist yet is returned unchanged.
215
+ */
216
+ function realPathOf(target, platform) {
217
+ const P = platform === 'win32' ? path.win32 : path.posix
218
+ let current = target
219
+ const tail = []
220
+ for (;;) {
221
+ try {
222
+ const real = fs.realpathSync.native ? fs.realpathSync.native(current) : fs.realpathSync(current)
223
+ const complete = tail.length === 0 ? real : P.join(real, ...tail.reverse())
224
+ return P.normalize(complete)
225
+ } catch {
226
+ const parent = P.dirname(current)
227
+ if (parent === current) return target
228
+ tail.push(P.basename(current))
229
+ current = parent
230
+ }
231
+ }
232
+ }
233
+
234
+ /** True for `*`, `./*`, `**`, or any target that means "everything in a directory". */
235
+ function isWholeDirectoryGlob(target) {
236
+ return /^(\.?[\\/])?(\*{1,2}|\.\*)$/.test(target.trim())
237
+ }
238
+
239
+ /** Match a path against one compiled path rule. */
240
+ function pathRuleMatches(rule, target, mode, context) {
241
+ if (!rule.modes.includes(mode)) return false
242
+ if (rule.kind === 'git-control') {
243
+ const segments = target.split(/[\\/]+/).map(segment => segment.toLowerCase())
244
+ const index = segments.lastIndexOf('.git')
245
+ return index >= 0 && GIT_CONTROL_SEGMENTS.has(segments[index + 1] ?? '')
246
+ }
247
+ return rule.roots.some(root => contained(root, target, context.platform))
248
+ }
249
+
250
+ /**
251
+ * Deny rules that apply to one path. The temp directory is checked after
252
+ * credentials and git control but before the system rule: on service accounts
253
+ * `%TEMP%` can live under `C:\Windows\TEMP`, and a worker must still be able to
254
+ * write its scratch files there.
255
+ */
256
+ function pathDenial(policy, resolved, mode, context) {
257
+ const real = realPathOf(resolved, context.platform)
258
+ for (const rule of policy.pathRules) {
259
+ if (rule.id === 'path/system-directory') continue
260
+ if (pathRuleMatches(rule, resolved, mode, context) || pathRuleMatches(rule, real, mode, context)) {
261
+ return { rule: rule.id, reason: `${rule.reason}: ${resolved}` }
262
+ }
263
+ }
264
+ if (mode === 'write' && context.tmpdir && contained(context.tmpdir, resolved, context.platform)) {
265
+ return null
266
+ }
267
+ for (const rule of policy.pathRules) {
268
+ if (rule.id !== 'path/system-directory') continue
269
+ if (pathRuleMatches(rule, resolved, mode, context) || pathRuleMatches(rule, real, mode, context)) {
270
+ return { rule: rule.id, reason: `${rule.reason}: ${resolved}` }
271
+ }
272
+ }
273
+ return null
274
+ }
275
+
276
+ /** Evaluate one path for one mode and return a denial or null. */
277
+ function checkPath(policy, resolved, mode, context) {
278
+ const real = realPathOf(resolved, context.platform)
279
+ const denial = pathDenial(policy, resolved, mode, context)
280
+ if (denial) return denial
281
+ if (mode !== 'write') return null
282
+ if (isFilesystemRoot(resolved, context.platform)) {
283
+ return { rule: 'path/system-directory', reason: `refuses to write to the filesystem root: ${resolved}` }
284
+ }
285
+ const roots = context.allowRoots
286
+ const lexicalInside = roots.some(root => contained(root, resolved, context.platform))
287
+ const realInside = roots.some(root => contained(realPathOf(root, context.platform), real, context.platform))
288
+ if (lexicalInside && realInside) return null
289
+ const shown = roots.slice(0, 3).join(', ') + (roots.length > 3 ? ', …' : '')
290
+ return {
291
+ rule: 'path/outside-allowlist',
292
+ reason: `${resolved} is outside every allowed write root (${shown || 'none'})`,
293
+ }
294
+ }
295
+
296
+ /** Whether a destructive delete target is safe: strictly inside one allow root. */
297
+ function destructiveTargetVerdict(policy, target, context) {
298
+ const resolved = resolveTarget(target, context)
299
+ if (!resolved) {
300
+ // A literal relative name (`build`, `node_modules`) is safe; a variable or
301
+ // an unresolved expression is refused because its scope cannot be proven.
302
+ return /[*?$%]/.test(target)
303
+ ? { rule: 'cmd/recursive-force-delete', reason: `the delete target "${target}" cannot be proven to stay inside the workspace` }
304
+ : null
305
+ }
306
+ if (isWholeDirectoryGlob(target)) {
307
+ return { rule: 'cmd/recursive-force-delete', reason: `the delete target "${target}" would wipe an entire allowed directory` }
308
+ }
309
+ const denied = pathDenial(policy, resolved, 'write', context)
310
+ if (denied) return denied
311
+ if (isFilesystemRoot(resolved, context.platform)) {
312
+ return { rule: 'cmd/recursive-force-delete', reason: `refuses to delete a filesystem root: ${resolved}` }
313
+ }
314
+ const home = context.platform === 'win32' ? context.homedir.toLowerCase() : context.homedir
315
+ const targetPath = context.platform === 'win32' ? resolved.toLowerCase() : resolved
316
+ if (home === targetPath) {
317
+ return { rule: 'cmd/recursive-force-delete', reason: `refuses to delete the home directory: ${resolved}` }
318
+ }
319
+ // Deny when the target contains an allowed root: deleting `.` or `..` takes
320
+ // the workspace with it, even though the target itself looks local.
321
+ if (context.allowRoots.some(root => contained(resolved, root, context.platform))) {
322
+ return { rule: 'cmd/recursive-force-delete', reason: `the delete target contains an allowed write root: ${resolved}` }
323
+ }
324
+ if (!context.allowRoots.some(root => contained(root, resolved, context.platform))) {
325
+ return { rule: 'cmd/recursive-force-delete', reason: `${resolved} is outside every allowed write root` }
326
+ }
327
+ return null
328
+ }
329
+
330
+ /** Split a command line into independently evaluated segments. */
331
+ function segmentsOf(command) {
332
+ return command
333
+ .split(/\r?\n|&&|\|\||;|\|/)
334
+ .map(segment => segment.trim())
335
+ .filter(Boolean)
336
+ }
337
+
338
+ /** Tokenize one segment, keeping quoted strings as one token. */
339
+ function tokensOf(segment) {
340
+ const tokens = []
341
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g
342
+ for (let match = pattern.exec(segment); match; match = pattern.exec(segment)) {
343
+ tokens.push(match[1] ?? match[2] ?? match[3])
344
+ }
345
+ return tokens
346
+ }
347
+
348
+ function isFlagToken(token, platform) {
349
+ if (!token) return true
350
+ if (token.startsWith('-')) return true
351
+ if (/^[0-9]?[>&]/.test(token)) return true
352
+ if (platform === 'win32' && /^\/[a-z?]{1,2}$/i.test(token)) return true
353
+ return false
354
+ }
355
+
356
+ /** Extract candidate write targets from one shell segment. */
357
+ function writeTargetsOf(segment, platform) {
358
+ const targets = []
359
+ const push = value => {
360
+ if (value && !isFlagToken(value, platform)) targets.push(value)
361
+ }
362
+ // `> path`, `>> path`, but not `2>&1`.
363
+ for (const match of segment.matchAll(/(?:^|[^0-9&])>>?\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/g)) {
364
+ push(match[1] ?? match[2] ?? match[3])
365
+ }
366
+ for (const match of segment.matchAll(/\btee\s+(?:-a\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/gi)) {
367
+ push(match[1] ?? match[2] ?? match[3])
368
+ }
369
+ for (const match of segment.matchAll(/\b(?:set-content|add-content|out-file|new-item)\b/gi)) {
370
+ const after = segment.slice(match.index ?? 0)
371
+ const named = /-(?:path|filepath|literalpath)\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i.exec(after)
372
+ if (named) {
373
+ push(named[1] ?? named[2] ?? named[3])
374
+ continue
375
+ }
376
+ const tokens = tokensOf(after).slice(1).filter(token => !isFlagToken(token, platform))
377
+ if (tokens.length > 0) push(tokens.at(-1))
378
+ }
379
+ for (const match of segment.matchAll(/\[io\.file\]::(?:writealltext|writeallbytes|appendalltext|appendallbytes)\(\s*("([^"]+)"|'([^']+)')/gi)) {
380
+ push(match[2] ?? match[3])
381
+ }
382
+ const tokens = tokensOf(segment)
383
+ const head = (tokens[0] ?? '').toLowerCase()
384
+ if (['cp', 'copy', 'install', 'robocopy', 'xcopy', 'rsync', 'ln'].includes(head)) {
385
+ const positional = tokens.slice(1).filter(token => !isFlagToken(token, platform))
386
+ if (positional.length >= 2) push(positional.at(-1))
387
+ }
388
+ if (['mv', 'move', 'move-item', 'rename-item', 'rename'].includes(head)) {
389
+ // Moving away from a path modifies it too, so both ends are checked.
390
+ for (const token of tokens.slice(1)) push(token)
391
+ }
392
+ if (['touch', 'mkdir', 'md', 'new-item'].includes(head)) {
393
+ for (const token of tokens.slice(1)) push(token)
394
+ }
395
+ if (['rm', 'del', 'erase', 'rd', 'rmdir', 'remove-item'].includes(head)) {
396
+ for (const token of tokens.slice(1)) push(token)
397
+ }
398
+ if (['chmod', 'chown', 'chattr', 'attrib', 'icacls'].includes(head)) {
399
+ for (const token of tokens.slice(1)) {
400
+ if (!/^[0-7]{3,4}$/.test(token) && !/^[+=-][rwxXst]+$/.test(token)) push(token)
401
+ }
402
+ }
403
+ return targets
404
+ }
405
+
406
+ /** Extract delete targets from a recursive/forced delete segment. */
407
+ function recursiveDeleteTargets(segment, platform) {
408
+ const tokens = tokensOf(segment)
409
+ const head = (tokens[0] ?? '').toLowerCase()
410
+ if (head === 'rm') {
411
+ const flags = tokens.slice(1).filter(token => token.startsWith('-')).join(' ')
412
+ const recursive = /(^|\s)-[a-z]*r/i.test(flags) || /--recursive\b/i.test(flags)
413
+ const force = /(^|\s)-[a-z]*f/i.test(flags) || /--force\b/i.test(flags)
414
+ if (recursive && force) {
415
+ return tokens.slice(1).filter(token => !isFlagToken(token, platform))
416
+ }
417
+ return null
418
+ }
419
+ if (head === 'remove-item') {
420
+ const recursive = tokens.some(token => /^-r(e(c(u(r(s(e)?)?)?)?)?)?$/i.test(token) || token === '-recurse')
421
+ const force = tokens.some(token => /^-fo?r?c?e?$/i.test(token) || token === '-force')
422
+ if (recursive && force) {
423
+ const named = /-(?:path|literalpath)\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i.exec(segment)
424
+ if (named) return [named[1] ?? named[2] ?? named[3]]
425
+ const values = tokens.slice(1).filter(token => !isFlagToken(token, platform) && !/^-(path|literalpath)$/i.test(token))
426
+ return values
427
+ }
428
+ return null
429
+ }
430
+ if (['del', 'erase', 'rd', 'rmdir'].includes(head)) {
431
+ const recursive = tokens.some(token => /^\/s$/i.test(token))
432
+ if (recursive) {
433
+ const values = tokens.slice(1).filter(token => !isFlagToken(token, platform))
434
+ // `del /s /q` without a target deletes the current directory contents.
435
+ return values.length > 0 ? values : ['.']
436
+ }
437
+ }
438
+ return null
439
+ }
440
+
441
+ /** Compile one user-supplied command pattern, ignoring an invalid regex. */
442
+ function compilePattern(entry, index, prefix, warn) {
443
+ const raw = typeof entry === 'string' ? { pattern: entry } : entry
444
+ if (!raw || typeof raw.pattern !== 'string' || raw.pattern.length === 0) return null
445
+ try {
446
+ return {
447
+ id: `${prefix}/${String(raw.id ?? index + 1).replace(/[^a-zA-Z0-9._-]/g, '-')}`,
448
+ pattern: new RegExp(raw.pattern, 'i'),
449
+ reason: typeof raw.reason === 'string' && raw.reason.trim() ? raw.reason.trim() : null,
450
+ }
451
+ } catch (error) {
452
+ warn(`guard: ignoring invalid ${prefix} pattern ${JSON.stringify(raw.pattern)}: ${error?.message ?? error}`)
453
+ return null
454
+ }
455
+ }
456
+
457
+ /** Resolve user config and the built-in defaults into one policy. */
458
+ function resolvePolicy({ config, cwd, homedir, platform, env, tmpdir, warn }) {
459
+ const P = platform === 'win32' ? path.win32 : path.posix
460
+ const raw = config && typeof config === 'object' ? config : {}
461
+ const credentials = CREDENTIAL_NAMES.map(name => P.join(homedir, ...name.split('/')))
462
+ const systemWrite = platform === 'win32' ? WINDOWS_SYSTEM_WRITE : POSIX_SYSTEM_WRITE
463
+ const extraDeny = (Array.isArray(raw.denyPaths) ? raw.denyPaths : [])
464
+ .map(entry => resolveTarget(entry, { cwd, platform, homedir, env }))
465
+ .filter(Boolean)
466
+ const extraRoots = (Array.isArray(raw.allowWriteRoots) ? raw.allowWriteRoots : [])
467
+ .map(entry => resolveTarget(entry, { cwd, platform, homedir, env }))
468
+ .filter(Boolean)
469
+ const baseRoots = [P.normalize(tmpdir), ...extraRoots]
470
+ .filter(Boolean)
471
+ .map(entry => P.normalize(entry))
472
+ return {
473
+ baseRoots: [...new Set(baseRoots)],
474
+ pathRules: [
475
+ { id: 'path/credentials', kind: 'roots', modes: ['read', 'write'], roots: credentials, reason: 'credential store' },
476
+ { id: 'path/git-control', kind: 'git-control', modes: ['read', 'write'], roots: [], reason: 'repository control data' },
477
+ {
478
+ id: 'path/system-directory',
479
+ kind: 'roots',
480
+ modes: ['write'],
481
+ roots: systemWrite,
482
+ reason: 'system directory',
483
+ },
484
+ { id: 'path/user-denied', kind: 'roots', modes: ['read', 'write'], roots: extraDeny, reason: 'path denied by guard.denyPaths' },
485
+ ],
486
+ hardCommands: HARD_COMMAND_RULES,
487
+ denyCommands: (Array.isArray(raw.denyCommands) ? raw.denyCommands : [])
488
+ .map((entry, index) => compilePattern(entry, index, 'cmd/custom', warn))
489
+ .filter(Boolean),
490
+ allowCommands: (Array.isArray(raw.allowCommands) ? raw.allowCommands : [])
491
+ .map((entry, index) => compilePattern(entry, index, 'allow', warn))
492
+ .filter(Boolean),
493
+ maxEvents: Math.min(200, Math.max(1, Number.isFinite(Number(raw.maxEvents)) ? Math.trunc(Number(raw.maxEvents)) : 50)),
494
+ }
495
+ }
496
+
497
+ /** Evaluate one shell command and return a denial or null. */
498
+ function checkCommand(policy, command, context) {
499
+ const original = String(command ?? '')
500
+ if (!original.trim()) return null
501
+ const platform = context.platform
502
+ const segments = segmentsOf(original)
503
+
504
+ // An allow entry is checked first, but the denial is still computed so the
505
+ // audit event can name the rule the user chose to override.
506
+ let denial = null
507
+ for (const rule of policy.hardCommands) {
508
+ if (rule.test(original)) {
509
+ denial = { rule: rule.id, reason: rule.reason }
510
+ break
511
+ }
512
+ }
513
+ for (const rule of policy.denyCommands) {
514
+ if (!denial && rule.pattern.test(original)) {
515
+ denial = { rule: rule.id, reason: rule.reason ?? 'denied by guard.denyCommands' }
516
+ }
517
+ }
518
+ for (const marker of CREDENTIAL_MARKERS) {
519
+ if (!denial && marker.test(original)) {
520
+ denial = { rule: 'cmd/credential-access', reason: 'reads a credential store that workers may not touch' }
521
+ }
522
+ }
523
+ for (const segment of segments) {
524
+ const targets = recursiveDeleteTargets(segment, platform)
525
+ if (targets === null) continue
526
+ if (targets.length === 0) {
527
+ denial = { rule: 'cmd/recursive-force-delete', reason: 'recursive forced delete without a provable target' }
528
+ break
529
+ }
530
+ for (const target of targets) {
531
+ const verdict = destructiveTargetVerdict(policy, target, context)
532
+ if (verdict) {
533
+ denial = verdict
534
+ break
535
+ }
536
+ }
537
+ if (denial) break
538
+ }
539
+ if (!denial) {
540
+ for (const segment of segments) {
541
+ for (const target of writeTargetsOf(segment, platform)) {
542
+ const cleaned = target.replace(/^["']|["']$/g, '')
543
+ const resolved = resolveTarget(target, context)
544
+ if (resolved) {
545
+ const verdict = checkPath(policy, resolved, 'write', context)
546
+ if (verdict) {
547
+ denial = verdict
548
+ break
549
+ }
550
+ continue
551
+ }
552
+ // Unresolved variables (`$env:SystemRoot`, `%WINDIR%`) cannot be
553
+ // resolved to a path, so fall back to the literal system markers.
554
+ if (SYSTEM_WRITE_MARKERS.some(marker => marker.test(cleaned))) {
555
+ denial = { rule: 'cmd/system-write', reason: `writes into a system directory: ${cleaned}` }
556
+ break
557
+ }
558
+ }
559
+ if (denial) break
560
+ }
561
+ }
562
+
563
+ for (const rule of policy.allowCommands) {
564
+ if (!rule.pattern.test(original)) continue
565
+ return { denial: null, allow: { rule: rule.id, reason: rule.reason, overridden: denial?.rule ?? null } }
566
+ }
567
+ return { denial, allow: null }
568
+ }
569
+
570
+ /** Return the file paths a tool call will write or read. */
571
+ function toolPaths(name, args) {
572
+ const list = []
573
+ const add = (value, mode) => {
574
+ if (typeof value === 'string' && value.trim()) list.push({ path: value, mode })
575
+ }
576
+ switch (name) {
577
+ case 'write':
578
+ case 'edit':
579
+ add(args.file_path, 'write')
580
+ break
581
+ case 'read':
582
+ case 'read_image':
583
+ add(args.file_path, 'read')
584
+ break
585
+ case 'str_replace_editor':
586
+ add(args.path, args.command === 'view' ? 'read' : 'write')
587
+ break
588
+ case 'create_worktree':
589
+ add(args.path, 'write')
590
+ break
591
+ case 'apply_patch': {
592
+ const input = typeof args.input === 'string' ? args.input : ''
593
+ for (const match of input.matchAll(/^\*\*\*\s+(?:Add|Update|Delete) File:\s*(.+)$/gm)) {
594
+ add(match[1].trim(), 'write')
595
+ }
596
+ for (const match of input.matchAll(/^\*\*\*\s+Move to:\s*(.+)$/gm)) {
597
+ add(match[1].trim(), 'write')
598
+ }
599
+ break
600
+ }
601
+ default:
602
+ break
603
+ }
604
+ return list
605
+ }
606
+
607
+ /** Check every path a file tool touches. */
608
+ function checkFileTool(policy, name, args, context) {
609
+ for (const entry of toolPaths(name, args)) {
610
+ const resolved = resolveTarget(entry.path, context)
611
+ if (!resolved) continue
612
+ const verdict = checkPath(policy, resolved, entry.mode, context)
613
+ if (verdict) return { ...verdict, detail: resolved }
614
+ }
615
+ return null
616
+ }
617
+
618
+ /**
619
+ * Build the guard.
620
+ *
621
+ * @param {object} [options]
622
+ * @param {object} [options.config] - the `guard` block from `cordis.patch.yml`.
623
+ * @param {string} [options.cwd] - fallback workspace when a child session has none.
624
+ * @param {string} [options.homedir]
625
+ * @param {string} [options.platform] - `process.platform` by default.
626
+ * @param {object} [options.env] - environment used to expand `%VAR%`.
627
+ * @param {(message: string) => void} [options.warn]
628
+ * @param {() => number} [options.now]
629
+ */
630
+ export function createGuard(options = {}) {
631
+ const {
632
+ config = {},
633
+ cwd = process.cwd(),
634
+ homedir = os.homedir(),
635
+ tmpdir = os.tmpdir(),
636
+ platform = process.platform,
637
+ env = process.env,
638
+ warn = () => {},
639
+ now = () => Date.now(),
640
+ } = options
641
+ const enabled = !(config?.enabled === false || /^(false|0|off|no)$/i.test(String(config?.enabled ?? '')))
642
+ const policy = resolvePolicy({ config, cwd, homedir, platform, env, tmpdir, warn })
643
+ const P = platform === 'win32' ? path.win32 : path.posix
644
+
645
+ /** childId → { runId, label } */
646
+ const children = new Map()
647
+ /** runId → counters and the bounded event list. */
648
+ const runs = new Map()
649
+ const runOrder = []
650
+
651
+ function bucketFor(runId) {
652
+ let bucket = runs.get(runId)
653
+ if (!bucket) {
654
+ bucket = { blocked: 0, allowed: 0, byRule: {}, events: [], omitted: 0 }
655
+ runs.set(runId, bucket)
656
+ runOrder.push(runId)
657
+ if (runOrder.length > 500) {
658
+ const oldest = runOrder.shift()
659
+ if (oldest !== undefined) runs.delete(oldest)
660
+ }
661
+ }
662
+ return bucket
663
+ }
664
+
665
+ function record(runId, event) {
666
+ if (!runId) return
667
+ const bucket = bucketFor(runId)
668
+ if (event.decision === 'blocked') bucket.blocked += 1
669
+ else bucket.allowed += 1
670
+ bucket.byRule[event.rule] = (bucket.byRule[event.rule] ?? 0) + 1
671
+ if (bucket.events.length < policy.maxEvents) bucket.events.push(event)
672
+ else bucket.omitted += 1
673
+ }
674
+
675
+ function contextFor(exec) {
676
+ const sessionCwd = exec?.agent?.session?.header?.cwd
677
+ const workspace = typeof sessionCwd === 'string' && sessionCwd.trim() ? sessionCwd : cwd
678
+ return {
679
+ cwd: workspace,
680
+ homedir,
681
+ platform,
682
+ env,
683
+ tmpdir: P.normalize(tmpdir),
684
+ // The child's own workspace plus the shared temp/configured roots. The
685
+ // host's process cwd is not implicitly opened when the child reports one.
686
+ allowRoots: [...new Set([P.normalize(workspace), ...policy.baseRoots])],
687
+ }
688
+ }
689
+
690
+ function evaluate(exec) {
691
+ const name = typeof exec?.name === 'string' ? exec.name : ''
692
+ let args = exec?.arguments
693
+ if (typeof args === 'string') {
694
+ try {
695
+ args = JSON.parse(args)
696
+ } catch {
697
+ args = {}
698
+ }
699
+ }
700
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
701
+ return { blocked: false, rule: null, reason: null, detail: null }
702
+ }
703
+ const context = contextFor(exec)
704
+
705
+ let denial = null
706
+ if (name === 'bash' || name === 'pwsh' || name === 'terminal_send') {
707
+ const command = typeof args.command === 'string'
708
+ ? args.command
709
+ : (typeof args.text === 'string' ? args.text : '')
710
+ const workdir = typeof args.workdir === 'string' && args.workdir.trim() ? args.workdir : null
711
+ const commandContext = workdir
712
+ ? { ...context, cwd: resolveTarget(workdir, context) ?? context.cwd }
713
+ : context
714
+ const verdict = checkCommand(policy, command, commandContext)
715
+ if (verdict.allow) {
716
+ return {
717
+ blocked: false,
718
+ rule: verdict.allow.rule,
719
+ reason: verdict.allow.reason,
720
+ detail: truncate(command),
721
+ explicitAllow: true,
722
+ overridden: verdict.allow.overridden,
723
+ }
724
+ }
725
+ denial = verdict.denial
726
+ if (!denial) {
727
+ // Even a read-only command may not run inside a credential directory.
728
+ const resolvedWorkdir = workdir ? resolveTarget(workdir, context) : null
729
+ if (resolvedWorkdir) {
730
+ const workdirVerdict = checkPath(policy, resolvedWorkdir, 'read', context)
731
+ if (workdirVerdict) denial = workdirVerdict
732
+ }
733
+ }
734
+ if (denial) return { blocked: true, rule: denial.rule, reason: denial.reason, detail: truncate(command) }
735
+ return { blocked: false, rule: null, reason: null, detail: truncate(command) }
736
+ }
737
+
738
+ const fileVerdict = checkFileTool(policy, name, args, context)
739
+ if (fileVerdict) {
740
+ return { blocked: true, rule: fileVerdict.rule, reason: fileVerdict.reason, detail: truncate(fileVerdict.detail ?? '') }
741
+ }
742
+ return { blocked: false, rule: null, reason: null, detail: null }
743
+ }
744
+
745
+ return {
746
+ enabled,
747
+
748
+ /** Associate a spawned child with its run, so blocked calls can be attributed. */
749
+ bindChild(childId, binding = {}) {
750
+ if (!childId) return
751
+ children.set(childId, { runId: binding.runId ?? null, label: binding.label ?? null })
752
+ },
753
+
754
+ /** Forget a child once its activation is disposed. */
755
+ unbindChild(childId) {
756
+ children.delete(childId)
757
+ },
758
+
759
+ /**
760
+ * Evaluate one host tool call. Returns `{ blocked: false }` for any agent
761
+ * this guard does not own.
762
+ *
763
+ * @param {{ name?: string, arguments?: unknown, agent?: { id?: string, session?: object } }} exec
764
+ */
765
+ checkToolCall(exec) {
766
+ const childId = exec?.agent?.id
767
+ const binding = childId ? children.get(childId) : undefined
768
+ if (!enabled || !binding) return { blocked: false, rule: null, reason: null }
769
+ let verdict
770
+ try {
771
+ verdict = evaluate(exec)
772
+ } catch (error) {
773
+ // A guard bug must not become a silent pass-through.
774
+ verdict = {
775
+ blocked: true,
776
+ rule: 'guard/internal-error',
777
+ reason: `the guard could not evaluate this call (${error?.message ?? error})`,
778
+ detail: truncate(exec?.name ?? ''),
779
+ }
780
+ }
781
+ if (!verdict.blocked && !verdict.explicitAllow) return verdict
782
+ record(binding.runId, {
783
+ at: new Date(now()).toISOString(),
784
+ decision: verdict.blocked ? 'blocked' : 'allowed',
785
+ rule: verdict.rule,
786
+ tool: exec?.name ?? 'unknown',
787
+ label: binding.label,
788
+ detail: verdict.detail,
789
+ reason: verdict.reason,
790
+ overridden: verdict.overridden ?? null,
791
+ })
792
+ return {
793
+ ...verdict,
794
+ label: binding.label,
795
+ reasonText: verdict.blocked
796
+ ? `[guard] blocked ${exec?.name ?? 'tool'}: rule ${verdict.rule} — ${verdict.reason}. The call did not run. `
797
+ + 'Use a path inside the workspace, or ask the user to add a guard.allowWriteRoots or guard.allowCommands entry.'
798
+ : null,
799
+ }
800
+ },
801
+
802
+ /** Counters and events for one run, or null when nothing happened. */
803
+ snapshot(runId) {
804
+ const bucket = runs.get(runId)
805
+ if (!bucket) return null
806
+ return {
807
+ blocked: bucket.blocked,
808
+ allowed: bucket.allowed,
809
+ byRule: { ...bucket.byRule },
810
+ events: bucket.events.map(event => ({ ...event })),
811
+ omitted: bucket.omitted,
812
+ }
813
+ },
814
+
815
+ /** Markdown section appended to a finished run's report. */
816
+ reportSection(runId) {
817
+ const bucket = runs.get(runId)
818
+ if (!bucket || bucket.blocked + bucket.allowed === 0) return null
819
+ const lines = ['## Safety guard', '']
820
+ const parts = []
821
+ if (bucket.blocked > 0) parts.push(`${bucket.blocked} tool call(s) blocked`)
822
+ if (bucket.allowed > 0) parts.push(`${bucket.allowed} explicit allow(s) recorded`)
823
+ lines.push(`${parts.join('; ')}.`)
824
+ if (Object.keys(bucket.byRule).length > 0) {
825
+ lines.push('', `Rules: ${Object.entries(bucket.byRule).map(([rule, count]) => `${rule} ×${count}`).join(', ')}.`)
826
+ }
827
+ for (const event of bucket.events) {
828
+ const who = event.label ? ` ${event.label}` : ''
829
+ const detail = event.detail ? ` \`${event.detail.replaceAll('`', "'")}\`` : ''
830
+ lines.push('', `- ${event.decision}${who} · ${event.tool}${detail} — ${event.rule}: ${event.reason ?? ''}`.trim())
831
+ }
832
+ if (bucket.omitted > 0) lines.push('', `${bucket.omitted} further event(s) were counted but not listed (guard.maxEvents).`)
833
+ return lines.join('\n')
834
+ },
835
+ }
836
+ }
837
+
838
+ function truncate(value) {
839
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
840
+ return text.length > MAX_DETAIL ? `${text.slice(0, MAX_DETAIL - 1)}…` : text
841
+ }