@push.rocks/smartvpn 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md CHANGED
@@ -2,11 +2,12 @@
2
2
 
3
3
  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.
4
4
 
5
- 🔒 **Noise NK** handshake + **XChaCha20-Poly1305** encryption
6
- 🚀 **Dual transport**: WebSocket (Cloudflare-friendly) and raw **QUIC** (with datagram support)
7
- 📊 **Adaptive QoS**: packet classification, priority queues, per-client rate limiting
8
- 🔄 **Auto-transport**: tries QUIC first, falls back to WebSocket seamlessly
9
- 📡 **Real-time telemetry**: RTT, jitter, loss, link health — all exposed via typed APIs
5
+ 🔒 **Noise NK** handshake + **XChaCha20-Poly1305** encryption
6
+ 🚀 **Triple transport**: WebSocket (Cloudflare-friendly), raw **QUIC** (datagrams), and **WireGuard** (standard protocol)
7
+ 📊 **Adaptive QoS**: packet classification, priority queues, per-client rate limiting
8
+ 🔄 **Auto-transport**: tries QUIC first, falls back to WebSocket seamlessly
9
+ 📡 **Real-time telemetry**: RTT, jitter, loss, link health — all exposed via typed APIs
10
+ 🛡️ **WireGuard mode**: full userspace WireGuard via `boringtun` — generate `.conf` files, manage peers live
10
11
 
11
12
  ## Issue Reporting and Security
12
13
 
@@ -27,9 +28,10 @@ TypeScript (control plane) Rust (data plane)
27
28
  │ └─ VpnBridge │──stdio/──▶ │ ├─ management (JSON IPC) │
28
29
  │ └─ RustBridge │ socket │ ├─ transport_trait (abstraction) │
29
30
  │ (smartrust) │ │ │ ├─ transport (WebSocket/TLS) │
30
- └──────────────────────────┘ │ │ └─ quic_transport (QUIC/UDP) │
31
- │ ├─ crypto (Noise NK + XCha20)
32
- │ ├─ codec (binary framing)
31
+ │ │ │ │ └─ quic_transport (QUIC/UDP) │
32
+ WgConfigGenerator │ │ ├─ wireguard (boringtun WG)
33
+ └─ .conf file output │ │ ├─ crypto (Noise NK + XCha20)
34
+ └──────────────────────────┘ │ ├─ codec (binary framing) │
33
35
  │ ├─ keepalive (adaptive state FSM) │
34
36
  │ ├─ telemetry (RTT/jitter/loss) │
35
37
  │ ├─ qos (classify + priority Q) │
@@ -45,8 +47,9 @@ TypeScript (control plane) Rust (data plane)
45
47
 
46
48
  | Decision | Choice | Why |
47
49
  |----------|--------|-----|
48
- | Transport | WebSocket + QUIC (dual) | WS works through Cloudflare; QUIC gives lower latency + unreliable datagrams |
50
+ | Transport | WebSocket + QUIC + WireGuard | WS works through Cloudflare; QUIC gives low latency + datagrams; WG for standard protocol interop |
49
51
  | Auto-transport | QUIC first, WS fallback | Best performance when QUIC is available, graceful degradation when it's not |
52
+ | WireGuard | Userspace via `boringtun` | No kernel module needed, runs on any platform, full peer management via IPC |
50
53
  | Encryption | Noise NK + XChaCha20-Poly1305 | Strong forward secrecy, large nonce space (no counter sync needed) |
51
54
  | QUIC auth | Certificate hash pinning | WireGuard-style trust model — no CA needed, just pin the server cert hash |
52
55
  | Keepalive | Adaptive app-level pings | Cloudflare drops WS pings; interval adapts to link health (10–60s) |
@@ -132,6 +135,37 @@ await autoClient.connect({
132
135
  });
133
136
  ```
134
137
 
138
+ ### VPN Client with WireGuard
139
+
140
+ ```typescript
141
+ import { VpnClient } from '@push.rocks/smartvpn';
142
+
143
+ const wgClient = new VpnClient({
144
+ transport: { transport: 'stdio' },
145
+ });
146
+
147
+ await wgClient.start();
148
+
149
+ const { assignedIp } = await wgClient.connect({
150
+ serverPublicKey: 'BASE64_SERVER_WG_PUBLIC_KEY',
151
+ serverUrl: '', // not used for WireGuard
152
+ transport: 'wireguard',
153
+ wgPrivateKey: 'BASE64_CLIENT_PRIVATE_KEY',
154
+ wgAddress: '10.8.0.2',
155
+ wgAddressPrefix: 24,
156
+ wgEndpoint: 'vpn.example.com:51820',
157
+ wgAllowedIps: ['0.0.0.0/0'], // route all traffic
158
+ wgPersistentKeepalive: 25,
159
+ wgPresharedKey: 'OPTIONAL_PSK', // optional extra layer
160
+ dns: ['1.1.1.1'],
161
+ mtu: 1420,
162
+ });
163
+
164
+ console.log(`WireGuard connected! IP: ${assignedIp}`);
165
+ await wgClient.disconnect();
166
+ wgClient.stop();
167
+ ```
168
+
135
169
  ### VPN Server
136
170
 
137
171
  ```typescript
@@ -154,7 +188,7 @@ await server.start({
154
188
  dns: ['1.1.1.1'],
155
189
  mtu: 1420,
156
190
  enableNat: true,
157
- // Transport mode: 'websocket', 'quic', or 'both' (default)
191
+ // Transport mode: 'websocket', 'quic', 'both', or 'wireguard'
158
192
  transportMode: 'both',
159
193
  // Optional: separate QUIC listen address
160
194
  quicListenAddr: '0.0.0.0:4433',
@@ -188,6 +222,125 @@ await server.stopServer();
188
222
  server.stop();
189
223
  ```
190
224
 
225
+ ### WireGuard Server Mode
226
+
227
+ ```typescript
228
+ import { VpnServer } from '@push.rocks/smartvpn';
229
+
230
+ const wgServer = new VpnServer({
231
+ transport: { transport: 'stdio' },
232
+ });
233
+
234
+ // Generate a WireGuard X25519 keypair
235
+ await wgServer.start();
236
+ const keypair = await wgServer.generateWgKeypair();
237
+ console.log(`Server public key: ${keypair.publicKey}`);
238
+
239
+ // Start in WireGuard mode
240
+ await wgServer.start({
241
+ listenAddr: '0.0.0.0:51820',
242
+ privateKey: keypair.privateKey,
243
+ publicKey: keypair.publicKey,
244
+ subnet: '10.8.0.0/24',
245
+ transportMode: 'wireguard',
246
+ wgListenPort: 51820,
247
+ wgPeers: [
248
+ {
249
+ publicKey: 'CLIENT_PUBLIC_KEY_BASE64',
250
+ allowedIps: ['10.8.0.2/32'],
251
+ persistentKeepalive: 25,
252
+ },
253
+ ],
254
+ enableNat: true,
255
+ dns: ['1.1.1.1'],
256
+ mtu: 1420,
257
+ });
258
+
259
+ // Live peer management — add/remove peers without restart
260
+ await wgServer.addWgPeer({
261
+ publicKey: 'NEW_CLIENT_PUBLIC_KEY',
262
+ allowedIps: ['10.8.0.3/32'],
263
+ persistentKeepalive: 25,
264
+ });
265
+
266
+ // List peers with live stats
267
+ const peers = await wgServer.listWgPeers();
268
+ for (const peer of peers) {
269
+ console.log(`${peer.publicKey}: ↑${peer.bytesSent} ↓${peer.bytesReceived}`);
270
+ }
271
+
272
+ // Remove a peer by public key
273
+ await wgServer.removeWgPeer('CLIENT_PUBLIC_KEY_BASE64');
274
+
275
+ await wgServer.stopServer();
276
+ wgServer.stop();
277
+ ```
278
+
279
+ ### Generating WireGuard .conf Files
280
+
281
+ The `WgConfigGenerator` creates standard WireGuard `.conf` files compatible with `wg-quick`, iOS/Android apps, and all standard WireGuard clients:
282
+
283
+ ```typescript
284
+ import { WgConfigGenerator } from '@push.rocks/smartvpn';
285
+
286
+ // Client config (for wg-quick or mobile apps)
287
+ const clientConf = WgConfigGenerator.generateClientConfig({
288
+ privateKey: 'CLIENT_PRIVATE_KEY_BASE64',
289
+ address: '10.8.0.2/24',
290
+ dns: ['1.1.1.1', '8.8.8.8'],
291
+ mtu: 1420,
292
+ peer: {
293
+ publicKey: 'SERVER_PUBLIC_KEY_BASE64',
294
+ endpoint: 'vpn.example.com:51820',
295
+ allowedIps: ['0.0.0.0/0', '::/0'],
296
+ persistentKeepalive: 25,
297
+ presharedKey: 'OPTIONAL_PSK_BASE64',
298
+ },
299
+ });
300
+
301
+ // Server config (for wg-quick)
302
+ const serverConf = WgConfigGenerator.generateServerConfig({
303
+ privateKey: 'SERVER_PRIVATE_KEY_BASE64',
304
+ address: '10.8.0.1/24',
305
+ listenPort: 51820,
306
+ dns: ['1.1.1.1'],
307
+ mtu: 1420,
308
+ enableNat: true,
309
+ natInterface: 'eth0', // auto-detected if omitted
310
+ peers: [
311
+ {
312
+ publicKey: 'CLIENT_PUBLIC_KEY_BASE64',
313
+ allowedIps: ['10.8.0.2/32'],
314
+ persistentKeepalive: 25,
315
+ },
316
+ ],
317
+ });
318
+
319
+ // Write to disk
320
+ import * as fs from 'fs';
321
+ fs.writeFileSync('/etc/wireguard/wg0.conf', serverConf);
322
+ ```
323
+
324
+ <details>
325
+ <summary>Example output: client .conf</summary>
326
+
327
+ ```ini
328
+ [Interface]
329
+ PrivateKey = CLIENT_PRIVATE_KEY_BASE64
330
+ Address = 10.8.0.2/24
331
+ DNS = 1.1.1.1, 8.8.8.8
332
+ MTU = 1420
333
+
334
+ [Peer]
335
+ PublicKey = SERVER_PUBLIC_KEY_BASE64
336
+ PresharedKey = OPTIONAL_PSK_BASE64
337
+ Endpoint = vpn.example.com:51820
338
+ AllowedIPs = 0.0.0.0/0, ::/0
339
+ PersistentKeepalive = 25
340
+ ```
341
+
342
+ </details>
343
+
191
344
  ### Production: Socket Transport
192
345
 
193
346
  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
216
369
  | Method | Returns | Description |
217
370
  |--------|---------|-------------|
218
371
  | `start()` | `Promise<boolean>` | Start the daemon bridge (spawn or connect) |
219
- | `connect(config?)` | `Promise<{ assignedIp }>` | Connect to VPN server |
372
+ | `connect(config?)` | `Promise<{ assignedIp }>` | Connect to VPN server (WS, QUIC, or WireGuard) |
220
373
  | `disconnect()` | `Promise<void>` | Disconnect from VPN |
221
374
  | `getStatus()` | `Promise<IVpnStatus>` | Current connection state |
222
375
  | `getStatistics()` | `Promise<IVpnStatistics>` | Traffic stats + connection quality |
@@ -239,6 +392,10 @@ When using socket transport, `client.stop()` closes the socket but **does not ki
239
392
  | `setClientRateLimit(id, rate, burst)` | `Promise<void>` | Set per-client rate limit (bytes/sec) |
240
393
  | `removeClientRateLimit(id)` | `Promise<void>` | Remove rate limit (unlimited) |
241
394
  | `getClientTelemetry(id)` | `Promise<IVpnClientTelemetry>` | Per-client telemetry + drop stats |
395
+ | `generateWgKeypair()` | `Promise<IVpnKeypair>` | Generate WireGuard X25519 keypair |
396
+ | `addWgPeer(peer)` | `Promise<void>` | Add a WireGuard peer at runtime |
397
+ | `removeWgPeer(publicKey)` | `Promise<void>` | Remove a WireGuard peer by key |
398
+ | `listWgPeers()` | `Promise<IWgPeerInfo[]>` | List WG peers with traffic stats |
242
399
  | `stop()` | `void` | Kill/close the daemon bridge |
243
400
 
244
401
  ### `VpnConfig`
@@ -257,6 +414,19 @@ const config = await VpnConfig.loadFromFile<IVpnClientConfig>('/etc/smartvpn/cli
257
414
  await VpnConfig.saveToFile('/etc/smartvpn/client.json', config);
258
415
  ```
259
416
 
417
+ Validation covers both smartvpn-native configs and WireGuard configs — base64 key format, CIDR ranges, port ranges, and required fields are all checked.
418
+
419
+ ### `WgConfigGenerator`
420
+
421
+ Static generator for standard WireGuard `.conf` files:
422
+
423
+ | Method | Returns | Description |
424
+ |--------|---------|-------------|
425
+ | `generateClientConfig(opts)` | `string` | Generate a `wg-quick` compatible client `.conf` |
426
+ | `generateServerConfig(opts)` | `string` | Generate a `wg-quick` compatible server `.conf` with NAT rules |
427
+
428
+ Output is compatible with `wg-quick`, WireGuard iOS/Android apps, and any standard WireGuard implementation.
429
+
260
430
  ### `VpnInstaller`
261
431
 
262
432
  Generate system service units for the daemon:
@@ -306,9 +476,9 @@ server.on('stopped', () => { /* server listener stopped */ });
306
476
 
307
477
  ## 🌐 Transport Modes
308
478
 
309
- 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.
479
+ 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.
310
480
 
311
- ### WebSocket (default)
481
+ ### WebSocket (default for smartvpn-native)
312
482
 
313
483
  - Works through Cloudflare, reverse proxies, and HTTP load balancers
314
484
  - Reliable delivery only (no datagram support)
@@ -322,7 +492,17 @@ smartvpn supports two transport protocols through a unified transport abstractio
322
492
  - URL format: `host:port`
323
493
  - ALPN protocol: `smartvpn`
324
494
 
325
- ### Auto-Transport (Recommended)
495
+ ### WireGuard
496
+
497
+ - Standard WireGuard protocol via `boringtun` (userspace, no kernel module)
498
+ - Compatible with **all WireGuard clients** — iOS, Android, macOS, Windows, Linux, routers
499
+ - X25519 key exchange, ChaCha20-Poly1305 encryption
500
+ - Dynamic peer management at runtime (add/remove without restart)
501
+ - Optional preshared keys for post-quantum defense-in-depth
502
+ - Generate `.conf` files for standard clients via `WgConfigGenerator`
503
+ - Default port: `51820/UDP`
504
+
505
+ ### Auto-Transport (Recommended for smartvpn-native)
326
506
 
327
507
  The default `transport: 'auto'` mode gives you the best of both worlds:
328
508
 
@@ -339,16 +519,26 @@ await client.connect({
339
519
  });
340
520
  ```
341
521
 
342
- ### Server Dual-Mode
522
+ ### Server Dual-Mode / Multi-Mode
343
523
 
344
- The server can listen on both transports simultaneously:
524
+ The server can listen on multiple transports simultaneously:
345
525
 
346
526
  ```typescript
527
+ // WebSocket + QUIC (dual mode)
347
528
  await server.start({
348
529
  listenAddr: '0.0.0.0:443', // WebSocket listener
349
530
  quicListenAddr: '0.0.0.0:4433', // QUIC listener (optional, defaults to listenAddr)
350
- transportMode: 'both', // 'websocket' | 'quic' | 'both' (default)
351
- quicIdleTimeoutSecs: 30, // QUIC connection idle timeout
531
+ transportMode: 'both', // 'websocket' | 'quic' | 'both' | 'wireguard'
532
+ quicIdleTimeoutSecs: 30,
533
+ // ... other config
534
+ });
535
+
536
+ // WireGuard standalone
537
+ await server.start({
538
+ listenAddr: '0.0.0.0:51820',
539
+ transportMode: 'wireguard',
540
+ wgListenPort: 51820,
541
+ wgPeers: [{ publicKey: '...', allowedIps: ['10.8.0.2/32'] }],
352
542
  // ... other config
353
543
  });
354
544
  ```
@@ -428,6 +618,8 @@ For a standard 1500-byte Ethernet link, effective TUN MTU = **1421 bytes**. The
428
618
 
429
619
  ## 🔐 Security Model
430
620
 
621
+ ### smartvpn-native (WebSocket / QUIC)
622
+
431
623
  The VPN uses a **Noise NK** handshake pattern:
432
624
 
433
625
  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**:
440
632
  - 16-byte authentication tags
441
633
  - Wire format: `[nonce:24B][ciphertext:var][tag:16B]`
442
634
 
635
+ ### WireGuard Mode
636
+
637
+ Uses the standard [Noise IKpsk2](https://www.wireguard.com/protocol/) handshake:
638
+ - **X25519** key exchange (Curve25519 Diffie-Hellman)
639
+ - **ChaCha20-Poly1305** AEAD encryption
640
+ - Optional **preshared keys** for post-quantum defense-in-depth
641
+ - Implemented via `boringtun` — Cloudflare's userspace WireGuard in Rust
642
+
443
643
  ### QUIC Certificate Pinning
444
644
 
445
645
  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
481
681
 
482
682
  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.
483
683
 
684
+ > **Note:** WireGuard mode uses the standard WireGuard wire protocol, not this binary framing.
685
+
484
686
  ## 🛠️ Rust Daemon CLI
485
687
 
486
688
  ```bash
@@ -507,7 +709,7 @@ pnpm build
507
709
  # Build Rust only (debug)
508
710
  cd rust && cargo build
509
711
 
510
- # Run all tests (77 Rust + 59 TypeScript)
712
+ # Run all tests (82 Rust + 77 TypeScript)
511
713
  cd rust && cargo test
512
714
  pnpm test
513
715
  ```
@@ -533,12 +735,20 @@ type TVpnTransportOptions =
533
735
  // Client config
534
736
  interface IVpnClientConfig {
535
737
  serverUrl: string; // WS: 'wss://host/path' | QUIC: 'host:port'
536
- serverPublicKey: string; // Base64-encoded Noise static key
537
- transport?: 'auto' | 'websocket' | 'quic'; // Default: 'auto'
738
+ serverPublicKey: string; // Base64-encoded Noise static key (or WG public key)
739
+ transport?: 'auto' | 'websocket' | 'quic' | 'wireguard'; // Default: 'auto'
538
740
  serverCertHash?: string; // SHA-256 cert hash (base64) for QUIC pinning
539
741
  dns?: string[];
540
742
  mtu?: number;
541
743
  keepaliveIntervalSecs?: number;
744
+ // WireGuard-specific
745
+ wgPrivateKey?: string; // Client private key (base64, X25519)
746
+ wgAddress?: string; // Client TUN address (e.g. 10.8.0.2)
747
+ wgAddressPrefix?: number; // Address prefix length (default: 24)
748
+ wgPresharedKey?: string; // Optional preshared key (base64)
749
+ wgPersistentKeepalive?: number; // Persistent keepalive interval (seconds)
750
+ wgEndpoint?: string; // Server endpoint (host:port)
751
+ wgAllowedIps?: string[]; // Allowed IPs (CIDR strings)
542
752
  }
543
753
 
544
754
  // Server config
@@ -553,11 +763,36 @@ interface IVpnServerConfig {
553
763
  mtu?: number;
554
764
  keepaliveIntervalSecs?: number;
555
765
  enableNat?: boolean;
556
- transportMode?: 'websocket' | 'quic' | 'both'; // Default: 'both'
557
- quicListenAddr?: string; // Separate QUIC bind address
558
- quicIdleTimeoutSecs?: number; // QUIC idle timeout (default: 30)
766
+ transportMode?: 'websocket' | 'quic' | 'both' | 'wireguard';
767
+ quicListenAddr?: string;
768
+ quicIdleTimeoutSecs?: number;
559
769
  defaultRateLimitBytesPerSec?: number;
560
770
  defaultBurstBytes?: number;
771
+ // WireGuard-specific
772
+ wgListenPort?: number; // UDP port (default: 51820)
773
+ wgPeers?: IWgPeerConfig[]; // Initial peers
774
+ }
775
+
776
+ // WireGuard peer config
777
+ interface IWgPeerConfig {
778
+ publicKey: string; // Peer's X25519 public key (base64)
779
+ presharedKey?: string; // Optional preshared key (base64)
780
+ allowedIps: string[]; // Allowed IP ranges (CIDR)
781
+ endpoint?: string; // Peer endpoint (host:port)
782
+ persistentKeepalive?: number; // Keepalive interval (seconds)
783
+ }
784
+
785
+ // WireGuard peer info (with live stats)
786
+ interface IWgPeerInfo {
787
+ publicKey: string;
788
+ allowedIps: string[];
789
+ endpoint?: string;
790
+ persistentKeepalive?: number;
791
+ bytesSent: number;
792
+ bytesReceived: number;
793
+ packetsSent: number;
794
+ packetsReceived: number;
795
+ lastHandshakeTime?: string;
561
796
  }
562
797
 
563
798
  // Status
@@ -652,7 +887,7 @@ interface IVpnKeypair {
652
887
 
653
888
  ## License and Legal Information
654
889
 
655
- This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
890
+ 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.
656
891
 
657
892
  **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.
658
893
 
@@ -664,7 +899,7 @@ Use of these trademarks must comply with Task Venture Capital GmbH's Trademark G
664
899
 
665
900
  ### Company Information
666
901
 
667
- Task Venture Capital GmbH
902
+ Task Venture Capital GmbH
668
903
  Registered at District Court Bremen HRB 35230 HB, Germany
669
904
 
670
905
  For any legal inquiries or further information, please contact us via email at hello@task.vc.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartvpn',
6
- version: '1.4.1',
6
+ version: '1.6.0',
7
7
  description: 'A VPN solution with TypeScript control plane and Rust data plane daemon'
8
8
  }
package/ts/index.ts CHANGED
@@ -4,3 +4,4 @@ export { VpnClient } from './smartvpn.classes.vpnclient.js';
4
4
  export { VpnServer } from './smartvpn.classes.vpnserver.js';
5
5
  export { VpnConfig } from './smartvpn.classes.vpnconfig.js';
6
6
  export { VpnInstaller } from './smartvpn.classes.vpninstaller.js';
7
+ export { WgConfigGenerator } from './smartvpn.classes.wgconfig.js';
@@ -12,17 +12,45 @@ export class VpnConfig {
12
12
  * Validate a client config object. Throws on invalid config.
13
13
  */
14
14
  public static validateClientConfig(config: IVpnClientConfig): void {
15
- if (!config.serverUrl) {
16
- throw new Error('VpnConfig: serverUrl is required');
17
- }
18
- // For QUIC-only transport, serverUrl is a host:port address; for WebSocket/auto it must be ws:// or wss://
19
- if (config.transport !== 'quic') {
20
- if (!config.serverUrl.startsWith('wss://') && !config.serverUrl.startsWith('ws://')) {
21
- throw new Error('VpnConfig: serverUrl must start with wss:// or ws:// (for WebSocket transport)');
15
+ if (config.transport === 'wireguard') {
16
+ // WireGuard-specific validation
17
+ if (!config.wgPrivateKey) {
18
+ throw new Error('VpnConfig: wgPrivateKey is required for WireGuard transport');
19
+ }
20
+ VpnConfig.validateBase64Key(config.wgPrivateKey, 'wgPrivateKey');
21
+ if (!config.wgAddress) {
22
+ throw new Error('VpnConfig: wgAddress is required for WireGuard transport');
23
+ }
24
+ if (!config.serverPublicKey) {
25
+ throw new Error('VpnConfig: serverPublicKey is required for WireGuard transport');
26
+ }
27
+ VpnConfig.validateBase64Key(config.serverPublicKey, 'serverPublicKey');
28
+ if (!config.wgEndpoint) {
29
+ throw new Error('VpnConfig: wgEndpoint is required for WireGuard transport');
30
+ }
31
+ if (config.wgPresharedKey) {
32
+ VpnConfig.validateBase64Key(config.wgPresharedKey, 'wgPresharedKey');
33
+ }
34
+ if (config.wgAllowedIps) {
35
+ for (const cidr of config.wgAllowedIps) {
36
+ if (!VpnConfig.isValidCidr(cidr)) {
37
+ throw new Error(`VpnConfig: invalid allowedIp CIDR: ${cidr}`);
38
+ }
39
+ }
40
+ }
41
+ } else {
42
+ if (!config.serverUrl) {
43
+ throw new Error('VpnConfig: serverUrl is required');
44
+ }
45
+ // For QUIC-only transport, serverUrl is a host:port address; for WebSocket/auto it must be ws:// or wss://
46
+ if (config.transport !== 'quic') {
47
+ if (!config.serverUrl.startsWith('wss://') && !config.serverUrl.startsWith('ws://')) {
48
+ throw new Error('VpnConfig: serverUrl must start with wss:// or ws:// (for WebSocket transport)');
49
+ }
50
+ }
51
+ if (!config.serverPublicKey) {
52
+ throw new Error('VpnConfig: serverPublicKey is required');
22
53
  }
23
- }
24
- if (!config.serverPublicKey) {
25
- throw new Error('VpnConfig: serverPublicKey is required');
26
54
  }
27
55
  if (config.mtu !== undefined && (config.mtu < 576 || config.mtu > 65535)) {
28
56
  throw new Error('VpnConfig: mtu must be between 576 and 65535');
@@ -43,20 +71,51 @@ export class VpnConfig {
43
71
  * Validate a server config object. Throws on invalid config.
44
72
  */
45
73
  public static validateServerConfig(config: IVpnServerConfig): void {
46
- if (!config.listenAddr) {
47
- throw new Error('VpnConfig: listenAddr is required');
48
- }
49
- if (!config.privateKey) {
50
- throw new Error('VpnConfig: privateKey is required');
51
- }
52
- if (!config.publicKey) {
53
- throw new Error('VpnConfig: publicKey is required');
54
- }
55
- if (!config.subnet) {
56
- throw new Error('VpnConfig: subnet is required');
57
- }
58
- if (!VpnConfig.isValidSubnet(config.subnet)) {
59
- throw new Error(`VpnConfig: invalid subnet: ${config.subnet}`);
74
+ if (config.transportMode === 'wireguard') {
75
+ // WireGuard server validation
76
+ if (!config.privateKey) {
77
+ throw new Error('VpnConfig: privateKey is required');
78
+ }
79
+ VpnConfig.validateBase64Key(config.privateKey, 'privateKey');
80
+ if (!config.wgPeers || config.wgPeers.length === 0) {
81
+ throw new Error('VpnConfig: at least one wgPeers entry is required for WireGuard mode');
82
+ }
83
+ for (const peer of config.wgPeers) {
84
+ if (!peer.publicKey) {
85
+ throw new Error('VpnConfig: peer publicKey is required');
86
+ }
87
+ VpnConfig.validateBase64Key(peer.publicKey, 'peer.publicKey');
88
+ if (!peer.allowedIps || peer.allowedIps.length === 0) {
89
+ throw new Error('VpnConfig: peer allowedIps is required');
90
+ }
91
+ for (const cidr of peer.allowedIps) {
92
+ if (!VpnConfig.isValidCidr(cidr)) {
93
+ throw new Error(`VpnConfig: invalid peer allowedIp CIDR: ${cidr}`);
94
+ }
95
+ }
96
+ if (peer.presharedKey) {
97
+ VpnConfig.validateBase64Key(peer.presharedKey, 'peer.presharedKey');
98
+ }
99
+ }
100
+ if (config.wgListenPort !== undefined && (config.wgListenPort < 1 || config.wgListenPort > 65535)) {
101
+ throw new Error('VpnConfig: wgListenPort must be between 1 and 65535');
102
+ }
103
+ } else {
104
+ if (!config.listenAddr) {
105
+ throw new Error('VpnConfig: listenAddr is required');
106
+ }
107
+ if (!config.privateKey) {
108
+ throw new Error('VpnConfig: privateKey is required');
109
+ }
110
+ if (!config.publicKey) {
111
+ throw new Error('VpnConfig: publicKey is required');
112
+ }
113
+ if (!config.subnet) {
114
+ throw new Error('VpnConfig: subnet is required');
115
+ }
116
+ if (!VpnConfig.isValidSubnet(config.subnet)) {
117
+ throw new Error(`VpnConfig: invalid subnet: ${config.subnet}`);
118
+ }
60
119
  }
61
120
  if (config.mtu !== undefined && (config.mtu < 576 || config.mtu > 65535)) {
62
121
  throw new Error('VpnConfig: mtu must be between 576 and 65535');
@@ -104,4 +163,41 @@ export class VpnConfig {
104
163
  const prefixNum = parseInt(prefix, 10);
105
164
  return !isNaN(prefixNum) && prefixNum >= 0 && prefixNum <= 32;
106
165
  }
166
+
167
+ /**
168
+ * Validate a CIDR string (IPv4 or IPv6).
169
+ */
170
+ private static isValidCidr(cidr: string): boolean {
171
+ const parts = cidr.split('/');
172
+ if (parts.length !== 2) return false;
173
+ const prefixNum = parseInt(parts[1], 10);
174
+ if (isNaN(prefixNum) || prefixNum < 0) return false;
175
+ // IPv4
176
+ if (VpnConfig.isValidIp(parts[0])) {
177
+ return prefixNum <= 32;
178
+ }
179
+ // IPv6 (basic check)
180
+ if (parts[0].includes(':')) {
181
+ return prefixNum <= 128;
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /**
187
+ * Validate a base64-encoded 32-byte key (WireGuard X25519 format).
188
+ */
189
+ private static validateBase64Key(key: string, fieldName: string): void {
190
+ if (key.length !== 44) {
191
+ throw new Error(`VpnConfig: ${fieldName} must be 44 characters (base64 of 32 bytes), got ${key.length}`);
192
+ }
193
+ try {
194
+ const buf = Buffer.from(key, 'base64');
195
+ if (buf.length !== 32) {
196
+ throw new Error(`VpnConfig: ${fieldName} must decode to 32 bytes, got ${buf.length}`);
197
+ }
198
+ } catch (e) {
199
+ if (e instanceof Error && e.message.startsWith('VpnConfig:')) throw e;
200
+ throw new Error(`VpnConfig: ${fieldName} is not valid base64`);
201
+ }
202
+ }
107
203
  }
@@ -8,6 +8,8 @@ import type {
8
8
  IVpnClientInfo,
9
9
  IVpnKeypair,
10
10
  IVpnClientTelemetry,
11
+ IWgPeerConfig,
12
+ IWgPeerInfo,
11
13
  TVpnServerCommands,
12
14
  } from './smartvpn.interfaces.js';
13
15
 
@@ -121,6 +123,35 @@ export class VpnServer extends plugins.events.EventEmitter {
121
123
  return this.bridge.sendCommand('getClientTelemetry', { clientId });
122
124
  }
123
125
 
126
+ /**
127
+ * Generate a WireGuard-compatible X25519 keypair.
128
+ */
129
+ public async generateWgKeypair(): Promise<IVpnKeypair> {
130
+ return this.bridge.sendCommand('generateWgKeypair', {} as Record<string, never>);
131
+ }
132
+
133
+ /**
134
+ * Add a WireGuard peer (server must be running in wireguard mode).
135
+ */
136
+ public async addWgPeer(peer: IWgPeerConfig): Promise<void> {
137
+ await this.bridge.sendCommand('addWgPeer', { peer });
138
+ }
139
+
140
+ /**
141
+ * Remove a WireGuard peer by public key.
142
+ */
143
+ public async removeWgPeer(publicKey: string): Promise<void> {
144
+ await this.bridge.sendCommand('removeWgPeer', { publicKey });
145
+ }
146
+
147
+ /**
148
+ * List WireGuard peers with stats.
149
+ */
150
+ public async listWgPeers(): Promise<IWgPeerInfo[]> {
151
+ const result = await this.bridge.sendCommand('listWgPeers', {} as Record<string, never>);
152
+ return result.peers;
153
+ }
154
+
124
155
  /**
125
156
  * Stop the daemon bridge.
126
157
  */