Back to catalogue
SecurityPreToolUse· Bash
Secret detection before Bash execution
Catch a leaked API key before it ever runs
Intercepts every shell command and scans it for API keys, tokens or plaintext passwords before execution. Blocks the command if a secret pattern is found.
What does the Secret detection before Bash execution hook do?
Secret detection before Bash execution is a Claude Code PreToolUse hook matching Bash. It fires automatically at that lifecycle event — outside the model, so it can't be skipped or forgotten. Catch a leaked API key before it ever runs.
As a PreToolUse hook it runs before the action completes, so it can block or adjust what Claude is about to do. Because it is a deterministic Node.js script, it executes on every matching event without relying on the model to remember — the guarantee that makes agentic workflows safe to automate.
Use cases
- Credential protection
- DevSecOps audit
- Leak prevention in CI/CD
Tags
#security#bash#secrets#devsecops
settings.json fragment
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/detect-secrets.mjs",
"type": "command"
}
],
"matcher": "Bash"
}
]
}
}Script · .claude/hooks/detect-secrets.mjs
#!/usr/bin/env node
// @hookstack pre-bash-secret-detection
// Bloc les commandes Bash contenant des secrets potentiels (PreToolUse)
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
const SECRET_PATTERNS = [
/(?:ANTHROPIC|OPENAI|CLAUDE|GEMINI|GROQ)_API_KEY\s*=\s*['"]?\S{20,}/i,
/sk-(?:ant-|proj-)?[a-zA-Z0-9_-]{32,}/,
/ghp_[a-zA-Z0-9]{36}/,
/-----BEGIN (?:RSA |EC )?PRIVATE KEY/,
/(?:password|passwd|secret|token)\s*=\s*['"][^'"]{6,}/i,
];
export function run(input) {
const command = input.tool_input?.command ?? "";
const match = SECRET_PATTERNS.find((p) => p.test(command));
return match
? {
decision: "block",
reason:
"Secret potentiel détecté dans la commande. Vérifiez avant de continuer.",
}
: null;
}
/* v8 ignore next 5 */
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const input = JSON.parse(readFileSync(0, "utf8"));
const result = run(input);
if (result) process.stdout.write(JSON.stringify(result));
}