Add peer management routes and server configuration services
This commit is contained in:
30
lib/services/server_service.dart
Normal file
30
lib/services/server_service.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'dart:io';
|
||||
import 'package:waylume_server/config/supabase_config.dart';
|
||||
import 'package:waylume_server/core/utils.dart';
|
||||
|
||||
class ServerService {
|
||||
static Future<void> registerServer() async {
|
||||
String ip = await getWanIp();
|
||||
|
||||
var existsCheck = await SUPABASE_CLIENT
|
||||
.from("waylume_servers")
|
||||
.select()
|
||||
.eq("id", fromEnivronment('SERVER_ID'))
|
||||
.eq("host_ip", ip);
|
||||
|
||||
if (existsCheck.isEmpty) {
|
||||
await SUPABASE_CLIENT
|
||||
.from("waylume_servers")
|
||||
.insert({
|
||||
"id": fromEnivronment('SERVER_ID')!,
|
||||
"last_heartbeat": DateTime.now().toUtc().toIso8601String(),
|
||||
"host_ip": ip,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> isolatePeers() async {
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-j', 'DROP']);
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-m', 'state', '--state', 'ESTABLISHED,RELATED', '-j', 'ACCEPT']);
|
||||
}
|
||||
}
|
||||
35
lib/services/supabase_heartbeat.dart
Normal file
35
lib/services/supabase_heartbeat.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
|
||||
// Run a heartbeat to let supabase know that the client is still active.
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:supabase/supabase.dart';
|
||||
import 'package:waylume_server/config/supabase_config.dart';
|
||||
|
||||
void initHeartbeat() {
|
||||
|
||||
// Run this on a separate thread.
|
||||
Isolate.spawn((_) async {
|
||||
|
||||
// To avoid server deadlock
|
||||
await Future.delayed(Duration(seconds: Random().nextInt(5)));
|
||||
|
||||
while (true) {
|
||||
DateTime now = DateTime.now().toUtc();
|
||||
|
||||
await SUPABASE_CLIENT
|
||||
.from("waylume_servers")
|
||||
.update({ "last_heartbeat": now.toIso8601String() })
|
||||
.eq("id", fromEnivronment("SERVER_ID")!);
|
||||
|
||||
print("Heartbeat sent to Supabase at ${now.toIso8601String()}");
|
||||
|
||||
// Wait 30 seconds before sending the next heartbeat
|
||||
await Future.delayed(Duration(seconds: 30));
|
||||
}
|
||||
|
||||
}, null);
|
||||
|
||||
}
|
||||
119
lib/services/wireguard_service.dart
Normal file
119
lib/services/wireguard_service.dart
Normal file
@@ -0,0 +1,119 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
class WireGuardService {
|
||||
static const String interfaceName = 'wg0';
|
||||
static const String configPath = '/etc/wireguard/wg0.conf';
|
||||
static const String serverIP = '10.0.0.1/24';
|
||||
static const int serverPort = 51820;
|
||||
|
||||
static Future<void> initializeServer() async {
|
||||
try {
|
||||
// Check if wg0 interface already exists
|
||||
if (await _interfaceExists()) {
|
||||
print('WireGuard interface $interfaceName already exists.');
|
||||
return;
|
||||
}
|
||||
|
||||
print('Initializing WireGuard server interface...');
|
||||
|
||||
// Generate server keys if they don't exist
|
||||
final serverKeys = await _getOrCreateServerKeys();
|
||||
|
||||
// Create server config
|
||||
await _createServerConfig(serverKeys['privateKey']!);
|
||||
|
||||
// Bring up the interface
|
||||
await _bringUpInterface();
|
||||
|
||||
print('WireGuard server interface $interfaceName initialized successfully.');
|
||||
} catch (e) {
|
||||
throw Exception('Failed to initialize WireGuard server: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> _interfaceExists() async {
|
||||
try {
|
||||
final result = await Process.run('wg', ['show', interfaceName]);
|
||||
return result.exitCode == 0;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<Map<String, String>> _getOrCreateServerKeys() async {
|
||||
try {
|
||||
// Try to get existing keys from running interface
|
||||
final pubResult = await Process.run('wg', ['show', interfaceName, 'public-key']);
|
||||
final privResult = await Process.run('wg', ['show', interfaceName, 'private-key']);
|
||||
|
||||
if (pubResult.exitCode == 0 && privResult.exitCode == 0) {
|
||||
return {
|
||||
'publicKey': pubResult.stdout.toString().trim(),
|
||||
'privateKey': privResult.stdout.toString().trim(),
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
// Keys don't exist, generate new ones
|
||||
}
|
||||
|
||||
// Generate new keys
|
||||
final privateKeyResult = await Process.run('wg', ['genkey']);
|
||||
if (privateKeyResult.exitCode != 0) {
|
||||
throw Exception('Failed to generate private key');
|
||||
}
|
||||
|
||||
final privateKey = privateKeyResult.stdout.toString().trim();
|
||||
|
||||
// Generate public key from private key
|
||||
final pubProcess = await Process.start('wg', ['pubkey']);
|
||||
pubProcess.stdin.writeln(privateKey);
|
||||
await pubProcess.stdin.close();
|
||||
final publicKey = await pubProcess.stdout.transform(utf8.decoder).join();
|
||||
|
||||
return {
|
||||
'privateKey': privateKey,
|
||||
'publicKey': publicKey.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> _createServerConfig(String privateKey) async {
|
||||
final config = '''
|
||||
[Interface]
|
||||
PrivateKey = $privateKey
|
||||
Address = $serverIP
|
||||
ListenPort = $serverPort
|
||||
PostUp = iptables -A FORWARD -i $interfaceName -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
|
||||
PostDown = iptables -D FORWARD -i $interfaceName -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
|
||||
''';
|
||||
|
||||
// Ensure config directory exists
|
||||
final configDir = Directory('/etc/wireguard');
|
||||
if (!await configDir.exists()) {
|
||||
await configDir.create(recursive: true);
|
||||
}
|
||||
|
||||
// Write config file
|
||||
final configFile = File(configPath);
|
||||
await configFile.writeAsString(config);
|
||||
|
||||
// Set proper permissions (600)
|
||||
await Process.run('chmod', ['600', configPath]);
|
||||
}
|
||||
|
||||
static Future<void> _bringUpInterface() async {
|
||||
// Start WireGuard interface
|
||||
final result = await Process.run('wg-quick', ['up', interfaceName]);
|
||||
if (result.exitCode != 0) {
|
||||
throw Exception('Failed to bring up WireGuard interface: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> stopInterface() async {
|
||||
try {
|
||||
await Process.run('wg-quick', ['down', interfaceName]);
|
||||
} catch (e) {
|
||||
// Interface might not be running, ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user