SLOPSHOPPER

guard

Blocks destructive shell commands and access to secret files before they run, in Bash and PowerShell, anywhere in a compound command

guardcommandtoaststatus
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · guard
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(rm -rf build && git push --force origin main) ⎿ Denied by guard: guard blocked this (git-force-push): it force-pushes and can overwrite commits on the rem ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /guard ⎿ guard: Active. ⎿ guard: destructive commands: rm -rf (dangerous targets), git push --force, git reset --hard, git clean -f, chmod -R ⎿ guard: secret files: .env, .env.*, *.pem, *.key, *.p12, *.pfx, id_rsa, id_dsa, id_ecdsa, id_ed25519, .npmrc, .pypir ⎿ guard: Blocked this session (2): ⎿ guard: Bash · git-force-push · git push --force origin main ⎿ guard: Bash · secret-file · cat .env ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ guard: guard: 2 blocked
README

guard

Blocks destructive shell commands and access to secret files before they run.

Settings permissions.deny rules match command prefixes, so cd app && rm -rf ~, rm -fr /, rm -r -f / or git push origin main -f get past them. guard sees every tool call inside Claude Code, splits compound commands, normalizes flags and wrappers (sudo, env, VAR=1), and resolves symlinks before it lets a file through.

/plugin install guard@claude-mods

What it blocks

Destructive commands (Bash), anywhere in a compound command:

RuleBlocksLets through
rm-rfrm recursive + force on /, ~, $HOME, ., .., *, /usr, /home/me, C:/, a bare $VAR/rm -rf node_modules, rm -rf ./dist, rm -rf "${OUT:?}/"
git-force-push--force, -f, -fu, +refspec--force-with-lease
git-reset-hardgit reset --hard--soft, --mixed
git-cleangit clean -f…git clean -n
chmod-777chmod -R 777chmod 755 file
disk-writemkfs*, dd of=/dev/…dd of=./disk.img
pipe-to-shell`curl … \sh, wget … \sudo bash`curl -o install.sh …
fork-bomb`:(){ :\:& };:`

Secret files: .env, .env.*, *.pem, *.key, *.p12, *.pfx, id_rsa, id_ed25519 and friends, .npmrc, .pypirc, .netrc, .git-credentials, .aws/credentials, .docker/config.json, except .env.example, .env.sample, .env.template, .env.dist and *.pub.

They are blocked for Read, Edit, Write, NotebookEdit and Grep, on the path as given and on where it resolves (a symlink to .env is .env), and in shell commands that read, send or write them: cat .env, grep KEY .env, curl -d @.env, echo X >> .env, cp .env /tmp, git add .env. Commands that only name them pass: cp .env.example .env, echo .env >> .gitignore, source .env.

PowerShell (the PowerShell tool of Claude Code on Windows) gets the same rules and options, read in PowerShell's own syntax: cmdlets and their aliases, case-insensitive parameters that may be abbreviated (-rec, -fo), and -Name:value.

RuleBlocksLets through
rm-rfRemove-Item -Recurse (and rm, del, rd, ri, cmd /c rd /s) on C:\, C:\Users\me, $env:USERPROFILE, $HOME, ., .., a bare $dir\. PowerShell's -Recurse deletes without asking even without -Force, so -Force is not required for the blockRemove-Item -Recurse -Force .\node_modules, rm -r dist
pipe-to-shell`iwr … \iex, irm … \Invoke-Expression, iex (New-Object Net.WebClient).DownloadString(…)`iwr … -OutFile install.ps1
disk-writeFormat-Volume, Clear-Disk, Initialize-Disk, Remove-Partition, diskpart, format D:Get-Volume
chmod-777icacls … /grant Everyone:F /Ticacls … /grant me:R
git rulesas for Bash

Secret files are blocked in Get-Content/gc/type, Select-String, Copy-Item/Move-Item sources, Set-Content/Add-Content/Out-File paths, redirections (> .env) and Invoke-WebRequest -InFile; Copy-Item .env.example .env and Add-Content .gitignore ".env" pass.

The model gets the rule and what to do instead, e.g.:

guard blocked this (git-force-push): it force-pushes and can overwrite commits on the remote. Use --force-with-lease, or ask the user.

/guard

  • /guard lists the active rules and what was blocked this session
  • /guard off pauses it for the session, /guard on resumes it. Only accepted from the person (the prompt, Remote Control, the SDK host), never from another agent, a peer session or a channel message

The status line shows guard: N blocked (or guard: paused).

Options

Set them in /config or under pluginConfigs.guard.options in settings:

OptionDefault
destructivetrueBlock destructive commands
rmModedangerousany blocks every rm -rf
secretstrueProtect secret files
blockCommands[]Extra regular expressions tested against every Bash command, e.g. \bnpm publish\b
protectPaths[]Extra gitignore-like globs no tool may read or write, e.g. migrations/**
allowPaths[]Globs exempt from the file rules, e.g. test/fixtures/**

Limits

guard is a safety net against accidents, not a sandbox. The command check is a heuristic, not a shell parser: eval, scripts the model writes and then runs, interpreters (python -c, node -e), PowerShell script blocks and Start-Process are not inspected. Use Claude Code's sandbox and permission modes for containment.

Source 4 files
hooks/register.ts 141 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { GuardBlock } from '../types'
5import { buildPolicy, checkCommand, checkPath, denyMessage, describePolicy } from './rules'
6import type { Policy, Verdict } from './rules'
7import { checkPowerShell } from './powershell'
8
9const isPaused = atom({ plugin: 'guard', key: 'isPaused' } as const, false)
10const blocks = atom({ plugin: 'guard', key: 'blocks' } as const, [])
11
12/** Who may pause the guard: the person, never another agent, a channel or a peer session. */
13const PERSON = new Set(['composer', 'bridge', 'sdk'])
14
15const MAX_BLOCKS = 50
16
17async function showStatus($: EngineInterface) {
18  const count = (await read($, blocks)).length
19  const paused = await read($, isPaused)
20  $.ui.status(paused ? 'guard: paused' : count > 0 ? `guard: ${count} blocked` : undefined)
21}
22
23async function deny($: EngineInterface, tool: string, verdict: Verdict) {
24  const block: GuardBlock = { tool, rule: verdict.rule, subject: verdict.subject, at: await $.clock.now() }
25  await update($, blocks, list => [...list, block].slice(-MAX_BLOCKS))
26  await showStatus($)
27
28  return { deny: denyMessage(verdict) }
29}
30
31// The path as given, then where it really leads: a symlink to a secret file is
32// a secret file. A path that does not exist yet has no realPath.
33async function checkFile($: EngineInterface, path: string | undefined, policy: Policy) {
34  if (path === undefined || path === '') return undefined
35  const spelled = checkPath(path, policy)
36  if (spelled) return spelled
37
38  const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
39  const real = stat?.realPath
40  const resolved = real !== undefined && real !== path ? checkPath(real, policy) : undefined
41
42  return resolved ? { ...resolved, subject: `${path} → ${real}` } : undefined
43}
44
45export const register: Register = (on, options) => {
46  const { policy, problems } = buildPolicy(options)
47
48  on('session.start', async ($, e, next) => {
49    await $.command.register({
50      name: 'guard',
51      description: 'Show the guard rules and what it blocked; /guard off or /guard on pauses it for this session',
52      argumentHint: '[on|off]',
53    })
54    if (problems.length > 0) $.ui.toast(`guard: ${problems.join('; ')}`)
55
56    return next(e)
57  })
58
59  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
60    if (await read($, isPaused)) return next(e)
61    const verdict = checkCommand(e.command, policy)
62
63    return verdict ? deny($, e.tool, verdict) : next(e)
64  })
65
66  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
67    if (await read($, isPaused)) return next(e)
68    const verdict = await checkFile($, e.file_path, policy)
69
70    return verdict ? deny($, e.tool, verdict) : next(e)
71  })
72
73  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
74    if (await read($, isPaused)) return next(e)
75    const verdict = await checkFile($, e.file_path, policy)
76
77    return verdict ? deny($, e.tool, verdict) : next(e)
78  })
79
80  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
81    if (await read($, isPaused)) return next(e)
82    const verdict = await checkFile($, e.file_path, policy)
83
84    return verdict ? deny($, e.tool, verdict) : next(e)
85  })
86
87  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
88    if (await read($, isPaused)) return next(e)
89    const verdict = await checkFile($, e.notebook_path, policy)
90
91    return verdict ? deny($, e.tool, verdict) : next(e)
92  })
93
94  // Tools only some builds have, so matched by name rather than by this
95  // build's tool types: Grep (others search through Bash), and PowerShell
96  // (Windows builds), checked in its own syntax with the same rules as Bash.
97  on('tool.call', async ($, e, next) => {
98    const tool = String(e.tool)
99    if ((tool !== 'Grep' && tool !== 'PowerShell') || (await read($, isPaused))) return next(e)
100    const { path, command } = e as { path?: unknown; command?: unknown }
101    const verdict =
102      tool === 'Grep'
103        ? typeof path === 'string'
104          ? await checkFile($, path, policy)
105          : undefined
106        : typeof command === 'string'
107          ? checkPowerShell(command, policy)
108          : undefined
109
110    return verdict ? deny($, tool, verdict) : next(e)
111  })
112
113  on('command.run', { command: 'guard' }, async ($, e) => {
114    const arg = e.args.trim().toLowerCase()
115
116    if (arg === 'off' || arg === 'on') {
117      if (!PERSON.has(e.origin.kind)) {
118        return { text: `/guard ${arg} is only accepted from the person at the prompt (got ${e.origin.kind}).` }
119      }
120      await update($, isPaused, () => arg === 'off')
121      await showStatus($)
122
123      return {
124        text: arg === 'off' ? 'Paused for this session. /guard on resumes it.' : 'Active.',
125      }
126    }
127    if (arg !== '' && arg !== 'status') return { text: 'Usage: /guard [on|off]' }
128
129    const list = await read($, blocks)
130    const paused = await read($, isPaused)
131    const lines = [
132      paused ? 'Paused for this session (/guard on resumes it).' : 'Active.',
133      ...describePolicy(policy).map(line => `  ${line}`),
134      list.length === 0 ? 'Nothing blocked this session.' : `Blocked this session (${list.length}):`,
135      ...list.slice(-10).map(block => `  ${block.tool} · ${block.rule} · ${block.subject.slice(0, 80)}`),
136    ]
137
138    return { text: lines.join('\n') }
139  })
140}
141
hooks/rules.ts 389 lines
1// The guard's rules as pure functions: no `$`, so tests call them directly.
2
3export type Verdict = {
4  /** The rule that fired, as /guard lists it. */
5  rule: string
6  /** What was matched: a command segment or a path. */
7  subject: string
8  /** Why it is blocked, for the model and the person. */
9  reason: string
10  /** What to do instead. */
11  hint: string
12}
13
14export type RmMode = 'dangerous' | 'any'
15
16export type Policy = {
17  destructive: boolean
18  rmMode: RmMode
19  commands: { source: string; pattern: RegExp }[]
20  secrets: boolean
21  protect: { source: string; pattern: RegExp }[]
22  allow: RegExp[]
23}
24
25export const SECRET_GLOBS = [
26  '.env',
27  '.env.*',
28  '*.pem',
29  '*.key',
30  '*.p12',
31  '*.pfx',
32  'id_rsa',
33  'id_dsa',
34  'id_ecdsa',
35  'id_ed25519',
36  '.npmrc',
37  '.pypirc',
38  '.netrc',
39  '.git-credentials',
40  '.aws/credentials',
41  '.docker/config.json',
42]
43
44export const SECRET_EXCEPTIONS = ['.env.example', '.env.sample', '.env.template', '.env.dist', '*.pub']
45
46const SECRETS = SECRET_GLOBS.map(glob => globToRegExp(glob))
47const EXCEPTIONS = SECRET_EXCEPTIONS.map(glob => globToRegExp(glob))
48
49/**
50 * A gitignore-like glob: `*` and `?` stay within one path segment, `**`
51 * crosses them, and a pattern matches the end of the path at a segment
52 * boundary, so `.env` matches `/repo/.env` and `.aws/credentials` matches
53 * `~/.aws/credentials`. Case-insensitive, since some file systems are.
54 */
55export function globToRegExp(glob: string): RegExp {
56  const g = glob.replace(/\\/g, '/').replace(/^\.\//, '')
57  let source = ''
58
59  for (let i = 0; i < g.length; i++) {
60    const char = g[i]!
61    if (char === '*' && g[i + 1] === '*') {
62      i++
63      if (g[i + 1] === '/') {
64        i++
65        source += '(?:.*/)?'
66      } else {
67        source += '.*'
68      }
69    } else if (char === '*') {
70      source += '[^/]*'
71    } else if (char === '?') {
72      source += '[^/]'
73    } else {
74      source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
75    }
76  }
77
78  return new RegExp(`(?:^|/)${source}$`, 'i')
79}
80
81const normalize = (path: string) => path.replace(/\\/g, '/')
82
83const asList = (value: unknown): string[] =>
84  Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item.trim() !== '') : []
85
86/** Builds the policy from the mod's options; bad patterns are reported, not thrown. */
87export function buildPolicy(options: Readonly<Record<string, unknown>>): { policy: Policy; problems: string[] } {
88  const problems: string[] = []
89  const commands: Policy['commands'] = []
90
91  for (const source of asList(options.blockCommands)) {
92    try {
93      commands.push({ source, pattern: new RegExp(source) })
94    } catch {
95      problems.push(`invalid blockCommands pattern /${source}/`)
96    }
97  }
98
99  return {
100    policy: {
101      destructive: options.destructive !== false,
102      rmMode: options.rmMode === 'any' ? 'any' : 'dangerous',
103      commands,
104      secrets: options.secrets !== false,
105      protect: asList(options.protectPaths).map(source => ({ source, pattern: globToRegExp(source) })),
106      allow: asList(options.allowPaths).map(source => globToRegExp(source)),
107    },
108    problems,
109  }
110}
111
112/** Checks one path (as given, or resolved) against the secret files and the protected paths. */
113export function checkPath(path: string, policy: Policy): Verdict | undefined {
114  const p = normalize(path)
115  if (policy.allow.some(pattern => pattern.test(p))) return undefined
116
117  if (policy.secrets && SECRETS.some(pattern => pattern.test(p)) && !EXCEPTIONS.some(pattern => pattern.test(p))) {
118    return {
119      rule: 'secret-file',
120      subject: path,
121      reason: 'it is a secret file (credentials, keys, environment)',
122      hint: 'Work from an example file such as .env.example, or ask the user for the value you need.',
123    }
124  }
125
126  const protectedBy = policy.protect.find(({ pattern }) => pattern.test(p))
127  if (protectedBy) {
128    return {
129      rule: 'protected-path',
130      subject: path,
131      reason: `it matches the protected path ${protectedBy.source}`,
132      hint: 'Leave this file alone, or ask the user to change it.',
133    }
134  }
135
136  return undefined
137}
138
139// ---------------------------------------------------------------------------
140// Shell commands
141
142const PREFIXES = new Set(['sudo', 'doas', 'command', 'builtin', 'exec', 'nohup', 'time', 'nice', 'ionice', 'xargs'])
143const OPTION_WITH_VALUE = new Set(['-u', '-g', '-n', '-c', '-C', '-p', '-I', '-L', '-P'])
144
145/** Programs that read, copy, send or edit the files they are given. */
146const FILE_TOUCHERS = new Set([
147  'cat', 'tac', 'less', 'more', 'head', 'tail', 'bat', 'nl', 'xxd', 'od', 'hexdump', 'strings', 'base64',
148  'grep', 'egrep', 'fgrep', 'rg', 'ag', 'awk', 'sed', 'cut', 'sort', 'uniq', 'diff', 'jq', 'yq',
149  'cp', 'mv', 'ln', 'scp', 'rsync', 'tee', 'curl', 'wget', 'nc', 'zip', 'tar', 'gzip',
150  'nano', 'vi', 'vim', 'nvim', 'emacs', 'code', 'open', 'type', 'truncate', 'shred',
151])
152
153/** Programs whose last argument is a destination: writing a secret file from a template is fine. */
154const COPIERS = new Set(['cp', 'mv', 'ln', 'scp', 'rsync'])
155
156const unquote = (token: string) => token.replace(/^(['"])(.*)\1$/, '$2')
157
158/**
159 * Splits a command line into simple commands (on `;`, `&&`, `||`, `|`, `&`,
160 * newlines, `$(`, backticks and parentheses) and each into words. Quoting is
161 * honoured for grouping only: this is a heuristic, not a shell parser.
162 */
163export function splitCommand(command: string): string[][] {
164  return command
165    .split(/\|\||&&|[;&|\n()`]|\$\(/)
166    .map(part => (part.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map(unquote))
167    .filter(words => words.length > 0)
168}
169
170/** Drops wrappers (`sudo -u x`, `env A=1`, `VAR=1`, `nohup`) to reach the program and its arguments. */
171export function stripPrefixes(words: string[]): string[] {
172  const rest = [...words]
173
174  for (;;) {
175    const first = rest[0]
176    if (first === undefined) return rest
177    const name = basename(first)
178
179    if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first)) {
180      rest.shift()
181    } else if (name === 'env') {
182      rest.shift()
183      while (rest[0] !== undefined && (rest[0].startsWith('-') || rest[0].includes('='))) rest.shift()
184    } else if (PREFIXES.has(name)) {
185      rest.shift()
186      while (rest[0]?.startsWith('-')) {
187        const option = rest.shift()!
188        if (OPTION_WITH_VALUE.has(option)) rest.shift()
189      }
190    } else {
191      return rest
192    }
193  }
194}
195
196const basename = (word: string) => normalize(word).split('/').pop() ?? word
197
198const shortFlags = (args: string[]) => args.filter(arg => /^-[^-]/.test(arg)).join('')
199
200const hasFlag = (args: string[], short: string, long: string) =>
201  args.includes(long) || shortFlags(args).includes(short)
202
203/** A target an `rm -rf` must not reach: a root, a home, the whole project, an unset variable. */
204export function isDangerousTarget(target: string): boolean {
205  const t = normalize(target)
206  const p = t.length > 1 ? t.replace(/\/+$/, '') : t
207
208  return (
209    /^(\/|\/\*|~|~\/\*|\$\{?HOME\}?(\/\*)?)$/.test(p) ||
210    /^(\.|\.\/\*|\*|\.\*|\.\.|\.\.\/\*)$/.test(p) ||
211    /^\/[^/]+(\/[^/]+)?(\/\*)?$/.test(p) ||
212    /^(~|\$\{?HOME\}?)\/[^/]+$/.test(p) ||
213    /^[A-Za-z]:(\/[^/]*)?$/.test(p) ||
214    // `$DIR/` or `"$DIR"/*` with DIR unset is `/`; `${DIR:?}` refuses to expand empty
215    (/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?(\/\*?)?$/.test(p) && !p.includes(':?'))
216  )
217}
218
219const deny = (rule: string, words: string[], reason: string, hint: string): Verdict => ({
220  rule,
221  subject: words.join(' '),
222  reason,
223  hint,
224})
225
226export function checkDestructive(words: string[], rmMode: RmMode): Verdict | undefined {
227  const [program = '', ...args] = words
228  const name = basename(program)
229
230  if (name === 'rm') {
231    const end = args.indexOf('--')
232    const flags = (end < 0 ? args : args.slice(0, end)).filter(arg => arg.startsWith('-'))
233    const targets = args.filter((arg, i) => !(arg.startsWith('-') && (end < 0 || i < end)) && arg !== '--')
234    const isRecursive = flags.includes('--recursive') || /[rR]/.test(shortFlags(flags))
235    const isForced = flags.includes('--force') || shortFlags(flags).includes('f')
236
237    if (isRecursive && isForced) {
238      if (rmMode === 'any') {
239        return deny('rm-rf', words, 'it force-deletes recursively', 'Delete specific files, or ask the user to run it.')
240      }
241      const target = targets.find(isDangerousTarget)
242      if (target !== undefined) {
243        return deny(
244          'rm-rf',
245          words,
246          `it force-deletes ${target} recursively`,
247          'Name a specific path inside the project, guard variables with ${VAR:?}, or ask the user to run it.',
248        )
249      }
250    }
251  }
252
253  if (name === 'git') {
254    let i = 0
255    while (i < args.length && args[i]!.startsWith('-')) i += args[i] === '-C' || args[i] === '-c' ? 2 : 1
256    const sub = args[i]
257    const rest = args.slice(i + 1)
258
259    if (sub === 'push') {
260      const isForced =
261        rest.includes('--force') || shortFlags(rest).includes('f') || rest.some(arg => /^\+[^+]/.test(arg))
262      if (isForced) {
263        return deny(
264          'git-force-push',
265          words,
266          'it force-pushes and can overwrite commits on the remote',
267          'Use --force-with-lease, or ask the user.',
268        )
269      }
270    }
271    if (sub === 'reset' && rest.includes('--hard')) {
272      return deny(
273        'git-reset-hard',
274        words,
275        'it discards uncommitted changes for good',
276        'Use git stash, or ask the user.',
277      )
278    }
279    if (sub === 'clean' && hasFlag(rest, 'f', '--force') && !hasFlag(rest, 'n', '--dry-run')) {
280      return deny(
281        'git-clean',
282        words,
283        'it deletes untracked files for good',
284        'Preview with git clean -n and ask the user.',
285      )
286    }
287  }
288
289  if (name === 'chmod' && hasFlag(args, 'R', '--recursive') && args.some(arg => /^(0?777|a\+rwx|ugo\+rwx)$/.test(arg))) {
290    return deny('chmod-777', words, 'it makes a whole tree world-writable', 'Grant the narrowest permission needed.')
291  }
292
293  if (name.startsWith('mkfs') || (name === 'dd' && args.some(arg => /^of=\/dev\//.test(arg)))) {
294    return deny('disk-write', words, 'it writes a file system or raw data to a device', 'Ask the user to run it.')
295  }
296
297  return undefined
298}
299
300function checkWhole(command: string): Verdict | undefined {
301  const piped = command.match(/\b(curl|wget)\b[^\n;&|]*\|\s*(sudo\s+)?(env\s+(\S+=\S*\s+)*)?(ba|z|da|k|fi)?sh\b/)
302  if (piped) {
303    return {
304      rule: 'pipe-to-shell',
305      subject: piped[0],
306      reason: 'it runs a downloaded script without review',
307      hint: 'Download the script to a file, show it to the user, and run it only after they agree.',
308    }
309  }
310  if (/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/.test(command)) {
311    return { rule: 'fork-bomb', subject: ':(){ :|:& };:', reason: 'it is a fork bomb', hint: 'Do not run it.' }
312  }
313
314  return undefined
315}
316
317function checkSecretMentions(words: string[], policy: Policy): Verdict | undefined {
318  const [program = '', ...args] = words
319  const name = basename(program)
320  const isGitAdd = name === 'git' && args.includes('add')
321  const destination = COPIERS.has(name) ? args.findLastIndex(arg => !arg.startsWith('-')) : -1
322
323  for (let i = 0; i < args.length; i++) {
324    if (i === destination) continue
325    const arg = args[i]!
326    const isRedirect = /^\d*(>>?|<)&?$/.test(arg)
327    const target = isRedirect ? args[i + 1] : arg.replace(/^\d*(>>?|<)&?/, '')
328
329    if (!isRedirect && !/^\d*(>>?|<)/.test(arg) && !FILE_TOUCHERS.has(name) && !isGitAdd) continue
330    if (target === undefined || target === '' || target.startsWith('-')) continue
331
332    const verdict = checkPath(target.replace(/^@/, '').replace(/^[A-Za-z_]+=/, ''), policy)
333    if (verdict) return { ...verdict, subject: words.join(' ') }
334  }
335
336  return undefined
337}
338
339/** Checks a whole Bash command line; the first rule that fires wins. */
340export function checkCommand(command: string, policy: Policy): Verdict | undefined {
341  for (const { source, pattern } of policy.commands) {
342    if (pattern.test(command)) {
343      return {
344        rule: 'blocked-command',
345        subject: command,
346        reason: `it matches the blocked pattern /${source}/`,
347        hint: 'Find another way, or ask the user to run it.',
348      }
349    }
350  }
351
352  if (policy.destructive) {
353    const whole = checkWhole(command)
354    if (whole) return whole
355  }
356
357  for (const words of splitCommand(command).map(stripPrefixes)) {
358    if (words.length === 0) continue
359    const verdict =
360      (policy.destructive ? checkDestructive(words, policy.rmMode) : undefined) ??
361      (policy.secrets || policy.protect.length > 0 ? checkSecretMentions(words, policy) : undefined)
362    if (verdict) return verdict
363  }
364
365  return undefined
366}
367
368/** The text the model receives in place of the tool's result. */
369export function denyMessage(verdict: Verdict): string {
370  return `guard blocked this (${verdict.rule}): ${verdict.reason}. ${verdict.hint}`
371}
372
373/** The active rules, one per line, for /guard. */
374export function describePolicy(policy: Policy): string[] {
375  const lines: string[] = []
376  if (policy.destructive) {
377    lines.push(
378      `destructive commands: rm -rf (${policy.rmMode === 'any' ? 'any target' : 'dangerous targets'}), git push --force, git reset --hard, git clean -f, chmod -R 777, mkfs/dd to devices, curl|sh`,
379    )
380  }
381  if (policy.secrets) lines.push(`secret files: ${SECRET_GLOBS.join(', ')} (except ${SECRET_EXCEPTIONS.join(', ')})`)
382  if (policy.protect.length > 0) lines.push(`protected paths: ${policy.protect.map(({ source }) => source).join(', ')}`)
383  if (policy.commands.length > 0) lines.push(`blocked patterns: ${policy.commands.map(({ source }) => `/${source}/`).join(', ')}`)
384  if (policy.allow.length > 0) lines.push('allowed paths override the file rules')
385  if (lines.length === 0) lines.push('no rules are on')
386
387  return lines
388}
389
hooks/powershell.ts 180 lines
1// The guard's rules for Claude Code's PowerShell tool, in PowerShell's own
2// syntax: cmdlets and their aliases, case-insensitive parameters that may be
3// abbreviated, `-Name:value`. Pure functions, like rules.ts.
4
5import { checkDestructive, checkPath, isDangerousTarget, splitCommand } from './rules'
6import type { Policy, Verdict } from './rules'
7
8const REMOVE = new Set(['remove-item', 'rm', 'del', 'erase', 'rd', 'rmdir', 'ri'])
9const READERS = new Set(['get-content', 'gc', 'cat', 'type', 'select-string', 'sls', 'format-hex', 'fhx', 'import-csv', 'ipcsv'])
10const WRITERS = new Set(['set-content', 'sc', 'add-content', 'ac', 'out-file', 'tee-object', 'tee'])
11const COPIERS = new Set(['copy-item', 'cp', 'copy', 'cpi', 'move-item', 'mv', 'move', 'mi', 'compress-archive', 'invoke-webrequest', 'iwr', 'invoke-restmethod', 'irm'])
12const DISK = new Set(['format-volume', 'clear-disk', 'initialize-disk', 'remove-partition', 'diskpart'])
13
14/** Parameters whose value is a path the cmdlet reads or writes. */
15const PATH_PARAMS = ['path', 'literalpath', 'lp', 'pspath', 'filepath', 'infile']
16/** Parameters that take a value, so the next word is not a positional argument. */
17const VALUE_PARAMS = [...PATH_PARAMS, 'destination', 'encoding', 'filter', 'include', 'exclude', 'value', 'pattern', 'delimiter', 'outfile', 'uri', 'body', 'method', 'headers']
18
19const deny = (rule: string, words: string[], reason: string, hint: string): Verdict => ({ rule, subject: words.join(' '), reason, hint })
20
21/** A word as PowerShell names a command: no path, no `.exe`, lower case. */
22const commandName = (word: string) =>
23  word
24    .replace(/\\/g, '/')
25    .split('/')
26    .pop()!
27    .replace(/\.exe$/i, '')
28    .toLowerCase()
29
30/** `-Recurse`, `-rec`, `-r`: PowerShell accepts any unambiguous prefix. */
31const isPrefixOf = (name: string, full: string, shortest = 1) => name.length >= shortest && full.startsWith(name)
32
33type Parsed = { switches: string[]; named: Map<string, string>; positional: string[] }
34
35/** Splits a cmdlet's words into switches, named values and positional arguments. */
36export function parseParams(args: readonly string[]): Parsed {
37  const parsed: Parsed = { switches: [], named: new Map(), positional: [] }
38  for (let i = 0; i < args.length; i++) {
39    const word = args[i]!
40    if (!/^-[A-Za-z]/.test(word)) {
41      parsed.positional.push(word)
42      continue
43    }
44    const [rawName = '', inline] = word.slice(1).split(/:(.*)/s)
45    const name = rawName.toLowerCase()
46    // -Force, -fo, -f and -Recurse never take a value
47    const isSwitch = name === 'f' || isPrefixOf(name, 'force', 2) || isPrefixOf(name, 'recurse')
48    const takesValue = !isSwitch && VALUE_PARAMS.some(full => isPrefixOf(name, full, 2))
49    if (isSwitch) {
50      // `-Recurse:$true` is the switch on, `-Recurse:$false` off
51      if (!/^\$false$/i.test(inline ?? '')) parsed.switches.push(name)
52    } else if (inline !== undefined && inline !== '') {
53      parsed.named.set(name, inline)
54    } else if (takesValue && args[i + 1] !== undefined) {
55      parsed.named.set(name, args[++i]!)
56    } else {
57      parsed.switches.push(name)
58    }
59  }
60  return parsed
61}
62
63/** PowerShell's home and system locations, spelled as rules.ts reads them. */
64function asUnixTarget(target: string): string {
65  return target
66    .replace(/^\$env:(USERPROFILE|HOMEPATH)/i, '~')
67    .replace(/^\$HOME\b/i, '~')
68    .replace(/^\$env:(SystemRoot|windir|SystemDrive|ProgramFiles(\(x86\))?|ProgramData)/i, '/')
69    .replace(/^\$env:([A-Za-z_]\w*)/i, '$$$1')
70    .replace(/\\/g, '/')
71}
72
73/** A target a recursive delete must not reach; `C:\Users\me` as well as `/home/me`. */
74export function isDangerousPsTarget(target: string): boolean {
75  const t = asUnixTarget(target).replace(/\/+$/, '')
76  return isDangerousTarget(t === '' ? '/' : t) || /^[A-Za-z]:\/[^/]+\/[^/]+(\/\*)?$/.test(t)
77}
78
79function checkRemove(name: string, args: string[], words: string[], policy: Policy): Verdict | undefined {
80  if (!REMOVE.has(name)) return undefined
81  const { switches, named, positional } = parseParams(args)
82  // cmd's `rd /s` and a bash-style `-rf` count as recursive too
83  const isRecursive =
84    switches.some(s => isPrefixOf(s, 'recurse') || /^r[f]?$|^fr$/.test(s)) || args.some(arg => /^\/s$/i.test(arg))
85  if (!isRecursive) return undefined
86
87  if (policy.rmMode === 'any') {
88    return deny('rm-rf', words, 'it deletes a folder recursively', 'Delete specific files, or ask the user to run it.')
89  }
90  const targets = [...PATH_PARAMS.map(p => named.get(p)), ...positional.filter(arg => !/^\/[a-z]$/i.test(arg))].filter(
91    (target): target is string => target !== undefined,
92  )
93  const target = targets.find(isDangerousPsTarget)
94  if (target === undefined) return undefined
95  return deny(
96    'rm-rf',
97    words,
98    `it deletes ${target} recursively (PowerShell's -Recurse does not ask, even without -Force)`,
99    'Name a specific path inside the project, or ask the user to run it.',
100  )
101}
102
103function checkOther(name: string, args: string[], words: string[]): Verdict | undefined {
104  if (DISK.has(name) || (name === 'format' && /^[A-Za-z]:$/.test(args[0] ?? ''))) {
105    return deny('disk-write', words, 'it formats or wipes a disk or partition', 'Ask the user to run it.')
106  }
107  if (name === 'icacls' && args.some(arg => /^\/t$/i.test(arg)) && /\/grant\S*\s+(\*?S-1-1-0|everyone)\S*:\(?(OI\)\(CI\)\(?)?F/i.test(args.join(' '))) {
108    return deny('chmod-777', words, 'it gives Everyone full control of a whole tree', 'Grant the narrowest permission needed.')
109  }
110  return undefined
111}
112
113/** The files a cmdlet reads, copies, sends or writes: never a copy's destination. */
114function touchedPaths(name: string, args: string[]): string[] {
115  const isCopier = COPIERS.has(name)
116  if (!READERS.has(name) && !WRITERS.has(name) && !isCopier) return []
117  const { named, positional } = parseParams(args)
118  const paths = PATH_PARAMS.map(p => named.get(p)).filter((path): path is string => path !== undefined)
119  if (WRITERS.has(name)) {
120    // Set-Content .env "x": the path comes first, the rest is the value written
121    return paths.length > 0 ? paths : positional.slice(0, 1)
122  }
123  // Invoke-WebRequest -InFile sends a file; Copy-Item's second positional is the destination
124  const sources = isCopier && !named.has('destination') && positional.length > 1 ? positional.slice(0, -1) : positional
125  return [...paths, ...sources]
126}
127
128/** `> .env`, `>> secrets.txt`, `2>file`: what a redirection writes to. */
129function redirectTargets(args: readonly string[]): string[] {
130  const out: string[] = []
131  args.forEach((arg, i) => {
132    if (/^\d?>>?$/.test(arg) && args[i + 1]) out.push(args[i + 1]!)
133    else if (/^\d?>>?./.test(arg)) out.push(arg.replace(/^\d?>>?/, ''))
134  })
135  return out
136}
137
138/** Checks a whole PowerShell command line with the same policy as Bash; the first rule that fires wins. */
139export function checkPowerShell(command: string, policy: Policy): Verdict | undefined {
140  for (const { source, pattern } of policy.commands) {
141    if (pattern.test(command)) {
142      return { rule: 'blocked-command', subject: command, reason: `it matches the blocked pattern /${source}/`, hint: 'Find another way, or ask the user to run it.' }
143    }
144  }
145
146  if (
147    policy.destructive &&
148    (/\b(iwr|irm|invoke-webrequest|invoke-restmethod|curl|wget|downloadstring|downloadfile)\b[\s\S]*\|\s*(iex|invoke-expression)\b/i.test(command) ||
149      /\b(iex|invoke-expression)\b[\s\S]*\b(iwr|irm|invoke-webrequest|invoke-restmethod|downloadstring|net\.webclient)\b/i.test(command))
150  ) {
151    return { rule: 'pipe-to-shell', subject: command, reason: 'it runs a downloaded script without review', hint: 'Download the script to a file, show it to the user, and run it only after they agree.' }
152  }
153
154  for (const segment of splitCommand(command)) {
155    let words = segment
156    while (words[0] === '&' || words[0] === '.') words = words.slice(1)
157    // `cmd /c rd /s /q C:\` runs cmd's command inside PowerShell
158    if (commandName(words[0] ?? '') === 'cmd' && /^\/[ck]$/i.test(words[1] ?? '')) words = words.slice(2)
159    if (words.length === 0) continue
160
161    const name = commandName(words[0]!)
162    const args = words.slice(1)
163
164    if (policy.destructive) {
165      const verdict = checkRemove(name, args, words, policy) ?? checkOther(name, args, words) ?? (name === 'git' ? checkDestructive(['git', ...args], policy.rmMode) : undefined)
166      if (verdict) return verdict
167    }
168
169    if (policy.secrets || policy.protect.length > 0) {
170      const candidates = [...touchedPaths(name, args), ...redirectTargets(args), ...(name === 'git' && args[0] === 'add' ? args.slice(1).filter(a => !a.startsWith('-')) : [])]
171      for (const path of candidates) {
172        const verdict = checkPath(path, policy)
173        if (verdict) return { ...verdict, subject: words.join(' ') }
174      }
175    }
176  }
177
178  return undefined
179}
180
types/index.d.ts 20 lines
1export type GuardBlock = {
2  /** The tool whose call was denied. */
3  tool: string
4  /** The rule that fired. */
5  rule: string
6  /** The command segment or path it matched. */
7  subject: string
8  /** When, in ms since the epoch. */
9  at: number
10}
11
12declare module 'claude-code' {
13  interface PluginState {
14    guard: {
15      isPaused: boolean
16      blocks: GuardBlock[]
17    }
18  }
19}
20