@serve.zone/dcrouter 11.12.4 → 11.13.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.
Files changed (50) hide show
  1. package/dist_serve/bundle.js +705 -548
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/classes.dcrouter.d.ts +30 -0
  4. package/dist_ts/classes.dcrouter.js +92 -2
  5. package/dist_ts/config/classes.route-config-manager.d.ts +2 -1
  6. package/dist_ts/config/classes.route-config-manager.js +21 -5
  7. package/dist_ts/opsserver/classes.opsserver.d.ts +1 -0
  8. package/dist_ts/opsserver/classes.opsserver.js +3 -1
  9. package/dist_ts/opsserver/handlers/index.d.ts +1 -0
  10. package/dist_ts/opsserver/handlers/index.js +2 -1
  11. package/dist_ts/opsserver/handlers/vpn.handler.d.ts +6 -0
  12. package/dist_ts/opsserver/handlers/vpn.handler.js +199 -0
  13. package/dist_ts/plugins.d.ts +2 -1
  14. package/dist_ts/plugins.js +3 -2
  15. package/dist_ts/vpn/classes.vpn-manager.d.ts +113 -0
  16. package/dist_ts/vpn/classes.vpn-manager.js +297 -0
  17. package/dist_ts/vpn/index.d.ts +1 -0
  18. package/dist_ts/vpn/index.js +2 -0
  19. package/dist_ts_interfaces/data/index.d.ts +1 -0
  20. package/dist_ts_interfaces/data/index.js +2 -1
  21. package/dist_ts_interfaces/data/remoteingress.d.ts +10 -1
  22. package/dist_ts_interfaces/data/vpn.d.ts +43 -0
  23. package/dist_ts_interfaces/data/vpn.js +2 -0
  24. package/dist_ts_interfaces/requests/index.d.ts +1 -0
  25. package/dist_ts_interfaces/requests/index.js +2 -1
  26. package/dist_ts_interfaces/requests/vpn.d.ts +135 -0
  27. package/dist_ts_interfaces/requests/vpn.js +3 -0
  28. package/dist_ts_web/00_commitinfo_data.js +1 -1
  29. package/dist_ts_web/appstate.d.ts +22 -0
  30. package/dist_ts_web/appstate.js +111 -1
  31. package/dist_ts_web/elements/index.d.ts +1 -0
  32. package/dist_ts_web/elements/index.js +2 -1
  33. package/dist_ts_web/elements/ops-dashboard.js +7 -1
  34. package/dist_ts_web/elements/ops-view-vpn.d.ts +14 -0
  35. package/dist_ts_web/elements/ops-view-vpn.js +369 -0
  36. package/package.json +2 -1
  37. package/ts/00_commitinfo_data.ts +1 -1
  38. package/ts/classes.dcrouter.ts +126 -0
  39. package/ts/config/classes.route-config-manager.ts +20 -3
  40. package/ts/opsserver/classes.opsserver.ts +2 -0
  41. package/ts/opsserver/handlers/index.ts +2 -1
  42. package/ts/opsserver/handlers/vpn.handler.ts +257 -0
  43. package/ts/plugins.ts +2 -1
  44. package/ts/vpn/classes.vpn-manager.ts +378 -0
  45. package/ts/vpn/index.ts +1 -0
  46. package/ts_web/00_commitinfo_data.ts +1 -1
  47. package/ts_web/appstate.ts +164 -0
  48. package/ts_web/elements/index.ts +1 -0
  49. package/ts_web/elements/ops-dashboard.ts +6 -0
  50. package/ts_web/elements/ops-view-vpn.ts +330 -0
@@ -0,0 +1,257 @@
1
+ import * as plugins from '../../plugins.js';
2
+ import type { OpsServer } from '../classes.opsserver.js';
3
+ import * as interfaces from '../../../ts_interfaces/index.js';
4
+
5
+ export class VpnHandler {
6
+ constructor(private opsServerRef: OpsServer) {
7
+ this.registerHandlers();
8
+ }
9
+
10
+ private registerHandlers(): void {
11
+ const viewRouter = this.opsServerRef.viewRouter;
12
+ const adminRouter = this.opsServerRef.adminRouter;
13
+
14
+ // ---- Read endpoints (viewRouter — valid identity required via middleware) ----
15
+
16
+ // Get all registered VPN clients
17
+ viewRouter.addTypedHandler(
18
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnClients>(
19
+ 'getVpnClients',
20
+ async (dataArg, toolsArg) => {
21
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
22
+ if (!manager) {
23
+ return { clients: [] };
24
+ }
25
+ const clients = manager.listClients().map((c) => ({
26
+ clientId: c.clientId,
27
+ enabled: c.enabled,
28
+ tags: c.tags,
29
+ description: c.description,
30
+ assignedIp: c.assignedIp,
31
+ createdAt: c.createdAt,
32
+ updatedAt: c.updatedAt,
33
+ expiresAt: c.expiresAt,
34
+ }));
35
+ return { clients };
36
+ },
37
+ ),
38
+ );
39
+
40
+ // Get VPN server status
41
+ viewRouter.addTypedHandler(
42
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnStatus>(
43
+ 'getVpnStatus',
44
+ async (dataArg, toolsArg) => {
45
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
46
+ const vpnConfig = this.opsServerRef.dcRouterRef.options.vpnConfig;
47
+ if (!manager) {
48
+ return {
49
+ status: {
50
+ running: false,
51
+ forwardingMode: 'socket' as const,
52
+ subnet: vpnConfig?.subnet || '10.8.0.0/24',
53
+ wgListenPort: vpnConfig?.wgListenPort ?? 51820,
54
+ serverPublicKeys: null,
55
+ registeredClients: 0,
56
+ connectedClients: 0,
57
+ },
58
+ };
59
+ }
60
+
61
+ const connected = await manager.getConnectedClients();
62
+ return {
63
+ status: {
64
+ running: manager.running,
65
+ forwardingMode: manager.forwardingMode,
66
+ subnet: manager.getSubnet(),
67
+ wgListenPort: vpnConfig?.wgListenPort ?? 51820,
68
+ serverPublicKeys: manager.getServerPublicKeys(),
69
+ registeredClients: manager.listClients().length,
70
+ connectedClients: connected.length,
71
+ },
72
+ };
73
+ },
74
+ ),
75
+ );
76
+
77
+ // ---- Write endpoints (adminRouter — admin identity required via middleware) ----
78
+
79
+ // Create a new VPN client
80
+ adminRouter.addTypedHandler(
81
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateVpnClient>(
82
+ 'createVpnClient',
83
+ async (dataArg, toolsArg) => {
84
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
85
+ if (!manager) {
86
+ return { success: false, message: 'VPN not configured' };
87
+ }
88
+
89
+ try {
90
+ const bundle = await manager.createClient({
91
+ clientId: dataArg.clientId,
92
+ tags: dataArg.tags,
93
+ description: dataArg.description,
94
+ });
95
+
96
+ return {
97
+ success: true,
98
+ client: {
99
+ clientId: bundle.entry.clientId,
100
+ enabled: bundle.entry.enabled ?? true,
101
+ tags: bundle.entry.tags,
102
+ description: bundle.entry.description,
103
+ assignedIp: bundle.entry.assignedIp,
104
+ createdAt: Date.now(),
105
+ updatedAt: Date.now(),
106
+ expiresAt: bundle.entry.expiresAt,
107
+ },
108
+ wireguardConfig: bundle.wireguardConfig,
109
+ };
110
+ } catch (err: unknown) {
111
+ return { success: false, message: (err as Error).message };
112
+ }
113
+ },
114
+ ),
115
+ );
116
+
117
+ // Delete a VPN client
118
+ adminRouter.addTypedHandler(
119
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteVpnClient>(
120
+ 'deleteVpnClient',
121
+ async (dataArg, toolsArg) => {
122
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
123
+ if (!manager) {
124
+ return { success: false, message: 'VPN not configured' };
125
+ }
126
+
127
+ try {
128
+ await manager.removeClient(dataArg.clientId);
129
+ return { success: true };
130
+ } catch (err: unknown) {
131
+ return { success: false, message: (err as Error).message };
132
+ }
133
+ },
134
+ ),
135
+ );
136
+
137
+ // Enable a VPN client
138
+ adminRouter.addTypedHandler(
139
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_EnableVpnClient>(
140
+ 'enableVpnClient',
141
+ async (dataArg, toolsArg) => {
142
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
143
+ if (!manager) {
144
+ return { success: false, message: 'VPN not configured' };
145
+ }
146
+
147
+ try {
148
+ await manager.enableClient(dataArg.clientId);
149
+ return { success: true };
150
+ } catch (err: unknown) {
151
+ return { success: false, message: (err as Error).message };
152
+ }
153
+ },
154
+ ),
155
+ );
156
+
157
+ // Disable a VPN client
158
+ adminRouter.addTypedHandler(
159
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DisableVpnClient>(
160
+ 'disableVpnClient',
161
+ async (dataArg, toolsArg) => {
162
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
163
+ if (!manager) {
164
+ return { success: false, message: 'VPN not configured' };
165
+ }
166
+
167
+ try {
168
+ await manager.disableClient(dataArg.clientId);
169
+ return { success: true };
170
+ } catch (err: unknown) {
171
+ return { success: false, message: (err as Error).message };
172
+ }
173
+ },
174
+ ),
175
+ );
176
+
177
+ // Rotate a VPN client's keys
178
+ adminRouter.addTypedHandler(
179
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RotateVpnClientKey>(
180
+ 'rotateVpnClientKey',
181
+ async (dataArg, toolsArg) => {
182
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
183
+ if (!manager) {
184
+ return { success: false, message: 'VPN not configured' };
185
+ }
186
+
187
+ try {
188
+ const bundle = await manager.rotateClientKey(dataArg.clientId);
189
+ return {
190
+ success: true,
191
+ wireguardConfig: bundle.wireguardConfig,
192
+ };
193
+ } catch (err: unknown) {
194
+ return { success: false, message: (err as Error).message };
195
+ }
196
+ },
197
+ ),
198
+ );
199
+
200
+ // Export a VPN client config
201
+ adminRouter.addTypedHandler(
202
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ExportVpnClientConfig>(
203
+ 'exportVpnClientConfig',
204
+ async (dataArg, toolsArg) => {
205
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
206
+ if (!manager) {
207
+ return { success: false, message: 'VPN not configured' };
208
+ }
209
+
210
+ try {
211
+ const config = await manager.exportClientConfig(dataArg.clientId, dataArg.format);
212
+ return { success: true, config };
213
+ } catch (err: unknown) {
214
+ return { success: false, message: (err as Error).message };
215
+ }
216
+ },
217
+ ),
218
+ );
219
+
220
+ // Get telemetry for a specific VPN client
221
+ viewRouter.addTypedHandler(
222
+ new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnClientTelemetry>(
223
+ 'getVpnClientTelemetry',
224
+ async (dataArg, toolsArg) => {
225
+ const manager = this.opsServerRef.dcRouterRef.vpnManager;
226
+ if (!manager) {
227
+ return { success: false, message: 'VPN not configured' };
228
+ }
229
+
230
+ try {
231
+ const telemetry = await manager.getClientTelemetry(dataArg.clientId);
232
+ if (!telemetry) {
233
+ return { success: false, message: 'Client not found or not connected' };
234
+ }
235
+ return {
236
+ success: true,
237
+ telemetry: {
238
+ clientId: telemetry.clientId,
239
+ assignedIp: telemetry.assignedIp,
240
+ bytesSent: telemetry.bytesSent,
241
+ bytesReceived: telemetry.bytesReceived,
242
+ packetsDropped: telemetry.packetsDropped,
243
+ bytesDropped: telemetry.bytesDropped,
244
+ lastKeepaliveAt: telemetry.lastKeepaliveAt,
245
+ keepalivesReceived: telemetry.keepalivesReceived,
246
+ rateLimitBytesPerSec: telemetry.rateLimitBytesPerSec,
247
+ burstBytes: telemetry.burstBytes,
248
+ },
249
+ };
250
+ } catch (err: unknown) {
251
+ return { success: false, message: (err as Error).message };
252
+ }
253
+ },
254
+ ),
255
+ );
256
+ }
257
+ }
package/ts/plugins.ts CHANGED
@@ -58,13 +58,14 @@ import * as smartnetwork from '@push.rocks/smartnetwork';
58
58
  import * as smartpath from '@push.rocks/smartpath';
59
59
  import * as smartproxy from '@push.rocks/smartproxy';
60
60
  import * as smartpromise from '@push.rocks/smartpromise';
61
+ import * as smartvpn from '@push.rocks/smartvpn';
61
62
  import * as smartradius from '@push.rocks/smartradius';
62
63
  import * as smartrequest from '@push.rocks/smartrequest';
63
64
  import * as smartrx from '@push.rocks/smartrx';
64
65
  import * as smartunique from '@push.rocks/smartunique';
65
66
  import * as taskbuffer from '@push.rocks/taskbuffer';
66
67
 
67
- export { projectinfo, qenv, smartacme, smartdata, smartdns, smartfs, smartguard, smartjwt, smartlog, smartmetrics, smartdb, smartmta, smartnetwork, smartpath, smartproxy, smartpromise, smartradius, smartrequest, smartrx, smartunique, taskbuffer };
68
+ export { projectinfo, qenv, smartacme, smartdata, smartdns, smartfs, smartguard, smartjwt, smartlog, smartmetrics, smartdb, smartmta, smartnetwork, smartpath, smartproxy, smartpromise, smartradius, smartrequest, smartrx, smartunique, smartvpn, taskbuffer };
68
69
 
69
70
  // Define SmartLog types for use in error handling
70
71
  export type TLogLevel = 'error' | 'warn' | 'info' | 'success' | 'debug';
@@ -0,0 +1,378 @@
1
+ import * as plugins from '../plugins.js';
2
+ import { logger } from '../logger.js';
3
+ import type { StorageManager } from '../storage/classes.storagemanager.js';
4
+
5
+ const STORAGE_PREFIX_KEYS = '/vpn/server-keys';
6
+ const STORAGE_PREFIX_CLIENTS = '/vpn/clients/';
7
+
8
+ export interface IVpnManagerConfig {
9
+ /** VPN subnet CIDR (default: '10.8.0.0/24') */
10
+ subnet?: string;
11
+ /** WireGuard UDP listen port (default: 51820) */
12
+ wgListenPort?: number;
13
+ /** DNS servers pushed to VPN clients */
14
+ dns?: string[];
15
+ /** Server endpoint hostname for client configs (e.g. 'vpn.example.com') */
16
+ serverEndpoint?: string;
17
+ /** Override forwarding mode. Default: auto-detect (tun if root, socket otherwise) */
18
+ forwardingMode?: 'tun' | 'socket';
19
+ }
20
+
21
+ interface IPersistedServerKeys {
22
+ noisePrivateKey: string;
23
+ noisePublicKey: string;
24
+ wgPrivateKey: string;
25
+ wgPublicKey: string;
26
+ }
27
+
28
+ interface IPersistedClient {
29
+ clientId: string;
30
+ enabled: boolean;
31
+ tags?: string[];
32
+ description?: string;
33
+ assignedIp?: string;
34
+ noisePublicKey: string;
35
+ wgPublicKey: string;
36
+ createdAt: number;
37
+ updatedAt: number;
38
+ expiresAt?: string;
39
+ }
40
+
41
+ /**
42
+ * Manages the SmartVPN server lifecycle and VPN client CRUD.
43
+ * Persists server keys and client registrations via StorageManager.
44
+ */
45
+ export class VpnManager {
46
+ private storageManager: StorageManager;
47
+ private config: IVpnManagerConfig;
48
+ private vpnServer?: plugins.smartvpn.VpnServer;
49
+ private clients: Map<string, IPersistedClient> = new Map();
50
+ private serverKeys?: IPersistedServerKeys;
51
+ private _forwardingMode: 'tun' | 'socket';
52
+
53
+ constructor(storageManager: StorageManager, config: IVpnManagerConfig) {
54
+ this.storageManager = storageManager;
55
+ this.config = config;
56
+ // Auto-detect forwarding mode: tun if root, socket otherwise
57
+ this._forwardingMode = config.forwardingMode
58
+ ?? (process.getuid?.() === 0 ? 'tun' : 'socket');
59
+ }
60
+
61
+ /** The effective forwarding mode (tun or socket). */
62
+ public get forwardingMode(): 'tun' | 'socket' {
63
+ return this._forwardingMode;
64
+ }
65
+
66
+ /** The VPN subnet CIDR. */
67
+ public getSubnet(): string {
68
+ return this.config.subnet || '10.8.0.0/24';
69
+ }
70
+
71
+ /** Whether the VPN server is running. */
72
+ public get running(): boolean {
73
+ return this.vpnServer?.running ?? false;
74
+ }
75
+
76
+ /**
77
+ * Start the VPN server.
78
+ * Loads or generates server keys, loads persisted clients, starts VpnServer.
79
+ */
80
+ public async start(): Promise<void> {
81
+ // Load or generate server keys
82
+ this.serverKeys = await this.loadOrGenerateServerKeys();
83
+
84
+ // Load persisted clients
85
+ await this.loadPersistedClients();
86
+
87
+ // Build client entries for the daemon
88
+ const clientEntries: plugins.smartvpn.IClientEntry[] = [];
89
+ for (const client of this.clients.values()) {
90
+ clientEntries.push({
91
+ clientId: client.clientId,
92
+ publicKey: client.noisePublicKey,
93
+ wgPublicKey: client.wgPublicKey,
94
+ enabled: client.enabled,
95
+ tags: client.tags,
96
+ description: client.description,
97
+ assignedIp: client.assignedIp,
98
+ expiresAt: client.expiresAt,
99
+ });
100
+ }
101
+
102
+ const subnet = this.getSubnet();
103
+ const wgListenPort = this.config.wgListenPort ?? 51820;
104
+
105
+ // Create and start VpnServer
106
+ this.vpnServer = new plugins.smartvpn.VpnServer({
107
+ transport: { transport: 'stdio' },
108
+ });
109
+
110
+ const serverConfig: plugins.smartvpn.IVpnServerConfig = {
111
+ listenAddr: '0.0.0.0:0', // WS listener not strictly needed but required field
112
+ privateKey: this.serverKeys.noisePrivateKey,
113
+ publicKey: this.serverKeys.noisePublicKey,
114
+ subnet,
115
+ dns: this.config.dns,
116
+ forwardingMode: this._forwardingMode,
117
+ transportMode: 'all',
118
+ wgPrivateKey: this.serverKeys.wgPrivateKey,
119
+ wgListenPort,
120
+ clients: clientEntries,
121
+ socketForwardProxyProtocol: this._forwardingMode === 'socket',
122
+ };
123
+
124
+ await this.vpnServer.start(serverConfig);
125
+ logger.log('info', `VPN server started: mode=${this._forwardingMode}, subnet=${subnet}, wg=:${wgListenPort}, clients=${this.clients.size}`);
126
+ }
127
+
128
+ /**
129
+ * Stop the VPN server.
130
+ */
131
+ public async stop(): Promise<void> {
132
+ if (this.vpnServer) {
133
+ try {
134
+ await this.vpnServer.stopServer();
135
+ } catch {
136
+ // Ignore stop errors
137
+ }
138
+ this.vpnServer.stop();
139
+ this.vpnServer = undefined;
140
+ }
141
+ logger.log('info', 'VPN server stopped');
142
+ }
143
+
144
+ // ── Client CRUD ────────────────────────────────────────────────────────
145
+
146
+ /**
147
+ * Create a new VPN client. Returns the config bundle (secrets only shown once).
148
+ */
149
+ public async createClient(opts: {
150
+ clientId: string;
151
+ tags?: string[];
152
+ description?: string;
153
+ }): Promise<plugins.smartvpn.IClientConfigBundle> {
154
+ if (!this.vpnServer) {
155
+ throw new Error('VPN server not running');
156
+ }
157
+
158
+ const bundle = await this.vpnServer.createClient({
159
+ clientId: opts.clientId,
160
+ tags: opts.tags,
161
+ description: opts.description,
162
+ });
163
+
164
+ // Update WireGuard config endpoint if serverEndpoint is configured
165
+ if (this.config.serverEndpoint && bundle.wireguardConfig) {
166
+ const wgPort = this.config.wgListenPort ?? 51820;
167
+ bundle.wireguardConfig = bundle.wireguardConfig.replace(
168
+ /Endpoint\s*=\s*.+/,
169
+ `Endpoint = ${this.config.serverEndpoint}:${wgPort}`,
170
+ );
171
+ }
172
+
173
+ // Persist client entry (without private keys)
174
+ const persisted: IPersistedClient = {
175
+ clientId: bundle.entry.clientId,
176
+ enabled: bundle.entry.enabled ?? true,
177
+ tags: bundle.entry.tags,
178
+ description: bundle.entry.description,
179
+ assignedIp: bundle.entry.assignedIp,
180
+ noisePublicKey: bundle.entry.publicKey,
181
+ wgPublicKey: bundle.entry.wgPublicKey || '',
182
+ createdAt: Date.now(),
183
+ updatedAt: Date.now(),
184
+ expiresAt: bundle.entry.expiresAt,
185
+ };
186
+ this.clients.set(persisted.clientId, persisted);
187
+ await this.persistClient(persisted);
188
+
189
+ return bundle;
190
+ }
191
+
192
+ /**
193
+ * Remove a VPN client.
194
+ */
195
+ public async removeClient(clientId: string): Promise<void> {
196
+ if (!this.vpnServer) {
197
+ throw new Error('VPN server not running');
198
+ }
199
+ await this.vpnServer.removeClient(clientId);
200
+ this.clients.delete(clientId);
201
+ await this.storageManager.delete(`${STORAGE_PREFIX_CLIENTS}${clientId}`);
202
+ }
203
+
204
+ /**
205
+ * List all registered clients (without secrets).
206
+ */
207
+ public listClients(): IPersistedClient[] {
208
+ return [...this.clients.values()];
209
+ }
210
+
211
+ /**
212
+ * Enable a client.
213
+ */
214
+ public async enableClient(clientId: string): Promise<void> {
215
+ if (!this.vpnServer) throw new Error('VPN server not running');
216
+ await this.vpnServer.enableClient(clientId);
217
+ const client = this.clients.get(clientId);
218
+ if (client) {
219
+ client.enabled = true;
220
+ client.updatedAt = Date.now();
221
+ await this.persistClient(client);
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Disable a client.
227
+ */
228
+ public async disableClient(clientId: string): Promise<void> {
229
+ if (!this.vpnServer) throw new Error('VPN server not running');
230
+ await this.vpnServer.disableClient(clientId);
231
+ const client = this.clients.get(clientId);
232
+ if (client) {
233
+ client.enabled = false;
234
+ client.updatedAt = Date.now();
235
+ await this.persistClient(client);
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Rotate a client's keys. Returns the new config bundle.
241
+ */
242
+ public async rotateClientKey(clientId: string): Promise<plugins.smartvpn.IClientConfigBundle> {
243
+ if (!this.vpnServer) throw new Error('VPN server not running');
244
+ const bundle = await this.vpnServer.rotateClientKey(clientId);
245
+
246
+ // Update endpoint in WireGuard config
247
+ if (this.config.serverEndpoint && bundle.wireguardConfig) {
248
+ const wgPort = this.config.wgListenPort ?? 51820;
249
+ bundle.wireguardConfig = bundle.wireguardConfig.replace(
250
+ /Endpoint\s*=\s*.+/,
251
+ `Endpoint = ${this.config.serverEndpoint}:${wgPort}`,
252
+ );
253
+ }
254
+
255
+ // Update persisted entry with new public keys
256
+ const client = this.clients.get(clientId);
257
+ if (client) {
258
+ client.noisePublicKey = bundle.entry.publicKey;
259
+ client.wgPublicKey = bundle.entry.wgPublicKey || '';
260
+ client.updatedAt = Date.now();
261
+ await this.persistClient(client);
262
+ }
263
+
264
+ return bundle;
265
+ }
266
+
267
+ /**
268
+ * Export a client config (without secrets).
269
+ */
270
+ public async exportClientConfig(clientId: string, format: 'smartvpn' | 'wireguard'): Promise<string> {
271
+ if (!this.vpnServer) throw new Error('VPN server not running');
272
+ let config = await this.vpnServer.exportClientConfig(clientId, format);
273
+
274
+ // Update endpoint in WireGuard config
275
+ if (format === 'wireguard' && this.config.serverEndpoint) {
276
+ const wgPort = this.config.wgListenPort ?? 51820;
277
+ config = config.replace(
278
+ /Endpoint\s*=\s*.+/,
279
+ `Endpoint = ${this.config.serverEndpoint}:${wgPort}`,
280
+ );
281
+ }
282
+
283
+ return config;
284
+ }
285
+
286
+ // ── Status and telemetry ───────────────────────────────────────────────
287
+
288
+ /**
289
+ * Get server status.
290
+ */
291
+ public async getStatus(): Promise<plugins.smartvpn.IVpnStatus | null> {
292
+ if (!this.vpnServer) return null;
293
+ return this.vpnServer.getStatus();
294
+ }
295
+
296
+ /**
297
+ * Get server statistics.
298
+ */
299
+ public async getStatistics(): Promise<plugins.smartvpn.IVpnServerStatistics | null> {
300
+ if (!this.vpnServer) return null;
301
+ return this.vpnServer.getStatistics();
302
+ }
303
+
304
+ /**
305
+ * List currently connected clients.
306
+ */
307
+ public async getConnectedClients(): Promise<plugins.smartvpn.IVpnClientInfo[]> {
308
+ if (!this.vpnServer) return [];
309
+ return this.vpnServer.listClients();
310
+ }
311
+
312
+ /**
313
+ * Get telemetry for a specific client.
314
+ */
315
+ public async getClientTelemetry(clientId: string): Promise<plugins.smartvpn.IVpnClientTelemetry | null> {
316
+ if (!this.vpnServer) return null;
317
+ return this.vpnServer.getClientTelemetry(clientId);
318
+ }
319
+
320
+ /**
321
+ * Get server public keys (for display/info).
322
+ */
323
+ public getServerPublicKeys(): { noisePublicKey: string; wgPublicKey: string } | null {
324
+ if (!this.serverKeys) return null;
325
+ return {
326
+ noisePublicKey: this.serverKeys.noisePublicKey,
327
+ wgPublicKey: this.serverKeys.wgPublicKey,
328
+ };
329
+ }
330
+
331
+ // ── Private helpers ────────────────────────────────────────────────────
332
+
333
+ private async loadOrGenerateServerKeys(): Promise<IPersistedServerKeys> {
334
+ const stored = await this.storageManager.getJSON<IPersistedServerKeys>(STORAGE_PREFIX_KEYS);
335
+ if (stored?.noisePrivateKey && stored?.wgPrivateKey) {
336
+ logger.log('info', 'Loaded VPN server keys from storage');
337
+ return stored;
338
+ }
339
+
340
+ // Generate new keys via the daemon
341
+ const tempServer = new plugins.smartvpn.VpnServer({
342
+ transport: { transport: 'stdio' },
343
+ });
344
+ await tempServer.start();
345
+
346
+ const noiseKeys = await tempServer.generateKeypair();
347
+ const wgKeys = await tempServer.generateWgKeypair();
348
+ tempServer.stop();
349
+
350
+ const keys: IPersistedServerKeys = {
351
+ noisePrivateKey: noiseKeys.privateKey,
352
+ noisePublicKey: noiseKeys.publicKey,
353
+ wgPrivateKey: wgKeys.privateKey,
354
+ wgPublicKey: wgKeys.publicKey,
355
+ };
356
+
357
+ await this.storageManager.setJSON(STORAGE_PREFIX_KEYS, keys);
358
+ logger.log('info', 'Generated and persisted new VPN server keys');
359
+ return keys;
360
+ }
361
+
362
+ private async loadPersistedClients(): Promise<void> {
363
+ const keys = await this.storageManager.list(STORAGE_PREFIX_CLIENTS);
364
+ for (const key of keys) {
365
+ const client = await this.storageManager.getJSON<IPersistedClient>(key);
366
+ if (client) {
367
+ this.clients.set(client.clientId, client);
368
+ }
369
+ }
370
+ if (this.clients.size > 0) {
371
+ logger.log('info', `Loaded ${this.clients.size} persisted VPN client(s)`);
372
+ }
373
+ }
374
+
375
+ private async persistClient(client: IPersistedClient): Promise<void> {
376
+ await this.storageManager.setJSON(`${STORAGE_PREFIX_CLIENTS}${client.clientId}`, client);
377
+ }
378
+ }
@@ -0,0 +1 @@
1
+ export * from './classes.vpn-manager.js';
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@serve.zone/dcrouter',
6
- version: '11.12.4',
6
+ version: '11.13.0',
7
7
  description: 'A multifaceted routing service handling mail and SMS delivery functions.'
8
8
  }