OpenCodeHub - Production Deployment Guide
✅ Production Readiness Status
Section titled “✅ Production Readiness Status”ALL CRITICAL SECURITY FIXES IMPLEMENTED
OpenCodeHub is now production-ready with enterprise-grade security features.
🔒 Implemented Security Features
Section titled “🔒 Implemented Security Features”1. Rate Limiting ✅
Section titled “1. Rate Limiting ✅”Location: src/middleware/rate-limit.ts
Protection:
- Login attempts: 5 per 15 minutes
- API requests: 100 per minute
- Git operations: 200 per minute
Applied To:
/api/auth/login/api/auth/register/api/repos/[repoId]/branch-protection
2. CSRF Protection ✅
Section titled “2. CSRF Protection ✅”Location: src/middleware/csrf.ts
Method: Double-submit cookie pattern Coverage: All state-changing operations (POST/PUT/DELETE)
3. Input Validation ✅
Section titled “3. Input Validation ✅”Location: src/lib/validation.ts
Schemas:
RegisterUserSchema- Username, email, password validationBranchProtectionSchema- Pattern and permission validationCreateRepositorySchema,CreateIssueSchema,CreatePullRequestSchemaStorageConfigSchema,GeneralConfigSchema,WebhookConfigSchema
Prevention: SQL injection, XSS, invalid data attacks
4. Git Hook Authentication ✅
Section titled “4. Git Hook Authentication ✅”Locations:
src/lib/git.ts- Hook installation with secretssrc/pages/api/internal/hooks/pre-receive.tssrc/pages/api/internal/hooks/post-receive.ts
Security: Shared secret in X-Hook-Secret header prevents unauthorized hook execution
5. Environment Validation ✅
Section titled “5. Environment Validation ✅”Location: src/lib/env-validation.ts
Validates:
- Required secrets (JWT_SECRET, SESSION_SECRET, INTERNAL_HOOK_SECRET)
- Secret strength (32+ characters)
- URL formats (SITE_URL must be valid)
- Production-specific checks (HTTPS, no default secrets)
📋 Production Deployment Checklist
Section titled “📋 Production Deployment Checklist”Prerequisites
Section titled “Prerequisites”- PostgreSQL 14+ database configured
- Domain name with DNS configured
- SSL certificate (Let’s Encrypt recommended)
- S3/R2 bucket for storage (or cloud storage alternative)
Required Environment Variables
Section titled “Required Environment Variables”Critical Security (MUST SET):
# Generate with: openssl rand -hex 32JWT_SECRET=<64-char-hex>SESSION_SECRET=<64-char-hex>INTERNAL_HOOK_SECRET=<64-char-hex>
# Production URL (MUST be HTTPS)SITE_URL=https://git.yourcompany.comNODE_ENV=productionDatabase:
DATABASE_DRIVER=postgresDATABASE_URL=postgresql://user:password@host:5432/opencodehubStorage (Use cloud storage, not local):
STORAGE_TYPE=s3STORAGE_BUCKET=opencodehub-productionSTORAGE_REGION=us-east-1S3_ACCESS_KEY=<your-access-key>S3_ACCESS_KEY=<your-access-key>S3_SECRET_KEY=<your-secret-key>Google Drive + Turso Stack: See docs/GDRIVE_STACK.md for detailed setup.
STORAGE_TYPE=gdriveGOOGLE_CLIENT_ID=...GOOGLE_CLIENT_SECRET=...GOOGLE_REFRESH_TOKEN=...GOOGLE_FOLDER_ID=...Optional but Recommended:
# Error MonitoringSENTRY_DSN=https://your-sentry-dsn
# EmailSMTP_HOST=smtp.example.comSMTP_PORT=587SMTP_USER=noreply@yourcompany.comSMTP_PASSWORD=<smtp-password>SMTP_FROM=noreply@yourcompany.com
# Redis (for session management)REDIS_URL=redis://localhost:6379Deployment Steps
Section titled “Deployment Steps”# 1. Clone and configuregit clone https://github.com/swadhinbiswas/OpencodeHub.gitcd OpenCodeHub
# 2. Install dependenciesnpm install # or bun install
# 3. Create production .envcp .env.example .envnano .env # Configure all production values
# 4. Validate environmentbun run src/lib/env-validation.ts# Should output: ✅ Environment validation passed
# 5. Run database migrationsnpm run db:push# or generate versioned migrations:npm run db:generatenpm run db:migrate
# 6. Create admin userbun run scripts/seed-admin.ts# Enter username, email, password when prompted
# 7. Build for productionnpm run build
# 8. Start production servernpm startDocker Deployment (Recommended)
Section titled “Docker Deployment (Recommended)”version: '3.8'
services: app: build: . restart: always ports: - "3000:3000" env_file: .env.production depends_on: - postgres - redis volumes: - ./data:/app/data environment: NODE_ENV: production 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: ${DATABASE_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432"
redis: image: redis:7-alpine restart: always command: redis-server --requirepass ${REDIS_PASSWORD} ports: - "6379:6379"
volumes: postgres_data:# Deploy with Dockerdocker-compose -f docker-compose.prod.yml up -d
# View logsdocker-compose -f docker-compose.prod.yml logs -f app
# Create admin user in containerdocker-compose exec app bun run scripts/seed-admin.tsReverse Proxy (Nginx)
Section titled “Reverse Proxy (Nginx)”server { listen 443 ssl http2; server_name git.yourcompany.com;
ssl_certificate /etc/letsencrypt/live/git.yourcompany.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/git.yourcompany.com/privkey.pem;
# Security headers add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always;
# Proxy configuration 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;
# WebSocket support (for live updates) proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
# Git operations (larger timeouts) location ~ ^/[^/]+/[^/]+\.git/ { proxy_pass http://localhost:3000; proxy_read_timeout 600s; proxy_send_timeout 600s; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; client_max_body_size 100M; }}
# Redirect HTTP to HTTPSserver { listen 80; server_name git.yourcompany.com; return 301 https://$server_name$request_uri;}# Enable sitesudo ln -s /etc/nginx/sites-available/opencodehub /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginx🔍 Verification Steps
Section titled “🔍 Verification Steps”1. Environment Validation
Section titled “1. Environment Validation”bun run src/lib/env-validation.tsExpected Output:
🔍 Validating environment configuration...✅ Environment validation passed2. Build Verification
Section titled “2. Build Verification”npm run buildExpected: No errors, successful build output
3. Security Features Test
Section titled “3. Security Features Test”Rate Limiting:
# Try 6 login attempts rapidly - should get rate limitedfor i in {1..6}; do curl -X POST https://git.yourcompany.com/api/auth/login \ -H "Content-Type: application/json" \ -d '{"login":"test","password":"wrong"}' \ -w "\nStatus: %{http_code}\n"doneExpected: First 5 return 401, 6th returns 429 (Too Many Requests)
Hook Authentication:
# Try without secret - should failcurl -X POST https://git.yourcompany.com/api/internal/hooks/post-receive \ -H "Content-Type: application/json" \ -d '{"oldrev":"abc","newrev":"def","refname":"refs/heads/main"}'Expected: 401 Unauthorized
4. Health Check
Section titled “4. Health Check”curl https://git.yourcompany.com/api/healthExpected:
{ "status": "ok", "checks": { "database": "ok", "storage": "ok" }, "uptime": 12345, "version": "1.0.0"}🐛 Troubleshooting
Section titled “🐛 Troubleshooting”Rate Limit Issues
Section titled “Rate Limit Issues”Problem: Users getting rate limited legitimately
Solution:
# Increase limits in .envRATE_LIMIT_AUTH=10 # Increase from 5RATE_LIMIT_API=200 # Increase from 100Git Hooks Not Working
Section titled “Git Hooks Not Working”Problem: Push succeeds but hooks don’t trigger
Checklist:
- Verify
SITE_URLis set correctly - Verify
INTERNAL_HOOK_SECRETmatches in .env - Check hook files exist:
data/repos/owner/repo.git/hooks/post-receive - Verify hooks are executable:
chmod +x hooks/* - Check application logs for hook errors
Database Connection Errors
Section titled “Database Connection Errors”Problem: Can’t connect to database
Solutions:
# Test connectionpsql $DATABASE_URL
# Check PostgreSQL is runningsudo systemctl status postgresql
# Verify credentials in .envecho $DATABASE_URLStorage Upload Failures
Section titled “Storage Upload Failures”Problem: Can’t upload files
Solutions:
- Test S3 credentials:
aws s3 ls s3://$STORAGE_BUCKET --profile opencodehub-
Verify bucket permissions (needs: s3:PutObject, s3:GetObject, s3:DeleteObject)
-
Check CORS configuration if using direct uploads
📊 Monitoring & Maintenance
Section titled “📊 Monitoring & Maintenance”Database Backups
Section titled “Database Backups”# Daily backup script#!/bin/bashDATE=$(date +%Y%m%d_%H%M%S)pg_dump $DATABASE_URL | gzip > /backups/opencodehub_$DATE.sql.gz
# Retain last 30 daysfind /backups -name "opencodehub_*.sql.gz" -mtime +30 -deleteAdd to crontab:
0 2 * * * /usr/local/bin/backup-opencodehub.shLog Rotation
Section titled “Log Rotation”/var/log/opencodehub/*.log { daily rotate 30 compress delaycompress notifempty create 0644 www-data www-data sharedscripts postrotate systemctl reload opencodehub endscript}Metrics to Monitor
Section titled “Metrics to Monitor”- Request rate (should stay within rate limits)
- Failed login attempts (detect brute force)
- Database connection pool usage
- Storage usage
- Memory and CPU usage
- Error rate (4xx, 5xx responses)
🚀 Post-Deployment
Section titled “🚀 Post-Deployment”Create Organizations
Section titled “Create Organizations”- Login as admin
- Navigate to Settings → Organizations
- Create organization
- Invite team members
Configure Branch Protection
Section titled “Configure Branch Protection”- Go to Repository → Settings → Branches
- Add protection rule for
main:- Require PR: ✅
- Required approvals: 2
- Dismiss stale reviews: ✅
Setup CI/CD Runners
Section titled “Setup CI/CD Runners”# Start self-hosted runnerdocker run -d \ --name opencodehub-runner \ -e SERVER_URL=https://git.yourcompany.com \ -e RUNNER_TOKEN=<from-admin-panel> \ opencodehub/runner:latestEnable Email Notifications
Section titled “Enable Email Notifications”Configure SMTP in .env, then test:
curl -X POST https://git.yourcompany.com/api/admin/test-email \ -H "Cookie: och_session=<your-session>" \ -H "Content-Type: application/json" \ -d '{"to":"admin@yourcompany.com"}'📚 Additional Resources
Section titled “📚 Additional Resources”- API Documentation: https://git.yourcompany.com/api/docs
- Admin Panel: https://git.yourcompany.com/admin
- User Guide: See README.md
- Security Best Practices: See production_analysis.md
✅ Production Readiness Confirmed
Section titled “✅ Production Readiness Confirmed”All critical security features are implemented and tested:
- ✅ Rate limiting (brute force protection)
- ✅ CSRF protection (cross-site attacks)
- ✅ Input validation (injection prevention)
- ✅ Hook authentication (git security)
- ✅ Environment validation (configuration safety)
OpenCodeHub is ready for production deployment! 🎉