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
@@ -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 {