Browse Source

better typescript

pull/1250/head
Bernd Storath 9 months ago
parent
commit
f96cc766c2
  1. 163
      src/utils/WireGuard.ts

163
src/utils/WireGuard.ts

@ -31,70 +31,85 @@ class ServerError extends Error {
} }
} }
type Server = {
privateKey: string;
publicKey: string;
address: string;
};
type Client = {
enabled: boolean;
name: string;
publicKey: string;
privateKey: string;
preSharedKey: string;
address: string;
createdAt: number;
updatedAt: Date;
allowedIPs?: string[];
};
type Config = {
server: Server;
clients: Record<string, Client>;
};
class WireGuard { class WireGuard {
async __buildConfig() { async __buildConfig() {
this.__configPromise = Promise.resolve().then(async () => { if (!WG_HOST) {
if (!WG_HOST) { throw new Error('WG_HOST Environment Variable Not Set!');
throw new Error('WG_HOST Environment Variable Not Set!'); }
}
debug('Loading configuration...'); debug('Loading configuration...');
let config; try {
try { const config = await fs.readFile(path.join(WG_PATH, 'wg0.json'), 'utf8');
config = await fs.readFile(path.join(WG_PATH, 'wg0.json'), 'utf8'); const parsedConfig = JSON.parse(config);
config = JSON.parse(config); debug('Configuration loaded.');
debug('Configuration loaded.'); return parsedConfig as Config;
} catch { } catch {
const privateKey = await exec('wg genkey'); const privateKey = await exec('wg genkey');
const publicKey = await exec(`echo ${privateKey} | wg pubkey`, { const publicKey = await exec(`echo ${privateKey} | wg pubkey`, {
log: 'echo ***hidden*** | wg pubkey', log: 'echo ***hidden*** | wg pubkey',
}); });
const address = WG_DEFAULT_ADDRESS.replace('x', '1'); const address = WG_DEFAULT_ADDRESS.replace('x', '1');
config = {
server: {
privateKey,
publicKey,
address,
},
clients: {},
};
debug('Configuration generated.');
}
const config: Config = {
server: {
privateKey,
publicKey,
address,
},
clients: {},
};
debug('Configuration generated.');
return config; return config;
}); }
return this.__configPromise;
} }
async getConfig() { async getConfig(): Promise<Config> {
if (!this.__configPromise) { const config = await this.__buildConfig();
const config = await this.__buildConfig();
await this.__saveConfig(config);
await this.__saveConfig(config); await exec('wg-quick down wg0').catch(() => {});
await exec('wg-quick down wg0').catch(() => {}); await exec('wg-quick up wg0').catch((err) => {
await exec('wg-quick up wg0').catch((err) => { if (
if ( err &&
err && err.message &&
err.message && err.message.includes('Cannot find device "wg0"')
err.message.includes('Cannot find device "wg0"') ) {
) { throw new Error(
throw new Error( 'WireGuard exited with the error: Cannot find device "wg0"\nThis usually means that your host\'s kernel does not support WireGuard!'
'WireGuard exited with the error: Cannot find device "wg0"\nThis usually means that your host\'s kernel does not support WireGuard!' );
); }
}
throw err;
});
// await Util.exec(`iptables -t nat -A POSTROUTING -s ${WG_DEFAULT_ADDRESS.replace('x', '0')}/24 -o ' + WG_DEVICE + ' -j MASQUERADE`);
// await Util.exec('iptables -A INPUT -p udp -m udp --dport 51820 -j ACCEPT');
// await Util.exec('iptables -A FORWARD -i wg0 -j ACCEPT');
// await Util.exec('iptables -A FORWARD -o wg0 -j ACCEPT');
await this.__syncConfig();
}
return this.__configPromise; throw err;
});
// await Util.exec(`iptables -t nat -A POSTROUTING -s ${WG_DEFAULT_ADDRESS.replace('x', '0')}/24 -o ' + WG_DEVICE + ' -j MASQUERADE`);
// await Util.exec('iptables -A INPUT -p udp -m udp --dport 51820 -j ACCEPT');
// await Util.exec('iptables -A FORWARD -i wg0 -j ACCEPT');
// await Util.exec('iptables -A FORWARD -o wg0 -j ACCEPT');
await this.__syncConfig();
return config;
} }
async saveConfig() { async saveConfig() {
@ -103,7 +118,7 @@ class WireGuard {
await this.__syncConfig(); await this.__syncConfig();
} }
async __saveConfig(config) { async __saveConfig(config: Config) {
let result = ` let result = `
# Note: Do not edit this file directly. # Note: Do not edit this file directly.
# Your changes will be overwritten! # Your changes will be overwritten!
@ -135,7 +150,7 @@ ${
debug('Config saving...'); debug('Config saving...');
await fs.writeFile( await fs.writeFile(
path.join(WG_PATH, 'wg0.json'), path.join(WG_PATH, 'wg0.json'),
JSON.stringify(config, false, 2), JSON.stringify(config, undefined, 2),
{ {
mode: 0o660, mode: 0o660,
} }
@ -207,7 +222,7 @@ ${
return clients; return clients;
} }
async getClient({ clientId }) { async getClient({ clientId }: { clientId: string }) {
const config = await this.getConfig(); const config = await this.getConfig();
const client = config.clients[clientId]; const client = config.clients[clientId];
if (!client) { if (!client) {
@ -217,7 +232,7 @@ ${
return client; return client;
} }
async getClientConfiguration({ clientId }) { async getClientConfiguration({ clientId }: { clientId: string }) {
const config = await this.getConfig(); const config = await this.getConfig();
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
@ -237,7 +252,7 @@ PersistentKeepalive = ${WG_PERSISTENT_KEEPALIVE}
Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`; Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
} }
async getClientQRCodeSVG({ clientId }) { async getClientQRCodeSVG({ clientId }: { clientId: string }) {
const config = await this.getClientConfiguration({ clientId }); const config = await this.getClientConfiguration({ clientId });
return QRCode.toString(config, { return QRCode.toString(config, {
type: 'svg', type: 'svg',
@ -245,7 +260,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
}); });
} }
async createClient({ name }) { async createClient({ name }: { name: string }) {
if (!name) { if (!name) {
throw new Error('Missing: Name'); throw new Error('Missing: Name');
} }
@ -298,7 +313,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
return client; return client;
} }
async deleteClient({ clientId }) { async deleteClient({ clientId }: { clientId: string }) {
const config = await this.getConfig(); const config = await this.getConfig();
if (config.clients[clientId]) { if (config.clients[clientId]) {
@ -307,7 +322,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
} }
} }
async enableClient({ clientId }) { async enableClient({ clientId }: { clientId: string }) {
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.enabled = true; client.enabled = true;
@ -316,7 +331,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
await this.saveConfig(); await this.saveConfig();
} }
async disableClient({ clientId }) { async disableClient({ clientId }: { clientId: string }) {
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.enabled = false; client.enabled = false;
@ -325,7 +340,13 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
await this.saveConfig(); await this.saveConfig();
} }
async updateClientName({ clientId, name }) { async updateClientName({
clientId,
name,
}: {
clientId: string;
name: string;
}) {
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.name = name; client.name = name;
@ -334,7 +355,13 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
await this.saveConfig(); await this.saveConfig();
} }
async updateClientAddress({ clientId, address }) { async updateClientAddress({
clientId,
address,
}: {
clientId: string;
address: string;
}) {
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
if (!isValidIPv4(address)) { if (!isValidIPv4(address)) {
@ -352,7 +379,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
await this.__syncConfig(); await this.__syncConfig();
} }
async restoreConfiguration(config) { async restoreConfiguration(config: string) {
debug('Starting configuration restore process.'); debug('Starting configuration restore process.');
const _config = JSON.parse(config); const _config = JSON.parse(config);
await this.__saveConfig(_config); await this.__saveConfig(_config);

Loading…
Cancel
Save