wireguard-client-wrapper
Version:
Crossplatform wrapper for wireguard client
96 lines (95 loc) • 3.22 kB
JavaScript
import { ExecError } from '../utils';
import { WgStrategy } from './wgStrategy';
export class WgWindowsStrategy extends WgStrategy {
async isInstalled() {
try {
await this.exec('wg --version', false);
}
catch (error) {
if (error instanceof ExecError) {
return false;
}
throw error;
}
try {
await this.exec('wireguard --version', false);
return false;
}
catch (error) {
if (error instanceof ExecError) {
if (String(error.stderr).includes('не является внутренней или внешней')) {
return false;
}
if (String(error.stderr).includes('is not recognized as an internal')) {
return false;
}
return true;
}
throw error;
}
}
async getActiveDevice() {
try {
const { stderr, stdout } = await this.exec('wg show', false);
if (stderr) {
throw new Error(stderr);
}
const lines = stdout.split(/\n/);
return lines[0].split(' ')[1]?.replace(/(\r\n|\n|\r)/gm, '') || null;
}
catch (error) {
if (error instanceof ExecError && error.stderr) {
const splittedText = String(error.stderr).split(':');
if (splittedText.length === 0) {
return '';
}
return splittedText[0].split(' ').slice(-1)[0];
}
throw error;
}
}
async up(filePath) {
await this.exec(`wireguard /installtunnelservice "${filePath}"`);
}
async down(filePath) {
await this.exec(`wireguard /uninstalltunnelservice ${this.getNameFromPath(filePath)}`);
}
getNameFromPath(filePath) {
const filename = filePath.replace(/^.*[\\/]/, '');
return filename.slice(0, Math.max(0, filename.lastIndexOf('.')));
}
async status(device) {
try {
const { stderr, stdout } = await this.exec(`wg show ${device}`);
if (stderr) {
throw new Error(String(stderr));
}
return Boolean(stdout.match(/interface: (.*)/));
}
catch (error) {
if (error instanceof ExecError &&
String(error.error).includes('No such file or directory')) {
return false;
}
throw error;
}
}
async generatePrivateKey() {
const { stdout, stderr } = await this.exec('wg genkey', false);
if (stderr) {
throw new Error(stderr);
}
return stdout.trim();
}
async getPublicKey(privateKey) {
const command = `echo ${privateKey} | wg pubkey`;
const { stdout, stderr } = await this.exec(command, false);
if (stderr) {
throw new Error(stderr);
}
return stdout.trim();
}
async exec(command, sudoPrompt = true) {
return super.exec(`set "PATH=%PATH%;%ProgramFiles%\\Wireguard" & ${command}`, sudoPrompt);
}
}