Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
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 {
|
||||
await vpn.disconnectAndWait()
|
||||
currentNode = nil
|
||||
message = "正在断开,系统将自动恢复原网络"
|
||||
return
|
||||
}
|
||||
guard let profile,
|
||||
let route = profile.routeModes.first(where: { $0.id == selectedRouteID })
|
||||
else {
|
||||
errorMessage = "没有可用的代理模式。"
|
||||
return
|
||||
}
|
||||
if route.id == "direct" {
|
||||
await vpn.disconnectAndWait()
|
||||
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))
|
||||
|
||||
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
|
||||
let configJSON = try response.configJSONString()
|
||||
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
|
||||
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
|
||||
}
|
||||
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let pinnedGatewayIPv4 = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let remoteAddress: String
|
||||
if let pinnedGatewayIPv4, NetworkAddress.isPublicIPv4(pinnedGatewayIPv4) {
|
||||
remoteAddress = pinnedGatewayIPv4
|
||||
} else {
|
||||
let hostToResolve = (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
|
||||
remoteAddress = try await api.resolvePublicIPv4(host: hostToResolve)
|
||||
}
|
||||
currentNode = response.node
|
||||
message = "正在连接 \(response.node.displayName)(第 \(attempt) 次验证)…"
|
||||
try await vpn.connect(
|
||||
configJSON: configJSON,
|
||||
resolvedRemoteAddress: remoteAddress,
|
||||
node: response.node,
|
||||
route: route
|
||||
)
|
||||
try await api.verifyProxyEgress()
|
||||
guard vpn.status == .connected else {
|
||||
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在切换备用节点。")
|
||||
}
|
||||
message = "已连接 \(response.node.displayName),出口验证通过"
|
||||
return
|
||||
} catch {
|
||||
lastError = error
|
||||
let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil)
|
||||
currentNode = nil
|
||||
await vpn.disconnectAndWait()
|
||||
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 = "所有可用节点均未通过验证,已恢复本地网络"
|
||||
}
|
||||
|
||||
func logout() async {
|
||||
guard !busy else { return }
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
await vpn.disconnectAndWait()
|
||||
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 {
|
||||
await vpn.disconnectAndWait()
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
UCVLColors.background.ignoresSafeArea()
|
||||
if let profile = state.profile {
|
||||
DashboardView(profile: profile)
|
||||
} else {
|
||||
LoginView()
|
||||
}
|
||||
}
|
||||
.tint(UCVLColors.royal)
|
||||
.alert("提示", isPresented: Binding(
|
||||
get: { !state.errorMessage.isEmpty },
|
||||
set: { if !$0 { state.errorMessage = "" } }
|
||||
)) {
|
||||
Button("确定", role: .cancel) { state.errorMessage = "" }
|
||||
} message: {
|
||||
Text(state.errorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct BrandHeader: View {
|
||||
var compact = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: compact ? 8 : 16) {
|
||||
Image("UCVLLogo")
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: compact ? 84 : 132, height: compact ? 84 : 132)
|
||||
.accessibilityLabel("优创未来 Logo")
|
||||
Text("优创⁺纵横家")
|
||||
.font(compact ? .title2.bold() : .largeTitle.bold())
|
||||
.foregroundStyle(.white)
|
||||
Text("优创未来安全网络")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(UCVLColors.sky)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct LoginView: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
@State private var identifier = SecureStore.lastLogin
|
||||
@State private var password = ""
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 28) {
|
||||
BrandHeader()
|
||||
.padding(.top, 34)
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Text("公司统一账号登录")
|
||||
.font(.title2.bold())
|
||||
.foregroundStyle(UCVLColors.navy)
|
||||
TextField("用户名或邮箱", text: $identifier)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
.keyboardType(.emailAddress)
|
||||
.textContentType(.username)
|
||||
.ucvlField()
|
||||
SecureField("密码", text: $password)
|
||||
.textContentType(.password)
|
||||
.ucvlField()
|
||||
.onSubmit { Task { await state.login(identifier: identifier, password: password) } }
|
||||
Button {
|
||||
Task {
|
||||
await state.login(identifier: identifier, password: password)
|
||||
if state.profile != nil { password = "" }
|
||||
}
|
||||
} label: {
|
||||
HStack {
|
||||
if state.busy { ProgressView().tint(.white) }
|
||||
Text(state.busy ? "正在登录…" : "安全登录").fontWeight(.semibold)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 14)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(state.busy)
|
||||
Text("账号停用后,设备授权与线路将自动失效。")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
HStack {
|
||||
Text("还没有账号?")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
Link("注册新用户", destination: URL(string: "https://vpn.toplc.cn/register/")!)
|
||||
.font(.footnote.weight(.semibold))
|
||||
}
|
||||
}
|
||||
.padding(24)
|
||||
.background(.white, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
|
||||
.shadow(color: .black.opacity(0.14), radius: 24, y: 12)
|
||||
.frame(maxWidth: 540)
|
||||
Text("vpn.toplc.cn · © 2026 UCVL")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(UCVLColors.sky)
|
||||
.padding(.bottom, 30)
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DashboardView: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
let profile: ClientProfile
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 18) {
|
||||
HStack(spacing: 16) {
|
||||
BrandHeader(compact: true)
|
||||
Spacer()
|
||||
VStack(alignment: .trailing, spacing: 4) {
|
||||
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
|
||||
.font(.headline)
|
||||
.foregroundStyle(.white)
|
||||
Text("\(profile.email) · \(profile.identityType == "employee" ? "内部员工" : "外部联系人")")
|
||||
.font(.caption)
|
||||
.foregroundStyle(UCVLColors.sky)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
|
||||
StatusCard()
|
||||
|
||||
UCVLCard(title: "工作节点与代理模式", systemImage: "point.3.connected.trianglepath.dotted") {
|
||||
VStack(spacing: 14) {
|
||||
HStack {
|
||||
Text("当前工作节点")
|
||||
Spacer()
|
||||
Text(state.currentNode?.displayName ?? "由 vpn-ai 自动选择")
|
||||
.foregroundStyle(state.currentNode == nil ? .secondary : UCVLColors.royal)
|
||||
.multilineTextAlignment(.trailing)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Text("代理模式")
|
||||
Spacer()
|
||||
Picker("代理模式", selection: $state.selectedRouteID) {
|
||||
ForEach(profile.routeModes) { route in Text(route.name).tag(route.id) }
|
||||
}
|
||||
.pickerStyle(.menu)
|
||||
.disabled(state.vpn.isConnected || state.busy)
|
||||
}
|
||||
Button {
|
||||
Task { await state.toggleConnection() }
|
||||
} label: {
|
||||
HStack {
|
||||
if state.busy { ProgressView().tint(.white) }
|
||||
Image(systemName: state.vpn.isConnected ? "stop.fill" : "bolt.shield.fill")
|
||||
Text(state.vpn.isConnected ? "断开连接" : "连接")
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 12)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(state.vpn.isConnected ? UCVLColors.navy : UCVLColors.royal)
|
||||
.disabled(state.busy || profile.nodes.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
UsageCard(subscription: profile.subscription)
|
||||
|
||||
HStack(spacing: 12) {
|
||||
Button { Task { await state.refresh() } } label: {
|
||||
Label("刷新", systemImage: "arrow.clockwise")
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(state.busy)
|
||||
Button(role: .destructive) { Task { await state.logout() } } label: {
|
||||
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(state.busy)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 760)
|
||||
.padding(.horizontal, 18)
|
||||
.padding(.vertical, 18)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct StatusCard: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
|
||||
var body: some View {
|
||||
UCVLCard(title: "连接状态", systemImage: "network.badge.shield.half.filled") {
|
||||
HStack(spacing: 14) {
|
||||
Circle()
|
||||
.fill(state.statusIsActive ? Color.green : Color.gray)
|
||||
.frame(width: 13, height: 13)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(state.statusTitle).font(.title3.bold())
|
||||
Text(state.message.isEmpty ? "点击连接,vpn-ai 将自动选择并验证工作节点" : state.message)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct UsageCard: View {
|
||||
let subscription: SubscriptionProfile
|
||||
|
||||
private var fraction: Double {
|
||||
guard subscription.trafficLimitBytes > 0 else { return 0 }
|
||||
return min(1, max(0, Double(subscription.usedBytes) / Double(subscription.trafficLimitBytes)))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
UCVLCard(title: "本期流量", systemImage: "chart.bar.fill") {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Text(format(subscription.usedBytes))
|
||||
Spacer()
|
||||
Text(subscription.trafficLimitBytes > 0 ? format(subscription.trafficLimitBytes) : "不限流量")
|
||||
.foregroundStyle(UCVLColors.royal)
|
||||
}
|
||||
ProgressView(value: fraction)
|
||||
.tint(UCVLColors.royal)
|
||||
Text("套餐:\(subscription.plan) · 设备上限 \(subscription.deviceLimit) 台\(expiryText)")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var expiryText: String {
|
||||
guard let expiresAt = subscription.expiresAt else { return " · 长期有效" }
|
||||
return " · 到期 \(String(expiresAt.prefix(10)))"
|
||||
}
|
||||
|
||||
private func format(_ value: Int64) -> String {
|
||||
ByteCountFormatter.string(fromByteCount: value, countStyle: .file)
|
||||
}
|
||||
}
|
||||
|
||||
private struct UCVLCard<Content: View>: View {
|
||||
let title: String
|
||||
let systemImage: String
|
||||
let content: Content
|
||||
|
||||
init(title: String, systemImage: String, @ViewBuilder content: () -> Content) {
|
||||
self.title = title
|
||||
self.systemImage = systemImage
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Label(title, systemImage: systemImage)
|
||||
.font(.headline)
|
||||
.foregroundStyle(UCVLColors.navy)
|
||||
content
|
||||
}
|
||||
.padding(20)
|
||||
.background(.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
|
||||
.shadow(color: .black.opacity(0.08), radius: 14, y: 7)
|
||||
}
|
||||
}
|
||||
|
||||
private enum UCVLColors {
|
||||
static let navy = Color(red: 0.02, green: 0.10, blue: 0.26)
|
||||
static let royal = Color(red: 0.02, green: 0.39, blue: 0.86)
|
||||
static let sky = Color(red: 0.17, green: 0.73, blue: 0.98)
|
||||
static let background = LinearGradient(
|
||||
colors: [navy, Color(red: 0.03, green: 0.25, blue: 0.48)],
|
||||
startPoint: .topLeading,
|
||||
endPoint: .bottomTrailing
|
||||
)
|
||||
}
|
||||
|
||||
private extension View {
|
||||
func ucvlField() -> some View {
|
||||
self
|
||||
.padding(.horizontal, 14)
|
||||
.frame(height: 52)
|
||||
.background(Color.gray.opacity(0.08), in: RoundedRectangle(cornerRadius: 13))
|
||||
.overlay(RoundedRectangle(cornerRadius: 13).stroke(Color.gray.opacity(0.2)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict/></plist>
|
||||
@@ -0,0 +1,195 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
actor PlatformAPI {
|
||||
static let shared = PlatformAPI()
|
||||
|
||||
private let baseURL = URL(string: "https://vpn.toplc.cn/")!
|
||||
private let session: URLSession
|
||||
private let decoder = JSONDecoder()
|
||||
private let encoder = JSONEncoder()
|
||||
|
||||
init() {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.timeoutIntervalForRequest = 20
|
||||
configuration.timeoutIntervalForResource = 30
|
||||
configuration.waitsForConnectivity = true
|
||||
configuration.httpAdditionalHeaders = [
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "UCVL-Zonghengjia/1.0.2 iOS",
|
||||
]
|
||||
session = URLSession(configuration: configuration)
|
||||
}
|
||||
|
||||
func login(login: String, password: String) async throws -> LoginResponse {
|
||||
let payload: [String: String] = [
|
||||
"login": login,
|
||||
"password": password,
|
||||
"device_id": SecureStore.deviceID(),
|
||||
"device_name": await MainActor.run { UIDevice.current.name },
|
||||
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.2",
|
||||
"platform": "ios",
|
||||
]
|
||||
return try await send(
|
||||
path: "api/v1/client/login/",
|
||||
method: "POST",
|
||||
body: try encoder.encode(payload),
|
||||
token: nil,
|
||||
as: LoginResponse.self
|
||||
)
|
||||
}
|
||||
|
||||
func profile(token: String) async throws -> ClientProfile {
|
||||
let envelope = try await send(
|
||||
path: "api/v1/client/profile/",
|
||||
method: "GET",
|
||||
body: nil,
|
||||
token: token,
|
||||
as: ProfileEnvelope.self
|
||||
)
|
||||
return envelope.profile
|
||||
}
|
||||
|
||||
func config(token: String, route: String, excluding excludedNodes: [String] = []) async throws -> ClientConfigResponse {
|
||||
var components = URLComponents(url: baseURL.appendingPathComponent("api/v1/client/config/"), resolvingAgainstBaseURL: false)!
|
||||
components.queryItems = [
|
||||
URLQueryItem(name: "node", value: "auto"),
|
||||
URLQueryItem(name: "route", value: route),
|
||||
URLQueryItem(name: "new_connection", value: "1"),
|
||||
]
|
||||
if !excludedNodes.isEmpty {
|
||||
components.queryItems?.append(
|
||||
URLQueryItem(name: "exclude", value: excludedNodes.sorted().joined(separator: ","))
|
||||
)
|
||||
}
|
||||
return try await send(url: components.url!, method: "GET", body: nil, token: token, as: ClientConfigResponse.self)
|
||||
}
|
||||
|
||||
func verifyProxyEgress() async throws {
|
||||
let endpoints = [
|
||||
URL(string: "https://api.openai.com/v1/models")!,
|
||||
URL(string: "https://chatgpt.com/api/auth/session")!,
|
||||
]
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.timeoutIntervalForRequest = 12
|
||||
configuration.timeoutIntervalForResource = 15
|
||||
configuration.waitsForConnectivity = false
|
||||
configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
|
||||
let verifier = URLSession(configuration: configuration)
|
||||
defer { verifier.invalidateAndCancel() }
|
||||
|
||||
for endpoint in endpoints {
|
||||
var request = URLRequest(url: endpoint)
|
||||
request.httpMethod = "GET"
|
||||
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
|
||||
do {
|
||||
let (_, response) = try await verifier.data(for: request)
|
||||
if let http = response as? HTTPURLResponse, (200..<500).contains(http.statusCode) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
throw UCVLError.connection("当前节点未通过 OpenAI/ChatGPT 出口验证,正在切换其它节点。")
|
||||
}
|
||||
|
||||
func resolvePublicIPv4(host: String) async throws -> String {
|
||||
if NetworkAddress.isPublicIPv4(host) { return host }
|
||||
// 001/002 是后台节点名称。NPM TCP Stream 依靠 11081/11082 等端口
|
||||
// 分流,不要求每个节点子域名都单独发布 A 记录;解析不到时使用统一入口。
|
||||
let candidateHosts = host == "vpn.toplc.cn" ? [host] : [host, "vpn.toplc.cn"]
|
||||
let resolvers = [
|
||||
"https://dns.alidns.com/resolve",
|
||||
"https://doh.pub/resolve",
|
||||
]
|
||||
|
||||
for candidateHost in candidateHosts {
|
||||
for resolver in resolvers {
|
||||
guard var components = URLComponents(string: resolver) else { continue }
|
||||
components.queryItems = [
|
||||
URLQueryItem(name: "name", value: candidateHost),
|
||||
URLQueryItem(name: "type", value: "A"),
|
||||
]
|
||||
guard let url = components.url else { continue }
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = "GET"
|
||||
request.setValue("application/dns-json", forHTTPHeaderField: "Accept")
|
||||
do {
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse,
|
||||
(200..<300).contains(http.statusCode),
|
||||
let result = try? decoder.decode(DNSResponse.self, from: data)
|
||||
else { continue }
|
||||
if let address = result.answer?
|
||||
.first(where: { $0.type == 1 && NetworkAddress.isPublicIPv4($0.data) })?
|
||||
.data {
|
||||
return address
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
throw UCVLError.connection("无法取得 NPM 入口 vpn.toplc.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
|
||||
}
|
||||
|
||||
func logout(token: String) async {
|
||||
_ = try? await send(
|
||||
path: "api/v1/client/logout/",
|
||||
method: "POST",
|
||||
body: Data(),
|
||||
token: token,
|
||||
as: EmptyResponse.self
|
||||
)
|
||||
}
|
||||
|
||||
private func send<T: Decodable>(
|
||||
path: String,
|
||||
method: String,
|
||||
body: Data?,
|
||||
token: String?,
|
||||
as type: T.Type
|
||||
) async throws -> T {
|
||||
try await send(url: baseURL.appendingPathComponent(path), method: method, body: body, token: token, as: type)
|
||||
}
|
||||
|
||||
private func send<T: Decodable>(
|
||||
url: URL,
|
||||
method: String,
|
||||
body: Data?,
|
||||
token: String?,
|
||||
as type: T.Type
|
||||
) async throws -> T {
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
request.httpBody = body
|
||||
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
||||
if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
|
||||
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else { throw UCVLError.invalidResponse }
|
||||
guard (200..<300).contains(http.statusCode) else {
|
||||
let message = (try? decoder.decode(APIErrorEnvelope.self, from: data).error)
|
||||
?? "服务暂时不可用(\(http.statusCode))。"
|
||||
throw UCVLError.api(status: http.statusCode, message: message)
|
||||
}
|
||||
guard let value = try? decoder.decode(type, from: data) else { throw UCVLError.invalidResponse }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
private struct EmptyResponse: Decodable {}
|
||||
|
||||
private struct DNSResponse: Decodable {
|
||||
let answer: [DNSAnswer]?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case answer = "Answer"
|
||||
}
|
||||
}
|
||||
|
||||
private struct DNSAnswer: Decodable {
|
||||
let type: Int
|
||||
let data: String
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
enum SecureStore {
|
||||
private static let service = "cn.toplc.zonghengjia.credentials"
|
||||
private static let tokenAccount = "access-token"
|
||||
private static let deviceAccount = "device-id"
|
||||
private static let lastLoginKey = "ucvl.last-login"
|
||||
|
||||
static var lastLogin: String {
|
||||
get { UserDefaults.standard.string(forKey: lastLoginKey) ?? "" }
|
||||
set { UserDefaults.standard.set(newValue, forKey: lastLoginKey) }
|
||||
}
|
||||
|
||||
static func token() -> String? {
|
||||
read(account: tokenAccount)
|
||||
}
|
||||
|
||||
static func saveToken(_ token: String) throws {
|
||||
try write(token, account: tokenAccount)
|
||||
}
|
||||
|
||||
static func clearToken() {
|
||||
delete(account: tokenAccount)
|
||||
}
|
||||
|
||||
static func deviceID() -> String {
|
||||
if let stored = read(account: deviceAccount), !stored.isEmpty {
|
||||
return stored
|
||||
}
|
||||
let created = "ios-\(UUID().uuidString.lowercased())"
|
||||
try? write(created, account: deviceAccount)
|
||||
return created
|
||||
}
|
||||
|
||||
private static func read(account: String) -> String? {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||
kSecReturnData as String: true,
|
||||
]
|
||||
var result: CFTypeRef?
|
||||
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
|
||||
let data = result as? Data
|
||||
else { return nil }
|
||||
return String(data: data, encoding: .utf8)
|
||||
}
|
||||
|
||||
private static func write(_ value: String, account: String) throws {
|
||||
guard let data = value.data(using: .utf8) else { return }
|
||||
delete(account: account)
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
||||
kSecValueData as String: data,
|
||||
]
|
||||
let status = SecItemAdd(query as CFDictionary, nil)
|
||||
guard status == errSecSuccess else {
|
||||
throw UCVLError.invalidConfiguration("无法安全保存登录授权(\(status))。")
|
||||
}
|
||||
}
|
||||
|
||||
private static func delete(account: String) {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
]
|
||||
SecItemDelete(query as CFDictionary)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.developer.networking.networkextension</key>
|
||||
<array>
|
||||
<string>packet-tunnel-provider</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,14 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct UCVLZonghengjiaApp: App {
|
||||
@StateObject private var state = AppState()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
.environmentObject(state)
|
||||
.task { await state.start() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
|
||||
@MainActor
|
||||
final class VPNController: ObservableObject {
|
||||
@Published private(set) var status: NEVPNStatus = .invalid
|
||||
@Published private(set) var activeNodeSlug: String?
|
||||
private var manager: NETunnelProviderManager?
|
||||
private var observer: NSObjectProtocol?
|
||||
|
||||
init() {
|
||||
observer = NotificationCenter.default.addObserver(
|
||||
forName: .NEVPNStatusDidChange,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] note in
|
||||
guard let connection = note.object as? NEVPNConnection else { return }
|
||||
Task { @MainActor in self?.status = connection.status }
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let observer { NotificationCenter.default.removeObserver(observer) }
|
||||
}
|
||||
|
||||
func restore() async {
|
||||
do {
|
||||
manager = try await loadManager()
|
||||
status = manager?.connection.status ?? .invalid
|
||||
if isConnected,
|
||||
let tunnelProtocol = manager?.protocolConfiguration as? NETunnelProviderProtocol,
|
||||
let configuration = tunnelProtocol.providerConfiguration {
|
||||
activeNodeSlug = configuration["nodeSlug"] as? String
|
||||
}
|
||||
} catch {
|
||||
status = .invalid
|
||||
activeNodeSlug = nil
|
||||
}
|
||||
}
|
||||
|
||||
func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws {
|
||||
guard route.id != "direct" else {
|
||||
disconnect()
|
||||
return
|
||||
}
|
||||
let selected = try await loadManager()
|
||||
let tunnelProtocol = NETunnelProviderProtocol()
|
||||
tunnelProtocol.providerBundleIdentifier = "cn.toplc.zonghengjia.PacketTunnel"
|
||||
tunnelProtocol.serverAddress = node.name
|
||||
tunnelProtocol.disconnectOnSleep = false
|
||||
tunnelProtocol.includeAllNetworks = false
|
||||
tunnelProtocol.providerConfiguration = [
|
||||
"configJSON": configJSON,
|
||||
"resolvedRemoteAddress": resolvedRemoteAddress,
|
||||
"nodeSlug": node.slug,
|
||||
"nodeName": node.name,
|
||||
"routeMode": route.id,
|
||||
]
|
||||
|
||||
selected.localizedDescription = "优创⁺纵横家"
|
||||
selected.protocolConfiguration = tunnelProtocol
|
||||
selected.isEnabled = true
|
||||
try await save(selected)
|
||||
try await reload(selected)
|
||||
manager = selected
|
||||
activeNodeSlug = node.slug
|
||||
do {
|
||||
try selected.connection.startVPNTunnel()
|
||||
} catch {
|
||||
activeNodeSlug = nil
|
||||
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。")
|
||||
}
|
||||
do {
|
||||
try await waitUntilConnected(selected.connection)
|
||||
} catch {
|
||||
selected.connection.stopVPNTunnel()
|
||||
activeNodeSlug = nil
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
manager?.connection.stopVPNTunnel()
|
||||
activeNodeSlug = nil
|
||||
}
|
||||
|
||||
func disconnectAndWait(timeout: TimeInterval = 8) async {
|
||||
disconnect()
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
while Date() < deadline {
|
||||
let current = manager?.connection.status ?? .disconnected
|
||||
status = current
|
||||
if current == .disconnected || current == .invalid { return }
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
var isConnected: Bool {
|
||||
status == .connected || status == .connecting || status == .reasserting
|
||||
}
|
||||
|
||||
private func waitUntilConnected(_ connection: NEVPNConnection, timeout: TimeInterval = 25) async throws {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
var observedTransition = false
|
||||
while Date() < deadline {
|
||||
let current = connection.status
|
||||
status = current
|
||||
switch current {
|
||||
case .connected:
|
||||
return
|
||||
case .connecting, .reasserting:
|
||||
observedTransition = true
|
||||
case .disconnected where observedTransition:
|
||||
throw UCVLError.connection("Apple 系统 VPN 扩展启动后退出。")
|
||||
case .invalid:
|
||||
throw UCVLError.connection("Apple 系统 VPN 配置无效。")
|
||||
default:
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 250_000_000)
|
||||
}
|
||||
throw UCVLError.connection("Apple 系统 VPN 连接超时。")
|
||||
}
|
||||
|
||||
private func loadManager() async throws -> NETunnelProviderManager {
|
||||
let managers: [NETunnelProviderManager] = try await withCheckedThrowingContinuation { continuation in
|
||||
NETunnelProviderManager.loadAllFromPreferences { managers, error in
|
||||
if let error { continuation.resume(throwing: error) }
|
||||
else { continuation.resume(returning: managers ?? []) }
|
||||
}
|
||||
}
|
||||
if let existing = managers.first(where: {
|
||||
($0.protocolConfiguration as? NETunnelProviderProtocol)?.providerBundleIdentifier == "cn.toplc.zonghengjia.PacketTunnel"
|
||||
}) {
|
||||
return existing
|
||||
}
|
||||
return NETunnelProviderManager()
|
||||
}
|
||||
|
||||
private func save(_ manager: NETunnelProviderManager) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
||||
manager.saveToPreferences { error in
|
||||
if let error { continuation.resume(throwing: error) }
|
||||
else { continuation.resume(returning: ()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func reload(_ manager: NETunnelProviderManager) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
||||
manager.loadFromPreferences { error in
|
||||
if let error { continuation.resume(throwing: error) }
|
||||
else { continuation.resume(returning: ()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user