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:
wangjia
2026-06-21 21:18:33 +08:00
parent 43b25c8aa0
commit 447f3f494e
19 changed files with 629 additions and 143 deletions
@@ -7,10 +7,16 @@ import Foundation
import flutter_secure_storage_macos
import package_info_plus
import screen_retriever_macos
import shared_preferences_foundation
import tray_manager
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
TrayManagerPlugin.register(with: registry.registrar(forPlugin: "TrayManagerPlugin"))
WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin"))
}
+10 -1
View File
@@ -2,12 +2,21 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- 网络扩展类别强制要求:扩展自己的 Info.plist 必须有此键,否则
sysextd category 校验失败并卸载("require the presence of the
'NSSystemExtensionUsageDescription' property")。主 app 的同名键不顶用。 -->
<key>NSSystemExtensionUsageDescription</key>
<string>Pangolin 需要安装网络扩展以提供安全的网络连接。</string>
<!-- 自定义键:声明 NEPacketTunnelProvider。其余标准 CFBundle* 键由
GENERATE_INFOPLIST_FILE=YES 自动生成并合并,此处不重复写以免冲突。 -->
<key>NetworkExtension</key>
<dict>
<!-- NEMachServiceName 必须以扩展所属的某个 App Group 为前缀(Apple 规则)。
App Group 用 macOS 原生格式 BYL4KQHMTN.com.pangolin.pangolin,mach 名 = 该 group
+ .PacketTunnel。参照可工作的 Tailscale:group=<Team>.io.tailscale.ipn.macsys、
mach=该 group + .network-extension。 -->
<key>NEMachServiceName</key>
<string>$(TeamIdentifierPrefix)group.com.pangolin.pangolin</string>
<string>BYL4KQHMTN.com.pangolin.pangolin.PacketTunnel</string>
<key>NEProviderClasses</key>
<dict>
<key>com.apple.networkextension.packet-tunnel</key>
@@ -2,20 +2,26 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- 开发期:App Extension 变体,Apple Development 自动签名即可编/签/本机调试。
⚠️ 上线(站外 Developer ID 分发)时改为 System Extension:
- 把本值换成 packet-tunnel-provider-systemextension
- target 产物类型转 System Extension(.systemextension)
- 用 Developer ID 手动签名 + 公证;首启 systemextensionsctl developer on
Swift 代码两形态一致,仅打包/签名不同。详见 docs/p1-macos-system-extension.md。 -->
<!-- Developer ID 分发 + 公证:禁止调试附加。 -->
<key>com.apple.security.get-task-allow</key>
<false/>
<!-- 沙箱内的 packet tunnel 需显式网络权限才能对外建连/收发(对照可工作的 Tailscale)。 -->
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<!-- System Extension 形态(站外 Developer ID 分发):用 -systemextension 变体,
与 Developer ID profile(Pangolin PacketTunnel DevID)授权一致。
详见 docs/p1-macos-system-extension.md。 -->
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>packet-tunnel-provider</string>
<string>packet-tunnel-provider-systemextension</string>
</array>
<!-- 与主 app 共享配置/状态(同一 App Group) -->
<!-- 与主 app 共享配置/状态(同一 App Group)。macOS 原生格式 <TeamID>.<name>,
非 iOS 的 group. 前缀——sysextd realize 前校验请求方/扩展时要求此格式。 -->
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.pangolin.pangolin</string>
<string>BYL4KQHMTN.com.pangolin.pangolin</string>
</array>
</dict>
</plist>
@@ -15,7 +15,9 @@ import NetworkExtension
import os
private let log = Logger(subsystem: "com.pangolin.pangolin.PacketTunnel", category: "provider")
private let appGroup = "group.com.pangolin.pangolin"
// macOS App Group <TeamID>.<name>( iOS group. )
// sysextd app ; group. realize
private let appGroup = "BYL4KQHMTN.com.pangolin.pangolin"
final class PacketTunnelProvider: NEPacketTunnelProvider {
private var commandServer: LibboxCommandServer?
@@ -25,7 +27,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
completionHandler: @escaping (Error?) -> Void) {
log.info("startTunnel")
do {
let configContent = try resolveConfig(options)
let rawConfig = try resolveConfig(options)
guard let base = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
@@ -34,6 +36,10 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
let work = base.appendingPathComponent("work", isDirectory: true)
try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
// rule-set(#5); sing-box box.log(debug)
let configContent = Self.stripRemoteRuleSets(
rawConfig, logOutput: base.appendingPathComponent("box.log").path)
let setup = LibboxSetupOptions()
setup.basePath = base.path
setup.workingPath = work.path
@@ -50,13 +56,17 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
throw newErr ?? simpleError("LibboxNewCommandServer returned nil")
}
try server.start()
try server.startOrReloadService(configContent, options: nil)
// options: libbox StartOrReloadService options,
// nil command_server.go:175 SIGSEGV(),
try server.startOrReloadService(configContent, options: LibboxOverrideOptions())
self.commandServer = server
log.info("startTunnel: service started")
completionHandler(nil)
} catch {
log.error("startTunnel failed: \(error.localizedDescription)")
// stderr.log; public os_log <private>
FileHandle.standardError.write("startTunnel failed: \(error)\n".data(using: .utf8)!)
log.error("startTunnel failed: \(error.localizedDescription, privacy: .public)")
completionHandler(error)
}
}
@@ -90,13 +100,33 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
guard !content.isEmpty else { throw simpleError("empty sing-box config") }
return content
}
// rule-set , route.rules rule_set
// .srs()
static func stripRemoteRuleSets(_ json: String, logOutput: String) -> String {
guard let data = json.data(using: .utf8),
var root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
var route = root["route"] as? [String: Any] else {
return json
}
if route["rule_set"] != nil { route.removeValue(forKey: "rule_set") }
if let rules = route["rules"] as? [[String: Any]] {
route["rules"] = rules.filter { $0["rule_set"] == nil }
}
root["route"] = route
// sing-box box.log(debug),
root["log"] = ["level": "debug", "timestamp": true, "output": logOutput]
guard let out = try? JSONSerialization.data(withJSONObject: root),
let s = String(data: out, encoding: .utf8) else { return json }
return s
}
}
// LibboxCommandServerHandler:
extension PacketTunnelProvider: LibboxCommandServerHandlerProtocol {
func serviceReload() throws {
if let cfg = try? resolveConfig(nil) {
try commandServer?.startOrReloadService(cfg, options: nil)
try commandServer?.startOrReloadService(cfg, options: LibboxOverrideOptions())
}
}
func serviceStop() throws { cancelTunnelWithError(nil) }
@@ -106,7 +136,15 @@ extension PacketTunnelProvider: LibboxCommandServerHandlerProtocol {
}
func setSystemProxyEnabled(_ enabled: Bool) throws {}
func writeStatus(_ message: LibboxStatusMessage?) {}
func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {}
func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {
// sing-box stderr.log,
guard let it = messageList else { return }
while it.hasNext() {
guard let entry = it.next() else { continue }
let line = "[box] \(entry.message)\n"
FileHandle.standardError.write(line.data(using: .utf8) ?? Data())
}
}
func writeConnectionEvents(_ events: LibboxConnectionEvents?) {}
func writeGroups(_ message: (any LibboxOutboundGroupIteratorProtocol)?) {}
func writeDebugMessage(_ message: String?) {}
@@ -170,6 +208,11 @@ final class PangolinPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol
func startDefaultInterfaceMonitor(_ listener: (any LibboxInterfaceUpdateListenerProtocol)?) throws {
let m = NWPathMonitor()
monitor = m
// path : sing-box rule-set
// defaultInterfaceIndex -1,autoDetectControl "no available
// network interface" sing-box-for-apple
let firstUpdate = DispatchSemaphore(value: 0)
var signaled = false
m.pathUpdateHandler = { [weak self] path in
guard let self else { return }
let iface = path.availableInterfaces.first { path.usesInterfaceType($0.type) }
@@ -180,8 +223,10 @@ final class PangolinPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol
listener?.updateDefaultInterface(name, interfaceIndex: index,
isExpensive: path.isExpensive,
isConstrained: path.isConstrained)
if !signaled { signaled = true; firstUpdate.signal() }
}
m.start(queue: monitorQueue)
_ = firstUpdate.wait(timeout: .now() + 5)
}
func closeDefaultInterfaceMonitor(_ listener: (any LibboxInterfaceUpdateListenerProtocol)?) throws {
stopMonitor()
+11
View File
@@ -7,6 +7,17 @@
import Foundation
import NetworkExtension
// stderr/stdout App Group , libbox(Go)
// fatal error / panic stderr
if let c = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: "BYL4KQHMTN.com.pangolin.pangolin") {
let p = c.appendingPathComponent("stderr.log").path
freopen(p, "a", stderr)
freopen(p, "a", stdout)
setvbuf(stderr, nil, _IONBF, 0)
FileHandle.standardError.write("=== boot \(Date()) ===\n".data(using: .utf8)!)
}
autoreleasepool {
NEProvider.startSystemExtensionMode()
}
+65 -40
View File
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 70;
objectVersion = 54;
objects = {
/* Begin PBXAggregateTarget section */
@@ -92,7 +92,6 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
A17B79F72FE52309001ABF28 /* Libbox.xcframework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -137,7 +136,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
A17B79EE2FE50746001ABF28 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
A17B79EE2FE50746001ABF28 /* Exceptions for "PacketTunnel" folder in "PacketTunnel" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -147,7 +146,18 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
A17B79E22FE50746001ABF28 /* PacketTunnel */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (A17B79EE2FE50746001ABF28 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = PacketTunnel; sourceTree = "<group>"; };
A17B79E22FE50746001ABF28 /* PacketTunnel */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
A17B79EE2FE50746001ABF28 /* Exceptions for "PacketTunnel" folder in "PacketTunnel" target */,
);
explicitFileTypes = {
};
explicitFolders = (
);
path = PacketTunnel;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -338,6 +348,20 @@
productReference = 33CC10ED2044A3C60003C045 /* pangolin_vpn.app */;
productType = "com.apple.product-type.application";
};
FACE0FF0FACE0FF0FACE0001 /* Sign Libbox (Developer ID) */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Sign Libbox (Developer ID)";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "bash \"${SRCROOT}/sign_libbox.sh\"\n";
};
A17B79DE2FE50745001ABF28 /* PacketTunnel */ = {
isa = PBXNativeTarget;
buildConfigurationList = A17B79EF2FE50746001ABF28 /* Build configuration list for PBXNativeTarget "PacketTunnel" */;
@@ -346,6 +370,7 @@
A17B79DC2FE50745001ABF28 /* Frameworks */,
A17B79DD2FE50745001ABF28 /* Resources */,
A17B79F82FE52309001ABF28 /* Embed Frameworks */,
FACE0FF0FACE0FF0FACE0001 /* Sign Libbox (Developer ID) */,
);
buildRules = (
);
@@ -355,8 +380,6 @@
A17B79E22FE50746001ABF28 /* PacketTunnel */,
);
name = PacketTunnel;
packageProductDependencies = (
);
productName = PacketTunnel;
productReference = A17B79DF2FE50745001ABF28 /* PacketTunnel.systemextension */;
productType = "com.apple.product-type.system-extension";
@@ -379,7 +402,6 @@
33CC10EC2044A3C60003C045 = {
CreatedOnToolsVersion = 9.2;
LastSwiftMigration = 1100;
ProvisioningStyle = Automatic;
SystemCapabilities = {
com.apple.Sandbox = {
enabled = 1;
@@ -405,7 +427,7 @@
);
mainGroup = 33CC10E42044A3C60003C045;
packageReferences = (
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */,
);
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
projectDirPath = "";
@@ -536,14 +558,10 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
@@ -616,7 +634,7 @@
baseConfigurationReference = C57BBFD43F9175D1E23685EF /* Pods-RunnerTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -631,7 +649,7 @@
baseConfigurationReference = F8904897A48DC81799B8752E /* Pods-RunnerTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -646,7 +664,7 @@
baseConfigurationReference = B21E68FC1F5D33DD67A0DF5E /* Pods-RunnerTests.profile.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -712,11 +730,11 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
ENABLE_HARDENED_RUNTIME = YES;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
@@ -847,11 +865,11 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
ENABLE_HARDENED_RUNTIME = YES;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
@@ -870,17 +888,18 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
ENABLE_HARDENED_RUNTIME = YES;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CODE_SIGN_IDENTITY = "Developer ID Application";
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
OTHER_CODE_SIGN_FLAGS = "--timestamp";
PROVISIONING_PROFILE_SPECIFIER = "Pangolin App DevID";
SWIFT_VERSION = 5.0;
};
name = Release;
@@ -914,13 +933,13 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -933,12 +952,14 @@
"@executable_path/../../../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.2;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MARKETING_VERSION = 1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
OTHER_LDFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.PacketTunnel;
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = com.pangolin.pangolin.PacketTunnel;
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
@@ -962,13 +983,13 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CODE_SIGN_IDENTITY = "Developer ID Application";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -981,11 +1002,14 @@
"@executable_path/../../../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.2;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
OTHER_CODE_SIGN_FLAGS = "--timestamp";
OTHER_LDFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.PacketTunnel;
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = com.pangolin.pangolin.PacketTunnel;
PROVISIONING_PROFILE_SPECIFIER = "Pangolin PacketTunnel DevID";
SKIP_INSTALL = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
@@ -1008,13 +1032,13 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -1027,11 +1051,12 @@
"@executable_path/../../../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.2;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.PacketTunnel;
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = com.pangolin.pangolin.PacketTunnel;
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
@@ -1097,7 +1122,7 @@
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
};
@@ -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>
+3
View File
@@ -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>
+16 -3
View File
@@ -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>
+40 -6
View File
@@ -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
}
}
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# 构建期重签 PacketTunnel 内嵌的 Libbox.framework 为当前签名身份(Developer ID)。
# 原因:Libbox 是 gomobile xcframework,内部二进制是 adhoc/linker-signed,Xcode 的
# CodeSignOnCopy 不会替换它 → 公证会拒。本脚本在 sysext 被 Xcode 封签之前重签 Libbox,
# 使其 Developer ID + 带时间戳,避免事后手动重签(那会破坏框架对扩展的校验)。
set -e
LIBBOX="${CODESIGNING_FOLDER_PATH}/Contents/Frameworks/Libbox.framework"
[ -d "$LIBBOX" ] || { echo "sign_libbox: 未找到 $LIBBOX,跳过"; exit 0; }
[ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" ] || { echo "sign_libbox: 无签名身份,跳过"; exit 0; }
echo "sign_libbox: 用 ${EXPANDED_CODE_SIGN_IDENTITY_NAME:-$EXPANDED_CODE_SIGN_IDENTITY} 重签 Libbox"
/usr/bin/codesign --force --options runtime --timestamp -s "${EXPANDED_CODE_SIGN_IDENTITY}" "$LIBBOX/Versions/A/Libbox"
/usr/bin/codesign --force --options runtime --timestamp -s "${EXPANDED_CODE_SIGN_IDENTITY}" "$LIBBOX"
echo "sign_libbox: 完成"