精選
Hooks Automation Security Configuration
Claude Code Hooks:自動化策略完整指南
精通 Claude Code 的 Hooks 系統。學習如何自動執行策略、驗證操作,以及使用 PreToolUse、PostToolUse 和 Stop hooks 建立防護機制。
2026年1月10日 • 18 分鐘閱讀 • 作者:Claude World
Hooks 是 Claude Code 的自動化層——它們讓你能夠自動攔截、驗證和修改 Claude 的操作。本指南涵蓋每種 hook 類型、配置模式和實際使用案例。
什麼是 Hooks?
根據官方文件,Hooks 是:
- 事件攔截器,在 Claude 操作前/後執行
- 策略執行器,自動驗證行為
- 防護機制,防止危險操作
- 自動化工具,觸發自訂邏輯
可以把 Hooks 想像成 Claude Code 的中介軟體——它們位於 Claude 的意圖和實際執行之間。
Hook 架構
┌────────────────────────────────────────────────────────────┐
│ Claude Code CLI │
│ │
│ User Prompt ──────────────────────────────────────► │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ UserPromptSubmit│ Hook: Validate/modify prompt │
│ │ Hook │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ PreToolUse │ Hook: Approve/deny/modify action │
│ │ Hook │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Tool Execution │ Actual action (Read, Write, Bash) │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ PostToolUse │ Hook: React to results │
│ │ Hook │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Stop Hook │ Hook: Verify completion │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ Response ◄──────────────────────────────────────── │
└────────────────────────────────────────────────────────────┘
Hook 事件
| 事件 | 觸發時機 | 常見使用案例 |
|---|---|---|
SessionStart | Session 開始時 | 載入上下文、驗證設定 |
UserPromptSubmit | 使用者送出提示時 | 新增上下文、驗證輸入 |
PreToolUse | 工具執行前 | 核准/拒絕操作 |
PostToolUse | 工具執行後 | 稽核、回應結果 |
Stop | Claude 停止時 | 驗證完成狀態 |
SubagentStop | Subagent 完成時 | 確保任務完成 |
Hook 配置
Hooks 在 .claude/settings.json 中配置:
{
"hooks": {
"PreToolUse": [...],
"PostToolUse": [...],
"Stop": [...],
"SessionStart": [...],
"UserPromptSubmit": [...],
"SubagentStop": [...]
}
}
Hook 結構
{
"hooks": {
"EventName": [
{
"matcher": "ToolName or *",
"hooks": [
{
"type": "prompt | command",
"prompt": "Instructions for Claude",
"command": "shell command to run",
"onFailure": "block | warn | ignore"
}
]
}
]
}
}
PreToolUse Hooks
用途: 在操作執行前攔截。可以核准、拒絕或修改。
阻擋危險指令
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "Check if command contains destructive operations (rm -rf, DROP TABLE, git push --force). If yes, return 'ask' for confirmation. Otherwise return 'approve'."
}]
}]
}
}
驗證檔案存取
{
"hooks": {
"PreToolUse": [{
"matcher": "Read",
"hooks": [{
"type": "prompt",
"prompt": "If the file path contains .env, secrets, or credentials, return 'block' with explanation. Otherwise return 'approve'."
}]
}]
}
}
寫入前安全掃描
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Scan the content for potential secrets (API keys, passwords, tokens). If found, return 'block' with the line numbers. Otherwise return 'approve'."
}]
}]
}
}
SQL 注入防護
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "If the code contains string concatenation with SQL keywords (SELECT, INSERT, UPDATE, DELETE), return 'block' with SQL injection warning. Otherwise return 'approve'."
}]
}]
}
}
PostToolUse Hooks
用途: 在操作完成後回應。適合用於日誌記錄、稽核和觸發後續動作。
稽核檔案變更
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Log the file path and a summary of changes. If the file is in auth/, payment/, or admin/, note that security review is recommended."
}]
}]
}
}
編輯後自動執行測試
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "npm test --passWithNoTests",
"onFailure": "warn"
}]
}]
}
}
觸發安全掃描
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "If the written file is in auth/, payment/, or admin/ directories, trigger security-auditor agent for review."
}]
}]
}
}
Stop Hooks
用途: 在 Claude 停止前驗證完成條件。對於品質關卡至關重要。
驗證測試已執行
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Check if code was modified (Write or Edit used). If yes, verify tests were run. If no tests ran, block and explain that tests are required before completion."
}]
}]
}
}
需要安全審查
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If code in auth/, payment/, or admin/ was modified, verify security-auditor was run. If not, block and explain security review requirement."
}]
}]
}
}
文件檢查
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If public API was modified, verify documentation was updated. If not, remind about documentation update before approving."
}]
}]
}
}
覆蓋率關卡
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "npm run test:coverage -- --coverageThreshold='{\"global\":{\"lines\":80}}'",
"onFailure": "block"
}]
}]
}
}
SessionStart Hooks
用途: 當 session 開始時初始化上下文。
載入專案上下文
{
"hooks": {
"SessionStart": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Read CLAUDE.md and summarize key project policies. Load any saved memory entities related to recent work."
}]
}]
}
}
環境檢查
{
"hooks": {
"SessionStart": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "node --version && npm --version",
"onFailure": "warn"
}]
}]
}
}
UserPromptSubmit Hooks
用途: 在 Claude 執行動作前處理使用者輸入。
新增上下文
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If the prompt mentions 'deploy' or 'release', add reminder about running full test suite first."
}]
}]
}
}
關鍵字偵測
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If prompt contains 'urgent' or 'quickly', add reminder to maintain code quality despite time pressure."
}]
}]
}
}
SubagentStop Hooks
用途: 驗證 subagent 任務完成狀態。
驗證 Subagent 結果
{
"hooks": {
"SubagentStop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Review subagent results. If the task was security-related and no security-auditor was used, flag for review."
}]
}]
}
}
Hook 類型
Prompt Hooks
使用 Claude 來評估條件:
{
"type": "prompt",
"prompt": "Your evaluation instructions..."
}
Prompt Hook 回應:
approve- 允許操作deny或block- 阻擋操作ask- 請求使用者確認- 其他任何文字 - 視為修改/上下文
Command Hooks
執行 shell 指令:
{
"type": "command",
"command": "npm test",
"onFailure": "block | warn | ignore"
}
onFailure 選項:
block- 指令失敗時停止warn- 顯示警告但繼續ignore- 靜默忽略失敗
Matchers
特定工具 Matcher
{
"matcher": "Bash"
}
萬用字元 Matcher
{
"matcher": "*"
}
多個工具
為每個工具建立獨立的條目:
{
"hooks": {
"PreToolUse": [
{ "matcher": "Write", "hooks": [...] },
{ "matcher": "Edit", "hooks": [...] },
{ "matcher": "Bash", "hooks": [...] }
]
}
}
實際範例
範例 1:安全優先配置
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "Block if command contains: rm -rf, DROP, TRUNCATE, --force, sudo rm. Return 'block' with explanation, or 'approve'."
}]
},
{
"matcher": "Read",
"hooks": [{
"type": "prompt",
"prompt": "Block if path contains: .env, secret, credential, private, key. Return 'block' or 'approve'."
}]
},
{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Scan for secrets (API keys starting with sk_, tokens, passwords). Block if found."
}]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "If file in auth/payment/admin, recommend security-auditor review."
}]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If auth/payment code modified, verify security-auditor ran. Block if not."
}]
}
]
}
}
範例 2:品質關卡配置
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "npm run lint -- --quiet",
"onFailure": "warn"
}]
},
{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "npm run typecheck",
"onFailure": "warn"
}]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Verify: 1) Tests ran and passed, 2) Lint passed, 3) Types check. Block if any failed."
}]
},
{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "npm test -- --passWithNoTests",
"onFailure": "block"
}]
}
]
}
}
範例 3:稽核軌跡配置
{
"hooks": {
"SessionStart": [
{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "echo \"Session started: $(date)\" >> .claude/audit.log",
"onFailure": "ignore"
}]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Log: file path, action type, timestamp. Append to .claude/audit.log"
}]
},
{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "Log: command executed, exit status. Append to .claude/audit.log"
}]
}
]
}
}
範例 4:團隊工作流程配置
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "If command is 'git push', verify: 1) Tests pass, 2) Lint passes, 3) PR exists or being created. Block push without PR."
}]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If feature work completed, remind to: 1) Update documentation, 2) Create/update PR, 3) Request review."
}]
}
]
}
}
Hooks 與其他工具的比較
| 功能 | Hooks | Permissions | CLAUDE.md |
|---|---|---|---|
| 自動化 | ✅ 是 | ✅ 是 | ❌ 手動 |
| 條件式 | ✅ 是 | ❌ 否 | ❌ 否 |
| 自訂邏輯 | ✅ 是 | ❌ 否 | ❌ 否 |
| Shell 指令 | ✅ 是 | ❌ 否 | ❌ 否 |
| 配置難易度 | 中等 | 簡單 | 簡單 |
何時使用 Hooks
使用 Hooks 當:
- 你需要條件邏輯
- 你想要自動執行規則
- 你需要執行外部指令
- 你想要稽核軌跡
使用 Permissions 當:
- 簡單的允許/拒絕規則
- 不需要條件邏輯
- 靜態檔案存取控制
使用 CLAUDE.md 當:
- 指引和偏好設定
- 上下文和文件說明
- 非強制性的建議
除錯 Hooks
Hook 未觸發
- 檢查 matcher 是否完全符合工具名稱
- 驗證 JSON 語法正確
- 檢查 hooks 陣列結構
Command Hook 失敗
- 在終端機手動測試指令
- 檢查指令路徑和權限
- 檢視 onFailure 設定
Prompt Hook 無法運作
- 確保 prompt 指示清楚
- 確保回應選項明確
- 先用較簡單的 prompt 測試
最佳實踐
1. 從簡單開始
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "Block rm -rf commands. Return 'block' or 'approve'."
}]
}]
}
}
2. 明確指定回應
{
"type": "prompt",
"prompt": "Evaluate X. Return exactly one of: 'approve', 'block', or 'ask'."
}
3. 適當使用 onFailure
// Critical: block on failure
{ "command": "npm test", "onFailure": "block" }
// Important: warn on failure
{ "command": "npm run lint", "onFailure": "warn" }
// Optional: ignore on failure
{ "command": "npm run optional-check", "onFailure": "ignore" }
4. 分層你的 Hooks
PreToolUse → 防止不當操作
PostToolUse → 稽核和回應
Stop → 驗證完成狀態
開始使用
今天:
- 為危險指令新增一個 PreToolUse hook
- 為測試驗證新增一個 Stop hook
- 用簡單的場景測試
本週:
- 建立完整的安全 hooks
- 新增品質關卡 hooks
- 用實際工作流程測試
本月:
- 開發完整的 hook 配置
- 新增團隊特定策略
- 建立稽核軌跡系統
Hooks 將 Claude Code 從被動助手轉變為策略執行夥伴。設定一次,永久信任。