Browse Source

improve debug, fix custom migration

pull/1619/head
Bernd Storath 3 months ago
parent
commit
65d8e7839e
  1. 2
      Dockerfile.dev
  2. 6
      src/server/database/migrations/0001_next_george_stacy.sql
  3. 9
      src/server/database/sqlite.ts
  4. 29
      src/server/utils/WireGuard.ts
  5. 7
      src/server/utils/cmd.ts

2
Dockerfile.dev

@ -23,7 +23,7 @@ RUN update-alternatives --install /usr/sbin/iptables iptables /usr/sbin/iptables
RUN update-alternatives --install /usr/sbin/ip6tables ip6tables /usr/sbin/ip6tables-legacy 10 --slave /usr/sbin/ip6tables-restore ip6tables-restore /usr/sbin/ip6tables-legacy-restore --slave /usr/sbin/ip6tables-save ip6tables-save /usr/sbin/ip6tables-legacy-save
# Set Environment
ENV DEBUG=Server,WireGuard,LowDB
ENV DEBUG=Server,WireGuard,Database,CMD
ENV PORT=51821
ENV HOST=0.0.0.0

6
src/server/database/migrations/0001_next_george_stacy.sql

@ -1,10 +1,10 @@
-- Insert default values --
PRAGMA journal_mode=WAL;--> statement-breakpoint
INSERT INTO `general_table` (`setupStep`, `session_password`, `session_timeout`)
VALUES (1, hex(randomblob(256)), 3600);
--> statement-breakpoint
INSERT INTO `interfaces_table` (`name`, `device`, `port`, `private_key`, `public_key`, `ipv4_cidr`, `ipv6_cidr`, `mtu`, `enabled`)
VALUES ('wg0', 'eth0', 51820, '---default---', '---default---', '10.8.0.0/24', 'fdcc:ad94:bacf:61a4::cafe:0/112', 1420, 1);
--> statement-breakpoint
INSERT INTO `hooks_table` (`id`, `pre_up`, `post_up`, `pre_down`, `post_down`)
VALUES (
'wg0',

9
src/server/database/sqlite.ts

@ -1,6 +1,7 @@
import { drizzle } from 'drizzle-orm/libsql';
import { migrate as drizzleMigrate } from 'drizzle-orm/libsql/migrator';
import { createClient } from '@libsql/client';
import debug from 'debug';
import * as schema from './schema';
import { ClientService } from './repositories/client/service';
@ -11,6 +12,8 @@ import { InterfaceService } from './repositories/interface/service';
import { HooksService } from './repositories/hooks/service';
import { OneTimeLinkService } from './repositories/oneTimeLink/service';
const DB_DEBUG = debug('Database');
const client = createClient({ url: 'file:/etc/wireguard/wg0.db' });
const db = drizzle({ client, schema });
@ -43,14 +46,14 @@ export type DBServiceType = DBService;
async function migrate() {
try {
console.log('Migrating database...');
DB_DEBUG('Migrating database...');
await drizzleMigrate(db, {
migrationsFolder: './server/database/migrations',
});
console.log('Migration complete');
DB_DEBUG('Migration complete');
} catch (e) {
if (e instanceof Error) {
console.log('Failed to migrate database:', e.message);
DB_DEBUG('Failed to migrate database:', e.message);
}
}
}

29
src/server/utils/WireGuard.ts

@ -3,7 +3,7 @@ import debug from 'debug';
import QRCode from 'qrcode';
import type { ID } from '#db/schema';
const DEBUG = debug('WireGuard');
const WG_DEBUG = debug('WireGuard');
class WireGuard {
/**
@ -36,17 +36,17 @@ class WireGuard {
result.push(wg.generateServerPeer(client));
}
DEBUG('Saving Config...');
WG_DEBUG('Saving Config...');
await fs.writeFile(`/etc/wireguard/${infName}.conf`, result.join('\n\n'), {
mode: 0o600,
});
DEBUG('Config saved successfully.');
WG_DEBUG('Config saved successfully.');
}
async #syncWireguardConfig(infName: string) {
DEBUG('Syncing Config...');
WG_DEBUG('Syncing Config...');
await wg.sync(infName);
DEBUG('Config synced successfully.');
WG_DEBUG('Config synced successfully.');
}
async getClients() {
@ -123,6 +123,7 @@ class WireGuard {
}
async Startup() {
WG_DEBUG('Starting WireGuard...');
const wgInterfaces = await Database.interfaces.getAll();
for (const wgInterface of wgInterfaces) {
if (wgInterface.enabled !== true) {
@ -133,7 +134,7 @@ class WireGuard {
wgInterface.privateKey === '---default---' &&
wgInterface.publicKey === '---default---'
) {
DEBUG('Generating new Wireguard Keys...');
WG_DEBUG('Generating new Wireguard Keys...');
const privateKey = await wg.generatePrivateKey();
const publicKey = await wg.getPublicKey(privateKey);
@ -142,9 +143,9 @@ class WireGuard {
privateKey,
publicKey
);
DEBUG('New Wireguard Keys generated successfully.');
WG_DEBUG('New Wireguard Keys generated successfully.');
}
DEBUG(`Starting Wireguard Interface ${wgInterface.name}...`);
WG_DEBUG(`Starting Wireguard Interface ${wgInterface.name}...`);
await this.#saveWireguardConfig(wgInterface.name);
await wg.down(wgInterface.name).catch(() => {});
await wg.up(wgInterface.name).catch((err) => {
@ -162,18 +163,18 @@ class WireGuard {
throw err;
});
await this.#syncWireguardConfig(wgInterface.name);
DEBUG(`Wireguard Interface ${wgInterface.name} started successfully.`);
WG_DEBUG(`Wireguard Interface ${wgInterface.name} started successfully.`);
}
DEBUG('Starting Cron Job.');
WG_DEBUG('Starting Cron Job...');
await this.startCronJob();
DEBUG('Cron Job started successfully.');
WG_DEBUG('Cron Job started successfully.');
}
// TODO: handle as worker_thread
async startCronJob() {
await this.cronJob().catch((err) => {
DEBUG('Running Cron Job failed.');
WG_DEBUG('Running Cron Job failed.');
console.error(err);
});
setTimeout(() => {
@ -198,7 +199,7 @@ class WireGuard {
client.expiresAt !== null &&
new Date() > new Date(client.expiresAt)
) {
DEBUG(`Client ${client.id} expired.`);
WG_DEBUG(`Client ${client.id} expired.`);
await Database.clients.toggle(client.id, false);
}
}
@ -209,7 +210,7 @@ class WireGuard {
client.oneTimeLink !== null &&
new Date() > new Date(client.oneTimeLink.expiresAt)
) {
DEBUG(`Client ${client.id} One Time Link expired.`);
WG_DEBUG(`Client ${client.id} One Time Link expired.`);
await Database.oneTimeLinks.delete(client.id);
}
}

7
src/server/utils/cmd.ts

@ -1,15 +1,16 @@
import childProcess from 'child_process';
import debug from 'debug';
import {} from '~/';
const CMD_DEBUG = debug('CMD');
export function exec(
cmd: string,
{ log }: { log: boolean | string } = { log: true }
) {
if (typeof log === 'string') {
console.log(`$ ${log}`);
CMD_DEBUG(`$ ${log}`);
} else if (log === true) {
console.log(`$ ${cmd}`);
CMD_DEBUG(`$ ${cmd}`);
}
if (process.platform !== 'linux') {

Loading…
Cancel
Save