908 lines
31 KiB
Markdown
908 lines
31 KiB
Markdown
# @push.rocks/smartvpn
|
||
|
||
A high-performance VPN with a **TypeScript control plane** and a **Rust data plane daemon**. Manage VPN connections with clean, fully-typed APIs while all networking heavy lifting — encryption, tunneling, QoS, rate limiting — runs at native speed in Rust.
|
||
|
||
🔒 **Noise NK** handshake + **XChaCha20-Poly1305** encryption
|
||
🚀 **Triple transport**: WebSocket (Cloudflare-friendly), raw **QUIC** (datagrams), and **WireGuard** (standard protocol)
|
||
📊 **Adaptive QoS**: packet classification, priority queues, per-client rate limiting
|
||
🔄 **Auto-transport**: tries QUIC first, falls back to WebSocket seamlessly
|
||
📡 **Real-time telemetry**: RTT, jitter, loss, link health — all exposed via typed APIs
|
||
🛡️ **WireGuard mode**: full userspace WireGuard via `boringtun` — generate `.conf` files, manage peers live
|
||
|
||
## Issue Reporting and Security
|
||
|
||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||
|
||
## Install
|
||
|
||
```bash
|
||
pnpm install @push.rocks/smartvpn
|
||
```
|
||
|
||
## 🏗️ Architecture
|
||
|
||
```
|
||
TypeScript (control plane) Rust (data plane)
|
||
┌──────────────────────────┐ ┌────────────────────────────────────┐
|
||
│ VpnClient / VpnServer │ │ smartvpn_daemon │
|
||
│ └─ VpnBridge │──stdio/──▶ │ ├─ management (JSON IPC) │
|
||
│ └─ RustBridge │ socket │ ├─ transport_trait (abstraction) │
|
||
│ (smartrust) │ │ │ ├─ transport (WebSocket/TLS) │
|
||
│ │ │ │ └─ quic_transport (QUIC/UDP) │
|
||
│ WgConfigGenerator │ │ ├─ wireguard (boringtun WG) │
|
||
│ └─ .conf file output │ │ ├─ crypto (Noise NK + XCha20) │
|
||
└──────────────────────────┘ │ ├─ codec (binary framing) │
|
||
│ ├─ keepalive (adaptive state FSM) │
|
||
│ ├─ telemetry (RTT/jitter/loss) │
|
||
│ ├─ qos (classify + priority Q) │
|
||
│ ├─ ratelimit (token bucket) │
|
||
│ ├─ mtu (overhead calc + ICMP) │
|
||
│ ├─ tunnel (TUN device) │
|
||
│ ├─ network (NAT/IP pool) │
|
||
│ └─ reconnect (exp. backoff) │
|
||
└────────────────────────────────────┘
|
||
```
|
||
|
||
**Key design decisions:**
|
||
|
||
| Decision | Choice | Why |
|
||
|----------|--------|-----|
|
||
| Transport | WebSocket + QUIC + WireGuard | WS works through Cloudflare; QUIC gives low latency + datagrams; WG for standard protocol interop |
|
||
| Auto-transport | QUIC first, WS fallback | Best performance when QUIC is available, graceful degradation when it's not |
|
||
| WireGuard | Userspace via `boringtun` | No kernel module needed, runs on any platform, full peer management via IPC |
|
||
| Encryption | Noise NK + XChaCha20-Poly1305 | Strong forward secrecy, large nonce space (no counter sync needed) |
|
||
| QUIC auth | Certificate hash pinning | WireGuard-style trust model — no CA needed, just pin the server cert hash |
|
||
| Keepalive | Adaptive app-level pings | Cloudflare drops WS pings; interval adapts to link health (10–60s) |
|
||
| QoS | Packet classification + priority queues | DNS/SSH/ICMP always drain first; bulk flows get deprioritized |
|
||
| Rate limiting | Per-client token bucket | Byte-granular, dynamically reconfigurable via IPC |
|
||
| IPC | JSON lines over stdio / Unix socket | `stdio` for dev, `socket` for production (daemon stays alive) |
|
||
| Binary protocol | `[type:1B][length:4B][payload:NB]` | Minimal overhead, easy to parse at wire speed |
|
||
|
||
## 🚀 Quick Start
|
||
|
||
### VPN Client
|
||
|
||
```typescript
|
||
import { VpnClient } from '@push.rocks/smartvpn';
|
||
|
||
const client = new VpnClient({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
await client.start();
|
||
|
||
const { assignedIp } = await client.connect({
|
||
serverUrl: 'wss://vpn.example.com/tunnel',
|
||
serverPublicKey: 'BASE64_SERVER_PUBLIC_KEY',
|
||
dns: ['1.1.1.1', '8.8.8.8'],
|
||
mtu: 1420,
|
||
keepaliveIntervalSecs: 30,
|
||
});
|
||
|
||
console.log(`Connected! Assigned IP: ${assignedIp}`);
|
||
|
||
// Connection quality (adaptive keepalive + telemetry)
|
||
const quality = await client.getConnectionQuality();
|
||
console.log(quality);
|
||
// {
|
||
// srttMs: 42.5, jitterMs: 3.2, minRttMs: 38.0, maxRttMs: 67.0,
|
||
// lossRatio: 0.0, consecutiveTimeouts: 0,
|
||
// linkHealth: 'healthy', currentKeepaliveIntervalSecs: 60
|
||
// }
|
||
|
||
// MTU info
|
||
const mtu = await client.getMtuInfo();
|
||
console.log(mtu);
|
||
// { tunMtu: 1420, effectiveMtu: 1421, linkMtu: 1500, overheadBytes: 79, ... }
|
||
|
||
// Traffic stats (includes quality snapshot)
|
||
const stats = await client.getStatistics();
|
||
|
||
await client.disconnect();
|
||
client.stop();
|
||
```
|
||
|
||
### VPN Client with QUIC
|
||
|
||
```typescript
|
||
import { VpnClient } from '@push.rocks/smartvpn';
|
||
|
||
// Explicit QUIC — serverUrl is host:port, pinned by cert hash
|
||
const quicClient = new VpnClient({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
await quicClient.start();
|
||
|
||
const { assignedIp } = await quicClient.connect({
|
||
serverUrl: 'vpn.example.com:443',
|
||
serverPublicKey: 'BASE64_SERVER_PUBLIC_KEY',
|
||
transport: 'quic',
|
||
serverCertHash: 'BASE64_SHA256_CERT_HASH', // printed by server on startup
|
||
});
|
||
|
||
// Or use auto-transport: tries QUIC first (3s timeout), falls back to WS
|
||
const autoClient = new VpnClient({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
await autoClient.start();
|
||
|
||
await autoClient.connect({
|
||
serverUrl: 'wss://vpn.example.com/tunnel', // WS URL — host:port extracted for QUIC attempt
|
||
serverPublicKey: 'BASE64_SERVER_PUBLIC_KEY',
|
||
transport: 'auto', // default — QUIC first, then WS
|
||
});
|
||
```
|
||
|
||
### VPN Client with WireGuard
|
||
|
||
```typescript
|
||
import { VpnClient } from '@push.rocks/smartvpn';
|
||
|
||
const wgClient = new VpnClient({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
await wgClient.start();
|
||
|
||
const { assignedIp } = await wgClient.connect({
|
||
serverPublicKey: 'BASE64_SERVER_WG_PUBLIC_KEY',
|
||
serverUrl: '', // not used for WireGuard
|
||
transport: 'wireguard',
|
||
wgPrivateKey: 'BASE64_CLIENT_PRIVATE_KEY',
|
||
wgAddress: '10.8.0.2',
|
||
wgAddressPrefix: 24,
|
||
wgEndpoint: 'vpn.example.com:51820',
|
||
wgAllowedIps: ['0.0.0.0/0'], // route all traffic
|
||
wgPersistentKeepalive: 25,
|
||
wgPresharedKey: 'OPTIONAL_PSK', // optional extra layer
|
||
dns: ['1.1.1.1'],
|
||
mtu: 1420,
|
||
});
|
||
|
||
console.log(`WireGuard connected! IP: ${assignedIp}`);
|
||
await wgClient.disconnect();
|
||
wgClient.stop();
|
||
```
|
||
|
||
### VPN Server
|
||
|
||
```typescript
|
||
import { VpnServer } from '@push.rocks/smartvpn';
|
||
|
||
const server = new VpnServer({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
// Generate a Noise keypair first
|
||
await server.start();
|
||
const keypair = await server.generateKeypair();
|
||
|
||
// Start the VPN listener
|
||
await server.start({
|
||
listenAddr: '0.0.0.0:443',
|
||
privateKey: keypair.privateKey,
|
||
publicKey: keypair.publicKey,
|
||
subnet: '10.8.0.0/24',
|
||
dns: ['1.1.1.1'],
|
||
mtu: 1420,
|
||
enableNat: true,
|
||
// Transport mode: 'websocket', 'quic', 'both', or 'wireguard'
|
||
transportMode: 'both',
|
||
// Optional: separate QUIC listen address
|
||
quicListenAddr: '0.0.0.0:4433',
|
||
// Optional: QUIC idle timeout
|
||
quicIdleTimeoutSecs: 30,
|
||
// Optional: default rate limit for all new clients
|
||
defaultRateLimitBytesPerSec: 10_000_000, // 10 MB/s
|
||
defaultBurstBytes: 20_000_000, // 20 MB burst
|
||
});
|
||
|
||
// List connected clients
|
||
const clients = await server.listClients();
|
||
|
||
// Per-client rate limiting (live, no reconnect needed)
|
||
await server.setClientRateLimit('client-id', 5_000_000, 10_000_000);
|
||
await server.removeClientRateLimit('client-id'); // unlimited
|
||
|
||
// Per-client telemetry
|
||
const telemetry = await server.getClientTelemetry('client-id');
|
||
console.log(telemetry);
|
||
// {
|
||
// clientId, assignedIp, lastKeepaliveAt, keepalivesReceived,
|
||
// packetsDropped, bytesDropped, bytesReceived, bytesSent,
|
||
// rateLimitBytesPerSec, burstBytes
|
||
// }
|
||
|
||
// Kick a client
|
||
await server.disconnectClient('client-id');
|
||
|
||
await server.stopServer();
|
||
server.stop();
|
||
```
|
||
|
||
### WireGuard Server Mode
|
||
|
||
```typescript
|
||
import { VpnServer } from '@push.rocks/smartvpn';
|
||
|
||
const wgServer = new VpnServer({
|
||
transport: { transport: 'stdio' },
|
||
});
|
||
|
||
// Generate a WireGuard X25519 keypair
|
||
await wgServer.start();
|
||
const keypair = await wgServer.generateWgKeypair();
|
||
console.log(`Server public key: ${keypair.publicKey}`);
|
||
|
||
// Start in WireGuard mode
|
||
await wgServer.start({
|
||
listenAddr: '0.0.0.0:51820',
|
||
privateKey: keypair.privateKey,
|
||
publicKey: keypair.publicKey,
|
||
subnet: '10.8.0.0/24',
|
||
transportMode: 'wireguard',
|
||
wgListenPort: 51820,
|
||
wgPeers: [
|
||
{
|
||
publicKey: 'CLIENT_PUBLIC_KEY_BASE64',
|
||
allowedIps: ['10.8.0.2/32'],
|
||
persistentKeepalive: 25,
|
||
},
|
||
],
|
||
enableNat: true,
|
||
dns: ['1.1.1.1'],
|
||
mtu: 1420,
|
||
});
|
||
|
||
// Live peer management — add/remove peers without restart
|
||
await wgServer.addWgPeer({
|
||
publicKey: 'NEW_CLIENT_PUBLIC_KEY',
|
||
allowedIps: ['10.8.0.3/32'],
|
||
persistentKeepalive: 25,
|
||
});
|
||
|
||
// List peers with live stats
|
||
const peers = await wgServer.listWgPeers();
|
||
for (const peer of peers) {
|
||
console.log(`${peer.publicKey}: ↑${peer.bytesSent} ↓${peer.bytesReceived}`);
|
||
}
|
||
|
||
// Remove a peer by public key
|
||
await wgServer.removeWgPeer('CLIENT_PUBLIC_KEY_BASE64');
|
||
|
||
await wgServer.stopServer();
|
||
wgServer.stop();
|
||
```
|
||
|
||
### Generating WireGuard .conf Files
|
||
|
||
The `WgConfigGenerator` creates standard WireGuard `.conf` files compatible with `wg-quick`, iOS/Android apps, and all standard WireGuard clients:
|
||
|
||
```typescript
|
||
import { WgConfigGenerator } from '@push.rocks/smartvpn';
|
||
|
||
// Client config (for wg-quick or mobile apps)
|
||
const clientConf = WgConfigGenerator.generateClientConfig({
|
||
privateKey: 'CLIENT_PRIVATE_KEY_BASE64',
|
||
address: '10.8.0.2/24',
|
||
dns: ['1.1.1.1', '8.8.8.8'],
|
||
mtu: 1420,
|
||
peer: {
|
||
publicKey: 'SERVER_PUBLIC_KEY_BASE64',
|
||
endpoint: 'vpn.example.com:51820',
|
||
allowedIps: ['0.0.0.0/0', '::/0'],
|
||
persistentKeepalive: 25,
|
||
presharedKey: 'OPTIONAL_PSK_BASE64',
|
||
},
|
||
});
|
||
|
||
// Server config (for wg-quick)
|
||
const serverConf = WgConfigGenerator.generateServerConfig({
|
||
privateKey: 'SERVER_PRIVATE_KEY_BASE64',
|
||
address: '10.8.0.1/24',
|
||
listenPort: 51820,
|
||
dns: ['1.1.1.1'],
|
||
mtu: 1420,
|
||
enableNat: true,
|
||
natInterface: 'eth0', // auto-detected if omitted
|
||
peers: [
|
||
{
|
||
publicKey: 'CLIENT_PUBLIC_KEY_BASE64',
|
||
allowedIps: ['10.8.0.2/32'],
|
||
persistentKeepalive: 25,
|
||
},
|
||
],
|
||
});
|
||
|
||
// Write to disk
|
||
import * as fs from 'fs';
|
||
fs.writeFileSync('/etc/wireguard/wg0.conf', serverConf);
|
||
```
|
||
|
||
<details>
|
||
<summary>Example output: client .conf</summary>
|
||
|
||
```ini
|
||
[Interface]
|
||
PrivateKey = CLIENT_PRIVATE_KEY_BASE64
|
||
Address = 10.8.0.2/24
|
||
DNS = 1.1.1.1, 8.8.8.8
|
||
MTU = 1420
|
||
|
||
[Peer]
|
||
PublicKey = SERVER_PUBLIC_KEY_BASE64
|
||
PresharedKey = OPTIONAL_PSK_BASE64
|
||
Endpoint = vpn.example.com:51820
|
||
AllowedIPs = 0.0.0.0/0, ::/0
|
||
PersistentKeepalive = 25
|
||
```
|
||
|
||
</details>
|
||
|
||
### Production: Socket Transport
|
||
|
||
In production, the daemon runs as a system service and you connect over a Unix socket:
|
||
|
||
```typescript
|
||
const client = new VpnClient({
|
||
transport: {
|
||
transport: 'socket',
|
||
socketPath: '/var/run/smartvpn.sock',
|
||
autoReconnect: true,
|
||
reconnectBaseDelayMs: 100,
|
||
reconnectMaxDelayMs: 30000,
|
||
maxReconnectAttempts: 10,
|
||
},
|
||
});
|
||
|
||
await client.start(); // connects to existing daemon (does not spawn)
|
||
```
|
||
|
||
When using socket transport, `client.stop()` closes the socket but **does not kill the daemon** — exactly what you want in production.
|
||
|
||
## 📋 API Reference
|
||
|
||
### `VpnClient`
|
||
|
||
| Method | Returns | Description |
|
||
|--------|---------|-------------|
|
||
| `start()` | `Promise<boolean>` | Start the daemon bridge (spawn or connect) |
|
||
| `connect(config?)` | `Promise<{ assignedIp }>` | Connect to VPN server (WS, QUIC, or WireGuard) |
|
||
| `disconnect()` | `Promise<void>` | Disconnect from VPN |
|
||
| `getStatus()` | `Promise<IVpnStatus>` | Current connection state |
|
||
| `getStatistics()` | `Promise<IVpnStatistics>` | Traffic stats + connection quality |
|
||
| `getConnectionQuality()` | `Promise<IVpnConnectionQuality>` | RTT, jitter, loss, link health |
|
||
| `getMtuInfo()` | `Promise<IVpnMtuInfo>` | MTU info and overhead breakdown |
|
||
| `stop()` | `void` | Kill/close the daemon bridge |
|
||
| `running` | `boolean` | Whether bridge is active |
|
||
|
||
### `VpnServer`
|
||
|
||
| Method | Returns | Description |
|
||
|--------|---------|-------------|
|
||
| `start(config?)` | `Promise<void>` | Start daemon + VPN server |
|
||
| `stopServer()` | `Promise<void>` | Stop the VPN server |
|
||
| `getStatus()` | `Promise<IVpnStatus>` | Server connection state |
|
||
| `getStatistics()` | `Promise<IVpnServerStatistics>` | Server stats (includes client counts) |
|
||
| `listClients()` | `Promise<IVpnClientInfo[]>` | Connected clients with QoS stats |
|
||
| `disconnectClient(id)` | `Promise<void>` | Kick a client |
|
||
| `generateKeypair()` | `Promise<IVpnKeypair>` | Generate Noise NK keypair |
|
||
| `setClientRateLimit(id, rate, burst)` | `Promise<void>` | Set per-client rate limit (bytes/sec) |
|
||
| `removeClientRateLimit(id)` | `Promise<void>` | Remove rate limit (unlimited) |
|
||
| `getClientTelemetry(id)` | `Promise<IVpnClientTelemetry>` | Per-client telemetry + drop stats |
|
||
| `generateWgKeypair()` | `Promise<IVpnKeypair>` | Generate WireGuard X25519 keypair |
|
||
| `addWgPeer(peer)` | `Promise<void>` | Add a WireGuard peer at runtime |
|
||
| `removeWgPeer(publicKey)` | `Promise<void>` | Remove a WireGuard peer by key |
|
||
| `listWgPeers()` | `Promise<IWgPeerInfo[]>` | List WG peers with traffic stats |
|
||
| `stop()` | `void` | Kill/close the daemon bridge |
|
||
|
||
### `VpnConfig`
|
||
|
||
Static utility class for config validation and file I/O:
|
||
|
||
```typescript
|
||
import { VpnConfig } from '@push.rocks/smartvpn';
|
||
|
||
// Validate (throws on invalid)
|
||
VpnConfig.validateClientConfig(config);
|
||
VpnConfig.validateServerConfig(config);
|
||
|
||
// Load/save JSON configs
|
||
const config = await VpnConfig.loadFromFile<IVpnClientConfig>('/etc/smartvpn/client.json');
|
||
await VpnConfig.saveToFile('/etc/smartvpn/client.json', config);
|
||
```
|
||
|
||
Validation covers both smartvpn-native configs and WireGuard configs — base64 key format, CIDR ranges, port ranges, and required fields are all checked.
|
||
|
||
### `WgConfigGenerator`
|
||
|
||
Static generator for standard WireGuard `.conf` files:
|
||
|
||
| Method | Returns | Description |
|
||
|--------|---------|-------------|
|
||
| `generateClientConfig(opts)` | `string` | Generate a `wg-quick` compatible client `.conf` |
|
||
| `generateServerConfig(opts)` | `string` | Generate a `wg-quick` compatible server `.conf` with NAT rules |
|
||
|
||
Output is compatible with `wg-quick`, WireGuard iOS/Android apps, and any standard WireGuard implementation.
|
||
|
||
### `VpnInstaller`
|
||
|
||
Generate system service units for the daemon:
|
||
|
||
```typescript
|
||
import { VpnInstaller } from '@push.rocks/smartvpn';
|
||
|
||
const platform = VpnInstaller.detectPlatform(); // 'linux' | 'macos' | 'windows' | 'unknown'
|
||
|
||
// Linux (systemd)
|
||
const unit = VpnInstaller.generateSystemdUnit({
|
||
binaryPath: '/usr/local/bin/smartvpn_daemon',
|
||
socketPath: '/var/run/smartvpn.sock',
|
||
mode: 'server',
|
||
});
|
||
|
||
// macOS (launchd)
|
||
const plist = VpnInstaller.generateLaunchdPlist({
|
||
binaryPath: '/usr/local/bin/smartvpn_daemon',
|
||
socketPath: '/var/run/smartvpn.sock',
|
||
mode: 'client',
|
||
});
|
||
|
||
// Auto-detect platform
|
||
const serviceUnit = VpnInstaller.generateServiceUnit({
|
||
binaryPath: '/usr/local/bin/smartvpn_daemon',
|
||
socketPath: '/var/run/smartvpn.sock',
|
||
mode: 'server',
|
||
});
|
||
```
|
||
|
||
### Events
|
||
|
||
Both `VpnClient` and `VpnServer` extend `EventEmitter`:
|
||
|
||
```typescript
|
||
client.on('exit', ({ code, signal }) => { /* daemon exited */ });
|
||
client.on('reconnected', () => { /* socket reconnected */ });
|
||
client.on('status', (status) => { /* IVpnStatus update */ });
|
||
client.on('error', (error) => { /* error from daemon */ });
|
||
|
||
server.on('client-connected', (info) => { /* IVpnClientInfo */ });
|
||
server.on('client-disconnected', ({ clientId, reason }) => { /* ... */ });
|
||
server.on('started', () => { /* server listener started */ });
|
||
server.on('stopped', () => { /* server listener stopped */ });
|
||
```
|
||
|
||
## 🌐 Transport Modes
|
||
|
||
smartvpn supports three transport protocols. The smartvpn-native transports (WebSocket + QUIC) share the same encryption, framing, and QoS pipeline. WireGuard mode uses the standard WireGuard protocol for broad interoperability.
|
||
|
||
### WebSocket (default for smartvpn-native)
|
||
|
||
- Works through Cloudflare, reverse proxies, and HTTP load balancers
|
||
- Reliable delivery only (no datagram support)
|
||
- URL format: `wss://host/path` or `ws://host:port/path`
|
||
|
||
### QUIC
|
||
|
||
- Lower latency, built-in multiplexing, 0-RTT connection establishment
|
||
- Supports **unreliable datagrams** for IP packets (with automatic fallback to reliable if oversized)
|
||
- Certificate hash pinning — no CA chain needed, WireGuard-style trust
|
||
- URL format: `host:port`
|
||
- ALPN protocol: `smartvpn`
|
||
|
||
### WireGuard
|
||
|
||
- Standard WireGuard protocol via `boringtun` (userspace, no kernel module)
|
||
- Compatible with **all WireGuard clients** — iOS, Android, macOS, Windows, Linux, routers
|
||
- X25519 key exchange, ChaCha20-Poly1305 encryption
|
||
- Dynamic peer management at runtime (add/remove without restart)
|
||
- Optional preshared keys for post-quantum defense-in-depth
|
||
- Generate `.conf` files for standard clients via `WgConfigGenerator`
|
||
- Default port: `51820/UDP`
|
||
|
||
### Auto-Transport (Recommended for smartvpn-native)
|
||
|
||
The default `transport: 'auto'` mode gives you the best of both worlds:
|
||
|
||
1. Extract `host:port` from the WebSocket URL
|
||
2. Attempt QUIC connection (3-second timeout)
|
||
3. If QUIC fails or times out → fall back to WebSocket
|
||
4. Completely transparent to the application
|
||
|
||
```typescript
|
||
await client.connect({
|
||
serverUrl: 'wss://vpn.example.com/tunnel',
|
||
serverPublicKey: '...',
|
||
transport: 'auto', // default — QUIC first, WS fallback
|
||
});
|
||
```
|
||
|
||
### Server Dual-Mode / Multi-Mode
|
||
|
||
The server can listen on multiple transports simultaneously:
|
||
|
||
```typescript
|
||
// WebSocket + QUIC (dual mode)
|
||
await server.start({
|
||
listenAddr: '0.0.0.0:443', // WebSocket listener
|
||
quicListenAddr: '0.0.0.0:4433', // QUIC listener (optional, defaults to listenAddr)
|
||
transportMode: 'both', // 'websocket' | 'quic' | 'both' | 'wireguard'
|
||
quicIdleTimeoutSecs: 30,
|
||
// ... other config
|
||
});
|
||
|
||
// WireGuard standalone
|
||
await server.start({
|
||
listenAddr: '0.0.0.0:51820',
|
||
transportMode: 'wireguard',
|
||
wgListenPort: 51820,
|
||
wgPeers: [{ publicKey: '...', allowedIps: ['10.8.0.2/32'] }],
|
||
// ... other config
|
||
});
|
||
```
|
||
|
||
When using `'both'` mode, the server logs the QUIC certificate hash on startup — share this with clients for cert pinning.
|
||
|
||
## 📊 QoS System
|
||
|
||
The Rust daemon includes a full QoS stack that operates on decrypted IP packets:
|
||
|
||
### Adaptive Keepalive
|
||
|
||
The keepalive system automatically adjusts its interval based on connection quality:
|
||
|
||
| Link Health | Keepalive Interval | Triggered When |
|
||
|-------------|-------------------|----------------|
|
||
| 🟢 Healthy | 60s | Jitter < 30ms, loss < 2%, no timeouts |
|
||
| 🟡 Degraded | 30s | Jitter > 50ms, loss > 5%, or 1+ timeout |
|
||
| 🔴 Critical | 10s | Loss > 20% or 2+ consecutive timeouts |
|
||
|
||
State transitions include hysteresis (3 consecutive good checks to upgrade, 2 to recover) to prevent flapping. Dead peer detection fires after 3 consecutive timeouts in Critical state.
|
||
|
||
### Packet Classification
|
||
|
||
IP packets are classified into three priority levels by inspecting headers (no deep packet inspection):
|
||
|
||
| Priority | Traffic |
|
||
|----------|---------|
|
||
| **High** | ICMP, DNS (port 53), SSH (port 22), small packets (< 128 bytes) |
|
||
| **Normal** | Everything else |
|
||
| **Low** | Bulk flows exceeding 1 MB within a 60s window |
|
||
|
||
Priority channels drain with biased `tokio::select!` — high-priority packets always go first.
|
||
|
||
### Smart Packet Dropping
|
||
|
||
Under backpressure, packets are dropped intelligently:
|
||
|
||
1. **Low** queue full → drop silently
|
||
2. **Normal** queue full → drop
|
||
3. **High** queue full → wait 5ms, then drop as last resort
|
||
|
||
Drop statistics are tracked per priority level and exposed via telemetry.
|
||
|
||
### Per-Client Rate Limiting
|
||
|
||
Token bucket algorithm with byte granularity:
|
||
|
||
```typescript
|
||
// Set: 10 MB/s sustained, 20 MB burst
|
||
await server.setClientRateLimit('client-id', 10_000_000, 20_000_000);
|
||
|
||
// Check drops via telemetry
|
||
const t = await server.getClientTelemetry('client-id');
|
||
console.log(`Dropped: ${t.packetsDropped} packets, ${t.bytesDropped} bytes`);
|
||
|
||
// Remove limit
|
||
await server.removeClientRateLimit('client-id');
|
||
```
|
||
|
||
Rate limits can be changed live without disconnecting the client.
|
||
|
||
### Path MTU
|
||
|
||
Tunnel overhead is calculated precisely:
|
||
|
||
| Layer | Bytes |
|
||
|-------|-------|
|
||
| IP header | 20 |
|
||
| TCP header (with timestamps) | 32 |
|
||
| WebSocket framing | 6 |
|
||
| VPN frame header | 5 |
|
||
| Noise AEAD tag | 16 |
|
||
| **Total overhead** | **79** |
|
||
|
||
For a standard 1500-byte Ethernet link, effective TUN MTU = **1421 bytes**. The default TUN MTU of 1420 is conservative and correct. Oversized packets get an ICMP "Fragmentation Needed" (Type 3, Code 4) written back into the TUN, so the source TCP adjusts its MSS automatically.
|
||
|
||
## 🔐 Security Model
|
||
|
||
### smartvpn-native (WebSocket / QUIC)
|
||
|
||
The VPN uses a **Noise NK** handshake pattern:
|
||
|
||
1. **NK** = client does **N**ot authenticate, but **K**nows the server's static public key
|
||
2. The client generates an ephemeral keypair, performs `e, es` (DH with server's static key)
|
||
3. Server responds with `e, ee` (DH with both ephemeral keys)
|
||
4. Result: forward-secret transport keys derived from both DH operations
|
||
|
||
Post-handshake, all IP packets are encrypted with **XChaCha20-Poly1305**:
|
||
- 24-byte random nonces (no counter synchronization needed)
|
||
- 16-byte authentication tags
|
||
- Wire format: `[nonce:24B][ciphertext:var][tag:16B]`
|
||
|
||
### WireGuard Mode
|
||
|
||
Uses the standard [Noise IKpsk2](https://www.wireguard.com/protocol/) handshake:
|
||
- **X25519** key exchange (Curve25519 Diffie-Hellman)
|
||
- **ChaCha20-Poly1305** AEAD encryption
|
||
- Optional **preshared keys** for post-quantum defense-in-depth
|
||
- Implemented via `boringtun` — Cloudflare's userspace WireGuard in Rust
|
||
|
||
### QUIC Certificate Pinning
|
||
|
||
When using QUIC transport, the server generates a self-signed TLS certificate (or uses a configured PEM). Instead of relying on a CA chain, clients pin the server's certificate by its **SHA-256 hash** (base64-encoded) — a WireGuard-inspired trust model:
|
||
|
||
```typescript
|
||
// Server logs the cert hash on startup:
|
||
// "QUIC cert hash: <BASE64_HASH>"
|
||
|
||
// Client pins it:
|
||
await client.connect({
|
||
serverUrl: 'vpn.example.com:443',
|
||
transport: 'quic',
|
||
serverCertHash: '<BASE64_HASH>',
|
||
serverPublicKey: '...',
|
||
});
|
||
```
|
||
|
||
## 📦 Binary Protocol
|
||
|
||
Inside the tunnel (both WebSocket and QUIC reliable channels), packets use a simple binary framing:
|
||
|
||
```
|
||
┌──────────┬──────────┬────────────────────┐
|
||
│ Type (1B)│ Len (4B) │ Payload (variable) │
|
||
└──────────┴──────────┴────────────────────┘
|
||
```
|
||
|
||
| Type | Value | Description |
|
||
|------|-------|-------------|
|
||
| `HandshakeInit` | `0x01` | Client → Server handshake |
|
||
| `HandshakeResp` | `0x02` | Server → Client handshake |
|
||
| `IpPacket` | `0x10` | Encrypted IP packet |
|
||
| `Keepalive` | `0x20` | App-level ping (8-byte timestamp payload) |
|
||
| `KeepaliveAck` | `0x21` | App-level pong (echoes timestamp for RTT) |
|
||
| `SessionResume` | `0x30` | Resume a dropped session |
|
||
| `SessionResumeOk` | `0x31` | Resume accepted |
|
||
| `SessionResumeErr` | `0x32` | Resume rejected |
|
||
| `Disconnect` | `0x3F` | Graceful disconnect |
|
||
|
||
When QUIC datagrams are available, IP packets can optionally be sent via the unreliable datagram channel for lower latency. Packets that exceed the max datagram size automatically fall back to the reliable stream.
|
||
|
||
> **Note:** WireGuard mode uses the standard WireGuard wire protocol, not this binary framing.
|
||
|
||
## 🛠️ Rust Daemon CLI
|
||
|
||
```bash
|
||
# Development: stdio management (JSON lines on stdin/stdout)
|
||
smartvpn_daemon --management --mode client
|
||
smartvpn_daemon --management --mode server
|
||
|
||
# Production: Unix socket management
|
||
smartvpn_daemon --management-socket /var/run/smartvpn.sock --mode server
|
||
|
||
# Generate a Noise keypair
|
||
smartvpn_daemon --generate-keypair
|
||
```
|
||
|
||
## 🔧 Building from Source
|
||
|
||
```bash
|
||
# Install dependencies
|
||
pnpm install
|
||
|
||
# Build TypeScript + cross-compile Rust (amd64 + arm64)
|
||
pnpm build
|
||
|
||
# Build Rust only (debug)
|
||
cd rust && cargo build
|
||
|
||
# Run all tests (82 Rust + 77 TypeScript)
|
||
cd rust && cargo test
|
||
pnpm test
|
||
```
|
||
|
||
## 📘 TypeScript Interfaces
|
||
|
||
<details>
|
||
<summary>Click to expand full type definitions</summary>
|
||
|
||
```typescript
|
||
// Transport options
|
||
type TVpnTransportOptions =
|
||
| { transport: 'stdio' }
|
||
| {
|
||
transport: 'socket';
|
||
socketPath: string;
|
||
autoReconnect?: boolean;
|
||
reconnectBaseDelayMs?: number;
|
||
reconnectMaxDelayMs?: number;
|
||
maxReconnectAttempts?: number;
|
||
};
|
||
|
||
// Client config
|
||
interface IVpnClientConfig {
|
||
serverUrl: string; // WS: 'wss://host/path' | QUIC: 'host:port'
|
||
serverPublicKey: string; // Base64-encoded Noise static key (or WG public key)
|
||
transport?: 'auto' | 'websocket' | 'quic' | 'wireguard'; // Default: 'auto'
|
||
serverCertHash?: string; // SHA-256 cert hash (base64) for QUIC pinning
|
||
dns?: string[];
|
||
mtu?: number;
|
||
keepaliveIntervalSecs?: number;
|
||
// WireGuard-specific
|
||
wgPrivateKey?: string; // Client private key (base64, X25519)
|
||
wgAddress?: string; // Client TUN address (e.g. 10.8.0.2)
|
||
wgAddressPrefix?: number; // Address prefix length (default: 24)
|
||
wgPresharedKey?: string; // Optional preshared key (base64)
|
||
wgPersistentKeepalive?: number; // Persistent keepalive interval (seconds)
|
||
wgEndpoint?: string; // Server endpoint (host:port)
|
||
wgAllowedIps?: string[]; // Allowed IPs (CIDR strings)
|
||
}
|
||
|
||
// Server config
|
||
interface IVpnServerConfig {
|
||
listenAddr: string;
|
||
privateKey: string;
|
||
publicKey: string;
|
||
subnet: string;
|
||
tlsCert?: string;
|
||
tlsKey?: string;
|
||
dns?: string[];
|
||
mtu?: number;
|
||
keepaliveIntervalSecs?: number;
|
||
enableNat?: boolean;
|
||
transportMode?: 'websocket' | 'quic' | 'both' | 'wireguard';
|
||
quicListenAddr?: string;
|
||
quicIdleTimeoutSecs?: number;
|
||
defaultRateLimitBytesPerSec?: number;
|
||
defaultBurstBytes?: number;
|
||
// WireGuard-specific
|
||
wgListenPort?: number; // UDP port (default: 51820)
|
||
wgPeers?: IWgPeerConfig[]; // Initial peers
|
||
}
|
||
|
||
// WireGuard peer config
|
||
interface IWgPeerConfig {
|
||
publicKey: string; // Peer's X25519 public key (base64)
|
||
presharedKey?: string; // Optional preshared key (base64)
|
||
allowedIps: string[]; // Allowed IP ranges (CIDR)
|
||
endpoint?: string; // Peer endpoint (host:port)
|
||
persistentKeepalive?: number; // Keepalive interval (seconds)
|
||
}
|
||
|
||
// WireGuard peer info (with live stats)
|
||
interface IWgPeerInfo {
|
||
publicKey: string;
|
||
allowedIps: string[];
|
||
endpoint?: string;
|
||
persistentKeepalive?: number;
|
||
bytesSent: number;
|
||
bytesReceived: number;
|
||
packetsSent: number;
|
||
packetsReceived: number;
|
||
lastHandshakeTime?: string;
|
||
}
|
||
|
||
// Status
|
||
type TVpnConnectionState = 'disconnected' | 'connecting' | 'handshaking'
|
||
| 'connected' | 'reconnecting' | 'error';
|
||
|
||
interface IVpnStatus {
|
||
state: TVpnConnectionState;
|
||
assignedIp?: string;
|
||
serverAddr?: string;
|
||
connectedSince?: string;
|
||
lastError?: string;
|
||
}
|
||
|
||
// Statistics
|
||
interface IVpnStatistics {
|
||
bytesSent: number;
|
||
bytesReceived: number;
|
||
packetsSent: number;
|
||
packetsReceived: number;
|
||
keepalivesSent: number;
|
||
keepalivesReceived: number;
|
||
uptimeSeconds: number;
|
||
quality?: IVpnConnectionQuality;
|
||
}
|
||
|
||
interface IVpnServerStatistics extends IVpnStatistics {
|
||
activeClients: number;
|
||
totalConnections: number;
|
||
}
|
||
|
||
// Connection quality (QoS)
|
||
type TVpnLinkHealth = 'healthy' | 'degraded' | 'critical';
|
||
|
||
interface IVpnConnectionQuality {
|
||
srttMs: number;
|
||
jitterMs: number;
|
||
minRttMs: number;
|
||
maxRttMs: number;
|
||
lossRatio: number;
|
||
consecutiveTimeouts: number;
|
||
linkHealth: TVpnLinkHealth;
|
||
currentKeepaliveIntervalSecs: number;
|
||
}
|
||
|
||
// MTU info
|
||
interface IVpnMtuInfo {
|
||
tunMtu: number;
|
||
effectiveMtu: number;
|
||
linkMtu: number;
|
||
overheadBytes: number;
|
||
oversizedPacketsDropped: number;
|
||
icmpTooBigSent: number;
|
||
}
|
||
|
||
// Client info (with QoS fields)
|
||
interface IVpnClientInfo {
|
||
clientId: string;
|
||
assignedIp: string;
|
||
connectedSince: string;
|
||
bytesSent: number;
|
||
bytesReceived: number;
|
||
packetsDropped: number;
|
||
bytesDropped: number;
|
||
lastKeepaliveAt?: string;
|
||
keepalivesReceived: number;
|
||
rateLimitBytesPerSec?: number;
|
||
burstBytes?: number;
|
||
}
|
||
|
||
// Per-client telemetry
|
||
interface IVpnClientTelemetry {
|
||
clientId: string;
|
||
assignedIp: string;
|
||
lastKeepaliveAt?: string;
|
||
keepalivesReceived: number;
|
||
packetsDropped: number;
|
||
bytesDropped: number;
|
||
bytesReceived: number;
|
||
bytesSent: number;
|
||
rateLimitBytesPerSec?: number;
|
||
burstBytes?: number;
|
||
}
|
||
|
||
interface IVpnKeypair {
|
||
publicKey: string;
|
||
privateKey: string;
|
||
}
|
||
```
|
||
|
||
</details>
|
||
|
||
## License and Legal Information
|
||
|
||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./license.md) file.
|
||
|
||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||
|
||
### Trademarks
|
||
|
||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||
|
||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||
|
||
### Company Information
|
||
|
||
Task Venture Capital GmbH
|
||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||
|
||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||
|
||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|