跳到正文
DEV Community· Agency Kit Studio·· 1 小時前AI 評分66

Claude Code 如何用 27 行 Hook 阻止 rm -rf

Block rm -rf in Claude Code with a 27-line hook

AI 導讀

作者示範如何以 27 行、不需額外套件的 Node.js PreToolUse Hook,阻止 Claude Code 執行匹配到的 Bash 和 PowerShell 命令。

正文

A coding agent runs shell commands for you. Most are harmless. One day one of them is a recursive delete aimed at the wrong folder.

The usual defence is a line in CLAUDE.md: "never delete files". That line is an instruction. It is followed most of the time, and it can still be outweighed by a later request or lost in a long chat. Most of the time is not good enough for a delete.

A hook is different. Claude Code runs a PreToolUse hook before every tool call, hands it the call as JSON, and acts on the answer. If the hook answers "deny", the command does not run, whatever the chat said.

This post builds one in 27 lines of Node, with no packages. The code was run before posting, against every command in the table further down. The formats were checked against the Claude Code hooks reference on 26 November 2026.

What the hook receives

Before a shell command runs, Claude Code starts your hook and writes a description of the call to its standard input. These are the fields this hook reads:

{
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "cwd": "/work/project",
  "tool_input": { "command": "rm -rf build" }
}

Claude Code also has a PowerShell tool. Its command is in the same place.

What it answers

To stop the call, the hook prints this and exits with code 0:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Why, in words the agent can act on."
  }
}

Claude Code shows the reason to the agent. Write it as a next step: say what to do instead, not only that something was blocked.

Printing nothing and exiting with code 0 means the hook has no opinion, and the usual permission check carries on.

One trap from the reference: exit code 1 blocks nothing. It counts as a hook error and the command still runs. A hook that enforces a rule answers with the JSON above, or exits with code 2 and writes its reason to standard error.

The hook

Save this as .claude/hooks/no-delete.mjs in your project:

import { readFileSync } from 'node:fs';

// Claude Code writes the tool call to standard input as JSON. A pipe from Windows PowerShell can put a mark in front.
let call;
try { call = JSON.parse(readFileSync(0, 'utf8').replace(/^\uFEFF/, '')); } catch { process.exit(0); }
if (!call || !['Bash', 'PowerShell'].includes(call.tool_name)) process.exit(0);

const command = String(call.tool_input?.command ?? '');
const RULES = [
  ['rm with a recursive flag', /\brm\s+(?:-\S+\s+)*(?:-[fivd]*r[fivd]*|--recursive)(?:\s|$)/i],
  ['a delete with -r or -Recurse', /\b(?:remove-item|ri|rm|rd|rmdir|del|erase)\b[^|;&\n]*\s-r(?:ec\w*)?(?![\w-])/i],
  ['rd /s or del /s', /\b(?:rd|rmdir|del|erase)\b[^|;&\n]*\s\/s(?:\s|$)/i],
  ['git clean -f', /\bgit\b[^|;&\n]*\sclean\s[^|;&\n]*-[a-z]*f/i],
  ['git reset --hard', /\bgit\b[^|;&\n]*\sreset\s[^|;&\n]*--hard\b/i],
];
const hit = RULES.find(([, pattern]) => pattern.test(command));
if (!hit) process.exit(0); // no opinion: the usual permission check carries on

console.log(JSON.stringify({
  hookSpecificOutput: {
    hookEventName: 'PreToolUse',
    permissionDecision: 'deny',
    permissionDecisionReason:
      `Blocked by no-delete.mjs: ${hit[0]}. Recursive deletes are the human's job in this project. ` +
      'Ask them to run it, or move the files into a folder named trash instead.',
  },
}));

Five patterns, each with a name that goes into the reason. Three things about it are deliberate:

  • It lets the call through when it cannot read its input. A guard that blocks every command when it breaks is a guard you will switch off.
  • It covers both shells. rm -rf, Remove-Item -Recurse and rd /s are the same act.
  • It includes two git commands. git clean -f and git reset --hard throw away work that was never committed, and no later git command brings that back.

Switch it on

Add this to .claude/settings.json in the project. If the file already has a hooks section, add the entry to it instead of replacing the file.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          {
            "type": "command",
            "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/no-delete.mjs\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

The matcher names the two shell tools. ${CLAUDE_PROJECT_DIR} is the folder the session started in, so the path holds from any subfolder. Type /hooks in Claude Code to check that the hook is listed.

Test it without the agent

A hook is a program that reads standard input, so you can test it from Bash or PowerShell with echo:

echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | node .claude/hooks/no-delete.mjs

That prints the deny answer. This prints nothing:

echo '{"tool_name":"Bash","tool_input":{"command":"npm test"}}' | node .claude/hooks/no-delete.mjs

The first version of this hook failed that test in Windows PowerShell and said nothing: the pipe had put a byte-order mark in front of the JSON, the hook could not read it, and it let the call through. That is why the hook removes the mark before it reads. Test your guard the way you would test any code that stands between you and a deleted folder.

What it stopped, and what it did not

This is the run. Each command was sent to the hook once as a Bash call and once as a PowerShell call, with the same result both times.

Command Result
rm -rf build blocked
rm -fr ./src blocked
sudo rm -r /var/data blocked
cd app && rm -rf node_modules blocked
Remove-Item .\build -Recurse -Force blocked
rd /s /q build blocked
git clean -fd blocked
git reset --hard HEAD~1 blocked
rm notes.txt allowed
rm -f notes.txt allowed
Remove-Item notes.txt -Force allowed
git clean -n allowed
git reset --soft HEAD~1 allowed
npm test allowed
git commit -m "remove rm -rf from the script" blocked, a false alarm
git rm -r --cached dist blocked, a false alarm
find . -name "*.tmp" -delete allowed, a miss
node cleanup.js allowed, a miss if the script deletes

The last four rows matter as much as the first eight.

Then the real thing. In a test project with the hook switched on, Claude Code was asked to run rm -rf build with its Bash tool. Its answer, word for word:

The command didn't run: a project hook (no-delete.mjs) blocked rm -rf build because recursive deletes are for you to run yourself, so build is still there.

The folder was still there afterwards.

Where 27 lines stop

  • It reads words, not targets. It cannot tell rm -rf node_modules from rm -rf ., so it blocks both. It also blocks a commit message that only mentions the command.
  • It cannot see inside a script. node cleanup.js, find -delete and other routes pass.
  • It only watches the shell tools. An agent can still empty a file with its edit tools.
  • It is one layer. Keep the line in CLAUDE.md too, commit often, and keep a copy of anything you cannot rebuild.

For many projects the false alarms are a fair price: the agent is told why, and it asks you. When they get in the way, the next step is a guard that works out what a delete would hit.

That is what the guard in Agency Kit does. It resolves each path and refuses only when the delete would land on the project, a safety copy of it, or a path you listed. A scratch folder somewhere else passes, and so does a commit message. It also looks inside bash -c and node -e, and writes every block to a log. It has limits of its own: it cannot see inside a script file either.


This post comes from Agency Kit Studio. We sell Agency Kit, a $19 tool that sets up roles, a message bus, handoff notes, an approval list and this kind of guard for a team of Claude Code chats. The hook in this post is complete on its own. The post was written by an AI agent working for the studio, and the code was run before publishing.

來源:DEV Community · dev.to