Skip to content

Repository files navigation

WireGuard VPN Manager

Advanced WireGuard API cho việc tạo, quản lý và bandwidth control của VPN peers.

⚡ Tính năng

  • Tạo peer - Tạo WireGuard peer mới với 10MB bandwidth limit default
  • Xóa peer - Xóa peer theo public key + auto cleanup bandwidth limits
  • 🆕 Bandwidth limiting - Set/update bandwidth limits cho từng peer (1MB-1000MB)
  • IP validation - Tự động assign IP trong range 10.0.0.x
  • Config generation - Tự động tạo client config
  • 🛡️ Safety - Auto cleanup bandwidth limits khi xóa peer

🚀 Setup

npm install
npm run build
npm start
# hoặc với systemd: sudo systemctl start wireguard-api

📡 API

API Key required: X-API-Key: your-key

Tạo Peer (No Automatic Limits)

POST /api/create
{
  "name": "iPhone của Hà"
}

Response:

{
  "success": true,
  "data": {
    "public_key": "abc123...",
    "private_key": "def456...",
    "client_ip": "10.0.0.2",
    "config": "[Interface]\nPrivateKey = ...\n[Peer]\n...",
    "bandwidth_limit_mbps": 0,
    "monthly_data_limit_gb": 0,
    "current_month_usage_gb": 0
  },
  "message": "Peer created successfully without automatic limits - central server will manage bandwidth and data limits",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Xóa Peer

POST /api/delete
{
  "public_key": "abc123..."
}

Response:

{
  "success": true,
  "message": "Peer deleted successfully",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

🆕 Update Bandwidth Limit

POST /api/update-bandwidth
{
  "public_key": "abc123...",
  "limit_mbps": 50
}

Alternative with client_ip:

POST /api/update-bandwidth
{
  "client_ip": "10.0.0.2",
  "limit_mbps": 100
}

Response:

{
  "success": true,
  "client_ip": "10.0.0.2",
  "old_limit_mbps": 10,
  "new_limit_mbps": 50,
  "message": "Bandwidth limit updated successfully",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

🆕 List Bandwidth Limits

GET /api/bandwidth-limits

Response:

{
  "success": true,
  "peer_limits": [
    {
      "ip": "10.0.0.2",
      "limit_mbps": 10,
      "public_key": "abc123..."
    },
    {
      "ip": "10.0.0.3", 
      "limit_mbps": 50,
      "public_key": "def456..."
    }
  ],
  "message": "Found 2 peers with bandwidth limits",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

🔧 CURL Examples

# Tạo peer mới (10Mbps default)
curl -X POST http://localhost:3000/api/create \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{"name": "iPhone Hà"}'

# Xóa peer
curl -X POST http://localhost:3000/api/delete \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{"public_key": "abc123..."}'

# Update bandwidth limit lên 50Mbps
curl -X POST http://localhost:3000/api/update-bandwidth \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "public_key": "abc123...",
    "limit_mbps": 50
  }'

# List all bandwidth limits
curl -X GET http://localhost:3000/api/bandwidth-limits \
  -H "X-API-Key: your-api-key"

# Health check (no API key needed)
curl http://localhost:3000/health

📱 Firebase Integration

// Tạo peer mới (10Mbps default)
const createPeer = async (deviceName) => {
  const response = await fetch('/api/create', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY 
    },
    body: JSON.stringify({ name: deviceName })
  });
  
  return response.json();
};

// Xóa peer
const deletePeer = async (publicKey) => {
  const response = await fetch('/api/delete', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY 
    },
    body: JSON.stringify({ public_key: publicKey })
  });
  
  return response.json();
};

// 🆕 Update bandwidth limit
const updateBandwidth = async (publicKey, limitMbps) => {
  const response = await fetch('/api/update-bandwidth', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY 
    },
    body: JSON.stringify({
      public_key: publicKey,
      limit_mbps: limitMbps
    })
  });
  
  return response.json();
};

// 🆕 Get all bandwidth limits
const getBandwidthLimits = async () => {
  const response = await fetch('/api/bandwidth-limits', {
    method: 'GET',
    headers: { 
      'X-API-Key': API_KEY 
    }
  });
  
  return response.json();
};

// Examples:
// Upgrade to 100Mbps bandwidth
await updateBandwidth(publicKey, 100);

📁 Structure

src/
├── controllers/simple.ts    # 4 endpoints (create, delete, update-bandwidth, bandwidth-limits)
├── routes/simple.ts         # Routing  
├── utils/wireguard.ts       # WireGuard core + bandwidth functions
├── config/app.ts            # Configuration
├── middleware/auth.ts       # API key authentication
├── services/logger.ts       # Logging
├── types/api.ts             # TypeScript interfaces
└── server.ts                # Express server

📋 Requirements

  • Node.js 18+
  • WireGuard installed (sudo apt install wireguard)
  • Traffic Control (tc) available (pre-installed on most Linux systems)
  • sudo access for wg and tc commands
  • systemd service (optional)

🔧 Configuration

// src/config/app.ts
export const config = {
  wireguard: {
    serverPublicKey: 'your-server-public-key',
    serverEndpoint: 'your-server-ip',
    serverPort: 51820
  },
  auth: {
    apiKey: 'your-api-key'
  }
};

🎯 Architecture

Firebase App ↔ API Server ↔ WireGuard Server
                    ↓
            Linux Traffic Control (tc)
  • Firebase: User management, payments, UI, bandwidth controls
  • API Server: Peer management + bandwidth limiting logic
  • WireGuard: VPN server
  • Traffic Control: Linux kernel bandwidth shaping (HTB + filters)

🆕 Core Features:

  • 10Mbps default: All new peers start with 10Mbps limit (free tier)
  • 🆕 Bandwidth limiting: 1Mbps-1000Mbps per peer using Linux TC
  • 🆕 Auto-cleanup: Bandwidth limits removed when peer deleted
  • Simple management: Create, delete, update bandwidth, list limits

🔧 Bandwidth Implementation:

  • Linux Traffic Control (tc) with Hierarchical Token Bucket (HTB)
  • Per-peer classes: 1:10X where X = IP last octet + 100
  • Bidirectional limiting: Both upload and download controlled
  • Automatic cleanup: Limits removed when peer deleted
  • Default 10Mbps: All new peers start with 10Mbps limit

🚀 Deployment

# Build
npm run build

# Start
npm start

# hoặc với PM2
pm2 start dist/server.js --name wireguard-api

# hoặc với systemd
sudo systemctl enable wireguard-api
sudo systemctl start wireguard-api

🛡️ Safety Features

Automatic Cleanup:

  • Graceful bandwidth errors: Peer creation doesn't fail if TC fails
  • ✅ Auto-cleanup bandwidth limits when peer deleted
  • ✅ Comprehensive audit logging
  • ✅ Consistent error handling

Error Recovery:

# Check bandwidth limits:
sudo tc class show dev wg0
sudo tc filter show dev wg0

# Reset all bandwidth limits:
sudo tc qdisc del dev wg0 root

📖 Error Handling

API trả về consistent error format:

{
  "success": false,
  "error": "Failed to update bandwidth limit",
  "message": "Bandwidth limit must be between 1 and 1000 Mbps",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Common errors:

  • 400 - Missing required fields, invalid bandwidth limit
  • 404 - Peer not found in WireGuard config
  • 500 - WireGuard command failed
  • 401 - Invalid API key

Bandwidth-specific errors:

  • Bandwidth limit out of range (1-1000Mbps)
  • Traffic Control command failed
  • Peer IP not found for bandwidth update
  • TC qdisc setup failed

💡 Usage Scenarios

Freemium Model:

// New user: 10Mbps default
await createPeer("New User Device");

// Premium upgrade: 100Mbps
await updateBandwidth(publicKey, 100);

// Enterprise: 1000Mbps (1Gbps)
await updateBandwidth(publicKey, 1000);

Tiered Plans:

// Free tier: 10Mbps (default)
await createPeer("Free User");

// Basic: 50Mbps
await updateBandwidth(publicKey, 50);

// Pro: 200Mbps
await updateBandwidth(publicKey, 200);

// Business: 500Mbps
await updateBandwidth(publicKey, 500);

Simple. Fast. Production-Ready. Bandwidth-Controlled. 🚀

WireGuard Server with Monthly Data Limits

API server for managing WireGuard peers with bandwidth and monthly data limit controls.

Features

  • Peer Management: Create and delete WireGuard peers
  • Bandwidth Control: Set upload/download speed limits (1-1000 Mbps)
  • Monthly Data Limits: Set monthly data usage limits (1-100 GB) with automatic enforcement
  • Usage Tracking: Real-time monitoring of data consumption
  • Automatic Enforcement: Bandwidth throttled when monthly limit is exceeded

API Endpoints

Core Peer Management

Create Peer

POST /api/create
Content-Type: application/json
X-API-Key: your-api-key

{
  "name": "My Device",
  "monthly_data_limit_gb": 2
}

Response:

{
  "success": true,
  "data": {
    "public_key": "...",
    "private_key": "...",
    "client_ip": "10.0.0.2",
    "config": "...",
    "bandwidth_limit_mbps": 10,
    "monthly_data_limit_gb": 2,
    "current_month_usage_gb": 0
  },
  "message": "Peer created successfully with 10Mbps bandwidth limit and 2GB monthly data limit"
}

Delete Peer

POST /api/delete
Content-Type: application/json
X-API-Key: your-api-key

{
  "public_key": "peer_public_key_here"
}

Monthly Data Management

Update Monthly Data Limit

POST /api/update-monthly-limit
Content-Type: application/json
X-API-Key: your-api-key

{
  "public_key": "peer_public_key_here",
  "monthly_limit_gb": 5
}

Response:

{
  "success": true,
  "client_ip": "10.0.0.2",
  "old_limit_gb": 2,
  "new_limit_gb": 5,
  "current_usage_gb": 1.25,
  "usage_percentage": 25.0,
  "message": "Monthly data limit updated successfully"
}

Get Peer Data Usage

GET /api/data-usage/10.0.0.2
X-API-Key: your-api-key

Response:

{
  "success": true,
  "data_usage": {
    "peer_ip": "10.0.0.2",
    "public_key": "...",
    "monthly_limit_gb": 2,
    "current_usage_gb": 1.25,
    "usage_percentage": 62.5,
    "total_bytes": 1342177280,
    "reset_date": "2024-02-01T00:00:00.000Z",
    "is_limit_exceeded": false
  }
}

List All Data Usage

GET /api/data-usage
X-API-Key: your-api-key

Bandwidth Management

Update Bandwidth Limit

POST /api/update-bandwidth
Content-Type: application/json
X-API-Key: your-api-key

{
  "public_key": "peer_public_key_here",
  "limit_mbps": 50
}

List Bandwidth Limits

GET /api/bandwidth-limits
X-API-Key: your-api-key

Configuration

Environment Variables

# Server Configuration
PORT=3000
NODE_ENV=production
API_KEY=your-secure-api-key

# WireGuard Configuration
WIREGUARD_INTERFACE=wg0
WIREGUARD_SERVER_PORT=51820
WIREGUARD_SERVER_IP=10.0.0.1
WIREGUARD_SUBNET=10.0.0.0/24
WIREGUARD_DNS=8.8.8.8
WIREGUARD_SERVER_PUBLIC_KEY=your_server_public_key
WIREGUARD_SERVER_ENDPOINT=your-server.com

# Monthly Data Limits
DEFAULT_MONTHLY_DATA_LIMIT_GB=2
DATA_RESET_DAY=1

Default Limits

  • Bandwidth: 10 Mbps for new peers
  • Monthly Data: 2 GB per month
  • Data Reset: 1st day of each month
  • Enforcement: Bandwidth throttled to 1 Mbps when monthly limit exceeded

Data Usage Tracking

The system tracks monthly data usage for each peer:

  1. Real-time Monitoring: Usage is updated from WireGuard transfer statistics
  2. Automatic Reset: Usage resets on the 1st day of each month
  3. Limit Enforcement: When monthly limit is exceeded, bandwidth is automatically throttled to 1 Mbps
  4. Restoration: When limit is increased or new month begins, normal bandwidth is restored

Installation

  1. Install dependencies:
npm install
  1. Configure environment variables:
cp .env.example .env
# Edit .env with your configuration
  1. Build and start:
npm run build
npm start

Usage Examples

Create a peer with 5GB monthly limit

curl -X POST http://localhost:3000/api/create \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "name": "Premium User",
    "monthly_data_limit_gb": 5
  }'

Check data usage

curl -X GET http://localhost:3000/api/data-usage/10.0.0.2 \
  -H "X-API-Key: your-api-key"

Increase monthly limit

curl -X POST http://localhost:3000/api/update-monthly-limit \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "client_ip": "10.0.0.2",
    "monthly_limit_gb": 10
  }'

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages