4 Commits

7 changed files with 1172 additions and 329 deletions

View File

@@ -1,5 +1,19 @@
# Changelog
## 2026-03-29 - 1.7.0 - feat(rust-tests)
add end-to-end WireGuard UDP integration tests and align TypeScript build configuration
- Add userspace Rust end-to-end tests that validate WireGuard handshake, encryption, peer isolation, and preshared-key data exchange over real UDP sockets.
- Update the TypeScript build setup by removing the allowimplicitany build flag and explicitly including Node types in tsconfig.
- Refresh development toolchain versions to support the updated test and build workflow.
## 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.7.0",
"private": false,
"description": "A VPN solution with TypeScript control plane and Rust data plane daemon",
"type": "module",
@@ -10,7 +10,7 @@
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"scripts": {
"build": "(tsbuild tsfolders --allowimplicitany) && (tsrust)",
"build": "(tsbuild tsfolders) && (tsrust)",
"test:before": "(tsrust)",
"test": "tstest test/ --verbose",
"buildDocs": "tsdoc"
@@ -33,10 +33,10 @@
"@push.rocks/smartrust": "^1.3.2"
},
"devDependencies": {
"@git.zone/tsbuild": "^4.3.0",
"@git.zone/tsrun": "^2.0.1",
"@git.zone/tsrust": "^1.3.0",
"@git.zone/tstest": "^3.5.0",
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tsrun": "^2.0.2",
"@git.zone/tsrust": "^1.3.2",
"@git.zone/tstest": "^3.6.3",
"@types/node": "^25.5.0"
},
"files": [

865
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

285
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 (93 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.

320
rust/tests/wg_e2e.rs Normal file
View File

@@ -0,0 +1,320 @@
//! End-to-end WireGuard protocol tests over real UDP sockets.
//!
//! Entirely userspace — no root, no TUN devices.
//! Two boringtun `Tunn` instances exchange real WireGuard packets
//! over loopback UDP, validating handshake, encryption, and data flow.
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;
use boringtun::noise::{Tunn, TunnResult};
use boringtun::x25519::{PublicKey, StaticSecret};
use tokio::net::UdpSocket;
use tokio::time;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use smartvpn_daemon::wireguard::generate_wg_keypair;
// ============================================================================
// Helpers
// ============================================================================
fn parse_key_pair(pub_b64: &str, priv_b64: &str) -> (PublicKey, StaticSecret) {
let pub_bytes: [u8; 32] = BASE64.decode(pub_b64).unwrap().try_into().unwrap();
let priv_bytes: [u8; 32] = BASE64.decode(priv_b64).unwrap().try_into().unwrap();
(PublicKey::from(pub_bytes), StaticSecret::from(priv_bytes))
}
fn clone_secret(priv_b64: &str) -> StaticSecret {
let priv_bytes: [u8; 32] = BASE64.decode(priv_b64).unwrap().try_into().unwrap();
StaticSecret::from(priv_bytes)
}
fn make_ipv4_packet(src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec<u8> {
let total_len = 20 + payload.len();
let mut pkt = vec![0u8; total_len];
pkt[0] = 0x45;
pkt[2] = (total_len >> 8) as u8;
pkt[3] = total_len as u8;
pkt[9] = 0x11;
pkt[12..16].copy_from_slice(&src.octets());
pkt[16..20].copy_from_slice(&dst.octets());
pkt[20..].copy_from_slice(payload);
pkt
}
/// Send any WriteToNetwork result, then drain the tunn for more packets.
async fn send_and_drain(
tunn: &mut Tunn,
pkt: &[u8],
socket: &UdpSocket,
peer: SocketAddr,
) {
socket.send_to(pkt, peer).await.unwrap();
let mut drain_buf = vec![0u8; 2048];
loop {
match tunn.decapsulate(None, &[], &mut drain_buf) {
TunnResult::WriteToNetwork(p) => { socket.send_to(p, peer).await.unwrap(); }
_ => break,
}
}
}
/// Try to receive a UDP packet and decapsulate it. Returns decrypted IP data if any.
async fn try_recv_decap(
tunn: &mut Tunn,
socket: &UdpSocket,
timeout_ms: u64,
) -> Option<(Vec<u8>, Ipv4Addr, SocketAddr)> {
let mut recv_buf = vec![0u8; 65536];
let mut dst_buf = vec![0u8; 65536];
let (n, src_addr) = match time::timeout(
Duration::from_millis(timeout_ms),
socket.recv_from(&mut recv_buf),
).await {
Ok(Ok(r)) => r,
_ => return None,
};
let result = tunn.decapsulate(Some(src_addr.ip()), &recv_buf[..n], &mut dst_buf);
match result {
TunnResult::WriteToNetwork(pkt) => {
send_and_drain(tunn, pkt, socket, src_addr).await;
None
}
TunnResult::WriteToTunnelV4(pkt, addr) => Some((pkt.to_vec(), addr, src_addr)),
TunnResult::WriteToTunnelV6(_, _) => None,
TunnResult::Done => None,
TunnResult::Err(_) => None,
}
}
/// Drive the full WireGuard handshake between client and server over real UDP.
async fn do_handshake(
client_tunn: &mut Tunn,
server_tunn: &mut Tunn,
client_socket: &UdpSocket,
server_socket: &UdpSocket,
server_addr: SocketAddr,
) {
let mut buf = vec![0u8; 2048];
let mut recv_buf = vec![0u8; 65536];
let mut dst_buf = vec![0u8; 65536];
// Step 1: Client initiates handshake
match client_tunn.encapsulate(&[], &mut buf) {
TunnResult::WriteToNetwork(pkt) => {
client_socket.send_to(pkt, server_addr).await.unwrap();
}
_ => panic!("Expected handshake init"),
}
// Step 2: Server receives init → sends response
let (n, client_from) = server_socket.recv_from(&mut recv_buf).await.unwrap();
match server_tunn.decapsulate(Some(client_from.ip()), &recv_buf[..n], &mut dst_buf) {
TunnResult::WriteToNetwork(pkt) => {
send_and_drain(server_tunn, pkt, server_socket, client_from).await;
}
other => panic!("Expected WriteToNetwork from server, got variant {}", variant_name(&other)),
}
// Step 3: Client receives response
let (n, _) = client_socket.recv_from(&mut recv_buf).await.unwrap();
match client_tunn.decapsulate(Some(server_addr.ip()), &recv_buf[..n], &mut dst_buf) {
TunnResult::WriteToNetwork(pkt) => {
send_and_drain(client_tunn, pkt, client_socket, server_addr).await;
}
TunnResult::Done => {}
_ => {}
}
// Step 4: Process any remaining handshake packets
let _ = try_recv_decap(server_tunn, server_socket, 200).await;
let _ = try_recv_decap(client_tunn, client_socket, 100).await;
// Step 5: Timer ticks to settle
for _ in 0..3 {
match server_tunn.update_timers(&mut dst_buf) {
TunnResult::WriteToNetwork(pkt) => {
server_socket.send_to(pkt, client_from).await.unwrap();
}
_ => {}
}
match client_tunn.update_timers(&mut dst_buf) {
TunnResult::WriteToNetwork(pkt) => {
client_socket.send_to(pkt, server_addr).await.unwrap();
}
_ => {}
}
let _ = try_recv_decap(server_tunn, server_socket, 50).await;
let _ = try_recv_decap(client_tunn, client_socket, 50).await;
}
}
fn variant_name(r: &TunnResult) -> &'static str {
match r {
TunnResult::Done => "Done",
TunnResult::Err(_) => "Err",
TunnResult::WriteToNetwork(_) => "WriteToNetwork",
TunnResult::WriteToTunnelV4(_, _) => "WriteToTunnelV4",
TunnResult::WriteToTunnelV6(_, _) => "WriteToTunnelV6",
}
}
/// Encapsulate an IP packet and send it, then loop-receive on the other side until decrypted.
async fn send_and_expect_data(
sender_tunn: &mut Tunn,
receiver_tunn: &mut Tunn,
sender_socket: &UdpSocket,
receiver_socket: &UdpSocket,
dest_addr: SocketAddr,
ip_packet: &[u8],
) -> (Vec<u8>, Ipv4Addr) {
let mut enc_buf = vec![0u8; 65536];
match sender_tunn.encapsulate(ip_packet, &mut enc_buf) {
TunnResult::WriteToNetwork(pkt) => {
sender_socket.send_to(pkt, dest_addr).await.unwrap();
}
TunnResult::Err(e) => panic!("Encapsulate failed: {:?}", e),
other => panic!("Expected WriteToNetwork, got {}", variant_name(&other)),
}
// Receive — may need a few rounds for control packets
for _ in 0..10 {
if let Some((data, addr, _)) = try_recv_decap(receiver_tunn, receiver_socket, 1000).await {
return (data, addr);
}
}
panic!("Did not receive decrypted IP packet");
}
// ============================================================================
// Test 1: Single client ↔ server bidirectional data exchange
// ============================================================================
#[tokio::test]
async fn wg_e2e_single_client_bidirectional() {
let (server_pub_b64, server_priv_b64) = generate_wg_keypair();
let (client_pub_b64, client_priv_b64) = generate_wg_keypair();
let (server_public, server_secret) = parse_key_pair(&server_pub_b64, &server_priv_b64);
let (client_public, client_secret) = parse_key_pair(&client_pub_b64, &client_priv_b64);
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_addr = server_socket.local_addr().unwrap();
let client_addr = client_socket.local_addr().unwrap();
let mut server_tunn = Tunn::new(server_secret, client_public, None, None, 0, None);
let mut client_tunn = Tunn::new(client_secret, server_public, None, None, 1, None);
do_handshake(&mut client_tunn, &mut server_tunn, &client_socket, &server_socket, server_addr).await;
// Client → Server
let pkt_c2s = make_ipv4_packet(Ipv4Addr::new(10, 0, 0, 2), Ipv4Addr::new(10, 0, 0, 1), b"Hello from client!");
let (decrypted, src_ip) = send_and_expect_data(
&mut client_tunn, &mut server_tunn,
&client_socket, &server_socket,
server_addr, &pkt_c2s,
).await;
assert_eq!(src_ip, Ipv4Addr::new(10, 0, 0, 2));
assert_eq!(&decrypted[..pkt_c2s.len()], &pkt_c2s[..]);
// Server → Client
let pkt_s2c = make_ipv4_packet(Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2), b"Hello from server!");
let (decrypted, src_ip) = send_and_expect_data(
&mut server_tunn, &mut client_tunn,
&server_socket, &client_socket,
client_addr, &pkt_s2c,
).await;
assert_eq!(src_ip, Ipv4Addr::new(10, 0, 0, 1));
assert_eq!(&decrypted[..pkt_s2c.len()], &pkt_s2c[..]);
}
// ============================================================================
// Test 2: Two clients ↔ one server (peer routing)
// ============================================================================
#[tokio::test]
async fn wg_e2e_two_clients_peer_routing() {
let (server_pub_b64, server_priv_b64) = generate_wg_keypair();
let (client1_pub_b64, client1_priv_b64) = generate_wg_keypair();
let (client2_pub_b64, client2_priv_b64) = generate_wg_keypair();
let (server_public, _) = parse_key_pair(&server_pub_b64, &server_priv_b64);
let (client1_public, client1_secret) = parse_key_pair(&client1_pub_b64, &client1_priv_b64);
let (client2_public, client2_secret) = parse_key_pair(&client2_pub_b64, &client2_priv_b64);
// Separate server socket per peer to avoid UDP mux complexity in test
let server_socket_1 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_socket_2 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client1_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client2_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_addr_1 = server_socket_1.local_addr().unwrap();
let server_addr_2 = server_socket_2.local_addr().unwrap();
let mut server_tunn_1 = Tunn::new(clone_secret(&server_priv_b64), client1_public, None, None, 0, None);
let mut server_tunn_2 = Tunn::new(clone_secret(&server_priv_b64), client2_public, None, None, 1, None);
let mut client1_tunn = Tunn::new(client1_secret, server_public.clone(), None, None, 2, None);
let mut client2_tunn = Tunn::new(client2_secret, server_public, None, None, 3, None);
do_handshake(&mut client1_tunn, &mut server_tunn_1, &client1_socket, &server_socket_1, server_addr_1).await;
do_handshake(&mut client2_tunn, &mut server_tunn_2, &client2_socket, &server_socket_2, server_addr_2).await;
// Client 1 → Server
let pkt1 = make_ipv4_packet(Ipv4Addr::new(10, 0, 0, 2), Ipv4Addr::new(10, 0, 0, 1), b"From client 1");
let (decrypted, src_ip) = send_and_expect_data(
&mut client1_tunn, &mut server_tunn_1,
&client1_socket, &server_socket_1,
server_addr_1, &pkt1,
).await;
assert_eq!(src_ip, Ipv4Addr::new(10, 0, 0, 2));
assert_eq!(&decrypted[..pkt1.len()], &pkt1[..]);
// Client 2 → Server
let pkt2 = make_ipv4_packet(Ipv4Addr::new(10, 0, 0, 3), Ipv4Addr::new(10, 0, 0, 1), b"From client 2");
let (decrypted, src_ip) = send_and_expect_data(
&mut client2_tunn, &mut server_tunn_2,
&client2_socket, &server_socket_2,
server_addr_2, &pkt2,
).await;
assert_eq!(src_ip, Ipv4Addr::new(10, 0, 0, 3));
assert_eq!(&decrypted[..pkt2.len()], &pkt2[..]);
}
// ============================================================================
// Test 3: Preshared key handshake + data exchange
// ============================================================================
#[tokio::test]
async fn wg_e2e_preshared_key() {
let (server_pub_b64, server_priv_b64) = generate_wg_keypair();
let (client_pub_b64, client_priv_b64) = generate_wg_keypair();
let (server_public, server_secret) = parse_key_pair(&server_pub_b64, &server_priv_b64);
let (client_public, client_secret) = parse_key_pair(&client_pub_b64, &client_priv_b64);
let psk: [u8; 32] = rand::random();
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_addr = server_socket.local_addr().unwrap();
let mut server_tunn = Tunn::new(server_secret, client_public, Some(psk), None, 0, None);
let mut client_tunn = Tunn::new(client_secret, server_public, Some(psk), None, 1, None);
do_handshake(&mut client_tunn, &mut server_tunn, &client_socket, &server_socket, server_addr).await;
let pkt = make_ipv4_packet(Ipv4Addr::new(10, 0, 0, 2), Ipv4Addr::new(10, 0, 0, 1), b"PSK-protected data");
let (decrypted, src_ip) = send_and_expect_data(
&mut client_tunn, &mut server_tunn,
&client_socket, &server_socket,
server_addr, &pkt,
).await;
assert_eq!(src_ip, Ipv4Addr::new(10, 0, 0, 2));
assert_eq!(&decrypted[..pkt.len()], &pkt[..]);
}

View File

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

View File

@@ -6,7 +6,8 @@
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
"verbatimModuleSyntax": true,
"types": ["node"]
},
"exclude": [
"dist_ts/**/*.d.ts"