@crisego/cgrok-server
v1.0.7
Published
Self-hosted tunneling server - High-performance tunnel server for cgrok. Open-source ngrok alternative server with custom domains. Pair with @crisego/cgrok for complete self-hosted solution.
Maintainers
Keywords
Readme
CGrok Server - Self-Hosted Tunneling Server
High-performance tunneling server for self-hosted HTTPS tunnels. Open-source ngrok alternative server with custom domains, authentication, and real-time metrics. Pair with @crisego/cgrok for complete self-hosted solution.
🚀 This is the server component. Install cgrok on your development machine to complete your self-hosted tunneling infrastructure.
🔥 Perfect for: Self-hosted infrastructure, custom domain tunneling, team collaboration, webhook testing, localhost sharing without third-party services
✨ Key Features
- 🔧 Advanced Configuration Management: Supports persistent config file (
~/.cgrok-server/config.json), environment variables, and CLI arguments with hierarchical priority - 📊 Real-Time Metrics: Track active connections, request statistics, response times, and client performance
- 🔄 Intelligent Connection Management: WebSocket heartbeat, automatic cleanup, and graceful shutdown
- 🌐 Custom Subdomains: Allow clients to request specific subdomains for their tunnels
- 🗜️ Built-in Rate Limiting: Configurable rate limiting per client to prevent abuse
- 🔐 Robust Authentication: Support for token-based and basic authentication
- 📝 Detailed Logging: Structured logging with timestamps and event categorization
- 🎨 Interactive Setup: Guided configuration wizard for easy server setup
- ⚡ High Performance: Built with Bun and TypeScript, optimized for low latency
- 🛡️ Error Handling: Robust error management with configurable timeouts and validation
- 🔄 Daemon Management: Start/stop/restart server as background daemon with status monitoring
🎯 What is CGrok Server?
CGrok Server is a complete self-hosted tunneling solution consisting of two components:
- cgrok-server (this package) - Server you deploy on your VPS/cloud
- cgrok - CLI client you install on your development machine
Together, they provide a 100% self-hosted alternative to ngrok, giving you:
- ✅ Full control over your infrastructure
- ✅ Custom domains (your-app.yourdomain.com)
- ✅ No usage limits or paid tiers
- ✅ Privacy - your traffic stays on your servers
- ✅ Team sharing - multiple developers, one server
- ✅ Authentication - secure access control
- ✅ Real-time metrics - detailed usage statistics
- ✅ Rate limiting - protection against abuse
🔧 Server Configuration
The cgrok-server supports multiple configuration methods with the following priority order:
Priority (highest to lowest): CLI Arguments → Configuration File → Environment Variables → Default Values
Configuration File
The server automatically creates a configuration file at ~/.cgrok-server/config.json:
{
"port": 5001,
"maxConnections": 100,
"requestTimeout": 30000,
"rateLimitWindow": 60000,
"rateLimitMax": 100,
"enableAuth": false,
"authToken": "your_secret_token",
"enableBasicAuth": false,
"basicAuthUsername": "admin",
"basicAuthPassword": "secure_password",
"enableMetrics": true,
"logLevel": "info",
"humanReadableIds": true,
"idLength": 6,
"includeTimestamp": false,
"enableCustomSubdomains": true
}Environment Variables
export CGROK_PORT=5001
export CGROK_MAX_CONNECTIONS=100
export CGROK_REQUEST_TIMEOUT=30000
export CGROK_RATE_LIMIT_WINDOW=60000
export CGROK_RATE_LIMIT_MAX=100
export CGROK_ENABLE_AUTH=false
export CGROK_AUTH_TOKEN=your_secret_token
export CGROK_ENABLE_BASIC_AUTH=false
export CGROK_BASIC_AUTH_USERNAME=admin
export CGROK_BASIC_AUTH_PASSWORD=secure_password
export CGROK_ENABLE_METRICS=true
export CGROK_LOG_LEVEL=info
export CGROK_HUMAN_READABLE_IDS=true
export CGROK_ID_LENGTH=6
export CGROK_INCLUDE_TIMESTAMP=false
export CGROK_ENABLE_CUSTOM_SUBDOMAINS=trueCLI Arguments
cgrok-server --port 5001 \
--max-connections 100 \
--enable-auth \
--auth-token your_token \
--enable-metrics🚀 Why CGrok Server?
vs. Third-Party Services (ngrok, etc.)
| Feature | CGrok Server (Self-Hosted) | ngrok Free | ngrok Paid | |---------|----------------------------|------------|------------| | Custom domains | ✅ Unlimited | ❌ No | ✅ Limited | | Data privacy | ✅ Your servers | ❌ Third-party | ❌ Third-party | | Cost | ✅ Free (hosting only) | ⚠️ Limited | 💰 $8-65/mo | | Authentication | ✅ Token + Basic Auth | ❌ No | ⚠️ Basic | | Rate limiting | ✅ Configurable | ❌ No | ⚠️ Limited | | Real-time metrics | ✅ Included | ❌ No | ⚠️ Limited | | Team sharing | ✅ Free | ❌ No | 💰 Extra cost | | Request limits | ✅ None | ❌ 40/min | ⚠️ Varies | | Connection time | ✅ Unlimited | ❌ 2hrs | ✅ Unlimited | | Custom subdomains | ✅ Yes | ❌ No | ⚠️ Limited |
vs. Other Self-Hosted Solutions
- ⚡ Faster than frp - Built with Bun runtime
- 🎯 Simpler than Cloudflare Tunnel - No complex setup
- 🛠️ More flexible than localtunnel - Authentication + custom subdomains
- 📦 Lighter than traefik - Specifically for development tunneling
- 📊 Built-in metrics - Real-time tracking without additional tools
- 🔐 Authentication - Token and basic auth support
- 🔄 Daemon management - Background process control
⚡ Quick Start (5 minutes)
Prerequisites
You need a server/VPS with:
- Ubuntu/Debian or similar Linux distribution
- Node.js >= 16.0.0 (or Bun >= 1.0)
- Domain name pointing to your server
Install Server
# Install globally
npm install -g @crisego/cgrok-server
# Or with Yarn
yarn global add @crisego/cgrok-server
# Or with pnpm
pnpm add -g @crisego/cgrok-serverSetup with Interactive Wizard
# Run interactive setup
cgrok-server --setup
# This will guide you through:
# - Domain configuration
# - Authentication setup
# - Port configuration
# - SSL certificate setup (Lets Encrypt)Start Server
# Start in foreground
cgrok-server
# Or start as daemon
cgrok-server --daemon
# Check status
cgrok-server --status
# Stop daemon
cgrok-server --stop-daemon
# Restart daemon
cgrok-server --restart-daemonAccess Your Server
🌐 Server running at: https://tunnel.yourdomain.com
📊 Health check: https://tunnel.yourdomain.com/_health
📈 Metrics: https://tunnel.yourdomain.com/_metrics
✨ WebSocket endpoint: wss://tunnel.yourdomain.com/_tunnelThats it! Your tunneling server is ready. Now install the client on your development machine.
📊 Metrics and Monitoring
The cgrok-server includes comprehensive monitoring capabilities:
Health Check Endpoint
GET /_healthReturns server status, active connections, uptime, and timestamp.
Metrics Endpoint (when enabled)
GET /_metricsReturns detailed statistics including:
- Server Metrics: Active connections, total clients
- Client Metrics: Per-client request counts, response times, error rates
- Performance Data: Average latency, throughput, success rates
Real-Time Logging
The server produces structured logs with timestamps:
🔗 [2024-01-01T12:00:00.000Z] New tunnel: abc123 (client: def456)
📤 [2024-01-01T12:00:01.000Z] Forwarded to CLI: req789 (GET /api/data)
✅ [2024-01-01T12:00:01.150Z] Request completed: req789 -> 200 (150ms)🏗️ Architecture
Flow:
- Internet clients make HTTPS requests to your domain
- cgrok-server receives requests and routes them via WebSocket
- cgrok client receives requests and forwards to localhost
- Response flows back through the same path
Server Features:
- 🔄 WebSocket connection management with heartbeat
- 📊 Real-time metrics collection
- 🗜️ Rate limiting and abuse protection
- 🔐 Authentication and authorization
- ⏱️ Configurable timeouts and validation
- 🧹 Automatic resource cleanup
📋 Complete Setup Guide
1. Domain Configuration
Point your domain to your server:
# A Record
*.tunnel.yourdomain.com → YOUR_SERVER_IP
# Or specific subdomain
tunnel.yourdomain.com → YOUR_SERVER_IP2. SSL Certificate Setup
The interactive setup will automatically configure Lets Encrypt SSL certificates for HTTPS.
3. Server Installation & Configuration
Method 1: Interactive Setup (Recommended)
# Install server
npm install -g @crisego/cgrok-server
# Run setup wizard
cgrok-server --setup
# Start server
cgrok-server --daemonMethod 2: Manual Configuration
# Install server
npm install -g @crisego/cgrok-server
# Create config file
mkdir -p ~/.cgrok-server
nano ~/.cgrok-server/config.json
# Configure your settings
{
"port": 5001,
"maxConnections": 100,
"enableAuth": true,
"authToken": "your_secret_token",
"enableMetrics": true,
"enableCustomSubdomains": true
}
# Start server
cgrok-serverMethod 3: Environment Variables
# Configure in your shell
export CGROK_PORT=5001
export CGROK_ENABLE_AUTH=true
export CGROK_AUTH_TOKEN=your_secret_token
export CGROK_ENABLE_METRICS=true
# Start server
cgrok-server🎯 Use Cases
Development Teams
# Team server configuration
cgrok-server --setup --domain tunnel.company.com
# Developers can now use:
# cgrok --port 3000 --server wss://tunnel.company.com/_tunnel
# Results in: https://abc123.tunnel.company.comWebhook Development
# Configure server with authentication
cgrok-server --enable-auth --auth-token webhook_secret
# Developers use token for webhook testing
# cgrok --port 3000 --token webhook_secretAPI Testing & Demos
# Enable custom subdomains for organized testing
cgrok-server --enable-custom-subdomains
# Developers can request specific names
# cgrok --port 3000 --subdomain api-demo
# Results in: https://api-demo.tunnel.company.comSecure Internal Access
# Enable basic auth for internal tools
cgrok-server --enable-basic-auth --basic-auth-username admin
# Access internal services securely
# https://admin:[email protected]🔧 Advanced Configuration Options
Authentication
Token Authentication
{
"enableAuth": true,
"authToken": "single_token_string"
}Or multiple tokens:
{
"enableAuth": true,
"authToken": ["token1", "token2", "admin_token"]
}Basic Authentication
{
"enableBasicAuth": true,
"basicAuthUsername": "admin",
"basicAuthPassword": "secure_password"
}Rate Limiting
{
"rateLimitWindow": 60000, // Time window in ms
"rateLimitMax": 100 // Max requests per window
}Connection Management
{
"maxConnections": 100, // Maximum concurrent tunnels
"requestTimeout": 30000 // Request timeout in ms
}ID Generation
{
"humanReadableIds": true, // Use readable IDs instead of random
"idLength": 6, // Length of generated IDs
"includeTimestamp": false, // Include timestamp in IDs
"enableCustomSubdomains": true // Allow custom subdomain requests
}📖 Complete Usage Guide
Command Line Options
Usage: cgrok-server [options]
Server Configuration:
--port PORT Server port (default: 5001)
--max-connections NUM Maximum concurrent connections
--request-timeout MS Request timeout in milliseconds
--rate-limit-window MS Rate limit time window
--rate-limit-max NUM Maximum requests per rate limit window
Authentication:
--enable-auth Enable token authentication
--auth-token TOKEN Authentication token(s)
--enable-basic-auth Enable basic authentication
--basic-auth-username USER Basic auth username
--basic-auth-password PASS Basic auth password
Features:
--enable-metrics Enable metrics collection
--log-level LEVEL Log level (error, warn, info, debug)
--human-readable-ids Use human-readable subdomain IDs
--id-length NUM Length of generated IDs
--include-timestamp Include timestamp in generated IDs
--enable-custom-subdomains Allow clients to specify custom subdomains
Management:
--interactive Run in interactive mode
--config PATH Path to configuration file
--setup Run interactive setup to configure server
--daemon, -d Start server as daemon in background
--stop-daemon, -k Stop the running daemon
--restart-daemon, -r Restart the daemon
--status, -s Show daemon status
--version, -V Show version number
Examples:
# Basic server
cgrok-server --port 5001
# With authentication
cgrok-server --enable-auth --auth-token secret_token
# Full configuration
cgrok-server --port 5001 --max-connections 100 \
--enable-auth --auth-token token \
--enable-metrics --daemonConfiguration Priority
- Command-line arguments (highest)
- Configuration file (
~/.cgrok-server/config.json) - Environment variables
- Default values (lowest)
🔒 Security & Authentication
Token-Based Auth
When enabled, clients must include the token:
# WebSocket connections (automatic in cgrok client)
Authorization: Bearer your_secret_token
# HTTP requests to protected endpoints
curl -H "Authorization: Bearer your_secret_token" \
https://tunnel.yourdomain.com/_metricsBasic Authentication
For web-based access to metrics and health endpoints:
# Access protected endpoints
curl -u admin:password https://tunnel.yourdomain.com/_metricsSecurity Best Practices
- ✅ Use strong tokens for production servers
- ✅ Enable HTTPS with valid SSL certificates
- ✅ Configure rate limiting to prevent abuse
- ✅ Use basic auth for web access to sensitive endpoints
- ✅ Rotate tokens periodically
- ⚠️ Dont commit tokens to git
- ⚠️ Use firewall rules to restrict access
📊 Features
🔧 Core Tunneling
- ✅ HTTPS tunneling with custom domains
- ✅ WebSocket-based communication
- ✅ Binary content support (images, PDFs, files)
- ✅ Automatic subdomain generation
- ✅ Custom subdomain support
- ✅ Connection persistence with heartbeat
🌐 Connectivity
- ✅ Configurable timeouts
- ✅ Automatic cleanup of dead connections
- ✅ Graceful shutdown with client notification
- ✅ Request validation and size limits (10MB)
- ✅ Header filtering and security
📈 Monitoring
- ✅ Health check endpoint (
/_health) - ✅ Metrics endpoint (
/_metrics) with detailed statistics - ✅ Structured logging with timestamps
- ✅ Per-client performance tracking
- ✅ Real-time connection monitoring
⚙️ Configuration
- ✅ Environment variables
- ✅ Command-line options
- ✅ Persistent configuration file
- ✅ Interactive setup wizard
- ✅ Token and basic authentication
🔄 Management
- ✅ Daemon mode with background operation
- ✅ Start/stop/restart commands
- ✅ Status monitoring
- ✅ PID file management
- ✅ Automatic log rotation
🔍 Self-Hosted Benefits
Full Control
- Host on your infrastructure
- Custom SSL certificates
- Your own domain names
- No third-party dependencies
- Complete audit trail
Cost Savings
- No monthly subscriptions
- Unlimited connections
- Unlimited bandwidth (server limits only)
- Free for unlimited team members
- No per-request charges
Privacy & Security
- Your data never leaves your servers
- End-to-end encryption
- Configurable authentication
- Rate limiting protection
- GDPR/HIPAA friendly
Customization
- Modify server behavior as needed
- Integrate with your monitoring tools
- Custom authentication logic
- Team-specific configurations
- Advanced routing rules
🚨 Troubleshooting
Connection Issues
# Test server health
curl https://tunnel.yourdomain.com/_health
# Check WebSocket connectivity
wscat -c wss://tunnel.yourdomain.com/_tunnel
# Verify SSL certificate
openssl s_client -connect tunnel.yourdomain.com:443
# Check server logs
cgrok-server --statusCommon Errors
Error: Port already in use
# Find process using port
lsof -i :5001
# Kill process or change port
cgrok-server --port 5002Error: Authentication failed
# Verify token configuration
cgrok-server --status
# Check client token matches server
cgrok --port 3000 --token correct_token --verboseError: Rate limit exceeded
# Adjust rate limiting settings
cgrok-server --rate-limit-max 200 --rate-limit-window 120000
# Or disable rate limiting
cgrok-server --rate-limit-max 999999Debug Mode
# Enable debug logging
cgrok-server --log-level debug
# Or with environment variable
CGROK_LOG_LEVEL=debug cgrok-serverDaemon Issues
# Check daemon status
cgrok-server --status
# View daemon logs
tail -f ~/.cgrok-server/daemon.log
# Restart daemon
cgrok-server --restart-daemon📦 Related Packages
- cgrok - Client component (required)
- Coming soon: cgrok-web - Web UI for server management
🤝 Contributing
Contributions welcome! This is a community project.
# Fork and clone
git clone https://github.com/cristiangonsevi/cgrok-server.git
cd cgrok-server
# Install dependencies
bun install
# Make changes
# ...
# Test locally
bun run index.ts
# Build
npm run build
# Submit PR📄 License
MIT License - see LICENSE file.
🔗 Links
- Server (this repo): github.com/cristiangonsevi/cgrok-server
- Client: github.com/cristiangonsevi/cgrok
- npm Package: npmjs.com/package/cgrok-server
- Issues: github.com/cristiangonsevi/cgrok-server/issues
- Author: Cristian Gonzalez
⭐ If CGrok helps you, please star both repos! ⭐
Made with ❤️ for the self-hosting community
