Skip to content

perashanid/code-review-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Code Review Bot

An AI-powered GitHub App that automatically reviews pull requests, detects security vulnerabilities, and enforces code quality standards.

TypeScript React Node.js GitHub

Table of Contents

Features

Security Analysis

  • Hardcoded Secret Detection: Identifies API keys, passwords, tokens, and private keys
  • SQL Injection Detection: Detects potential SQL injection vulnerabilities
  • XSS Vulnerability Detection: Finds Cross-Site Scripting risks
  • Insecure HTTP Detection: Flags non-HTTPS URLs
  • Eval Usage Detection: Warns about dangerous eval() usage

Code Quality & Style

  • Console Log Detection: Identifies leftover debug statements
  • Debugger Statement Detection: Finds debugging code
  • TODO/FIXME Comment Tracking: Highlights incomplete work
  • Long Function Detection: Flags functions exceeding 50 lines
  • Deep Nesting Detection: Identifies overly nested code (4+ levels)
  • Magic Number Detection: Suggests named constants for unexplained numbers

GitHub Integration

  • Automatic PR review on open, synchronize, and reopen events
  • GitHub Check Runs integration with detailed status reporting
  • Review comments posted directly on PRs
  • Support for private and public repositories
  • Webhook signature verification for security

Dashboard (Frontend)

  • Real-time repository overview
  • Rule management interface
  • Recent review history
  • Issue statistics and categorization
  • Responsive design for mobile and desktop

Tech Stack

Backend

Technology Purpose
Node.js Runtime environment
Express.js Web framework
TypeScript Type-safe development
Octokit GitHub API integration
ESLint Code analysis engine
Winston Logging system
SQLite Local database
Redis + Bull Job queue processing
Helmet Security headers
Rate Limit API protection

Frontend

Technology Purpose
React 19 UI library
TypeScript Type-safe development
Vite Build tool & dev server
Tailwind CSS Utility-first styling
Lucide React Icon library
React Router Client-side routing
Zustand State management
TanStack Query Server state management
Recharts Data visualization

Architecture

code-review-bot/
 backend/                    # Node.js + Express API
    src/
       index.ts           # Server entry point
       routes/            # API routes
          webhook.ts     # GitHub webhook handler
          repositories.ts # Repository management
          rules.ts       # Rule management
       services/          # Business logic
          githubService.ts  # GitHub API integration
          reviewService.ts  # Code review engine
       rules/             # Analysis rules
          securityRules.ts  # Security checks
          styleRules.ts     # Style checks
       middleware/        # Express middleware
       types/             # TypeScript types
       utils/             # Utilities (logger)
    package.json
    tsconfig.json
    .env.example

 frontend/                   # React + Vite SPA
    src/
       App.tsx            # Main application
       main.tsx           # Entry point
       index.css          # Styles
    index.html
    package.json
    vite.config.ts
    tsconfig.json
    tailwind.config.js
    postcss.config.js

 README.md                   # This file

Installation

Prerequisites

  • Node.js 18+
  • npm or yarn
  • Redis (optional, for job queue)
  • GitHub App credentials

1. Clone the Repository

git clone https://github.com/yourusername/code-review-bot.git
cd code-review-bot

2. Backend Setup

cd backend

# Install dependencies
npm install

# Copy environment file
cp .env.example .env

# Edit .env with your credentials
# See "Environment Variables" section below

3. Frontend Setup

cd ../frontend

# Install dependencies
npm install

# Development server
npm run dev

4. Running the Application

Backend:

cd backend
npm run dev        # Development with hot reload
npm run build      # Build for production
npm start          # Run production build

Frontend:

cd frontend
npm run dev        # Development server (port 5173)
npm run build      # Build for production
npm run preview    # Preview production build

GitHub App Setup

Step 1: Create a GitHub App

  1. Go to Settings β†’ Developer settings β†’ GitHub Apps β†’ New GitHub App

  2. Fill in the app details:

    • GitHub App Name: Your Code Review Bot
    • Homepage URL: http://localhost:5173 (or your deployed URL)
    • Webhook URL: https://your-domain.com/webhooks/github (or use Smee for local dev)
    • Webhook Secret: Generate a secure random string
  3. Set Permissions:

    Permission Access
    Pull requests Read & Write
    Contents Read
    Checks Read & Write
    Issues Write
    Metadata Read
  4. Subscribe to Events:

    • Pull request
    • Push
    • Installation
    • Installation repositories
  5. Where can this GitHub App be installed?

    • Select "Any account" (or "Only this account" for testing)
  6. Click Create GitHub App

Step 2: Generate Private Key

  1. In your GitHub App settings, scroll to "Private keys"
  2. Click Generate a private key
  3. Download the .pem file
  4. Move it to your backend directory: backend/private-key.pem

Step 3: Get App Credentials

From your GitHub App settings page, note:

  • App ID (numeric)
  • Client ID
  • Client Secret (generate if needed)

Step 4: Install the App

  1. In your GitHub App settings, click Install App
  2. Select the organization/user account
  3. Choose repositories to grant access to
  4. Click Install

Environment Variables

Create a .env file in the backend directory:

# Server Configuration
NODE_ENV=development
PORT=3002
FRONTEND_URL=http://localhost:5173

# GitHub App Configuration
GITHUB_APP_ID=your-github-app-id
GITHUB_PRIVATE_KEY_PATH=./private-key.pem
GITHUB_WEBHOOK_SECRET=your-webhook-secret
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret

# Security
JWT_SECRET=your-jwt-secret-min-32-characters-long

# Database & Cache
REDIS_URL=redis://localhost:6379
DB_PATH=./data/code_review.db

# Webhook Proxy (for local development)
WEBHOOK_PROXY_URL=https://smee.io/your-channel

# Logging
LOG_LEVEL=info

Variable Descriptions

Variable Description Required
NODE_ENV Environment mode: development or production Yes
PORT Server port number Yes
FRONTEND_URL URL of the frontend app (for CORS) Yes
GITHUB_APP_ID Your GitHub App ID Yes
GITHUB_PRIVATE_KEY_PATH Path to the .pem private key file Yes
GITHUB_WEBHOOK_SECRET Secret for webhook signature verification Yes
GITHUB_CLIENT_ID GitHub App OAuth client ID Optional
GITHUB_CLIENT_SECRET GitHub App OAuth client secret Optional
JWT_SECRET Secret for JWT token signing Yes
REDIS_URL Redis connection URL Optional
DB_PATH SQLite database file path Yes
WEBHOOK_PROXY_URL Smee.io URL for local webhook testing Dev only

Webhook Configuration

Local Development with Smee

GitHub webhooks require a public URL. For local development, use Smee.io:

  1. Go to https://smee.io and click Start a new channel
  2. Copy your unique Smee URL (e.g., https://smee.io/abc123)
  3. Add to your .env: WEBHOOK_PROXY_URL=https://smee.io/abc123
  4. Install Smee client:
    npm install -g smee-client
  5. Run Smee client (in a separate terminal):
    smee -u https://smee.io/abc123 -t http://localhost:3002/webhooks/github
  6. Set the Webhook URL in your GitHub App settings to your Smee URL

Production Webhook Setup

  1. Deploy your backend to a server with a public URL
  2. Set the Webhook URL in GitHub App settings to:
    https://your-domain.com/webhooks/github
    
  3. Ensure your server can receive POST requests at this endpoint
  4. Set a strong Webhook Secret and add it to your .env

Security Rules Documentation

SEC-001: Hardcoded Secret Detection

  • Severity: Critical
  • Description: Detects potential hardcoded secrets, API keys, and passwords
  • Patterns Detected:
    • API keys with 16+ characters
    • Password assignments
    • AWS credentials
    • Private keys (PEM format)
    • Authentication tokens
  • Suggestion: Use environment variables or a secrets manager

SEC-002: SQL Injection Risk

  • Severity: Critical
  • Description: Detects potential SQL injection vulnerabilities
  • Patterns Detected:
    • String concatenation in SQL queries
    • Template literals in database calls
    • User input directly in queries
  • Suggestion: Use parameterized queries or prepared statements

SEC-004: Eval Usage

  • Severity: Error 🟠
  • Description: Detects dangerous use of eval() and similar functions
  • Risk: Code injection and arbitrary code execution
  • Suggestion: Use JSON.parse() for JSON data or refactor to avoid dynamic execution

SEC-005: Insecure HTTP

  • Severity: Warning 🟑
  • Description: Detects usage of insecure HTTP URLs
  • Exclusions: localhost, 127.0.0.1
  • Suggestion: Use HTTPS URLs for all external resources

SEC-006: XSS Vulnerability

  • Severity: Critical
  • Description: Detects potential Cross-Site Scripting vulnerabilities
  • Patterns Detected:
    • dangerouslySetInnerHTML usage
    • innerHTML assignments
    • document.write() calls
  • Suggestion: Use textContent or sanitize HTML with DOMPurify

STYLE-001: Console Log Detection

  • Severity: Info
  • Description: Detects console.log statements
  • Suggestion: Remove before production or use a proper logging library

STYLE-002: Debugger Statement

  • Severity: Warning 🟑
  • Description: Detects debugger; statements
  • Suggestion: Remove all debugger statements before committing

STYLE-003: TODO Comment

  • Severity: Info/Warning 🟑
  • Description: Detects TODO, FIXME, XXX, HACK comments
  • Severity Levels:
    • FIXME β†’ Warning
    • TODO, XXX, HACK β†’ Info
  • Suggestion: Address or create proper issues to track

STYLE-004: Long Function

  • Severity: Warning 🟑
  • Threshold: 50 lines
  • Description: Functions longer than recommended length
  • Suggestion: Break into smaller, focused functions

STYLE-005: Deep Nesting

  • Severity: Warning 🟑
  • Threshold: 4 levels
  • Description: Deeply nested code blocks
  • Suggestion: Extract nested logic or use early returns

STYLE-007: Magic Numbers

  • Severity: Info
  • Description: Unexplained numeric literals
  • Exclusions: 0-10, dates, times, colors, versions, HTTP status codes
  • Suggestion: Extract into named constants

API Endpoints

Health Check

GET /health
Response: { status: "ok", timestamp: "...", version: "1.0.0" }

Webhooks

POST /webhooks/github
Headers: X-GitHub-Event, X-Hub-Signature-256
Body: GitHub webhook payload

Repositories

GET    /api/repositories              # List all installations
GET    /api/repositories/:owner/:repo # Get repository details
GET    /api/repositories/:owner/:repo/settings # Get settings
PATCH  /api/repositories/:owner/:repo/settings # Update settings

Rules

GET /api/rules                    # List all rules
GET /api/rules/category/:category # Filter by category
GET /api/rules/:id                # Get specific rule

Development

Project Structure

backend/src/
 index.ts              # Express app setup
 routes/               # Route handlers
 services/             # Business logic
 rules/                # Analysis rules
 middleware/           # Express middleware
 types/                # TypeScript interfaces
 utils/                # Helper functions

Adding New Rules

  1. Create rule definition in backend/src/rules/:
// backend/src/rules/customRules.ts
import { ReviewRule, CodeIssue } from '../types';

export const customRules: ReviewRule[] = [
  {
    id: 'CUSTOM-001',
    name: 'My Custom Rule',
    description: 'Description of what it checks',
    category: 'best-practice',
    severity: 'warning',
    languages: ['javascript', 'typescript'],
    enabled: true,
    builtIn: true,
  },
];

export function detectMyPattern(content: string, filePath: string): CodeIssue[] {
  const issues: CodeIssue[] = [];
  // Your detection logic here
  return issues;
}
  1. Register in reviewService.ts:
import { detectMyPattern } from '../rules/customRules';

// In analyzeFile method:
issues.push(...detectMyPattern(content, file.filename));
  1. Export from rules.ts route if needed for API exposure.

Running Tests

cd backend
npm run lint       # Run ESLint
npm run build      # TypeScript compilation check

Production Deployment

Docker Deployment

Create a Dockerfile in the backend directory:

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3002

CMD ["npm", "start"]

Environment Checklist

  • Set NODE_ENV=production
  • Use strong, unique secrets
  • Configure proper webhook URL
  • Set up Redis for job queue
  • Enable rate limiting
  • Configure logging to files
  • Use HTTPS for webhook endpoint
  • Restrict CORS origins

Security Recommendations

  1. Webhook Secret: Always use a strong, random webhook secret
  2. Private Key: Store the .pem file securely; never commit it
  3. Rate Limiting: Already enabled by default (100 req/15min)
  4. Helmet: Security headers enabled by default
  5. CORS: Restrict to your frontend URL only

Troubleshooting

Common Issues

Webhook not receiving events:

  • Check Smee client is running (for local dev)
  • Verify webhook URL in GitHub App settings
  • Check server logs for errors

Authentication errors:

  • Verify GitHub App ID and private key
  • Check App is installed on the repository
  • Ensure permissions are correct

Build errors:

  • Run npm install in both frontend and backend
  • Check TypeScript version compatibility
  • Clear node_modules and reinstall

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors