@push.rocks/smartvpn 1.0.3

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.
Files changed (35) hide show
  1. package/dist_rust/smartvpn_daemon_linux_amd64 +0 -0
  2. package/dist_rust/smartvpn_daemon_linux_arm64 +0 -0
  3. package/dist_ts/00_commitinfo_data.d.ts +8 -0
  4. package/dist_ts/00_commitinfo_data.js +9 -0
  5. package/dist_ts/index.d.ts +6 -0
  6. package/dist_ts/index.js +7 -0
  7. package/dist_ts/smartvpn.classes.vpnbridge.d.ts +34 -0
  8. package/dist_ts/smartvpn.classes.vpnbridge.js +123 -0
  9. package/dist_ts/smartvpn.classes.vpnclient.d.ts +40 -0
  10. package/dist_ts/smartvpn.classes.vpnclient.js +69 -0
  11. package/dist_ts/smartvpn.classes.vpnconfig.d.ts +30 -0
  12. package/dist_ts/smartvpn.classes.vpnconfig.js +98 -0
  13. package/dist_ts/smartvpn.classes.vpninstaller.d.ts +37 -0
  14. package/dist_ts/smartvpn.classes.vpninstaller.js +105 -0
  15. package/dist_ts/smartvpn.classes.vpnserver.d.ts +46 -0
  16. package/dist_ts/smartvpn.classes.vpnserver.js +85 -0
  17. package/dist_ts/smartvpn.interfaces.d.ts +167 -0
  18. package/dist_ts/smartvpn.interfaces.js +5 -0
  19. package/dist_ts/smartvpn.paths.d.ts +1 -0
  20. package/dist_ts/smartvpn.paths.js +3 -0
  21. package/dist_ts/smartvpn.plugins.d.ts +9 -0
  22. package/dist_ts/smartvpn.plugins.js +12 -0
  23. package/license.md +21 -0
  24. package/package.json +52 -0
  25. package/readme.md +410 -0
  26. package/ts/00_commitinfo_data.ts +8 -0
  27. package/ts/index.ts +6 -0
  28. package/ts/smartvpn.classes.vpnbridge.ts +152 -0
  29. package/ts/smartvpn.classes.vpnclient.ts +87 -0
  30. package/ts/smartvpn.classes.vpnconfig.ts +104 -0
  31. package/ts/smartvpn.classes.vpninstaller.ts +126 -0
  32. package/ts/smartvpn.classes.vpnserver.ts +107 -0
  33. package/ts/smartvpn.interfaces.ts +166 -0
  34. package/ts/smartvpn.paths.ts +6 -0
  35. package/ts/smartvpn.plugins.ts +14 -0
package/readme.md ADDED
@@ -0,0 +1,410 @@
1
+ # @push.rocks/smartvpn
2
+
3
+ A high-performance VPN solution with a **TypeScript control plane** and a **Rust data plane daemon**. Manage VPN connections with clean, typed APIs while all networking heavy lifting β€” encryption, tunneling, packet forwarding β€” runs at native speed in Rust.
4
+
5
+ ## Issue Reporting and Security
6
+
7
+ 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.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @push.rocks/smartvpn
13
+ # or
14
+ pnpm install @push.rocks/smartvpn
15
+ ```
16
+
17
+ ## πŸ—οΈ Architecture
18
+
19
+ ```
20
+ TypeScript (control plane) Rust (data plane)
21
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
22
+ β”‚ VpnClient / VpnServer β”‚ β”‚ smartvpn_daemon β”‚
23
+ β”‚ └─ VpnBridge │──stdio/──▢ β”‚ β”œβ”€ management (JSON IPC) β”‚
24
+ β”‚ └─ RustBridge β”‚ socket β”‚ β”œβ”€ transport (WebSocket/TLS) β”‚
25
+ β”‚ (smartrust) β”‚ β”‚ β”œβ”€ crypto (Noise NK + XCha) β”‚
26
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”œβ”€ codec (binary framing) β”‚
27
+ β”‚ β”œβ”€ keepalive (app-level) β”‚
28
+ β”‚ β”œβ”€ tunnel (TUN device) β”‚
29
+ β”‚ β”œβ”€ network (NAT/IP pool) β”‚
30
+ β”‚ └─ reconnect (backoff) β”‚
31
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
32
+ ```
33
+
34
+ **Key design decisions:**
35
+
36
+ | Decision | Choice | Why |
37
+ |----------|--------|-----|
38
+ | Transport | WebSocket over HTTPS | Works through Cloudflare and other terminating proxies |
39
+ | Encryption | Noise NK + XChaCha20-Poly1305 | Strong forward secrecy, large nonce space (no counter needed) |
40
+ | Keepalive | App-level (not WS pings) | Cloudflare drops WS ping frames; app-level pings survive |
41
+ | IPC | JSON lines over stdio/Unix socket | `stdio` for dev, `socket` for production (daemon stays alive) |
42
+ | Binary protocol | `[type:1B][length:4B][payload:NB]` | Minimal overhead, easy to parse at wire speed |
43
+
44
+ ## πŸš€ Quick Start
45
+
46
+ ### VPN Client
47
+
48
+ ```typescript
49
+ import { VpnClient } from '@push.rocks/smartvpn';
50
+
51
+ // Development: spawn the Rust daemon as a child process
52
+ const client = new VpnClient({
53
+ transport: { transport: 'stdio' },
54
+ });
55
+
56
+ // Start the daemon bridge
57
+ await client.start();
58
+
59
+ // Connect to a VPN server
60
+ const { assignedIp } = await client.connect({
61
+ serverUrl: 'wss://vpn.example.com/tunnel',
62
+ serverPublicKey: 'BASE64_SERVER_PUBLIC_KEY',
63
+ dns: ['1.1.1.1', '8.8.8.8'],
64
+ mtu: 1420,
65
+ keepaliveIntervalSecs: 30,
66
+ });
67
+
68
+ console.log(`Connected! Assigned IP: ${assignedIp}`);
69
+
70
+ // Check status
71
+ const status = await client.getStatus();
72
+ console.log(status); // { state: 'connected', assignedIp: '10.8.0.2', ... }
73
+
74
+ // Get traffic stats
75
+ const stats = await client.getStatistics();
76
+ console.log(stats); // { bytesSent, bytesReceived, packetsSent, ... }
77
+
78
+ // Disconnect
79
+ await client.disconnect();
80
+ client.stop();
81
+ ```
82
+
83
+ ### VPN Server
84
+
85
+ ```typescript
86
+ import { VpnServer } from '@push.rocks/smartvpn';
87
+
88
+ const server = new VpnServer({
89
+ transport: { transport: 'stdio' },
90
+ });
91
+
92
+ // Start the daemon and the VPN server
93
+ await server.start({
94
+ listenAddr: '0.0.0.0:443',
95
+ privateKey: 'BASE64_PRIVATE_KEY',
96
+ publicKey: 'BASE64_PUBLIC_KEY',
97
+ subnet: '10.8.0.0/24',
98
+ dns: ['1.1.1.1'],
99
+ mtu: 1420,
100
+ enableNat: true,
101
+ });
102
+
103
+ // Generate a Noise keypair
104
+ const keypair = await server.generateKeypair();
105
+ console.log(keypair); // { publicKey: '...', privateKey: '...' }
106
+
107
+ // List connected clients
108
+ const clients = await server.listClients();
109
+ // [{ clientId, assignedIp, connectedSince, bytesSent, bytesReceived }]
110
+
111
+ // Disconnect a specific client
112
+ await server.disconnectClient('some-client-id');
113
+
114
+ // Get server stats
115
+ const stats = await server.getStatistics();
116
+ // { bytesSent, bytesReceived, activeClients, totalConnections, ... }
117
+
118
+ // Stop
119
+ await server.stopServer();
120
+ server.stop();
121
+ ```
122
+
123
+ ### Production: Socket Transport
124
+
125
+ In production, the daemon runs as a system service and you connect over a Unix socket:
126
+
127
+ ```typescript
128
+ const client = new VpnClient({
129
+ transport: {
130
+ transport: 'socket',
131
+ socketPath: '/var/run/smartvpn.sock',
132
+ autoReconnect: true,
133
+ reconnectBaseDelayMs: 100,
134
+ reconnectMaxDelayMs: 30000,
135
+ maxReconnectAttempts: 10,
136
+ },
137
+ });
138
+
139
+ await client.start(); // connects to existing daemon (does not spawn)
140
+ ```
141
+
142
+ When using socket transport, `client.stop()` closes the socket but **does not kill the daemon** β€” exactly what you want in production.
143
+
144
+ ## πŸ“‹ API Reference
145
+
146
+ ### `VpnClient`
147
+
148
+ | Method | Returns | Description |
149
+ |--------|---------|-------------|
150
+ | `start()` | `Promise<boolean>` | Start the daemon bridge (spawn or connect) |
151
+ | `connect(config?)` | `Promise<{ assignedIp }>` | Connect to VPN server |
152
+ | `disconnect()` | `Promise<void>` | Disconnect from VPN |
153
+ | `getStatus()` | `Promise<IVpnStatus>` | Current connection state |
154
+ | `getStatistics()` | `Promise<IVpnStatistics>` | Traffic statistics |
155
+ | `stop()` | `void` | Kill/close the daemon bridge |
156
+ | `running` | `boolean` | Whether bridge is active |
157
+
158
+ ### `VpnServer`
159
+
160
+ | Method | Returns | Description |
161
+ |--------|---------|-------------|
162
+ | `start(config?)` | `Promise<void>` | Start daemon + VPN server |
163
+ | `stopServer()` | `Promise<void>` | Stop the VPN server |
164
+ | `getStatus()` | `Promise<IVpnStatus>` | Server connection state |
165
+ | `getStatistics()` | `Promise<IVpnServerStatistics>` | Server stats (includes client counts) |
166
+ | `listClients()` | `Promise<IVpnClientInfo[]>` | Connected clients |
167
+ | `disconnectClient(id)` | `Promise<void>` | Kick a client |
168
+ | `generateKeypair()` | `Promise<IVpnKeypair>` | Generate Noise NK keypair |
169
+ | `stop()` | `void` | Kill/close the daemon bridge |
170
+
171
+ ### `VpnConfig`
172
+
173
+ Static utility class for config validation and file I/O:
174
+
175
+ ```typescript
176
+ import { VpnConfig } from '@push.rocks/smartvpn';
177
+
178
+ // Validate (throws on invalid)
179
+ VpnConfig.validateClientConfig(config);
180
+ VpnConfig.validateServerConfig(config);
181
+
182
+ // Load/save JSON configs
183
+ const config = await VpnConfig.loadFromFile<IVpnClientConfig>('/etc/smartvpn/client.json');
184
+ await VpnConfig.saveToFile('/etc/smartvpn/client.json', config);
185
+ ```
186
+
187
+ ### `VpnInstaller`
188
+
189
+ Generate system service units for the daemon:
190
+
191
+ ```typescript
192
+ import { VpnInstaller } from '@push.rocks/smartvpn';
193
+
194
+ // Auto-detect platform
195
+ const platform = VpnInstaller.detectPlatform(); // 'linux' | 'macos' | 'windows' | 'unknown'
196
+
197
+ // Generate systemd unit (Linux)
198
+ const unit = VpnInstaller.generateSystemdUnit({
199
+ binaryPath: '/usr/local/bin/smartvpn_daemon',
200
+ socketPath: '/var/run/smartvpn.sock',
201
+ mode: 'server',
202
+ });
203
+ // unit.content = full systemd .service file
204
+ // unit.installPath = '/etc/systemd/system/smartvpn-server.service'
205
+
206
+ // Generate launchd plist (macOS)
207
+ const plist = VpnInstaller.generateLaunchdPlist({
208
+ binaryPath: '/usr/local/bin/smartvpn_daemon',
209
+ socketPath: '/var/run/smartvpn.sock',
210
+ mode: 'client',
211
+ });
212
+
213
+ // Auto-detect and generate
214
+ const serviceUnit = VpnInstaller.generateServiceUnit({
215
+ binaryPath: '/usr/local/bin/smartvpn_daemon',
216
+ socketPath: '/var/run/smartvpn.sock',
217
+ mode: 'server',
218
+ });
219
+ ```
220
+
221
+ ### Events
222
+
223
+ Both `VpnClient` and `VpnServer` extend `EventEmitter`:
224
+
225
+ ```typescript
226
+ client.on('status', (status) => { /* IVpnStatus */ });
227
+ client.on('error', (err) => { /* { message, code? } */ });
228
+ client.on('exit', ({ code, signal }) => { /* daemon exited */ });
229
+ client.on('reconnected', () => { /* socket reconnected */ });
230
+
231
+ server.on('client-connected', (info) => { /* IVpnClientInfo */ });
232
+ server.on('client-disconnected', ({ clientId, reason }) => { /* ... */ });
233
+ ```
234
+
235
+ ## πŸ” Security Model
236
+
237
+ The VPN uses a **Noise NK** handshake pattern:
238
+
239
+ 1. **NK** = client does **N**ot authenticate, but **K**nows the server's static public key
240
+ 2. The client generates an ephemeral keypair, performs `e, es` (Diffie-Hellman with server's static key)
241
+ 3. Server responds with `e, ee` (Diffie-Hellman with both ephemeral keys)
242
+ 4. Result: forward-secret transport keys derived from both DH operations
243
+
244
+ Post-handshake, all IP packets are encrypted with **XChaCha20-Poly1305**:
245
+ - 24-byte random nonces (no counter synchronization needed)
246
+ - 16-byte authentication tags
247
+ - Wire format: `[nonce:24B][ciphertext:var][tag:16B]`
248
+
249
+ ## πŸ“¦ Binary Protocol
250
+
251
+ Inside the WebSocket tunnel, packets use a simple binary framing:
252
+
253
+ ```
254
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
255
+ β”‚ Type (1B)β”‚ Len (4B) β”‚ Payload (variable) β”‚
256
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
257
+ ```
258
+
259
+ | Type | Value | Description |
260
+ |------|-------|-------------|
261
+ | `HandshakeInit` | `0x01` | Client β†’ Server handshake |
262
+ | `HandshakeResp` | `0x02` | Server β†’ Client handshake |
263
+ | `IpPacket` | `0x10` | Encrypted IP packet |
264
+ | `Keepalive` | `0x20` | App-level ping |
265
+ | `KeepaliveAck` | `0x21` | App-level pong |
266
+ | `SessionResume` | `0x30` | Resume a dropped session |
267
+ | `SessionResumeOk` | `0x31` | Resume accepted |
268
+ | `SessionResumeErr` | `0x32` | Resume rejected |
269
+ | `Disconnect` | `0x3F` | Graceful disconnect |
270
+
271
+ ## πŸ› οΈ Rust Daemon CLI
272
+
273
+ The Rust binary supports several modes:
274
+
275
+ ```bash
276
+ # Development: stdio management (JSON lines on stdin/stdout)
277
+ smartvpn_daemon --management --mode client
278
+ smartvpn_daemon --management --mode server
279
+
280
+ # Production: Unix socket management
281
+ smartvpn_daemon --management-socket /var/run/smartvpn.sock --mode server
282
+
283
+ # Generate a Noise keypair
284
+ smartvpn_daemon --generate-keypair
285
+ ```
286
+
287
+ ## πŸ”§ Building from Source
288
+
289
+ ```bash
290
+ # Install dependencies
291
+ pnpm install
292
+
293
+ # Build TypeScript + cross-compile Rust
294
+ pnpm build
295
+
296
+ # Build Rust only (debug)
297
+ cd rust && cargo build
298
+
299
+ # Run Rust tests
300
+ cd rust && cargo test
301
+
302
+ # Run TypeScript tests
303
+ pnpm test
304
+ ```
305
+
306
+ ## TypeScript Interfaces
307
+
308
+ <details>
309
+ <summary>Click to expand full type definitions</summary>
310
+
311
+ ```typescript
312
+ // Transport options
313
+ type TVpnTransportOptions =
314
+ | { transport: 'stdio' }
315
+ | {
316
+ transport: 'socket';
317
+ socketPath: string;
318
+ autoReconnect?: boolean;
319
+ reconnectBaseDelayMs?: number;
320
+ reconnectMaxDelayMs?: number;
321
+ maxReconnectAttempts?: number;
322
+ };
323
+
324
+ // Client config
325
+ interface IVpnClientConfig {
326
+ serverUrl: string; // e.g. 'wss://vpn.example.com/tunnel'
327
+ serverPublicKey: string; // base64-encoded Noise static key
328
+ dns?: string[];
329
+ mtu?: number; // default: 1420
330
+ keepaliveIntervalSecs?: number; // default: 30
331
+ }
332
+
333
+ // Server config
334
+ interface IVpnServerConfig {
335
+ listenAddr: string; // e.g. '0.0.0.0:443'
336
+ privateKey: string; // base64 Noise static private key
337
+ publicKey: string; // base64 Noise static public key
338
+ subnet: string; // e.g. '10.8.0.0/24'
339
+ tlsCert?: string;
340
+ tlsKey?: string;
341
+ dns?: string[];
342
+ mtu?: number;
343
+ keepaliveIntervalSecs?: number;
344
+ enableNat?: boolean;
345
+ }
346
+
347
+ // Status
348
+ type TVpnConnectionState = 'disconnected' | 'connecting' | 'handshaking'
349
+ | 'connected' | 'reconnecting' | 'error';
350
+
351
+ interface IVpnStatus {
352
+ state: TVpnConnectionState;
353
+ assignedIp?: string;
354
+ serverAddr?: string;
355
+ connectedSince?: string;
356
+ lastError?: string;
357
+ }
358
+
359
+ // Statistics
360
+ interface IVpnStatistics {
361
+ bytesSent: number;
362
+ bytesReceived: number;
363
+ packetsSent: number;
364
+ packetsReceived: number;
365
+ keepalivesSent: number;
366
+ keepalivesReceived: number;
367
+ uptimeSeconds: number;
368
+ }
369
+
370
+ interface IVpnServerStatistics extends IVpnStatistics {
371
+ activeClients: number;
372
+ totalConnections: number;
373
+ }
374
+
375
+ interface IVpnClientInfo {
376
+ clientId: string;
377
+ assignedIp: string;
378
+ connectedSince: string;
379
+ bytesSent: number;
380
+ bytesReceived: number;
381
+ }
382
+
383
+ interface IVpnKeypair {
384
+ publicKey: string;
385
+ privateKey: string;
386
+ }
387
+ ```
388
+
389
+ </details>
390
+
391
+ ## License and Legal Information
392
+
393
+ This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
394
+
395
+ **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.
396
+
397
+ ### Trademarks
398
+
399
+ 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.
400
+
401
+ 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.
402
+
403
+ ### Company Information
404
+
405
+ Task Venture Capital GmbH
406
+ Registered at District Court Bremen HRB 35230 HB, Germany
407
+
408
+ For any legal inquiries or further information, please contact us via email at hello@task.vc.
409
+
410
+ 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.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * autocreated commitinfo by @push.rocks/commitinfo
3
+ */
4
+ export const commitinfo = {
5
+ name: '@push.rocks/smartvpn',
6
+ version: '1.0.3',
7
+ description: 'A VPN solution with TypeScript control plane and Rust data plane daemon'
8
+ }
package/ts/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './smartvpn.interfaces.js';
2
+ export { VpnBridge } from './smartvpn.classes.vpnbridge.js';
3
+ export { VpnClient } from './smartvpn.classes.vpnclient.js';
4
+ export { VpnServer } from './smartvpn.classes.vpnserver.js';
5
+ export { VpnConfig } from './smartvpn.classes.vpnconfig.js';
6
+ export { VpnInstaller } from './smartvpn.classes.vpninstaller.js';
@@ -0,0 +1,152 @@
1
+ import * as plugins from './smartvpn.plugins.js';
2
+ import * as paths from './smartvpn.paths.js';
3
+ import type {
4
+ TVpnTransportOptions,
5
+ IVpnTransportSocket,
6
+ } from './smartvpn.interfaces.js';
7
+ import type { TCommandMap } from '@push.rocks/smartrust';
8
+
9
+ /**
10
+ * Get the package root directory.
11
+ */
12
+ function getPackageRoot(): string {
13
+ const thisDir = plugins.path.dirname(plugins.url.fileURLToPath(import.meta.url));
14
+ return plugins.path.resolve(thisDir, '..');
15
+ }
16
+
17
+ /**
18
+ * Map Node.js platform/arch to tsrust's platform suffix.
19
+ */
20
+ function getTsrustPlatformSuffix(): string | null {
21
+ const archMap: Record<string, string> = { x64: 'amd64', arm64: 'arm64' };
22
+ const osMap: Record<string, string> = { linux: 'linux', darwin: 'macos' };
23
+ const os = osMap[process.platform];
24
+ const arch = archMap[process.arch];
25
+ if (os && arch) {
26
+ return `${os}_${arch}`;
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /**
32
+ * Build local search paths for the smartvpn daemon binary.
33
+ */
34
+ function buildLocalPaths(binaryName: string): string[] {
35
+ const packageRoot = getPackageRoot();
36
+ const suffix = getTsrustPlatformSuffix();
37
+ const paths: string[] = [];
38
+
39
+ // dist_rust/ (tsrust cross-compiled output)
40
+ if (suffix) {
41
+ paths.push(plugins.path.join(packageRoot, 'dist_rust', `${binaryName}_${suffix}`));
42
+ }
43
+ paths.push(plugins.path.join(packageRoot, 'dist_rust', binaryName));
44
+
45
+ // Local dev build paths
46
+ paths.push(plugins.path.resolve(process.cwd(), 'rust', 'target', 'release', binaryName));
47
+ paths.push(plugins.path.resolve(process.cwd(), 'rust', 'target', 'debug', binaryName));
48
+
49
+ return paths;
50
+ }
51
+
52
+ /**
53
+ * Shared bridge wrapper around smartrust RustBridge.
54
+ * Supports stdio mode (dev: spawn child process) and socket mode (production: connect to running daemon).
55
+ */
56
+ export class VpnBridge<TCommands extends TCommandMap> extends plugins.events.EventEmitter {
57
+ private bridge: plugins.smartrust.RustBridge<TCommands>;
58
+ private transportOptions: TVpnTransportOptions;
59
+ private mode: 'client' | 'server';
60
+
61
+ constructor(options: {
62
+ transport: TVpnTransportOptions;
63
+ mode: 'client' | 'server';
64
+ binaryName?: string;
65
+ }) {
66
+ super();
67
+
68
+ const binaryName = options.binaryName || 'smartvpn_daemon';
69
+ this.transportOptions = options.transport;
70
+ this.mode = options.mode;
71
+
72
+ this.bridge = new plugins.smartrust.RustBridge<TCommands>({
73
+ binaryName,
74
+ envVarName: 'SMARTVPN_RUST_BINARY',
75
+ platformPackagePrefix: '@push.rocks/smartvpn',
76
+ localPaths: buildLocalPaths(binaryName),
77
+ cliArgs: ['--management', '--mode', this.mode],
78
+ maxPayloadSize: 10 * 1024 * 1024, // 10 MB
79
+ });
80
+
81
+ // Forward events from inner bridge
82
+ this.bridge.on('exit', (code: number | null, signal: string | null) => {
83
+ this.emit('exit', code, signal);
84
+ });
85
+ this.bridge.on('reconnected', () => {
86
+ this.emit('reconnected');
87
+ });
88
+
89
+ // Forward management events from the daemon
90
+ // smartrust emits 'management:<eventName>' for unsolicited events
91
+ this.bridge.on('management:status', (data: any) => {
92
+ this.emit('status', data);
93
+ });
94
+ this.bridge.on('management:error', (data: any) => {
95
+ this.emit('error', data);
96
+ });
97
+ this.bridge.on('management:client-connected', (data: any) => {
98
+ this.emit('client-connected', data);
99
+ });
100
+ this.bridge.on('management:client-disconnected', (data: any) => {
101
+ this.emit('client-disconnected', data);
102
+ });
103
+ this.bridge.on('management:started', (data: any) => {
104
+ this.emit('started', data);
105
+ });
106
+ this.bridge.on('management:stopped', (data: any) => {
107
+ this.emit('stopped', data);
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Start the bridge: spawn in stdio mode or connect in socket mode.
113
+ */
114
+ public async start(): Promise<boolean> {
115
+ if (this.transportOptions.transport === 'socket') {
116
+ const socketOpts = this.transportOptions as IVpnTransportSocket;
117
+ return this.bridge.connect(socketOpts.socketPath, {
118
+ autoReconnect: socketOpts.autoReconnect,
119
+ reconnectBaseDelayMs: socketOpts.reconnectBaseDelayMs,
120
+ reconnectMaxDelayMs: socketOpts.reconnectMaxDelayMs,
121
+ maxReconnectAttempts: socketOpts.maxReconnectAttempts,
122
+ });
123
+ } else {
124
+ return this.bridge.spawn();
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Stop the bridge. In socket mode, closes the socket (daemon stays alive).
130
+ * In stdio mode, kills the child process.
131
+ */
132
+ public stop(): void {
133
+ this.bridge.kill();
134
+ }
135
+
136
+ /**
137
+ * Send a typed command to the daemon.
138
+ */
139
+ public async sendCommand<K extends string & keyof TCommands>(
140
+ method: K,
141
+ params: TCommands[K]['params'],
142
+ ): Promise<TCommands[K]['result']> {
143
+ return this.bridge.sendCommand(method, params);
144
+ }
145
+
146
+ /**
147
+ * Whether the bridge is currently running/connected.
148
+ */
149
+ public get running(): boolean {
150
+ return this.bridge.running;
151
+ }
152
+ }
@@ -0,0 +1,87 @@
1
+ import * as plugins from './smartvpn.plugins.js';
2
+ import { VpnBridge } from './smartvpn.classes.vpnbridge.js';
3
+ import type {
4
+ IVpnClientOptions,
5
+ IVpnClientConfig,
6
+ IVpnStatus,
7
+ IVpnStatistics,
8
+ TVpnClientCommands,
9
+ } from './smartvpn.interfaces.js';
10
+
11
+ /**
12
+ * VPN Client β€” manages a smartvpn daemon in client mode.
13
+ */
14
+ export class VpnClient extends plugins.events.EventEmitter {
15
+ private bridge: VpnBridge<TVpnClientCommands>;
16
+ private options: IVpnClientOptions;
17
+
18
+ constructor(options: IVpnClientOptions) {
19
+ super();
20
+ this.options = options;
21
+ this.bridge = new VpnBridge<TVpnClientCommands>({
22
+ transport: options.transport,
23
+ mode: 'client',
24
+ });
25
+
26
+ // Forward bridge events
27
+ this.bridge.on('exit', (code: number | null, signal: string | null) => {
28
+ this.emit('exit', { code, signal });
29
+ });
30
+ this.bridge.on('reconnected', () => {
31
+ this.emit('reconnected');
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Start the daemon bridge (spawn or connect).
37
+ */
38
+ public async start(): Promise<boolean> {
39
+ return this.bridge.start();
40
+ }
41
+
42
+ /**
43
+ * Connect to the VPN server using the provided config.
44
+ */
45
+ public async connect(config?: IVpnClientConfig): Promise<{ assignedIp: string }> {
46
+ const cfg = config || this.options.config;
47
+ if (!cfg) {
48
+ throw new Error('VpnClient.connect: no config provided');
49
+ }
50
+ return this.bridge.sendCommand('connect', { config: cfg });
51
+ }
52
+
53
+ /**
54
+ * Disconnect from the VPN server.
55
+ */
56
+ public async disconnect(): Promise<void> {
57
+ await this.bridge.sendCommand('disconnect', {} as Record<string, never>);
58
+ }
59
+
60
+ /**
61
+ * Get current connection status.
62
+ */
63
+ public async getStatus(): Promise<IVpnStatus> {
64
+ return this.bridge.sendCommand('getStatus', {} as Record<string, never>);
65
+ }
66
+
67
+ /**
68
+ * Get traffic statistics.
69
+ */
70
+ public async getStatistics(): Promise<IVpnStatistics> {
71
+ return this.bridge.sendCommand('getStatistics', {} as Record<string, never>);
72
+ }
73
+
74
+ /**
75
+ * Stop the daemon bridge.
76
+ */
77
+ public stop(): void {
78
+ this.bridge.stop();
79
+ }
80
+
81
+ /**
82
+ * Whether the bridge is running.
83
+ */
84
+ public get running(): boolean {
85
+ return this.bridge.running;
86
+ }
87
+ }