Compare commits

...
4 Commits
Author SHA1 Message Date
shenandshen f94dab0555 Improve VPN video routing, profile storage and authorization reuse 2026-10-13 00:34:16 -07:00
shenandshen c94143dfae Keep macOS client running in the menu bar when its window closes
Retain the main Flutter window, add reopen and explicit quit actions, and preserve its controller while hidden. Fix native test host paths and cover the window and menu lifecycle with XCTest.
2026-10-12 18:46:53 -07:00
shenandshen c7cc2aa865 Fix VPN internet connectivity and simplify client setup
Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
2026-10-12 06:51:25 -07:00
shenleiandClaude Haiku 5.5 2f185f914d Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages,
  responsive layout, and related tests
- Add meshport-socks crate and sing-box bridge scripts/docs
- Add singbox_flutter binding and meshport_client_core package
- FFI, VPN helper (unified mac path), and Android/macOS runner updates
- Docs for architecture, client runtime, UI design, and validation
- UI design output artifacts under outputs/ui

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-12 10:06:15 +09:00
169 changed files with 16141 additions and 433 deletions
+8
View File
@@ -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
Generated
+16
View File
@@ -2398,8 +2398,11 @@ name = "meshport-ffi"
version = "0.1.0"
dependencies = [
"anyhow",
"easytier",
"easytier-core",
"meshport",
"meshport-easytier",
"meshport-socks",
"serde_json",
"tokio",
"tracing",
@@ -2415,6 +2418,19 @@ dependencies = [
"tokio",
]
[[package]]
name = "meshport-socks"
version = "0.1.0"
dependencies = [
"anyhow",
"easytier",
"easytier-core",
"meshport",
"meshport-easytier",
"serde_json",
"tokio",
]
[[package]]
name = "meshport-test-server"
version = "0.1.0"
+1
View File
@@ -19,3 +19,4 @@ easytier-core = { path = "vendor/easytier/easytier-core", default-features = fal
meshport = { path = "crates/meshport" }
meshport-easytier = { path = "crates/meshport-easytier" }
meshport-netstack = { path = "crates/meshport-netstack" }
meshport-socks = { path = "crates/meshport-socks" }
+12 -2
View File
@@ -36,10 +36,16 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
## 目录
下一阶段的设计文档:[移动端 UI V4(24 页与公共状态)](docs/ui-design.md)、[组网与代理组合架构](docs/next-stage-architecture.md)。这些是拟实施方案,当前实现范围仍以下文为准。
已完成的下一阶段基础能力:[SOCKS 桥接](docs/socks-bridge.md)、[sing-box 引擎封装与本机 TCP/UDP 联调](docs/singbox-integration.md)。新增 [客户端原生绑定、代理配置与联合运行](docs/client-runtime.md),支持节点/订阅导入、规则/全局/直连和基础 DNS;[高级客户端功能](docs/advanced-client-features.md)已接入自动订阅更新、规则集、DoH/DoT、原生文件和二维码导入、登录启动与自动连接。出口仍手动选择。Android 单一 VPN 原型待真机验证,macOS 统一 TUN/helper、FakeIP 和 24 页主要界面已接入;具体测试范围及禁用功能见 [验证记录](docs/development-validation.md)。
- `crates/meshport`:Rust 公共 API。
- `crates/meshport-easytier`:固定上游快照、配置约束、实例与状态适配。
- `crates/meshport-netstack`:复用 EasyTier 已有 smoltcp 数据面,提供通信类型和回显验证。
- `crates/meshport-ffi`:C ABI、实例/连接句柄、JSON 控制接口。
- `crates/meshport-socks`:可选的本机 SOCKS5 IPv4 TCP/UDP 组网桥接,原生任务并发转发;[接入说明](docs/socks-bridge.md)。
- `engines/singbox`:固定版本 Go 引擎封装,受管理的本机组网分流与跨语言验证。
- `bindings/flutter/meshport_flutter`:Dart FFI SDK,原生调用放在后台 isolate。
- `apps/meshport_lab`:响应式 Flutter 验证工具。
- `tools/meshport-vpn-helper`:macOS 开发版特权 TUN 控制与自检。
@@ -50,12 +56,12 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
## 使用边界
- 默认应用内模式不创建 TUN/TAP,只影响 SDK 连接;macOS 开发版可切换系统组网模式,创建 utun 并安装虚拟网段路由。详见 [系统组网](docs/system-vpn.md)。
- SDK 默认应用内模式不创建 TUN/TAP,只影响 SDK 连接;Lab 客户端默认统一 VPN,使用 TUN 接入代理,也可选择仅组网模式。详见 [系统组网](docs/system-vpn.md)。
- IPv4 数据面;底层 TCP/UDP 传输。其他协议、安全模式和完整 EasyTier 配置未全部开放。
- UDP 接收当前按已经主动发送过的远端会话匹配;不支持陌生远端首包的通用 UDP 服务端监听。
- Rust API 为 async;ABI v1 是同步、每 context 串行的开发接口。Dart 放到后台 isolate 避免阻塞 UI,但尚不适合高并发/低开销的最终游戏数据面。
- 超时写入可能已经发送部分 TCP 数据,不能盲目重发。
- macOS 设置页可独立保存配置到 Keychain,启动自动回填,手动连接;扫码、文件导入、完整候选路径优化、长期压测和移动端后台运行尚未完成。
- macOS 和 Android 配置保存到用户私有目录,启动自动回填,自动连接可独立设置;旧配置支持迁移。支持扫码和文件导入,长期压测和移动端后台稳定性仍需验证。
- 稳定性页面目前执行真实的重复连接/回显探测;不表示所有设计稿中的测试模式均已实现。
线路策略和实测工具见 [跨国线路优化](docs/optimization.md)。
@@ -65,3 +71,7 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
详见 [架构](docs/architecture.md)、[配置](docs/configuration.md)、[ABI](docs/ffi-contract.md)、[验证记录](docs/testing.md)和[兼容范围](docs/compatibility.md)。
两种模式均自动学习符合规则的节点公告子网,无需填写远端 CIDR。应用内模式仅供 SDK TCP/UDP 访问;系统模式自动同步 OS 路由。规则及 macOS 启动方式见 [系统组网](docs/system-vpn.md)。
## 清理构建缓存
运行 `python3 scripts/clean-build-artifacts.py` 预览,增加 `--delete` 删除可重新生成的构建缓存和临时测试产物。脚本保留工具链、用户配置、Git 历史和 `outputs/android`、`outputs/macos` 安装包;下次构建需要重新生成缓存。
@@ -51,3 +51,9 @@ android {
flutter {
source = "../.."
}
// Offline QR decoding and an in-app camera capture Activity.
dependencies {
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
testImplementation("junit:junit:4.13.2")
}
@@ -1,4 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
@@ -8,6 +9,10 @@
android:label="MeshPort"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<!-- Override ZXing's sensorLandscape default and respect user rotation. -->
<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullUser"
tools:replace="android:screenOrientation" />
<service android:name=".MeshVpnService" android:exported="false"
android:permission="android.permission.BIND_VPN_SERVICE" android:foregroundServiceType="specialUse">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
@@ -4,6 +4,8 @@ add_library(meshport_ffi SHARED IMPORTED)
set_target_properties(meshport_ffi PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_ffi.so"
IMPORTED_NO_SONAME TRUE)
add_library(meshport_proxy SHARED IMPORTED)
set_target_properties(meshport_proxy PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_proxy.so" IMPORTED_NO_SONAME TRUE)
add_library(meshport_android SHARED bridge.cpp)
target_link_libraries(meshport_android meshport_ffi)
target_link_libraries(meshport_android meshport_ffi meshport_proxy)
target_link_options(meshport_android PRIVATE "-Wl,-z,max-page-size=16384")
@@ -2,7 +2,15 @@
#include <cstdint>
#include <cstring>
#include <string>
#include <sys/ioctl.h>
#include <linux/if_tun.h>
#include <net/if.h>
extern "C" {
uint64_t meshport_proxy_context_new();
void meshport_proxy_context_free(uint64_t);
char* meshport_proxy_call(uint64_t, const char*);
void meshport_proxy_string_free(char*);
void meshport_proxy_set_socket_protector(uintptr_t);
uint64_t meshport_context_new();
void meshport_context_free(uint64_t);
char* meshport_call(uint64_t, const char*);
@@ -21,6 +29,7 @@ static bool protectSocket(int fd) {
if (attached) vm->DetachCurrentThread();
return ok;
}
static int proxyProtectSocket(int fd) { return protectSocket(fd) ? 1 : 0; }
extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
vm = value;
JNIEnv* env = nullptr;
@@ -31,6 +40,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
protectMethod = env->GetStaticMethodID(bridge, "protectFd", "(I)Z");
if (!protectMethod) return JNI_ERR;
meshport_set_android_socket_protector(protectSocket);
meshport_proxy_set_socket_protector(reinterpret_cast<uintptr_t>(proxyProtectSocket));
return JNI_VERSION_1_6;
}
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newContext(JNIEnv*, jobject) {
@@ -39,7 +49,7 @@ extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_n
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeContext(JNIEnv*, jobject, jlong handle) {
meshport_context_free(static_cast<uint64_t>(handle));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) {
static jstring controlCall(JNIEnv* env, jlong handle, jstring text, bool proxy) {
auto stringClass = env->FindClass("java/lang/String");
auto charset = env->NewStringUTF("UTF-8");
auto getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
@@ -49,11 +59,25 @@ extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge
if (size > 131072) return env->NewStringUTF("{\"ok\":false,\"error\":\"Request too large\"}");
std::string input(size, '\0');
env->GetByteArrayRegion(bytes, 0, size, reinterpret_cast<jbyte*>(input.data()));
char* response = meshport_call(static_cast<uint64_t>(handle), input.c_str());
char* response = (proxy ? meshport_proxy_call : meshport_call)(static_cast<uint64_t>(handle), input.c_str());
if (!response) return nullptr;
auto output = env->NewByteArray(static_cast<jsize>(strlen(response)));
env->SetByteArrayRegion(output, 0, env->GetArrayLength(output), reinterpret_cast<jbyte*>(response));
meshport_string_free(response);
(proxy ? meshport_proxy_string_free : meshport_string_free)(response);
auto constructor = env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V");
return static_cast<jstring>(env->NewObject(stringClass, constructor, output, charset));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,false); }
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newProxyContext(JNIEnv*, jobject) {
return static_cast<jlong>(meshport_proxy_context_new());
}
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeProxyContext(JNIEnv*, jobject, jlong handle) {
meshport_proxy_context_free(static_cast<uint64_t>(handle));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_proxyCall(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,true); }
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_tunName(JNIEnv* env, jobject, jint fd) {
struct ifreq request{};
if (ioctl(fd,TUNGETIFF,&request)<0) return nullptr;
return env->NewStringUTF(request.ifr_name);
}
@@ -0,0 +1,83 @@
package com.example.meshport_lab
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.PosixFilePermissions
/** App-private local profiles. Legacy access is used once and never on save. */
class LocalProfileFiles(val root: File, private val namespace: String, private val legacyRead: () -> String?) {
init { require(namespace == "proxy" || namespace == "profile") }
private val name = if (namespace == "proxy") "proxy-profile.json" else "network-profile.toml"
private val file get() = File(root, name).toPath()
private val done get() = File(root, ".$name.migrated").toPath()
private val pending get() = File(root, ".$name.migration-pending").toPath()
private fun exists(path: java.nio.file.Path) = Files.exists(path, NOFOLLOW_LINKS)
private fun prepare() {
val path = root.toPath()
if (!exists(path)) Files.createDirectories(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
check(Files.isDirectory(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration directory" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwx------"))
}
private fun verify(path: java.nio.file.Path) {
check(Files.isRegularFile(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration file" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-------"))
}
private fun write(data: ByteArray, target: java.nio.file.Path) {
prepare()
if (exists(target)) verify(target)
val temp = Files.createTempFile(root.toPath(), ".profile-", ".tmp",
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")))
try {
FileChannel.open(temp, StandardOpenOption.WRITE).use { channel ->
val buffer = ByteBuffer.wrap(data)
while (buffer.hasRemaining()) channel.write(buffer)
channel.force(true)
}
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} finally { Files.deleteIfExists(temp) }
}
private fun finish() {
write(byteArrayOf(), done)
if (exists(pending)) { verify(pending); Files.delete(pending) }
}
fun save(text: String) {
val data = text.toByteArray(Charsets.UTF_8)
require(data.size <= 65536) { "Configuration exceeds storage limit" }
write(data, file)
finish()
}
fun load(): String? {
prepare()
if (exists(file)) {
verify(file)
check(Files.size(file) <= 65536) { "Configuration exceeds storage limit" }
return Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(Files.readAllBytes(file))).toString()
}
if (exists(done) || exists(pending)) return null
return try {
val text = legacyRead()
if (text == null) finish() else save(text)
text
} catch (_: Exception) { write(byteArrayOf(), pending); null }
}
fun migrationPending(): Boolean { prepare(); return exists(pending) }
fun migratePending() {
prepare()
if (!exists(pending)) return
if (exists(file)) { verify(file); finish(); return }
val text = legacyRead()
if (text == null) finish() else save(text)
}
fun delete() {
prepare()
if (exists(file)) { verify(file); Files.delete(file) }
finish() // Do not resurrect a deleted local profile from legacy storage.
}
}
@@ -4,6 +4,19 @@ import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.app.Activity
import android.graphics.BitmapFactory
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.multi.GenericMultipleBarcodeReader
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import android.content.Intent
import android.net.VpnService
import android.os.Handler
@@ -16,9 +29,41 @@ class MainActivity : FlutterActivity() {
private val background = Executors.newSingleThreadExecutor()
private val main = Handler(Looper.getMainLooper())
private var permissionResult: MethodChannel.Result? = null
private var importResult: MethodChannel.Result? = null
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
try {
if (call.method == "scan_qr") {
val options = ScanOptions().setDesiredBarcodeFormats(ScanOptions.QR_CODE).setBeepEnabled(false).setPrompt("扫描配置二维码").setOrientationLocked(false)
startActivityForResult(ScanContract().createIntent(this, options), 2003)
} else {
val image = call.method == "import_qr_image"
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(if (image) "image/*" else "*/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(intent, if (image) 2002 else 2001)
}
} catch (_: Exception) { importResult=null;result.error("IMPORT_UNAVAILABLE", "No file picker or camera available", null) }
return@setMethodCallHandler
}
if (call.method == "startup_status" || call.method == "set_startup") {
val prefs = getSharedPreferences("startup",MODE_PRIVATE)
if (call.method == "set_startup") {
val args = call.arguments as? Map<*, *>
if (args?.containsKey("login") == true) {result.error("UNSUPPORTED", "Android does not use macOS login items", null); return@setMethodCallHandler}
(args?.get("auto_connect") as? Boolean)?.let { prefs.edit().putBoolean("auto_connect",it).apply() }
}
result.success(mapOf("auto_connect" to prefs.getBoolean("auto_connect",false),"login_status" to "unsupported"));return@setMethodCallHandler
}
if (call.method == "prepare_android_vpn") {
if (permissionResult != null) { result.error("VPN_BUSY", "VPN authorization pending", null); return@setMethodCallHandler }
val intent = VpnService.prepare(this)
@@ -31,6 +76,15 @@ class MainActivity : FlutterActivity() {
try {
val profiles = ProfileStore(this)
when (call.method) {
"profile_storage_status" -> {
val pending = profiles.migrationPending() || ProfileStore(this,"proxy").migrationPending()
main.post { result.success(mapOf("path" to profiles.directory, "migration_pending" to pending)) }
}
"migrate_profiles" -> {
ProfileStore(this,"proxy").migratePending()
profiles.migratePending()
main.post { result.success(null) }
}
"debug_os_echo" -> {
check(BuildConfig.DEBUG)
val host = "10.253.79.1"
@@ -52,6 +106,9 @@ class MainActivity : FlutterActivity() {
}
main.post { result.success(true) }
}
"load_proxy_profile" -> { val value = ProfileStore(this,"proxy").load(); main.post { result.success(value) } }
"save_proxy_profile" -> { ProfileStore(this,"proxy").save(call.arguments as String); main.post { result.success(null) } }
"delete_proxy_profile" -> { ProfileStore(this,"proxy").delete(); main.post { result.success(null) } }
"load_profile" -> { val value = profiles.load(); main.post { result.success(value) } }
"save_profile" -> { profiles.save(call.arguments as String); main.post { result.success(null) } }
"delete_profile" -> { profiles.delete(); main.post { result.success(null) } }
@@ -101,6 +158,46 @@ class MainActivity : FlutterActivity() {
@Deprecated("Legacy VPN permission result")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode in 2001..2003) {
val pending = importResult; importResult=null
if (pending == null) return
if (resultCode != Activity.RESULT_OK) { pending.success(null);return }
if (requestCode == 2003) {
val contents = ScanContract().parseResult(resultCode,data).contents
if (contents != null && contents.toByteArray(Charsets.UTF_8).size > 1024*1024) pending.error("IMPORT_LIMIT","QR payload too large",null) else pending.success(contents)
return
}
val uri=data?.data
if(uri==null) {pending.error("IMPORT_FAILED","No file selected",null);return}
background.execute {
try {
val max = if(requestCode==2002) 20*1024*1024 else 1024*1024
val bytes = contentResolver.openInputStream(uri)?.use { input ->
val output=ByteArrayOutputStream();val buffer=ByteArray(8192)
while(true) {val n=input.read(buffer);if(n<0) break;require(output.size()+n <= max);output.write(buffer,0,n)}
output.toByteArray()
} ?: error("Unreadable file")
val text = if(requestCode==2001) {
Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString()
} else {
val bounds=BitmapFactory.Options().apply {inJustDecodeBounds=true}
BitmapFactory.decodeByteArray(bytes,0,bytes.size,bounds)
require(bounds.outWidth>0 && bounds.outHeight>0 && bounds.outWidth.toLong()*bounds.outHeight<=20000000)
val bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.size) ?: error("Invalid image")
try {
val pixels=IntArray(bitmap.width*bitmap.height);bitmap.getPixels(pixels,0,bitmap.width,0,0,bitmap.width,bitmap.height)
val binary=BinaryBitmap(HybridBinarizer(RGBLuminanceSource(bitmap.width,bitmap.height,pixels)))
val hints=mapOf(DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE))
val codes=GenericMultipleBarcodeReader(MultiFormatReader()).decodeMultiple(binary,hints).map {it.text}.toSet()
require(codes.size==1);codes.single()
} finally {bitmap.recycle()}
}
require(text.toByteArray(Charsets.UTF_8).size<=1024*1024)
main.post {pending.success(text)}
} catch (_:Exception) {main.post {pending.error("IMPORT_FAILED","Invalid, oversized file or no unique QR code",null)}}
}
return
}
if (requestCode == 1001) {
Log.i("MeshPortVPN", "VPN permission result: $resultCode")
val pending = permissionResult; permissionResult = null
@@ -111,6 +208,7 @@ class MainActivity : FlutterActivity() {
override fun onDestroy() {
permissionResult?.error("VPN_CANCELLED", "Activity closed during VPN authorization", null)
permissionResult = null
importResult?.error("IMPORT_CANCELLED", "Activity closed", null); importResult=null
background.shutdown()
super.onDestroy()
}
@@ -22,6 +22,13 @@ class MeshVpnService : VpnService() {
val worker = ScheduledThreadPoolExecutor(1)
private var handle = 0L
private var tun: ParcelFileDescriptor? = null
private var proxyHandle = 0L
private var unified = false
private var meshEnabled = true
private var proxyProfile = JSONObject()
private val protected = sortedSetOf<String>()
private var physical: android.net.Network? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var ipv4 = ""
private var installed = emptyList<String>()
private var running = false
@@ -33,14 +40,18 @@ 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 {
if (unified) {
check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running")
if (!meshEnabled) return@scheduleWithFixedDelay
}
val snapshot = native(JSONObject().put("op", "status")).getJSONObject("data")
val routes = snapshot.getJSONObject("platform_network").getJSONArray("subnet_routes")
val next = (0 until routes.length()).map { routes.getString(it) }.sorted()
if (next != installed) rebuild(next)
if (next != installed) { if (unified) restartProxy(next) else rebuild(next) }
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
}, 2, 2, TimeUnit.SECONDS)
}
@@ -59,6 +70,13 @@ class MeshVpnService : VpnService() {
try {
handle = NativeBridge.newContext()
val config = request.getString("toml")
unified = request.has("unified_profile")
if (unified) {
proxyProfile = JSONObject(request.getJSONObject("unified_profile").toString())
meshEnabled = proxyProfile.optString("feature", "combined") != "proxy"
startUnified(config)
return JSONObject().put("ok",true).put("data", JSONObject().put("started",true))
}
val validation = native(JSONObject().put("op", "validate").put("toml", config).put("include_profile", true)).getJSONObject("data")
check(validation.getString("runtime_mode") == "system_vpn")
ipv4 = validation.getJSONObject("profile").getString("ipv4")
@@ -73,7 +91,7 @@ class MeshVpnService : VpnService() {
"stop" -> { shutdown(); stopSelf(); JSONObject().put("ok", true).put("data", JSONObject()) }
"status" -> {
if (!running) JSONObject().put("ok", true).put("data", JSONObject().put("state", if (failure == null) "Stopped" else "Failed").put("peer_count", 0))
else native(request).also { reply ->
else (if (unified) unifiedStatus() else native(request)).also { reply ->
reply.getJSONObject("data").getJSONObject("platform_network")
.put("installed_subnet_routes", org.json.JSONArray(installed)).put("route_installation", "android_vpn")
}
@@ -142,8 +160,118 @@ class MeshVpnService : VpnService() {
previous?.close()
} catch (error: Exception) { next.close(); throw error }
}
private fun proxyCall(value: JSONObject): JSONObject {
val result = JSONObject(NativeBridge.proxyCall(proxyHandle, value.toString()))
check(result.optBoolean("ok")) { result.optString("error", "Proxy engine failed") }
return result
}
private fun physicalNetwork(): android.net.Network {
val manager = getSystemService(ConnectivityManager::class.java)
return manager.allNetworks.firstOrNull {
val caps = manager.getNetworkCapabilities(it)
caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
} ?: error("No physical network available")
}
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" }
native(JSONObject().put("op","start").put("toml",config))
val bridge = native(JSONObject().put("op","socks_start")).getJSONObject("data").getString("listen")
proxyProfile.put("mesh_socks", bridge)
}
val builder = Builder().setSession("MeshPort · 代理与组网").setMtu(1280)
.addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126)
val internet = proxyProfile.optString("feature","combined") != "mesh"
val routes = if (meshEnabled) {
val state = native(JSONObject().put("op","status")).getJSONObject("data")
val address = state.optString("ipv4").split('/')
check(address.size == 2 && address[0].isNotEmpty()) { "Static mesh address required for unified VPN" }
val prefix = IpPrefix(InetAddress.getByName(address[0]),address[1].toInt())
val virtual = "${prefix.address.hostAddress}/${prefix.prefixLength}"
protected.add(virtual)
val list = state.getJSONObject("platform_network").getJSONArray("subnet_routes")
(0 until list.length()).map { list.getString(it) }
} else emptyList()
if (internet) {
builder.addRoute("0.0.0.0",0).addRoute("::",0).addDnsServer("172.19.0.2")
} else {
for (route in protected + routes) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) }
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() } }
}
manager.registerNetworkCallback(android.net.NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(),networkCallback!!)
}
private fun updatePhysical() {
if (!running || !unified) return
try {
val next = physicalNetwork()
if (next != physical) { physical=next;setUnderlyingNetworks(arrayOf(next));restartProxy(installed) }
} catch (_: Exception) { failure="物理网络已断开,请重新连接";shutdown();stopSelf() }
}
private fun restartProxy(routes: List<String>) {
proxyCall(JSONObject().put("op","stop"))
val config = JSONObject(proxyProfile.toString())
val active = routes.toMutableSet()
if (meshEnabled) {
val state = native(JSONObject().put("op","status")).getJSONObject("data")
val value = state.getString("ipv4").split('/')
val prefix = IpPrefix(InetAddress.getByName(value[0]),value[1].toInt())
active.add("${prefix.address.hostAddress}/${prefix.prefixLength}")
protected.addAll(active)
}
val manager = getSystemService(ConnectivityManager::class.java)
val iface = manager.getLinkProperties(physical!!)?.interfaceName ?: error("Physical interface unavailable")
val index = java.net.NetworkInterface.getByName(iface)?.index ?: error("Physical index unavailable")
if (proxyProfile.optString("feature") == "mesh" && routes != installed) {
val builder = Builder().setSession("MeshPort · 组网").setMtu(1280)
.addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126).allowFamily(OsConstants.AF_INET6)
for (route in protected) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) }
val previous=tun
try { tun=builder.establish() ?: error("VPN authorization revoked") } finally { previous?.close() }
}
config.put("listen_port",10818).put("mesh_cidrs",org.json.JSONArray(active.sorted()))
.put("protected_cidrs",org.json.JSONArray(protected))
.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 {
val data = if (meshEnabled) native(JSONObject().put("op","status")).getJSONObject("data")
else JSONObject().put("state","Running").put("peer_count",0)
data.put("runtime_mode","unified_vpn").put("proxy",proxyCall(JSONObject().put("op","status")).getJSONObject("data"))
val platform = data.optJSONObject("platform_network") ?: JSONObject()
platform.put("ready",tun!=null).put("route_installation","singbox_tun").put("protected_subnets",org.json.JSONArray(protected))
data.put("platform_network",platform)
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)
networkCallback?.let { try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {} }
networkCallback = null; physical = null; protected.clear(); unified = false
if (handle != 0L) { NativeBridge.freeContext(handle); handle = 0L }
tun?.close(); tun = null; installed = emptyList()
}
@@ -2,6 +2,10 @@ package com.example.meshport_lab
object NativeBridge {
init { System.loadLibrary("meshport_android") }
external fun tunName(fd: Int): String?
external fun newProxyContext(): Long
external fun freeProxyContext(handle: Long)
external fun proxyCall(handle: Long, request: String): String
external fun newContext(): Long
external fun freeContext(handle: Long)
external fun call(handle: Long, request: String): String
@@ -1,40 +1,30 @@
package com.example.meshport_lab
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.io.File
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class ProfileStore(context: Context, namespace: String = "profile") {
private val prefs = context.getSharedPreferences("meshport_$namespace", Context.MODE_PRIVATE)
private val alias = "MeshPort.Network.$namespace"
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey(alias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
fun save(config: String) {
require(config.toByteArray(Charsets.UTF_8).size <= 65536)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val data = cipher.doFinal(config.toByteArray(Charsets.UTF_8))
check(prefs.edit().putString("data", Base64.encodeToString(data, Base64.NO_WRAP))
.putString("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).commit())
}
fun load(): String? {
private val local = LocalProfileFiles(File(context.filesDir, "MeshPort"), namespace, ::loadLegacy)
val directory: String get() = local.root.absolutePath
private fun loadLegacy(): String? {
val data = prefs.getString("data", null) ?: return null
val iv = prefs.getString("iv", null) ?: error("Missing profile IV")
val iv = prefs.getString("iv", null) ?: error("Missing legacy profile IV")
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val key = store.getKey(alias, null) as? SecretKey ?: error("Legacy profile key unavailable")
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
return cipher.doFinal(Base64.decode(data, Base64.NO_WRAP)).toString(Charsets.UTF_8)
}
fun delete() { check(prefs.edit().clear().commit()) }
fun save(config: String) = local.save(config)
fun load(): String? = local.load()
fun delete() = local.delete()
fun migrationPending(): Boolean = local.migrationPending()
fun migratePending() = local.migratePending()
}
@@ -0,0 +1,68 @@
package com.example.meshport_lab
import org.junit.Test
import org.junit.After
import org.junit.Assert.*
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
class LocalProfileFilesTest {
private val root = Files.createTempDirectory("meshport-profile-tests").toFile()
@After fun cleanup() { Files.walk(root.toPath()).use { it.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) } }
@Test fun migrationAndReadsUseLocalFilesWithPrivatePermissions() {
var legacyReads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { legacyReads++; "{\"nodes\":[]}" }
assertEquals("{\"nodes\":[]}", store.load())
store.save("{\"nodes\":[\"fixture\"]}")
assertEquals("{\"nodes\":[\"fixture\"]}", store.load())
assertEquals(1, legacyReads)
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(dir.toPath()))
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(dir.resolve("proxy-profile.json").toPath()))
val reopened = LocalProfileFiles(dir, "proxy") { error("Unexpected legacy access") }
assertEquals(store.load(), reopened.load())
store.delete()
assertNull(store.load())
assertEquals(1, legacyReads)
}
@Test fun failedMigrationIsNotRepeatedAndCanBeRetriedExplicitly() {
var reads = 0
var available = false
val store = LocalProfileFiles(root.resolve("MeshPort"), "profile") {
reads++; check(available); "network_name = \"fixture\""
}
assertNull(store.load())
assertNull(store.load())
assertEquals(1, reads)
assertTrue(store.migrationPending())
available = true
store.migratePending()
assertEquals("network_name = \"fixture\"", store.load())
assertFalse(store.migrationPending())
assertEquals(2, reads)
}
@Test fun rejectedWriteAndCorruptFileDoNotOverwriteValidOrLegacyData() {
var reads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { reads++; null }
store.save("valid")
assertThrows(IllegalArgumentException::class.java) { store.save("x".repeat(65537)) }
assertEquals("valid", store.load())
Files.write(dir.resolve("proxy-profile.json").toPath(), byteArrayOf(-1))
assertThrows(java.nio.charset.CharacterCodingException::class.java) { store.load() }
assertEquals(0, reads)
}
@Test fun symlinksCannotReadOrOverwriteOutsideFiles() {
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { null }
store.save("initial")
val outside = root.resolve("outside").apply { writeText("unchanged") }
val profile = dir.resolve("proxy-profile.json").toPath()
Files.delete(profile)
Files.createSymbolicLink(profile, outside.toPath())
assertThrows(IllegalStateException::class.java) { store.load() }
assertThrows(IllegalStateException::class.java) { store.save("replacement") }
assertEquals("unchanged", outside.readText())
}
}
@@ -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<void> 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<void>();
} finally {
client.close(force: true);
}
}
Future<void> 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<void> udpCheck() async {
final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
final reply = Completer<Datagram>();
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<void> tunDnsCheck() async {
final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
final reply = Completer<Datagram>();
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<bool>('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<void>('prepare_android_vpn'),
request: (request) async =>
jsonDecode(
(await channel.invokeMethod<String>(
'android_vpn_request',
jsonEncode(request),
))!,
)
as Map<String, dynamic>,
);
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<void>.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<void>.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)),
);
}
+27 -20
View File
@@ -7,26 +7,33 @@ class MeshPortApp extends StatelessWidget {
Widget build(BuildContext context) => MaterialApp(
title: 'MeshPort',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xff087d8e),
surface: const Color(0xfffaf8f4),
),
scaffoldBackgroundColor: const Color(0xfffaf8f4),
inputDecorationTheme: const InputDecorationTheme(
border: OutlineInputBorder(),
isDense: true,
),
cardTheme: CardThemeData(
elevation: 0,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: const BorderSide(color: Color(0xffe4e0d9)),
),
),
theme: meshPortTheme(),
home: const LabScreen(
initializeNative: !bool.fromEnvironment('MESHPORT_UI_PREVIEW'),
),
home: const LabScreen(),
);
}
ThemeData meshPortTheme() => ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xff087d8e),
surface: const Color(0xfffaf8f4),
),
scaffoldBackgroundColor: const Color(0xfffaf8f4),
inputDecorationTheme: const InputDecorationTheme(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
helperMaxLines: 3,
errorMaxLines: 3,
),
cardTheme: CardThemeData(
elevation: 0,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: const BorderSide(color: Color(0xffe4e0d9)),
),
),
);
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// The dialog owns its controller until the route has actually been removed.
class ConfigImportDialog extends StatefulWidget {
@@ -15,16 +16,60 @@ class _ConfigImportDialogState extends State<ConfigImportDialog> {
super.dispose();
}
String error = '';
Future<void> read(String method) async {
try {
final value = await const MethodChannel(
'meshport/system_vpn',
).invokeMethod<String>(method);
if (value != null && mounted) {
setState(() {
editor.text = value;
error = '';
});
}
} catch (_) {
if (mounted) setState(() => error = '导入失败,请检查权限或文件格式');
}
}
@override
Widget build(BuildContext context) => AlertDialog(
title: const Text('导入 TOML'),
content: SizedBox(
width: 560,
child: TextField(
controller: editor,
maxLines: 12,
autofocus: true,
decoration: const InputDecoration(hintText: '粘贴完整配置。不支持的配置将拒绝导入。'),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Wrap(
spacing: 8,
children: [
TextButton(
onPressed: () => read('import_file'),
child: const Text('文件'),
),
TextButton(
onPressed: () => read('scan_qr'),
child: const Text('扫码'),
),
TextButton(
onPressed: () => read('import_qr_image'),
child: const Text('二维码图片'),
),
],
),
if (error.isNotEmpty) Text(error),
Flexible(
child: TextField(
controller: editor,
maxLines: 12,
autofocus: true,
decoration: const InputDecoration(
hintText: '粘贴完整配置。不支持的配置将拒绝导入。',
),
),
),
],
),
),
actions: [
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,425 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'network_telemetry.dart';
class LiveDetailPage extends StatefulWidget {
final String title;
final Widget Function() builder;
const LiveDetailPage({super.key, required this.title, required this.builder});
@override
State<LiveDetailPage> createState() => _LiveDetailPageState();
}
class _LiveDetailPageState extends State<LiveDetailPage> {
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 820),
child: widget.builder(),
),
),
),
);
}
class NodeDetailBody extends StatelessWidget {
final Map<String, dynamic> node, status;
final Map<String, dynamic>? peer;
const NodeDetailBody({
super.key,
required this.node,
required this.peer,
required this.status,
});
@override
Widget build(BuildContext context) {
final direct =
peer?['direct'] == true &&
(node['next_hop_peer_id'] == null ||
node['next_hop_peer_id'] == node['peer_id']);
final measured = direct ? (peer?['latency_ms']) : null;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'${node['hostname'] ?? node['peer_id']}',
style: Theme.of(context).textTheme.headlineSmall,
),
ListTile(
title: const Text('当前路径'),
subtitle: Text(
'${direct ? '直连' : '中继'} · 下一跳 ${node['next_hop_peer_id'] ?? node['peer_id']}',
),
),
ListTile(
title: const Text('直连能力'),
subtitle: Text(
'${peer?['direct'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}',
),
),
ListTile(
title: Text(measured != null ? '链路 RTT' : '路由估算'),
subtitle: Text(
'${measured ?? node['estimated_latency_ms'] ?? '未测得'}${measured != null || node['estimated_latency_ms'] != null ? ' ms' : ''}',
),
),
ListTile(
title: const Text('虚拟地址 / NAT'),
subtitle: Text(
'${node['ipv4'] ?? '—'} · ${node['udp_nat_type'] ?? '未知'}',
),
),
ListTile(
title: const Text('当前链路上传 / 下载'),
subtitle: Text(
peer == null
? '通过下一跳,未单独计量'
: '↑ ${formatBytes(peer?['tx_bytes_per_second'], rate: true)} · ↓ ${formatBytes(peer?['rx_bytes_per_second'], rate: true)}',
),
),
ListTile(
title: const Text('链路累计'),
subtitle: Text(
'↑ ${formatBytes(peer?['tx_bytes'])} · ↓ ${formatBytes(peer?['rx_bytes'])}',
),
),
const Text('隧道统计包含控制流量。页面显示最近 SDK 采样;没有采样时间的值不保证是即时测量。'),
const Divider(),
const Text('发布子网'),
for (final subnet in node['advertised_subnets'] as List? ?? [])
ListTile(title: Text('$subnet')),
const Divider(),
Text('核心 ${node['version'] ?? '未知'} · 节点 ID ${node['peer_id']}'),
],
);
}
}
class SubnetListPageBody extends StatelessWidget {
final Map<String, dynamic> status;
final Map<String, dynamic> Function()? statusProvider;
const SubnetListPageBody({
super.key,
required this.status,
this.statusProvider,
});
@override
Widget build(BuildContext context) {
final platform = status['platform_network'] as Map? ?? {};
final accepted = (platform['subnet_routes'] as List? ?? [])
.cast<String>()
.toSet();
final installed = (platform['installed_subnet_routes'] as List? ?? [])
.cast<String>()
.toSet();
final protected = (platform['protected_subnets'] as List? ?? [])
.cast<String>()
.toSet();
final sources = <String, List<Map<String, dynamic>>>{};
for (final row in status['routes'] as List? ?? []) {
for (final subnet in row['advertised_subnets'] as List? ?? []) {
sources
.putIfAbsent('$subnet', () => [])
.add(Map<String, dynamic>.from(row));
}
}
final all = {...sources.keys, ...accepted, ...protected};
final system =
status['runtime_mode'] == 'system_vpn' ||
status['runtime_mode'] == 'unified_vpn';
String label(String subnet) {
if (accepted.contains(subnet)) {
return system
? (platform['ready'] == true &&
(installed.contains(subnet) ||
platform['route_installation'] == 'macos_unified_tun')
? '已生效 · 系统接入'
: '接入中 / 待确认')
: '已生效 · 应用内可用';
}
if (protected.contains(subnet)) return '已失效 · 保护中';
return '已学习 · 未接入(查看详情)';
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'已学习 ${sources.length} · 当前接受 ${accepted.length} · 保护 ${protected.length}',
),
const Text('自动学习合规公告,无远端手动列表。合规判定由 SDK 执行;不接管所有私网。'),
if (all.isEmpty)
const Padding(padding: EdgeInsets.all(24), child: Text('暂无子网公告')),
for (final subnet in all)
Card(
child: ListTile(
title: Text(subnet),
subtitle: Text(label(subnet)),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => LiveDetailPage(
title: '子网详情',
builder: () => SubnetDetailBody(
subnet: subnet,
status: statusProvider?.call() ?? status,
),
),
),
),
),
),
],
);
}
}
class LogsPageBody extends StatelessWidget {
final List<String> logs;
final VoidCallback onClear;
const LogsPageBody({super.key, required this.logs, required this.onClear});
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'显示本次应用会话最近 300 条事件。macOS 同步写入系统日志,可在 Console 中筛选 MeshPort / Runtime。复制保留节点地址,隐藏认证信息。',
),
Wrap(
spacing: 12,
children: [
OutlinedButton(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已复制当前日志')));
}
},
child: const Text('复制当前范围'),
),
TextButton(onPressed: onClear, child: const Text('清空显示')),
],
),
for (final line in logs)
Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: SelectableText(
line,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
),
),
],
);
}
class OnboardingBody extends StatelessWidget {
const OnboardingBody({super.key});
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('欢迎使用 MeshPort', style: Theme.of(context).textTheme.headlineMedium),
const ListTile(
leading: Icon(Icons.hub_outlined),
title: Text('仅组网'),
subtitle: Text('填写网络名称、密钥、虚拟 IP 和引导节点,访问游戏服务器及节点公告子网。'),
),
const ListTile(
leading: Icon(Icons.language),
title: Text('仅代理'),
subtitle: Text('导入或添加代理节点,选择规则 / 全局 / 直连。无需组网凭据。'),
),
const ListTile(
leading: Icon(Icons.route),
title: Text('代理+组网'),
subtitle: Text('两侧配置齐全后连接,组网目标优先。统一 VPN 由一个 TUN 分流。'),
),
const Text(
'应用内入口仅供 SOCKS/SDK 接入,统一 VPN 才接管系统应用。管理员或系统 VPN 授权在连接时请求;默认手动连接,可在启动与后台设置中开启自动连接。',
),
],
);
}
class StartupPageBody extends StatefulWidget {
final MethodChannel channel;
const StartupPageBody({super.key, required this.channel});
@override
State<StartupPageBody> createState() => _StartupPageBodyState();
}
class _StartupPageBodyState extends State<StartupPageBody> {
Map<String, dynamic> preferences = {};
bool loading = true;
String error = '';
@override
void initState() {
super.initState();
unawaited(load());
}
Future<void> load() async {
try {
final status = await widget.channel.invokeMapMethod<String, dynamic>(
'startup_status',
);
if (mounted) setState(() => preferences = status ?? {});
} catch (_) {
if (mounted) setState(() => error = '此平台尚未接入启动管理');
} finally {
if (mounted) setState(() => loading = false);
}
}
Future<void> update(Map<String, dynamic> changes) async {
setState(() {
loading = true;
error = '';
});
try {
final status = await widget.channel.invokeMapMethod<String, dynamic>(
'set_startup',
changes,
);
if (mounted) setState(() => preferences = status ?? {});
} catch (_) {
if (mounted) {
setState(() => error = '设置失败。请将 APP 安装到 Applications,并检查系统登录项权限。');
}
} finally {
if (mounted) setState(() => loading = false);
}
}
@override
Widget build(BuildContext context) => Column(
children: [
if (error.isNotEmpty) Text(error),
const ListTile(
title: Text('启动回填已保存配置'),
subtitle: Text('网络及代理配置从安全存储读取。'),
),
SwitchListTile(
value: preferences['auto_connect'] == true,
onChanged: loading || !(Platform.isMacOS || Platform.isAndroid)
? null
: (v) => update({'auto_connect': v}),
title: const Text('自动连接'),
subtitle: const Text('下次启动按已保存入口与代理开关连接;需要时请求管理员授权。启动失败不反复重试。'),
),
SwitchListTile(
value: [
'enabled',
'requires_approval',
].contains(preferences['login_status']),
onChanged:
loading ||
!Platform.isMacOS ||
preferences['login_status'] == 'unsupported'
? null
: (v) => update({'login': v}),
title: const Text('登录时启动'),
subtitle: Text(
'macOS 13+ · 当前状态:${preferences['login_status'] ?? '读取中'}',
),
),
if (preferences['login_status'] == 'requires_approval')
TextButton(
onPressed: () =>
widget.channel.invokeMethod<void>('open_login_settings'),
child: const Text('打开系统登录项,允许 MeshPort'),
),
TextButton(onPressed: loading ? null : load, child: const Text('刷新系统状态')),
const Text('登录启动与自动连接可分别开启。默认关闭;退出后不会自动重新抢占 VPN。'),
ListTile(
title: const Text('后台运行'),
subtitle: Text(
Platform.isAndroid
? 'VPN 使用前台服务。被其他 VPN 替换时停止。'
: '退出应用会停止网络;订阅定时更新仅在应用运行期间执行。',
),
),
],
);
}
class SubnetDetailBody extends StatelessWidget {
final String subnet;
final Map<String, dynamic> status;
const SubnetDetailBody({
super.key,
required this.subnet,
required this.status,
});
@override
Widget build(BuildContext context) {
final platform = status['platform_network'] as Map? ?? {};
final accepted = (platform['subnet_routes'] as List? ?? []).contains(
subnet,
);
final protected = (platform['protected_subnets'] as List? ?? []).contains(
subnet,
);
final installed = (platform['installed_subnet_routes'] as List? ?? [])
.contains(subnet);
final system = [
'system_vpn',
'unified_vpn',
].contains(status['runtime_mode']);
final ready = platform['ready'] == true;
final sources = (status['routes'] as List? ?? []).where(
(r) => (r['advertised_subnets'] as List? ?? []).contains(subnet),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(subnet, style: Theme.of(context).textTheme.headlineSmall),
Text(
accepted
? (system
? (ready && installed ? '已生效 · 系统接入' : '接入中 / 待确认')
: '已生效 · 应用内可用')
: protected
? '已失效 · 保护中'
: '未接入',
),
for (final source in sources)
ListTile(
title: Text('发布者 ${source['hostname'] ?? source['peer_id']}'),
subtitle: Text(
'节点 ${source['peer_id']} · 下一跳 ${source['next_hop_peer_id'] ?? '未确定'}',
),
),
if (!accepted && !protected)
const Text('SDK 未接受或等待接入;可能为默认路由、公网、过宽子网、本地冲突或不可达。接口暂未提供具体拒绝原因。'),
if (!accepted && protected)
const Text('路径撤销后拒绝转发,不能回退互联网代理。显式停止会话解除保护,可能中断连接。'),
const Text('同 CIDR 发布者合并;实际下一跳由 SDK 选路。状态每 2 秒刷新。'),
],
);
}
}
File diff suppressed because it is too large Load Diff
@@ -13,8 +13,9 @@ String formatBytes(num? value, {bool rate = false}) {
}
class NodeTelemetry extends StatelessWidget {
const NodeTelemetry({super.key, required this.status});
const NodeTelemetry({super.key, required this.status, this.onNode});
final Map<String, dynamic> status;
final void Function(Map<String, dynamic>, Map<String, dynamic>?)? onNode;
@override
Widget build(BuildContext context) {
@@ -87,60 +88,63 @@ class NodeTelemetry extends StatelessWidget {
final estimated = node['estimated_latency_ms'] as num?;
final latency = measured ?? estimated;
final latencyLabel = measured != null ? '链路 RTT' : '路由估算';
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
direct ? Icons.link : Icons.alt_route,
size: 20,
color: const Color(0xff087d8e),
),
const SizedBox(width: 10),
Expanded(
child: Text(
'${node['hostname'] ?? '节点 ${node['peer_id']}'}',
style: const TextStyle(fontWeight: FontWeight.w600),
return InkWell(
onTap: onNode == null ? null : () => onNode!(node, peer),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
direct ? Icons.link : Icons.alt_route,
size: 20,
color: const Color(0xff087d8e),
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
'${node['hostname'] ?? '节点 ${node['peer_id']}'}',
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
Text(
latency == null
? '等待测量'
: '${latency.toStringAsFixed(1)} ms',
style: const TextStyle(
color: Color(0xff8a611c),
fontWeight: FontWeight.w600,
),
),
],
),
const SizedBox(height: 6),
Text(
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${direct && peer?['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
),
if (node['udp_nat_type'] != null)
Text(
latency == null
? '等待测量'
: '${latency.toStringAsFixed(1)} ms',
style: const TextStyle(
color: Color(0xff8a611c),
fontWeight: FontWeight.w600,
),
'UDP NAT:${node['udp_nat_type']} · 核心 ${node['version'] ?? '未知'}',
),
],
),
const SizedBox(height: 6),
Text(
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${direct && peer?['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
),
if (node['udp_nat_type'] != null)
if ((node['advertised_subnets'] as List? ?? []).isNotEmpty)
Text(
'发布子网:${(node['advertised_subnets'] as List).join(', ')}',
),
const SizedBox(height: 6),
Text(
'UDP NAT:${node['udp_nat_type']} · 核心 ${node['version'] ?? '未知'}',
peer == null
? '流量经下一跳 ${node['next_hop_peer_id'] ?? '—'},未单独计量'
: '↓ ${formatBytes(peer['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(peer['tx_bytes_per_second'] as num?, rate: true)}',
),
if ((node['advertised_subnets'] as List? ?? []).isNotEmpty)
Text(
'发布子网:${(node['advertised_subnets'] as List).join(', ')}',
),
const SizedBox(height: 6),
Text(
peer == null
? '流量经下一跳 ${node['next_hop_peer_id'] ?? '—'},未单独计量'
: '↓ ${formatBytes(peer['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(peer['tx_bytes_per_second'] as num?, rate: true)}',
),
if (peer != null)
Text(
'当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['tx_bytes'] as num?)}',
style: Theme.of(context).textTheme.bodySmall,
),
],
if (peer != null)
Text(
'当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['tx_bytes'] as num?)}',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}),
@@ -0,0 +1,381 @@
import 'package:flutter/material.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'configuration_pages.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
class ProxyNodeEditor extends StatefulWidget {
final ProxyNode? node;
const ProxyNodeEditor({super.key, this.node});
@override
State<ProxyNodeEditor> createState() => _ProxyNodeEditorState();
}
String headerText(dynamic value) =>
value is List ? value.map((v) => '$v').join(', ') : value?.toString() ?? '';
class _ProxyNodeEditorState extends State<ProxyNodeEditor> {
late final original = widget.node?.options ?? <String, dynamic>{};
late String protocol = original['type'] as String? ?? 'socks';
late String security = original['tls']?['reality']?['enabled'] == true
? 'reality'
: original['tls']?['enabled'] == true
? 'tls'
: 'none';
late String transport = original['transport']?['type'] as String? ?? 'tcp';
late String cipher = original['method'] as String? ?? 'aes-128-gcm';
late final label = TextEditingController(text: widget.node?.name ?? '我的节点');
late final host = TextEditingController(
text: original['server'] as String? ?? '',
);
late final port = TextEditingController(
text: '${original['server_port'] ?? 1080}',
);
late final username = TextEditingController(
text: original['username'] as String? ?? '',
);
late final password = TextEditingController(
text: original['password'] as String? ?? '',
);
late final uuid = TextEditingController(
text: original['uuid'] as String? ?? '',
);
late final sni = TextEditingController(
text: original['tls']?['server_name'] as String? ?? '',
);
late final publicKey = TextEditingController(
text: original['tls']?['reality']?['public_key'] as String? ?? '',
);
late final shortId = TextEditingController(
text: original['tls']?['reality']?['short_id'] as String? ?? '',
);
late final path = TextEditingController(
text: original['transport']?['path'] as String? ?? '/',
);
late final wsHost = TextEditingController(
text: headerText(original['transport']?['headers']?['Host']),
);
late final service = TextEditingController(
text: original['transport']?['service_name'] as String? ?? '',
);
late final flow = TextEditingController(
text: original['flow'] as String? ?? '',
);
String error = '';
bool dirty = false, testing = false;
String testResult = '';
bool reveal = false;
bool get tlsSupported =>
{'http', 'vmess', 'vless', 'trojan'}.contains(protocol);
bool get transportSupported =>
{'vmess', 'vless', 'trojan'}.contains(protocol);
@override
void dispose() {
for (final c in [
label,
host,
port,
username,
password,
uuid,
sni,
publicKey,
shortId,
path,
wsHost,
service,
flow,
]) {
c.dispose();
}
super.dispose();
}
Widget field(
String title,
TextEditingController controller, {
bool secret = false,
}) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextField(
controller: controller,
onChanged: (_) => setState(() => dirty = true),
obscureText: secret && !reveal,
decoration: InputDecoration(labelText: title),
),
);
Widget choose(
String title,
String value,
List<String> values,
void Function(String) changed,
) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: DropdownButtonFormField<String>(
isExpanded: true,
key: ValueKey('$title-$value'),
initialValue: value,
decoration: InputDecoration(labelText: title),
items: values
.map((v) => DropdownMenuItem(value: v, child: Text(v)))
.toList(),
onChanged: (v) => setState(() {
changed(v!);
dirty = true;
}),
),
);
ProxyNode draftNode() {
// Preserve supported advanced values on edits, but changing protocol resets
// its options. Imported transports that this form cannot edit use JSON.
final options = <String, dynamic>{
if (original['type'] == protocol) ...original,
'type': protocol,
'server': host.text.trim(),
'server_port': int.tryParse(port.text) ?? 0,
};
if ({'socks', 'http'}.contains(protocol)) {
options['username'] = username.text;
options['password'] = password.text;
if (protocol == 'socks') options['version'] = '5';
}
if ({'trojan', 'shadowsocks'}.contains(protocol)) {
options['password'] = password.text;
}
if ({'vmess', 'vless'}.contains(protocol)) {
options['uuid'] = uuid.text.trim();
}
if (protocol == 'shadowsocks') options['method'] = cipher;
if (protocol == 'vmess') {
options['security'] = original['security'] ?? 'auto';
}
if (protocol == 'vless') {
if (flow.text.trim().isNotEmpty) {
options['flow'] = flow.text.trim();
} else {
options.remove('flow');
}
}
if (tlsSupported && security != 'none') {
final tls = <String, dynamic>{
if (original['type'] == protocol && original['tls'] is Map)
...Map<String, dynamic>.from(original['tls']),
'enabled': true,
'server_name': sni.text.trim().isEmpty
? host.text.trim()
: sni.text.trim(),
};
tls.remove('reality');
if (security == 'reality') {
if (publicKey.text.trim().isEmpty ||
!RegExp(r'^[0-9a-fA-F]{0,16}$').hasMatch(shortId.text) ||
shortId.text.length.isOdd) {
throw const FormatException('Reality 公钥或 Short ID 无效');
}
tls['reality'] = {
'enabled': true,
'public_key': publicKey.text.trim(),
'short_id': shortId.text,
};
tls['utls'] = {
'enabled': true,
'fingerprint': original['tls']?['utls']?['fingerprint'] ?? 'chrome',
};
}
options['tls'] = tls;
} else {
options.remove('tls');
}
options.remove('transport');
if (transportSupported && transport == 'ws') {
options['transport'] = {
if (original['type'] == protocol &&
original['transport']?['type'] == 'ws')
...Map<String, dynamic>.from(original['transport']),
'type': 'ws',
'path': path.text,
'headers': {
if (original['type'] == protocol &&
original['transport']?['headers'] is Map)
...Map<String, dynamic>.from(original['transport']['headers'])
..remove('Host'),
if (wsHost.text.trim().isNotEmpty) 'Host': wsHost.text.trim(),
},
};
}
if (transportSupported && transport == 'grpc') {
options['transport'] = {
if (original['type'] == protocol &&
original['transport']?['type'] == 'grpc')
...Map<String, dynamic>.from(original['transport']),
'type': 'grpc',
'service_name': service.text.trim(),
};
}
final node = ProxyNode(
id: widget.node?.source == 'manual'
? widget.node!.id
: '${DateTime.now().microsecondsSinceEpoch}',
name: label.text.trim().isEmpty ? '我的节点' : label.text.trim(),
options: options,
);
return node;
}
void save() {
try {
final node = draftNode();
setState(() => dirty = false);
Navigator.pop(context, node);
} on FormatException catch (e) {
setState(() => error = e.message);
} catch (_) {
setState(() => error = '节点字段无效');
}
}
Future<void> testDraft() async {
if (testing) return;
setState(() => testing = true);
NativeProxyEngine? engine;
try {
final node = draftNode();
engine = await NativeProxyEngine.open();
final result = await engine.probeNode(node.options);
if (mounted) {
setState(
() => testResult =
'HTTP 检测耗时:${(result['elapsed_ms'] as num).toStringAsFixed(1)} ms · HTTP ${result['status_code']}',
);
}
} catch (_) {
if (mounted) setState(() => testResult = '草稿检测失败,请检查节点配置或网络;没有保存或切换出口。');
} finally {
try {
await engine?.close();
} finally {
if (mounted) setState(() => testing = false);
}
}
}
@override
Widget build(BuildContext context) => PopScope(
canPop: !dirty,
onPopInvokedWithResult: (didPop, result) async {
if (!didPop && await confirmDiscard(context) && context.mounted) {
Navigator.pop(context);
}
},
child: Scaffold(
appBar: AppBar(
title: Text(widget.node?.source == 'manual' ? '编辑节点' : '添加手动节点'),
actions: [
TextButton(
onPressed: testing ? null : save,
child: const Text('保存节点'),
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 16,
children: [
if (error.isNotEmpty)
Text(
error,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
if (widget.node != null && widget.node!.source != 'manual')
const Text('订阅节点保持只读,这里保存的是手动副本。'),
field('名称', label),
choose('协议', protocol, supportedProxyTypes.toList(), (v) {
protocol = v;
security = v == 'trojan' ? 'tls' : 'none';
transport = 'tcp';
}),
field('服务器', host),
field('端口', port),
if ({'socks', 'http'}.contains(protocol))
field('用户名(可选)', username),
if ({
'socks',
'http',
'trojan',
'shadowsocks',
}.contains(protocol))
field('密码', password, secret: true),
if ({'vmess', 'vless'}.contains(protocol))
field('UUID', uuid, secret: true),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('显示认证字段'),
value: reveal,
onChanged: (v) => setState(() => reveal = v),
),
if (protocol == 'shadowsocks')
choose(
'加密方法',
cipher,
{
cipher,
'aes-128-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305',
'2022-blake3-aes-128-gcm',
'2022-blake3-aes-256-gcm',
'2022-blake3-chacha20-poly1305',
}.toList(),
(v) => cipher = v,
),
if (protocol == 'vless') field('Flow(可选)', flow),
if (tlsSupported) ...[
choose(
'安全方式',
security,
protocol == 'vless' || security == 'reality'
? ['none', 'tls', 'reality']
: ['none', 'tls'],
(v) => security = v,
),
if (security != 'none') field('TLS Server Name', sni),
if (security == 'reality') ...[
field('Reality 公钥', publicKey),
field('Short ID', shortId),
],
],
if (transportSupported) ...[
choose('传输方式', transport, [
'tcp',
'ws',
'grpc',
], (v) => transport = v),
if (transport == 'ws') ...[
field('WebSocket 路径', path),
field('WebSocket Host(可选)', wsHost),
],
if (transport == 'grpc') field('gRPC Service Name', service),
],
OutlinedButton(
onPressed: testing ? null : testDraft,
child: Text(testing ? '检测中…' : '检测草稿连通性'),
),
if (testResult.isNotEmpty) Text(testResult),
const Text(
'检测使用独立本机引擎访问 HTTPS 测试目标,不保存、不安装路由、不切换运行出口。耗时不等于组网 RTT。',
),
const Text('保存为草稿,不启动正式代理,也不改变正在运行的出口。'),
],
),
),
),
),
),
);
}
@@ -0,0 +1,618 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'proxy_node_editor.dart';
import 'configuration_pages.dart';
import 'proxy_source_pages.dart';
import 'detail_pages.dart';
class ProxyPanel extends StatefulWidget {
final ProxyProfile profile;
final String entry;
final void Function(String) entryChanged;
final bool busy, running;
final bool draftChanged, saving, saveFailed;
final Future<void> Function() save, connect;
final VoidCallback changed;
final VoidCallback? showLogs;
const ProxyPanel({
super.key,
required this.profile,
required this.entry,
required this.entryChanged,
required this.busy,
required this.running,
required this.save,
required this.connect,
required this.changed,
this.showLogs,
this.draftChanged = false,
this.saving = false,
this.saveFailed = false,
});
@override
State<ProxyPanel> createState() => _ProxyPanelState();
}
class _ProxyPanelState extends State<ProxyPanel> {
ProxyProfile get p => widget.profile;
bool working = false;
String error = '';
void change(VoidCallback work) {
setState(() {
work();
error = '';
});
widget.changed();
}
Future<void> act(Future<void> Function() work) async {
if (working || widget.busy) return;
setState(() {
working = true;
error = '';
});
try {
await work();
} catch (e) {
if (mounted) {
setState(
() => error = e is FormatException
? e.message
: '操作失败,请检查配置、网络及概览中的实际运行状态。',
);
}
} finally {
if (mounted) setState(() => working = false);
}
}
Future<bool> confirm(String title, String text) async =>
await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text(title),
content: Text(text),
actions: [
TextButton(
onPressed: () => Navigator.pop(c, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(c, true),
child: const Text('确认'),
),
],
),
) ??
false;
Future<String?> input(
String title, {
String initial = '',
String hint = '',
bool secret = false,
}) => showDialog<String>(
context: context,
builder: (_) => _TextEditorDialog(
title: title,
initial: initial,
hint: hint,
secret: secret,
),
);
Future<void> importNodes() async {
final preview = await Navigator.push<Object>(
context,
MaterialPageRoute(builder: (_) => const ProxyImportPage()),
);
if (preview == null || !mounted) return;
if (preview is ImportPreview) {
change(() => p.addNodes(preview.nodes));
}
if (preview is Map<String, dynamic>) {
final sub = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: preview),
),
);
if (sub != null && mounted) {
final next = Map<String, dynamic>.from(sub)..remove('update');
change(() => p.subscriptions.add(next));
if (sub['update'] == true) await updateSubscription(next);
}
}
}
Future<void> editNode([ProxyNode? existing]) async {
final transport = existing?.options['transport']?['type'];
if (transport != null && !{'ws', 'grpc'}.contains(transport)) {
final value = await input(
'高级节点 JSON',
initial: const JsonEncoder.withIndent(
' ',
).convert({...existing!.options, 'tag': existing.name}),
);
if (value == null) return;
final preview = importProxyNodes(value);
if (preview.nodes.length != 1) throw const FormatException('只接受一个节点');
final node = preview.nodes.single;
change(() {
if (existing.source == 'manual') {
p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = ProxyNode(
id: existing.id,
name: node.name,
options: node.options,
);
} else {
p.addNodes([node]);
}
});
return;
}
final node = await Navigator.push<ProxyNode>(
context,
MaterialPageRoute(builder: (_) => ProxyNodeEditor(node: existing)),
);
if (node == null || !mounted) return;
change(
() => existing == null || existing.source != 'manual'
? p.addNodes([node])
: p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = node,
);
}
Future<void> editSubscription([Map<String, dynamic>? existing]) async {
final result = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: existing),
),
);
if (result == null || !mounted) return;
final next = Map<String, dynamic>.from(result)..remove('update');
change(
() => existing == null
? p.subscriptions.add(next)
: p.subscriptions[p.subscriptions.indexOf(existing)] = next,
);
if (result['update'] == true) await updateSubscription(next);
}
Future<void> updateSubscription(Map<String, dynamic> sub) async {
final source = sub['id'] as String;
final preview = await fetchSubscription(
sub['url'] as String,
source: source,
);
if (preview.nodes.isEmpty) throw const FormatException('订阅没有可用节点,保留原配置');
final old = p.nodes.where((n) => n.source == source).toList();
final replacement = preview.nodes.map((n) {
final retained = old
.where((o) => jsonEncode(o.options) == jsonEncode(n.options))
.firstOrNull;
return ProxyNode(
id: retained?.id ?? n.id,
name: n.name,
source: source,
options: n.options,
);
}).toList();
final removed =
p.selectedId != null &&
old.any((n) => n.id == p.selectedId) &&
!replacement.any((n) => n.id == p.selectedId);
if (!mounted ||
!await confirm(
'订阅更新预览',
'${replacement.length} 个支持节点,忽略 ${preview.unsupported} 个项目。${removed ? '当前选中节点将被删除,需重新选择;正在运行的出口保持到显式重连。' : '相同节点保留选择。'}',
)) {
return;
}
change(() {
replaceSubscription(p, source, preview, DateTime.now());
});
}
Widget subscriptionsBody() {
final disabled = working || widget.busy;
return section('订阅', [
OutlinedButton(
onPressed: disabled ? null : () => act(() => editSubscription()),
child: const Text('添加订阅'),
),
for (final sub in p.subscriptions)
ListTile(
title: Text(sub['name'] as String),
subtitle: Text(
'${sub['updated'] == null ? '尚未更新' : '更新于 ${sub['updated']}'} · ${sub['auto_update'] == true ? '自动更新 ${sub['interval_minutes'] ?? 360} 分钟' : '手动更新'}',
),
trailing: Wrap(
children: [
IconButton(
tooltip: '编辑',
onPressed: disabled
? null
: () => act(() => editSubscription(sub)),
icon: const Icon(Icons.edit_outlined),
),
IconButton(
tooltip: '更新并预览',
onPressed: disabled
? null
: () => act(() => updateSubscription(sub)),
icon: const Icon(Icons.sync),
),
IconButton(
tooltip: '删除订阅及所属节点',
onPressed: disabled
? null
: () => act(() async {
if (await confirm(
'删除订阅',
'删除该来源的节点,手动节点保留;正在运行的出口保持到重连。',
)) {
change(() {
p.nodes.removeWhere((n) => n.source == sub['id']);
p.subscriptions.remove(sub);
if (!p.nodes.any((n) => n.id == p.selectedId)) {
p.selectedId = null;
}
});
}
}),
icon: const Icon(Icons.delete_outline),
),
],
),
),
]);
}
Widget section(String title, List<Widget> children) => Card(
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 20),
for (final child in children) ...[child, const SizedBox(height: 18)],
],
),
),
);
@override
Widget build(BuildContext context) {
final disabled = widget.busy || working;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (error.isNotEmpty)
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
section('连接', [
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.feature,
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!;
if (widget.entry == 'system_vpn' && v != 'mesh') {
widget.entryChanged('unified_vpn');
}
}),
),
Text(
p.feature == 'mesh'
? '填写组网配置后连接。'
: p.mode == 'direct'
? '直连模式无需代理节点。'
: '导入节点后连接即可,已提供默认加密 DNS。',
),
if (p.feature != 'mesh')
DropdownButtonFormField<String>(
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.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(
spacing: 8,
runSpacing: 12,
children: [
OutlinedButton(
onPressed: disabled ? null : () => act(importNodes),
child: const Text('导入与预览'),
),
OutlinedButton(
onPressed: disabled ? null : () => act(() => editNode()),
child: const Text('添加节点'),
),
],
),
if (p.nodes.isEmpty) const Text('导入第一个节点即可开始;多个节点时请选择一个出口。'),
for (final node in p.nodes)
ListTile(
leading: IconButton(
tooltip: '选择出口',
icon: Icon(
p.selectedId == node.id
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
onPressed: disabled
? null
: () => change(() => p.selectedId = node.id),
),
title: Text(
node.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => ProxyNodeDetails(
node: node,
selected: node.id == p.selectedId,
select: () => change(() => p.selectedId = node.id),
edit: () => act(() => editNode(node)),
),
),
),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']} · ${node.source == 'manual' ? '手动' : '订阅'}',
),
trailing: PopupMenuButton<String>(
enabled: !disabled,
onSelected: (v) => act(() async {
if (v == 'edit') {
await editNode(node);
} else if (await confirm('删除节点', '删除草稿中的节点,不会立即改变正在运行的出口。')) {
change(() {
p.nodes.remove(node);
if (p.selectedId == node.id) p.selectedId = null;
});
}
}),
itemBuilder: (_) => [
PopupMenuItem(
value: 'edit',
child: Text(node.source == 'manual' ? '编辑' : '复制为手动节点'),
),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
),
]),
section('订阅', [
ListTile(
title: const Text('订阅管理'),
subtitle: Text('${p.subscriptions.length} 个来源'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
LiveDetailPage(title: '订阅管理', builder: subscriptionsBody),
),
),
),
]),
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<String>(
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<String>(
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<void>(
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<void>(
context,
MaterialPageRoute(
builder: (_) => DnsPage(
profile: p,
changed: widget.changed,
),
),
),
child: const Text('编辑 DNS'),
),
Text(
'FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。',
),
],
),
),
],
),
),
],
);
}
}
class _TextEditorDialog extends StatefulWidget {
final String title, initial, hint;
final bool secret;
const _TextEditorDialog({
required this.title,
required this.initial,
required this.hint,
required this.secret,
});
@override
State<_TextEditorDialog> createState() => _TextEditorDialogState();
}
class _TextEditorDialogState extends State<_TextEditorDialog> {
late final controller = TextEditingController(text: widget.initial);
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: 520,
child: TextField(
controller: controller,
autofocus: true,
maxLines: widget.secret ? 1 : 8,
obscureText: widget.secret,
decoration: InputDecoration(hintText: widget.hint),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('确定'),
),
],
);
}
@@ -0,0 +1,295 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'configuration_pages.dart';
class ProxyImportPage extends StatefulWidget {
const ProxyImportPage({super.key});
@override
State<ProxyImportPage> createState() => _ProxyImportPageState();
}
class _ProxyImportPageState extends State<ProxyImportPage> {
final input = TextEditingController();
ImportPreview? preview;
String error = '';
Future<void> importNative(String method) async {
try {
final text = await const MethodChannel(
'meshport/system_vpn',
).invokeMethod<String>(method);
if (text != null && mounted) {
setState(() {
input.text = text;
preview = null;
error = '';
});
}
} catch (_) {
if (mounted) setState(() => error = '导入失败,请检查文件格式或相机权限;此入口需要平台支持。');
}
}
@override
void dispose() {
input.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('导入代理配置')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'支持分享链接、Base64 和 sing-box JSON;只提取节点,不覆盖 TUN、DNS 或路由。文件和二维码内容先填入编辑框,预览确认后才导入。',
),
Wrap(
spacing: 8,
children: [
OutlinedButton(
onPressed: () => importNative('import_file'),
child: const Text('文件导入'),
),
OutlinedButton(
onPressed: () => importNative('scan_qr'),
child: const Text('相机扫码'),
),
OutlinedButton(
onPressed: () => importNative('import_qr_image'),
child: const Text('二维码图片'),
),
],
),
TextField(
controller: input,
maxLines: 8,
onChanged: (_) => setState(() => preview = null),
decoration: const InputDecoration(labelText: '粘贴配置内容'),
),
if (error.isNotEmpty)
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
OutlinedButton(
onPressed: () {
try {
final p = importProxyNodes(input.text);
setState(() {
preview = p;
error = '';
});
} catch (_) {
setState(() => error = '解析失败:请检查格式、字段和支持协议;输入已保留。');
}
},
child: const Text('解析并预览'),
),
if (input.text.trim().startsWith('https://') &&
!input.text.trim().contains('\n'))
TextButton(
onPressed: () => Navigator.pop(context, <String, dynamic>{
'id': 'subscription-${DateTime.now().microsecondsSinceEpoch}',
'name': '导入的订阅',
'url': input.text.trim(),
}),
child: const Text('作为订阅地址添加'),
),
if (preview != null) ...[
const Text('导入预览'),
Text(
'${preview!.nodes.length} 个支持节点,忽略 ${preview!.unsupported} 个不支持项目',
),
for (final node in preview!.nodes)
ListTile(
title: Text(node.name),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']}',
),
),
FilledButton(
onPressed: () => Navigator.pop(context, preview),
child: const Text('确认导入'),
),
],
],
),
),
);
}
class SubscriptionEditor extends StatefulWidget {
final Map<String, dynamic>? subscription;
const SubscriptionEditor({super.key, this.subscription});
@override
State<SubscriptionEditor> createState() => _SubscriptionEditorState();
}
class _SubscriptionEditorState extends State<SubscriptionEditor> {
late final name = TextEditingController(
text: widget.subscription?['name'] ?? '',
),
url = TextEditingController(text: widget.subscription?['url'] ?? '');
late bool autoUpdate = widget.subscription?['auto_update'] == true;
late int interval = widget.subscription?['interval_minutes'] ?? 360;
bool reveal = false, dirty = false;
String error = '';
@override
void dispose() {
name.dispose();
url.dispose();
super.dispose();
}
void save(bool update) {
final uri = Uri.tryParse(url.text.trim());
if (uri == null ||
uri.scheme != 'https' ||
uri.host.isEmpty ||
uri.userInfo.isNotEmpty ||
uri.fragment.isNotEmpty ||
name.text.trim().isEmpty) {
setState(() => error = '需要订阅名称和有效 HTTPS 地址,不接受 URL 认证或片段');
return;
}
setState(() => dirty = false);
Navigator.pop(context, {
...?(widget.subscription),
'auto_update': autoUpdate,
'interval_minutes': interval,
'id':
widget.subscription?['id'] ??
'subscription-${DateTime.now().microsecondsSinceEpoch}',
'name': name.text.trim(),
'url': url.text.trim(),
'update': update,
});
}
@override
Widget build(BuildContext context) => DraftScaffold(
title: '编辑订阅',
dirty: dirty,
busy: false,
save: () => save(false),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (error.isNotEmpty) Text(error),
TextField(
controller: name,
onChanged: (_) => setState(() => dirty = true),
decoration: const InputDecoration(labelText: '名称'),
),
TextField(
controller: url,
obscureText: !reveal,
onChanged: (_) => setState(() => dirty = true),
decoration: const InputDecoration(labelText: 'HTTPS 订阅地址'),
),
SwitchListTile(
value: reveal,
onChanged: (v) => setState(() => reveal = v),
title: const Text('显示订阅地址'),
),
SwitchListTile(
title: const Text('自动更新订阅'),
subtitle: const Text('应用运行期间更新;失败保留旧节点,正在运行的会话需重连才能使用新节点。'),
value: autoUpdate,
onChanged: (v) => setState(() {
autoUpdate = v;
dirty = true;
}),
),
if (autoUpdate)
DropdownButtonFormField<int>(
initialValue: interval,
items: [15, 60, 360, 720, 1440, 10080]
.map((v) => DropdownMenuItem(value: v, child: Text('$v 分钟')))
.toList(),
onChanged: (v) => setState(() {
interval = v!;
dirty = true;
}),
),
const Text('保存只修改来源地址;保存并更新会下载到暂存结果,预览确认后才替换该来源节点。手动节点保留。'),
FilledButton(onPressed: () => save(true), child: const Text('保存并更新')),
const SwitchListTile(
value: false,
onChanged: null,
title: Text('自动更新 · 暂未开放'),
),
const Text('下载限制:15 秒超时、1 MiB、禁止 HTTP 跳转。'),
],
),
);
}
class ProxyNodeDetails extends StatelessWidget {
final ProxyNode node;
final bool selected;
final VoidCallback select, edit;
const ProxyNodeDetails({
super.key,
required this.node,
required this.selected,
required this.select,
required this.edit,
});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('代理节点详情')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(node.name, style: Theme.of(context).textTheme.headlineSmall),
ListTile(
title: const Text('来源'),
subtitle: Text(node.source == 'manual' ? '手动节点' : '订阅节点 · 只读'),
),
ListTile(
title: const Text('协议 / 服务器'),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']}',
),
),
const ListTile(
title: Text('认证字段'),
subtitle: Text('默认隐藏;编辑手动节点或副本时显式查看。'),
),
ListTile(
title: const Text('安全 / 传输'),
subtitle: Text(
'${node.options['tls']?['reality']?['enabled'] == true
? 'Reality'
: node.options['tls']?['enabled'] == true
? 'TLS'
: '无 TLS'} · ${node.options['transport']?['type'] ?? 'tcp'}',
),
),
Text(selected ? '当前草稿选中出口' : '尚未选中;选择不等于启动'),
FilledButton(
onPressed: () {
select();
Navigator.pop(context);
},
child: const Text('选为草稿出口'),
),
OutlinedButton(
onPressed: edit,
child: Text(node.source == 'manual' ? '编辑节点' : '复制为手动节点'),
),
const Text(
'运行出口保持到显式重连;手动节点编辑页支持草稿 HTTP 检测。出口由用户手动选择,HTTP 检测耗时不等于 RTT。',
),
],
),
),
);
}
@@ -0,0 +1,44 @@
/// Keeps known credentials for the whole session, including replaced drafts.
class DiagnosticRedactor {
final _secrets = <String>{};
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;
}
}
+4 -1
View File
@@ -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
+16
View File
@@ -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
@@ -21,12 +21,15 @@
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A137C030AA00000000000002 /* LocalProfileStore.swift */; };
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
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 +63,14 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
A137C030AA00000000000002 /* LocalProfileStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalProfileStore.swift; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
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 = "<group>"; };
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
@@ -76,8 +82,14 @@
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
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 +97,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
4AB602CD95E220C185C9978C /* Pods_RunnerTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -92,6 +105,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B0B2671181DD147C22F9DA95 /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -125,6 +139,7 @@
331C80D6294CF71000263BE5 /* RunnerTests */,
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
7A80F7A78DF7A6F1790E273C /* Pods */,
);
sourceTree = "<group>";
};
@@ -164,6 +179,7 @@
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
A137C030AA00000000000002 /* LocalProfileStore.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -172,9 +188,25 @@
path = Runner;
sourceTree = "<group>";
};
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 = "<group>";
};
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
isa = PBXGroup;
children = (
7A55BFDF956E46C7632C102B /* Pods_Runner.framework */,
BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
@@ -186,6 +218,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 +237,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 +325,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 +385,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 */
@@ -345,6 +423,7 @@
buildActionMask = 2147483647;
files = (
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
@@ -380,6 +459,7 @@
/* Begin XCBuildConfiguration section */
331C80DB294CF71000263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -388,12 +468,13 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Debug;
};
331C80DC294CF71000263BE5 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -402,12 +483,13 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Release;
};
331C80DD294CF71000263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -416,7 +498,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Profile;
};
@@ -461,7 +543,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 +625,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 +675,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;
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -31,7 +31,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -66,7 +66,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -83,7 +83,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -4,4 +4,7 @@
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -3,10 +3,54 @@ import FlutterMacOS
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
private(set) var statusItem: NSStatusItem?
// Flutter's nib outlet is weak; retain the same window and engine while hidden.
private var retainedMainWindow: NSWindow?
override func applicationDidFinishLaunching(_ notification: Notification) {
// FlutterAppDelegate initializes its UI in applicationWillFinishLaunching;
// it has no applicationDidFinishLaunching implementation to call via super.
retainedMainWindow = mainFlutterWindow
mainFlutterWindow?.isReleasedWhenClosed = false
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
let image = NSImage(systemSymbolName: "network", accessibilityDescription: "MeshPort")
image?.isTemplate = true
item.button?.image = image
item.button?.toolTip = "MeshPort"
item.button?.setAccessibilityLabel("MeshPort")
let menu = NSMenu()
let open = NSMenuItem(title: "打开 MeshPort", action: #selector(showMainWindow), keyEquivalent: "")
open.target = self
menu.addItem(open)
menu.addItem(.separator())
let quit = NSMenuItem(title: "退出 MeshPort", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp
menu.addItem(quit)
item.menu = menu
statusItem = item
}
@objc private func showMainWindow() {
guard let window = retainedMainWindow else { return }
NSApp.activate(ignoringOtherApps: true)
if window.isMiniaturized { window.deminiaturize(nil) }
window.makeKeyAndOrderFront(nil)
}
deinit {
if let item = statusItem { NSStatusBar.system.removeStatusItem(item) }
}
override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
showMainWindow()
return true
}
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return false
}
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
@@ -10,5 +10,7 @@
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
</dict>
</plist>
@@ -24,6 +24,8 @@
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSCameraUsageDescription</key>
<string>扫描二维码以导入代理或组网配置。</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
@@ -0,0 +1,141 @@
import Foundation
import Security
import Darwin
import LocalAuthentication
enum StoredProfile: CaseIterable {
case proxy, network
var fileName: String { self == .proxy ? "proxy-profile.json" : "network-profile.toml" }
var service: String { self == .proxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile" }
var account: String { self == .proxy ? "last-proxy" : "last-network" }
}
final class LocalProfileStore {
typealias LegacyReader = (StoredProfile, Bool) throws -> Data?
let root: URL
private let legacyReader: LegacyReader
private let fm = FileManager.default
private let limit = 65536
init(root: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Application Support/MeshPort", isDirectory: true),
legacyReader: @escaping LegacyReader = LocalProfileStore.readKeychain) {
self.root = root
self.legacyReader = legacyReader
}
private func failure(_ message: String) -> NSError {
NSError(domain: "MeshPort.LocalProfile", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
}
private func verify(_ url: URL, directory: Bool = false) throws {
let attrs = try fm.attributesOfItem(atPath: url.path)
guard attrs[.type] as? FileAttributeType == (directory ? .typeDirectory : .typeRegular),
(attrs[.ownerAccountID] as? NSNumber)?.uint32Value == getuid() else {
throw failure("Configuration path must be owned by the current user and cannot be a symbolic link")
}
try fm.setAttributes([.posixPermissions: directory ? 0o700 : 0o600], ofItemAtPath: url.path)
}
private func prepare() throws {
if !fm.fileExists(atPath: root.path) {
try fm.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
}
try verify(root, directory: true)
}
private func marker(_ kind: StoredProfile, _ suffix: String) -> URL {
root.appendingPathComponent(".\(kind.fileName).\(suffix)")
}
private func exists(_ url: URL) -> Bool {
// Attributes also detect dangling symlinks, which fileExists follows.
(try? fm.attributesOfItem(atPath: url.path)) != nil
}
private func atomicWrite(_ data: Data, to target: URL) throws {
try prepare()
if exists(target) { try verify(target) }
var template = Array(root.appendingPathComponent(".profile-XXXXXX").path.utf8CString)
let fd = mkstemp(&template)
guard fd >= 0 else { throw failure("Cannot create private configuration file") }
let temporary = String(cString: template)
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
defer { try? handle.close(); unlink(temporary) }
guard fchmod(fd, 0o600) == 0 else { throw failure("Cannot protect configuration file") }
try handle.write(contentsOf: data)
try handle.synchronize()
guard rename(temporary, target.path) == 0 else { throw failure("Cannot replace configuration file") }
}
private func finishMigration(_ kind: StoredProfile) throws {
try atomicWrite(Data(), to: marker(kind, "migrated"))
let pending = marker(kind, "migration-pending")
if exists(pending) { try verify(pending); try fm.removeItem(at: pending) }
}
func save(_ text: String, kind: StoredProfile) throws {
guard let data = text.data(using: .utf8), data.count <= limit else {
throw failure("Configuration exceeds storage limit")
}
try atomicWrite(data, to: root.appendingPathComponent(kind.fileName))
try finishMigration(kind)
}
func load(_ kind: StoredProfile) throws -> String? {
try prepare()
let file = root.appendingPathComponent(kind.fileName)
if exists(file) {
try verify(file)
let size = (try fm.attributesOfItem(atPath: file.path)[.size] as? NSNumber)?.intValue ?? limit + 1
guard size <= limit, let text = String(data: try Data(contentsOf: file), encoding: .utf8) else {
throw failure("Invalid local configuration")
}
return text
}
if exists(marker(kind, "migrated")) || exists(marker(kind, "migration-pending")) { return nil }
// Never show a Keychain dialog during automatic startup migration.
do { return try migrate(kind, interactive: false) }
catch {
try atomicWrite(Data(), to: marker(kind, "migration-pending"))
return nil
}
}
private func migrate(_ kind: StoredProfile, interactive: Bool) throws -> String? {
guard let data = try legacyReader(kind, interactive) else {
try finishMigration(kind)
return nil
}
guard data.count <= limit, let text = String(data: data, encoding: .utf8) else {
throw failure("Invalid legacy configuration")
}
try save(text, kind: kind)
return text
}
func migratePending() throws {
try prepare()
for kind in StoredProfile.allCases where exists(marker(kind, "migration-pending")) {
// Never overwrite local edits with the legacy backup.
if exists(root.appendingPathComponent(kind.fileName)) { try finishMigration(kind) }
else { _ = try migrate(kind, interactive: true) }
}
}
func migrationPending() throws -> Bool {
try prepare()
return StoredProfile.allCases.contains { exists(marker($0, "migration-pending")) }
}
func delete(_ kind: StoredProfile) throws {
try prepare()
let file = root.appendingPathComponent(kind.fileName)
if exists(file) { try verify(file); try fm.removeItem(at: file) }
// A deleted profile must not reappear from the old Keychain backup.
try finishMigration(kind)
}
static func readKeychain(_ kind: StoredProfile, _ interactive: Bool) throws -> Data? {
var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kind.service, kSecAttrAccount as String: kind.account,
kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]
let authentication = LAContext()
authentication.interactionNotAllowed = !interactive
query[kSecUseAuthenticationContext as String] = authentication
var value: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &value)
if status == errSecItemNotFound { return nil }
guard status == errSecSuccess, let data = value as? Data else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
return data
}
}
@@ -1,9 +1,27 @@
import Cocoa
import Security
import FlutterMacOS
import ServiceManagement
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
private let profileStore = LocalProfileStore()
private let profileQueue = DispatchQueue(label: "com.meshport.local-profiles")
override func close() {
// Hiding keeps the Flutter engine, drafts and active network sessions alive.
// Only the explicit Quit action terminates the application.
qrScanner?.cancelScan()
orderOut(nil)
}
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
@@ -13,40 +31,36 @@ class MainFlutterWindow: NSWindow {
RegisterGeneratedPlugins(registry: flutterViewController)
vpnChannel = FlutterMethodChannel(name: "meshport/system_vpn", binaryMessenger: flutterViewController.engine.binaryMessenger)
vpnChannel?.setMethodCallHandler { call, result in
let profileQuery: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "MeshPort.Lab.NetworkProfile",
kSecAttrAccount as String: "last-network"
]
if call.method == "save_profile", let config = call.arguments as? String,
config.utf8.count <= 65536, let data = config.data(using: .utf8) {
let attributes = [kSecValueData as String: data]
var status = SecItemUpdate(profileQuery as CFDictionary, attributes as CFDictionary)
if status == errSecItemNotFound {
var item = profileQuery
item[kSecValueData as String] = data
status = SecItemAdd(item as CFDictionary, nil)
vpnChannel?.setMethodCallHandler { [weak self] call, result in
guard let self = self else { result(FlutterError(code:"WINDOW_CLOSED",message:"Window closed",details:nil)); return }
if self.handleCapabilities(call, result:result) { return }
let profileMethod = call.method.replacingOccurrences(of: "_proxy_profile", with: "_profile")
if ["save_profile", "load_profile", "delete_profile", "profile_storage_status", "migrate_profiles"].contains(profileMethod) {
let kind: StoredProfile = call.method.contains("_proxy_profile") ? .proxy : .network
self.profileQueue.async {
do {
let value: Any?
switch profileMethod {
case "save_profile":
guard let text = call.arguments as? String else {
throw NSError(domain: "MeshPort.LocalProfile", code: 1)
}
try self.profileStore.save(text, kind: kind)
value = nil
case "load_profile": value = try self.profileStore.load(kind)
case "delete_profile": try self.profileStore.delete(kind); value = nil
case "migrate_profiles": try self.profileStore.migratePending(); value = nil
default:
value = ["path": self.profileStore.root.path,
"migration_pending": try self.profileStore.migrationPending()]
}
DispatchQueue.main.async { result(value) }
} catch {
DispatchQueue.main.async {
result(FlutterError(code: "PROFILE_STORAGE", message: "Could not read, save or migrate local configuration", details: (error as NSError).code))
}
}
}
if status == errSecSuccess { result(nil) }
else { result(FlutterError(code: "KEYCHAIN_SAVE", message: "Could not save network profile to Keychain", details: status)) }
return
}
if call.method == "load_profile" {
var query = profileQuery
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var value: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &value)
if status == errSecItemNotFound { result(nil) }
else if status == errSecSuccess, let data = value as? Data { result(String(data: data, encoding: .utf8)) }
else { result(FlutterError(code: "KEYCHAIN_LOAD", message: "Could not read network profile", details: status)) }
return
}
if call.method == "delete_profile" {
let status = SecItemDelete(profileQuery as CFDictionary)
if status == errSecSuccess || status == errSecItemNotFound { result(nil) }
else { result(FlutterError(code: "KEYCHAIN_DELETE", message: "Could not delete network profile", details: status)) }
return
}
guard call.method == "launch", let args = call.arguments as? [String: Any],
@@ -77,4 +91,167 @@ class MainFlutterWindow: NSWindow {
}
super.awakeFromNib()
}
private func startupStatus() -> [String: Any] {
var status = "unsupported"
if #available(macOS 13.0, *) {
switch SMAppService.mainApp.status {
case .enabled: status = "enabled"
case .requiresApproval: status = "requires_approval"
case .notRegistered: status = "disabled"
case .notFound: status = "not_found"
@unknown default: status = "unknown"
}
}
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 }
do {
if let login = args["login"] as? Bool {
if #available(macOS 13.0, *) {
if login { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }
} else { throw NSError(domain:"MeshPort",code:13) }
}
if let connect = args["auto_connect"] as? Bool { UserDefaults.standard.set(connect,forKey:"MeshPort.autoConnect") }
result(startupStatus())
} catch { result(FlutterError(code:"STARTUP_SETTINGS",message:"Unable to update login preferences; install the app in Applications and check System Settings",details:nil)) }
return true
}
if call.method == "open_login_settings" {
if #available(macOS 13.0, *) { SMAppService.openSystemSettingsLoginItems() }
result(nil); return true
}
if call.method == "import_file" || call.method == "import_qr_image" {
guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true }
importing = true
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false; panel.canChooseDirectories = false
if #available(macOS 11.0, *) {
panel.allowedContentTypes = call.method == "import_qr_image" ? [.image] : [.text,.json,.data]
}
panel.beginSheetModal(for:self) { [weak self] response in
self?.importing = false
guard response == .OK, let url = panel.url else { result(nil); return }
let access = url.startAccessingSecurityScopedResource()
defer { if access { url.stopAccessingSecurityScopedResource() } }
do {
let size = try url.resourceValues(forKeys:[.fileSizeKey]).fileSize ?? Int.max
let isImage = call.method == "import_qr_image"
guard size <= (isImage ? 20*1024*1024 : 1024*1024) else { throw NSError(domain:"MeshPort",code:1) }
if isImage {
guard let source = CGImageSourceCreateWithURL(url as CFURL,nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source,0,nil) as? [CFString:Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int,
width > 0 && height > 0 && width <= 20000000 / height else { throw NSError(domain:"MeshPort",code:2) }
let request = VNDetectBarcodesRequest(); request.symbologies = [.qr]
try VNImageRequestHandler(url:url,options:[:]).perform([request])
let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue })
guard codes.count == 1, let code = codes.first, code.utf8.count <= 1024*1024 else { throw NSError(domain:"MeshPort",code:3) }
result(code)
} else {
let data = try Data(contentsOf:url)
guard data.count <= 1024*1024, let text = String(data:data,encoding:.utf8) else { throw NSError(domain:"MeshPort",code:4) }
result(text)
}
} catch { result(FlutterError(code:"IMPORT_FAILED",message:"Invalid, oversized file or no unique QR code",details:nil)) }
}
return true
}
if call.method == "scan_qr" {
guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true }
importing = true
AVCaptureDevice.requestAccess(for:.video) { [weak self] granted in
DispatchQueue.main.async {
guard let self = self else { result(nil);return }
self.importing = false
guard granted else { result(FlutterError(code:"CAMERA_PERMISSION",message:"Allow camera access in System Settings",details:nil));return }
let scanner = MeshQRScanner { [weak self] text, failed in
self?.qrScanner = nil
if failed { result(FlutterError(code:"CAMERA_FAILED",message:"Camera unavailable",details:nil)) } else { result(text) }
}
self.qrScanner = scanner
scanner.show(on:self)
}
}
return true
}
return false
}
}
// Only the native capture/panel lifetime lives here; Flutter owns imported drafts.
private final class MeshQRPreview: NSView {
let preview: AVCaptureVideoPreviewLayer
init(session:AVCaptureSession) {
preview = AVCaptureVideoPreviewLayer(session:session)
super.init(frame:NSRect(x:0,y:0,width:640,height:400))
wantsLayer = true; preview.videoGravity = .resizeAspectFill
layer?.addSublayer(preview)
}
required init?(coder:NSCoder) { fatalError("init(coder:) unsupported") }
override func layout() { super.layout(); preview.frame = bounds }
}
private final class MeshQRScanner: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, NSWindowDelegate {
let session = AVCaptureSession()
let queue = DispatchQueue(label:"MeshPort.qrCapture")
let completion: (String?,Bool) -> Void
var panel:NSPanel?
weak var parent:NSWindow?
var finished = false, lastFrame = Date.distantPast
init(completion:@escaping (String?,Bool) -> Void) { self.completion = completion }
func show(on window:NSWindow) {
parent = window
let panel = NSPanel(contentRect:NSRect(x:0,y:0,width:640,height:450),styleMask:[.titled,.closable],backing:.buffered,defer:false)
panel.title = "扫描配置二维码"; panel.delegate = self; self.panel = panel
let preview = MeshQRPreview(session:session)
let cancel = NSButton(title:"取消",target:self,action:#selector(cancelScan))
let stack = NSStackView(views:[preview,cancel]); stack.orientation = .vertical; stack.spacing = 8
panel.contentView = stack
preview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([preview.widthAnchor.constraint(equalToConstant:640),preview.heightAnchor.constraint(equalToConstant:400)])
window.beginSheet(panel)
queue.async { [weak self] in
guard let self = self else { return }
do {
guard let device = AVCaptureDevice.default(for:.video) else { throw NSError(domain:"MeshPort",code:1) }
let input = try AVCaptureDeviceInput(device:device), output = AVCaptureVideoDataOutput()
output.alwaysDiscardsLateVideoFrames = true
output.setSampleBufferDelegate(self,queue:self.queue)
self.session.beginConfiguration()
guard self.session.canAddInput(input), self.session.canAddOutput(output) else { self.session.commitConfiguration(); throw NSError(domain:"MeshPort",code:2) }
self.session.addInput(input);self.session.addOutput(output);self.session.commitConfiguration()
self.session.startRunning()
} catch { DispatchQueue.main.async { self.finish(nil,failed:true) } }
}
}
@objc func cancelScan() { finish(nil,failed:false) }
func windowShouldClose(_ sender:NSWindow) -> Bool { cancelScan();return false }
func finish(_ text:String?,failed:Bool) {
guard !finished else { return }; finished = true
if let panel = panel { parent?.endSheet(panel);panel.orderOut(nil) }
queue.async { [self] in session.stopRunning() }
completion(text,failed)
}
func captureOutput(_ output:AVCaptureOutput,didOutput buffer:CMSampleBuffer,from connection:AVCaptureConnection) {
guard Date().timeIntervalSince(lastFrame) > 0.4 else { return };lastFrame=Date()
let request = VNDetectBarcodesRequest();request.symbologies=[.qr]
do {
guard let image = CMSampleBufferGetImageBuffer(buffer) else { return }
try VNImageRequestHandler(cvPixelBuffer:image,orientation:.up,options:[:]).perform([request])
let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue })
if codes.count == 1, let text = codes.first, text.utf8.count <= 1024*1024 { DispatchQueue.main.async { [weak self] in self?.finish(text,failed:false) } }
} catch { /* A frame may be temporarily unreadable; the user can cancel. */ }
}
}
@@ -8,5 +8,7 @@
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
</dict>
</plist>
@@ -1,12 +1,49 @@
import Cocoa
import FlutterMacOS
import XCTest
@testable import MeshPort
class RunnerTests: XCTestCase {
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
func testCloseRetainsControllerAndCanReopenSameWindow() {
let window = MainFlutterWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
let controller = NSViewController()
controller.view = NSView(frame: window.contentLayoutRect)
window.contentViewController = controller
window.makeKeyAndOrderFront(nil)
XCTAssertTrue(window.isVisible)
window.performClose(nil)
XCTAssertFalse(window.isVisible)
XCTAssertTrue(window.contentViewController === controller)
window.makeKeyAndOrderFront(nil)
XCTAssertTrue(window.isVisible)
XCTAssertTrue(window.contentViewController === controller)
window.orderOut(nil)
}
func testMenuReopensRetainedWindowAndQuitIsExplicit() {
let delegate = AppDelegate()
let window = MainFlutterWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable], backing: .buffered, defer: false)
delegate.mainFlutterWindow = window
delegate.applicationDidFinishLaunching(Notification(name: NSApplication.didFinishLaunchingNotification))
XCTAssertFalse(delegate.applicationShouldTerminateAfterLastWindowClosed(NSApp))
guard let menu = delegate.statusItem?.menu, let open = menu.items.first,
let action = open.action, let quit = menu.items.last else {
return XCTFail("Menu bar actions missing")
}
XCTAssertEqual(open.title, "打开 MeshPort")
window.close()
XCTAssertFalse(window.isVisible)
XCTAssertTrue(NSApp.sendAction(action, to: open.target, from: open))
XCTAssertTrue(window.isVisible)
XCTAssertTrue(delegate.mainFlutterWindow === window)
XCTAssertEqual(quit.title, "退出 MeshPort")
XCTAssertTrue(quit.target === NSApp)
XCTAssertEqual(quit.action, #selector(NSApplication.terminate(_:)))
window.orderOut(nil)
}
}
+14
View File
@@ -154,6 +154,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meshport_client_core:
dependency: "direct main"
description:
path: "../../packages/meshport_client_core"
relative: true
source: path
version: "0.1.0"
meshport_flutter:
dependency: "direct main"
description:
@@ -193,6 +200,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.6"
singbox_flutter:
dependency: "direct main"
description:
path: "../../bindings/flutter/singbox_flutter"
relative: true
source: path
version: "0.1.0"
sky_engine:
dependency: transitive
description: flutter
+4
View File
@@ -28,6 +28,10 @@ environment:
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
meshport_client_core:
path: ../../packages/meshport_client_core
singbox_flutter:
path: ../../bindings/flutter/singbox_flutter
meshport_flutter:
path: ../../bindings/flutter/meshport_flutter
flutter:
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/proxy_source_pages.dart';
import 'package:meshport_lab/features/detail_pages.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
void main() {
const channel = MethodChannel('meshport/system_vpn');
tearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null),
);
testWidgets('file import fills draft and requires explicit node preview', (
tester,
) async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
(call) async =>
call.method == 'import_file' ? 'socks://127.0.0.1:1001' : null,
);
await tester.pumpWidget(const MaterialApp(home: ProxyImportPage()));
await tester.tap(find.text('文件导入'));
await tester.pumpAndSettle();
expect(find.text('确认导入'), findsNothing);
await tester.tap(find.text('解析并预览'));
await tester.pumpAndSettle();
expect(find.text('确认导入'), findsOneWidget);
});
testWidgets('subscription options and metadata survive save', (tester) async {
Map<String, dynamic>? result;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () async {
result = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => const SubscriptionEditor(
subscription: {
'id': 's',
'name': 'Test',
'url': 'https://example.test/sub',
'updated': '2026-10-10T00:00:00Z',
'auto_update': true,
'interval_minutes': 360,
},
),
),
);
},
child: const Text('open'),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
await tester.tap(find.text('自动更新订阅'));
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(result?['auto_update'], false);
expect(result?['updated'], '2026-10-10T00:00:00Z');
});
testWidgets(
'startup screen reads actual status without registering login item',
(tester) async {
final calls = <String>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
calls.add(call.method);
return {'login_status': 'requires_approval', 'auto_connect': false};
});
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: StartupPageBody(channel: channel)),
),
);
await tester.pumpAndSettle();
expect(find.text('打开系统登录项,允许 MeshPort'), findsOneWidget);
expect(calls, ['startup_status']);
},
);
testWidgets('DoT default port is accepted and saved', (tester) async {
final p = ProxyProfile();
await tester.pumpWidget(
MaterialApp(
home: DnsPage(profile: p, changed: () {}),
),
);
await tester.enterText(find.byType(TextField).at(1), 'tls://dns.example');
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(p.directDnsServer, 'tls://dns.example');
});
}
@@ -0,0 +1,151 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
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()
..mode = 'bypass_cn'
..defaultAction = 'reject';
p.rules = [
{'type': 'ip_cidr', 'value': '0.0.0.0/0', 'action': 'reject'},
];
final restored = ProxyProfile.fromJson(jsonDecode(jsonEncode(p.toJson())));
expect(restored.mode, 'bypass_cn');
expect(restored.modeLabel, '绕过中国大陆');
expect(restored.rules, p.rules);
restored.mode = 'global';
expect(restored.runtime()['mode'], 'global');
expect(restored.rules, p.rules);
});
test('subscription merge preserves manual node and stable selection', () {
final p = ProxyProfile();
p.nodes = importProxyNodes(
'socks://127.0.0.1:1001\nsocks://127.0.0.1:1002',
source: 's',
).nodes;
final stable = p.nodes.first.id;
p.selectedId = stable;
final manual = importProxyNodes('socks://127.0.0.1:1003').nodes.single;
p.nodes.add(manual);
p.subscriptions = [
{'id': 's', 'auto_update': true, 'interval_minutes': 60},
];
final now = DateTime.utc(2026, 10, 11);
replaceSubscription(
p,
's',
importProxyNodes(
'socks://127.0.0.1:1001\nsocks://127.0.0.1:1004',
source: 's',
),
now,
);
expect(p.nodes.any((n) => identical(n, manual)), true);
expect(p.selectedId, stable);
expect(
subscriptionDue(
p.subscriptions.single,
now.add(const Duration(minutes: 59)),
),
false,
);
expect(
subscriptionDue(
p.subscriptions.single,
now.add(const Duration(hours: 1)),
),
true,
);
replaceSubscription(
p,
's',
importProxyNodes('socks://127.0.0.1:1005', source: 's'),
now,
);
expect(p.selectedId, isNull);
});
test(
'encrypted DNS and rulesets persist without leaking selected node into runtime storage',
() {
final p = ProxyProfile()
..directDnsServer = 'https://dns.example/dns-query'
..proxyDnsServer = 'tls://dns.example'
..proxyEnabled = true;
p.ruleSets = [
{
'tag': 'sites',
'enabled': true,
'rules': [
{
'domain_suffix': ['example.test'],
},
],
'action': 'direct',
},
];
final restored = ProxyProfile.fromJson(
jsonDecode(jsonEncode(p.toJson())),
);
expect(restored.runtime()['direct_dns_server'], p.directDnsServer);
expect(restored.ruleSets, p.ruleSets);
expect(restored.proxyEnabled, true);
for (final value in [
'https://dns.example/dns-query',
'tls://dns.example:853',
'tls://dns.example',
'1.1.1.1',
]) {
expect(validResolver(value), true);
}
for (final value in [
'http://dns.example',
'tls://dns.example/path',
'https://u:p@dns.example',
'https://dns.example:0',
'https://dns.example?x=1',
]) {
expect(validResolver(value), false);
}
},
);
}
@@ -0,0 +1,84 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
testWidgets('DNS saves FakeIP draft and keeps mesh exclusions', (
tester,
) async {
final p = ProxyProfile()
..meshDns = [
{'suffix': 'mesh.test', 'server': '10.77.0.2'},
];
bool changed = false;
await tester.pumpWidget(
MaterialApp(
home: DnsPage(profile: p, changed: () => changed = true),
),
);
await tester.tap(find.text('FakeIP'));
await tester.pumpAndSettle();
expect(p.fakeIP, isFalse);
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(p.fakeIP, isTrue);
expect(changed, isTrue);
expect(p.runtime()['mesh_dns'], isNotEmpty);
p.feature = 'proxy';
expect(p.runtime()['mesh_dns'], isEmpty);
});
testWidgets('P2P disable pauses punching without losing values', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: NetworkConfigPage(
section: '连接与打洞',
initial: {
'flags': {'disable_p2p': true, 'disable_udp_hole_punching': true},
},
save: (_) async {},
),
),
);
final switches = tester
.widgetList<SwitchListTile>(find.byType(SwitchListTile))
.toList();
expect(switches[1].onChanged, isNull);
expect(switches[1].value, isTrue);
await tester.tap(find.text('禁用 P2P'));
await tester.pumpAndSettle();
final next = tester
.widgetList<SwitchListTile>(find.byType(SwitchListTile))
.toList();
expect(next[1].onChanged, isNotNull);
expect(next[1].value, isTrue);
});
testWidgets('rule editor rejects wildcard domains', (tester) async {
await tester.pumpWidget(const MaterialApp(home: RuleEditor()));
await tester.enterText(find.byType(TextField), '*.example.com');
await tester.tap(find.text('保存规则'));
await tester.pumpAndSettle();
expect(find.text('请输入有效域名或 CIDR,不接受星号语法'), findsOneWidget);
});
test(
'network draft preserves supported options and forces encrypted single-stack host',
() {
final draft = NetworkProfile({
'runtime_mode': 'unified_vpn',
'ipv4': '10.77.0.11/24',
'network_name': 'test',
'network_secret': 'test-only',
'flags': {'disable_p2p': true},
'listeners': ['udp://0.0.0.0:11010'],
'stun_servers': [],
'optimization': {'mode': 'direct'},
});
expect(draft.toToml(), contains('no_tun = true'));
expect(draft.toToml(), contains('disable_p2p = true'));
expect(draft.toToml(), contains('enable_encryption = true'));
expect(draft.toToml(), contains('stun_servers = []'));
},
);
}
@@ -0,0 +1,55 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
void main() {
test('recovers old unlimited sentinel and preserves exact u64 limits', () {
final p = NetworkProfile({
'flags': {'foreign_relay_bps_limit': 18446744073709552000.0},
});
expect(
p.toToml(),
contains('foreign_relay_bps_limit = "18446744073709551615"'),
);
expect(
NetworkProfile.unsignedLimit('18446744073709551614'),
'18446744073709551614',
);
expect(NetworkProfile.unsignedLimit(1024), '1024');
for (final v in [-1, 1.5, '18446744073709551616', 9007199254740992.0]) {
expect(() => NetworkProfile.unsignedLimit(v), throwsFormatException);
}
});
test(
'native projected config regenerates valid TOML after editing entry',
() async {
final client = await MeshPortClient.open(
libraryPath: Platform.environment['MESHPORT_LIBRARY'],
);
try {
final original =
"ipv4 = '192.168.20.4/24'\nlisteners = []\n[network_identity]\nnetwork_name = 'test-only'\nnetwork_secret = 'test-only'\n";
final projected = await client.request({
'op': 'validate',
'toml': original,
'include_profile': true,
});
final p = NetworkProfile(
Map<String, dynamic>.from(projected['profile']),
);
p.values['runtime_mode'] = 'unified_vpn';
await client.validate(p.toToml());
expect(
p.toToml(),
contains('foreign_relay_bps_limit = "18446744073709551615"'),
);
} finally {
await client.close();
}
},
skip: Platform.environment['MESHPORT_LIBRARY'] == null
? 'Requires native Rust library'
: false,
);
}
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/proxy_node_editor.dart';
void main() {
testWidgets('subscription edit saves manual copy and preserves TLS options', (
tester,
) async {
ProxyNode? saved;
final node = ProxyNode(
id: 'subscription-node',
name: 'TLS node',
source: 'subscription-1',
options: {
'type': 'trojan',
'server': 'proxy.example.com',
'server_port': 443,
'password': 'test-secret',
'tls': {
'enabled': true,
'server_name': 'proxy.example.com',
'alpn': ['h2'],
'utls': {'enabled': true, 'fingerprint': 'firefox'},
},
},
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () async {
saved = await Navigator.push<ProxyNode>(
context,
MaterialPageRoute(
builder: (_) => ProxyNodeEditor(node: node),
),
);
},
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
final password = tester.widget<TextField>(find.byType(TextField).at(3));
expect(password.obscureText, isTrue);
await tester.tap(find.text('保存节点'));
await tester.pumpAndSettle();
expect(saved?.source, 'manual');
expect(saved?.id, isNot(node.id));
expect(saved?.options['tls']['utls']['fingerprint'], 'firefox');
expect(saved?.options['tls']['alpn'], ['h2']);
expect(tester.takeException(), isNull);
});
testWidgets('invalid server cannot be saved', (tester) async {
await tester.pumpWidget(const MaterialApp(home: ProxyNodeEditor()));
await tester.tap(find.text('保存节点'));
await tester.pumpAndSettle();
expect(find.text('代理服务器或端口无效'), findsOneWidget);
});
}
@@ -0,0 +1,104 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
void main() {
test(
'full JSON extracts nodes without importing route/DNS and deduplicates',
() {
final value = jsonEncode({
'inbounds': [
{'type': 'tun'},
],
'route': {'final': 'bad'},
'dns': {'servers': []},
'outbounds': [
{'type': 'direct', 'tag': 'D'},
{
'type': 'socks',
'tag': 'A',
'server': '127.0.0.1',
'server_port': 1080,
},
{
'type': 'socks',
'tag': 'B',
'server': '127.0.0.1',
'server_port': 1080,
},
],
});
final preview = importProxyNodes(value);
expect(preview.nodes.length, 1);
expect(preview.unsupported, 1);
expect(preview.nodes.single.options.containsKey('route'), false);
},
);
test('URI/Base64 supports credentials and TLS without logging inputs', () {
final input =
'vless://00000000-0000-0000-0000-000000000001@example.test:443?security=tls&sni=example.test&type=ws&path=%2Fmesh#Node';
final node = importProxyNodes(
base64.encode(utf8.encode(input)),
).nodes.single;
expect(node.options['type'], 'vless');
expect(node.options['tls']['enabled'], true);
expect(node.options['transport']['path'], '/mesh');
final ss = importProxyNodes(
'ss://${base64.encode(utf8.encode('aes-128-gcm:test-only'))}@example.test:8388#SS',
).nodes.single;
expect(ss.options['method'], 'aes-128-gcm');
expect(ss.options['password'], 'test-only');
});
test(
'rejects invalid credential fields, oversize input and injected dialer',
() {
for (final raw in [
'{"type":"socks","server":"a.test","server_port":0}',
'{"type":"vless","server":"a.test","server_port":443,"uuid":"invalid"}',
'{"type":"socks","server":"a.test","server_port":1080,"detour":"meshport"}',
]) {
expect(() => importProxyNodes(raw), throwsFormatException);
}
expect(
() => importProxyNodes('x' * (1024 * 1024 + 1)),
throwsFormatException,
);
},
);
test(
'profile round trip preserves subscription provenance and selection',
() {
final p = ProxyProfile();
p.nodes = importProxyNodes(
'socks5://user:test-only@example.test:1080#Node',
source: 'source-1',
).nodes;
p.selectedId = p.nodes.single.id;
p.mode = 'global';
p.subscriptions = [
{
'id': 'source-1',
'name': 'Source',
'url': 'https://example.test/sub?token=test-only',
},
];
final loaded = ProxyProfile.fromJson(
jsonDecode(jsonEncode(p.toJson())) as Map<String, dynamic>,
);
expect(loaded.selectedId, p.selectedId);
expect(loaded.nodes.single.source, 'source-1');
expect(loaded.runtime()['proxy']['password'], 'test-only');
expect(loaded.mode, 'global');
},
);
test('subscription requires HTTPS without auth URL', () async {
await expectLater(
fetchSubscription('http://example.test/sub', source: 's'),
throwsFormatException,
);
await expectLater(
fetchSubscription('https://user:password@example.test/sub', source: 's'),
throwsFormatException,
);
});
}
@@ -0,0 +1,296 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
class FakeProxy implements ProxyEngine {
final List<String> events;
String state = 'Stopped';
bool failStart = false;
Map<String, dynamic>? lastProfile;
FakeProxy(this.events);
@override
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
}) async {
lastProfile = profile;
events.add('proxy.start:${prefixes.join(',')}');
if (failStart) throw StateError('occupied port');
state = 'Running';
return {'state': state};
}
@override
Future<Map<String, dynamic>> status() async => {'state': state};
@override
Future<void> stop() async {
events.add('proxy.stop');
state = 'Stopped';
}
@override
Future<void> close() async {
events.add('proxy.close');
}
}
class Fixture {
final events = <String>[];
late final proxy = FakeProxy(events);
late final mesh = MeshPortClient.fromTransport(
request: request,
close: () async {},
);
late final session = MeshProxySession(mesh: mesh, proxy: proxy);
String state = 'Stopped', mode = 'application';
String? ip = '10.77.0.11/24';
List<String> routes = ['192.168.21.0/24'];
Future<Map<String, dynamic>> request(Map<String, dynamic> input) async {
final op = input['op'] as String;
events.add('mesh.$op');
final data = switch (op) {
'validate' => {'runtime_mode': mode},
'start' => (() {
state = 'Running';
return <String, dynamic>{};
})(),
'stop' => (() {
state = 'Stopped';
return <String, dynamic>{};
})(),
'socks_start' => {'listen': '127.0.0.1:50001'},
'socks_status' => {'running': true},
'status' => {
'state': state,
'ipv4': ip,
'platform_network': {
'subnet_routes_scope': 'accepted_projection',
'subnet_routes': routes,
},
},
_ => <String, dynamic>{},
};
return {'ok': true, 'data': data};
}
}
void main() {
test(
'joint lifecycle, canonical routes, update and ordered cleanup',
() async {
final f = Fixture();
await f.session.start('test');
expect(f.session.state, 'Running');
expect(f.session.endpoint, '127.0.0.1:10818');
final starts = f.events.where((e) => e.startsWith('proxy.start')).length;
f.routes = ['192.168.21.17/24', '192.168.21.0/24'];
await f.session.refresh();
expect(f.events.where((e) => e.startsWith('proxy.start')).length, starts);
f.routes = ['192.168.22.0/24'];
await f.session.refresh();
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.22.0/24');
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
'192.168.22.0/24',
]);
f.events.clear();
await f.session.stop();
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
await f.session.start('test');
await f.session.close();
expect(f.events.last, 'proxy.close');
await expectLater(f.session.start('test'), throwsStateError);
},
);
test('failed engine startup rolls back and permits retry', () async {
final f = Fixture();
f.proxy.failStart = true;
await expectLater(f.session.start('test'), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
expect(f.events.sublist(f.events.length - 3), [
'proxy.stop',
'mesh.socks_stop',
'mesh.stop',
]);
f.proxy.failStart = false;
await f.session.start('test');
await f.session.close();
});
test(
'queue prevents concurrent duplicate starts; system mode is refused',
() async {
final f = Fixture();
final first = f.session.start('test');
final duplicate = f.session.start('test');
await expectLater(duplicate, throwsStateError);
await first;
expect(f.events.where((e) => e == 'mesh.start').length, 1);
await f.session.stop();
f.mode = 'system_vpn';
await expectLater(f.session.start('test'), throwsUnsupportedError);
await f.session.close();
},
);
test(
'wait for DHCP then start; unexpected engine failure cleans mesh',
() async {
final f = Fixture();
f.ip = null;
f.routes = [];
await f.session.start('test');
expect(f.session.state, 'AwaitingAddress');
f.ip = '10.77.0.11/24';
await f.session.refresh();
expect(f.session.state, 'Running');
f.proxy.state = 'Failed';
await expectLater(f.session.refresh(), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
await f.session.close();
},
);
test(
'reject public/overbroad projection and ignore untrusted route scope',
() {
expect(
() => effectiveMeshPrefixes({'ipv4': '8.8.8.8/24'}),
throwsStateError,
);
expect(
() => effectiveMeshPrefixes({'ipv4': '10.0.0.1/8'}),
throwsStateError,
);
expect(
effectiveMeshPrefixes({
'ipv4': '10.77.0.11/24',
'platform_network': {
'subnet_routes': ['0.0.0.0/0'],
},
}),
['10.77.0.0/24'],
);
},
);
test(
'proxy-only session does not start mesh or require network credentials',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'proxy', 'mode': 'direct'},
);
await session.start('invalid mesh config');
expect(session.state, 'Running');
expect(
f.events.where((e) => e == 'mesh.start' || e == 'mesh.validate'),
isEmpty,
);
expect(f.proxy.lastProfile?['feature'], 'proxy');
await session.close();
},
);
test(
'combined keeps proxy available and protects mesh when native network stops',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'combined', 'mode': 'global'},
);
await session.start('test');
f.state = 'Stopped';
await session.refresh();
expect(session.state, 'Partial');
expect(session.endpoint, isNotNull);
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
]);
await session.close();
},
);
final path = Platform.environment['MESHPORT_PROXY_LIBRARY'];
test(
'native Go ABI loads from Dart, releases listeners and closes context',
() async {
final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = listener.port;
await listener.close();
final engine = await NativeProxyEngine.open(libraryPath: path);
expect((await engine.status())['state'], 'Stopped');
await engine.start(
port: port,
meshSocks: '127.0.0.1:9',
prefixes: ['10.77.0.0/24'],
);
expect((await engine.status())['state'], 'Running');
final socket = await Socket.connect('127.0.0.1', port);
await engine.close();
expect(
await socket
.fold<int>(0, (count, bytes) => count + bytes.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
final reused = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reused.close();
await expectLater(engine.status(), throwsStateError);
},
skip: path == null
? 'Set MESHPORT_PROXY_LIBRARY after building native library'
: false,
);
final meshPath = Platform.environment['MESHPORT_LIBRARY'];
test(
'Rust and Go coexist in one Dart process with joint native cleanup',
() async {
final mesh = await MeshPortClient.open(libraryPath: meshPath);
final engine = await NativeProxyEngine.open(libraryPath: path);
final reserve = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = reserve.port;
await reserve.close();
final session = MeshProxySession(mesh: mesh, proxy: engine, port: port);
try {
await session.start(
"ipv4 = '10.253.82.11/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n[network_identity]\nnetwork_name = 'native-lifecycle-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true\n",
);
expect(session.state, 'Running');
expect((await mesh.socksBridgeStatus())['running'], true);
final socket = await Socket.connect('127.0.0.1', port);
await session.stop();
expect(
await socket
.fold<int>(0, (n, b) => n + b.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
expect((await mesh.status())['state'], 'Stopped');
expect((await mesh.socksBridgeStatus())['running'], false);
final reuse = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reuse.close();
} finally {
await session.close();
await mesh.close();
}
},
skip: path == null || meshPath == null
? 'Set both native library paths'
: false,
);
}
@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/app.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
import 'package:meshport_lab/features/lab_screen.dart';
import 'package:meshport_lab/features/proxy_node_editor.dart';
void main() {
for (final width in [360.0, 800.0]) {
testWidgets('main tabs fit ${width}px with larger text', (tester) async {
tester.view.physicalSize = Size(width, 850);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
theme: meshPortTheme(),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(1.4)),
child: child!,
),
home: const LabScreen(initializeNative: false),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
for (final label in ['代理', '组网', '设置', '概览']) {
await tester.tap(find.text(label).last);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: label);
}
});
}
testWidgets('forms keep fields apart at phone width', (tester) async {
tester.view.physicalSize = const Size(360, 850);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
for (final page in <Widget>[
DnsPage(profile: ProxyProfile(), changed: () {}),
const ProxyNodeEditor(),
const RuleEditor(),
NetworkConfigPage(section: '基础配置', initial: const {}, save: (_) async {}),
]) {
await tester.pumpWidget(MaterialApp(theme: meshPortTheme(), home: page));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
final fields = find.byType(TextField).evaluate().toList();
for (var i = 1; i < fields.length; i++) {
final previous = tester.getRect(find.byWidget(fields[i - 1].widget));
final current = tester.getRect(find.byWidget(fields[i].widget));
expect(current.top - previous.bottom, greaterThanOrEqualTo(12));
}
}
});
}
@@ -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'));
});
}
@@ -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<void> 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<void> chooseMode(WidgetTester tester, String mode) async {
final field = find.byWidgetPredicate(
(w) =>
w is DropdownButtonFormField<String> &&
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<void>();
final saves = <Map<String, dynamic>>[];
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
if (call.method == 'save_proxy_profile') {
saves.add(
jsonDecode(call.arguments as String) as Map<String, dynamic>,
);
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,
);
}
@@ -1,9 +1,136 @@
import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
void main() {
test(
'macOS session reuses authorized IPC after stop and cleans up on exit',
() async {
var launches = 0;
final paths = <String>[];
final sockets = <Socket>[];
var state = 'Stopped';
var idleChecks = 0;
final session = MacSystemVpnSession(
keepAlive: const Duration(milliseconds: 10),
open: () => openMacSystemVpn(
launch: (address, uid) async {
launches++;
paths.add(address);
final socket = await Socket.connect(
InternetAddress(address, type: InternetAddressType.unix),
0,
);
sockets.add(socket);
socket
.cast<List<int>>()
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
final op = (jsonDecode(line) as Map<String, dynamic>)['op'];
if (op == 'start') state = 'Running';
if (op == 'stop') state = 'Stopped';
if (op == 'status' && state == 'Stopped') idleChecks++;
socket.write(
'${jsonEncode({
'ok': true,
'data': {'state': state},
})}\n',
);
});
},
),
);
try {
final first = await session.acquire();
await first.request({'op': 'start'});
await session.release(first);
expect(state, 'Stopped');
expect(await Directory(File(paths.single).parent.path).exists(), true);
await Future<void>.delayed(const Duration(milliseconds: 40));
expect(idleChecks, greaterThan(0));
final second = await session.acquire();
expect(identical(first, second), true);
expect(launches, 1);
await second.request({'op': 'start'});
await session.release(second);
await session.close();
expect(state, 'Stopped');
expect(await Directory(File(paths.single).parent.path).exists(), false);
await expectLater(session.acquire(), throwsStateError);
} finally {
await session.close();
for (final socket in sockets) {
socket.destroy();
}
}
},
skip: !Platform.isMacOS,
);
test(
'dead helper is replaced and cancelled authorization can be retried',
() async {
var opens = 0, closed = 0;
var failed = false;
final session = MacSystemVpnSession(
open: () async {
opens++;
if (opens == 1) throw StateError('authorization cancelled');
return MeshPortClient.fromTransport(
request: (request) async {
if (failed && opens == 2) throw StateError('helper disconnected');
return {
'ok': true,
'data': {'state': 'Stopped'},
};
},
close: () async {
closed++;
},
);
},
);
try {
await expectLater(session.acquire(), throwsStateError);
final first = await session.acquire();
await session.release(first);
failed = true;
final replacement = await session.acquire();
expect(identical(first, replacement), false);
expect(opens, 3);
expect(closed, 1);
} finally {
await session.close();
}
expect(closed, 2);
},
);
test(
'closing while authorization is pending does not leave a helper',
() async {
final pending = Completer<MeshPortClient>();
var closes = 0;
final session = MacSystemVpnSession(open: () => pending.future);
final opening = session.acquire();
final rejected = expectLater(opening, throwsStateError);
final closing = session.close();
pending.complete(
MeshPortClient.fromTransport(
request: (_) async => {'ok': true, 'data': {}},
close: () async {
closes++;
},
),
);
await rejected;
await closing;
expect(closes, 1);
},
);
test(
'Unix control serializes replies and removes socket on close',
() async {
+93 -3
View File
@@ -3,6 +3,63 @@ 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 {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
final mode = find.byWidgetPredicate(
(w) =>
w is DropdownButtonFormField<String> &&
w.decoration.labelText == '上网模式',
);
await tester.ensureVisible(mode);
await tester.tap(mode);
await tester.pumpAndSettle();
await tester.tap(find.text('绕过中国大陆').last);
await tester.pumpAndSettle();
expect(find.textContaining('中国大陆 IP 和普通私网直连'), findsOneWidget);
await tester.tap(mode);
await tester.pumpAndSettle();
await tester.tap(find.text('全局代理').last);
await tester.pumpAndSettle();
expect(find.textContaining('中国大陆 IP 和普通私网直连'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('Starts disconnected and exposes networking configuration', (
tester,
) async {
@@ -10,10 +67,43 @@ void main() {
const MaterialApp(home: LabScreen(initializeNative: false)),
);
expect(find.text('尚未连接'), findsOneWidget);
await tester.tap(find.text('设置').last);
await tester.tap(find.text('组网').last);
await tester.pumpAndSettle();
await tester.tap(find.text('基础配置'));
await tester.pumpAndSettle();
expect(find.text('网络密钥'), findsOneWidget);
expect(find.text('校验并连接'), findsOneWidget);
expect(find.text('保存配置'), findsOneWidget);
expect(find.text('保存草稿'), findsOneWidget);
});
testWidgets('proxy import requires preview and preserves draft separation', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
expect(find.text('上网模式'), findsOneWidget);
await tester.ensureVisible(find.text('导入与预览'));
await tester.tap(find.text('导入与预览'));
await tester.pumpAndSettle();
await tester.enterText(
find.byType(TextField).last,
'socks5://127.0.0.1:1080#Preview',
);
await tester.tap(find.text('解析并预览'));
await tester.pumpAndSettle();
expect(find.text('导入预览'), findsOneWidget);
expect(find.text('Preview'), findsOneWidget);
await tester.tap(find.text('确认导入'));
await tester.pumpAndSettle();
expect(find.text('Preview'), 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);
});
}
@@ -0,0 +1,3 @@
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver(timeout: const Duration(minutes: 15));
@@ -107,6 +107,21 @@ class MeshPortClient {
await request({'op': 'stop'});
}
/// Local IPv4 TCP/UDP bridge for a host proxy engine. Application mode only.
/// Data travels on native sockets, outside the serial JSON I/O interface.
Future<Map<String, dynamic>> startSocksBridge({
int port = 0,
int maxSessions = 128,
}) =>
request({'op': 'socks_start', 'port': port, 'max_sessions': maxSessions});
Future<void> stopSocksBridge() async {
await request({'op': 'socks_stop'});
}
Future<Map<String, dynamic>> socksBridgeStatus() =>
request({'op': 'socks_status'});
/// Opt in to bounded process-wide punch tracing. Does not replace host logging.
Future<Map<String, dynamic>> enableDiagnostics() =>
request({'op': 'diagnostics_enable'});
@@ -4,6 +4,102 @@ import 'dart:ffi';
import 'dart:io';
import 'client.dart';
/// Reuses one authenticated helper while its owning app is running. Stopping
/// the engine releases VPN resources; closing this session also closes IPC.
/// No service is installed and no credentials are stored by this class.
class MacSystemVpnSession {
MacSystemVpnSession({
required this.open,
this.keepAlive = const Duration(seconds: 30),
});
final Future<MeshPortClient> Function() open;
final Duration keepAlive;
MeshPortClient? _client;
Future<MeshPortClient>? _opening;
Timer? _heartbeat;
bool _disposed = false, _checking = false;
Future<MeshPortClient> acquire() async {
if (_disposed) throw StateError('VPN authorization session is closed');
_heartbeat?.cancel();
final pending = _opening ??= _acquire();
try {
final client = await pending;
if (_disposed) throw StateError('VPN authorization session is closed');
return client;
} finally {
if (identical(_opening, pending)) _opening = null;
}
}
Future<MeshPortClient> _acquire() async {
final cached = _client;
if (cached != null) {
try {
await cached.status();
return cached;
} catch (_) {
_client = null;
try {
await cached.close();
} catch (_) {}
}
}
final next = await open();
if (_disposed) {
await next.close();
throw StateError('VPN authorization session is closed');
}
return _client = next;
}
Future<void> release(MeshPortClient client) async {
if (!identical(client, _client) || _disposed) {
await client.close();
return;
}
try {
await client.stop();
} catch (_) {
_client = null;
try {
await client.close();
} catch (_) {}
rethrow;
}
if (_disposed || !identical(_client, client)) return;
_heartbeat?.cancel();
_heartbeat = Timer.periodic(keepAlive, (_) async {
if (_checking || _disposed || !identical(_client, client)) return;
_checking = true;
try {
await client.status();
} catch (_) {
if (identical(_client, client)) {
_client = null;
_heartbeat?.cancel();
}
try {
await client.close();
} catch (_) {}
} finally {
_checking = false;
}
});
}
Future<void> close() async {
_disposed = true;
_heartbeat?.cancel();
try {
await _opening;
} catch (_) {}
final client = _client;
_client = null;
await client?.close();
}
}
/// Android's host supplies VpnService authorization and a serialized control
/// channel. Keeping Flutter APIs out of this library permits non-Flutter hosts.
Future<MeshPortClient> openAndroidSystemVpn({
@@ -0,0 +1,4 @@
/// Optional proxy engine bindings; does not load native code until open().
library;
export 'src/proxy_engine.dart';
@@ -0,0 +1,147 @@
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'package:ffi/ffi.dart';
abstract interface class ProxyEngine {
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
});
Future<Map<String, dynamic>> status();
Future<void> stop();
Future<void> close();
}
String _libraryPath() {
if (Platform.isMacOS) {
return '${File(Platform.resolvedExecutable).parent.parent.path}/Frameworks/libmeshport_proxy.dylib';
}
if (Platform.isAndroid) return 'libmeshport_proxy.so';
throw UnsupportedError('Proxy engine currently supports macOS and Android');
}
Map<String, dynamic> _invoke(String path, int handle, String text) {
final library = DynamicLibrary.open(path);
final call = library
.lookupFunction<
Pointer<Utf8> Function(Uint64, Pointer<Utf8>),
Pointer<Utf8> Function(int, Pointer<Utf8>)
>('meshport_proxy_call');
final free = library
.lookupFunction<
Void Function(Pointer<Utf8>),
void Function(Pointer<Utf8>)
>('meshport_proxy_string_free');
final input = text.toNativeUtf8();
try {
final output = call(handle, input);
if (output == nullptr) throw StateError('Native engine response is null');
try {
return jsonDecode(output.toDartString()) as Map<String, dynamic>;
} finally {
free(output);
}
} finally {
calloc.free(input);
}
}
/// Calls run outside the UI isolate. Close is queued after in-flight operations.
class NativeProxyEngine implements ProxyEngine {
final String libraryPath;
final int _handle;
bool _closed = false;
Future<void> _tail = Future.value();
NativeProxyEngine._(this.libraryPath, this._handle);
static Future<NativeProxyEngine> open({String? libraryPath}) async {
final path = libraryPath ?? _libraryPath();
final handle = await Isolate.run(() {
final lib = DynamicLibrary.open(path);
final abi = lib.lookupFunction<Uint32 Function(), int Function()>(
'meshport_proxy_abi_version',
)();
if (abi != 1) throw StateError('Unsupported proxy engine ABI: $abi');
return lib.lookupFunction<Uint64 Function(), int Function()>(
'meshport_proxy_context_new',
)();
});
if (handle == 0) throw StateError('Could not create proxy engine context');
final engine = NativeProxyEngine._(path, handle);
try {
await engine._request({
'op': 'configure_cache',
'directory': Directory.systemTemp.path,
});
} catch (_) {
await engine.close();
rethrow;
}
return engine;
}
Future<T> _queue<T>(Future<T> Function() work) {
final result = _tail.then((_) => work());
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace __) {});
return result;
}
Future<Map<String, dynamic>> _request(Map<String, dynamic> request) {
if (_closed) return Future.error(StateError('Proxy engine is closed'));
final path = libraryPath, handle = _handle, text = jsonEncode(request);
return _queue(() async {
final response = await Isolate.run(() => _invoke(path, handle, text));
if (response['ok'] != true)
throw StateError(
response['error'] as String? ?? 'Proxy engine operation failed',
);
return response['data'] as Map<String, dynamic>;
});
}
@override
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
}) => _request({
'op': 'start',
'config': {
...?profile,
'listen_port': port,
'mesh_socks': meshSocks,
'mesh_cidrs': prefixes,
},
});
Future<Map<String, dynamic>> probeNode(Map<String, dynamic> options) =>
_request({
'op': 'probe_node',
'config': {'proxy': options},
});
@override
Future<Map<String, dynamic>> status() => _request({'op': 'status'});
@override
Future<void> stop() async {
await _request({'op': 'stop'});
}
@override
Future<void> close() {
if (_closed) return _tail;
_closed = true;
final path = libraryPath, handle = _handle;
return _queue(
() => Isolate.run(
() => DynamicLibrary.open(path)
.lookupFunction<Void Function(Uint64), void Function(int)>(
'meshport_proxy_context_free',
)(handle),
),
);
}
}
@@ -0,0 +1,8 @@
name: singbox_flutter
description: Managed native sing-box lifecycle bindings for MeshPort clients.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.11.0
dependencies:
ffi: ^2.1.4
+5
View File
@@ -10,6 +10,7 @@ crate-type = ["cdylib", "staticlib", "rlib"]
[dependencies]
meshport.workspace = true
meshport-easytier.workspace = true
meshport-socks.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
@@ -19,3 +20,7 @@ tracing-subscriber = { version = "0.3", default-features = false, features = ["s
[features]
default = []
system-vpn = ["meshport/system-vpn"]
[dev-dependencies]
easytier = { workspace = true, features = ["proxy-packet"] }
easytier-core.workspace = true
+155 -3
View File
@@ -26,12 +26,18 @@ static CONTEXTS: LazyLock<Mutex<HashMap<u64, Arc<Context>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
struct Context {
runtime: Runtime,
network: Mutex<Option<Network>>,
network: Mutex<Option<Arc<Network>>>,
socks: Mutex<Option<meshport_socks::Bridge>>,
tcp: tokio::sync::Mutex<HashMap<u64, meshport::TcpStream>>,
udp: tokio::sync::Mutex<HashMap<u64, meshport::UdpSocket>>,
}
impl Drop for Context {
fn drop(&mut self) {
if let Ok(slot) = self.socks.get_mut()
&& let Some(mut bridge) = slot.take()
{
let _ = self.runtime.block_on(bridge.stop());
}
if let Ok(slot) = self.network.get_mut()
&& let Some(n) = slot.take()
{
@@ -60,6 +66,7 @@ pub extern "C" fn meshport_context_new() -> u64 {
Arc::new(Context {
runtime,
network: Mutex::new(None),
socks: Mutex::new(None),
tcp: tokio::sync::Mutex::new(HashMap::new()),
udp: tokio::sync::Mutex::new(HashMap::new()),
}),
@@ -105,7 +112,22 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
"peers": config.get_peers().iter().map(|peer| peer.uri.to_string()).collect::<Vec<_>>(),
"enable_ipv6": flags.enable_ipv6,
"latency_first": flags.latency_first,
"optimization": optimization
"optimization": optimization,
"listeners": config.get_listener_uris().iter().map(|uri| uri.to_string()).collect::<Vec<_>>(),
"stun_servers": config.get_stun_servers(),
"stun_servers_v6": config.get_stun_servers_v6(),
"flags": {
"default_protocol": flags.default_protocol,
"disable_p2p": flags.disable_p2p,
"disable_tcp_hole_punching": flags.disable_tcp_hole_punching,
"disable_udp_hole_punching": flags.disable_udp_hole_punching,
"disable_sym_hole_punching": flags.disable_sym_hole_punching,
"p2p_only": flags.p2p_only,
"lazy_p2p": flags.lazy_p2p,
"need_p2p": flags.need_p2p,
"private_mode": flags.private_mode,
"foreign_relay_bps_limit": flags.foreign_relay_bps_limit.to_string()
}
});
}
return Ok(result);
@@ -136,10 +158,13 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
let config = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
*network = Some(context.runtime.block_on(Network::start(config))?);
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
Ok(json!({"engine_started": true}))
}
"stop" => {
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
context.runtime.block_on(bridge.stop())?;
}
context.tcp.blocking_lock().clear();
context.udp.blocking_lock().clear();
if let Some(n) = network.take() {
@@ -147,6 +172,61 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
}
Ok(json!({"stopped": true}))
}
"socks_start" => {
let n = network
.as_ref()
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
let mut slot = context.socks.lock().unwrap();
anyhow::ensure!(slot.is_none(), "SOCKS bridge already started");
let port = match request.get("port") {
Some(value) => u16::try_from(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid port"))?,
)?,
None => 0,
};
let max_sessions = match request.get("max_sessions") {
Some(value) => usize::try_from(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid session limit"))?,
)?,
None => 128,
};
let options = meshport_socks::Options {
listen: std::net::SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port),
max_sessions,
..Default::default()
};
let bridge = context
.runtime
.block_on(meshport_socks::Bridge::start(n.clone(), options))?;
let address = bridge.local_addr().to_string();
*slot = Some(bridge);
Ok(
json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}),
)
}
"socks_stop" => {
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
context.runtime.block_on(bridge.stop())?;
}
Ok(json!({"stopped": true}))
}
"socks_status" => {
let slot = context.socks.lock().unwrap();
Ok(match slot.as_ref() {
Some(bridge) => {
let s = bridge.snapshot();
json!({"running": s.running, "listen": bridge.local_addr().to_string(),
"active_sessions": s.active_sessions, "accepted_sessions": s.accepted_sessions,
"completed_sessions": s.completed_sessions, "failed_sessions": s.failed_sessions,
"refused_at_capacity": s.refused_at_capacity, "dropped_udp_packets": s.dropped_udp_packets})
}
None => json!({"running": false, "active_sessions": 0}),
})
}
"status" => match network.as_ref() {
Some(n) => {
let mut snapshot = context.runtime.block_on(n.snapshot());
@@ -390,6 +470,10 @@ mod tests {
&json!({"op": "validate", "toml": config, "include_profile": true}).to_string(),
);
assert_eq!(projected["ok"], true);
assert_eq!(
projected["data"]["profile"]["flags"]["foreign_relay_bps_limit"],
"18446744073709551615"
);
assert_eq!(
projected["data"]["profile"]["network_secret"],
"test-only-secret"
@@ -401,4 +485,72 @@ mod tests {
);
meshport_context_free(id);
}
#[test]
fn socks_control_lifecycle_and_context_cleanup() {
use std::io::{Read, Write};
let id = meshport_context_new();
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
let config = "ipv4 = '10.253.83.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'socks-ffi-test'\nnetwork_secret = 'test-only'\n";
assert_eq!(
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
true
);
assert_eq!(
call(id, r#"{"op":"socks_start","port":65536}"#)["ok"],
false
);
assert_eq!(
call(id, r#"{"op":"socks_start","max_sessions":0}"#)["ok"],
false
);
let started = call(id, r#"{"op":"socks_start"}"#);
assert_eq!(started["ok"], true);
let address = started["data"]["listen"].as_str().unwrap();
let mut control = std::net::TcpStream::connect(address).unwrap();
control
.set_read_timeout(Some(Duration::from_secs(3)))
.unwrap();
control.write_all(&[5, 1, 0]).unwrap();
let mut reply = [0; 2];
control.read_exact(&mut reply).unwrap();
assert_eq!(reply, [5, 0]);
// A native session waiting for its request does not hold the ABI lock.
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["active_sessions"],
1
);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
assert_eq!(control.read(&mut [0]).unwrap(), 0);
assert!(std::net::TcpStream::connect(address).is_err());
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
false
);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], true);
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
false
);
assert_eq!(
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
true
);
let restarted = call(id, r#"{"op":"socks_start"}"#);
let address = restarted["data"]["listen"].as_str().unwrap();
let mut control = std::net::TcpStream::connect(address).unwrap();
control
.set_read_timeout(Some(Duration::from_secs(3)))
.unwrap();
control.write_all(&[5, 1, 0]).unwrap();
control.read_exact(&mut reply).unwrap();
meshport_context_free(id);
assert_eq!(control.read(&mut [0]).unwrap(), 0);
// No lingering listener after context destruction.
std::net::TcpListener::bind(address).unwrap();
}
}
+77
View File
@@ -0,0 +1,77 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::TomlConfig;
use serde_json::{Value, json};
use std::ffi::{CStr, CString};
fn call(id: u64, request: Value) -> Value {
let input = CString::new(request.to_string()).unwrap();
unsafe {
let reply = meshport_ffi::meshport_call(id, input.as_ptr());
let result = serde_json::from_slice(CStr::from_ptr(reply).to_bytes()).unwrap();
meshport_ffi::meshport_string_free(reply);
result
}
}
use std::time::Duration;
use tokio::net::UdpSocket;
#[test]
fn ffi_udp_through_adjacent_mapped_subnet() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let _entered = runtime.enter();
let setup = async {
let port = UdpSocket::bind("127.0.0.1:0")
.await
.unwrap()
.local_addr()
.unwrap()
.port();
let identity =
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
let server_config = TomlConfig::new_from_str(&format!(
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).unwrap();
let server = create_native_instance(server_config).unwrap();
server.start().await.unwrap();
let client = format!(
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
);
(server, client)
};
let (server, client) = runtime.block_on(setup);
drop(_entered);
let id = meshport_ffi::meshport_context_new();
assert_eq!(call(id, json!({"op":"start", "toml":client}))["ok"], true);
let deadline = std::time::Instant::now();
loop {
if call(id, json!({"op":"status"}))["data"]["platform_network"]["subnet_routes"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
break;
}
assert!(deadline.elapsed() < Duration::from_secs(15));
std::thread::sleep(Duration::from_millis(100));
}
let (target, echo): (std::net::SocketAddr, _) = runtime.block_on(async {
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let echo = tokio::spawn(async move {
let mut buffer = [0; 128];
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
});
(target, echo)
});
let result = call(
id,
json!({"op":"probe", "target":target.to_string(), "protocol":"UDP", "echo":true, "timeout_ms":3000}),
);
echo.abort();
call(id, json!({"op":"stop"}));
meshport_ffi::meshport_context_free(id);
runtime.block_on(server.stop());
assert_eq!(result["ok"], true, "FFI UDP failed: {result}");
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "meshport-socks"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[dependencies]
meshport.workspace = true
anyhow.workspace = true
tokio.workspace = true
[dev-dependencies]
meshport-easytier.workspace = true
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
easytier-core.workspace = true
tokio = { workspace = true, features = ["signal", "process"] }
serde_json.workspace = true
@@ -0,0 +1,43 @@
//! Run with an application-mode TOML file; never prints its credentials.
use anyhow::{Context, Result};
use meshport::Network;
use meshport_socks::{Bridge, Options};
use std::{
net::{Ipv4Addr, SocketAddrV4},
sync::Arc,
};
#[tokio::main]
async fn main() -> Result<()> {
let mut arguments = std::env::args().skip(1);
let path = arguments
.next()
.context("usage: local_bridge CONFIG.toml [PORT]")?;
let port = arguments
.next()
.map(|s| s.parse::<u16>())
.transpose()?
.unwrap_or(0);
anyhow::ensure!(arguments.next().is_none(), "too many arguments");
let config = std::fs::read_to_string(path).context("cannot read configuration")?;
let network = Arc::new(Network::start(&config).await?);
let result = async {
let mut bridge = Bridge::start(
network.clone(),
Options {
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, port),
..Default::default()
},
)
.await?;
println!("MeshPort SOCKS5 IPv4 TCP/UDP: {}", bridge.local_addr());
println!("Waiting for Ctrl-C; engine startup does not guarantee remote reachability.");
let signal = tokio::signal::ctrl_c().await;
bridge.stop().await?;
signal?;
Ok::<_, anyhow::Error>(())
}
.await;
network.stop().await;
result
}
+395
View File
@@ -0,0 +1,395 @@
//! Local IPv4 SOCKS5 bridge to the MeshPort application data plane.
//! No DNS or ordinary internet fallback. This is a restricted internal bridge,
//! not a public SOCKS service (no GSSAPI, password authentication, or BIND).
mod protocol;
use anyhow::{Result, ensure};
use meshport::Network;
use protocol::*;
use std::{
collections::HashSet,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, copy, split},
net::{TcpListener, TcpStream, UdpSocket},
sync::{Semaphore, watch},
task::{JoinHandle, JoinSet},
time::{Instant, sleep_until, timeout},
};
#[derive(Clone, Debug)]
pub struct Options {
pub listen: SocketAddrV4,
pub max_sessions: usize,
pub handshake_timeout: Duration,
pub connect_timeout: Duration,
/// Grace period for the remaining direction after either side reaches EOF.
pub tcp_close_timeout: Duration,
pub udp_idle_timeout: Duration,
pub udp_io_timeout: Duration,
pub max_udp_targets: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0),
max_sessions: 128,
handshake_timeout: Duration::from_secs(5),
connect_timeout: Duration::from_secs(10),
tcp_close_timeout: Duration::from_secs(30),
udp_idle_timeout: Duration::from_secs(120),
udp_io_timeout: Duration::from_secs(5),
max_udp_targets: 64,
}
}
}
#[derive(Default)]
struct Counters {
active: AtomicUsize,
accepted: AtomicU64,
completed: AtomicU64,
failed: AtomicU64,
refused_at_capacity: AtomicU64,
dropped_udp: AtomicU64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Snapshot {
pub running: bool,
pub active_sessions: usize,
pub accepted_sessions: u64,
pub completed_sessions: u64,
pub failed_sessions: u64,
pub refused_at_capacity: u64,
pub dropped_udp_packets: u64,
}
struct Active(Arc<Counters>);
impl Drop for Active {
fn drop(&mut self) {
self.0.active.fetch_sub(1, Ordering::Relaxed);
}
}
/// Owns the listener and its sessions, but not the supplied network.
/// Stop the bridge before stopping the network. Dropping aborts all sessions;
/// `stop` additionally waits for resources to be released.
pub struct Bridge {
address: SocketAddrV4,
shutdown: watch::Sender<bool>,
task: Option<JoinHandle<std::io::Result<()>>>,
counters: Arc<Counters>,
}
impl Bridge {
pub async fn start(network: Arc<Network>, options: Options) -> Result<Self> {
ensure!(
options.listen.ip().is_loopback(),
"SOCKS bridge must bind IPv4 loopback"
);
ensure!(
options.max_sessions > 0 && options.max_sessions <= 4096,
"invalid session limit"
);
ensure!(
options.max_udp_targets > 0 && options.max_udp_targets <= 1024,
"invalid UDP target limit"
);
ensure!(
!options.handshake_timeout.is_zero()
&& !options.connect_timeout.is_zero()
&& !options.tcp_close_timeout.is_zero()
&& !options.udp_idle_timeout.is_zero()
&& !options.udp_io_timeout.is_zero(),
"timeouts must be positive"
);
let status = network.snapshot().await;
ensure!(
status["application_only"] == true,
"SOCKS bridge requires application mode"
);
ensure!(status["state"] == "Running", "network is not running");
let listener = TcpListener::bind(options.listen).await?;
let SocketAddr::V4(address) = listener.local_addr()? else {
unreachable!()
};
let counters = Arc::new(Counters::default());
let (shutdown, rx) = watch::channel(false);
let task = tokio::spawn(serve(listener, network, options, rx, counters.clone()));
Ok(Self {
address,
shutdown,
task: Some(task),
counters,
})
}
pub fn local_addr(&self) -> SocketAddrV4 {
self.address
}
pub fn snapshot(&self) -> Snapshot {
let c = &self.counters;
Snapshot {
running: self.task.as_ref().is_some_and(|task| !task.is_finished()),
active_sessions: c.active.load(Ordering::Relaxed),
accepted_sessions: c.accepted.load(Ordering::Relaxed),
completed_sessions: c.completed.load(Ordering::Relaxed),
failed_sessions: c.failed.load(Ordering::Relaxed),
refused_at_capacity: c.refused_at_capacity.load(Ordering::Relaxed),
dropped_udp_packets: c.dropped_udp.load(Ordering::Relaxed),
}
}
pub async fn stop(&mut self) -> Result<()> {
self.shutdown.send_replace(true);
if let Some(task) = self.task.take() {
task.await??;
}
Ok(())
}
}
impl Drop for Bridge {
fn drop(&mut self) {
self.shutdown.send_replace(true);
if let Some(task) = &self.task {
task.abort();
}
}
}
async fn serve(
listener: TcpListener,
network: Arc<Network>,
options: Options,
mut shutdown: watch::Receiver<bool>,
counters: Arc<Counters>,
) -> std::io::Result<()> {
let permits = Arc::new(Semaphore::new(options.max_sessions));
let mut sessions = JoinSet::new();
let result = loop {
tokio::select! {
biased;
_ = shutdown.changed() => break Ok(()),
_ = sessions.join_next(), if !sessions.is_empty() => {},
accepted = listener.accept() => {
let (stream, peer) = match accepted { Ok(v) => v, Err(e) => break Err(e) };
let Ok(permit) = permits.clone().try_acquire_owned() else {
counters.refused_at_capacity.fetch_add(1, Ordering::Relaxed);
drop(stream);
continue;
};
let SocketAddr::V4(peer) = peer else { continue; };
counters.active.fetch_add(1, Ordering::Relaxed);
counters.accepted.fetch_add(1, Ordering::Relaxed);
let active = Active(counters.clone());
let c = counters.clone();
let network = network.clone();
let options = options.clone();
sessions.spawn(async move {
let _permit = permit;
let _active = active;
if session(stream, peer, network, options, &c).await.is_err() {
c.failed.fetch_add(1, Ordering::Relaxed);
} else {
c.completed.fetch_add(1, Ordering::Relaxed);
}
});
}
}
};
drop(listener);
sessions.shutdown().await;
result
}
fn empty_address() -> SocketAddrV4 {
SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)
}
async fn session(
mut stream: TcpStream,
peer: SocketAddrV4,
network: Arc<Network>,
options: Options,
counters: &Counters,
) -> Result<()> {
let request = timeout(options.handshake_timeout, async {
ensure!(negotiate(&mut stream).await?, "no acceptable SOCKS method");
Ok::<_, anyhow::Error>(request(&mut stream).await?)
})
.await??;
let request = match request {
Ok(request) => request,
Err(code) => {
reply(&mut stream, code, empty_address()).await?;
anyhow::bail!("unsupported SOCKS request");
}
};
if request.command == 1 {
if !valid_target(request.address) {
reply(&mut stream, DENIED, empty_address()).await?;
anyhow::bail!("invalid mesh destination");
}
let result = timeout(
options.connect_timeout,
network.connect_tcp(request.address.into(), options.connect_timeout),
)
.await;
let mut overlay = match result {
Ok(Ok(stream)) => stream,
error => {
let code = match &error {
Ok(Err(e))
if e.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused) =>
{
REFUSED
}
_ => HOST_UNREACHABLE,
};
reply(&mut stream, code, empty_address()).await?;
anyhow::bail!("mesh connection unavailable");
}
};
let SocketAddr::V4(bound) = overlay.local_addr() else {
unreachable!()
};
reply(&mut stream, SUCCESS, bound).await?;
relay_tcp(&mut stream, &mut overlay, options.tcp_close_timeout).await?;
return Ok(());
}
if !request.address.ip().is_unspecified() && request.address.ip() != peer.ip() {
reply(&mut stream, DENIED, empty_address()).await?;
anyhow::bail!("UDP source differs from control connection");
}
let setup = timeout(options.connect_timeout, async {
let SocketAddr::V4(local) = stream.local_addr()? else {
unreachable!()
};
let relay = UdpSocket::bind(SocketAddrV4::new(*local.ip(), 0)).await?;
let overlay = network.bind_udp(0, options.connect_timeout).await?;
Ok::<_, anyhow::Error>((relay, overlay))
})
.await;
let (relay, overlay) = match setup {
Ok(Ok(v)) => v,
_ => {
reply(&mut stream, FAILURE, empty_address()).await?;
anyhow::bail!("UDP setup failed");
}
};
let SocketAddr::V4(bound) = relay.local_addr()? else {
unreachable!()
};
reply(&mut stream, SUCCESS, bound).await?;
udp_session(
stream,
peer,
request.address.port(),
relay,
overlay,
options,
counters,
)
.await
}
async fn relay_tcp(
local: &mut TcpStream,
remote: &mut meshport::TcpStream,
close_timeout: Duration,
) -> Result<()> {
let (mut local_read, mut local_write) = split(local);
let (mut remote_read, mut remote_write) = split(remote);
let (closed, mut closure) = watch::channel(false);
let upload = async {
copy(&mut local_read, &mut remote_write).await?;
// Notify before native shutdown: a FIN ACK may never arrive after
// a route disappears. Permit pending response data a bounded grace.
closed.send_replace(true);
remote_write.shutdown().await
};
let download = async {
copy(&mut remote_read, &mut local_write).await?;
closed.send_replace(true);
local_write.shutdown().await
};
let forwarding = async { tokio::try_join!(upload, download) };
tokio::pin!(forwarding);
tokio::select! {
result = &mut forwarding => { result?; }
_ = closure.changed() => { timeout(close_timeout, forwarding).await??; }
}
Ok(())
}
async fn udp_session(
mut control: TcpStream,
peer: SocketAddrV4,
source_port: u16,
relay: UdpSocket,
overlay: meshport::UdpSocket,
options: Options,
counters: &Counters,
) -> Result<()> {
let mut endpoint = (source_port != 0).then_some(SocketAddrV4::new(*peer.ip(), source_port));
let mut targets = HashSet::new();
let mut local_buffer = vec![0; 65535];
let mut remote_buffer = vec![0; 65535];
let mut control_buffer = [0; 1];
let mut idle = Instant::now() + options.udp_idle_timeout;
loop {
tokio::select! {
// Association lifetime is tied to its TCP control channel.
result = control.read(&mut control_buffer) => {
result?;
return Ok(()); // EOF or unexpected control payload closes it.
}
_ = sleep_until(idle) => return Ok(()),
result = relay.recv_from(&mut local_buffer) => {
let (len, source) = result?;
let SocketAddr::V4(source) = source else { continue; };
let decoded = udp_request(&local_buffer[..len]);
if source.ip() != peer.ip() || endpoint.is_some_and(|e| e != source) || decoded.is_none() {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
}
let (target, payload) = decoded.unwrap();
if !targets.contains(&target) && targets.len() >= options.max_udp_targets {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
}
endpoint = Some(source);
// Count attempted destinations too: the native socket can register
// a flow before a send fails. This bounds its resource growth.
targets.insert(target);
match timeout(options.udp_io_timeout, overlay.send_to(payload, target.into())).await {
Ok(Ok(n)) if n == payload.len() => idle = Instant::now() + options.udp_idle_timeout,
_ => { counters.dropped_udp.fetch_add(1, Ordering::Relaxed); }
}
}
result = overlay.recv_from(&mut remote_buffer) => {
let (len, source) = result?;
let SocketAddr::V4(source) = source else { continue; };
let Some(endpoint) = endpoint else { continue; };
if !targets.contains(&source) { continue; }
let Some(frame) = udp_reply(source, &remote_buffer[..len]) else {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
};
timeout(options.udp_io_timeout, relay.send_to(&frame, endpoint)).await??;
idle = Instant::now() + options.udp_idle_timeout;
}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
use std::net::{Ipv4Addr, SocketAddrV4};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
pub(crate) const SUCCESS: u8 = 0;
pub(crate) const FAILURE: u8 = 1;
pub(crate) const DENIED: u8 = 2;
pub(crate) const HOST_UNREACHABLE: u8 = 4;
pub(crate) const REFUSED: u8 = 5;
pub(crate) const COMMAND_UNSUPPORTED: u8 = 7;
pub(crate) const ADDRESS_UNSUPPORTED: u8 = 8;
pub(crate) struct Request {
pub command: u8,
pub address: SocketAddrV4,
}
pub(crate) async fn negotiate<S: AsyncRead + AsyncWrite + Unpin>(
s: &mut S,
) -> std::io::Result<bool> {
let mut header = [0; 2];
s.read_exact(&mut header).await?;
if header[0] != 5 || header[1] == 0 {
return Ok(false);
}
let mut methods = vec![0; header[1] as usize];
s.read_exact(&mut methods).await?;
let accepted = methods.contains(&0);
s.write_all(&[5, if accepted { 0 } else { 255 }]).await?;
Ok(accepted)
}
/// Unsupported address types are deliberately not resolved using system DNS.
pub(crate) async fn request<S: AsyncRead + Unpin>(
s: &mut S,
) -> std::io::Result<Result<Request, u8>> {
let mut header = [0; 4];
s.read_exact(&mut header).await?;
if header[0] != 5 || header[2] != 0 {
return Ok(Err(FAILURE));
}
if !matches!(header[1], 1 | 3) {
return Ok(Err(COMMAND_UNSUPPORTED));
}
if header[3] != 1 {
return Ok(Err(ADDRESS_UNSUPPORTED));
}
let mut address = [0; 6];
s.read_exact(&mut address).await?;
Ok(Ok(Request {
command: header[1],
address: decode_address(&address),
}))
}
fn decode_address(bytes: &[u8]) -> SocketAddrV4 {
SocketAddrV4::new(
Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]),
u16::from_be_bytes([bytes[4], bytes[5]]),
)
}
pub(crate) fn address_bytes(address: SocketAddrV4) -> [u8; 6] {
let [a, b, c, d] = address.ip().octets();
let [hi, lo] = address.port().to_be_bytes();
[a, b, c, d, hi, lo]
}
pub(crate) async fn reply<S: AsyncWrite + Unpin>(
s: &mut S,
code: u8,
address: SocketAddrV4,
) -> std::io::Result<()> {
let mut bytes = vec![5, code, 0, 1];
bytes.extend_from_slice(&address_bytes(address));
s.write_all(&bytes).await
}
pub(crate) fn valid_target(address: SocketAddrV4) -> bool {
address.port() != 0
&& !address.ip().is_unspecified()
&& !address.ip().is_multicast()
&& !address.ip().is_broadcast()
&& !address.ip().is_loopback()
}
pub(crate) fn udp_request(bytes: &[u8]) -> Option<(SocketAddrV4, &[u8])> {
// No fragmentation, domain resolution, IPv6, or reserved bits.
if bytes.len() < 10 || bytes[..4] != [0, 0, 0, 1] || bytes.len() > 65507 {
return None;
}
let address = decode_address(&bytes[4..10]);
valid_target(address).then_some((address, &bytes[10..]))
}
pub(crate) fn udp_reply(address: SocketAddrV4, payload: &[u8]) -> Option<Vec<u8>> {
if payload.len() > 65497 {
return None;
}
let mut bytes = Vec::with_capacity(10 + payload.len());
bytes.extend_from_slice(&[0, 0, 0, 1]);
bytes.extend_from_slice(&address_bytes(address));
bytes.extend_from_slice(payload);
Some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn udp_rejects_malformed_fragmented_and_non_mesh_addresses() {
let target = "10.77.0.2:7007".parse().unwrap();
let frame = udp_reply(target, b"hello").unwrap();
assert_eq!(udp_request(&frame), Some((target, &b"hello"[..])));
for length in 0..10 {
assert!(udp_request(&frame[..length]).is_none());
}
for (index, value) in [(0, 1), (1, 1), (2, 1), (3, 3), (3, 4)] {
let mut bad = frame.clone();
bad[index] = value;
assert!(udp_request(&bad).is_none());
}
for address in [
"0.0.0.0:1",
"127.0.0.1:1",
"224.0.0.1:1",
"255.255.255.255:1",
"10.0.0.1:0",
] {
assert!(udp_request(&udp_reply(address.parse().unwrap(), b"x").unwrap()).is_none());
}
assert!(udp_reply(target, &vec![0; 65498]).is_none());
}
}
+482
View File
@@ -0,0 +1,482 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
use meshport::Network;
use meshport_socks::{Bridge, Options};
use std::{
net::SocketAddrV4,
path::{Path, PathBuf},
process::Stdio,
sync::Arc,
time::{Duration, SystemTime},
};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
net::{TcpListener, TcpStream, UdpSocket},
task::JoinSet,
time::{sleep, timeout},
};
const WAIT: Duration = Duration::from_secs(15);
struct ExternalEngine {
child: tokio::process::Child,
config_path: PathBuf,
listen: SocketAddrV4,
}
impl Drop for ExternalEngine {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.config_path);
}
}
impl ExternalEngine {
async fn start(binary: &Path, bridge: SocketAddrV4, network: &Network) -> Self {
let reserved = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let listen: SocketAddrV4 = reserved.local_addr().unwrap().to_string().parse().unwrap();
let stamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_nanos();
let config_path = std::env::temp_dir().join(format!(
"meshport-singbox-{}-{stamp}.json",
std::process::id()
));
let snapshot = network.snapshot().await;
let mut prefixes = snapshot["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.clone();
prefixes.push(snapshot["ipv4"].clone());
let config = serde_json::json!({"listen_port": listen.port(), "mesh_socks": bridge.to_string(), "mesh_cidrs": prefixes});
std::fs::write(&config_path, config.to_string()).unwrap();
drop(reserved);
let child = tokio::process::Command::new(binary)
.arg(&config_path)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut engine = Self {
child,
config_path,
listen,
};
let mut readiness = String::new();
timeout(
WAIT,
BufReader::new(engine.child.stdout.take().unwrap()).read_line(&mut readiness),
)
.await
.unwrap()
.unwrap();
let ready: serde_json::Value = serde_json::from_str(&readiness).unwrap();
assert_eq!(ready["state"], "Running");
engine
}
async fn stop(&mut self) {
let id = self.child.id().unwrap();
let status = std::process::Command::new("/bin/kill")
.args(["-TERM", &id.to_string()])
.status()
.unwrap();
assert!(status.success());
assert!(
timeout(WAIT, self.child.wait())
.await
.unwrap()
.unwrap()
.success()
);
assert!(TcpStream::connect(self.listen).await.is_err());
}
}
fn config(ip: &str, bootstrap: Option<u16>) -> String {
let peer = bootstrap
.map(|port| format!("[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n"))
.unwrap_or_default();
format!(
"ipv4 = '{ip}/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n{peer}[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n"
)
}
async fn negotiate(addr: SocketAddrV4) -> TcpStream {
let mut s = TcpStream::connect(addr).await.unwrap();
// Deliberately split protocol fields across writes.
s.write_all(&[5]).await.unwrap();
s.write_all(&[1, 0]).await.unwrap();
let mut reply = [0; 2];
s.read_exact(&mut reply).await.unwrap();
assert_eq!(reply, [5, 0]);
s
}
async fn request(s: &mut TcpStream, command: u8, target: SocketAddrV4) -> (u8, SocketAddrV4) {
let mut bytes = vec![5, command, 0, 1];
bytes.extend_from_slice(&target.ip().octets());
bytes.extend_from_slice(&target.port().to_be_bytes());
s.write_all(&bytes).await.unwrap();
let mut reply = [0; 10];
s.read_exact(&mut reply).await.unwrap();
assert_eq!([reply[0], reply[2], reply[3]], [5, 0, 1]);
(
reply[1],
SocketAddrV4::new(
[reply[4], reply[5], reply[6], reply[7]].into(),
u16::from_be_bytes([reply[8], reply[9]]),
),
)
}
fn frame(target: SocketAddrV4, payload: &[u8]) -> Vec<u8> {
let mut bytes = vec![0, 0, 0, 1];
bytes.extend_from_slice(&target.ip().octets());
bytes.extend_from_slice(&target.port().to_be_bytes());
bytes.extend_from_slice(payload);
bytes
}
async fn wait_no_sessions(bridge: &Bridge) {
timeout(WAIT, async {
while bridge.snapshot().active_sessions != 0 {
sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_tcp_udp_over_learned_subnet_and_withdrawal() {
overlay_check(None).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires the built Go engine; run sh scripts/test-singbox-bridge.sh"]
async fn singbox_to_meshport_tcp_udp_and_withdrawal() {
let binary = std::env::var_os("MESHPORT_SINGBOX_BIN").expect("MESHPORT_SINGBOX_BIN required");
overlay_check(Some(PathBuf::from(binary))).await;
}
async fn overlay_check(engine_binary: Option<PathBuf>) {
let port = std::net::UdpSocket::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
// A real remote gateway maps its advertised private subnet to an OS echo
// server. Unlike the SDK UDP listener, this accepts unknown first packets.
let server_config = TomlConfig::new_from_str(&format!(
"ipv4 = '10.253.81.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true"
)).unwrap();
let server = create_native_instance(server_config.clone()).unwrap();
server.start().await.unwrap();
let network = Arc::new(
Network::start(&config("10.253.80.11", Some(port)))
.await
.unwrap(),
);
timeout(WAIT, async {
while !network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.iter()
.any(|r| r == "10.253.79.0/24")
{
sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
let tcp_target: SocketAddrV4 = format!("10.253.79.1:{}", tcp.local_addr().unwrap().port())
.parse()
.unwrap();
let tcp_echo = tokio::spawn(async move {
let mut children = JoinSet::new();
loop {
tokio::select! {
accepted = tcp.accept() => {
let (mut s, _) = accepted.unwrap();
children.spawn(async move {
let mut buffer = [0; 4096];
loop {
let n = s.read(&mut buffer).await.unwrap();
if n == 0 { break; }
s.write_all(&buffer[..n]).await.unwrap();
}
});
}
_ = children.join_next(), if !children.is_empty() => {}
}
}
});
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let udp_target: SocketAddrV4 = format!("10.253.79.1:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let udp_echo = tokio::spawn(async move {
let mut buffer = [0; 65535];
loop {
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
}
});
let mut bridge = Bridge::start(
network.clone(),
Options {
tcp_close_timeout: Duration::from_secs(1),
..Options::default()
},
)
.await
.unwrap();
let mut engine = match engine_binary {
Some(binary) => Some(ExternalEngine::start(&binary, bridge.local_addr(), &network).await),
None => None,
};
let entry = engine.as_ref().map_or(bridge.local_addr(), |e| e.listen);
let result = timeout(Duration::from_secs(45), async {
// An established TCP connection blocked on read does not serialize
// the other connections or either UDP association.
let mut idle = negotiate(entry).await;
assert_eq!(request(&mut idle, 1, tcp_target).await.0, 0);
let mut clients = JoinSet::new();
for i in 0..4 {
let addr = entry;
clients.spawn(async move {
let mut s = negotiate(addr).await;
assert_eq!(request(&mut s, 1, tcp_target).await.0, 0);
let payload = vec![i; 32768];
s.write_all(&payload).await.unwrap();
let mut received = vec![0; payload.len()];
s.read_exact(&mut received).await.unwrap();
assert_eq!(received, payload);
s.shutdown().await.unwrap();
});
}
while let Some(result) = clients.join_next().await {
result.unwrap();
}
let mut associations = Vec::new();
for payload in [b"first-session".as_slice(), b"second-session".as_slice()] {
let local = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut control = negotiate(entry).await;
let (code, relay) = request(&mut control, 3, "0.0.0.0:0".parse().unwrap()).await;
assert_eq!(code, 0);
local
.send_to(&frame(udp_target, payload), relay)
.await
.unwrap();
associations.push((control, local, relay, payload));
}
for (_, local, _, payload) in &associations {
let mut buffer = [0; 256];
let (n, _) = timeout(WAIT, local.recv_from(&mut buffer))
.await
.unwrap()
.unwrap();
assert_eq!(&buffer[..n], frame(udp_target, payload));
}
// The direct bridge enforces endpoint pinning. The outer engine's
// inbound association policy is independently owned by sing-box.
let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let (control, local, relay, _) = associations.remove(0);
let mut buffer = [0; 128];
if engine.is_none() {
intruder
.send_to(&frame(udp_target, b"injected"), relay)
.await
.unwrap();
assert!(
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
.await
.is_err()
);
let mut fragmented = frame(udp_target, b"fragmented");
fragmented[2] = 1;
local.send_to(&fragmented, relay).await.unwrap();
assert!(
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
.await
.is_err()
);
}
drop(control);
let (remaining_control, remaining_local, remaining_relay, _) = associations.remove(0);
drop(idle);
if engine.is_none() {
assert!(bridge.snapshot().dropped_udp_packets >= 2);
}
// Removal propagates through the real route plane. A fresh SOCKS
// request fails rather than reaching the ordinary network.
server_config.clear_proxy_cidrs();
let updated =
easytier_core::instance::CoreInstanceConfig::from_toml(&server_config).unwrap();
server
.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
services: updated.connectivity.runtime,
peer: Arc::new(updated.peer.snapshot),
})
.await
.unwrap();
timeout(WAIT, async {
while !network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.is_empty()
{
sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
let mut rejected = negotiate(entry).await;
let code = request(&mut rejected, 1, tcp_target).await.0;
if engine.is_some() && code == 0 {
// sing-box acknowledges SOCKS before its asynchronous outbound
// dial. A route failure must then close, never deliver data.
let closed = timeout(WAIT, rejected.read(&mut buffer)).await.unwrap();
assert!(matches!(closed, Ok(0) | Err(_)));
} else {
assert_ne!(code, 0);
}
remaining_local
.send_to(&frame(udp_target, b"after-withdrawal"), remaining_relay)
.await
.unwrap();
assert!(
timeout(
Duration::from_millis(400),
remaining_local.recv_from(&mut buffer)
)
.await
.is_err()
);
drop(remaining_control);
drop(rejected);
if engine.is_none() {
wait_no_sessions(&bridge).await;
}
})
.await;
if let Some(engine) = &mut engine {
engine.stop().await;
}
bridge.stop().await.unwrap();
assert_eq!(bridge.snapshot().active_sessions, 0);
assert!(!bridge.snapshot().running);
assert!(TcpStream::connect(bridge.local_addr()).await.is_err());
bridge.stop().await.unwrap();
// Explicit stop releases the address, allowing a new bridge lifecycle.
let mut restarted = Bridge::start(
network.clone(),
Options {
listen: bridge.local_addr(),
..Options::default()
},
)
.await
.unwrap();
restarted.stop().await.unwrap();
network.stop().await;
server.stop().await;
tcp_echo.abort();
udp_echo.abort();
result.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn limits_protocol_errors_timeout_and_shutdown() {
let network = Arc::new(Network::start(&config("10.253.82.11", None)).await.unwrap());
assert!(
Bridge::start(
network.clone(),
Options {
listen: "0.0.0.0:0".parse().unwrap(),
..Options::default()
}
)
.await
.is_err()
);
let mut bridge = Bridge::start(
network.clone(),
Options {
max_sessions: 2,
handshake_timeout: Duration::from_millis(300),
udp_idle_timeout: Duration::from_millis(300),
..Options::default()
},
)
.await
.unwrap();
let result = timeout(WAIT, async {
let mut auth = TcpStream::connect(bridge.local_addr()).await.unwrap();
auth.write_all(&[5, 1, 2]).await.unwrap();
let mut selection = [0; 2];
auth.read_exact(&mut selection).await.unwrap();
assert_eq!(selection, [5, 255]);
assert_eq!(auth.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
for (bytes, code) in [
(&[5, 2, 0, 1][..], 7),
(&[5, 1, 0, 3][..], 8),
(&[5, 1, 0, 4][..], 8),
(&[4, 1, 0, 1][..], 1),
(&[5, 1, 1, 1][..], 1),
] {
let mut s = negotiate(bridge.local_addr()).await;
s.write_all(bytes).await.unwrap();
let mut response = [0; 10];
s.read_exact(&mut response).await.unwrap();
assert_eq!(response[1], code);
assert_eq!(s.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
}
let mut wrong_source = negotiate(bridge.local_addr()).await;
assert_eq!(
request(&mut wrong_source, 3, "127.0.0.2:1".parse().unwrap())
.await
.0,
2
);
drop(wrong_source);
wait_no_sessions(&bridge).await;
let mut control = negotiate(bridge.local_addr()).await;
assert_eq!(
request(&mut control, 3, "0.0.0.0:0".parse().unwrap())
.await
.0,
0
);
assert_eq!(control.read(&mut [0]).await.unwrap(), 0); // idle association expiry
wait_no_sessions(&bridge).await;
let mut incomplete = TcpStream::connect(bridge.local_addr()).await.unwrap();
incomplete.write_all(&[5]).await.unwrap();
assert_eq!(incomplete.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
// Exhaust both slots with incomplete handshakes.
let _a = TcpStream::connect(bridge.local_addr()).await.unwrap();
let _b = TcpStream::connect(bridge.local_addr()).await.unwrap();
timeout(Duration::from_millis(200), async {
while bridge.snapshot().active_sessions < 2 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let mut rejected = TcpStream::connect(bridge.local_addr()).await.unwrap();
assert_eq!(rejected.read(&mut [0]).await.unwrap(), 0);
assert_eq!(bridge.snapshot().refused_at_capacity, 1);
bridge.stop().await.unwrap();
assert_eq!(bridge.snapshot().active_sessions, 0);
})
.await;
bridge.stop().await.unwrap();
network.stop().await;
result.unwrap();
}
@@ -0,0 +1,57 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::TomlConfig;
use meshport::Network;
use std::time::Duration;
use tokio::net::UdpSocket;
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn udp_through_adjacent_mapped_subnet() {
let port = UdpSocket::bind("127.0.0.1:0")
.await
.unwrap()
.local_addr()
.unwrap()
.port();
let identity =
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
let server_config = TomlConfig::new_from_str(&format!(
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).unwrap();
let server = create_native_instance(server_config).unwrap();
server.start().await.unwrap();
let network = Network::start(&format!(
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).await.unwrap();
tokio::time::timeout(Duration::from_secs(15), async {
loop {
if network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
})
.await
.unwrap();
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let echo = tokio::spawn(async move {
let mut buffer = [0; 128];
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
});
let result = network
.probe(target, true, true, Duration::from_secs(3))
.await;
echo.abort();
network.stop().await;
server.stop().await;
assert!(
result.is_ok(),
"adjacent mapped subnet UDP failed: {result:?}"
);
}
+62
View File
@@ -0,0 +1,62 @@
# 客户端自动更新、规则集与导入
更新:2026-10-11。出口仍由用户手动选择;本轮按要求不实现自动测速选出口。
| 功能 | macOS | Android |
| --- | --- | --- |
| 订阅定时更新 | 应用运行期间 | 应用运行期间 |
| 内联 / HTTPS source、binary 规则集 | 已接入引擎 | 已接入引擎 |
| 普通 DNS、DoH、DoT | 已接入引擎 | 已接入引擎 |
| 代理节点 / TOML 文件导入 | NSOpenPanel | 系统文档选择器 |
| 相机扫码 / 二维码图片 | AVFoundation + Vision | 内置 ZXing 扫描与图片解码 |
| 应用启动后自动连接 | 已接入 | 已接入 |
| 登录时启动 | macOS 13+ 系统登录项 | 不支持,未实现 Android 开机广播连接 |
Android 本轮已编译,按用户安排暂不安装真机。macOS 图片二维码入口已实际验证;相机权限、真实登录启动和自动连接恢复仍需要用户环境验证,未为测试开启用户的登录项或自动连接开关。
## 使用入口
- **代理 → 订阅管理 → 编辑订阅**:启用自动更新,选择 15 分钟至 7 天的间隔,返回代理页点击“安全保存配置”。定时器每分钟检查到期项;应用重开也检查逾期项。
- **代理 → 编辑普通规则**:添加、排序、启停规则集。普通规则先匹配,随后规则集,再使用默认出口;组网有效子网和已撤销子网保护始终在前。全局 / 直连模式暂停普通规则和规则集。
- **代理 → 编辑 DNS**:启动解析器仍为 IP;直连和代理解析器可填写 IP、`https://主机/dns-query` 或 `tls://主机:853`。DoH 默认 443、DoT 默认 853;TLS 校验保持开启。代理 DNS 经手动所选节点;解析器主机名由独立启动 DNS 解析,避免循环依赖。仅组网模式不接管互联网 DNS。
- **代理 → 导入与预览**:选择文件、相机扫码或二维码图片。只填入草稿,点击“解析并预览”后确认导入。HTTPS 订阅链接可以选择“作为订阅地址添加”。导入普通 sing-box JSON 只提取节点,不能覆盖受管理 TUN、DNS 和组网路由。
- **组网配置导入**:TOML 导入对话框同样支持文件、相机和二维码图片,校验后由用户点击连接。
- **设置 → 启动与后台**:分别选择自动连接与 macOS 登录启动。登录项需要系统批准时会显示实际状态和系统设置入口;Android 自动连接指打开 APP 后连接,不代表开机后台建立 VPN。
## 更新与缓存行为
订阅只替换自己的来源节点,保留手动节点、其他订阅及相同节点的 ID。选中节点被删除时清空选择,用户需重新选择,不自动换出口。空响应、仅含不支持节点的响应、网络失败或超出 64 KiB 保存限额,都保留旧配置;失败后 15 分钟重试。编辑期间不自动覆盖草稿。更新成功保存到平台安全存储,当前会话的实际出口保持到显式重连。
远程规则集支持 sing-box source JSON 和 `.srs` binary,初次连接下载、连接期间每 1–168 小时更新。它们可选择直连或所选代理下载。首次下载失败且没有缓存会阻止引擎启动;后续下载或解析失败保留最后一份有效规则。缓存与 FakeIP 一样属于当前引擎私有会话,公告引起的重建可复用,释放会话会清理,不保证 APP 重启后离线使用。
内联 source JSON 可直接编辑或从文件导入,最多 256 条 / 24 KiB。全配置仍受 64 KiB 存储与引擎输入限制。二维码必须有唯一内容;文本文件最多 1 MiB、图片最多 20 MiB / 2000 万像素。文件路径不交给特权 helper,客户端只读取用户选择的内容。
自动连接默认关闭,仅使用已保存的配置和入口,每次 APP 启动尝试一次。没有已保存网络时不靠私用默认文件自动连接;仅代理功能允许使用已保存代理配置独立启动。授权取消、代理节点缺失、现有 VPN 冲突等失败会显示实际错误,不反复抢占 VPN。
## 上游规则集修补与验证
本轮真实并发刷新测试发现 sing-box 1.14.3 规则列表读写未完整同步。项目保留固定版本的最小源码修补,详情见 [补丁说明](../engines/singbox/patches/README.md)。`scripts/go-local.sh` 在忽略目录准备私有模块副本,通过备用 modfile 编译,不修改上游下载缓存;版本或原始文件哈希改变会要求重新审查修补。所有项目 Go 构建脚本均通过该入口执行。
修补同时将远程规则集下载限制为 30 秒、32 MiB、最多五次 HTTPS 重定向,拒绝 HTTP 降级和 URL 用户名密码。配置由 sing-box 原生规则集解析器校验,无法从规则集声明任意 TUN 或出口。
新增测试位于 `advanced_profile_test.dart`、`advanced_pages_test.dart` 与 `advanced_config_test.go`:订阅来源与选择保留、更新到期、配置往返、导入需预览、启动页只读状态、DoT 默认端口、真实 DoH / DoT 请求、规则集组网优先、HTTPS 规则自动刷新及失败保留。TLS 测试仅在隔离测试引擎信任临时测试证书,不修改系统证书。
原生接口依照 [Apple SMAppService](https://developer.apple.com/documentation/servicemanagement/smappservice)、[Android 文档选择器](https://developer.android.com/guide/components/intents-common#Storage) 与 [ZXing Android Embedded](https://github.com/journeyapps/zxing-android-embedded) 接入;后者固定 4.3.0,采用 Apache-2.0 许可证。DNS 采用 sing-box [HTTPS](https://sing-box.sagernet.org/configuration/dns/server/https/) 和 [TLS](https://sing-box.sagernet.org/configuration/dns/server/tls/) 传输。
## 绕过中国大陆预设
代理页的“普通互联网流量模式”新增“绕过中国大陆”。无需配置规则集:引擎使用 SagerNet 的 [geoip-cn 二进制规则集](https://github.com/SagerNet/sing-geoip/tree/rule-set),通过所选代理首次下载并每 24 小时更新。目标大陆 IP 与普通私网直连,其余目标走代理;组网有效前缀与已撤销前缀保护先于普通私网和大陆规则执行。
域名经真实 IP 解析后匹配,包括 FakeIP 恢复域名后的解析;当前引擎仍以 IPv4 为主。判断按目标 IP,不能保证“中国网站”全部直连。远程列表首次下载失败时连接失败,后续更新失败保留会话内有效列表;跨 APP 重启离线缓存尚未接入。
预设暂停自定义规则、规则集与自定义默认动作,但不覆盖保存内容。全局模式不加载大陆 IP 列表,普通流量全部走代理。原有自定义规则和直连模式仍保留;旧配置不自动切换。修改模式后保存,连接或重连生效,已有连接可能中断。
## 代理 DNS 防泄露
客户端默认启用受管理的 DNS 保护,适用于自定义规则、绕过中国大陆与全局代理。用户必须在 DNS 页明确填写代理解析器(IP / DoH / DoT),没有内置代理 DNS 服务商;缺少配置时连接前报错,不停止已有会话。普通域名查询和目标解析经所选代理发送,解析失败不尝试直连或启动解析器。
代理节点、解析器主机名仍可能通过直连启动 DNS 解析;使用 IP 地址能减少必要的启动查询,但 TLS 主机验证保持开启。配置的组网后缀 DNS 和撤销保护继续优先执行。直连模式不保证经代理的 DNS 隐私,仅组网不接管普通 DNS;应用内 SOCKS5 仅处理应用交给它的请求。统一 VPN 捕获的普通 53 端口 DNS 进入内部 DNS 模块,应用自带 DoH/DoT 仍按普通连接策略处理,不声称全设备所有解析都经过指定解析器。
本次没有加入退出 VPN 后的系统防火墙锁定,也未完成平台 IPv6、网络切换和全局 DNS 真机验收。单纯 DoH/DoT 或 FakeIP 不是这些边界的替代。
SDK 的原始 Go JSON 新增可选 `dns_protection`,启用后代理模式要求显式 `proxy_dns_server`;Flutter 客户端核心默认启用,旧保存配置重载时同样启用。未使用该字段的旧原始引擎调用保持兼容。
+30 -8
View File
@@ -7,7 +7,7 @@
构建环境需要 Flutter、JDK 17、Android SDK、NDK 28.2.13676358、CMake 3.22.1,以及 Rust 的 aarch64-linux-android target。
```sh
scripts/build-lab-android.sh --release
scripts/package-lab-android.sh
```
脚本先编译含 system-vpn 功能的 Rust 库,再打包 Flutter APK,输出到 outputs/android。当前使用开发签名,适合本机安装验证。正式发行需配置自己的签名和应用 ID。原生库与 JNI 桥接使用 16 KB ELF 页面对齐;当前真机为 4 KB 页面,16 KB 设备运行尚未验证。
@@ -16,34 +16,56 @@ 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 查询。
配置使用 Android Keystore 的 AES-GCM 密钥加密,私有存储仅保存密文与 IV,关闭 Android 备份。启动恢复表单,不自动连接;后台服务仍运行时重新打开界面会恢复该会话。
配置保存到应用私有目录 `filesDir/MeshPort/` 的 `proxy-profile.json` 和 `network-profile.toml`,目录权限 0700、文件权限 0600,使用原子写入,关闭 Android 备份。文件内容为明文,由应用沙箱隔离。旧版 Keystore 加密配置首次读取时迁移;迁移失败可在设置页手动重试,保留旧备份。启动恢复表单,自动连接由独立开关控制;后台服务仍运行时重新打开界面会恢复该会话。
## 真机验证
integration_test/android_network_test.dart 使用隔离网络身份和 USB 转发的本机测试网关,覆盖加密存储、应用内 TCP/UDP、普通系统 Socket 经 VPN 访问自动公告子网,以及公告撤销。
integration_test/android_network_test.dart 使用隔离网络身份和 USB 转发的本机测试网关,覆盖配置保存与恢复、应用内 TCP/UDP、普通系统 Socket 经 VPN 访问自动公告子网,以及公告撤销。
```sh
# 先在项目根目录启动本机夹具
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 通信、公告子网自动安装及撤销。隔离测试不修改用户配置。公网打洞、长期后台运行及移动网络切换尚未验证。
## 自用默认配置
自用配置文件为 `apps/meshport_lab/assets/config/default.private.toml`,不会提交 Git。可以从同目录的 `default.example.toml` 复制后填写网络身份、密钥、虚拟 IP 和初始节点。每台设备应使用不同的静态虚拟 IP。
Android 和 macOS 打包脚本会先执行 `sh scripts/prepare-lab-default.sh`,将私人文件复制为安装包资源 `default.toml`;没有私人文件时使用示例。直接运行 Flutter 命令之前也应先执行该脚本。APK 里的默认配置可以被提取,含密钥的自用安装包不要分发。
开发构建脚本会先执行 `sh scripts/prepare-lab-default.sh`,将私人文件复制为安装包资源 `default.toml`;没有私人文件时使用示例。直接运行 Flutter 命令之前也应先执行该脚本。APK 里的默认配置可以被提取,含密钥的自用安装包不要分发。
客户端优先读取安全存储中已保存的配置;没有可用保存配置时加载安装包默认配置,并默认开启配置保存。默认配置只预填表单,不会自动连接。保存后下次启动会恢复修改后的配置;删除保存配置后,下次启动重新使用安装包默认值。
发布打包使用 `package-lab-android.sh` 或 `package-lab-macos.sh`,仅打入公开示例配置,并恢复本地开发配置。
客户端优先读取应用私有目录中已保存的配置;没有可用保存配置时加载安装包默认配置,并默认开启配置保存。默认配置只预填表单,不会自动连接。保存后下次启动会恢复修改后的配置;删除保存配置后,下次启动重新使用安装包默认值。
最新同步版构建与验证结果见 [Android 最终包验证](../outputs/validation/android-final-sync-20261013.md)。
+4
View File
@@ -1,5 +1,9 @@
# 架构
本文描述当前实现。下一阶段 sing-box 组合客户端方案见 [组网与代理组合架构](next-stage-architecture.md),配套页面见 [移动端 UI V4](ui-design.md)。
已新增可选的应用内 [SOCKS 桥接](socks-bridge.md):通过 Rust 数据面并发转发本机 SOCKS5 TCP/UDP,C ABI/Dart 只负责启动、停止和状态。[sing-box Go 封装与本机联调](singbox-integration.md)已通过;客户端统一 TUN 尚未接入,现有普通 JSON I/O 的串行限制仍保留。
Flutter Lab → Dart SDK → C ABI → MeshPort → EasyTier 原生实例与其 smoltcp 数据面。
当前上游已经提供 `data_plane_tcp_connect`、`data_plane_tcp_bind`、`data_plane_udp_bind`。因此第一版不维护第二套 TCP/IP 栈;netstack crate 是适配边界,可在以后替换实现。
+78
View File
@@ -0,0 +1,78 @@
# 客户端联合运行控制
更新日期:2026-10-10。应用内代理与组网联合运行、节点配置、订阅导入和基础 DNS 已接入。Android 单一 VPN 已实现并交叉编译,真机验证按用户要求暂缓;macOS 统一系统 TUN/helper 已接入,实际测试范围见开发验证记录。此文区分已验证能力和待验证能力,架构图中的最终目标不等于全部完成。
## 模块边界
| 模块 | 职责 |
| --- | --- |
| `crates/meshport-socks` | 回环 SOCKS5 到独立组网 SDK 的 TCP/UDP 桥接 |
| `engines/singbox/bridge` | 受管理代理配置、分流、DNS、生命周期及宿主 TUN 适配 |
| `engines/singbox/cmd/meshport-singbox-ffi` | 数字上下文、JSON 控制、C ABI 与 socket 保护回调 |
| `bindings/flutter/singbox_flutter` | 工作 isolate 中的原生调用、按上下文排队 |
| `packages/meshport_client_core` | 联合会话、配置模型、节点与订阅解析 |
| `apps/meshport_lab` | 概览、代理、组网、设置四个主页面,24 个页面入口及平台安全存储 |
其他应用只依赖 `meshport_flutter`,继续使用独立组网 SDK,无需加载 sing-box。代理功能属于客户端可选层。
## 已实现的配置和界面
- 功能选择:仅组网、仅代理、代理与组网;仅代理不启动 MeshPort,也不要求网络名称或密钥。
- 普通互联网模式:绕过中国大陆、自定义规则、全局、直连。绕过中国大陆使用受管理的大陆 IP 列表,大陆 IP 与普通私网直连,其他走所选代理;保存的自定义规则和默认出口在该预设下暂停。全局和直连暂停普通规则,仍保留组网优先及失效目标保护。
- 节点协议:SOCKS、HTTP、Shadowsocks、VMess、VLESS、Trojan;受支持的 TLS/uTLS/Reality、WebSocket、gRPC 参数由固定上游版本验证。
- 节点按协议编辑,认证字段默认隐藏;订阅节点编辑保存为手动副本。高级传输保留 JSON 编辑入口。
- 导入分享链接、Base64 订阅和 sing-box JSON。只提取支持的节点,完整 JSON 的入口、路由、DNS 不会覆盖受管理配置。导入先预览,再确认。
- HTTPS 订阅添加、更新、删除;更新显式触发,禁止跳转,限制超时和内容大小。删除选中出口前确认,手动节点保留。
- 草稿、保存、运行出口分离。保存不改变连接;运行期间应用草稿需确认重连。macOS Keychain 和 Android KeyStore 加密保存代理配置,组网配置独立保存。
- 普通规则支持域名、域名后缀、CIDR 与 proxy/direct/reject,已使用表单编辑;DNS、组网基础、打洞、高级与线路策略均有独立页面。页面实现和限制见 [界面实现清单](ui-implementation.md)。
- 草稿节点可独立检测 HTTPS 连通性,显示 HTTP 耗时;不保存、不切换运行出口,不创建 TUN。
应用内入口为 `127.0.0.1:10818` SOCKS5,不自动设置 macOS 系统代理或系统路由。系统 VPN 组网原有路径保持独立;统一 VPN 使用 sing-box 唯一 TUN,MeshPort 使用应用内数据面。macOS helper 只加载 App 内固定 Go 动态库,互联网外层绑定物理接口,组网桥接明确绑定 lo0,避免本机回环连接被错误绑定物理网卡。
macOS 统一 VPN 的仅组网模式使用 IPv4 TUN,只安装合规公告及会话保护前缀,可与其他默认路由 VPN 共存;互联网代理模式接管拆分默认路由,检测到其他 TUN 占用时拒绝启动,不删除其他软件路由。统一模式使用静态组网 IPv4。网络切换及长期运行仍需验证。
## 生命周期与保护
组网启动顺序为 MeshPort → Rust SOCKS 桥接 → Go 引擎。停止顺序相反。启动失败回滚已有资源,网络停止失败保留所有权以便重试。`close()` 等待队列并释放代理上下文;宿主最终关闭 MeshPort。
每 2 秒读取当前虚拟 IPv4 和 `platform_network.subnet_routes`,只采用 `accepted_projection`。规范化后有变化才重建 Go 配置,无需手动远端子网列表。重建关闭已有代理连接,尚非无损热更新。
本次连接期间见过的合规组网前缀形成保护集合。有效前缀先走组网,撤销的已知前缀被拒绝,不能落入普通代理或直连;显式停止会话后清空集合。SDK 数据面也独立验证当前有效公告。
应用内联合模式中,组网暂不可用时普通代理可继续运行,状态为 `Partial`,组网目标保持拒绝。仅组网出现故障则清理会话。Android 服务故障目前整体停止,恢复行为尚需真机验证。
## DNS
- 启动解析使用明确 IP 的 UDP DNS,默认 `1.1.1.1`,不依赖尚未建立的代理。
- 客户端默认发送 `dns_protection=true`。自定义规则、绕过大陆和全局模式均须显式配置代理 DNS,经所选代理查询,失败不回退;普通目标默认解析器使用代理 DNS。直连模式使用直连 DNS 或启动 DNS。代理节点、解析器地址使用单独的启动解析避免循环依赖。
- 组网 DNS 配置指定后缀及合规组网 IP,经 MeshPort 查询;其服务公告撤销后拒绝对应查询,不回退公共 DNS。
- 组网域名查询及后续连接均保持组网出口优先。
- FakeIP 可选:IPv4 198.18.0.0/15、IPv6 fc00::/18。组网 DNS 规则先匹配且排除 FakeIP,普通 localhost/local/lan 默认排除;支持自定义后缀。真实 TCP 测试验证 FakeIP 反查与代理出口,以及公告重建后保留映射。
- 缓存放入宿主私有临时目录;Go 引擎 stop/start 保留当前会话缓存,最终释放上下文删除文件。重新连接会话会清理缓存,旧连接可能中断。
- macOS 互联网统一模式向 Dynamic Store 增加临时 DNS 补充项,helper 退出时移除,不改写持久网络服务配置;全局 DNS 与现有 TUN 共存不承诺。
- DoH/DoT 与规则集已接入,细节见 [高级客户端功能](advanced-client-features.md);完整 IPv6 端到端验证尚未完成。
## Android 单一 VPN 原型
`MeshVpnService` 持有唯一系统 TUN,MeshPort 使用应用内网络,sing-box 接收宿主提供的重复 FD 并负责 TUN 分流。JNI 为 Rust/Go 外层 socket 提供 `VpnService.protect` 回调,选择非 VPN 底层网络并监听变化;有效公告变化重建配置,组网专用捕获路由随公告更新。
入口标注“待真机验证”。仅组网捕获保护子网;互联网代理模式捕获默认路由。联合模式暂要求静态组网 IPv4。代码和 APK 编译成功不代表底层网络切换、后台运行或实际单一 VPN TCP/UDP 已验证。
## 原生接口和验证
C ABI 提供 version、context_new、call、string_free、context_free,以及宿主 socket 保护回调注册。请求为 NUL 终止 UTF-8,JSON 最大 64 KiB;未知字段、尾随数据与操作拒绝,错误不返回配置凭据。Java JNI 使用标准 UTF-8,避免认证字段中非 ASCII 字符损坏。
```sh
sh scripts/go-local.sh test -race ./...
sh scripts/go-local.sh vet ./...
sh scripts/test-client-runtime.sh
sh scripts/test-singbox-bridge.sh
sh scripts/build-lab-macos.sh
sh scripts/build-lab-android.sh --debug
```
Go 测试包含真实 SOCKS/直连通信、三种模式的组网优先、DNS 域名规则、撤销 DNS 拒绝及 ABI 并发释放。Flutter 测试包含生命周期、失效前缀保护、组网故障后的部分运行、配置导入、节点编辑与真实 Rust/Go 动态库启停。跨语言组网 TCP/UDP 和公告撤销端到端验证见 [引擎接入](singbox-integration.md)。构建产物和本轮验证记录见 [开发验证记录](development-validation.md)。
## 尚未完成
Android 单一 VPN 真机通信与网络切换、macOS 互联网统一模式全局 DNS 和网络切换、相机及真实登录启动恢复、长时间和后台稳定性测试仍需验证。规则集、扫码/文件导入、自动订阅更新与应用启动自动连接已接入,见 [高级客户端功能](advanced-client-features.md)。自动测速选出口按用户要求不实现。原有 Android 独立组网真机测试与本轮新增代理联合模式测试是不同范围。
+128
View File
@@ -0,0 +1,128 @@
# 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。
| 检查 | 结果和范围 |
| --- | --- |
| Go `test -race ./...` | 12 项顶层测试通过;模式、组网优先、真实 DNS/FakeIP TCP 通信、撤销 DNS、缓存重建、隔离草稿 HTTP 检测、诊断范围隔离及 ABI 生命周期 |
| Go `vet ./...` | 通过 |
| Flutter `analyze` | 无问题 |
| Flutter 客户端测试 | 22 项通过,含原生 Rust/Go 联合启停、Partial、撤销保护、导入、认证隐藏、DNS/规则/组网表单 |
| macOS APP | 构建通过,包含统一 TUN helper;最终开发签名 `codesign --verify --deep --strict` 通过 |
| Android ARM64 APK | 构建通过;APK v2 签名、zipalign 16 KiB 校验通过,JNI/Rust/Go ELF LOAD 对齐均 ≥ 16 KiB |
| macOS 系统 TUN | 普通 OS TCP/UDP 回显、公告子网自动接入、停止删除测试路由及保持默认路由均通过;范围仅为 10.253.88.0/24 测试网 |
| Rust/FFI 映射子网 UDP | 同一 /24 内相邻 /25 的纯 SDK 和 FFI 回归均通过;测试网关必须编译 `proxy-packet`,此前 FFI 超时来自测试构建缺少此组件 |
| Android 联合 VPN 真机 | 未执行;入口明确标注待验证 |
Go/Rust 上游仍存在既有链接或弃用警告,不影响上述成功结果。第一次 Go 回归在沙盒中不能监听本机端口,放开本机测试端口后全部通过;不是功能回归。macOS TUN 首轮发现测试构造需要进入 Tokio runtime,随后修正 smoltcp TCP 回显服务提前关闭,以及错误地把出站 SDK UDP socket 当作入站服务的问题;UDP 自检使用远端映射子网和普通 OS 服务;正式流量通路已明确区分物理出口与 lo0 桥接出口;另修复有效前缀与保护前缀重复生成 TUN 路由,避免公告重建时重复删除导致清理失败,并新增回归测试。helper 自检网关已显式启用 `proxy-packet`,此前 UDP 包到达网关后没有进入子网转发,并非已证实的正式远端网关故障。新增不使用 TUN 的 SDK/FFI 回归覆盖这一场景。TUN 关闭后等待内部地址释放再重建;系统自检已验证重建后路由保留及普通 TCP/UDP 回显,尚不代表长时间稳定性验收。仅组网模式还移除了无对应公告的 IPv6 TUN 地址,避免上游根据空 IPv6 route_address 安装隐式 IPv6 默认路由。
系统自检记录见 [macOS 统一 TUN 日志](../outputs/validation/macos-unified-tun-20261011.log),日志仅含本机测试网络,不包含用户网络配置。
## 构建产物
- macOS:`apps/meshport_lab/build/macos/Build/Products/Debug/MeshPort.app`,构建号 `20261011095231`。
- Android:`outputs/android/MeshPort-0.1.0-1791641256-debug.apk`,ARM64 调试签名。
macOS 是本机开发签名,未公证;Android 是调试 APK,均不是正式发布版本。
## 验证边界
保留用户现有 v2rayN 与已连接 MeshPort,不做全局路由切换。因此 macOS 互联网统一 TUN 的全局 DNS、IPv6、网络切换与长时间运行未实测;不把仅组网的受限路由测试称作全局代理测试。Android 新增联合 VPN 的实际通信、后台和网络切换仍需真机。
公告变化重建 Go 引擎,会中断已有连接,尚无无损热更新。新版概览、代理与 DNS/FakeIP 页面已在 macOS 实际窗口检查,四个导航和编辑入口可达;全部页面的不同尺寸视觉验收仍需继续。
FakeIP 缓存在同一上下文重建时保留,最终释放清理,跨会话重新连接可能影响系统保留的旧 DNS 结果。
页面和限制见 [界面实现清单](ui-implementation.md);使用方法与模块边界见 [客户端运行控制](client-runtime.md)。
## 2026-10-11:高级客户端功能
已追加自动订阅更新、source/binary 与内联规则集、DoH/DoT、macOS/Android 原生文件和二维码导入、应用启动自动连接与 macOS 13+ 登录项设置;自动选出口按要求不实现。使用入口、缓存范围和平台差异见 [高级客户端功能](advanced-client-features.md)。
- Flutter 全量测试:34 项通过,3 项专门环境/UI 开关测试跳过;Rust/Go 动态库生命周期测试实际执行。
- Go 全量 `test -race ./...` 和 `vet ./...` 通过;新增真实 DoH / DoT 解析、规则集组网优先、HTTPS source 自动刷新、下载失败保留有效规则和直连模式暂停代理 DNS / 规则集测试。
- 并发测试暴露 sing-box 1.14.3 远程规则集读取与更新的竞争,已用 [固定版本补丁](../engines/singbox/patches/README.md) 修复,复现测试继续保留。
- macOS:构建、深度签名验证通过;真实图片选择器读取测试 QR,并显示 1 个节点的预览,未保存或连接测试节点。
- Android:ARM64 APK 已编译;相机、文档选择与新自动连接尚未真机验证。本轮未连接手机或安装 APK。
- 未开启用户的登录项、自动连接或相机权限,未替换 `/Applications/MeshPort.app`,保留现有 v2rayN 与 MeshPort 连接。真实登录恢复、相机与公共加密 DNS 在当前网络的可达性需后续验证。
最终高级功能 APP 与 APK 的路径记录在 `outputs/validation/advanced-client-20261011.md`;APP 位于独立输出目录,避免覆盖用户正在查看的开发构建。
## 2026-10-11:macOS 连接配置修复
实际客户端连接失败来自 `foreign_relay_bps_limit`:上游默认 u64::MAX 投影为 JSON 数值后,被 Dart 舍入为浮点数,重新生成 TOML 导致 EasyTier 配置校验失败。FFI 投影和编辑器改为精确十进制字符串,客户端迁移旧的默认无限制值并拒绝其他不精确输入。
- 原生 Rust FFI 投影测试通过;Flutter 原生配置往返与配置页面共 6 项测试通过;Flutter analyze 无问题。
- 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` 已覆盖安装并打开,保留现有配置。此次只修改方向配置,未自动开启手机相机或扫描用户二维码。
### macOS 关闭窗口与菜单栏驻留
MainFlutterWindow.close 改为隐藏窗口,保留 Flutter 控制器和网络会话;取消最后窗口关闭时退出。AppDelegate 强持有主窗口与状态栏项,顶部图标提供“打开 MeshPort”和“退出 MeshPort”;Dock 重新打开同样恢复原窗口,不创建第二个引擎。关闭主窗口时取消正在进行的相机扫码。
原生 XCTest 两项通过:performClose 隐藏窗口但保留同一控制器,菜单打开动作恢复保留的窗口,退出项明确指向 NSApplication.terminate。修复了原有 RunnerTests 仍引用 meshport_lab.app 的 TEST_HOST 和 scheme 名称。使用隔离预览验证关闭后进程保留、明确退出后进程消失;界面工具无法直接读取状态栏项,其打开动作由原生检查覆盖。未在本轮切换真实 VPN 连接。
普通入口产物 `outputs/macos/MeshPort-0.1.0-menubar.app` 及 ZIP;未开启 MESHPORT_UI_PREVIEW。构建和深度严格签名验证通过,本机开发签名。测试预览已退出,原有配置未改动。
+17
View File
@@ -12,6 +12,10 @@
控制操作:validate/start(toml)、stop、status。
`validate` 的 `include_profile=true` 投影将 `flags.foreign_relay_bps_limit` 编码为十进制字符串,以精确保留 u64 范围;宿主重新生成 TOML 时也应使用十进制字符串。默认无限制值为 `"18446744073709551615"`,不能经过浮点数转换。Flutter 会迁移旧配置中被舍入的默认无限制值,其他不精确或越界值要求重新输入。
应用内组网桥接:`socks_start`(可选 port,默认 0;max_sessions,默认 128)、`socks_status`、`socks_stop`。数据转发直接走原生并发任务,不经 JSON 字节 I/O。仅支持 IPv4 回环 SOCKS5 TCP/UDP;域名、IPv6、不支持的命令不做外部回退。stop/context free 先清理桥接再停止网络;socks_stop 不停止组网。需要新版原生库,详见 [SOCKS 桥接](socks-bridge.md)。
Android 系统模式需宿主 VpnService 创建 TUN 后调用 attach_tun(fd)。fd 由宿主持有,原生库不负责关闭;必须在原生实例停止后再关闭,替换网卡时须等新接口 ready 后关闭旧 fd。启动前注册 meshport_set_android_socket_protector,将原生 worker 的外层 socket 交给 VpnService.protect,回调与 JVM 桥接需保持有效。参考客户端 MeshVpnService 和 JNI NativeBridge。
TCP:tcp_connect(target)返回 resource;tcp_write(resource、bytes);tcp_read(resource、max_bytes、timeout_ms)返回 bytes/eof。
@@ -39,3 +43,16 @@ probe:target、protocol(TCP/UDP)、echo、timeout_ms。TCP echo=false 只
注意上游 directly_connected_conns 只统计非打洞连接,本 SDK 不再直接以其为空推断中继。peers.direct 包括 TCP/UDP 打洞后的物理连接,hole_punched 表示存在上游归类为打洞的存活连接。页面的直连/中继标签仍根据所选下一跳判断,而非仅根据 direct。
`quality_sample` 请求:`resource` 为已绑定 UDP 句柄,`target` 为 IPv4:port,`sequence` 为 u64,`timeout_ms` 为100–5000(默认1000)。返回 success、elapsed_ms、target_peer_id、next_hop_peer_id、next_hop_after、route_changed。超时/I/O错误返回 success=false、elapsed_ms=null;非法句柄或参数走 ABI 错误。复用 socket 并顺序调用,目标须支持原样 echo;状态前后采样不计入 RTT。
### 高级受管理代理配置(2026-10-11)
`direct_dns_server` 可选,`proxy_dns_server` 支持普通 IP DNS、HTTPS DoH、TLS DoT。`dns_server` 保留为独立 IP 启动解析器。直连模式不建立代理 DNS 依赖;代理 DNS 非直连模式需要手动选择代理节点。
`rule_sets` 是最多 32 个受管理条目的数组:`tag`(唯一)、`enabled`、`action`(proxy/direct/reject)。远程条目使用 `url`(HTTPS)、`format`(source/binary)、`download_detour`(direct/proxy)、`update_hours`(1–168,默认 24);内联条目使用 `rules`(sing-box headless 规则)。远程和内联不能混用,不接收特权文件路径。仅规则模式加载规则集,组网保护优先。配置入口仍拒绝未知字段及超过 64 KiB 的请求;不接受完整未管理 sing-box 配置。
订阅的 `auto_update` / `interval_minutes`、代理配置的 `proxy_enabled` 以及平台启动首选项由客户端持久化层管理,不是 EasyTier 组网 SDK 新参数。版本 1 配置可读取旧字段缺失的保存数据。自动连接仍按系统权限实际结果报告状态。
## 代理 DNS 保护
sing-box 引擎配置新增可选布尔字段 `dns_protection`。启用后,非直连互联网模式要求明确的 `proxy_dns_server` 和代理节点,普通解析和默认域名解析器均使用代理 DNS;不配置默认公共解析器,不回退启动 DNS。Flutter ProxyProfile 默认发送此字段,旧 JSON 调用未设置字段时兼容旧行为。代理节点与解析器主机名使用受管理 bootstrap 解析以避免循环;仅组网与直连模式保持独立。宿主应在关闭旧会话之前执行连接校验。
+113
View File
@@ -0,0 +1,113 @@
# 下一阶段架构:组网与代理组合客户端
更新日期:2026-10-10。状态:部分实现。现有实现见 [当前架构](architecture.md),页面和行为依据见 [UI 设计 V4](ui-design.md)及其交互说明。
开发进度:已完成 [MeshPort SOCKS 桥接](socks-bridge.md)及 FFI/Dart 控制入口,并新增 [sing-box Go 封装](singbox-integration.md),通过本机跨语言 TCP/UDP 与公告撤销验证。组网 SDK 原有 JSON I/O 仍串行;已新增 [独立 singbox_flutter 与客户端核心](client-runtime.md),实现应用内联合生命周期和公告变化后的配置重建;普通代理配置、订阅、模式和基础 DNS 已接入;Android 统一 TUN 为待真机验证原型,macOS 统一 TUN/helper、FakeIP 与新版主要页面已接入,测试范围见 [验证记录](development-validation.md)。下文目录与架构图表达最终目标,具体已实现范围以接入文档为准。
## 模块架构
保留 MeshPort 独立组网 SDK。代理引擎与组合会话管理属于客户端扩展,不让其他应用使用组网 SDK 时强制依赖 sing-box。
```mermaid
flowchart TD
UI[Flutter 客户端:概览 / 代理 / 组网 / 设置] --> Core[客户端核心:状态 / 配置 / 订阅 / 路由 / DNS]
Core --> MB[meshport_flutter]
Core --> SB[singbox_flutter]
Core --> Platform[平台权限 / 安全存储 / 网络入口]
MB --> FFI[meshport-ffi:C ABI]
FFI --> SDK[meshport:Rust SDK]
SDK --> Adapter[meshport-easytier / meshport-netstack]
Adapter --> ET[EasyTier 核心与应用内数据面]
SB --> Go[sing-box Go 封装]
Go --> Socks[meshport-socks:组网 SOCKS5 桥接]
Socks --> SDK
Platform --> Android[Android:VPN Service / 原生桥接]
Platform --> Mac[macOS:系统接入 / 特权 helper]
Other[其他项目应用] --> MB
```
客户端核心负责组合状态、配置验证、持久化与生效、公告变化和故障反馈。Rust SDK 负责组网、节点、选路及数据面;Go 封装负责代理引擎运行和接口适配。Flutter 页面不直接拼装内核配置或操作系统路由。
## 组合模式数据路径
```mermaid
flowchart LR
Apps[系统应用 TCP / UDP] --> TUN[一个平台 TUN]
TUN --> Route[sing-box 统一分流]
Route -->|有效组网地址与公告子网| Socks[MeshPort SOCKS5:TCP / UDP]
Socks --> Stack[MeshPort 应用内数据面]
Stack --> ET[EasyTier:直连或中继]
ET --> Remote[远端节点 / 公告局域网]
Route -->|普通代理目标| Proxy[代理出口]
Route -->|普通直连目标| Physical[物理网络]
Proxy --> Physical
ET --> Physical
```
这张图表示目标方案。组合会话只允许一个系统 TUN 所有者,MeshPort 使用应用内数据面,不同时启动现有 EasyTier 系统 TUN。现有独立系统组网模式仍可单独使用。
组网优先规则仅包含合规且有效的目标,不泛化为所有私网地址。两侧引擎的外层连接需绕过自身 TUN,避免循环;代理服务器启动解析也不能依赖尚未建立的同一个代理。Android 的连接保护和底层网络选择、macOS 的物理网络出口处理属于原生平台适配职责。
公告接入、撤销和失联时同步更新有效分流与状态。组网目的地不可静默降级到互联网代理;保护记录及恢复本地访问行为按 V4 交互说明实施。
## 目标目录
“新增”为计划模块,其余保留现有边界;目录名称在落实接口时可调整。
```text
MeshPort/
├── crates/
│ ├── meshport/ # 现有:组网 SDK 公共接口
│ ├── meshport-easytier/ # 现有:EasyTier 适配、选路、公告子网
│ ├── meshport-netstack/ # 现有:应用内 TCP/UDP 数据面
│ ├── meshport-ffi/ # 现有:C ABI
│ └── meshport-socks/ # 新增:组网 SOCKS5 TCP/UDP 桥接
├── engines/
│ └── singbox/ # 新增:Go 引擎封装
│ ├── bridge/ # 启停、状态、统计、出口切换
│ ├── platform/ # TUN 与底层连接接口
│ └── tests/
├── bindings/flutter/
│ ├── meshport_flutter/ # 现有:独立组网 SDK 绑定
│ └── singbox_flutter/ # 新增:代理引擎平台绑定
├── packages/
│ └── meshport_client_core/ # 新增:共用客户端业务逻辑
│ └── lib/
│ ├── runtime/ # 两侧生命周期、组合状态
│ ├── configuration/ # 草稿、保存、运行快照、迁移
│ ├── subscriptions/ # 导入、更新、来源、节点归属
│ ├── routing/ # 组网优先、普通规则、默认出口
│ ├── dns/ # 域名范围、解析出口、失败策略
│ ├── telemetry/ # 状态、流量、测量、脱敏日志
│ └── platform/ # 权限、能力、安全存储接口
├── apps/meshport_lab/ # 现有客户端,逐步重构
│ ├── lib/
│ │ ├── app/ # 导航、主题、依赖组装
│ │ ├── features/
│ │ │ ├── overview/
│ │ │ ├── proxy/
│ │ │ ├── network/
│ │ │ └── settings/
│ │ └── shared/ # 控件、状态视图、确认框
│ ├── android/ # VPN Service、权限、连接保护
│ └── macos/ # 系统接入、helper、安全存储
├── tools/
│ ├── meshport-vpn-helper/ # 现有 macOS 特权入口,按需扩展
│ └── meshport-test-server/ # 现有 TCP/UDP 验证服务
├── tests/integration/ # 新增:组合模式与平台联调
├── scripts/ # Rust/Go 构建、打包、安装
└── docs/ # 架构、设计、配置、验证
```
## 开发顺序与完成条件
| 阶段 | 工作 | 完成条件 |
| --- | --- | --- |
| 1:组网桥接 | SOCKS5 TCP/UDP、连接级并发、取消及资源清理 | 并发连接不被单次读取串行阻塞,目标与会话正确隔离,停止无残留 |
| 2:引擎及平台入口 | Go 封装、Android 单一 VPN 入口,随后 macOS | 仅组网、仅代理、组合模式通信通过;两侧外层流量不循环 |
| 3:配置与状态 | 订阅、草稿/保存/生效、DNS、公告接入及撤销 | 部分失败和权限取消准确呈现,更新可确认,失效组网目标不泄漏到互联网代理 |
| 4:UI 与稳定性 | 按 V4 拆页面、后台与恢复、持续验证 | 网络切换、重连、故障恢复及长时间运行通过真实设备验证 |
当前 ABI 每 context 串行,不能直接作为大量 SOCKS 并发连接的最终数据面;先完善异步提交、取消和连接级并发,或为桥接层提供等价的 Rust 原生并发接口。
初期保留 apps/meshport_lab 的目录与安装标识,减少同时迁移构建脚本、包名和配置存储的风险;正式命名迁移另列任务。实现应固定依赖版本、记录构建特性与上游许可证,并按实际平台能力开放 UI。
+66
View File
@@ -0,0 +1,66 @@
# sing-box 引擎接入:第一阶段
更新日期:2026-10-10。本文件记录第一阶段组网桥接的验证路径,下文“本阶段”均指最初 mesh-only 范围。当前已追加普通代理出口、配置与订阅、模式和基础 DNS;Android 单一 VPN 为待真机验证原型。最新范围见 [客户端运行控制](client-runtime.md)。
## 已实现的路径
```mermaid
flowchart LR
Test[本机 SOCKS5 测试客户端] --> Go[sing-box:回环入口与受管理分流]
Go --> Rust[MeshPort SOCKS5:原生并发 TCP/UDP]
Rust --> SDK[应用内 MeshPort / EasyTier]
SDK --> Gateway[远端节点:自动学习的合规公告子网]
Gateway --> Service[TCP / UDP echo 服务]
```
引擎固定使用 sing-box 1.14.3,依赖版本与校验记录在 engines/singbox/go.mod 和 go.sum。项目本地脚本设置独立 Go 模块、构建缓存,工具链最低要求由 go.mod 的 Go 1.25.5 声明决定;没有升级系统 Go 安装。
SOCKS 出口依据 [sing-box 官方接口](https://sing-box.sagernet.org/configuration/outbound/socks/)接入;本阶段只注册所需的本机 SOCKS 能力。模块固定上游版本,不改写下载缓存内的源码;当前规则集并发修补通过项目私有模块副本构建,见 [补丁说明](../engines/singbox/patches/README.md)。上游许可证副本见 [sing-box LICENSE](upstream/sing-box-LICENSE)。
## 模块职责
| 文件 | 作用 |
| --- | --- |
| engines/singbox/bridge/config.go | 从有效组网前缀生成受管理配置;验证回环端点、地址范围和数量 |
| engines/singbox/bridge/engine.go | 引擎启动、停止、状态及失败恢复;重复启动拒绝,停止可重复调用 |
| engines/singbox/bridge/inbound.go | 跟踪已接受但尚未路由的 TCP 控制连接;停止时关闭全部控制连接,最多 128 个 |
| engines/singbox/bridge/outbound.go | TCP 使用上游 SOCKS 出口;UDP 标准化关联握手并复用上游报文封装 |
| engines/singbox/cmd/meshport-singbox | 读取受管理配置、输出一次就绪状态、响应退出信号的开发程序 |
| crates/meshport-socks | 本机 SOCKS 到独立组网 SDK 的桥接 |
只有配置前缀内的 IPv4 流量进入组网出口;其他目标和域名请求显式拒绝,没有普通互联网出口。当前前缀额外限制为私网 /16–/32,不接受所有私网、公共段、IPv6 或默认路由。地址属于允许范围不等于已公告,宿主仍需从 SDK 的合规有效投影生成配置。
mesh_cidrs 是宿主从 SDK 状态生成的内部字段,不是新增的用户手动远端子网列表。联调测试直接读取 platform_network.subnet_routes 和当前虚拟地址。Go 使用启动时快照;公告撤销由底层 SDK 即时阻止转发。现有客户端核心按有效投影变化自动重建 Go 引擎,无需手动列表;变化会关闭已有代理连接。无损热更新仍待实现;当前客户端核心已保留本次会话中的已知前缀,撤销目标由显式拒绝规则保护。
组网目标没有路由时返回连接失败或关闭连接,UDP 不交给其他出口。域名在分流第一条即拒绝,不做系统 DNS;此处描述最初 mesh-only 配置;当前联合模式已实现组网 DNS 和普通代理解析,FakeIP 已实现,范围见客户端运行控制。
## 联调中修正的问题
- TCP 半关闭时远端 FIN ACK 可能因路由撤销而无法返回,Rust 桥接加入有界收尾时间,避免永久占用会话。
- 引擎停止时,尚未完成 SOCKS 请求的连接还没进入路由连接管理器;Go 接入层在协议处理前跟踪连接,保证停止时主动关闭。
- UDP ASSOCIATE 按 [RFC 1928](https://www.rfc-editor.org/rfc/rfc1928)表达客户端预计使用的来源端点。Go 适配层在尚未分配 UDP 端点时发送 IPv4 0.0.0.0:0,避免将远端私网目标或其服务端口误当作来源。Rust 的来源 IP/端口隔离保持有效;不修改上游版本的握手实现。
Go UDP 握手受上下文取消和最长 5 秒超时控制;仅接受同一桥接 IP 返回的有效 IPv4 回环端点。取得关联后保留 TCP 控制通道,关联关闭会清理控制和 UDP 资源。宿主在上下文取消后仍需调用 Engine.Stop;Snapshot 不将已取消上下文标作 Running。
## 构建与验证
```sh
sh scripts/go-local.sh mod download
sh scripts/go-local.sh test -race ./...
sh scripts/go-local.sh vet ./...
sh scripts/build-singbox.sh
sh scripts/test-singbox-bridge.sh
scripts/cargo-local.sh test -p meshport-socks -p meshport-ffi --locked
```
开发程序输出到 target/debug/meshport-singbox,缓存和二进制均在 Git 忽略目录。配置输入上限 64 KiB,拒绝未知字段和尾随 JSON,不接收任意完整 sing-box 配置;默认关闭内核日志,只输出就绪状态,不打印配置或凭据。
端到端测试自行建立本机真实 EasyTier 网关、客户端和 echo 服务,自动学习测试公告;网关将测试私网映射到回环地址。它启动 Go 引擎,然后验证四个并发 TCP 连接、空闲 TCP 与两组 UDP 会话、公告撤销后的 TCP/UDP 失败及程序停止。测试不需要管理员 VPN 权限,不改系统路由,不读取个人网络配置。
第一阶段 Go 引擎有 3 项测试(配置约束、拒绝未配置目标/域名、启停与恢复),通过 race 检查;新增代理策略测试见客户端验证记录。Rust 桥接/FFI 常规测试 7 项通过。跨语言端到端测试默认显式忽略,由 test-singbox-bridge.sh 构建引擎后单独执行,已通过。Rust Clippy 与 Go vet 通过。
本次验证平台为开发机 macOS ARM64。链接器仍报告上游/工具链的重复 objc 与 race 对象符号表警告,编译与测试成功;不据此宣称已通过 Android 或实际系统 VPN 验证。
## 后续进度
以 [客户端运行控制](client-runtime.md) 和 [开发验证记录](development-validation.md) 为准。macOS 统一 TUN 的限定子网 TCP/UDP 与清理自检已通过;Android 联合模式仍需真机验证。新增高级功能范围见 [高级客户端功能](advanced-client-features.md)。
+77
View File
@@ -0,0 +1,77 @@
# 应用内组网 SOCKS 桥接
更新日期:2026-10-10。下一阶段第一批实现:新增 `crates/meshport-socks`,并提供 C ABI 与 Dart 控制入口。[sing-box 本机引擎联调](singbox-integration.md)已完成;统一 TUN 和新 UI 尚未接入,现有客户端不会自动启动此桥接。
## 接入方式
```text
本机代理引擎/测试程序 → 回环 SOCKS5 → Rust MeshPort 数据面 → EasyTier → 虚拟地址/合规公告子网
```
每个连接/关联在 Tokio 独立任务中运行,转发直接使用 Rust 数据面,不通过串行 JSON 字节读写。现有 ABI 的普通 TCP/UDP 读写操作仍是每 context 串行;本次没有将它们改为异步 ABI。
按 [RFC 1928](https://www.rfc-editor.org/rfc/rfc1928)的报文格式实现受限的本机桥接:CONNECT 与 UDP ASSOCIATE,IPv4 地址、无认证协商。没有 GSSAPI、用户名密码、BIND、IPv6、域名解析或 UDP 分片,不能作为完整公开 SOCKS 服务使用。不支持的 TCP 请求返回协议错误;不支持的 UDP 报文丢弃。
- 仅允许 IPv4 回环监听,默认动态端口;调用者持有同一应用内 `Network`。
- SDK 公共 TCP 数据面采用 OverlayOnly,未找到组网路由时失败,不调用普通互联网直连。UDP 使用组网数据面,不提供外部回退。
- 公告子网仍由现有 SDK 自动学习、过滤与撤销;无需手动填写远端 CIDR。
- 域名需上层按 DNS 策略解析到 IPv4,再交给桥接;桥接不使用系统 DNS,避免意外域名泄漏。
- UDP 关联绑定 TCP 控制连接来源 IP,按请求端口或首个合法数据报固定来源端口;仅向本关联已发送过的目标接收返回数据。
- 关联在控制连接关闭、空闲超时或桥接停止后释放。TCP 在任一方向 EOF 后给另一方向有限的收尾时间,防止路由失效后无限等待 FIN ACK。
- 本机无认证监听不隔离同一设备上的其他进程;后续正式集成若需要隔离,应增加认证或平台内通道,不能把回环监听视为秘密凭据保护。
## Rust
```rust,ignore
let network = std::sync::Arc::new(meshport::Network::start(&toml).await?);
let mut bridge = meshport_socks::Bridge::start(
network.clone(),
meshport_socks::Options::default(),
).await?;
let endpoint = bridge.local_addr();
// 将 endpoint 配置为宿主代理引擎的组网 SOCKS 出口。
bridge.stop().await?;
network.stop().await;
```
生命周期顺序:启动组网 → 启动桥接 → 启动宿主代理;停止时先停宿主代理,再停止桥接,最后停止组网。`Bridge::stop` 等待子任务清理,可重复调用;Drop 发起取消但不能同步保证异步任务已回收。
默认限制:128 个会话,握手 5 秒,连接/UDP 建立 10 秒,TCP 半关闭收尾 30 秒,UDP 空闲 120 秒、单次发送 5 秒,每关联最多 64 个尝试目标。超限不排队创建无限任务;关联目标集合包含发送失败的尝试,避免底层 flow 无限增长。Rust Options 可调整,启动时校验范围和非零超时。
SOCKS IPv4 UDP 封装增加 10 字节,当前每个数据报最多承载 65497 字节。大于此值的远端响应会丢弃;这不表示实际线路 MTU 支持同样大的无分片报文。TCP/UDP 协议和 MTU 限制不提供 ICMP 转发。
## C ABI / Flutter
新增控制请求(保留 ABI 版本 1):
```json
{"op":"socks_start","port":0,"max_sessions":128}
{"op":"socks_status"}
{"op":"socks_stop"}
```
`socks_start` 返回 running、listen、tcp、udp、ipv4_only、dns_resolution。已有桥接时启动失败;系统 VPN 模式或未启动网络时启动失败。`socks_status` 返回运行状态、当前/累计会话、完成/失败会话、容量拒绝及 UDP 丢弃数量;这些是桥接计数,不是链路丢包率或应用流量。
`stop` 和 context free 会先停止桥接,再停止组网,关闭监听与所有会话;`socks_stop` 保留组网实例。容量拒绝的连接不计入 accepted;取消的会话不会计入 completed/failed,因此累计值不要求严格相加相等。
```dart
await client.start(applicationToml);
final bridge = await client.startSocksBridge();
final endpoint = bridge['listen'];
final status = await client.socksBridgeStatus();
await client.stopSocksBridge();
await client.stop();
```
运行这些方法需要重新构建原生 FFI 库。只更新 Dart 而加载旧库会返回未知操作,不会产生可用桥接。平台宿主的单一 TUN 与外层连接保护留给下一批实现。
## 验证
```sh
scripts/cargo-local.sh test -p meshport-socks -p meshport-ffi --locked
scripts/cargo-local.sh run -p meshport-socks --example local_bridge -- /path/to/application.toml
```
测试使用本机真实 EasyTier 引导节点与远端网关,网关将公告私网映射到回环 TCP/UDP echo 服务,不修改系统路由,不读取私人配置。覆盖:并发 TCP、空闲 TCP 不阻塞其他会话、双 UDP 关联隔离、来源端口限制、分片拒绝、公告学习与撤销、协议错误、容量/握手/空闲超时、重启及 FFI/context 清理。
这批验证只覆盖开发机本地网络。Android 原生构建与真机、macOS 实际组合 VPN、远程高延迟与长时间压测仍需后续验证。
+42
View File
@@ -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 构建号、系统版本、入口与功能、节点协议、网络类型、时长、请求数量/失败数量、延迟、内存趋势、恢复时间和遗留资源检查。测试报告区分“已通过”“失败”“未执行”;只有三种入口及目标平台的相关场景完成后,才对对应范围给出稳定性结论。
+4 -4
View File
@@ -22,15 +22,15 @@ Rust 的 `system-vpn` feature 是显式编译开关;默认 SDK 构建保持应
## 启动和生命周期
运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接、控制通道关闭或空闲超时后停止引擎;临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。
运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接停止引擎,但应用存活期间保留已授权 helper 和控制通道,使用每 30 秒一次的空闲心跳支持下次连接复用授权。退出应用关闭控制通道并清理 helper;控制通道异常关闭或空闲超时也会停止引擎,临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。
原生调用超过 60 秒时 helper 退出,以关闭 utun 文件描述符;Dart 控制请求超时为 30 秒。
设置页顶部有“配置保存”面板,可在未连接时点击“保存配置”。完整 TOML(包含网络密钥)保存在 macOS Keychain;启动时自动回填表单,不自动连接。已保存的配置可以重新载入或删除。“连接成功后自动保存配置”首次默认关闭,主动保存或加载已有配置后开启。未编辑的导入配置原样保留高级参数;修改表单后使用表单生成的配置。
设置页支持自动保存和独立的自动连接开关。配置保存在 `~/Library/Application Support/MeshPort/`,代理文件为 `proxy-profile.json`,组网文件为 `network-profile.toml`;目录权限 0700、文件权限 0600,内容为明文,使用原子写入。启动时尝试无弹窗迁移旧 Keychain 配置;需要授权时在设置页点击“迁移旧配置”,保留旧备份且不覆盖已有本地配置。未编辑的导入配置保留高级参数;修改表单后使用表单生成的配置。
## 发布边界
这是开发版 helper 方案,使用临时管理员授权与 ad-hoc 签名,尚未完成正式签名、公证或 Network Extension 发布流程;macOS App Sandbox 已为此开发方案关闭。Android VpnService 已接入,并通过隔离真机 TCP/UDP 和自动公告路由验证,详见 [Android](android.md)。iOS Packet Tunnel、移动端长期后台恢复仍待验证。
这是开发版 helper 方案,使用管理员授权。Release 打包优先使用可用的 Apple Development 身份保持签名稳定,没有身份时使用 ad-hoc;尚未完成 Developer ID 签名、公证或 Network Extension 发布流程;macOS App Sandbox 已为此开发方案关闭。Android VpnService 已接入,并通过隔离真机 TCP/UDP 和自动公告路由验证,详见 [Android](android.md)。iOS Packet Tunnel、移动端长期后台恢复仍待验证。
显式特权自检:`sudo target/debug/meshport-vpn-helper --self-test`。自检通过 loopback 建立两个隔离的 EasyTier 节点,使用 10.253.77.0/24 作为客户端虚拟网段,自动学习另一节点发布的 10.253.78.0/24,验证额外子网路由以及普通系统 TCP/UDP 经 utun 回显、默认路由保持不变、公告撤回后的路由删除和停止后的接口删除。最多运行 45 秒;阶段日志写入 `/tmp/meshport-vpn-self-test-<pid>.log`,不写网络密钥。
@@ -42,4 +42,4 @@ macOS 的节点连接使用物理网卡候选,IPv4/IPv6 都排除其他 VPN
保留 v2rayN TUN,先用 `route -n get 192.168.21.201` 检查更具体的 /24 路由是否指向 MeshPort 的 utun。只设置 v2rayN “直连”规则不能建立 EasyTier 子网路由。如路由仍被代理接管,再检查 TUN 路由排除配置;不要依赖变化的 utun 编号设置永久路由。
旧版 runtime.subnet_routes 已移除;Lab 从钥匙串恢复旧版单行配置时会删除该字段并改用自动学习。直接使用 SDK 的旧配置应移除此字段。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。
旧版 runtime.subnet_routes 已移除;Lab 恢复旧版已保存单行配置时会删除该字段并改用自动学习。直接使用 SDK 的旧配置应移除此字段。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。
+59
View File
@@ -0,0 +1,59 @@
# MeshPort 移动端 UI 设计 V4
更新日期:2026-10-10。包含 24 个页面和 4 个公共状态示例,覆盖组网与代理组合客户端的目标交互。此文档为下一阶段设计依据,图片中的数据为示例,不表示客户端已经实现全部功能。
配套文档:[交互规则与验收场景](../outputs/ui/meshport-ui-v4-interactions.md)、[下一阶段架构](next-stage-architecture.md)、[V3 审查记录](../outputs/ui/meshport-ui-v3-review.md)、[图片生成提示词](../outputs/ui/meshport-ui-v4-prompts.md)。
## 1–4:主页面
概览、代理、组网、设置。组合模式分别显示两侧状态;代理模式只控制普通互联网流量;统计区分链路测量与路由估算。
![主页面:概览、代理、组网、设置](../outputs/ui/meshport-ui-v4-main.png)
## 5–8:代理配置
导入代理配置、订阅管理、代理节点详情、分流规则。订阅是节点来源;选中、检测可用和正在运行是不同状态。普通导入只提取支持的节点,不覆盖受管理的路由和 DNS。
![代理配置:导入、订阅、节点详情、分流规则](../outputs/ui/meshport-ui-v4-proxy.png)
## 9–12:组网配置
基础配置、连接与打洞、高级配置、线路策略。参数按 SDK 能力开放,未支持项禁用;配置保存与运行生效分开,候选中继不表示强制中继。
![组网配置:基础、打洞、高级、线路策略](../outputs/ui/meshport-ui-v4-network-config.png)
## 13–16:节点与路由
节点详情、自动接入子网、子网详情、网络诊断。公告子网区分学习与实际生效,接入方式决定状态文案。同 CIDR 多发布者合并展示;列表顶部数字为状态统计,不是筛选标签。
![节点与路由:节点详情、公告子网、子网详情、诊断](../outputs/ui/meshport-ui-v4-network-details.png)
## 17–20:应用设置
DNS 设置、默认配置、启动与后台、运行日志。DNS 定义域名范围、服务器、出口与失败策略;启动、恢复功能选择和自动连接分别控制;日志始终脱敏。
![应用设置:DNS、默认配置、启动后台、日志](../outputs/ui/meshport-ui-v4-settings.png)
## 21–24:引导与编辑
首次使用、添加代理节点、编辑订阅、编辑分流规则。首次使用按所选功能要求配置,进入首页不隐式连接;节点字段按协议变化,保存和测试草稿分别执行。
![引导与编辑:首次使用、代理节点、订阅、规则](../outputs/ui/meshport-ui-v4-editors.png)
## 公共状态与确认
等待 VPN 授权、导入失败、保存后重连、订阅更新导致当前节点失效。它们是当前流程中的状态或确认视图,不是额外导航页面。
![公共状态:授权、失败、重连、节点失效](../outputs/ui/meshport-ui-v4-states.png)
## 实现约束
- 统一运行功能排列:仅组网 / 仅代理 / 代理+组网。生成图中个别控件排列、图标、换行以实际组件统一。
- 只有所选能力全部就绪才显示全部可用;权限未完成、没有节点、部分失败均有独立状态。
- 配置区分草稿、持久化配置和运行快照;重建网络入口前提示现有连接可能中断。
- 有效组网目标优先,故障或撤销时不静默交给互联网代理;具体保护、撤销和本地冲突处理见交互规则。
- 尚未实现的功能按平台和 SDK 能力禁用,不能接受配置后忽略。
完整的 24 页修正对应关系和后续功能验收条件见 [V4 交互说明](../outputs/ui/meshport-ui-v4-interactions.md)。
当前客户端已接入主要页面,实际能力与禁用项见 [界面实现清单](ui-implementation.md)。原型图片仍为目标视觉设计,不代表全部未来功能已经完成。
+36
View File
@@ -0,0 +1,36 @@
# 移动端与桌面客户端界面实现
更新:2026-10-10。沿用 V4 的四个主导航,以下是代码中的实际页面,不是设计图上的示例数据。Flutter 同时供 macOS 与 Android 使用;视觉效果仍需设备与不同屏幕尺寸的人工验收。
| 页码 | 页面 | 入口与已接入功能 |
| --- | --- | --- |
| 1 | 概览 | 主导航;连接、分功能状态、实际节点 RTT 和流量 |
| 2 | 代理 | 主导航;功能、入口、模式、草稿节点与运行出口 |
| 3 | 组网 | 主导航;实际节点、配置与诊断入口 |
| 4 | 设置 | 主导航;DNS、默认配置、后台、日志、引导与关于 |
| 5 | 导入代理配置 | 代理;文本解析、预览、确认、失败保留输入 |
| 6 | 订阅管理 | 代理;HTTPS 更新、删除与来源管理 |
| 7 | 代理节点详情 | 点击节点;参数与认证隐藏,手动编辑/订阅复制 |
| 8 | 分流规则 | 代理;顺序、编辑、删除、默认动作,组网优先固定 |
| 9 | 基础配置 | 组网;网络名称、密钥、IP/DHCP、初始节点、运行入口 |
| 10 | 连接与打洞 | 组网;协议、监听、P2P、UDP/TCP/对称 NAT 打洞、STUN |
| 11 | 高级配置 | 组网;私有模式、惰性 P2P、强制 P2P、外部中继限制 |
| 12 | 线路策略 | 组网;优化模式、优势阈值、观察/冷却时间、候选节点 |
| 13 | 节点详情 | 点击组网节点;路由、链路 RTT/估算、直连可用性与流量 |
| 14 | 自动接入子网 | 组网;公告合并、接受/安装/失效保护状态,无手动列表 |
| 15 | 子网详情 | 点击子网;发布者、下一跳、接入状态与拒绝原因边界 |
| 16 | 网络诊断 | 组网或设置;SDK 实际 TCP/UDP 测试 |
| 17 | DNS 设置 | 设置;启动/代理 DNS、组网后缀 DNS、FakeIP 与排除项 |
| 18 | 默认配置 | 设置;配置优先级、恢复内置草稿,需确认 |
| 19 | 启动与后台 | 设置;说明已保存配置自动回填、平台后台限制 |
| 20 | 运行日志 | 设置;会话内事件、复制与清空,凭据脱敏 |
| 21 | 首次使用 | 设置中的使用引导;介绍三种功能与入口,不自动连接 |
| 22 | 添加代理节点 | 代理;六种协议表单、TLS/Reality、传输、草稿连通检测 |
| 23 | 编辑订阅 | 订阅管理;名称、URL、保存与更新分离 |
| 24 | 编辑分流规则 | 分流规则;域名/后缀/CIDR、动作和输入检查 |
表单保存只修改配置草稿;运行期间应用配置会确认重连,现有连接可能中断。表单未保存退出有确认。HTTP 检测耗时不等于网络 RTT;组网延迟注明来源,控制流量和应用流量不混称。
扫码、文件选择导入、自动订阅更新、规则集和应用启动自动连接已实现;macOS 13+ 登录启动已接入系统状态与授权入口,Android 不接入开机广播。详见 [高级客户端功能](advanced-client-features.md)。自动选出口按用户要求不实现。引导可从设置进入,尚无首次启动强制流程。关于页与公共授权/错误/重连确认不是额外导航项。
实现主要文件:`configuration_pages.dart`、`detail_pages.dart`、`proxy_source_pages.dart`、`proxy_node_editor.dart`、`proxy_panel.dart`、`lab_screen.dart`。原型图见 [UI 设计](ui-design.md),平台和验证范围见 [客户端运行控制](client-runtime.md)。
+17
View File
@@ -0,0 +1,17 @@
Copyright (C) 2022 by nekohasekai <contact-sagernet@sekai.icu>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, no derivative work may use the name or imply association
with this application without prior consent.
+15
View File
@@ -0,0 +1,15 @@
# MeshPort sing-box 接入
固定依赖 sing-box 1.14.3。当前提供本机 SOCKS 入口、受管理的 IPv4 组网分流、MeshPort SOCKS 出口及启停控制;完整 APP/TUN、互联网代理配置与订阅尚未接入。
从项目根目录执行:
```sh
sh scripts/go-local.sh test -race ./...
sh scripts/build-singbox.sh
sh scripts/test-singbox-bridge.sh
```
Go API:bridge.Engine.Start(context, bridge.Config)、Stop()、Snapshot()。调用方生成有效配置投影并拥有生命周期,停止或上下文取消后需调用 Stop。
完整接入方式、验证及限制见 [项目文档](../../docs/singbox-integration.md),上游许可证见 [LICENSE 副本](../../docs/upstream/sing-box-LICENSE)。
@@ -0,0 +1,228 @@
package bridge
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"encoding/pem"
D "github.com/miekg/dns"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common/json/badoption"
"io"
"net"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
box "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/option"
sjson "github.com/sagernet/sing/common/json"
M "github.com/sagernet/sing/common/metadata"
)
func TestEncryptedResolversAndRemoteRuleSetsDecode(t *testing.T) {
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "rule", DefaultAction: "direct", DirectDNS: "https://dns.example/dns-query", ProxyDNS: "tls://dns.example:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12346}, RuleSets: []RuleSet{{Tag: "private-sites", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", UpdateHours: 6, DownloadDetour: "direct"}}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
ctx := registryContext(context.Background())
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
instance, err := box.New(box.Options{Context: ctx, Options: options})
if err != nil {
t.Fatal(err)
}
defer instance.Close()
var result map[string]any
json.Unmarshal(data, &result)
servers := result["dns"].(map[string]any)["servers"].([]any)
if len(servers) != 3 || servers[1].(map[string]any)["type"] != "https" || servers[2].(map[string]any)["detour"] != "proxy" {
t.Fatal("encrypted DNS transport/detour missing")
}
for _, v := range []string{"http://dns.example/dns-query", "tls://dns.example/path", "https://user:pass@dns.example", "https://dns.example:0", "https://dns.example/dns-query?x=1"} {
c.DirectDNS = v
if _, err := c.managedJSON(); err == nil {
t.Fatalf("accepted invalid resolver %q", v)
}
}
}
func TestInlineRuleSetsRouteAndPreserveMeshPriority(t *testing.T) {
mesh, meshCount := socksEcho(t)
defer mesh.Close()
proxy, proxyCount := socksEcho(t)
defer proxy.Close()
listener, port := reservePort(t)
listener.Close()
c := Config{ListenPort: port, Feature: "combined", Mode: "rule", DefaultAction: "reject", MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.23.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "test", Enabled: true, Action: "proxy", Rules: []map[string]any{{"ip_cidr": []string{"10.23.0.0/24", "198.51.100.0/24"}}}}}}
engine := &Engine{}
if err := engine.Start(context.Background(), c); err != nil {
t.Fatalf("start: %v / %v", err, engine.startupCause)
}
defer engine.Close()
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
echoThrough(t, port, M.ParseSocksaddr("10.23.0.1:1234"), true)
if proxyCount.Load() != 1 || meshCount.Load() != 1 {
t.Fatal("rule set overrode protected mesh precedence")
}
}
func TestDoHAndDoTExchangeWithCertificateVerification(t *testing.T) {
answer := func(r *D.Msg) *D.Msg {
m := new(D.Msg)
m.SetReply(r)
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
return m
}
var count atomic.Int32
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var data []byte
var err error
if r.Method == "POST" {
data, err = io.ReadAll(io.LimitReader(r.Body, 65536))
} else {
data, err = base64.RawURLEncoding.DecodeString(r.URL.Query().Get("dns"))
}
request := new(D.Msg)
if err != nil || request.Unpack(data) != nil {
w.WriteHeader(400)
return
}
count.Add(1)
reply, _ := answer(request).Pack()
w.Header().Set("Content-Type", "application/dns-message")
w.Write(reply)
}))
defer server.Close()
listener, err := tls.Listen("tcp4", "127.0.0.1:0", &tls.Config{Certificates: server.TLS.Certificates, MinVersion: tls.VersionTLS12})
if err != nil {
t.Fatal(err)
}
dnsServer := &D.Server{Listener: listener, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { count.Add(1); w.WriteMsg(answer(r)) })}
go dnsServer.ActivateAndServe()
defer dnsServer.Shutdown()
certificate := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))
for _, url := range []string{server.URL + "/dns-query", "tls://" + listener.Addr().String()} {
t.Run(url, func(t *testing.T) {
upstream, proxyCount := socksEcho(t)
defer upstream.Close()
socket, port := reservePort(t)
socket.Close()
c := Config{ListenPort: port, Feature: "proxy", Mode: "global", DirectDNS: url, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
ctx := registryContext(context.Background())
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
// A test-only trust root is installed in this isolated box, never the OS.
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{certificate}}
instance, err := box.New(box.Options{Context: ctx, Options: opts})
if err != nil {
t.Fatal(err)
}
defer instance.Close()
if err = instance.Start(); err != nil {
t.Fatal(err)
}
before := count.Load()
echoThrough(t, port, M.ParseSocksaddr("encrypted.example.test:1234"), true)
if count.Load() <= before || proxyCount.Load() != 1 {
t.Fatal("encrypted DNS path not used")
}
})
}
}
func TestRemoteRuleSetRefreshKeepsLastGoodRulesOnFailure(t *testing.T) {
var stage atomic.Int32
var requests atomic.Int32
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
if stage.Load() == 2 {
w.WriteHeader(503)
return
}
prefix := "198.51.100.0/24"
if stage.Load() == 1 {
prefix = "203.0.113.0/24"
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"version": 3, "rules": []any{map[string]any{"ip_cidr": []string{prefix}}}})
}))
defer server.Close()
upstream, _ := socksEcho(t)
defer upstream.Close()
socket, port := reservePort(t)
socket.Close()
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: server.URL + "/rules.json", Format: "source", Action: "proxy", UpdateHours: 1}}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
ctx := registryContext(context.Background())
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))}}
opts.Route.RuleSet[0].RemoteOptions.UpdateInterval = badoption.Duration(100 * time.Millisecond)
instance, err := box.New(box.Options{Context: ctx, Options: opts})
if err != nil {
t.Fatal(err)
}
defer instance.Close()
if err = instance.Start(); err != nil {
t.Fatal(err)
}
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
stage.Store(1)
set, ok := instance.Router().RuleSet("remote")
if !ok {
t.Fatal("remote set missing")
}
deadline := time.Now().Add(3 * time.Second)
for !set.Match(&adapter.InboundContext{Destination: M.ParseSocksaddr("203.0.113.1:1234")}) {
if time.Now().After(deadline) {
t.Fatal("remote rules did not refresh")
}
time.Sleep(20 * time.Millisecond)
}
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), false)
stage.Store(2)
before := requests.Load()
deadline = time.Now().Add(3 * time.Second)
for requests.Load() <= before {
if time.Now().After(deadline) {
t.Fatal("failed refresh not attempted")
}
time.Sleep(20 * time.Millisecond)
}
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
}
func TestDirectModePausesProxyDNSAndRemoteRuleSets(t *testing.T) {
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "direct", ProxyDNS: "tls://dns.example", RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", DownloadDetour: "proxy"}}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
var result map[string]any
json.Unmarshal(data, &result)
if _, ok := result["route"].(map[string]any)["rule_set"]; ok {
t.Fatal("direct mode still loads rule sets")
}
if len(result["dns"].(map[string]any)["servers"].([]any)) != 1 {
t.Fatal("direct mode still depends on proxy DNS")
}
}
+166
View File
@@ -0,0 +1,166 @@
package bridge
import (
"context"
"encoding/json"
D "github.com/miekg/dns"
box "github.com/sagernet/sing-box"
M "github.com/sagernet/sing/common/metadata"
"net"
"testing"
"time"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
"github.com/sagernet/sing-box/option"
sjson "github.com/sagernet/sing/common/json"
)
func TestBypassChinaPresetAndGlobalIsolation(t *testing.T) {
for _, fake := range []bool{false, true} {
c := Config{ListenPort: 12345, Feature: "combined", Mode: "bypass_cn", FakeIP: fake,
MeshSOCKS: "127.0.0.1:12346", MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"},
DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12347},
Rules: []Rule{{Type: "ip_cidr", Value: "0.0.0.0/0", Action: "reject"}},
RuleSets: []RuleSet{{Tag: "custom", Enabled: true, Action: "reject", Rules: []map[string]any{{"ip_cidr": []string{"0.0.0.0/0"}}}}}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
if _, err = sjson.UnmarshalExtendedContext[option.Options](registryContext(context.Background()), data); err != nil {
t.Fatal(err)
}
var result map[string]any
json.Unmarshal(data, &result)
route := result["route"].(map[string]any)
if route["final"] != "proxy" {
t.Fatal("preset did not force proxy fallback")
}
sets := route["rule_set"].([]any)
set := sets[0].(map[string]any)
if len(sets) != 1 || set["tag"] != "meshport-geoip-cn" || set["format"] != "binary" || set["download_detour"] != "proxy" || set["update_interval"] != "24h" {
t.Fatal("managed GeoIP update missing")
}
rules := route["rules"].([]any)
// DNS hijack/real-IP resolution precede mesh, withdrawn-prefix protection,
// ordinary private addresses and finally the China IP rule.
if len(rules) != 6 || rules[1].(map[string]any)["action"] != "resolve" || rules[2].(map[string]any)["outbound"] != "meshport" || rules[3].(map[string]any)["action"] != "reject" || rules[4].(map[string]any)["ip_is_private"] != true || rules[5].(map[string]any)["outbound"] != "direct" {
t.Fatal("GeoIP or mesh priority broken")
}
if len(c.Rules) != 1 || c.RuleSets[0].Tag != "custom" {
t.Fatal("preset modified saved custom rules")
}
c.Mode = "global"
data, err = c.managedJSON()
if err != nil {
t.Fatal(err)
}
json.Unmarshal(data, &result)
route = result["route"].(map[string]any)
if _, ok := route["rule_set"]; ok {
t.Fatal("global mode still loads GeoIP")
}
if len(route["rules"].([]any)) != 4 || route["final"] != "proxy" {
t.Fatal("global mode contains ordinary bypass rules")
}
c.Mode = "bypass_cn"
c.Proxy = nil
if _, err = c.managedJSON(); err == nil {
t.Fatal("preset accepted missing proxy node")
}
c.Feature = "mesh"
c.MeshDNS = nil
if _, err = c.managedJSON(); fake && err == nil {
t.Fatal("mesh-only accepted FakeIP")
} else if !fake && err != nil {
t.Fatal(err)
}
}
}
// Use documentation IPs and isolated SOCKS counters in place of physical
// exits, so real-IP/FakeIP policy is exercised without public connections.
func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
for _, fake := range []bool{false, true} {
direct, dc := socksEcho(t)
defer direct.Close()
proxy, pc := socksEcho(t)
defer proxy.Close()
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
m := new(D.Msg)
m.SetReply(r)
ip := "203.0.113.7"
if r.Question[0].Name == "china.test." {
ip = "198.51.100.7"
}
if r.Question[0].Qtype == D.TypeA {
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP(ip)}}
}
w.WriteMsg(m)
})}
go server.ActivateAndServe()
defer server.Shutdown()
listener, port := reservePort(t)
listener.Close()
c := Config{ListenPort: port, Feature: "proxy", Mode: "bypass_cn", FakeIP: fake, DNS: socket.LocalAddr().String(), Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
var generated map[string]any
json.Unmarshal(data, &generated)
route := generated["route"].(map[string]any)
route["rule_set"] = []any{map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}}
outbounds := generated["outbounds"].([]any)
outbounds[0] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
data, _ = json.Marshal(generated)
ctx := registryContext(context.Background())
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
instance, err := box.New(box.Options{Context: ctx, Options: options})
if err != nil {
t.Fatal(err)
}
if err = instance.Start(); err != nil {
t.Fatal(err)
}
for _, domain := range []string{"china.test", "foreign.test"} {
target := domain
if fake {
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
if err != nil {
t.Fatal(err)
}
conn.SetDeadline(time.Now().Add(3 * time.Second))
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
if err != nil {
t.Fatal(err)
}
dnsConn := &D.Conn{Conn: conn}
msg := new(D.Msg)
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
if err = dnsConn.WriteMsg(msg); err != nil {
t.Fatal(err)
}
answer, err := dnsConn.ReadMsg()
conn.Close()
if err != nil || len(answer.Answer) != 1 {
t.Fatalf("FakeIP answer: %v / %v", answer, err)
}
target = answer.Answer[0].(*D.A).A.String()
}
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), true)
}
if dc.Load() != 1 || pc.Load() != 1 {
t.Fatalf("fake=%v direct=%d proxy=%d", fake, dc.Load(), pc.Load())
}
instance.Close()
}
}
+585
View File
@@ -0,0 +1,585 @@
package bridge
import (
"encoding/json"
"errors"
"fmt"
"net/netip"
"net/url"
"os"
"runtime"
"sort"
"strings"
)
// Only node fields may be imported. Route, DNS and TUN ownership remain managed.
type Rule struct {
Type string `json:"type"`
Value string `json:"value"`
Action string `json:"action"`
}
type MeshDNS struct {
Suffix string `json:"suffix"`
Server string `json:"server"`
}
type TunConfig struct {
FD int `json:"fd"`
Name string `json:"name"`
Interface string `json:"physical_interface"`
Index int `json:"physical_index"`
}
type RuleSet struct {
Tag string `json:"tag"`
Enabled bool `json:"enabled"`
URL string `json:"url,omitempty"`
Format string `json:"format,omitempty"`
Rules []map[string]any `json:"rules,omitempty"`
Action string `json:"action"`
DownloadDetour string `json:"download_detour,omitempty"`
UpdateHours int `json:"update_hours,omitempty"`
}
type Config struct {
DNSProtection bool `json:"dns_protection,omitempty"`
RuleSets []RuleSet `json:"rule_sets,omitempty"`
DirectDNS string `json:"direct_dns_server,omitempty"`
ListenPort uint16 `json:"listen_port"`
MeshSOCKS string `json:"mesh_socks"`
MeshCIDRs []string `json:"mesh_cidrs"`
ProtectedCIDRs []string `json:"protected_cidrs,omitempty"`
Feature string `json:"feature,omitempty"`
Mode string `json:"mode,omitempty"`
Proxy map[string]any `json:"proxy,omitempty"`
Rules []Rule `json:"rules,omitempty"`
DefaultAction string `json:"default_action,omitempty"`
DNS string `json:"dns_server,omitempty"`
ProxyDNS string `json:"proxy_dns_server,omitempty"`
MeshDNS []MeshDNS `json:"mesh_dns,omitempty"`
FakeIP bool `json:"fakeip,omitempty"`
FakeIPExclude []string `json:"fakeip_exclude,omitempty"`
DesktopTun bool `json:"desktop_tun,omitempty"`
PhysicalInterface string `json:"physical_interface,omitempty"`
Tun *TunConfig `json:"tun,omitempty"`
}
// Diagnostics are restricted to the privileged, mesh-only local fixture. They
// cannot enable logging of a user's ordinary proxy nodes or network traffic.
func (c Config) selfTestTrace() bool {
if os.Getenv("MESHPORT_SELF_TEST_TRACE") != "1" || os.Geteuid() != 0 ||
!c.DesktopTun || c.Feature != "mesh" || c.Proxy != nil || len(c.MeshCIDRs) == 0 {
return false
}
fixture := netip.MustParsePrefix("10.253.88.0/24")
for _, value := range append(append([]string{}, c.MeshCIDRs...), c.ProtectedCIDRs...) {
prefix, err := netip.ParsePrefix(value)
if err != nil || prefix.Bits() < fixture.Bits() || !fixture.Contains(prefix.Addr()) {
return false
}
}
return true
}
func prefixes(values []string) ([]string, error) {
if len(values) > 128 {
return nil, errors.New("too many mesh prefixes")
}
set := map[string]bool{}
for _, v := range values {
p, e := netip.ParsePrefix(v)
if e != nil || !p.Addr().Is4() || p.Bits() < 16 || !p.Addr().IsPrivate() {
return nil, errors.New("invalid or unsupported mesh prefix")
}
set[p.Masked().String()] = true
}
result := make([]string, 0, len(set))
for p := range set {
result = append(result, p)
}
sort.Strings(result)
return result, nil
}
func domain(v string) bool {
if len(v) > 253 || v == "" || strings.ContainsAny(v, " /:@*\r\n") {
return false
}
for _, label := range strings.Split(v, ".") {
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for _, c := range label {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
return false
}
}
}
return true
}
func proxyNode(node map[string]any) (map[string]any, error) {
kind, _ := node["type"].(string)
fields := map[string]string{"socks": "version,username,password", "http": "username,password,tls", "shadowsocks": "method,password", "vmess": "uuid,security,alter_id,tls,transport", "vless": "uuid,flow,tls,transport", "trojan": "password,tls,transport"}
extra, ok := fields[kind]
if !ok {
return nil, errors.New("unsupported proxy protocol")
}
allowed := ",type,server,server_port," + extra + ","
result := map[string]any{"tag": "proxy"}
for key, value := range node {
if !strings.Contains(allowed, ","+key+",") {
return nil, errors.New("unsupported proxy node field")
}
result[key] = value
}
host, ok := node["server"].(string)
if !ok {
return nil, errors.New("proxy server required")
}
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
return nil, errors.New("invalid proxy server")
}
raw, _ := json.Marshal(node["server_port"])
var port uint16
if json.Unmarshal(raw, &port) != nil || port == 0 {
return nil, errors.New("invalid proxy port")
}
// Nested transport/TLS options are validated by the fixed upstream registry;
// they cannot supply route, DNS, dialer or arbitrary outbound configuration.
if tls, ok := node["tls"].(map[string]any); ok {
for k := range tls {
if !strings.Contains(",enabled,server_name,alpn,reality,utls,", ","+k+",") {
return nil, errors.New("unsupported TLS option")
}
}
}
if tr, ok := node["transport"].(map[string]any); ok {
for k := range tr {
if !strings.Contains(",type,path,headers,service_name,host,", ","+k+",") {
return nil, errors.New("unsupported transport option")
}
}
}
return result, nil
}
func dnsAddress(value string) (string, uint16, error) {
if ip, e := netip.ParseAddr(value); e == nil {
return ip.String(), 53, nil
}
if addr, e := netip.ParseAddrPort(value); e == nil && addr.Port() > 0 {
return addr.Addr().String(), addr.Port(), nil
}
return "", 0, errors.New("DNS server must be an IP with optional port")
}
// Encrypted resolver hostnames use the independent IP bootstrap resolver.
func resolver(value, tag, detour string) (map[string]any, error) {
result := map[string]any{"tag": tag}
if !strings.Contains(value, "://") {
host, port, err := dnsAddress(value)
if err != nil {
return nil, err
}
result["type"], result["server"], result["server_port"] = "udp", host, port
} else {
u, err := url.Parse(value)
if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Scheme != "https" && u.Scheme != "tls") {
return nil, errors.New("invalid encrypted DNS URL")
}
host := u.Hostname()
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
return nil, errors.New("invalid DNS host")
}
port := uint16(443)
kind := "https"
if u.Scheme == "tls" {
port, kind = 853, "tls"
if u.Path != "" && u.Path != "/" {
return nil, errors.New("DoT does not accept a path")
}
}
if u.Port() != "" {
if _, err := fmt.Sscanf(u.Port(), "%d", &port); err != nil || port == 0 {
return nil, errors.New("invalid DNS port")
}
}
result["type"], result["server"], result["server_port"] = kind, host, port
result["tls"] = map[string]any{"enabled": true, "server_name": host}
if _, err := netip.ParseAddr(host); err != nil {
result["domain_resolver"] = map[string]any{"server": "bootstrap"}
}
if kind == "https" {
path := u.EscapedPath()
if path == "" {
path = "/dns-query"
}
result["path"] = path
}
}
if detour != "" {
result["detour"] = detour
}
return result, nil
}
func (c Config) managedJSON() ([]byte, error) {
return c.managedJSONForPlatform(runtime.GOOS)
}
func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
feature := c.Feature
if feature == "" {
feature = "mesh"
}
if feature != "mesh" && feature != "proxy" && feature != "combined" {
return nil, errors.New("invalid feature")
}
mesh := feature != "proxy"
internet := feature != "mesh"
mode := c.Mode
if mode == "" {
mode = "rule"
}
if mode != "rule" && mode != "global" && mode != "direct" && mode != "bypass_cn" {
return nil, errors.New("invalid proxy mode")
}
// A managed preset must not inherit custom rules that could override GeoIP.
bypassCN := mode == "bypass_cn"
if bypassCN {
mode = "rule"
c.DefaultAction = "proxy"
c.Rules = nil
c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true,
URL: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
Format: "binary", Action: "direct", DownloadDetour: "proxy", UpdateHours: 24}}
}
active, err := prefixes(c.MeshCIDRs)
if err != nil {
return nil, err
}
protected, err := prefixes(c.ProtectedCIDRs)
if err != nil {
return nil, err
}
if c.ListenPort == 0 {
return nil, errors.New("listen port required")
}
outbounds := []any{}
if mesh {
endpoint, e := netip.ParseAddrPort(c.MeshSOCKS)
if e != nil || !endpoint.Addr().Is4() || !endpoint.Addr().IsLoopback() || endpoint.Port() == 0 {
return nil, errors.New("mesh SOCKS must be an IPv4 loopback endpoint with a port")
}
if len(active) == 0 && len(protected) == 0 {
return nil, errors.New("effective mesh prefixes required")
}
meshOutbound := map[string]any{"type": "socks", "tag": "meshport", "server": endpoint.Addr().String(), "server_port": endpoint.Port(), "version": "5", "udp_over_tcp": false}
// The Rust bridge is local. The internet default_interface must not
// bind this loopback connection to a physical network adapter.
if c.DesktopTun {
meshOutbound["bind_interface"] = "lo0"
}
outbounds = append(outbounds, meshOutbound)
}
if internet {
outbounds = append(outbounds, map[string]any{"type": "direct", "tag": "direct"})
if c.Proxy != nil {
node, e := proxyNode(c.Proxy)
if e != nil {
return nil, e
}
// Only the proxy endpoint may bootstrap outside the proxy.
node["domain_resolver"] = map[string]any{"server": "bootstrap"}
outbounds = append(outbounds, node)
}
}
action := c.DefaultAction
if action == "" {
action = "proxy"
}
if action != "proxy" && action != "direct" && action != "reject" {
return nil, errors.New("invalid default action")
}
if internet && mode == "global" {
action = "proxy"
}
if internet && mode == "direct" {
action = "direct"
}
routeRules := []any{}
dns := map[string]any{}
defaultResolver := "bootstrap"
if internet {
server := c.DNS
if server == "" {
server = "1.1.1.1"
}
server, dnsPort, e := dnsAddress(server)
if e != nil {
return nil, e
}
dnsServers := []any{map[string]any{"type": "udp", "tag": "bootstrap", "server": server, "server_port": dnsPort}}
dnsFinal := "bootstrap"
if c.DirectDNS != "" {
server, e := resolver(c.DirectDNS, "direct-dns", "")
if e != nil {
return nil, e
}
dnsServers = append(dnsServers, server)
dnsFinal = "direct-dns"
}
if c.DNSProtection && mode != "direct" {
if c.Proxy == nil {
return nil, errors.New("DNS protection requires a selected proxy node; use direct mode for direct-only traffic")
}
if c.ProxyDNS == "" {
return nil, errors.New("DNS protection requires an explicitly configured proxy DNS server")
}
}
if c.ProxyDNS != "" && mode != "direct" {
if c.Proxy == nil {
return nil, errors.New("proxy DNS requires proxy node")
}
server, e := resolver(c.ProxyDNS, "proxy-dns", "proxy")
if e != nil {
return nil, e
}
dnsServers = append(dnsServers, server)
if mode != "direct" {
dnsFinal = "proxy-dns"
}
}
dnsRules := []any{}
for i, m := range c.MeshDNS {
ip, e := netip.ParseAddr(m.Server)
activeDNS, knownDNS := false, false
for _, v := range active {
if netip.MustParsePrefix(v).Contains(ip) {
activeDNS = true
}
}
for _, v := range protected {
if netip.MustParsePrefix(v).Contains(ip) {
knownDNS = true
}
}
if !mesh || !domain(m.Suffix) || e != nil || !(activeDNS || knownDNS) {
return nil, errors.New("mesh DNS requires a known mesh server and valid suffix")
}
if !activeDNS {
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "reject"})
continue
}
tag := "mesh-dns-" + strings.Repeat("x", i+1)
dnsServers = append(dnsServers, map[string]any{"type": "udp", "tag": tag, "server": m.Server, "detour": "meshport"})
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "route", "server": tag})
}
if c.FakeIP {
if len(c.FakeIPExclude) > 128 {
return nil, errors.New("too many FakeIP exclusions")
}
excluded := []string{"localhost", "local", "lan"}
for _, v := range c.FakeIPExclude {
if !domain(v) {
return nil, errors.New("invalid FakeIP exclusion")
}
excluded = append(excluded, v)
}
dnsRules = append(dnsRules, map[string]any{"domain_suffix": excluded, "action": "route", "server": dnsFinal})
dnsServers = append(dnsServers, map[string]any{"type": "fakeip", "tag": "fakeip", "inet4_range": "198.18.0.0/15", "inet6_range": "fc00::/18"})
dnsRules = append(dnsRules, map[string]any{"query_type": []string{"A", "AAAA"}, "action": "route", "server": "fakeip"})
}
defaultResolver = dnsFinal
dns = map[string]any{"servers": dnsServers, "rules": dnsRules, "final": dnsFinal, "strategy": "ipv4_only"}
routeRules = append(routeRules, map[string]any{"port": 53, "action": "hijack-dns"}, map[string]any{"action": "resolve", "strategy": "ipv4_only"})
} else {
routeRules = append(routeRules, map[string]any{"domain_regex": []string{".+"}, "action": "reject"})
}
if mesh && internet {
for _, rule := range c.MeshDNS {
routeRules = append(routeRules, map[string]any{"domain_suffix": []string{rule.Suffix}, "action": "route", "outbound": "meshport"})
}
}
if mesh && len(active) > 0 {
routeRules = append(routeRules, map[string]any{"ip_cidr": active, "action": "route", "outbound": "meshport"})
}
if mesh && len(protected) > 0 {
routeRules = append(routeRules, map[string]any{"ip_cidr": protected, "action": "reject"})
}
if internet && bypassCN {
routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"})
}
usedProxy := internet && action == "proxy"
if internet && mode == "rule" {
if len(c.Rules) > 256 {
return nil, errors.New("too many rules")
}
for _, r := range c.Rules {
item := map[string]any{}
switch r.Type {
case "domain", "domain_suffix":
if !domain(r.Value) {
return nil, errors.New("invalid rule domain")
}
item[r.Type] = []string{r.Value}
case "ip_cidr":
p, e := netip.ParsePrefix(r.Value)
if e != nil {
return nil, errors.New("invalid rule CIDR")
}
item[r.Type] = []string{p.Masked().String()}
default:
return nil, errors.New("unsupported rule type")
}
switch r.Action {
case "reject":
item["action"] = "reject"
case "direct", "proxy":
item["action"] = "route"
item["outbound"] = r.Action
if r.Action == "proxy" {
usedProxy = true
}
default:
return nil, errors.New("invalid rule action")
}
routeRules = append(routeRules, item)
}
}
ruleSets := []any{}
if len(c.RuleSets) > 32 {
return nil, errors.New("too many rule sets")
}
tags := map[string]bool{}
for _, set := range c.RuleSets {
if !set.Enabled || !internet || mode != "rule" {
continue
}
if !domain(set.Tag) || tags[set.Tag] {
return nil, errors.New("invalid or duplicate rule set tag")
}
tags[set.Tag] = true
if set.Action != "proxy" && set.Action != "direct" && set.Action != "reject" {
return nil, errors.New("invalid rule set action")
}
item := map[string]any{"tag": set.Tag}
if set.URL != "" {
u, err := url.Parse(set.URL)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || len(set.Rules) != 0 {
return nil, errors.New("invalid remote rule set URL")
}
if set.Format != "source" && set.Format != "binary" {
return nil, errors.New("invalid rule set format")
}
hours := set.UpdateHours
if hours == 0 {
hours = 24
}
if hours < 1 || hours > 168 {
return nil, errors.New("invalid rule set interval")
}
detour := set.DownloadDetour
if detour == "" {
detour = "direct"
}
if detour != "proxy" && detour != "direct" {
return nil, errors.New("invalid rule set download detour")
}
if detour == "proxy" && c.Proxy == nil {
return nil, errors.New("rule set download requires proxy")
}
item["type"], item["format"], item["url"] = "remote", set.Format, set.URL
item["update_interval"], item["download_detour"] = fmt.Sprintf("%dh", hours), detour
} else {
if len(set.Rules) == 0 || len(set.Rules) > 256 {
return nil, errors.New("invalid inline rule set")
}
item["type"], item["rules"] = "inline", set.Rules
}
if internet && mode == "rule" {
ruleSets = append(ruleSets, item)
match := map[string]any{"rule_set": []string{set.Tag}, "action": "route", "outbound": set.Action}
if set.Action == "reject" {
delete(match, "outbound")
match["action"] = "reject"
}
if set.Action == "proxy" {
usedProxy = true
}
routeRules = append(routeRules, match)
}
}
if usedProxy && c.Proxy == nil {
return nil, errors.New("selected proxy node required")
}
final := "meshport"
if internet && action != "reject" {
final = action
} else {
routeRules = append(routeRules, map[string]any{"action": "reject"})
if internet {
final = "direct"
}
}
if c.FakeIP && !internet {
return nil, errors.New("FakeIP requires ordinary proxy feature")
}
if internet && final == "proxy" && (bypassCN || mode == "global") && c.preferVideoTCPOn(platform) {
// Keep mesh, private, GeoIP and explicit routes ahead of this policy.
// Detect QUIC first: other UDP/443 traffic must remain usable.
routeRules = append(routeRules,
map[string]any{"network": "udp", "port": 443, "action": "sniff", "sniffer": []string{"quic"}},
map[string]any{"network": "udp", "port": 443, "protocol": "quic", "domain_suffix": []string{"googlevideo.com"}, "action": "reject"},
)
}
inbounds := []any{map[string]any{"type": "socks", "tag": "local", "listen": "127.0.0.1", "listen_port": c.ListenPort}}
route := map[string]any{"rules": routeRules, "final": final}
if len(ruleSets) > 0 {
route["rule_set"] = ruleSets
}
if internet {
route["default_domain_resolver"] = map[string]any{"server": defaultResolver}
}
if c.DesktopTun {
if c.Tun != nil || c.PhysicalInterface == "" || strings.ContainsAny(c.PhysicalInterface, " /\\\t\r\n") {
return nil, errors.New("desktop TUN requires physical interface")
}
route["default_interface"] = c.PhysicalInterface
routes := []string{"0.0.0.0/1", "128.0.0.0/1", "::/1", "8000::/1"}
if !internet {
// Active prefixes also belong to the session's protection set.
// Duplicate routes make Darwin delete the same entry twice on close,
// which breaks subsequent announcement-driven engine restarts.
captureSet := make(map[string]bool)
for _, prefix := range append(append([]string{}, active...), protected...) {
captureSet[prefix] = true
}
capture := make([]string, 0, len(captureSet))
for prefix := range captureSet {
capture = append(capture, prefix)
}
routes, err = prefixes(capture)
if err != nil {
return nil, err
}
}
dnsMode := "native"
addresses := []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}
if !internet {
dnsMode = "disabled"
// No accepted IPv6 mesh prefixes exist yet. Giving Darwin an IPv6
// address with auto_route and no IPv6 route_address captures its
// IPv6 default route, even in the subnet-only mode.
addresses = []string{"172.19.0.1/30"}
}
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "address": addresses, "mtu": 1280, "auto_route": true, "route_address": routes, "stack": "system", "dns_mode": dnsMode})
}
if c.Tun != nil {
if c.Tun.FD <= 0 || c.Tun.Name == "" || c.Tun.Interface == "" || c.Tun.Index <= 0 {
return nil, errors.New("valid platform TUN and physical network required")
}
route["auto_detect_interface"] = true
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "interface_name": c.Tun.Name, "address": []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}, "mtu": 1280, "auto_route": false, "stack": "system", "dns_mode": "disabled"})
}
result := map[string]any{"log": map[string]any{"disabled": !c.selfTestTrace(), "level": "debug"}, "inbounds": inbounds, "outbounds": outbounds, "route": route}
if internet {
result["dns"] = dns
}
return json.Marshal(result)
}
+39
View File
@@ -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)
}
@@ -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")
}
}
}
@@ -0,0 +1,141 @@
package bridge
import (
"context"
"crypto/tls"
"encoding/json"
"encoding/pem"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
"net"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
D "github.com/miekg/dns"
box "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/option"
sjson "github.com/sagernet/sing/common/json"
M "github.com/sagernet/sing/common/metadata"
)
func TestDNSProtectionRequiresExplicitResolverAndKeepsBootstrapNarrow(t *testing.T) {
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "global", DNSProtection: true, Proxy: map[string]any{"type": "socks", "server": "proxy.example", "server_port": 1080}}
if _, err := c.managedJSON(); err == nil {
t.Fatal("silently chose a DNS provider")
}
c.ProxyDNS = "tls://resolver.example"
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
var v map[string]any
json.Unmarshal(data, &v)
if v["dns"].(map[string]any)["final"] != "proxy-dns" || v["route"].(map[string]any)["default_domain_resolver"].(map[string]any)["server"] != "proxy-dns" {
t.Fatal("ordinary lookup escapes proxy DNS")
}
outbounds := v["outbounds"].([]any)
if outbounds[1].(map[string]any)["domain_resolver"].(map[string]any)["server"] != "bootstrap" {
t.Fatal("proxy endpoint resolution loops")
}
c.Mode = "direct"
c.Proxy = nil
c.ProxyDNS = ""
if _, err := c.managedJSON(); err != nil {
t.Fatal("direct mode required proxy DNS", err)
}
}
func TestDNSProtectionNoDirectFallbackOnProxyFailure(t *testing.T) {
// All addresses and trust are isolated test fixtures, not public DNS providers.
fixture := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer fixture.Close()
for _, fake := range []bool{false, true} {
for _, fail := range []bool{false, true} {
var proxiedQueries, bootQueries atomic.Int32
proxy, _ := socksFixture(t, func(conn net.Conn) {
if fail {
return
}
stream := tls.Server(conn, &tls.Config{Certificates: fixture.TLS.Certificates, MinVersion: tls.VersionTLS12})
dc := &D.Conn{Conn: stream}
for {
request, err := dc.ReadMsg()
if err != nil {
return
}
proxiedQueries.Add(1)
response := new(D.Msg)
response.SetReply(request)
response.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: request.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
if dc.WriteMsg(response) != nil {
return
}
}
})
defer proxy.Close()
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
bootstrap := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { bootQueries.Add(1); m := new(D.Msg); m.SetReply(r); w.WriteMsg(m) })}
go bootstrap.ActivateAndServe()
defer bootstrap.Shutdown()
l, port := reservePort(t)
l.Close()
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", DNS: socket.LocalAddr().String(), DNSProtection: true, FakeIP: fake,
ProxyDNS: "tls://127.0.0.1:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
ctx := registryContext(context.Background())
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.Certificate().Raw}))}}
instance, err := box.New(box.Options{Context: ctx, Options: opts})
if err != nil {
t.Fatal(err)
}
if err = instance.Start(); err != nil {
t.Fatal(err)
}
target := "private-query.test"
if fake {
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
if err != nil {
t.Fatal(err)
}
conn.SetDeadline(time.Now().Add(3 * time.Second))
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
if err != nil {
t.Fatal(err)
}
dc := &D.Conn{Conn: conn}
msg := new(D.Msg)
msg.SetQuestion("private-query.test.", D.TypeA)
if err = dc.WriteMsg(msg); err != nil {
t.Fatal(err)
}
answer, err := dc.ReadMsg()
conn.Close()
if err != nil || len(answer.Answer) != 1 {
t.Fatalf("FakeIP query: %v / %v", answer, err)
}
target = answer.Answer[0].(*D.A).A.String()
}
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), false)
instance.Close()
if bootQueries.Load() != 0 {
t.Fatal("target query leaked to bootstrap DNS")
}
if !fail && proxiedQueries.Load() == 0 {
t.Fatal("proxy DNS wasn't used")
}
}
}
}
+248
View File
@@ -0,0 +1,248 @@
// Package bridge provides an explicitly managed sing-box lifecycle. Platform
// TUN integration and ordinary internet proxy profiles are separate milestones.
package bridge
import (
"context"
"errors"
"fmt"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common/control"
"github.com/sagernet/sing/service"
"net"
"os"
"path/filepath"
"runtime"
"sync"
"time"
box "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/adapter/certificate"
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
boxservice "github.com/sagernet/sing-box/adapter/service"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/dns/transport"
"github.com/sagernet/sing-box/dns/transport/fakeip"
"github.com/sagernet/sing-box/dns/transport/local"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/protocol/http"
"github.com/sagernet/sing-box/protocol/shadowsocks"
"github.com/sagernet/sing-box/protocol/trojan"
"github.com/sagernet/sing-box/protocol/tun"
"github.com/sagernet/sing-box/protocol/vless"
"github.com/sagernet/sing-box/protocol/vmess"
sjson "github.com/sagernet/sing/common/json"
)
func registryContext(ctx context.Context) context.Context {
in := inbound.NewRegistry()
registerTrackedInbound(in)
tun.RegisterInbound(in)
out := outbound.NewRegistry()
registerMeshOutbound(out)
shadowsocks.RegisterOutbound(out)
vmess.RegisterOutbound(out)
vless.RegisterOutbound(out)
trojan.RegisterOutbound(out)
http.RegisterOutbound(out)
direct.RegisterOutbound(out) // Required for sing-box's internal defaults.
dnsRegistry := dns.NewTransportRegistry()
local.RegisterTransport(dnsRegistry)
transport.RegisterUDP(dnsRegistry)
transport.RegisterHTTPS(dnsRegistry)
transport.RegisterTLS(dnsRegistry)
fakeip.RegisterTransport(dnsRegistry)
return box.Context(ctx, in, out, endpoint.NewRegistry(), dnsRegistry,
boxservice.NewRegistry(), certificate.NewRegistry())
}
type Snapshot struct {
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.
CacheRoot string
cacheDir string
Protect func(int) error
mu sync.Mutex
box *box.Box
state string
cancel context.CancelFunc
ctx context.Context
desktopTun bool
}
func (e *Engine) Snapshot() Snapshot {
e.mu.Lock()
defer e.mu.Unlock()
state := e.state
if state == "" {
state = "Stopped"
}
if state == "Running" && e.ctx.Err() != nil {
state = "Failed"
}
return Snapshot{State: state, Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()}
}
func (e *Engine) Start(parent context.Context, config Config) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.box != nil {
return errors.New("engine already started; stop before applying configuration")
}
if parent.Err() != nil {
return errors.New("engine context is canceled")
}
if config.DesktopTun && (runtime.GOOS != "darwin" || os.Geteuid() != 0) {
return errors.New("desktop TUN requires macOS privileged helper")
}
if config.DesktopTun {
attached, err := desktopTunAddressAttached()
if err != nil {
return errors.New("cannot inspect desktop TUN address")
}
if attached {
return errors.New("desktop TUN address already in use")
}
}
data, err := config.managedJSON()
if err != nil {
return err
}
e.selfTestTrace = config.selfTestTrace()
e.desktopTun = config.DesktopTun
e.state = "Starting"
ctx, cancel := context.WithCancel(parent)
ctx = registryContext(ctx)
if config.Tun != nil {
if e.Protect == nil {
cancel()
e.state = "Failed"
return errors.New("platform socket protection required")
}
physical := &control.Interface{Name: config.Tun.Interface, Index: config.Tun.Index, MTU: 1500, Flags: net.FlagUp}
ctx = service.ContextWith[adapter.PlatformInterface](ctx, &hostPlatform{config: *config.Tun, protect: e.Protect, monitor: &hostMonitor{physical: physical}})
}
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
cancel()
e.state = "Failed"
return startupFailure("decode_configuration", err)
}
if config.FakeIP || len(config.RuleSets) > 0 {
if e.cacheDir == "" {
e.cacheDir, err = os.MkdirTemp(e.CacheRoot, "meshport-fakeip-")
if err != nil {
cancel()
e.state = "Failed"
return errors.New("cannot create private DNS cache")
}
}
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 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 startupFailure("start_engine", err)
}
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
return nil
}
func (e *Engine) Stop() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.box == nil {
e.state = "Stopped"
return nil
}
e.state = "Stopping"
err := e.box.Close()
e.cancel()
e.box, e.cancel, e.ctx = nil, nil, nil
if e.desktopTun && err == nil {
// Darwin can retain the utun address until its last kernel reference
// drains. Reusing that address immediately can attach the new routes
// to the retiring interface and remove them when it finally disappears.
deadline := time.Now().Add(2 * time.Second)
for {
attached, inspectErr := desktopTunAddressAttached()
if inspectErr != nil {
err = inspectErr
break
}
if !attached {
break
}
if time.Now().After(deadline) {
err = errors.New("desktop TUN address did not detach")
break
}
time.Sleep(20 * time.Millisecond)
}
}
if err != nil {
e.state = "Failed"
if e.selfTestTrace {
fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err)
}
return errors.New("proxy engine cleanup failed")
}
e.state = "Stopped"
return nil
}
func desktopTunAddressAttached() (bool, error) {
addresses, err := net.InterfaceAddrs()
if err != nil {
return false, err
}
for _, address := range addresses {
ip, _, err := net.ParseCIDR(address.String())
if err == nil && ip.Equal(net.ParseIP("172.19.0.1")) {
return true, nil
}
}
return false, nil
}
// Close releases the session's private cache only after the engine is stopped.
func (e *Engine) Close() error {
err := e.Stop()
e.mu.Lock()
defer e.mu.Unlock()
if e.cacheDir != "" {
removeErr := os.RemoveAll(e.cacheDir)
e.cacheDir = ""
if err == nil {
err = removeErr
}
}
return err
}
+149
View File
@@ -0,0 +1,149 @@
package bridge
import (
"context"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
"io"
"net"
"net/netip"
"strings"
"testing"
"time"
)
func reservePort(t *testing.T) (net.Listener, uint16) {
t.Helper()
l, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return l, uint16(l.Addr().(*net.TCPAddr).Port)
}
func TestUnconfiguredTargetsAndDomainsAreRejected(t *testing.T) {
bridgeListener, _ := reservePort(t)
defer bridgeListener.Close()
entry, port := reservePort(t)
entry.Close()
var engine Engine
if err := engine.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: bridgeListener.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
t.Fatal(err)
}
defer engine.Stop()
for _, destination := range []M.Socksaddr{
M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(bridgeListener.Addr().(*net.TCPAddr).Port)),
M.SocksaddrFrom(netip.MustParseAddr("10.78.0.1"), 1234),
M.ParseSocksaddr("must-not-resolve.invalid:1234"),
} {
conn, err := net.Dial("tcp4", entry.Addr().String())
if err != nil {
t.Fatal(err)
}
conn.SetDeadline(time.Now().Add(3 * time.Second))
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, destination, "", "")
conn.Close()
if err == nil {
t.Fatal("unconfigured target accepted:", destination)
}
if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
t.Fatal("rejection timed out:", destination)
}
}
bridgeListener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
if conn, err := bridgeListener.Accept(); err == nil {
conn.Close()
t.Fatal("rejected request reached mesh bridge")
}
}
func TestConfigurationRejectsUnsupportedEndpointsAndPrefixes(t *testing.T) {
base := Config{ListenPort: 1080, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.0/24"}}
for _, endpoint := range []string{"example.com:1080", "0.0.0.0:1080", "10.0.0.1:1080", "127.0.0.1:0", "[::1]:1080"} {
c := base
c.MeshSOCKS = endpoint
if _, err := c.managedJSON(); err == nil {
t.Errorf("accepted endpoint %s", endpoint)
}
}
for _, prefix := range []string{"0.0.0.0/0", "10.0.0.0/8", "1.1.1.0/24", "127.0.0.0/24", "fd00::/64", "invalid"} {
c := base
c.MeshCIDRs = []string{prefix}
if _, err := c.managedJSON(); err == nil {
t.Errorf("accepted prefix %s", prefix)
}
}
c := base
c.MeshCIDRs = nil
if _, err := c.managedJSON(); err == nil {
t.Error("accepted empty projection")
}
}
func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
occupied, port := reservePort(t)
defer occupied.Close()
c := Config{ListenPort: port, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.11/24", "10.77.0.0/24"}}
var engine Engine
if engine.Snapshot().State != "Stopped" {
t.Fatal("initial state")
}
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")
}
occupied.Close()
if err := engine.Start(context.Background(), c); err != nil {
t.Fatal(err)
}
defer engine.Stop()
if engine.Snapshot().State != "Running" {
t.Fatal("running state")
}
if engine.Start(context.Background(), c) == nil {
t.Fatal("duplicate start accepted")
}
conn, err := net.Dial("tcp4", occupied.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := conn.Write([]byte{5, 1, 0}); err != nil {
t.Fatal(err)
}
var reply [2]byte
if _, err := io.ReadFull(conn, reply[:]); err != nil {
t.Fatal(err)
}
if reply != [2]byte{5, 0} {
t.Fatal("unexpected negotiation", reply)
}
if err := engine.Stop(); err != nil {
t.Fatal(err)
}
if err := engine.Stop(); err != nil {
t.Fatal(err)
}
if engine.Snapshot().State != "Stopped" {
t.Fatal("stop state")
}
if n, err := conn.Read(reply[:]); n != 0 {
t.Fatal("active connection retained after stop")
} else if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
t.Fatal("active connection only closed by client timeout")
}
l, err := net.Listen("tcp4", occupied.Addr().String())
if err != nil {
t.Fatal("listener leaked:", err)
}
l.Close()
if err := engine.Start(context.Background(), c); err != nil {
t.Fatal("restart:", err)
}
}
+107
View File
@@ -0,0 +1,107 @@
package bridge
import (
"context"
"net"
"sync"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/common/listener"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/protocol/socks"
N "github.com/sagernet/sing/common/network"
)
// Track accepted controls before SOCKS negotiation, including connections that
// have not entered sing-box's routed connection manager yet.
type connectionSet struct {
mu sync.Mutex
closed bool
connections map[*trackedConnection]struct{}
}
type trackedConnection struct {
net.Conn
owner *connectionSet
}
func (c *trackedConnection) Close() error {
err := c.Conn.Close()
c.owner.mu.Lock()
delete(c.owner.connections, c)
c.owner.mu.Unlock()
return err
}
func (s *connectionSet) track(conn net.Conn) *trackedConnection {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || len(s.connections) >= 128 {
return nil
}
c := &trackedConnection{Conn: conn, owner: s}
s.connections[c] = struct{}{}
return c
}
func (s *connectionSet) closeAll() {
s.mu.Lock()
s.closed = true
connections := make([]*trackedConnection, 0, len(s.connections))
for conn := range s.connections {
connections = append(connections, conn)
}
s.mu.Unlock()
for _, conn := range connections {
_ = conn.Close()
}
}
type trackedInbound struct {
*socks.Inbound
listener *listener.Listener
connections connectionSet
}
func registerTrackedInbound(registry *inbound.Registry) {
inbound.Register[option.SocksInboundOptions](registry, C.TypeSOCKS,
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SocksInboundOptions) (adapter.Inbound, error) {
delegate, err := socks.NewInbound(ctx, router, logger, tag, options)
if err != nil {
return nil, err
}
tracked := &trackedInbound{Inbound: delegate.(*socks.Inbound), connections: connectionSet{connections: make(map[*trackedConnection]struct{})}}
// The delegate only handles the protocol. This listener owns the
// accepted TCP controls; its options also constrain UDP association
// allocation through the delegate's original packet-listener helper.
tracked.listener = listener.New(listener.Options{Context: ctx, Logger: logger, Network: []string{N.NetworkTCP}, Listen: options.ListenOptions, ConnectionHandler: tracked})
return tracked, nil
})
}
func (h *trackedInbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
if stage != adapter.StartStateStart {
return nil
}
if err := h.listener.Start(); err != nil {
return err
}
scope.Add(func() error {
err := h.listener.Close()
h.connections.closeAll()
return err
})
return nil
}
func (h *trackedInbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
tracked := h.connections.track(conn)
if tracked == nil {
_ = conn.Close()
return
}
h.Inbound.NewConnection(ctx, tracked, metadata, onClose)
}
+122
View File
@@ -0,0 +1,122 @@
package bridge
import (
"context"
"errors"
"net"
"net/netip"
"time"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/common/dialer"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
boxsocks "github.com/sagernet/sing-box/protocol/socks"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/varbin"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
)
type meshOutbound struct {
adapter.Outbound
dialer N.Dialer
server M.Socksaddr
logger log.ContextLogger
}
func registerMeshOutbound(registry *outbound.Registry) {
outbound.Register[option.SOCKSOutboundOptions](registry, C.TypeSOCKS,
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SOCKSOutboundOptions) (adapter.Outbound, error) {
delegate, err := boxsocks.NewOutbound(ctx, router, logger, tag, options)
if err != nil {
return nil, err
}
if tag != "meshport" {
return delegate, nil
}
d, err := dialer.New(ctx, options.DialerOptions, false)
if err != nil {
return nil, err
}
return &meshOutbound{Outbound: delegate, dialer: d, server: options.ServerOptions.Build(), logger: logger}, nil
})
}
func (o *meshOutbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
if N.NetworkName(network) == N.NetworkUDP {
return o.associate(ctx, destination)
}
return o.Outbound.DialContext(ctx, network, destination)
}
func (o *meshOutbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
return o.associate(ctx, destination)
}
// RFC 1928 UDP ASSOCIATE names the client's expected UDP endpoint, not the
// remote destination. That endpoint is not yet allocated, so request 0.0.0.0:0.
// Keep this normalization in our adapter instead of weakening the Rust bridge's
// source IP/port isolation to accept another client's private-address heuristic.
func (o *meshOutbound) associate(ctx context.Context, destination M.Socksaddr) (packet *socks.AssociatePacketConn, err error) {
control, err := o.dialer.DialContext(ctx, N.NetworkTCP, o.server)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
_ = control.Close()
}
}()
stopCancel := context.AfterFunc(ctx, func() { _ = control.Close() })
defer func() {
if !stopCancel() {
if packet != nil {
_ = packet.Close()
packet = nil
}
err = ctx.Err()
}
}()
deadline := time.Now().Add(5 * time.Second)
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
deadline = d
}
if err = control.SetDeadline(deadline); err != nil {
return nil, err
}
reader := varbin.StubReader(control)
if err = socks5.WriteAuthRequest(control, socks5.AuthRequest{Methods: []byte{socks5.AuthTypeNotRequired}}); err != nil {
return nil, err
}
auth, err := socks5.ReadAuthResponse(reader)
if err != nil {
return nil, err
}
if auth.Method != socks5.AuthTypeNotRequired {
return nil, errors.New("mesh bridge rejected authentication method")
}
if err = socks5.WriteRequest(control, socks5.Request{Command: socks5.CommandUDPAssociate, Destination: M.SocksaddrFrom(netip.IPv4Unspecified(), 0)}); err != nil {
return nil, err
}
o.logger.DebugContext(ctx, "mesh UDP association requested")
response, err := socks5.ReadResponse(reader)
if err != nil {
return nil, err
}
if response.ReplyCode != socks5.ReplyCodeSuccess || !response.Bind.Addr.Is4() || response.Bind.Addr != o.server.Addr || response.Bind.Port == 0 {
return nil, errors.New("mesh bridge rejected UDP association or returned an invalid endpoint")
}
if err = control.SetDeadline(time.Time{}); err != nil {
return nil, err
}
udp, err := o.dialer.DialContext(ctx, N.NetworkUDP, response.Bind)
if err != nil {
return nil, err
}
o.logger.DebugContext(ctx, "mesh UDP association ready: ", udp.LocalAddr(), " -> ", response.Bind)
return socks.NewAssociatePacketConn(udp, destination, control), nil
}
+133
View File
@@ -0,0 +1,133 @@
package bridge
import (
"context"
"errors"
"net"
"net/netip"
"sync"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-tun"
"github.com/sagernet/sing/common/control"
"github.com/sagernet/sing/common/logger"
"github.com/sagernet/sing/common/x/list"
"golang.org/x/sys/unix"
)
// This adapter owns a duplicate of the host's TUN. It never creates OS routes.
// All optional platform capabilities explicitly remain unavailable.
type hostPlatform struct {
config TunConfig
protect func(int) error
monitor *hostMonitor
}
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 {
return errors.New("socket protector missing")
}
return p.protect(fd)
}
func (p *hostPlatform) UsePlatformInterface() bool { return true }
func (p *hostPlatform) OpenInterface(o *tun.Options, _ option.TunPlatformOptions) (tun.Tun, error) {
fd, e := unix.Dup(p.config.FD)
if e != nil {
return nil, e
}
unix.CloseOnExec(fd)
o.FileDescriptor = fd
o.Name = p.config.Name
p.monitor.RegisterMyInterface(o.Name)
result, e := tun.New(*o)
if e != nil {
unix.Close(fd)
}
return result, e
}
func (*hostPlatform) ProcessPlatformOptions(option.TunPlatformOptions) error { return nil }
func (*hostPlatform) UsePlatformDefaultInterfaceMonitor() bool { return true }
func (p *hostPlatform) CreateDefaultInterfaceMonitor(logger.Logger) tun.DefaultInterfaceMonitor {
return p.monitor
}
func (*hostPlatform) UsePlatformNetworkInterfaces() bool { return true }
func (p *hostPlatform) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
return []adapter.NetworkInterface{{Interface: *p.monitor.physical}, {Interface: control.Interface{Name: "lo", Index: 1, MTU: 65536, Flags: net.FlagUp | net.FlagLoopback, Addresses: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/8")}}}}, nil
}
func (*hostPlatform) UnderNetworkExtension() bool { return false }
func (*hostPlatform) NetworkExtensionIncludeAllNetworks() bool { return false }
func (*hostPlatform) ClearDNSCache() {}
func (*hostPlatform) RequestPermissionForWIFIState() error { return errors.New("unsupported") }
func (*hostPlatform) ReadWIFIState(context.Context) adapter.WIFIState { return adapter.WIFIState{} }
func (*hostPlatform) UsePlatformConnectionOwnerFinder() bool { return false }
func (*hostPlatform) FindConnectionOwner(*adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
return nil, errors.New("unsupported")
}
func (*hostPlatform) UsePlatformWIFIMonitor() bool { return false }
func (*hostPlatform) UsePlatformNotification() bool { return false }
func (*hostPlatform) SendNotification(*adapter.Notification) error { return errors.New("unsupported") }
func (*hostPlatform) CancelNotification(string, int32) error { return errors.New("unsupported") }
func (*hostPlatform) MyInterfaceAddress() []netip.Addr {
return []netip.Addr{netip.MustParseAddr("172.19.0.1"), netip.MustParseAddr("fdfe:dcba:9876::1")}
}
func (*hostPlatform) UsePlatformNeighborResolver() bool { return false }
func (*hostPlatform) StartNeighborMonitor(adapter.NeighborUpdateListener) error {
return errors.New("unsupported")
}
func (*hostPlatform) CloseNeighborMonitor(adapter.NeighborUpdateListener) error { return nil }
func (*hostPlatform) UsePlatformShell() bool { return false }
func (*hostPlatform) CheckPlatformShell() error { return errors.New("unsupported") }
func (*hostPlatform) OpenShellSession(*adapter.PlatformUser, string, []string, string, int32, int32) (adapter.ShellSession, error) {
return nil, errors.New("unsupported")
}
func (*hostPlatform) LookupUser(string) (*adapter.PlatformUser, error) {
return nil, errors.New("unsupported")
}
func (*hostPlatform) LookupSFTPServer() (string, error) { return "", errors.New("unsupported") }
func (*hostPlatform) ReadSystemSSHHostKey() ([]byte, error) { return nil, errors.New("unsupported") }
func (*hostPlatform) TailscaleHostname() string { return "" }
func (*hostPlatform) UsePlatformBridge() bool { return false }
func (*hostPlatform) CreateBridge(adapter.BridgeOptions) (adapter.BridgeSession, error) {
return nil, errors.New("unsupported")
}
type hostMonitor struct {
physical *control.Interface
mu sync.Mutex
names []string
callbacks list.List[tun.DefaultInterfaceUpdateCallback]
}
func (*hostMonitor) Start() error { return nil }
func (*hostMonitor) Close() error { return nil }
func (m *hostMonitor) DefaultInterface() *control.Interface { return m.physical }
func (*hostMonitor) OverrideAndroidVPN() bool { return true }
func (*hostMonitor) AndroidVPNEnabled() bool { return false }
func (m *hostMonitor) RegisterCallback(c tun.DefaultInterfaceUpdateCallback) *list.Element[tun.DefaultInterfaceUpdateCallback] {
m.mu.Lock()
defer m.mu.Unlock()
return m.callbacks.PushBack(c)
}
func (m *hostMonitor) UnregisterCallback(e *list.Element[tun.DefaultInterfaceUpdateCallback]) {
m.mu.Lock()
defer m.mu.Unlock()
m.callbacks.Remove(e)
}
func (m *hostMonitor) RegisterMyInterface(n string) {
m.mu.Lock()
defer m.mu.Unlock()
m.names = append(m.names, n)
}
func (m *hostMonitor) MyInterfaces() []string {
m.mu.Lock()
defer m.mu.Unlock()
return append([]string{}, m.names...)
}
+103
View File
@@ -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")
}
}
+292
View File
@@ -0,0 +1,292 @@
package bridge
import (
"context"
"encoding/json"
"io"
"net"
"net/netip"
"sync/atomic"
"testing"
"time"
D "github.com/miekg/dns"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
)
// A real SOCKS5 fixture echoes through the selected outlet; a request counter
// distinguishes route selection from mere successful engine startup.
func socksEcho(t *testing.T) (net.Listener, *atomic.Int32) {
return socksFixture(t, func(c net.Conn) { io.Copy(c, c) })
}
func socksFixture(t *testing.T, handler func(net.Conn)) (net.Listener, *atomic.Int32) {
l, _ := reservePort(t)
counter := &atomic.Int32{}
go func() {
for {
c, e := l.Accept()
if e != nil {
return
}
go func() {
defer c.Close()
c.SetDeadline(time.Now().Add(5 * time.Second))
var greeting [2]byte
if _, e := io.ReadFull(c, greeting[:]); e != nil {
return
}
methods := make([]byte, int(greeting[1]))
if _, e := io.ReadFull(c, methods); e != nil {
return
}
c.Write([]byte{5, 0})
var req [4]byte
if _, e := io.ReadFull(c, req[:]); e != nil {
return
}
n := 4
if req[3] == 3 {
var size [1]byte
if _, e := io.ReadFull(c, size[:]); e != nil {
return
}
n = int(size[0])
} else if req[3] == 4 {
n = 16
}
if _, e := io.ReadFull(c, make([]byte, n+2)); e != nil {
return
}
counter.Add(1)
c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 1})
handler(c)
}()
}
}()
return l, counter
}
func echoThrough(t *testing.T, port uint16, target M.Socksaddr, want bool) {
t.Helper()
c, e := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
if e != nil {
t.Fatal(e)
}
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
_, e = socks.ClientHandshake5(c, socks5.CommandConnect, target, "", "")
if !want {
if e == nil {
c.Write([]byte("x"))
var b [1]byte
n, readErr := c.Read(b[:])
if n != 0 || readErr == nil {
t.Fatal("protected target passed")
}
if ne, ok := readErr.(net.Error); ok && ne.Timeout() {
t.Fatal("rejection timed out")
}
}
return
}
if e != nil {
t.Fatal(e)
}
c.Write([]byte("route-echo"))
result := make([]byte, 10)
if _, e := io.ReadFull(c, result); e != nil {
t.Fatal(e)
}
if string(result) != "route-echo" {
t.Fatal(string(result))
}
}
func jsonNumber(n int) string { raw, _ := json.Marshal(n); return string(raw) }
func TestModesAndMeshPriority(t *testing.T) {
proxy, count := socksEcho(t)
defer proxy.Close()
mesh, meshCount := socksEcho(t)
defer mesh.Close()
direct, _ := reservePort(t)
defer direct.Close()
go func() {
for {
c, e := direct.Accept()
if e != nil {
return
}
go func() { defer c.Close(); io.Copy(c, c) }()
}
}()
for _, mode := range []string{"rule", "global", "direct"} {
t.Run(mode, func(t *testing.T) {
entry, port := reservePort(t)
entry.Close()
var engine Engine
config := Config{ListenPort: port, Feature: "combined", Mode: mode, MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"}, Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "ip_cidr", Value: "127.0.0.0/8", Action: "direct"}}}
if e := engine.Start(context.Background(), config); e != nil {
t.Fatalf("%v: %v", e, engine.startupCause)
}
defer engine.Stop()
before := count.Load()
beforeMesh := meshCount.Load()
echoThrough(t, port, M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(direct.Addr().(*net.TCPAddr).Port)), true)
expected := int32(0)
if mode == "global" {
expected = 1
}
if count.Load()-before != expected {
t.Fatal("wrong internet outlet")
}
echoThrough(t, port, M.ParseSocksaddr("10.77.0.2:1234"), true)
if meshCount.Load()-beforeMesh != 1 {
t.Fatal("mesh priority lost")
}
before = count.Load()
echoThrough(t, port, M.ParseSocksaddr("10.88.0.2:1234"), false)
if count.Load() != before {
t.Fatal("protected destination leaked to proxy")
}
})
}
}
func TestDNSAndDomainRule(t *testing.T) {
upstream, count := socksEcho(t)
defer upstream.Close()
dnsSock, e := net.ListenPacket("udp4", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
m := new(D.Msg)
m.SetReply(r)
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
w.WriteMsg(m)
})}
go dnsServer.ActivateAndServe()
defer dnsServer.Shutdown()
entry, port := reservePort(t)
entry.Close()
var engine Engine
config := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DNS: dnsSock.LocalAddr().String(), DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "domain_suffix", Value: "example.test", Action: "proxy"}}}
if e := engine.Start(context.Background(), config); e != nil {
t.Fatalf("%v: %v", e, engine.startupCause)
}
defer engine.Stop()
echoThrough(t, port, M.ParseSocksaddr("sub.example.test:1234"), true)
if count.Load() != 1 {
t.Fatal("domain rule not selected")
}
echoThrough(t, port, M.ParseSocksaddr("blocked.invalid:1234"), false)
if count.Load() != 1 {
t.Fatal("default reject bypassed")
}
}
func TestImportedNodeCannotReplaceManagedDialer(t *testing.T) {
for _, field := range []string{"detour", "bind_interface", "routing_mark", "domain_resolver", "tag", "route"} {
node := map[string]any{"type": "socks", "server": "example.test", "server_port": 1080, field: "unmanaged"}
if _, e := proxyNode(node); e == nil {
t.Fatal("injected field accepted", field)
}
}
var engine Engine
config := Config{ListenPort: 10818, Feature: "proxy", Mode: "direct", Tun: &TunConfig{FD: 123, Name: "tun0", Interface: "eth0", Index: 2}}
if e := engine.Start(context.Background(), config); e == nil {
engine.Stop()
t.Fatal("unprotected platform TUN accepted")
}
}
func TestWithdrawnMeshDNSIsRejectedWithoutFallback(t *testing.T) {
upstream, count := socksEcho(t)
defer upstream.Close()
entry, port := reservePort(t)
entry.Close()
var engine Engine
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", ProtectedCIDRs: []string{"10.77.0.0/24"}, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
if e := engine.Start(context.Background(), config); e != nil {
t.Fatalf("%v: %v", e, engine.startupCause)
}
defer engine.Stop()
echoThrough(t, port, M.ParseSocksaddr("secret.mesh.test:1234"), false)
if count.Load() != 0 {
t.Fatal("mesh DNS failed open to proxy")
}
}
func TestFakeIPMappingAndMeshExclusion(t *testing.T) {
dnsSock, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
m := new(D.Msg)
m.SetReply(r)
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
w.WriteMsg(m)
})}
go dnsServer.ActivateAndServe()
defer dnsServer.Shutdown()
proxy, count := socksEcho(t)
defer proxy.Close()
listener, port := reservePort(t)
listener.Close()
engine := &Engine{}
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", DNS: dnsSock.LocalAddr().String(), ProtectedCIDRs: []string{"10.77.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, FakeIP: true, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}}
if e := engine.Start(context.Background(), config); e != nil {
t.Fatalf("%v: %v", e, engine.startupCause)
}
defer engine.Close()
query := func(domain string) *D.Msg {
t.Helper()
c, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
if err != nil {
t.Fatal(err)
}
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
if err != nil {
t.Fatal(err)
}
conn := &D.Conn{Conn: c}
msg := new(D.Msg)
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
if e := conn.WriteMsg(msg); e != nil {
t.Fatal(e)
}
reply, e := conn.ReadMsg()
if e != nil {
t.Fatal(e)
}
return reply
}
reply := query("public.test")
if len(reply.Answer) != 1 {
t.Fatalf("missing FakeIP answer: %v", reply)
}
address, ok := reply.Answer[0].(*D.A)
if !ok || !netip.MustParsePrefix("198.18.0.0/15").Contains(netip.MustParseAddr(address.A.String())) {
t.Fatal("not a FakeIP answer")
}
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
if count.Load() != 1 {
t.Fatal("FakeIP connection did not use selected proxy")
}
if err := engine.Stop(); err != nil {
t.Fatal(err)
}
if err := engine.Start(context.Background(), config); err != nil {
t.Fatal(err)
}
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
if count.Load() != 2 {
t.Fatal("FakeIP mapping lost across managed rebuild")
}
// Known withdrawn mesh domains must reject before the generic FakeIP rule.
reply = query("host.mesh.test")
if len(reply.Answer) != 0 || reply.Rcode == D.RcodeSuccess {
t.Fatal("withdrawn mesh domain leaked to FakeIP")
}
}
+72
View File
@@ -0,0 +1,72 @@
package bridge
import (
"context"
"errors"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
"io"
"net"
"net/http"
"strconv"
"time"
)
type ProbeResult struct {
Method string `json:"method"`
ElapsedMS float64 `json:"elapsed_ms"`
StatusCode int `json:"status_code"`
}
// A draft probe owns an isolated loopback engine and never installs a TUN or
// changes the running instance. The public ABI fixes its HTTPS test destination.
func ProbeNode(parent context.Context, node map[string]any, dnsServer string, target string) (ProbeResult, error) {
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
defer cancel()
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
return ProbeResult{}, errors.New("cannot reserve probe port")
}
port := uint16(listener.Addr().(*net.TCPAddr).Port)
listener.Close()
var engine Engine
defer engine.Close()
if err := engine.Start(ctx, Config{ListenPort: port, Feature: "proxy", Mode: "global", Proxy: node, DNS: dnsServer}); err != nil {
return ProbeResult{}, errors.New("invalid draft proxy configuration")
}
transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
c, err := (&net.Dialer{}).DialContext(ctx, "tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
if err != nil {
return nil, err
}
c.SetDeadline(time.Now().Add(8 * time.Second))
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr(address), "", "")
if err != nil {
c.Close()
return nil, err
}
return c, nil
}, TLSHandshakeTimeout: 8 * time.Second, DisableKeepAlives: true}
defer transport.CloseIdleConnections()
client := http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return ProbeResult{}, errors.New("invalid probe target")
}
started := time.Now()
response, err := client.Do(request)
if err != nil {
return ProbeResult{}, errors.New("HTTPS connectivity check failed")
}
defer response.Body.Close()
_, err = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
if err != nil {
return ProbeResult{}, errors.New("connectivity response failed")
}
result := ProbeResult{Method: "HTTP connectivity", ElapsedMS: float64(time.Since(started).Microseconds()) / 1000, StatusCode: response.StatusCode}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return result, errors.New("connectivity target returned a non-success status")
}
return result, nil
}
+48
View File
@@ -0,0 +1,48 @@
package bridge
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"testing"
)
func TestDraftHTTPProbeIsIsolated(t *testing.T) {
proxy, count := socksFixture(t, func(c net.Conn) {
request, err := http.ReadRequest(bufio.NewReader(c))
if err != nil {
t.Error(err)
return
}
if request.Host != "203.0.113.7" || request.Method != "GET" {
t.Error("unexpected draft request")
}
fmt.Fprint(c, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
})
defer proxy.Close()
l, port := reservePort(t)
l.Close()
var running Engine
if err := running.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: "127.0.0.1:9", MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
t.Fatal(err)
}
defer running.Close()
node := map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}
result, err := ProbeNode(context.Background(), node, "", "http://203.0.113.7/probe")
if err != nil {
t.Fatal(err)
}
if result.StatusCode != 204 || result.ElapsedMS <= 0 || count.Load() != 1 {
t.Fatal("probe did not use selected draft node")
}
if running.Snapshot().State != "Running" {
t.Fatal("probe changed running engine")
}
canceled, cancel := context.WithCancel(context.Background())
cancel()
if _, err := ProbeNode(canceled, node, "", "http://203.0.113.7/probe"); err == nil {
t.Fatal("canceled probe accepted")
}
}
+75
View File
@@ -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...)
}
@@ -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")
}
}
+85
View File
@@ -0,0 +1,85 @@
package bridge
import (
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
)
// Isolate managed SOCKS forwarding from WAN, DNS, TLS and privileged TUN.
// This is not a benchmark of the system VPN or a user's real proxy node.
func BenchmarkManagedDownload(b *testing.B) {
const size = 32 * 1024 * 1024
chunk := make([]byte, 64*1024)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for remaining := size; remaining > 0; remaining -= len(chunk) {
if _, err := w.Write(chunk); err != nil {
return
}
}
}))
defer server.Close()
for _, managed := range []bool{false, true} {
name := "direct"
transport := &http.Transport{DisableCompression: true}
var engine Engine
if managed {
name = "managed_socks"
reserved, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
b.Fatal(err)
}
port := uint16(reserved.Addr().(*net.TCPAddr).Port)
entry := reserved.Addr().String()
reserved.Close()
if err = engine.Start(context.Background(), Config{Feature: "proxy", Mode: "direct", ListenPort: port}); err != nil {
b.Fatal(err)
}
transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
c, err := (&net.Dialer{}).DialContext(ctx, "tcp", entry)
if err != nil {
return nil, err
}
_ = c.SetDeadline(time.Now().Add(10 * time.Second))
if _, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr(address), "", ""); err != nil {
c.Close()
return nil, err
}
_ = c.SetDeadline(time.Time{})
return c, nil
}
}
b.Run(name, func(b *testing.B) {
client := &http.Client{Transport: transport, Timeout: 20 * time.Second}
b.SetBytes(size)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
r, err := client.Get(server.URL)
if err != nil {
b.Fatal(err)
}
n, err := io.Copy(io.Discard, r.Body)
r.Body.Close()
if err != nil {
b.Fatal(err)
}
if n != size {
b.Fatalf("short download: %d", n)
}
}
})
transport.CloseIdleConnections()
if managed {
_ = engine.Close()
}
}
}
+46
View File
@@ -0,0 +1,46 @@
package bridge
import (
"encoding/json"
"testing"
)
func TestDesktopTunCaptureRoutesDoNotDuplicateProtection(t *testing.T) {
data, err := (Config{ListenPort: 10818, Feature: "mesh", MeshSOCKS: "127.0.0.1:19001", MeshCIDRs: []string{"10.253.88.0/25"}, ProtectedCIDRs: []string{"10.253.88.0/25", "10.253.88.128/25"}, DesktopTun: true, PhysicalInterface: "en0"}).managedJSON()
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
t.Fatal(err)
}
inbounds := config["inbounds"].([]any)
addresses := inbounds[1].(map[string]any)["address"].([]any)
if len(addresses) != 1 || addresses[0] != "172.19.0.1/30" {
t.Fatalf("mesh-only TUN must not create implicit IPv6 default routes: %v", addresses)
}
routes := inbounds[1].(map[string]any)["route_address"].([]any)
if len(routes) != 2 || routes[0] != "10.253.88.0/25" || routes[1] != "10.253.88.128/25" {
t.Fatalf("unsafe capture routes: %v", routes)
}
}
func TestTraceCannotLogOrdinaryNetworkProfiles(t *testing.T) {
t.Setenv("MESHPORT_SELF_TEST_TRACE", "1")
fixture := Config{Feature: "mesh", DesktopTun: true, MeshCIDRs: []string{"10.253.88.0/25"}}
for _, change := range []func(*Config){
func(c *Config) { c.MeshCIDRs = []string{"192.168.20.0/24"} },
func(c *Config) { c.ProtectedCIDRs = []string{"192.168.21.0/24"} },
func(c *Config) { c.MeshCIDRs = []string{"10.253.0.0/16"} },
func(c *Config) { c.Feature = "combined" },
func(c *Config) { c.DesktopTun = false },
func(c *Config) { c.Proxy = map[string]any{"type": "socks"} },
func(c *Config) { c.MeshCIDRs = nil },
} {
config := fixture
change(&config)
if config.selfTestTrace() {
t.Fatal("self-test tracing accepted an ordinary network profile")
}
}
}

Some files were not shown because too many files have changed in this diff Show More