Merge branch 'main' into feature/windows
This commit is contained in:
@@ -16,7 +16,7 @@ import 'dart:io' show Platform;
|
||||
/// P1 方案B 开关:macOS 是否走原生 System Extension(VpnNativeBridge)而非 PoC 的
|
||||
/// sudo 子进程(DesktopVpnBridge)。默认 false——待 PacketTunnel target/签名就绪、
|
||||
/// 原生侧联调通过后置 true。见 docs/p1-macos-system-extension.md。
|
||||
const bool kUseNativeVpnMacOS = false;
|
||||
const bool kUseNativeVpnMacOS = true;
|
||||
|
||||
/// 全局单例 VpnBridge。Ref 生命周期内不变。
|
||||
final vpnBridgeProvider = Provider<VpnBridge>((ref) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../l10n/app_text.dart';
|
||||
import '../pangolin_theme.dart';
|
||||
import '../state/account_providers.dart';
|
||||
import '../state/app_providers.dart';
|
||||
import '../state/auth_provider.dart';
|
||||
import '../state/navigation_provider.dart';
|
||||
import '../widgets/account_screens.dart';
|
||||
import '../widgets/app_top_bar.dart';
|
||||
@@ -93,7 +94,13 @@ class AccountPage extends ConsumerWidget {
|
||||
]),
|
||||
const SizedBox(height: 16),
|
||||
_Card(children: [
|
||||
_NavRow(icon: PangolinIcons.logOut, title: t.signOut, danger: true, onTap: () {}),
|
||||
_NavRow(
|
||||
icon: PangolinIcons.logOut,
|
||||
title: t.signOut,
|
||||
danger: true,
|
||||
// 清除本地令牌 → authProvider 置未登录 → 根据登录态回登录页。
|
||||
onTap: () => ref.read(authProvider.notifier).logout(),
|
||||
),
|
||||
]),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// api_config.dart — 控制面 API 基址单源。
|
||||
//
|
||||
// 历史上各 service/provider 各自重复声明 _kApiUrl;统一收敛到这里,
|
||||
// 由 --dart-define=PANGOLIN_API_URL 注入(默认本地 8080)。
|
||||
// 由 --dart-define=PANGOLIN_API_URL 注入。
|
||||
// TODO(联调临时): 默认值改成测试节点,避免 release 构建漏传 dart-define;发版前改回 localhost 或正式控制面域名。
|
||||
const String kApiBaseUrl = String.fromEnvironment(
|
||||
'PANGOLIN_API_URL',
|
||||
defaultValue: 'http://localhost:8080',
|
||||
defaultValue: 'http://103.119.13.48:8080',
|
||||
);
|
||||
|
||||
@@ -99,15 +99,20 @@ class AuthApi {
|
||||
|
||||
Future<http.Response> _post(String path, Map<String, dynamic> body) async {
|
||||
final uri = Uri.parse('$baseUrl$path');
|
||||
print('>>>AUTHLOG POST $uri (baseUrl=$baseUrl) 发起...');
|
||||
final sw = Stopwatch()..start();
|
||||
try {
|
||||
return await _client
|
||||
final resp = await _client
|
||||
.post(
|
||||
uri,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(body),
|
||||
)
|
||||
.timeout(const Duration(seconds: 15));
|
||||
print('>>>AUTHLOG POST $uri -> HTTP ${resp.statusCode} (${sw.elapsedMilliseconds}ms)');
|
||||
return resp;
|
||||
} on Exception catch (e) {
|
||||
print('>>>AUTHLOG POST $uri 失败 (${sw.elapsedMilliseconds}ms): ${e.runtimeType}: $e');
|
||||
throw AuthApiException(
|
||||
statusCode: -1,
|
||||
messageZh: '网络请求失败,请检查连接后重试',
|
||||
|
||||
@@ -12,6 +12,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../bridge/vpn_bridge.dart';
|
||||
import '../bridge/vpn_bridge_provider.dart';
|
||||
import '../l10n/app_text.dart';
|
||||
import '../services/api_config.dart';
|
||||
import '../services/connect_api.dart';
|
||||
import 'app_providers.dart';
|
||||
import 'auth_provider.dart';
|
||||
@@ -25,12 +26,7 @@ const _kDeviceId = String.fromEnvironment(
|
||||
defaultValue: 'mac-001',
|
||||
);
|
||||
|
||||
// ── API base URL ─────────────────────────────────────────────────
|
||||
|
||||
const _kApiUrl = String.fromEnvironment(
|
||||
'PANGOLIN_API_URL',
|
||||
defaultValue: 'http://localhost:8080',
|
||||
);
|
||||
// API base URL 统一用 api_config.dart 的 kApiBaseUrl(单一来源,勿再重复声明)。
|
||||
|
||||
// ── 连接阶段枚举 ──────────────────────────────────────────────────
|
||||
|
||||
@@ -103,7 +99,6 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
Future<void> _connect() async {
|
||||
state = const ConnectionState(phase: VpnPhase.connecting);
|
||||
|
||||
final token = _ref.read(authProvider).accessToken ?? '';
|
||||
final node = _ref.read(effectiveNodeProvider);
|
||||
final zh = _ref.read(localeProvider) == AppLang.zh;
|
||||
|
||||
@@ -119,14 +114,7 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
}
|
||||
|
||||
try {
|
||||
_api?.dispose();
|
||||
_api = ConnectApi(baseUrl: _kApiUrl, authToken: token);
|
||||
final configJson = await _api!.fetchConfig(
|
||||
nodeId: node.uuid,
|
||||
deviceId: _kDeviceId,
|
||||
// smartRoute 偏好 → 国内分流(#5):国内 IP/域名直连,不走隧道。
|
||||
splitCN: _ref.read(settingsProvider).smartRoute,
|
||||
);
|
||||
final configJson = await _fetchConfigWithRefresh(node.uuid);
|
||||
// bridge.start() 不阻塞至连接建立;on 状态由 statusStream 回调驱动。
|
||||
await _bridge.start(configJson);
|
||||
} on ConnectApiException catch (e) {
|
||||
@@ -142,6 +130,33 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 取配置;access token 过期(401)时用 refresh token 续期后**重试一次**。
|
||||
/// 续期失败(refresh 也过期 / 被拒)由 authProvider.refresh() 触发登出 → UI 回登录页。
|
||||
Future<String> _fetchConfigWithRefresh(String nodeUuid) async {
|
||||
Future<String> doFetch() {
|
||||
final token = _ref.read(authProvider).accessToken ?? '';
|
||||
_api?.dispose();
|
||||
_api = ConnectApi(baseUrl: kApiBaseUrl, authToken: token);
|
||||
return _api!.fetchConfig(
|
||||
nodeId: nodeUuid,
|
||||
deviceId: _kDeviceId,
|
||||
// smartRoute 偏好 → 国内分流(#5):国内 IP/域名直连,不走隧道。
|
||||
splitCN: _ref.read(settingsProvider).smartRoute,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
return await doFetch();
|
||||
} on ConnectApiException catch (e) {
|
||||
if (e.statusCode == 401) {
|
||||
// token 过期 → 续期后重试一次;续期成功则用新 token 再取。
|
||||
final ok = await _ref.read(authProvider.notifier).refresh();
|
||||
if (ok) return await doFetch();
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disconnect() async {
|
||||
_stopElapsed();
|
||||
try {
|
||||
|
||||
@@ -8,17 +8,14 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../l10n/app_text.dart';
|
||||
import '../pangolin_theme.dart';
|
||||
import '../services/api_config.dart';
|
||||
import '../services/auth_api.dart';
|
||||
import '../state/auth_provider.dart';
|
||||
import 'pangolin_button.dart';
|
||||
import 'pangolin_icons.dart';
|
||||
import 'pangolin_logo.dart';
|
||||
|
||||
// API base URL(由 --dart-define 注入)
|
||||
const _kApiUrl = String.fromEnvironment(
|
||||
'PANGOLIN_API_URL',
|
||||
defaultValue: 'http://localhost:8080',
|
||||
);
|
||||
// API base URL 统一用 api_config.dart 的 kApiBaseUrl(单一来源,勿再重复声明)。
|
||||
|
||||
const _easeOut = Cubic(0.22, 1, 0.36, 1);
|
||||
|
||||
@@ -55,7 +52,7 @@ class _AuthScreenState extends ConsumerState<AuthScreen>
|
||||
duration: const Duration(milliseconds: 620),
|
||||
);
|
||||
|
||||
late final AuthApi _api = AuthApi(baseUrl: _kApiUrl);
|
||||
late final AuthApi _api = AuthApi(baseUrl: kApiBaseUrl);
|
||||
|
||||
bool get _emailValid => RegExp(r'\S+@\S+\.\S+').hasMatch(_email.text);
|
||||
|
||||
|
||||
@@ -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?
|
||||
@@ -24,40 +26,48 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
override func startTunnel(options: [String: NSObject]?,
|
||||
completionHandler: @escaping (Error?) -> Void) {
|
||||
log.info("startTunnel")
|
||||
do {
|
||||
let configContent = try resolveConfig(options)
|
||||
// libbox 启动必须放后台队列:startOrReloadService 会同步回调 openTun →
|
||||
// setTunnelNetworkSettings,其完成回调要在 provider 队列上投递;若在 provider
|
||||
// 队列(NE 调 startTunnel 所在队列)同步跑 startOrReloadService 会三方死锁。
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
guard let self else { return }
|
||||
do {
|
||||
let configContent = try self.resolveConfig(options)
|
||||
|
||||
guard let base = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
||||
throw simpleError("no app group container")
|
||||
guard let base = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
||||
throw simpleError("no app group container")
|
||||
}
|
||||
let work = base.appendingPathComponent("work", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
|
||||
|
||||
let setup = LibboxSetupOptions()
|
||||
setup.basePath = base.path
|
||||
setup.workingPath = work.path
|
||||
setup.tempPath = NSTemporaryDirectory()
|
||||
var setupErr: NSError?
|
||||
LibboxSetup(setup, &setupErr)
|
||||
if let setupErr { throw setupErr }
|
||||
|
||||
let platform = PangolinPlatformInterface(provider: self)
|
||||
self.platform = platform
|
||||
|
||||
var newErr: NSError?
|
||||
guard let server = LibboxNewCommandServer(self, platform, &newErr) else {
|
||||
throw newErr ?? simpleError("LibboxNewCommandServer returned nil")
|
||||
}
|
||||
try server.start()
|
||||
// 必须传非空 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, privacy: .public)")
|
||||
completionHandler(error)
|
||||
}
|
||||
let work = base.appendingPathComponent("work", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
|
||||
|
||||
let setup = LibboxSetupOptions()
|
||||
setup.basePath = base.path
|
||||
setup.workingPath = work.path
|
||||
setup.tempPath = NSTemporaryDirectory()
|
||||
var setupErr: NSError?
|
||||
LibboxSetup(setup, &setupErr)
|
||||
if let setupErr { throw setupErr }
|
||||
|
||||
let platform = PangolinPlatformInterface(provider: self)
|
||||
self.platform = platform
|
||||
|
||||
var newErr: NSError?
|
||||
guard let server = LibboxNewCommandServer(self, platform, &newErr) else {
|
||||
throw newErr ?? simpleError("LibboxNewCommandServer returned nil")
|
||||
}
|
||||
try server.start()
|
||||
try server.startOrReloadService(configContent, options: nil)
|
||||
self.commandServer = server
|
||||
|
||||
log.info("startTunnel: service started")
|
||||
completionHandler(nil)
|
||||
} catch {
|
||||
log.error("startTunnel failed: \(error.localizedDescription)")
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +106,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
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) }
|
||||
@@ -170,6 +180,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 +195,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()
|
||||
|
||||
@@ -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 = 13;
|
||||
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 = 13;
|
||||
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 = 13;
|
||||
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 = 13;
|
||||
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 = 13;
|
||||
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 = 13;
|
||||
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>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+13
@@ -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: 完成"
|
||||
Reference in New Issue
Block a user