Files

109 lines
4.4 KiB
Swift
Raw Permalink Normal View History

import Foundation
enum TunnelConfigurationBuilder {
static let egressProbeURLs = [
URL(string: "https://cp.cloudflare.com/generate_204")!,
URL(string: "https://api.openai.com/v1/models")!,
URL(string: "https://chatgpt.com/api/auth/session")!,
]
static func makeConfiguration(
rawJSON: String,
tunnelFileDescriptor: Int32,
assetDirectory: String,
resolvedRemoteAddress: String? = nil
) throws -> String {
guard let data = rawJSON.data(using: .utf8),
var root = try JSONSerialization.jsonObject(with: data) as? [String: Any]
else {
throw UCVLError.invalidConfiguration("线路配置不是有效的 Xray JSON。")
}
var environment = root["env"] as? [String: Any] ?? [:]
environment["xray.tun.fd"] = String(tunnelFileDescriptor)
environment["xray.location.asset"] = assetDirectory
root["env"] = environment
root["metrics"] = NSNull()
if let resolvedRemoteAddress {
try replaceProxyRemoteAddress(in: &root, with: resolvedRemoteAddress)
}
try addTransportRules(to: &root)
root["inbounds"] = [[
"tag": "tun-in",
"port": 0,
"protocol": "tun",
"settings": [
"name": "ucvl-tun",
"mtu": 1500,
"userLevel": 0,
],
"sniffing": [
"enabled": true,
"destOverride": ["http", "tls", "quic"],
"routeOnly": true,
],
]]
guard JSONSerialization.isValidJSONObject(root) else {
throw UCVLError.invalidConfiguration("无法生成 Apple Packet Tunnel 配置。")
}
let output = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])
return String(decoding: output, as: UTF8.self)
}
private static func addTransportRules(to root: inout [String: Any]) throws {
guard let outbounds = root["outbounds"] as? [[String: Any]],
outbounds.contains(where: { $0["tag"] as? String == "proxy" }),
var routing = root["routing"] as? [String: Any],
var rules = routing["rules"] as? [[String: Any]]
else {
throw UCVLError.invalidConfiguration("线路配置缺少用于代理出口验证的路由。")
}
// A request to any probe host must use the authorized outbound even
// when the platform's smart routing rules would otherwise send it direct.
rules.insert([
"type": "field",
"domain": egressProbeURLs.compactMap { $0.host }.map { "full:" + $0 },
"port": "443",
"outboundTag": "proxy",
], at: 0)
if outbounds.contains(where: { $0["tag"] as? String == "direct" }) {
rules.insert([
"type": "field",
"domain": [#"regexp:(?i)(^|\.)(tailscale\.com|ts\.net)\.?$"#],
"outboundTag": "direct",
], at: 0)
}
routing["rules"] = rules
root["routing"] = routing
}
static func remoteAddress(from rawJSON: String) -> String? {
guard let data = rawJSON.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let outbounds = root["outbounds"] as? [[String: Any]],
let proxy = outbounds.first(where: { ($0["tag"] as? String) == "proxy" }),
let settings = proxy["settings"] as? [String: Any],
let vnext = settings["vnext"] as? [[String: Any]],
let address = vnext.first?["address"] as? String,
!address.isEmpty
else { return nil }
return address
}
private static func replaceProxyRemoteAddress(in root: inout [String: Any], with address: String) throws {
guard var outbounds = root["outbounds"] as? [[String: Any]],
let proxyIndex = outbounds.firstIndex(where: { ($0["tag"] as? String) == "proxy" }),
var settings = outbounds[proxyIndex]["settings"] as? [String: Any],
var vnext = settings["vnext"] as? [[String: Any]],
!vnext.isEmpty
else {
throw UCVLError.invalidConfiguration("线路配置缺少代理服务器地址。")
}
vnext[0]["address"] = address
settings["vnext"] = vnext
outbounds[proxyIndex]["settings"] = settings
root["outbounds"] = outbounds
}
}