UNPKG

wireguard-tools

Version:

The best way to interact with WireGuard from Node

325 lines (324 loc) 15.4 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WgConfig = void 0; var configParser_1 = require("./utils/configParser"); var getConfigFromFile_1 = require("./utils/getConfigFromFile"); var generateKeyPair_1 = require("./utils/generateKeyPair"); var writeConfig_1 = require("./utils/writeConfig"); var lodash_mergewith_1 = __importDefault(require("lodash.mergewith")); var exec_1 = require("./utils/exec"); /** A Javascript object representation of a WireGuard config file with some extras */ var WgConfig = /** @class */ (function () { /** creates a new WgConfig */ function WgConfig(init) { /** Defines the VPN settings for the local node. */ this.wgInterface = {}; if (init.filePath) this.filePath = init.filePath; if (init === null || init === void 0 ? void 0 : init.wgInterface) this.wgInterface = init.wgInterface; this.peers = (init === null || init === void 0 ? void 0 : init.peers) || []; this.preSharedKey = init === null || init === void 0 ? void 0 : init.preSharedKey; this.publicKey = init === null || init === void 0 ? void 0 : init.publicKey; } /** Return a string akin to a WireGuard config file from this WgConfig object */ WgConfig.prototype.toString = function () { return configParser_1.generateConfigString(this); }; /** JSON.stringify this WgConfig object */ WgConfig.prototype.toJson = function () { return JSON.stringify(this); }; /** Parse a WireGuard config file in the form of a string into this WgConfig object */ WgConfig.prototype.parse = function (configAsString) { var parsedObj = configParser_1.parseConfigString(configAsString); Object.assign(this, parsedObj); }; /** Parse a WireGuard config file from it's path in the file system */ WgConfig.prototype.parseFile = function (filePath) { return __awaiter(this, void 0, void 0, function () { var res; return __generator(this, function (_a) { switch (_a.label) { case 0: filePath = filePath || this.filePath; if (!filePath) throw new Error("No filePath found for WgConfig"); this.filePath = filePath; return [4 /*yield*/, getConfigFromFile_1.getConfigObjectFromFile({ filePath: filePath })]; case 1: res = _a.sent(); Object.assign(this, res); return [2 /*return*/]; } }); }); }; /** Write this WgConfig object as a WireGuard config file to a file in the system */ WgConfig.prototype.writeToFile = function (filePath) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: filePath = filePath || this.filePath; if (!filePath) throw new Error("No filePath found for WgConfig"); return [4 /*yield*/, writeConfig_1.writeConfig({ filePath: filePath, config: this })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** Generate a public/private key pair for this WgConfig object */ WgConfig.prototype.generateKeys = function (opts) { var _a; return __awaiter(this, void 0, void 0, function () { var overwrite, privateKey, preSharedKey, keys; return __generator(this, function (_b) { switch (_b.label) { case 0: overwrite = opts === null || opts === void 0 ? void 0 : opts.overwrite; privateKey = overwrite ? undefined : (_a = this.wgInterface) === null || _a === void 0 ? void 0 : _a.privateKey; preSharedKey = (opts === null || opts === void 0 ? void 0 : opts.preSharedKey) || false; return [4 /*yield*/, generateKeyPair_1.generateKeyPair({ preSharedKey: preSharedKey, privateKey: privateKey })]; case 1: keys = _b.sent(); this.publicKey = keys.publicKey; this.wgInterface.privateKey = keys.privateKey; this.preSharedKey = keys.preSharedKey; return [2 /*return*/, keys]; } }); }); }; /** * Add a peer to the peers for this WgConfig. * * If the peer already exists (found by public key) then it will be updated by merging the * existing with the new. The allowedIps will be replaced by the new peer's allowedIps unless * { mergeAllowedIps: true } is passed in as settings */ WgConfig.prototype.addPeer = function (peer, settings) { var mergeAllowedIps = settings === null || settings === void 0 ? void 0 : settings.mergeAllowedIps; if (!this.peers) this.peers = []; // check if peer exists by public key var i = this.peers.map(function (x) { return x.publicKey; }).indexOf(peer.publicKey); if (i === -1) { this.peers.push(peer); } else { lodash_mergewith_1.default(this.peers[i], peer, function (objValue, srcValue, key) { if (key === 'allowedIps' && Array.isArray(objValue) && Array.isArray(srcValue)) { return mergeAllowedIps ? __spread(new Set(__spread(objValue, srcValue))) : srcValue; } }); } }; /** * Remove a peer if it exists in the peer array by its public key */ WgConfig.prototype.removePeer = function (publicKey) { if (!this.peers) this.peers = []; var i = this.peers.map(function (x) { return x.publicKey; }).indexOf(publicKey); if (i !== -1) { this.peers.splice(i, 1); } }; /** Creates a WfgConfigPeer object from this WgCongig object */ WgConfig.prototype.createPeer = function (settings) { if (!this.publicKey) throw new Error('WgConfig object has no public key. Run generateKeys() first'); var peer = __assign({ publicKey: this.publicKey }, settings); return peer; }; /** Get a peer from the peer array by it's public key */ WgConfig.prototype.getPeer = function (publicKey) { if (!publicKey) return undefined; if (!this.peers || !this.peers.length) return undefined; return this.peers.find(function (x) { return x.publicKey === publicKey; }); }; /** brings up the wireguard interface */ WgConfig.prototype.up = function (filePath) { return __awaiter(this, void 0, void 0, function () { var code, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: filePath = filePath || this.filePath; if (!filePath) throw new Error("No filePath found for WgConfig"); code = 0; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, exec_1.exec("wg-quick up " + filePath, { // onData: (d) => console.log(d), // onError: (d) => console.log(d), onClose: function (d) { console.log("Wireguard interface " + filePath + " is up"); code = d; } })]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: e_1 = _a.sent(); if (code !== 0 && !(e_1.message.includes('already exists as') && e_1.message.includes('wg-quick'))) { throw e_1; } return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; /** brings down the wireguard interface */ WgConfig.prototype.down = function (filePath) { return __awaiter(this, void 0, void 0, function () { var code, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: filePath = filePath || this.filePath; if (!filePath) throw new Error("No filePath found for WgConfig"); code = 0; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, exec_1.exec("wg-quick down " + filePath, { // onData: (d) => console.log(d), // onError: (e) => console.error(e), onClose: function (d) { console.log("Wireguard interface " + filePath + " is down"); code = d; } })]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: e_2 = _a.sent(); if (code !== 0 && !e_2.message.includes('is not a WireGuard interface')) { throw e_2; } return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; /** restarts the wireguard interface */ WgConfig.prototype.restart = function (filePath) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.down(filePath)]; case 1: _a.sent(); return [4 /*yield*/, this.up(filePath)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** Saves the config to file and restarts it unless `{ noUp: true }` is passed */ WgConfig.prototype.save = function (opts) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.writeToFile(opts === null || opts === void 0 ? void 0 : opts.filePath)]; case 1: _a.sent(); if (!!(opts === null || opts === void 0 ? void 0 : opts.noUp)) return [3 /*break*/, 3]; return [4 /*yield*/, this.restart(opts === null || opts === void 0 ? void 0 : opts.filePath)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; return WgConfig; }()); exports.WgConfig = WgConfig;