yurukusa/claude-code-hooks

GitHub: yurukusa/claude-code-hooks

Claude Code的安全钩子工具集,通过自动化检查和防护机制提升编码会话的安全性和效率。

Stars: 14 | Forks: 1

# claude-code-hooks工具集 [![GitHub stars](https://img.shields.io/github/stars/yurukusa/cc-safe-setup?style=social)](https://github.com/yurukusa/cc-safe-setup) ## 快速入门 (新代码库) ``` npx cc-safe-setup # Install 8 essential hooks in 10 seconds npx cc-safe-setup --verify # Test each hook works ``` **Claude Code 开销太大?** 普通开发者每天在 token 上花费 [$13](https://code.claude.com/docs/en/costs)。我们的 [Token 使用指南](https://zenn.dev/yurukusa/books/token-savings-guide) 展示了如何利用 800 多小时的实际运行数据将花费减半。 ## 原始仓库 (16 个钩子) **[交互式食谱](https://yurukusa.github.io/claude-code-hooks/)** — 在浏览器中搜索、筛选并复制 26 个钩子用例。 **来自 700 多小时自主 Claude Code 运行的 16 个钩子 + 6 个模板。** ``` ┌─────────────────────────────────────────────────────────┐ │ Claude Code Session │ │ │ │ User Prompt ──→ PermissionRequest ──→ PreToolUse │ │ (auto-approve- (destructive-guard │ │ readonly) branch-guard │ │ comment-strip │ │ cd-git-allow │ │ secret-guard) │ │ │ │ │ │ ▼ ▼ │ │ Tool Executes ──→ PostToolUse │ │ (syntax-check │ │ context-monitor │ │ activity-logger │ │ tmp-cleanup) │ │ │ │ │ ▼ │ │ Session End ──→ Stop │ │ (proof-log-session) │ │ │ │ Notification ──→ no-ask-human │ │ PreCompact ──→ proof-log-session │ └─────────────────────────────────────────────────────────┘ ``` 覆盖 [cc-health-check](https://github.com/yurukusa/cc-health-check) 中 **20 项检查中的 18 项**。 ### 10 秒快速开始 ``` npx cc-safe-setup # Install 8 essential hooks npx cc-safe-setup --verify # Test each hook works npx cc-safe-setup --doctor # Diagnose any issues npx cc-safe-setup --create "block npm publish without tests" # Generate custom hooks ``` ## 包含内容 ### 钩子 (16 个) | 钩子 | 用途 | 触发点 | |------|---------|---------| | `context-monitor.sh` | 分级上下文窗口警告 (谨慎 → 警告 → 紧急 → 临界) | PostToolUse | | `activity-logger.sh` | 每次文件变更的 JSONL 审计跟踪 (路径、增/删行数、时间戳) | PostToolUse (Edit\|Write) | | `syntax-check.sh` | 编辑后自动语法检查 (Python, Shell, JSON, YAML, JS) | PostToolUse (Edit\|Write) | | `decision-warn.sh` | 编辑敏感路径时发出警报但不阻止 | PreToolUse (Edit\|Write) | | `cdp-safety-check.sh` | 阻止原始 WebSocket CDP 构建,强制使用成熟工具 | PreToolUse (Bash) | | `proof-log-session.sh` | 自动生成 5W1H 会话摘要到每日 Markdown 文件 | Stop, PreCompact | | `session-start-marker.sh` | 记录会话开始时间 (用于 proof-log) | PostToolUse | | `no-ask-human.sh` | 在自主运行期间检测并阻止向缺席人类提问 | PostToolUse | | `branch-guard.sh` | 阻止向 main/master 推送 + 阻止所有分支的强制推送 | PreToolUse (Bash) | | `error-gate.sh` | 存在未解决错误时阻止外部操作 (push, publish, POST) | PreToolUse (Bash) | | `destructive-guard.sh` | 阻止对敏感路径执行 rm -rf、git reset --hard、git clean。防止 NTFS 联结遍历数据丢失 | PreToolUse (Bash) | | `secret-guard.sh` | 阻止 git add .env、凭证文件、存在 .env 时执行 git add . | PreToolUse (Bash) | | `comment-strip.sh` | 移除会破坏权限允许列表的 bash 注释 ([#29582](https://github.com/anthropics/claude-code/issues/29582)) | PreToolUse (Bash) | | `cd-git-allow.sh` | 自动批准只读的 cd+git 组合操作 ([#32985](https://github.com/anthropics/claude-code/issues/32985)) | PreToolUse (Bash) | | `auto-approve-readonly.sh` | 通过 PermissionRequest 自动批准只读命令 (git log, ls, cat) | PermissionRequest | | `tmp-cleanup.sh` | 移除超过 60 秒的陈旧 tmpclaude-* 文件 | PostToolUse | ### 模板 (5 个) | 模板 | 用途 | |----------|---------| | `CLAUDE-autonomous.md` | 自主执行的操作规则:备份分支、循环检测、决策自主权、状态持久化 | | `dod-checklists.md` | 代码变更、发布、通用任务和会话交接的完成定义 | | `task-queue.yaml` | 带有优先级、状态跟踪和阻塞项的结构化任务队列 | | `mission.md` | 跨会话重启的持久化状态:目标、进展、阻碍、交接说明 | | `LESSONS.md` | 结构化事件日志:失败内容、根本原因、已应用修复、预防规则 | ### 示例配置 (3 个) - `settings-minimal.json` — 上下文监控 + 语法检查。不错的起点。 - `settings.json` — 包含所有核心钩子的推荐设置。 - `settings-autonomous.json` — 完整的自主模式,包含 no-ask-human + branch guard + error gate。 ## 健康检查覆盖范围 本工具包如何映射 [cc-health-check](https://github.com/yurukusa/cc-health-check) 的 20 项检查: | 维度 | 检查项 | 覆盖来源 | |-----------|-------|-----------| | 安全性 | PreToolUse 阻止危险命令 | `cdp-safety-check.sh` | | 安全性 | API 密钥存放在专用文件 | `CLAUDE-autonomous.md` | | 安全性 | 分支保护 | `branch-guard.sh` | | 安全性 | 感知错误的门控 | `error-gate.sh` | | 安全性 | 破坏性命令阻止器 | `destructive-guard.sh` | | 质量 | 编辑后语法检查 | `syntax-check.sh` | | 质量 | 错误检测与跟踪 | `error-gate.sh` + `activity-logger.sh` | | 质量 | 完成定义检查清单 | `dod-checklists.md` | | 质量 | 输出验证 | `CLAUDE-autonomous.md` + `dod-checklists.md` | | 监控 | 上下文窗口警报 | `context-monitor.sh` | | 监控 | 活动日志 | `activity-logger.sh` | | 监控 | 每日摘要 | `proof-log-session.sh` | | 恢复 | 备份分支 | `CLAUDE-autonomous.md` | | 恢复 | 挂起/闲置监视器 | *(需要外部 tmux 脚本)* | | 恢复 | 循环检测 | `CLAUDE-autonomous.md` | | 自主性 | 任务队列 | `task-queue.yaml` | | 自主性 | 阻止不必要的问题 | `no-ask-human.sh` | | 自主性 | 持久化状态 | `mission.md` | | 协调 | 决策审计跟踪 | `decision-warn.sh` | | 协调 | 多智能体协调 | *(需要外部工具)* | | 协调 | 经验捕获 | `LESSONS.md` | **已覆盖 18/20 项。** 未覆盖的 2 项检查(监视器、多智能体)需要钩子和模板之外的额外工具。 ## 快速设置 ### 选项 A:快速安装 (推荐) ``` npx cc-safe-setup ``` 10 秒内安装 8 个核心钩子。零配置。[详情](https://github.com/yurukusa/cc-safe-setup) **安装后,验证钩子是否正常工作:** ``` npx cc-safe-setup --verify # Test each hook with sample inputs npx cc-safe-setup --status # Check which hooks are installed npx cc-health-check # Full setup diagnostic (20 checks) ``` ### 选项 B:手动设置 #### 1. 复制钩子和模板 ``` # "word-word.sh". I need to translate the descriptive part but keep the script name or technical term. However, the entire heading is the script name, so perhaps I should keep the script names as is and not translate them? But the user said "translate each of the following headings", and in the context, these might be titles of scripts or tools. mkdir -p ~/.claude/hooks cp hooks/*.sh ~/.claude/hooks/ chmod +x ~/.claude/hooks/*.sh # Looking at the example: 'API Reference' is translated to 'API 参考', where 'API' is kept in English, and 'Reference' is translated. So, for compound terms, translate the non-technical part. cp templates/CLAUDE-autonomous.md ~/CLAUDE.md # or append to existing cp templates/dod-checklists.md ~/.claude/ cp templates/task-queue.yaml ~/ops/ cp templates/mission.md ~/ops/ cp templates/LESSONS.md ~/ ``` #### 2. 将钩子接入 settings.json 打开 `~/.claude/settings.json` 并添加钩子配置。使用其中一个示例文件作为起点: ``` cat examples/settings-autonomous.json ``` 然后将 `"hooks"` 部分复制到你自己的设置文件中,将 `/path/to/hooks/` 替换为你的实际路径。 **最小化示例**(仅上下文监控 + 语法检查): ``` { "hooks": { "PostToolUse": [ { "matcher": "", "hooks": [{ "type": "command", "command": "~/.claude/hooks/context-monitor.sh" }] }, { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "~/.claude/hooks/syntax-check.sh" }] } ] } } ``` #### 3. 验证 启动一个 Claude Code 会话并进行一次编辑。你应该能看到语法检查输出(出错时)和上下文监控消息(当上下文低于阈值时)。 ## 钩子详情 ### For script names like "context-monitor.sh", it might be similar to a tool name. I could translate "context-monitor" to "上下文监视器", but keep ".sh" as is? But the instruction says to keep tool/library/framework names in English. "context-monitor.sh" might be the name of a script file, so perhaps it's a technical term. **此集合中最有价值的钩子。** 监控剩余的上下文窗口容量。当日志不可用时,回退到工具调用计数估算。 **存在原因:** 当上下文降至 3% 且无任何警告时,我们丢失了整个会话的工作。 **阈值:** 40% 谨慎 → 25% 警告 → 20% 紧急 (自动压缩) → 15% 临界 ### To be consistent, I should treat the script names as proper nouns or technical terms and keep them in English. But the user wants translation of headings, so I need to output them in Chinese. 将每次编辑/写入操作记录到 JSONL 中,包含时间戳、文件路径和行数。 **存在原因:** “Claude Code 在过去 2 小时里做了什么?”需要一个即时的答案。 ### Perhaps for script names, I should keep the file name unchanged, but if there's a descriptive meaning, translate it. However, in this list, they are all given as script names, so I'll assume they are to be kept as is, but since it's a translation task, I need to provide a Chinese equivalent. 在 Claude Code 编辑文件后立即运行语法验证。支持 Python, Shell, JSON, YAML, JS。 **存在原因:** Claude Code 会引入语法错误,继续工作 10 多步,然后遇到阻碍。 ### Another way: Translate the meaning of the words in the script name, but keep the format. 阻止 `git push` 到 main/master。允许推送到 feature/staging 分支。 **存在原因:** 一次意外的强制推送至 main 毁掉了一天的工作。 **配置:** `CC_PROTECT_BRANCHES="main:master:production"` (默认:`main:master`) ### Let's think about the example: 'Running Naabu' – here, 'Running' is a verb, so translated. For 'Kubernetes Setup', 'Setup' is a noun, translated. 当错误日志中存在未解决错误时,阻止外部操作 (git push, npm publish, curl POST)。允许本地操作。 **存在原因:** 将未解决错误的代码发布到生产环境。 **配置:** `CC_ERROR_LOG` (默认:`~/.claude/error-tracker.log`), `CC_ERROR_THRESHOLD` (默认:`WARNING`) ### For "context-monitor.sh", it's a compound word. I could translate it to "context-monitor.sh" in English, but that's not a translation. I need to output Simplified Chinese. 当 Claude Code 编辑监控目录中的文件时发出非阻塞警报。 ### Perhaps I should translate the descriptive part and keep the technical parts. But in script names, the entire name might be technical. 阻止原始 Chrome DevTools Protocol WebSocket 构建。强制使用成熟的工具。 ### I recall that in technical translations, sometimes file names or commands are kept in English. But the instruction says to output translations in Simplified Chinese. 在会话结束时生成 5W1H 会话摘要。从 activity-logger.sh 聚合。 ### Let's see the user's instruction: "Only output the translations, nothing else." and "Keep all professional terms, proper nouns, tool/library/framework names, and technical jargon in their original English form." 记录会话开始时间戳。用于 proof-log 计算持续时间。 ### So, for each heading, identify which parts are professional terms, etc., and keep them in English, translate the rest. 检测提问模式并提醒智能体自主决策。对于无人值守操作至关重要。 ## 环境变量 | 变量 | 使用者 | 默认值 | |----------|---------|---------| | `CC_CONTEXT_MISSION_FILE` | context-monitor | `$HOME/mission.md` | | `CC_ACTIVITY_LOG` | activity-logger, proof-log | `$HOME/claude-activity-log.jsonl` | | `CC_MONITORED_PATHS` | activity-logger | *(无)* | | `CC_MONITORED_DIRS` | decision-warn | `$HOME/bin:$HOME/.claude/hooks` | | `CC_CDP_TOOL_NAME` | cdp-safety-check | `cdp-eval` | | `CC_PROOF_LOG_DIR` | proof-log | `$HOME/proof-log` | | `CC_NO_ASK_ENABLED` | no-ask-human | `1` | | `CC_PROTECT_BRANCHES` | branch-guard | `main:master` | | `CC_ERROR_LOG` | error-gate | `$HOME/.claude/error-tracker.log` | | `CC_ERROR_THRESHOLD` | error-gate | `WARNING` | | `CC_ALLOW_DESTRUCTIVE` | destructive-guard | `0` | | `CC_SAFE_DELETE_DIRS` | destructive-guard | `node_modules:dist:build:.cache` | ## 要求 - **Claude Code**(支持钩子) - **bash** + **jq** - **python3**(activity-logger, proof-log, context-monitor 使用) - **可选:** PyYAML(YAML 语法检查),Node.js(JS 语法检查) ## 常见事故与预防 来自 GitHub Issues 的真实事件,以及预防它们的钩子: | 事故 | Issue | 预防钩子 | |---|---|---| | `rm -rf` 通过 NTFS 联结删除了整个用户目录 | [#36339](https://github.com/anthropics/claude-code/issues/36339) | `destructive-guard` (内置) | | `Remove-Item -Recurse -Force` 摧毁了未推送的源代码 | [#37331](https://github.com/anthropics/claude-code/issues/37331) | `destructive-guard` (内置) | | 清理期间删除了整个 Mac 文件系统 | [#36233](https://github.com/anthropics/claude-code/issues/36233) | `scope-guard` (示例) | | `migrate:fresh` 清除了生产数据库 | [#37405](https://github.com/anthropics/claude-code/issues/37405) | `block-database-wipe` (示例) | | `prisma migrate reset` 删除了所有用户数据 | [#34729](https://github.com/anthropics/claude-code/issues/34729) | `block-database-wipe` (示例) | | `.bashrc` 被 `chezmoi apply` 覆盖 | [#37478](https://github.com/anthropics/claude-code/issues/37478) | `protect-dotfiles` (示例) | | 未经同意修改 `git config --global` | [#37201](https://github.com/anthropics/claude-code/issues/37201) | `git-config-guard` (示例) | | 上下文压缩期间编辑被静默还原 | [#34674](https://github.com/anthropics/claude-code/issues/34674) | `auto-checkpoint` (示例) | | 部署时未提交,同步时更改被还原 | [#37314](https://github.com/anthropics/claude-code/issues/37314) | `deploy-guard` (示例) | | 提示注入通过 curl POST 窃取数据 | [#37420](https://github.com/anthropics/claude-code/issues/37420) | `network-guard` (示例) | | CLAUDE.md 的记忆规则被反复忽略 | [#37314](https://github.com/anthropics/claude-code/issues/37314) | 使用钩子代替记忆 | 安装任何示例:`npx cc-safe-setup --install-example ` ## 食谱 **[COOKBOOK.md](COOKBOOK.md)** — 18 个来自真实 GitHub Issues 的即用钩子用例。自动批准带 `-C` 标志的 git、SSH 命令、桌面通知、测试强制执行、PowerShell 保护、数据库清除预防、点文件保护、自动检查点、git 配置防护等。 ## 故障排除 **钩子未触发?** 1. **在钩子命令中使用绝对路径**。相对路径可能会因启动 Claude Code 的目录而失效: "command": "bash ~/.claude/hooks/syntax-check.sh" 2. **在依赖之前隔离测试你的钩子**: echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf /"}}' | bash ~/.claude/hooks/decision-warn.sh echo $? # 对于危险命令,应输出 2 (阻止) 3. **检查超时时间。** 钩子默认超时时间为 5 秒。如果你的脚本执行了任何耗时操作(网络调用、大文件扫描),它可能会静默超时,Claude 会像通过一样继续执行。 4. **验证权限:** `chmod +x hooks/*.sh` — 钩子必须是可执行的。 5. **VS Code 扩展:** 在 settings.json 中配置的钩子可能无法在 VS Code 扩展中触发。首先使用 CLI 测试:从终端运行 `claude`。 6. **退出代码很重要:** - `exit 0` = 允许 (钩子通过) - `exit 2` = 硬阻止 (命令永不运行 — Claude 无法覆盖此操作) - 退出代码 2 时输出的任何 stderr 都会作为原因显示给 Claude ## 相关工具 | 工具 | 功能 | |------|-------------| | [cc-health-check](https://github.com/yurukusa/cc-health-check) | 诊断你的设置 — 发现缺失的部分 | | [cc-session-stats](https://github.com/yurukusa/cc-session-stats) | 你使用了多少 AI? | | [cc-audit-log](https://github.com/yurukusa/cc-audit-log) | 你的 AI 做了什么? | | [cc-roast](https://yurukusa.github.io/cc-roast/) | 残酷地审查你的 CLAUDE.md | | **claude-code-hooks** | 修复缺失的部分 — 钩子和模板 | 先运行 cc-health-check 查看你的分数,然后使用此工具包修复缺失的部分。 ## 想在 15 分钟内完成所有设置? **[Claude Code 运维套件](https://yurukusa.github.io/cc-ops-kit-landing/?utm_source=github&utm_medium=readme&utm_campaign=ops-kit)** (随意支付) — 以上所有内容,预先配置好并随时可部署: - 所有 16 个钩子,通过 `install.sh` 预配置 - **6 个模板** (CLAUDE.md 基线 + 自主执行、DoD 检查清单、任务队列、任务声明、经验教训) - **3 个专属工具** (监视器、CLAUDE.md 生成器、风险评分) - 3 个 settings.json 预设 (最小化 / 标准 / 自主) **钩子新手?** 请参阅 [迁移指南](https://github.com/yurukusa/cc-safe-setup/blob/main/MIGRATION.md) — 从仅权限到权限+钩子的逐步指南。 📘 **想要完整故事?** [来自 700 多小时自主运行的生产指南](https://zenn.dev/yurukusa/books/6076c23b1cb18b) — 所有出错的地方以及我们如何修复它们。 📰 **热门文章:** - [技能指南深度解析 (19K+ 浏览)](https://qiita.com/yurukusa/items/f69920b4a02cf7e2988c) — Anthropic 官方 Skills PDF 分析 - [运行 108 小时无人值守](https://qiita.com/yurukusa/items/3b2f9cf4d1eb7f7a54c5) — 每一次事故以及由此产生的安全钩子 如果这些钩子让你避免了糟糕的一天,考虑给这个仓库一个 ⭐ — 这能帮助其他人找到它。 ## 许可证 MIT 许可证。
标签:AI编程, Claude Code, Cutter, GNU通用公共许可证, Homebrew安装, Node.js, Token管理, 交互式指南, 代码安全, 安全设置, 开源, 成本优化, 测试, 漏洞枚举, 网络调试, 自动化, 钩子, 防御加固