
Code Reviewer
- 29 installs
- 9 repo stars
- Updated November 16, 2025
- womendefiningai/claude-code-skills
Run structured pre-merge PR reviews that combine automated audits with OWASP-oriented manual checks for security, performance, and quality.
About
Code Reviewer is an agent skill for solo and indie builders who merge their own PRs and need more than a thumbs-up from the model. The bundled examples walk a full pre-merge review: run quick-audit.sh, interpret npm audit and lint output, then apply an OWASP Top 10 lens to real files like auth routes and validation middleware. It emphasizes security failures such as missing auth middleware, weak password handling, and SQL injection risk, alongside performance and maintainability. You invoke it when a feature branch is ready but you lack a human reviewer—common for one-person SaaS, APIs, and CLIs. The skill is example-driven rather than a single rigid checklist count, so the agent learns both comprehensive and security-only review modes. It fits ship review subphase first, but the same process helps during build when you refactor sensitive modules. Outcome is an actionable review comment set aligned with automated tool results, not vague style nitpicks.
- End-to-end examples for comprehensive, security-focused, and anti-pattern reviews
- Runs bash scripts/quick-audit.sh plus npm audit, ESLint, TypeScript, and Prettier checks
- Manual pass structured around OWASP Top 10 (access control, crypto, injection)
- Covers authentication API patterns: bcrypt hashing, JWT env secrets, parameterized ORM queries
- Separates good comprehensive review workflow from bad review examples to train the agent
Code Reviewer by the numbers
- 29 all-time installs (skills.sh)
- +1 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #676 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/womendefiningai/claude-code-skills --skill code-reviewerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 29 |
|---|---|
| repo stars | ★ 9 |
| Security audit | 2 / 3 scanners passed |
| Last updated | November 16, 2025 |
| Repository | womendefiningai/claude-code-skills ↗ |
What it does
Run structured pre-merge PR reviews that combine automated audits with OWASP-oriented manual checks for security, performance, and quality.
Files
<!-- Created by: Madina Gbotoe (https://madinagbotoe.com/) Version: 1.0 Created: November 3, 2025 License: Creative Commons Attribution 4.0 International (CC BY 4.0) Attribution Required: Yes - Include author name and link when sharing/modifying GitHub: https://github.com/mgbotoe/claude-code-share/tree/main/claude-code-skills/code-reviewer
Purpose: Code Reviewer Skill - Research-backed code review with OWASP 2025, SAST integration, and DevSecOps best practices
Research Backing:
- OWASP Code Review Guide 2025
- OWASP Top 10 2021 (Current Standard)
- CWE Top 25 (2024)
- Empirical Study: arxiv.org/html/2311.16396v2 (135,560 code reviews analyzed)
- NIST Secure Software Development Framework
- DevSecOps automation research (92% faster remediation with continuous review)
-->
Code Reviewer Skill
Comprehensive code review skill implementing 2025 research-backed best practices with automated security checks, performance analysis, and quality standards enforcement.
Core Philosophy
Balanced Quality + Security Approach:
- 50% Security focus (OWASP Top 10, vulnerabilities, authentication)
- 30% Code quality (maintainability, standards, duplication)
- 20% Performance (N+1 queries, algorithm complexity, bundle size)
Research Finding: Teams with continuous code review fix vulnerabilities 92% faster than traditional batch reviews.
---
When to Use This Skill
Auto-invoked when user mentions:
- "review this code"
- "check for bugs"
- "security audit"
- "analyze this PR"
- "code review"
- "check code quality"
- "review my changes"
- "find vulnerabilities"
- "performance check"
Manual invocation:
- Before committing critical changes
- Pre-deployment validation
- After implementing security-sensitive features
- When integrating SAST tool results
---
Core Review Workflow
NEW TO CODE REVIEW? See EXAMPLES.md for complete walkthrough examples showing good vs bad reviews.
Phase 1: Automated Analysis (Run First)
Step 1: Identify Code to Review
- If reviewing specific files: Read those files
- If reviewing PR/changes: Use
git diffto see changes - If reviewing entire feature: Identify affected files via grep/glob
Step 2: Run Automated SAST Tools (If Available)
Use the scripts in scripts/ directory:
# Quick security audit
bash scripts/quick-audit.sh
# Or run individual tools:
npm audit # Dependency vulnerabilities
npm run lint # ESLint code quality
npx prettier --check . # Code formatting
# Advanced (if installed):
sonar-scanner # SonarQube
codeql database analyze # CodeQL
snyk test # Snyk securityStep 3: Parse SAST Results
- Categorize findings by severity (Critical/High/Medium/Low)
- Filter false positives (document reasoning)
- Cross-reference with manual checks
Phase 2: Manual Security Analysis
Check OWASP Top 10 2021 (Current Standard):
1. A01:2021 – Broken Access Control
- Are authentication checks on all protected routes?
- Is user input validated before authorization decisions?
- Are direct object references protected (IDOR prevention)?
2. A03:2021 – Injection (SQL, NoSQL, Command)
- Are parameterized queries used instead of string concatenation?
- Is user input sanitized before database queries?
- Are ORMs used correctly (no raw queries with user input)?
3. A03:2021 – Cross-Site Scripting (XSS)
- Is user input escaped before rendering in HTML?
- Are Content Security Policy headers configured?
- Is
dangerouslySetInnerHTMLavoided or properly sanitized?
4. A07:2021 – Identification and Authentication Failures
- Are passwords hashed with bcrypt/argon2 (not MD5/SHA1)?
- Is session management secure (httpOnly cookies, CSRF tokens)?
- Is rate limiting implemented on login endpoints?
5. A02:2021 – Cryptographic Failures
- Is sensitive data encrypted at rest and in transit?
- Are API keys/secrets stored in environment variables (not hardcoded)?
- Is HTTPS enforced for all external communication?
See REFERENCE.md for complete OWASP Top 10 checklist
Phase 3: Performance Pattern Detection
Check for Common Performance Issues:
1. N+1 Query Problem
// 🔴 BAD: N+1 queries
users.forEach(user => {
db.query("SELECT * FROM posts WHERE user_id = ?", user.id)
})
// ✅ GOOD: Single query with JOIN
db.query("SELECT * FROM users LEFT JOIN posts ON users.id = posts.user_id")2. O(n²) or Worse Algorithms
- Nested loops over large datasets
- Inefficient sorting/searching
- Recursive functions without memoization
3. Missing Database Indexes
- Queries on unindexed columns
- WHERE clauses without supporting indexes
- JOIN operations on unindexed foreign keys
4. Memory Leaks
- Event listeners not cleaned up
- Closures holding large objects
- Unbounded caches
5. Large Bundle Sizes
- Importing entire libraries instead of specific functions
- Unoptimized images
- Missing code splitting
See REFERENCE.md for performance pattern catalog
Phase 4: Code Quality Standards
Check TypeScript/JavaScript Standards:
- [ ] No
anytypes without justification comment - [ ] Proper error handling (no empty catch blocks)
- [ ] No
console.logstatements (use proper logging) - [ ] Functions < 50 lines (extract if larger)
- [ ] Cyclomatic complexity < 10
- [ ] No commented-out code
- [ ] Import order follows convention (React → Third-party → Internal → Relative)
Check Naming Conventions:
- Files:
kebab-case(user-service.ts) - Components:
PascalCase(UserProfile.tsx) - Functions/Variables:
camelCase(getUserData) - Constants:
UPPER_SNAKE_CASE(MAX_RETRIES)
See REFERENCE.md for complete standards checklist
Phase 5: Generate Review Report
Use templates from resources/templates/ to create structured output:
- Comprehensive Review: Use
resources/templates/code-review-report.md - Security Audit: Use
resources/templates/security-review-template.md - Performance Review: Use
resources/templates/performance-review-template.md - Quick Check: Use
resources/templates/quick-checklist.md
Example report format:
# Code Review Report
**Verdict:** ✅ APPROVED | ⚠️ APPROVED WITH RESERVATIONS | ❌ REQUIRES REVISION
**Files Reviewed:** [List]
**Review Date:** [ISO Date]
## Critical Issues (Must Fix Before Merge)
[None or list with code snippets]
## High Priority Issues (Fix Within 48h)
[None or list with recommendations]
## Medium Priority Issues (Fix This Sprint)
[None or list]
## Low Priority / Suggestions
[Optional improvements]
## Strengths & Good Practices
[What was done well]
## Metrics
- **Lines Changed:** X
- **Files Modified:** Y
- **Estimated Risk:** Low/Medium/High
- **Test Coverage:** Z%---
Integration with SAST Tools
SonarQube Integration
If SonarQube results available: 1. Read sonar-report.json or access SonarQube API 2. Focus manual review on issues SonarQube missed:
- Business logic vulnerabilities
- Context-specific security issues
- Authorization logic
3. Validate SonarQube findings (check false positives)
Key SonarQube Metrics to Review:
- Security Hotspots: Require manual validation
- Code Smells: Maintainability issues (threshold: Grade A or B)
- Duplications: Keep < 3%
- Coverage: Target > 80%
CodeQL Integration
If CodeQL scan available: 1. Review CodeQL alerts in GitHub Security tab 2. Prioritize alerts by severity:
- Critical/High: Must fix before merge
- Medium: Fix within sprint
- Low: Backlog
3. Use CodeQL's suggested fixes when available 4. Manual review for:
- Authentication flows
- Authorization decisions
- Cryptographic operations
CodeQL Strengths (88% accuracy):
- SQL injection detection
- Path traversal vulnerabilities
- Command injection
- Insecure deserialization
Snyk Integration
If Snyk results available: 1. Run snyk test for dependency vulnerabilities 2. Run snyk code test for code-level issues 3. Prioritize by:
- Critical: Fix immediately
- High: Fix within 7 days
- Medium: Fix within 30 days
4. Check for available patches: snyk wizard
Snyk Strengths:
- Dependency vulnerabilities (real-time CVE database)
- License compliance
- Container security
- Infrastructure as Code (IaC) scanning
ESLint + Prettier + npm audit
Basic Security Stack (Always Run):
# Run these three commands ALWAYS
npm audit --audit-level=high # Dependency vulnerabilities
npm run lint # Code quality (ESLint)
npx prettier --check . # Code formattingInterpretation:
- npm audit: Fix all high/critical vulnerabilities
- ESLint: Must pass with 0 errors (warnings acceptable if documented)
- Prettier: Auto-fix with
npx prettier --write .
---
Severity Classification
Use this framework to categorize all findings:
🔴 Critical (Blocks Deployment)
- SQL injection vulnerabilities
- XSS vulnerabilities (unescaped user input)
- Authentication bypass
- Hardcoded secrets/API keys
- Remote code execution (RCE) risks
- Sensitive data logged in plain text
Action: STOP. Must fix immediately before proceeding.
🟠 High (Fix Within 48 Hours)
- Missing authentication checks
- Insecure session management
- CSRF vulnerabilities
- Missing rate limiting on sensitive endpoints
- Weak cryptography (MD5, SHA1)
- N+1 query problems in critical paths
- Memory leaks in production code
Action: Create blocker ticket. Fix before next deployment.
🟡 Medium (Fix This Sprint)
- Missing input validation (non-critical fields)
- Inefficient algorithms (O(n²) on small datasets)
- Missing database indexes (< 1000 rows)
- Code duplication (> 5 occurrences)
- Missing error handling
- Accessibility violations (WCAG AA)
Action: Create ticket. Fix within current sprint.
🔵 Low (Backlog / Nice-to-Have)
- Code style violations (if not enforced by linter)
- Missing comments on complex code
- Minor performance optimizations
- Refactoring opportunities
- Documentation improvements
Action: Optional. Add to backlog for future improvement.
---
Key Metrics to Track
From 2025 Research:
1. Mean Time to Remediate (MTTR)
- Target: < 7 days for high severity issues
- Critical issues: < 24 hours
2. Defect Density
- Formula: (# of bugs) / (1000 lines of code)
- Target: < 1.0 defects per 1000 LOC
3. Review Coverage
- Target: 100% of changed lines reviewed
- Critical paths: 100% manual review (not just automated)
4. False Positive Rate
- CodeQL: ~5% (best in class)
- SonarQube: ~8-10%
- Snyk: ~8%
- Track your project's rate to calibrate trust
---
Common Pitfalls to Avoid
1. Over-reliance on Automation
- Automated tools catch 60-70% of security issues
- Manual review essential for business logic, authorization, context-specific issues
2. Ignoring Performance for Security
- A secure but unusable app is not secure (DoS via performance)
- Balance security checks with performance impact
3. Blocking Every Minor Issue
- Use severity classification to prioritize
- Don't let perfection block progress
4. Missing the Forest for the Trees
- Step back and review overall architecture
- Check if the approach is fundamentally sound
5. Not Checking Test Coverage
- Untested code = unreviewed code
- Require tests for all security-critical paths
---
Quick Reference Checklist
Before approving any code review:
Security:
- [ ] No SQL injection vulnerabilities (parameterized queries)
- [ ] No XSS vulnerabilities (user input escaped)
- [ ] Authentication checks on protected routes
- [ ] Secrets in environment variables (not hardcoded)
- [ ] HTTPS enforced for external APIs
- [ ] CSRF protection on state-changing endpoints
Performance:
- [ ] No N+1 query patterns
- [ ] No O(n²) or worse algorithms on large datasets
- [ ] Database indexes present for queried columns
- [ ] No memory leaks (event listeners cleaned up)
- [ ] Images optimized and lazy-loaded
Code Quality:
- [ ] TypeScript strict mode compliance (no
anywithout justification) - [ ] Error handling present (no empty catch blocks)
- [ ] No console.log statements
- [ ] Functions < 50 lines
- [ ] Test coverage > 80%
- [ ] No commented-out code
Documentation:
- [ ] Complex logic has explanatory comments
- [ ] Public APIs have JSDoc comments
- [ ] README updated if behavior changed
- [ ] Environment variables documented
---
Next Steps After Review
If APPROVED (✅): 1. Merge the PR 2. Monitor deployment for issues 3. Update test coverage metrics
If APPROVED WITH RESERVATIONS (⚠️): 1. Create tickets for medium/low priority issues 2. Merge if critical/high issues are fixed 3. Schedule follow-up review
If REQUIRES REVISION (❌): 1. Provide detailed feedback with code snippets 2. Block merge until critical issues resolved 3. Offer to pair-program on fixes if needed
---
Supporting Files
For detailed information, see:
- EXAMPLES.md - Complete end-to-end code review examples (good, bad, security-focused)
- REFERENCE.md - Complete OWASP Top 10 checklist, performance patterns, CWE references
- FORMS.md - Review report templates overview and guidance
- resources/templates/ - Ready-to-use review templates
code-review-report.md- Comprehensive review templatesecurity-review-template.md- Security-focused audit templateperformance-review-template.md- Performance analysis templatequick-checklist.md- 3-minute rapid review checklist- resources/examples/ - Real-world review examples
good-review-example.md- What a thorough review looks likebad-review-example.md- What to avoid (rubber stamp reviews)- scripts/ - Automated SAST tool integration scripts
quick-audit.sh- Quick security audit (Linux/Mac)quick-audit.bat- Quick security audit (Windows)
Research Citations:
- OWASP Code Review Guide: https://owasp.org/www-project-code-review-guide/
- OWASP Top 10 2021: https://owasp.org/Top10/
- Empirical Study (2024): https://arxiv.org/html/2311.16396v2
- CWE Top 25: https://cwe.mitre.org/top25/
---
Remember: Code review is not about finding fault—it's about ensuring quality, security, and maintainability. Be constructive, specific, and always suggest solutions alongside identifying problems.
Code Review Examples
Complete end-to-end examples showing how to use the code-reviewer skill effectively.
---
Table of Contents
1. Example 1: Good Comprehensive Code Review 2. Example 2: Security-Focused Review 3. Example 3: Bad Review (What NOT to Do)
---
Example 1: Good Comprehensive Code Review
Context
Feature: User authentication API endpoint Files Changed: src/api/auth.ts, src/middleware/validate.ts Lines Changed: +150/-30 Review Type: Pre-merge PR review
User Request
"Review this authentication PR for security, performance, and code quality issues"Review Process
Step 1: Run Automated Tools
bash scripts/quick-audit.shResults:
- ✅ npm audit: No vulnerabilities
- ✅ ESLint: 0 errors, 2 warnings
- ✅ TypeScript: All type checks pass
- ⚠️ Prettier: 3 files need formatting
Step 2: Manual Security Review (OWASP Top 10)
Checked src/api/auth.ts:
A01 - Broken Access Control:
- ✅ Authentication middleware present on all protected routes
- ✅ Token validation checks user permissions
- ✅ Direct object references prevented with user ID validation
A02 - Cryptographic Failures:
- ✅ Passwords hashed with bcrypt (cost factor 12)
- ✅ JWT secrets in environment variables
- ✅ HTTPS enforced in production
A03 - Injection:
- ✅ Parameterized queries used (TypeORM)
- ✅ Input validation with Zod schemas
- ✅ No string concatenation in SQL
A07 - Authentication Failures:
- ✅ Rate limiting implemented (5 attempts/15 minutes)
- ⚠️ ISSUE FOUND: Session timeout set to 7 days (too long)
- ✅ Password requirements enforced (12 chars min)
Step 3: Performance Analysis
// File: src/api/auth.ts:45
async function getUserWithPosts(userId: string) {
const user = await User.findOne({ where: { id: userId } });
const posts = await Post.find({ where: { userId } }); // 🔴 N+1 potential
return { ...user, posts };
}🔴 ISSUE FOUND: Potential N+1 query if called in loop. Should use JOIN.
Step 4: Code Quality
- ✅ Functions < 50 lines
- ✅ No
anytypes - ✅ Proper error handling
- ⚠️ ISSUE FOUND:
console.logon line 78 should be removed - ✅ Test coverage: 85%
Review Report Generated
# Code Review Report: User Authentication API
**Reviewed by:** Claude (code-reviewer skill)
**Date:** 2025-11-03
**PR:** #123
**Review Type:** Standard Pre-Merge Review
---
## Executive Summary
**Verdict:** ⚠️ APPROVED WITH RESERVATIONS
**Overview:**
Solid authentication implementation with proper security practices. Two medium-priority issues identified that should be fixed before merge.
**Key Metrics:**
- **Files Modified:** 2
- **Lines Changed:** +150/-30
- **Estimated Risk:** 🟡 Medium
- **Test Coverage:** 85%
- **Review Duration:** 8 minutes
---
## Critical Issues (Blocking - Must Fix Before Merge)
**None identified** ✅
---
## High Priority Issues (Fix Within 48 Hours)
**None identified** ✅
---
## Medium Priority Issues (Fix This Sprint)
### 1. Session Timeout Too Long 🟡
**Location:** `src/api/auth.ts:23`
**Issue:**const token = jwt.sign({ userId }, JWT_SECRET, { expiresIn: '7d' });
Session timeout of 7 days is excessive and increases risk if token is compromised.
**Recommendation:**const token = jwt.sign({ userId }, JWT_SECRET, { expiresIn: '24h' });
Change to 24 hours (or 1 hour for high-security applications).
**Severity:** 🟡 Medium
**Category:** Security - Authentication
**OWASP:** A07:2021 - Identification and Authentication Failures
---
### 2. Potential N+1 Query Pattern 🟡
**Location:** `src/api/auth.ts:45-48`
**Issue:**async function getUserWithPosts(userId: string) { const user = await User.findOne({ where: { id: userId } }); const posts = await Post.find({ where: { userId } }); return { ...user, posts }; }
If this function is called in a loop, it will create N+1 queries.
**Recommendation:**async function getUserWithPosts(userId: string) { const user = await User.findOne({ where: { id: userId }, relations: ['posts'] }); return user; }
Use TypeORM relations to fetch in single query.
**Severity:** 🟡 Medium
**Category:** Performance
**Impact:** Could slow down API if user list grows
---
## Low Priority / Suggestions
### 3. Remove Debug Console Statement 🔵
**Location:** `src/api/auth.ts:78`
console.log('User logged in:', user.email); // Remove this
Replace with proper logging or remove.
**Recommendation:**logger.info('User logged in', { userId: user.id });
---
## Strengths & Good Practices
✅ **Excellent password hashing** - bcrypt with cost factor 12
✅ **Rate limiting implemented** - Prevents brute force attacks
✅ **Input validation** - Zod schemas used throughout
✅ **Parameterized queries** - No SQL injection risks
✅ **High test coverage** - 85% coverage with edge cases tested
✅ **Type safety** - No `any` types, strict TypeScript
---
## Recommendations Summary
1. **Before Merge:** Fix session timeout (5 minutes)
2. **Before Merge:** Fix N+1 query pattern (10 minutes)
3. **Optional:** Remove console.log and use proper logger
**Estimated Fix Time:** 15 minutes
---
## Sign-off
**Status:** ⚠️ APPROVED WITH RESERVATIONS
This PR demonstrates strong security practices and code quality. The two medium-priority issues are straightforward fixes that should be completed before merge to ensure optimal security and performance.
Once fixes are committed, this PR is ready to merge.
**Next Steps:**
1. Author: Fix session timeout and N+1 query
2. Author: Push fixes to PR
3. Reviewer: Quick re-review of changes
4. Merge to main---
Example 2: Security-Focused Review
Context
Feature: Payment processing endpoint Files Changed: src/api/payments.ts Lines Changed: +200 Review Type: Security audit before deployment
User Request
"Security audit for the payment processing code before we deploy to production"Review Process
Step 1: OWASP Top 10 Deep Dive
A01 - Broken Access Control:
// 🔴 CRITICAL ISSUE FOUND
app.post('/api/payments/:userId', async (req, res) => {
const { userId } = req.params;
const payment = await processPayment(userId, req.body);
res.json(payment);
});PROBLEM: Any authenticated user can process payment for ANY user by changing userId in URL!
FIX REQUIRED:
app.post('/api/payments/:userId', authenticateUser, async (req, res) => {
const { userId } = req.params;
// Verify user can only process their own payments
if (req.user.id !== userId) {
return res.status(403).json({ error: 'Forbidden' });
}
const payment = await processPayment(userId, req.body);
res.json(payment);
});A02 - Cryptographic Failures:
// 🔴 CRITICAL ISSUE FOUND
const creditCard = {
number: req.body.cardNumber, // Stored in plain text!
cvv: req.body.cvv, // CVV stored (PCI-DSS violation!)
exp: req.body.expiry
};
await db.save('credit_cards', creditCard);PROBLEMS: 1. Credit card stored in plain text 2. CVV stored at all (never allowed under PCI-DSS) 3. No encryption
FIX REQUIRED:
// Use payment processor API instead of storing cards
const stripeToken = await stripe.tokens.create({
card: {
number: req.body.cardNumber,
exp_month: req.body.expMonth,
exp_year: req.body.expYear,
cvc: req.body.cvv // Stripe handles this, we never store it
}
});
// Store only the token (not the actual card)
await db.save('payment_methods', {
userId: req.user.id,
stripeToken: stripeToken.id,
lastFour: req.body.cardNumber.slice(-4) // Only last 4 digits
});A03 - Injection: ✅ Parameterized queries used ✅ Input validated with Zod
A04 - Insecure Design:
// 🟠 HIGH PRIORITY ISSUE
async function processPayment(userId, amount) {
await debitAccount(userId, amount);
await creditMerchant(amount); // No transaction wrapper!
}PROBLEM: If creditMerchant fails, user is charged but merchant isn't paid.
FIX REQUIRED:
async function processPayment(userId, amount) {
const transaction = await db.transaction();
try {
await debitAccount(userId, amount, transaction);
await creditMerchant(amount, transaction);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}Review Report
# Security Audit Report: Payment Processing
**Verdict:** ❌ REQUIRES REVISION - DO NOT DEPLOY
**Critical Issues Found:** 2
**High Priority Issues:** 1
---
## 🔴 Critical Issues (BLOCK DEPLOYMENT)
### 1. Broken Access Control - IDOR Vulnerability
**Severity:** 🔴 Critical
**OWASP:** A01:2021 - Broken Access Control
**CWE:** CWE-639 (Authorization Bypass)
Any user can process payments for other users by changing userId in URL.
**Impact:** Financial fraud, unauthorized transactions
**Fix Time:** 10 minutes
**Must Fix:** YES - Before any deployment
---
### 2. PCI-DSS Violation - Credit Card Storage
**Severity:** 🔴 Critical
**OWASP:** A02:2021 - Cryptographic Failures
**Compliance:** PCI-DSS violation
Credit cards stored in plain text, CVV stored (never allowed).
**Impact:**
- PCI-DSS compliance failure
- Legal liability
- Massive fines if breached
- Customer data exposure
**Fix Time:** 2 hours (integrate payment processor)
**Must Fix:** YES - Legal requirement
---
## 🟠 High Priority Issues
### 3. Race Condition in Payment Processing
**Severity:** 🟠 High
**Category:** Insecure Design
No database transaction wrapping payment operations.
**Impact:** User charged but merchant not paid (or vice versa)
**Fix Time:** 30 minutes
---
## Recommendation
**DO NOT DEPLOY THIS CODE TO PRODUCTION**
The critical security issues pose immediate risk:
1. Financial fraud (access control issue)
2. Legal liability (PCI-DSS violation)
**Required Actions:**
1. Fix IDOR vulnerability (10 min)
2. Integrate Stripe/payment processor (2 hours)
3. Add transaction wrapping (30 min)
4. Re-audit after fixes
5. Penetration testing recommended
**Estimated Total Fix Time:** 3 hours
**Status:** ❌ REJECTED - Requires revision before deployment---
Example 3: Bad Review (What NOT to Do)
Context
Same authentication PR from Example 1
User Request
"Review this authentication PR"❌ Bad Review Example
# Code Review
Looks good! 👍
The code seems fine. I didn't find any major issues.
**Verdict:** ✅ APPROVED
Ship it!❌ Why This Review is Bad
Problems:
1. No Specificity
- "Looks good" - What specifically was checked?
- "Seems fine" - Based on what criteria?
2. No Evidence
- No mention of tools run
- No code snippets reviewed
- No security checklist
3. Missed Critical Issues
- 7-day session timeout not mentioned
- N+1 query not caught
- Console.log not flagged
4. No Actionable Feedback
- No recommendations
- No severity classification
- No specific files/lines referenced
5. False Confidence
- Approved without thorough review
- Could ship vulnerable code
✅ What a Good Review Should Have
Compare to Example 1:
1. Ran automated tools (npm audit, ESLint, TypeScript) 2. Checked OWASP Top 10 (specific categories) 3. Analyzed performance (found N+1 query) 4. Reviewed code quality (found console.log) 5. Provided specific recommendations (with code snippets) 6. Severity classification (Critical/High/Medium/Low) 7. Actionable next steps ("Fix X before merge")
---
Key Takeaways
Good Code Review Checklist
✅ Run automated tools first
- npm audit, ESLint, TypeScript checks
- Review tool output systematically
✅ Check security (OWASP Top 10)
- Don't skip this even if tools pass
- Manual review catches business logic issues
✅ Analyze performance
- Look for N+1 queries
- Check algorithm complexity
- Review database indexes
✅ Provide specific feedback
- File names and line numbers
- Code snippets showing issue
- Code snippets showing fix
✅ Classify severity
- Critical: Block deployment
- High: Fix within 48h
- Medium: Fix this sprint
- Low: Nice to have
✅ Be constructive
- Suggest solutions, not just problems
- Acknowledge good practices too
- Be specific and helpful
---
Remember: The goal of code review is not to find fault, but to ensure quality, security, and maintainability. A thorough review saves time, money, and reputation in the long run.
Code Reviewer - Templates & Forms
Ready-to-use templates for code review reports, checklists, and documentation.
Use these templates to ensure consistent, thorough code reviews across your team.
---
📁 Template Files Location
Full templates are available in `resources/templates/` directory:
- `code-review-report.md` - Comprehensive review template (most common use case)
- `security-review-template.md` - Security-focused audit with OWASP Top 10 checklist
- `performance-review-template.md` - Performance analysis with metrics and benchmarks
- `quick-checklist.md` - 3-minute rapid review checklist for small changes
Examples are available in `resources/examples/` directory:
- `good-review-example.md` - Complete walkthrough of a thorough, helpful review
- `bad-review-example.md` - What NOT to do (rubber stamp reviews)
---
Table of Contents
1. Template Usage Guide 2. Code Review Report Template (Overview) 3. Quick Review Checklist (Overview) 4. Security-Focused Review Template (Overview) 5. Performance-Focused Review Template (Overview) 6. PR Comment Templates 7. SAST Integration Report
---
Template Usage Guide
Which template should I use?
| Scenario | Template | Location |
|---|---|---|
| Standard PR review | Code Review Report | resources/templates/code-review-report.md |
| Security audit before deployment | Security Review | resources/templates/security-review-template.md |
| Performance optimization review | Performance Review | resources/templates/performance-review-template.md |
| Quick pre-commit check | Quick Checklist | resources/templates/quick-checklist.md |
| Learn by example | Good/Bad Examples | resources/examples/*.md |
How to use:
1. Copy the appropriate template from resources/templates/ 2. Fill in the sections as you review 3. Customize severity thresholds for your project 4. Save as part of PR comment or documentation
---
Code Review Report Template (Overview)
Full template: resources/templates/code-review-report.md
Use for: Comprehensive code reviews, PR reviews, pre-deployment audits
# Code Review Report: [Feature/PR Name]
**Reviewed by:** [Your Name]
**Date:** [YYYY-MM-DD]
**Commit/PR:** [#123 or commit hash]
**Review Type:** [Standard | Security Audit | Performance Review | Pre-Deployment]
---
## Executive Summary
**Verdict:** ✅ APPROVED | ⚠️ APPROVED WITH RESERVATIONS | ❌ REQUIRES REVISION
**Overview:**
[2-3 sentence summary of what was reviewed and overall quality]
**Key Metrics:**
- **Files Modified:** X
- **Lines Changed:** +Y/-Z
- **Estimated Risk:** 🟢 Low | 🟡 Medium | 🔴 High
- **Test Coverage:** X% (target: >80%)
- **Review Duration:** X minutes
---
## Critical Issues (Blocking - Must Fix Before Merge)
| # | Severity | Location | Issue | Recommendation |
|---|----------|----------|-------|----------------|
| 1 | 🔴 Critical | `file.ts:45` | SQL injection vulnerability in login query | Use parameterized queries: `db.query(sql, [params])` |
| 2 | 🔴 Critical | `auth.ts:23` | Hardcoded API key in source code | Move to environment variable: `process.env.API_KEY` |
**Total Critical Issues:** X
---
## High Priority Issues (Fix Within 48 Hours)
| # | Severity | Location | Issue | Recommendation |
|---|----------|----------|-------|----------------|
| 1 | 🟠 High | `api.ts:67` | Missing rate limiting on login endpoint | Implement express-rate-limit with 5 attempts/15min |
| 2 | 🟠 High | `user.ts:89` | N+1 query problem in user list | Use JOIN or DataLoader for batching |
**Total High Priority Issues:** X
---
## Medium Priority Issues (Fix This Sprint)
| # | Severity | Location | Issue | Recommendation |
|---|----------|----------|-------|----------------|
| 1 | 🟡 Medium | `utils.ts:34` | Missing input validation on email field | Add Zod schema validation |
| 2 | 🟡 Medium | `dashboard.tsx:120` | Component exceeds 300 lines | Extract subcomponents |
**Total Medium Priority Issues:** X
---
## Low Priority / Suggestions (Backlog)
| # | Severity | Location | Issue | Recommendation |
|---|----------|----------|-------|----------------|
| 1 | 🔵 Low | `types.ts:12` | Consider using branded types for IDs | Implement branded types for type safety |
| 2 | 🔵 Low | `README.md:45` | Typo in documentation | Fix spelling |
**Total Low Priority Issues:** X
---
## Strengths & Good Practices
**What was done well:**
- ✅ Comprehensive test coverage (85%)
- ✅ Clear naming conventions followed
- ✅ Proper error handling throughout
- ✅ Documentation updated alongside code
- ✅ [Add more specific positive observations]
---
## Detailed Analysis
### Security Assessment
**OWASP Top 10 Check:**
- [x] A01: Access Control - ✅ Proper authentication on all routes
- [x] A02: Cryptography - ✅ Secrets in environment variables
- [x] A03: Injection - ⚠️ Found 1 SQL injection vulnerability (see critical issues)
- [x] A03: XSS - ✅ User input properly escaped
- [x] A04: Insecure Design - ✅ Rate limiting implemented
- [x] A05: Security Misconfiguration - ✅ Production config secured
- [x] A06: Vulnerable Components - ✅ No known CVEs in dependencies
- [x] A07: Authentication - ✅ Proper session management
- [x] A08: Data Integrity - ✅ Input validation present
- [x] A09: Logging - ✅ Security events logged (no sensitive data)
- [x] A10: SSRF - ✅ URL validation on external requests
**Overall Security Rating:** 🟢 Good | 🟡 Needs Improvement | 🔴 Critical Issues
---
### Performance Assessment
**Identified Issues:**
- [ ] N+1 query patterns: [Describe]
- [ ] Algorithm complexity > O(n log n): [Describe]
- [ ] Missing database indexes: [Describe]
- [ ] Memory leaks: [None detected]
- [ ] Large bundle size additions: [Describe impact]
**Performance Impact:** 🟢 Negligible | 🟡 Moderate | 🔴 Significant
---
### Code Quality Assessment
**Metrics:**
- **Cyclomatic Complexity:** Average X (target: <10)
- **Function Length:** Average X lines (target: <50)
- **Code Duplication:** X% (target: <3%)
- **TypeScript Coverage:** X% (target: 100%)
**Standards Compliance:**
- [x] TypeScript strict mode enabled
- [x] ESLint passes with 0 errors
- [x] Prettier formatting applied
- [x] No `console.log` statements
- [x] Proper import order
- [x] Naming conventions followed
---
### Test Coverage Analysis
**Current Coverage:** X%
**Missing Tests:**
- [ ] `function1()` - Edge case: empty input
- [ ] `function2()` - Error handling path
- [ ] `ComponentA` - User interaction: button click
**Test Quality:**
- ✅ Unit tests present
- ✅ Integration tests present
- ⚠️ E2E tests missing for critical flow
- ✅ Mock data follows production schema
---
## SAST Tool Results
**Tools Run:**
- ✅ npm audit: 0 high/critical vulnerabilities
- ✅ ESLint: 0 errors, 2 warnings (acceptable)
- ✅ SonarQube: Quality Gate PASSED (Grade A)
- ✅ Snyk: 0 high/critical vulnerabilities
**False Positives Filtered:** X
**Verified Issues:** Y
---
## Recommendations
### Immediate Actions (Before Merge)
1. **[Critical Issue #1]**
- **File:** `file.ts:45`
- **Fix:** [Specific code change]
- **Effort:** X minutes
- **Example:**// Before (vulnerable) const sql = SELECT * FROM users WHERE id = '${userId}';
// After (secure) const sql = 'SELECT * FROM users WHERE id = ?'; db.query(sql, [userId]);
2. **[Critical Issue #2]**
- [Same format]
---
### Short-term Improvements (This Sprint)
1. **[High Priority Issue #1]** - [Brief description]
2. **[Medium Priority Issue #1]** - [Brief description]
---
### Long-term Considerations (Backlog)
1. **Refactoring Opportunities** - [Describe technical debt]
2. **Performance Optimization** - [Describe future improvements]
3. **Architecture Improvements** - [Describe design enhancements]
---
## Next Steps
**For Developer:**
1. [ ] Address all critical issues
2. [ ] Create tickets for high/medium priority issues
3. [ ] Update tests to cover new edge cases
4. [ ] Request re-review after fixes
**For Reviewer:**
1. [ ] Follow up after fixes applied
2. [ ] Verify critical issues resolved
3. [ ] Approve merge if all blockers addressed
---
## Sign-off
**Reviewed by:** [Name]
**Approval Status:** [Approved | Approved with Reservations | Rejected]
**Next Review Required:** [Yes/No - If yes, when?]
---
_Generated using Code Reviewer Skill v1.0_
_Review completed in X minutes_---
Quick Review Checklist
Use for: Fast reviews, pre-commit checks, daily code reviews
# Quick Code Review Checklist
**File/Feature:** _______________
**Reviewer:** _______________
**Date:** _______________
## Security (30 seconds)
- [ ] No hardcoded secrets/API keys
- [ ] User input sanitized/validated
- [ ] Authentication present on protected routes
- [ ] No SQL injection (parameterized queries used)
- [ ] Passwords hashed (bcrypt/argon2, not MD5)
## Performance (30 seconds)
- [ ] No N+1 query patterns
- [ ] No nested loops over large datasets
- [ ] Database indexes present for queried columns
- [ ] No synchronous file operations (use async)
## Code Quality (60 seconds)
- [ ] TypeScript strict mode (no `any` without justification)
- [ ] Functions < 50 lines
- [ ] No commented-out code
- [ ] Proper error handling (no empty catch blocks)
- [ ] No console.log statements
## Tests (30 seconds)
- [ ] Unit tests present for new functions
- [ ] Test coverage > 80%
- [ ] Edge cases tested
- [ ] Tests pass locally
## Documentation (30 seconds)
- [ ] Complex logic has comments
- [ ] README updated if needed
- [ ] Public APIs have JSDoc comments
## Total Time: 3 minutes
**Decision:**
- ✅ APPROVED - Ready to merge
- ⚠️ APPROVED WITH NOTES - Create follow-up tickets
- ❌ CHANGES REQUIRED - Address issues before merge
**Notes:**
_______________________________________
_______________________________________---
Security-Focused Review Template
Use for: Security audits, pre-deployment security checks, sensitive features
# Security-Focused Code Review
**Feature:** _______________
**Reviewer:** _______________
**Date:** _______________
**Risk Level:** 🟢 Low | 🟡 Medium | 🔴 High | ⚫ Critical
---
## OWASP Top 10 2021 Detailed Check
### A01: Broken Access Control
- [ ] Authentication required on ALL protected endpoints?
- [ ] Authorization checks verify user owns resource?
- [ ] Direct object references validated (IDOR prevention)?
- [ ] File path traversal prevented (`../` blocked)?
- [ ] API rate limiting implemented?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
### A02: Cryptographic Failures
- [ ] HTTPS enforced for all external communication?
- [ ] Passwords hashed with bcrypt/argon2 (NOT MD5/SHA1)?
- [ ] Secrets in environment variables (not hardcoded)?
- [ ] Sensitive data encrypted at rest?
- [ ] TLS 1.2+ enforced (no SSL, TLS 1.0, TLS 1.1)?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
### A03: Injection
- [ ] Parameterized queries used (no string concatenation)?
- [ ] User input sanitized before DB operations?
- [ ] Command injection prevented (no `exec()` with user input)?
- [ ] NoSQL injection prevented?
- [ ] XML injection prevented (XXE attacks)?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
### A03: Cross-Site Scripting (XSS)
- [ ] User input escaped before rendering in HTML?
- [ ] Content Security Policy (CSP) headers configured?
- [ ] `dangerouslySetInnerHTML` avoided or sanitized (DOMPurify)?
- [ ] JSON responses have proper Content-Type?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
### A07: Authentication Failures
- [ ] Session tokens cryptographically random?
- [ ] Session expiration implemented (timeout)?
- [ ] Multi-factor authentication available?
- [ ] Account lockout after failed attempts?
- [ ] Password reset tokens expire after use?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
### A09: Logging and Monitoring
- [ ] Security events logged (login, access denied)?
- [ ] Sensitive data NOT logged (passwords, tokens)?
- [ ] Logs include timestamp, user ID, IP, action?
- [ ] Alerting configured for suspicious activity?
**Findings:** _______________
**Risk:** 🟢 🟡 🔴 ⚫
---
## Threat Modeling
**Attack Vectors Considered:**
- [ ] SQL Injection
- [ ] XSS
- [ ] CSRF
- [ ] Authentication bypass
- [ ] Authorization bypass
- [ ] Session hijacking
- [ ] Brute force attacks
- [ ] API abuse
- [ ] Data exfiltration
**Highest Risk Attack:** _______________
**Mitigation Status:** _______________
---
## Security Test Results
**Automated Scans:**
- npm audit: ___ vulnerabilities (Critical: ___, High: ___)
- Snyk: ___ vulnerabilities (Critical: ___, High: ___)
- SonarQube Security Rating: ___
**Manual Testing:**
- [ ] Attempted SQL injection - Result: ___
- [ ] Attempted XSS - Result: ___
- [ ] Attempted authentication bypass - Result: ___
- [ ] Attempted IDOR attack - Result: ___
---
## Overall Security Assessment
**Risk Level:** 🟢 Low | 🟡 Medium | 🔴 High | ⚫ Critical
**Recommendation:**
- ✅ APPROVED - Security requirements met
- ⚠️ CONDITIONAL APPROVAL - Minor issues, create tickets
- ❌ REJECTED - Critical security issues, must fix before deployment
**Critical Issues to Address:**
1. _______________
2. _______________
3. _______________---
Performance-Focused Review Template
Use for: Performance reviews, optimization audits, high-traffic features
# Performance-Focused Code Review
**Feature:** _______________
**Reviewer:** _______________
**Date:** _______________
**Expected Load:** ___ requests/second
---
## Database Performance
**Query Analysis:**
- [ ] N+1 query patterns identified: ___
- [ ] Missing indexes identified: ___
- [ ] Query complexity analyzed (EXPLAIN PLAN)
- [ ] Connection pooling configured properly
**Findings:**
- Slowest query: ___ ms (target: <100ms)
- Query count per request: ___ (target: <10)
- Recommended indexes: ___
---
## Algorithm Complexity
**Functions Analyzed:**
| Function | Current Complexity | Dataset Size | Acceptable? |
|----------|-------------------|--------------|-------------|
| `function1()` | O(n²) | 1000 items | ❌ |
| `function2()` | O(n log n) | 10000 items | ✅ |
**Optimization Recommendations:**
1. _______________
2. _______________
---
## Memory Usage
**Potential Leaks:**
- [ ] Event listeners cleaned up
- [ ] Closures releasing references
- [ ] Streams properly closed
- [ ] Caches have max size limits
**Findings:** _______________
---
## Bundle Size Impact
**Added to Bundle:**
- New dependencies: ___ KB
- New code: ___ KB
- Total impact: ___ KB (target: <50KB per feature)
**Optimization Opportunities:**
- [ ] Tree-shaking enabled
- [ ] Code splitting implemented
- [ ] Lazy loading used for heavy components
- [ ] Images optimized (WebP, proper sizing)
---
## Frontend Performance
**React-Specific:**
- [ ] Unnecessary re-renders identified
- [ ] Heavy components memoized (React.memo)
- [ ] Expensive calculations memoized (useMemo)
- [ ] Virtual scrolling for long lists
**Findings:** _______________
---
## Load Testing Results
**Metrics:**
- Response time (p50): ___ ms (target: <200ms)
- Response time (p95): ___ ms (target: <500ms)
- Response time (p99): ___ ms (target: <1000ms)
- Throughput: ___ req/s (target: > ___ req/s)
- Error rate: ___% (target: <1%)
**Bottlenecks Identified:**
1. _______________
2. _______________
---
## Overall Performance Assessment
**Performance Grade:** A | B | C | D | F
**Recommendation:**
- ✅ APPROVED - Performance acceptable
- ⚠️ APPROVED WITH MONITORING - Watch metrics in production
- ❌ REQUIRES OPTIMIZATION - Performance unacceptable
**Critical Optimizations Needed:**
1. _______________
2. _______________---
PR Comment Templates
Use for: Inline code review comments on GitHub/GitLab
Security Issue Template
🔴 **Security Issue: [Issue Type]**
**Risk:** Critical | High | Medium | Low
**CWE:** [CWE-XXX](https://cwe.mitre.org/data/definitions/XXX.html)
**Problem:**
[Explain the vulnerability]
**Exploit Scenario:**
[How an attacker could exploit this]
**Recommended Fix:**
\```typescript
// Before (vulnerable)
[vulnerable code]
// After (secure)
[secure code]
\```
**References:**
- [OWASP link]
- [CVE link if applicable]Performance Issue Template
⚠️ **Performance Issue: [Issue Type]**
**Impact:** High | Medium | Low
**Estimated Overhead:** [X ms per request | Y MB memory | Z% CPU]
**Problem:**
[Explain the performance issue]
**Recommendation:**
\```typescript
// Current implementation (O(n²))
[current code]
// Optimized version (O(n))
[optimized code]
\```
**Expected Improvement:** [X% faster | Y MB less memory]Code Quality Issue Template
💡 **Code Quality: [Issue Type]**
**Priority:** High | Medium | Low
**Issue:**
[Describe what's wrong]
**Why It Matters:**
[Explain impact on maintainability, readability, or testing]
**Suggested Improvement:**
\```typescript
// Current
[current code]
// Suggested
[improved code]
\```
**Alternative Approaches:**
- [Option 1]
- [Option 2]Praise Template
✨ **Great Work!**
[Specific thing done well]
This is a great example of [best practice] because [reason]. Keep it up!---
SAST Integration Report
Use for: Consolidating results from multiple SAST tools
# SAST Integration Report
**Project:** _______________
**Scan Date:** _______________
**Scanned By:** _______________
---
## Tools Run
- [x] npm audit
- [x] ESLint
- [x] Prettier
- [x] SonarQube
- [x] CodeQL
- [x] Snyk
- [ ] Other: _______________
---
## Consolidated Results
### Critical Findings (Across All Tools)
| Tool | Rule | File:Line | Issue | Status |
|------|------|-----------|-------|--------|
| Snyk | CVE-2021-XXXX | package.json | Vulnerable lodash version | 🔄 In Progress |
| CodeQL | js/sql-injection | api.ts:45 | SQL injection risk | ✅ Fixed |
**Total Critical:** X
---
### High Priority Findings
| Tool | Rule | File:Line | Issue | Status |
|------|------|-----------|-------|--------|
| SonarQube | squid:S2068 | config.ts:12 | Hardcoded password | 🔄 In Progress |
**Total High Priority:** X
---
### False Positives (Validated and Dismissed)
| Tool | Rule | File:Line | Reason for Dismissal |
|------|------|-----------|----------------------|
| CodeQL | js/xss | render.tsx:67 | React auto-escapes, safe by default |
**Total False Positives:** X
---
## Tool-Specific Details
### npm audit
- **Critical:** X
- **High:** X
- **Fixable Automatically:** X
- **Requires Manual Update:** X
**Command to fix:** `npm audit fix`
---
### SonarQube
- **Quality Gate:** PASSED | FAILED
- **Bugs:** X (Grade: A/B/C/D/E)
- **Vulnerabilities:** X (Grade: A/B/C/D/E)
- **Code Smells:** X (Grade: A/B/C/D/E)
- **Coverage:** X% (Target: >80%)
- **Duplication:** X% (Target: <3%)
**Dashboard:** [Link to SonarQube]
---
### CodeQL
- **Alerts:** X
- **Critical:** X
- **High:** X
- **Medium:** X
- **Low:** X
**Most Common Issues:**
1. [Issue type] - X occurrences
2. [Issue type] - X occurrences
---
### Snyk
- **Critical:** X
- **High:** X
- **Medium:** X
- **Low:** X
**Vulnerable Packages:**
1. [package@version] - [CVE-XXXX-XXXX]
2. [package@version] - [CVE-XXXX-XXXX]
**Fix Available:** Yes/No
**Command to fix:** `snyk fix`
---
## Summary
**Overall Security Posture:** 🟢 Good | 🟡 Needs Improvement | 🔴 Critical Issues
**Recommendation:**
- ✅ READY FOR DEPLOYMENT - All critical issues resolved
- ⚠️ DEPLOY WITH MONITORING - Monitor for issues
- ❌ BLOCK DEPLOYMENT - Critical issues must be fixed
**Next Actions:**
1. [ ] Fix critical issues
2. [ ] Create tickets for high/medium issues
3. [ ] Re-run scans after fixes
4. [ ] Update documentation
---
_Report generated by Code Reviewer Skill v1.0_
_Scan completed in X minutes_---
These templates should be customized based on your team's specific needs and processes.
Last Updated: November 3, 2025
Code Reviewer Skill
Research-backed code review with OWASP 2025, SAST integration, and DevSecOps best practices.
Version: 1.0 Created: November 3, 2025 Research-Backed: OWASP, CWE, Google, Microsoft, IEEE
---
🎯 Quick Start
Run a Code Review
# Quick security audit (2 minutes)
bash scripts/quick-audit.sh # Linux/Mac
scripts\quick-audit.bat # Windows
# Or invoke the skill directly
"Review this code for security issues"
"Check for bugs and vulnerabilities"
"Analyze this PR"What This Skill Does
- ✅ OWASP Top 10 Security Checks - Identifies injection, XSS, authentication issues
- ✅ Performance Analysis - Detects N+1 queries, O(n²) algorithms, memory leaks
- ✅ Code Quality Standards - TypeScript, ESLint, naming conventions, complexity
- ✅ SAST Integration - Works with SonarQube, CodeQL, Snyk, npm audit
- ✅ Structured Reports - Clear severity classification with actionable recommendations
---
📁 File Structure
code-reviewer/
├── SKILL.md # Main skill instructions (~2,600 tokens)
├── EXAMPLES.md # Complete review examples (good, bad, security)
├── REFERENCE.md # Complete OWASP Top 10, CWE Top 25 (~15,000 tokens)
├── FORMS.md # Template overview and guidance
├── README.md # This file - Quick start guide
├── scripts/
│ ├── quick-audit.sh # Quick security audit (Linux/Mac)
│ └── quick-audit.bat # Quick security audit (Windows)
└── resources/
├── templates/
│ ├── code-review-report.md # Comprehensive review template
│ ├── security-review-template.md # Security-focused audit template
│ ├── performance-review-template.md # Performance analysis template
│ └── quick-checklist.md # 3-minute rapid review checklist
└── examples/
├── good-review-example.md # What a thorough review looks like
└── bad-review-example.md # What to avoid (rubber stamps)Progressive Disclosure: Core skill loads ~2,600 tokens. Templates, reference docs, and examples loaded on-demand when needed.
---
🔍 Auto-Invoke Triggers
This skill automatically activates when you mention:
- "review this code"
- "check for bugs"
- "security audit"
- "analyze this PR"
- "code review"
- "check code quality"
- "find vulnerabilities"
- "performance check"
---
🛡️ Research Backing
OWASP Standards
- OWASP Code Review Guide 2025 - Official review methodology
- OWASP Top 10 2021 - Current security standard
- CWE Top 25 2024 - Most dangerous software weaknesses
Industry Research
- Google Research (2018): 9M code reviews analyzed
- Median review latency: < 4 hours
- 200-400 LOC optimal for catching defects
- Microsoft Research (2013): 900+ developers surveyed
- Code review finds 60-70% of defects
- Best defect detection rate at 200-400 LOC
- Empirical Study (2024): 135,560 code review comments analyzed
- Reviewers caught security issues in 35/40 weakness categories
- Most missed: Memory errors, resource management
Key Finding
Teams with continuous code review fix vulnerabilities 92% faster than batch reviews.
---
🎯 Review Focus (Balanced Quality + Security)
- 50% Security - OWASP Top 10, vulnerabilities, authentication
- 30% Code Quality - Maintainability, standards, duplication
- 20% Performance - N+1 queries, algorithm complexity, bundle size
---
🔧 SAST Tool Integration
Supported Tools
Always Available:
- ✅ npm audit (dependency vulnerabilities)
- ✅ ESLint (code quality)
- ✅ Prettier (code formatting)
- ✅ TypeScript type checking
Advanced (If Installed):
- ✅ SonarQube - Comprehensive quality + security
- Quality Gates, Code Smells, Duplications
- ✅ CodeQL - Semantic analysis (88% accuracy)
- SQL injection, XSS, command injection detection
- ✅ Snyk - Developer-friendly security (85% accuracy)
- Dependency vulnerabilities, real-time feedback
- ✅ Semgrep - Custom security rules (82% accuracy)
- Policy-as-code, organization-specific patterns
Tool Accuracy Benchmarks (2025 Research)
| Tool | Accuracy | False Positive Rate | Best Use Case |
|---|---|---|---|
| CodeQL | 88% | 5% | Semantic analysis, SQL injection |
| Snyk | 85% | 8% | Dependencies, real-time IDE feedback |
| Semgrep | 82% | 12% | Custom rules, policy enforcement |
| SonarQube | ~80% | 8-10% | Comprehensive quality + security |
---
📊 Severity Classification
🔴 Critical (Blocks Deployment)
- SQL injection vulnerabilities
- XSS vulnerabilities
- Authentication bypass
- Hardcoded secrets/API keys
- Remote code execution risks
Action: STOP. Must fix immediately.
🟠 High (Fix Within 48 Hours)
- Missing authentication checks
- Insecure session management
- CSRF vulnerabilities
- N+1 query problems in critical paths
Action: Create blocker ticket. Fix before next deployment.
🟡 Medium (Fix This Sprint)
- Missing input validation
- Inefficient algorithms (O(n²) on small datasets)
- Code duplication
- Missing error handling
Action: Create ticket. Fix within current sprint.
🔵 Low (Backlog)
- Code style violations
- Minor performance optimizations
- Refactoring opportunities
- Documentation improvements
Action: Optional. Add to backlog.
---
📋 Quick Review Checklist (3 Minutes)
Security (30 seconds):
- [ ] No hardcoded secrets/API keys
- [ ] User input sanitized/validated
- [ ] Authentication on protected routes
- [ ] No SQL injection (parameterized queries)
- [ ] Passwords hashed (bcrypt/argon2)
Performance (30 seconds):
- [ ] No N+1 query patterns
- [ ] No nested loops over large datasets
- [ ] Database indexes present
- [ ] No synchronous file operations
Code Quality (60 seconds):
- [ ] TypeScript strict mode (no
any) - [ ] Functions < 50 lines
- [ ] No commented-out code
- [ ] Proper error handling
- [ ] No console.log statements
Tests (30 seconds):
- [ ] Unit tests present
- [ ] Test coverage > 80%
- [ ] Edge cases tested
- [ ] Tests pass locally
Documentation (30 seconds):
- [ ] Complex logic has comments
- [ ] README updated
- [ ] Public APIs have JSDoc
Total Time: 3 minutes
---
💡 Usage Examples
Example 1: Quick PR Review
User: "Review this PR for security issues"
Skill Output:
✅ Runs quick-audit.sh
✅ Checks OWASP Top 10
✅ Analyzes performance patterns
✅ Generates structured report with severity classificationExample 2: Pre-Deployment Audit
User: "Security audit before deployment"
Skill Output:
✅ Comprehensive security review
✅ SAST tool integration (SonarQube, Snyk, CodeQL)
✅ Threat modeling
✅ Manual testing checklist
✅ Deployment recommendation (APPROVED/REJECTED)Example 3: Performance Review
User: "Check performance of the user list endpoint"
Skill Output:
✅ N+1 query detection
✅ Algorithm complexity analysis
✅ Database index recommendations
✅ Memory leak detection
✅ Bundle size impact---
🚀 Key Features
1. Research-Backed Standards
Every checklist item backed by OWASP, CWE, or academic research.
2. Progressive Disclosure
Core skill loads fast (4,500 tokens). Detailed references loaded on-demand.
3. Multi-Tool Integration
Works with SonarQube, CodeQL, Snyk, or just npm audit + ESLint.
4. Structured Output
Clear reports with severity classification, code snippets, and specific recommendations.
5. Automation Scripts
Quick-audit scripts run all basic checks in 2 minutes.
---
📖 Documentation
For detailed information, see:
- EXAMPLES.md - Complete walkthrough examples (start here if new to code review!)
- SKILL.md - Main review workflow and procedures
- REFERENCE.md - Complete OWASP Top 10, CWE Top 25, performance patterns
- FORMS.md - Template overview and usage guide
- resources/templates/ - Ready-to-use review templates
- resources/examples/ - Real-world good/bad review examples
Research Citations:
- OWASP Code Review Guide: https://owasp.org/www-project-code-review-guide/
- OWASP Top 10 2021: https://owasp.org/Top10/
- CWE Top 25: https://cwe.mitre.org/top25/
- Empirical Study (2024): https://arxiv.org/html/2311.16396v2
---
🔄 Integration with Other Skills
Works well with:
- qa-testing - Code review identifies issues, QA testing verifies fixes
- feature-orchestrator - Reviews features during implementation phase
- critic-agent - Code-reviewer for quick checks, critic-agent for deep audits
- devops-deployment - Pre-deployment security validation
---
⚙️ Customization
Adjust Severity Thresholds
Edit SKILL.md to change what's considered critical vs high priority for your project.
Add Custom Security Rules
Create files in resources/ directory with project-specific patterns to check.
Integrate Additional Tools
Add tool-specific scripts to scripts/ directory and update quick-audit scripts.
---
📊 Metrics to Track
From 2025 Research:
1. Mean Time to Remediate (MTTR)
- Target: < 7 days for high severity
- Critical issues: < 24 hours
2. Defect Density
- Formula: (# of bugs) / (1000 lines of code)
- Target: < 1.0 defects per 1000 LOC
3. Review Coverage
- Target: 100% of changed lines reviewed
4. False Positive Rate
- Track your project's rate to calibrate trust in automated tools
---
🤝 Contributing
Found a new security pattern? Improved a checklist? Submit updates to:
- GitHub: https://github.com/mgbotoe/claude-code-share/tree/main/claude-code-skills/code-reviewer
- License: CC BY 4.0 (attribution required)
---
📜 License
Creative Commons Attribution 4.0 International (CC BY 4.0)
Created by: Madina Gbotoe (https://madinagbotoe.com/)
Attribution Required: Yes - Include author name and link when sharing/modifying
---
Remember: Code review is not about finding fault—it's about ensuring quality, security, and maintainability. Be constructive, specific, and always suggest solutions alongside identifying problems.
Code Reviewer - Reference Guide
Complete technical reference for code review procedures, OWASP standards, and SAST tool integration.
This file contains detailed checklists, vulnerability patterns, and tool-specific guidance. Read sections as needed during code review.
---
Table of Contents
1. OWASP Top 10 2021 - Complete Checklist 2. CWE Top 25 Most Dangerous Weaknesses 3. Performance Patterns Catalog 4. SAST Tool Integration Details 5. Language-Specific Patterns 6. Security Testing Procedures
---
OWASP Top 10 2021 - Complete Checklist
A01:2021 – Broken Access Control
What to Check:
- [ ] Authentication checks on ALL protected routes/endpoints
- [ ] Authorization checks verify user has permission for specific resource
- [ ] Direct object references are validated (prevent IDOR attacks)
- [ ] File path traversal prevented (
../in user input) - [ ] API endpoints require proper authentication tokens
- [ ] Role-based access control (RBAC) implemented correctly
- [ ] Session invalidation on logout works
Common Vulnerabilities:
// 🔴 VULNERABLE: Missing authorization check
app.get('/api/user/:id', (req, res) => {
const user = db.getUser(req.params.id); // Any user can access any profile!
res.json(user);
});
// ✅ SECURE: Proper authorization
app.get('/api/user/:id', authenticateUser, (req, res) => {
if (req.user.id !== req.params.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = db.getUser(req.params.id);
res.json(user);
});CWE References: CWE-639 (Authorization Bypass), CWE-284 (Improper Access Control)
---
A02:2021 – Cryptographic Failures
What to Check:
- [ ] Sensitive data encrypted at rest (database encryption)
- [ ] HTTPS enforced for all external communication (no HTTP)
- [ ] Passwords hashed with bcrypt, argon2, or scrypt (NOT MD5/SHA1)
- [ ] API keys stored in environment variables (not hardcoded)
- [ ] Secrets not committed to version control
- [ ] TLS 1.2+ enforced (no SSL, TLS 1.0, TLS 1.1)
- [ ] Proper key rotation strategy in place
Common Vulnerabilities:
// 🔴 VULNERABLE: Weak hashing
import crypto from 'crypto';
const hash = crypto.createHash('md5').update(password).digest('hex');
// ✅ SECURE: Strong hashing with salt
import bcrypt from 'bcrypt';
const hash = await bcrypt.hash(password, 10);
// 🔴 VULNERABLE: Hardcoded secret
const JWT_SECRET = 'my-secret-key-12345';
// ✅ SECURE: Environment variable
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) throw new Error('JWT_SECRET not configured');CWE References: CWE-326 (Inadequate Encryption Strength), CWE-327 (Broken Crypto), CWE-798 (Hardcoded Credentials)
---
A03:2021 – Injection
What to Check:
- [ ] Parameterized queries used (no string concatenation)
- [ ] ORM used correctly (no raw queries with user input)
- [ ] User input sanitized before database operations
- [ ] NoSQL injection prevented (MongoDB, etc.)
- [ ] Command injection prevented (no
exec()with user input) - [ ] LDAP injection prevented
- [ ] XML injection prevented (XXE attacks)
SQL Injection Examples:
// 🔴 VULNERABLE: SQL injection
const query = `SELECT * FROM users WHERE email = '${userInput}'`;
db.query(query);
// ✅ SECURE: Parameterized query
const query = 'SELECT * FROM users WHERE email = ?';
db.query(query, [userInput]);
// 🔴 VULNERABLE: Command injection
const fileName = req.body.file;
exec(`cat ${fileName}`, callback); // Attacker: "; rm -rf /"
// ✅ SECURE: Avoid shell execution, use libraries
const fs = require('fs');
fs.readFile(fileName, 'utf8', callback);CWE References: CWE-89 (SQL Injection), CWE-78 (OS Command Injection), CWE-91 (XML Injection)
---
A03:2021 – Cross-Site Scripting (XSS)
What to Check:
- [ ] User input escaped before rendering in HTML
- [ ] Content Security Policy (CSP) headers configured
- [ ]
dangerouslySetInnerHTMLavoided or properly sanitized - [ ] React/Vue/Angular auto-escaping trusted
- [ ] URL parameters sanitized before display
- [ ] Rich text editor output sanitized (DOMPurify)
- [ ] JSON responses have proper Content-Type
XSS Examples:
// 🔴 VULNERABLE: Unescaped user input
<div>{userInput}</div> // If React, this is actually safe
<div innerHTML={userInput}></div> // DANGEROUS in plain JS
// ✅ SECURE: React auto-escapes
<div>{userInput}</div> // Safe in React
// 🔴 VULNERABLE: dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: userInput }} />
// ✅ SECURE: Sanitize first
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);
<div dangerouslySetInnerHTML={{ __html: clean }} />CWE References: CWE-79 (XSS), CWE-80 (Basic XSS), CWE-83 (Improper Neutralization)
---
A04:2021 – Insecure Design
What to Check:
- [ ] Threat modeling performed for sensitive features
- [ ] Security requirements defined early (not retrofitted)
- [ ] Rate limiting implemented on sensitive endpoints
- [ ] Input validation at multiple layers (client + server)
- [ ] Fail-secure defaults (deny by default, allow by exception)
- [ ] Business logic flaws identified and mitigated
- [ ] Separation of duties for critical operations
Design Flaws:
- No rate limiting on login → Brute force attacks
- No CAPTCHA on public forms → Bot abuse
- No email verification → Fake account creation
- Insufficient workflow validation → Business logic bypass
CWE References: CWE-840 (Business Logic Errors), CWE-841 (Improper Enforcement of Behavioral Workflow)
---
A05:2021 – Security Misconfiguration
What to Check:
- [ ] Default credentials changed
- [ ] Unnecessary features disabled (debug mode OFF in production)
- [ ] Error messages don't leak stack traces to users
- [ ] HTTP security headers configured (HSTS, X-Frame-Options, etc.)
- [ ] CORS configured restrictively (not
*for credentials) - [ ] Unused dependencies removed
- [ ] Cloud storage buckets not publicly accessible
Configuration Checks:
// 🔴 VULNERABLE: Debug mode in production
if (process.env.NODE_ENV === 'development') {
// Forgot to check this in production!
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}
// ✅ SECURE: Explicit production check
if (process.env.NODE_ENV === 'production') {
app.use(errorHandler({ log: true, showStack: false }));
} else {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}
// 🔴 VULNERABLE: Permissive CORS
app.use(cors({ origin: '*', credentials: true }));
// ✅ SECURE: Restrictive CORS
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(','),
credentials: true
}));CWE References: CWE-16 (Configuration), CWE-11 (ASP.NET Misconfiguration)
---
A06:2021 – Vulnerable and Outdated Components
What to Check:
- [ ] Dependencies updated regularly (
npm audit) - [ ] No known CVEs in production dependencies
- [ ] Dependency versions pinned (not
^or~in production) - [ ] Unused dependencies removed
- [ ] Supply chain security (verify package integrity)
- [ ] Transitive dependencies checked
- [ ] License compliance verified
Tools to Use:
# Check for vulnerabilities
npm audit
npm audit fix
# Advanced checking
snyk test
npm outdated
npx depcheck # Find unused dependenciesCWE References: CWE-1104 (Use of Unmaintained Third Party Components), CWE-937 (OWASP Top 10 2013 A9)
---
A07:2021 – Identification and Authentication Failures
What to Check:
- [ ] Passwords hashed with salt (bcrypt, argon2)
- [ ] Session tokens cryptographically random (not predictable)
- [ ] Session expiration implemented (timeout after inactivity)
- [ ] Multi-factor authentication (MFA) available
- [ ] Account lockout after failed login attempts
- [ ] Password reset tokens expire after use
- [ ] Session invalidation on password change
Authentication Examples:
// 🔴 VULNERABLE: Weak session token
const sessionId = Math.random().toString();
// ✅ SECURE: Cryptographically random token
import crypto from 'crypto';
const sessionId = crypto.randomBytes(32).toString('hex');
// 🔴 VULNERABLE: No rate limiting
app.post('/login', async (req, res) => {
const user = await checkCredentials(req.body);
// Attacker can brute force passwords!
});
// ✅ SECURE: Rate limiting
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5 // Max 5 attempts
});
app.post('/login', loginLimiter, async (req, res) => {
// ...
});CWE References: CWE-287 (Improper Authentication), CWE-307 (Improper Restriction of Excessive Authentication Attempts)
---
A08:2021 – Software and Data Integrity Failures
What to Check:
- [ ] Dependencies verified (integrity hashes, signatures)
- [ ] CI/CD pipeline secured (no unauthorized deployments)
- [ ] Code signing implemented for releases
- [ ] Serialized objects validated before deserialization
- [ ] Auto-update mechanisms secured
- [ ] Git commits signed (GPG)
Deserialization Vulnerabilities:
// 🔴 VULNERABLE: Unsafe deserialization
const userData = JSON.parse(untrustedInput);
eval(userData.callback); // EXTREMELY DANGEROUS
// ✅ SECURE: Validate structure before use
import Ajv from 'ajv';
const ajv = new Ajv();
const validate = ajv.compile(userSchema);
if (validate(userData)) {
// Safe to use
}CWE References: CWE-502 (Deserialization of Untrusted Data), CWE-565 (Reliance on Cookies without Validation)
---
A09:2021 – Security Logging and Monitoring Failures
What to Check:
- [ ] Security events logged (login, logout, access denied)
- [ ] Logs include timestamp, user ID, IP, action
- [ ] Sensitive data NOT logged (passwords, tokens, PII)
- [ ] Log aggregation in place (centralized logging)
- [ ] Alerting configured for suspicious activities
- [ ] Log retention policy defined
- [ ] Logs integrity protected (tamper-proof)
Logging Best Practices:
// 🔴 VULNERABLE: Logging sensitive data
logger.info(`User logged in with password: ${password}`);
// ✅ SECURE: Log events, not sensitive data
logger.info(`User ${userId} logged in from ${req.ip}`);
// ✅ GOOD: Security event logging
logger.warn(`Failed login attempt for ${email} from ${req.ip}`);
logger.error(`Access denied: User ${userId} attempted to access resource ${resourceId}`);CWE References: CWE-778 (Insufficient Logging), CWE-117 (Improper Output Neutralization for Logs)
---
A10:2021 – Server-Side Request Forgery (SSRF)
What to Check:
- [ ] User-controlled URLs validated before fetching
- [ ] Internal IP addresses blocked (127.0.0.1, 10.0.0.0/8, etc.)
- [ ] URL allowlist implemented (not blocklist)
- [ ] DNS rebinding prevented
- [ ] Cloud metadata endpoints blocked (169.254.169.254)
- [ ] HTTP redirects limited or disabled
SSRF Examples:
// 🔴 VULNERABLE: SSRF
app.get('/fetch', async (req, res) => {
const url = req.query.url; // Attacker: http://localhost:8080/admin
const data = await fetch(url);
res.send(data);
});
// ✅ SECURE: URL validation
import { URL } from 'url';
const ALLOWED_DOMAINS = ['api.example.com', 'cdn.example.com'];
app.get('/fetch', async (req, res) => {
const url = new URL(req.query.url);
// Block internal IPs
if (url.hostname === 'localhost' ||
url.hostname.startsWith('127.') ||
url.hostname.startsWith('10.') ||
url.hostname.startsWith('192.168.')) {
return res.status(400).json({ error: 'Invalid URL' });
}
// Allowlist domains
if (!ALLOWED_DOMAINS.includes(url.hostname)) {
return res.status(400).json({ error: 'Domain not allowed' });
}
const data = await fetch(url.toString());
res.send(data);
});CWE References: CWE-918 (SSRF)
---
CWE Top 25 Most Dangerous Weaknesses
Based on 2024 CWE Top 25 List
Top 10 Most Critical:
1. CWE-787: Out-of-bounds Write (Buffer overflow) 2. CWE-79: Cross-site Scripting (XSS) 3. CWE-89: SQL Injection 4. CWE-416: Use After Free (Memory corruption) 5. CWE-78: OS Command Injection 6. CWE-20: Improper Input Validation 7. CWE-125: Out-of-bounds Read 8. CWE-22: Path Traversal 9. CWE-352: Cross-Site Request Forgery (CSRF) 10. CWE-434: Unrestricted Upload of File with Dangerous Type
For JavaScript/TypeScript, most relevant:
- CWE-79 (XSS)
- CWE-89 (SQL Injection)
- CWE-78 (Command Injection)
- CWE-352 (CSRF)
- CWE-798 (Hardcoded Credentials)
- CWE-327 (Broken Crypto)
- CWE-502 (Unsafe Deserialization)
Full list: https://cwe.mitre.org/top25/
---
Performance Patterns Catalog
N+1 Query Problem
Detection:
// 🔴 RED FLAG: Loop with database query inside
users.forEach(async (user) => {
const posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
// If 100 users → 1 query for users + 100 queries for posts = 101 queries
});Solutions:
// ✅ SOLUTION 1: JOIN query
const usersWithPosts = await db.query(`
SELECT users.*, posts.*
FROM users
LEFT JOIN posts ON users.id = posts.user_id
`);
// ✅ SOLUTION 2: DataLoader (batching)
import DataLoader from 'dataloader';
const postLoader = new DataLoader(async (userIds) => {
const posts = await db.query('SELECT * FROM posts WHERE user_id IN (?)', [userIds]);
// Return posts grouped by user_id
});---
O(n²) Algorithm Detection
Common Patterns:
// 🔴 O(n²): Nested loops
for (const item1 of array1) {
for (const item2 of array2) {
if (item1.id === item2.id) { /* ... */ }
}
}
// ✅ O(n): Use Map/Set
const map = new Map(array2.map(item => [item.id, item]));
for (const item1 of array1) {
const match = map.get(item1.id);
if (match) { /* ... */ }
}---
Memory Leaks
Common Causes: 1. Event listeners not removed
// 🔴 LEAK
useEffect(() => {
window.addEventListener('resize', handleResize);
// Missing cleanup!
}, []);
// ✅ CORRECT
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);2. Closures holding references
// 🔴 LEAK
let largeData = fetchLargeData();
setInterval(() => {
console.log(largeData.length); // Keeps largeData in memory forever
}, 1000);
// ✅ CORRECT
setInterval(() => {
const largeData = fetchLargeData();
console.log(largeData.length);
}, 1000);---
Bundle Size Optimization
Check for:
- [ ] Tree-shaking enabled (ES modules, not CommonJS)
- [ ] Code splitting implemented (React.lazy, dynamic imports)
- [ ] Large libraries imported selectively (lodash → lodash/specific-function)
- [ ] Images optimized (WebP, proper sizing, lazy loading)
- [ ] Source maps disabled in production
- [ ] Gzip/Brotli compression enabled
Examples:
// 🔴 BAD: Import entire library
import _ from 'lodash';
_.debounce(fn, 300);
// ✅ GOOD: Import specific function
import debounce from 'lodash/debounce';
debounce(fn, 300);
// 🔴 BAD: Load all components upfront
import HeavyComponent from './HeavyComponent';
// ✅ GOOD: Lazy load
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));---
SAST Tool Integration Details
SonarQube
Quality Gates:
- Bugs: 0 (A rating)
- Vulnerabilities: 0 (A rating)
- Security Hotspots: Reviewed 100%
- Code Smells: < 3% density (A or B rating)
- Coverage: > 80%
- Duplications: < 3%
Reading SonarQube Output:
{
"issues": [
{
"severity": "BLOCKER", // Must fix before merge
"type": "VULNERABILITY",
"rule": "java:S2076", // SQL Injection
"message": "Ensure that the query is not vulnerable to SQL injection",
"line": 45
}
]
}Integration Script:
# Run SonarQube scan
sonar-scanner \
-Dsonar.projectKey=my-project \
-Dsonar.sources=src \
-Dsonar.host.url=http://localhost:9000 \
-Dsonar.login=$SONAR_TOKEN
# Check quality gate status
curl -u $SONAR_TOKEN: \
"http://localhost:9000/api/qualitygates/project_status?projectKey=my-project"---
CodeQL
High-Value Queries:
js/sql-injection- SQL injection detectionjs/command-line-injection- Command injectionjs/path-injection- Path traversaljs/xss- Cross-site scriptingjs/hardcoded-credentials- Hardcoded secrets
Reading CodeQL Alerts:
alerts:
- rule: js/sql-injection
severity: error
message: "This SQL query is vulnerable to injection"
location: src/api/users.ts:45:12
paths:
- source: req.body.username
sink: db.query()Integration:
# Create CodeQL database
codeql database create mydb --language=javascript
# Run queries
codeql database analyze mydb \
--format=sarif-latest \
--output=results.sarif
# Upload to GitHub
codeql github upload-results \
--sarif=results.sarif---
Snyk
Vulnerability Priorities:
- Critical (9.0-10.0 CVSS): Fix immediately
- High (7.0-8.9): Fix within 7 days
- Medium (4.0-6.9): Fix within 30 days
- Low (0.1-3.9): Backlog
Reading Snyk Output:
{
"vulnerabilities": [
{
"title": "Prototype Pollution",
"severity": "high",
"packageName": "lodash",
"version": "4.17.15",
"fixedIn": ["4.17.21"],
"cvssScore": 7.4,
"cve": "CVE-2020-8203"
}
]
}Integration:
# Test for vulnerabilities
snyk test
# Test code (SAST)
snyk code test
# Fix vulnerabilities
snyk fix
# Monitor continuously
snyk monitor---
Language-Specific Patterns
TypeScript/JavaScript
Common Issues: 1. Unsafe type assertions
// 🔴 DANGEROUS
const data = response as UserData; // No runtime validation!
// ✅ SAFE
import { z } from 'zod';
const UserSchema = z.object({ id: z.string(), name: z.string() });
const data = UserSchema.parse(response); // Validates at runtime2. Promise rejection handling
// 🔴 UNHANDLED
fetchData().then(data => processData(data));
// ✅ HANDLED
fetchData()
.then(data => processData(data))
.catch(error => logger.error('Fetch failed:', error));---
React
Common Issues: 1. Missing dependency arrays
// 🔴 INFINITE LOOP RISK
useEffect(() => {
fetchData();
}); // Missing dependency array
// ✅ CORRECT
useEffect(() => {
fetchData();
}, []); // Empty array = run once2. Unnecessary re-renders
// 🔴 RE-RENDERS ON EVERY PARENT RENDER
<ExpensiveComponent data={data} />
// ✅ MEMOIZED
const MemoizedComponent = React.memo(ExpensiveComponent);
<MemoizedComponent data={data} />---
Node.js
Common Issues: 1. Blocking the event loop
// 🔴 BLOCKS EVENT LOOP
const data = fs.readFileSync('large-file.txt'); // Synchronous
// ✅ NON-BLOCKING
const data = await fs.promises.readFile('large-file.txt'); // Async2. Memory leaks in streams
// 🔴 LEAK
const stream = fs.createReadStream('file.txt');
// Missing error handler or close
// ✅ CORRECT
const stream = fs.createReadStream('file.txt');
stream.on('error', (err) => logger.error(err));
stream.on('close', () => cleanup());---
Security Testing Procedures
Manual Testing Checklist
Authentication Testing:
- [ ] Try accessing protected routes without authentication
- [ ] Try using expired tokens
- [ ] Try using tokens from different users
- [ ] Test account lockout after failed attempts
- [ ] Test password reset flow for vulnerabilities
Authorization Testing:
- [ ] Try accessing resources belonging to other users
- [ ] Try privilege escalation (regular user → admin)
- [ ] Test horizontal privilege escalation (user A → user B)
- [ ] Test direct object reference manipulation (change IDs in URLs)
Input Validation Testing:
- [ ] Test with extremely long inputs (> 10,000 chars)
- [ ] Test with special characters:
< > " ' ; / \` - [ ] Test with SQL metacharacters:
' OR '1'='1 - [ ] Test with XSS payloads:
<script>alert(1)</script> - [ ] Test with path traversal:
../../etc/passwd
---
Research Citations & Best Practices
OWASP Standards (Primary Sources)
OWASP Code Review Guide 2025
- URL: https://owasp.org/www-project-code-review-guide/
- Purpose: Official methodology for secure code review
- Key Contributions: Security-focused review procedures, vulnerability patterns
OWASP Top 10 2021 (Current Standard)
- URL: https://owasp.org/Top10/
- Purpose: Most critical web application security risks
- Updated: 2021 (next update expected 2025)
- Key Changes from 2017: New categories for insecure design, software integrity failures, SSRF
OWASP ASVS (Application Security Verification Standard)
- URL: https://owasp.org/www-project-application-security-verification-standard/
- Purpose: Testing requirements for web app security
- Levels: 1 (Opportunistic), 2 (Standard), 3 (Advanced)
---
CWE (Common Weakness Enumeration)
CWE Top 25 Most Dangerous Software Weaknesses (2024)
- URL: https://cwe.mitre.org/top25/
- Updated: Annually based on CVE data
- Key Weaknesses Referenced in This Skill:
- CWE-79: Cross-site Scripting (XSS)
- CWE-89: SQL Injection
- CWE-639: Authorization Bypass
- CWE-798: Use of Hard-coded Credentials
- CWE-287: Improper Authentication
- CWE-434: Unrestricted Upload of Dangerous File Type
---
Academic Research & Empirical Studies
1. Google Research: Code Review at Google (2018)
- Study: "Modern Code Review: A Case Study at Google"
- Sample Size: 9 million code reviews analyzed
- Key Findings:
- Median review latency: < 4 hours
- Optimal review size: 200-400 lines of code
- Small changes reviewed faster and more thoroughly
- 75% of changes get a response within 1 hour
- Citation: Sadowski et al., "Modern Code Review: A Case Study at Google," ICSE-SEIP 2018
- Relevance: Informed our recommendation for incremental reviews and review size limits
2. Microsoft Research: Code Reviews (2013)
- Study: "Expectations, Outcomes, and Challenges of Modern Code Review"
- Sample Size: 900+ developers surveyed, 17 teams
- Key Findings:
- Code review finds 60-70% of defects
- Best defect detection at 200-400 LOC
- Reviews improve code quality and knowledge sharing
- 10% of review time spent on style/naming issues
- Citation: Bacchelli & Bird, "Expectations, Outcomes, and Challenges of Modern Code Review," ICSE 2013
- Relevance: Established evidence base for code review effectiveness
3. Empirical Study: Security in Code Reviews (2024)
- Study: "An Empirical Study of Security Vulnerabilities in Code Reviews"
- URL: https://arxiv.org/html/2311.16396v2
- Sample Size: 135,560 code review comments analyzed
- Key Findings:
- Reviewers caught security issues in 35/40 CWE weakness categories
- Most missed: Memory errors (CWE-119), resource management (CWE-404)
- Security comments represent 2.5% of all review comments
- 92% faster vulnerability remediation with continuous review vs batch
- Citation: arXiv:2311.16396 [cs.SE]
- Relevance: Our 50% security focus and OWASP checklist address most-missed categories
4. IEEE: Automated SAST Tool Accuracy (2023)
- Study: "Comparative Analysis of Static Application Security Testing Tools"
- Sample Size: 1,200+ known vulnerabilities tested across 6 SAST tools
- Key Findings:
- CodeQL: 88% detection rate, 5% false positives
- Snyk: 85% detection rate, 8% false positives
- Semgrep: 82% detection rate, 12% false positives
- SonarQube: ~80% detection rate, 8-10% false positives
- No tool catches everything - manual review essential
- Relevance: Our tool accuracy benchmarks and recommendation to combine automated + manual review
5. NIST Secure Software Development Framework (SSDF)
- Document: NIST SP 800-218
- URL: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-218.pdf
- Purpose: Software development security practices
- Key Practices:
- PW.7: Review code before release
- PW.8: Reuse existing, verified components
- PW.9: Create hardened, secure build environments
- Relevance: Framework for DevSecOps practices integrated in this skill
---
Industry Best Practices
DevSecOps Automation Research
- Finding: Teams with continuous security review (integrated in CI/CD) fix vulnerabilities 92% faster
- Source: DevSecOps Community Survey 2024
- Implementation: Our quick-audit scripts for CI/CD integration
PCI-DSS Requirements (Payment Card Industry)
- Requirement 6.3.2: Code review before release to production
- Requirement 6.5: Address common coding vulnerabilities (references OWASP Top 10)
- Relevance: Security review template includes PCI-DSS considerations
SOC 2 Type II Requirements
- CC7.1: Change management includes review before deployment
- CC7.2: System security involves secure development practices
- Relevance: Review reports support compliance documentation
---
SAST Tool Integration Research
Tool Selection Criteria (Based on 2023 Forrester Research) 1. Accuracy: Detection rate vs false positive rate 2. Speed: Time to scan (critical for CI/CD) 3. Coverage: Languages and frameworks supported 4. Integration: Developer workflow integration 5. Remediation: Actionable fix guidance
Recommended Tool Stack:
- CodeQL (GitHub) - Best for semantic analysis, SQL injection
- Snyk - Best for dependencies, real-time IDE feedback
- SonarQube - Best for comprehensive quality + security
- Semgrep - Best for custom rules, policy enforcement
- npm audit - Essential baseline for Node.js projects
---
Performance Pattern Research
N+1 Query Problem
- Study: "Database Performance Anti-Patterns" (2020)
- Impact: 10-100x slowdown depending on dataset size
- Detection: ORM query logs, APM tools
- Fix: Eager loading, batch queries
Algorithm Complexity
- Source: "Introduction to Algorithms" (CLRS, 4th Ed)
- Big-O Benchmarks:
- O(1): < 1ms for any dataset
- O(log n): Acceptable for large datasets
- O(n): Acceptable if unavoidable
- O(n log n): Only for sorting
- O(n²): Red flag for n > 100
- O(2ⁿ): Never acceptable in production
Memory Leak Patterns
- Study: "Memory Leak Detection in JavaScript" (2019)
- Common Causes:
- Event listeners not removed: 45% of leaks
- Closures holding large objects: 30%
- Unbounded caches: 15%
- Timers not cleared: 10%
---
Key Metrics to Track (Research-Based)
Mean Time to Remediate (MTTR)
- Industry Benchmark: < 7 days for high severity (Veracode State of Software Security 2024)
- Our Target: < 24 hours for critical, < 7 days for high
Defect Density
- Industry Average: 1-25 defects per 1000 LOC (varies by language)
- High-Quality Code: < 1.0 defects per 1000 LOC
- Our Target: < 1.0 defects per 1000 LOC
Review Coverage
- Google Standard: 100% of changed lines reviewed before merge
- Microsoft Standard: 95%+ code coverage with reviews
- Our Target: 100% of changed lines, 100% manual review for critical paths
---
Further Reading
Books
- "The Art of Software Security Assessment" by Dowd, McDonald, Schuh
- "Secure Programming with Static Analysis" by Chess & West
- "Code Complete" by Steve McConnell (Chapter on code reviews)
Standards
- ISO/IEC 27034 - Application Security
- ISO/IEC 25010 - Software Quality Model
- NIST SP 800-53 - Security Controls
Online Resources
- OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org/
- CWE/SANS Top 25: https://cwe.mitre.org/top25/
- Google's Engineering Practices: https://google.github.io/eng-practices/review/
---
This reference guide should be used alongside SKILL.md for comprehensive code reviews.
Last Updated: November 3, 2025 Version: 1.0
Research Sources:
- OWASP Code Review Guide 2025
- OWASP Top 10 2021
- CWE Top 25 (2024)
- Academic papers (Google, Microsoft, IEEE, arXiv)
- NIST Secure Software Development Framework
- Industry standards (PCI-DSS, SOC 2)
Bad Code Review Example (What NOT to Do)
This example shows a superficial, unhelpful code review that misses critical issues and provides no value.
---
Context
PR Title: Add user profile update endpoint Files Changed: 2 Lines Changed: +120/-15 Author: @developer Reviewer: @careless-reviewer
NOTE: This is the SAME PR as the good review example. Compare how differently it's handled!
---
❌ The Bad Review
Reviewer's Comment
Looks good! LGTM 👍
>
Verdict: ✅ APPROVED
---
🚫 Why This Review is Terrible
Let me count the ways this review fails...
---
❌ Problem 1: No Specificity
What the reviewer said:
"Looks good!"
What's wrong:
- Doesn't say WHAT looks good
- Doesn't say WHAT was checked
- Provides zero evidence of actual review
What SHOULD have been said:
"I reviewed the authentication logic, input validation, and test coverage. The authorization check on line 45 properly prevents users from updating other profiles, and the 88% test coverage is excellent."
---
❌ Problem 2: Missed Critical Security Issue
What the code has:
router.put('/profile/:userId', authenticateUser, async (req, res) => {
// NO RATE LIMITING!
const updated = await updateUserProfile(req.params.userId, req.body);
res.json(updated);
});What the reviewer said: Nothing. Didn't catch it.
Impact of Missing This:
- Attackers can spam profile updates
- DoS vulnerability
- No protection against abuse
- Will cause production issues
What SHOULD have been caught: "Missing rate limiting on this endpoint. Add rate limiter to prevent abuse (5 updates per 15 minutes recommended)."
---
❌ Problem 3: Missed Performance Issue
What the code has:
async getUserWithPreferences(userId: string) {
const user = await User.findOne({ where: { id: userId } });
const preferences = await Preferences.find({ where: { userId } });
// N+1 query pattern!
return { ...user, preferences };
}What the reviewer said: Nothing. Didn't notice.
Impact of Missing This:
- Slow API responses
- Database load increases
- Will get worse as users grow
- Could cause scaling issues
What SHOULD have been caught: "N+1 query detected. Use TypeORM relations to fetch in single query for 40% performance improvement."
---
❌ Problem 4: No Evidence of Testing
What the reviewer SHOULD have done:
# Pull the branch
git checkout feature/profile-update
# Run tests
npm test
# Check coverage
npm run test:coverage
# Try the endpoint
curl -X PUT http://localhost:3000/api/profile/123 \
-H "Authorization: Bearer $TOKEN" \
-d '{"email":"test@example.com"}'What the reviewer actually did: 🤷♂️ Unknown. Probably just glanced at the code.
---
❌ Problem 5: No Actionable Feedback
What was provided:
- "LGTM" (Looks Good To Me)
- A thumbs up emoji
What's missing:
- No specific comments
- No improvement suggestions
- No educational value
- Nothing for the author to learn from
Compare to a good review:
- "Great work on the authorization logic!"
- "Consider adding DTOs for validation"
- "Fix the N+1 query before merge"
---
❌ Problem 6: Rubber Stamp Approval
What happened: Reviewer approved without actually reviewing.
Signs of rubber stamping:
- ✅ Instant approval (< 2 minutes for 120 lines)
- ✅ Generic praise ("looks good")
- ✅ No specific comments
- ✅ No questions asked
- ✅ No code snippets referenced
Impact:
- Bugs ship to production
- Security vulnerabilities not caught
- Team loses trust in code review process
- Technical debt accumulates
---
🎯 Direct Comparison
Same PR, Two Reviews
| Aspect | Bad Review | Good Review |
|---|---|---|
| Time spent | < 2 minutes | 12 minutes |
| Issues found | 0 | 2 medium, 2 low |
| Security checks | None | OWASP Top 10 |
| Performance analysis | None | Found N+1 query |
| Specificity | None | File:line numbers |
| Code snippets | None | Problem + solution |
| Educational value | Zero | High |
| Author learns | Nothing | Multiple best practices |
| Verdict | ✅ APPROVED | ⚠️ APPROVED WITH RESERVATIONS |
| Production risk | HIGH | LOW (after fixes) |
---
💣 Real-World Consequences of Bad Reviews
What Happened After This Bad Review
Week 1:
Production deployed ✅
No immediate issues 😊Week 2:
⚠️ API response times increasing
⚠️ Database load spiking
⚠️ Users complaining about slow profile updatesWeek 3:
🔴 Attacker discovers no rate limiting
🔴 Spam attack: 10,000 profile updates in 5 minutes
🔴 Database overloaded
🔴 Site goes down for 2 hoursWeek 4:
💰 Incident post-mortem
💰 Lost revenue: $50,000
💰 Engineer time: 40 hours debugging
💰 Customer support: 200 tickets
😞 Customer trust damagedTotal cost of "LGTM" review: > $75,000
Time to add rate limiting: 10 minutes
---
🛡️ How to Avoid Being This Reviewer
Minimum Review Checklist
Before approving ANY PR, you MUST:
1. Pull and run the code
git checkout feature-branch
npm install
npm test2. Run automated tools
npm audit
npm run lint
npm run type-check3. Check security (2 minutes)
- Authentication/authorization present?
- User input validated?
- No hardcoded secrets?
4. Check performance (2 minutes)
- Any N+1 queries?
- Nested loops over large data?
- Database indexes present?
5. Check code quality (2 minutes)
- Tests present and passing?
- No console.log statements?
- TypeScript strict mode?
6. Provide specific feedback
- File:line references
- Code snippets
- Specific suggestions
Total time: 8-15 minutes for typical PR
Value delivered: Prevents production issues, educates team, improves code quality
---
🎓 Learning Exercise
Try This:
1. Read the Good Review Example 2. Note what the good reviewer found 3. Look at this bad review again 4. See how much value was lost?
Ask Yourself:
- Would I want my name on this review?
- Would I trust this reviewer with my production code?
- Am I sometimes this reviewer?
Be honest: We've all done quick "LGTM" reviews. The goal is to do better.
---
✅ The Fix: How to Do Better
Time Investment
Bad review: 2 minutes → $75,000 production incident
Good review: 12 minutes → Issues caught before production
ROI: 6x time investment, infinite value
---
Quick Improvement Plan
Week 1: Commit to running automated tools
npm audit && npm run lint && npm testWeek 2: Add security checklist
- Check for hardcoded secrets
- Verify authentication/authorization
- Review input validation
Week 3: Add performance checklist
- Look for N+1 queries
- Check algorithm complexity
- Review database queries
Week 4: Provide specific feedback
- Use file:line format
- Include code snippets
- Suggest improvements
---
💡 Remember
Bad reviews are worse than no reviews.
Why?
- Creates false confidence ("it was reviewed")
- Issues slip through
- Author doesn't learn
- Team culture suffers
Good reviews:
- Catch issues early
- Educate the team
- Improve code quality
- Build trust
---
🎯 Key Takeaways
❌ DON'T:
- Rubber stamp with "LGTM"
- Approve without running code
- Skip security checks
- Provide vague feedback
- Rush through reviews
✅ DO:
- Run automated tools
- Check OWASP Top 10
- Analyze performance
- Provide specific feedback
- Take time to do it right
---
The Bottom Line:
If you don't have time to review properly, say so:
"I don't have bandwidth for a thorough review right now. Can someone else take this, or should we wait until tomorrow when I can give it proper attention?"
This is infinitely better than a rushed, bad review.
---
Remember: Your name on an approval means "I've verified this is safe and ready for production." Own it. 🛡️
Good Code Review Example
This example demonstrates a thorough, constructive code review that follows all best practices.
---
Context
PR Title: Add user profile update endpoint Files Changed: 2 Lines Changed: +120/-15 Author: @developer Reviewer: @senior-dev
---
The Review
Initial Comment
Thanks for working on this feature! I've done a comprehensive review covering security, performance, and code quality. Overall this is solid work with good test coverage. I found two medium-priority issues that should be addressed before merge, and some minor suggestions for improvement.
>
Estimated fix time: 20 minutes
---
🟡 Medium Priority Issues
1. Missing Rate Limiting on Profile Update Endpoint
Location: src/api/profile.ts:45-60
Issue: The profile update endpoint doesn't have rate limiting, which could allow abuse (spam profile updates, DoS).
Current Code:
router.put('/profile/:userId', authenticateUser, async (req, res) => {
// No rate limiting here
const updated = await updateUserProfile(req.params.userId, req.body);
res.json(updated);
});Recommendation:
import rateLimit from 'express-rate-limit';
const profileUpdateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 updates per 15 minutes
message: 'Too many profile updates, please try again later'
});
router.put('/profile/:userId',
profileUpdateLimiter, // Add rate limiter
authenticateUser,
async (req, res) => {
const updated = await updateUserProfile(req.params.userId, req.body);
res.json(updated);
}
);Why This Matters:
- Prevents abuse/spam
- Protects against DoS attacks
- Industry standard: 5-10 updates per 15 minutes is reasonable
Severity: 🟡 Medium Category: Security OWASP: A04:2021 - Insecure Design
References:
---
2. N+1 Query When Fetching User with Preferences
Location: src/services/userService.ts:78-85
Issue: When fetching a user with their preferences, the code makes separate queries instead of using a JOIN.
Current Code:
async getUserWithPreferences(userId: string) {
const user = await User.findOne({ where: { id: userId } });
const preferences = await Preferences.find({ where: { userId } });
return { ...user, preferences };
}Performance Impact:
- Current: 2 queries per user
- If called in a loop for 100 users: 200 queries (N+1 problem)
Recommendation:
async getUserWithPreferences(userId: string) {
const user = await User.findOne({
where: { id: userId },
relations: ['preferences'] // Use TypeORM relations
});
return user;
}Why This Matters:
- Reduces database load
- Improves response time (1 query vs 2)
- Prevents scaling issues if called in loops
Severity: 🟡 Medium Category: Performance
Benchmark (estimated):
- Current: ~20ms per call
- Optimized: ~12ms per call (40% faster)
---
🔵 Low Priority Suggestions
3. Consider Using DTOs for Request Validation
Location: src/api/profile.ts:50
Current:
const { email, bio, avatar } = req.body;
// Manual validation scattered throughout
if (!email || !isValidEmail(email)) { ... }
if (bio && bio.length > 500) { ... }Suggestion:
import { IsEmail, MaxLength, IsOptional } from 'class-validator';
class UpdateProfileDto {
@IsEmail()
email: string;
@MaxLength(500)
@IsOptional()
bio?: string;
@IsOptional()
avatar?: string;
}
// In route
router.put('/profile/:userId', validateDto(UpdateProfileDto), async (req, res) => {
// req.body is now typed and validated
});Benefits:
- Centralized validation logic
- Type safety
- Self-documenting API
- Easier to maintain
Not Required For: This change, but consider for future endpoints
---
4. Typo in Comment
Location: src/services/userService.ts:82
// Retrives user preferences from database ← "Retrives" should be "Retrieves"Minor fix while you're in there! 😊
---
✅ Strengths & Good Practices
Really nice work on several fronts:
✅ Excellent test coverage (88%)
- Unit tests for all service functions
- Integration tests for API endpoints
- Edge cases covered (invalid email, missing fields)
✅ Proper authorization
if (req.user.id !== req.params.userId) {
return res.status(403).json({ error: 'Forbidden' });
}Good catch preventing users from updating other users' profiles!
✅ Input validation
- Email format validated
- Bio length limited
- XSS prevented with sanitization
✅ Error handling
try {
// ... update logic
} catch (error) {
logger.error('Profile update failed', { userId, error });
res.status(500).json({ error: 'Update failed' });
}Proper logging without exposing sensitive details to user.
✅ TypeScript strict mode
- No
anytypes - All functions typed
- Good interface definitions
---
📊 Review Summary
OWASP Top 10 Check:
- ✅ A01 - Access Control: Proper authorization
- ⚠️ A04 - Insecure Design: Missing rate limiting (fix needed)
- ✅ A03 - Injection: Parameterized queries
- ✅ A07 - Authentication: Session validation present
Performance Check:
- ⚠️ N+1 query pattern (fix recommended)
- ✅ No O(n²) algorithms
- ✅ Efficient database queries elsewhere
Code Quality:
- ✅ Test coverage: 88%
- ✅ TypeScript: Strict mode
- ✅ Functions < 50 lines
- ✅ Proper error handling
Metrics:
- Files Modified: 2
- Lines Changed: +120/-15
- Estimated Risk: 🟡 Medium (due to auth changes)
- Review Duration: 12 minutes
---
📋 Action Items
Before Merge: 1. Add rate limiting to profile update endpoint (10 min) 2. Fix N+1 query with TypeORM relations (10 min)
Optional (can do after merge): 3. Consider DTO pattern for validation (technical debt ticket) 4. Fix typo in comment (1 min - might as well do it)
Total Required Fix Time: ~20 minutes
---
✅ Verdict
Status: ⚠️ APPROVED WITH RESERVATIONS
This is well-written code with good practices. The two medium-priority issues are straightforward fixes that will improve security and performance. Once those are addressed, this is ready to merge.
Great work on the test coverage and authorization logic! 👏
---
Next Steps: 1. Author: Implement rate limiting and fix N+1 query 2. Author: Push fixes to PR 3. Reviewer: Quick re-review (5 min) to verify fixes 4. Merge!
---
What Makes This a Good Review
✅ Good Practices Demonstrated
1. Specific and Actionable
- Exact file and line numbers
- Code snippets showing problem AND solution
- Clear explanation of why it matters
2. Balanced Feedback
- Found real issues (rate limiting, N+1 query)
- Acknowledged strengths (test coverage, authorization)
- Provided suggestions, not just criticism
3. Severity Classification
- Medium issues blocking merge
- Low priority suggestions for future
- Clear about what's required vs nice-to-have
4. Educational
- Explained why changes matter
- Provided links to OWASP documentation
- Showed performance impact with estimates
5. Constructive Tone
- "Thanks for working on this feature!"
- "Really nice work on several fronts"
- Used emojis appropriately to keep it friendly
6. Clear Next Steps
- Specific action items with time estimates
- Clear verdict (approved with reservations)
- Process for how to proceed
7. Thorough Coverage
- Security (OWASP Top 10)
- Performance (N+1 queries)
- Code quality (TypeScript, tests)
- Multiple severity levels
---
Key Takeaways
A good review:
- ✅ Finds real issues
- ✅ Provides specific fixes
- ✅ Acknowledges good work
- ✅ Classifies severity
- ✅ Is actionable and clear
- ✅ Maintains constructive tone
- ✅ Educates the author
Review time: 12 minutes for thorough, valuable feedback Author fix time: 20 minutes Total time saved: Countless hours debugging production issues
---
Remember: The goal is to ship quality code, not to find fault. Good reviews make both the code and the team better.
Code Review Report: [Feature/PR Name]
Reviewed by: [Your Name] Date: [YYYY-MM-DD] Commit/PR: [#123 or commit hash] Review Type: [Standard | Security Audit | Performance Review | Pre-Deployment]
---
Executive Summary
Verdict: ✅ APPROVED | ⚠️ APPROVED WITH RESERVATIONS | ❌ REQUIRES REVISION
Overview: [2-3 sentence summary of what was reviewed and overall quality]
Key Metrics:
- Files Modified: X
- Lines Changed: +Y/-Z
- Estimated Risk: 🟢 Low | 🟡 Medium | 🔴 High
- Test Coverage: X% (target: >80%)
- Review Duration: X minutes
---
Critical Issues (Blocking - Must Fix Before Merge)
[If none, write "None identified ✅"]
Issue Title 🔴
Location: file.ts:line
Issue:
[Code snippet showing the problem]Why This is Critical: [Explanation of the security/functional impact]
Recommendation:
[Code snippet showing the fix]Severity: 🔴 Critical Category: [Security | Performance | Functionality] OWASP/CWE: [If applicable]
---
High Priority Issues (Fix Within 48 Hours)
[If none, write "None identified ✅"]
Issue Title 🟠
Location: file.ts:line
Issue: [Description]
Recommendation: [Specific fix with code example if needed]
Severity: 🟠 High Category: [Security | Performance | Code Quality]
---
Medium Priority Issues (Fix This Sprint)
[If none, write "None identified ✅"]
Issue Title 🟡
Location: file.ts:line
Issue: [Description]
Recommendation: [Specific fix]
Severity: 🟡 Medium
---
Low Priority / Suggestions (Backlog)
[If none, write "None identified ✅"]
Issue Title 🔵
Location: file.ts:line
Suggestion: [Description and recommendation]
---
Strengths & Good Practices
✅ [What was done well - be specific] ✅ [Good patterns observed] ✅ [Security best practices followed] ✅ [Performance optimizations]
---
Detailed Analysis
Security Review (OWASP Top 10)
- A01 - Broken Access Control: [Status]
- A02 - Cryptographic Failures: [Status]
- A03 - Injection: [Status]
- A07 - Authentication Failures: [Status]
- A05 - Security Misconfiguration: [Status]
Performance Analysis
- Database Queries: [No N+1 issues | Issues found]
- Algorithm Complexity: [O(n) | Issues found]
- Memory Usage: [Efficient | Concerns noted]
Code Quality
- TypeScript Compliance: [Strict mode | Issues]
- Test Coverage: [X%]
- Complexity: [Functions < 50 lines | Issues]
- Error Handling: [Proper | Missing in places]
---
SAST Tool Results
[If tools were run, include results]
npm audit
- Critical: X
- High: Y
- Medium: Z
ESLint
- Errors: X
- Warnings: Y
TypeScript
- Type Errors: X
---
Recommendations Summary
Before Merge: 1. [Action item with estimated time] 2. [Action item with estimated time]
After Merge (Follow-up): 1. [Optional improvement] 2. [Optional refactoring]
Total Estimated Fix Time: X hours/minutes
---
Next Steps
If Approved (✅): 1. Merge the PR 2. Monitor deployment 3. Update metrics
If Approved with Reservations (⚠️): 1. Fix critical/high issues 2. Re-review changes 3. Merge when fixes confirmed
If Requires Revision (❌): 1. Author: Address all critical issues 2. Author: Push fixes 3. Reviewer: Full re-review required
---
Sign-off
Status: [✅ APPROVED | ⚠️ APPROVED WITH RESERVATIONS | ❌ REQUIRES REVISION]
[Final summary paragraph with overall assessment and confidence level]
Reviewer Signature: [Your Name] Date: [YYYY-MM-DD]
Performance-Focused Code Review: [Feature/PR Name]
Reviewed by: [Your Name] Date: [YYYY-MM-DD] Commit/PR: [#123 or commit hash] Review Type: Performance Review
---
Executive Summary
Performance Verdict: ✅ OPTIMAL | ⚠️ NEEDS OPTIMIZATION | ❌ CRITICAL ISSUES
Performance Risk: 🟢 Low | 🟡 Medium | 🔴 High
Overview: [Brief assessment of performance characteristics]
Critical Issues: X Optimization Opportunities: Y
---
Database Performance
Query Analysis
N+1 Query Detection:
- [ ] No N+1 query patterns found
- [ ] Relationships properly eager-loaded
- [ ] Batch queries used where appropriate
Findings: [List any N+1 issues with location and fix]
---
Index Coverage:
- [ ] All queried columns have indexes
- [ ] Foreign keys indexed
- [ ] Composite indexes for multi-column queries
Missing Indexes: [List any missing indexes]
Recommendation:
CREATE INDEX idx_table_column ON table(column);---
Query Complexity:
- [ ] No queries returning > 1000 rows without pagination
- [ ] JOINs limited to < 5 tables
- [ ] Subqueries optimized
Slow Queries Found: [List queries that need optimization]
---
Algorithm Complexity
Time Complexity Analysis
Function: [functionName] at file.ts:line
Current Complexity: O(n²) | O(n log n) | O(n) | O(1)
Analysis:
// Current implementation
[Code snippet]Issue: [Explanation of performance problem]
Optimized Version: O([complexity])
// Optimized implementation
[Code snippet]Impact:
- Small dataset (n < 100): [negligible | minor | significant]
- Medium dataset (n < 1000): [negligible | minor | significant]
- Large dataset (n > 1000): [negligible | minor | significant]
---
Memory Usage
Memory Leak Detection
Potential Leaks:
- [ ] No unbounded caches
- [ ] Event listeners cleaned up
- [ ] Closures don't hold large objects
- [ ] Timers/intervals cleared
Issues Found: [List memory leak risks]
---
Memory Allocation
Large Object Analysis:
- [ ] No unnecessary object cloning
- [ ] Streaming used for large data
- [ ] Pagination for large lists
Findings: [List memory-heavy operations]
---
Bundle Size Impact
Frontend Bundle Analysis
Files Modified:
file1.tsx- +X KBfile2.tsx- +Y KB
Total Impact: +Z KB
Bundle Budget: [Current: X KB] [Budget: Y KB] [Status: ✅ Within | ⚠️ Near Limit | ❌ Exceeded]
Optimization Opportunities:
- [ ] Dynamic imports for code splitting
- [ ] Tree shaking enabled
- [ ] Remove unused dependencies
- [ ] Optimize images/assets
Recommendations:
// Use dynamic imports
const HeavyComponent = lazy(() => import('./HeavyComponent'));---
Frontend Performance
Rendering Performance
React Component Analysis:
Component: [ComponentName]
Issues:
- [ ] Unnecessary re-renders
- [ ] Missing React.memo
- [ ] Expensive calculations not memoized
- [ ] No virtualization for long lists
Current:
// Current implementation
[Code snippet showing problem]Optimized:
// Optimized with useMemo/useCallback
[Code snippet showing fix]---
Network Performance
API Calls:
- [ ] No excessive API calls
- [ ] Request caching implemented
- [ ] Debouncing on user inputs
- [ ] Response compression enabled
Findings: [List API performance issues]
---
Asset Loading
Images:
- [ ] Images optimized (WebP format)
- [ ] Responsive images used
- [ ] Lazy loading implemented
- [ ] Proper sizing (no oversized images)
Fonts:
- [ ] Font loading optimized
- [ ] System fonts as fallback
- [ ] Font subsetting used
JavaScript:
- [ ] Code splitting implemented
- [ ] Critical JS inlined
- [ ] Non-critical JS deferred
Findings: [List asset optimization opportunities]
---
Load Testing Results
Performance Metrics
Before Changes:
- Response Time (p50): X ms
- Response Time (p95): Y ms
- Response Time (p99): Z ms
- Throughput: X req/sec
- Error Rate: Y%
After Changes (Projected):
- Response Time (p50): X ms
- Response Time (p95): Y ms
- Response Time (p99): Z ms
- Throughput: X req/sec
- Error Rate: Y%
Impact: [Improved by X% | Degraded by Y% | No significant change]
---
Lighthouse/Core Web Vitals
Metrics
First Contentful Paint (FCP):
- Current: X s
- Target: < 1.8s
- Status: [✅ Pass | ⚠️ Needs Improvement | ❌ Fail]
Largest Contentful Paint (LCP):
- Current: X s
- Target: < 2.5s
- Status: [✅ Pass | ⚠️ Needs Improvement | ❌ Fail]
Time to Interactive (TTI):
- Current: X s
- Target: < 3.8s
- Status: [✅ Pass | ⚠️ Needs Improvement | ❌ Fail]
Total Blocking Time (TBT):
- Current: X ms
- Target: < 200ms
- Status: [✅ Pass | ⚠️ Needs Improvement | ❌ Fail]
Cumulative Layout Shift (CLS):
- Current: X
- Target: < 0.1
- Status: [✅ Pass | ⚠️ Needs Improvement | ❌ Fail]
---
Overall Performance Assessment
Critical Performance Issues 🔴
[List issues that will significantly degrade user experience]
High Priority Optimizations 🟠
[List optimizations that will provide noticeable improvement]
Medium Priority Optimizations 🟡
[List nice-to-have optimizations]
---
Recommendations
Immediate Actions (Before Merge)
1. [Fix with estimated time] 2. [Fix with estimated time]
Short-term (Within Sprint)
1. [Optimization] 2. [Optimization]
Long-term (Technical Debt)
1. [Refactoring opportunity] 2. [Architecture improvement]
Total Optimization Time: X hours
---
Performance Testing Plan
Before Merge:
- [ ] Load test with [X] concurrent users
- [ ] Memory profiling
- [ ] Bundle size analysis
- [ ] Lighthouse audit
After Deployment:
- [ ] Monitor response times
- [ ] Watch for memory leaks
- [ ] Track Core Web Vitals
- [ ] Set up alerts
---
Performance Sign-off
Performance Status: [✅ APPROVED | ⚠️ CONDITIONAL APPROVAL | ❌ REQUIRES OPTIMIZATION]
Conditions (if conditional):
- [List performance improvements required]
Monitoring Plan:
- [What metrics to monitor post-deployment]
Reviewer: [Your Name] Date: [YYYY-MM-DD]
Quick Code Review Checklist (3 Minutes)
Use this for rapid reviews of small changes or pre-commit checks.
---
Security (30 seconds) 🔒
- [ ] No hardcoded secrets/API keys - Check for
api_key,password,secretin code - [ ] User input sanitized/validated - All user inputs go through validation
- [ ] Authentication on protected routes - Middleware present on all protected endpoints
- [ ] No SQL injection - Parameterized queries only, no string concatenation
- [ ] Passwords hashed - bcrypt/argon2 used (not MD5/SHA1)
Quick command:
git diff --staged | grep -i "api_key\|password\|secret"---
Performance (30 seconds) ⚡
- [ ] No N+1 query patterns - No loops containing database queries
- [ ] No nested loops over large datasets - Check for O(n²) algorithms
- [ ] Database indexes present - Queried columns have indexes
- [ ] No synchronous file operations - Use async/await for I/O
Quick check: Look for:
forEachormapcontainingawait db.query- Nested
forloops fs.readFileSyncin Node.js
---
Code Quality (60 seconds) ✨
- [ ] TypeScript strict mode - No
anytypes without justification - [ ] Functions < 50 lines - Extract larger functions
- [ ] No commented-out code - Remove dead code
- [ ] Proper error handling - No empty
catchblocks - [ ] No console.log statements - Use proper logging library
Quick command:
# Find console.logs
git diff --staged | grep "console.log"
# Find any types
git diff --staged | grep ": any"---
Tests (30 seconds) 🧪
- [ ] Unit tests present - New code has corresponding tests
- [ ] Test coverage > 80% - Check coverage report
- [ ] Edge cases tested - Not just happy path
- [ ] Tests pass locally - Run test suite before review
Quick command:
npm test
npm run test:coverage---
Documentation (30 seconds) 📚
- [ ] Complex logic has comments - Explain the "why", not the "what"
- [ ] README updated - If behavior changed or new features added
- [ ] Public APIs have JSDoc - Functions exported have documentation
Quick check:
- Are there functions > 20 lines without any comments?
- Did public API change? Is it documented?
---
Total Time: 3 minutes ⏱️
---
Quick Pass/Fail Criteria
❌ Immediate Fail (Stop Review)
If you find ANY of these:
- Hardcoded API keys or passwords
- SQL injection vulnerability (string concatenation in queries)
- XSS vulnerability (unescaped user input in HTML)
- Authentication bypass
- Plain text password storage
Action: Reject immediately. Security takes priority.
---
⚠️ Conditional Pass (Requires Fixes)
If you find:
- Missing tests for new code
- console.log statements
anytypes- No error handling
- Functions > 50 lines
Action: Request changes before merge.
---
✅ Pass
If:
- All checklist items pass
- No security vulnerabilities
- Tests present and passing
- Code is readable and maintainable
Action: Approve and merge.
---
When to Do a Full Review
Use the full code review process (15-30 minutes) instead of this quick checklist if:
- Changes affect authentication or authorization
- Changes handle sensitive data (PII, payment info, health data)
- Changes affect critical user flows
- Changes are > 400 lines
- Changes touch database migrations
- Pre-deployment security audit
For these cases, see:
code-review-report.mdfor comprehensive reviewssecurity-review-template.mdfor security auditsperformance-review-template.mdfor performance reviews
---
Tips for Fast Reviews
1. Use git diff - Review only what changed 2. Run automated tools first - Let tools catch obvious issues 3. Focus on critical paths - Authentication, authorization, data handling 4. Trust but verify - Good test coverage lets you move faster 5. Know when to go deep - Some changes deserve more time
---
Remember: This is a screening tool, not a replacement for thorough code review. Use your judgment on when to go deeper.
Security-Focused Code Review: [Feature/PR Name]
Reviewed by: [Your Name] Date: [YYYY-MM-DD] Commit/PR: [#123 or commit hash] Review Type: Security Audit
---
Executive Summary
Security Verdict: ✅ SECURE | ⚠️ MINOR ISSUES | ❌ CRITICAL VULNERABILITIES
Risk Level: 🟢 Low | 🟡 Medium | 🔴 High
Overview: [Brief assessment of security posture]
Critical Vulnerabilities: X High Priority Issues: Y Medium Priority Issues: Z
---
OWASP Top 10 2021 Detailed Check
A01:2021 – Broken Access Control
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Authentication required on protected routes
- [ ] Authorization validates user permissions
- [ ] Direct object references protected (IDOR prevention)
- [ ] Path traversal prevented
- [ ] CORS configured correctly
Findings: [List any issues found with severity and location]
---
A02:2021 – Cryptographic Failures
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Sensitive data encrypted at rest
- [ ] Sensitive data encrypted in transit (HTTPS)
- [ ] Passwords hashed with bcrypt/argon2
- [ ] API keys/secrets in environment variables
- [ ] No hardcoded credentials
Findings: [List any issues]
---
A03:2021 – Injection
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Parameterized queries used (no string concatenation)
- [ ] Input validation on all user inputs
- [ ] ORM used correctly (no raw queries with user input)
- [ ] Command injection prevented
- [ ] NoSQL injection prevented
Findings: [List any issues]
---
A04:2021 – Insecure Design
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Threat modeling performed
- [ ] Secure by default
- [ ] Defense in depth
- [ ] Fail securely
- [ ] Separation of duties
Findings: [List any issues]
---
A05:2021 – Security Misconfiguration
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Security headers configured (CSP, HSTS, X-Frame-Options)
- [ ] Error messages don't leak information
- [ ] Default credentials changed
- [ ] Unnecessary features disabled
- [ ] Software up to date
Findings: [List any issues]
---
A06:2021 – Vulnerable and Outdated Components
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] npm audit shows no critical/high vulnerabilities
- [ ] Dependencies up to date
- [ ] Known vulnerable components not used
- [ ] Component versions tracked
Findings: [npm audit results]
---
A07:2021 – Identification and Authentication Failures
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Multi-factor authentication available
- [ ] Password requirements enforced
- [ ] Session management secure
- [ ] Rate limiting on authentication endpoints
- [ ] Account lockout after failed attempts
Findings: [List any issues]
---
A08:2021 – Software and Data Integrity Failures
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Code signature verification
- [ ] Dependency integrity checks
- [ ] No unsigned/unverified plugins
- [ ] CI/CD pipeline secured
Findings: [List any issues]
---
A09:2021 – Security Logging and Monitoring Failures
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] Authentication failures logged
- [ ] Authorization failures logged
- [ ] High-value transactions logged
- [ ] Logs protected from tampering
- [ ] Alerting on suspicious activity
Findings: [List any issues]
---
A10:2021 – Server-Side Request Forgery (SSRF)
Status: ✅ Pass | ⚠️ Minor Issues | ❌ Vulnerabilities Found
Checks Performed:
- [ ] URL validation on user-supplied URLs
- [ ] Network segmentation
- [ ] Whitelist of allowed domains
- [ ] Internal IP ranges blocked
Findings: [List any issues]
---
Threat Modeling
Attack Surface Analysis
External Endpoints:
- [List public-facing endpoints]
Authentication Methods:
- [List auth methods used]
Sensitive Data Handled:
- [List types of sensitive data]
Potential Attack Vectors
1. [Attack Vector Name]
- Likelihood: High | Medium | Low
- Impact: High | Medium | Low
- Mitigation: [Current controls]
---
Security Test Results
Automated Testing
- SAST Tool: [Tool name and version]
- Results: [Summary]
Manual Testing
- Penetration Testing: [If performed]
- Code Review: [Findings]
---
Compliance Checklist
Applicable Standards:
- [ ] PCI-DSS (if handling payments)
- [ ] HIPAA (if handling health data)
- [ ] GDPR (if handling EU citizen data)
- [ ] SOC 2 (if SaaS application)
Findings: [List any compliance issues]
---
Overall Security Assessment
Risk Summary
Critical Risks: X
- [List critical vulnerabilities]
High Risks: Y
- [List high priority issues]
Medium Risks: Z
- [List medium issues]
Recommendations
Immediate Actions (Critical): 1. [Action with timeline] 2. [Action with timeline]
Short-term (Within 7 days): 1. [Action] 2. [Action]
Long-term (Within 30 days): 1. [Action] 2. [Action]
---
Security Sign-off
Security Status: [✅ APPROVED | ⚠️ CONDITIONAL APPROVAL | ❌ REJECTED]
Conditions (if conditional):
- [List conditions that must be met]
Next Security Review: [Date or trigger]
Reviewer: [Your Name] Date: [YYYY-MM-DD]
@echo off
REM Quick Security Audit Script (Windows)
REM Runs basic SAST tools available in most Node.js projects
REM Usage: scripts\quick-audit.bat
echo Running Quick Security Audit...
echo =================================
echo.
setlocal enabledelayedexpansion
set CRITICAL_ISSUES=0
set HIGH_ISSUES=0
REM 1. npm audit
echo Running npm audit...
where npm >nul 2>nul
if %ERRORLEVEL% EQU 0 (
npm audit --audit-level=high
if !ERRORLEVEL! EQU 0 (
echo [32mNo high/critical vulnerabilities found[0m
) else (
echo [31mnpm audit found vulnerabilities[0m
set /a CRITICAL_ISSUES+=1
)
) else (
echo [33mnpm not found, skipping[0m
)
echo.
REM 2. ESLint
echo Running ESLint...
where npx >nul 2>nul
if %ERRORLEVEL% EQU 0 (
if exist ".eslintrc.js" (
npx eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 10
if !ERRORLEVEL! EQU 0 (
echo [32mESLint passed[0m
) else (
echo [31mESLint found issues[0m
set /a HIGH_ISSUES+=1
)
) else (
echo [33mESLint not configured, skipping[0m
)
) else (
echo [33mnpx not found, skipping[0m
)
echo.
REM 3. Prettier check
echo Running Prettier...
where npx >nul 2>nul
if %ERRORLEVEL% EQU 0 (
if exist ".prettierrc" (
npx prettier --check . 2>nul
if !ERRORLEVEL! EQU 0 (
echo [32mCode formatting is consistent[0m
) else (
echo [33mCode formatting inconsistencies found (auto-fixable)[0m
echo Run: npx prettier --write .
)
) else (
echo [33mPrettier not configured, skipping[0m
)
) else (
echo [33mnpx not found, skipping[0m
)
echo.
REM 4. TypeScript type check
echo Running TypeScript type check...
where npx >nul 2>nul
if %ERRORLEVEL% EQU 0 (
if exist "tsconfig.json" (
npx tsc --noEmit
if !ERRORLEVEL! EQU 0 (
echo [32mTypeScript type check passed[0m
) else (
echo [31mTypeScript type errors found[0m
set /a HIGH_ISSUES+=1
)
) else (
echo [33mTypeScript not configured, skipping[0m
)
) else (
echo [33mnpx not found, skipping[0m
)
echo.
REM 5. Check for hardcoded secrets (basic findstr)
echo Checking for hardcoded secrets...
findstr /S /I /R "api_key.*=.*[\"'][a-zA-Z0-9]\{20,\}[\"'] password.*=.*[\"'][a-zA-Z0-9]\{20,\}[\"'] secret.*=.*[\"'][a-zA-Z0-9]\{20,\}[\"']" src\*.* 2>nul
if !ERRORLEVEL! EQU 0 (
echo [31mPotential hardcoded secrets found![0m
echo Review the files above and move secrets to environment variables
set /a CRITICAL_ISSUES+=1
) else (
echo [32mNo obvious hardcoded secrets detected[0m
)
echo.
REM Final summary
echo =================================
echo Audit Summary
echo =================================
echo.
if !CRITICAL_ISSUES! GTR 0 (
echo [31mCRITICAL ISSUES: !CRITICAL_ISSUES![0m
echo Must be fixed before deployment
)
if !HIGH_ISSUES! GTR 0 (
echo [33mHIGH PRIORITY ISSUES: !HIGH_ISSUES![0m
echo Should be fixed within 48 hours
)
if !CRITICAL_ISSUES! EQU 0 if !HIGH_ISSUES! EQU 0 (
echo [32mALL CHECKS PASSED[0m
echo Code is ready for review
)
echo.
echo For detailed analysis, consider running:
echo - sonar-scanner (if SonarQube configured)
echo - codeql database analyze (if CodeQL installed)
echo - snyk test (if Snyk configured)
echo.
REM Exit with error code if critical issues found
if !CRITICAL_ISSUES! GTR 0 exit /b 1
exit /b 0
#!/bin/bash
# Quick Security Audit Script
# Runs basic SAST tools available in most Node.js projects
# Usage: bash scripts/quick-audit.sh
set -e
echo "🔍 Running Quick Security Audit..."
echo "================================="
echo ""
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Track overall status
CRITICAL_ISSUES=0
HIGH_ISSUES=0
# 1. npm audit
echo "📦 Running npm audit..."
if command -v npm &> /dev/null; then
if npm audit --audit-level=high; then
echo -e "${GREEN}✓ No high/critical vulnerabilities found${NC}"
else
echo -e "${RED}✗ npm audit found vulnerabilities${NC}"
CRITICAL_ISSUES=$((CRITICAL_ISSUES + 1))
fi
else
echo -e "${YELLOW}⚠ npm not found, skipping${NC}"
fi
echo ""
# 2. ESLint
echo "🔧 Running ESLint..."
if command -v npx &> /dev/null && [ -f ".eslintrc.js" ] || [ -f ".eslintrc.json" ] || [ -f "eslint.config.js" ]; then
if npx eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 10; then
echo -e "${GREEN}✓ ESLint passed${NC}"
else
echo -e "${RED}✗ ESLint found issues${NC}"
HIGH_ISSUES=$((HIGH_ISSUES + 1))
fi
else
echo -e "${YELLOW}⚠ ESLint not configured, skipping${NC}"
fi
echo ""
# 3. Prettier check
echo "💅 Running Prettier..."
if command -v npx &> /dev/null && [ -f ".prettierrc" ] || [ -f ".prettierrc.json" ] || [ -f "prettier.config.js" ]; then
if npx prettier --check . 2>/dev/null; then
echo -e "${GREEN}✓ Code formatting is consistent${NC}"
else
echo -e "${YELLOW}⚠ Code formatting inconsistencies found (auto-fixable)${NC}"
echo " Run: npx prettier --write ."
fi
else
echo -e "${YELLOW}⚠ Prettier not configured, skipping${NC}"
fi
echo ""
# 4. TypeScript type check
echo "📘 Running TypeScript type check..."
if command -v npx &> /dev/null && [ -f "tsconfig.json" ]; then
if npx tsc --noEmit; then
echo -e "${GREEN}✓ TypeScript type check passed${NC}"
else
echo -e "${RED}✗ TypeScript type errors found${NC}"
HIGH_ISSUES=$((HIGH_ISSUES + 1))
fi
else
echo -e "${YELLOW}⚠ TypeScript not configured, skipping${NC}"
fi
echo ""
# 5. Check for hardcoded secrets (basic grep)
echo "🔑 Checking for hardcoded secrets..."
if grep -r -i -E "(api_key|apikey|api-key|password|secret|token|auth|credentials).*=.*['\"][a-zA-Z0-9]{20,}['\"]" src/ --exclude-dir=node_modules --exclude-dir=.git 2>/dev/null; then
echo -e "${RED}✗ Potential hardcoded secrets found!${NC}"
echo " Review the files above and move secrets to environment variables"
CRITICAL_ISSUES=$((CRITICAL_ISSUES + 1))
else
echo -e "${GREEN}✓ No obvious hardcoded secrets detected${NC}"
fi
echo ""
# Final summary
echo "================================="
echo "📊 Audit Summary"
echo "================================="
echo ""
if [ $CRITICAL_ISSUES -gt 0 ]; then
echo -e "${RED}❌ CRITICAL ISSUES: $CRITICAL_ISSUES${NC}"
echo " Must be fixed before deployment"
fi
if [ $HIGH_ISSUES -gt 0 ]; then
echo -e "${YELLOW}⚠️ HIGH PRIORITY ISSUES: $HIGH_ISSUES${NC}"
echo " Should be fixed within 48 hours"
fi
if [ $CRITICAL_ISSUES -eq 0 ] && [ $HIGH_ISSUES -eq 0 ]; then
echo -e "${GREEN}✅ ALL CHECKS PASSED${NC}"
echo " Code is ready for review"
fi
echo ""
echo "For detailed analysis, consider running:"
echo " - sonar-scanner (if SonarQube configured)"
echo " - codeql database analyze (if CodeQL installed)"
echo " - snyk test (if Snyk configured)"
echo ""
# Exit with error code if critical issues found
if [ $CRITICAL_ISSUES -gt 0 ]; then
exit 1
fi
exit 0
Related skills
FAQ
Is Code Reviewer safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.