Initial commit
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
90
lib/main.dart
Normal file
90
lib/main.dart
Normal file
@@ -0,0 +1,90 @@
|
||||
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dotenv/dotenv.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:shelf/shelf_io.dart';
|
||||
import 'package:shelf_router/shelf_router.dart';
|
||||
import 'package:supabase/supabase.dart';
|
||||
import 'package:waylume_server/supabase_heartbeat.dart';
|
||||
import 'package:waylume_server/utils.dart';
|
||||
|
||||
var env = DotEnv()..load();
|
||||
|
||||
dynamic fromEnivronment(String key) {
|
||||
if (kIsRunningInDocker) {
|
||||
return Platform.environment[key];
|
||||
} else {
|
||||
return env[key];
|
||||
}
|
||||
}
|
||||
|
||||
final SupabaseClient SUPABASE_CLIENT = SupabaseClient(
|
||||
"https://lsdrctuvnwdrzrdyoqzu.supabase.co",
|
||||
fromEnivronment('SUPABASE_KEY')!
|
||||
);
|
||||
|
||||
|
||||
|
||||
void main() async {
|
||||
|
||||
if (kIsRunningInDocker) {
|
||||
print('Running in Docker environment.');
|
||||
} else {
|
||||
print('Not running in Docker environment.');
|
||||
}
|
||||
|
||||
String ip = await getWanIp();
|
||||
|
||||
// Check if SERVER_ID already exists in the database
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
// Verify that WireGuard is installed
|
||||
if (!await isWireguardInstalled()) {
|
||||
print('WireGuard is not installed. Please install WireGuard to run this server.');
|
||||
exit(1);
|
||||
} else {
|
||||
print('WireGuard is installed.');
|
||||
}
|
||||
|
||||
// Start the heartbeat to keep the server alive
|
||||
initHeartbeat();
|
||||
|
||||
// Isolate peers to block traffic between them
|
||||
if (!Platform.isMacOS) {
|
||||
await isolatePeers();
|
||||
}
|
||||
|
||||
Router app = Router();
|
||||
|
||||
app.get('/', (request) {
|
||||
return Response.ok('Welcome to Waylume Server!');
|
||||
});
|
||||
|
||||
var server = await serve(app, '0.0.0.0', 3000);
|
||||
print('Server running on http://${server.address.host}:${server.port}');
|
||||
}
|
||||
|
||||
Future<void> isolatePeers() async {
|
||||
// Block traffic between peers (peer-to-peer isolation)
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-j', 'DROP']);
|
||||
|
||||
// Allow established/related connections (for return traffic)
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-m', 'state', '--state', 'ESTABLISHED,RELATED', '-j', 'ACCEPT']);
|
||||
}
|
||||
35
lib/supabase_heartbeat.dart
Normal file
35
lib/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/main.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);
|
||||
|
||||
}
|
||||
29
lib/utils.dart
Normal file
29
lib/utils.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Get the current WAN IP address of the device.
|
||||
Future<String> getWanIp() async {
|
||||
// Get the IP address of the server. https://api.ipify.org?format=json
|
||||
var ipResponse = await http.get(Uri.parse('https://api.ipify.org?format=json'));
|
||||
if (ipResponse.statusCode == 200) {
|
||||
var ipData = jsonDecode(ipResponse.body);
|
||||
return ipData['ip'] as String;
|
||||
} else {
|
||||
throw Exception('Failed to get server IP address');
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if Wireguard is installed on the system.
|
||||
Future<bool> isWireguardInstalled() async {
|
||||
try {
|
||||
var result = await Process.run('wg', ['--version']);
|
||||
return result.exitCode == 0;
|
||||
} catch (e) {
|
||||
print('Error checking WireGuard installation: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool get kIsRunningInDocker => File('/.dockerenv').existsSync();
|
||||
176
lib/wireguard/peers.dart
Normal file
176
lib/wireguard/peers.dart
Normal file
@@ -0,0 +1,176 @@
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:waylume_server/utils.dart';
|
||||
import 'package:waylume_server/wireguard/utils.dart';
|
||||
|
||||
class WireGuardPeer {
|
||||
final String privateKey;
|
||||
final String publicKey;
|
||||
final String ip;
|
||||
|
||||
WireGuardPeer({
|
||||
required this.privateKey,
|
||||
required this.publicKey,
|
||||
required this.ip,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'privateKey': privateKey,
|
||||
'publicKey': publicKey,
|
||||
'ip': ip,
|
||||
};
|
||||
|
||||
factory WireGuardPeer.fromJson(Map<String, dynamic> json) => WireGuardPeer(
|
||||
privateKey: json['privateKey'],
|
||||
publicKey: json['publicKey'],
|
||||
ip: json['ip'],
|
||||
);
|
||||
|
||||
String generateClientConfig({
|
||||
required String serverPublicKey,
|
||||
required String serverEndpoint,
|
||||
String dns = '1.1.1.1, 8.8.8.8', // Cloudflare and Google DNS
|
||||
String allowedIPs = '0.0.0.0/0',
|
||||
}) {
|
||||
return '''
|
||||
[Interface]
|
||||
PrivateKey = $privateKey
|
||||
Address = $ip/32
|
||||
DNS = $dns
|
||||
|
||||
[Peer]
|
||||
PublicKey = $serverPublicKey
|
||||
Endpoint = $serverEndpoint
|
||||
AllowedIPs = $allowedIPs
|
||||
PersistentKeepalive = 25
|
||||
''';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> generateClientConfig(WireGuardPeer peer) async {
|
||||
|
||||
String server_endpoint = '${await getWanIp()}:51820'; // Assuming default WireGuard port
|
||||
String serverPublicKey = await getServerPublicKey();
|
||||
|
||||
return peer.generateClientConfig(
|
||||
serverPublicKey: serverPublicKey,
|
||||
serverEndpoint: server_endpoint,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/// Creates a new WireGuard peer and returns the peer info
|
||||
Future<WireGuardPeer> createPeer() async {
|
||||
// Generate private key
|
||||
final privateKeyResult = await Process.run('wg', ['genkey']);
|
||||
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();
|
||||
|
||||
// Get next available IP
|
||||
final ip = await _getNextIP();
|
||||
|
||||
// Add peer to WireGuard
|
||||
await Process.run('wg', ['set', 'wg0', 'peer', publicKey.trim(), 'allowed-ips', '$ip/32']);
|
||||
|
||||
return WireGuardPeer(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey.trim(),
|
||||
ip: ip,
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> deletePeer(String publicKey) async {
|
||||
// Remove peer from WireGuard
|
||||
final result = await Process.run('wg', ['set', 'wg0', 'peer', publicKey, 'remove']);
|
||||
if (result.exitCode != 0) {
|
||||
print('Error removing peer: ${result.stderr}');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> setSpeedLimit(String publicKey, int speedKbps) async {
|
||||
final peerIP = await _getPeerIP(publicKey);
|
||||
if (peerIP == null) throw Exception('Peer not found');
|
||||
|
||||
final mark = _getMarkForIP(peerIP);
|
||||
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-s', peerIP, '-j', 'MARK', '--set-mark', mark.toString()]);
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-d', peerIP, '-j', 'MARK', '--set-mark', mark.toString()]);
|
||||
await Process.run('tc', ['class', 'add', 'dev', 'wg0', 'parent', '1:1', 'classid', '1:$mark', 'htb', 'rate', '${speedKbps}kbit', 'ceil', '${speedKbps}kbit']);
|
||||
await Process.run('tc', ['filter', 'add', 'dev', 'wg0', 'protocol', 'ip', 'parent', '1:', 'prio', '1', 'handle', mark.toString(), 'fw', 'flowid', '1:$mark']);
|
||||
}
|
||||
|
||||
Future<void> setDataCap(String publicKey, int dataCapMB) async {
|
||||
final peerIP = await _getPeerIP(publicKey);
|
||||
if (peerIP == null) throw Exception('Peer not found');
|
||||
|
||||
final quotaBytes = dataCapMB * 1024 * 1024;
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-s', peerIP, '-m', 'quota', '--quota', quotaBytes.toString(), '-j', 'ACCEPT']);
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-d', peerIP, '-m', 'quota', '--quota', quotaBytes.toString(), '-j', 'ACCEPT']);
|
||||
await Process.run('iptables', ['-A', 'FORWARD', '-s', peerIP, '-j', 'DROP']);
|
||||
await Process.run('iptables', ['-A', 'FORWARD', '-d', peerIP, '-j', 'DROP']);
|
||||
}
|
||||
|
||||
Future<String?> _getPeerIP(String publicKey) async {
|
||||
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
|
||||
if (result.exitCode != 0) return null;
|
||||
|
||||
final lines = result.stdout.toString().split('\n');
|
||||
for (final line in lines) {
|
||||
if (line.contains(publicKey)) {
|
||||
final match = RegExp(r'(\d+\.\d+\.\d+\.\d+)').firstMatch(line);
|
||||
return match?.group(1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
int _getMarkForIP(String ip) {
|
||||
return ip.split('.').last.hashCode % 65535 + 1;
|
||||
}
|
||||
|
||||
Future<String> _getNextIP() async {
|
||||
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
|
||||
final usedIPs = RegExp(r'10\.(\d+)\.(\d+)\.(\d+)')
|
||||
.allMatches(result.stdout.toString())
|
||||
.map((m) => '${m.group(1)}.${m.group(2)}.${m.group(3)}')
|
||||
.toSet();
|
||||
|
||||
// Start from 10.0.0.2 (skip .1 for server)
|
||||
for (int a = 0; a <= 255; a++) {
|
||||
for (int b = 0; b <= 255; b++) {
|
||||
for (int c = (a == 0 && b == 0 ? 2 : 1); c <= 254; c++) {
|
||||
final ip = '10.$a.$b.$c';
|
||||
if (!usedIPs.contains('$a.$b.$c')) return ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw Exception('No available IPs');
|
||||
}
|
||||
|
||||
void main() async {
|
||||
try {
|
||||
final peer = await createPeer();
|
||||
print('New WireGuard Peer Created:');
|
||||
print('Private Key: ${peer.privateKey}');
|
||||
print('Public Key: ${peer.publicKey}');
|
||||
print('IP Address: ${peer.ip}');
|
||||
|
||||
// Example usage of generating client config
|
||||
final clientConfig = peer.generateClientConfig(
|
||||
serverPublicKey: 'your_server_public_key',
|
||||
serverEndpoint: 'your_server_endpoint:51820',
|
||||
);
|
||||
print('Client Config:\n$clientConfig');
|
||||
} catch (e) {
|
||||
print('Error creating WireGuard peer: $e');
|
||||
}
|
||||
}
|
||||
10
lib/wireguard/utils.dart
Normal file
10
lib/wireguard/utils.dart
Normal file
@@ -0,0 +1,10 @@
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
Future<String> getServerPublicKey() async {
|
||||
final result = await Process.run('wg', ['show', 'wg0', 'public-key']);
|
||||
if (result.exitCode != 0) {
|
||||
throw Exception('Failed to get server public key: ${result.stderr}');
|
||||
}
|
||||
return result.stdout.toString().trim();
|
||||
}
|
||||
Reference in New Issue
Block a user