Fix VPN internet connectivity and simplify client setup

Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
This commit is contained in:
shen
2026-10-12 06:51:25 -07:00
parent 2f185f914d
commit c7cc2aa865
41 changed files with 2841 additions and 247 deletions
+266 -94
View File
@@ -11,6 +11,7 @@ import 'network_telemetry.dart';
import 'proxy_panel.dart';
import 'configuration_pages.dart';
import 'detail_pages.dart';
import 'runtime_diagnostics.dart';
class LabScreen extends StatefulWidget {
const LabScreen({super.key, this.initializeNative = true});
@@ -21,12 +22,22 @@ class LabScreen extends StatefulWidget {
class _LabScreenState extends State<LabScreen> {
MeshPortClient? client, applicationClient, systemClient;
String runtimeMode = 'application';
String runtimeMode = Platform.isMacOS || Platform.isAndroid
? 'unified_vpn'
: 'application';
bool singBoxEnabled = false;
MeshProxySession? proxySession;
ProxyProfile proxyProfile = ProxyProfile();
ProxyProfile proxyProfile = ProxyProfile()
..feature = 'proxy'
..mode = 'global'
..entry = (Platform.isMacOS || Platform.isAndroid
? 'unified_vpn'
: 'application');
String runningProxyLabel = '', runningProxyMode = '';
bool proxyDraftChanged = false;
int proxySavesPending = 0;
bool proxySaveFailed = false;
Future<void> proxySaveTail = Future.value();
bool rememberConfig = false;
String? savedConfig;
String? loadedConfig, loadedForm;
@@ -54,6 +65,9 @@ class _LabScreenState extends State<LabScreen> {
Map<String, dynamic> status = {'state': 'Stopped', 'peer_count': 0};
Map<String, dynamic>? result;
final logs = <String>[];
final diagnosticRedactor = DiagnosticRedactor();
String lastProxyState = '';
int proxyEventSequence = 0;
final latencies = <double>[];
final name = TextEditingController(text: 'game-net');
final secret = TextEditingController();
@@ -81,9 +95,11 @@ class _LabScreenState extends State<LabScreen> {
Future<void> initialize() async {
try {
log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启');
const path = String.fromEnvironment('MESHPORT_LIBRARY');
final opened = await MeshPortClient.open(
libraryPath: path.isEmpty ? null : path,
final opened = await diagnosticStage(
'加载 MeshPort 动态库',
() => MeshPortClient.open(libraryPath: path.isEmpty ? null : path),
);
if (!mounted) {
await opened.close();
@@ -100,6 +116,9 @@ class _LabScreenState extends State<LabScreen> {
proxyProfile = ProxyProfile.fromJson(
jsonDecode(stored) as Map<String, dynamic>,
);
if (proxyProfile.entry == 'system_vpn') {
proxyProfile.feature = 'mesh';
}
savedProxyJson = jsonEncode(proxyProfile.toJson());
}
} catch (_) {
@@ -142,7 +161,11 @@ class _LabScreenState extends State<LabScreen> {
await loadForm(defaults);
if (mounted) setState(() => rememberConfig = profileSupported);
log(
secret.text.isEmpty
proxyProfile.feature == 'proxy'
? (proxyProfile.nodes.isEmpty
? '默认代理设置已就绪,导入节点后即可连接'
: '已载入代理设置,点击连接即可使用')
: secret.text.isEmpty
? '已载入默认配置,首次填写网络密钥后保存即可'
: '已载入默认网络配置,点击连接即可组网',
);
@@ -150,8 +173,11 @@ class _LabScreenState extends State<LabScreen> {
log('默认配置加载失败,请在设置中导入配置');
}
}
if (proxyProfile.proxyEnabled || !restored) {
if (savedProxyJson != null || !restored) {
runtimeMode = proxyProfile.entry;
} else {
proxyProfile.feature = 'mesh';
proxyProfile.entry = runtimeMode;
}
singBoxEnabled = proxyProfile.proxyEnabled;
final diagnostics = await opened.enableDiagnostics();
@@ -226,26 +252,19 @@ class _LabScreenState extends State<LabScreen> {
}
void log(String text) {
final secrets = <String>[
secret.text,
for (final node in proxyProfile.nodes)
for (final key in ['password', 'uuid'])
if (node.options[key] is String) node.options[key] as String,
];
for (final value in secrets.where((value) => value.isNotEmpty)) {
text = text.replaceAll(value, '[已隐藏]');
}
text = text.replaceAllMapped(
RegExp(r'(https?://)[^\s/]+@'),
(m) => '${m[1]}[已隐藏]@',
);
text = text.replaceAllMapped(
RegExp(r'(https?://[^\s?]+)\?[^\s]+'),
(m) => '${m[1]}?[已隐藏]',
);
if (!mounted) {
return;
}
diagnosticRedactor.remember({'network_secret': secret.text});
diagnosticRedactor.remember(proxyProfile.toJson());
text = diagnosticRedactor.sanitize(text);
if ((Platform.isMacOS || Platform.isAndroid) && widget.initializeNative) {
unawaited(
vpnChannel
.invokeMethod<void>('runtime_log', text)
.catchError((Object _) {}),
);
}
setState(() {
logs.insert(
0,
@@ -257,15 +276,43 @@ class _LabScreenState extends State<LabScreen> {
});
}
Future<T> diagnosticStage<T>(
String stage,
Future<T> Function() action,
) async {
final elapsed = Stopwatch()..start();
log('[$stage] 开始');
try {
final result = await action();
log('[$stage] 成功 · ${elapsed.elapsedMilliseconds} ms');
return result;
} catch (e) {
log('[$stage] 失败 · ${elapsed.elapsedMilliseconds} ms · $e');
rethrow;
}
}
Future<void> refresh() async {
if (refreshing) return;
refreshing = true;
try {
final next =
runtimeMode != 'system_vpn' && singBoxEnabled && proxySession != null
final next = client == applicationClient && proxySession != null
? await proxySession!.refresh()
: await client?.status();
if (mounted && next != null) {
for (final event
in (next['proxy'] as Map?)?['runtime_events'] as List? ?? []) {
final sequence = (event['sequence'] as num).toInt();
if (sequence > proxyEventSequence) {
log('代理 · ${event['message']}');
proxyEventSequence = sequence;
}
}
final proxyState = proxySession?.state ?? '';
if (proxyState != lastProxyState) {
lastProxyState = proxyState;
if (proxyState.isNotEmpty) log('代理会话状态 → $proxyState');
}
final instance = next['instance_id'] as String? ?? '';
if (eventInstance != instance) {
eventInstance = instance;
@@ -449,11 +496,16 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> startConfig(String config) async {
proxyEventSequence = 0;
if (singBoxEnabled) proxyProfile.validateConnection();
// Validation selects mode from effective flags, avoiding ad-hoc TOML parsing.
final validated = singBoxEnabled && proxyProfile.feature == 'proxy'
? <String, dynamic>{'runtime_mode': 'application'}
: await applicationClient!.request({'op': 'validate', 'toml': config});
: await diagnosticStage(
'校验组网配置',
() =>
applicationClient!.request({'op': 'validate', 'toml': config}),
);
final unified = runtimeMode == 'unified_vpn';
final system = validated['runtime_mode'] == 'system_vpn' || unified;
if (proxySession != null) {
@@ -471,15 +523,18 @@ class _LabScreenState extends State<LabScreen> {
if (singBoxEnabled) {
proxySession = MeshProxySession(
mesh: applicationClient!,
proxy: await NativeProxyEngine.open(),
proxy: await diagnosticStage(
'加载 sing-box 动态库',
NativeProxyEngine.open,
),
profile:
jsonDecode(jsonEncode(proxyProfile.runtime()))
as Map<String, dynamic>,
);
await proxySession!.start(config);
await diagnosticStage('启动应用内代理会话', () => proxySession!.start(config));
log('sing-box 组网入口:${proxySession!.endpoint ?? '等待虚拟地址'}');
} else {
await applicationClient!.start(config);
await diagnosticStage('启动组网引擎', () => applicationClient!.start(config));
}
if (!singBoxEnabled || proxyProfile.feature != 'proxy') {
await saveProfile(config);
@@ -497,25 +552,35 @@ class _LabScreenState extends State<LabScreen> {
: await openMacSystemVpn(
launch: (path, uid) async {
log('等待管理员授权以创建虚拟网卡');
await vpnChannel.invokeMethod<void>('launch', {
'socket': path,
'uid': uid,
});
await diagnosticStage(
'授权并启动 macOS VPN 辅助进程',
() => vpnChannel.invokeMethod<void>('launch', {
'socket': path,
'uid': uid,
}),
);
},
);
try {
await opened.enableDiagnostics();
if (unified) {
await opened.request({
'op': 'start',
'toml': config,
'unified_profile': proxyProfile.runtime(),
});
await diagnosticStage(
'启动统一 VPN 代理',
() => opened.request({
'op': 'start',
'toml': config,
'unified_profile': proxyProfile.runtime(),
}),
);
} else {
await opened.start(config);
}
systemClient = client = opened;
log('系统 VPN 已启动,接入虚拟网段与远端子网');
log(
unified && proxyProfile.feature == 'proxy'
? '统一 VPN 已启动,互联网流量已接入'
: '系统 VPN 已启动,接入虚拟网段与远端子网',
);
await saveProfile(config);
} catch (_) {
await opened.close();
@@ -775,7 +840,63 @@ class _LabScreenState extends State<LabScreen> {
},
);
Widget overview() => Column(
Widget overview() {
if (proxyProfile.feature != 'proxy') return networkOverview();
final selected = proxyProfile.nodes
.where((node) => node.id == proxyProfile.selectedId)
.firstOrNull;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
panel('连接', [
ListTile(
leading: Icon(
running ? Icons.check_circle_outline : Icons.power_settings_new,
),
title: Text(running ? '代理已连接' : '尚未连接'),
subtitle: Text(
running && runningProxyLabel.isNotEmpty
? '$runningProxyMode · $runningProxyLabel'
: selected == null
? '导入一个节点即可开始'
: '${proxyProfile.modeLabel} · ${selected.name}',
),
trailing: TextButton(
onPressed: busy || client == null ? null : primaryConnection,
child: Text(
running ? (proxyDraftChanged ? '重连应用修改' : '断开连接') : '连接',
),
),
),
if (proxyDraftChanged) const Text('配置已修改,重连后生效。'),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
FilledButton.tonal(
onPressed: () => setState(() => page = 1),
child: const Text('管理代理节点'),
),
OutlinedButton(
onPressed: () => openDetail(
'运行日志',
() => LogsPageBody(
logs: logs,
onClear: () => setState(() => logs.clear()),
),
),
child: const Text('诊断与日志'),
),
],
),
]),
if (logs.isNotEmpty)
panel('最近事件', logs.take(3).map((line) => Text(line)).toList()),
],
);
}
Widget networkOverview() => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
@@ -800,16 +921,10 @@ class _LabScreenState extends State<LabScreen> {
: '应用内网络'}',
),
trailing: TextButton(
onPressed: busy || client == null
? null
: () => perform(
running
? (c) async {
await stopActive(c);
}
: connect,
),
child: Text(running ? '断开连接' : '连接网络'),
onPressed: busy || client == null ? null : primaryConnection,
child: Text(
running ? (proxyDraftChanged ? '重连应用修改' : '断开连接') : '连接',
),
),
),
),
@@ -916,12 +1031,22 @@ class _LabScreenState extends State<LabScreen> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
panel('组网配置', [
for (final title in ['基础配置', '连接与打洞', '高级配置', '线路策略'])
ListTile(
title: Text(title),
trailing: const Icon(Icons.chevron_right),
onTap: () => openNetworkConfig(title),
),
ListTile(
title: const Text('基础配置'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openNetworkConfig('基础配置'),
),
ExpansionTile(
title: const Text('高级组网设置'),
children: [
for (final title in ['连接与打洞', '高级配置', '线路策略'])
ListTile(
title: Text(title),
trailing: const Icon(Icons.chevron_right),
onTap: () => openNetworkConfig(title),
),
],
),
ListTile(
title: const Text('自动接入子网'),
trailing: const Icon(Icons.chevron_right),
@@ -1128,10 +1253,8 @@ class _LabScreenState extends State<LabScreen> {
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => DnsPage(
profile: proxyProfile,
changed: () => setState(() => proxyDraftChanged = true),
),
builder: (_) =>
DnsPage(profile: proxyProfile, changed: proxyChanged),
),
),
),
@@ -1174,6 +1297,7 @@ class _LabScreenState extends State<LabScreen> {
if (!mounted ||
busy ||
subscriptionUpdating ||
proxySavesPending > 0 ||
savedProxyJson != jsonEncode(proxyProfile.toJson()) ||
!profileSupported) {
return;
@@ -1241,42 +1365,69 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> saveProxyProfile() async {
if (const bool.fromEnvironment('MESHPORT_UI_PREVIEW')) return;
final text = jsonEncode(proxyProfile.toJson());
if (utf8.encode(text).length > 65536) {
if (mounted) setState(() => proxySaveFailed = true);
throw const FormatException('保存配置超过 64 KiB,请减少节点数量');
}
await vpnChannel.invokeMethod<void>('save_proxy_profile', text);
savedProxyJson = text;
if (mounted && !running) setState(() => proxyDraftChanged = false);
log('代理配置已安全保存');
if (!profileSupported) return;
if (mounted) setState(() => proxySavesPending++);
final job = proxySaveTail.then((_) async {
try {
await vpnChannel.invokeMethod<void>('save_proxy_profile', text);
savedProxyJson = text;
if (mounted) setState(() => proxySaveFailed = false);
} catch (_) {
if (mounted) setState(() => proxySaveFailed = true);
rethrow;
} finally {
if (mounted) setState(() => proxySavesPending--);
}
});
proxySaveTail = job.then<void>(
(_) {},
onError: (Object error, StackTrace trace) {},
);
await job;
}
void proxyChanged() {
if (!mounted) return;
setState(() => proxyDraftChanged = running);
unawaited(
saveProxyProfile().catchError((Object _) {
log('自动保存失败,请在代理页重试保存');
}),
);
}
Future<void> primaryConnection() async {
if (running && !proxyDraftChanged) {
await perform(stopActive);
} else {
await connectProxy();
}
}
Future<void> connectProxy() async {
if (runtimeMode != 'system_vpn') proxyProfile.validateConnection();
if (running) {
final approved = await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: const Text('重连使配置生效'),
content: const Text('当前会话和连接将关闭,再按草稿启动。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(c, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(c, true),
child: const Text('重连'),
),
],
),
);
if (approved != true) return;
}
log(
'请求代理连接 · 入口=$runtimeMode · 功能=${proxyProfile.feature} · '
'模式=${proxyProfile.mode} · 节点数=${proxyProfile.nodes.length} · '
'已选择出口=${proxyProfile.nodes.any((n) => n.id == proxyProfile.selectedId)} · '
'代理 DNS=已配置',
);
await diagnosticStage('校验代理配置', () async {
if (runtimeMode != 'system_vpn') proxyProfile.validateConnection();
});
if (!mounted) return;
await perform((c) async {
if (runtimeMode == 'system_vpn' && proxyProfile.feature != 'mesh') {
throw StateError('互联网代理需要选择统一 VPN 或应用内入口');
}
await proxySaveTail;
proxyProfile.entry = runtimeMode;
if (profileSupported) await saveProxyProfile();
final nextConfig = buildFormConfig();
if (proxyProfile.feature != 'proxy') {
await applicationClient!.request({
@@ -1285,7 +1436,9 @@ class _LabScreenState extends State<LabScreen> {
});
}
if (running) await stopActive(c);
singBoxEnabled = runtimeMode != 'system_vpn';
singBoxEnabled =
runtimeMode == 'unified_vpn' ||
(runtimeMode == 'application' && proxyProfile.feature != 'mesh');
await startConfig(buildFormConfig());
runningProxyLabel =
proxyProfile.nodes
@@ -1302,17 +1455,27 @@ class _LabScreenState extends State<LabScreen> {
Widget proxyPage() => ProxyPanel(
entry: runtimeMode,
entryChanged: (v) => setState(() {
runtimeMode = v;
proxyProfile.entry = v;
proxyDraftChanged = true;
}),
entryChanged: (v) {
setState(() {
runtimeMode = v;
proxyProfile.entry = v;
});
proxyChanged();
},
profile: proxyProfile,
busy: busy,
running: running,
save: saveProxyProfile,
connect: connectProxy,
changed: () => setState(() => proxyDraftChanged = true),
connect: primaryConnection,
changed: proxyChanged,
draftChanged: proxyDraftChanged,
saving: proxySavesPending > 0,
saveFailed: proxySaveFailed,
showLogs: () => openDetail(
'运行日志',
() =>
LogsPageBody(logs: logs, onClear: () => setState(() => logs.clear())),
),
);
Future<void> importConfig() async {
final text = await showDialog<String>(
@@ -1322,7 +1485,16 @@ class _LabScreenState extends State<LabScreen> {
if (text != null && mounted) {
await perform((c) async {
await loadForm(text);
proxyProfile.feature = 'mesh';
proxyProfile.entry = runtimeMode;
proxyProfile.proxyEnabled = false;
singBoxEnabled = false;
await startConfig(text);
try {
await saveProxyProfile();
} catch (_) {
log('组网已连接,但连接方式未能保存,请重试保存');
}
log('导入配置并启动引擎');
});
}
@@ -1385,7 +1557,7 @@ class _LabScreenState extends State<LabScreen> {
],
),
actions: [
if (wide)
if (wide && proxyProfile.feature != 'proxy')
Padding(
padding: const EdgeInsets.only(right: 20),
child: ConstrainedBox(