2 Commits

4 changed files with 270 additions and 28 deletions

View File

@@ -1,5 +1,12 @@
# Changelog
## 2026-03-29 - 1.6.0 - feat(readme)
document WireGuard transport support, configuration, and usage examples
- Expand the README from dual-transport to triple-transport support by adding WireGuard alongside WebSocket and QUIC
- Add client and server WireGuard examples, including live peer management and .conf generation with WgConfigGenerator
- Document new WireGuard-related API methods, config fields, transport modes, and security model details
## 2026-03-29 - 1.5.0 - feat(wireguard)
add WireGuard transport support with management APIs and config generation

View File

@@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartvpn",
"version": "1.5.0",
"version": "1.6.0",
"private": false,
"description": "A VPN solution with TypeScript control plane and Rust data plane daemon",
"type": "module",

287
readme.md
View File

@@ -2,11 +2,12 @@
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
🚀 **Dual transport**: WebSocket (Cloudflare-friendly) and raw **QUIC** (with datagram support)
📊 **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
🔒 **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
@@ -27,9 +28,10 @@ TypeScript (control plane) Rust (data plane)
│ └─ VpnBridge │──stdio/──▶ │ ├─ management (JSON IPC) │
│ └─ RustBridge │ socket │ ├─ transport_trait (abstraction) │
│ (smartrust) │ │ │ ├─ transport (WebSocket/TLS) │
└──────────────────────────┘ │ │ └─ quic_transport (QUIC/UDP) │
│ ├─ crypto (Noise NK + XCha20)
│ ├─ codec (binary framing)
│ │ │ │ └─ 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) │
@@ -45,8 +47,9 @@ TypeScript (control plane) Rust (data plane)
| Decision | Choice | Why |
|----------|--------|-----|
| Transport | WebSocket + QUIC (dual) | WS works through Cloudflare; QUIC gives lower latency + unreliable datagrams |
| 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 (1060s) |
@@ -132,6 +135,37 @@ await autoClient.connect({
});
```
### 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
@@ -154,7 +188,7 @@ await server.start({
dns: ['1.1.1.1'],
mtu: 1420,
enableNat: true,
// Transport mode: 'websocket', 'quic', or 'both' (default)
// Transport mode: 'websocket', 'quic', 'both', or 'wireguard'
transportMode: 'both',
// Optional: separate QUIC listen address
quicListenAddr: '0.0.0.0:4433',
@@ -188,6 +222,125 @@ 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:
@@ -216,7 +369,7 @@ When using socket transport, `client.stop()` closes the socket but **does not ki
| Method | Returns | Description |
|--------|---------|-------------|
| `start()` | `Promise<boolean>` | Start the daemon bridge (spawn or connect) |
| `connect(config?)` | `Promise<{ assignedIp }>` | Connect to VPN server |
| `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 |
@@ -239,6 +392,10 @@ When using socket transport, `client.stop()` closes the socket but **does not ki
| `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`
@@ -257,6 +414,19 @@ const config = await VpnConfig.loadFromFile<IVpnClientConfig>('/etc/smartvpn/cli
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:
@@ -306,9 +476,9 @@ server.on('stopped', () => { /* server listener stopped */ });
## 🌐 Transport Modes
smartvpn supports two transport protocols through a unified transport abstraction layer. Both use the same encryption, framing, and QoS pipeline — the transport is swappable without changing any application logic.
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)
### WebSocket (default for smartvpn-native)
- Works through Cloudflare, reverse proxies, and HTTP load balancers
- Reliable delivery only (no datagram support)
@@ -322,7 +492,17 @@ smartvpn supports two transport protocols through a unified transport abstractio
- URL format: `host:port`
- ALPN protocol: `smartvpn`
### Auto-Transport (Recommended)
### 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:
@@ -339,16 +519,26 @@ await client.connect({
});
```
### Server Dual-Mode
### Server Dual-Mode / Multi-Mode
The server can listen on both transports simultaneously:
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' (default)
quicIdleTimeoutSecs: 30, // QUIC connection idle timeout
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
});
```
@@ -428,6 +618,8 @@ For a standard 1500-byte Ethernet link, effective TUN MTU = **1421 bytes**. The
## 🔐 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
@@ -440,6 +632,14 @@ Post-handshake, all IP packets are encrypted with **XChaCha20-Poly1305**:
- 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:
@@ -481,6 +681,8 @@ Inside the tunnel (both WebSocket and QUIC reliable channels), packets use a sim
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
@@ -507,7 +709,7 @@ pnpm build
# Build Rust only (debug)
cd rust && cargo build
# Run all tests (77 Rust + 59 TypeScript)
# Run all tests (82 Rust + 77 TypeScript)
cd rust && cargo test
pnpm test
```
@@ -533,12 +735,20 @@ type TVpnTransportOptions =
// Client config
interface IVpnClientConfig {
serverUrl: string; // WS: 'wss://host/path' | QUIC: 'host:port'
serverPublicKey: string; // Base64-encoded Noise static key
transport?: 'auto' | 'websocket' | 'quic'; // Default: 'auto'
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
@@ -553,11 +763,36 @@ interface IVpnServerConfig {
mtu?: number;
keepaliveIntervalSecs?: number;
enableNat?: boolean;
transportMode?: 'websocket' | 'quic' | 'both'; // Default: 'both'
quicListenAddr?: string; // Separate QUIC bind address
quicIdleTimeoutSecs?: number; // QUIC idle timeout (default: 30)
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
@@ -652,7 +887,7 @@ interface IVpnKeypair {
## 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) file.
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.
@@ -664,7 +899,7 @@ Use of these trademarks must comply with Task Venture Capital GmbH's Trademark G
### Company Information
Task Venture Capital GmbH
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.

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartvpn',
version: '1.5.0',
version: '1.6.0',
description: 'A VPN solution with TypeScript control plane and Rust data plane daemon'
}