Runs an AI-based secure code review on staged changes (changed hunks only) during git commit.
It uses the same prompt.txt as GitHub Action, so local and PR reviews stay consistent.
- Reviews only staged hunks (not whole files).
- Uses secure prompt instructions (copied from the GitHub Action).
- Summarizes High/Medium/Low risks with clear remediation.
- Warn-only by default (commits go through even with findings).
- Strict mode available β block commits if high-risk issues are detected.
- Only two environment variables are configurable for simplicity.
- Add this repo to your projectβs
.pre-commit-config.yaml:
repos:
- repo: https://github.com/DevSecOps-AppSec/ai-secure-code-review-precommit
rev: v1.0.0
hooks:
- id: ai-secure-review-staged- Install pre-commit:
pip install pre-commit
pre-commit installNow, the hook will run automatically on each commit.
export OPENAI_API_KEY="sk-..."export PRECOMMIT_STRICT=1 # Block commit on High-risk findings (default: warn-only)π To persist, add them to ~/.bashrc, ~/.zshrc, or your shell profile.
- Collects unified diffs of staged files with risky extensions (
.js, .py, .go, .java, etc.). - Sends trimmed hunks to the model with secure prompt instructions (
prompt.txt). - Prints review results inline before commit finishes.
- In default mode β warnings are shown but commit proceeds.
- With
PRECOMMIT_STRICT=1β commit is blocked if AI flags High-risk issues.
ai-secure-code-review-precommit/
ββ .pre-commit-hooks.yaml # hook manifest
ββ scripts/
β ββ ai_precommit_review.js # Node.js script for staged diff review
ββ prompt.txt # Secure review prompt (same as Action)
ββ README.md
ββ LICENSE
# Stage a risky file
git add app.js
# Try to commit
git commit -m "Add new feature"
# Output:
# ββ AI Secure Review (pre-commit) ββ
# Risk Summary: High:1, Medium:2, Low:0
# 1. [Finding] Possible SQL Injection...
# Why it matters...
# Evidence: + db.query("SELECT * FROM " + userInput)
# Fix: Use parameterized queries.
#
# Safeguards Checklist:
# - [x] Input validation
# - [ ] SQL injection prevention
#
# β Commit blocked (if PRECOMMIT_STRICT=1)-
[pre-commit] OPENAI_API_KEY not set β skipping AI review.
β Make sure you exported your key (export OPENAI_API_KEY=...). -
API quota exceeded / 429
β Upgrade your API plan or use another base URL (hardcoded to OpenAI default). -
Timeout
β Reduce diff size or line counts (hardcoded MAX_LINES=1200).
pre-commit uninstallMIT