Add proxy routing and sing-box support
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter_singbox_proxy/flutter_singbox_proxy.dart';
|
||||
import 'package:flutter_tor/flutter_tor.dart';
|
||||
|
||||
enum ProxyLogSource { singBox, tor }
|
||||
|
||||
class ProxyLogMessage with FastEquatable {
|
||||
final ProxyLogSource source;
|
||||
final String level;
|
||||
final String message;
|
||||
final int timestamp;
|
||||
final String? profileId;
|
||||
|
||||
ProxyLogMessage({
|
||||
required this.source,
|
||||
required this.level,
|
||||
required this.message,
|
||||
required this.timestamp,
|
||||
this.profileId,
|
||||
});
|
||||
|
||||
factory ProxyLogMessage.fromSingbox(SingboxProxyLogMessage message) {
|
||||
return ProxyLogMessage(
|
||||
source: ProxyLogSource.singBox,
|
||||
level: message.level,
|
||||
message: message.message,
|
||||
timestamp: message.timestamp,
|
||||
profileId: message.profileId,
|
||||
);
|
||||
}
|
||||
|
||||
factory ProxyLogMessage.fromTor(TorLogMessage message) {
|
||||
return ProxyLogMessage(
|
||||
source: ProxyLogSource.tor,
|
||||
level: _torSeverityToLevel(message.severity),
|
||||
message: message.message,
|
||||
timestamp: message.timestamp,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
source,
|
||||
level,
|
||||
message,
|
||||
timestamp,
|
||||
profileId,
|
||||
];
|
||||
}
|
||||
|
||||
String _torSeverityToLevel(String severity) {
|
||||
return switch (severity.toUpperCase()) {
|
||||
'ERR' => 'error',
|
||||
'WARN' => 'warn',
|
||||
'DEBUG' => 'debug',
|
||||
'INFO' || 'NOTICE' => 'info',
|
||||
_ => severity.toLowerCase(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter_singbox_proxy/flutter_singbox_proxy.dart';
|
||||
|
||||
/// Pre-filled state handed to the create-mode editor when the user reached it
|
||||
/// through a guided method (file import, clipboard, QR, etc.).
|
||||
///
|
||||
/// Carries structured [values] for [SingboxProxyFormSpec]-driven types.
|
||||
/// [dnsOverrideJson] is applied to the editor's DNS override section when
|
||||
/// present.
|
||||
class ProxyProfileSeed with FastEquatable {
|
||||
final SingboxProxyProfileType type;
|
||||
final String? name;
|
||||
final Map<String, String> values;
|
||||
final String? dnsOverrideJson;
|
||||
|
||||
ProxyProfileSeed({
|
||||
required this.type,
|
||||
this.name,
|
||||
this.values = const {},
|
||||
this.dnsOverrideJson,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [type, name, values, dnsOverrideJson];
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter_singbox_proxy/flutter_singbox_proxy.dart';
|
||||
|
||||
/// Custom share-link scheme for round-tripping a WebLibre proxy profile
|
||||
/// (including any secret config) between WebLibre installs. NOT cross-app
|
||||
/// compatible — for that use the standard ss://, vless://, etc. URIs imported
|
||||
/// from the editor (and exposed by future per-protocol exporters).
|
||||
const weblibreProxyShareScheme = 'weblibre-proxy';
|
||||
|
||||
class ProxyShareEnvelope with FastEquatable {
|
||||
/// Schema version — bumped if the wrapped JSON shape ever changes.
|
||||
/// v1: name + type + config + secret.
|
||||
/// v2: also carries dnsOverrideJson so per-profile DNS settings survive
|
||||
/// share/import. Older v1 payloads stay readable (treated as no
|
||||
/// override).
|
||||
static const int currentVersion = 2;
|
||||
|
||||
final String name;
|
||||
final SingboxProxyProfileType type;
|
||||
final String configJson;
|
||||
final String? secretJson;
|
||||
final String? dnsOverrideJson;
|
||||
|
||||
ProxyShareEnvelope({
|
||||
required this.name,
|
||||
required this.type,
|
||||
required this.configJson,
|
||||
this.secretJson,
|
||||
this.dnsOverrideJson,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
name,
|
||||
type,
|
||||
configJson,
|
||||
secretJson,
|
||||
dnsOverrideJson,
|
||||
];
|
||||
}
|
||||
|
||||
/// Encodes the profile as `weblibre-proxy://<base64url(JSON)>`. The JSON body
|
||||
/// is compact (no whitespace) to keep the URL short for QR rendering once
|
||||
/// added.
|
||||
String encodeProxyShareUri(ProxyShareEnvelope envelope) {
|
||||
final body = <String, Object?>{
|
||||
'v': ProxyShareEnvelope.currentVersion,
|
||||
'name': envelope.name,
|
||||
'type': envelope.type.name,
|
||||
'config': jsonDecode(envelope.configJson),
|
||||
if (envelope.secretJson != null && envelope.secretJson!.isNotEmpty)
|
||||
'secret': jsonDecode(envelope.secretJson!),
|
||||
if (envelope.dnsOverrideJson != null &&
|
||||
envelope.dnsOverrideJson!.isNotEmpty)
|
||||
'dnsOverride': jsonDecode(envelope.dnsOverrideJson!),
|
||||
};
|
||||
final encoded = base64UrlEncode(utf8.encode(jsonEncode(body)));
|
||||
return '$weblibreProxyShareScheme://$encoded';
|
||||
}
|
||||
|
||||
/// Decodes a `weblibre-proxy://...` share URI. Throws [FormatException] on
|
||||
/// malformed input or version mismatch.
|
||||
const _shareUriPrefix = '$weblibreProxyShareScheme://';
|
||||
|
||||
ProxyShareEnvelope decodeProxyShareUri(String rawUri) {
|
||||
final trimmed = rawUri.trim();
|
||||
if (!trimmed.startsWith(_shareUriPrefix)) {
|
||||
throw const FormatException(
|
||||
'Not a WebLibre proxy share URI (expected scheme $weblibreProxyShareScheme).',
|
||||
);
|
||||
}
|
||||
final payload = trimmed.substring(_shareUriPrefix.length);
|
||||
final List<int> bytes;
|
||||
try {
|
||||
bytes = base64Url.decode(base64Url.normalize(payload));
|
||||
} on FormatException {
|
||||
throw const FormatException('Share URI payload is not valid base64url.');
|
||||
}
|
||||
|
||||
final dynamic decoded;
|
||||
try {
|
||||
decoded = jsonDecode(utf8.decode(bytes));
|
||||
} on FormatException {
|
||||
throw const FormatException('Share URI payload is not valid JSON.');
|
||||
}
|
||||
if (decoded is! Map<String, Object?>) {
|
||||
throw const FormatException('Share URI payload must be a JSON object.');
|
||||
}
|
||||
|
||||
final version = decoded['v'];
|
||||
if (version is! int ||
|
||||
version < 1 ||
|
||||
version > ProxyShareEnvelope.currentVersion) {
|
||||
throw FormatException('Unsupported share URI version: $version.');
|
||||
}
|
||||
|
||||
final name = decoded['name'];
|
||||
final typeName = decoded['type'];
|
||||
final config = decoded['config'];
|
||||
final secret = decoded['secret'];
|
||||
final dnsOverride = decoded['dnsOverride'];
|
||||
|
||||
if (name is! String || typeName is! String || config == null) {
|
||||
throw const FormatException('Share URI is missing required fields.');
|
||||
}
|
||||
final type = SingboxProxyProfileType.values
|
||||
.where((value) => value.name == typeName)
|
||||
.firstOrNull;
|
||||
if (type == null) {
|
||||
throw FormatException('Unknown profile type: $typeName.');
|
||||
}
|
||||
|
||||
return ProxyShareEnvelope(
|
||||
name: name,
|
||||
type: type,
|
||||
configJson: jsonEncode(config),
|
||||
secretJson: secret == null ? null : jsonEncode(secret),
|
||||
dnsOverrideJson: dnsOverride == null ? null : jsonEncode(dnsOverride),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_singbox_proxy/flutter_singbox_proxy.dart';
|
||||
import 'package:weblibre/features/proxy/data/proxy_connection.dart';
|
||||
import 'package:weblibre/features/user/data/database/definitions.drift.dart'
|
||||
show ProxyProfile;
|
||||
|
||||
extension ProxyProfileExt on ProxyProfile {
|
||||
ProxyConnectionId get proxyConnection => SingboxProxyConnectionId(id);
|
||||
|
||||
String get proxyConnectionId => proxyConnection.encode();
|
||||
|
||||
SingboxProxyProfile toRuntimeProfile({String? secretJson}) {
|
||||
return SingboxProxyProfile(
|
||||
id: proxyConnectionId,
|
||||
name: name,
|
||||
type: type,
|
||||
configJson: configJson,
|
||||
secretJson: secretJson,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:weblibre/features/proxy/data/parsers/host_port.dart';
|
||||
|
||||
class WireguardConfigImport with FastEquatable {
|
||||
/// Values that seed the shared [SingboxProxyFormSpec]-driven WireGuard form.
|
||||
final Map<String, String> values;
|
||||
|
||||
/// Newline-separated DNS servers parsed from the WireGuard `[Interface] DNS`
|
||||
/// line. Not round-tripped through sing-box outbound JSON because DNS lives
|
||||
/// in the top-level `dns` block and is surfaced as a per-profile override.
|
||||
final String dns;
|
||||
|
||||
WireguardConfigImport({required this.values, this.dns = ''});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [values, dns];
|
||||
|
||||
factory WireguardConfigImport.fromConfigText(String configText) {
|
||||
final sections = _parseWireguardConfig(configText);
|
||||
final interface = sections['interface'];
|
||||
final peer = sections['peer'];
|
||||
if (interface == null || peer == null) {
|
||||
throw const FormatException(
|
||||
'WireGuard config must contain [Interface] and [Peer] sections.',
|
||||
);
|
||||
}
|
||||
|
||||
final rawEndpoint = (peer['endpoint'] ?? '').trim();
|
||||
final endpoint = rawEndpoint.isEmpty
|
||||
? (host: '', port: '')
|
||||
: parseHostPort(
|
||||
rawEndpoint,
|
||||
invalidMessage: 'WireGuard endpoint must be host:port.',
|
||||
);
|
||||
final mtu = interface['mtu']?.trim();
|
||||
|
||||
return WireguardConfigImport(
|
||||
values: {
|
||||
'server': endpoint.host,
|
||||
'server_port': endpoint.port,
|
||||
'local_address': _wireguardListValue(interface['address']),
|
||||
'private_key': interface['privatekey']?.trim() ?? '',
|
||||
'peer_public_key': peer['publickey']?.trim() ?? '',
|
||||
'pre_shared_key': peer['presharedkey']?.trim() ?? '',
|
||||
'mtu': mtu == null || mtu.isEmpty ? '1408' : mtu,
|
||||
},
|
||||
dns: _wireguardListValue(interface['dns']),
|
||||
);
|
||||
}
|
||||
|
||||
/// First parsed DNS entry as a sing-box-compatible address, or null when
|
||||
/// the imported config had no `DNS = …` line. Bare IPs become `udp://<ip>`
|
||||
/// (sing-box's plain-UDP scheme); anything already containing `://` is kept
|
||||
/// verbatim so users can paste `https://…/dns-query` etc.
|
||||
String? get primaryDnsAddress {
|
||||
final entries = _splitList(dns);
|
||||
if (entries.isEmpty) return null;
|
||||
final first = entries.first;
|
||||
if (first.contains('://')) return first;
|
||||
return 'udp://$first';
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _splitList(String value) {
|
||||
return value
|
||||
.replaceAll('[', '')
|
||||
.replaceAll(']', '')
|
||||
.split(RegExp(r'[\n,]'))
|
||||
.map((item) => item.trim())
|
||||
.where((item) => item.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
Map<String, Map<String, String>> _parseWireguardConfig(String configText) {
|
||||
final sections = <String, Map<String, String>>{};
|
||||
String? currentSection;
|
||||
|
||||
for (final rawLine in const LineSplitter().convert(configText)) {
|
||||
final line = _stripWireguardComment(rawLine).trim();
|
||||
if (line.isEmpty) continue;
|
||||
|
||||
if (line.startsWith('[') && line.endsWith(']')) {
|
||||
currentSection = line.substring(1, line.length - 1).trim().toLowerCase();
|
||||
if (currentSection.isEmpty) {
|
||||
throw const FormatException('WireGuard config contains empty section.');
|
||||
}
|
||||
sections.putIfAbsent(currentSection, () => <String, String>{});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentSection == null) {
|
||||
throw const FormatException(
|
||||
'WireGuard config entries must be inside a section.',
|
||||
);
|
||||
}
|
||||
|
||||
final separatorIndex = line.indexOf('=');
|
||||
if (separatorIndex < 1) {
|
||||
throw FormatException('Invalid WireGuard config line: $rawLine');
|
||||
}
|
||||
|
||||
final key = line.substring(0, separatorIndex).trim().toLowerCase();
|
||||
final value = line.substring(separatorIndex + 1).trim();
|
||||
if (key.isEmpty) {
|
||||
throw FormatException('Invalid WireGuard config line: $rawLine');
|
||||
}
|
||||
sections[currentSection]![key] = value;
|
||||
}
|
||||
|
||||
return sections;
|
||||
}
|
||||
|
||||
String _stripWireguardComment(String line) {
|
||||
final hashIndex = line.indexOf('#');
|
||||
final semicolonIndex = line.indexOf(';');
|
||||
final indexes = [
|
||||
if (hashIndex >= 0) hashIndex,
|
||||
if (semicolonIndex >= 0) semicolonIndex,
|
||||
];
|
||||
if (indexes.isEmpty) return line;
|
||||
indexes.sort();
|
||||
return line.substring(0, indexes.first);
|
||||
}
|
||||
|
||||
String _wireguardListValue(String? value) {
|
||||
if (value == null) return '';
|
||||
return value
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.where((item) => item.isNotEmpty)
|
||||
.join('\n');
|
||||
}
|
||||
Reference in New Issue
Block a user