为仓库添加密钥扫描钩子
为仓库添加密钥扫描钩子
技能标识:add-precommit-secrets-hook
Set up a two-layer pre-commit hook that prevents committing secrets to git. Layer 1 blocks any .env* filename structurally (except .env.example). Layer 2 runs secretlint on staged diff to catch token / key patterns (GitHub PAT, OpenAI, AWS, Slack, GCP, etc.). Use when the user asks to "add secret scanning", "prevent committing .env", "set up pre-commit for secrets", "gitleaks / secretlint hook", or when a private GitHub repo can’t use GHAS secret scanning.
写操作说明: 本技能会安装依赖、修改
package.json、写.husky/pre-commit并提交——仅在用户要求为该仓库加密钥扫描时执行;改写 git 历史(filter-repo/BFG)属于破坏性操作,必须先停下征得用户明确同意。
/add-precommit-secrets-hook — Local Secret Scanning Pre-commit Hook
Install a two-layer defense against accidentally committing secrets.
Why two layers
GitHub’s native secret scanning is paid for private repos (requires GHAS,
Enterprise-only). Local pre-commit hooks are the free equivalent — and fire
earlier (at commit time, before any push).
But secretlint alone has blind spots: plain-string passwords like
<一串无前缀的弱口令>, bare base64 tokens, or database connection strings with inline
credentials are hard to match by pattern. So we pair it with a structural
filename check — no .env* file may ever be committed (except
.env.example). Together they cover both “pattern-matchable token” and
“opaque secret in a file that just shouldn’t exist in git” cases.
Prerequisites
The skill assumes:
- Target directory is a git repo (otherwise
git init -b mainfirst) - A
package.jsonexists (root of Node/JS project or monorepo) - Node + a package manager (pnpm preferred, npm/yarn OK)
Detect the package manager before starting:
if [ -f pnpm-lock.yaml ] || [ -f pnpm-workspace.yaml ]; then PM=pnpm
elif [ -f yarn.lock ]; then PM=yarn
else PM=npm
fi
echo "Using $PM"
For pnpm monorepos, add -w (workspace root) to install commands. For npm/yarn,
install normally.
Step 1 — Install dependencies
# pnpm workspace root
pnpm add -Dw husky lint-staged secretlint @secretlint/secretlint-rule-preset-recommend
# pnpm non-workspace
pnpm add -D husky lint-staged secretlint @secretlint/secretlint-rule-preset-recommend
# npm / yarn
npm i -D husky lint-staged secretlint @secretlint/secretlint-rule-preset-recommend
Use husky@^9 (current major). Older husky v8 has a different init command
and hook format — this skill assumes v9.
Step 2 — Write .secretlintrc.json
At repo root:
{
"rules": [
{
"id": "@secretlint/secretlint-rule-preset-recommend"
}
]
}
The preset-recommend rule set includes: GitHub PAT, OpenAI, AWS, Slack,
GCP, Sendgrid, Stripe, npm token, Anthropic, and more. If the project has
domain-specific secrets worth flagging (e.g. internal API keys with a known
prefix), add a custom rule — but that’s out of scope for this skill.
Step 3 — Update package.json
Add two scripts and a lint-staged config. Edit in place to preserve
the rest of package.json:
{
"scripts": {
"prepare": "husky",
"secrets:scan": "secretlint '**/*'"
},
"lint-staged": {
"*": "secretlint"
}
}
prepareruns automatically afterinstall, which installs the husky hooks directory. Without this, the hook won’t fire on fresh clones.secrets:scangives the user a one-liner to audit the whole repo on demand (e.g. before cutting a release).lint-staged "*"runs secretlint on every staged file type. secretlint is content-aware, not file-type-aware — it’s fine to run on JSON, YAML, TypeScript, Markdown, etc.
Step 4 — Initialize husky and write the pre-commit hook
$PM exec husky init # creates .husky/ and .husky/_/ internals
This writes a default .husky/pre-commit containing pnpm test. Replace
it with the two-layer hook below. Write it with a file-write tool (not echo
file) to keep quoting clean:
.husky/pre-commit (exact content — do not change the regex):
# Layer 1: 结构性保护 — .env 文件名禁止 staged(.env.example 除外)
# secretlint 靠模式识别抓密钥,但 "无前缀的裸口令" 这种裸字符串它认不出;
# 直接禁 .env 文件名是更稳的兜底。
# 用两步过滤兼容 BSD grep(macOS 默认):
# 1) 先匹配所有 .env 文件名(.env / .env.foo / path/.env.bar)
# 2) 再 grep -v 排除 .example
leaked=$(git diff --cached --name-only --diff-filter=ACM \
| grep -E '(^|/)\.env(\.[A-Za-z0-9_-]+)?$' \
| grep -v '\.example$' || true)
if [ -n "$leaked" ]; then
echo "❌ 拒绝提交 .env 文件(加到 .gitignore,或改名为 .env.example):"
echo "$leaked" | sed 's/^/ /'
exit 1
fi
# Layer 2: 内容模式扫描 — secretlint 在 staged diff 里找 token / key pattern
pnpm exec lint-staged
Translate the last line based on package manager:
- pnpm:
pnpm exec lint-staged - npm:
npx lint-staged - yarn:
yarn lint-staged
⚠ BSD grep gotcha
Do not use PCRE-style negative lookahead (?!example) in the regex.
macOS ships BSD grep, which errors out with grep: repetition-operator operand invalid. When that happens, grep returns non-zero, the || true
swallows it, and Layer 1 silently lets everything through — the worst
failure mode for a security hook. Use the two-step grep | grep -v pipeline
as shown.
Step 5 — Ensure .gitignore covers .env files
Add (or verify exists) in .gitignore:
.env
.env.local
.env.*.local
.env.production
Layer 1 of the hook is belt-and-suspenders. .gitignore is the primary
prevention; the hook only fires if someone uses git add -f to override it.
Step 6 — Smoke test both layers
Run these in order. Each test stages a fake file, invokes the hook directly
(not through git commit, to avoid actually committing), then cleans up.
# T1: .env.local should be blocked by Layer 1
echo 'FAKE=x' > .env.local
git add -f .env.local
sh .husky/pre-commit 2>&1 | head -3
git reset HEAD .env.local >/dev/null 2>&1
rm -f .env.local
# Expect: "❌ 拒绝提交 .env 文件 ..."
# T2: .env.example should pass Layer 1 (may still fail Layer 2 if it has real secrets)
echo 'FAKE=x' > .env.example.tmp
mv .env.example.tmp some.env.example
git add -f some.env.example
sh .husky/pre-commit 2>&1 | tail -5
git reset HEAD some.env.example >/dev/null 2>&1
rm -f some.env.example
# Expect: no "拒绝" line; secretlint runs clean
# T3: A fake GitHub PAT should be caught by Layer 2
# 运行时拼出一个假的 GitHub PAT 形状(ghp_ + 36 个字母数字),避免在文档里出现完整 token 字面量
echo "TOKEN=ghp_$(printf 'A%.0s' $(seq 1 36))" > fake.yml
git add fake.yml
sh .husky/pre-commit 2>&1 | tail -10
git reset HEAD fake.yml >/dev/null 2>&1
rm -f fake.yml
# Expect: "error [GITHUB_TOKEN] found GitHub Token"
Do not use git commit to smoke-test. If the hook has a bug (e.g. the
BSD grep issue above), your test secret gets committed for real, and you
then need destructive history rewriting to remove it. sh .husky/pre-commit
runs the logic without mutating history.
Step 7 — Audit existing history (optional)
The hook only protects future commits. If the repo has history, scan it once:
$PM run secrets:scan
If secretlint flags anything already committed, the fix is git filter-branch / git filter-repo / BFG Repo-Cleaner to rewrite history
— all destructive. Stop and ask the user before doing that.
Final commit
Stage the changes and commit:
git add .husky/pre-commit .secretlintrc.json package.json \
pnpm-lock.yaml # or package-lock.json / yarn.lock
git commit -m "chore: add secretlint + lint-staged pre-commit hook"
The commit itself triggers the hook — if secretlint flags anything in the newly-added config files (it shouldn’t), lint-staged will auto-revert.
Known caveats
- AWS doc placeholders (the well-known
AKIA…EXAMPLEsample key in AWS docs) are intentionally not flagged by secretlint (they’d cause constant false positives on docs and examples). If the user needs to block them specifically, write a custom rule. - DB connection strings in README / AGENTS.md will false-positive. The
database-connection-stringrule matches URL structure (mysql://x:y@host:port/db), not the actual secrecy ofx:y. Writingmysql://<user>:<password>@localhost:3306/mydbas an example still trips it. Two fixes, in order of preference:- Don’t write full connection-string examples at all — list env var
names instead (
DATABASE_URL # points at the MySQL dev container). - Whitelist placeholder patterns in
.secretlintrc.json. The<angle>:<brackets>@shape is a safe signal that something is a placeholder, not a real secret:
This still catches{ "rules": [ { "id": "@secretlint/secretlint-rule-preset-recommend", "rules": [ { "id": "@secretlint/secretlint-rule-database-connection-string", "options": { "allows": [ "/(mysql|postgres|postgresql|mongodb):\\/\\/<[a-z_]+>:<[a-z_]+>@/i" ] } } ] } ] }mysql://admin:hunter2@host(no<>around identifiers), so it’s a narrow exception, not a blanket bypass. Verify the regex is tight before shipping — allows rules that are too loose defeat the whole point of the hook.
- Don’t write full connection-string examples at all — list env var
names instead (
- Bare base64 strings / DB passwords with no identifying prefix are
content-invisible to secretlint. Layer 1’s filename block is the
mitigation — keep those secrets in
.envfiles, never inline. pnpm exec <cmd> | taildiscards the exit code of<cmd>(the shell$?becomestail’s exit). When testing exit codes, invoke the binary directly:./node_modules/.bin/secretlint file.env.- Husky v9 vs v8: v9 removed the shebang line and the
husky.shsource line from hook files. If the user is on v8, the hook body needs:
at the top. This skill assumes v9.#!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" - Team adoption: every team member needs
$PM installonce after pulling — that’s what triggersprepare→husky→.git/hooksinstallation. Mention this inREADME.mdunder “first-time setup” if it’s a shared repo.
原文链接:https://www.ssssmy.com/notes/skill-add-precommit-secrets-hook