Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages, responsive layout, and related tests - Add meshport-socks crate and sing-box bridge scripts/docs - Add singbox_flutter binding and meshport_client_core package - FFI, VPN helper (unified mac path), and Android/macOS runner updates - Docs for architecture, client runtime, UI design, and validation - UI design output artifacts under outputs/ui Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 5.5
parent
10b10e5bdf
commit
2f185f914d
@@ -0,0 +1,6 @@
|
||||
/// Shared client runtime; independent apps may continue using meshport_flutter alone.
|
||||
library;
|
||||
|
||||
export 'src/mesh_proxy_session.dart';
|
||||
export 'src/proxy_profile.dart';
|
||||
export 'src/network_profile.dart';
|
||||
@@ -0,0 +1,214 @@
|
||||
import 'package:meshport_flutter/meshport_flutter.dart';
|
||||
import 'package:singbox_flutter/singbox_flutter.dart';
|
||||
|
||||
/// Owns one application-mode network and its bridge/engine. Do not control the
|
||||
/// same MeshPort context separately while this session owns it.
|
||||
class MeshProxySession {
|
||||
final MeshPortClient mesh;
|
||||
final ProxyEngine proxy;
|
||||
final int port;
|
||||
final Map<String, dynamic> profile;
|
||||
final Set<String> _protected = {};
|
||||
bool _active = false;
|
||||
bool get usesMesh => profile['feature'] != 'proxy';
|
||||
String _state = 'Stopped';
|
||||
String get state => _state;
|
||||
String? endpoint;
|
||||
String? _bridge;
|
||||
List<String> _prefixes = [];
|
||||
bool _ownsNetwork = false, _closed = false;
|
||||
Future<void> _tail = Future.value();
|
||||
MeshProxySession({
|
||||
required this.mesh,
|
||||
required this.proxy,
|
||||
this.port = 10818,
|
||||
this.profile = const {},
|
||||
});
|
||||
|
||||
Future<T> _queue<T>(Future<T> Function() work) {
|
||||
if (_closed) return Future.error(StateError('Session is closed'));
|
||||
final result = _tail.then((_) => work());
|
||||
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace __) {});
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> start(String toml) => _queue(() async {
|
||||
if (_active || _ownsNetwork) throw StateError('Session already started');
|
||||
if (port < 1 || port > 65535) throw ArgumentError('Invalid proxy port');
|
||||
if (!usesMesh) {
|
||||
_active = true;
|
||||
_state = 'Starting';
|
||||
try {
|
||||
await _sync({});
|
||||
} catch (_) {
|
||||
await _fail();
|
||||
rethrow;
|
||||
}
|
||||
return;
|
||||
}
|
||||
final validated = await mesh.request({'op': 'validate', 'toml': toml});
|
||||
if (validated['runtime_mode'] != 'application')
|
||||
throw UnsupportedError('Unified system VPN is not implemented yet');
|
||||
if ((await mesh.status())['state'] != 'Stopped')
|
||||
throw StateError('MeshPort context must be stopped');
|
||||
_state = 'Starting';
|
||||
try {
|
||||
// Claim ownership before start so partial native startup is cleaned up.
|
||||
_ownsNetwork = true;
|
||||
_active = true;
|
||||
await mesh.start(toml);
|
||||
_bridge = (await mesh.startSocksBridge())['listen'] as String;
|
||||
await _sync(await mesh.status());
|
||||
} catch (_) {
|
||||
await _fail();
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
|
||||
/// Called by the host's status poll. Rebuild only on effective prefix changes.
|
||||
/// Existing engine sessions close on rebuild; withdrawn routes also fail at SDK.
|
||||
Future<Map<String, dynamic>> refresh() => _queue(() async {
|
||||
try {
|
||||
final snapshot = await mesh.status();
|
||||
bool meshAvailable = true;
|
||||
if (_ownsNetwork) {
|
||||
if (profile['feature'] == 'combined') {
|
||||
meshAvailable =
|
||||
snapshot['state'] == 'Running' &&
|
||||
(await mesh.socksBridgeStatus())['running'] == true;
|
||||
} else if (snapshot['state'] != 'Running')
|
||||
throw StateError('Mesh network stopped unexpectedly');
|
||||
if (profile['feature'] != 'combined' &&
|
||||
(await mesh.socksBridgeStatus())['running'] != true)
|
||||
throw StateError('Mesh bridge stopped unexpectedly');
|
||||
}
|
||||
if (_active) {
|
||||
await _sync(meshAvailable ? snapshot : <String, dynamic>{});
|
||||
}
|
||||
return snapshot;
|
||||
} catch (_) {
|
||||
if (_active || _ownsNetwork) await _fail();
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
Future<void> _sync(Map<String, dynamic> snapshot) async {
|
||||
final prefixes = usesMesh ? effectiveMeshPrefixes(snapshot) : <String>[];
|
||||
_protected.addAll(prefixes);
|
||||
if (prefixes.join(',') == _prefixes.join(',') &&
|
||||
(state == 'Running' || state == 'Partial')) {
|
||||
if ((await proxy.status())['state'] != 'Running')
|
||||
throw StateError('Proxy engine stopped unexpectedly');
|
||||
return;
|
||||
}
|
||||
endpoint = null;
|
||||
_state = 'Updating';
|
||||
await proxy.stop();
|
||||
_prefixes = [];
|
||||
if (usesMesh && prefixes.isEmpty && _protected.isEmpty) {
|
||||
_state = 'AwaitingAddress';
|
||||
return;
|
||||
}
|
||||
await proxy.start(
|
||||
port: port,
|
||||
meshSocks: _bridge ?? '127.0.0.1:1',
|
||||
prefixes: prefixes,
|
||||
profile: {...profile, 'protected_cidrs': _protected.toList()..sort()},
|
||||
);
|
||||
_prefixes = prefixes;
|
||||
endpoint = '127.0.0.1:$port';
|
||||
_state = usesMesh && prefixes.isEmpty && profile['feature'] == 'combined'
|
||||
? 'Partial'
|
||||
: 'Running';
|
||||
}
|
||||
|
||||
Future<void> _fail() async {
|
||||
try {
|
||||
await _stop();
|
||||
} finally {
|
||||
_state = 'Failed';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() => _queue(_stop);
|
||||
Future<void> _stop() async {
|
||||
_state = 'Stopping';
|
||||
endpoint = null;
|
||||
Object? failure;
|
||||
try {
|
||||
await proxy.stop();
|
||||
} catch (e) {
|
||||
failure = e;
|
||||
}
|
||||
if (_ownsNetwork) {
|
||||
try {
|
||||
await mesh.stopSocksBridge();
|
||||
} catch (e) {
|
||||
failure ??= e;
|
||||
}
|
||||
try {
|
||||
await mesh.stop();
|
||||
_ownsNetwork = false;
|
||||
} catch (e) {
|
||||
failure ??= e;
|
||||
}
|
||||
}
|
||||
_active = false;
|
||||
_protected.clear();
|
||||
_bridge = null;
|
||||
_prefixes = [];
|
||||
_state = failure == null ? 'Stopped' : 'Failed';
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
|
||||
/// Closes the engine; the caller retains ownership of the MeshPort context.
|
||||
Future<void> close() {
|
||||
if (_closed) return _tail;
|
||||
final result = _queue(() async {
|
||||
try {
|
||||
await _stop();
|
||||
} finally {
|
||||
await proxy.close();
|
||||
}
|
||||
});
|
||||
_closed = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// Only accepted SDK projections and the current virtual subnet enter routing.
|
||||
/// Canonicalization prevents needless restarts caused by ordering/host-bit changes.
|
||||
List<String> effectiveMeshPrefixes(Map<String, dynamic> snapshot) {
|
||||
final platform = snapshot['platform_network'] as Map?;
|
||||
final values = <dynamic>[
|
||||
snapshot['ipv4'],
|
||||
if (platform?['subnet_routes_scope'] == 'accepted_projection')
|
||||
...?platform?['subnet_routes'] as List?,
|
||||
];
|
||||
final result = <String>{};
|
||||
for (final value in values) {
|
||||
if (value == null || value == '') continue;
|
||||
if (value is! String) throw StateError('Invalid mesh prefix projection');
|
||||
final parts = value.split('/');
|
||||
final octets = parts.first.split('.').map(int.tryParse).toList();
|
||||
final bits = parts.length == 2 ? int.tryParse(parts[1]) : null;
|
||||
if (bits == null ||
|
||||
bits < 16 ||
|
||||
bits > 32 ||
|
||||
octets.length != 4 ||
|
||||
octets.any((v) => v == null || v < 0 || v > 255))
|
||||
throw StateError('Unsupported mesh prefix projection');
|
||||
final ip = octets.cast<int>();
|
||||
final private =
|
||||
ip[0] == 10 ||
|
||||
(ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31) ||
|
||||
(ip[0] == 192 && ip[1] == 168);
|
||||
if (!private) throw StateError('Mesh prefix must be private IPv4');
|
||||
final address = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3];
|
||||
final network = address & (0xffffffff << (32 - bits));
|
||||
result.add(
|
||||
'${(network >> 24) & 255}.${(network >> 16) & 255}.${(network >> 8) & 255}.${network & 255}/$bits',
|
||||
);
|
||||
}
|
||||
if (result.length > 128) throw StateError('Too many mesh prefixes');
|
||||
return result.toList()..sort();
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Client draft only; the Rust SDK remains the authority for native validation.
|
||||
class NetworkProfile {
|
||||
final Map<String, dynamic> values;
|
||||
NetworkProfile(Map<String, dynamic> input)
|
||||
: values = jsonDecode(jsonEncode(input)) as Map<String, dynamic> {
|
||||
final flags = values['flags'] as Map<String, dynamic>?;
|
||||
if (flags != null) {
|
||||
for (final key in [
|
||||
'foreign_relay_bps_limit',
|
||||
'instance_recv_bps_limit',
|
||||
]) {
|
||||
if (flags[key] != null) flags[key] = unsignedLimit(flags[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String unsignedLimit(dynamic value) {
|
||||
final max = BigInt.parse('18446744073709551615');
|
||||
// Older native profiles encoded the unlimited sentinel as a JSON number.
|
||||
// Dart rounded it to this double; recover only that known sentinel.
|
||||
if (value is double) {
|
||||
if (value == max.toDouble()) return max.toString();
|
||||
if (!value.isFinite ||
|
||||
value < 0 ||
|
||||
value > 9007199254740991 ||
|
||||
value != value.truncateToDouble()) {
|
||||
throw const FormatException('速率限制数值精度已丢失,请重新填写整数');
|
||||
}
|
||||
value = value.toInt();
|
||||
}
|
||||
final result = BigInt.tryParse('$value');
|
||||
if (result == null || result < BigInt.zero || result > max) {
|
||||
throw const FormatException('速率限制需为 0 到 18446744073709551615 的整数');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
String toToml() {
|
||||
final v = values;
|
||||
final mode = v['runtime_mode'] ?? 'application';
|
||||
final system = mode == 'system_vpn';
|
||||
final optimization = Map<String, dynamic>.from(
|
||||
v['optimization'] as Map? ?? {'mode': 'adaptive'},
|
||||
);
|
||||
final flags = <String, dynamic>{
|
||||
...?v['flags'] as Map<String, dynamic>?,
|
||||
'no_tun': !system,
|
||||
'use_smoltcp': !system,
|
||||
'enable_encryption': true,
|
||||
'enable_ipv6': v['enable_ipv6'] ?? true,
|
||||
'latency_first': ['adaptive', 'latency'].contains(optimization['mode']),
|
||||
};
|
||||
final lines = <String>[
|
||||
'hostname = ${jsonEncode(v['hostname'] ?? 'MeshPort')}',
|
||||
if (v['dhcp'] == true)
|
||||
'dhcp = true'
|
||||
else
|
||||
'ipv4 = ${jsonEncode(v['ipv4'] ?? '')}',
|
||||
'listeners = ${jsonEncode(v['listeners'] ?? [])}',
|
||||
for (final key in ['stun_servers', 'stun_servers_v6'])
|
||||
if (v[key] != null) '$key = ${jsonEncode(v[key])}',
|
||||
for (final uri in v['peers'] as List? ?? [])
|
||||
'[[peer]]\nuri = ${jsonEncode(uri)}',
|
||||
'[network_identity]',
|
||||
'network_name = ${jsonEncode(v['network_name'] ?? '')}',
|
||||
'network_secret = ${jsonEncode(v['network_secret'] ?? '')}',
|
||||
'[flags]',
|
||||
for (final entry in flags.entries)
|
||||
'${entry.key} = ${jsonEncode(entry.value)}',
|
||||
'[runtime]',
|
||||
'mode = ${jsonEncode(system ? 'system_vpn' : 'application')}',
|
||||
'[optimization]',
|
||||
for (final entry in optimization.entries)
|
||||
'${entry.key} = ${jsonEncode(entry.value)}',
|
||||
];
|
||||
return '${lines.join('\n')}\n';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
const supportedProxyTypes = {
|
||||
'socks',
|
||||
'http',
|
||||
'shadowsocks',
|
||||
'vmess',
|
||||
'vless',
|
||||
'trojan',
|
||||
};
|
||||
|
||||
class ProxyNode {
|
||||
final String id, name, source;
|
||||
final Map<String, dynamic> options;
|
||||
ProxyNode({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.source = 'manual',
|
||||
required this.options,
|
||||
}) {
|
||||
validate();
|
||||
}
|
||||
void validate() {
|
||||
if (!supportedProxyTypes.contains(options['type']))
|
||||
throw FormatException('不支持的代理协议');
|
||||
final host = options['server'];
|
||||
final port = options['server_port'];
|
||||
if (host is! String ||
|
||||
host.isEmpty ||
|
||||
host.contains(RegExp(r'[\s/:@]')) &&
|
||||
InternetAddress.tryParse(host) == null ||
|
||||
port is! int ||
|
||||
port < 1 ||
|
||||
port > 65535)
|
||||
throw FormatException('代理服务器或端口无效');
|
||||
final kind = options['type'];
|
||||
if (['vmess', 'vless'].contains(kind) &&
|
||||
(options['uuid'] is! String ||
|
||||
!RegExp(
|
||||
r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$',
|
||||
).hasMatch(options['uuid'])))
|
||||
throw FormatException('UUID 无效');
|
||||
if (['trojan', 'shadowsocks'].contains(kind) &&
|
||||
(options['password'] is! String ||
|
||||
(options['password'] as String).isEmpty))
|
||||
throw FormatException('需要节点密码');
|
||||
if (kind == 'shadowsocks' && options['method'] is! String)
|
||||
throw FormatException('需要加密方法');
|
||||
final fields = {
|
||||
'socks': {'version', 'username', 'password'},
|
||||
'http': {'username', 'password', 'tls'},
|
||||
'shadowsocks': {'method', 'password'},
|
||||
'vmess': {'uuid', 'security', 'alter_id', 'tls', 'transport'},
|
||||
'vless': {'uuid', 'flow', 'tls', 'transport'},
|
||||
'trojan': {'password', 'tls', 'transport'},
|
||||
};
|
||||
if (options.keys.any(
|
||||
(k) => !{'type', 'server', 'server_port', ...fields[kind]!}.contains(k),
|
||||
))
|
||||
throw FormatException('节点包含不受支持的配置字段');
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'source': source,
|
||||
'options': options,
|
||||
};
|
||||
factory ProxyNode.fromJson(Map<String, dynamic> j) => ProxyNode(
|
||||
id: j['id'] as String,
|
||||
name: j['name'] as String,
|
||||
source: j['source'] as String? ?? 'manual',
|
||||
options: Map<String, dynamic>.from(j['options'] as Map),
|
||||
);
|
||||
}
|
||||
|
||||
class ImportPreview {
|
||||
final List<ProxyNode> nodes;
|
||||
final int unsupported;
|
||||
ImportPreview(this.nodes, this.unsupported);
|
||||
}
|
||||
|
||||
String _decode64(String value) => utf8.decode(
|
||||
base64.decode(
|
||||
base64.normalize(value.replaceAll('-', '+').replaceAll('_', '/')),
|
||||
),
|
||||
);
|
||||
ImportPreview importProxyNodes(String input, {String source = 'manual'}) {
|
||||
if (utf8.encode(input).length > 1024 * 1024)
|
||||
throw FormatException('导入内容超过 1 MiB');
|
||||
var text = input.trim();
|
||||
if (text.isEmpty) throw FormatException('导入内容为空');
|
||||
if (!text.startsWith('{') && !text.startsWith('[') && !text.contains('://')) {
|
||||
try {
|
||||
text = _decode64(text).trim();
|
||||
} catch (_) {
|
||||
throw FormatException('不支持的导入格式');
|
||||
}
|
||||
}
|
||||
final raw = <Map<String, dynamic>>[];
|
||||
var unsupported = 0;
|
||||
if (text.startsWith('{') || text.startsWith('[')) {
|
||||
final json = jsonDecode(text);
|
||||
final entries = json is List
|
||||
? json
|
||||
: json is Map && json['outbounds'] is List
|
||||
? json['outbounds']
|
||||
: [json];
|
||||
for (final entry in entries) {
|
||||
if (entry is! Map) {
|
||||
throw FormatException('节点格式无效');
|
||||
}
|
||||
final node = Map<String, dynamic>.from(entry);
|
||||
if (!supportedProxyTypes.contains(node['type'])) {
|
||||
unsupported++;
|
||||
continue;
|
||||
}
|
||||
raw.add(node);
|
||||
}
|
||||
} else {
|
||||
for (final line
|
||||
in text.split(RegExp(r'\r?\n')).where((s) => s.trim().isNotEmpty)) {
|
||||
final uri = Uri.tryParse(line.trim());
|
||||
if (uri == null ||
|
||||
!{
|
||||
'ss',
|
||||
'vmess',
|
||||
'vless',
|
||||
'trojan',
|
||||
'socks',
|
||||
'socks5',
|
||||
'http',
|
||||
'https',
|
||||
}.contains(uri.scheme)) {
|
||||
unsupported++;
|
||||
continue;
|
||||
}
|
||||
if (uri.scheme == 'vmess') {
|
||||
final data = jsonDecode(_decode64(line.trim().substring(8))) as Map;
|
||||
final node = <String, dynamic>{
|
||||
'type': 'vmess',
|
||||
'server': data['add'],
|
||||
'server_port': int.parse('${data['port']}'),
|
||||
'uuid': data['id'],
|
||||
'security': data['scy'] ?? 'auto',
|
||||
'tag': data['ps'] ?? 'VMess',
|
||||
};
|
||||
if ('${data['aid'] ?? 0}' != '0')
|
||||
node['alter_id'] = int.parse('${data['aid']}');
|
||||
if (data['tls'] == 'tls')
|
||||
node['tls'] = {
|
||||
'enabled': true,
|
||||
'server_name': data['sni'] ?? data['host'] ?? data['add'],
|
||||
};
|
||||
if (data['net'] == 'ws')
|
||||
node['transport'] = {
|
||||
'type': 'ws',
|
||||
'path': data['path'] ?? '/',
|
||||
'headers': {'Host': data['host'] ?? data['add']},
|
||||
};
|
||||
else if (data['net'] != null && data['net'] != 'tcp')
|
||||
throw FormatException('暂不支持该 VMess 传输');
|
||||
raw.add(node);
|
||||
continue;
|
||||
}
|
||||
if (uri.scheme == 'ss') {
|
||||
if (uri.queryParameters.isNotEmpty)
|
||||
throw FormatException('暂不支持 Shadowsocks 插件');
|
||||
Uri parsed = uri;
|
||||
var auth = uri.userInfo;
|
||||
if (auth.isEmpty) {
|
||||
final decoded = _decode64(line.trim().substring(5).split('#').first);
|
||||
parsed = Uri.parse('ss://$decoded');
|
||||
auth = parsed.userInfo;
|
||||
}
|
||||
if (!auth.contains(':')) auth = _decode64(auth);
|
||||
final split = auth.indexOf(':');
|
||||
if (split < 1) throw FormatException('Shadowsocks 认证无效');
|
||||
raw.add({
|
||||
'type': 'shadowsocks',
|
||||
'server': parsed.host,
|
||||
'server_port': parsed.port,
|
||||
'method': Uri.decodeComponent(auth.substring(0, split)),
|
||||
'password': Uri.decodeComponent(auth.substring(split + 1)),
|
||||
'tag': uri.fragment.isEmpty ? 'Shadowsocks' : uri.fragment,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
final kind = uri.scheme == 'socks5'
|
||||
? 'socks'
|
||||
: uri.scheme == 'https'
|
||||
? 'http'
|
||||
: uri.scheme;
|
||||
final node = <String, dynamic>{
|
||||
'type': kind,
|
||||
'server': uri.host,
|
||||
'server_port': uri.hasPort
|
||||
? uri.port
|
||||
: kind == 'http'
|
||||
? (uri.scheme == 'https' ? 443 : 80)
|
||||
: {'vless', 'trojan'}.contains(kind)
|
||||
? 443
|
||||
: 1080,
|
||||
'tag': uri.fragment.isEmpty ? kind : uri.fragment,
|
||||
};
|
||||
final user = Uri.decodeComponent(uri.userInfo);
|
||||
if (kind == 'vless') {
|
||||
node['uuid'] = user;
|
||||
if (uri.queryParameters['flow'] != null)
|
||||
node['flow'] = uri.queryParameters['flow'];
|
||||
} else if (kind == 'trojan') {
|
||||
node['password'] = user;
|
||||
} else if (user.isNotEmpty) {
|
||||
final colon = user.indexOf(':');
|
||||
node['username'] = colon < 0 ? user : user.substring(0, colon);
|
||||
node['password'] = colon < 0 ? '' : user.substring(colon + 1);
|
||||
if (kind == 'socks') node['version'] = '5';
|
||||
}
|
||||
final security =
|
||||
uri.queryParameters['security'] ??
|
||||
(kind == 'trojan' || uri.scheme == 'https' ? 'tls' : 'none');
|
||||
if (security == 'tls' || security == 'reality') {
|
||||
final tls = <String, dynamic>{
|
||||
'enabled': true,
|
||||
'server_name': uri.queryParameters['sni'] ?? uri.host,
|
||||
};
|
||||
if (uri.queryParameters['alpn'] != null)
|
||||
tls['alpn'] = uri.queryParameters['alpn']!.split(',');
|
||||
if (security == 'reality') {
|
||||
tls['reality'] = {
|
||||
'enabled': true,
|
||||
'public_key': uri.queryParameters['pbk'] ?? '',
|
||||
'short_id': uri.queryParameters['sid'] ?? '',
|
||||
};
|
||||
tls['utls'] = {
|
||||
'enabled': true,
|
||||
'fingerprint': uri.queryParameters['fp'] ?? 'chrome',
|
||||
};
|
||||
}
|
||||
node['tls'] = tls;
|
||||
} else if (security != 'none')
|
||||
throw FormatException('不支持的安全方式');
|
||||
final transport = uri.queryParameters['type'] ?? 'tcp';
|
||||
if (transport == 'ws')
|
||||
node['transport'] = {
|
||||
'type': 'ws',
|
||||
'path': uri.queryParameters['path'] ?? '/',
|
||||
'headers': {'Host': uri.queryParameters['host'] ?? uri.host},
|
||||
};
|
||||
else if (transport == 'grpc')
|
||||
node['transport'] = {
|
||||
'type': 'grpc',
|
||||
'service_name': uri.queryParameters['serviceName'] ?? '',
|
||||
};
|
||||
else if (transport != 'tcp')
|
||||
throw FormatException('不支持的传输方式');
|
||||
raw.add(node);
|
||||
}
|
||||
}
|
||||
final nodes = <ProxyNode>[];
|
||||
final seen = <String>{};
|
||||
for (final data in raw) {
|
||||
final options = Map<String, dynamic>.from(data);
|
||||
final name = '${options.remove('tag') ?? options['type']}';
|
||||
final key = jsonEncode(options);
|
||||
if (seen.add(key))
|
||||
nodes.add(
|
||||
ProxyNode(
|
||||
id: '${DateTime.now().microsecondsSinceEpoch}-${nodes.length}',
|
||||
name: name,
|
||||
source: source,
|
||||
options: options,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (nodes.isEmpty) throw FormatException('未发现支持的代理节点');
|
||||
if (nodes.length > 256) throw FormatException('最多导入 256 个节点');
|
||||
return ImportPreview(nodes, unsupported);
|
||||
}
|
||||
|
||||
class ProxyProfile {
|
||||
List<ProxyNode> nodes = [];
|
||||
List<Map<String, dynamic>> rules = [];
|
||||
List<Map<String, dynamic>> meshDns = [];
|
||||
List<Map<String, dynamic>> subscriptions = [];
|
||||
List<Map<String, dynamic>> ruleSets = [];
|
||||
String directDnsServer = "";
|
||||
bool proxyEnabled = false;
|
||||
String entry = 'application';
|
||||
bool fakeIP = false;
|
||||
List<String> fakeIPExclude = [];
|
||||
String? selectedId;
|
||||
String feature = 'combined',
|
||||
mode = 'rule',
|
||||
defaultAction = 'proxy',
|
||||
dnsServer = '1.1.1.1',
|
||||
proxyDnsServer = '';
|
||||
String get modeLabel => switch (mode) {
|
||||
'bypass_cn' => '绕过中国大陆',
|
||||
'global' => '全局代理',
|
||||
'direct' => '直连',
|
||||
_ => '自定义规则',
|
||||
};
|
||||
void validateConnection() {
|
||||
if (feature != 'mesh' &&
|
||||
mode != 'direct' &&
|
||||
proxyDnsServer.trim().isEmpty) {
|
||||
throw StateError('请在 DNS 设置中填写代理 DNS;防泄露模式不会自动选择解析服务或回退到直连 DNS');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> runtime() {
|
||||
final node = nodes.where((n) => n.id == selectedId).firstOrNull;
|
||||
return {
|
||||
'feature': feature,
|
||||
'mode': mode,
|
||||
'default_action': defaultAction,
|
||||
'rules': rules,
|
||||
'dns_protection': true,
|
||||
'dns_server': dnsServer,
|
||||
'proxy_dns_server': proxyDnsServer,
|
||||
'direct_dns_server': directDnsServer,
|
||||
'rule_sets': ruleSets,
|
||||
'mesh_dns': feature == 'proxy' ? [] : meshDns,
|
||||
'fakeip': feature != 'mesh' && fakeIP,
|
||||
'fakeip_exclude': fakeIPExclude,
|
||||
if (node != null) 'proxy': node.options,
|
||||
};
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'version': 1,
|
||||
'entry': entry,
|
||||
'proxy_enabled': proxyEnabled,
|
||||
'nodes': nodes.map((n) => n.toJson()).toList(),
|
||||
'selected': selectedId,
|
||||
'runtime': runtime()..remove('proxy'),
|
||||
'subscriptions': subscriptions,
|
||||
};
|
||||
factory ProxyProfile.fromJson(Map<String, dynamic> j) {
|
||||
if (j['version'] != 1) throw FormatException('不支持的配置版本');
|
||||
final p = ProxyProfile();
|
||||
p.entry = j['entry'] as String? ?? 'application';
|
||||
p.proxyEnabled = j['proxy_enabled'] as bool? ?? p.entry == 'unified_vpn';
|
||||
p.nodes = (j['nodes'] as List)
|
||||
.map((n) => ProxyNode.fromJson(Map<String, dynamic>.from(n)))
|
||||
.toList();
|
||||
p.selectedId = j['selected'] as String?;
|
||||
final r = j['runtime'] as Map;
|
||||
p.directDnsServer = r['direct_dns_server'] as String? ?? '';
|
||||
p.ruleSets = (r['rule_sets'] as List? ?? [])
|
||||
.map((v) => Map<String, dynamic>.from(v))
|
||||
.toList();
|
||||
p.fakeIP = r['fakeip'] == true;
|
||||
p.fakeIPExclude = List<String>.from(r['fakeip_exclude'] as List? ?? []);
|
||||
p.feature = r['feature'] as String;
|
||||
p.mode = r['mode'] as String;
|
||||
p.defaultAction = r['default_action'] as String;
|
||||
p.dnsServer = r['dns_server'] as String;
|
||||
p.proxyDnsServer = r['proxy_dns_server'] as String? ?? '';
|
||||
p.rules = List<Map<String, dynamic>>.from(
|
||||
(r['rules'] as List).map((v) => Map<String, dynamic>.from(v)),
|
||||
);
|
||||
p.meshDns = List<Map<String, dynamic>>.from(
|
||||
(r['mesh_dns'] as List? ?? []).map((v) => Map<String, dynamic>.from(v)),
|
||||
);
|
||||
p.subscriptions = List<Map<String, dynamic>>.from(
|
||||
(j['subscriptions'] as List? ?? []).map(
|
||||
(v) => Map<String, dynamic>.from(v),
|
||||
),
|
||||
);
|
||||
return p;
|
||||
}
|
||||
ProxyProfile();
|
||||
}
|
||||
|
||||
Future<ImportPreview> fetchSubscription(
|
||||
String url, {
|
||||
required String source,
|
||||
}) async {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null ||
|
||||
uri.scheme != 'https' ||
|
||||
uri.host.isEmpty ||
|
||||
uri.userInfo.isNotEmpty ||
|
||||
uri.fragment.isNotEmpty)
|
||||
throw FormatException('订阅需使用 HTTPS 地址');
|
||||
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
|
||||
try {
|
||||
final req = await client.getUrl(uri).timeout(const Duration(seconds: 15));
|
||||
req.followRedirects = false;
|
||||
final response = await req.close().timeout(const Duration(seconds: 15));
|
||||
if (response.statusCode != 200)
|
||||
throw StateError('订阅服务器返回 ${response.statusCode}');
|
||||
final bytes = <int>[];
|
||||
await for (final chunk in response.timeout(const Duration(seconds: 15))) {
|
||||
bytes.addAll(chunk);
|
||||
if (bytes.length > 1024 * 1024) throw StateError('订阅超过 1 MiB');
|
||||
}
|
||||
return importProxyNodes(utf8.decode(bytes), source: source);
|
||||
} on FormatException {
|
||||
rethrow;
|
||||
} catch (_) {
|
||||
throw StateError('订阅更新失败,原配置保持不变');
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty/unsupported-only responses never erase a working subscription.
|
||||
void replaceSubscription(
|
||||
ProxyProfile profile,
|
||||
String source,
|
||||
ImportPreview preview,
|
||||
DateTime now,
|
||||
) {
|
||||
if (preview.nodes.isEmpty) throw const FormatException('订阅没有可用节点,保留原配置');
|
||||
final old = profile.nodes.where((n) => n.source == source).toList();
|
||||
final next = preview.nodes.map((n) {
|
||||
final retained = old
|
||||
.where((o) => jsonEncode(o.options) == jsonEncode(n.options))
|
||||
.firstOrNull;
|
||||
return ProxyNode(
|
||||
id: retained?.id ?? n.id,
|
||||
name: n.name,
|
||||
source: source,
|
||||
options: n.options,
|
||||
);
|
||||
}).toList();
|
||||
profile.nodes = [...profile.nodes.where((n) => n.source != source), ...next];
|
||||
if (old.any((n) => n.id == profile.selectedId) &&
|
||||
!next.any((n) => n.id == profile.selectedId))
|
||||
profile.selectedId = null;
|
||||
profile.subscriptions
|
||||
.where((s) => s['id'] == source)
|
||||
.firstOrNull?['updated'] = now
|
||||
.toUtc()
|
||||
.toIso8601String();
|
||||
}
|
||||
|
||||
bool subscriptionDue(Map<String, dynamic> sub, DateTime now) {
|
||||
if (sub['auto_update'] != true) return false;
|
||||
final last = DateTime.tryParse(sub['updated'] as String? ?? '');
|
||||
final minutes = sub['interval_minutes'] as int? ?? 360;
|
||||
return last == null ||
|
||||
now.difference(last) >= Duration(minutes: minutes.clamp(15, 10080));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
name: meshport_client_core
|
||||
description: MeshPort client session orchestration, separate from the networking SDK.
|
||||
version: 0.1.0
|
||||
publish_to: none
|
||||
environment:
|
||||
sdk: ^3.11.0
|
||||
dependencies:
|
||||
meshport_flutter:
|
||||
path: ../../bindings/flutter/meshport_flutter
|
||||
singbox_flutter:
|
||||
path: ../../bindings/flutter/singbox_flutter
|
||||
Reference in New Issue
Block a user