Files

203 lines
7.8 KiB
Swift
Raw Permalink Normal View History

import Foundation
import UIKit
actor PlatformAPI {
static let shared = PlatformAPI()
private let baseURL = URL(string: "https://vpn.ucvl.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.4 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.4",
"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 configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForRequest = 12
configuration.timeoutIntervalForResource = 15
configuration.waitsForConnectivity = false
configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let verifier = URLSession(configuration: configuration)
defer { verifier.invalidateAndCancel() }
let reachable = await withTaskGroup(of: Bool.self) { probes in
for endpoint in TunnelConfigurationBuilder.egressProbeURLs {
probes.addTask {
var request = URLRequest(url: endpoint)
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
do {
let (_, response) = try await verifier.data(for: request)
guard let response = response as? HTTPURLResponse else { return false }
return response.url?.scheme == "https" && response.url?.host == endpoint.host
&& (100...599).contains(response.statusCode)
} catch {
return false
}
}
}
for await success in probes where success {
probes.cancelAll()
return true
}
return false
}
try Task.checkCancellation()
guard reachable else {
throw UCVLError.connection("当前入口未通过代理 HTTPS 出口验证。")
}
}
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.ucvl.cn" ? [host] : [host, "vpn.ucvl.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.ucvl.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
}