Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 295799b1ab |
+16
-2
@@ -1,5 +1,19 @@
|
||||
# 优创⁺纵横家 iPhone / iPad 验收记录
|
||||
|
||||
## 2026-10-27:1.0.3 / 10003 源码候选(非 IPA)
|
||||
|
||||
结论:`SOURCE_CANDIDATE`。本次新增的是源码与归档流程;没有生成、签名、安装或发布 iPhone/iPad 二进制,也没有对用户手机执行操作。
|
||||
|
||||
- 源码连接策略只接受后台为当前节点明确授权的内部 IP 入口,先执行限时 ICMP Ping;匹配回复后才尝试内部代理,并验证实际出口。内部 Ping 不通或内部传输失败先回退同一节点的原公网配置;本次连接一旦走公网,含后续节点重试在内都不自动切回内部入口。
|
||||
- 内部入口依赖系统原有可达路由;不登录、启动、停止或管理 Tailscale,不修改其配置,不承诺 iOS 同时运行两个 Packet Tunnel。Ping 通过不能代替本应用 VPN 建立后的真实代理业务验收。
|
||||
- 2026-10-27 对公司 Git 的认证只读查询:iOS 仓库启用 Actions,runner API `total_count=0`;仅有的 5 次运行均为 `source-audit.yml` 且全部 cancelled,未发现 `apple-build.yml` 执行。未读取秘密值、触发 workflow 或更改远端。
|
||||
- `Scripts/verify-and-archive.sh` 改为从 `project.yml` 读取唯一有效版本,归档为 `build/UCVL-Zonghengjia-1.0.3.xcarchive`;支持 `SIMULATOR_DESTINATION` 覆盖默认 iPhone 16 Pro。缺少 Team、版本无效、导出文件缺失或 plist 格式错误时,在下载/构建前停止;fetch 的官方 SHA256 校验流程保留。
|
||||
- Windows 上已运行 9 项 Python subprocess 测试,复制真实归档脚本到临时目录并替换外部命令,验证精确的归档/导出参数、模拟器覆盖、预检及逐阶段失败停止。测试先在旧脚本上失败,再在修改后通过;它不执行 Xcode/XCTest、真实 `plutil`、下载、签名或真实 VPN 流量。
|
||||
|
||||
仍缺可用 Mac/Xcode runner、获授权 Apple Team 与 Network Extension Provisioning Profile、对应分发方式的签名/ExportOptions,以及真实 iPhone/iPad 的 VPN 授权、内部入口/同节点公网回退、出口、睡眠唤醒、切网和断开恢复验收。源码静态审计以本次 `Scripts/source-audit.py` 的实际报告为准;离线脚本测试不能替代这些条件,当前没有可安装 IPA 或 TestFlight/MDM 发布结果。
|
||||
|
||||
以下保留历史版本记录,其检查结果不自动转移到本次候选。
|
||||
|
||||
## 2026-09-09:1.0.2 源码候选(非 IPA)
|
||||
|
||||
工程 `MARKETING_VERSION` 为 1.0.2,README 已与之同步,源码审计新增文档版本一致性检查并通过。现有错误分类源码区分平台/本机授权/节点失败及 401/403 授权失效;XCTest 已编写,仍未运行。这次只修正文档和静态校验,没有新的 iOS 二进制构建、签名、安装包、真机连接或公开发布。未取得 Mac/Xcode/开发者团队条件,不能把 Windows 测试当成苹果验收。
|
||||
@@ -17,14 +31,14 @@
|
||||
- 登录令牌保存在 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 和其它保留地址。
|
||||
- 001/002 节点由 NPM TCP Stream 端口分流;节点子域无 A 记录时,主应用通过阿里/腾讯 DoH 获取统一入口 `vpn.example.invalid` 的真实公网 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 真机出口验收。
|
||||
- Windows 侧对 NPM 公网入口 `203.0.113.17` 复核:`vpn.example.invalid` HTTPS 健康接口正常,TCP `11081`、`11082`、`11083` 均可建立连接。该检查只证明 NPM 入口与端口在线,不替代 VLESS Reality 握手或 iPhone 真机出口验收。
|
||||
|
||||
## 必须在 Mac 和真机完成后才能发布 IPA
|
||||
|
||||
|
||||
+83
-31
@@ -65,9 +65,11 @@ final class AppState: ObservableObject {
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
if vpn.isConnected {
|
||||
await vpn.disconnectAndWait()
|
||||
currentNode = nil
|
||||
message = "正在断开,系统将自动恢复原网络"
|
||||
do {
|
||||
try await vpn.disconnectAndWait()
|
||||
currentNode = nil
|
||||
message = "已断开,系统已撤销本应用的 VPN 连接"
|
||||
} catch { errorMessage = friendly(error) }
|
||||
return
|
||||
}
|
||||
guard let profile,
|
||||
@@ -77,7 +79,8 @@ final class AppState: ObservableObject {
|
||||
return
|
||||
}
|
||||
if route.id == "direct" {
|
||||
await vpn.disconnectAndWait()
|
||||
do { try await vpn.disconnectAndWait() }
|
||||
catch { errorMessage = friendly(error); return }
|
||||
currentNode = nil
|
||||
message = "当前为本地直连,不经过 VPN 节点"
|
||||
return
|
||||
@@ -91,44 +94,29 @@ final class AppState: ObservableObject {
|
||||
var excludedNodes: [String] = []
|
||||
var lastError: Error = UCVLError.connection("没有可用节点。")
|
||||
let maximumAttempts = max(1, min(profile.nodes.count, 3))
|
||||
// One explicit connect owns this state across all assigned nodes.
|
||||
// No timers or system restore path may promote a public connection.
|
||||
var transport = ProxyTransportSession()
|
||||
|
||||
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),出口验证通过"
|
||||
try await connectAssigned(response, route: route, transport: &transport)
|
||||
return
|
||||
} catch {
|
||||
lastError = error
|
||||
let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil)
|
||||
currentNode = nil
|
||||
await vpn.disconnectAndWait()
|
||||
do { try await vpn.disconnectAndWait() }
|
||||
catch {
|
||||
errorMessage = friendly(error)
|
||||
message = "系统尚未完成断开,已停止切换线路"
|
||||
return
|
||||
}
|
||||
if decision == .revokeAuthorization {
|
||||
logoutLocal()
|
||||
errorMessage = friendly(error)
|
||||
@@ -149,11 +137,74 @@ final class AppState: ObservableObject {
|
||||
message = "所有可用节点均未通过验证,已恢复本地网络"
|
||||
}
|
||||
|
||||
private func connectAssigned(
|
||||
_ response: ClientConfigResponse, route: RouteMode, transport: inout ProxyTransportSession
|
||||
) async throws {
|
||||
let configJSON = try response.configJSONString()
|
||||
if !transport.domainOnly,
|
||||
let endpoint = ProxyTransportPolicy.authorizedInternalEndpoint(response: response) {
|
||||
let reachable = await InternalIPProbe.isReachable(endpoint.address)
|
||||
try Task.checkCancellation()
|
||||
if reachable {
|
||||
message = "正在通过内部 IP 连接 \(response.node.displayName)…"
|
||||
do {
|
||||
try await vpn.connect(
|
||||
configJSON: configJSON, resolvedRemoteAddress: endpoint.address,
|
||||
node: response.node, route: route, internalEndpoint: endpoint,
|
||||
configContract: response.configContract, connectionScope: response.connectionScope
|
||||
)
|
||||
try await verifyActiveEgress()
|
||||
message = "已连接 \(response.node.displayName) · 内部 IP,出口验证通过"
|
||||
return
|
||||
} catch {
|
||||
guard ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: true) == .retryNode else {
|
||||
throw error
|
||||
}
|
||||
try await vpn.disconnectAndWait()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transport.commitPublicFallback()
|
||||
try Task.checkCancellation()
|
||||
// Resolve only when public transport is actually needed. DNS failure
|
||||
// must not prevent an otherwise usable authorized internal endpoint.
|
||||
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
|
||||
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
|
||||
}
|
||||
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let pinnedAddress = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let publicAddress: String
|
||||
if let pinnedAddress, NetworkAddress.isPublicIPv4(pinnedAddress) {
|
||||
publicAddress = pinnedAddress
|
||||
} else {
|
||||
publicAddress = try await api.resolvePublicIPv4(
|
||||
host: (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
|
||||
)
|
||||
}
|
||||
message = "正在通过域名入口连接 \(response.node.displayName)…"
|
||||
try await vpn.connect(
|
||||
configJSON: configJSON, resolvedRemoteAddress: publicAddress, node: response.node, route: route
|
||||
)
|
||||
try await verifyActiveEgress()
|
||||
message = "已连接 \(response.node.displayName) · 域名入口,本次连接保持不切换"
|
||||
}
|
||||
|
||||
private func verifyActiveEgress() async throws {
|
||||
try Task.checkCancellation()
|
||||
try await api.verifyProxyEgress()
|
||||
try Task.checkCancellation()
|
||||
guard vpn.status == .connected else {
|
||||
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在尝试备用入口。")
|
||||
}
|
||||
}
|
||||
|
||||
func logout() async {
|
||||
guard !busy else { return }
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
await vpn.disconnectAndWait()
|
||||
do { try await vpn.disconnectAndWait() }
|
||||
catch { errorMessage = friendly(error); return }
|
||||
if let token = SecureStore.token() {
|
||||
await api.logout(token: token)
|
||||
}
|
||||
@@ -182,7 +233,8 @@ final class AppState: ObservableObject {
|
||||
apply(try await api.profile(token: token))
|
||||
message = "账号和线路已同步"
|
||||
} catch UCVLError.api(let status, let message) where status == 401 || status == 403 {
|
||||
await vpn.disconnectAndWait()
|
||||
do { try await vpn.disconnectAndWait() }
|
||||
catch { errorMessage = friendly(error) }
|
||||
SecureStore.clearToken()
|
||||
profile = nil
|
||||
errorMessage = message
|
||||
|
||||
+261
-94
@@ -5,7 +5,8 @@ struct ContentView: View {
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
UCVLColors.background.ignoresSafeArea()
|
||||
LandscapeArtwork()
|
||||
.ignoresSafeArea()
|
||||
if let profile = state.profile {
|
||||
DashboardView(profile: profile)
|
||||
} else {
|
||||
@@ -13,6 +14,8 @@ struct ContentView: View {
|
||||
}
|
||||
}
|
||||
.tint(UCVLColors.royal)
|
||||
.foregroundColor(UCVLColors.navy)
|
||||
.preferredColorScheme(.light)
|
||||
.alert("提示", isPresented: Binding(
|
||||
get: { !state.errorMessage.isEmpty },
|
||||
set: { if !$0 { state.errorMessage = "" } }
|
||||
@@ -24,23 +27,81 @@ struct ContentView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// Both placements draw the same original asset with a native aspect-fill crop.
|
||||
// Artwork remains separate from the real controls and never changes VPN state.
|
||||
private struct LandscapeArtwork: View {
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
Image("MountainLandscape")
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
.frame(width: geometry.size.width, height: geometry.size.height)
|
||||
.clipped()
|
||||
}
|
||||
.background(UCVLColors.surface)
|
||||
.allowsHitTesting(false)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ScenicPage<Content: View>: View {
|
||||
let maxWidth: CGFloat
|
||||
let content: Content
|
||||
|
||||
init(maxWidth: CGFloat, @ViewBuilder content: () -> Content) {
|
||||
self.maxWidth = maxWidth
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
content
|
||||
.frame(maxWidth: maxWidth)
|
||||
.padding(.horizontal, 18)
|
||||
.padding(.vertical, 24)
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct BrandHeader: View {
|
||||
var compact = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: compact ? 8 : 16) {
|
||||
VStack(spacing: compact ? 8 : 12) {
|
||||
Image("UCVLLogo")
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: compact ? 84 : 132, height: compact ? 84 : 132)
|
||||
.accessibilityLabel("优创未来 Logo")
|
||||
Text("优创⁺纵横家")
|
||||
.frame(width: compact ? 60 : 88, height: compact ? 60 : 88)
|
||||
.accessibilityHidden(true)
|
||||
Text("纵横家")
|
||||
.font(compact ? .title2.bold() : .largeTitle.bold())
|
||||
.foregroundStyle(.white)
|
||||
Text("优创未来安全网络")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(UCVLColors.sky)
|
||||
.foregroundStyle(UCVLColors.navy)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Text(AppVersion.label)
|
||||
.font(.caption)
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.multilineTextAlignment(.center)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, compact ? 16 : 24)
|
||||
.background {
|
||||
LandscapeArtwork()
|
||||
.overlay(Color.white.opacity(0.18))
|
||||
.mask(LinearGradient(colors: [.black, .black, .clear], startPoint: .top, endPoint: .bottom))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum AppVersion {
|
||||
static var label: String {
|
||||
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
|
||||
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
|
||||
guard let version, !version.isEmpty else { return "版本信息不可用" }
|
||||
guard let build, !build.isEmpty else { return "版本 \(version)" }
|
||||
return "版本 \(version) (\(build))"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,36 +109,39 @@ private struct LoginView: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
@State private var identifier = SecureStore.lastLogin
|
||||
@State private var password = ""
|
||||
@FocusState private var focusedField: Field?
|
||||
|
||||
private enum Field: Hashable { case identifier, password }
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 28) {
|
||||
ScenicPage(maxWidth: 540) {
|
||||
VStack(spacing: 20) {
|
||||
BrandHeader()
|
||||
.padding(.top, 34)
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Text("公司统一账号登录")
|
||||
.font(.title2.bold())
|
||||
.foregroundStyle(UCVLColors.navy)
|
||||
TextField("用户名或邮箱", text: $identifier)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
.disableAutocorrection(true)
|
||||
.keyboardType(.emailAddress)
|
||||
.textContentType(.username)
|
||||
.submitLabel(.next)
|
||||
.focused($focusedField, equals: .identifier)
|
||||
.ucvlField()
|
||||
.onSubmit { focusedField = .password }
|
||||
SecureField("密码", text: $password)
|
||||
.textContentType(.password)
|
||||
.submitLabel(.go)
|
||||
.focused($focusedField, equals: .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: {
|
||||
.onSubmit { signIn() }
|
||||
Button(action: signIn) {
|
||||
HStack {
|
||||
if state.busy { ProgressView().tint(.white) }
|
||||
Text(state.busy ? "正在登录…" : "安全登录").fontWeight(.semibold)
|
||||
}
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 14)
|
||||
}
|
||||
@@ -85,65 +149,113 @@ private struct LoginView: View {
|
||||
.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))
|
||||
}
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
RegistrationPrompt()
|
||||
}
|
||||
.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(20)
|
||||
.scenicCard(cornerRadius: 24)
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItemGroup(placement: .keyboard) {
|
||||
Spacer()
|
||||
Button("完成") { focusedField = nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func signIn() {
|
||||
focusedField = nil
|
||||
Task {
|
||||
await state.login(identifier: identifier, password: password)
|
||||
if state.profile != nil { password = "" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct RegistrationPrompt: View {
|
||||
private var message: AttributedString {
|
||||
var prompt = AttributedString("还没有账号?")
|
||||
prompt.foregroundColor = UCVLColors.muted
|
||||
var link = AttributedString("注册新用户")
|
||||
link.link = URL(string: "https://vpn.example.invalid/register/")
|
||||
link.foregroundColor = UCVLColors.royal
|
||||
link.font = .footnote.weight(.semibold)
|
||||
prompt.append(link)
|
||||
return prompt
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
// A single inline run shares a baseline and wraps naturally at large sizes.
|
||||
Text(message)
|
||||
.font(.footnote)
|
||||
.lineSpacing(4)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DashboardHeader: View {
|
||||
@Environment(\.horizontalSizeClass) private var sizeClass
|
||||
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
|
||||
let profile: ClientProfile
|
||||
|
||||
private var account: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
|
||||
.font(.headline)
|
||||
Text(profile.email)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
Text(profile.identityType == "employee" ? "内部员工" : "外部联系人")
|
||||
.font(.caption)
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
}
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
|
||||
HStack(spacing: 24) {
|
||||
BrandHeader(compact: true)
|
||||
account
|
||||
}
|
||||
} else {
|
||||
VStack(spacing: 16) {
|
||||
BrandHeader(compact: true)
|
||||
account
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(18)
|
||||
.scenicCard()
|
||||
}
|
||||
}
|
||||
|
||||
private struct DashboardView: View {
|
||||
@EnvironmentObject private var state: AppState
|
||||
@Environment(\.horizontalSizeClass) private var sizeClass
|
||||
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
|
||||
let profile: ClientProfile
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
ScenicPage(maxWidth: 760) {
|
||||
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)
|
||||
DashboardHeader(profile: profile)
|
||||
|
||||
StatusCard()
|
||||
|
||||
UCVLCard(title: "工作节点与代理模式", systemImage: "point.3.connected.trianglepath.dotted") {
|
||||
VStack(spacing: 14) {
|
||||
HStack {
|
||||
Text("当前工作节点")
|
||||
Spacer()
|
||||
AdaptiveDetailRow(title: "当前工作节点") {
|
||||
Text(state.currentNode?.displayName ?? "由 vpn-ai 自动选择")
|
||||
.foregroundStyle(state.currentNode == nil ? .secondary : UCVLColors.royal)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.foregroundStyle(state.currentNode == nil ? UCVLColors.muted : UCVLColors.royal)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Text("代理模式")
|
||||
Spacer()
|
||||
AdaptiveDetailRow(title: "代理模式") {
|
||||
Picker("代理模式", selection: $state.selectedRouteID) {
|
||||
ForEach(profile.routeModes) { route in Text(route.name).tag(route.id) }
|
||||
}
|
||||
@@ -158,6 +270,7 @@ private struct DashboardView: View {
|
||||
Image(systemName: state.vpn.isConnected ? "stop.fill" : "bolt.shield.fill")
|
||||
Text(state.vpn.isConnected ? "断开连接" : "连接")
|
||||
}
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 12)
|
||||
}
|
||||
@@ -169,25 +282,66 @@ private struct DashboardView: View {
|
||||
|
||||
UsageCard(subscription: profile.subscription)
|
||||
|
||||
HStack(spacing: 12) {
|
||||
Button { Task { await state.refresh() } } label: {
|
||||
Label("刷新", systemImage: "arrow.clockwise")
|
||||
.frame(maxWidth: .infinity)
|
||||
Group {
|
||||
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
|
||||
HStack(spacing: 12) { accountActions }
|
||||
} else {
|
||||
VStack(spacing: 12) { accountActions }
|
||||
}
|
||||
.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)
|
||||
}
|
||||
.padding(16)
|
||||
.scenicCard()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var accountActions: some View {
|
||||
Button { Task { await state.refresh() } } label: {
|
||||
Label("刷新", systemImage: "arrow.clockwise")
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(state.busy)
|
||||
Button(role: .destructive) { Task { await state.logout() } } label: {
|
||||
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(state.busy)
|
||||
}
|
||||
}
|
||||
|
||||
private struct AdaptiveDetailRow<Content: View>: View {
|
||||
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
|
||||
let title: String
|
||||
let content: Content
|
||||
|
||||
init(title: String, @ViewBuilder content: () -> Content) {
|
||||
self.title = title
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if dynamicTypeSize.isAccessibilitySize {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(title)
|
||||
content
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
} else {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 12) {
|
||||
Text(title)
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
content
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(maxWidth: .infinity, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 760)
|
||||
.padding(.horizontal, 18)
|
||||
.padding(.vertical, 18)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,17 +350,19 @@ private struct StatusCard: View {
|
||||
|
||||
var body: some View {
|
||||
UCVLCard(title: "连接状态", systemImage: "network.badge.shield.half.filled") {
|
||||
HStack(spacing: 14) {
|
||||
HStack(alignment: .top, spacing: 14) {
|
||||
Circle()
|
||||
.fill(state.statusIsActive ? Color.green : Color.gray)
|
||||
.fill(state.statusIsActive ? UCVLColors.success : UCVLColors.muted)
|
||||
.frame(width: 13, height: 13)
|
||||
.padding(.top, 6)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(state.statusTitle).font(.title3.bold())
|
||||
Text(state.message.isEmpty ? "点击连接,vpn-ai 将自动选择并验证工作节点" : state.message)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(.secondary)
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
}
|
||||
Spacer()
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -223,17 +379,21 @@ private struct UsageCard: View {
|
||||
var body: some View {
|
||||
UCVLCard(title: "本期流量", systemImage: "chart.bar.fill") {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
AdaptiveDetailRow(title: "已用流量") {
|
||||
Text(format(subscription.usedBytes))
|
||||
Spacer()
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
AdaptiveDetailRow(title: "套餐流量") {
|
||||
Text(subscription.trafficLimitBytes > 0 ? format(subscription.trafficLimitBytes) : "不限流量")
|
||||
.foregroundStyle(UCVLColors.royal)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
ProgressView(value: fraction)
|
||||
.tint(UCVLColors.royal)
|
||||
Text("套餐:\(subscription.plan) · 设备上限 \(subscription.deviceLimit) 台\(expiryText)")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
.foregroundStyle(UCVLColors.muted)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,31 +424,38 @@ private struct UCVLCard<Content: View>: View {
|
||||
Label(title, systemImage: systemImage)
|
||||
.font(.headline)
|
||||
.foregroundStyle(UCVLColors.navy)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
content
|
||||
}
|
||||
.padding(20)
|
||||
.background(.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
|
||||
.shadow(color: .black.opacity(0.08), radius: 14, y: 7)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.scenicCard()
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
static let navy = Color(red: 10 / 255, green: 34 / 255, blue: 91 / 255)
|
||||
static let royal = Color(red: 0, green: 80 / 255, blue: 221 / 255)
|
||||
static let muted = Color(red: 52 / 255, green: 79 / 255, blue: 116 / 255)
|
||||
static let surface = Color(red: 237 / 255, green: 248 / 255, blue: 1)
|
||||
static let success = Color(red: 0, green: 113 / 255, blue: 110 / 255)
|
||||
}
|
||||
|
||||
private extension View {
|
||||
func scenicCard(cornerRadius: CGFloat = 22) -> some View {
|
||||
self
|
||||
.background(Color.white.opacity(0.50), in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
|
||||
.overlay(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).stroke(Color.white.opacity(0.55)))
|
||||
.shadow(color: UCVLColors.navy.opacity(0.08), radius: 14, y: 7)
|
||||
}
|
||||
|
||||
func ucvlField() -> some View {
|
||||
self
|
||||
.foregroundColor(UCVLColors.navy)
|
||||
.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)))
|
||||
.padding(.vertical, 14)
|
||||
.frame(minHeight: 52)
|
||||
.background(Color.white.opacity(0.72), in: RoundedRectangle(cornerRadius: 13))
|
||||
.overlay(RoundedRectangle(cornerRadius: 13).stroke(UCVLColors.navy.opacity(0.16)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
enum InternalIPProbe {
|
||||
static func isReachable(_ address: String) async -> Bool {
|
||||
guard NetworkAddress.isAuthorizedInternalIPv4(address), !Task.isCancelled else { return false }
|
||||
let attempt = PingAttempt()
|
||||
return await withTaskCancellationHandler(operation: {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
continuation.resume(returning: attempt.run(address))
|
||||
}
|
||||
}
|
||||
}, onCancel: { attempt.cancel() })
|
||||
}
|
||||
}
|
||||
|
||||
private final class PingAttempt: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var cancelled = false
|
||||
|
||||
func cancel() {
|
||||
lock.lock()
|
||||
cancelled = true
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
private var isCancelled: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return cancelled
|
||||
}
|
||||
|
||||
func run(_ address: String) -> Bool {
|
||||
let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000
|
||||
guard !isCancelled else { return false }
|
||||
// Darwin datagram ICMP is unprivileged. Never run a shell, query a VPN
|
||||
// service or replace ICMP with a TCP/HTTP test.
|
||||
let descriptor = Darwin.socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
|
||||
guard descriptor >= 0 else { return false }
|
||||
defer { Darwin.close(descriptor) }
|
||||
let flags = fcntl(descriptor, F_GETFL, 0)
|
||||
guard flags >= 0, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 else { return false }
|
||||
|
||||
var destination = sockaddr_in()
|
||||
destination.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
destination.sin_family = sa_family_t(AF_INET)
|
||||
guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return false }
|
||||
let connected = withUnsafePointer(to: &destination) {
|
||||
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
|
||||
Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
|
||||
}
|
||||
}
|
||||
guard connected == 0, !isCancelled else { return false }
|
||||
|
||||
let payload = Array(UUID().uuidString.utf8)
|
||||
let packet = ICMPEchoPacket.request(identifier: UInt16.random(in: 1...UInt16.max), payload: payload)
|
||||
let sent = packet.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) }
|
||||
guard sent == packet.count else { return false }
|
||||
var descriptorState = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0)
|
||||
while !isCancelled {
|
||||
let now = DispatchTime.now().uptimeNanoseconds
|
||||
guard now < deadline else { return false }
|
||||
let waitMS = Int32(min(50, max(1, (deadline - now) / 1_000_000)))
|
||||
let ready = Darwin.poll(&descriptorState, 1, waitMS)
|
||||
if ready < 0 {
|
||||
if errno == EINTR { continue }
|
||||
return false
|
||||
}
|
||||
guard ready > 0 else { continue }
|
||||
guard descriptorState.revents & Int16(POLLIN) != 0 else { return false }
|
||||
var buffer = [UInt8](repeating: 0, count: 4096)
|
||||
var sender = sockaddr_in()
|
||||
var senderSize = socklen_t(MemoryLayout<sockaddr_in>.size)
|
||||
let received = withUnsafeMutablePointer(to: &sender) { senderPointer in
|
||||
senderPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in
|
||||
buffer.withUnsafeMutableBytes {
|
||||
Darwin.recvfrom(descriptor, $0.baseAddress, $0.count, 0, socketPointer, &senderSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
guard received > 0 else {
|
||||
if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { continue }
|
||||
return false
|
||||
}
|
||||
if sender.sin_family == sa_family_t(AF_INET),
|
||||
sender.sin_addr.s_addr == destination.sin_addr.s_addr,
|
||||
ICMPEchoPacket.isReply(Array(buffer.prefix(received)), payload: payload) {
|
||||
return !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import UIKit
|
||||
actor PlatformAPI {
|
||||
static let shared = PlatformAPI()
|
||||
|
||||
private let baseURL = URL(string: "https://vpn.toplc.cn/")!
|
||||
private let baseURL = URL(string: "https://vpn.example.invalid/")!
|
||||
private let session: URLSession
|
||||
private let decoder = JSONDecoder()
|
||||
private let encoder = JSONEncoder()
|
||||
@@ -16,7 +16,7 @@ actor PlatformAPI {
|
||||
configuration.waitsForConnectivity = true
|
||||
configuration.httpAdditionalHeaders = [
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "UCVL-Zonghengjia/1.0.2 iOS",
|
||||
"User-Agent": "UCVL-Zonghengjia/1.0.3 iOS",
|
||||
]
|
||||
session = URLSession(configuration: configuration)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ actor PlatformAPI {
|
||||
"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",
|
||||
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.3",
|
||||
"platform": "ios",
|
||||
]
|
||||
return try await send(
|
||||
@@ -98,7 +98,7 @@ actor PlatformAPI {
|
||||
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 candidateHosts = host == "vpn.example.invalid" ? [host] : [host, "vpn.example.invalid"]
|
||||
let resolvers = [
|
||||
"https://dns.alidns.com/resolve",
|
||||
"https://doh.pub/resolve",
|
||||
@@ -131,7 +131,7 @@ actor PlatformAPI {
|
||||
}
|
||||
}
|
||||
}
|
||||
throw UCVLError.connection("无法取得 NPM 入口 vpn.toplc.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
|
||||
throw UCVLError.connection("无法取得 NPM 入口 vpn.example.invalid 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
|
||||
}
|
||||
|
||||
func logout(token: String) async {
|
||||
|
||||
+39
-10
@@ -15,7 +15,10 @@ final class VPNController: ObservableObject {
|
||||
queue: .main
|
||||
) { [weak self] note in
|
||||
guard let connection = note.object as? NEVPNConnection else { return }
|
||||
Task { @MainActor in self?.status = connection.status }
|
||||
Task { @MainActor in
|
||||
guard let self, connection === self.manager?.connection else { return }
|
||||
self.status = connection.status
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,26 +41,51 @@ final class VPNController: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws {
|
||||
func connect(
|
||||
configJSON: String,
|
||||
resolvedRemoteAddress: String,
|
||||
node: VPNNode,
|
||||
route: RouteMode,
|
||||
internalEndpoint: ProxyTransportEndpoint? = nil,
|
||||
configContract: Int? = nil,
|
||||
connectionScope: String? = nil
|
||||
) async throws {
|
||||
guard route.id != "direct" else {
|
||||
disconnect()
|
||||
try await disconnectAndWait()
|
||||
return
|
||||
}
|
||||
if let internalEndpoint {
|
||||
guard internalEndpoint.address == resolvedRemoteAddress,
|
||||
ProxyTransportPolicy.authorizedInternalEndpoint(
|
||||
endpoint: internalEndpoint, nodeSlug: node.slug, configContract: configContract,
|
||||
connectionScope: connectionScope, routeMode: route.id, configJSON: configJSON
|
||||
) != nil else {
|
||||
throw UCVLError.invalidConfiguration("内部入口与后台授权节点不一致。")
|
||||
}
|
||||
} else if !NetworkAddress.isPublicIPv4(resolvedRemoteAddress) {
|
||||
throw UCVLError.invalidConfiguration("公网入口地址不可用。")
|
||||
}
|
||||
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 = [
|
||||
var configuration: [String: Any] = [
|
||||
"configJSON": configJSON,
|
||||
"resolvedRemoteAddress": resolvedRemoteAddress,
|
||||
"nodeSlug": node.slug,
|
||||
"nodeName": node.name,
|
||||
"routeMode": route.id,
|
||||
]
|
||||
if let internalEndpoint {
|
||||
configuration["internalEndpointJSON"] = try JSONEncoder().encode(internalEndpoint)
|
||||
configuration["configContract"] = configContract
|
||||
configuration["connectionScope"] = connectionScope ?? ""
|
||||
}
|
||||
tunnelProtocol.providerConfiguration = configuration
|
||||
|
||||
selected.localizedDescription = "优创⁺纵横家"
|
||||
selected.localizedDescription = "纵横家"
|
||||
selected.protocolConfiguration = tunnelProtocol
|
||||
selected.isEnabled = true
|
||||
try await save(selected)
|
||||
@@ -68,7 +96,7 @@ final class VPNController: ObservableObject {
|
||||
try selected.connection.startVPNTunnel()
|
||||
} catch {
|
||||
activeNodeSlug = nil
|
||||
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。")
|
||||
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许纵横家添加 VPN 配置。")
|
||||
}
|
||||
do {
|
||||
try await waitUntilConnected(selected.connection)
|
||||
@@ -84,15 +112,16 @@ final class VPNController: ObservableObject {
|
||||
activeNodeSlug = nil
|
||||
}
|
||||
|
||||
func disconnectAndWait(timeout: TimeInterval = 8) async {
|
||||
func disconnectAndWait(timeout: TimeInterval = 8) async throws {
|
||||
disconnect()
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
while Date() < deadline {
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + timeout
|
||||
while ProcessInfo.processInfo.systemUptime < deadline {
|
||||
let current = manager?.connection.status ?? .disconnected
|
||||
status = current
|
||||
if current == .disconnected || current == .invalid { return }
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
}
|
||||
throw UCVLError.invalidConfiguration("系统 VPN 尚未完成断开,已停止切换线路,请稍后重试。")
|
||||
}
|
||||
|
||||
var isConnected: Bool {
|
||||
|
||||
+3
-19
@@ -1,21 +1,5 @@
|
||||
MIT License
|
||||
# 优创⁺纵横家 iOS 客户端许可说明
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
除 `THIRD_PARTY_NOTICES.md` 与 `ThirdParty/` 中另行标明的第三方组件外,本仓库中的优创⁺纵横家 iOS 客户端代码、界面与品牌资源归优创未来所有,仅限公司授权的开发、构建、测试和内部使用。未经书面许可,不得向第三方发布、销售或再许可。
|
||||
|
||||
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.
|
||||
第三方组件继续适用其原始许可证;本说明不改变 MIT、MPL-2.0 或数据资源各自的许可义务。
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
# 第三方许可及 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 再许可范围。
|
||||
|
||||
来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。
|
||||
@@ -27,10 +27,28 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
guard let self else { return }
|
||||
do {
|
||||
let resolvedRemoteAddress: String
|
||||
if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
|
||||
let runtimeJSON: String
|
||||
if let endpointData = providerConfiguration["internalEndpointJSON"] as? Data {
|
||||
let endpoint = try JSONDecoder().decode(ProxyTransportEndpoint.self, from: endpointData)
|
||||
guard endpoint.address == providedRemoteAddress,
|
||||
ProxyTransportPolicy.authorizedInternalEndpoint(
|
||||
endpoint: endpoint,
|
||||
nodeSlug: providerConfiguration["nodeSlug"] as? String ?? "",
|
||||
configContract: providerConfiguration["configContract"] as? Int,
|
||||
connectionScope: providerConfiguration["connectionScope"] as? String,
|
||||
routeMode: providerConfiguration["routeMode"] as? String ?? "",
|
||||
configJSON: rawJSON
|
||||
) != nil else {
|
||||
throw UCVLError.invalidConfiguration("内部代理入口与授权配置不一致。")
|
||||
}
|
||||
resolvedRemoteAddress = endpoint.address
|
||||
runtimeJSON = try ProxyTransportPolicy.internalConfigJSON(rawJSON: rawJSON, endpoint: endpoint)
|
||||
} else if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
|
||||
resolvedRemoteAddress = providedRemoteAddress
|
||||
runtimeJSON = rawJSON
|
||||
} else {
|
||||
resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost)
|
||||
runtimeJSON = rawJSON
|
||||
}
|
||||
let settings = self.makeNetworkSettings(remoteAddress: resolvedRemoteAddress)
|
||||
self.setTunnelNetworkSettings(settings) { [weak self] error in
|
||||
@@ -50,7 +68,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
throw UCVLError.invalidConfiguration("路由规则资源缺失。")
|
||||
}
|
||||
let config = try TunnelConfigurationBuilder.makeConfiguration(
|
||||
rawJSON: rawJSON,
|
||||
rawJSON: runtimeJSON,
|
||||
tunnelFileDescriptor: tunnelFD,
|
||||
assetDirectory: geoIP.deletingLastPathComponent().path,
|
||||
resolvedRemoteAddress: resolvedRemoteAddress
|
||||
@@ -142,7 +160,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
var hints = addrinfo()
|
||||
hints.ai_flags = AI_ADDRCONFIG
|
||||
hints.ai_family = AF_INET
|
||||
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
hints.ai_protocol = IPPROTO_TCP
|
||||
var results: UnsafeMutablePointer<addrinfo>?
|
||||
let status = host.withCString { getaddrinfo($0, nil, &hints, &results) }
|
||||
|
||||
+54
-8
@@ -1,15 +1,61 @@
|
||||
# 纵横家 iPhone / iPad 1.0.2 源码候选版(开源)
|
||||
# 纵横家 iPhone / iPad 1.0.3 源码候选版
|
||||
|
||||
Swift 主应用与 Apple Packet Tunnel 扩展源码,版本 `1.0.2`,最低 iOS 15。仅为源码快照和静态结构检查;没有可安装 IPA,未执行 Xcode 编译、XCTest、Apple 签名或 iPhone/iPad 真机 VPN 验收。macOS 客户端不在本目录范围。
|
||||
公司内部 Apple 系统 VPN 客户端源码,版本 `1.0.3`,构建号 `10003`,主应用 Bundle ID 为 `cn.toplc.zonghengjia`,Packet Tunnel 扩展 Bundle ID 为 `cn.toplc.zonghengjia.PacketTunnel`。
|
||||
|
||||
## 构建前提
|
||||
当前没有可安装的 IPA;以下功能指已编写的实现,不代表通过 Xcode 编译或 iPhone 真机验收。1.0.3 增加后台授权内部 IP 的 ICMP Ping 探测、同节点公网回退和本次连接的公网路径保持。平台/本机错误继续停止尝试,401/403 清理失效登录状态。对应 XCTest 已编写,但本机构建环境不能执行。
|
||||
|
||||
需要 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` 提供测试/归档入口,不代表这里已执行通过。公开示例端点需替换成自己的配置。
|
||||
登录与主页统一“纵横家”品牌,使用与 Windows 相同的原创山水背景及50%白色卡片;注册提示与链接保持同行自然换行,适配手机键盘和大字体。后台配置节点未提供 `status` 时按“未知”解析,避免有效配置在连接前解码失败;不把未知状态冒充在线。Xcode 的 Swift 语言模式为 `5.0`,它与编译器版本号不同。
|
||||
|
||||
Scripts/fetch-libxray.sh 从原固定官方版本 v26.7.28 下载 Apple cgo XCFramework,并核验其源码中固定的 SHA-256;Vendor/ 二进制不在本仓库。下载脚本仅恢复 libXray,不能恢复 Geo 数据,也不提供 Apple 签名材料。
|
||||
## 源码功能
|
||||
|
||||
## 未打包的 Geo 数据
|
||||
- 使用 `vpn.example.invalid` 平台账号登录与设备授权。
|
||||
- 展示套餐、流量、当前实际工作节点和代理模式;不向用户提供节点选择。
|
||||
- 支持 AI 智能代理、全局代理与本地直连。
|
||||
- 请求后台 `vpn-ai` 自动分配节点;连接失败时排除故障节点并重新分配,最多尝试三次。
|
||||
- Apple 系统 VPN 建立后使用 OpenAI / ChatGPT HTTPS 入口验证实际出口,未通过就自动恢复本地网络并切换节点。
|
||||
- 使用 Apple `NEPacketTunnelProvider` 实现 iPhone/iPad 整机代理。
|
||||
- 断开时由 iOS 自动撤销虚拟路由并恢复原网络。
|
||||
- 登录令牌通过 iOS Keychain 保存。
|
||||
- 内嵌官方 libXray `v26.7.28` Apple XCFramework,支持 VLESS Reality。
|
||||
- 仅当后台 `config_contract=2` 为当前同一节点下发有效的 `tailscale_endpoint`、公开连接范围及兼容 VLESS Reality 配置时,先对授权内部 IP 做限时 ICMP Ping;收到匹配回复后才尝试该内部入口。任意私网地址、其它节点入口或用户自行输入的地址不会因此获得授权。
|
||||
- 内部 Ping 不通或内部传输失败时,先使用同一节点的原公网配置;一旦选用公网,本次用户发起的连接及其节点重试都保持公网路径,不自动切回内部入口。公网节点连接失败后才继续原有节点切换策略。
|
||||
- 内部 IP 路径使用系统现有的可达路由;客户端不登录、启动、停止或管理 Tailscale。没有承诺 iOS 上两个 Packet Tunnel 能同时运行,Ping 成功也不代表启动本应用 VPN 后仍然可达;后者仍须完成代理出口验证,失败则按上述规则回退。
|
||||
- 001/002 等节点的公网配置通过同一 NPM TCP Stream 入口、由端口分流,不要求各节点子域名单独发布 A 记录。需要公网路径时先解析节点域名,解析不到就通过阿里/腾讯 DoH 解析统一入口 `vpn.example.invalid` 的真实公网 IPv4;公网路径仍拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网及 Tailscale 地址。
|
||||
- 在接管默认路由前把 NPM 入口公网 IP 排除出隧道,并把运行时 VLESS 地址固定为同一 IP;节点端口及 Reality `serverName` 保持不变,避免节点连接被送回 TUN 形成回环。
|
||||
- 兼容后台 `config_contract=2`:优先使用后台下发的统一 NPM 网关,旧后台未返回该字段时仍按原有域名解析流程连接。
|
||||
- OpenAI/ChatGPT 出口探测完成后再次核对系统 VPN 状态,避免把“探测成功但隧道已退出”误报为已连接。
|
||||
|
||||
Resources/Geo/geoip.dat 与 geosite.dat 未纳入公开导出:旧源码未完整记录数据项目/版本及许可。project.yml 仍保留 Resources/Geo 的资源接入位置,但构建前须自行从可信官方数据源取得对应数据、核验下载校验值与许可,并放入该目录。此仓库不猜测或声称存在已验证的 Geo 下载 URL/hash,不能把 libXray 归档校验值当作 Geo 校验值。
|
||||
## 在 Mac 上生成工程
|
||||
|
||||
公司自有代码适用 LICENSE.md/MIT;ThirdParty/ 和 THIRD_PARTY_NOTICES.md 保留原始第三方许可证与说明。公司商标/Logo 不在 MIT 授权范围。公司公开 API 域名只为源码兼容保留,不授予服务访问权限。
|
||||
1. 安装 Xcode 及 XcodeGen:`brew install xcodegen`。
|
||||
2. 若源码包不保留执行位,先运行 `chmod +x Scripts/*.sh`。运行 `./Scripts/fetch-libxray.sh` 下载官方 Apple XCFramework并核对固定 SHA256,再运行 `./Scripts/generate-project.sh`。
|
||||
3. 在 Xcode 的 Signing & Capabilities 中为主应用和 `PacketTunnel` 目标选择同一个 Apple Developer Team。
|
||||
4. 为两个 App ID 启用 Network Extensions / Packet Tunnel Provider 权限。
|
||||
5. 使用真机运行;iOS 模拟器不能完整验证 Packet Tunnel 数据通路。
|
||||
|
||||
具备上述条件后,可用 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh` 执行测试并归档。脚本从 `project.yml` 的唯一数字三段 `MARKETING_VERSION` 生成归档路径;当前为 `build/UCVL-Zonghengjia-1.0.3.xcarchive`。默认模拟器为 `platform=iOS Simulator,name=iPhone 16 Pro`;可通过 `SIMULATOR_DESTINATION='platform=iOS Simulator,id=已安装模拟器的UDID'` 显式指定本机可用设备。
|
||||
|
||||
如需同时导出 IPA,再传入 Xcode 生成且适用于所选分发方式的发布选项文件:`EXPORT_OPTIONS_PLIST=/path/ExportOptions.plist DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh`。脚本在下载或构建前检查 Team 非空、版本唯一有效、导出文件可读及 `plutil -lint` 通过;任何依赖、测试、归档或导出失败都会停止后续步骤。plist 格式检查不代表签名配置和发布选项已被 Xcode 接受。
|
||||
|
||||
仓库配置了 push/PR 源码审计 workflow 和手动 `apple-build.yml`。2026-10-27 通过认证的 iOS 仓库 runner API 返回 `total_count=0`;历史 5 次运行均是已取消的源码审计,没有 Apple 构建运行记录。当前没有可用 Mac runner 的证据,不能把 workflow 文件存在称为 CI 验收通过。Apple workflow 也未配置签名材料导入、IPA 附件上传或 TestFlight/MDM 发布。
|
||||
|
||||
## 目前验收范围
|
||||
|
||||
- Windows 可运行 `py -3 Scripts/source-audit.py` 检查项目结构、plist、Packet Tunnel entitlement、依赖 SHA256 及源码约束;它不会编译或运行 Swift。
|
||||
- `py -3 -m unittest discover -s Scripts/tests -p 'test_*.py' -v` 使用已有 Git Bash,在临时目录运行真实归档脚本,以替身命令验证参数、预检与失败停止。它不下载依赖,不执行 Xcode,不生成 IPA,也不证明真实 Apple 工具行为。
|
||||
- 当前没有已验证可用的 Mac/Xcode 构建机、Apple Developer Team 与包含 Network Extension 权限的 Provisioning Profile,也未完成 iPhone 真机授权和测试;Swift 编译、XCTest、签名、IPA 导出及真机全隧道验收均未完成。
|
||||
- 源码候选版不是可安装 IPA,不能把 ZIP 改名为 IPA,也不能以“绿色版”方式绕过 iOS 签名。
|
||||
|
||||
## 直接安装与发布限制
|
||||
|
||||
IPA 必须在 macOS 的 Xcode 中使用苹果开发者证书和包含 Network Extension / Packet Tunnel Provider 权限的 Provisioning Profile 签名。没有证书时可以审查全部源码,但不能生成可安装到普通 iPhone 的正式 IPA。
|
||||
|
||||
不通过 App Store 的可行交付方式只有经过苹果签名的 Ad Hoc、组织内 MDM/Custom App,或符合苹果条件的 Enterprise 内部分发;都不是免签名绿色版。获得构建机、Team ID 和授权后,运行 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh`,再用对应的 ExportOptions 导出 IPA。导出的 IPA 仍须按所选分发方式登记设备或由组织设备管理安装。
|
||||
|
||||
## 源码包说明
|
||||
|
||||
Git 源码不提交约 300 MB 的 `Vendor/LibXray.xcframework`,避免把第三方构建产物塞进业务仓库。`Scripts/fetch-libxray.sh` 会从 XTLS 官方 v26.7.28 发布页下载 `libxray-apple-cgo.zip`,严格核对下面的 SHA256 后放入正确目录。仓库不包含账号、密码、访问令牌、Apple 证书、Provisioning Profile 或私钥。
|
||||
|
||||
## 开源基础
|
||||
|
||||
VPN 核心使用 XTLS/libXray `v26.7.28`(MIT)及其对应的 Xray-core。官方二进制 SHA-256 为 `07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`。
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "landscape-header-v1.png",
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
@@ -1 +1 @@
|
||||
Geo 数据未打包。请按 ../../README.md 的资源说明取得并核验自己的合法数据;libXray 下载脚本不恢复 Geo 数据。
|
||||
Public source export omits Resources/Geo/geoip.dat and Resources/Geo/geosite.dat because their redistribution license was not established. Before building, obtain legally licensed compatible data, verify its origin/license and SHA256, and restore those exact paths. Vendor/LibXray.xcframework must be restored using Scripts/fetch-libxray.sh and its pinned hash; ThirdParty/ contains the retained license texts. Logo/trademark rights are not granted by MIT. Source-audit evidence covers the private complete frozen snapshot only. This export has not been compiled with Xcode, run through XCTest, signed, exported as IPA, or accepted on an Apple device.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# 蓝青山水头图 v1
|
||||
|
||||
## iOS 资源引用
|
||||
|
||||
- iOS 资源:`Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png`。
|
||||
- 来源:同仓库 Windows 工程 `../toplc-vpn-windows/assets/landscape-header-v1.png`,下文完整保留其相邻来源说明。
|
||||
- 2026-10-27 按字节复制原始 PNG,未进行栅格裁切、缩放、重绘或重新导出;SHA256 保持 `E87B91F59038C1E9CCFE616FBC84A0F6CD8D00D6D98E71388C62562017D9DFD8`。
|
||||
- SwiftUI 仅在屏幕背景与品牌头部使用原生等比填充裁切;所有文字、Logo、输入框、卡片与操作均由原生界面独立绘制。
|
||||
|
||||
## 原始来源说明
|
||||
|
||||
- 生成日期:2026-09-21。
|
||||
- 生成方式:内置 `image_gen`,原创装饰背景;没有把用户界面截图作为图像编辑目标。
|
||||
- 项目文件:`assets/landscape-header-v1.png`。
|
||||
- 实际尺寸:2172 × 724,PNG,3:1。未进行裁切、缩放或再绘制。
|
||||
- SHA256:`E87B91F59038C1E9CCFE616FBC84A0F6CD8D00D6D98E71388C62562017D9DFD8`。
|
||||
- 原始生成文件保留在:`C:/Users/Administrator/.codex/generated_images/01a0c255-9c6f-7c60-8b73-e3d797d0c29c/exec-ee03a49a-7931-433f-8a9c-db4b1e4ee543.png`。
|
||||
- 人工视觉检查:蓝青山水、雾、水面、小暖金日轮;上部及左右留白,无文字、商标、控件、统计数据或界面边框。官方 Logo、标题、窗口按钮、卡片、文字和图表必须由现有程序独立绘制。
|
||||
- 用途:窗口标题区域与品牌头图区连续的装饰背景,不是完整软件界面,不替代任何交互控件。
|
||||
|
||||
## 完整生成提示词
|
||||
|
||||
```text
|
||||
Use case: stylized-concept
|
||||
Asset type: standalone decorative panoramic header background for an existing Windows desktop app; NOT an interface mockup.
|
||||
Primary request: Create an original blue-cyan Chinese shanshui ink-and-watercolor mountain landscape, intended as a subtle continuous background behind a title bar and separate real software controls.
|
||||
Scene/backdrop: very pale icy blue sky, layered blue-cyan mountain ridges and rocky central peaks, drifting white mist and soft calm water; one small pale warm-gold sun at about 70 percent across, below the top safe strip.
|
||||
Style/medium: refined contemporary Chinese ink wash and watercolor, airy luminous atmosphere, lightly textured painting, restrained elegant detail.
|
||||
Composition/framing: very wide panoramic 3:1 aspect ratio, preferably 3072 by 1024 pixels. Keep the entire top 15 percent mostly clear pale sky so independent window buttons can later be drawn there. Keep the left 30 percent mostly open pale mist and sky for an existing official logo and product name added in code. Place the most distinct mountain peaks around the horizontal middle 40–65 percent, with peaks in the middle-to-lower half. Keep the rightmost 25 percent light and sparse for independent typography. Mountain bases and water dissolve softly into pale blue mist toward the bottom edge. Seamless tonal continuity across the entire canvas, no separate title bar or section bands.
|
||||
Color palette: icy blue-white, powder blue, restrained cyan-teal, muted indigo-blue details and a small pale gold sun; never black-heavy or saturated dark background.
|
||||
Constraints: output ONLY the landscape illustration. Absolutely NO text, lettering, calligraphy, Chinese characters, signature, watermark, stamps, red seals, logos, compass marks, icons, buttons, graphs, cards, borders, interface panels, people, buildings, labels, or numerals. This is a reusable background asset, not a screenshot and not a full UI.
|
||||
```
|
||||
@@ -20,10 +20,19 @@ EXPECTED = [
|
||||
"Shared/Models.swift",
|
||||
"Shared/TunnelConfigurationBuilder.swift",
|
||||
"Shared/NetworkAddress.swift",
|
||||
"Resources/Geo/geoip.dat",
|
||||
"Resources/Geo/geosite.dat",
|
||||
"Tests/TunnelConfigurationBuilderTests.swift",
|
||||
"Tests/ClientConfigResponseTests.swift",
|
||||
"Shared/ConnectionAttemptPolicy.swift",
|
||||
"Tests/ConnectionAttemptPolicyTests.swift",
|
||||
"Shared/ProxyTransportPolicy.swift",
|
||||
"Shared/ICMPEchoPacket.swift",
|
||||
"App/InternalIPProbe.swift",
|
||||
"Tests/ProxyTransportPolicyTests.swift",
|
||||
"Tests/ICMPEchoPacketTests.swift",
|
||||
"Resources/Assets.xcassets/MountainLandscape.imageset/Contents.json",
|
||||
"Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png",
|
||||
]
|
||||
|
||||
|
||||
@@ -54,6 +63,15 @@ def main() -> int:
|
||||
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 最低版本与验收基线不一致")
|
||||
require("Shared/ProxyTransportPolicy.swift" in project,
|
||||
"Packet Tunnel 未包含授权入口校验类型")
|
||||
artwork = ROOT / "Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png"
|
||||
require(hashlib.sha256(artwork.read_bytes()).hexdigest()
|
||||
== "e87b91f59038c1e9ccfe616fbc84a0f6cd8d00d6d98e71388c62562017d9dfd8",
|
||||
"原创山水图摘要不匹配")
|
||||
asset = json.loads(artwork.with_name("Contents.json").read_text(encoding="utf-8"))
|
||||
require(any(image.get("filename") == artwork.name for image in asset.get("images", [])),
|
||||
"山水资源索引缺失")
|
||||
|
||||
app_state = (ROOT / "App/AppState.swift").read_text(encoding="utf-8")
|
||||
api = (ROOT / "App/PlatformAPI.swift").read_text(encoding="utf-8")
|
||||
@@ -90,16 +108,9 @@ def main() -> int:
|
||||
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,
|
||||
@@ -107,6 +118,13 @@ def main() -> int:
|
||||
"domain_loop_prevention": True,
|
||||
"gateway_contract": 2,
|
||||
"legacy_backend_compatible": True,
|
||||
"authorized_internal_ip_source_implemented": True,
|
||||
"sticky_public_fallback_source_implemented": True,
|
||||
"original_landscape_sha256": hashlib.sha256(artwork.read_bytes()).hexdigest(),
|
||||
"swift_compilation_executed": False,
|
||||
"xctest_executed": False,
|
||||
"ipa_generated": False,
|
||||
"device_installation_verified": False,
|
||||
"network_extension_entitlement": True,
|
||||
"libxray_archive_sha256": vendor_result,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Offline subprocess checks for archive orchestration, never Xcode acceptance."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "verify-and-archive.sh"
|
||||
|
||||
|
||||
def find_bash() -> str | None:
|
||||
if os.name == "nt":
|
||||
candidate = Path("C:/Program Files/Git/bin/bash.exe")
|
||||
return str(candidate) if candidate.is_file() else None
|
||||
return shutil.which("bash")
|
||||
|
||||
|
||||
BASH = find_bash()
|
||||
|
||||
|
||||
@unittest.skipUnless(BASH, "Requires bash; Windows checks use existing Git Bash")
|
||||
class ArchiveScriptTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ucvl-ios-archive-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
(self.root / "Scripts").mkdir()
|
||||
(self.root / "bin").mkdir()
|
||||
self.trace = self.root / "trace"
|
||||
self.trace.mkdir()
|
||||
shutil.copyfile(SCRIPT, self.root / "Scripts/verify-and-archive.sh")
|
||||
self.project(' MARKETING_VERSION: "1.0.3"\n')
|
||||
self.environment = os.environ.copy()
|
||||
self.environment.update({
|
||||
"PATH": str(self.root / "bin") + os.pathsep + self.environment.get("PATH", ""),
|
||||
"DEVELOPMENT_TEAM": "TESTTEAM01",
|
||||
"ARCHIVE_TEST_TRACE": self.trace.as_posix(),
|
||||
})
|
||||
for name in ("EXPORT_OPTIONS_PLIST", "SIMULATOR_DESTINATION", "ARCHIVE_TEST_FAIL_STAGE"):
|
||||
self.environment.pop(name, None)
|
||||
for stage, name in (("fetch", "fetch-libxray.sh"), ("generate", "generate-project.sh")):
|
||||
self.executable(self.root / "Scripts" / name,
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
f'printf "%s\\n" {stage} >> "$ARCHIVE_TEST_TRACE/events"\n'
|
||||
f'[ "${{ARCHIVE_TEST_FAIL_STAGE:-}}" != {stage} ] || exit 37\n')
|
||||
self.executable(self.root / "bin/xcodebuild", r'''#!/bin/sh
|
||||
set -eu
|
||||
action=
|
||||
for argument do
|
||||
case "$argument" in test|archive|-exportArchive) action=$argument;; esac
|
||||
done
|
||||
[ "$action" != -exportArchive ] || action=export
|
||||
printf '%s\n' "$action" >> "$ARCHIVE_TEST_TRACE/events"
|
||||
printf '%s\0' "$@" > "$ARCHIVE_TEST_TRACE/$action.args"
|
||||
[ "${ARCHIVE_TEST_FAIL_STAGE:-}" != "$action" ] || exit 37
|
||||
''')
|
||||
self.executable(self.root / "bin/plutil", r'''#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\n' validate_export >> "$ARCHIVE_TEST_TRACE/events"
|
||||
printf '%s\0' "$@" > "$ARCHIVE_TEST_TRACE/plutil.args"
|
||||
[ "${ARCHIVE_TEST_FAIL_STAGE:-}" != validate_export ] || exit 37
|
||||
''')
|
||||
|
||||
@staticmethod
|
||||
def executable(path: Path, text: str) -> None:
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
path.chmod(0o755)
|
||||
|
||||
def project(self, text: str) -> None:
|
||||
(self.root / "project.yml").write_text("settings:\n base:\n" + text,
|
||||
encoding="utf-8", newline="\n")
|
||||
|
||||
def run_script(self) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([BASH, "--noprofile", "--norc", "./Scripts/verify-and-archive.sh"],
|
||||
cwd=self.root, env=self.environment, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=15, check=False)
|
||||
|
||||
def events(self) -> list[str]:
|
||||
path = self.trace / "events"
|
||||
return path.read_text(encoding="utf-8").splitlines() if path.exists() else []
|
||||
|
||||
def arguments(self, stage: str) -> list[str]:
|
||||
raw = (self.trace / (stage + ".args")).read_bytes()
|
||||
self.assertTrue(raw.endswith(b"\0"))
|
||||
return [value.decode("utf-8") for value in raw[:-1].split(b"\0")]
|
||||
|
||||
def export_options(self) -> str:
|
||||
path = self.root / "export options.plist"
|
||||
path.write_bytes(plistlib.dumps({"method": "debugging", "teamID": "TESTTEAM01"}))
|
||||
return path.as_posix()
|
||||
|
||||
def test_archive_uses_project_version_and_default_simulator(self) -> None:
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.events(), ["fetch", "generate", "test", "archive"])
|
||||
self.assertEqual(self.arguments("test"), [
|
||||
"-project", "UCVLZonghengjia.xcodeproj", "-scheme", "UCVLZonghengjia",
|
||||
"-destination", "platform=iOS Simulator,name=iPhone 16 Pro",
|
||||
"DEVELOPMENT_TEAM=TESTTEAM01", "test"])
|
||||
self.assertEqual(self.arguments("archive"), [
|
||||
"-project", "UCVLZonghengjia.xcodeproj", "-scheme", "UCVLZonghengjia",
|
||||
"-configuration", "Release", "-destination", "generic/platform=iOS",
|
||||
"-archivePath", "build/UCVL-Zonghengjia-1.0.3.xcarchive",
|
||||
"DEVELOPMENT_TEAM=TESTTEAM01", "archive"])
|
||||
|
||||
def test_changed_project_version_changes_archive_path(self) -> None:
|
||||
self.project(' MARKETING_VERSION: "2.7.19"\n')
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
arguments = self.arguments("archive")
|
||||
self.assertEqual(arguments[arguments.index("-archivePath") + 1],
|
||||
"build/UCVL-Zonghengjia-2.7.19.xcarchive")
|
||||
|
||||
def test_explicit_simulator_destination_is_one_argument(self) -> None:
|
||||
self.environment["SIMULATOR_DESTINATION"] = "platform=iOS Simulator,id=test-simulator-id"
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
arguments = self.arguments("test")
|
||||
self.assertEqual(arguments[arguments.index("-destination") + 1],
|
||||
"platform=iOS Simulator,id=test-simulator-id")
|
||||
|
||||
def test_export_validates_first_and_uses_same_versioned_archive(self) -> None:
|
||||
options = self.export_options()
|
||||
self.environment["EXPORT_OPTIONS_PLIST"] = options
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.events(), ["validate_export", "fetch", "generate", "test", "archive", "export"])
|
||||
self.assertEqual(self.arguments("plutil"), ["-lint", "--", options])
|
||||
self.assertEqual(self.arguments("export"), [
|
||||
"-exportArchive", "-archivePath", "build/UCVL-Zonghengjia-1.0.3.xcarchive",
|
||||
"-exportPath", "build/export", "-exportOptionsPlist", options])
|
||||
|
||||
def test_missing_team_stops_before_external_commands(self) -> None:
|
||||
self.environment.pop("DEVELOPMENT_TEAM")
|
||||
result = self.run_script()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.events(), [])
|
||||
|
||||
def test_missing_export_file_stops_before_fetch_or_build(self) -> None:
|
||||
self.environment["EXPORT_OPTIONS_PLIST"] = (self.root / "missing.plist").as_posix()
|
||||
result = self.run_script()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.events(), [])
|
||||
|
||||
def test_export_lint_failure_stops_before_fetch_or_build(self) -> None:
|
||||
self.environment["EXPORT_OPTIONS_PLIST"] = self.export_options()
|
||||
self.environment["ARCHIVE_TEST_FAIL_STAGE"] = "validate_export"
|
||||
result = self.run_script()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.events(), ["validate_export"])
|
||||
|
||||
def test_invalid_or_ambiguous_project_version_stops_before_fetch(self) -> None:
|
||||
for text in (' SWIFT_VERSION: "5.10"\n',
|
||||
' MARKETING_VERSION: "../../escape"\n',
|
||||
' MARKETING_VERSION: "1.0.3"\n MARKETING_VERSION: "1.0.4"\n'):
|
||||
with self.subTest(project=text):
|
||||
self.project(text)
|
||||
result = self.run_script()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.events(), [])
|
||||
|
||||
def test_each_failed_stage_prevents_all_later_stages(self) -> None:
|
||||
stages = ["fetch", "generate", "test", "archive", "export"]
|
||||
self.environment["EXPORT_OPTIONS_PLIST"] = self.export_options()
|
||||
for index, stage in enumerate(stages):
|
||||
with self.subTest(stage=stage):
|
||||
(self.trace / "events").unlink(missing_ok=True)
|
||||
self.environment["ARCHIVE_TEST_FAIL_STAGE"] = stage
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 37, result.stderr)
|
||||
self.assertEqual(self.events(), ["validate_export"] + stages[:index + 1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Exercise the source-audit boundary; these are not Swift runtime tests."""
|
||||
from contextlib import redirect_stdout
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "source-audit.py"
|
||||
spec = importlib.util.spec_from_file_location("ios_source_audit", SCRIPT)
|
||||
audit = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(audit)
|
||||
SOURCE = SCRIPT.parent.parent
|
||||
|
||||
|
||||
class SourceAuditTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name) / "ios"
|
||||
shutil.copytree(SOURCE, self.root,
|
||||
ignore=shutil.ignore_patterns(".git", "Vendor", "BuildArtifacts", "__pycache__"))
|
||||
self.original = audit.ROOT
|
||||
audit.ROOT = self.root
|
||||
self.addCleanup(setattr, audit, "ROOT", self.original)
|
||||
|
||||
def run_audit(self):
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output):
|
||||
result = audit.main()
|
||||
self.assertEqual(result, 0)
|
||||
return json.loads(output.getvalue())
|
||||
|
||||
def test_valid_source_reports_only_source_acceptance(self):
|
||||
report = self.run_audit()
|
||||
self.assertEqual(report["source_version"], "1.0.3")
|
||||
self.assertFalse(report["swift_compilation_executed"])
|
||||
self.assertFalse(report["xctest_executed"])
|
||||
self.assertFalse(report["ipa_generated"])
|
||||
self.assertFalse(report["device_installation_verified"])
|
||||
|
||||
def test_missing_shared_policy_stops_audit(self):
|
||||
(self.root / "Shared/ProxyTransportPolicy.swift").unlink()
|
||||
with self.assertRaisesRegex(RuntimeError, "ProxyTransportPolicy"):
|
||||
self.run_audit()
|
||||
|
||||
def test_unbundled_artwork_stops_audit(self):
|
||||
path = self.root / "Resources/Assets.xcassets/MountainLandscape.imageset/Contents.json"
|
||||
path.write_text('{"images":[]}', encoding="utf-8")
|
||||
with self.assertRaisesRegex(RuntimeError, "山水资源"):
|
||||
self.run_audit()
|
||||
|
||||
def test_modified_artwork_stops_audit(self):
|
||||
path = self.root / "Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png"
|
||||
path.write_bytes(b"replaced artwork")
|
||||
with self.assertRaisesRegex(RuntimeError, "山水图"):
|
||||
self.run_audit()
|
||||
|
||||
def test_missing_extension_entitlement_stops_audit(self):
|
||||
path = self.root / "PacketTunnel/PacketTunnel.entitlements"
|
||||
path.write_bytes(plistlib.dumps({}))
|
||||
with self.assertRaisesRegex(RuntimeError, "权限缺失"):
|
||||
self.run_audit()
|
||||
|
||||
def test_version_mismatch_stops_audit(self):
|
||||
path = self.root / "README.md"
|
||||
path.write_text(path.read_text(encoding="utf-8").replace("1.0.3", "1.0.2"), encoding="utf-8")
|
||||
with self.assertRaisesRegex(RuntimeError, "版本不一致"):
|
||||
self.run_audit()
|
||||
|
||||
def test_modified_vendor_archive_stops_audit(self):
|
||||
path = self.root / "Vendor/libxray-apple-cgo-v26.7.28.zip"
|
||||
path.parent.mkdir()
|
||||
path.write_bytes(b"untrusted binary")
|
||||
with self.assertRaisesRegex(RuntimeError, "libXray"):
|
||||
self.run_audit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,12 +5,43 @@ test -n "${DEVELOPMENT_TEAM:-}" || {
|
||||
echo "请设置 DEVELOPMENT_TEAM(Apple Developer Team ID)。" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
source_version=$(awk '
|
||||
$1 == "MARKETING_VERSION:" {
|
||||
value = $2
|
||||
sub(/^"/, "", value)
|
||||
sub(/"$/, "", value)
|
||||
if (value !~ /^[0-9]+\.[0-9]+\.[0-9]+$/ || seen++) exit 1
|
||||
version = value
|
||||
}
|
||||
END {
|
||||
if (seen != 1 || version == "") exit 1
|
||||
print version
|
||||
}
|
||||
' project.yml) || {
|
||||
echo "project.yml 必须包含唯一的数字三段 MARKETING_VERSION。" >&2
|
||||
exit 1
|
||||
}
|
||||
archive_path="build/UCVL-Zonghengjia-${source_version}.xcarchive"
|
||||
simulator_destination=${SIMULATOR_DESTINATION:-'platform=iOS Simulator,name=iPhone 16 Pro'}
|
||||
|
||||
if [ -n "${EXPORT_OPTIONS_PLIST:-}" ]; then
|
||||
test -f "$EXPORT_OPTIONS_PLIST" && test -r "$EXPORT_OPTIONS_PLIST" || {
|
||||
echo "EXPORT_OPTIONS_PLIST 必须指定可读的发布选项文件。" >&2
|
||||
exit 1
|
||||
}
|
||||
plutil -lint -- "$EXPORT_OPTIONS_PLIST" >/dev/null || {
|
||||
echo "EXPORT_OPTIONS_PLIST 不是有效的 plist 文件。" >&2
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
|
||||
./Scripts/fetch-libxray.sh
|
||||
./Scripts/generate-project.sh
|
||||
xcodebuild \
|
||||
-project UCVLZonghengjia.xcodeproj \
|
||||
-scheme UCVLZonghengjia \
|
||||
-destination 'platform=iOS Simulator,name=iPhone 16 Pro' \
|
||||
-destination "$simulator_destination" \
|
||||
DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
|
||||
test
|
||||
xcodebuild \
|
||||
@@ -18,18 +49,14 @@ xcodebuild \
|
||||
-scheme UCVLZonghengjia \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \
|
||||
-archivePath "$archive_path" \
|
||||
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 \
|
||||
-archivePath "$archive_path" \
|
||||
-exportPath build/export \
|
||||
-exportOptionsPlist "$EXPORT_OPTIONS_PLIST"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
// A nonce in the payload binds a reply to this request. The kernel may rewrite
|
||||
// the identifier on an unprivileged datagram ICMP socket.
|
||||
enum ICMPEchoPacket {
|
||||
static func checksum(_ bytes: [UInt8]) -> UInt16 {
|
||||
var sum: UInt32 = 0
|
||||
var index = 0
|
||||
while index + 1 < bytes.count {
|
||||
sum += (UInt32(bytes[index]) << 8) | UInt32(bytes[index + 1])
|
||||
index += 2
|
||||
}
|
||||
if index < bytes.count { sum += UInt32(bytes[index]) << 8 }
|
||||
while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) }
|
||||
return ~UInt16(sum)
|
||||
}
|
||||
|
||||
static func request(identifier: UInt16, payload: [UInt8]) -> [UInt8] {
|
||||
var bytes: [UInt8] = [8, 0, 0, 0, UInt8(identifier >> 8), UInt8(identifier & 0xff), 0, 1]
|
||||
bytes += payload
|
||||
let value = checksum(bytes)
|
||||
bytes[2] = UInt8(value >> 8)
|
||||
bytes[3] = UInt8(value & 0xff)
|
||||
return bytes
|
||||
}
|
||||
|
||||
static func isReply(_ received: [UInt8], payload: [UInt8]) -> Bool {
|
||||
var offset = 0
|
||||
if let first = received.first, first >> 4 == 4 {
|
||||
offset = Int(first & 0x0f) * 4
|
||||
guard offset >= 20 else { return false }
|
||||
}
|
||||
guard received.count == offset + 8 + payload.count else { return false }
|
||||
let reply = Array(received.dropFirst(offset))
|
||||
return reply[0] == 0 && reply[1] == 0 && reply[6] == 0 && reply[7] == 1
|
||||
&& Array(reply.dropFirst(8)) == payload && checksum(reply) == 0
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,18 @@ struct VPNNode: Decodable, Identifiable, Hashable, Sendable {
|
||||
let region: String
|
||||
let status: String
|
||||
|
||||
enum CodingKeys: String, CodingKey { case slug, name, region, status }
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
slug = try container.decode(String.self, forKey: .slug)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
region = try container.decode(String.self, forKey: .region)
|
||||
// Config responses omit the profile-only node status. Absence is not
|
||||
// evidence of offline/online state and must not break a valid config.
|
||||
status = try container.decodeIfPresent(String.self, forKey: .status) ?? "unknown"
|
||||
}
|
||||
|
||||
var id: String { slug }
|
||||
var displayName: String { region.isEmpty ? name : "\(name) · \(region)" }
|
||||
}
|
||||
@@ -121,6 +133,8 @@ struct ClientConfigResponse: Decodable, Sendable {
|
||||
|
||||
let configContract: Int?
|
||||
let gateway: Gateway?
|
||||
let tailscaleEndpoint: ProxyTransportEndpoint?
|
||||
let connectionScope: String?
|
||||
let node: VPNNode
|
||||
let routeMode: String
|
||||
let config: [String: JSONValue]
|
||||
@@ -128,11 +142,34 @@ struct ClientConfigResponse: Decodable, Sendable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case configContract = "config_contract"
|
||||
case gateway
|
||||
case tailscaleEndpoint = "tailscale_endpoint"
|
||||
case connectionScope = "connection_scope"
|
||||
case node
|
||||
case routeMode = "route_mode"
|
||||
case config
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
configContract = try container.decodeIfPresent(Int.self, forKey: .configContract)
|
||||
gateway = try container.decodeIfPresent(Gateway.self, forKey: .gateway)
|
||||
node = try container.decode(VPNNode.self, forKey: .node)
|
||||
routeMode = try container.decode(String.self, forKey: .routeMode)
|
||||
config = try container.decode([String: JSONValue].self, forKey: .config)
|
||||
|
||||
// Optional transport hints never make a valid public configuration fail.
|
||||
// A malformed scope also disables the hint: it is not a legacy absence.
|
||||
let scopeIsNull = (try? container.decodeNil(forKey: .connectionScope)) ?? true
|
||||
let scopePresent = container.contains(.connectionScope) && !scopeIsNull
|
||||
let decodedScope = try? container.decode(String.self, forKey: .connectionScope)
|
||||
connectionScope = decodedScope
|
||||
if scopePresent && decodedScope == nil {
|
||||
tailscaleEndpoint = nil
|
||||
} else {
|
||||
tailscaleEndpoint = try? container.decode(ProxyTransportEndpoint.self, forKey: .tailscaleEndpoint)
|
||||
}
|
||||
}
|
||||
|
||||
func configJSONString() throws -> String {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import Foundation
|
||||
|
||||
enum NetworkAddress {
|
||||
static func isAuthorizedInternalIPv4(_ value: String) -> Bool {
|
||||
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4 else { return false }
|
||||
let octets = parts.compactMap { UInt8($0) }
|
||||
guard octets.count == 4,
|
||||
octets.map({ String($0) }).joined(separator: ".") == value,
|
||||
octets[0] == 100,
|
||||
(64...127).contains(octets[1])
|
||||
else { return false }
|
||||
return value != "100.64.0.0"
|
||||
&& value != "100.127.255.255"
|
||||
&& value != "100.100.100.100"
|
||||
}
|
||||
|
||||
static func isPublicIPv4(_ value: String) -> Bool {
|
||||
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import Foundation
|
||||
|
||||
struct ProxyTransportEndpoint: Codable, Equatable, Sendable {
|
||||
let contract: Int
|
||||
let nodeSlug: String
|
||||
let address: String
|
||||
let port: Int
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case contract
|
||||
case nodeSlug = "node_slug"
|
||||
case address
|
||||
case port
|
||||
}
|
||||
}
|
||||
|
||||
// One value belongs to one explicit user connection, including its node retries.
|
||||
// Once public ingress is chosen, automatic recovery has no promotion operation.
|
||||
struct ProxyTransportSession {
|
||||
private(set) var domainOnly = false
|
||||
|
||||
mutating func commitPublicFallback() {
|
||||
domainOnly = true
|
||||
}
|
||||
}
|
||||
|
||||
enum ProxyTransportPolicy {
|
||||
static func authorizedInternalEndpoint(response: ClientConfigResponse) -> ProxyTransportEndpoint? {
|
||||
guard let rawJSON = try? response.configJSONString() else { return nil }
|
||||
return authorizedInternalEndpoint(
|
||||
endpoint: response.tailscaleEndpoint,
|
||||
nodeSlug: response.node.slug,
|
||||
configContract: response.configContract,
|
||||
connectionScope: response.connectionScope,
|
||||
routeMode: response.routeMode,
|
||||
configJSON: rawJSON
|
||||
)
|
||||
}
|
||||
|
||||
// The Packet Tunnel repeats the same gates over its saved original config.
|
||||
static func authorizedInternalEndpoint(
|
||||
endpoint: ProxyTransportEndpoint?,
|
||||
nodeSlug: String,
|
||||
configContract: Int?,
|
||||
connectionScope: String?,
|
||||
routeMode: String,
|
||||
configJSON: String
|
||||
) -> ProxyTransportEndpoint? {
|
||||
guard let endpoint,
|
||||
configContract == 2,
|
||||
connectionScope == nil || connectionScope == "" || connectionScope == "public",
|
||||
routeMode == "smart" || routeMode == "global",
|
||||
!nodeSlug.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
endpoint.nodeSlug == nodeSlug,
|
||||
isValidEndpoint(endpoint),
|
||||
let root = configurationRoot(configJSON),
|
||||
proxyIndex(in: root) != nil
|
||||
else { return nil }
|
||||
return endpoint
|
||||
}
|
||||
|
||||
// The caller keeps rawJSON for same-node public fallback. Nothing else in
|
||||
// the authorization, Reality identity or routing is reconstructed here.
|
||||
static func internalConfigJSON(rawJSON: String, endpoint: ProxyTransportEndpoint) throws -> String {
|
||||
guard isValidEndpoint(endpoint),
|
||||
var root = configurationRoot(rawJSON),
|
||||
let index = proxyIndex(in: root),
|
||||
var outbounds = root["outbounds"] as? [[String: Any]],
|
||||
var settings = outbounds[index]["settings"] as? [String: Any],
|
||||
var servers = settings["vnext"] as? [[String: Any]]
|
||||
else {
|
||||
throw UCVLError.invalidConfiguration("授权内部入口与节点代理配置不匹配。")
|
||||
}
|
||||
servers[0]["address"] = endpoint.address
|
||||
servers[0]["port"] = endpoint.port
|
||||
settings["vnext"] = servers
|
||||
outbounds[index]["settings"] = settings
|
||||
root["outbounds"] = outbounds
|
||||
let output = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])
|
||||
return String(decoding: output, as: UTF8.self)
|
||||
}
|
||||
|
||||
private static func isValidEndpoint(_ endpoint: ProxyTransportEndpoint) -> Bool {
|
||||
endpoint.contract == 1
|
||||
&& !endpoint.nodeSlug.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
&& NetworkAddress.isAuthorizedInternalIPv4(endpoint.address)
|
||||
&& (1...65535).contains(endpoint.port)
|
||||
}
|
||||
|
||||
private static func configurationRoot(_ rawJSON: String) -> [String: Any]? {
|
||||
guard let data = rawJSON.data(using: .utf8),
|
||||
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
root["ucvl_private_auxiliary"] == nil,
|
||||
root["ucvl_tailnet_transport"] == nil
|
||||
else { return nil }
|
||||
return root
|
||||
}
|
||||
|
||||
private static func proxyIndex(in root: [String: Any]) -> Int? {
|
||||
guard let outbounds = root["outbounds"] as? [[String: Any]] else { return nil }
|
||||
let matches = outbounds.indices.filter { outbounds[$0]["tag"] as? String == "proxy" }
|
||||
guard matches.count == 1, let index = matches.first else { return nil }
|
||||
let proxy = outbounds[index]
|
||||
guard proxy["protocol"] as? String == "vless",
|
||||
let settings = proxy["settings"] as? [String: Any],
|
||||
let servers = settings["vnext"] as? [[String: Any]], servers.count == 1,
|
||||
let users = servers[0]["users"] as? [[String: Any]], !users.isEmpty,
|
||||
users.allSatisfy({ nonemptyString($0["id"]) }),
|
||||
let stream = proxy["streamSettings"] as? [String: Any],
|
||||
stream["security"] as? String == "reality",
|
||||
let network = stream["network"] as? String,
|
||||
network == "tcp" || network == "raw",
|
||||
let reality = stream["realitySettings"] as? [String: Any],
|
||||
nonemptyString(reality["serverName"]),
|
||||
nonemptyString(reality["password"]) || nonemptyString(reality["publicKey"])
|
||||
else { return nil }
|
||||
return index
|
||||
}
|
||||
|
||||
private static func nonemptyString(_ value: Any?) -> Bool {
|
||||
guard let value = value as? String else { return false }
|
||||
return !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,20 @@ import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class ClientConfigResponseTests: XCTestCase {
|
||||
func testActualBackendConfigNodeDoesNotRequireProfileOnlyStatus() throws {
|
||||
let data = Data(#"{"config_contract":2,"node":{"slug":"n1","name":"VPN001","region":"东京"},"route_mode":"smart","config":{}}"#.utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
XCTAssertEqual(response.node.slug, "n1")
|
||||
XCTAssertEqual(response.node.status, "unknown")
|
||||
}
|
||||
|
||||
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 data = Data(#"{"config_contract":2,"gateway":{"host":"vpn.example.invalid","ipv4":"203.0.113.17"},"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")
|
||||
XCTAssertEqual(response.gateway?.host, "vpn.example.invalid")
|
||||
XCTAssertEqual(response.gateway?.ipv4, "203.0.113.17")
|
||||
}
|
||||
|
||||
func testOldBackendPayloadRemainsCompatible() throws {
|
||||
@@ -17,5 +24,42 @@ final class ClientConfigResponseTests: XCTestCase {
|
||||
|
||||
XCTAssertNil(response.configContract)
|
||||
XCTAssertNil(response.gateway)
|
||||
XCTAssertNil(response.tailscaleEndpoint)
|
||||
XCTAssertNil(response.connectionScope)
|
||||
}
|
||||
|
||||
func testDecodesOptionalInternalEndpointWithoutChangingPublicConfiguration() throws {
|
||||
let data = Data(#"{"config_contract":2,"connection_scope":"public","tailscale_endpoint":{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":12001},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}"#.utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
|
||||
XCTAssertEqual(response.connectionScope, "public")
|
||||
XCTAssertEqual(response.tailscaleEndpoint?.nodeSlug, "n1")
|
||||
XCTAssertEqual(response.tailscaleEndpoint?.address, "100.70.1.2")
|
||||
XCTAssertEqual(response.tailscaleEndpoint?.port, 12001)
|
||||
XCTAssertEqual(response.config["public"], .string("preserved"))
|
||||
}
|
||||
|
||||
func testMalformedOptionalEndpointDoesNotBreakPublicPayload() throws {
|
||||
for optionalValue in ["null", "true", "[]", "{}", #"{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":"12001"}"#] {
|
||||
let data = Data("""
|
||||
{"tailscale_endpoint":\(optionalValue),"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}
|
||||
""".utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
|
||||
XCTAssertNil(response.tailscaleEndpoint)
|
||||
XCTAssertEqual(response.config["public"], .string("preserved"))
|
||||
}
|
||||
}
|
||||
|
||||
func testMalformedOptionalScopeDisablesInternalEndpointAndPreservesPublicPayload() throws {
|
||||
for scope in ["true", "1", "[]", "{}"] {
|
||||
let data = Data("""
|
||||
{"config_contract":2,"connection_scope":\(scope),"tailscale_endpoint":{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":12001},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}
|
||||
""".utf8)
|
||||
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
|
||||
|
||||
XCTAssertNil(response.tailscaleEndpoint)
|
||||
XCTAssertEqual(response.config["public"], .string("preserved"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class ICMPEchoPacketTests: XCTestCase {
|
||||
func testEchoRequestHasValidChecksumAndPayload() {
|
||||
let payload: [UInt8] = [1, 2, 3, 4, 5]
|
||||
let request = ICMPEchoPacket.request(identifier: 0x1234, payload: payload)
|
||||
XCTAssertEqual(Array(request.prefix(2)), [8, 0])
|
||||
XCTAssertEqual(Array(request[4..<8]), [0x12, 0x34, 0, 1])
|
||||
XCTAssertEqual(Array(request.dropFirst(8)), payload)
|
||||
XCTAssertEqual(ICMPEchoPacket.checksum(request), 0)
|
||||
}
|
||||
|
||||
func testAcceptsOnlyMatchingEchoReply() {
|
||||
let payload: [UInt8] = [11, 12, 13]
|
||||
var reply = ICMPEchoPacket.request(identifier: 7, payload: payload)
|
||||
reply[0] = 0
|
||||
reply[2] = 0
|
||||
reply[3] = 0
|
||||
let checksum = ICMPEchoPacket.checksum(reply)
|
||||
reply[2] = UInt8(checksum >> 8)
|
||||
reply[3] = UInt8(checksum & 0xff)
|
||||
XCTAssertTrue(ICMPEchoPacket.isReply(reply, payload: payload))
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: [99]))
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply(Array(reply.dropLast()), payload: payload))
|
||||
reply[1] = 1
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: payload))
|
||||
}
|
||||
|
||||
func testRejectsRequestAndCorruptReply() {
|
||||
let payload: [UInt8] = [11, 12]
|
||||
let request = ICMPEchoPacket.request(identifier: 7, payload: payload)
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply(request, payload: payload))
|
||||
var corrupt = request
|
||||
corrupt[0] = 0
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply(corrupt, payload: payload))
|
||||
XCTAssertFalse(ICMPEchoPacket.isReply([], payload: []))
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,15 @@ import XCTest
|
||||
|
||||
final class NetworkAddressTests: XCTestCase {
|
||||
func testAcceptsPublicIPv4() {
|
||||
XCTAssertTrue(NetworkAddress.isPublicIPv4("192.0.2.1"))
|
||||
XCTAssertTrue(NetworkAddress.isPublicIPv4("203.0.113.17"))
|
||||
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("192.168.8.1"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("100.99.142.38"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("198.18.0.119"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.toplc.cn"))
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.example.invalid"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import XCTest
|
||||
@testable import UCVLZonghengjia
|
||||
|
||||
final class ProxyTransportPolicyTests: XCTestCase {
|
||||
private let fixture = #"""
|
||||
{
|
||||
"config_contract":2,"connection_scope":"public",
|
||||
"tailscale_endpoint":{"contract":1,"node_slug":"fixture-node","address":"100.70.1.2","port":12001},
|
||||
"node":{"slug":"fixture-node","name":"Fixture","region":"","status":"online"},
|
||||
"route_mode":"smart",
|
||||
"config":{
|
||||
"log":{"loglevel":"warning"},
|
||||
"outbounds":[
|
||||
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"node.example.test","port":443,"users":[{"id":"11111111-2222-3333-4444-555555555555","flow":"xtls-rprx-vision","encryption":"none"}]}]},"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"server.example.test","publicKey":"fixture-public-key","shortId":"abcd"}}},
|
||||
{"tag":"direct","protocol":"freedom"}
|
||||
],
|
||||
"routing":{"rules":[{"type":"field","domain":["example.test"],"outboundTag":"proxy"}]}
|
||||
}
|
||||
}
|
||||
"""#
|
||||
|
||||
private func response(_ change: (inout [String: Any]) -> Void = { _ in }) throws -> ClientConfigResponse {
|
||||
var root = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(fixture.utf8)) as? [String: Any])
|
||||
change(&root)
|
||||
return try JSONDecoder().decode(ClientConfigResponse.self, from: JSONSerialization.data(withJSONObject: root))
|
||||
}
|
||||
|
||||
private func changingEndpoint(_ change: (inout [String: Any]) -> Void) throws -> ClientConfigResponse {
|
||||
try response { root in
|
||||
var endpoint = root["tailscale_endpoint"] as! [String: Any]
|
||||
change(&endpoint)
|
||||
root["tailscale_endpoint"] = endpoint
|
||||
}
|
||||
}
|
||||
|
||||
private func changingProxy(_ change: (inout [String: Any]) -> Void) throws -> ClientConfigResponse {
|
||||
try response { root in
|
||||
var config = root["config"] as! [String: Any]
|
||||
var outbounds = config["outbounds"] as! [[String: Any]]
|
||||
change(&outbounds[0])
|
||||
config["outbounds"] = outbounds
|
||||
root["config"] = config
|
||||
}
|
||||
}
|
||||
|
||||
func testAcceptsOnlyCanonicalAuthorizedInternalIPv4() {
|
||||
for address in ["100.64.0.1", "100.70.1.2", "100.127.255.254"] {
|
||||
XCTAssertTrue(NetworkAddress.isAuthorizedInternalIPv4(address), address)
|
||||
XCTAssertFalse(NetworkAddress.isPublicIPv4(address), address)
|
||||
}
|
||||
for address in ["100.63.255.255", "100.128.0.0", "100.64.0.0", "100.127.255.255", "100.100.100.100", "100.070.1.2", "+100.70.1.2", " 100.70.1.2", "100.70.1.2 ", "100.70.1", "100.70.1.256", "192.168.1.2", "198.18.1.2", "8.8.8.8", "node.example.test"] {
|
||||
XCTAssertFalse(NetworkAddress.isAuthorizedInternalIPv4(address), address)
|
||||
}
|
||||
}
|
||||
|
||||
func testAuthorizedEndpointAcceptsCompatiblePublicScopesAndRouteModes() throws {
|
||||
for scope in [nil, "", "public"] as [String?] {
|
||||
for route in ["smart", "global"] {
|
||||
let value = try response { root in
|
||||
root["connection_scope"] = scope
|
||||
root["route_mode"] = route
|
||||
}
|
||||
XCTAssertEqual(ProxyTransportPolicy.authorizedInternalEndpoint(response: value)?.address, "100.70.1.2")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testMissingInvalidOrUnauthorizedMetadataNeverCreatesAnInternalCandidate() throws {
|
||||
let changes: [(inout [String: Any]) -> Void] = [
|
||||
{ $0.removeValue(forKey: "tailscale_endpoint") },
|
||||
{ $0["tailscale_endpoint"] = NSNull() },
|
||||
{ $0["config_contract"] = 3 },
|
||||
{ $0.removeValue(forKey: "config_contract") },
|
||||
{ $0["connection_scope"] = "private_auxiliary" },
|
||||
{ $0["connection_scope"] = true },
|
||||
{ $0["route_mode"] = "direct" },
|
||||
{ $0["route_mode"] = "unsupported" }
|
||||
]
|
||||
for change in changes {
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try response(change)))
|
||||
}
|
||||
for port in [0, -1, 65536] {
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = port }))
|
||||
}
|
||||
for address in ["8.8.8.8", "192.168.1.2", "198.18.1.2", "100.100.100.100", "100.070.1.2"] {
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["address"] = address }))
|
||||
}
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["node_slug"] = "other-node" }))
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["contract"] = 2 }))
|
||||
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = 1 }))
|
||||
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = 65535 }))
|
||||
}
|
||||
|
||||
func testUnsupportedOrAmbiguousProxyIdentityIsRejected() throws {
|
||||
let changes: [(inout [String: Any]) -> Void] = [
|
||||
{ $0["protocol"] = "socks" },
|
||||
{ $0["streamSettings"] = ["network":"tcp", "security":"tls"] },
|
||||
{ $0["settings"] = ["vnext":[]] },
|
||||
{ $0["settings"] = ["vnext":[["address":"node.example.test", "port":443, "users":[]]]] },
|
||||
{ $0["settings"] = ["vnext":[["address":"node.example.test", "port":443, "users":[["id":" "]]]]] },
|
||||
{ $0["streamSettings"] = ["network":"ws", "security":"reality", "realitySettings":["serverName":"server.example.test", "publicKey":"fixture-public-key"]] },
|
||||
{ $0["streamSettings"] = ["network":"tcp", "security":"reality", "realitySettings":["serverName":" ", "publicKey":"fixture-public-key"]] },
|
||||
{ $0["streamSettings"] = ["network":"tcp", "security":"reality", "realitySettings":["serverName":"server.example.test", "publicKey":" "]] }
|
||||
]
|
||||
for change in changes {
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingProxy(change)))
|
||||
}
|
||||
let duplicate = try response { root in
|
||||
var config = root["config"] as! [String: Any]
|
||||
var outbounds = config["outbounds"] as! [[String: Any]]
|
||||
outbounds.append(outbounds[0])
|
||||
config["outbounds"] = outbounds
|
||||
root["config"] = config
|
||||
}
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: duplicate))
|
||||
let multipleServers = try changingProxy { proxy in
|
||||
var settings = proxy["settings"] as! [String: Any]
|
||||
var servers = settings["vnext"] as! [[String: Any]]
|
||||
servers.append(servers[0])
|
||||
settings["vnext"] = servers
|
||||
proxy["settings"] = settings
|
||||
}
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: multipleServers))
|
||||
}
|
||||
|
||||
func testRawNetworkAndRealityPasswordRemainCompatible() throws {
|
||||
let value = try changingProxy { proxy in
|
||||
var reality = ["serverName":"server.example.test"]
|
||||
reality["password"] = "fixture-public-key"
|
||||
proxy["streamSettings"] = ["network":"raw", "security":"reality", "realitySettings":reality]
|
||||
}
|
||||
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
|
||||
}
|
||||
|
||||
func testPrivateOrPreviouslyPreparedConfigurationsDoNotCreateAnInternalCandidate() throws {
|
||||
for marker in ["ucvl_private_auxiliary", "ucvl_tailnet_transport"] {
|
||||
let value = try response { root in
|
||||
var config = root["config"] as! [String: Any]
|
||||
config[marker] = ["address":"100.70.1.2"]
|
||||
root["config"] = config
|
||||
}
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
|
||||
}
|
||||
}
|
||||
|
||||
func testRuntimeReplacementChangesOnlyAddressAndPort() throws {
|
||||
let value = try response()
|
||||
let endpoint = try XCTUnwrap(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
|
||||
let original = try value.configJSONString()
|
||||
let runtime = try ProxyTransportPolicy.internalConfigJSON(rawJSON: original, endpoint: endpoint)
|
||||
var output = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(runtime.utf8)) as? [String: Any])
|
||||
var outbounds = try XCTUnwrap(output["outbounds"] as? [[String: Any]])
|
||||
var settings = try XCTUnwrap(outbounds[0]["settings"] as? [String: Any])
|
||||
var servers = try XCTUnwrap(settings["vnext"] as? [[String: Any]])
|
||||
XCTAssertEqual(servers[0]["address"] as? String, "100.70.1.2")
|
||||
XCTAssertEqual(servers[0]["port"] as? Int, 12001)
|
||||
servers[0]["address"] = "node.example.test"
|
||||
servers[0]["port"] = 443
|
||||
settings["vnext"] = servers
|
||||
outbounds[0]["settings"] = settings
|
||||
output["outbounds"] = outbounds
|
||||
let expected = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(original.utf8)) as? [String: Any])
|
||||
XCTAssertTrue(NSDictionary(dictionary: output).isEqual(to: expected))
|
||||
XCTAssertEqual(try value.configJSONString(), original)
|
||||
}
|
||||
|
||||
func testRuntimeReplacementRejectsInvalidEndpointOrProxy() throws {
|
||||
let value = try response()
|
||||
let endpoint = try XCTUnwrap(value.tailscaleEndpoint)
|
||||
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: "{}", endpoint: endpoint))
|
||||
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: "invalid", endpoint: endpoint))
|
||||
let publicAddress = ProxyTransportEndpoint(contract: 1, nodeSlug: "fixture-node", address: "8.8.8.8", port: 12001)
|
||||
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: try value.configJSONString(), endpoint: publicAddress))
|
||||
}
|
||||
|
||||
func testProviderValidationRepeatsNodeContractAndConfigurationGates() throws {
|
||||
let value = try response()
|
||||
let endpoint = try XCTUnwrap(value.tailscaleEndpoint)
|
||||
let config = try value.configJSONString()
|
||||
XCTAssertEqual(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: config), endpoint)
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "other-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: config))
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 3, connectionScope: "public", routeMode: "smart", configJSON: config))
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "private_auxiliary", routeMode: "smart", configJSON: config))
|
||||
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: "{}"))
|
||||
}
|
||||
|
||||
func testPublicFallbackRemainsLockedForTheEntireSession() {
|
||||
var session = ProxyTransportSession()
|
||||
XCTAssertFalse(session.domainOnly)
|
||||
session.commitPublicFallback()
|
||||
XCTAssertTrue(session.domainOnly)
|
||||
session.commitPublicFallback()
|
||||
XCTAssertTrue(session.domainOnly)
|
||||
XCTAssertFalse(ProxyTransportSession().domainOnly)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
|
||||
"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":"proxy","protocol":"vless","settings":{"vnext":[{"address":"001.vpn.example.invalid","port":11081,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","realitySettings":{"serverName":"www.microsoft.com"}}},
|
||||
{"tag":"direct","protocol":"freedom"}
|
||||
],
|
||||
"routing":{"rules":[]}
|
||||
@@ -19,7 +19,7 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
|
||||
rawJSON: raw,
|
||||
tunnelFileDescriptor: 42,
|
||||
assetDirectory: "/app/assets",
|
||||
resolvedRemoteAddress: "192.0.2.1"
|
||||
resolvedRemoteAddress: "203.0.113.17"
|
||||
)
|
||||
let data = try XCTUnwrap(output.data(using: .utf8))
|
||||
let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
@@ -35,10 +35,10 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
|
||||
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")
|
||||
XCTAssertEqual(vnext.first?["address"] as? String, "203.0.113.17")
|
||||
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")
|
||||
XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.example.invalid")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# iOS 1.0.3 同步更新计划
|
||||
|
||||
> **For agentic workers:** Use executing-plans, test-driven-development and verification-before-completion. User already opted out of repeated design and publication approval questions.
|
||||
|
||||
**Goal:** 更新现有 iPhone/iPad 源码,沿用已发布 Windows 0.3.1 的授权内部 IP 优先、公网回落保持与山水半透明视觉;如缺 Apple 构建/签名条件,明确交付源码候选,绝不冒称 IPA 或安装完成。
|
||||
|
||||
**Architecture:** 保留 SwiftUI + NetworkExtension + 官方固定 libXray。后台可选契约提供同节点内部入口;严格验证后最多1秒原生 ICMP,出口仍需现有 HTTPS 验证。显式连接拥有一次公网回落状态,完整断开前不启动备用;不管理 Tailscale,不承诺同机两个 Packet Tunnel 并存。
|
||||
|
||||
**Tech Stack:** Swift5语言模式 / iOS15 / XcodeGen / XCTest / Python源审计。
|
||||
|
||||
## Global constraints
|
||||
|
||||
- 不改 Windows 已发布内容、后台生产、路由器、现用网络、Sony 夜猫或电视。
|
||||
- 仅使用认证后台返回且同节点匹配的100.64.0.0/10入口;不硬编码节点;不把Ping当身份验证。
|
||||
- 只重写代理地址与端口;Reality/UUID/路由等原始授权保持。公网解析延迟到公网分支。
|
||||
- 统一品牌“纵横家”,复用有来源的原创山水图;不把许可不明人物图公开。
|
||||
- 真机、签名与Xcode缺失时保持 IPA/正式稳定发行/生产验收=false,静态审计不冒充Swift行为测试。
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ] 建立可选端点容错解析、严格100/10和同身份替换、sticky策略的XCTest;增加可执行静态审计负向夹具并保留RED。
|
||||
- [ ] 实现受限入口策略、原生ICMP、同节点公网回退;Provider重复验证并仅排除所选/32;清理超时停止;过滤无关VPN通知。
|
||||
- [ ] 同步山水背景、50%卡片、注册行对齐、品牌与响应式iPhone/iPad布局;不伪造速度数据。
|
||||
- [ ] 版本1.0.3/build10003,改归档脚本版本路径与可配置Simulator;更新真实验收范围。
|
||||
- [ ] 跑源审计及其负向夹具、全部可执行本地检查;XCTest/Xcode只能在实际可用构建机上执行。独立审查重要问题。
|
||||
- [ ] 冻结精确源码与审计/未验收声明,推送新的专属分支和公开清洁源码分支,逐blob与附件下载核对;源码候选只标prerelease。
|
||||
|
||||
## Review focus
|
||||
|
||||
- 缺失/null/格式错误的可选入口不得破坏旧公网配置。
|
||||
- 节点、契约、scope、端口、单一VLESS Reality身份不匹配不得触发Ping或改写。
|
||||
- Ping/内部出口失败后的同节点公网回退,随后其它节点不得再次提升内部。
|
||||
- 清理超时、取消、本机权限、401/403不能继续切换或误报连接成功。
|
||||
- iPhone窄屏/键盘/大字体保持可操作;同机Tailscale被系统替换后不循环重试内网。
|
||||
|
||||
## Capability evidence
|
||||
|
||||
2026-10-27 authenticated read-only company Git audit: iOS repo11 private; Actions runner inventory empty, all5 historical runs cancelled. Windows host has no Swift/Xcode. No configured signing/export/TestFlight/MDM publication path. This is an external installable-release blocker, not a request to reconfirm publication authority.
|
||||
|
||||
## Execution ledger before source freeze
|
||||
|
||||
- User confirmed no Mac/build/signing environment. Continue source update and scoped source synchronization; no installable or stable iOS release can be claimed.
|
||||
- Added native bounded ICMP and nonce/source/checksum reply matching; optional endpoint authorization and same-node sticky fallback. Actual Swift/XCTest execution is unavailable. XCTest sources were written first but their RED/GREEN runtime cycle remains unexecuted; no static grep is counted as their replacement.
|
||||
- Source audit and all16 executable Python tests passed (9 real shell subprocess archive tests,7 source-audit boundary tests). Old archive script produced expected failures before its change; source version mismatch was also observed and corrected. No Xcode, simulator, IPA, real plutil, download or device activity is represented by these tests.
|
||||
- Independent review corrected two important baseline issues: config node.status absent in real backend payload now decodes to unknown, with exact-shape XCTest; Swift language setting changed from invalid5.10 to5.0. UI review corrected inherited foreground on primary buttons. Swift compilation remains unverified.
|
||||
- Source-only candidate identity1.0.3/build10003. Public export must omit unlicensed Geo binaries as in previous publication, preserve third-party licenses/trademark exceptions and provide restore notes. Do not call public resource omission a complete binary build.
|
||||
+7
-5
@@ -7,9 +7,9 @@ options:
|
||||
groupSortPosition: top
|
||||
settings:
|
||||
base:
|
||||
SWIFT_VERSION: "5.10"
|
||||
MARKETING_VERSION: "1.0.2"
|
||||
CURRENT_PROJECT_VERSION: "10002"
|
||||
SWIFT_VERSION: "5.0"
|
||||
MARKETING_VERSION: "1.0.3"
|
||||
CURRENT_PROJECT_VERSION: "10003"
|
||||
CODE_SIGN_STYLE: Automatic
|
||||
DEVELOPMENT_TEAM: ""
|
||||
CLANG_ENABLE_MODULES: YES
|
||||
@@ -31,7 +31,8 @@ targets:
|
||||
info:
|
||||
path: App/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: 优创⁺纵横家
|
||||
CFBundleDisplayName: 纵横家
|
||||
NSLocalNetworkUsageDescription: 用于检测后台授权的内部代理地址是否可达,以优先使用内部网络。
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
|
||||
UILaunchScreen:
|
||||
@@ -65,6 +66,7 @@ targets:
|
||||
- path: Shared/TunnelConfigurationBuilder.swift
|
||||
- path: Shared/Models.swift
|
||||
- path: Shared/NetworkAddress.swift
|
||||
- path: Shared/ProxyTransportPolicy.swift
|
||||
resources:
|
||||
- path: Resources/Geo
|
||||
entitlements:
|
||||
@@ -72,7 +74,7 @@ targets:
|
||||
info:
|
||||
path: PacketTunnel/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: 优创⁺纵横家网络扩展
|
||||
CFBundleDisplayName: 纵横家网络扩展
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
|
||||
NSExtension:
|
||||
|
||||
Reference in New Issue
Block a user