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( 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( 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 }