diff --git a/.gitignore b/.gitignore index e7641f9..d6602da 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,16 @@ /target/ /work/ /build/ +/outputs/android/ +/outputs/macos/ +# Runtime captures remain local; commit the validation summaries instead. +/outputs/validation/*.log **/.dart_tool/ **/build/ +!vendor/easytier/easytier/build/ +!vendor/easytier/easytier/build/** +!vendor/easytier/easytier-proto/build/ +!vendor/easytier/easytier-proto/build/** **/.flutter-plugins-dependencies **/Flutter/ephemeral/ .DS_Store diff --git a/apps/meshport_lab/android/app/src/main/AndroidManifest.xml b/apps/meshport_lab/android/app/src/main/AndroidManifest.xml index 4d431a8..6aed4b1 100644 --- a/apps/meshport_lab/android/app/src/main/AndroidManifest.xml +++ b/apps/meshport_lab/android/app/src/main/AndroidManifest.xml @@ -1,4 +1,5 @@ - + @@ -8,6 +9,10 @@ android:label="MeshPort" android:name="${applicationName}" android:icon="@mipmap/ic_launcher"> + + diff --git a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt index 2b31e74..a3ef755 100644 --- a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt +++ b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt @@ -33,6 +33,13 @@ class MainActivity : FlutterActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "meshport/system_vpn").setMethodCallHandler { call, result -> + if (call.method == "runtime_log") { + // Flutter redacts credentials before sending these bounded events. + val text = call.arguments as? String ?: "" + Log.i("MeshPortRuntime", text.take(4096)) + result.success(null) + return@setMethodCallHandler + } if (call.method in listOf("import_file", "import_qr_image", "scan_qr")) { if (importResult != null) { result.error("IMPORT_BUSY", "Import already open", null); return@setMethodCallHandler } importResult = result diff --git a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt index 9c1fee5..4b4eb61 100644 --- a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt +++ b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt @@ -40,7 +40,7 @@ class MeshVpnService : VpnService() { manager.createNotificationChannel(NotificationChannel("meshport_vpn", "MeshPort 组网", NotificationManager.IMPORTANCE_LOW)) val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) startForeground(77, Notification.Builder(this, "meshport_vpn") - .setContentTitle("MeshPort").setContentText("虚拟组网服务正在运行") + .setContentTitle("MeshPort").setContentText("VPN 服务正在运行") .setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build()) worker.scheduleWithFixedDelay({ if (running) try { @@ -177,6 +177,7 @@ class MeshVpnService : VpnService() { private fun startUnified(config: String) { val manager = getSystemService(ConnectivityManager::class.java) physical = physicalNetwork(); setUnderlyingNetworks(arrayOf(physical!!)) + Log.i("MeshPortVPN", "Unified VPN: physical network selected; mesh enabled=$meshEnabled") if (meshEnabled) { val validated = native(JSONObject().put("op","validate").put("toml",config)).getJSONObject("data") check(validated.getString("runtime_mode") == "application") { "Unified VPN requires application-mode MeshPort" } @@ -204,11 +205,13 @@ class MeshVpnService : VpnService() { builder.allowFamily(OsConstants.AF_INET6) } tun = builder.establish() ?: error("VPN authorization revoked") + Log.i("MeshPortVPN", "Unified VPN: TUN established; internet routes=$internet") proxyHandle = NativeBridge.newProxyContext() check(proxyHandle != 0L) proxyCall(JSONObject().put("op","configure_cache").put("directory",cacheDir.absolutePath)) restartProxy(routes) running = true + Log.i("MeshPortVPN", "Unified VPN: proxy engine ready") networkCallback = object: ConnectivityManager.NetworkCallback() { override fun onAvailable(network: android.net.Network) { worker.execute { updatePhysical() } } override fun onLost(network: android.net.Network) { worker.execute { updatePhysical() } } @@ -250,6 +253,7 @@ class MeshVpnService : VpnService() { .put("tun",JSONObject().put("fd",tun!!.fd).put("name",NativeBridge.tunName(tun!!.fd) ?: error("TUN name unavailable")) .put("physical_interface",iface).put("physical_index",index)) proxyCall(JSONObject().put("op","start").put("config",config)) + Log.i("MeshPortVPN", "Unified VPN: protected physical sockets; learned routes=${routes.size}") installed = routes } private fun unifiedStatus(): JSONObject { @@ -262,6 +266,7 @@ class MeshVpnService : VpnService() { return JSONObject().put("ok",true).put("data",data) } private fun shutdown() { + if (running || handle != 0L || proxyHandle != 0L || tun != null) Log.i("MeshPortVPN", "Stopping VPN and releasing TUN") running = false if (proxyHandle != 0L) { NativeBridge.freeProxyContext(proxyHandle); proxyHandle = 0L } val connectivity = getSystemService(ConnectivityManager::class.java) diff --git a/apps/meshport_lab/integration_test/android_proxy_test.dart b/apps/meshport_lab/integration_test/android_proxy_test.dart new file mode 100644 index 0000000..f71545a --- /dev/null +++ b/apps/meshport_lab/integration_test/android_proxy_test.dart @@ -0,0 +1,168 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:meshport_client_core/meshport_client_core.dart'; +import 'package:meshport_flutter/meshport_flutter.dart'; + +const channel = MethodChannel('meshport/system_vpn'); +const fixtureHost = String.fromEnvironment('ANDROID_PROXY_FIXTURE'); + +Future httpsCheck() async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 20); + try { + final request = await client.getUrl( + Uri.parse('https://www.gstatic.com/generate_204'), + ); + final reply = await request.close().timeout(const Duration(seconds: 30)); + expect(reply.statusCode, 204); + await reply.drain(); + } finally { + client.close(force: true); + } +} + +Future proxyTcpCheck() async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 10); + try { + final request = await client.getUrl( + Uri.parse('http://198.51.100.45:18082/meshport-device-test'), + ); + final reply = await request.close().timeout(const Duration(seconds: 15)); + expect(reply.statusCode, 200); + expect(await utf8.decoder.bind(reply).join(), 'MeshPort proxy fixture'); + } finally { + client.close(force: true); + } +} + +Future udpCheck() async { + final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0); + final reply = Completer(); + final subscription = socket.listen((event) { + if (event == RawSocketEvent.read) { + final packet = socket.receive(); + if (packet != null && !reply.isCompleted) reply.complete(packet); + } + }, onError: reply.completeError); + final payload = utf8.encode('MeshPort Android UDP'); + try { + socket.send(payload, InternetAddress('198.51.100.45'), 18083); + expect( + (await reply.future.timeout(const Duration(seconds: 15))).data, + orderedEquals(payload), + ); + } finally { + await subscription.cancel(); + socket.close(); + } +} + +Future tunDnsCheck() async { + final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0); + final reply = Completer(); + final subscription = socket.listen((event) { + if (event == RawSocketEvent.read) { + final packet = socket.receive(); + if (packet != null && !reply.isCompleted) reply.complete(packet); + } + }, onError: reply.completeError); + // An uncached name asks the VPN DNS server to use the default encrypted DNS. + final packet = BytesBuilder() + ..add([0x4d, 0x50, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0]); + for (final label in 'example.com'.split('.')) { + packet.addByte(label.length); + packet.add(ascii.encode(label)); + } + packet.add([0, 0, 1, 0, 1]); + try { + socket.send(packet.toBytes(), InternetAddress('172.19.0.2'), 53); + final data = (await reply.future.timeout(const Duration(seconds: 30))).data; + expect(data.length, greaterThan(12)); + expect(data.take(2), [0x4d, 0x50]); + expect(data[3] & 15, 0, reason: 'DNS response must succeed'); + expect((data[6] << 8) | data[7], greaterThan(0)); + } finally { + await subscription.cancel(); + socket.close(); + } +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'Android unified VPN default DNS and proxy data plane', + (tester) async { + expect(fixtureHost, isNotEmpty); + await tester.pumpWidget( + const MaterialApp( + home: Scaffold(body: Center(child: Text('MeshPort Android 代理验证中'))), + ), + ); + expect(await channel.invokeMethod('debug_storage_self_test'), true); + await httpsCheck(); + debugPrint('ANDROID_BASELINE_HTTPS_PASS'); + final profile = ProxyProfile() + ..feature = 'proxy' + ..mode = 'global' + ..entry = 'unified_vpn'; + profile.addNodes( + importProxyNodes('socks5://$fixtureHost:18084#Device-test').nodes, + ); + profile.validateConnection(); + expect(profile.selectedId, profile.nodes.single.id); + expect(profile.effectiveProxyDns, ProxyProfile.defaultProxyDns); + debugPrint('WAITING_FOR_ANDROID_VPN_PERMISSION'); + final vpn = await openAndroidSystemVpn( + prepare: () => channel.invokeMethod('prepare_android_vpn'), + request: (request) async => + jsonDecode( + (await channel.invokeMethod( + 'android_vpn_request', + jsonEncode(request), + ))!, + ) + as Map, + ); + try { + for (var attempt = 0; attempt < 2; attempt++) { + await vpn.request({ + 'op': 'start', + 'toml': '', // Proxy-only must not require a mesh configuration. + 'unified_profile': profile.runtime(), + }); + // Wait for system clients to observe the newly established VPN. + await Future.delayed(const Duration(seconds: 2)); + final state = await vpn.status(); + expect(state['state'], 'Running'); + expect(state['platform_network']['ready'], true); + await proxyTcpCheck(); + debugPrint('ANDROID_UNIFIED_OS_TCP_PASS_$attempt'); + await udpCheck(); + debugPrint('ANDROID_UNIFIED_OS_UDP_PASS_$attempt'); + await tunDnsCheck(); + debugPrint('ANDROID_DEFAULT_DOH_PASS_$attempt'); + await httpsCheck(); + debugPrint('ANDROID_UNIFIED_HTTPS_PASS_$attempt'); + await vpn.stop(); + await Future.delayed(const Duration(seconds: 2)); + expect((await vpn.status())['state'], 'Stopped'); + await httpsCheck(); + debugPrint('ANDROID_NETWORK_RESTORED_PASS_$attempt'); + } + } catch (_) { + debugPrint( + 'ANDROID_UNIFIED_FAILURE_STATE ${jsonEncode(await vpn.status())}', + ); + rethrow; + } finally { + await vpn.close(); + } + }, + timeout: const Timeout(Duration(minutes: 8)), + ); +} diff --git a/apps/meshport_lab/lib/app.dart b/apps/meshport_lab/lib/app.dart index 2b395e0..2c7b9b5 100644 --- a/apps/meshport_lab/lib/app.dart +++ b/apps/meshport_lab/lib/app.dart @@ -8,7 +8,9 @@ class MeshPortApp extends StatelessWidget { title: 'MeshPort', debugShowCheckedModeBanner: false, theme: meshPortTheme(), - home: const LabScreen(), + home: const LabScreen( + initializeNative: !bool.fromEnvironment('MESHPORT_UI_PREVIEW'), + ), ); } diff --git a/apps/meshport_lab/lib/features/configuration_pages.dart b/apps/meshport_lab/lib/features/configuration_pages.dart index 5859542..efc5b53 100644 --- a/apps/meshport_lab/lib/features/configuration_pages.dart +++ b/apps/meshport_lab/lib/features/configuration_pages.dart @@ -452,7 +452,7 @@ class _DnsPageState extends State { style: TextStyle(color: Theme.of(context).colorScheme.error), ), const Text( - '代理模式下须明确配置代理 DNS;普通域名解析经所选代理,失败不回退直连 DNS。启动 DNS 仅用于节点和解析器地址,组网域名走组网 DNS。直连模式不提供代理 DNS 防泄露;应用内入口仅保护交给它的流量。', + '默认使用 Cloudflare 加密 DNS,经所选代理查询,失败不回退直连。代理 DNS 留空时使用默认值。直连模式使用直连 DNS。启动 DNS 用于连接节点和解析器,组网域名走组网 DNS。', ), TextField( controller: bootstrap, @@ -475,7 +475,8 @@ class _DnsPageState extends State { onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: '代理 DNS', - helperText: '代理模式必填:IP / DoH / DoT;经所选代理,失败不回退', + helperText: + '留空使用 https://cloudflare-dns.com/dns-query;支持 IP / DoH / DoT', ), ), SwitchListTile( diff --git a/apps/meshport_lab/lib/features/detail_pages.dart b/apps/meshport_lab/lib/features/detail_pages.dart index 21c5d1f..6173a22 100644 --- a/apps/meshport_lab/lib/features/detail_pages.dart +++ b/apps/meshport_lab/lib/features/detail_pages.dart @@ -204,7 +204,9 @@ class LogsPageBody extends StatelessWidget { Widget build(BuildContext context) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - const Text('仅保留本次应用会话最近 300 条事件,不写日志文件。复制会保留节点地址,但移除认证信息。'), + const Text( + '显示本次应用会话最近 300 条事件。macOS 同步写入系统日志,可在 Console 中筛选 MeshPort / Runtime。复制保留节点地址,隐藏认证信息。', + ), Wrap( spacing: 12, children: [ diff --git a/apps/meshport_lab/lib/features/lab_screen.dart b/apps/meshport_lab/lib/features/lab_screen.dart index d6ed650..965f743 100644 --- a/apps/meshport_lab/lib/features/lab_screen.dart +++ b/apps/meshport_lab/lib/features/lab_screen.dart @@ -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 { 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 proxySaveTail = Future.value(); bool rememberConfig = false; String? savedConfig; String? loadedConfig, loadedForm; @@ -54,6 +65,9 @@ class _LabScreenState extends State { Map status = {'state': 'Stopped', 'peer_count': 0}; Map? result; final logs = []; + final diagnosticRedactor = DiagnosticRedactor(); + String lastProxyState = ''; + int proxyEventSequence = 0; final latencies = []; final name = TextEditingController(text: 'game-net'); final secret = TextEditingController(); @@ -81,9 +95,11 @@ class _LabScreenState extends State { Future 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 { proxyProfile = ProxyProfile.fromJson( jsonDecode(stored) as Map, ); + if (proxyProfile.entry == 'system_vpn') { + proxyProfile.feature = 'mesh'; + } savedProxyJson = jsonEncode(proxyProfile.toJson()); } } catch (_) { @@ -142,7 +161,11 @@ class _LabScreenState extends State { 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 { 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 { } void log(String text) { - final secrets = [ - 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('runtime_log', text) + .catchError((Object _) {}), + ); + } setState(() { logs.insert( 0, @@ -257,15 +276,43 @@ class _LabScreenState extends State { }); } + Future diagnosticStage( + String stage, + Future 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 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 { } Future 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' ? {'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 { if (singBoxEnabled) { proxySession = MeshProxySession( mesh: applicationClient!, - proxy: await NativeProxyEngine.open(), + proxy: await diagnosticStage( + '加载 sing-box 动态库', + NativeProxyEngine.open, + ), profile: jsonDecode(jsonEncode(proxyProfile.runtime())) as Map, ); - 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 { : await openMacSystemVpn( launch: (path, uid) async { log('等待管理员授权以创建虚拟网卡'); - await vpnChannel.invokeMethod('launch', { - 'socket': path, - 'uid': uid, - }); + await diagnosticStage( + '授权并启动 macOS VPN 辅助进程', + () => vpnChannel.invokeMethod('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 { }, ); - 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 { : '应用内网络'}', ), 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 { 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 { onTap: () => Navigator.push( context, MaterialPageRoute( - builder: (_) => DnsPage( - profile: proxyProfile, - changed: () => setState(() => proxyDraftChanged = true), - ), + builder: (_) => + DnsPage(profile: proxyProfile, changed: proxyChanged), ), ), ), @@ -1174,6 +1297,7 @@ class _LabScreenState extends State { if (!mounted || busy || subscriptionUpdating || + proxySavesPending > 0 || savedProxyJson != jsonEncode(proxyProfile.toJson()) || !profileSupported) { return; @@ -1241,42 +1365,69 @@ class _LabScreenState extends State { } Future 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('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('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( + (_) {}, + onError: (Object error, StackTrace trace) {}, + ); + await job; + } + + void proxyChanged() { + if (!mounted) return; + setState(() => proxyDraftChanged = running); + unawaited( + saveProxyProfile().catchError((Object _) { + log('自动保存失败,请在代理页重试保存'); + }), + ); + } + + Future primaryConnection() async { + if (running && !proxyDraftChanged) { + await perform(stopActive); + } else { + await connectProxy(); + } } Future connectProxy() async { - if (runtimeMode != 'system_vpn') proxyProfile.validateConnection(); - if (running) { - final approved = await showDialog( - 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 { }); } 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 { 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 importConfig() async { final text = await showDialog( @@ -1322,7 +1485,16 @@ class _LabScreenState extends State { 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 { ], ), actions: [ - if (wide) + if (wide && proxyProfile.feature != 'proxy') Padding( padding: const EdgeInsets.only(right: 20), child: ConstrainedBox( diff --git a/apps/meshport_lab/lib/features/proxy_panel.dart b/apps/meshport_lab/lib/features/proxy_panel.dart index 821d689..e97f163 100644 --- a/apps/meshport_lab/lib/features/proxy_panel.dart +++ b/apps/meshport_lab/lib/features/proxy_panel.dart @@ -11,8 +11,10 @@ class ProxyPanel extends StatefulWidget { final String entry; final void Function(String) entryChanged; final bool busy, running; + final bool draftChanged, saving, saveFailed; final Future Function() save, connect; final VoidCallback changed; + final VoidCallback? showLogs; const ProxyPanel({ super.key, required this.profile, @@ -23,6 +25,10 @@ class ProxyPanel extends StatefulWidget { required this.save, required this.connect, required this.changed, + this.showLogs, + this.draftChanged = false, + this.saving = false, + this.saveFailed = false, }); @override State createState() => _ProxyPanelState(); @@ -33,13 +39,19 @@ class _ProxyPanelState extends State { bool working = false; String error = ''; void change(VoidCallback work) { - setState(work); + setState(() { + work(); + error = ''; + }); widget.changed(); } Future act(Future Function() work) async { if (working || widget.busy) return; - setState(() => working = true); + setState(() { + working = true; + error = ''; + }); try { await work(); } catch (e) { @@ -96,7 +108,7 @@ class _ProxyPanelState extends State { ); if (preview == null || !mounted) return; if (preview is ImportPreview) { - change(() => p.nodes.addAll(preview.nodes)); + change(() => p.addNodes(preview.nodes)); } if (preview is Map) { final sub = await Navigator.push>( @@ -134,7 +146,7 @@ class _ProxyPanelState extends State { options: node.options, ); } else { - p.nodes.add(node); + p.addNodes([node]); } }); return; @@ -146,7 +158,7 @@ class _ProxyPanelState extends State { if (node == null || !mounted) return; change( () => existing == null || existing.source != 'manual' - ? p.nodes.add(node) + ? p.addNodes([node]) : p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = node, ); } @@ -199,10 +211,7 @@ class _ProxyPanelState extends State { return; } change(() { - p.nodes.removeWhere((n) => n.source == source); - p.nodes.addAll(replacement); - if (removed) p.selectedId = null; - sub['updated'] = DateTime.now().toIso8601String(); + replaceSubscription(p, source, preview, DateTime.now()); }); } @@ -285,74 +294,95 @@ class _ProxyPanelState extends State { error, style: TextStyle(color: Theme.of(context).colorScheme.error), ), - section('代理与组网', [ - DropdownButtonFormField( - isExpanded: true, - initialValue: widget.entry, - decoration: const InputDecoration(labelText: '网络入口'), - items: const [ - DropdownMenuItem(value: 'application', child: Text('应用内 SOCKS5')), - DropdownMenuItem(value: 'system_vpn', child: Text('独立系统组网')), - DropdownMenuItem( - value: 'unified_vpn', - child: Text('统一 VPN · 单一 TUN'), - ), - ], - onChanged: disabled ? null : (v) => widget.entryChanged(v!), - ), - const Text( - '修改的是草稿。保存不会更改运行出口;连接或重连后生效。应用内模式通过 SOCKS5 127.0.0.1:10818 接入。', - ), + section('连接', [ DropdownButtonFormField( isExpanded: true, initialValue: p.feature, - decoration: const InputDecoration(labelText: '启用功能'), + decoration: const InputDecoration(labelText: '连接方式'), items: const [ DropdownMenuItem(value: 'mesh', child: Text('仅组网')), DropdownMenuItem(value: 'proxy', child: Text('仅代理')), DropdownMenuItem(value: 'combined', child: Text('代理 + 组网')), ], - onChanged: disabled ? null : (v) => change(() => p.feature = v!), - ), - DropdownButtonFormField( - isExpanded: true, - initialValue: p.mode, - decoration: const InputDecoration(labelText: '普通互联网流量模式'), - items: const [ - DropdownMenuItem(value: 'bypass_cn', child: Text('绕过中国大陆')), - DropdownMenuItem(value: 'rule', child: Text('自定义规则')), - DropdownMenuItem(value: 'global', child: Text('全局代理')), - DropdownMenuItem(value: 'direct', child: Text('直连')), - ], - onChanged: disabled || p.feature == 'mesh' + onChanged: disabled ? null - : (v) => change(() => p.mode = v!), + : (v) => change(() { + p.feature = v!; + if (widget.entry == 'system_vpn' && v != 'mesh') { + widget.entryChanged('unified_vpn'); + } + }), ), - if (widget.entry == 'system_vpn' && p.feature != 'mesh') - const Text('独立系统组网只支持仅组网;代理功能请选择统一 VPN 或应用内入口。'), Text( - p.mode == 'bypass_cn' && p.feature != 'mesh' - ? '中国大陆 IP 和普通私网直连,其余走所选代理;组网始终优先。内置 IP 规则集通过代理每 24 小时更新,首次下载失败会阻止连接。' - : '组网优先始终生效。全局/直连暂停普通规则;仅组网不接管互联网。', + p.feature == 'mesh' + ? '填写组网配置后连接。' + : p.mode == 'direct' + ? '直连模式无需代理节点。' + : '导入节点后连接即可,已提供默认加密 DNS。', + ), + if (p.feature != 'mesh') + DropdownButtonFormField( + isExpanded: true, + initialValue: p.mode, + decoration: const InputDecoration(labelText: '上网模式'), + items: const [ + DropdownMenuItem(value: 'bypass_cn', child: Text('绕过中国大陆')), + DropdownMenuItem(value: 'rule', child: Text('自定义规则')), + DropdownMenuItem(value: 'global', child: Text('全局代理')), + DropdownMenuItem(value: 'direct', child: Text('直连')), + ], + onChanged: disabled || p.feature == 'mesh' + ? null + : (v) => change(() => p.mode = v!), + ), + if (p.mode == 'bypass_cn' && p.feature != 'mesh') + const Text('中国大陆 IP 和普通私网直连,其余通过代理。首次使用会下载分流规则。'), + Text( + widget.entry == 'application' + ? '应用内代理:需要在使用它的软件中设置 SOCKS5 127.0.0.1:10818。' + : widget.entry == 'system_vpn' + ? '连接后接入组网地址。' + : '连接后设备流量自动接入。', ), Wrap( spacing: 8, runSpacing: 12, children: [ - FilledButton( - onPressed: - disabled || - (widget.entry == 'system_vpn' && p.feature != 'mesh') - ? null - : () => act(widget.connect), - child: Text(widget.running ? '重连使草稿生效' : '连接'), - ), - OutlinedButton( - onPressed: disabled ? null : () => act(widget.save), - child: const Text('安全保存配置'), + FilledButton.icon( + onPressed: disabled ? null : () => act(widget.connect), + icon: Icon( + widget.running && !widget.draftChanged + ? Icons.stop + : Icons.power_settings_new, + ), + label: Text( + widget.running + ? (widget.draftChanged ? '重连应用修改' : '断开连接') + : '连接', + ), ), + if (widget.showLogs != null) + OutlinedButton.icon( + onPressed: widget.showLogs, + icon: const Icon(Icons.monitor_heart_outlined), + label: const Text('诊断与日志'), + ), + if (widget.saveFailed) + OutlinedButton( + onPressed: disabled ? null : () => act(widget.save), + child: const Text('重试保存'), + ), ], ), + Text( + widget.saveFailed + ? '配置未保存,请重试。' + : widget.saving + ? '正在自动保存…' + : widget.running && widget.draftChanged + ? '修改已保存,重连后生效。' + : '配置修改后自动保存。', + ), ]), section('代理节点', [ Wrap( @@ -369,7 +399,7 @@ class _ProxyPanelState extends State { ), ], ), - if (p.nodes.isEmpty) const Text('尚未添加节点。全局代理或使用代理出口的规则需要选中一个节点。'), + if (p.nodes.isEmpty) const Text('导入第一个节点即可开始;多个节点时请选择一个出口。'), for (final node in p.nodes) ListTile( leading: IconButton( @@ -383,7 +413,11 @@ class _ProxyPanelState extends State { ? null : () => change(() => p.selectedId = node.id), ), - title: Text(node.name), + title: Text( + node.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), onTap: () => Navigator.push( context, MaterialPageRoute( @@ -434,53 +468,103 @@ class _ProxyPanelState extends State { ), ), ]), - section('分流与 DNS', [ - const Text('受管理规则:有效组网地址 → 组网;已失效的已知组网地址 → 拒绝;随后才应用普通规则与默认出口。'), - DropdownButtonFormField( - isExpanded: true, - initialValue: p.defaultAction, - decoration: const InputDecoration(labelText: '规则模式默认出口'), - items: const [ - DropdownMenuItem(value: 'proxy', child: Text('所选代理')), - DropdownMenuItem(value: 'direct', child: Text('直连')), - DropdownMenuItem(value: 'reject', child: Text('拒绝')), + Card( + child: ExpansionTile( + key: const PageStorageKey('proxy-advanced'), + title: const Text('高级设置'), + subtitle: const Text('网络入口、DNS 与分流规则'), + children: [ + Padding( + padding: const EdgeInsets.all(18), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + DropdownButtonFormField( + key: ValueKey('entry-${widget.entry}'), + isExpanded: true, + initialValue: widget.entry, + decoration: const InputDecoration(labelText: '网络入口'), + items: const [ + DropdownMenuItem( + value: 'application', + child: Text('应用内 SOCKS5'), + ), + DropdownMenuItem( + value: 'system_vpn', + child: Text('独立系统组网'), + ), + DropdownMenuItem( + value: 'unified_vpn', + child: Text('统一 VPN · 单一 TUN'), + ), + ], + onChanged: disabled + ? null + : (v) => widget.entryChanged(v!), + ), + const SizedBox(height: 18), + const Text('修改连接设置后,重连使其生效。'), + const SizedBox(height: 18), + const Text( + '受管理规则:有效组网地址 → 组网;已失效的已知组网地址 → 拒绝;随后才应用普通规则与默认出口。', + ), + DropdownButtonFormField( + isExpanded: true, + initialValue: p.defaultAction, + decoration: const InputDecoration(labelText: '规则模式默认出口'), + items: const [ + DropdownMenuItem(value: 'proxy', child: Text('所选代理')), + DropdownMenuItem(value: 'direct', child: Text('直连')), + DropdownMenuItem(value: 'reject', child: Text('拒绝')), + ], + onChanged: + disabled || p.mode != 'rule' || p.feature == 'mesh' + ? null + : (v) => change(() => p.defaultAction = v!), + ), + Text( + '${p.rules.length} 条普通规则 · ${p.mode == 'rule' && p.feature != 'mesh' ? '规则模式执行' : '已暂停'}', + ), + OutlinedButton( + onPressed: disabled + ? null + : () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => RulesPage( + profile: p, + changed: widget.changed, + ), + ), + ), + child: const Text('编辑普通规则'), + ), + Text( + '启动 DNS:${p.dnsServer} · 直连 DNS:${p.directDnsServer.isEmpty ? '启动 DNS' : p.directDnsServer} · 代理 DNS:${p.effectiveProxyDns}', + ), + OutlinedButton( + onPressed: disabled + ? null + : () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => DnsPage( + profile: p, + changed: widget.changed, + ), + ), + ), + child: const Text('编辑 DNS'), + ), + Text( + 'FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。', + ), + ], + ), + ), ], - onChanged: disabled || p.mode != 'rule' || p.feature == 'mesh' - ? null - : (v) => change(() => p.defaultAction = v!), ), - Text( - '${p.rules.length} 条普通规则 · ${p.mode == 'rule' && p.feature != 'mesh' ? '规则模式执行' : '已暂停'}', - ), - OutlinedButton( - onPressed: disabled - ? null - : () => Navigator.push( - context, - MaterialPageRoute( - builder: (_) => - RulesPage(profile: p, changed: widget.changed), - ), - ), - child: const Text('编辑普通规则'), - ), - Text( - '启动 DNS:${p.dnsServer} · 直连 DNS:${p.directDnsServer.isEmpty ? '启动 DNS' : p.directDnsServer} · 代理 DNS:${p.proxyDnsServer.isEmpty ? '待配置 · 代理模式必填' : p.proxyDnsServer}', - ), - OutlinedButton( - onPressed: disabled - ? null - : () => Navigator.push( - context, - MaterialPageRoute( - builder: (_) => - DnsPage(profile: p, changed: widget.changed), - ), - ), - child: const Text('编辑 DNS'), - ), - Text('FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。'), - ]), + ), ], ); } diff --git a/apps/meshport_lab/lib/features/runtime_diagnostics.dart b/apps/meshport_lab/lib/features/runtime_diagnostics.dart new file mode 100644 index 0000000..66bb808 --- /dev/null +++ b/apps/meshport_lab/lib/features/runtime_diagnostics.dart @@ -0,0 +1,44 @@ +/// Keeps known credentials for the whole session, including replaced drafts. +class DiagnosticRedactor { + final _secrets = {}; + + void remember(Object? value, {String? key}) { + if (value is Map) { + for (final entry in value.entries) { + remember(entry.value, key: '${entry.key}'); + } + } else if (value is Iterable) { + for (final item in value) { + remember(item, key: key); + } + } else if (value is String && + value.isNotEmpty && + { + 'password', + 'username', + 'uuid', + 'network_secret', + 'token', + 'private_key', + }.contains(key)) { + _secrets.add(value); + } + } + + String sanitize(String text) { + final secrets = _secrets.toList() + ..sort((a, b) => b.length.compareTo(a.length)); + for (final value in secrets) { + text = text.replaceAll(value, '[已隐藏]'); + } + text = text.replaceAllMapped( + RegExp(r'([a-zA-Z][a-zA-Z0-9+.-]*://)[^\s/]+@'), + (m) => '${m[1]}[已隐藏]@', + ); + text = text.replaceAllMapped( + RegExp(r'([a-zA-Z][a-zA-Z0-9+.-]*://[^\s?]+)\?[^\s]+'), + (m) => '${m[1]}?[已隐藏]', + ); + return text; + } +} diff --git a/apps/meshport_lab/macos/Podfile b/apps/meshport_lab/macos/Podfile index ff5ddb3..351e12a 100644 --- a/apps/meshport_lab/macos/Podfile +++ b/apps/meshport_lab/macos/Podfile @@ -1,4 +1,4 @@ -platform :osx, '10.15' +platform :osx, '12.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' @@ -38,5 +38,8 @@ end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_macos_build_settings(target) + target.build_configurations.each do |config| + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0' + end end end diff --git a/apps/meshport_lab/macos/Podfile.lock b/apps/meshport_lab/macos/Podfile.lock new file mode 100644 index 0000000..6630a5d --- /dev/null +++ b/apps/meshport_lab/macos/Podfile.lock @@ -0,0 +1,16 @@ +PODS: + - FlutterMacOS (1.0.0) + +DEPENDENCIES: + - FlutterMacOS (from `Flutter/ephemeral`) + +EXTERNAL SOURCES: + FlutterMacOS: + :path: Flutter/ephemeral + +SPEC CHECKSUMS: + FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 + +PODFILE CHECKSUM: 13edfb9e70ac3646927b8e6c9a212ad1d0fa29b2 + +COCOAPODS: 1.16.2 diff --git a/apps/meshport_lab/macos/Runner.xcodeproj/project.pbxproj b/apps/meshport_lab/macos/Runner.xcodeproj/project.pbxproj index a6e4ab6..540db7c 100644 --- a/apps/meshport_lab/macos/Runner.xcodeproj/project.pbxproj +++ b/apps/meshport_lab/macos/Runner.xcodeproj/project.pbxproj @@ -27,6 +27,8 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 4AB602CD95E220C185C9978C /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */; }; + B0B2671181DD147C22F9DA95 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7A55BFDF956E46C7632C102B /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -60,11 +62,13 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 092517D44FE622E53982B8F7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* meshport_lab.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "meshport_lab.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10ED2044A3C60003C045 /* meshport_lab.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = meshport_lab.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; @@ -76,8 +80,14 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 7A18F7D923A92E299909B27F /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 7A55BFDF956E46C7632C102B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 927C0C870CC973445A7543D6 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -85,6 +95,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 4AB602CD95E220C185C9978C /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -92,6 +103,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + B0B2671181DD147C22F9DA95 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -125,6 +137,7 @@ 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, + 7A80F7A78DF7A6F1790E273C /* Pods */, ); sourceTree = ""; }; @@ -172,9 +185,25 @@ path = Runner; sourceTree = ""; }; + 7A80F7A78DF7A6F1790E273C /* Pods */ = { + isa = PBXGroup; + children = ( + 092517D44FE622E53982B8F7 /* Pods-Runner.debug.xcconfig */, + 927C0C870CC973445A7543D6 /* Pods-Runner.release.xcconfig */, + 7A18F7D923A92E299909B27F /* Pods-Runner.profile.xcconfig */, + 393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */, + 0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */, + 671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( + 7A55BFDF956E46C7632C102B /* Pods_Runner.framework */, + BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -186,6 +215,7 @@ isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( + 29CF92A05BAD308ACBBCF0A7 /* [CP] Check Pods Manifest.lock */, 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, @@ -204,6 +234,7 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + 49184CD3D43FEC521263B28B /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -291,6 +322,28 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 29CF92A05BAD308ACBBCF0A7 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -329,6 +382,28 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; + 49184CD3D43FEC521263B28B /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -380,6 +455,7 @@ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -394,6 +470,7 @@ }; 331C80DC294CF71000263BE5 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -408,6 +485,7 @@ }; 331C80DD294CF71000263BE5 /* Profile */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -461,7 +539,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -543,7 +621,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -593,7 +671,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/apps/meshport_lab/macos/Runner.xcworkspace/contents.xcworkspacedata b/apps/meshport_lab/macos/Runner.xcworkspace/contents.xcworkspacedata index 1d526a1..21a3cc1 100644 --- a/apps/meshport_lab/macos/Runner.xcworkspace/contents.xcworkspacedata +++ b/apps/meshport_lab/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/apps/meshport_lab/macos/Runner/MainFlutterWindow.swift b/apps/meshport_lab/macos/Runner/MainFlutterWindow.swift index 09933a2..fb20150 100644 --- a/apps/meshport_lab/macos/Runner/MainFlutterWindow.swift +++ b/apps/meshport_lab/macos/Runner/MainFlutterWindow.swift @@ -6,8 +6,10 @@ import UniformTypeIdentifiers import AVFoundation import Vision import ImageIO +import OSLog class MainFlutterWindow: NSWindow { + private let runtimeLogger = Logger(subsystem: "com.example.meshportLab", category: "Runtime") private var vpnChannel: FlutterMethodChannel? private var qrScanner: MeshQRScanner? private var importing = false @@ -102,6 +104,14 @@ class MainFlutterWindow: NSWindow { return ["login_status":status,"auto_connect":UserDefaults.standard.bool(forKey:"MeshPort.autoConnect")] } private func handleCapabilities(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Bool { + if call.method == "runtime_log" { + guard let message = call.arguments as? String, message.utf8.count <= 8192 else { + result(FlutterError(code: "BAD_LOG", message: "Invalid diagnostic event", details: nil)); return true + } + // Flutter sends only credential-redacted diagnostic events, never profiles. + runtimeLogger.notice("\(message, privacy: .public)") + result(nil); return true + } if call.method == "startup_status" { result(startupStatus()); return true } if call.method == "set_startup" { guard let args = call.arguments as? [String:Any] else { result(FlutterError(code:"BAD_ARGUMENT",message:"Invalid preferences",details:nil));return true } diff --git a/apps/meshport_lab/test/advanced_profile_test.dart b/apps/meshport_lab/test/advanced_profile_test.dart index c25256d..068a7de 100644 --- a/apps/meshport_lab/test/advanced_profile_test.dart +++ b/apps/meshport_lab/test/advanced_profile_test.dart @@ -4,22 +4,42 @@ import 'package:meshport_client_core/meshport_client_core.dart'; import 'package:meshport_lab/features/configuration_pages.dart'; void main() { - test( - 'client protects DNS and requires explicit resolver before connecting', - () { - final p = ProxyProfile(); - expect(p.runtime()['dns_protection'], true); - expect(p.validateConnection, throwsStateError); - p.proxyDnsServer = 'tls://resolver.example'; - expect(p.validateConnection, returnsNormally); - p.proxyDnsServer = ''; - p.mode = 'direct'; - expect(p.validateConnection, returnsNormally); - p.mode = 'global'; - p.feature = 'mesh'; - expect(p.validateConnection, returnsNormally); - }, - ); + test('client supplies encrypted default DNS and protects proxy queries', () { + final p = ProxyProfile(); + expect(p.runtime()['dns_protection'], true); + expect(p.validateConnection, throwsFormatException); + p.nodes = importProxyNodes('socks://127.0.0.1:1080').nodes; + p.selectedId = p.nodes.single.id; + p.proxyDnsServer = 'tls://resolver.example'; + expect(p.validateConnection, returnsNormally); + p.proxyDnsServer = ''; + expect(p.runtime()['proxy_dns_server'], ProxyProfile.defaultProxyDns); + expect(p.validateConnection, returnsNormally); + p.mode = 'direct'; + expect(p.validateConnection, returnsNormally); + p.mode = 'global'; + p.feature = 'mesh'; + expect(p.validateConnection, returnsNormally); + }); + + test('proxy requires a selected node, while direct and mesh do not', () { + final p = ProxyProfile()..proxyDnsServer = 'tls://resolver.example'; + for (final mode in ['rule', 'global', 'bypass_cn']) { + p.mode = mode; + expect(p.validateConnection, throwsFormatException); + } + p.nodes = importProxyNodes('socks://127.0.0.1:1080').nodes; + p.selectedId = 'deleted-node'; + expect(p.validateConnection, throwsFormatException); + p.selectedId = p.nodes.single.id; + expect(p.validateConnection, returnsNormally); + p.nodes.clear(); + p.mode = 'direct'; + expect(p.validateConnection, returnsNormally); + p.mode = 'global'; + p.feature = 'mesh'; + expect(p.validateConnection, returnsNormally); + }); test('China bypass mode persists without rewriting custom rules', () { final p = ProxyProfile() diff --git a/apps/meshport_lab/test/runtime_diagnostics_test.dart b/apps/meshport_lab/test/runtime_diagnostics_test.dart new file mode 100644 index 0000000..f965bfd --- /dev/null +++ b/apps/meshport_lab/test/runtime_diagnostics_test.dart @@ -0,0 +1,40 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshport_lab/features/runtime_diagnostics.dart'; + +void main() { + test('diagnostics redact nested credentials and retain replaced secrets', () { + final redactor = DiagnosticRedactor(); + redactor.remember({ + 'network_secret': 'mesh-secret', + 'nodes': [ + { + 'options': { + 'username': 'proxy-user', + 'password': 'proxy-password', + 'uuid': '00000000-0000-0000-0000-000000000001', + }, + }, + ], + }); + redactor.remember({'password': 'replacement-password'}); + final text = redactor.sanitize( + 'mesh-secret proxy-user proxy-password replacement-password ' + '00000000-0000-0000-0000-000000000001 ' + 'socks://other-user:other-pass@proxy.example:1080 ' + 'https://example.test/sub?token=subscription-secret', + ); + for (final secret in [ + 'mesh-secret', + 'proxy-user', + 'proxy-password', + 'replacement-password', + '00000000-0000-0000-0000-000000000001', + 'other-user', + 'other-pass', + 'subscription-secret', + ]) { + expect(text, isNot(contains(secret))); + } + expect(text, contains('proxy.example:1080')); + }); +} diff --git a/apps/meshport_lab/test/simple_connection_test.dart b/apps/meshport_lab/test/simple_connection_test.dart new file mode 100644 index 0000000..06086c1 --- /dev/null +++ b/apps/meshport_lab/test/simple_connection_test.dart @@ -0,0 +1,150 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshport_client_core/meshport_client_core.dart'; +import 'package:meshport_lab/features/lab_screen.dart'; + +void main() { + test('sharing links show decoded Unicode names', () { + for (final fragment in ['演示节点', '%E6%BC%94%E7%A4%BA%E8%8A%82%E7%82%B9']) { + expect( + importProxyNodes('socks5://127.0.0.1:1080#$fragment').nodes.single.name, + '演示节点', + ); + } + }); + test('blank and legacy DNS use default while custom resolver survives', () { + final p = ProxyProfile(); + p.addNodes(importProxyNodes('socks://127.0.0.1:1080').nodes); + p.proxyDnsServer = ' '; + expect(p.runtime()['proxy_dns_server'], ProxyProfile.defaultProxyDns); + expect(p.runtime()['dns_protection'], true); + expect(p.validateConnection, returnsNormally); + final legacy = p.toJson(); + (legacy['runtime'] as Map)['proxy_dns_server'] = ''; + expect( + ProxyProfile.fromJson(legacy).proxyDnsServer, + ProxyProfile.defaultProxyDns, + ); + p.proxyDnsServer = 'tls://resolver.example'; + expect(ProxyProfile.fromJson(p.toJson()).proxyDnsServer, p.proxyDnsServer); + }); + + test('only initial single node is selected automatically', () { + final p = ProxyProfile(); + p.addNodes(importProxyNodes('socks://127.0.0.1:1080').nodes); + final selected = p.selectedId; + expect(selected, p.nodes.single.id); + p.addNodes(importProxyNodes('socks://127.0.0.1:1081').nodes); + expect(p.selectedId, selected); + final multiple = ProxyProfile(); + multiple.addNodes( + importProxyNodes('socks://127.0.0.1:1080\nsocks://127.0.0.1:1081').nodes, + ); + expect(multiple.selectedId, isNull); + final subscription = ProxyProfile(); + replaceSubscription( + subscription, + 's', + importProxyNodes('socks://127.0.0.1:1080', source: 's'), + DateTime.now(), + ); + expect(subscription.selectedId, subscription.nodes.single.id); + replaceSubscription( + subscription, + 's', + importProxyNodes('socks://127.0.0.1:1081', source: 's'), + DateTime.now(), + ); + expect(subscription.selectedId, isNull); + }); + + const channel = MethodChannel('meshport/system_vpn'); + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + tearDown( + () => + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null), + ); + + Future openProxy(WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: LabScreen(initializeNative: false)), + ); + await tester.tap(find.text('代理').last); + await tester.pumpAndSettle(); + expect(find.text('仅代理'), findsOneWidget); + expect(find.text('网络入口'), findsNothing); + expect(find.text('编辑 DNS'), findsNothing); + } + + Future chooseMode(WidgetTester tester, String mode) async { + final field = find.byWidgetPredicate( + (w) => + w is DropdownButtonFormField && + w.decoration.labelText == '上网模式', + ); + await tester.ensureVisible(field); + await tester.tap(field); + await tester.pumpAndSettle(); + await tester.tap(find.text(mode).last); + await tester.pumpAndSettle(); + } + + testWidgets( + 'automatic saves serialize rapid edits and keep latest value', + (tester) async { + final first = Completer(); + final saves = >[]; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + if (call.method == 'save_proxy_profile') { + saves.add( + jsonDecode(call.arguments as String) as Map, + ); + if (saves.length == 1) await first.future; + } + return null; + }); + await openProxy(tester); + await chooseMode(tester, '直连'); + await chooseMode(tester, '全局代理'); + expect(saves.length, 1); + first.complete(); + await tester.pumpAndSettle(); + expect(saves.length, 2); + expect((saves.last['runtime'] as Map)['mode'], 'global'); + expect(find.text('正在自动保存…'), findsNothing); + expect(find.text('重试保存'), findsNothing); + }, + skip: !Platform.isMacOS, + ); + + testWidgets( + 'failed automatic save offers retry and clears after success', + (tester) async { + var fail = true; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + if (call.method == 'save_proxy_profile' && fail) { + throw PlatformException(code: 'KEYCHAIN_SAVE'); + } + return null; + }); + await openProxy(tester); + await chooseMode(tester, '直连'); + expect(find.text('重试保存'), findsOneWidget); + fail = false; + await tester.ensureVisible(find.text('重试保存')); + await tester.tap(find.text('重试保存')); + await tester.pumpAndSettle(); + expect(find.text('重试保存'), findsNothing); + expect(tester.takeException(), isNull); + }, + skip: !Platform.isMacOS, + ); +} diff --git a/apps/meshport_lab/test/widget_test.dart b/apps/meshport_lab/test/widget_test.dart index 374856e..b41e816 100644 --- a/apps/meshport_lab/test/widget_test.dart +++ b/apps/meshport_lab/test/widget_test.dart @@ -3,6 +3,36 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:meshport_lab/features/lab_screen.dart'; void main() { + testWidgets('connection explains missing node and clears stale errors', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp(home: LabScreen(initializeNative: false)), + ); + await tester.tap(find.text('代理').last); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('连接').last); + await tester.tap(find.text('连接').last); + await tester.pumpAndSettle(); + expect(find.textContaining('请先添加代理节点'), findsOneWidget); + + await tester.ensureVisible(find.text('诊断与日志')); + await tester.tap(find.text('诊断与日志')); + await tester.pumpAndSettle(); + expect(find.textContaining('[校验代理配置] 失败'), findsOneWidget); + expect(find.textContaining('入口=unified_vpn'), findsOneWidget); + await tester.pageBack(); + await tester.pumpAndSettle(); + + await tester.ensureVisible(find.text('全局代理').last); + await tester.tap(find.text('全局代理').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('直连').last); + await tester.pumpAndSettle(); + expect(find.textContaining('请先添加代理节点'), findsNothing); + expect(tester.takeException(), isNull); + }); + testWidgets('China bypass can be selected and switched to global', ( tester, ) async { @@ -14,7 +44,7 @@ void main() { final mode = find.byWidgetPredicate( (w) => w is DropdownButtonFormField && - w.decoration.labelText == '普通互联网流量模式', + w.decoration.labelText == '上网模式', ); await tester.ensureVisible(mode); await tester.tap(mode); @@ -52,7 +82,7 @@ void main() { ); await tester.tap(find.text('代理').last); await tester.pumpAndSettle(); - expect(find.text('普通互联网流量模式'), findsOneWidget); + expect(find.text('上网模式'), findsOneWidget); await tester.ensureVisible(find.text('导入与预览')); await tester.tap(find.text('导入与预览')); await tester.pumpAndSettle(); @@ -67,6 +97,13 @@ void main() { await tester.tap(find.text('确认导入')); await tester.pumpAndSettle(); expect(find.text('Preview'), findsOneWidget); - expect(find.text('安全保存配置'), findsOneWidget); + expect(find.byIcon(Icons.radio_button_checked), findsOneWidget); + expect(find.text('网络入口'), findsNothing); + expect(find.text('编辑 DNS'), findsNothing); + await tester.ensureVisible(find.text('高级设置')); + await tester.tap(find.text('高级设置')); + await tester.pumpAndSettle(); + expect(find.text('网络入口'), findsOneWidget); + expect(find.text('编辑 DNS'), findsOneWidget); }); } diff --git a/apps/meshport_lab/test_driver/integration_test.dart b/apps/meshport_lab/test_driver/integration_test.dart new file mode 100644 index 0000000..8a2b59a --- /dev/null +++ b/apps/meshport_lab/test_driver/integration_test.dart @@ -0,0 +1,3 @@ +import 'package:integration_test/integration_test_driver.dart'; + +Future main() => integrationDriver(timeout: const Duration(minutes: 15)); diff --git a/docs/android.md b/docs/android.md index 5a4a858..2e5a296 100644 --- a/docs/android.md +++ b/docs/android.md @@ -16,8 +16,9 @@ scripts/build-lab-android.sh --release - 应用内:通过 meshport_flutter SDK 的 TCP/UDP 接口通信,不创建系统 VPN。 - 系统 VPN:宿主请求用户授权,由前台 VpnService 创建虚拟网卡,将文件描述符交给 Rust 引擎。虚拟网段及符合规则的公告子网自动安装、更新和撤销,不需要填写远端子网。 +- 统一 VPN:通过 Android VpnService 建立 TUN,交给 sing-box 接入互联网代理和可选的组网 SOCKS 桥。首次启动默认“仅代理 / 全局代理 / 统一 VPN”;首次导入单个节点自动选中,DNS 默认 `https://cloudflare-dns.com/dns-query`。原有配置与自定义 DNS 保留。设置自动保存,运行中修改需要点击“重连应用修改”。 -外层连接通过 VpnService.protect 排除在自己的 VPN 之外。系统模式不配置默认路由或 DNS;IPv6 保留系统通路,当前虚拟网络数据面为 IPv4。其他 Android VPN 与此系统 VPN 不能同时作为当前 VPN 运行。 +外层连接通过 VpnService.protect 排除在自己的 VPN 之外。仅组网的系统模式不配置默认路由或 DNS;IPv6 保留系统通路,当前虚拟网络数据面为 IPv4。统一 VPN 的互联网模式接管 IPv4/IPv6 默认路由和 DNS,并跟踪底层物理网络。其他 Android VPN 不能同时作为当前 VPN 运行。 VPN 建立和路由更新会等待 Android ConnectivityService 发布匹配的虚拟地址及路由,再报告就绪,避免新连接提前使用物理源地址。JNI 使用库名链接 Rust 动态库,不携带构建机绝对路径;系统模式启用受保护的 DNS resolver,数字 IP 不经过 DNS 查询。 @@ -32,12 +33,29 @@ integration_test/android_network_test.dart 使用隔离网络身份和 USB 转 scripts/cargo-local.sh run -p meshport-easytier --example android_test_server adb reverse tcp:18080 tcp:18080 adb reverse tcp:18081 tcp:18081 -cd apps/meshport_lab -flutter test integration_test/android_network_test.dart -d DEVICE_SERIAL +# Use a normal APK and its matching build number; restore it automatically. +sh scripts/test-android-device.sh DEVICE_SERIAL NORMAL_APK BUILD_NUMBER network ``` 测试中的系统 VPN 授权必须由用户在手机上完成。测试结束应删除两条 adb reverse 并关闭夹具。测试使用固定地址,不覆盖公网打洞、移动网络切换、长期后台存活或实际游戏负载。 +互联网统一 VPN 使用单独的隔离 SOCKS5 夹具,手机与电脑须在同一局域网。仅接受明确指定的手机 IP,测试地址返回确定的 TCP/UDP 回显,公共 HTTPS 和默认 DoH 使用真实上游;不读取或修改用户节点配置。 + +```sh +python3 scripts/android-proxy-fixture.py --host COMPUTER_LAN_IP --device PHONE_LAN_IP +sh scripts/test-android-device.sh DEVICE_SERIAL NORMAL_APK BUILD_NUMBER proxy COMPUTER_LAN_IP +``` + +覆盖普通系统 TCP/UDP、TUN DNS、默认加密 DNS、证书验证的 HTTPS、两次启停与断开恢复。实际结果记录在 [开发验证](development-validation.md),脚本存在不代表设备已通过。包装脚本用 `flutter drive --keep-app-running` 避免 Flutter 默认卸载测试 APP;结束或失败时覆盖安装并打开普通 APK,保留已有存储。测试完成后停止夹具。直接使用 `flutter test` 会在结束时卸载测试 APP,不能用于保留用户配置的测试。 + +## Android 连接日志 + +APP 的“诊断与日志”记录配置校验、授权、引擎启动与运行错误。Flutter 在输出前隐藏已知凭据,Android 同步到 `MeshPortRuntime`;VPN 服务的阶段事件使用 `MeshPortVPN`,不打印完整配置。可以通过以下命令采集本次连接事件: + +```sh +adb -s DEVICE_SERIAL logcat -s MeshPortRuntime:I MeshPortVPN:I AndroidRuntime:E +``` + 2026-10-10 在 OPPO PJZ110(API 37、4 KB 页面)完整通过:加密配置保存/重新读取/删除、SDK 应用内 TCP/UDP、Java 与 Dart 普通系统 TCP/UDP 经 VPN 通信、公告子网自动安装及撤销。隔离测试不修改用户配置。公网打洞、长期后台运行及移动网络切换尚未验证。 ## 自用默认配置 diff --git a/docs/development-validation.md b/docs/development-validation.md index c364b53..c04126f 100644 --- a/docs/development-validation.md +++ b/docs/development-validation.md @@ -1,5 +1,31 @@ # 2026-10-11 开发验证记录 +## 2026-10-12:互联网统一 VPN 断网排查 + +实际用户节点的独立 HTTPS 检测返回 HTTP 204;关闭统一 VPN 后普通 HTTPS 同样成功。启用统一 VPN 后,自动采样确认普通域名解析超时、本机 SOCKS 返回网络不可达、固定 IP HTTPS 被重置。退出测试 APP 后物理默认路由和原有 DNS 恢复。 + +新增按引擎隔离、最多 32 条的运行时警告/错误记录,在内存中脱敏节点认证及 URL 凭据后投影至客户端日志;不将原始上游错误写入 stderr 或日志文件。实际错误明确为启动 DNS 的 `dial udp 1.1.1.1:53: connect: network is unreachable`,随后导致 `cloudflare-dns.com` 与网页解析失败。 + +修复为在接管全局路由前安装物理接口的 IPv4 scoped default route,供绑定物理接口的启动 DNS 和代理外层 socket 使用。复用既有 scoped route,停止时只删除本次创建且网关/接口仍匹配的路由。APP 已构建、签名验证通过;Rust 路由所有权测试、Go 并发测试及日志脱敏回归通过;Flutter 全量测试 42 项通过、6 项环境测试跳过。产物为 `outputs/macos/MeshPort-0.1.0-unified-vpn-fix.app` 及同目录 ZIP。 + +**实际运行验收通过**:2026-10-12 04:17(America/Los_Angeles),使用用户原有的 VLESS/Reality 节点、绕过中国大陆及代理加密 DNS 配置,统一 VPN 启用时,物理接口绑定 UDP connect 成功;普通 HTTPS、SOCKS5h HTTPS 和固定 IP HTTPS 均返回 HTTP 204;TUN DNS 返回有效 A 记录。采样后退出测试 APP,原有默认路由和 DNS 恢复,新增 scoped default 已移除,普通 HTTPS 再次返回 HTTP 204。短时验证覆盖本次 IPv4 互联网断网问题;IPv6 端到端、网络切换和长期运行仍需验证。 + +失败证据保留于本机 `outputs/validation/macos-internet-tun-runtime-failure-20261012.log` 和 `macos-internet-tun-runtime-errors-20261012.log`,原始运行采样不随源码上传。 + +修复成功证据保留于本机 `outputs/validation/macos-internet-tun-fixed-20261012.log`。 + +## 2026-10-11:代理连接诊断版 + +- 修复代理 DNS 缺失时具体错误被替换成通用“操作失败”的问题;代理模式新增出口选择校验,重试清除旧错误。 +- 代理页新增“查看连接日志”。记录入口、功能、模式、节点数量、DNS 是否配置,以及配置校验、动态库加载、helper 授权、引擎启动的阶段与耗时。认证值在写入前脱敏,已替换草稿的凭据仍保持隐藏;不输出完整配置。 +- Go 引擎初始化/启动失败返回固定的阶段与错误分类,如 `listen_port_in_use`、`permission_denied`、`dns_resolution_failed`;不暴露上游错误中的认证或 URL 内容。 +- macOS 通过 `OSLog` 同步记录脱敏事件,subsystem 为 `com.example.meshportLab`,category 为 `Runtime`。真实启动和缺少 DNS 的失败均已在 APP 日志页及系统日志中验证。 +- 从固定 EasyTier 提交恢复被 `**/build/` 忽略而遗漏的三个构建源码文件,并修正忽略规则。适配本机 Xcode,macOS 最低版本为 12.0。 +- Flutter 全量测试 42 项通过、6 项原生/环境依赖测试跳过;另启用 Rust/Go 动态库的配置往返与联合生命周期测试 11 项通过。Flutter analyze、Go `test -race ./...`、Go vet、APP 深度签名验证均通过。 +- 产物:`outputs/macos/MeshPort-0.1.0-proxy-diagnostics.app`,开发调试签名,构建号 `20261012143711`;ZIP 位于同目录。已启动该产物,用户将自行导入真实节点;尚未验证用户代理的互联网通信。 + +实际日志证据保留于本机 `outputs/validation/proxy-diagnostics-macos-20261011.log`。 + 本轮继续实现统一 TUN、主要 24 页 UI 和 FakeIP。Android 真机验证按用户要求暂缓,没有安装 APK,也没有替换正在使用的 macOS APP。 | 检查 | 结果和范围 | @@ -57,3 +83,38 @@ FakeIP 缓存在同一上下文重建时保留,最终释放清理,跨会话 - Rust SDK/helper 与 macOS APP 构建通过,开发签名深度验证通过。 - 修复版:`outputs/macos/MeshPort-0.1.0-config-fix.app`。 - 经用户授权,将旧窗口中的代理配置保存到本机钥匙串;修复版重新启动后实际读到现有节点。当前代理 DNS 尚未填写,实际互联网 SOCKS5 验证等待用户选择 DNS。v2rayN 保持运行,未切换系统路由。 + +## 2026-10-12:互联网连接修复与配置简化 + +macOS 互联网统一 VPN 的实际故障是物理出口绑定后的 UDP DNS 请求返回 `network is unreachable`。helper 在安装 TUN 路由前补充并验证物理接口的 scoped default route;复用已有路由,只清理自己创建且仍匹配原网关/接口的路由。此前实测用户节点通过普通 HTTPS、SOCKS5 HTTPS、固定 IP HTTPS 和 TUN DNS 检查,停止后原 DNS、默认路由和互联网访问恢复。本机证据为 `outputs/validation/macos-internet-tun-fixed-20261012.log`。该修复的 IPv6、网络切换和长时间运行仍未验收。 + +本次简化配置与界面: + +- 首次启动默认“仅代理 / 全局代理”,macOS 和 Android 默认统一 VPN。恢复已有功能、节点和自定义 DNS;旧仅组网入口归一为组网功能。 +- 代理 DNS 默认 `https://cloudflare-dns.com/dns-query`;缺失或留空均使用此默认值,自定义值保留。直连模式仍使用直连 DNS。 +- 首次仅导入一个节点时自动选中;多个节点由用户选择。订阅更新删除原出口时不自动换到另一节点。 +- 配置修改自动按顺序保存,失败显示“重试保存”;运行中修改提示“重连应用修改”,由用户执行后才改变运行配置。概览与代理页共用连接动作。 +- 仅代理概览只展示连接信息、节点管理、日志和最近事件;网络入口、DNS/FakeIP、分流规则折叠到“高级设置”,组网高级配置同样折叠。分享链接的中文名称正确解码。 + +验证:Flutter analyze 无问题;启用 Rust/Go 动态库的 Flutter 全量测试 50 项通过,3 项需要专门开关的旧原生/UI 测试跳过。覆盖默认 DNS、首次节点选择、连续编辑保存顺序、保存失败重试、原生生命周期及不同窗口宽度。macOS 隔离预览窗口检查了概览、代理页和导入页布局;自动化输入受本机输入法影响,节点导入/选择通过 widget 测试验收。预览使用 `MESHPORT_UI_PREVIEW=true`,不读写用户配置、不初始化原生连接;交付 APP 未开启此标记。 + +产物:`outputs/macos/MeshPort-0.1.0-simple.app` 及同名 ZIP,包含 Rust/Go 动态库和 VPN helper;macOS 构建与深度严格签名验证通过。使用本机开发签名,未公证。本轮界面简化未再次切换实际系统 VPN;Android 共用配置逻辑已更新,未进行真机连接验证。 + +## 2026-10-12:Android 真机统一代理修复 + +MI 8 Lite(Android 15 / API 35、ARM64、4 KB 页面)完成新一轮真机验证。首次测试等待授权超时后,Flutter 自动卸载了临时 APP;已改用保留测试包并自动恢复普通 APP 的包装脚本,失败和成功均恢复安装,保留用户存储。 + +统一 VPN 实际复现“引擎 Running 但无法连接”,错误为 `no available network interface`。平台适配器的 Initialize 现在先发布物理接口列表给 sing-box NetworkManager。新增 Go 回归使用真实出站拨号:修复前复现同样错误,修复后 TCP 回显和 TCP/UDP socket 保护调用检查通过;Go 全量 race 与 vet 通过。 + +- 系统组网 VPN:加密存储、应用内 TCP/UDP、Java/Dart 普通系统 TCP/UDP、公告子网安装与撤销全部通过。 +- 互联网统一 VPN:默认 Cloudflare DoH、普通 TCP/UDP、HTTPS 204、两次启动/停止和停止后 HTTPS 恢复全部通过。仅代理启动不依赖组网 TOML;首次单节点自动选择也在真机测试执行。 +- Android 增加脱敏 MeshPortRuntime 事件和 VPN 创建、引擎就绪、清理阶段日志;仅代理启动提示改为导入节点后连接。 +- 未保存测试节点;已退出测试 VPN、停止两套本机夹具并移除 adb reverse,手机恢复普通 APP。 + +详细结果和日志见 [Android 验证记录](../outputs/validation/android-client-20261012.md)。测试使用 Wi-Fi 与隔离 SOCKS5 出口;用户自己的代理节点、移动网络切换、长时间后台和 IPv6 上网仍需后续验证。 + +最终交付 `outputs/android/MeshPort-0.1.0-1791811912-debug.apk`,普通入口,开发签名,已安装并在 MI 8 Lite 前台打开;APK v2 签名、16 KB zipalign 校验通过。最终 Flutter analyze 无问题、50 项回归通过(3 项专门开关测试跳过)。 + +### Android 扫码方向修复 + +用户反馈点击相机扫码后变成横屏。ZXing 4.3.0 的 CaptureActivity 库 manifest 默认 `sensorLandscape`;原有 `setOrientationLocked(false)` 只关闭额外锁定,不覆盖 manifest 的横屏要求。宿主 manifest 现在覆盖为 `fullUser`,跟随用户旋转设置,保留原有关闭方向锁定选项。合并 manifest 已确认 CaptureActivity 为 fullUser;构建、签名和 16 KB zipalign 检查通过。`outputs/android/MeshPort-0.1.0-1791812247-debug.apk` 已覆盖安装并打开,保留现有配置。此次只修改方向配置,未自动开启手机相机或扫描用户二维码。 diff --git a/docs/stability-testing.md b/docs/stability-testing.md new file mode 100644 index 0000000..a151f86 --- /dev/null +++ b/docs/stability-testing.md @@ -0,0 +1,42 @@ +# MeshPort 稳定性验证 + +当前已完成短时 macOS 联网及 Android 真机 TCP/UDP、DNS、HTTPS、启停和清理验证;尚未完成长时间后台与物理网络切换验收。短时通过不能替代稳定性验收。 + +## 测试安排 + +| 阶段 | 操作 | 观察与通过条件 | +| --- | --- | --- | +| 启停回归 | 同一配置连接/断开 50 次,组网、代理、联合模式分别执行 | 无崩溃、无遗留 VPN;每次可重新连接;断开后普通上网恢复 | +| 连续通信 | 连续运行 1 小时,每 30 秒执行 HTTPS 请求、组网 TCP 和 UDP 回显 | 记录成功率、延迟和错误阶段;与未使用 MeshPort 的网络基线比较,区分公网故障与 APP 故障 | +| 后台运行 | 连续 8 小时,包含锁屏、切换 APP、恢复前台 | 后台连接符合预期;恢复后状态准确,能通信或明确报告连接失败;无永久卡在“已连接但无网” | +| 网络变化 | Wi-Fi 断开/恢复、两个 Wi-Fi 间切换、有移动数据的设备切换 Wi-Fi/移动网络,各 10 次 | 记录恢复时间;可自动恢复或明确提示重连;代理出站不进入自身 VPN | +| 故障恢复 | 关闭测试代理/组网网关、使 DNS 不可达,再恢复服务 | 有可定位的日志;失败不偷偷切换出口或泄漏组网流量;恢复或重连后可用 | +| 资源与清理 | 比较启动前、运行中、重复启停后、停止后的资源 | 排除启动预热与缓存后,内存、线程、FD 不持续增长;停止后无测试 TUN、路由或 DNS 遗留 | + +先执行短时测试,再逐步延长。不要用全部无响应的数据推断 APP 故障;应保留同一网络上的基线、测试节点可达性和发生时间。 + +## 使用现有测试 + +- 应用内 UDP 质量页可记录 RTT、P95、抖动和未响应率,需要远端回显服务;它不能代表系统 VPN 的稳定性。 +- Android 系统组网与统一代理真机脚本见 [Android 文档](android.md)。使用 `scripts/test-android-device.sh`,结束时自动恢复普通 APP,避免 Flutter 直接测试后卸载用户 APP。 +- 当前统一代理真机脚本只重复两次启停;50 次、8 小时后台及网络切换仍需单独执行并记录。 +- macOS 检查连接前后的默认路由、物理 scoped route 和 DNS;只清理测试会话拥有的路由。 + +## Android 采样 + +```sh +# 记录脱敏运行阶段,不采集全部系统日志。 +adb -s DEVICE_SERIAL logcat -s MeshPortRuntime:I MeshPortVPN:I AndroidRuntime:E + +# 在各阶段重复采样,比对 PSS、线程和 FD 趋势。 +adb -s DEVICE_SERIAL shell dumpsys meminfo com.example.meshport_lab +adb -s DEVICE_SERIAL shell pidof com.example.meshport_lab +adb -s DEVICE_SERIAL shell ls /proc/APP_PID/fd +adb -s DEVICE_SERIAL shell ls /proc/APP_PID/task +``` + +部分设备限制读取 `/proc`,这时记录可获取的 meminfo 与进程状态;不要为了采样关闭设备安全保护。原始日志留在本机 `outputs/validation`,Git 只提交不含私人配置的验证摘要。 + +## 验收记录 + +每次记录 APP 构建号、系统版本、入口与功能、节点协议、网络类型、时长、请求数量/失败数量、延迟、内存趋势、恢复时间和遗留资源检查。测试报告区分“已通过”“失败”“未执行”;只有三种入口及目标平台的相关场景完成后,才对对应范围给出稳定性结论。 diff --git a/engines/singbox/bridge/diagnostics.go b/engines/singbox/bridge/diagnostics.go new file mode 100644 index 0000000..ca3a6bc --- /dev/null +++ b/engines/singbox/bridge/diagnostics.go @@ -0,0 +1,39 @@ +package bridge + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "strings" + "syscall" +) + +// Return fixed diagnostic categories, never upstream messages containing node +// credentials, subscription URLs, or the generated configuration. +func startupFailure(stage string, cause error) error { + code := "engine_failure" + var dnsError *net.DNSError + var networkError net.Error + message := strings.ToLower(cause.Error()) + switch { + case errors.Is(cause, syscall.EADDRINUSE): + code = "listen_port_in_use" + case errors.Is(cause, os.ErrPermission): + code = "permission_denied" + case errors.Is(cause, context.DeadlineExceeded) || errors.As(cause, &networkError) && networkError.Timeout(): + code = "network_timeout" + case errors.As(cause, &dnsError): + code = "dns_resolution_failed" + case strings.Contains(message, "certificate") || strings.Contains(message, "x509"): + code = "tls_certificate_failed" + case strings.Contains(message, "rule-set") || strings.Contains(message, "rule set"): + code = "rule_set_failed" + case strings.Contains(message, "connection refused"): + code = "connection_refused" + case strings.Contains(message, "unsupported") || strings.Contains(message, "unknown") || strings.Contains(message, "invalid"): + code = "invalid_engine_options" + } + return fmt.Errorf("proxy startup failed [stage=%s, code=%s]", stage, code) +} diff --git a/engines/singbox/bridge/diagnostics_test.go b/engines/singbox/bridge/diagnostics_test.go new file mode 100644 index 0000000..c2da237 --- /dev/null +++ b/engines/singbox/bridge/diagnostics_test.go @@ -0,0 +1,23 @@ +package bridge + +import ( + "errors" + "strings" + "testing" +) + +func TestStartupDiagnosticsDoNotExposeUpstreamCredentials(t *testing.T) { + for _, message := range []string{ + "unknown option password=test-secret https://example.test/sub?token=test-token", + "rule-set download https://user:test-secret@example.test/sub?token=test-token", + "unclassified failure with test-secret and test-token", + } { + result := startupFailure("initialize_engine", errors.New(message)).Error() + if strings.Contains(result, "test-secret") || strings.Contains(result, "test-token") || strings.Contains(result, "example.test") { + t.Fatalf("diagnostic exposed upstream contents: %s", result) + } + if !strings.Contains(result, "stage=initialize_engine") { + t.Fatal("diagnostic omitted failing stage") + } + } +} diff --git a/engines/singbox/bridge/engine.go b/engines/singbox/bridge/engine.go index 184dbae..2689f25 100644 --- a/engines/singbox/bridge/engine.go +++ b/engines/singbox/bridge/engine.go @@ -60,11 +60,13 @@ func registryContext(ctx context.Context) context.Context { } type Snapshot struct { - State string `json:"state"` - Version string `json:"version"` + State string `json:"state"` + Version string `json:"version"` + RuntimeEvents []RuntimeEvent `json:"runtime_events,omitempty"` } type Engine struct { + runtimeLogs runtimeLogs selfTestTrace bool startupCause error // Private diagnostic for package tests; never returned over ABI. // Protector must be installed before starting a host TUN. @@ -89,7 +91,7 @@ func (e *Engine) Snapshot() Snapshot { if state == "Running" && e.ctx.Err() != nil { state = "Failed" } - return Snapshot{State: state, Version: "1.14.3"} + return Snapshot{State: state, Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()} } func (e *Engine) Start(parent context.Context, config Config) error { @@ -135,7 +137,7 @@ func (e *Engine) Start(parent context.Context, config Config) error { if err != nil { cancel() e.state = "Failed" - return errors.New("invalid managed engine configuration") + return startupFailure("decode_configuration", err) } if config.FakeIP || len(config.RuleSets) > 0 { if e.cacheDir == "" { @@ -148,19 +150,26 @@ func (e *Engine) Start(parent context.Context, config Config) error { } options.Experimental = &option.ExperimentalOptions{CacheFile: &option.CacheFileOptions{Enabled: true, Path: filepath.Join(e.cacheDir, "fakeip.db"), StoreFakeIP: config.FakeIP}} } + e.runtimeLogs.configure(config.Proxy) + // Collect bounded, credential-redacted warning/error events in memory. + // Raw upstream logs must never go to stderr or a user's log file. + if !e.selfTestTrace { + options.Log = &option.LogOptions{Level: "warn", Output: os.DevNull} + } instance, err := box.New(box.Options{Options: options, Context: ctx}) if err != nil { e.startupCause = err cancel() e.state = "Failed" - return errors.New("cannot initialize proxy engine") + return startupFailure("initialize_engine", err) } + instance.LogFactory().AttachPlatformWriter(&e.runtimeLogs) if err = instance.Start(); err != nil { e.startupCause = err _ = instance.Close() cancel() e.state = "Failed" - return errors.New("cannot start proxy engine") + return startupFailure("start_engine", err) } e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running" return nil diff --git a/engines/singbox/bridge/engine_test.go b/engines/singbox/bridge/engine_test.go index a8bd939..220fc9e 100644 --- a/engines/singbox/bridge/engine_test.go +++ b/engines/singbox/bridge/engine_test.go @@ -8,6 +8,7 @@ import ( "io" "net" "net/netip" + "strings" "testing" "time" ) @@ -88,8 +89,10 @@ func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) { if engine.Snapshot().State != "Stopped" { t.Fatal("initial state") } - if engine.Start(context.Background(), c) == nil { + if err := engine.Start(context.Background(), c); err == nil { t.Fatal("started on occupied port") + } else if !strings.Contains(err.Error(), "listen_port_in_use") { + t.Fatalf("missing safe occupied-port diagnostic: %v", err) } if engine.Snapshot().State != "Failed" { t.Fatal("failed start state") diff --git a/engines/singbox/bridge/platform.go b/engines/singbox/bridge/platform.go index 6a82664..084b6e1 100644 --- a/engines/singbox/bridge/platform.go +++ b/engines/singbox/bridge/platform.go @@ -24,7 +24,12 @@ type hostPlatform struct { monitor *hostMonitor } -func (p *hostPlatform) Initialize(adapter.NetworkManager) error { return nil } +func (p *hostPlatform) Initialize(manager adapter.NetworkManager) error { + // The host monitor already knows the physical default, but sing-box keeps + // its own selectable-interface list. Populate it before outbound startup. + // Android cannot fill this list via the restricted kernel network monitor. + return manager.UpdateInterfaces() +} func (p *hostPlatform) UsePlatformAutoDetectInterfaceControl() bool { return true } func (p *hostPlatform) AutoDetectInterfaceControl(fd int) error { if p.protect == nil { diff --git a/engines/singbox/bridge/platform_test.go b/engines/singbox/bridge/platform_test.go new file mode 100644 index 0000000..66df99f --- /dev/null +++ b/engines/singbox/bridge/platform_test.go @@ -0,0 +1,103 @@ +package bridge + +import ( + "context" + "io" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/sagernet/sing-box/adapter" + "github.com/sagernet/sing-box/common/dialer" + "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing-box/option" + "github.com/sagernet/sing-box/route" + "github.com/sagernet/sing/common/control" + M "github.com/sagernet/sing/common/metadata" + "github.com/sagernet/sing/service" +) + +// Exercise sing-box's real interface selection, which otherwise fails with +// "no available network interface" even though the host reports a default. +func TestHostPlatformInitialPhysicalNetwork(t *testing.T) { + interfaces, err := net.Interfaces() + if err != nil { + t.Fatal(err) + } + var physical net.Interface + for _, candidate := range interfaces { + if candidate.Flags&net.FlagUp != 0 && candidate.Flags&net.FlagLoopback == 0 { + physical = candidate + break + } + } + if physical.Index == 0 { + t.Skip("No active physical interface") + } + var protected atomic.Int32 + p := &hostPlatform{ + monitor: &hostMonitor{physical: &control.Interface{Name: physical.Name, Index: physical.Index, MTU: physical.MTU, Flags: physical.Flags}}, + protect: func(fd int) error { + if fd < 0 { + t.Fatal("Invalid protected fd") + } + protected.Add(1) + return nil + }, + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ctx = service.ContextWith[adapter.PlatformInterface](ctx, p) + manager, err := route.NewNetworkManager(ctx, log.NewNOPFactory().Logger(), option.RouteOptions{AutoDetectInterface: true}, option.DNSOptions{}) + if err != nil { + t.Fatal(err) + } + if err = p.Initialize(manager); err != nil { + t.Fatal(err) + } + ctx = service.ContextWith[adapter.NetworkManager](ctx, manager) + d, err := dialer.NewDefault(ctx, option.DialerOptions{}) + if err != nil { + t.Fatal(err) + } + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + go func() { + for { + c, err := listener.Accept() + if err != nil { + return + } + go func() { defer c.Close(); _, _ = io.Copy(c, c) }() + } + }() + conn, err := d.DialContext(ctx, "tcp", M.ParseSocksaddr(listener.Addr().String())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(3 * time.Second)) + if _, err = conn.Write([]byte("protected TCP")); err != nil { + t.Fatal(err) + } + data := make([]byte, len("protected TCP")) + if _, err = io.ReadFull(conn, data); err != nil { + t.Fatal(err) + } + if string(data) != "protected TCP" || protected.Load() == 0 { + t.Fatal("TCP bypassed socket protection or echo failed") + } + before := protected.Load() + udp, err := d.ListenPacket(ctx, M.ParseSocksaddr("127.0.0.1:12345")) + if err != nil { + t.Fatal(err) + } + defer udp.Close() + if protected.Load() <= before { + t.Fatal("UDP bypassed socket protection") + } +} diff --git a/engines/singbox/bridge/runtime_logs.go b/engines/singbox/bridge/runtime_logs.go new file mode 100644 index 0000000..7b86cb6 --- /dev/null +++ b/engines/singbox/bridge/runtime_logs.go @@ -0,0 +1,75 @@ +package bridge + +import ( + "regexp" + "sort" + "strings" + "sync" + + "github.com/sagernet/sing-box/log" +) + +type RuntimeEvent struct { + Sequence uint64 `json:"sequence"` + Message string `json:"message"` +} + +type runtimeLogs struct { + mu sync.Mutex + sequence uint64 + events []RuntimeEvent + secrets []string +} + +var logURLAuth = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://)[^\s/]+@`) +var logURLQuery = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://[^\s?]+)\?[^\s]+`) +var logANSI = regexp.MustCompile("\x1b\\[[0-9;]*m") + +func (r *runtimeLogs) configure(node map[string]any) { + r.mu.Lock() + defer r.mu.Unlock() + var remember func(map[string]any) + remember = func(values map[string]any) { + for key, value := range values { + if nested, ok := value.(map[string]any); ok { + remember(nested) + } + switch key { + case "password", "username", "uuid", "private_key", "token": + if text, ok := value.(string); ok && text != "" { + r.secrets = append(r.secrets, text) + } + } + } + } + remember(node) + sort.Slice(r.secrets, func(i, j int) bool { return len(r.secrets[i]) > len(r.secrets[j]) }) +} + +func (r *runtimeLogs) WriteMessage(level log.Level, message string) { + if level > log.LevelWarn { + return + } + r.mu.Lock() + defer r.mu.Unlock() + for _, value := range r.secrets { + message = strings.ReplaceAll(message, value, "[redacted]") + } + message = logURLAuth.ReplaceAllString(message, "${1}[redacted]@") + message = logURLQuery.ReplaceAllString(message, "${1}?[redacted]") + message = logANSI.ReplaceAllString(message, "") + if len(message) > 2048 { + message = string([]rune(message)[:min(512, len([]rune(message)))]) + "…" + } + r.sequence++ + r.events = append(r.events, RuntimeEvent{Sequence: r.sequence, Message: message}) + if len(r.events) > 32 { + r.events = append([]RuntimeEvent(nil), r.events[len(r.events)-32:]...) + } +} + +func (r *runtimeLogs) snapshot() []RuntimeEvent { + r.mu.Lock() + defer r.mu.Unlock() + return append([]RuntimeEvent(nil), r.events...) +} diff --git a/engines/singbox/bridge/runtime_logs_test.go b/engines/singbox/bridge/runtime_logs_test.go new file mode 100644 index 0000000..65d348f --- /dev/null +++ b/engines/singbox/bridge/runtime_logs_test.go @@ -0,0 +1,36 @@ +package bridge + +import ( + "github.com/sagernet/sing-box/log" + "strings" + "testing" +) + +func TestRuntimeLogsBoundedAndRedacted(t *testing.T) { + var logs runtimeLogs + logs.configure(map[string]any{"uuid": "secret-uuid", "password": "secret-password"}) + logs.WriteMessage(log.LevelInfo, "ignored") + for i := 0; i < 40; i++ { + logs.WriteMessage(log.LevelError, "failure secret-uuid secret-password https://u:p@example.test/?token=secret-token") + } + events := logs.snapshot() + if len(events) != 32 || events[0].Sequence != 9 { + t.Fatal("unbounded or incorrect log sequence") + } + for _, e := range events { + for _, secret := range []string{"secret-uuid", "secret-password", "secret-token", "u:p"} { + if strings.Contains(e.Message, secret) { + t.Fatal("runtime log exposed credential") + } + } + } +} + +func TestRuntimeLogsRedactOverlappingCredentialValues(t *testing.T) { + var logs runtimeLogs + logs.configure(map[string]any{"username": "secret", "password": "secret-credential"}) + logs.WriteMessage(log.LevelError, "authentication failed for secret-credential") + if strings.Contains(logs.snapshot()[0].Message, "credential") { + t.Fatal("short credential prevented full password redaction") + } +} diff --git a/outputs/validation/android-client-20261012.md b/outputs/validation/android-client-20261012.md new file mode 100644 index 0000000..d5eca61 --- /dev/null +++ b/outputs/validation/android-client-20261012.md @@ -0,0 +1,16 @@ +# Android 开发验证(2026-10-12) + +- 设备:MI 8 Lite,ARM64,Android 15 / API 35,页面大小 4096 字节。 +- 修复后联网验证包:`outputs/android/MeshPort-0.1.0-1791811765-debug.apk`。最终提示整理包:`outputs/android/MeshPort-0.1.0-1791811912-debug.apk`,已安装并打开,附 SHA-256。 +- 构建成功;APK v2 签名验证、zipalign 16 KB 检查通过。JNI / Rust / Go 动态库的 ELF LOAD 对齐不低于 16 KB;不代表已在 16 KB 页面设备执行。 +- Flutter analyze 无问题;启用本机 Rust / Go 动态库的 Flutter 测试 50 项通过、3 项专门环境开关测试跳过。 +- 真机隔离测试已通过 Android Keystore 保存/读取/删除,以及应用内 TCP/UDP。 +- 用户完成手机授权后,系统 VPN 的 Java/Dart 普通 Socket TCP/UDP、公告子网自动安装和撤销全部通过,见 `android-network-20261012.log`。 +- 统一代理 VPN 在本机 Wi-Fi 复现 `no available network interface`:hostPlatform 只报告默认接口,没有初始化 sing-box 的可选接口列表。修复为在平台 Initialize 中调用 NetworkManager.UpdateInterfaces。Go 回归测试修复前复现相同错误,修复后真实 TCP 回显与 TCP/UDP socket protector 检查通过。 +- `integration_test/android_proxy_test.dart` 和 `scripts/android-proxy-fixture.py` 真机通过:首次单节点自动选择、默认 Cloudflare DoH、仅代理无需组网配置、普通系统 TCP/UDP、证书验证的 HTTPS、两次启停与断开恢复。见 `android-unified-fixed-20261012.log`;失败证据为 `android-unified-failure-20261012.log`。使用隔离局域网 SOCKS5 出口,不代表用户的所有代理协议或真实节点都已验证。 +- Go `test -race ./...`、`vet ./...` 通过。 +- 新增 Android `MeshPortRuntime` 脱敏事件输出和 `MeshPortVPN` 启动/清理阶段日志;保留 APP 日志页。 + +测试完毕已关闭隔离网关/SOCKS 夹具、移除两条 adb reverse,并恢复普通开发包。测试节点未保存到用户配置。移动网络切换、长期后台和 IPv6 互联网尚未真机验收。 + +首次直接使用 Flutter test 时,等待授权超时后被工具卸载临时 APP;后改用 `scripts/test-android-device.sh`,采用 keep-app-running 与匹配构建号避免测试卸载,并在退出时自动覆盖安装和打开普通 APP。成功和失败恢复均已实际验证。 diff --git a/packages/meshport_client_core/lib/src/proxy_profile.dart b/packages/meshport_client_core/lib/src/proxy_profile.dart index c422cf3..3e74d6f 100644 --- a/packages/meshport_client_core/lib/src/proxy_profile.dart +++ b/packages/meshport_client_core/lib/src/proxy_profile.dart @@ -183,7 +183,9 @@ ImportPreview importProxyNodes(String input, {String source = 'manual'}) { '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, + 'tag': uri.fragment.isEmpty + ? 'Shadowsocks' + : Uri.decodeComponent(uri.fragment), }); continue; } @@ -202,7 +204,7 @@ ImportPreview importProxyNodes(String input, {String source = 'manual'}) { : {'vless', 'trojan'}.contains(kind) ? 443 : 1080, - 'tag': uri.fragment.isEmpty ? kind : uri.fragment, + 'tag': uri.fragment.isEmpty ? kind : Uri.decodeComponent(uri.fragment), }; final user = Uri.decodeComponent(uri.userInfo); if (kind == 'vless') { @@ -280,6 +282,7 @@ ImportPreview importProxyNodes(String input, {String source = 'manual'}) { } class ProxyProfile { + static const defaultProxyDns = 'https://cloudflare-dns.com/dns-query'; List nodes = []; List> rules = []; List> meshDns = []; @@ -295,7 +298,16 @@ class ProxyProfile { mode = 'rule', defaultAction = 'proxy', dnsServer = '1.1.1.1', - proxyDnsServer = ''; + proxyDnsServer = defaultProxyDns; + String get effectiveProxyDns => + proxyDnsServer.trim().isEmpty ? defaultProxyDns : proxyDnsServer.trim(); + + void addNodes(Iterable incoming) { + final firstImport = nodes.isEmpty && selectedId == null; + nodes.addAll(incoming); + if (firstImport && nodes.length == 1) selectedId = nodes.single.id; + } + String get modeLabel => switch (mode) { 'bypass_cn' => '绕过中国大陆', 'global' => '全局代理', @@ -305,8 +317,8 @@ class ProxyProfile { void validateConnection() { if (feature != 'mesh' && mode != 'direct' && - proxyDnsServer.trim().isEmpty) { - throw StateError('请在 DNS 设置中填写代理 DNS;防泄露模式不会自动选择解析服务或回退到直连 DNS'); + !nodes.any((node) => node.id == selectedId)) { + throw const FormatException('请先添加代理节点,并点击节点左侧的选择出口按钮'); } } @@ -319,7 +331,7 @@ class ProxyProfile { 'rules': rules, 'dns_protection': true, 'dns_server': dnsServer, - 'proxy_dns_server': proxyDnsServer, + 'proxy_dns_server': effectiveProxyDns, 'direct_dns_server': directDnsServer, 'rule_sets': ruleSets, 'mesh_dns': feature == 'proxy' ? [] : meshDns, @@ -358,7 +370,10 @@ class ProxyProfile { 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? ?? ''; + final resolver = r['proxy_dns_server'] as String?; + p.proxyDnsServer = resolver == null || resolver.trim().isEmpty + ? defaultProxyDns + : resolver; p.rules = List>.from( (r['rules'] as List).map((v) => Map.from(v)), ); @@ -415,6 +430,7 @@ void replaceSubscription( ImportPreview preview, DateTime now, ) { + final firstImport = profile.nodes.isEmpty && profile.selectedId == null; if (preview.nodes.isEmpty) throw const FormatException('订阅没有可用节点,保留原配置'); final old = profile.nodes.where((n) => n.source == source).toList(); final next = preview.nodes.map((n) { @@ -429,6 +445,9 @@ void replaceSubscription( ); }).toList(); profile.nodes = [...profile.nodes.where((n) => n.source != source), ...next]; + if (firstImport && profile.nodes.length == 1) { + profile.selectedId = profile.nodes.single.id; + } if (old.any((n) => n.id == profile.selectedId) && !next.any((n) => n.id == profile.selectedId)) profile.selectedId = null; diff --git a/scripts/android-proxy-fixture.py b/scripts/android-proxy-fixture.py new file mode 100644 index 0000000..8315096 --- /dev/null +++ b/scripts/android-proxy-fixture.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Isolated LAN SOCKS5 fixture for android_proxy_test.dart; no user profiles. + +Only the explicitly supplied device IP is accepted. Documentation addresses +serve deterministic TCP/UDP replies; other TCP destinations use real sockets +to verify default DoH and certificate-validated HTTPS through the proxy. +""" +import argparse +import ipaddress +import select +import socket +import socketserver +import struct + + +def read_exact(sock, length): + result = b"" + while len(result) < length: + chunk = sock.recv(length - len(result)) + if not chunk: + raise EOFError() + result += chunk + return result + + +def address(sock, kind): + if kind == 1: + host = socket.inet_ntop(socket.AF_INET, read_exact(sock, 4)) + elif kind == 4: + host = socket.inet_ntop(socket.AF_INET6, read_exact(sock, 16)) + elif kind == 3: + host = read_exact(sock, read_exact(sock, 1)[0]).decode("ascii") + else: + raise ValueError("Invalid SOCKS address") + return host, struct.unpack("!H", read_exact(sock, 2))[0] + + +class Handler(socketserver.BaseRequestHandler): + def handle(self): + if self.client_address[0] != self.server.device: + return + client = self.request + client.settimeout(45) + try: + version, count = read_exact(client, 2) + methods = read_exact(client, count) + if version != 5 or 0 not in methods: + return + client.sendall(b"\x05\x00") + version, command, _, kind = read_exact(client, 4) + host, port = address(client, kind) + if command == 3: + self.udp(client) + return + if version != 5 or command != 1: + return + if host == "198.51.100.45" and port == 18082: + client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6) + data = b"" + while b"\r\n\r\n" not in data and len(data) < 8192: + data += client.recv(4096) + body = b"MeshPort proxy fixture" + client.sendall(b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: " + + str(len(body)).encode() + b"\r\n\r\n" + body) + print("FIXTURE_TCP_PASS", flush=True) + return + # No connections to private hosts, other devices, or host services. + destinations = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + public = [x for x in destinations if ipaddress.ip_address(x[4][0]).is_global] + if not public: + raise ValueError("Only public upstreams allowed") + remote = None + for family, kind, proto, _, destination in public: + candidate = socket.socket(family, kind, proto) + candidate.settimeout(10) + try: + candidate.connect(destination) + remote = candidate + break + except OSError: + candidate.close() + if remote is None: + raise OSError("No reachable public upstream") + with remote: + client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6) + print("FIXTURE_PUBLIC_TCP_CONNECTED", flush=True) + while True: + readable, _, _ = select.select([client, remote], [], [], 45) + if not readable: + return + for source in readable: + data = source.recv(65536) + if not data: + return + (remote if source is client else client).sendall(data) + except (OSError, ValueError, EOFError) as error: + print("FIXTURE_CONNECTION_ERROR", type(error).__name__, flush=True) + + def udp(self, client): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp: + udp.bind((self.server.server_address[0], 0)) + endpoint = udp.getsockname() + client.sendall(b"\x05\x00\x00\x01" + socket.inet_aton(endpoint[0]) + + struct.pack("!H", endpoint[1])) + while True: + readable, _, _ = select.select([client, udp], [], [], 45) + if not readable or client in readable: + return + data, peer = udp.recvfrom(65536) + if peer[0] != self.server.device: + continue + if data[:4] == b"\x00\x00\x00\x01" and len(data) >= 10: + target = socket.inet_ntoa(data[4:8]) + port = struct.unpack("!H", data[8:10])[0] + if target == "198.51.100.45" and port == 18083: + udp.sendto(data, peer) + print("FIXTURE_UDP_PASS", flush=True) + + +class Server(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", required=True) + parser.add_argument("--device", required=True) + args = parser.parse_args() + with Server((args.host, 18084), Handler) as server: + server.device = args.device + print("Android proxy fixture ready", flush=True) + server.serve_forever() diff --git a/scripts/go-local.sh b/scripts/go-local.sh index 384b736..d5c0f31 100644 --- a/scripts/go-local.sh +++ b/scripts/go-local.sh @@ -1,6 +1,9 @@ #!/bin/sh set -eu cd "$(dirname "$0")/.." +if [ -x work/toolchain/go-sdk/go/bin/go ]; then + export PATH="$PWD/work/toolchain/go-sdk/go/bin:$PATH" +fi export GOPATH="$PWD/work/toolchain/go" export GOMODCACHE="$GOPATH/pkg/mod" export GOCACHE="$PWD/work/cache/go-build" diff --git a/scripts/test-android-device.sh b/scripts/test-android-device.sh new file mode 100644 index 0000000..1f40d1b --- /dev/null +++ b/scripts/test-android-device.sh @@ -0,0 +1,50 @@ +#!/bin/sh +# Keep user storage and restore the normal APP even when device tests fail. +set -eu +cd "$(dirname "$0")/.." +root="$PWD" +if [ "$#" -lt 4 ]; then + printf '%s\n' 'usage: test-android-device.sh SERIAL NORMAL_APK BUILD_NUMBER network|proxy [FIXTURE_IP]' >&2 + exit 2 +fi +serial="$1" +apk="$2" +case "$apk" in /*) ;; *) apk="$root/$apk" ;; esac +[ -f "$apk" ] || { printf '%s\n' 'Normal APK not found' >&2; exit 2; } +number="$3" +case "$number" in ''|*[!0-9]*) printf '%s\n' 'Numeric build number required' >&2; exit 2 ;; esac +case "$4" in + network) target=integration_test/android_network_test.dart ;; + proxy) target=integration_test/android_proxy_test.dart; [ "$#" -ge 5 ] || exit 2 ;; + *) exit 2 ;; +esac +restore() { + result=$? + trap - EXIT HUP INT TERM + printf '%s\n' 'Restoring the normal MeshPort APP (keeping stored profiles)' + adb -s "$serial" shell am force-stop com.example.meshport_lab || true + if adb -s "$serial" install -r -d "$apk"; then + adb -s "$serial" shell am start -W -n com.example.meshport_lab/.MainActivity || result=1 + else + result=1 + fi + exit "$result" +} +trap restore EXIT +trap 'exit 130' HUP INT TERM +cd apps/meshport_lab +# Matching build numbers avoid Flutter's uninstall/reinstall downgrade fallback. +# drive's keep-app-running also suppresses the default test-package uninstall. +if [ "$4" = proxy ]; then + flutter build apk --debug --target-platform android-arm64 --target="$target" \ + --build-number="$number" --dart-define="ANDROID_PROXY_FIXTURE=$5" + flutter drive -d "$serial" --target="$target" \ + --driver=test_driver/integration_test.dart --keep-app-running \ + --use-application-binary="$PWD/build/app/outputs/flutter-apk/app-debug.apk" +else + flutter build apk --debug --target-platform android-arm64 --target="$target" \ + --build-number="$number" + flutter drive -d "$serial" --target="$target" \ + --driver=test_driver/integration_test.dart --keep-app-running \ + --use-application-binary="$PWD/build/app/outputs/flutter-apk/app-debug.apk" +fi diff --git a/tools/meshport-vpn-helper/src/mac/unified.rs b/tools/meshport-vpn-helper/src/mac/unified.rs index b2a57e3..48a8150 100644 --- a/tools/meshport-vpn-helper/src/mac/unified.rs +++ b/tools/meshport-vpn-helper/src/mac/unified.rs @@ -77,6 +77,119 @@ impl Drop for Proxy { struct DnsGuard { child: Child, } + +// Darwin IP_BOUND_IF sockets need an interface-scoped default when the TUN's +// more-specific split defaults become the global route. Own only our new route. +struct PhysicalRouteGuard { + interface: String, + gateway: std::net::Ipv4Addr, + owned: bool, +} +fn route_field<'a>(text: &'a str, field: &str) -> Option<&'a str> { + text.lines() + .find_map(|line| line.trim().strip_prefix(field).map(str::trim)) +} +fn scoped_route_matches(text: &str, interface: &str, gateway: std::net::Ipv4Addr) -> bool { + route_field(text, "interface:") == Some(interface) + && route_field(text, "gateway:").and_then(|value| value.parse().ok()) == Some(gateway) + && route_field(text, "flags:").is_some_and(|flags| flags.contains("IFSCOPE")) +} +impl PhysicalRouteGuard { + fn install(interface: &str) -> Result { + let before = Command::new("/sbin/route") + .args(["-n", "get", "-ifscope", interface, "default"]) + .output()?; + ensure!(before.status.success(), "physical IPv4 gateway unavailable"); + let text = String::from_utf8(before.stdout)?; + ensure!( + route_field(&text, "interface:") == Some(interface), + "physical gateway interface changed" + ); + let gateway: std::net::Ipv4Addr = route_field(&text, "gateway:") + .context("physical IPv4 gateway missing")? + .parse()?; + let mut guard = Self { + interface: interface.into(), + gateway, + owned: false, + }; + if scoped_route_matches(&text, interface, gateway) { + return Ok(guard); + } + let installed = Command::new("/sbin/route") + .args([ + "-n", + "add", + "-inet", + "-ifscope", + interface, + "default", + &gateway.to_string(), + ]) + .output()?; + if !installed.status.success() { + // Another owner may have installed it meanwhile. Reuse, never remove. + let existing = Command::new("/sbin/route") + .args(["-n", "get", "-ifscope", interface, "default"]) + .output()?; + ensure!( + existing.status.success() + && scoped_route_matches( + &String::from_utf8_lossy(&existing.stdout), + interface, + gateway + ), + "cannot protect physical IPv4 default route" + ); + return Ok(guard); + } + guard.owned = true; + let verified = Command::new("/sbin/route") + .args(["-n", "get", "-ifscope", interface, "default"]) + .output()?; + ensure!( + verified.status.success() + && scoped_route_matches( + &String::from_utf8_lossy(&verified.stdout), + interface, + gateway + ), + "physical scoped route verification failed" + ); + Ok(guard) + } +} +impl Drop for PhysicalRouteGuard { + fn drop(&mut self) { + if !self.owned { + return; + } + if let Ok(current) = Command::new("/sbin/route") + .args(["-n", "get", "-ifscope", &self.interface, "default"]) + .output() + { + if current.status.success() + && scoped_route_matches( + &String::from_utf8_lossy(¤t.stdout), + &self.interface, + self.gateway, + ) + { + let _ = Command::new("/sbin/route") + .args([ + "-n", + "delete", + "-inet", + "-ifscope", + &self.interface, + "default", + &self.gateway.to_string(), + ]) + .output(); + } + } + } +} impl DnsGuard { fn install() -> Result { let mut child = Command::new("/usr/sbin/scutil") @@ -122,6 +235,7 @@ impl Drop for DnsGuard { } #[derive(Default)] pub(super) struct Unified { + physical_route: Option, dns: Option, proxy: Option, profile: Value, @@ -237,7 +351,13 @@ impl Unified { ); } self.mesh = self.profile["feature"] != "proxy"; + let physical_route = if self.profile["feature"] != "mesh" { + Some(PhysicalRouteGuard::install(&self.physical)?) + } else { + None + }; self.proxy = Some(Proxy::open()?); + self.physical_route = physical_route; self.proxy .as_ref() .unwrap() @@ -326,6 +446,7 @@ impl Unified { .take() .and_then(|proxy| proxy.request(json!({"op":"stop"})).err()); let network = super::call(id, &json!({"op":"stop"})); + self.physical_route.take(); self.protected.clear(); self.active.clear(); if let Some(error) = proxy_error { @@ -335,3 +456,22 @@ impl Unified { Ok(()) } } + +#[cfg(test)] +mod route_guard_tests { + use super::scoped_route_matches; + #[test] + fn only_matching_scoped_route_is_owned() { + let gateway = "192.168.21.1".parse().unwrap(); + let original = "gateway: 192.168.21.1\ninterface: en0\nflags: "; + assert!(!scoped_route_matches(original, "en0", gateway)); + let scoped = original.replace("GLOBAL", "IFSCOPE"); + assert!(scoped_route_matches(&scoped, "en0", gateway)); + assert!(!scoped_route_matches(&scoped, "en1", gateway)); + assert!(!scoped_route_matches( + &scoped, + "en0", + "192.168.21.2".parse().unwrap() + )); + } +} diff --git a/vendor/easytier/easytier-proto/build/main.rs b/vendor/easytier/easytier-proto/build/main.rs new file mode 100644 index 0000000..2dcd1ec --- /dev/null +++ b/vendor/easytier/easytier-proto/build/main.rs @@ -0,0 +1,148 @@ +mod rpc; + +use crate::rpc::ServiceGenerator; +use std::{env, path::PathBuf}; + +#[cfg(target_os = "windows")] +use std::io::Cursor; + +#[cfg(target_os = "windows")] +fn check_protoc_exist() -> Option { + let path = env::var_os("PROTOC").map(PathBuf::from); + if path.is_some() && path.as_ref().unwrap().exists() { + return path; + } + + let path = env::var_os("PATH").unwrap_or_default(); + for p in env::split_paths(&path) { + let p = p.join("protoc.exe"); + if p.exists() && p.is_file() { + return Some(p); + } + } + + None +} + +#[cfg(target_os = "windows")] +fn get_cargo_target_dir() -> Result> { + let out_dir = PathBuf::from(env::var("OUT_DIR")?); + let profile = env::var("PROFILE")?; + let mut target_dir = None; + let mut sub_path = out_dir.as_path(); + while let Some(parent) = sub_path.parent() { + if parent.ends_with(&profile) { + target_dir = Some(parent); + break; + } + sub_path = parent; + } + let target_dir = target_dir.ok_or("not found")?; + Ok(target_dir.to_path_buf()) +} + +#[cfg(target_os = "windows")] +fn download_protoc() -> PathBuf { + let out_dir = get_cargo_target_dir().unwrap().join("protobuf"); + let fname = out_dir.join("bin/protoc.exe"); + if fname.exists() { + println!("cargo:info=use existing protoc: {:?}", fname); + return fname; + } + + println!("cargo:info=need download protoc, please wait..."); + + let url = "https://github.com/protocolbuffers/protobuf/releases/download/v26.0-rc1/protoc-26.0-rc-1-win64.zip"; + let response = reqwest::blocking::get(url).unwrap(); + println!("{:?}", response); + let mut content = response + .bytes() + .map(|v| v.to_vec()) + .map(Cursor::new) + .map(zip::ZipArchive::new) + .unwrap() + .unwrap(); + content.extract(out_dir).unwrap(); + + fname +} + +#[cfg(target_os = "windows")] +fn ensure_protoc_for_windows() { + let protoc_path = if let Some(path) = check_protoc_exist() { + println!("cargo:info=use os existing protoc: {:?}", path); + path + } else { + download_protoc() + }; + + unsafe { + env::set_var("PROTOC", protoc_path); + } +} + +fn main() -> Result<(), Box> { + #[cfg(target_os = "windows")] + ensure_protoc_for_windows(); + + let proto_files_reflect = ["proto/peer_rpc.proto", "proto/common.proto"]; + + let proto_files = [ + "proto/core_peer.proto", + "proto/core_config.proto", + "proto/error.proto", + "proto/tests.proto", + "proto/api_instance.proto", + "proto/api_logger.proto", + "proto/api_config.proto", + "proto/api_manage.proto", + "proto/web.proto", + "proto/magic_dns.proto", + "proto/acl.proto", + ]; + + for proto_file in proto_files.iter().chain(proto_files_reflect.iter()) { + println!("cargo:rerun-if-changed={proto_file}"); + } + + let out = PathBuf::from(env::var("OUT_DIR")?); + let descriptor = out.join("descriptors.bin"); + + let mut config = prost_build::Config::new(); + if env::var_os("CARGO_FEATURE_JSON_RPC").is_some() { + config + .extern_path(".google.protobuf.Any", "::prost_wkt_types::Any") + .extern_path(".google.protobuf.Timestamp", "::prost_wkt_types::Timestamp") + .extern_path(".google.protobuf.Value", "::prost_wkt_types::Value"); + } else { + config + .extern_path(".google.protobuf.Any", "::prost_types::Any") + .extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp") + .extern_path(".google.protobuf.Value", "::prost_types::Value"); + } + config + .file_descriptor_set_path(&descriptor) + .service_generator(Box::new(ServiceGenerator::default())) + .btree_map(["."]) + .skip_debug([ + ".common.Ipv4Addr", + ".common.Ipv6Addr", + ".common.UUID", + ".api.manage.ManagedCredentialConfig", + ".api.manage.VpnPortalConfig", + ]); + + config.compile_protos(&proto_files, &["proto/"])?; + + config.file_descriptor_set_path(out.join("file_descriptor_set.bin")); + config.compile_protos(&proto_files_reflect, &["proto/"])?; + + let descriptor = std::fs::read(descriptor)?; + pbjson_build::Builder::new() + .register_descriptors(&descriptor)? + .preserve_proto_field_names() + .btree_map(["."]) + .build(&["."])?; + + Ok(()) +} diff --git a/vendor/easytier/easytier-proto/build/rpc.rs b/vendor/easytier/easytier-proto/build/rpc.rs new file mode 100644 index 0000000..8b57982 --- /dev/null +++ b/vendor/easytier/easytier-proto/build/rpc.rs @@ -0,0 +1,721 @@ +#![allow(non_snake_case)] + +use indoc::formatdoc; +use proc_macro2::{Ident, TokenStream}; +use quote::{format_ident, quote}; +use std::str::FromStr; + +fn parse(value: &str) -> TokenStream { + TokenStream::from_str(value) + .unwrap_or_else(|err| panic!("Failed to parse tokens: {} ({})", value, err)) +} + +fn doc(comments: &prost_build::Comments) -> TokenStream { + let doc = comments + .leading + .iter() + .flat_map(|c| c.lines().filter(|s| !s.is_empty())); + quote! { #( #[doc = #doc] )* } +} + +const NAMESPACE: &str = "crate::proto::rpc_types"; + +struct Method { + index: u8, + doc: TokenStream, + method: Ident, + method_inner: Ident, + method_str: String, + method_proto: Ident, + method_proto_str: String, + Input: TokenStream, + Input_proto_str: String, + Output: TokenStream, + Output_proto_str: String, +} + +impl Method { + fn new(index: u8, method: prost_build::Method) -> Self { + assert!( + !method.client_streaming, + "Client streaming not yet supported for method {}", + method.proto_name + ); + assert!( + !method.server_streaming, + "Server streaming not yet supported for method {}", + method.proto_name + ); + Self { + index, + doc: doc(&method.comments), + method: format_ident!("{}", method.name), + method_inner: format_ident!("{}_inner", method.name), + method_str: method.name, + method_proto: format_ident!("{}", method.proto_name), + method_proto_str: method.proto_name, + Input: parse(&method.input_type), + Input_proto_str: method.input_proto_type, + Output: parse(&method.output_type), + Output_proto_str: method.output_proto_type, + } + } +} + +struct Service { + namespace: TokenStream, + doc: TokenStream, + Service: Ident, + ServiceDescriptor: Ident, + ServiceServer: Ident, + ServiceClient: Ident, + ServiceClientFactory: Ident, + ServiceMethodDescriptor: Ident, + Service_str: String, + Service_proto_str: String, + Service_package_str: String, + methods: Vec, +} + +impl Service { + fn new(service: prost_build::Service) -> Self { + let methods = service + .methods + .into_iter() + .enumerate() + .map(|(i, method)| Method::new((i + 1) as u8, method)) + .collect(); + + Self { + namespace: parse(NAMESPACE), + doc: doc(&service.comments), + Service: format_ident!("{}", service.name), + ServiceDescriptor: format_ident!("{}Descriptor", service.name), + ServiceServer: format_ident!("{}Server", service.name), + ServiceClient: format_ident!("{}Client", service.name), + ServiceClientFactory: format_ident!("{}ClientFactory", service.name), + ServiceMethodDescriptor: format_ident!("{}MethodDescriptor", service.name), + Service_str: service.name, + Service_proto_str: service.proto_name, + Service_package_str: service.package, + methods, + } + } + + fn trait_Service(&self) -> TokenStream { + let Self { + namespace, + doc, + Service, + methods, + .. + } = self; + + let match_json_call_method = methods.iter().map( + |Method { + method, + method_str, + method_proto_str, + Input, + .. + }| { + quote! { + #method_str | #method_proto_str => { + let req: #Input = ::serde_json::from_value(json) + .map_err(|e| #namespace::error::Error::MalformatRpcPacket(format!("json error: {}", e)))?; + let resp = self.#method(ctrl, req).await?; + Ok(::serde_json::to_value(resp) + .map_err(|e| #namespace::error::Error::MalformatRpcPacket(format!("json error: {}", e)))?) + } + } + }, + ); + + let methods = methods.iter().map( + |Method { + doc, + method, + Input, + Output, + .. + }| { + quote! { + #doc + async fn #method(&self, ctrl: Self::Controller, input: #Input) -> #namespace::error::Result<#Output>; + } + }, + ); + + quote! { + #doc + #[async_trait::async_trait] + #[auto_impl::auto_impl(&, Arc, Box)] + pub trait #Service { + type Controller: #namespace::controller::Controller; + + #(#methods)* + + #[cfg(feature = "json-rpc")] + async fn json_call_method( + &self, + ctrl: Self::Controller, + method: &str, + json: ::serde_json::Value, + ) -> #namespace::error::Result<::serde_json::Value> { + match method { + #(#match_json_call_method)* + _ => Err(#namespace::error::Error::InvalidMethodIndex(0, method.to_string())), + } + } + } + } + } + + fn impl_Service_for_Weak(&self) -> TokenStream { + let Self { + namespace, + Service, + methods, + .. + } = self; + let methods = methods.iter().map( + |Method { + method, + Input, + Output, + .. + }| { + quote! { + async fn #method(&self, ctrl: Self::Controller, input: #Input) -> #namespace::error::Result<#Output> { + let Some(service) = self.upgrade() else { + return Err(#namespace::error::Error::Shutdown); + }; + service.#method(ctrl, input).await + } + } + }, + ); + + quote! { + #[async_trait::async_trait] + impl #Service for ::std::sync::Weak + where + T: Send + Sync + 'static, + ::std::sync::Arc: #Service, + { + type Controller = <::std::sync::Arc as #Service>::Controller; + + #(#methods)* + } + } + } + + fn struct_ServiceDescriptor(&self) -> TokenStream { + let Self { + namespace, + ServiceDescriptor, + ServiceMethodDescriptor, + Service_str, + Service_proto_str, + Service_package_str, + methods, + .. + } = self; + + let doc = format!("A service descriptor for a `{}`.", Service_str); + + let methods = methods.iter().map(|Method { method_proto, .. }| { + quote! { #ServiceMethodDescriptor::#method_proto, } + }); + + quote! { + #[doc = #doc] + #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Default)] + pub struct #ServiceDescriptor; + + impl #namespace::descriptor::ServiceDescriptor for #ServiceDescriptor { + type Method = #ServiceMethodDescriptor; + fn name(&self) -> &'static str { #Service_str } + fn proto_name(&self) -> &'static str { #Service_proto_str } + fn package(&self) -> &'static str { #Service_package_str } + fn methods(&self) -> &'static [Self::Method] { + &[ #(#methods)* ] + } + } + } + } + + fn enum_ServiceMethodDescriptor(&self) -> TokenStream { + let Self { + ServiceMethodDescriptor, + Service_str, + methods, + .. + } = self; + + let doc = formatdoc! {" + Methods available on a `{Service_str}`. + + This can be used as a key when routing requests for servers/clients of a `{Service_str}`. + "}; + + let variants = methods.iter().map( + |Method { + method_proto, + index, + .. + }| { + quote! { #method_proto = #index, } + }, + ); + + let impl_MethodDescriptor = self.impl_MethodDescriptor_for_ServiceMethodDescriptor(); + let impl_TryFrom = self.impl_TryFrom_for_ServiceMethodDescriptor(); + quote! { + #[doc = #doc] + #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] + #[repr(u8)] + pub enum #ServiceMethodDescriptor { + #(#variants)* + } + + #impl_MethodDescriptor + + #impl_TryFrom + } + } + + fn impl_MethodDescriptor_for_ServiceMethodDescriptor(&self) -> TokenStream { + let Self { + namespace, + ServiceMethodDescriptor, + methods, + .. + } = self; + + let name = { + let arms = methods.iter().map( + |Method { + method_proto, + method_str, + .. + }| { + quote! { #ServiceMethodDescriptor::#method_proto => #method_str, } + }, + ); + + quote! { + fn name(&self) -> &'static str { + match *self { + #(#arms)* + } + } + } + }; + + let proto_name = { + let arms = methods.iter().map( + |Method { + method_proto, + method_proto_str, + .. + }| { + quote! { #ServiceMethodDescriptor::#method_proto => #method_proto_str, } + }, + ); + + quote! { + fn proto_name(&self) -> &'static str { + match *self { + #(#arms)* + } + } + } + }; + + let input_type = { + let arms = methods.iter().map(|Method { method_proto, Input, .. }| { + quote! { #ServiceMethodDescriptor::#method_proto => ::std::any::TypeId::of::<#Input>(), } + }); + + quote! { + fn input_type(&self) -> ::std::any::TypeId { + match *self { + #(#arms)* + } + } + } + }; + + let input_proto_type = { + let arms = methods.iter().map( + |Method { + method_proto, + Input_proto_str, + .. + }| { + quote! { #ServiceMethodDescriptor::#method_proto => #Input_proto_str, } + }, + ); + + quote! { + fn input_proto_type(&self) -> &'static str { + match *self { + #(#arms)* + } + } + } + }; + + let output_type = { + let arms = methods.iter().map(|Method { method_proto, Output, .. }| { + quote! { #ServiceMethodDescriptor::#method_proto => ::std::any::TypeId::of::<#Output>(), } + }); + + quote! { + fn output_type(&self) -> ::std::any::TypeId { + match *self { + #(#arms)* + } + } + } + }; + + let output_proto_type = { + let arms = methods.iter().map( + |Method { + method_proto, + Output_proto_str, + .. + }| { + quote! { #ServiceMethodDescriptor::#method_proto => #Output_proto_str, } + }, + ); + + quote! { + fn output_proto_type(&self) -> &'static str { + match *self { + #(#arms)* + } + } + } + }; + + quote! { + impl #namespace::descriptor::MethodDescriptor for #ServiceMethodDescriptor { + #name + + #proto_name + + #input_type + + #input_proto_type + + #output_type + + #output_proto_type + + fn index(&self) -> u8 { + *self as u8 + } + } + } + } + + fn impl_TryFrom_for_ServiceMethodDescriptor(&self) -> TokenStream { + let Self { + namespace, + ServiceMethodDescriptor, + Service_str, + methods, + .. + } = self; + + let arms = methods.iter().map( + |Method { + method_proto, + index, + .. + }| { + quote! { #index => Ok(#ServiceMethodDescriptor::#method_proto), } + }, + ); + + quote! { + impl std::convert::TryFrom for #ServiceMethodDescriptor { + type Error = #namespace::error::Error; + fn try_from(value: u8) -> #namespace::error::Result { + match value { + #(#arms)* + _ => Err(#namespace::error::Error::InvalidMethodIndex(value, #Service_str.to_string())), + } + } + } + } + } + + fn struct_ServiceClient(&self) -> TokenStream { + let Self { + namespace, + ServiceDescriptor, + ServiceClient, + Service_str, + .. + } = self; + + let doc = formatdoc! {" + A client for a `{Service_str}`. + + This implements the `{Service_str}` trait by dispatching all method calls to the supplied `Handler`. + "}; + + let impl_service_client = self.impl_ServiceClient(); + let impl_service_for_client = self.impl_Service_for_ServiceClient(); + quote! { + #[doc = #doc] + #[derive(Clone, Debug)] + pub struct #ServiceClient(H) where H: #namespace::handler::Handler; + + impl #ServiceClient where H: #namespace::handler::Handler { + /// Creates a new client instance that delegates all method calls to the supplied handler. + pub fn new(handler: H) -> Self { + Self(handler) + } + } + + #impl_service_client + + #impl_service_for_client + } + } + + fn impl_ServiceClient(&self) -> TokenStream { + let Self { + namespace, + ServiceClient, + ServiceDescriptor, + ServiceMethodDescriptor, + methods, + .. + } = self; + + let methods = methods.iter().map( + |Method { + method_inner, + method_proto, + Input, + Output, + .. + }| { + quote! { + async fn #method_inner(handler: H, ctrl: H::Controller, input: #Input) -> #namespace::error::Result<#Output> { + #namespace::__rt::call_method(handler, ctrl, #ServiceMethodDescriptor::#method_proto, input).await + } + } + }, + ); + + quote! { + impl #ServiceClient where H: #namespace::handler::Handler { + #(#methods)* + } + } + } + + fn impl_Service_for_ServiceClient(&self) -> TokenStream { + let Self { + namespace, + Service, + ServiceClient, + ServiceDescriptor, + methods, + .. + } = self; + + let methods = methods.iter().map( + |Method { + method, + method_inner, + Input, + Output, + .. + }| { + quote! { + async fn #method(&self, ctrl: H::Controller, input: #Input) -> #namespace::error::Result<#Output> { + #ServiceClient::#method_inner(self.0.clone(), ctrl, input).await + } + } + }, + ); + + quote! { + #[async_trait::async_trait] + impl #Service for #ServiceClient where H: #namespace::handler::Handler { + type Controller = H::Controller; + + #(#methods)* + } + } + } + + fn struct_ServiceClientFactory(&self) -> TokenStream { + let Self { + namespace, + Service, + ServiceClient, + ServiceClientFactory, + ServiceDescriptor, + .. + } = self; + + quote! { + pub struct #ServiceClientFactory(std::marker::PhantomData); + + impl Clone for #ServiceClientFactory { + fn clone(&self) -> Self { + Self(std::marker::PhantomData) + } + } + + impl #namespace::__rt::RpcClientFactory for #ServiceClientFactory where C: #namespace::controller::Controller { + type Descriptor = #ServiceDescriptor; + type ClientImpl = Box + Send + Sync + 'static>; + type Controller = C; + + fn new(handler: impl #namespace::handler::Handler) -> Self::ClientImpl { + Box::new(#ServiceClient::new(handler)) + } + } + } + } + + fn struct_ServiceServer(&self) -> TokenStream { + let Self { + namespace, + Service, + ServiceDescriptor, + ServiceServer, + ServiceMethodDescriptor, + Service_str, + methods, + .. + } = self; + + let doc = formatdoc! {" + A server for a `{Service_str}`. + + This implements the `Server` trait by handling requests and dispatch them to methods on the + supplied `{Service_str}`. + "}; + + let arms = methods.iter().map( + |Method { + method_proto, + method, + Input, + .. + }| { + quote! { + #ServiceMethodDescriptor::#method_proto => { + let decoded: #Input = #namespace::__rt::decode(input)?; + let ret = service.#method(ctrl, decoded).await?; + #namespace::__rt::encode(ret) + } + } + }, + ); + + quote! { + #[doc = #doc] + #[derive(Clone, Debug)] + pub struct #ServiceServer(A) where A: #Service + Clone + Send + 'static; + + impl #ServiceServer<::std::sync::Weak> + where + T: Send + Sync + 'static, + ::std::sync::Arc: #Service, + { + pub fn new_arc(service: ::std::sync::Arc) -> #ServiceServer<::std::sync::Weak> { + #ServiceServer(::std::sync::Arc::downgrade(&service)) + } + } + + impl #ServiceServer where A: #Service + Clone + Send + 'static { + /// Creates a new server instance that dispatches all calls to the supplied service. + pub fn new(service: A) -> #ServiceServer { + #ServiceServer(service) + } + + async fn call_inner( + service: A, + method: #ServiceMethodDescriptor, + ctrl: A::Controller, + input: ::bytes::Bytes) + -> #namespace::error::Result<::bytes::Bytes> { + match method { + #(#arms)* + } + } + } + + #[async_trait::async_trait] + impl #namespace::handler::Handler for #ServiceServer + where + A: #Service + Clone + Send + Sync + 'static { + type Descriptor = #ServiceDescriptor; + type Controller = A::Controller; + + async fn call( + &self, + ctrl: A::Controller, + method: #ServiceMethodDescriptor, + input: ::bytes::Bytes) + -> #namespace::error::Result<::bytes::Bytes> { + #ServiceServer::call_inner(self.0.clone(), method, ctrl, input).await + } + } + } + } +} + +/// The service generator to be used with `prost-build` to generate RPC implementations for +/// `prost-simple-rpc`. +/// +/// See the crate-level documentation for more info. +#[non_exhaustive] +#[derive(Debug, Default)] +pub struct ServiceGenerator; + +impl prost_build::ServiceGenerator for ServiceGenerator { + fn generate(&mut self, service: prost_build::Service, buf: &mut String) { + let info = Service::new(service); + + let trait_Service = info.trait_Service(); + let impl_Service_for_Weak = info.impl_Service_for_Weak(); + let struct_ServiceDescriptor = info.struct_ServiceDescriptor(); + let enum_ServiceMethodDescriptor = info.enum_ServiceMethodDescriptor(); + let struct_ServiceClient = info.struct_ServiceClient(); + let struct_ServiceClientFactory = info.struct_ServiceClientFactory(); + let struct_ServiceServer = info.struct_ServiceServer(); + + let tokens = quote! { + #trait_Service + + #impl_Service_for_Weak + + #struct_ServiceDescriptor + + #enum_ServiceMethodDescriptor + + #struct_ServiceClient + + #struct_ServiceClientFactory + + #struct_ServiceServer + }; + + buf.push('\n'); + buf.push_str(&tokens.to_string()); + buf.push('\n'); + } +} diff --git a/vendor/easytier/easytier/build/main.rs b/vendor/easytier/easytier/build/main.rs new file mode 100644 index 0000000..a46d056 --- /dev/null +++ b/vendor/easytier/easytier/build/main.rs @@ -0,0 +1,92 @@ +use cfg_aliases::cfg_aliases; +use std::env; + +#[cfg(target_os = "windows")] +struct WindowsBuild {} + +#[cfg(target_os = "windows")] +impl WindowsBuild { + pub fn check_for_win() { + // add third_party dir to link search path + let target = std::env::var("TARGET").unwrap_or_default(); + let variant = if target.contains("x86_64") { + "x86_64" + } else if target.contains("i686") { + "i686" + } else if target.contains("aarch64") { + "arm64" + } else { + return; + }; + + let mut path = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); + path.push("third_party"); + path.push(variant); + println!("cargo:rustc-link-search=native={}", path.to_str().unwrap()); + } +} + +fn workdir() -> Option { + if let Ok(cargo_manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") { + return Some(cargo_manifest_dir); + } + + let dest = std::env::var("OUT_DIR"); + if dest.is_err() { + return None; + } + let dest = dest.unwrap(); + + let seperator = regex::Regex::new(r"(/target/(.+?)/build/)|(\\target\\(.+?)\\build\\)") + .expect("Invalid regex"); + let parts = seperator.split(dest.as_str()).collect::>(); + + if parts.len() >= 2 { + return Some(parts[0].to_string()); + } + + None +} + +fn check_locale() { + let workdir = workdir().unwrap_or("./".to_string()); + + let locale_path = format!("{workdir}/**/locales/**/*"); + if let Ok(globs) = globwalk::glob(locale_path) { + for entry in globs { + if let Err(e) = entry { + println!("cargo:i18n-error={e}"); + continue; + } + + let entry = entry.unwrap().into_path(); + println!("cargo:rerun-if-changed={}", entry.display()); + } + } +} + +fn main() -> Result<(), Box> { + cfg_aliases! { + mobile: { + any( + target_os = "android", + target_os = "ios", + all(target_os = "macos", feature = "macos-ne"), + target_env = "ohos" + ) + } + } + + let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); + // enable thunk-rs when target os is windows and arch is x86_64 or i686 + if target_os == "windows" && (target_arch == "x86" || target_arch == "x86_64") { + thunk::thunk(); + } + + #[cfg(target_os = "windows")] + WindowsBuild::check_for_win(); + + check_locale(); + Ok(()) +}