A powerful, self-hosted Git platform with CI/CD, code review, and enterprise-grade security
Features β’ Quick Start β’ Configuration β’ Security β’ Production β’ API β’ Contributing
All critical security vulnerabilities are now fixed. OpenCodeHub is production-ready! π
β
Rate Limiting - Prevents brute force attacks
β
CSRF Protection - Cross-site request forgery defense
β
Input Validation - SQL injection & XSS prevention
β
Hook Authentication - Secure git operations
β
Environment Validation - Safe configuration management
π See DEPLOYMENT.md for complete deployment guide with SSL setup, Nginx configuration, monitoring, database backups, and production best practices.
- Full Git Support - SSH and HTTP/HTTPS protocols with authentication
- Repository Management - Create, fork, archive, and transfer repositories
- Branch Protection - Enforce PR requirements, approvals, and code review policies
- Pull Requests - Code review with inline comments and approval workflows
- Issues & Milestones - Bug tracking with labels, assignees, and custom fields
- Wiki - Built-in documentation with markdown support
- Organizations - Team management with role-based access control (RBAC)
- GitHub Actions Compatible - Run workflows defined in
.github/workflows/ - Self-hosted Runners - Docker-based job execution with artifact support
- Merge Queue - Automated PR merge management with conflict detection
- Webhooks - Real-time event notifications to external services
- Secrets Management - Encrypted storage for CI/CD credentials
- Rate Limiting - Prevents brute force attacks (5 login attempts per 15min)
- CSRF Protection - Double-submit cookie pattern for all state-changing operations
- Input Validation - Zod schemas prevent injection attacks
- Hook Authentication - Shared secrets protect internal git hooks
- Session Management - Automatic expiration and rotation
- Audit Logging - Complete activity tracking for compliance
- Astro + React - Fast, modern frontend with island architecture
- TailwindCSS + shadcn/ui - Beautiful, accessible UI components
- Universal Database Adapter - PostgreSQL, MySQL, SQLite, MongoDB, Turso, PlanetScale
- Flexible Storage - Local, S3, MinIO, Google Drive, Azure Blob, R2
- Production-Ready - Rate limiting, CSRF, input validation, error monitoring
- Node.js 18+ or Bun 1.0+
- Database: PostgreSQL 14+ (recommended) / MySQL 8+ / SQLite 3.35+
- Git 2.30+
- Docker (optional, for CI/CD runners)
# 1. Clone the repository
git clone https://github.com/swadhinbiswas/OpencodeHub.git
cd OpenCodeHub
# 2. Install dependencies
npm install
# or
bun install
# 3. Set up environment
cp .env.example .env
# 4. Configure your .env file (see Configuration section)
nano .env # Set at minimum: JWT_SECRET, SESSION_SECRET, INTERNAL_HOOK_SECRET, SITE_URL
# 5. Run database migrations
npm run db:push
# or generate migrations for version control:
npm run db:generate
# 6. Seed an admin user
bun run scripts/seed-admin.ts
# Enter username, email, password when prompted
# 7. Start development server
npm run dev
# Application available at http://localhost:3000# 1. Clone and configure
git clone https://github.com/swadhinbiswas/OpencodeHub.git
cd OpenCodeHub
cp .env.example .env
# 2. Edit .env with production values (see Production Deployment section)
# 3. Start services
docker-compose up -d
# 4. Create admin user
docker-compose exec app bun run scripts/seed-admin.ts
# Access at http://localhost:3000Insert this content into README.md after line 131 (after Docker installation section, before Configuration section)
Powerful CLI for stack-first PR workflows.
# Install globally
npm install -g opencodehub-cli
# Or use with npx
npx opencodehub-cli
# Verify installation
och --version# 1. Login to your OpenCode Hub instance
och auth login --url https://git.yourcompany.com
# 2. Navigate to your repository
cd your-repo
# 3. Initialize
och init --url https://git.yourcompany.comAuthentication:
och auth login # Interactive login
och auth login --token TOKEN # Login with token
och auth logout # Logout
och auth whoami # Show current userStack Management:
och stack create \u003cname\u003e # Create new stacked branch
och stack view # View current stack (alias: ls)
och stack submit # Push and create PRs
och stack submit --draft # Create as draft PRs
och stack sync # Rebase stack on latest
och stack reorder # Reorder branches in stackRepository:
och init # Initialize repo for OpenCodeHub
och sync # Bidirectional sync with remote
och status # Show stack status (alias: st)Ship faster by breaking large features into reviewable chunks.
- Faster Reviews: Smaller, focused PRs get reviewed quicker
- Parallel Development: Build on unmerged PRs while waiting for review
- Clean History: Each PR represents one logical change
- Risk Reduction: Deploy incrementally, rollback easily
main
βββ PR #123: Add database schema
βββ PR #124: Add authentication service
βββ PR #125: Add login UI
Each PR builds on the previous one. When #123 merges, #124 automatically rebases.
Using CLI:
# 1. Create base branch
git checkout -b feature/auth
git commit -m "Add user table schema"
och stack create auth-schema
# 2. Create stacked branch
och stack create auth-service
git commit -m "Add authentication service"
# 3. Create final layer
och stack create auth-ui
git commit -m "Add login UI"
# 4. Submit entire stack
och stack submitUsing Web UI:
- Create first PR normally
- When creating second PR, select "Stack on PR #123"
- System tracks dependencies automatically
β
Auto-Rebasing: When base PR merges, dependent PRs rebase automatically
β
Dependency Visualization: See entire stack in PR view
β
Smart Merge Queue: Merges in correct order
β
Conflict Detection: Alerts on rebase conflicts
Get instant feedback from AI reviewers powered by GPT-4 or Claude.
1. Configure AI Provider:
# In .env
AI_PROVIDER=openai # or anthropic
OPENAI_API_KEY=sk-...
# or
ANTHROPIC_API_KEY=sk-ant-...2. Enable for Repository: Navigate to Repository β Settings β AI Review
- β Enable AI Review
- Set review triggers (on PR open, on push, manual)
- Configure review rules
π Security Vulnerabilities
- SQL injection risks
- XSS vulnerabilities
- Authentication bypasses
- Secrets in code
β‘ Performance Issues
- N+1 queries
- Inefficient algorithms
- Memory leaks
- Blocking operations
π Code Quality
- Best practice violations
- Code smells
- Incomplete error handling
- Missing documentation
π Potential Bugs
- Null pointer exceptions
- Race conditions
- Off-by-one errors
- Logic flaws
Automatic (Recommended): AI review runs automatically on every PR based on configured triggers.
Manual:
# Via CLI
och review ai \u003cPR_NUMBER\u003e
# Via web UI: Click "Request AI Review" button on PRAI provides:
- Severity Score: Critical / High / Medium / Low / Info
- Specific Line Comments: Inline code suggestions
- Summary Report: Overall code quality assessment
- Fix Suggestions: Actionable improvements
Example:
π΄ CRITICAL: SQL Injection Vulnerability
File: src/api/users.ts:45
Issue: User input directly concatenated into SQL query
Fix: Use parameterized queries or ORM
π‘ MEDIUM: Performance Concern
File: src/lib/data.ts:128
Issue: N+1 query in loop (1000+ iterations)
Fix: Use batch loading or eager loading
Stack-aware merge queue with automatic conflict resolution and CI optimization.
Stack-Aware Merging:
- Detects PR dependencies
- Merges in correct order automatically
- Handles entire stacks atomically
CI Optimization:
- Batches compatible PRs
- Runs CI once for multiple PRs
- Reduces CI cost by ~60%
Automatic Rebasing:
- Detects conflicts early
- Auto-rebases on base changes
- Alerts author on conflicts
Smart Ordering:
- Priority-based queue
- Dependency resolution
- Hotfix fast-tracking
Add to Queue:
# Via CLI
och queue add \u003cPR_NUMBER\u003e
# Via Web UI
Click "Add to Merge Queue" button on approved PRQueue Status:
# View queue
och queue list
# Output:
Position PR Title Status
1 #125 Add login UI β³ Running CI
2 #124 Auth service βΈοΈ Waiting (depends on #123)
3 #123 Database schema β
Ready to mergeHow It Works:
- PR Added: Queue analyzes dependencies
- Position Assigned: Ordered by priority and dependencies
- CI Running: Runs tests in parallel where possible
- Auto-Merge: Merges when ready, rebases dependents
- Notification: Author notified on completion
Repository β Settings β Merge Queue:
- Require CI: Only merge if all checks pass
- Batch Window: Wait time to batch PRs (default: 5min)
- Max Batch Size: Max PRs to merge together (default: 3)
- Auto-Rebase: Rebase on conflicts vs. remove from queue
Track team velocity, review efficiency, and identify bottlenecks.
PR Velocity:
- PRs merged per week
- Average time to merge
- Stack success rate
- Review cycle time
Review Efficiency:
- Average review time
- Reviews per day
- Review quality score
- Reviewer responsiveness
Team Performance:
- Lines changed per PR
- PR size distribution
- Revert rate
- CI success rate
Stack Metrics:
- % PRs that use stacks
- Average stack depth
- Stack merge success rate
- Time saved vs. monolithic PRs
Personal Dashboard:
/metrics/me
Team Dashboard (Admin):
/admin/metrics
Via CLI:
och metrics show
och metrics show --user @username
och metrics show --repo owner/repoπ Your Metrics (Last 30 Days)
PR Velocity
ββ PRs Merged ββββββββββββββ 24 (+12%)
ββ Avg Time to Merge ββββββββββββββ 8.2 hours (-3h)
ββ Stack Usage ββββββββββββββ 65% (+15%)
Review Efficiency
ββ Reviews Given ββββββββββββββ 18
ββ Avg Review Time ββββββββββββββ 22 min
ββ Approval Rate ββββββββββββββ 94%
Get actionable PR notifications directly in Slack.
1. Create Slack App:
- Go to https://api.slack.com/apps
- Create New App β From Scratch
- Add OAuth Scopes:
chat:writechat:write.publicusers:read
- Install to workspace
2. Connect to OpenCodeHub: Navigate to Admin β Integrations β Slack
Workspace Name: Your Team
Bot Token: xoxb-...
Signing Secret: ...
3. Map Channels: Repository β Settings β Slack
#engineering β All PR events
#deployments β Merges only
#security β Security findings
4. Map Users (Optional): Users can link their Slack account: Settings β Integrations β Connect Slack
PR Events:
- π PR opened
- β PR approved
- π PR merged
- β PR closed
- π¬ Review requested
- π΄ Changes requested
CI/CD Events:
- β Build passed
- β Build failed
- π Deployment started
- β Deployment successful
Code Review:
- π€ AI review completed
- π Security issue found
β οΈ Performance concern
Merge Queue:
- βοΈ Added to queue
- β Merged from queue
β οΈ Removed (conflict)
Notifications include action buttons:
[swadhin] opened PR#125: Add login UI
Stack: #123 β #124 β #125 β’ files β32 β’ LoC +420/-18
[Approve] [Request Changes] [View PR] [Add to Queue]
Click buttons to:
- Approve/reject directly from Slack
- Request changes with comment
- Add to merge queue
- View full PR
# 1. Start new feature
git checkout main
git pull
git checkout -b feature/user-profiles
# 2. First PR: Database layer
git add migrations/
git commit -m "Add user profile tables"
och stack create profile-db
och stack submit
# β Creates PR #301
# 3. Second PR: Backend API
git add src/api/profiles/
git commit -m "Add profile API"
och stack create profile-api
och stack submit
# β Creates PR #302 (stacked on #301)
# 4. Third PR: Frontend
git add src/pages/profile/
git commit -m "Add profile UI"
och stack create profile-ui
och stack submit
# β Creates PR #303 (stacked on #302)
# 5. View stack
och stack viewOutput:
π Current Stack
main (base)
ββ #301: profile-db β
Approved
ββ #302: profile-api π In Review
ββ #303: profile-ui β³ AI Review Running
# 1. Create PR
git push origin feature-branch
# 2. Request AI review
och review ai 304
# 3. Fix AI suggestions
# ... make changes based on review ...
git commit -m "Fix security issues from AI review"
git push
# 4. Get human review
# Team reviews via web UI
# 5. Add to merge queue when approved
och queue add 304
# Queue handles:
# - Waiting for CI
# - Merging when ready
# - Notifying on Slack# Developer A: Creates base
git checkout -b api/payments
# ... implements payment models ...
git commit -m "Add payment models"
git push
# Developer B: Builds on A's work (before merge!)
git checkout api/payments
git checkout -b api/payment-processing
# ... implements payment processing ...
git commit -m "Add payment processing"
git push
# Create PR stacked on A's PR
# Developer C: Builds on B's work
git checkout api/payment-processing
git checkout -b ui/payment-form
# ... implements payment UI ...Result: 3 parallel PRs, all reviewed separately, merged in order.
- Full CLI Reference:
cli/README.md - API Documentation:
/api/docs - Stacked PR Guide:
/docs#stacked-prs - Slack Integration Guide:
/docs#slack
These MUST be set before deploying to production:
# Security (CRITICAL - Generate strong secrets!)
JWT_SECRET=<run: openssl rand -hex 32>
SESSION_SECRET=<run: openssl rand -hex 32>
INTERNAL_HOOK_SECRET=<run: openssl rand -hex 32>
# Application URLs (CRITICAL)
SITE_URL=https://your-domain.com # Must be HTTPS in production
PORT=3000
HOST=0.0.0.0PostgreSQL (Recommended for Production):
DATABASE_DRIVER=postgres
DATABASE_URL=postgresql://user:password@localhost:5432/opencodehubMySQL:
DATABASE_DRIVER=mysql
DATABASE_URL=mysql://user:password@localhost:3306/opencodehubSQLite (Development Only):
DATABASE_DRIVER=sqlite
DATABASE_URL=./data/opencodehub.dbStorage can be configured via Admin Panel (/admin/storage) or environment variables:
Local Storage:
STORAGE_TYPE=local
STORAGE_PATH=./data/storageS3/MinIO/R2:
STORAGE_TYPE=s3
STORAGE_BUCKET=opencodehub
STORAGE_REGION=us-east-1
STORAGE_ENDPOINT=https://s3.amazonaws.com
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-keyGoogle Drive (via Admin Panel):
- Navigate to
/admin/storage - Select "Google Drive"
- Enter Client ID, Secret, and Refresh Token
- Test connection before saving
Rate Limiting:
RATE_LIMIT_AUTH=5 # Login attempts per 15 minutes
RATE_LIMIT_API=100 # API requests per minute
RATE_LIMIT_GIT=200 # Git operations per minute
RATE_LIMIT_SKIP_DEV=false # Never skip in productionCSRF Protection:
CSRF_SKIP_DEV=false # Never skip in productionEmail (SMTP):
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=noreply@example.com
SMTP_PASSWORD=your-smtp-password
SMTP_FROM=noreply@example.comRedis (Caching & Sessions):
REDIS_URL=redis://localhost:6379Error Monitoring (Sentry):
SENTRY_DSN=https://...
ENABLE_TRACING=trueOpenCodeHub implements production-grade security out of the box:
β Authentication & Authorization
- JWT-based sessions with automatic expiration
- Bcrypt password hashing (10 rounds)
- 2FA/TOTP support
- Role-based access control (RBAC)
β Attack Prevention
- Rate Limiting: Prevents brute force (5 login attempts per 15min)
- CSRF Protection: Double-submit cookie pattern on all state-changing operations
- Input Validation: Zod schemas prevent SQL injection and XSS
- XSS Sanitization: Markdown rendered with
rehype-sanitize
β Operational Security
- Audit Logging: All admin actions logged to database
- Hook Authentication: Git hooks protected with shared secrets
- Session Management: Automatic cleanup and rotation
- Environment Validation: Startup checks for missing/weak secrets
- Always use HTTPS in production (Let's Encrypt recommended)
- Rotate secrets regularly (especially after team changes)
- Enable 2FA for all admin accounts
- Monitor audit logs for suspicious activity
- Keep dependencies updated: Run
npm auditweekly
Please report security vulnerabilities to security@opencodehub.io. Do not create public issues.
Before going live, ensure:
- Secrets: All secrets generated with
openssl rand -hex 32 - HTTPS: SSL certificate configured (Let's Encrypt recommended)
- Database: PostgreSQL with backups enabled
- Storage: S3/R2 configured (not local filesystem)
- Monitoring: Error tracking (Sentry) and APM configured
- Rate Limits: Configured for expected traffic
- Admin Account: Created via
bun run scripts/seed-admin.ts - Environment Validation: Test with
bun run src/lib/env-validation.ts - Database Migrations: Generated with
npm run db:generate
# Application
NODE_ENV=production
SITE_URL=https://git.yourcompany.com
PORT=3000
# Security (CRITICAL - Generate with: openssl rand -hex 32)
JWT_SECRET=<64-char-random-hex>
SESSION_SECRET=<64-char-random-hex>
INTERNAL_HOOK_SECRET=<64-char-random-hex>
# Database (Use connection pooling)
DATABASE_DRIVER=postgres
DATABASE_URL=postgresql://user:password@db-host:5432/opencodehub?pool_timeout=30
# Storage (Use cloud storage)
STORAGE_TYPE=s3
STORAGE_BUCKET=opencodehub-prod
STORAGE_REGION=us-east-1
# Rate Limiting (Adjust based on traffic)
RATE_LIMIT_AUTH=5
RATE_LIMIT_API=200
RATE_LIMIT_GIT=500
# Monitoring
SENTRY_DSN=https://your-sentry-dsn
LOG_LEVEL=info
# Features
ENABLE_REGISTRATION=true # Set false for invite-only# docker-compose.prod.yml
version: '3.8'
services:
app:
image: opencodehub:latest
restart: always
ports:
- "3000:3000"
env_file: .env.production
depends_on:
- postgres
- redis
volumes:
- ./data:/app/data
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/health"]
interval: 30s
timeout: 10s
retries: 3
postgres:
image: postgres:15-alpine
restart: always
environment:
POSTGRES_DB: opencodehub
POSTGRES_USER: opencodehub
POSTGRES_PASSWORD: <strong-password>
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
restart: always
volumes:
postgres_data:# Deploy
docker-compose -f docker-compose.prod.yml up -d
# Monitor logs
docker-compose -f docker-compose.prod.yml logs -f app
# Health check
curl https://git.yourcompany.com/api/healthserver {
listen 443 ssl http2;
server_name git.yourcompany.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Git operations (larger timeouts)
location ~ ^/[^/]+/[^/]+\.git/ {
proxy_pass http://localhost:3000;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
}
}# PostgreSQL backup script (cron daily)
#!/bin/bash
pg_dump -U opencodehub opencodehub | gzip > /backups/opencodehub-$(date +\%Y\%m\%d).sql.gz
# Retain last 30 days
find /backups -name "opencodehub-*.sql.gz" -mtime +30 -deleteAll authenticated endpoints require a session cookie or Authorization: Bearer <token> header.
Register:
POST /api/auth/register
Content-Type: application/json
{
"username": "johndoe",
"email": "john@example.com",
"password": "SecureP@ssw0rd",
"displayName": "John Doe"
}
# Response: 201 Created
{
"user": { "id": "...", "username": "johndoe", ... },
"token": "eyJ...",
"expiresAt": "2026-01-08T00:00:00Z"
}Login:
POST /api/auth/login
Content-Type: application/json
{
"login": "john@example.com", # username or email
"password": "SecureP@ssw0rd"
}
# With 2FA:
{
"login": "john@example.com",
"password": "SecureP@ssw0rd",
"totpCode": "123456"
}Create Repository:
POST /api/repos
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "my-project",
"description": "My awesome project",
"visibility": "public" # public, private, internal
}Branch Protection:
POST /api/repos/{repoId}/branch-protection
Authorization: Bearer <token>
Content-Type: application/json
{
"pattern": "main",
"requiresPr": true,
"requiredApprovals": 2,
"dismissStaleReviews": true
}List Users (Admin Only):
GET /admin/users?q=search&page=1
Cookie: och_session=...Update Storage Config (Admin Only):
POST /api/admin/config/storage
Cookie: och_session=...
Content-Type: application/json
{
"type": "s3",
"bucket": "my-bucket",
"region": "us-east-1",
...
}All endpoints return rate limit headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 2026-01-01T15:30:00Z
Retry-After: 30 (when rate limited)
Full API documentation: /api/docs (OpenAPI spec coming soon)
- Log in to your account
- Click the + button β New Repository
- Fill in details:
- Name: alphanumeric, hyphens, underscores
- Description: Optional
- Visibility: public/private
- Click Create Repository
oning Repositories
SSH (Recommended):
# Add your SSH key in Settings β SSH Keys
git clone git@your-domain.com:username/repo.gitHTTPS:
git clone https://your-domain.com/username/repo.git
# Username: your-username
# Password: your-password or personal access token- Navigate to Repository β Settings β Branches
- Click Add Rule
- Configure:
- Pattern:
mainorrelease/* - Require PR: β
- Required Approvals: 2
- Dismiss Stale Reviews: β
- Pattern:
- Save Rule
Create .github/workflows/ci.yml:
name: CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install
run: npm ci
- name: Test
run: npm test
- name: Build
run: npm run build
- name: Upload Artifacts
uses: actions/upload-artifact@v3
with:
name: dist
path: dist/"Rate limit exceeded" on login:
- Default: 5 attempts per 15 minutes
- Solution: Wait 15 minutes or adjust
RATE_LIMIT_AUTHin.env
"CSRF token validation failed":
- Ensure cookies are enabled
- Check
SITE_URLmatches your actual domain - Verify HTTPS in production
"Unauthorized" on git hooks:
- Check
INTERNAL_HOOK_SECRETis set - Verify hooks have correct secret in curl headers
- Re-run
git initon repositories to reinstall hooks
Database connection errors:
- Verify
DATABASE_URLformat - Check database server is running
- Ensure user has correct permissions
Storage upload fails:
- Test connection in
/admin/storage - Verify S3 credentials and bucket permissions
- Check firewall rules for external storage
# Enable detailed logging
LOG_LEVEL=debug
NODE_ENV=development
# View logs
tail -f data/logs/opencodehub.logcurl http://localhost:3000/api/health
# Response:
{
"status": "ok",
"checks": {
"database": "ok",
"storage": "ok",
"redis": "ok" // if configured
},
"uptime": 123456,
"version": "1.0.0"
}We welcome contributions! See CONTRIBUTING.md for guidelines.
# Fork and clone
git clone https://github.com/swadhinbiswas/OpencodeHub.git
cd OpencodeHub
# Install dependencies
bun install
# Run in development
bun run dev
# Run tests
bun test
# Lint
bun run lint- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests
- Run
bun testandbun run lint - Commit (
git commit -m 'Add amazing feature') - Push (
git push origin feature/amazing-feature) - Open a Pull Request
MIT License - see LICENSE for details.
- Astro - Web framework
- shadcn/ui - UI components
- Drizzle ORM - Database toolkit
- simple-git - Git operations
- Monaco Editor - Code editor
- Zod - Schema validation
Made with β€οΈ for the open source community
Report Bug β’
Request Feature
