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

推荐订阅源

云风的 BLOG
云风的 BLOG
Security Archives - TechRepublic
Security Archives - TechRepublic
V
Vulnerabilities – Threatpost
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Proofpoint News Feed
G
GRAHAM CLULEY
P
Privacy International News Feed
The Hacker News
The Hacker News
Forbes - Security
Forbes - Security
U
Unit 42
N
News and Events Feed by Topic
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cisco Blogs
A
About on SuperTechFans
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
D
Docker
I
Intezer
Spread Privacy
Spread Privacy
The Last Watchdog
The Last Watchdog
V2EX - 技术
V2EX - 技术
S
Security @ Cisco Blogs
F
Full Disclosure
S
Secure Thoughts
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
W
WeLiveSecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Project Zero
Project Zero
Recorded Future
Recorded Future
Cyberwarzone
Cyberwarzone
S
Security Affairs
AWS News Blog
AWS News Blog
H
Help Net Security
The GitHub Blog
The GitHub Blog
Hacker News: Ask HN
Hacker News: Ask HN
Vercel News
Vercel News
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Register - Security
The Register - Security
S
Schneier on Security
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
L
LINUX DO - 最新话题
T
Tor Project blog
T
The Exploit Database - CXSecurity.com
MongoDB | Blog
MongoDB | Blog
Webroot Blog
Webroot Blog

博客园 - Zhentiw

[GenAI] Migration Plan: Flat API → Layered Architecture [Skill] Frontend Design Skill [GenAI] Pre-retieval overview [GenAI] About Indexing [GenAI] Indexing overview [Vibe Coding] 降低大模型幻觉 - 重试机制 [Vibe coding] 降低大模型幻觉 - JSON 安全输出提示词 [Node.js] WebSocket基础知识 [LangGraph] 应用结构 [LangGrpah] Unit testing [LangGraph] Functional API [LangGraph] 中断注意事项 [LangGraph] 中断相关细节 [LangGrpah] 静态断点 [LangGrpah] 非阻塞式中断 [LangGraph] 阻塞式中断 [LangGraph] 语义搜索 [LangGraph] 长期记忆 [LangGraph] 管理短期记忆 [LangGraph] 自定义checkpointer [LangGraph] 短期记忆 [LangGraph] 时间旅行 [LangGraph] checkpoint常用API [LangGraph] 元数据标记 [LangGraph] 流 [Vitest] mockClear, mockReset, mockRestore [LangGraph] 将子图添加为节点
Claude Code Hooks: Complete Guide
Zhentiw · 2026-06-30 · via 博客园 - Zhentiw

What are hooks? And why hooks matter

PreToolUse:

PostToolUse:

  • Safety: Prevent destructive commands (rm -rf, git push --force, credential exposure).
  • Quality: Auto-lint, format, test before code lands in your repo
  • Compliance: Log all code changes for audit trails.
  • Consistency: Enforce repo conventions automatically.

PreToolUse Hooks: Gatekeeper and confirmation

Common PreToolUse patterns:

1. Reject dangerous bash patterns:

if (toolName === "bash" && command.includes("rm -rf")) {
  return {
    status: "blocked",
    reason: "Destructive commands not allowed"
  };
}

2. Require approval for sensitive operations:

if (toolName === "bash" && command.includes("git push")) {
  return {
    status: "requires_approval",
    prompt: "This will push to remote. Approve?"
  };
}

3. Transform/sanitize commands:

if (toolName === "file_write" && path.includes(".env")) {
  return {
    status: "transform",
    newCommand: "Write to .env.example instead",
    newParams: { path: path.replace(".env", ".env.example") }
  };
}

PostToolUse Hooks: Quality gates and cleanup

Common PostToolUse patterns:

1. Auto-lint generated JavaScript/TypeScript:

if (toolName === "file_write" && filename.endsWith(".ts")) {
  const lintResult = await exec("eslint --fix " + filename);
  return {
    status: "success",
    message: "File written and linted: " + lintResult.output
  };
}

2. Run tests on modified files:

if (toolName === "file_write" && filename.includes("__tests__")) {
  const testResult = await exec("npm test -- " + filename);
  if (!testResult.success) {
    return { status: "warning", message: "Tests failed" };
  }
  return { status: "success" };
}

3. Format code with prettier:

if (toolName === "file_write" && /\.(js|ts|jsx|tsx|json)$/.test(filename)) {
  await exec("prettier --write " + filename);
  return { status: "success", message: "Code formatted" };
}

4. Prevent credential exposure:

if (toolName === "bash" && result.stdout.match(/password|token|secret|key=/i)) {
  return {
    status: "blocked",
    reason: "Output contains sensitive data"
  };
}

Hook configuration: .claude/hooks.json

{
  "preToolUse": [
    {
      "name": "block_dangerous_bash",
      "toolName": "bash",
      "rules": [
        { "pattern": "rm -rf", "action": "block" },
        { "pattern": "git push --force", "action": "require_approval" }
      ]
    }
  ],
  "postToolUse": [
    {
      "name": "auto_lint_ts",
      "toolName": "file_write",
      "filePattern": ".*\\.ts",
      "commands": [
        "eslint --fix {filepath}",
        "prettier --write {filepath}"
      ]
    }
  ]
}

Configuration options:

  • name: unique identifier for the hook
  • toolName: which tool this hook applies to (bash, file_write, git, etc.)
  • rules: conditions and actions (block, require_approval, transform, log)
  • commands: Shell commands to run (for PostToolUse)
  • filePattern: Regex to match files (for PostToolUse)

Real examples: Practical hook configurations

Example 1: Protect .env files

{
  "preToolUse": [{
    "name": "protect_env_files",
    "toolName": "file_write",
    "rules": [
      {
        "pattern": "^\\.env",
        "action": "block",
        "message": "Use .env.example or .env.local instead"
      }
    ]
  }]
}

Example 2: Auto-format and test on file write

{
  "postToolUse": [{
    "name": "format_and_test",
    "toolName": "file_write",
    "filePattern": "src/.*\\.tsx",
    "commands": [
      "prettier --write {filepath}",
      "eslint --fix {filepath}",
      "npm test -- --testPathPattern={filepath}"
    ]
  }]
}

Example 3: Require approval for git operations

{
  "preToolUse": [{
    "name": "git_safety",
    "toolName": "bash",
    "rules": [
      {
        "pattern": "git push.*--force",
        "action": "block",
        "message": "Force push not allowed"
      },
      {
        "pattern": "git push.*main",
        "action": "require_approval",
        "message": "Pushing to main requires approval"
      }
    ]
  }]
}

Example 4: Log all database migrations

{
  "postToolUse": [{
    "name": "audit_migrations",
    "toolName": "file_write",
    "filePattern": "migrations/.*\\.sql",
    "commands": [
      "echo Modified: {filepath} >> AUDIT_LOG.txt"
    ]
  }]
}

Example 5: Prevent secrets in commits

{
  "preToolUse": [{
    "name": "prevent_secret_commits",
    "toolName": "bash",
    "rules": [
      {
        "pattern": "git add.*\\.env",
        "action": "block",
        "message": ".env files should not be committed"
      },
      {
        "pattern": "echo.*password|echo.*token",
        "action": "block",
        "message": "Never echo secrets"
      }
    ]
  }]
}

Debugging hooks: Troubleshooting common issues

Hook not running?

  1. Check .claude/hooks.json exists in project root.
  2. Verify JSON syntax (use a linter).
  3. Ensure toolName matches exactly (case-sensitive).
  4. Check filePattern regex with a regex tester.

Hook blocking too much?

  1. Tighten your regex patterns.
  2. Use filePattern to scope to specific files.
  3. Switch from block to require_approval if the pattern is legitimate but sensitive.

Commands not executing in PostToolUse?

  1. Test the command manually in bash (syntax may be wrong).
  2. Use absolute paths for executables.
  3. Ensure {filepath} is being replaced with the actual filename.
  4. Check command timeout settings if operations are slow.

Security hooks: Preventing data leaks

Best practices for security-focused hooks:

1. Block credential patterns in output:

{
  "postToolUse": [{
    "name": "block_credential_output",
    "toolName": "bash",
    "rules": [
      {
        "outputPattern": "password|token|secret|api_key",
        "action": "block",
        "message": "Output contains sensitive data"
      }
    ]
  }]
}

2. Prevent writing to shared locations:

{
  "preToolUse": [{
    "name": "isolate_sensitive_files",
    "toolName": "file_write",
    "rules": [
      {
        "path": "/tmp|/var/log|/etc/",
        "action": "block",
        "message": "Cannot write to system directories"
      }
    ]
  }]
}

3. Audit sensitive bash commands:

{
  "preToolUse": [{
    "name": "audit_sensitive_ops",
    "toolName": "bash",
    "rules": [
      {
        "pattern": "curl.*Authorization|wget.*auth",
        "action": "require_approval",
        "message": "HTTP request with credentials"
      }
    ]
  }]
}

Summary

  • PreToolUse: Block dangerous patterns, require approval for sensitive operations, transform commands.
  • PostToolUse: Auto-lint, format, test, audit, and log code changes.
  • Configuration: Use .claude/hooks.json with clear rules, patterns, and actions.
  • Debug: Check JSON syntax, regex patterns, tool names, and command paths.
  • Security: Prevent credential exposure, isolate system directories, audit sensitive operations.