Advanced WireGuard API cho việc tạo, quản lý và bandwidth control của VPN peers.
- 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
npm install
npm run build
npm start
# hoặc với systemd: sudo systemctl start wireguard-apiAPI Key required: X-API-Key: your-key
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"
}POST /api/delete
{
"public_key": "abc123..."
}Response:
{
"success": true,
"message": "Peer deleted successfully",
"timestamp": "2024-01-01T00:00:00.000Z"
}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"
}GET /api/bandwidth-limitsResponse:
{
"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"
}# 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// 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);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
- 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)
// src/config/app.ts
export const config = {
wireguard: {
serverPublicKey: 'your-server-public-key',
serverEndpoint: 'your-server-ip',
serverPort: 51820
},
auth: {
apiKey: 'your-api-key'
}
};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)
- 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
- Linux Traffic Control (tc) with Hierarchical Token Bucket (HTB)
- Per-peer classes:
1:10Xwhere 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
# 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- ✅ Graceful bandwidth errors: Peer creation doesn't fail if TC fails
- ✅ Auto-cleanup bandwidth limits when peer deleted
- ✅ Comprehensive audit logging
- ✅ Consistent error handling
# 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 rootAPI 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"
}400- Missing required fields, invalid bandwidth limit404- Peer not found in WireGuard config500- WireGuard command failed401- Invalid API key
- Bandwidth limit out of range (1-1000Mbps)
- Traffic Control command failed
- Peer IP not found for bandwidth update
- TC qdisc setup failed
// New user: 10Mbps default
await createPeer("New User Device");
// Premium upgrade: 100Mbps
await updateBandwidth(publicKey, 100);
// Enterprise: 1000Mbps (1Gbps)
await updateBandwidth(publicKey, 1000);// 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. 🚀
API server for managing WireGuard peers with bandwidth and monthly data limit controls.
- 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
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"
}POST /api/delete
Content-Type: application/json
X-API-Key: your-api-key
{
"public_key": "peer_public_key_here"
}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 /api/data-usage/10.0.0.2
X-API-Key: your-api-keyResponse:
{
"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
}
}GET /api/data-usage
X-API-Key: your-api-keyPOST /api/update-bandwidth
Content-Type: application/json
X-API-Key: your-api-key
{
"public_key": "peer_public_key_here",
"limit_mbps": 50
}GET /api/bandwidth-limits
X-API-Key: your-api-key# 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- 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
The system tracks monthly data usage for each peer:
- Real-time Monitoring: Usage is updated from WireGuard transfer statistics
- Automatic Reset: Usage resets on the 1st day of each month
- Limit Enforcement: When monthly limit is exceeded, bandwidth is automatically throttled to 1 Mbps
- Restoration: When limit is increased or new month begins, normal bandwidth is restored
- Install dependencies:
npm install- Configure environment variables:
cp .env.example .env
# Edit .env with your configuration- Build and start:
npm run build
npm startcurl -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
}'curl -X GET http://localhost:3000/api/data-usage/10.0.0.2 \
-H "X-API-Key: your-api-key"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
}'