Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
* text=auto
|
||||
*.swift text eol=lf
|
||||
*.sh text eol=lf
|
||||
*.py text eol=lf
|
||||
*.md text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.plist text eol=lf
|
||||
*.json text eol=lf
|
||||
*.dat binary
|
||||
*.png binary
|
||||
@@ -0,0 +1,18 @@
|
||||
name: iOS Xcode acceptance
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
xcode-acceptance:
|
||||
runs-on: macos
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install XcodeGen
|
||||
run: brew install xcodegen
|
||||
- name: Restore verified libXray
|
||||
run: ./Scripts/fetch-libxray.sh
|
||||
- name: Generate project and run tests
|
||||
env:
|
||||
DEVELOPMENT_TEAM: ${{ secrets.APPLE_DEVELOPMENT_TEAM }}
|
||||
run: ./Scripts/verify-and-archive.sh
|
||||
@@ -0,0 +1,15 @@
|
||||
name: iOS source audit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, "codex/**"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Audit source, entitlements and secrets
|
||||
run: python3 Scripts/source-audit.py
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
DerivedData/
|
||||
build/
|
||||
*.xcarchive
|
||||
*.ipa
|
||||
*.mobileprovision
|
||||
*.p12
|
||||
*.cer
|
||||
xcuserdata/
|
||||
.DS_Store
|
||||
Vendor/libxray-apple-cgo-v26.7.28.zip
|
||||
Vendor/libxray-apple-cgo-v26.7.28/
|
||||
Vendor/libXray-source-v26.7.28/
|
||||
Vendor/Xray-core-source/
|
||||
Vendor/LibXray.xcframework/
|
||||
BuildArtifacts/
|
||||
@@ -0,0 +1,50 @@
|
||||
# 优创⁺纵横家 iPhone / iPad 验收记录
|
||||
|
||||
## 2026-09-09:1.0.2 源码候选(非 IPA)
|
||||
|
||||
工程 `MARKETING_VERSION` 为 1.0.2,README 已与之同步,源码审计新增文档版本一致性检查并通过。现有错误分类源码区分平台/本机授权/节点失败及 401/403 授权失效;XCTest 已编写,仍未运行。这次只修正文档和静态校验,没有新的 iOS 二进制构建、签名、安装包、真机连接或公开发布。未取得 Mac/Xcode/开发者团队条件,不能把 Windows 测试当成苹果验收。
|
||||
|
||||
## 2026-09-04:1.0.1 历史记录
|
||||
|
||||
日期:2026-09-04
|
||||
|
||||
结论:`SOURCE_CANDIDATE`。源码与依赖完整性静态检查通过;由于没有 macOS/Xcode、Apple Developer Team、Network Extension Provisioning Profile 和 iPhone 真机,本记录不代表可安装 IPA 或真机网络验收通过。
|
||||
|
||||
## 已通过
|
||||
|
||||
- 主应用与 Packet Tunnel Extension 使用独立 Bundle ID。
|
||||
- 两个目标声明 `packet-tunnel-provider` entitlement。
|
||||
- 登录令牌保存在 Keychain,源代码没有公司账号、密码、令牌、证书或私钥。
|
||||
- 后台以 `node=auto&new_connection=1` 分配节点,客户端隐藏节点选择,只显示实际工作节点。
|
||||
- 最多三次失败切换;每次失败把已失败节点加入 `exclude`,断开并等待系统 VPN 恢复后再试。
|
||||
- 001/002 节点由 NPM TCP Stream 端口分流;节点子域无 A 记录时,主应用通过阿里/腾讯 DoH 获取统一入口 `vpn.toplc.cn` 的真实公网 IPv4,拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网、Tailscale 和其它保留地址。
|
||||
- Packet Tunnel 在接管默认路由前排除该公网 IPv4,并将运行时 VLESS 地址改为同一 IP;Reality SNI 保持不变。
|
||||
- 支持后台 `config_contract=2` 统一 NPM 网关字段,同时兼容未返回该字段的旧后台。
|
||||
- VPN 连接状态变为 connected 后,再访问 OpenAI / ChatGPT HTTPS 入口;两个入口均失败才判定当前节点不可用。
|
||||
- 出口探测返回后再次确认系统 VPN 仍处于 connected,避免隧道已退出时出现假成功。
|
||||
- libXray v26.7.28 本地官方归档 SHA256:`07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`。
|
||||
- 注册入口、套餐与流量、AI 智能代理/全局代理/本地直连、退出账号与网络恢复流程均已在源码中接通。
|
||||
- Windows 侧对 NPM 公网入口 `192.0.2.1` 复核:`vpn.toplc.cn` HTTPS 健康接口正常,TCP `11081`、`11082`、`11083` 均可建立连接。该检查只证明 NPM 入口与端口在线,不替代 VLESS Reality 握手或 iPhone 真机出口验收。
|
||||
|
||||
## 必须在 Mac 和真机完成后才能发布 IPA
|
||||
|
||||
1. 使用当前 Xcode 编译主应用、扩展和单元测试,修复所有 warning/error。
|
||||
2. 为两个 App ID 开启 Network Extensions / Packet Tunnel Provider,并使用同一 Team 签名。
|
||||
3. 在至少一台真实 iPhone 上确认系统 VPN 授权、登录、连接、OpenAI/ChatGPT 出口、节点失败切换、断开恢复、锁屏/唤醒和换 Wi‑Fi/蜂窝网络。
|
||||
4. 验证强制结束、设备重启、账号停用、套餐到期和无可用节点时不会留下失效默认路由。
|
||||
5. 选择 Ad Hoc、MDM/Custom App 或符合资质的 Enterprise 内部分发,导出并安装最终 IPA;记录 IPA SHA256。
|
||||
|
||||
## 本地静态复核
|
||||
|
||||
在 Windows 工作区执行:
|
||||
|
||||
```powershell
|
||||
py -3 .\Scripts\source-audit.py
|
||||
```
|
||||
|
||||
只有输出 `"result": "PASS"` 才允许把本次源码候选版上传 Git。该命令明确不替代 Xcode 编译、苹果签名和 iPhone 真机测试。
|
||||
# 2026-09-08 补充:1.0.2 源码候选
|
||||
|
||||
新增连接错误分类:控制接口未返回节点、系统授权取消、本地配置错误不再循环记成全部节点故障;401/403 直接撤销会话,只有已分配节点的传输失败才尝试其它节点。阻止重复触发登录、刷新、连接和退出操作。新增 4 项 XCTest 源码。
|
||||
|
||||
本机仅执行 `Scripts/source-audit.py` 并通过;没有 Swift/Xcode 编译、XCTest 执行、签名、IPA 或 iPhone 真机验收。仍缺 Mac/Xcode、开发者团队和设备条件,不能称为已完成安装版。旧记录保留如下。
|
||||
@@ -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: ()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,10 @@
|
||||
# 第三方许可及 MIT 范围
|
||||
|
||||
顶层及 Windows、后台、iOS 中 MIT 仅适用于 UCVL 有权授权的自有程序代码/文档与原创山水插画。第三方代码、库、数据、工具、商标、公司名称与 Logo 另行适用原权利及许可证,不因聚合仓库的 MIT 而被重新许可;此发布不授予公司商标权或服务访问权。
|
||||
|
||||
- Windows:windows/THIRD_PARTY_NOTICES.md 原文保留;windows/licenses/ 包含固定发行 payload 中的 Xray MPL-2.0、Wintun 预编译二进制再分发许可、NSIS 许可。这里不分发这些第三方可执行文件。
|
||||
- iOS:ios/THIRD_PARTY_NOTICES.md、ios/ThirdParty/libXray-MIT.txt、ios/ThirdParty/Xray-core-MPL-2.0.txt 原文保留。Vendor XCFramework 与未明确来源许可的 Geo 数据未打包。
|
||||
- Android:保留其既有 GPL-3.0 项目及 LGPL/MIT/lwIP/Wintun 等依赖许可,见 android/README.md 链接;不改为 MIT。
|
||||
- 后台:requirements.txt 记录依赖。安装的第三方依赖继续遵循各上游版本许可证,不属于公司 MIT 再许可范围。
|
||||
|
||||
来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。
|
||||
@@ -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,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,171 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
|
||||
final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
private let coreQueue = DispatchQueue(label: "cn.toplc.zonghengjia.xray-core", qos: .userInitiated)
|
||||
|
||||
override func startTunnel(
|
||||
options: [String: NSObject]? = nil,
|
||||
completionHandler: @escaping (Error?) -> Void
|
||||
) {
|
||||
guard let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol,
|
||||
let providerConfiguration = tunnelProtocol.providerConfiguration,
|
||||
let rawJSON = providerConfiguration["configJSON"] as? String
|
||||
else {
|
||||
completionHandler(UCVLError.invalidConfiguration("没有收到线路配置,请返回应用重新连接。"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: rawJSON) else {
|
||||
completionHandler(UCVLError.invalidConfiguration("线路配置缺少节点地址。"))
|
||||
return
|
||||
}
|
||||
|
||||
let providedRemoteAddress = providerConfiguration["resolvedRemoteAddress"] as? String
|
||||
coreQueue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
do {
|
||||
let resolvedRemoteAddress: String
|
||||
if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
|
||||
resolvedRemoteAddress = providedRemoteAddress
|
||||
} else {
|
||||
resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost)
|
||||
}
|
||||
let settings = self.makeNetworkSettings(remoteAddress: resolvedRemoteAddress)
|
||||
self.setTunnelNetworkSettings(settings) { [weak self] error in
|
||||
guard let self else { return }
|
||||
if let error {
|
||||
completionHandler(error)
|
||||
return
|
||||
}
|
||||
self.coreQueue.async {
|
||||
do {
|
||||
guard let tunnelFD = Self.findTunnelFileDescriptor() else {
|
||||
throw UCVLError.invalidConfiguration("无法取得 Apple utun 虚拟网卡。")
|
||||
}
|
||||
guard let geoIP = Bundle.main.url(forResource: "geoip", withExtension: "dat"),
|
||||
Bundle.main.url(forResource: "geosite", withExtension: "dat") != nil
|
||||
else {
|
||||
throw UCVLError.invalidConfiguration("路由规则资源缺失。")
|
||||
}
|
||||
let config = try TunnelConfigurationBuilder.makeConfiguration(
|
||||
rawJSON: rawJSON,
|
||||
tunnelFileDescriptor: tunnelFD,
|
||||
assetDirectory: geoIP.deletingLastPathComponent().path,
|
||||
resolvedRemoteAddress: resolvedRemoteAddress
|
||||
)
|
||||
XrayBridge.stop()
|
||||
try XrayBridge.start(configJSON: config)
|
||||
completionHandler(nil)
|
||||
} catch {
|
||||
XrayBridge.stop()
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func stopTunnel(
|
||||
with reason: NEProviderStopReason,
|
||||
completionHandler: @escaping () -> Void
|
||||
) {
|
||||
coreQueue.async {
|
||||
XrayBridge.stop()
|
||||
completionHandler()
|
||||
}
|
||||
}
|
||||
|
||||
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
|
||||
let response = ["running": XrayBridge.isRunning()]
|
||||
completionHandler?(try? JSONSerialization.data(withJSONObject: response))
|
||||
}
|
||||
|
||||
override func sleep(completionHandler: @escaping () -> Void) {
|
||||
completionHandler()
|
||||
}
|
||||
|
||||
override func wake() {}
|
||||
|
||||
private func makeNetworkSettings(remoteAddress: String) -> NEPacketTunnelNetworkSettings {
|
||||
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress)
|
||||
let ipv4 = NEIPv4Settings(addresses: ["198.18.0.1"], subnetMasks: ["255.255.0.0"])
|
||||
ipv4.includedRoutes = [NEIPv4Route.default()]
|
||||
if Self.isIPv4Address(remoteAddress) {
|
||||
ipv4.excludedRoutes = [NEIPv4Route(destinationAddress: remoteAddress, subnetMask: "255.255.255.255")]
|
||||
}
|
||||
settings.ipv4Settings = ipv4
|
||||
|
||||
let ipv6 = NEIPv6Settings(addresses: ["fd00:7563:766c::1"], networkPrefixLengths: [64])
|
||||
ipv6.includedRoutes = [NEIPv6Route.default()]
|
||||
settings.ipv6Settings = ipv6
|
||||
|
||||
let dns = NEDNSSettings(servers: ["1.1.1.1", "8.8.8.8"])
|
||||
dns.matchDomains = [""]
|
||||
settings.dnsSettings = dns
|
||||
settings.mtu = 1500
|
||||
return settings
|
||||
}
|
||||
|
||||
private static func findTunnelFileDescriptor() -> Int32? {
|
||||
for fileDescriptor in Int32(0)...Int32(1024) {
|
||||
var interfaceName = [CChar](repeating: 0, count: Int(IFNAMSIZ))
|
||||
var length = socklen_t(interfaceName.count)
|
||||
let result = interfaceName.withUnsafeMutableBytes { pointer in
|
||||
getsockopt(
|
||||
fileDescriptor,
|
||||
SYSPROTO_CONTROL,
|
||||
2,
|
||||
pointer.baseAddress,
|
||||
&length
|
||||
)
|
||||
}
|
||||
if result == 0, String(cString: interfaceName).hasPrefix("utun") {
|
||||
return fileDescriptor
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func isIPv4Address(_ value: String) -> Bool {
|
||||
var address = in_addr()
|
||||
return value.withCString { inet_pton(AF_INET, $0, &address) } == 1
|
||||
}
|
||||
|
||||
private static func resolveIPv4Address(_ host: String) throws -> String {
|
||||
if NetworkAddress.isPublicIPv4(host) { return host }
|
||||
|
||||
var hints = addrinfo()
|
||||
hints.ai_flags = AI_ADDRCONFIG
|
||||
hints.ai_family = AF_INET
|
||||
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
|
||||
hints.ai_protocol = IPPROTO_TCP
|
||||
var results: UnsafeMutablePointer<addrinfo>?
|
||||
let status = host.withCString { getaddrinfo($0, nil, &hints, &results) }
|
||||
guard status == 0, let first = results else {
|
||||
let reason = status == 0 ? "没有 IPv4 地址" : String(cString: gai_strerror(status))
|
||||
throw UCVLError.invalidConfiguration("无法解析节点域名 \(host):\(reason)。")
|
||||
}
|
||||
defer { freeaddrinfo(first) }
|
||||
|
||||
var cursor: UnsafeMutablePointer<addrinfo>? = first
|
||||
while let current = cursor {
|
||||
cursor = current.pointee.ai_next
|
||||
guard current.pointee.ai_family == AF_INET,
|
||||
let socketAddress = current.pointee.ai_addr
|
||||
else { continue }
|
||||
var address = socketAddress.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
|
||||
$0.pointee.sin_addr
|
||||
}
|
||||
var text = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
|
||||
guard inet_ntop(AF_INET, &address, &text, socklen_t(INET_ADDRSTRLEN)) != nil else { continue }
|
||||
let value = String(cString: text)
|
||||
if NetworkAddress.isPublicIPv4(value) { return value }
|
||||
}
|
||||
throw UCVLError.invalidConfiguration("节点域名 \(host) 没有可用的 IPv4 地址。")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
import LibXray
|
||||
|
||||
enum XrayBridge {
|
||||
static func start(configJSON: String) throws {
|
||||
_ = try invoke(method: "runXrayFromJson", payload: ["configJSON": configJSON])
|
||||
}
|
||||
|
||||
static func stop() {
|
||||
_ = try? invoke(method: "stopXray", payload: nil)
|
||||
}
|
||||
|
||||
static func isRunning() -> Bool {
|
||||
guard let data = try? invoke(method: "getXrayState", payload: nil) else { return false }
|
||||
return data["running"] as? Bool ?? false
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private static func invoke(method: String, payload: [String: Any]?) throws -> [String: Any] {
|
||||
var request: [String: Any] = ["apiVersion": 1, "method": method]
|
||||
if let payload { request["payload"] = payload }
|
||||
let requestData = try JSONSerialization.data(withJSONObject: request, options: [])
|
||||
let requestText = String(decoding: requestData, as: UTF8.self)
|
||||
guard let requestPointer = requestText.withCString({ strdup($0) }) else {
|
||||
throw UCVLError.invalidConfiguration("无法调用 Xray 核心。")
|
||||
}
|
||||
defer { free(requestPointer) }
|
||||
guard let responsePointer = CGoInvoke(requestPointer) else {
|
||||
throw UCVLError.invalidConfiguration("Xray 核心没有返回结果。")
|
||||
}
|
||||
defer { CGoFree(responsePointer) }
|
||||
|
||||
let responseText = String(cString: responsePointer)
|
||||
guard let responseData = responseText.data(using: .utf8),
|
||||
let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any]
|
||||
else {
|
||||
throw UCVLError.invalidConfiguration("Xray 核心返回格式错误。")
|
||||
}
|
||||
guard response["success"] as? Bool == true else {
|
||||
let error = response["error"] as? String ?? "Xray 核心启动失败。"
|
||||
throw UCVLError.invalidConfiguration(error)
|
||||
}
|
||||
return response["data"] as? [String: Any] ?? [:]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# 纵横家 iPhone / iPad 1.0.2 源码候选版(开源)
|
||||
|
||||
Swift 主应用与 Apple Packet Tunnel 扩展源码,版本 `1.0.2`,最低 iOS 15。仅为源码快照和静态结构检查;没有可安装 IPA,未执行 Xcode 编译、XCTest、Apple 签名或 iPhone/iPad 真机 VPN 验收。macOS 客户端不在本目录范围。
|
||||
|
||||
## 构建前提
|
||||
|
||||
需要 Mac、Xcode、XcodeGen,以及获授权的 Apple Developer Team、Network Extension 权限和 Provisioning Profile。本快照通过 Git API 创建,脚本执行位不保留;在 Mac 的本目录先运行 `chmod +x Scripts/*.sh`,再运行 `./Scripts/generate-project.sh` 生成工程。`./Scripts/verify-and-archive.sh` 提供测试/归档入口,不代表这里已执行通过。公开示例端点需替换成自己的配置。
|
||||
|
||||
Scripts/fetch-libxray.sh 从原固定官方版本 v26.7.28 下载 Apple cgo XCFramework,并核验其源码中固定的 SHA-256;Vendor/ 二进制不在本仓库。下载脚本仅恢复 libXray,不能恢复 Geo 数据,也不提供 Apple 签名材料。
|
||||
|
||||
## 未打包的 Geo 数据
|
||||
|
||||
Resources/Geo/geoip.dat 与 geosite.dat 未纳入公开导出:旧源码未完整记录数据项目/版本及许可。project.yml 仍保留 Resources/Geo 的资源接入位置,但构建前须自行从可信官方数据源取得对应数据、核验下载校验值与许可,并放入该目录。此仓库不猜测或声称存在已验证的 Geo 下载 URL/hash,不能把 libXray 归档校验值当作 Geo 校验值。
|
||||
|
||||
公司自有代码适用 LICENSE.md/MIT;ThirdParty/ 和 THIRD_PARTY_NOTICES.md 保留原始第三方许可证与说明。公司商标/Logo 不在 MIT 授权范围。公司公开 API 域名只为源码兼容保留,不授予服务访问权限。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 443 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 632 KiB |
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "AppIcon-UCVL-opaque.png",
|
||||
"idiom" : "universal",
|
||||
"platform" : "ios",
|
||||
"size" : "1024x1024"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0.169",
|
||||
"green" : "0.102",
|
||||
"red" : "0.020"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "UCVLLogo.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 632 KiB |
@@ -0,0 +1 @@
|
||||
Geo 数据未打包。请按 ../../README.md 的资源说明取得并核验自己的合法数据;libXray 下载脚本不恢复 Geo 数据。
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
root_dir=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
vendor_dir="$root_dir/Vendor"
|
||||
destination="$vendor_dir/LibXray.xcframework"
|
||||
archive_url="https://github.com/XTLS/libXray/releases/download/v26.7.28/libxray-apple-cgo.zip"
|
||||
expected_sha256="07f7ed7697277930e1c517755855950f594f41435b0dfc5917a66eea6278aeb9"
|
||||
|
||||
if [ -d "$destination" ]; then
|
||||
echo "LibXray.xcframework 已存在。"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
work_dir=$(mktemp -d "${TMPDIR:-/tmp}/ucvl-libxray.XXXXXX")
|
||||
trap 'rm -rf "$work_dir"' EXIT INT TERM
|
||||
archive_path="$work_dir/libxray-apple-cgo.zip"
|
||||
|
||||
curl --fail --location --retry 3 --output "$archive_path" "$archive_url"
|
||||
actual_sha256=$(shasum -a 256 "$archive_path" | awk '{print tolower($1)}')
|
||||
if [ "$actual_sha256" != "$expected_sha256" ]; then
|
||||
echo "libXray SHA256 校验失败。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
unzip -q "$archive_path" -d "$work_dir/unpacked"
|
||||
framework_path=$(find "$work_dir/unpacked" -type d -name LibXray.xcframework -print -quit)
|
||||
if [ -z "$framework_path" ]; then
|
||||
echo "官方压缩包中没有 LibXray.xcframework。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$vendor_dir"
|
||||
mv "$framework_path" "$destination"
|
||||
echo "已安装并校验 libXray v26.7.28。"
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
command -v xcodegen >/dev/null 2>&1 || {
|
||||
echo "请先安装 XcodeGen:brew install xcodegen" >&2
|
||||
exit 1
|
||||
}
|
||||
xcodegen generate
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import plistlib
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EXPECTED = [
|
||||
"project.yml",
|
||||
"App/AppState.swift",
|
||||
"App/ContentView.swift",
|
||||
"App/PlatformAPI.swift",
|
||||
"App/VPNController.swift",
|
||||
"PacketTunnel/PacketTunnelProvider.swift",
|
||||
"PacketTunnel/XrayBridge.swift",
|
||||
"Shared/Models.swift",
|
||||
"Shared/TunnelConfigurationBuilder.swift",
|
||||
"Shared/NetworkAddress.swift",
|
||||
"Tests/TunnelConfigurationBuilderTests.swift",
|
||||
"Tests/ClientConfigResponseTests.swift",
|
||||
"Shared/ConnectionAttemptPolicy.swift",
|
||||
"Tests/ConnectionAttemptPolicyTests.swift",
|
||||
]
|
||||
|
||||
|
||||
def require(condition: bool, message: str) -> None:
|
||||
if not condition:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
for relative in EXPECTED:
|
||||
require((ROOT / relative).is_file(), f"缺少文件:{relative}")
|
||||
|
||||
for relative in ("App/Info.plist", "PacketTunnel/Info.plist", "App/UCVLZonghengjia.entitlements", "PacketTunnel/PacketTunnel.entitlements"):
|
||||
with (ROOT / relative).open("rb") as stream:
|
||||
value = plistlib.load(stream)
|
||||
if relative.endswith("entitlements"):
|
||||
require(
|
||||
"packet-tunnel-provider" in value.get("com.apple.developer.networking.networkextension", []),
|
||||
f"Network Extension 权限缺失:{relative}",
|
||||
)
|
||||
|
||||
project = (ROOT / "project.yml").read_text(encoding="utf-8")
|
||||
version_match = re.search(r'MARKETING_VERSION:\s*"(\d+\.\d+\.\d+)"', project)
|
||||
require(version_match is not None, "缺少规范的源码版本号")
|
||||
source_version = version_match.group(1)
|
||||
readme = (ROOT / "README.md").read_text(encoding="utf-8")
|
||||
require(f"{source_version} 源码候选版" in readme.splitlines()[0]
|
||||
and f"版本 `{source_version}`" in readme, "README 与工程版本不一致")
|
||||
require("cn.toplc.zonghengjia.PacketTunnel" in project, "Packet Tunnel Bundle ID 缺失")
|
||||
require('iOS: "15.0"' in project, "iOS 最低版本与验收基线不一致")
|
||||
|
||||
app_state = (ROOT / "App/AppState.swift").read_text(encoding="utf-8")
|
||||
api = (ROOT / "App/PlatformAPI.swift").read_text(encoding="utf-8")
|
||||
tunnel = (ROOT / "PacketTunnel/PacketTunnelProvider.swift").read_text(encoding="utf-8")
|
||||
require("selectedNodeID" not in app_state, "客户端仍暴露节点选择")
|
||||
require('URLQueryItem(name: "node", value: "auto")' in api, "未启用后台自动选节点")
|
||||
require("verifyProxyEgress" in api and "verifyProxyEgress" in app_state, "缺少出口验证")
|
||||
require("resolveIPv4Address" in tunnel and "excludedRoutes" in tunnel, "缺少节点域名防回环处理")
|
||||
require("dns.alidns.com/resolve" in api and "doh.pub/resolve" in api, "缺少国内 DoH 真实地址解析")
|
||||
require("NetworkAddress.isPublicIPv4" in api and "NetworkAddress.isPublicIPv4" in tunnel, "未拒绝 Fake-IP/内网地址")
|
||||
require("response.gateway" in app_state and "configContract" in (ROOT / "Shared/Models.swift").read_text(encoding="utf-8"), "未兼容后台网关契约")
|
||||
require("vpn.status == .connected" in app_state, "出口验证后未复核系统 VPN 状态")
|
||||
require("ConnectionAttemptPolicy.decide" in app_state and "attemptedNode" in app_state,
|
||||
"未区分控制面、本地授权与节点出口故障")
|
||||
|
||||
secret_pattern = re.compile(
|
||||
r"(?i)(password|passwd|private[_-]?key)['\"]?\s*[:=]\s*['\"][^'\"]{4,}['\"]"
|
||||
)
|
||||
findings: list[str] = []
|
||||
for path in ROOT.rglob("*"):
|
||||
if not path.is_file() or any(part in {".git", "Vendor", "BuildArtifacts"} for part in path.parts):
|
||||
continue
|
||||
if path.suffix.lower() not in {".swift", ".yml", ".yaml", ".json", ".md", ".sh", ".py", ".plist"}:
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8", errors="ignore")
|
||||
if secret_pattern.search(text):
|
||||
findings.append(str(path.relative_to(ROOT)))
|
||||
require(not findings, "疑似明文凭据:" + ", ".join(findings))
|
||||
|
||||
vendor_archive = ROOT / "Vendor/libxray-apple-cgo-v26.7.28.zip"
|
||||
vendor_result = "not-present"
|
||||
if vendor_archive.is_file():
|
||||
digest = hashlib.sha256(vendor_archive.read_bytes()).hexdigest()
|
||||
require(digest == "07f7ed7697277930e1c517755855950f594f41435b0dfc5917a66eea6278aeb9", "libXray 本地归档 SHA256 不匹配")
|
||||
vendor_result = digest
|
||||
|
||||
geo_files = [ROOT / "Resources/Geo/geoip.dat", ROOT / "Resources/Geo/geosite.dat"]
|
||||
geo_present = [path.is_file() for path in geo_files]
|
||||
require(all(geo_present) or not any(geo_present), "Geo data must be supplied as a complete pair")
|
||||
geo_status = "present-not-verified-by-source-audit" if all(geo_present) else "not-packaged"
|
||||
|
||||
report = {
|
||||
"result": "PASS",
|
||||
"source_version": source_version,
|
||||
"geo_data_status": geo_status,
|
||||
"geo_data_required_before_build_and_tunnel": True,
|
||||
"documentation_version_matches": True,
|
||||
"scope": "Source audit only; no Xcode compile, signing, IPA export, or iPhone tunnel acceptance",
|
||||
"automatic_node_selection": True,
|
||||
"egress_verification": ["api.openai.com", "chatgpt.com"],
|
||||
"domain_loop_prevention": True,
|
||||
"gateway_contract": 2,
|
||||
"legacy_backend_compatible": True,
|
||||
"network_extension_entitlement": True,
|
||||
"libxray_archive_sha256": vendor_result,
|
||||
}
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as exc:
|
||||
print(json.dumps({"result": "FAIL", "error": str(exc)}, ensure_ascii=False, indent=2), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
test -n "${DEVELOPMENT_TEAM:-}" || {
|
||||
echo "请设置 DEVELOPMENT_TEAM(Apple Developer Team ID)。" >&2
|
||||
exit 1
|
||||
}
|
||||
./Scripts/fetch-libxray.sh
|
||||
./Scripts/generate-project.sh
|
||||
xcodebuild \
|
||||
-project UCVLZonghengjia.xcodeproj \
|
||||
-scheme UCVLZonghengjia \
|
||||
-destination 'platform=iOS Simulator,name=iPhone 16 Pro' \
|
||||
DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
|
||||
test
|
||||
xcodebuild \
|
||||
-project UCVLZonghengjia.xcodeproj \
|
||||
-scheme UCVLZonghengjia \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \
|
||||
DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
|
||||
archive
|
||||
|
||||
if [ -n "${EXPORT_OPTIONS_PLIST:-}" ]; then
|
||||
test -f "$EXPORT_OPTIONS_PLIST" || {
|
||||
echo "EXPORT_OPTIONS_PLIST 指定的文件不存在。" >&2
|
||||
exit 1
|
||||
}
|
||||
xcodebuild \
|
||||
-exportArchive \
|
||||
-archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \
|
||||
-exportPath build/export \
|
||||
-exportOptionsPlist "$EXPORT_OPTIONS_PLIST"
|
||||
fi
|
||||
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
|
||||
enum ConnectionAttemptDecision: Equatable {
|
||||
case retryNode
|
||||
case stop
|
||||
case revokeAuthorization
|
||||
}
|
||||
|
||||
enum ConnectionAttemptPolicy {
|
||||
static func decide(error: Error, hasAssignedNode: Bool) -> ConnectionAttemptDecision {
|
||||
if error is CancellationError { return .stop }
|
||||
if let failure = error as? UCVLError {
|
||||
switch failure {
|
||||
case .api(let status, _):
|
||||
return status == 401 || status == 403 ? .revokeAuthorization : .stop
|
||||
case .vpnPermission, .invalidConfiguration, .invalidResponse:
|
||||
// Permission, malformed local configuration and control-plane
|
||||
// failures must not mark every otherwise healthy node as failed.
|
||||
return .stop
|
||||
case .connection:
|
||||
break
|
||||
}
|
||||
}
|
||||
return hasAssignedNode ? .retryNode : .stop
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import Foundation
|
||||
|
||||
enum JSONValue: Codable, Sendable, Equatable {
|
||||
case string(String)
|
||||
case integer(Int64)
|
||||
case number(Double)
|
||||
case object([String: JSONValue])
|
||||
case array([JSONValue])
|
||||
case bool(Bool)
|
||||
case null
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if container.decodeNil() {
|
||||
self = .null
|
||||
} else if let value = try? container.decode(Bool.self) {
|
||||
self = .bool(value)
|
||||
} else if let value = try? container.decode(Int64.self) {
|
||||
self = .integer(value)
|
||||
} else if let value = try? container.decode(Double.self) {
|
||||
self = .number(value)
|
||||
} else if let value = try? container.decode(String.self) {
|
||||
self = .string(value)
|
||||
} else if let value = try? container.decode([String: JSONValue].self) {
|
||||
self = .object(value)
|
||||
} else if let value = try? container.decode([JSONValue].self) {
|
||||
self = .array(value)
|
||||
} else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON value")
|
||||
}
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch self {
|
||||
case .string(let value): try container.encode(value)
|
||||
case .integer(let value): try container.encode(value)
|
||||
case .number(let value): try container.encode(value)
|
||||
case .object(let value): try container.encode(value)
|
||||
case .array(let value): try container.encode(value)
|
||||
case .bool(let value): try container.encode(value)
|
||||
case .null: try container.encodeNil()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoginResponse: Decodable, Sendable {
|
||||
let accessToken: String
|
||||
let expiresAt: String
|
||||
let profile: ClientProfile
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case accessToken = "access_token"
|
||||
case expiresAt = "expires_at"
|
||||
case profile
|
||||
}
|
||||
}
|
||||
|
||||
struct ProfileEnvelope: Decodable, Sendable {
|
||||
let profile: ClientProfile
|
||||
}
|
||||
|
||||
struct ClientProfile: Decodable, Sendable {
|
||||
let username: String
|
||||
let displayName: String
|
||||
let email: String
|
||||
let identityType: String
|
||||
let subscription: SubscriptionProfile
|
||||
let nodes: [VPNNode]
|
||||
let routeModes: [RouteMode]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case username
|
||||
case displayName = "display_name"
|
||||
case email
|
||||
case identityType = "identity_type"
|
||||
case subscription
|
||||
case nodes
|
||||
case routeModes = "route_modes"
|
||||
}
|
||||
}
|
||||
|
||||
struct SubscriptionProfile: Decodable, Sendable {
|
||||
let status: String
|
||||
let plan: String
|
||||
let usedBytes: Int64
|
||||
let trafficLimitBytes: Int64
|
||||
let expiresAt: String?
|
||||
let deviceLimit: Int
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case status
|
||||
case plan
|
||||
case usedBytes = "used_bytes"
|
||||
case trafficLimitBytes = "traffic_limit_bytes"
|
||||
case expiresAt = "expires_at"
|
||||
case deviceLimit = "device_limit"
|
||||
}
|
||||
}
|
||||
|
||||
struct VPNNode: Decodable, Identifiable, Hashable, Sendable {
|
||||
let slug: String
|
||||
let name: String
|
||||
let region: String
|
||||
let status: String
|
||||
|
||||
var id: String { slug }
|
||||
var displayName: String { region.isEmpty ? name : "\(name) · \(region)" }
|
||||
}
|
||||
|
||||
struct RouteMode: Decodable, Identifiable, Hashable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
}
|
||||
|
||||
struct ClientConfigResponse: Decodable, Sendable {
|
||||
struct Gateway: Decodable, Sendable {
|
||||
let host: String
|
||||
let ipv4: String?
|
||||
}
|
||||
|
||||
let configContract: Int?
|
||||
let gateway: Gateway?
|
||||
let node: VPNNode
|
||||
let routeMode: String
|
||||
let config: [String: JSONValue]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case configContract = "config_contract"
|
||||
case gateway
|
||||
case node
|
||||
case routeMode = "route_mode"
|
||||
case config
|
||||
}
|
||||
|
||||
func configJSONString() throws -> String {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
|
||||
return String(decoding: try encoder.encode(config), as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
struct APIErrorEnvelope: Decodable {
|
||||
let error: String?
|
||||
}
|
||||
|
||||
enum UCVLError: LocalizedError {
|
||||
case api(status: Int, message: String)
|
||||
case invalidResponse
|
||||
case invalidConfiguration(String)
|
||||
case vpnPermission(String)
|
||||
case connection(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .api(_, let message), .invalidConfiguration(let message), .vpnPermission(let message), .connection(let message):
|
||||
return message
|
||||
case .invalidResponse:
|
||||
return "平台返回了无法识别的数据。"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import Foundation
|
||||
|
||||
enum NetworkAddress {
|
||||
static func isPublicIPv4(_ value: String) -> Bool {
|
||||
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4,
|
||||
let a = UInt8(parts[0]),
|
||||
let b = UInt8(parts[1]),
|
||||
let c = UInt8(parts[2]),
|
||||
UInt8(parts[3]) != nil
|
||||
else { return false }
|
||||
|
||||
if a == 0 || a == 10 || a == 127 || a >= 224 { return false }
|
||||
if a == 100 && (64...127).contains(b) { return false }
|
||||
if a == 169 && b == 254 { return false }
|
||||
if a == 172 && (16...31).contains(b) { return false }
|
||||
if a == 192 && b == 168 { return false }
|
||||
if a == 192 && b == 0 && (c == 0 || c == 2) { return false }
|
||||
if a == 198 && (b == 18 || b == 19) { return false }
|
||||
if a == 198 && b == 51 && c == 100 { return false }
|
||||
if a == 203 && b == 0 && c == 113 { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import Foundation
|
||||
|
||||
enum TunnelConfigurationBuilder {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# 第三方软件声明
|
||||
|
||||
## XTLS/libXray
|
||||
|
||||
- 版本:`v26.7.28`
|
||||
- 项目:https://github.com/XTLS/libXray
|
||||
- 许可证:MIT
|
||||
- 修改状态:未修改官方 libXray 源码;客户端链接官方 Apple cgo XCFramework。
|
||||
- 官方发布包 SHA-256:`07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`
|
||||
|
||||
完整许可证见 `ThirdParty/libXray-MIT.txt`。
|
||||
|
||||
## XTLS/Xray-core
|
||||
|
||||
- 项目:https://github.com/XTLS/Xray-core
|
||||
- 对应源码:https://github.com/XTLS/Xray-core/tree/5ca6f4b7d4dc
|
||||
- 许可证:Mozilla Public License 2.0
|
||||
- 用途:由 libXray 静态链接,作为 Packet Tunnel 内的网络核心。
|
||||
- 修改状态:未修改 Xray-core 源码。
|
||||
|
||||
完整许可证见 `ThirdParty/Xray-core-MPL-2.0.txt`。
|
||||
|
||||
## Geo 路由数据
|
||||
|
||||
`geoip.dat` 与 `geosite.dat` 仅用于实现平台下发的中国大陆直连、广告分流和私有地址规则。发布时应继续保留其数据源项目的许可声明。
|
||||
@@ -0,0 +1,21 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class ClientConfigResponseTests: XCTestCase {
|
||||
func testDecodesVersionedGatewayContract() throws {
|
||||
let data = Data(#"{"config_contract":2,"gateway":{"host":"vpn.toplc.cn","ipv4":"192.0.2.1"},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
|
||||
XCTAssertEqual(response.configContract, 2)
|
||||
XCTAssertEqual(response.gateway?.host, "vpn.toplc.cn")
|
||||
XCTAssertEqual(response.gateway?.ipv4, "192.0.2.1")
|
||||
}
|
||||
|
||||
func testOldBackendPayloadRemainsCompatible() throws {
|
||||
let data = Data(#"{"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
|
||||
XCTAssertNil(response.configContract)
|
||||
XCTAssertNil(response.gateway)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class ConnectionAttemptPolicyTests: XCTestCase {
|
||||
func testControlPlaneTimeoutDoesNotBlacklistUnassignedNode() {
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(error: URLError(.timedOut), hasAssignedNode: false), .stop)
|
||||
}
|
||||
|
||||
func testAuthorizationFailureDoesNotCycleNodes() {
|
||||
for status in [401, 403] {
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(
|
||||
error: UCVLError.api(status: status, message: "fixture"), hasAssignedNode: true), .revokeAuthorization)
|
||||
}
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(
|
||||
error: UCVLError.api(status: 503, message: "fixture"), hasAssignedNode: false), .stop)
|
||||
}
|
||||
|
||||
func testPermissionAndConfigurationFailuresAreLocal() {
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.vpnPermission("fixture"), hasAssignedNode: true), .stop)
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.invalidConfiguration("fixture"), hasAssignedNode: true), .stop)
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(error: CancellationError(), hasAssignedNode: true), .stop)
|
||||
}
|
||||
|
||||
func testAssignedNodeTransportFailureCanFailOver() {
|
||||
XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.connection("fixture"), hasAssignedNode: true), .retryNode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class NetworkAddressTests: XCTestCase {
|
||||
func testAcceptsPublicIPv4() {
|
||||
XCTAssertTrue(NetworkAddress.isPublicIPv4("192.0.2.1"))
|
||||
XCTAssertTrue(NetworkAddress.isPublicIPv4("8.216.53.107"))
|
||||
}
|
||||
|
||||
func testRejectsPrivateTailscaleAndFakeIPv4() {
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("127.0.0.1"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("192.168.50.1"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("100.64.0.2"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("198.18.0.119"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.toplc.cn"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class TunnelConfigurationBuilderTests: XCTestCase {
|
||||
func testReplacesDesktopInboundsWithAppleTunnelAndPreservesRealityOutbound() throws {
|
||||
let raw = #"""
|
||||
{
|
||||
"log":{"loglevel":"warning"},
|
||||
"inbounds":[{"tag":"socks-in","protocol":"socks","port":10808}],
|
||||
"outbounds":[
|
||||
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"001.vpn.toplc.cn","port":11081,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","realitySettings":{"serverName":"www.microsoft.com"}}},
|
||||
{"tag":"direct","protocol":"freedom"}
|
||||
],
|
||||
"routing":{"rules":[]}
|
||||
}
|
||||
"""#
|
||||
|
||||
let output = try TunnelConfigurationBuilder.makeConfiguration(
|
||||
rawJSON: raw,
|
||||
tunnelFileDescriptor: 42,
|
||||
assetDirectory: "/app/assets",
|
||||
resolvedRemoteAddress: "192.0.2.1"
|
||||
)
|
||||
let data = try XCTUnwrap(output.data(using: .utf8))
|
||||
let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
let environment = try XCTUnwrap(root["env"] as? [String: String])
|
||||
XCTAssertEqual(environment["xray.tun.fd"], "42")
|
||||
XCTAssertEqual(environment["xray.location.asset"], "/app/assets")
|
||||
|
||||
let inbounds = try XCTUnwrap(root["inbounds"] as? [[String: Any]])
|
||||
XCTAssertEqual(inbounds.count, 1)
|
||||
XCTAssertEqual(inbounds[0]["protocol"] as? String, "tun")
|
||||
|
||||
let outbounds = try XCTUnwrap(root["outbounds"] as? [[String: Any]])
|
||||
XCTAssertEqual(outbounds.first?["protocol"] as? String, "vless")
|
||||
let settings = try XCTUnwrap(outbounds.first?["settings"] as? [String: Any])
|
||||
let vnext = try XCTUnwrap(settings["vnext"] as? [[String: Any]])
|
||||
XCTAssertEqual(vnext.first?["address"] as? String, "192.0.2.1")
|
||||
let stream = try XCTUnwrap(outbounds.first?["streamSettings"] as? [String: Any])
|
||||
let reality = try XCTUnwrap(stream["realitySettings"] as? [String: Any])
|
||||
XCTAssertEqual(reality["serverName"] as? String, "www.microsoft.com")
|
||||
XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.toplc.cn")
|
||||
}
|
||||
}
|
||||
Vendored
+373
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023-2025 XTLS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
name: UCVLZonghengjia
|
||||
options:
|
||||
bundleIdPrefix: cn.toplc
|
||||
deploymentTarget:
|
||||
iOS: "15.0"
|
||||
createIntermediateGroups: true
|
||||
groupSortPosition: top
|
||||
settings:
|
||||
base:
|
||||
SWIFT_VERSION: "5.10"
|
||||
MARKETING_VERSION: "1.0.2"
|
||||
CURRENT_PROJECT_VERSION: "10002"
|
||||
CODE_SIGN_STYLE: Automatic
|
||||
DEVELOPMENT_TEAM: ""
|
||||
CLANG_ENABLE_MODULES: YES
|
||||
ENABLE_USER_SCRIPT_SANDBOXING: YES
|
||||
configs:
|
||||
Debug: debug
|
||||
Release: release
|
||||
targets:
|
||||
UCVLZonghengjia:
|
||||
type: application
|
||||
platform: iOS
|
||||
sources:
|
||||
- path: App
|
||||
- path: Shared
|
||||
resources:
|
||||
- path: Resources/Assets.xcassets
|
||||
entitlements:
|
||||
path: App/UCVLZonghengjia.entitlements
|
||||
info:
|
||||
path: App/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: 优创⁺纵横家
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
|
||||
UILaunchScreen:
|
||||
UIColorName: UCVLLaunchBackground
|
||||
UIImageName: UCVLLogo
|
||||
UISupportedInterfaceOrientations:
|
||||
- UIInterfaceOrientationPortrait
|
||||
- UIInterfaceOrientationLandscapeLeft
|
||||
- UIInterfaceOrientationLandscapeRight
|
||||
UISupportedInterfaceOrientations~ipad:
|
||||
- UIInterfaceOrientationPortrait
|
||||
- UIInterfaceOrientationPortraitUpsideDown
|
||||
- UIInterfaceOrientationLandscapeLeft
|
||||
- UIInterfaceOrientationLandscapeRight
|
||||
dependencies:
|
||||
- target: PacketTunnel
|
||||
embed: true
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia
|
||||
PRODUCT_NAME: UCVLZonghengjia
|
||||
TARGETED_DEVICE_FAMILY: "1,2"
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.utilities
|
||||
|
||||
PacketTunnel:
|
||||
type: app-extension
|
||||
platform: iOS
|
||||
sources:
|
||||
- path: PacketTunnel
|
||||
- path: Shared/TunnelConfigurationBuilder.swift
|
||||
- path: Shared/Models.swift
|
||||
- path: Shared/NetworkAddress.swift
|
||||
resources:
|
||||
- path: Resources/Geo
|
||||
entitlements:
|
||||
path: PacketTunnel/PacketTunnel.entitlements
|
||||
info:
|
||||
path: PacketTunnel/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: 优创⁺纵横家网络扩展
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
|
||||
NSExtension:
|
||||
NSExtensionPointIdentifier: com.apple.networkextension.packet-tunnel
|
||||
NSExtensionPrincipalClass: $(PRODUCT_MODULE_NAME).PacketTunnelProvider
|
||||
dependencies:
|
||||
- framework: Vendor/LibXray.xcframework
|
||||
embed: false
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia.PacketTunnel
|
||||
PRODUCT_NAME: PacketTunnel
|
||||
TARGETED_DEVICE_FAMILY: "1,2"
|
||||
APPLICATION_EXTENSION_API_ONLY: YES
|
||||
SKIP_INSTALL: YES
|
||||
OTHER_LDFLAGS:
|
||||
- $(inherited)
|
||||
- -ObjC
|
||||
|
||||
UCVLZonghengjiaTests:
|
||||
type: bundle.unit-test
|
||||
platform: iOS
|
||||
sources:
|
||||
- path: Tests
|
||||
dependencies:
|
||||
- target: UCVLZonghengjia
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia.tests
|
||||
GENERATE_INFOPLIST_FILE: YES
|
||||
|
||||
schemes:
|
||||
UCVLZonghengjia:
|
||||
build:
|
||||
targets:
|
||||
UCVLZonghengjia: all
|
||||
PacketTunnel: all
|
||||
UCVLZonghengjiaTests: [test]
|
||||
test:
|
||||
targets:
|
||||
- UCVLZonghengjiaTests
|
||||
archive:
|
||||
config: Release
|
||||
Reference in New Issue
Block a user