Files
waylume_server/README.md

255 lines
9.3 KiB
Markdown

# Waylume Server
## About
Waylume Server is a self-managing WireGuard VPN node that operates as part of the Waylume VPN infrastructure. Each server instance automatically registers with Supabase, manages WireGuard peer configurations, and responds to connection requests through Supabase Edge Functions. The server is designed for autonomous operation with minimal maintenance requirements.
## Architecture
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Flutter Client │───▶│ Supabase Edge │───▶│ Waylume Server │
│ App │ │ Functions │ │ Node │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ PostgreSQL │ │ WireGuard │
│ Database │ │ Interface │
└─────────────────┘ └─────────────────┘
```
**Client Flow:**
1. Flutter app requests available servers via `vpn-nodes-list` edge function
2. User selects server and requests connection via `connection-request` edge function
3. Edge function calls Waylume Server API to create WireGuard peer
4. Server responds with peer configuration through Supabase
5. Client receives WireGuard config and establishes VPN connection
## Role in Waylume Ecosystem
### Server Registration & Discovery
- **Automatic Registration**: Servers register themselves in the `waylume_servers` table on startup
- **Heartbeat Monitoring**: Continuous health reporting to maintain server availability status
- **Geolocation Integration**: Provides location data for client server selection interface
- **Load Distribution**: Multiple servers can be deployed for geographic distribution and load balancing
### Integration with Supabase Edge Functions
The server's REST API is exclusively accessed through Supabase Edge Functions:
- **`connection-request`**: Calls `POST /api/peers` to create new VPN peers
- **Session Management**: Works with `vpn_sessions` table for connection tracking
- **Configuration Delivery**: Peer configs are delivered through Supabase to clients
### WireGuard Management
- **Interface Initialization**: Automatically configures `wg0` interface on startup
- **Dynamic Peer Creation**: Creates peers with unique keys and IP assignments
- **Traffic Control**: Implements speed limiting and data caps per peer
- **Peer Isolation**: Enforces security rules to prevent peer-to-peer communication
- **Cleanup Operations**: Removes peers and associated configurations on disconnect
## Features
### Self-Managing Operations
- **Zero-Touch Deployment**: Fully automated setup with Docker
- **Health Monitoring**: Built-in health checks and status reporting
- **Automatic Recovery**: Handles WireGuard interface failures and restarts
- **Resource Management**: Efficient peer lifecycle management
### Security & Traffic Control
- **Peer Isolation**: iptables rules prevent peer-to-peer communication
- **Bandwidth Control**: HTB-based speed limiting per peer
- **Data Quotas**: iptables quota enforcement for usage limits
- **IP Management**: Automatic IP assignment from managed subnets
### API Endpoints (Internal Use Only)
> **⚠️ Important**: These endpoints are for internal server management through Supabase Edge Functions only. They are not designed for direct client access and lack authentication for security reasons.
#### `POST /api/peers`
Creates a new WireGuard peer with generated keys and IP assignment.
- **Called by**: `connection-request` edge function
- **Purpose**: Establish new VPN connection for authenticated user
#### `POST /api/peers/delete`
Removes a WireGuard peer and cleans up configuration.
- **Called by**: Session cleanup processes
- **Purpose**: Terminate VPN connections and free resources
#### `POST /api/peers/speed-limit`
Applies bandwidth limitations to specific peers.
- **Called by**: Subscription management functions
- **Purpose**: Enforce plan-based speed limits
#### `POST /api/peers/data-cap`
Sets data usage quotas for peers.
- **Called by**: Usage monitoring systems
- **Purpose**: Enforce plan-based data allowances
## Prerequisites
- Docker and Docker Compose
- WireGuard kernel module support
- Supabase project with proper database schema
- Network capabilities for WireGuard interface management
## Environment Variables
Create a `.env` file with the following variables:
```env
# Supabase Configuration
SUPABASE_URL=your_supabase_project_url
SUPABASE_KEY=your_supabase_anon_key
# Server Configuration
SERVER_ID=unique_server_identifier
EXTERNAL_PORT=3000
# Load Balancing Configuration
MAX_CAPACITY=1000
# Optional: Geographic Information
SERVER_COUNTRY=United Kingdom
SERVER_CITY=London
SERVER_COORDS_LAT=51.5074
SERVER_COORDS_LON=-0.1278
```
## Configuration Details
### Load Balancing
**MAX_CAPACITY** (integer, default: 1000)
- Soft capacity limit for the server
- When reached, the load balancer will prioritize other servers
- Does not prevent new connections, just influences routing decisions
- Range: 1-32,767 (int2)
- Used by the Supabase Edge Function `connection-request` for optimal server selection
### Server Registration
**SERVER_ID** (string, required)
- Unique identifier for the server in the Waylume network
- Used for rolling codes authentication and session tracking
- Should be URL-safe (alphanumeric with hyphens/underscores)
**Geographic Information** (optional but recommended)
- Enables location-based server selection for premium users
- Improves load distribution across regions
- Required for the location selection feature in the client app
## Quick Deployment
### Using Docker Compose (Recommended)
1. Clone the repository
2. Create your `.env` file with required Supabase credentials
3. Deploy the server:
```bash
docker-compose up -d
```
The server will:
- Initialize WireGuard interface (`wg0`)
- Register with your Supabase backend
- Begin heartbeat monitoring
- Start accepting API requests on port 3000
### Verification
Check that the server registered successfully:
```sql
-- In your Supabase SQL editor
SELECT * FROM waylume_servers WHERE id = 'your_server_id';
```
## Network Configuration
- **WireGuard Interface**: `wg0` on `10.0.0.1/24`
- **Peer IP Range**: `10.0.0.2` - `10.255.255.254`
- **WireGuard Port**: `51820/udp`
- **API Port**: `3000/tcp` (internal access only)
## Production Deployment
### Security Considerations
- Deploy behind a firewall with port 3000 restricted to Supabase Edge Functions
- Use private networks when possible for API communication
- Implement network segmentation for additional security
- Monitor logs for unusual API access patterns
### Scaling Strategy
- Deploy multiple servers across different geographic regions
- Use unique `SERVER_ID` values for each instance
- Monitor server load through Supabase analytics
- Implement auto-scaling based on connection demand
### Monitoring & Maintenance
- Server health is automatically reported to Supabase
- Monitor `waylume_servers` table for server availability
- Check Docker logs for operational issues
- WireGuard interface status is self-managed
## Development
### Project Structure
```
lib/
├── config/ # Supabase configuration and credentials
├── core/ # Utility functions and helpers
├── services/ # Core services (server, heartbeat, wireguard)
├── web/ # HTTP routes and API handlers
├── wireguard/ # WireGuard-specific functionality
└── main.dart # Application entry point and server initialization
```
### Testing Server Integration
You can test the integration by triggering a connection request through your Supabase Edge Functions:
```bash
# Test server listing
curl -X GET https://your-project.supabase.co/functions/v1/vpn-nodes-list
# Test connection request (requires authentication)
curl -X POST https://your-project.supabase.co/functions/v1/connection-request \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"server_id": "your_server_id"}'
```
## Troubleshooting
### Common Issues
**Server not appearing in node list:**
- Check Supabase credentials in `.env`
- Verify server registered in `waylume_servers` table
- Ensure heartbeat process is running
**WireGuard interface issues:**
- Verify WireGuard kernel module is loaded: `lsmod | grep wireguard`
- Check Docker has `NET_ADMIN` capability
- Ensure `/dev/net/tun` is accessible
**API connectivity problems:**
- Verify port 3000 is accessible from Supabase Edge Functions
- Check firewall rules and network configuration
- Review Docker logs for startup errors
### Logging
The server provides comprehensive logging including:
- Supabase registration and heartbeat status
- WireGuard interface management
- API request processing
- Peer lifecycle events
- Error conditions and recovery attempts
Monitor logs with:
```bash
docker-compose logs -f waylume-server
```