UNPKG

node-vpn-client

Version:

Controls a instance of OpenVpn Client through the manager interface

68 lines 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const node_vpn_manager_1 = require("node-vpn-manager"); const path = require("path"); const node_fetch_1 = require("node-fetch"); const ip_address_1 = require("ip-address"); const appRoot = require('app-root-path'); class Client { constructor({ sudoPasswd, ovpnFiles, ovpnFilePath, vpnUsername, vpnPasswd, onDisconnected, timeout }) { this.sudoPasswd = sudoPasswd; this.ovpnFiles = ovpnFiles; this.ovpnFilePath = ovpnFilePath; this.vpnUsername = vpnUsername; this.vpnPasswd = vpnPasswd; this.onDisconnected = onDisconnected; this.timeout = timeout; } connect() { return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () { let connectionTimeout = 0; const monitorConnectionTimeout = setInterval(() => tslib_1.__awaiter(this, void 0, void 0, function* () { connectionTimeout++; if (connectionTimeout > this.timeout) { yield vpn.kill(); this.state = 'disconnected'; clearInterval(monitorConnectionTimeout); yield vpn.kill(); reject("Connection Timeout"); } }), 1000); const vpn = new node_vpn_manager_1.default({ sudoPasswd: this.sudoPasswd, ovpnFile: path.normalize(path.resolve(appRoot + this.ovpnFiles[Math.floor(Math.random() * this.ovpnFiles.length)])), username: this.vpnUsername, password: this.vpnPasswd, onStateChange: (state) => tslib_1.__awaiter(this, void 0, void 0, function* () { if (state === 'CONNECTED' && this.state !== 'connected') { this.state = 'connected'; const res = yield node_fetch_1.default('http://icanhazip.com/'); const remoteIp = yield res.text(); console.log(remoteIp); const address = new ip_address_1.Address4(remoteIp.replace('\n', '')); if (address.isValid()) { clearInterval(monitorConnectionTimeout); resolve(remoteIp); } clearInterval(monitorConnectionTimeout); reject('Error getting ip address'); } if (state === 'EXITING' && this.onDisconnected && this.state !== 'disconnected') { this.state = 'disconnected'; yield vpn.kill(); clearInterval(monitorConnectionTimeout); this.onDisconnected(); } }) }); yield vpn.init(); yield vpn.connect(); })); } } exports.default = Client; //# sourceMappingURL=main.js.map