2026-10-11 23:23:20 +00:00
|
|
|
import Combine
|
|
|
|
|
import Foundation
|
|
|
|
|
import NetworkExtension
|
|
|
|
|
|
|
|
|
|
@MainActor
|
|
|
|
|
final class AppState: ObservableObject {
|
|
|
|
|
@Published var profile: ClientProfile?
|
|
|
|
|
@Published var currentNode: VPNNode?
|
|
|
|
|
@Published var selectedRouteID = "smart"
|
|
|
|
|
@Published var busy = false
|
|
|
|
|
@Published var message = ""
|
|
|
|
|
@Published var errorMessage = ""
|
|
|
|
|
|
|
|
|
|
let vpn = VPNController()
|
|
|
|
|
private let api = PlatformAPI.shared
|
|
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
|
|
|
|
|
|
init() {
|
|
|
|
|
vpn.$status
|
|
|
|
|
.sink { [weak self] _ in self?.objectWillChange.send() }
|
|
|
|
|
.store(in: &cancellables)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func start() async {
|
|
|
|
|
await vpn.restore()
|
|
|
|
|
guard let token = SecureStore.token() else { return }
|
|
|
|
|
await refresh(token: token, initial: true)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func login(identifier: String, password: String) async {
|
|
|
|
|
guard !busy else { return }
|
|
|
|
|
let identifier = identifier.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
|
|
guard !identifier.isEmpty, !password.isEmpty else {
|
|
|
|
|
errorMessage = "请输入用户名(或邮箱)和密码。"
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
busy = true
|
|
|
|
|
message = "正在安全登录…"
|
|
|
|
|
errorMessage = ""
|
|
|
|
|
defer { busy = false }
|
|
|
|
|
do {
|
|
|
|
|
let response = try await api.login(login: identifier, password: password)
|
|
|
|
|
try SecureStore.saveToken(response.accessToken)
|
|
|
|
|
SecureStore.lastLogin = identifier
|
|
|
|
|
apply(response.profile)
|
|
|
|
|
message = "账号和线路已同步"
|
|
|
|
|
} catch {
|
|
|
|
|
errorMessage = friendly(error)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func refresh() async {
|
|
|
|
|
guard !busy else { return }
|
|
|
|
|
guard let token = SecureStore.token() else {
|
|
|
|
|
logoutLocal()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
await refresh(token: token, initial: false)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func toggleConnection() async {
|
|
|
|
|
guard !busy else { return }
|
|
|
|
|
// Acquire before the first await, including disconnect/direct branches.
|
|
|
|
|
// A second tap must not start another operation during network restoration.
|
|
|
|
|
busy = true
|
|
|
|
|
defer { busy = false }
|
|
|
|
|
if vpn.isConnected {
|
2026-10-27 02:46:08 +00:00
|
|
|
do {
|
|
|
|
|
try await vpn.disconnectAndWait()
|
|
|
|
|
currentNode = nil
|
|
|
|
|
message = "已断开,系统已撤销本应用的 VPN 连接"
|
|
|
|
|
} catch { errorMessage = friendly(error) }
|
2026-10-11 23:23:20 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
guard let profile,
|
|
|
|
|
let route = profile.routeModes.first(where: { $0.id == selectedRouteID })
|
|
|
|
|
else {
|
|
|
|
|
errorMessage = "没有可用的代理模式。"
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if route.id == "direct" {
|
2026-10-27 02:46:08 +00:00
|
|
|
do { try await vpn.disconnectAndWait() }
|
|
|
|
|
catch { errorMessage = friendly(error); return }
|
2026-10-11 23:23:20 +00:00
|
|
|
currentNode = nil
|
|
|
|
|
message = "当前为本地直连,不经过 VPN 节点"
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
guard let token = SecureStore.token() else {
|
|
|
|
|
logoutLocal()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
message = "vpn-ai 正在选择工作节点…"
|
|
|
|
|
errorMessage = ""
|
|
|
|
|
var excludedNodes: [String] = []
|
|
|
|
|
var lastError: Error = UCVLError.connection("没有可用节点。")
|
|
|
|
|
let maximumAttempts = max(1, min(profile.nodes.count, 3))
|
2026-10-27 02:46:08 +00:00
|
|
|
// One explicit connect owns this state across all assigned nodes.
|
|
|
|
|
// No timers or system restore path may promote a public connection.
|
|
|
|
|
var transport = ProxyTransportSession()
|
2026-10-11 23:23:20 +00:00
|
|
|
|
|
|
|
|
for attempt in 1...maximumAttempts {
|
|
|
|
|
var attemptedNode: VPNNode?
|
|
|
|
|
do {
|
|
|
|
|
let response = try await api.config(token: token, route: route.id, excluding: excludedNodes)
|
|
|
|
|
attemptedNode = response.node
|
|
|
|
|
currentNode = response.node
|
|
|
|
|
message = "正在连接 \(response.node.displayName)(第 \(attempt) 次验证)…"
|
2026-10-27 02:46:08 +00:00
|
|
|
try await connectAssigned(response, route: route, transport: &transport)
|
2026-10-11 23:23:20 +00:00
|
|
|
return
|
|
|
|
|
} catch {
|
|
|
|
|
lastError = error
|
|
|
|
|
let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil)
|
|
|
|
|
currentNode = nil
|
2026-10-27 02:46:08 +00:00
|
|
|
do { try await vpn.disconnectAndWait() }
|
|
|
|
|
catch {
|
|
|
|
|
errorMessage = friendly(error)
|
|
|
|
|
message = "系统尚未完成断开,已停止切换线路"
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-10-11 23:23:20 +00:00
|
|
|
if decision == .revokeAuthorization {
|
|
|
|
|
logoutLocal()
|
|
|
|
|
errorMessage = friendly(error)
|
|
|
|
|
message = "账号授权已失效,已停止连接,请重新登录"
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if decision == .stop {
|
|
|
|
|
errorMessage = friendly(error)
|
|
|
|
|
message = "连接未完成;未将本机设置或平台请求错误记为全部节点故障"
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if let slug = attemptedNode?.slug, !excludedNodes.contains(slug) {
|
|
|
|
|
excludedNodes.append(slug)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
errorMessage = friendly(lastError)
|
|
|
|
|
message = "所有可用节点均未通过验证,已恢复本地网络"
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-27 02:46:08 +00:00
|
|
|
private func connectAssigned(
|
|
|
|
|
_ response: ClientConfigResponse, route: RouteMode, transport: inout ProxyTransportSession
|
|
|
|
|
) async throws {
|
|
|
|
|
let configJSON = try response.configJSONString()
|
|
|
|
|
if !transport.domainOnly,
|
|
|
|
|
let endpoint = ProxyTransportPolicy.authorizedInternalEndpoint(response: response) {
|
2026-11-15 14:04:42 +00:00
|
|
|
let reachable = await InternalIPProbe.isReachable(endpoint.address, port: endpoint.port)
|
2026-10-27 02:46:08 +00:00
|
|
|
try Task.checkCancellation()
|
|
|
|
|
if reachable {
|
|
|
|
|
message = "正在通过内部 IP 连接 \(response.node.displayName)…"
|
|
|
|
|
do {
|
|
|
|
|
try await vpn.connect(
|
|
|
|
|
configJSON: configJSON, resolvedRemoteAddress: endpoint.address,
|
|
|
|
|
node: response.node, route: route, internalEndpoint: endpoint,
|
|
|
|
|
configContract: response.configContract, connectionScope: response.connectionScope
|
|
|
|
|
)
|
|
|
|
|
try await verifyActiveEgress()
|
|
|
|
|
message = "已连接 \(response.node.displayName) · 内部 IP,出口验证通过"
|
|
|
|
|
return
|
|
|
|
|
} catch {
|
|
|
|
|
guard ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: true) == .retryNode else {
|
|
|
|
|
throw error
|
|
|
|
|
}
|
|
|
|
|
try await vpn.disconnectAndWait()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
transport.commitPublicFallback()
|
|
|
|
|
try Task.checkCancellation()
|
|
|
|
|
// Resolve only when public transport is actually needed. DNS failure
|
|
|
|
|
// must not prevent an otherwise usable authorized internal endpoint.
|
|
|
|
|
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
|
|
|
|
|
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
|
|
|
|
|
}
|
|
|
|
|
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
|
|
let pinnedAddress = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
|
|
let publicAddress: String
|
|
|
|
|
if let pinnedAddress, NetworkAddress.isPublicIPv4(pinnedAddress) {
|
|
|
|
|
publicAddress = pinnedAddress
|
|
|
|
|
} else {
|
|
|
|
|
publicAddress = try await api.resolvePublicIPv4(
|
|
|
|
|
host: (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
message = "正在通过域名入口连接 \(response.node.displayName)…"
|
|
|
|
|
try await vpn.connect(
|
|
|
|
|
configJSON: configJSON, resolvedRemoteAddress: publicAddress, node: response.node, route: route
|
|
|
|
|
)
|
|
|
|
|
try await verifyActiveEgress()
|
|
|
|
|
message = "已连接 \(response.node.displayName) · 域名入口,本次连接保持不切换"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func verifyActiveEgress() async throws {
|
|
|
|
|
try Task.checkCancellation()
|
|
|
|
|
try await api.verifyProxyEgress()
|
|
|
|
|
try Task.checkCancellation()
|
|
|
|
|
guard vpn.status == .connected else {
|
|
|
|
|
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在尝试备用入口。")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-11 23:23:20 +00:00
|
|
|
func logout() async {
|
|
|
|
|
guard !busy else { return }
|
|
|
|
|
busy = true
|
|
|
|
|
defer { busy = false }
|
2026-10-27 02:46:08 +00:00
|
|
|
do { try await vpn.disconnectAndWait() }
|
|
|
|
|
catch { errorMessage = friendly(error); return }
|
2026-10-11 23:23:20 +00:00
|
|
|
if let token = SecureStore.token() {
|
|
|
|
|
await api.logout(token: token)
|
|
|
|
|
}
|
|
|
|
|
logoutLocal()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var statusTitle: String {
|
|
|
|
|
switch vpn.status {
|
|
|
|
|
case .connected: return "已安全连接"
|
|
|
|
|
case .connecting: return "正在连接"
|
|
|
|
|
case .disconnecting: return "正在断开"
|
|
|
|
|
case .reasserting: return "正在恢复连接"
|
|
|
|
|
case .disconnected: return selectedRouteID == "direct" ? "本地直连" : "未连接"
|
|
|
|
|
case .invalid: return "未配置"
|
|
|
|
|
@unknown default: return "状态更新中"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var statusIsActive: Bool { vpn.status == .connected }
|
|
|
|
|
|
|
|
|
|
private func refresh(token: String, initial: Bool) async {
|
|
|
|
|
busy = true
|
|
|
|
|
message = "正在同步账号和线路…"
|
|
|
|
|
defer { busy = false }
|
|
|
|
|
do {
|
|
|
|
|
apply(try await api.profile(token: token))
|
|
|
|
|
message = "账号和线路已同步"
|
|
|
|
|
} catch UCVLError.api(let status, let message) where status == 401 || status == 403 {
|
2026-10-27 02:46:08 +00:00
|
|
|
do { try await vpn.disconnectAndWait() }
|
|
|
|
|
catch { errorMessage = friendly(error) }
|
2026-10-11 23:23:20 +00:00
|
|
|
SecureStore.clearToken()
|
|
|
|
|
profile = nil
|
|
|
|
|
errorMessage = message
|
|
|
|
|
} catch {
|
|
|
|
|
errorMessage = friendly(error)
|
|
|
|
|
if initial { profile = nil }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func apply(_ value: ClientProfile) {
|
|
|
|
|
profile = value
|
|
|
|
|
if vpn.isConnected, let slug = vpn.activeNodeSlug {
|
|
|
|
|
currentNode = value.nodes.first(where: { $0.slug == slug })
|
|
|
|
|
}
|
|
|
|
|
if !value.routeModes.contains(where: { $0.id == selectedRouteID }) {
|
|
|
|
|
selectedRouteID = value.routeModes.first?.id ?? "smart"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func logoutLocal() {
|
|
|
|
|
SecureStore.clearToken()
|
|
|
|
|
profile = nil
|
|
|
|
|
currentNode = nil
|
|
|
|
|
selectedRouteID = "smart"
|
|
|
|
|
message = ""
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func friendly(_ error: Error) -> String {
|
|
|
|
|
if let localized = error as? LocalizedError, let description = localized.errorDescription {
|
|
|
|
|
return description
|
|
|
|
|
}
|
|
|
|
|
if (error as NSError).code == NSURLErrorTimedOut {
|
|
|
|
|
return "连接平台超时,请稍后重试。"
|
|
|
|
|
}
|
|
|
|
|
return error.localizedDescription
|
|
|
|
|
}
|
|
|
|
|
}
|