Improve VPN video routing, profile storage and authorization reuse

This commit is contained in:
shen
2026-10-13 00:34:16 -07:00
parent c94143dfae
commit f94dab0555
30 changed files with 1303 additions and 139 deletions
+6 -2
View File
@@ -56,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)。
@@ -71,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` 安装包;下次构建需要重新生成缓存。
@@ -53,4 +53,7 @@ flutter {
}
// Offline QR decoding and an in-app camera capture Activity.
dependencies { implementation("com.journeyapps:zxing-android-embedded:4.3.0") }
dependencies {
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
testImplementation("junit:junit:4.13.2")
}
@@ -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.
}
}
@@ -76,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"
@@ -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())
}
}
+102 -17
View File
@@ -22,6 +22,11 @@ class LabScreen extends StatefulWidget {
class _LabScreenState extends State<LabScreen> {
MeshPortClient? client, applicationClient, systemClient;
MacSystemVpnSession? macVpnSession;
bool legacyMigrationPending = false;
String localProfilePath = Platform.isAndroid
? 'APP 私有目录/MeshPort/'
: '~/Library/Application Support/MeshPort/';
String runtimeMode = Platform.isMacOS || Platform.isAndroid
? 'unified_vpn'
: 'application';
@@ -83,8 +88,7 @@ class _LabScreenState extends State<LabScreen> {
proxySession?.state == 'Running' ||
proxySession?.state == 'Partial';
bool get profileSupported => Platform.isMacOS || Platform.isAndroid;
String get profileStorage =>
Platform.isAndroid ? 'Android 安全存储' : 'macOS 钥匙串';
String get profileStorage => '本地配置目录 $localProfilePath';
@override
void initState() {
super.initState();
@@ -182,6 +186,7 @@ class _LabScreenState extends State<LabScreen> {
singBoxEnabled = proxyProfile.proxyEnabled;
final diagnostics = await opened.enableDiagnostics();
log(diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器');
if (profileSupported) await checkLocalProfileMigration();
if (Platform.isAndroid) {
final snapshot = await androidVpnRequest({'op': 'status'});
final data = snapshot['data'] as Map?;
@@ -209,6 +214,7 @@ class _LabScreenState extends State<LabScreen> {
'startup_status',
);
if (preferences?['auto_connect'] == true &&
!legacyMigrationPending &&
!running &&
(restored ||
(singBoxEnabled && proxyProfile.feature == 'proxy'))) {
@@ -514,7 +520,11 @@ class _LabScreenState extends State<LabScreen> {
}
if (systemClient != null) {
try {
await systemClient!.close();
if (Platform.isMacOS && macVpnSession != null) {
await macVpnSession!.release(systemClient!);
} else {
await systemClient!.close();
}
} catch (_) {}
systemClient = null;
client = applicationClient;
@@ -549,18 +559,20 @@ class _LabScreenState extends State<LabScreen> {
},
request: androidVpnRequest,
)
: await openMacSystemVpn(
launch: (path, uid) async {
log('等待管理员授权以创建虚拟网卡');
await diagnosticStage(
'授权并启动 macOS VPN 辅助进程',
() => vpnChannel.invokeMethod<void>('launch', {
'socket': path,
'uid': uid,
}),
);
},
);
: await (macVpnSession ??= MacSystemVpnSession(
open: () => openMacSystemVpn(
launch: (path, uid) async {
log('等待管理员授权以创建虚拟网卡');
await diagnosticStage(
'授权并启动 macOS VPN 辅助进程',
() => vpnChannel.invokeMethod<void>('launch', {
'socket': path,
'uid': uid,
}),
);
},
),
)).acquire();
try {
await opened.enableDiagnostics();
if (unified) {
@@ -588,6 +600,51 @@ class _LabScreenState extends State<LabScreen> {
}
}
Future<void> checkLocalProfileMigration() async {
try {
final info = await vpnChannel.invokeMapMethod<String, dynamic>(
'profile_storage_status',
);
if (mounted) {
setState(() {
legacyMigrationPending = info?['migration_pending'] == true;
if (info?['path'] is String) {
localProfilePath = info!['path'] as String;
}
});
}
if (legacyMigrationPending) log('旧配置需要迁移,请在设置中点击“迁移旧配置”');
} catch (_) {
log('无法检查本地配置目录,请在设置中重试');
}
}
Future<void> migrateLegacyProfiles() async {
await vpnChannel.invokeMethod<void>('migrate_profiles');
final proxy = await vpnChannel.invokeMethod<String>('load_proxy_profile');
final network = (await vpnChannel.invokeMethod<String>(
'load_profile',
))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), '');
if (network != null) await loadForm(network);
if (proxy != null) {
final imported = ProxyProfile.fromJson(
jsonDecode(proxy) as Map<String, dynamic>,
);
if (imported.entry == 'system_vpn') imported.feature = 'mesh';
proxyProfile = imported;
savedProxyJson = jsonEncode(imported.toJson());
runtimeMode = imported.entry;
singBoxEnabled = imported.proxyEnabled;
}
if (network != null) {
savedConfig = network;
rememberConfig = true;
}
await checkLocalProfileMigration();
if (mounted) setState(() {});
log('旧配置已迁移,后续读取和保存使用本地文件');
}
Future<void> saveProfile(String config, {bool explicit = false}) async {
if ((!rememberConfig && !explicit) || !profileSupported) return;
try {
@@ -611,11 +668,17 @@ class _LabScreenState extends State<LabScreen> {
if (c == applicationClient && proxySession != null) {
await proxySession!.stop();
}
await c.stop();
if (Platform.isMacOS && c == systemClient && macVpnSession != null) {
await macVpnSession!.release(c);
} else {
await c.stop();
}
} finally {
if (systemClient != null) {
try {
await systemClient!.close();
if (!Platform.isMacOS || macVpnSession == null) {
await systemClient!.close();
}
} finally {
systemClient = null;
client = applicationClient;
@@ -750,6 +813,9 @@ class _LabScreenState extends State<LabScreen> {
cancel = true;
timer?.cancel();
subscriptionTimer?.cancel();
unawaited(
macVpnSession?.close().catchError((Object _) {}) ?? Future<void>.value(),
);
if (client != null) {
final active = client!,
application = applicationClient,
@@ -1247,6 +1313,25 @@ class _LabScreenState extends State<LabScreen> {
Widget settings() => Column(
children: [
panel('应用设置', [
if (profileSupported) ...[
ListTile(
title: const Text('配置保存位置'),
subtitle: Text(localProfilePath),
),
if (legacyMigrationPending)
ListTile(
title: const Text('迁移旧配置'),
subtitle: Text(
Platform.isMacOS
? '点击后可能需要钥匙串授权;迁移后使用本地文件。'
: '读取旧版保存的配置并迁移到本地文件。',
),
trailing: const Icon(Icons.chevron_right),
onTap: busy || running
? null
: () => perform((_) => migrateLegacyProfiles()),
),
],
ListTile(
title: const Text('DNS 设置'),
trailing: const Icon(Icons.chevron_right),
@@ -21,6 +21,7 @@
/* 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 */; };
@@ -62,6 +63,7 @@
/* 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; };
@@ -177,6 +179,7 @@
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
A137C030AA00000000000002 /* LocalProfileStore.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -420,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 */,
);
@@ -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
}
}
@@ -13,6 +13,8 @@ class MainFlutterWindow: NSWindow {
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.
@@ -33,40 +35,32 @@ class MainFlutterWindow: NSWindow {
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")
let isProxy = call.method.contains("_proxy_profile")
let profileQuery: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: isProxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile",
kSecAttrAccount as String: isProxy ? "last-proxy" : "last-network"
]
if profileMethod == "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)
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 profileMethod == "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 profileMethod == "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],
@@ -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 {
@@ -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({
+9 -5
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 设备运行尚未验证。
@@ -22,11 +22,11 @@ scripts/build-lab-android.sh --release
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
# 先在项目根目录启动本机夹具
@@ -62,6 +62,10 @@ adb -s DEVICE_SERIAL logcat -s MeshPortRuntime:I MeshPortVPN:I AndroidRuntime:E
自用配置文件为 `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 -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 的打包与实际互通尚待验证。
+13
View File
@@ -7,6 +7,7 @@ import (
"net/netip"
"net/url"
"os"
"runtime"
"sort"
"strings"
)
@@ -217,6 +218,10 @@ func resolver(value, tag, detour string) (map[string]any, error) {
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"
@@ -515,6 +520,14 @@ func (c Config) managedJSON() ([]byte, error) {
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 {
+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()
}
}
}
+18
View File
@@ -0,0 +1,18 @@
package bridge
// The measured macOS VLESS/Reality Vision path benefits from video TCP fallback.
// Share the narrowly scoped policy with Android's platform-owned TUN. Native
// UDP proxies, custom routing policies and unrelated QUIC remain unchanged.
func (c Config) preferVideoTCPOn(platform string) bool {
tun := (platform == "darwin" && c.DesktopTun) || (platform == "android" && c.Tun != nil)
if !tun || c.Proxy == nil ||
c.Proxy["type"] != "vless" || c.Proxy["flow"] != "xtls-rprx-vision" || c.Proxy["transport"] != nil {
return false
}
tls, ok := c.Proxy["tls"].(map[string]any)
if !ok || tls["enabled"] != true {
return false
}
reality, ok := tls["reality"].(map[string]any)
return ok && reality["enabled"] == true
}
+121
View File
@@ -0,0 +1,121 @@
package bridge
import (
"context"
"strings"
"testing"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
R "github.com/sagernet/sing-box/route/rule"
sjson "github.com/sagernet/sing/common/json"
M "github.com/sagernet/sing/common/metadata"
)
func videoConfig() Config {
return Config{ListenPort: 12345, Feature: "proxy", Mode: "global", DesktopTun: true, PhysicalInterface: "en0",
Proxy: map[string]any{"type": "vless", "server": "proxy.example", "server_port": 443,
"uuid": "00000000-0000-4000-8000-000000000001", "flow": "xtls-rprx-vision",
"tls": map[string]any{"enabled": true, "server_name": "example.com",
"reality": map[string]any{"enabled": true, "public_key": strings.Repeat("A", 43)}}}}
}
func TestVideoFallbackMatchesOnlyYouTubeQUIC(t *testing.T) {
for _, platform := range []string{"darwin", "android"} {
for _, mode := range []string{"global", "bypass_cn"} {
t.Run(platform+"/"+mode, func(t *testing.T) {
c := videoConfig()
c.Mode = mode
if platform == "android" {
c.DesktopTun = false
c.Tun = &TunConfig{FD: 42, Name: "tun0", Interface: "wlan0", Index: 1}
}
checkVideoRule(t, c, platform)
})
}
}
}
func checkVideoRule(t *testing.T, c Config, platform string) {
t.Helper()
data, err := c.managedJSONForPlatform(platform)
if err != nil {
t.Fatal(err)
}
ctx := registryContext(context.Background())
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
rules := opts.Route.Rules
if len(rules) < 2 || rules[len(rules)-2].DefaultOptions.Action != "sniff" {
t.Fatal("QUIC detection missing before fallback")
}
if _, err := R.NewRule(ctx, log.NewNOPFactory().Logger(), rules[len(rules)-2], true); err != nil {
t.Fatalf("QUIC sniffer unavailable: %v", err)
}
reject, err := R.NewRule(ctx, log.NewNOPFactory().Logger(), rules[len(rules)-1], true)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
domain, protocol, network string
port uint16
want bool
}{
{"rr3---cdn.googlevideo.com", "quic", "udp", 443, true},
{"googlevideo.com", "quic", "udp", 443, true},
{"other.example", "quic", "udp", 443, false},
{"evilgooglevideo.com", "quic", "udp", 443, false},
{"rr3---cdn.googlevideo.com", "stun", "udp", 443, false},
{"rr3---cdn.googlevideo.com", "", "udp", 443, false},
{"rr3---cdn.googlevideo.com", "tls", "tcp", 443, false},
{"rr3---cdn.googlevideo.com", "quic", "udp", 8443, false},
} {
m := adapter.InboundContext{Domain: tc.domain, Protocol: tc.protocol, Network: tc.network,
Destination: M.Socksaddr{Fqdn: tc.domain, Port: tc.port}}
if got := reject.Match(&m); got != tc.want {
t.Fatalf("%+v: match=%v", tc, got)
}
}
}
func TestVideoFallbackDoesNotChangeOtherTransportsOrModes(t *testing.T) {
for _, mutate := range []func(*Config){
func(c *Config) { c.DesktopTun = false },
func(c *Config) { c.Mode = "direct" },
func(c *Config) { c.Mode = "rule" },
func(c *Config) { c.Proxy["flow"] = "" },
func(c *Config) { c.Proxy["tls"].(map[string]any)["reality"].(map[string]any)["enabled"] = false },
} {
c := videoConfig()
mutate(&c)
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), `"sniffer"`) {
t.Fatal("fallback changed unrelated mode/transport")
}
}
}
func TestAndroidVideoPolicyRequiresPlatformTunAndVision(t *testing.T) {
c := videoConfig()
c.DesktopTun = false
if c.preferVideoTCPOn("android") {
t.Fatal("application-only proxy enabled TUN policy")
}
c.Tun = &TunConfig{FD: 42, Name: "tun0", Interface: "wlan0", Index: 1}
if !c.preferVideoTCPOn("android") {
t.Fatal("Android platform TUN missing video policy")
}
if c.preferVideoTCPOn("linux") || c.preferVideoTCPOn("darwin") {
t.Fatal("policy leaked to other platforms")
}
c.Proxy["flow"] = ""
if c.preferVideoTCPOn("android") {
t.Fatal("non-Vision transport changed")
}
}
@@ -0,0 +1,29 @@
# Android final package — 2026-10-13
## Synced behavior
- macOS's targeted video policy now also applies to Android's platform-owned TUN: raw VLESS/Reality Vision, global or bypass-CN mode, detected QUIC on UDP/443 for googlevideo.com/subdomains only. Existing mesh, private and GeoIP routes take precedence. Other QUIC domains, non-QUIC UDP/443, other transports and custom rule mode remain unchanged. No new manual network settings.
- Android profiles now use the application-private files directory, `files/MeshPort/proxy-profile.json` and `files/MeshPort/network-profile.toml`, with 0700/0600 permissions and atomic writes. Existing encrypted SharedPreferences are read with their original Android Keystore keys once for migration. No new key is generated when reading legacy data. Regular reads/writes use files; old encrypted data remains as a backup. Deletion records a migration tombstone to prevent resurrection. A failed migration remains pending without retrying at every launch; Settings provides explicit retry.
- Shared settings show the native storage path and migration status. Auto-connect waits if migration is pending. Android VPN authorization continues to use VpnService.prepare, which already skips the consent dialog while permission remains granted. macOS administrator helpers and menu bar behavior do not apply to Android.
## Validation
- Shared Go bridge suite, race tests and vet passed. Real sing-box rule matching and sniffer construction cover macOS and Android configurations in global/bypass-CN modes; Android policy requires a platform TUN.
- Android JVM storage tests: 4 passed, 0 failures/errors/skips. Covered migration, private permissions, restart, deletion, pending retry, corrupt files, oversized writes and symlink rejection. These use isolated host filesystem fixtures, not real phone data or real Android Keystore entries.
- Flutter suite passed (50 passed, 6 skipped); analyzer clean.
- Release APK signature v2 verified. Certificate SHA-256 matches the preceding debug APK: 3c116d75d22a71f1a32a443d524c6293965b29c1647a7ac1cd41fcf13a312ec8. Release currently uses the existing Android debug signing identity for compatible local upgrades, not a store distribution key.
- ZIP alignment for 16 KB pages and every packaged native ELF load-segment alignment verified. APK is AOT Release, contains both native cores and only arm64-v8a libraries.
- Bundled default configuration byte-matches the public template; no private template or debug kernel blob bundled. Archive integrity passed. Packaging restores the original source configuration afterward.
- Direct Gradle Release unit-test invocation initially failed because Flutter tests regenerated a registrant containing the dev-only integration_test plugin. Debug JVM unit tests passed, followed by a fresh normal Flutter Release build which regenerated the production registrant. The shipped APK comes from that final build.
No ADB device was connected. No phone installation, real VPN permission dialogue, actual migration with phone Keystore data, or Android YouTube speed measurement was performed. Previous macOS throughput results do not establish Android performance.
## Artifact
`outputs/android/MeshPort-0.1.0-1791874725-release.apk`
Version code: 1791874725; minimum Android API 26 (Android 8.0); ARM64; 56,536,849 bytes.
SHA-256: `25ad7a828305766c190ee6d6eefbcc8b42b3bc321c8af8efe42755f6853ab8db`.
Rebuild with `sh scripts/package-lab-android.sh`. Install over the prior MeshPort APK to retain legacy configuration for migration; do not uninstall first. No commits or pushes were performed.
@@ -0,0 +1,24 @@
# macOS authorization reuse — 2026-10-12
## Change
Previously disconnect closed the authenticated control socket and terminated the privileged helper. Every reconnect launched another helper using administrator authorization. The macOS UI now owns a `MacSystemVpnSession` for its lifetime: stop releases the VPN through the existing stop operation, but retains the authenticated IPC channel. While stopped, a 30-second status heartbeat keeps the existing helper watchdog satisfied. Reconnect checks the cached helper before reusing it. Transport failure closes it and requests fresh authorization; cancellation can be retried. App disposal closes the owned session, and process exit closes its socket, triggering the helper's existing network cleanup. No launch daemon is installed, credentials are not cached, and socket ownership checks remain in place. Android behavior is unchanged.
The package script now uses the unique available Apple Development identity when no explicit `MESHPORT_SIGNING_IDENTITY` is supplied; otherwise it uses the requested identity or falls back to ad-hoc signing. The new package has an Apple certificate-based designated requirement rather than a changing ad-hoc code hash. Existing Keychain entries protected by the old signature may still require one migration confirmation. Future updates must retain the same signing requirement to avoid renewed access confirmation.
## Checks
- Real Unix socket fixture: stop/start reuses the same client and invokes launch once; idle heartbeat works; final close removes private control directory.
- Dead helper replacement, cancelled authorization retry and close during pending authorization pass.
- Existing socket serialization/cleanup test passes.
- Flutter test suite and analyzer pass.
- Release build, deep/strict signature verification and ZIP integrity pass. Public bundled configuration verified.
- This change has not yet been tested against real macOS password dialogs on the user's VPN. Tests verify launch counts and IPC lifecycle without requesting root privileges.
## Package
`outputs/macos/MeshPort-0.1.0-1791871988-arm64-release.zip`
SHA-256: `833337e3636cdf9ee2d49fbbebb3d0bd133dd4e6097a40b989ce12e11102327a`.
Apple Silicon, macOS 12+, Apple Development signed, not Developer ID/notarized. Includes the narrowed macOS YouTube TCP fallback from the preceding release. Existing installed APP and user profiles were not replaced. No commits/pushes performed in this request.
@@ -0,0 +1,27 @@
# macOS local profile storage — 2026-10-12
## Behavior
Profiles now live in `~/Library/Application Support/MeshPort/`: `proxy-profile.json` and `network-profile.toml`. The directory is 0700 and files are 0600. Writes use a private 0600 temporary file, synchronize it, then atomically rename it. Existing symbolic links, files owned by another user, invalid UTF-8 and files over the existing 64 KiB limit are rejected. All native profile operations run on one serial queue.
Normal reads, saves and deletes use files only. On first load with no local file, legacy Keychain migration uses an LAContext with interaction disabled. Success saves locally; a missing legacy entry is marked complete. Failure creates a pending marker so future starts do not repeatedly query Keychain. Settings exposes “迁移旧配置” only while pending; explicit migration can request Keychain authorization and never overwrites local edits. Old Keychain entries remain as backups. Deleting a local profile records a migration tombstone so the old entry cannot automatically reappear. Auto-connect is suppressed while migration remains pending. Android storage is unchanged.
This does not remove macOS administrator authorization for creating the VPN. The preceding helper reuse optimization is included.
## Validation
- Standalone Swift checks passed: local persistence, permissions, replacement, oversized-write rejection, silent migration, one-time pending state, manual migration, restart, deletion, symlinks and corruption handling. Fixtures use temporary directories and an injected legacy reader; no real profile credentials are touched.
- Flutter suite passed (50 passed, 6 skipped), analyzer reports no issues.
- Xcode project parses; Release compilation includes the new storage implementation and native channel handlers.
- Bundle deep/strict signature check, ZIP integrity and public default configuration checks passed.
- No installed app/profile was overwritten during packaging. User migration occurs when the new version runs.
## Package
`outputs/macos/MeshPort-0.1.0-1791873037-arm64-release.zip`
Original ZIP SHA-256: `e19108990fe411f7af3af61655f4f284a008e9c1effc0599286ee368d48ebaf9`.
Repacked from the same build during 2026-10-13 workspace cleanup; current ZIP SHA-256: `f4a27039dd1d81ca99aae17b6a49b8cf791eb089ef7db199b0d9777f4799fc66`. Version, signature and public bundled configuration were checked before deleting build caches.
Apple Silicon, macOS 12+, Release build, Apple Development signed, not Apple notarized. ZIP contains `MeshPort.app` so it can replace `/Applications/MeshPort.app` without leaving a duplicate version. Source changes are uncommitted; no push performed.
@@ -0,0 +1,25 @@
# macOS Release package — 2026-10-12
- Bundle: `MeshPort-0.1.0-1791871105-arm64-release.app`.
- ZIP: `MeshPort-0.1.0-1791871105-arm64-release.zip`, 34,237,920 bytes.
- SHA-256: `9c01cc6c44c2754540e165e5cd210324d81a70ddc4b5d7b16797963a46a2df71`.
- Apple Silicon arm64, minimum macOS 12.0. Flutter Release AOT and Rust release profile; optimized Go core.
- Ad-hoc local signature, deep/strict verification passed. No Developer ID Application identity available; this package is not Apple-notarized.
## Video policy
The measured prototype denied external UDP/443 and reached 119–127 Mbps on the user's video. This release narrows the mitigation to detected QUIC on UDP/443 for `googlevideo.com` and its subdomains, only on macOS DesktopTun with raw VLESS/Reality `xtls-rprx-vision` and global/bypass-CN modes. Existing mesh/private/GeoIP routes run first. Other QUIC domains, unrecognized UDP/443, custom rule mode, other transports and Android retain their policy. DNS, MTU and node settings are not changed.
This narrowed release policy has not yet been measured on the user's live VPN; the prototype's speed measurements are not a guarantee for every CDN or connection.
## Checks
- Go bridge suite and race checks passed; go vet passed.
- Real sing-box rule matcher verifies only YouTube QUIC matches, excluding lookalike domains, other domains, STUN/unrecognized UDP, TCP and other ports. QUIC sniffer rule construction passed.
- Packaged Go dylib loaded; ABI 1, context creation, stopped status and context/free calls passed without starting a VPN.
- Executable, helper and proxy dylib arm64 verified. AOT assets verified (no debug kernel blob).
- Bundled default configuration byte-matches public example; no private template bundled.
- Bundle codesign deep/strict check and ZIP integrity check passed.
- Existing installed APP and saved user configuration not replaced. Packaging temporarily uses public defaults and restores the original local asset on exit.
Rebuild with `sh scripts/package-lab-macos.sh`. Flutter's universal Release lipo verification failed with this installed toolchain; the script explicitly builds the host architecture, matching its native Rust/Go libraries, instead of advertising a universal package.
@@ -1,52 +0,0 @@
INFO[0000] inbound/socks[local]: tcp server started at 127.0.0.1:10818
INFO[0000] inbound/tun[unified-tun]: started at utun25
INFO[0000] sing-box started (0.01s)
INFO[0000] inbound/socks[local]: tcp server started at 127.0.0.1:10818
INFO[0000] inbound/tun[unified-tun]: started at utun25
INFO[0000] sing-box started (0.01s)
self-test route 10.253.88.2: route to: 10.253.88.2
destination: 10.253.88.0
mask: 255.255.255.128
gateway: 172.19.0.1
interface: utun25
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1280 0
self-test route 10.253.88.129: route to: 10.253.88.129
destination: 10.253.88.128
mask: 255.255.255.128
gateway: 172.19.0.1
interface: utun25
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1280 0
self-test route 172.19.0.1: route to: 172.19.0.1
destination: 172.19.0.1
interface: utun25
flags: <UP,HOST,DONE,LOCAL>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1280 0
self-test TUN interface: 25: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280
inet 172.19.0.1 --> 172.19.0.1 netmask 0xfffffffc
nd6 options=201<PERFORMNUD,DAD>
self-test UDP server received 29 bytes from 127.0.0.1:62966
self-test native UDP probe: {"data":{"elapsed_ms":4.484083,"kind":"echo_roundtrip","protocol":"UDP","target":"10.253.88.129:57916","verified_bytes":29},"ok":true}
DEBUG[0002] [3444557976 0ms] router: pre-match[1] ip_cidr=[10.253.88.0/25 10.253.88.128/25] => route(meshport)
INFO[0002] [3954399957 0ms] inbound/tun[unified-tun]: inbound connection from 172.19.0.1:59199
INFO[0002] [3954399957 0ms] inbound/tun[unified-tun]: inbound connection to 10.253.88.2:7007
DEBUG[0002] [3954399957 0ms] router: match[1] ip_cidr=[10.253.88.0/25 10.253.88.128/25] => route(meshport)
INFO[0002] [3954399957 0ms] outbound/socks[meshport]: outbound connection to 10.253.88.2:7007
PASS: OS TCP echo through unified TUN
DEBUG[0002] [3954399957 4ms] connection: connection upload finished
DEBUG[0002] [898754351 0ms] router: pre-match[1] ip_cidr=[10.253.88.0/25 10.253.88.128/25] => route(meshport)
INFO[0002] [2461669854 0ms] inbound/tun[unified-tun]: inbound packet connection from 172.19.0.1:60071
INFO[0002] [2461669854 0ms] inbound/tun[unified-tun]: inbound packet connection to 10.253.88.129:57916
DEBUG[0002] [2461669854 0ms] router: match[1] ip_cidr=[10.253.88.0/25 10.253.88.128/25] => route(meshport)
DEBUG[0002] [2461669854 0ms] outbound/socks[meshport]: mesh UDP association requested
DEBUG[0002] [2461669854 0ms] outbound/socks[meshport]: mesh UDP association ready: 127.0.0.1:52864 -> 127.0.0.1:60968
self-test UDP server received 11 bytes from 127.0.0.1:63999
PASS: OS TCP/UDP -> sing-box TUN -> MeshPort SOCKS -> EasyTier; stop removed test route and preserved default route
@@ -0,0 +1,60 @@
# macOS 视频吞吐调查
用户提供同一节点、同一浏览器、两个系统 VPN 对比:Shadowrocket 的同一 YouTube 视频约 90000+ Kbps,MeshPort 约 20000+ Kbps。截图显示 92512 Kbps、3840×2160@60、Buffer Health 18.33 秒;这里只把它当作当时播放器的测量值,不把单张截图当成可重复下载基准。
## 已检查
- MeshPort 选中 VLESS/Reality 节点,Flow 为 xtls-rprx-vision,TCP 传输。仅查看了配置,没有保存修改或显示 UUID。
- 当前功能是代理与组网,互联网模式为绕过中国大陆。尚未核对 Shadowrocket 的分流、DNS、UDP/QUIC 行为及实际视频 CDN 地址。
- 未在普通代理转发路径发现固定 20 Mbps 限速。普通互联网出口不经过 Rust 组网 SOCKS 桥。
- 当前 TUN 设为 system 栈、MTU 1280;DNS/目标解析限制为 IPv4。它们是待对比因素,尚未证明是慢速原因。
- 本机回环基准(Apple M4,32 MiB HTTP 响应,每组 3 次、重复 3 组)经过受管理 SOCKS 入口的直接出口约 6508–6779 MB/s。该基准不包含 TUN、真实 VLESS/Reality、外网延迟、QUIC 或 YouTube CDN,只用于检查简单 SOCKS 转发是否存在通用低速上限,不能推断真实 VPN 的速度。
复现命令:
```sh
sh scripts/go-local.sh test ./bridge -run '^$' \
-bench '^BenchmarkManagedDownload$' -benchtime=3x -count=3
```
## 外网对照结果
同一固定 Cloudflare IPv4 地址、同一 HTTPS 资源,每次丢弃 10,000,000 字节响应,所有请求成功返回 HTTP 200。curl 请求 HTTP/2,但实际均协商 HTTP/1.1。速度按完整请求(含握手及首包)的字节数/总时间计算。
| 路径 | 实测 Mbps |
| --- | --- |
| MeshPort 系统 VPN | 23.07、19.41 |
| MeshPort 本机 SOCKS(绕过 TUN,仍经过同一代理引擎) | 7.62、21.94 |
| Shadowrocket 系统 VPN | 23.37、23.74、25.90 |
本轮固定资源没有复现四倍差距;SOCKS 也未恢复到截图中的 90 Mbps,因此目前不支持把 TUN MTU 认定为唯一原因。上述样本很少,且视频仍在播放,不代表最大吞吐。
Shadowrocket 连接后,2026-10-12 22:24 的同一视频可见统计为 Connection Speed 29465 Kbps、3840×2160@60、Buffer Health 17.32 秒。Chrome 同时显示 3 个下载任务正在进行,这可能影响两边测试。已请用户暂停下载,再进行对照;未代为取消下载。
用户确认暂停下载后,Shadowrocket 同一固定资源三次结果为 19.04、24.22、11.50 Mbps(HTTP 200,实际 HTTP/1.1)。随后读取视频统计为 Connection Speed 17183 Kbps、Buffer Health 17.17 秒;这仍是播放和测速同时进行时的瞬时值,不能视为稳定速度上限。暂停下载没有在本轮恢复截图中的 90 Mbps,不能认定后台下载就是根因。已请求相同条件下切回 MeshPort 完成对照。
用户随后要求先断开并重新连接 Shadowrocket 再测。确认 MacPacketTunnel 进程存在、固定资源路由为 utun4。三次固定资源结果为 21.11、20.62、24.10 Mbps;请求完成后同一视频显示 Connection Speed **101646 Kbps**、Buffer Health **19.15 秒**。这复现了用户描述的 Shadowrocket 高速表现,同时证明该固定 Cloudflare 资源不能代表视频吞吐,不能用这个资源的接近结果否定视频差距。下一轮应在 MeshPort 下测同一视频的实际连接,并核对 CDN/协议。
MeshPort 播放期间 helper 的已采样 CPU 为 0.1–46.4%,RSS 约 28–66 MiB。ps CPU 为平均值,不能排除短时单核瓶颈。运行日志出现一次目标 443 连接超时,但尚无足够证据证明其导致视频持续低吞吐。
## 待实测
2026-10-12 22:31–22:33,用户确认已切回 MeshPort 且下载暂停。APP 概览显示统一 VPN/sing-box TUN 正在运行。同一视频此时为 7680×4320@60 AV1,Connection Speed 可见样本为 52348、47313、54396、68363、71273、64560、55173、62165、47999 Kbps,Buffer Health 约 19–26 秒。没有同时运行额外测速下载。DevTools 实际 videoplayback 请求使用 **h3**,CDN 为 rr1---sn-a5msenle.googlevideo.com,返回 HTTP 200。
22:36,用户再次确认切到 Shadowrocket。实际 videoplayback 请求使用 **http/1.1**,同样访问 rr1---sn-a5msenle.googlevideo.com;大响应示例为 36,064 kB/3.70 秒、34,872 kB/3.03 秒、33,645 kB/3.23 秒。播放器显示 93303 Kbps、Buffer Health 13.30 秒,但画质已变为 3840×2160@60。因此协议差异是有证据的排查方向,尚不能排除画质、重连和时段影响。两边统计上报请求的协议不能代替视频请求的协议。
准备独立实验包:复制 Go 模块到忽略目录 work/video-tcp-core,仅在该副本的 macOS DesktopTun 代理模式下添加 UDP/443 reject,位于组网/私网路由之后,让支持回退的 HTTPS 流量重试 TCP。没有修改正式 config.go 或用户配置。此规则是临时诊断范围,不能直接作为生产修复。副本 bridge 测试通过;仍需实际连接确认视频回退协议及吞吐。
实验包为 outputs/macos/MeshPort-video-tcp-test.app,以安装中的 APP 为基础,仅替换代理 dylib 并重新签名,codesign --verify --deep --strict 通过。测试 dylib SHA-256:5803e6f48158cf81895a6c6f63faca51b77e5314fb134d0b34e95e980211f45e。原 /Applications/MeshPort.app 未替换。已退出原 APP 并启动独立测试包,界面确认原有“代理+组网 / 绕过中国大陆”配置仍显示、尚未连接。等待用户停止 Shadowrocket、连接该测试包并完成管理员授权后,验证实际 videoplayback 协议与速度。
用户确认测试版连接并刷新同一视频、选择 4K60 后,22:43:51 可见 Connection Speed **118825 Kbps**,Buffer Health **15.97 秒**。实际视频请求为 HTTP 200、**http/1.1**,示例 41,203 kB/3.33 秒、38,061 kB/3.51 秒、33,580 kB/2.47 秒。这证实测试版回退 TCP 且能达到截图量级的速度;但 CDN 换为 rr3---sn-qja5m5-5h.googlevideo.com,因此不能把改善全部归因于协议改变,仍需控制 CDN/重复测试后决定正式策略。
约 20 秒后第二次读取为 **127139 Kbps**、Buffer Health **15.05 秒**,画质仍为 3840×2160@60。已请求保持当前页面/画质不刷新,切回 Shadowrocket 对比当前 CDN。测试包当前为实验性质:会拒绝符合范围的外网 UDP/443,不应在没有缩小策略和兼容性验证前作为正式发布包。
最后一轮用户确认已切回 Shadowrocket,22:48:21 同一 4K60 视频显示 **71219 Kbps**、Buffer Health **13.43 秒**。实际视频请求仍为 rr3---sn-qja5m5-5h.googlevideo.com、http/1.1,返回 200,样本 41,138 kB/3.84 秒、47,409 kB/6.83 秒、20,342 kB/1.85 秒、34,383 kB/3.39 秒、43,303 kB/4.61 秒。相同 CDN 域名并不等于已固定同一 CDN IP;时段、缓冲及连接状态仍有影响,不能宣称实验包稳定快于 Shadowrocket。
结论:原版实际出现 h3 视频请求;实验版回退 http/1.1 后两次达到 119–127 Mbps,与用户期望同量级,没有复现通用 20 Mbps 限速。TCP 回退为有实测支持的改善方向,尚未完成协议/CDN 严格隔离及长期兼容性验证,不认定唯一根因或正式修复完成。正式 config.go 未修改,未提交或推送本轮代码。确认实验 APP 已停止并释放网络资源后退出它,重新打开 /Applications/MeshPort.app;Shadowrocket 保持用户最后选择的连接状态。已关闭本轮打开的 DevTools。
先在没有后台下载时重做同一视频和固定资源对照,再核对实际视频 CDN、HTTP/2 与 HTTP/3、IPv4/IPv6,最后才进行单变量的 MTU/栈调整。
调查开始时 Shadowrocket 正在连接、MeshPort 已断开,因此本轮最初的 CPU 数据不能用于评估 MeshPort 播放性能。尚无经实测确认的修复,也未修改用户节点、系统网络参数或代理默认值。原始采样与测速输出保留在本机临时目录。
+6 -2
View File
@@ -1,7 +1,11 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
sh scripts/prepare-lab-default.sh
if [ "${MESHPORT_PUBLIC_CONFIG:-0}" = 1 ]; then
cp apps/meshport_lab/assets/config/default.example.toml apps/meshport_lab/assets/config/default.toml
else
sh scripts/prepare-lab-default.sh
fi
mode="${1:---release}"
case "$mode" in --debug|--release) ;; *) printf '%s\n' 'usage: build-lab-android.sh [--debug|--release]' >&2; exit 2;; esac
sdk="${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}"
@@ -21,7 +25,7 @@ sh scripts/build-singbox-library.sh android
mkdir -p apps/meshport_lab/android/app/src/main/jniLibs/arm64-v8a
cp "target/aarch64-linux-android/$profile/libmeshport_ffi.so" apps/meshport_lab/android/app/src/main/jniLibs/arm64-v8a/
cp target/singbox/android-arm64/libmeshport_proxy.so apps/meshport_lab/android/app/src/main/jniLibs/arm64-v8a/
build_number=$(date +%s)
build_number="${MESHPORT_BUILD_NUMBER:-$(date +%s)}"
cd apps/meshport_lab
flutter build apk "$mode" --target-platform android-arm64 --build-number="$build_number"
cd ../..
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Remove reproducible workspace artifacts, keeping tools, profiles and packages."""
import argparse
from pathlib import Path
import shutil
import subprocess
root = Path(__file__).resolve().parents[1]
paths = [
"target",
"apps/meshport_lab/build",
"apps/meshport_lab/.dart_tool",
"apps/meshport_lab/android/.gradle",
"apps/meshport_lab/android/.kotlin",
"apps/meshport_lab/android/app/src/main/jniLibs",
"work/cache",
"work/bin",
"work/android-validation",
"work/ui-preview",
"work/menubar-preview",
"work/menubar-native-tests.xcresult",
"work/menubar-native-tests-2.xcresult",
"work/menubar-native-tests-3.xcresult",
"work/video-tcp-core",
"work/singbox-patched",
"work/singbox-patched.go.mod",
"work/singbox-patched.go.sum",
"work/easytier-upstream.tar.gz",
"work/toolchain/go-sdk.tar.gz",
"work/toolchain/protoc.zip",
"work/toolchain/rustup-init.sh",
]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--delete", action="store_true", help="Actually delete; default only lists paths")
args = parser.parse_args()
repository = subprocess.check_output(["git", "rev-parse", "--show-toplevel"], cwd=root, text=True).strip()
if Path(repository).resolve() != root:
raise SystemExit("Refusing cleanup outside the repository root")
tracked = subprocess.check_output(["git", "ls-files", "-z", "--", *paths], cwd=root)
if tracked:
raise SystemExit("Refusing to remove tracked files under a cleanup path")
# Check every parent before deleting anything. Leaf symlinks are unlinked only.
for relative in paths:
if not (root / relative).parent.resolve().is_relative_to(root):
raise SystemExit(f"Refusing path with an external parent: {relative}")
for relative in paths:
path = root / relative
if not path.exists() and not path.is_symlink():
continue
print(("Removing " if args.delete else "Would remove ") + relative, flush=True)
if args.delete:
if path.is_symlink() or path.is_file():
path.unlink()
else:
shutil.rmtree(path)
print("Kept toolchains, user configuration, Git history and outputs/android + outputs/macos")
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
config=apps/meshport_lab/assets/config/default.toml
saved=$(mktemp)
had_config=0
if [ -f "$config" ]; then cp -p "$config" "$saved"; had_config=1; fi
restore_config() {
if [ "$had_config" = 1 ]; then cp -p "$saved" "$config"; else rm -f "$config"; fi
rm -f "$saved"
}
trap restore_config EXIT HUP INT TERM
build_number=$(date +%s)
MESHPORT_PUBLIC_CONFIG=1 MESHPORT_BUILD_NUMBER="$build_number" sh scripts/build-lab-android.sh --release
output="outputs/android/MeshPort-0.1.0-$build_number-release.apk"
shasum -a 256 "$output" > "$output.sha256"
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
root="$PWD"
# A stable Apple signing identity keeps the app's Keychain requirement stable
# across updates. An explicit identity can also be a Developer ID certificate.
signing_identity="${MESHPORT_SIGNING_IDENTITY:-}"
if [ -z "$signing_identity" ]; then
signing_identity=$(security find-identity -v -p codesigning | python3 -c 'import re,sys; ids=re.findall(r"([0-9A-F]{40}) \"Apple Development:", sys.stdin.read()); print(ids[0] if len(ids)==1 else "-")')
fi
config="$root/apps/meshport_lab/assets/config/default.toml"
saved=$(mktemp)
had_config=0
if [ -f "$config" ]; then
cp -p "$config" "$saved"
had_config=1
fi
restore_config() {
if [ "$had_config" = 1 ]; then cp -p "$saved" "$config"; else rm -f "$config"; fi
rm -f "$saved"
}
trap restore_config EXIT HUP INT TERM
# Distribution bundles use only the public template, never local credentials.
cp "$root/apps/meshport_lab/assets/config/default.example.toml" "$config"
scripts/cargo-local.sh build -p meshport-ffi -p meshport-vpn-helper --release --locked
sh scripts/build-singbox-library.sh macos
build_number=$(date +%s)
build_arch=$(uname -m)
cd "$root/apps/meshport_lab"
# Rust and Go libraries above target this host architecture as well.
FLUTTER_XCODE_ARCHS="$build_arch" flutter build macos --release --build-number="$build_number"
app="$PWD/build/macos/Build/Products/Release/MeshPort.app"
cp "$root/target/release/libmeshport_ffi.dylib" "$app/Contents/Frameworks/"
cp "$root/target/debug/libmeshport_proxy.dylib" "$app/Contents/Frameworks/"
cp "$root/target/release/meshport-vpn-helper" "$app/Contents/MacOS/"
codesign --force --sign "$signing_identity" "$app/Contents/MacOS/meshport-vpn-helper"
codesign --force --sign "$signing_identity" "$app/Contents/Frameworks/libmeshport_ffi.dylib"
codesign --force --sign "$signing_identity" "$app/Contents/Frameworks/libmeshport_proxy.dylib"
codesign --force --deep --sign "$signing_identity" --entitlements macos/Runner/Release.entitlements "$app"
codesign --verify --deep --strict "$app"
out="$root/outputs/macos/MeshPort-0.1.0-$build_number-$build_arch-release"
mkdir -p "$root/outputs/macos"
ditto "$app" "$out.app"
# Keep the installed filename stable so dragging it replaces the old APP.
ditto -c -k --sequesterRsrc --keepParent "$app" "$out.zip"
shasum -a 256 "$out.zip" > "$out.zip.sha256"
printf '%s\n' "$out.app" "$out.zip"
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p work/bin
xcrun swiftc -parse-as-library apps/meshport_lab/macos/Runner/LocalProfileStore.swift tools/tests/local-profile-store.swift -o work/bin/local-profile-store-check
work/bin/local-profile-store-check
+77
View File
@@ -0,0 +1,77 @@
import Foundation
import Security
@main struct ProfileStoreChecks {
static func require(_ condition: @autoclosure () -> Bool, _ message: String) throws {
if !condition() { throw NSError(domain: "ProfileStoreChecks", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
}
static func fails(_ action: () throws -> Void) throws {
var rejected = false
do { try action() } catch { rejected = true }
try require(rejected, "Unsafe operation was accepted")
}
static func main() throws {
let fm = FileManager.default
let temporary = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try fm.createDirectory(at: temporary, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: temporary) }
var calls = 0
let root = temporary.appendingPathComponent("profiles")
let store = LocalProfileStore(root: root, legacyReader: { _, interactive in
calls += 1
try require(!interactive, "Startup requested interactive authorization")
return Data("{\"nodes\":[]}".utf8)
})
let first = try store.load(.proxy)
try require(first == "{\"nodes\":[]}", "Silent migration lost content")
try store.save("{\"nodes\":[\"fixture\"]}", kind: .proxy)
let loaded = try store.load(.proxy)
try require(loaded == "{\"nodes\":[\"fixture\"]}", "Save/load mismatch")
try require(calls == 1, "Normal reads accessed Keychain")
let dirAttrs = try fm.attributesOfItem(atPath: root.path)
let file = root.appendingPathComponent("proxy-profile.json")
let attrs = try fm.attributesOfItem(atPath: file.path)
try require((dirAttrs[.posixPermissions] as? NSNumber)?.intValue == 0o700, "Directory is not private")
try require((attrs[.posixPermissions] as? NSNumber)?.intValue == 0o600, "File is not private")
try fails { try store.save(String(repeating: "x", count: 65537), kind: .proxy) }
let retained = try store.load(.proxy)
try require(retained == loaded, "Rejected save replaced valid content")
try store.delete(.proxy)
let deleted = try store.load(.proxy)
try require(deleted == nil && calls == 1, "Deleted profile resurrected from Keychain")
var attempts = [Bool]()
let pendingRoot = temporary.appendingPathComponent("pending")
let pending = LocalProfileStore(root: pendingRoot, legacyReader: { _, interactive in
attempts.append(interactive)
if !interactive { throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecInteractionNotAllowed)) }
return Data("network_name = \"fixture\"".utf8)
})
_ = try pending.load(.network)
_ = try pending.load(.network)
try require(attempts == [false], "Startup retried Keychain repeatedly")
let hasPending = try pending.migrationPending()
try require(hasPending, "Missing manual migration state")
try pending.migratePending()
let network = try pending.load(.network)
let stillPending = try pending.migrationPending()
try require(network == "network_name = \"fixture\"" && !stillPending && attempts == [false, true], "Manual migration failed")
let reopened = LocalProfileStore(root: pendingRoot, legacyReader: { _, _ in throw NSError(domain: "Unexpected Keychain access", code: 1) })
let reopenedText = try reopened.load(.network)
try require(reopenedText == network, "Restart did not read local profile")
let outside = temporary.appendingPathComponent("outside")
try Data("unchanged".utf8).write(to: outside)
try fm.createSymbolicLink(at: file, withDestinationURL: outside)
try fails { _ = try store.load(.proxy) }
try fails { try store.save("replacement", kind: .proxy) }
let outsideText = try String(contentsOf: outside, encoding: .utf8)
try require(outsideText == "unchanged", "Symlink target was modified")
try fm.removeItem(at: file)
try Data([0xff]).write(to: file)
try fails { _ = try store.load(.proxy) }
try require(calls == 1, "Corrupt file silently fell back to legacy credentials")
print("PASS: local read/write, private permissions, atomic replacement, migration, deletion, restart, size limit and symlink/corruption handling")
}
}