Browse Source

better typescript

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

81
src/utils/WireGuard.ts

@ -31,19 +31,41 @@ 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 {
config = await fs.readFile(path.join(WG_PATH, 'wg0.json'), 'utf8'); const config = await fs.readFile(path.join(WG_PATH, 'wg0.json'), 'utf8');
config = JSON.parse(config); const parsedConfig = 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`, {
@ -51,7 +73,7 @@ class WireGuard {
}); });
const address = WG_DEFAULT_ADDRESS.replace('x', '1'); const address = WG_DEFAULT_ADDRESS.replace('x', '1');
config = { const config: Config = {
server: { server: {
privateKey, privateKey,
publicKey, publicKey,
@ -60,16 +82,11 @@ class WireGuard {
clients: {}, clients: {},
}; };
debug('Configuration generated.'); 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);
@ -92,9 +109,7 @@ class WireGuard {
// await Util.exec('iptables -A FORWARD -i wg0 -j ACCEPT'); // await Util.exec('iptables -A FORWARD -i wg0 -j ACCEPT');
// await Util.exec('iptables -A FORWARD -o wg0 -j ACCEPT'); // await Util.exec('iptables -A FORWARD -o wg0 -j ACCEPT');
await this.__syncConfig(); await this.__syncConfig();
} return config;
return this.__configPromise;
} }
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