P

Pre-Commit Security Scanner

Pre-commit hook that scans staged files for hardcoded secrets, API keys, passwords, and sensitive data patterns before allowing commits.

HookClipticssecurityv1.0.0MIT
1 views0 copies

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

PatternExampleSeverity
AWS Access KeysAKIA[0-9A-Z]{16}Critical
AWS Secret Keys40-char base64 strings near AWS contextCritical
GitHub Tokensghp_[a-zA-Z0-9]{36}Critical
GitLab Tokensglpat-[a-zA-Z0-9\-]{20}Critical
Slack Tokensxoxb-, xoxp-, xoxs-Critical
Google API KeysAIza[0-9A-Za-z\-_]{35}Critical
Stripe Keyssk_live_[a-zA-Z0-9]{24,}Critical
JWT SecretsHardcoded strings in jwt.sign()Critical
Private Keys-----BEGIN (RSA|EC|DSA) PRIVATE KEY-----Critical
Database URLspostgres://, mongodb:// with credentialsCritical
Generic Passwordspassword = "...", passwd, secret assignmentsHigh
API Keysapi_key, apiKey, API_KEY with literal valuesHigh

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

LevelActionDescription
CriticalBlock commitLeaked secrets, RCE vulnerabilities, private keys
HighBlock commitInjection vectors, insecure crypto, disabled security
MediumWarning (allow)Weak patterns, missing headers, permissive configs
LowInfo onlyStyle 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

  1. Never commit secrets — Use .env files (gitignored) and secret managers
  2. Parameterize all queries — Never concatenate user input into queries
  3. Validate at boundaries — Sanitize all external input at entry points
  4. Use framework defaults — React escaping, Helmet headers, CORS config
  5. Keep dependencies updated — Run npm audit regularly
  6. Review bypass commits — Track --no-verify usage in CI
  7. Layer your defenses — Pre-commit hook + CI scan + code review

Supported Languages

LanguageSecret DetectionInjection AnalysisConfig Issues
JavaScript/TypeScriptāœ…āœ…āœ…
Pythonāœ…āœ…āœ…
Goāœ…āœ…āœ…
Rubyāœ…āœ…āœ…
Java/Kotlināœ…āœ…āœ…
PHPāœ…āœ…āœ…
Shell/Bashāœ…āœ…āœ…
YAML/JSON/TOMLāœ…ā€”āœ…
Dockerfileāœ…ā€”āœ…
Terraform/HCLāœ…ā€”āœ…
Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates