feat(client/macos): P1 原生隧道——PacketTunnel 系统扩展可加载 + libbox 运行
经长链路排查(同机对照可工作的 Tailscale),修复 macOS 系统扩展 realize 失败(OSSystemExtensionErrorDomain code=4)与 libbox 运行时崩溃,使内嵌 sing-box 的系统扩展能在 macOS 15 上激活并启动隧道。 系统扩展 realize(三个叠加根因): - 扩展自包含:PacketTunnel 加 OTHER_LDFLAGS="" 切断对项目级 CocoaPods 链接 标志的继承(原会把 flutter_secure_storage 链进扩展);Libbox.xcframework 改纯 Link(静态),从 Embed Frameworks 移除冗余内嵌 - bundle 名 = 标识符:PRODUCT_NAME 设为 com.pangolin.pangolin.PacketTunnel - 扩展 Info.plist 补 NSSystemExtensionUsageDescription(网络扩展类别强制要求) - App Group 改 macOS 原生格式 BYL4KQHMTN.com.pangolin.pangolin;NEMachServiceName 以其为前缀;扩展补 network.client/server;get-task-allow=false + 签名加 --timestamp - CFBundleVersion 随构建递增(否则 sysextd 视为同版本不更新) libbox 运行时: - startOrReloadService(options:) 传 nil 致空指针 SIGSEGV → 传 LibboxOverrideOptions() - 默认接口监控阻塞到首个 path 更新再返回,修 "no available network interface" 配套: - scripts/local_test.sh:build/sign/notarize/copy/run 一条龙(Developer ID + 公证) - client/macos/sign_libbox.sh:构建期以 Developer ID 重签内嵌 Libbox - VpnChannel:401 自动刷新 token、详尽 os_log;auth/api 统一走 kApiBaseUrl - docs/macos-sysext-realize-troubleshooting.html:完整踩坑复盘 WIP / 临时(后续清理): - 隧道运行时仍在排查:剥离远程 rule-set 后 sing-box 启动卡点未定位 - 含临时诊断代码:main.swift stderr 重定向、box.log 输出、rule-set 剥离、debug 日志 - api_config 仍指向联调节点,发版前还原 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JEHzjEcFzvGwgbxT6Wbt6c
This commit is contained in:
@@ -10,6 +10,14 @@
|
||||
<true/>
|
||||
<key>com.apple.security.network.server</key>
|
||||
<true/>
|
||||
<!-- P1 方案B:主 app 经 OSSystemExtensionRequest 安装 PacketTunnel sysext,需此权限。 -->
|
||||
<key>com.apple.developer.system-extension.install</key>
|
||||
<true/>
|
||||
<!-- 主 app 经 NETunnelProviderManager 管理 packet-tunnel,需 NE 权限(App ID 已开 Network Extensions)。 -->
|
||||
<key>com.apple.developer.networking.networkextension</key>
|
||||
<array>
|
||||
<string>packet-tunnel-provider</string>
|
||||
</array>
|
||||
<!-- flutter_secure_storage: Data Protection Keychain 需要此 entitlement,否则返回 -34018 -->
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
|
||||
@@ -28,5 +28,8 @@
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<!-- 安装 PacketTunnel System Extension 的必需键:OSSystemExtensionRequest 审批时展示给用户。 -->
|
||||
<key>NSSystemExtensionUsageDescription</key>
|
||||
<string>Pangolin 需要安装系统扩展以提供安全的网络连接。</string>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -2,20 +2,33 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Developer ID 分发 + 公证:禁止调试附加(否则公证会拒;也避免 Xcode 注入 =true)。 -->
|
||||
<key>com.apple.security.get-task-allow</key>
|
||||
<false/>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<false/>
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<!-- P1 方案B:主 app 经 OSSystemExtensionRequest 安装 PacketTunnel sysext,需此权限。 -->
|
||||
<key>com.apple.developer.system-extension.install</key>
|
||||
<true/>
|
||||
<!-- 主 app 经 NETunnelProviderManager 管理 packet-tunnel(System Extension 形态)。
|
||||
Developer ID profile 授权的是 -systemextension 变体,故用它(非 plain)。 -->
|
||||
<key>com.apple.developer.networking.networkextension</key>
|
||||
<array>
|
||||
<string>packet-tunnel-provider-systemextension</string>
|
||||
</array>
|
||||
<!-- flutter_secure_storage: Data Protection Keychain 需要此 entitlement,否则返回 -34018 -->
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)com.pangolin.pangolin</string>
|
||||
</array>
|
||||
<!-- P1 方案B:接 System Extension 时在此加(注册 App Group 后,见 p1-macos-system-extension.md §3):
|
||||
<!-- 与 PacketTunnel sysext 共享 App Group。必须用 macOS 原生格式 <TeamID>.<name>
|
||||
(BYL4KQHMTN.com.pangolin.pangolin),非 iOS 的 group. 前缀——否则 sysextd 在 realize
|
||||
暂存前校验请求方 app 时认定 app group 非法而拒绝(参照可工作的 Tailscale)。 -->
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.com.pangolin.pangolin</string>
|
||||
<string>BYL4KQHMTN.com.pangolin.pangolin</string>
|
||||
</array>
|
||||
-->
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -13,9 +13,16 @@
|
||||
import FlutterMacOS
|
||||
import NetworkExtension
|
||||
import SystemExtensions
|
||||
import os.log
|
||||
|
||||
// NSLog 兼容老部署目标(Runner < macOS 11,os.Logger 不可用)。
|
||||
private func vpnLog(_ message: String) { NSLog("[pangolin/vpn] %@", message) }
|
||||
// os_log + %{public} —— 让日志在 Console.app / `log show` 里可见(NSLog 的 %@ 参数会被
|
||||
// 系统 redact 成 <private>,排障时看不到内容)。os_log(C API)自 macOS 10.12 起可用,
|
||||
// 兼容 Runner 的 10.15 部署目标。过滤:`log show --predicate 'subsystem == "com.pangolin.pangolin"'`。
|
||||
private let vpnLogObj = OSLog(subsystem: "com.pangolin.pangolin", category: "vpn")
|
||||
private func vpnLog(_ message: String) {
|
||||
os_log("%{public}@", log: vpnLogObj, type: .default, message)
|
||||
NSLog("[pangolin/vpn] %@", message) // 同时进 stderr,flutter run 控制台也能看到
|
||||
}
|
||||
|
||||
final class VpnChannel: NSObject {
|
||||
private static let tunnelBundleId = "com.pangolin.pangolin.PacketTunnel"
|
||||
@@ -68,16 +75,26 @@ final class VpnChannel: NSObject {
|
||||
}
|
||||
|
||||
private func start(_ configJson: String, _ result: @escaping FlutterResult) async {
|
||||
vpnLog("start() 收到调用, config 长度=\(configJson.count) bytes")
|
||||
do {
|
||||
vpnLog("step① 激活 System Extension …")
|
||||
try await activateSystemExtensionIfNeeded()
|
||||
vpnLog("step① System Extension 激活完成 ✓")
|
||||
|
||||
vpnLog("step② 装配 NETunnelProviderManager …")
|
||||
let mgr = try await loadOrCreateManager()
|
||||
self.manager = mgr
|
||||
vpnLog("step② manager 就绪, 当前隧道状态=\(Self.statusString(mgr.connection.status))")
|
||||
|
||||
vpnLog("step③ startVPNTunnel(options: configContent) …")
|
||||
try mgr.connection.startVPNTunnel(options: [
|
||||
"configContent": configJson as NSString,
|
||||
])
|
||||
vpnLog("step③ startVPNTunnel 调用已返回(实际起停由 NEVPNStatus 流驱动)✓")
|
||||
result(nil)
|
||||
} catch {
|
||||
vpnLog("start failed: \(error.localizedDescription)")
|
||||
let ns = error as NSError
|
||||
vpnLog("start FAILED ✗ domain=\(ns.domain) code=\(ns.code) desc=\(ns.localizedDescription) userInfo=\(ns.userInfo)")
|
||||
result(FlutterError(code: "start_failed", message: error.localizedDescription, details: nil))
|
||||
}
|
||||
}
|
||||
@@ -90,6 +107,7 @@ final class VpnChannel: NSObject {
|
||||
// ── NETunnelProviderManager 装配 ────────────────────────────────
|
||||
private func loadOrCreateManager() async throws -> NETunnelProviderManager {
|
||||
let all = try await NETunnelProviderManager.loadAllFromPreferences()
|
||||
vpnLog(" loadAllFromPreferences: 已有 \(all.count) 个 VPN 配置")
|
||||
let mgr = all.first ?? NETunnelProviderManager()
|
||||
let proto = (mgr.protocolConfiguration as? NETunnelProviderProtocol) ?? NETunnelProviderProtocol()
|
||||
proto.providerBundleIdentifier = Self.tunnelBundleId
|
||||
@@ -97,14 +115,20 @@ final class VpnChannel: NSObject {
|
||||
mgr.protocolConfiguration = proto
|
||||
mgr.localizedDescription = "Pangolin"
|
||||
mgr.isEnabled = true
|
||||
vpnLog(" saveToPreferences(providerBundleId=\(Self.tunnelBundleId)) …")
|
||||
try await mgr.saveToPreferences()
|
||||
try await mgr.loadFromPreferences() // 保存后重载,拿到有效 connection
|
||||
vpnLog(" manager 保存+重载完成 ✓")
|
||||
return mgr
|
||||
}
|
||||
|
||||
// 请求系统加载/更新 PacketTunnel System Extension。首启系统会弹「隐私与安全性」
|
||||
// 让用户允许;允许后 didFinishWithResult 回来。已是最新则快速完成。
|
||||
private func activateSystemExtensionIfNeeded() async throws {
|
||||
vpnLog(" 提交 OSSystemExtensionRequest.activationRequest(id=\(Self.tunnelBundleId)) …")
|
||||
vpnLog(" 主 bundle=\(Bundle.main.bundlePath)")
|
||||
let sysextDir = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/SystemExtensions").path
|
||||
vpnLog(" SystemExtensions 目录=\(sysextDir) 内容=\((try? FileManager.default.contentsOfDirectory(atPath: sysextDir)) ?? ["<读取失败>"])")
|
||||
try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
|
||||
let req = OSSystemExtensionRequest.activationRequest(
|
||||
forExtensionWithIdentifier: Self.tunnelBundleId, queue: .main)
|
||||
@@ -112,6 +136,7 @@ final class VpnChannel: NSObject {
|
||||
self.sysextDelegate = delegate // 保活到回调结束
|
||||
req.delegate = delegate
|
||||
OSSystemExtensionManager.shared.submitRequest(req)
|
||||
vpnLog(" submitRequest 已提交, 等待 sysextd 回调(didFinish / didFail / needsApproval)…")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +146,9 @@ final class VpnChannel: NSObject {
|
||||
forName: .NEVPNStatusDidChange, object: nil, queue: .main
|
||||
) { [weak self] note in
|
||||
guard let conn = note.object as? NEVPNConnection else { return }
|
||||
self?.statusSink?(Self.statusString(conn.status))
|
||||
let s = Self.statusString(conn.status)
|
||||
vpnLog("NEVPNStatus 变化 → \(s) (raw=\(conn.status.rawValue))")
|
||||
self?.statusSink?(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,21 +207,28 @@ private final class SysExtActivationDelegate: NSObject, OSSystemExtensionRequest
|
||||
|
||||
func request(_ request: OSSystemExtensionRequest,
|
||||
didFinishWithResult result: OSSystemExtensionRequest.Result) {
|
||||
vpnLog("sysext didFinishWithResult ✓ result=\(result.rawValue) (0=completed, 1=willCompleteAfterReboot)")
|
||||
guard !resumed else { return }
|
||||
resumed = true
|
||||
continuation.resume()
|
||||
}
|
||||
func request(_ request: OSSystemExtensionRequest, didFailWithError error: Error) {
|
||||
let ns = error as NSError
|
||||
// OSSystemExtensionErrorDomain code 速查:1 unknown,2 missingEntitlement,
|
||||
// 3 unsupportedParentBundleLocation,4 extensionNotFound,8 codeSignatureInvalid,
|
||||
// 9 validationFailed,10 forbiddenBySystemPolicy,13 authorizationRequired。
|
||||
vpnLog("sysext didFailWithError ✗ domain=\(ns.domain) code=\(ns.code) desc=\(ns.localizedDescription)")
|
||||
guard !resumed else { return }
|
||||
resumed = true
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
func requestNeedsUserApproval(_ request: OSSystemExtensionRequest) {
|
||||
vpnLog("system extension 待用户允许(系统设置 → 隐私与安全性)")
|
||||
vpnLog("sysext requestNeedsUserApproval —— 需在 系统设置 → 隐私与安全性 点「允许」(等待中…)")
|
||||
}
|
||||
func request(_ request: OSSystemExtensionRequest,
|
||||
actionForReplacingExtension existing: OSSystemExtensionProperties,
|
||||
withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {
|
||||
.replace
|
||||
vpnLog("sysext 替换扩展: 已装 v\(existing.bundleVersion)/\(existing.bundleShortVersion) → 新 v\(ext.bundleVersion)/\(ext.bundleShortVersion), 选择 replace")
|
||||
return .replace
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user