Pre-Commit Security Scanner
Pre-commit hook that scans staged files for hardcoded secrets, API keys, passwords, and sensitive data patterns before allowing commits.
Pre-Commit Security Scanner
Hook Type
pre-commit ā Runs automatically before every git commit, blocking the commit if security issues are detected.
Overview
A Claude Code hook that scans your staged changes for security vulnerabilities, leaked secrets, and dangerous patterns before they enter your git history. Catches issues like hardcoded API keys, SQL injection, XSS vulnerabilities, insecure dependencies, and misconfigured permissions ā preventing costly security incidents at the earliest possible stage.
Why Pre-Commit?
Once secrets or vulnerabilities are committed to git, they exist in the repository history forever (even if deleted later). Pre-commit scanning prevents this by:
- Blocking leaked secrets before they reach remote repositories
- Catching injection vulnerabilities before code review
- Enforcing security patterns automatically across the team
- Reducing security review burden by catching low-hanging fruit
Quick Start
Add to your .claude/hooks.json:
{ "hooks": { "pre-commit": { "command": "claude-code-hook security-scan", "description": "Scan staged changes for security issues", "blocking": true } } }
Patterns Detected
Secrets & Credentials
| Pattern | Example | Severity |
|---|---|---|
| AWS Access Keys | AKIA[0-9A-Z]{16} | Critical |
| AWS Secret Keys | 40-char base64 strings near AWS context | Critical |
| GitHub Tokens | ghp_[a-zA-Z0-9]{36} | Critical |
| GitLab Tokens | glpat-[a-zA-Z0-9\-]{20} | Critical |
| Slack Tokens | xoxb-, xoxp-, xoxs- | Critical |
| Google API Keys | AIza[0-9A-Za-z\-_]{35} | Critical |
| Stripe Keys | sk_live_[a-zA-Z0-9]{24,} | Critical |
| JWT Secrets | Hardcoded strings in jwt.sign() | Critical |
| Private Keys | -----BEGIN (RSA|EC|DSA) PRIVATE KEY----- | Critical |
| Database URLs | postgres://, mongodb:// with credentials | Critical |
| Generic Passwords | password = "...", passwd, secret assignments | High |
| API Keys | api_key, apiKey, API_KEY with literal values | High |
Detection Examples
// BLOCKED: Hardcoded AWS credentials const AWS_ACCESS_KEY = 'AKIAIOSFODNN7EXAMPLE'; // ā Critical const AWS_SECRET_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'; // ā Critical // SAFE: Using environment variables const AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY_ID; // ā const AWS_SECRET_KEY = process.env.AWS_SECRET_ACCESS_KEY; // ā
# BLOCKED: Hardcoded database URL with credentials DATABASE_URL = "postgres://admin:p@[email protected]:5432/prod" # ā Critical # SAFE: Environment variable DATABASE_URL = os.environ["DATABASE_URL"] # ā
Injection Vulnerabilities
SQL Injection
// BLOCKED: String concatenation in SQL const query = `SELECT * FROM users WHERE email = '${email}'`; // ā High const query = "SELECT * FROM users WHERE id = " + userId; // ā High // SAFE: Parameterized queries const query = 'SELECT * FROM users WHERE email = $1'; // ā const result = await db.query(query, [email]);
NoSQL Injection
// BLOCKED: Unsanitized MongoDB query db.users.find({ username: req.body.username }); // ā High (can inject $gt, $ne) // SAFE: Explicit field validation const username = String(req.body.username); // ā db.users.find({ username });
Command Injection
// BLOCKED: Shell command with user input exec(`convert ${filename} output.png`); // ā Critical exec('git log --author=' + userName); // ā Critical // SAFE: Use arrays (no shell interpretation) execFile('convert', [filename, 'output.png']); // ā
XSS (Cross-Site Scripting)
// BLOCKED: Direct HTML insertion element.innerHTML = userInput; // ā High document.write(data); // ā High $('#content').html(userComment); // ā High // SAFE: Text content or framework escaping element.textContent = userInput; // ā // React JSX auto-escapes by default // ā
Insecure Configurations
// BLOCKED: CORS wildcard in production app.use(cors({ origin: '*' })); // ā Medium // BLOCKED: Disabled SSL verification process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // ā High rejectUnauthorized: false // ā High // BLOCKED: Weak cryptography crypto.createHash('md5'); // ā Medium (use sha256+) crypto.createCipher('des', key); // ā High (use aes-256-gcm) // BLOCKED: Insecure cookie settings res.cookie('session', token, { httpOnly: false }); // ā Medium res.cookie('session', token, { secure: false }); // ā Medium (in production)
File & Permission Issues
# BLOCKED: Overly permissive file permissions chmod 777 deploy.sh # ā High chmod 666 config.yml # ā Medium # BLOCKED: Sensitive files being committed .env # ā Critical (should be in .gitignore) id_rsa # ā Critical *.pem # ā High credentials.json # ā Critical
Dangerous Patterns
// BLOCKED: eval with dynamic input eval(userInput); // ā Critical new Function(userCode); // ā High setTimeout(stringCode, 0); // ā High (when string arg) // BLOCKED: Prototype pollution obj[key] = value; // ā Medium (when key is from user input) Object.assign(target, untrustedSource); // ā ļø Warning // BLOCKED: Insecure deserialization const data = JSON.parse(untrustedInput); // ā ļø Warning (needs validation after) yaml.load(untrustedInput); // ā High (use yaml.safeLoad)
Severity Levels
| Level | Action | Description |
|---|---|---|
| Critical | Block commit | Leaked secrets, RCE vulnerabilities, private keys |
| High | Block commit | Injection vectors, insecure crypto, disabled security |
| Medium | Warning (allow) | Weak patterns, missing headers, permissive configs |
| Low | Info only | Style issues, minor improvements |
Configuration
Custom Rules
Add project-specific patterns to .claude/security-rules.json:
{ "customPatterns": [ { "name": "Internal API Token", "pattern": "INTERNAL_[A-Z]+_TOKEN\\s*=\\s*['\"][^'\"]+['\"]", "severity": "critical", "message": "Hardcoded internal API token detected" } ], "ignorePaths": [ "**/*.test.ts", "**/*.spec.js", "**/fixtures/**", "**/mocks/**" ], "ignorePatterns": [ "EXAMPLE_KEY", "test-api-key", "dummy-secret" ], "severityThreshold": "high" }
Severity Threshold
Control which severity levels block commits:
{ "severityThreshold": "critical" // Only block on critical issues }
Options: "critical" | "high" (default) | "medium" | "low"
Ignore False Positives
{ "ignorePatterns": [ "AKIAIOSFODNN7EXAMPLE", "sk_test_", "pk_test_" ], "ignoreFiles": [ "docs/examples/auth.md", "tests/fixtures/mock-credentials.json" ] }
Output Format
When issues are found:
š Pre-Commit Security Scan
āāāāāāāāāāāāāāāāāāāāāāāāāā
ā CRITICAL: Hardcoded AWS Access Key
File: src/config/aws.ts:12
Pattern: AKIA[0-9A-Z]{16}
Fix: Use environment variable AWS_ACCESS_KEY_ID
ā HIGH: SQL Injection vulnerability
File: src/services/userService.ts:45
Pattern: String interpolation in SQL query
Fix: Use parameterized queries with $1, $2 placeholders
ā ļø MEDIUM: CORS wildcard origin
File: src/app.ts:8
Pattern: cors({ origin: '*' })
Fix: Specify allowed origins explicitly
āāāāāāāāāāāāāāāāāāāāāāāāāā
2 critical/high issues found. Commit blocked.
Fix the issues above and try again.
When all clear:
š Pre-Commit Security Scan
āāāāāāāāāāāāāāāāāāāāāāāāāā
ā
No security issues detected (scanned 12 files)
Bypass (Emergency Only)
In rare cases where a false positive blocks a legitimate commit:
# Skip the security hook (use with caution!) git commit --no-verify -m "feat: add example credentials in docs"
Warning: Only bypass when you've verified the flagged pattern is a false positive. Add it to ignorePatterns to prevent future false positives.
Integration with CI/CD
While this hook catches issues locally, pair it with CI security scanning for defense in depth:
# GitHub Actions example - name: Security Scan run: | npm audit --audit-level=high npx semgrep --config=auto src/
Best Practices
- Never commit secrets ā Use
.envfiles (gitignored) and secret managers - Parameterize all queries ā Never concatenate user input into queries
- Validate at boundaries ā Sanitize all external input at entry points
- Use framework defaults ā React escaping, Helmet headers, CORS config
- Keep dependencies updated ā Run
npm auditregularly - Review bypass commits ā Track
--no-verifyusage in CI - Layer your defenses ā Pre-commit hook + CI scan + code review
Supported Languages
| Language | Secret Detection | Injection Analysis | Config Issues |
|---|---|---|---|
| JavaScript/TypeScript | ā | ā | ā |
| Python | ā | ā | ā |
| Go | ā | ā | ā |
| Ruby | ā | ā | ā |
| Java/Kotlin | ā | ā | ā |
| PHP | ā | ā | ā |
| Shell/Bash | ā | ā | ā |
| YAML/JSON/TOML | ā | ā | ā |
| Dockerfile | ā | ā | ā |
| Terraform/HCL | ā | ā | ā |
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Agents Md Watcher
Streamline your workflow with this automatically, loads, agents, configuration. Includes structured workflows, validation checks, and reusable patterns for automation.
Automated Build Inspector
Boost productivity using this automatically, trigger, build, processes. Includes structured workflows, validation checks, and reusable patterns for automation.
Auto Change Logger
Boost productivity using this every, file, mutation, demo. Includes structured workflows, validation checks, and reusable patterns for automation.